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