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