xref: /freebsd/sys/kern/sysv_sem.c (revision dce6e6518b85561495cff38a3074a69d29d58a55)
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 		u_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 >= sizeof(semcalls)/sizeof(semcalls[0]))
290 		return (EINVAL);
291 	error = (*semcalls[uap->which])(td, &uap->a2);
292 	return (error);
293 }
294 
295 /*
296  * Allocate a new sem_undo structure for a process
297  * (returns ptr to structure or NULL if no more room)
298  */
299 
300 static struct sem_undo *
301 semu_alloc(td)
302 	struct thread *td;
303 {
304 	int i;
305 	struct sem_undo *suptr;
306 	struct sem_undo **supptr;
307 	int attempt;
308 
309 	SEMUNDO_LOCKASSERT(MA_OWNED);
310 	/*
311 	 * Try twice to allocate something.
312 	 * (we'll purge any empty structures after the first pass so
313 	 * two passes are always enough)
314 	 */
315 
316 	for (attempt = 0; attempt < 2; attempt++) {
317 		/*
318 		 * Look for a free structure.
319 		 * Fill it in and return it if we find one.
320 		 */
321 
322 		for (i = 0; i < seminfo.semmnu; i++) {
323 			suptr = SEMU(i);
324 			if (suptr->un_proc == NULL) {
325 				SLIST_INSERT_HEAD(&semu_list, suptr, un_next);
326 				suptr->un_cnt = 0;
327 				suptr->un_proc = td->td_proc;
328 				return(suptr);
329 			}
330 		}
331 
332 		/*
333 		 * We didn't find a free one, if this is the first attempt
334 		 * then try to free some structures.
335 		 */
336 
337 		if (attempt == 0) {
338 			/* All the structures are in use - try to free some */
339 			int did_something = 0;
340 
341 			SLIST_FOREACH_PREVPTR(suptr, supptr, &semu_list,
342 			    un_next) {
343 				if (suptr->un_cnt == 0) {
344 					suptr->un_proc = NULL;
345 					did_something = 1;
346 					*supptr = SLIST_NEXT(suptr, un_next);
347 				}
348 			}
349 
350 			/* If we didn't free anything then just give-up */
351 			if (!did_something)
352 				return(NULL);
353 		} else {
354 			/*
355 			 * The second pass failed even though we freed
356 			 * something after the first pass!
357 			 * This is IMPOSSIBLE!
358 			 */
359 			panic("semu_alloc - second attempt failed");
360 		}
361 	}
362 	return (NULL);
363 }
364 
365 /*
366  * Adjust a particular entry for a particular proc
367  */
368 
369 static int
370 semundo_adjust(td, supptr, semid, semnum, adjval)
371 	struct thread *td;
372 	struct sem_undo **supptr;
373 	int semid, semnum;
374 	int adjval;
375 {
376 	struct proc *p = td->td_proc;
377 	struct sem_undo *suptr;
378 	struct undo *sunptr;
379 	int i;
380 
381 	SEMUNDO_LOCKASSERT(MA_OWNED);
382 	/* Look for and remember the sem_undo if the caller doesn't provide
383 	   it */
384 
385 	suptr = *supptr;
386 	if (suptr == NULL) {
387 		SLIST_FOREACH(suptr, &semu_list, un_next) {
388 			if (suptr->un_proc == p) {
389 				*supptr = suptr;
390 				break;
391 			}
392 		}
393 		if (suptr == NULL) {
394 			if (adjval == 0)
395 				return(0);
396 			suptr = semu_alloc(td);
397 			if (suptr == NULL)
398 				return(ENOSPC);
399 			*supptr = suptr;
400 		}
401 	}
402 
403 	/*
404 	 * Look for the requested entry and adjust it (delete if adjval becomes
405 	 * 0).
406 	 */
407 	sunptr = &suptr->un_ent[0];
408 	for (i = 0; i < suptr->un_cnt; i++, sunptr++) {
409 		if (sunptr->un_id != semid || sunptr->un_num != semnum)
410 			continue;
411 		if (adjval != 0) {
412 			adjval += sunptr->un_adjval;
413 			if (adjval > seminfo.semaem || adjval < -seminfo.semaem)
414 				return (ERANGE);
415 		}
416 		sunptr->un_adjval = adjval;
417 		if (sunptr->un_adjval == 0) {
418 			suptr->un_cnt--;
419 			if (i < suptr->un_cnt)
420 				suptr->un_ent[i] =
421 				    suptr->un_ent[suptr->un_cnt];
422 		}
423 		return(0);
424 	}
425 
426 	/* Didn't find the right entry - create it */
427 	if (adjval == 0)
428 		return(0);
429 	if (adjval > seminfo.semaem || adjval < -seminfo.semaem)
430 		return (ERANGE);
431 	if (suptr->un_cnt != seminfo.semume) {
432 		sunptr = &suptr->un_ent[suptr->un_cnt];
433 		suptr->un_cnt++;
434 		sunptr->un_adjval = adjval;
435 		sunptr->un_id = semid; sunptr->un_num = semnum;
436 	} else
437 		return(EINVAL);
438 	return(0);
439 }
440 
441 static void
442 semundo_clear(semid, semnum)
443 	int semid, semnum;
444 {
445 	struct sem_undo *suptr;
446 
447 	SEMUNDO_LOCKASSERT(MA_OWNED);
448 	SLIST_FOREACH(suptr, &semu_list, un_next) {
449 		struct undo *sunptr = &suptr->un_ent[0];
450 		int i = 0;
451 
452 		while (i < suptr->un_cnt) {
453 			if (sunptr->un_id == semid) {
454 				if (semnum == -1 || sunptr->un_num == semnum) {
455 					suptr->un_cnt--;
456 					if (i < suptr->un_cnt) {
457 						suptr->un_ent[i] =
458 						  suptr->un_ent[suptr->un_cnt];
459 						continue;
460 					}
461 				}
462 				if (semnum != -1)
463 					break;
464 			}
465 			i++, sunptr++;
466 		}
467 	}
468 }
469 
470 static int
471 semvalid(semid, semaptr)
472 	int semid;
473 	struct semid_ds *semaptr;
474 {
475 
476 	return ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
477 	    semaptr->sem_perm.seq != IPCID_TO_SEQ(semid) ? EINVAL : 0);
478 }
479 
480 /*
481  * Note that the user-mode half of this passes a union, not a pointer
482  */
483 #ifndef _SYS_SYSPROTO_H_
484 struct __semctl_args {
485 	int	semid;
486 	int	semnum;
487 	int	cmd;
488 	union	semun *arg;
489 };
490 #endif
491 
492 /*
493  * MPSAFE
494  */
495 int
496 __semctl(td, uap)
497 	struct thread *td;
498 	struct __semctl_args *uap;
499 {
500 	int semid = uap->semid;
501 	int semnum = uap->semnum;
502 	int cmd = uap->cmd;
503 	u_short *array;
504 	union semun *arg = uap->arg;
505 	union semun real_arg;
506 	struct ucred *cred = td->td_ucred;
507 	int i, rval, error;
508 	struct semid_ds sbuf;
509 	struct semid_ds *semaptr;
510 	struct mtx *sema_mtxp;
511 	u_short usval, count;
512 
513 	DPRINTF(("call to semctl(%d, %d, %d, 0x%x)\n",
514 	    semid, semnum, cmd, arg));
515 	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
516 		return (ENOSYS);
517 
518 	array = NULL;
519 
520 	switch(cmd) {
521 	case SEM_STAT:
522 		if (semid < 0 || semid >= seminfo.semmni)
523 			return (EINVAL);
524 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
525 			return (error);
526 		semaptr = &sema[semid];
527 		sema_mtxp = &sema_mtx[semid];
528 		mtx_lock(sema_mtxp);
529 		if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ) {
530 			error = EINVAL;
531 			goto done2;
532 		}
533 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
534 			goto done2;
535 		mtx_unlock(sema_mtxp);
536 		error = copyout(semaptr, real_arg.buf, sizeof(struct semid_ds));
537 		rval = IXSEQ_TO_IPCID(semid,semaptr->sem_perm);
538 		if (error == 0)
539 			td->td_retval[0] = rval;
540 		return (error);
541 	}
542 
543 	semid = IPCID_TO_IX(semid);
544 	if (semid < 0 || semid >= seminfo.semmni)
545 		return (EINVAL);
546 
547 	semaptr = &sema[semid];
548 	sema_mtxp = &sema_mtx[semid];
549 
550 	error = 0;
551 	rval = 0;
552 
553 	switch (cmd) {
554 	case IPC_RMID:
555 		mtx_lock(sema_mtxp);
556 		if ((error = semvalid(uap->semid, semaptr)) != 0)
557 			goto done2;
558 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_M)))
559 			goto done2;
560 		semaptr->sem_perm.cuid = cred->cr_uid;
561 		semaptr->sem_perm.uid = cred->cr_uid;
562 		semtot -= semaptr->sem_nsems;
563 		for (i = semaptr->sem_base - sem; i < semtot; i++)
564 			sem[i] = sem[i + semaptr->sem_nsems];
565 		for (i = 0; i < seminfo.semmni; i++) {
566 			if ((sema[i].sem_perm.mode & SEM_ALLOC) &&
567 			    sema[i].sem_base > semaptr->sem_base)
568 				sema[i].sem_base -= semaptr->sem_nsems;
569 		}
570 		semaptr->sem_perm.mode = 0;
571 		SEMUNDO_LOCK();
572 		semundo_clear(semid, -1);
573 		SEMUNDO_UNLOCK();
574 		wakeup(semaptr);
575 		break;
576 
577 	case IPC_SET:
578 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
579 			goto done2;
580 		if ((error = copyin(real_arg.buf, &sbuf, sizeof(sbuf))) != 0)
581 			goto done2;
582 		mtx_lock(sema_mtxp);
583 		if ((error = semvalid(uap->semid, semaptr)) != 0)
584 			goto done2;
585 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_M)))
586 			goto done2;
587 		semaptr->sem_perm.uid = sbuf.sem_perm.uid;
588 		semaptr->sem_perm.gid = sbuf.sem_perm.gid;
589 		semaptr->sem_perm.mode = (semaptr->sem_perm.mode & ~0777) |
590 		    (sbuf.sem_perm.mode & 0777);
591 		semaptr->sem_ctime = time_second;
592 		break;
593 
594 	case IPC_STAT:
595 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
596 			goto done2;
597 		mtx_lock(sema_mtxp);
598 		if ((error = semvalid(uap->semid, semaptr)) != 0)
599 			goto done2;
600 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
601 			goto done2;
602 		sbuf = *semaptr;
603 		mtx_unlock(sema_mtxp);
604 		error = copyout(semaptr, real_arg.buf,
605 				sizeof(struct semid_ds));
606 		break;
607 
608 	case GETNCNT:
609 		mtx_lock(sema_mtxp);
610 		if ((error = semvalid(uap->semid, semaptr)) != 0)
611 			goto done2;
612 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
613 			goto done2;
614 		if (semnum < 0 || semnum >= semaptr->sem_nsems) {
615 			error = EINVAL;
616 			goto done2;
617 		}
618 		rval = semaptr->sem_base[semnum].semncnt;
619 		break;
620 
621 	case GETPID:
622 		mtx_lock(sema_mtxp);
623 		if ((error = semvalid(uap->semid, semaptr)) != 0)
624 			goto done2;
625 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
626 			goto done2;
627 		if (semnum < 0 || semnum >= semaptr->sem_nsems) {
628 			error = EINVAL;
629 			goto done2;
630 		}
631 		rval = semaptr->sem_base[semnum].sempid;
632 		break;
633 
634 	case GETVAL:
635 		mtx_lock(sema_mtxp);
636 		if ((error = semvalid(uap->semid, semaptr)) != 0)
637 			goto done2;
638 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
639 			goto done2;
640 		if (semnum < 0 || semnum >= semaptr->sem_nsems) {
641 			error = EINVAL;
642 			goto done2;
643 		}
644 		rval = semaptr->sem_base[semnum].semval;
645 		break;
646 
647 	case GETALL:
648 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
649 			goto done2;
650 		array = malloc(sizeof(*array) * semaptr->sem_nsems, M_TEMP,
651 		    M_WAITOK);
652 		mtx_lock(sema_mtxp);
653 		if ((error = semvalid(uap->semid, semaptr)) != 0)
654 			goto done2;
655 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
656 			goto done2;
657 		for (i = 0; i < semaptr->sem_nsems; i++)
658 			array[i] = semaptr->sem_base[i].semval;
659 		mtx_unlock(sema_mtxp);
660 		error = copyout(array, real_arg.array,
661 		    i * sizeof(real_arg.array[0]));
662 		break;
663 
664 	case GETZCNT:
665 		mtx_lock(sema_mtxp);
666 		if ((error = semvalid(uap->semid, semaptr)) != 0)
667 			goto done2;
668 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_R)))
669 			goto done2;
670 		if (semnum < 0 || semnum >= semaptr->sem_nsems) {
671 			error = EINVAL;
672 			goto done2;
673 		}
674 		rval = semaptr->sem_base[semnum].semzcnt;
675 		break;
676 
677 	case SETVAL:
678 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
679 			goto done2;
680 		mtx_lock(sema_mtxp);
681 		if ((error = semvalid(uap->semid, semaptr)) != 0)
682 			goto done2;
683 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_W)))
684 			goto done2;
685 		if (semnum < 0 || semnum >= semaptr->sem_nsems) {
686 			error = EINVAL;
687 			goto done2;
688 		}
689 		if (real_arg.val < 0 || real_arg.val > seminfo.semvmx) {
690 			error = ERANGE;
691 			goto done2;
692 		}
693 		semaptr->sem_base[semnum].semval = real_arg.val;
694 		SEMUNDO_LOCK();
695 		semundo_clear(semid, semnum);
696 		SEMUNDO_UNLOCK();
697 		wakeup(semaptr);
698 		break;
699 
700 	case SETALL:
701 		mtx_lock(sema_mtxp);
702 raced:
703 		if ((error = semvalid(uap->semid, semaptr)) != 0)
704 			goto done2;
705 		count = semaptr->sem_nsems;
706 		mtx_unlock(sema_mtxp);
707 		if ((error = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
708 			goto done2;
709 		array = malloc(sizeof(*array) * count, M_TEMP, M_WAITOK);
710 		copyin(real_arg.array, array, count * sizeof(*array));
711 		if (error)
712 			break;
713 		mtx_lock(sema_mtxp);
714 		if ((error = semvalid(uap->semid, semaptr)) != 0)
715 			goto done2;
716 		/* we could have raced? */
717 		if (count != semaptr->sem_nsems) {
718 			free(array, M_TEMP);
719 			array = NULL;
720 			goto raced;
721 		}
722 		if ((error = ipcperm(td, &semaptr->sem_perm, IPC_W)))
723 			goto done2;
724 		for (i = 0; i < semaptr->sem_nsems; i++) {
725 			usval = array[i];
726 			if (usval > seminfo.semvmx) {
727 				error = ERANGE;
728 				break;
729 			}
730 			semaptr->sem_base[i].semval = usval;
731 		}
732 		SEMUNDO_LOCK();
733 		semundo_clear(semid, -1);
734 		SEMUNDO_UNLOCK();
735 		wakeup(semaptr);
736 		break;
737 
738 	default:
739 		error = EINVAL;
740 		break;
741 	}
742 
743 	if (error == 0)
744 		td->td_retval[0] = rval;
745 done2:
746 	if (mtx_owned(sema_mtxp))
747 		mtx_unlock(sema_mtxp);
748 	if (array != NULL)
749 		free(array, M_TEMP);
750 	return(error);
751 }
752 
753 #ifndef _SYS_SYSPROTO_H_
754 struct semget_args {
755 	key_t	key;
756 	int	nsems;
757 	int	semflg;
758 };
759 #endif
760 
761 /*
762  * MPSAFE
763  */
764 int
765 semget(td, uap)
766 	struct thread *td;
767 	struct semget_args *uap;
768 {
769 	int semid, error = 0;
770 	int key = uap->key;
771 	int nsems = uap->nsems;
772 	int semflg = uap->semflg;
773 	struct ucred *cred = td->td_ucred;
774 
775 	DPRINTF(("semget(0x%x, %d, 0%o)\n", key, nsems, semflg));
776 	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
777 		return (ENOSYS);
778 
779 	mtx_lock(&Giant);
780 	if (key != IPC_PRIVATE) {
781 		for (semid = 0; semid < seminfo.semmni; semid++) {
782 			if ((sema[semid].sem_perm.mode & SEM_ALLOC) &&
783 			    sema[semid].sem_perm.key == key)
784 				break;
785 		}
786 		if (semid < seminfo.semmni) {
787 			DPRINTF(("found public key\n"));
788 			if ((error = ipcperm(td, &sema[semid].sem_perm,
789 			    semflg & 0700))) {
790 				goto done2;
791 			}
792 			if (nsems > 0 && sema[semid].sem_nsems < nsems) {
793 				DPRINTF(("too small\n"));
794 				error = EINVAL;
795 				goto done2;
796 			}
797 			if ((semflg & IPC_CREAT) && (semflg & IPC_EXCL)) {
798 				DPRINTF(("not exclusive\n"));
799 				error = EEXIST;
800 				goto done2;
801 			}
802 			goto found;
803 		}
804 	}
805 
806 	DPRINTF(("need to allocate the semid_ds\n"));
807 	if (key == IPC_PRIVATE || (semflg & IPC_CREAT)) {
808 		if (nsems <= 0 || nsems > seminfo.semmsl) {
809 			DPRINTF(("nsems out of range (0<%d<=%d)\n", nsems,
810 			    seminfo.semmsl));
811 			error = EINVAL;
812 			goto done2;
813 		}
814 		if (nsems > seminfo.semmns - semtot) {
815 			DPRINTF((
816 			    "not enough semaphores left (need %d, got %d)\n",
817 			    nsems, seminfo.semmns - semtot));
818 			error = ENOSPC;
819 			goto done2;
820 		}
821 		for (semid = 0; semid < seminfo.semmni; semid++) {
822 			if ((sema[semid].sem_perm.mode & SEM_ALLOC) == 0)
823 				break;
824 		}
825 		if (semid == seminfo.semmni) {
826 			DPRINTF(("no more semid_ds's available\n"));
827 			error = ENOSPC;
828 			goto done2;
829 		}
830 		DPRINTF(("semid %d is available\n", semid));
831 		sema[semid].sem_perm.key = key;
832 		sema[semid].sem_perm.cuid = cred->cr_uid;
833 		sema[semid].sem_perm.uid = cred->cr_uid;
834 		sema[semid].sem_perm.cgid = cred->cr_gid;
835 		sema[semid].sem_perm.gid = cred->cr_gid;
836 		sema[semid].sem_perm.mode = (semflg & 0777) | SEM_ALLOC;
837 		sema[semid].sem_perm.seq =
838 		    (sema[semid].sem_perm.seq + 1) & 0x7fff;
839 		sema[semid].sem_nsems = nsems;
840 		sema[semid].sem_otime = 0;
841 		sema[semid].sem_ctime = time_second;
842 		sema[semid].sem_base = &sem[semtot];
843 		semtot += nsems;
844 		bzero(sema[semid].sem_base,
845 		    sizeof(sema[semid].sem_base[0])*nsems);
846 		DPRINTF(("sembase = 0x%x, next = 0x%x\n", sema[semid].sem_base,
847 		    &sem[semtot]));
848 	} else {
849 		DPRINTF(("didn't find it and wasn't asked to create it\n"));
850 		error = ENOENT;
851 		goto done2;
852 	}
853 
854 found:
855 	td->td_retval[0] = IXSEQ_TO_IPCID(semid, sema[semid].sem_perm);
856 done2:
857 	mtx_unlock(&Giant);
858 	return (error);
859 }
860 
861 #ifndef _SYS_SYSPROTO_H_
862 struct semop_args {
863 	int	semid;
864 	struct	sembuf *sops;
865 	size_t	nsops;
866 };
867 #endif
868 
869 /*
870  * MPSAFE
871  */
872 int
873 semop(td, uap)
874 	struct thread *td;
875 	struct semop_args *uap;
876 {
877 	int semid = uap->semid;
878 	size_t nsops = uap->nsops;
879 	struct sembuf *sops;
880 	struct semid_ds *semaptr;
881 	struct sembuf *sopptr = 0;
882 	struct sem *semptr = 0;
883 	struct sem_undo *suptr;
884 	struct mtx *sema_mtxp;
885 	size_t i, j, k;
886 	int error;
887 	int do_wakeup, do_undos;
888 
889 	DPRINTF(("call to semop(%d, 0x%x, %u)\n", semid, sops, nsops));
890 
891 	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
892 		return (ENOSYS);
893 
894 	semid = IPCID_TO_IX(semid);	/* Convert back to zero origin */
895 
896 	if (semid < 0 || semid >= seminfo.semmni)
897 		return (EINVAL);
898 
899 	/* Allocate memory for sem_ops */
900 	if (nsops > seminfo.semopm) {
901 		DPRINTF(("too many sops (max=%d, nsops=%d)\n", seminfo.semopm,
902 		    nsops));
903 		return (E2BIG);
904 	}
905 	sops = malloc(nsops * sizeof(sops[0]), M_SEM, M_WAITOK);
906 	if ((error = copyin(uap->sops, sops, nsops * sizeof(sops[0]))) != 0) {
907 		DPRINTF(("error = %d from copyin(%08x, %08x, %d)\n", error,
908 		    uap->sops, sops, nsops * sizeof(sops[0])));
909 		free(sops, M_SEM);
910 		return (error);
911 	}
912 
913 	semaptr = &sema[semid];
914 	sema_mtxp = &sema_mtx[semid];
915 	mtx_lock(sema_mtxp);
916 	if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0) {
917 		error = EINVAL;
918 		goto done2;
919 	}
920 	if (semaptr->sem_perm.seq != IPCID_TO_SEQ(uap->semid)) {
921 		error = EINVAL;
922 		goto done2;
923 	}
924 	/*
925 	 * Initial pass thru sops to see what permissions are needed.
926 	 * Also perform any checks that don't need repeating on each
927 	 * attempt to satisfy the request vector.
928 	 */
929 	j = 0;		/* permission needed */
930 	do_undos = 0;
931 	for (i = 0; i < nsops; i++) {
932 		sopptr = &sops[i];
933 		if (sopptr->sem_num >= semaptr->sem_nsems) {
934 			error = EFBIG;
935 			goto done2;
936 		}
937 		if (sopptr->sem_flg & SEM_UNDO && sopptr->sem_op != 0)
938 			do_undos = 1;
939 		j |= (sopptr->sem_op == 0) ? SEM_R : SEM_A;
940 	}
941 
942 	if ((error = ipcperm(td, &semaptr->sem_perm, j))) {
943 		DPRINTF(("error = %d from ipaccess\n", error));
944 		goto done2;
945 	}
946 
947 	/*
948 	 * Loop trying to satisfy the vector of requests.
949 	 * If we reach a point where we must wait, any requests already
950 	 * performed are rolled back and we go to sleep until some other
951 	 * process wakes us up.  At this point, we start all over again.
952 	 *
953 	 * This ensures that from the perspective of other tasks, a set
954 	 * of requests is atomic (never partially satisfied).
955 	 */
956 	for (;;) {
957 		do_wakeup = 0;
958 		error = 0;	/* error return if necessary */
959 
960 		for (i = 0; i < nsops; i++) {
961 			sopptr = &sops[i];
962 			semptr = &semaptr->sem_base[sopptr->sem_num];
963 
964 			DPRINTF((
965 			    "semop:  semaptr=%x, sem_base=%x, "
966 			    "semptr=%x, sem[%d]=%d : op=%d, flag=%s\n",
967 			    semaptr, semaptr->sem_base, semptr,
968 			    sopptr->sem_num, semptr->semval, sopptr->sem_op,
969 			    (sopptr->sem_flg & IPC_NOWAIT) ?
970 			    "nowait" : "wait"));
971 
972 			if (sopptr->sem_op < 0) {
973 				if (semptr->semval + sopptr->sem_op < 0) {
974 					DPRINTF(("semop:  can't do it now\n"));
975 					break;
976 				} else {
977 					semptr->semval += sopptr->sem_op;
978 					if (semptr->semval == 0 &&
979 					    semptr->semzcnt > 0)
980 						do_wakeup = 1;
981 				}
982 			} else if (sopptr->sem_op == 0) {
983 				if (semptr->semval != 0) {
984 					DPRINTF(("semop:  not zero now\n"));
985 					break;
986 				}
987 			} else if (semptr->semval + sopptr->sem_op >
988 			    seminfo.semvmx) {
989 				error = ERANGE;
990 				break;
991 			} else {
992 				if (semptr->semncnt > 0)
993 					do_wakeup = 1;
994 				semptr->semval += sopptr->sem_op;
995 			}
996 		}
997 
998 		/*
999 		 * Did we get through the entire vector?
1000 		 */
1001 		if (i >= nsops)
1002 			goto done;
1003 
1004 		/*
1005 		 * No ... rollback anything that we've already done
1006 		 */
1007 		DPRINTF(("semop:  rollback 0 through %d\n", i-1));
1008 		for (j = 0; j < i; j++)
1009 			semaptr->sem_base[sops[j].sem_num].semval -=
1010 			    sops[j].sem_op;
1011 
1012 		/* If we detected an error, return it */
1013 		if (error != 0)
1014 			goto done2;
1015 
1016 		/*
1017 		 * If the request that we couldn't satisfy has the
1018 		 * NOWAIT flag set then return with EAGAIN.
1019 		 */
1020 		if (sopptr->sem_flg & IPC_NOWAIT) {
1021 			error = EAGAIN;
1022 			goto done2;
1023 		}
1024 
1025 		if (sopptr->sem_op == 0)
1026 			semptr->semzcnt++;
1027 		else
1028 			semptr->semncnt++;
1029 
1030 		DPRINTF(("semop:  good night!\n"));
1031 		error = msleep(semaptr, sema_mtxp, (PZERO - 4) | PCATCH,
1032 		    "semwait", 0);
1033 		DPRINTF(("semop:  good morning (error=%d)!\n", error));
1034 
1035 		if (error != 0) {
1036 			error = EINTR;
1037 			goto done2;
1038 		}
1039 		DPRINTF(("semop:  good morning!\n"));
1040 
1041 		/*
1042 		 * Make sure that the semaphore still exists
1043 		 */
1044 		if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
1045 		    semaptr->sem_perm.seq != IPCID_TO_SEQ(uap->semid)) {
1046 			error = EIDRM;
1047 			goto done2;
1048 		}
1049 
1050 		/*
1051 		 * The semaphore is still alive.  Readjust the count of
1052 		 * waiting processes.
1053 		 */
1054 		if (sopptr->sem_op == 0)
1055 			semptr->semzcnt--;
1056 		else
1057 			semptr->semncnt--;
1058 	}
1059 
1060 done:
1061 	/*
1062 	 * Process any SEM_UNDO requests.
1063 	 */
1064 	if (do_undos) {
1065 		SEMUNDO_LOCK();
1066 		suptr = NULL;
1067 		for (i = 0; i < nsops; i++) {
1068 			/*
1069 			 * We only need to deal with SEM_UNDO's for non-zero
1070 			 * op's.
1071 			 */
1072 			int adjval;
1073 
1074 			if ((sops[i].sem_flg & SEM_UNDO) == 0)
1075 				continue;
1076 			adjval = sops[i].sem_op;
1077 			if (adjval == 0)
1078 				continue;
1079 			error = semundo_adjust(td, &suptr, semid,
1080 			    sops[i].sem_num, -adjval);
1081 			if (error == 0)
1082 				continue;
1083 
1084 			/*
1085 			 * Oh-Oh!  We ran out of either sem_undo's or undo's.
1086 			 * Rollback the adjustments to this point and then
1087 			 * rollback the semaphore ups and down so we can return
1088 			 * with an error with all structures restored.  We
1089 			 * rollback the undo's in the exact reverse order that
1090 			 * we applied them.  This guarantees that we won't run
1091 			 * out of space as we roll things back out.
1092 			 */
1093 			for (j = 0; j < i; j++) {
1094 				k = i - j - 1;
1095 				if ((sops[k].sem_flg & SEM_UNDO) == 0)
1096 					continue;
1097 				adjval = sops[k].sem_op;
1098 				if (adjval == 0)
1099 					continue;
1100 				if (semundo_adjust(td, &suptr, semid,
1101 				    sops[k].sem_num, adjval) != 0)
1102 					panic("semop - can't undo undos");
1103 			}
1104 
1105 			for (j = 0; j < nsops; j++)
1106 				semaptr->sem_base[sops[j].sem_num].semval -=
1107 				    sops[j].sem_op;
1108 
1109 			DPRINTF(("error = %d from semundo_adjust\n", error));
1110 			SEMUNDO_UNLOCK();
1111 			goto done2;
1112 		} /* loop through the sops */
1113 		SEMUNDO_UNLOCK();
1114 	} /* if (do_undos) */
1115 
1116 	/* We're definitely done - set the sempid's and time */
1117 	for (i = 0; i < nsops; i++) {
1118 		sopptr = &sops[i];
1119 		semptr = &semaptr->sem_base[sopptr->sem_num];
1120 		semptr->sempid = td->td_proc->p_pid;
1121 	}
1122 	semaptr->sem_otime = time_second;
1123 
1124 	/*
1125 	 * Do a wakeup if any semaphore was up'd whilst something was
1126 	 * sleeping on it.
1127 	 */
1128 	if (do_wakeup) {
1129 		DPRINTF(("semop:  doing wakeup\n"));
1130 		wakeup(semaptr);
1131 		DPRINTF(("semop:  back from wakeup\n"));
1132 	}
1133 	DPRINTF(("semop:  done\n"));
1134 	td->td_retval[0] = 0;
1135 done2:
1136 	mtx_unlock(sema_mtxp);
1137 	free(sops, M_SEM);
1138 	return (error);
1139 }
1140 
1141 /*
1142  * Go through the undo structures for this process and apply the adjustments to
1143  * semaphores.
1144  */
1145 static void
1146 semexit_myhook(arg, p)
1147 	void *arg;
1148 	struct proc *p;
1149 {
1150 	struct sem_undo *suptr;
1151 	struct sem_undo **supptr;
1152 
1153 	/*
1154 	 * Go through the chain of undo vectors looking for one
1155 	 * associated with this process.
1156 	 */
1157 	SEMUNDO_LOCK();
1158 	SLIST_FOREACH_PREVPTR(suptr, supptr, &semu_list, un_next) {
1159 		if (suptr->un_proc == p)
1160 			break;
1161 	}
1162 	SEMUNDO_UNLOCK();
1163 
1164 	if (suptr == NULL)
1165 		return;
1166 
1167 	DPRINTF(("proc @%08x has undo structure with %d entries\n", p,
1168 	    suptr->un_cnt));
1169 
1170 	/*
1171 	 * If there are any active undo elements then process them.
1172 	 */
1173 	if (suptr->un_cnt > 0) {
1174 		int ix;
1175 
1176 		for (ix = 0; ix < suptr->un_cnt; ix++) {
1177 			int semid = suptr->un_ent[ix].un_id;
1178 			int semnum = suptr->un_ent[ix].un_num;
1179 			int adjval = suptr->un_ent[ix].un_adjval;
1180 			struct semid_ds *semaptr;
1181 			struct mtx *sema_mtxp;
1182 
1183 			semaptr = &sema[semid];
1184 			sema_mtxp = &sema_mtx[semid];
1185 			mtx_lock(sema_mtxp);
1186 			SEMUNDO_LOCK();
1187 			if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0)
1188 				panic("semexit - semid not allocated");
1189 			if (semnum >= semaptr->sem_nsems)
1190 				panic("semexit - semnum out of range");
1191 
1192 			DPRINTF((
1193 			    "semexit:  %08x id=%d num=%d(adj=%d) ; sem=%d\n",
1194 			    suptr->un_proc, suptr->un_ent[ix].un_id,
1195 			    suptr->un_ent[ix].un_num,
1196 			    suptr->un_ent[ix].un_adjval,
1197 			    semaptr->sem_base[semnum].semval));
1198 
1199 			if (adjval < 0) {
1200 				if (semaptr->sem_base[semnum].semval < -adjval)
1201 					semaptr->sem_base[semnum].semval = 0;
1202 				else
1203 					semaptr->sem_base[semnum].semval +=
1204 					    adjval;
1205 			} else
1206 				semaptr->sem_base[semnum].semval += adjval;
1207 
1208 			wakeup(semaptr);
1209 			DPRINTF(("semexit:  back from wakeup\n"));
1210 			mtx_unlock(sema_mtxp);
1211 			SEMUNDO_UNLOCK();
1212 		}
1213 	}
1214 
1215 	/*
1216 	 * Deallocate the undo vector.
1217 	 */
1218 	DPRINTF(("removing vector\n"));
1219 	suptr->un_proc = NULL;
1220 	*supptr = SLIST_NEXT(suptr, un_next);
1221 }
1222 
1223 static int
1224 sysctl_sema(SYSCTL_HANDLER_ARGS)
1225 {
1226 
1227 	return (SYSCTL_OUT(req, sema,
1228 	    sizeof(struct semid_ds) * seminfo.semmni));
1229 }
1230