xref: /freebsd/sys/kern/sysv_sem.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
1 /*
2  * Implementation of SVID semaphores
3  *
4  * Author:  Daniel Boulet
5  *
6  * This software is provided ``AS IS'' without any warranties of any kind.
7  */
8 
9 #include <sys/cdefs.h>
10 __FBSDID("$FreeBSD$");
11 
12 #include "opt_sysvipc.h"
13 
14 #include <sys/param.h>
15 #include <sys/systm.h>
16 #include <sys/sysproto.h>
17 #include <sys/eventhandler.h>
18 #include <sys/kernel.h>
19 #include <sys/proc.h>
20 #include <sys/lock.h>
21 #include <sys/mutex.h>
22 #include <sys/sem.h>
23 #include <sys/syscall.h>
24 #include <sys/sysent.h>
25 #include <sys/sysctl.h>
26 #include <sys/malloc.h>
27 #include <sys/jail.h>
28 
29 static MALLOC_DEFINE(M_SEM, "sem", "SVID compatible semaphores");
30 
31 #ifdef SEM_DEBUG
32 #define DPRINTF(a)	printf a
33 #else
34 #define DPRINTF(a)
35 #endif
36 
37 static void seminit(void);
38 static int sysvsem_modload(struct module *, int, void *);
39 static int semunload(void);
40 static void semexit_myhook(void *arg, struct proc *p);
41 static int sysctl_sema(SYSCTL_HANDLER_ARGS);
42 static int semvalid(int semid, struct semid_ds *semaptr);
43 
44 #ifndef _SYS_SYSPROTO_H_
45 struct __semctl_args;
46 int __semctl(struct thread *td, struct __semctl_args *uap);
47 struct semget_args;
48 int semget(struct thread *td, struct semget_args *uap);
49 struct semop_args;
50 int semop(struct thread *td, struct semop_args *uap);
51 #endif
52 
53 static struct sem_undo *semu_alloc(struct thread *td);
54 static int semundo_adjust(struct thread *td, struct sem_undo **supptr,
55 		int semid, int semnum, int adjval);
56 static void semundo_clear(int semid, int semnum);
57 
58 /* XXX casting to (sy_call_t *) is bogus, as usual. */
59 static sy_call_t *semcalls[] = {
60 	(sy_call_t *)__semctl, (sy_call_t *)semget,
61 	(sy_call_t *)semop
62 };
63 
64 static struct mtx	sem_mtx;	/* semaphore global lock */
65 static int	semtot = 0;
66 static struct semid_ds *sema;	/* semaphore id pool */
67 static struct mtx *sema_mtx;	/* semaphore id pool mutexes*/
68 static struct sem *sem;		/* semaphore pool */
69 SLIST_HEAD(, sem_undo) semu_list;	/* list of active undo structures */
70 static int	*semu;		/* undo structure pool */
71 static eventhandler_tag semexit_tag;
72 
73 #define SEMUNDO_MTX		sem_mtx
74 #define SEMUNDO_LOCK()		mtx_lock(&SEMUNDO_MTX);
75 #define SEMUNDO_UNLOCK()	mtx_unlock(&SEMUNDO_MTX);
76 #define SEMUNDO_LOCKASSERT(how)	mtx_assert(&SEMUNDO_MTX, (how));
77 
78 struct sem {
79 	u_short	semval;		/* semaphore value */
80 	pid_t	sempid;		/* pid of last operation */
81 	u_short	semncnt;	/* # awaiting semval > cval */
82 	u_short	semzcnt;	/* # awaiting semval = 0 */
83 };
84 
85 /*
86  * Undo structure (one per process)
87  */
88 struct sem_undo {
89 	SLIST_ENTRY(sem_undo) un_next;	/* ptr to next active undo structure */
90 	struct	proc *un_proc;		/* owner of this structure */
91 	short	un_cnt;			/* # of active entries */
92 	struct undo {
93 		short	un_adjval;	/* adjust on exit values */
94 		short	un_num;		/* semaphore # */
95 		int	un_id;		/* semid */
96 	} un_ent[1];			/* undo entries */
97 };
98 
99 /*
100  * Configuration parameters
101  */
102 #ifndef SEMMNI
103 #define SEMMNI	10		/* # of semaphore identifiers */
104 #endif
105 #ifndef SEMMNS
106 #define SEMMNS	60		/* # of semaphores in system */
107 #endif
108 #ifndef SEMUME
109 #define SEMUME	10		/* max # of undo entries per process */
110 #endif
111 #ifndef SEMMNU
112 #define SEMMNU	30		/* # of undo structures in system */
113 #endif
114 
115 /* shouldn't need tuning */
116 #ifndef SEMMAP
117 #define SEMMAP	30		/* # of entries in semaphore map */
118 #endif
119 #ifndef SEMMSL
120 #define SEMMSL	SEMMNS		/* max # of semaphores per id */
121 #endif
122 #ifndef SEMOPM
123 #define SEMOPM	100		/* max # of operations per semop call */
124 #endif
125 
126 #define SEMVMX	32767		/* semaphore maximum value */
127 #define SEMAEM	16384		/* adjust on exit max value */
128 
129 /*
130  * Due to the way semaphore memory is allocated, we have to ensure that
131  * SEMUSZ is properly aligned.
132  */
133 
134 #define SEM_ALIGN(bytes) (((bytes) + (sizeof(long) - 1)) & ~(sizeof(long) - 1))
135 
136 /* actual size of an undo structure */
137 #define SEMUSZ	SEM_ALIGN(offsetof(struct sem_undo, un_ent[SEMUME]))
138 
139 /*
140  * Macro to find a particular sem_undo vector
141  */
142 #define SEMU(ix) \
143 	((struct sem_undo *)(((intptr_t)semu)+ix * seminfo.semusz))
144 
145 /*
146  * semaphore info struct
147  */
148 struct seminfo seminfo = {
149                 SEMMAP,         /* # of entries in semaphore map */
150                 SEMMNI,         /* # of semaphore identifiers */
151                 SEMMNS,         /* # of semaphores in system */
152                 SEMMNU,         /* # of undo structures in system */
153                 SEMMSL,         /* max # of semaphores per id */
154                 SEMOPM,         /* max # of operations per semop call */
155                 SEMUME,         /* max # of undo entries per process */
156                 SEMUSZ,         /* size in bytes of undo structure */
157                 SEMVMX,         /* semaphore maximum value */
158                 SEMAEM          /* adjust on exit max value */
159 };
160 
161 SYSCTL_DECL(_kern_ipc);
162 SYSCTL_INT(_kern_ipc, OID_AUTO, semmap, CTLFLAG_RW, &seminfo.semmap, 0, "");
163 SYSCTL_INT(_kern_ipc, OID_AUTO, semmni, CTLFLAG_RD, &seminfo.semmni, 0, "");
164 SYSCTL_INT(_kern_ipc, OID_AUTO, semmns, CTLFLAG_RD, &seminfo.semmns, 0, "");
165 SYSCTL_INT(_kern_ipc, OID_AUTO, semmnu, CTLFLAG_RD, &seminfo.semmnu, 0, "");
166 SYSCTL_INT(_kern_ipc, OID_AUTO, semmsl, CTLFLAG_RW, &seminfo.semmsl, 0, "");
167 SYSCTL_INT(_kern_ipc, OID_AUTO, semopm, CTLFLAG_RD, &seminfo.semopm, 0, "");
168 SYSCTL_INT(_kern_ipc, OID_AUTO, semume, CTLFLAG_RD, &seminfo.semume, 0, "");
169 SYSCTL_INT(_kern_ipc, OID_AUTO, semusz, CTLFLAG_RD, &seminfo.semusz, 0, "");
170 SYSCTL_INT(_kern_ipc, OID_AUTO, semvmx, CTLFLAG_RW, &seminfo.semvmx, 0, "");
171 SYSCTL_INT(_kern_ipc, OID_AUTO, semaem, CTLFLAG_RW, &seminfo.semaem, 0, "");
172 SYSCTL_PROC(_kern_ipc, OID_AUTO, sema, CTLFLAG_RD,
173     NULL, 0, sysctl_sema, "", "");
174 
175 static void
176 seminit(void)
177 {
178 	int i;
179 
180 	TUNABLE_INT_FETCH("kern.ipc.semmap", &seminfo.semmap);
181 	TUNABLE_INT_FETCH("kern.ipc.semmni", &seminfo.semmni);
182 	TUNABLE_INT_FETCH("kern.ipc.semmns", &seminfo.semmns);
183 	TUNABLE_INT_FETCH("kern.ipc.semmnu", &seminfo.semmnu);
184 	TUNABLE_INT_FETCH("kern.ipc.semmsl", &seminfo.semmsl);
185 	TUNABLE_INT_FETCH("kern.ipc.semopm", &seminfo.semopm);
186 	TUNABLE_INT_FETCH("kern.ipc.semume", &seminfo.semume);
187 	TUNABLE_INT_FETCH("kern.ipc.semusz", &seminfo.semusz);
188 	TUNABLE_INT_FETCH("kern.ipc.semvmx", &seminfo.semvmx);
189 	TUNABLE_INT_FETCH("kern.ipc.semaem", &seminfo.semaem);
190 
191 	sem = malloc(sizeof(struct sem) * seminfo.semmns, M_SEM, M_WAITOK);
192 	sema = malloc(sizeof(struct semid_ds) * seminfo.semmni, M_SEM,
193 	    M_WAITOK);
194 	sema_mtx = malloc(sizeof(struct mtx) * seminfo.semmni, M_SEM,
195 	    M_WAITOK | M_ZERO);
196 	semu = malloc(seminfo.semmnu * seminfo.semusz, M_SEM, M_WAITOK);
197 
198 	for (i = 0; i < seminfo.semmni; i++) {
199 		sema[i].sem_base = 0;
200 		sema[i].sem_perm.mode = 0;
201 	}
202 	for (i = 0; i < seminfo.semmni; i++)
203 		mtx_init(&sema_mtx[i], "semid", NULL, MTX_DEF);
204 	for (i = 0; i < seminfo.semmnu; i++) {
205 		struct sem_undo *suptr = SEMU(i);
206 		suptr->un_proc = NULL;
207 	}
208 	SLIST_INIT(&semu_list);
209 	mtx_init(&sem_mtx, "sem", NULL, MTX_DEF);
210 	semexit_tag = EVENTHANDLER_REGISTER(process_exit, semexit_myhook, NULL,
211 	    EVENTHANDLER_PRI_ANY);
212 }
213 
214 static int
215 semunload(void)
216 {
217 	int i;
218 
219 	if (semtot != 0)
220 		return (EBUSY);
221 
222 	EVENTHANDLER_DEREGISTER(process_exit, semexit_tag);
223 	free(sem, M_SEM);
224 	free(sema, M_SEM);
225 	free(semu, M_SEM);
226 	for (i = 0; i < seminfo.semmni; i++)
227 		mtx_destroy(&sema_mtx[i]);
228 	mtx_destroy(&sem_mtx);
229 	return (0);
230 }
231 
232 static int
233 sysvsem_modload(struct module *module, int cmd, void *arg)
234 {
235 	int error = 0;
236 
237 	switch (cmd) {
238 	case MOD_LOAD:
239 		seminit();
240 		break;
241 	case MOD_UNLOAD:
242 		error = semunload();
243 		break;
244 	case MOD_SHUTDOWN:
245 		break;
246 	default:
247 		error = EINVAL;
248 		break;
249 	}
250 	return (error);
251 }
252 
253 static moduledata_t sysvsem_mod = {
254 	"sysvsem",
255 	&sysvsem_modload,
256 	NULL
257 };
258 
259 SYSCALL_MODULE_HELPER(semsys);
260 SYSCALL_MODULE_HELPER(__semctl);
261 SYSCALL_MODULE_HELPER(semget);
262 SYSCALL_MODULE_HELPER(semop);
263 
264 DECLARE_MODULE(sysvsem, sysvsem_mod,
265 	SI_SUB_SYSV_SEM, SI_ORDER_FIRST);
266 MODULE_VERSION(sysvsem, 1);
267 
268 /*
269  * Entry point for all SEM calls
270  *
271  * MPSAFE
272  */
273 int
274 semsys(td, uap)
275 	struct thread *td;
276 	/* XXX actually varargs. */
277 	struct semsys_args /* {
278 		int	which;
279 		int	a2;
280 		int	a3;
281 		int	a4;
282 		int	a5;
283 	} */ *uap;
284 {
285 	int error;
286 
287 	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
288 		return (ENOSYS);
289 	if (uap->which < 0 ||
290 	    uap->which >= sizeof(semcalls)/sizeof(semcalls[0]))
291 		return (EINVAL);
292 	error = (*semcalls[uap->which])(td, &uap->a2);
293 	return (error);
294 }
295 
296 /*
297  * Allocate a new sem_undo structure for a process
298  * (returns ptr to structure or NULL if no more room)
299  */
300 
301 static struct sem_undo *
302 semu_alloc(td)
303 	struct thread *td;
304 {
305 	int i;
306 	struct sem_undo *suptr;
307 	struct sem_undo **supptr;
308 	int attempt;
309 
310 	SEMUNDO_LOCKASSERT(MA_OWNED);
311 	/*
312 	 * Try twice to allocate something.
313 	 * (we'll purge any empty structures after the first pass so
314 	 * two passes are always enough)
315 	 */
316 
317 	for (attempt = 0; attempt < 2; attempt++) {
318 		/*
319 		 * Look for a free structure.
320 		 * Fill it in and return it if we find one.
321 		 */
322 
323 		for (i = 0; i < seminfo.semmnu; i++) {
324 			suptr = SEMU(i);
325 			if (suptr->un_proc == NULL) {
326 				SLIST_INSERT_HEAD(&semu_list, suptr, un_next);
327 				suptr->un_cnt = 0;
328 				suptr->un_proc = td->td_proc;
329 				return(suptr);
330 			}
331 		}
332 
333 		/*
334 		 * We didn't find a free one, if this is the first attempt
335 		 * then try to free some structures.
336 		 */
337 
338 		if (attempt == 0) {
339 			/* All the structures are in use - try to free some */
340 			int did_something = 0;
341 
342 			SLIST_FOREACH_PREVPTR(suptr, supptr, &semu_list,
343 			    un_next) {
344 				if (suptr->un_cnt == 0) {
345 					suptr->un_proc = NULL;
346 					did_something = 1;
347 					*supptr = SLIST_NEXT(suptr, un_next);
348 				}
349 			}
350 
351 			/* If we didn't free anything then just give-up */
352 			if (!did_something)
353 				return(NULL);
354 		} else {
355 			/*
356 			 * The second pass failed even though we freed
357 			 * something after the first pass!
358 			 * This is IMPOSSIBLE!
359 			 */
360 			panic("semu_alloc - second attempt failed");
361 		}
362 	}
363 	return (NULL);
364 }
365 
366 /*
367  * Adjust a particular entry for a particular proc
368  */
369 
370 static int
371 semundo_adjust(td, supptr, semid, semnum, adjval)
372 	struct thread *td;
373 	struct sem_undo **supptr;
374 	int semid, semnum;
375 	int adjval;
376 {
377 	struct proc *p = td->td_proc;
378 	struct sem_undo *suptr;
379 	struct undo *sunptr;
380 	int i;
381 
382 	SEMUNDO_LOCKASSERT(MA_OWNED);
383 	/* Look for and remember the sem_undo if the caller doesn't provide
384 	   it */
385 
386 	suptr = *supptr;
387 	if (suptr == NULL) {
388 		SLIST_FOREACH(suptr, &semu_list, un_next) {
389 			if (suptr->un_proc == p) {
390 				*supptr = suptr;
391 				break;
392 			}
393 		}
394 		if (suptr == NULL) {
395 			if (adjval == 0)
396 				return(0);
397 			suptr = semu_alloc(td);
398 			if (suptr == NULL)
399 				return(ENOSPC);
400 			*supptr = suptr;
401 		}
402 	}
403 
404 	/*
405 	 * Look for the requested entry and adjust it (delete if adjval becomes
406 	 * 0).
407 	 */
408 	sunptr = &suptr->un_ent[0];
409 	for (i = 0; i < suptr->un_cnt; i++, sunptr++) {
410 		if (sunptr->un_id != semid || sunptr->un_num != semnum)
411 			continue;
412 		if (adjval != 0) {
413 			adjval += sunptr->un_adjval;
414 			if (adjval > seminfo.semaem || adjval < -seminfo.semaem)
415 				return (ERANGE);
416 		}
417 		sunptr->un_adjval = adjval;
418 		if (sunptr->un_adjval == 0) {
419 			suptr->un_cnt--;
420 			if (i < suptr->un_cnt)
421 				suptr->un_ent[i] =
422 				    suptr->un_ent[suptr->un_cnt];
423 		}
424 		return(0);
425 	}
426 
427 	/* Didn't find the right entry - create it */
428 	if (adjval == 0)
429 		return(0);
430 	if (adjval > seminfo.semaem || adjval < -seminfo.semaem)
431 		return (ERANGE);
432 	if (suptr->un_cnt != seminfo.semume) {
433 		sunptr = &suptr->un_ent[suptr->un_cnt];
434 		suptr->un_cnt++;
435 		sunptr->un_adjval = adjval;
436 		sunptr->un_id = semid; sunptr->un_num = semnum;
437 	} else
438 		return(EINVAL);
439 	return(0);
440 }
441 
442 static void
443 semundo_clear(semid, semnum)
444 	int semid, semnum;
445 {
446 	struct sem_undo *suptr;
447 
448 	SEMUNDO_LOCKASSERT(MA_OWNED);
449 	SLIST_FOREACH(suptr, &semu_list, un_next) {
450 		struct undo *sunptr = &suptr->un_ent[0];
451 		int i = 0;
452 
453 		while (i < suptr->un_cnt) {
454 			if (sunptr->un_id == semid) {
455 				if (semnum == -1 || sunptr->un_num == semnum) {
456 					suptr->un_cnt--;
457 					if (i < suptr->un_cnt) {
458 						suptr->un_ent[i] =
459 						  suptr->un_ent[suptr->un_cnt];
460 						continue;
461 					}
462 				}
463 				if (semnum != -1)
464 					break;
465 			}
466 			i++, sunptr++;
467 		}
468 	}
469 }
470 
471 static int
472 semvalid(semid, semaptr)
473 	int semid;
474 	struct semid_ds *semaptr;
475 {
476 
477 	return ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
478 	    semaptr->sem_perm.seq != IPCID_TO_SEQ(semid) ? EINVAL : 0);
479 }
480 
481 /*
482  * Note that the user-mode half of this passes a union, not a pointer
483  */
484 #ifndef _SYS_SYSPROTO_H_
485 struct __semctl_args {
486 	int	semid;
487 	int	semnum;
488 	int	cmd;
489 	union	semun *arg;
490 };
491 #endif
492 
493 /*
494  * MPSAFE
495  */
496 int
497 __semctl(td, uap)
498 	struct thread *td;
499 	struct __semctl_args *uap;
500 {
501 	int semid = uap->semid;
502 	int semnum = uap->semnum;
503 	int cmd = uap->cmd;
504 	u_short *array;
505 	union semun *arg = uap->arg;
506 	union semun real_arg;
507 	struct ucred *cred = td->td_ucred;
508 	int i, rval, error;
509 	struct semid_ds sbuf;
510 	struct semid_ds *semaptr;
511 	struct mtx *sema_mtxp;
512 	u_short usval, count;
513 
514 	DPRINTF(("call to semctl(%d, %d, %d, 0x%x)\n",
515 	    semid, semnum, cmd, arg));
516 	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
517 		return (ENOSYS);
518 
519 	array = NULL;
520 
521 	switch(cmd) {
522 	case SEM_STAT:
523 		if (semid < 0 || semid >= seminfo.semmni)
524 			return (EINVAL);
525 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
526 			return (error);
527 		semaptr = &sema[semid];
528 		sema_mtxp = &sema_mtx[semid];
529 		mtx_lock(sema_mtxp);
530 		if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ) {
531 			error = EINVAL;
532 			goto done2;
533 		}
534 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
535 			goto done2;
536 		mtx_unlock(sema_mtxp);
537 		error = copyout(semaptr, real_arg.buf, sizeof(struct semid_ds));
538 		rval = IXSEQ_TO_IPCID(semid,semaptr->sem_perm);
539 		if (error == 0)
540 			td->td_retval[0] = rval;
541 		return (error);
542 	}
543 
544 	semid = IPCID_TO_IX(semid);
545 	if (semid < 0 || semid >= seminfo.semmni)
546 		return (EINVAL);
547 
548 	semaptr = &sema[semid];
549 	sema_mtxp = &sema_mtx[semid];
550 
551 	error = 0;
552 	rval = 0;
553 
554 	switch (cmd) {
555 	case IPC_RMID:
556 		mtx_lock(sema_mtxp);
557 		if ((error = semvalid(uap->semid, semaptr)) != 0)
558 			goto done2;
559 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_M)))
560 			goto done2;
561 		semaptr->sem_perm.cuid = cred->cr_uid;
562 		semaptr->sem_perm.uid = cred->cr_uid;
563 		semtot -= semaptr->sem_nsems;
564 		for (i = semaptr->sem_base - sem; i < semtot; i++)
565 			sem[i] = sem[i + semaptr->sem_nsems];
566 		for (i = 0; i < seminfo.semmni; i++) {
567 			if ((sema[i].sem_perm.mode & SEM_ALLOC) &&
568 			    sema[i].sem_base > semaptr->sem_base)
569 				sema[i].sem_base -= semaptr->sem_nsems;
570 		}
571 		semaptr->sem_perm.mode = 0;
572 		SEMUNDO_LOCK();
573 		semundo_clear(semid, -1);
574 		SEMUNDO_UNLOCK();
575 		wakeup(semaptr);
576 		break;
577 
578 	case IPC_SET:
579 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
580 			goto done2;
581 		if ((error = copyin(real_arg.buf, &sbuf, sizeof(sbuf))) != 0)
582 			goto done2;
583 		mtx_lock(sema_mtxp);
584 		if ((error = semvalid(uap->semid, semaptr)) != 0)
585 			goto done2;
586 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_M)))
587 			goto done2;
588 		semaptr->sem_perm.uid = sbuf.sem_perm.uid;
589 		semaptr->sem_perm.gid = sbuf.sem_perm.gid;
590 		semaptr->sem_perm.mode = (semaptr->sem_perm.mode & ~0777) |
591 		    (sbuf.sem_perm.mode & 0777);
592 		semaptr->sem_ctime = time_second;
593 		break;
594 
595 	case IPC_STAT:
596 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
597 			goto done2;
598 		mtx_lock(sema_mtxp);
599 		if ((error = semvalid(uap->semid, semaptr)) != 0)
600 			goto done2;
601 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
602 			goto done2;
603 		sbuf = *semaptr;
604 		mtx_unlock(sema_mtxp);
605 		error = copyout(semaptr, real_arg.buf,
606 				sizeof(struct semid_ds));
607 		break;
608 
609 	case GETNCNT:
610 		mtx_lock(sema_mtxp);
611 		if ((error = semvalid(uap->semid, semaptr)) != 0)
612 			goto done2;
613 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
614 			goto done2;
615 		if (semnum < 0 || semnum >= semaptr->sem_nsems) {
616 			error = EINVAL;
617 			goto done2;
618 		}
619 		rval = semaptr->sem_base[semnum].semncnt;
620 		break;
621 
622 	case GETPID:
623 		mtx_lock(sema_mtxp);
624 		if ((error = semvalid(uap->semid, semaptr)) != 0)
625 			goto done2;
626 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
627 			goto done2;
628 		if (semnum < 0 || semnum >= semaptr->sem_nsems) {
629 			error = EINVAL;
630 			goto done2;
631 		}
632 		rval = semaptr->sem_base[semnum].sempid;
633 		break;
634 
635 	case GETVAL:
636 		mtx_lock(sema_mtxp);
637 		if ((error = semvalid(uap->semid, semaptr)) != 0)
638 			goto done2;
639 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
640 			goto done2;
641 		if (semnum < 0 || semnum >= semaptr->sem_nsems) {
642 			error = EINVAL;
643 			goto done2;
644 		}
645 		rval = semaptr->sem_base[semnum].semval;
646 		break;
647 
648 	case GETALL:
649 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
650 			goto done2;
651 		array = malloc(sizeof(*array) * semaptr->sem_nsems, M_TEMP,
652 		    M_WAITOK);
653 		mtx_lock(sema_mtxp);
654 		if ((error = semvalid(uap->semid, semaptr)) != 0)
655 			goto done2;
656 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
657 			goto done2;
658 		for (i = 0; i < semaptr->sem_nsems; i++)
659 			array[i] = semaptr->sem_base[i].semval;
660 		mtx_unlock(sema_mtxp);
661 		error = copyout(array, real_arg.array,
662 		    i * sizeof(real_arg.array[0]));
663 		break;
664 
665 	case GETZCNT:
666 		mtx_lock(sema_mtxp);
667 		if ((error = semvalid(uap->semid, semaptr)) != 0)
668 			goto done2;
669 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
670 			goto done2;
671 		if (semnum < 0 || semnum >= semaptr->sem_nsems) {
672 			error = EINVAL;
673 			goto done2;
674 		}
675 		rval = semaptr->sem_base[semnum].semzcnt;
676 		break;
677 
678 	case SETVAL:
679 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
680 			goto done2;
681 		mtx_lock(sema_mtxp);
682 		if ((error = semvalid(uap->semid, semaptr)) != 0)
683 			goto done2;
684 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_W)))
685 			goto done2;
686 		if (semnum < 0 || semnum >= semaptr->sem_nsems) {
687 			error = EINVAL;
688 			goto done2;
689 		}
690 		if (real_arg.val < 0 || real_arg.val > seminfo.semvmx) {
691 			error = ERANGE;
692 			goto done2;
693 		}
694 		semaptr->sem_base[semnum].semval = real_arg.val;
695 		SEMUNDO_LOCK();
696 		semundo_clear(semid, semnum);
697 		SEMUNDO_UNLOCK();
698 		wakeup(semaptr);
699 		break;
700 
701 	case SETALL:
702 		mtx_lock(sema_mtxp);
703 raced:
704 		if ((error = semvalid(uap->semid, semaptr)) != 0)
705 			goto done2;
706 		count = semaptr->sem_nsems;
707 		mtx_unlock(sema_mtxp);
708 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
709 			goto done2;
710 		array = malloc(sizeof(*array) * count, M_TEMP, M_WAITOK);
711 		copyin(real_arg.array, array, count * sizeof(*array));
712 		if (error)
713 			break;
714 		mtx_lock(sema_mtxp);
715 		if ((error = semvalid(uap->semid, semaptr)) != 0)
716 			goto done2;
717 		/* we could have raced? */
718 		if (count != semaptr->sem_nsems) {
719 			free(array, M_TEMP);
720 			array = NULL;
721 			goto raced;
722 		}
723 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_W)))
724 			goto done2;
725 		for (i = 0; i < semaptr->sem_nsems; i++) {
726 			usval = array[i];
727 			if (usval > seminfo.semvmx) {
728 				error = ERANGE;
729 				break;
730 			}
731 			semaptr->sem_base[i].semval = usval;
732 		}
733 		SEMUNDO_LOCK();
734 		semundo_clear(semid, -1);
735 		SEMUNDO_UNLOCK();
736 		wakeup(semaptr);
737 		break;
738 
739 	default:
740 		error = EINVAL;
741 		break;
742 	}
743 
744 	if (error == 0)
745 		td->td_retval[0] = rval;
746 done2:
747 	if (mtx_owned(sema_mtxp))
748 		mtx_unlock(sema_mtxp);
749 	if (array != NULL)
750 		free(array, M_TEMP);
751 	return(error);
752 }
753 
754 #ifndef _SYS_SYSPROTO_H_
755 struct semget_args {
756 	key_t	key;
757 	int	nsems;
758 	int	semflg;
759 };
760 #endif
761 
762 /*
763  * MPSAFE
764  */
765 int
766 semget(td, uap)
767 	struct thread *td;
768 	struct semget_args *uap;
769 {
770 	int semid, error = 0;
771 	int key = uap->key;
772 	int nsems = uap->nsems;
773 	int semflg = uap->semflg;
774 	struct ucred *cred = td->td_ucred;
775 
776 	DPRINTF(("semget(0x%x, %d, 0%o)\n", key, nsems, semflg));
777 	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
778 		return (ENOSYS);
779 
780 	mtx_lock(&Giant);
781 	if (key != IPC_PRIVATE) {
782 		for (semid = 0; semid < seminfo.semmni; semid++) {
783 			if ((sema[semid].sem_perm.mode & SEM_ALLOC) &&
784 			    sema[semid].sem_perm.key == key)
785 				break;
786 		}
787 		if (semid < seminfo.semmni) {
788 			DPRINTF(("found public key\n"));
789 			if ((error = ipcperm(td, &sema[semid].sem_perm,
790 			    semflg & 0700))) {
791 				goto done2;
792 			}
793 			if (nsems > 0 && sema[semid].sem_nsems < nsems) {
794 				DPRINTF(("too small\n"));
795 				error = EINVAL;
796 				goto done2;
797 			}
798 			if ((semflg & IPC_CREAT) && (semflg & IPC_EXCL)) {
799 				DPRINTF(("not exclusive\n"));
800 				error = EEXIST;
801 				goto done2;
802 			}
803 			goto found;
804 		}
805 	}
806 
807 	DPRINTF(("need to allocate the semid_ds\n"));
808 	if (key == IPC_PRIVATE || (semflg & IPC_CREAT)) {
809 		if (nsems <= 0 || nsems > seminfo.semmsl) {
810 			DPRINTF(("nsems out of range (0<%d<=%d)\n", nsems,
811 			    seminfo.semmsl));
812 			error = EINVAL;
813 			goto done2;
814 		}
815 		if (nsems > seminfo.semmns - semtot) {
816 			DPRINTF((
817 			    "not enough semaphores left (need %d, got %d)\n",
818 			    nsems, seminfo.semmns - semtot));
819 			error = ENOSPC;
820 			goto done2;
821 		}
822 		for (semid = 0; semid < seminfo.semmni; semid++) {
823 			if ((sema[semid].sem_perm.mode & SEM_ALLOC) == 0)
824 				break;
825 		}
826 		if (semid == seminfo.semmni) {
827 			DPRINTF(("no more semid_ds's available\n"));
828 			error = ENOSPC;
829 			goto done2;
830 		}
831 		DPRINTF(("semid %d is available\n", semid));
832 		sema[semid].sem_perm.key = key;
833 		sema[semid].sem_perm.cuid = cred->cr_uid;
834 		sema[semid].sem_perm.uid = cred->cr_uid;
835 		sema[semid].sem_perm.cgid = cred->cr_gid;
836 		sema[semid].sem_perm.gid = cred->cr_gid;
837 		sema[semid].sem_perm.mode = (semflg & 0777) | SEM_ALLOC;
838 		sema[semid].sem_perm.seq =
839 		    (sema[semid].sem_perm.seq + 1) & 0x7fff;
840 		sema[semid].sem_nsems = nsems;
841 		sema[semid].sem_otime = 0;
842 		sema[semid].sem_ctime = time_second;
843 		sema[semid].sem_base = &sem[semtot];
844 		semtot += nsems;
845 		bzero(sema[semid].sem_base,
846 		    sizeof(sema[semid].sem_base[0])*nsems);
847 		DPRINTF(("sembase = 0x%x, next = 0x%x\n", sema[semid].sem_base,
848 		    &sem[semtot]));
849 	} else {
850 		DPRINTF(("didn't find it and wasn't asked to create it\n"));
851 		error = ENOENT;
852 		goto done2;
853 	}
854 
855 found:
856 	td->td_retval[0] = IXSEQ_TO_IPCID(semid, sema[semid].sem_perm);
857 done2:
858 	mtx_unlock(&Giant);
859 	return (error);
860 }
861 
862 #ifndef _SYS_SYSPROTO_H_
863 struct semop_args {
864 	int	semid;
865 	struct	sembuf *sops;
866 	size_t	nsops;
867 };
868 #endif
869 
870 /*
871  * MPSAFE
872  */
873 int
874 semop(td, uap)
875 	struct thread *td;
876 	struct semop_args *uap;
877 {
878 	int semid = uap->semid;
879 	size_t nsops = uap->nsops;
880 	struct sembuf *sops;
881 	struct semid_ds *semaptr;
882 	struct sembuf *sopptr = 0;
883 	struct sem *semptr = 0;
884 	struct sem_undo *suptr;
885 	struct mtx *sema_mtxp;
886 	size_t i, j, k;
887 	int error;
888 	int do_wakeup, do_undos;
889 
890 	DPRINTF(("call to semop(%d, 0x%x, %u)\n", semid, sops, nsops));
891 
892 	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
893 		return (ENOSYS);
894 
895 	semid = IPCID_TO_IX(semid);	/* Convert back to zero origin */
896 
897 	if (semid < 0 || semid >= seminfo.semmni)
898 		return (EINVAL);
899 
900 	/* Allocate memory for sem_ops */
901 	if (nsops > seminfo.semopm) {
902 		DPRINTF(("too many sops (max=%d, nsops=%d)\n", seminfo.semopm,
903 		    nsops));
904 		return (E2BIG);
905 	}
906 	sops = malloc(nsops * sizeof(sops[0]), M_SEM, M_WAITOK);
907 	if ((error = copyin(uap->sops, sops, nsops * sizeof(sops[0]))) != 0) {
908 		DPRINTF(("error = %d from copyin(%08x, %08x, %d)\n", error,
909 		    uap->sops, sops, nsops * sizeof(sops[0])));
910 		free(sops, M_SEM);
911 		return (error);
912 	}
913 
914 	semaptr = &sema[semid];
915 	sema_mtxp = &sema_mtx[semid];
916 	mtx_lock(sema_mtxp);
917 	if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0) {
918 		error = EINVAL;
919 		goto done2;
920 	}
921 	if (semaptr->sem_perm.seq != IPCID_TO_SEQ(uap->semid)) {
922 		error = EINVAL;
923 		goto done2;
924 	}
925 	/*
926 	 * Initial pass thru sops to see what permissions are needed.
927 	 * Also perform any checks that don't need repeating on each
928 	 * attempt to satisfy the request vector.
929 	 */
930 	j = 0;		/* permission needed */
931 	do_undos = 0;
932 	for (i = 0; i < nsops; i++) {
933 		sopptr = &sops[i];
934 		if (sopptr->sem_num >= semaptr->sem_nsems) {
935 			error = EFBIG;
936 			goto done2;
937 		}
938 		if (sopptr->sem_flg & SEM_UNDO && sopptr->sem_op != 0)
939 			do_undos = 1;
940 		j |= (sopptr->sem_op == 0) ? SEM_R : SEM_A;
941 	}
942 
943 	if ((error = ipcperm(td, &semaptr->sem_perm, j))) {
944 		DPRINTF(("error = %d from ipaccess\n", error));
945 		goto done2;
946 	}
947 
948 	/*
949 	 * Loop trying to satisfy the vector of requests.
950 	 * If we reach a point where we must wait, any requests already
951 	 * performed are rolled back and we go to sleep until some other
952 	 * process wakes us up.  At this point, we start all over again.
953 	 *
954 	 * This ensures that from the perspective of other tasks, a set
955 	 * of requests is atomic (never partially satisfied).
956 	 */
957 	for (;;) {
958 		do_wakeup = 0;
959 		error = 0;	/* error return if necessary */
960 
961 		for (i = 0; i < nsops; i++) {
962 			sopptr = &sops[i];
963 			semptr = &semaptr->sem_base[sopptr->sem_num];
964 
965 			DPRINTF((
966 			    "semop:  semaptr=%x, sem_base=%x, "
967 			    "semptr=%x, sem[%d]=%d : op=%d, flag=%s\n",
968 			    semaptr, semaptr->sem_base, semptr,
969 			    sopptr->sem_num, semptr->semval, sopptr->sem_op,
970 			    (sopptr->sem_flg & IPC_NOWAIT) ?
971 			    "nowait" : "wait"));
972 
973 			if (sopptr->sem_op < 0) {
974 				if (semptr->semval + sopptr->sem_op < 0) {
975 					DPRINTF(("semop:  can't do it now\n"));
976 					break;
977 				} else {
978 					semptr->semval += sopptr->sem_op;
979 					if (semptr->semval == 0 &&
980 					    semptr->semzcnt > 0)
981 						do_wakeup = 1;
982 				}
983 			} else if (sopptr->sem_op == 0) {
984 				if (semptr->semval != 0) {
985 					DPRINTF(("semop:  not zero now\n"));
986 					break;
987 				}
988 			} else if (semptr->semval + sopptr->sem_op >
989 			    seminfo.semvmx) {
990 				error = ERANGE;
991 				break;
992 			} else {
993 				if (semptr->semncnt > 0)
994 					do_wakeup = 1;
995 				semptr->semval += sopptr->sem_op;
996 			}
997 		}
998 
999 		/*
1000 		 * Did we get through the entire vector?
1001 		 */
1002 		if (i >= nsops)
1003 			goto done;
1004 
1005 		/*
1006 		 * No ... rollback anything that we've already done
1007 		 */
1008 		DPRINTF(("semop:  rollback 0 through %d\n", i-1));
1009 		for (j = 0; j < i; j++)
1010 			semaptr->sem_base[sops[j].sem_num].semval -=
1011 			    sops[j].sem_op;
1012 
1013 		/* If we detected an error, return it */
1014 		if (error != 0)
1015 			goto done2;
1016 
1017 		/*
1018 		 * If the request that we couldn't satisfy has the
1019 		 * NOWAIT flag set then return with EAGAIN.
1020 		 */
1021 		if (sopptr->sem_flg & IPC_NOWAIT) {
1022 			error = EAGAIN;
1023 			goto done2;
1024 		}
1025 
1026 		if (sopptr->sem_op == 0)
1027 			semptr->semzcnt++;
1028 		else
1029 			semptr->semncnt++;
1030 
1031 		DPRINTF(("semop:  good night!\n"));
1032 		error = msleep(semaptr, sema_mtxp, (PZERO - 4) | PCATCH,
1033 		    "semwait", 0);
1034 		DPRINTF(("semop:  good morning (error=%d)!\n", error));
1035 
1036 		if (error != 0) {
1037 			error = EINTR;
1038 			goto done2;
1039 		}
1040 		DPRINTF(("semop:  good morning!\n"));
1041 
1042 		/*
1043 		 * Make sure that the semaphore still exists
1044 		 */
1045 		if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
1046 		    semaptr->sem_perm.seq != IPCID_TO_SEQ(uap->semid)) {
1047 			error = EIDRM;
1048 			goto done2;
1049 		}
1050 
1051 		/*
1052 		 * The semaphore is still alive.  Readjust the count of
1053 		 * waiting processes.
1054 		 */
1055 		if (sopptr->sem_op == 0)
1056 			semptr->semzcnt--;
1057 		else
1058 			semptr->semncnt--;
1059 	}
1060 
1061 done:
1062 	/*
1063 	 * Process any SEM_UNDO requests.
1064 	 */
1065 	if (do_undos) {
1066 		SEMUNDO_LOCK();
1067 		suptr = NULL;
1068 		for (i = 0; i < nsops; i++) {
1069 			/*
1070 			 * We only need to deal with SEM_UNDO's for non-zero
1071 			 * op's.
1072 			 */
1073 			int adjval;
1074 
1075 			if ((sops[i].sem_flg & SEM_UNDO) == 0)
1076 				continue;
1077 			adjval = sops[i].sem_op;
1078 			if (adjval == 0)
1079 				continue;
1080 			error = semundo_adjust(td, &suptr, semid,
1081 			    sops[i].sem_num, -adjval);
1082 			if (error == 0)
1083 				continue;
1084 
1085 			/*
1086 			 * Oh-Oh!  We ran out of either sem_undo's or undo's.
1087 			 * Rollback the adjustments to this point and then
1088 			 * rollback the semaphore ups and down so we can return
1089 			 * with an error with all structures restored.  We
1090 			 * rollback the undo's in the exact reverse order that
1091 			 * we applied them.  This guarantees that we won't run
1092 			 * out of space as we roll things back out.
1093 			 */
1094 			for (j = 0; j < i; j++) {
1095 				k = i - j - 1;
1096 				if ((sops[k].sem_flg & SEM_UNDO) == 0)
1097 					continue;
1098 				adjval = sops[k].sem_op;
1099 				if (adjval == 0)
1100 					continue;
1101 				if (semundo_adjust(td, &suptr, semid,
1102 				    sops[k].sem_num, adjval) != 0)
1103 					panic("semop - can't undo undos");
1104 			}
1105 
1106 			for (j = 0; j < nsops; j++)
1107 				semaptr->sem_base[sops[j].sem_num].semval -=
1108 				    sops[j].sem_op;
1109 
1110 			DPRINTF(("error = %d from semundo_adjust\n", error));
1111 			SEMUNDO_UNLOCK();
1112 			goto done2;
1113 		} /* loop through the sops */
1114 		SEMUNDO_UNLOCK();
1115 	} /* if (do_undos) */
1116 
1117 	/* We're definitely done - set the sempid's and time */
1118 	for (i = 0; i < nsops; i++) {
1119 		sopptr = &sops[i];
1120 		semptr = &semaptr->sem_base[sopptr->sem_num];
1121 		semptr->sempid = td->td_proc->p_pid;
1122 	}
1123 	semaptr->sem_otime = time_second;
1124 
1125 	/*
1126 	 * Do a wakeup if any semaphore was up'd whilst something was
1127 	 * sleeping on it.
1128 	 */
1129 	if (do_wakeup) {
1130 		DPRINTF(("semop:  doing wakeup\n"));
1131 		wakeup(semaptr);
1132 		DPRINTF(("semop:  back from wakeup\n"));
1133 	}
1134 	DPRINTF(("semop:  done\n"));
1135 	td->td_retval[0] = 0;
1136 done2:
1137 	mtx_unlock(sema_mtxp);
1138 	free(sops, M_SEM);
1139 	return (error);
1140 }
1141 
1142 /*
1143  * Go through the undo structures for this process and apply the adjustments to
1144  * semaphores.
1145  */
1146 static void
1147 semexit_myhook(arg, p)
1148 	void *arg;
1149 	struct proc *p;
1150 {
1151 	struct sem_undo *suptr;
1152 	struct sem_undo **supptr;
1153 
1154 	/*
1155 	 * Go through the chain of undo vectors looking for one
1156 	 * associated with this process.
1157 	 */
1158 	SEMUNDO_LOCK();
1159 	SLIST_FOREACH_PREVPTR(suptr, supptr, &semu_list, un_next) {
1160 		if (suptr->un_proc == p)
1161 			break;
1162 	}
1163 	SEMUNDO_UNLOCK();
1164 
1165 	if (suptr == NULL)
1166 		return;
1167 
1168 	DPRINTF(("proc @%08x has undo structure with %d entries\n", p,
1169 	    suptr->un_cnt));
1170 
1171 	/*
1172 	 * If there are any active undo elements then process them.
1173 	 */
1174 	if (suptr->un_cnt > 0) {
1175 		int ix;
1176 
1177 		for (ix = 0; ix < suptr->un_cnt; ix++) {
1178 			int semid = suptr->un_ent[ix].un_id;
1179 			int semnum = suptr->un_ent[ix].un_num;
1180 			int adjval = suptr->un_ent[ix].un_adjval;
1181 			struct semid_ds *semaptr;
1182 			struct mtx *sema_mtxp;
1183 
1184 			semaptr = &sema[semid];
1185 			sema_mtxp = &sema_mtx[semid];
1186 			mtx_lock(sema_mtxp);
1187 			SEMUNDO_LOCK();
1188 			if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0)
1189 				panic("semexit - semid not allocated");
1190 			if (semnum >= semaptr->sem_nsems)
1191 				panic("semexit - semnum out of range");
1192 
1193 			DPRINTF((
1194 			    "semexit:  %08x id=%d num=%d(adj=%d) ; sem=%d\n",
1195 			    suptr->un_proc, suptr->un_ent[ix].un_id,
1196 			    suptr->un_ent[ix].un_num,
1197 			    suptr->un_ent[ix].un_adjval,
1198 			    semaptr->sem_base[semnum].semval));
1199 
1200 			if (adjval < 0) {
1201 				if (semaptr->sem_base[semnum].semval < -adjval)
1202 					semaptr->sem_base[semnum].semval = 0;
1203 				else
1204 					semaptr->sem_base[semnum].semval +=
1205 					    adjval;
1206 			} else
1207 				semaptr->sem_base[semnum].semval += adjval;
1208 
1209 			wakeup(semaptr);
1210 			DPRINTF(("semexit:  back from wakeup\n"));
1211 			mtx_unlock(sema_mtxp);
1212 			SEMUNDO_UNLOCK();
1213 		}
1214 	}
1215 
1216 	/*
1217 	 * Deallocate the undo vector.
1218 	 */
1219 	DPRINTF(("removing vector\n"));
1220 	suptr->un_proc = NULL;
1221 	*supptr = SLIST_NEXT(suptr, un_next);
1222 }
1223 
1224 static int
1225 sysctl_sema(SYSCTL_HANDLER_ARGS)
1226 {
1227 
1228 	return (SYSCTL_OUT(req, sema,
1229 	    sizeof(struct semid_ds) * seminfo.semmni));
1230 }
1231