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