xref: /netbsd-src/sys/kern/sysv_sem.c (revision 89c5a767f8fc7a4633b2d409966e2becbb98ff92)
1 /*	$NetBSD: sysv_sem.c,v 1.34 2000/01/31 15:12:30 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1999 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9  * NASA Ames Research Center.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by the NetBSD
22  *	Foundation, Inc. and its contributors.
23  * 4. Neither the name of The NetBSD Foundation nor the names of its
24  *    contributors may be used to endorse or promote products derived
25  *    from this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 /*
41  * Implementation of SVID semaphores
42  *
43  * Author: Daniel Boulet
44  *
45  * This software is provided ``AS IS'' without any warranties of any kind.
46  */
47 
48 #define SYSVSEM
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/kernel.h>
53 #include <sys/proc.h>
54 #include <sys/sem.h>
55 #include <sys/malloc.h>
56 
57 #include <sys/mount.h>
58 #include <sys/syscallargs.h>
59 
60 int	semtot = 0;
61 struct	proc *semlock_holder = NULL;
62 
63 #ifdef SEM_DEBUG
64 #define SEM_PRINTF(a) printf a
65 #else
66 #define SEM_PRINTF(a)
67 #endif
68 
69 void semlock __P((struct proc *));
70 struct sem_undo *semu_alloc __P((struct proc *));
71 int semundo_adjust __P((struct proc *, struct sem_undo **, int, int, int));
72 void semundo_clear __P((int, int));
73 
74 void
75 seminit()
76 {
77 	register int i;
78 
79 	if (sema == NULL)
80 		panic("sema is NULL");
81 	if (semu == NULL)
82 		panic("semu is NULL");
83 
84 	for (i = 0; i < seminfo.semmni; i++) {
85 		sema[i]._sem_base = 0;
86 		sema[i].sem_perm.mode = 0;
87 	}
88 	for (i = 0; i < seminfo.semmnu; i++) {
89 		register struct sem_undo *suptr = SEMU(i);
90 		suptr->un_proc = NULL;
91 	}
92 	semu_list = NULL;
93 }
94 
95 void
96 semlock(p)
97 	struct proc *p;
98 {
99 
100 	while (semlock_holder != NULL && semlock_holder != p)
101 		sleep((caddr_t)&semlock_holder, (PZERO - 4));
102 }
103 
104 /*
105  * Lock or unlock the entire semaphore facility.
106  *
107  * This will probably eventually evolve into a general purpose semaphore
108  * facility status enquiry mechanism (I don't like the "read /dev/kmem"
109  * approach currently taken by ipcs and the amount of info that we want
110  * to be able to extract for ipcs is probably beyond the capability of
111  * the getkerninfo facility.
112  *
113  * At the time that the current version of semconfig was written, ipcs is
114  * the only user of the semconfig facility.  It uses it to ensure that the
115  * semaphore facility data structures remain static while it fishes around
116  * in /dev/kmem.
117  */
118 
119 int
120 sys_semconfig(p, v, retval)
121 	struct proc *p;
122 	void *v;
123 	register_t *retval;
124 {
125 	struct sys_semconfig_args /* {
126 		syscallarg(int) flag;
127 	} */ *uap = v;
128 	int eval = 0;
129 
130 	semlock(p);
131 
132 	switch (SCARG(uap, flag)) {
133 	case SEM_CONFIG_FREEZE:
134 		semlock_holder = p;
135 		break;
136 
137 	case SEM_CONFIG_THAW:
138 		semlock_holder = NULL;
139 		wakeup((caddr_t)&semlock_holder);
140 		break;
141 
142 	default:
143 		printf(
144 		    "semconfig: unknown flag parameter value (%d) - ignored\n",
145 		    SCARG(uap, flag));
146 		eval = EINVAL;
147 		break;
148 	}
149 
150 	*retval = 0;
151 	return(eval);
152 }
153 
154 /*
155  * Allocate a new sem_undo structure for a process
156  * (returns ptr to structure or NULL if no more room)
157  */
158 
159 struct sem_undo *
160 semu_alloc(p)
161 	struct proc *p;
162 {
163 	register int i;
164 	register struct sem_undo *suptr;
165 	register struct sem_undo **supptr;
166 	int attempt;
167 
168 	/*
169 	 * Try twice to allocate something.
170 	 * (we'll purge any empty structures after the first pass so
171 	 * two passes are always enough)
172 	 */
173 
174 	for (attempt = 0; attempt < 2; attempt++) {
175 		/*
176 		 * Look for a free structure.
177 		 * Fill it in and return it if we find one.
178 		 */
179 
180 		for (i = 0; i < seminfo.semmnu; i++) {
181 			suptr = SEMU(i);
182 			if (suptr->un_proc == NULL) {
183 				suptr->un_next = semu_list;
184 				semu_list = suptr;
185 				suptr->un_cnt = 0;
186 				suptr->un_proc = p;
187 				return(suptr);
188 			}
189 		}
190 
191 		/*
192 		 * We didn't find a free one, if this is the first attempt
193 		 * then try to free some structures.
194 		 */
195 
196 		if (attempt == 0) {
197 			/* All the structures are in use - try to free some */
198 			int did_something = 0;
199 
200 			supptr = &semu_list;
201 			while ((suptr = *supptr) != NULL) {
202 				if (suptr->un_cnt == 0)  {
203 					suptr->un_proc = NULL;
204 					*supptr = suptr->un_next;
205 					did_something = 1;
206 				} else
207 					supptr = &(suptr->un_next);
208 			}
209 
210 			/* If we didn't free anything then just give-up */
211 			if (!did_something)
212 				return(NULL);
213 		} else {
214 			/*
215 			 * The second pass failed even though we freed
216 			 * something after the first pass!
217 			 * This is IMPOSSIBLE!
218 			 */
219 			panic("semu_alloc - second attempt failed");
220 		}
221 	}
222 	return NULL;
223 }
224 
225 /*
226  * Adjust a particular entry for a particular proc
227  */
228 
229 int
230 semundo_adjust(p, supptr, semid, semnum, adjval)
231 	register struct proc *p;
232 	struct sem_undo **supptr;
233 	int semid, semnum;
234 	int adjval;
235 {
236 	register struct sem_undo *suptr;
237 	register struct undo *sunptr;
238 	int i;
239 
240 	/* Look for and remember the sem_undo if the caller doesn't provide
241 	   it */
242 
243 	suptr = *supptr;
244 	if (suptr == NULL) {
245 		for (suptr = semu_list; suptr != NULL; suptr = suptr->un_next) {
246 			if (suptr->un_proc == p) {
247 				*supptr = suptr;
248 				break;
249 			}
250 		}
251 		if (suptr == NULL) {
252 			if (adjval == 0)
253 				return(0);
254 			suptr = semu_alloc(p);
255 			if (suptr == NULL)
256 				return(ENOSPC);
257 			*supptr = suptr;
258 		}
259 	}
260 
261 	/*
262 	 * Look for the requested entry and adjust it (delete if adjval becomes
263 	 * 0).
264 	 */
265 	sunptr = &suptr->un_ent[0];
266 	for (i = 0; i < suptr->un_cnt; i++, sunptr++) {
267 		if (sunptr->un_id != semid || sunptr->un_num != semnum)
268 			continue;
269 		if (adjval == 0)
270 			sunptr->un_adjval = 0;
271 		else
272 			sunptr->un_adjval += adjval;
273 		if (sunptr->un_adjval == 0) {
274 			suptr->un_cnt--;
275 			if (i < suptr->un_cnt)
276 				suptr->un_ent[i] =
277 				    suptr->un_ent[suptr->un_cnt];
278 		}
279 		return(0);
280 	}
281 
282 	/* Didn't find the right entry - create it */
283 	if (adjval == 0)
284 		return(0);
285 	if (suptr->un_cnt == SEMUME)
286 		return(EINVAL);
287 
288 	sunptr = &suptr->un_ent[suptr->un_cnt];
289 	suptr->un_cnt++;
290 	sunptr->un_adjval = adjval;
291 	sunptr->un_id = semid;
292 	sunptr->un_num = semnum;
293 	return(0);
294 }
295 
296 void
297 semundo_clear(semid, semnum)
298 	int semid, semnum;
299 {
300 	register struct sem_undo *suptr;
301 
302 	for (suptr = semu_list; suptr != NULL; suptr = suptr->un_next) {
303 		register struct undo *sunptr;
304 		register int i;
305 
306 		sunptr = &suptr->un_ent[0];
307 		for (i = 0; i < suptr->un_cnt; i++, sunptr++) {
308 			if (sunptr->un_id == semid) {
309 				if (semnum == -1 || sunptr->un_num == semnum) {
310 					suptr->un_cnt--;
311 					if (i < suptr->un_cnt) {
312 						suptr->un_ent[i] =
313 						  suptr->un_ent[suptr->un_cnt];
314 						i--, sunptr--;
315 					}
316 				}
317 				if (semnum != -1)
318 					break;
319 			}
320 		}
321 	}
322 }
323 
324 int
325 sys_____semctl13(p, v, retval)
326 	struct proc *p;
327 	void *v;
328 	register_t *retval;
329 {
330 	struct sys_____semctl13_args /* {
331 		syscallarg(int) semid;
332 		syscallarg(int) semnum;
333 		syscallarg(int) cmd;
334 		syscallarg(union __semun *) arg;
335 	} */ *uap = v;
336 	struct semid_ds sembuf;
337 	int cmd, error;
338 	void *pass_arg;
339 	union __semun karg;
340 
341 	cmd = SCARG(uap, cmd);
342 
343 	switch (cmd) {
344 	case IPC_SET:
345 	case IPC_STAT:
346 		pass_arg = &sembuf;
347 		break;
348 
349 	case GETALL:
350 	case SETVAL:
351 	case SETALL:
352 		pass_arg = &karg;
353 		break;
354 	default:
355 		pass_arg = NULL;
356 		break;
357 	}
358 
359 	if (pass_arg) {
360 		error = copyin(SCARG(uap, arg), &karg, sizeof(karg));
361 		if (error)
362 			return error;
363 		if (cmd == IPC_SET) {
364 			error = copyin(karg.buf, &sembuf, sizeof(sembuf));
365 			if (error)
366 				return (error);
367 		}
368 	}
369 
370 	error = semctl1(p, SCARG(uap, semid), SCARG(uap, semnum), cmd,
371 	    pass_arg, retval);
372 
373 	if (error == 0 && cmd == IPC_STAT)
374 		error = copyout(&sembuf, karg.buf, sizeof(sembuf));
375 
376 	return (error);
377 }
378 
379 int
380 semctl1(p, semid, semnum, cmd, v, retval)
381 	struct proc *p;
382 	int semid, semnum, cmd;
383 	void *v;
384 	register_t *retval;
385 {
386 	struct ucred *cred = p->p_ucred;
387 	union __semun *arg = v;
388 	struct semid_ds *sembuf = v, *semaptr;
389 	int i, error, ix;
390 
391 	SEM_PRINTF(("call to semctl(%d, %d, %d, %p)\n",
392 	    semid, semnum, cmd, v));
393 
394 	semlock(p);
395 
396 	ix = IPCID_TO_IX(semid);
397 	if (ix < 0 || ix >= seminfo.semmsl)
398 		return (EINVAL);
399 
400 	semaptr = &sema[ix];
401 	if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
402 	    semaptr->sem_perm._seq != IPCID_TO_SEQ(semid))
403 		return (EINVAL);
404 
405 	switch (cmd) {
406 	case IPC_RMID:
407 		if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_M)) != 0)
408 			return (error);
409 		semaptr->sem_perm.cuid = cred->cr_uid;
410 		semaptr->sem_perm.uid = cred->cr_uid;
411 		semtot -= semaptr->sem_nsems;
412 		for (i = semaptr->_sem_base - sem; i < semtot; i++)
413 			sem[i] = sem[i + semaptr->sem_nsems];
414 		for (i = 0; i < seminfo.semmni; i++) {
415 			if ((sema[i].sem_perm.mode & SEM_ALLOC) &&
416 			    sema[i]._sem_base > semaptr->_sem_base)
417 				sema[i]._sem_base -= semaptr->sem_nsems;
418 		}
419 		semaptr->sem_perm.mode = 0;
420 		semundo_clear(ix, -1);
421 		wakeup(semaptr);
422 		break;
423 
424 	case IPC_SET:
425 		if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_M)))
426 			return (error);
427 		semaptr->sem_perm.uid = sembuf->sem_perm.uid;
428 		semaptr->sem_perm.gid = sembuf->sem_perm.gid;
429 		semaptr->sem_perm.mode = (semaptr->sem_perm.mode & ~0777) |
430 		    (sembuf->sem_perm.mode & 0777);
431 		semaptr->sem_ctime = time.tv_sec;
432 		break;
433 
434 	case IPC_STAT:
435 		if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
436 			return (error);
437 		memcpy(sembuf, semaptr, sizeof(struct semid_ds));
438 		break;
439 
440 	case GETNCNT:
441 		if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
442 			return (error);
443 		if (semnum < 0 || semnum >= semaptr->sem_nsems)
444 			return (EINVAL);
445 		*retval = semaptr->_sem_base[semnum].semncnt;
446 		break;
447 
448 	case GETPID:
449 		if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
450 			return (error);
451 		if (semnum < 0 || semnum >= semaptr->sem_nsems)
452 			return (EINVAL);
453 		*retval = semaptr->_sem_base[semnum].sempid;
454 		break;
455 
456 	case GETVAL:
457 		if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
458 			return (error);
459 		if (semnum < 0 || semnum >= semaptr->sem_nsems)
460 			return (EINVAL);
461 		*retval = semaptr->_sem_base[semnum].semval;
462 		break;
463 
464 	case GETALL:
465 		if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
466 			return (error);
467 		for (i = 0; i < semaptr->sem_nsems; i++) {
468 			error = copyout(&semaptr->_sem_base[i].semval,
469 			    &arg->array[i], sizeof(arg->array[i]));
470 			if (error != 0)
471 				break;
472 		}
473 		break;
474 
475 	case GETZCNT:
476 		if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_R)))
477 			return (error);
478 		if (semnum < 0 || semnum >= semaptr->sem_nsems)
479 			return (EINVAL);
480 		*retval = semaptr->_sem_base[semnum].semzcnt;
481 		break;
482 
483 	case SETVAL:
484 		if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_W)))
485 			return (error);
486 		if (semnum < 0 || semnum >= semaptr->sem_nsems)
487 			return (EINVAL);
488 		semaptr->_sem_base[semnum].semval = arg->val;
489 		semundo_clear(ix, semnum);
490 		wakeup(semaptr);
491 		break;
492 
493 	case SETALL:
494 		if ((error = ipcperm(cred, &semaptr->sem_perm, IPC_W)))
495 			return (error);
496 		for (i = 0; i < semaptr->sem_nsems; i++) {
497 			error = copyin(&arg->array[i],
498 			    &semaptr->_sem_base[i].semval,
499 			    sizeof(arg->array[i]));
500 			if (error != 0)
501 				break;
502 		}
503 		semundo_clear(ix, -1);
504 		wakeup(semaptr);
505 		break;
506 
507 	default:
508 		return (EINVAL);
509 	}
510 
511 	return (error);
512 }
513 
514 int
515 sys_semget(p, v, retval)
516 	struct proc *p;
517 	void *v;
518 	register_t *retval;
519 {
520 	register struct sys_semget_args /* {
521 		syscallarg(key_t) key;
522 		syscallarg(int) nsems;
523 		syscallarg(int) semflg;
524 	} */ *uap = v;
525 	int semid, eval;
526 	int key = SCARG(uap, key);
527 	int nsems = SCARG(uap, nsems);
528 	int semflg = SCARG(uap, semflg);
529 	struct ucred *cred = p->p_ucred;
530 
531 	SEM_PRINTF(("semget(0x%x, %d, 0%o)\n", key, nsems, semflg));
532 
533 	semlock(p);
534 
535 	if (key != IPC_PRIVATE) {
536 		for (semid = 0; semid < seminfo.semmni; semid++) {
537 			if ((sema[semid].sem_perm.mode & SEM_ALLOC) &&
538 			    sema[semid].sem_perm._key == key)
539 				break;
540 		}
541 		if (semid < seminfo.semmni) {
542 			SEM_PRINTF(("found public key\n"));
543 			if ((eval = ipcperm(cred, &sema[semid].sem_perm,
544 			    semflg & 0700)))
545 				return(eval);
546 			if (nsems > 0 && sema[semid].sem_nsems < nsems) {
547 				SEM_PRINTF(("too small\n"));
548 				return(EINVAL);
549 			}
550 			if ((semflg & IPC_CREAT) && (semflg & IPC_EXCL)) {
551 				SEM_PRINTF(("not exclusive\n"));
552 				return(EEXIST);
553 			}
554 			goto found;
555 		}
556 	}
557 
558 	SEM_PRINTF(("need to allocate the semid_ds\n"));
559 	if (key == IPC_PRIVATE || (semflg & IPC_CREAT)) {
560 		if (nsems <= 0 || nsems > seminfo.semmsl) {
561 			SEM_PRINTF(("nsems out of range (0<%d<=%d)\n", nsems,
562 			    seminfo.semmsl));
563 			return(EINVAL);
564 		}
565 		if (nsems > seminfo.semmns - semtot) {
566 			SEM_PRINTF(("not enough semaphores left (need %d, got %d)\n",
567 			    nsems, seminfo.semmns - semtot));
568 			return(ENOSPC);
569 		}
570 		for (semid = 0; semid < seminfo.semmni; semid++) {
571 			if ((sema[semid].sem_perm.mode & SEM_ALLOC) == 0)
572 				break;
573 		}
574 		if (semid == seminfo.semmni) {
575 			SEM_PRINTF(("no more semid_ds's available\n"));
576 			return(ENOSPC);
577 		}
578 		SEM_PRINTF(("semid %d is available\n", semid));
579 		sema[semid].sem_perm._key = key;
580 		sema[semid].sem_perm.cuid = cred->cr_uid;
581 		sema[semid].sem_perm.uid = cred->cr_uid;
582 		sema[semid].sem_perm.cgid = cred->cr_gid;
583 		sema[semid].sem_perm.gid = cred->cr_gid;
584 		sema[semid].sem_perm.mode = (semflg & 0777) | SEM_ALLOC;
585 		sema[semid].sem_perm._seq =
586 		    (sema[semid].sem_perm._seq + 1) & 0x7fff;
587 		sema[semid].sem_nsems = nsems;
588 		sema[semid].sem_otime = 0;
589 		sema[semid].sem_ctime = time.tv_sec;
590 		sema[semid]._sem_base = &sem[semtot];
591 		semtot += nsems;
592 		memset(sema[semid]._sem_base, 0,
593 		    sizeof(sema[semid]._sem_base[0])*nsems);
594 		SEM_PRINTF(("sembase = %p, next = %p\n", sema[semid]._sem_base,
595 		    &sem[semtot]));
596 	} else {
597 		SEM_PRINTF(("didn't find it and wasn't asked to create it\n"));
598 		return(ENOENT);
599 	}
600 
601 found:
602 	*retval = IXSEQ_TO_IPCID(semid, sema[semid].sem_perm);
603 	return(0);
604 }
605 
606 int
607 sys_semop(p, v, retval)
608 	struct proc *p;
609 	void *v;
610 	register_t *retval;
611 {
612 	register struct sys_semop_args /* {
613 		syscallarg(int) semid;
614 		syscallarg(struct sembuf *) sops;
615 		syscallarg(size_t) nsops;
616 	} */ *uap = v;
617 	int semid = SCARG(uap, semid);
618 	int nsops = SCARG(uap, nsops);
619 	struct sembuf sops[MAX_SOPS];
620 	register struct semid_ds *semaptr;
621 	register struct sembuf *sopptr = NULL;
622 	register struct __sem *semptr = NULL;
623 	struct sem_undo *suptr = NULL;
624 	struct ucred *cred = p->p_ucred;
625 	int i, j, eval;
626 	int do_wakeup, do_undos;
627 
628 	SEM_PRINTF(("call to semop(%d, %p, %d)\n", semid, sops, nsops));
629 
630 	semlock(p);
631 
632 	semid = IPCID_TO_IX(semid);	/* Convert back to zero origin */
633 
634 	if (semid < 0 || semid >= seminfo.semmsl)
635 		return(EINVAL);
636 
637 	semaptr = &sema[semid];
638 	if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
639 	    semaptr->sem_perm._seq != IPCID_TO_SEQ(SCARG(uap, semid)))
640 		return(EINVAL);
641 
642 	if ((eval = ipcperm(cred, &semaptr->sem_perm, IPC_W))) {
643 		SEM_PRINTF(("eval = %d from ipaccess\n", eval));
644 		return(eval);
645 	}
646 
647 	if (nsops > MAX_SOPS) {
648 		SEM_PRINTF(("too many sops (max=%d, nsops=%d)\n", MAX_SOPS, nsops));
649 		return(E2BIG);
650 	}
651 
652 	if ((eval = copyin(SCARG(uap, sops), sops, nsops * sizeof(sops[0])))
653 	    != 0) {
654 		SEM_PRINTF(("eval = %d from copyin(%p, %p, %d)\n", eval,
655 		    SCARG(uap, sops), &sops, nsops * sizeof(sops[0])));
656 		return(eval);
657 	}
658 
659 	/*
660 	 * Loop trying to satisfy the vector of requests.
661 	 * If we reach a point where we must wait, any requests already
662 	 * performed are rolled back and we go to sleep until some other
663 	 * process wakes us up.  At this point, we start all over again.
664 	 *
665 	 * This ensures that from the perspective of other tasks, a set
666 	 * of requests is atomic (never partially satisfied).
667 	 */
668 	do_undos = 0;
669 
670 	for (;;) {
671 		do_wakeup = 0;
672 
673 		for (i = 0; i < nsops; i++) {
674 			sopptr = &sops[i];
675 
676 			if (sopptr->sem_num >= semaptr->sem_nsems)
677 				return(EFBIG);
678 
679 			semptr = &semaptr->_sem_base[sopptr->sem_num];
680 
681 			SEM_PRINTF(("semop:  semaptr=%x, sem_base=%x, semptr=%x, sem[%d]=%d : op=%d, flag=%s\n",
682 			    semaptr, semaptr->_sem_base, semptr,
683 			    sopptr->sem_num, semptr->semval, sopptr->sem_op,
684 			    (sopptr->sem_flg & IPC_NOWAIT) ? "nowait" : "wait"));
685 
686 			if (sopptr->sem_op < 0) {
687 				if ((int)(semptr->semval +
688 					  sopptr->sem_op) < 0) {
689 					SEM_PRINTF(("semop:  can't do it now\n"));
690 					break;
691 				} else {
692 					semptr->semval += sopptr->sem_op;
693 					if (semptr->semval == 0 &&
694 					    semptr->semzcnt > 0)
695 						do_wakeup = 1;
696 				}
697 				if (sopptr->sem_flg & SEM_UNDO)
698 					do_undos = 1;
699 			} else if (sopptr->sem_op == 0) {
700 				if (semptr->semval > 0) {
701 					SEM_PRINTF(("semop:  not zero now\n"));
702 					break;
703 				}
704 			} else {
705 				if (semptr->semncnt > 0)
706 					do_wakeup = 1;
707 				semptr->semval += sopptr->sem_op;
708 				if (sopptr->sem_flg & SEM_UNDO)
709 					do_undos = 1;
710 			}
711 		}
712 
713 		/*
714 		 * Did we get through the entire vector?
715 		 */
716 		if (i >= nsops)
717 			goto done;
718 
719 		/*
720 		 * No ... rollback anything that we've already done
721 		 */
722 		SEM_PRINTF(("semop:  rollback 0 through %d\n", i-1));
723 		for (j = 0; j < i; j++)
724 			semaptr->_sem_base[sops[j].sem_num].semval -=
725 			    sops[j].sem_op;
726 
727 		/*
728 		 * If the request that we couldn't satisfy has the
729 		 * NOWAIT flag set then return with EAGAIN.
730 		 */
731 		if (sopptr->sem_flg & IPC_NOWAIT)
732 			return(EAGAIN);
733 
734 		if (sopptr->sem_op == 0)
735 			semptr->semzcnt++;
736 		else
737 			semptr->semncnt++;
738 
739 		SEM_PRINTF(("semop:  good night!\n"));
740 		eval = tsleep((caddr_t)semaptr, (PZERO - 4) | PCATCH,
741 		    "semwait", 0);
742 		SEM_PRINTF(("semop:  good morning (eval=%d)!\n", eval));
743 
744 		suptr = NULL;	/* sem_undo may have been reallocated */
745 
746 		if (eval != 0)
747 			return(EINTR);
748 		SEM_PRINTF(("semop:  good morning!\n"));
749 
750 		/*
751 		 * Make sure that the semaphore still exists
752 		 */
753 		if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0 ||
754 		    semaptr->sem_perm._seq != IPCID_TO_SEQ(SCARG(uap, semid))) {
755 			/* The man page says to return EIDRM. */
756 			/* Unfortunately, BSD doesn't define that code! */
757 #ifdef EIDRM
758 			return(EIDRM);
759 #else
760 			return(EINVAL);
761 #endif
762 		}
763 
764 		/*
765 		 * The semaphore is still alive.  Readjust the count of
766 		 * waiting processes.
767 		 */
768 		if (sopptr->sem_op == 0)
769 			semptr->semzcnt--;
770 		else
771 			semptr->semncnt--;
772 	}
773 
774 done:
775 	/*
776 	 * Process any SEM_UNDO requests.
777 	 */
778 	if (do_undos) {
779 		for (i = 0; i < nsops; i++) {
780 			/*
781 			 * We only need to deal with SEM_UNDO's for non-zero
782 			 * op's.
783 			 */
784 			int adjval;
785 
786 			if ((sops[i].sem_flg & SEM_UNDO) == 0)
787 				continue;
788 			adjval = sops[i].sem_op;
789 			if (adjval == 0)
790 				continue;
791 			eval = semundo_adjust(p, &suptr, semid,
792 			    sops[i].sem_num, -adjval);
793 			if (eval == 0)
794 				continue;
795 
796 			/*
797 			 * Oh-Oh!  We ran out of either sem_undo's or undo's.
798 			 * Rollback the adjustments to this point and then
799 			 * rollback the semaphore ups and down so we can return
800 			 * with an error with all structures restored.  We
801 			 * rollback the undo's in the exact reverse order that
802 			 * we applied them.  This guarantees that we won't run
803 			 * out of space as we roll things back out.
804 			 */
805 			for (j = i - 1; j >= 0; j--) {
806 				if ((sops[j].sem_flg & SEM_UNDO) == 0)
807 					continue;
808 				adjval = sops[j].sem_op;
809 				if (adjval == 0)
810 					continue;
811 				if (semundo_adjust(p, &suptr, semid,
812 				    sops[j].sem_num, adjval) != 0)
813 					panic("semop - can't undo undos");
814 			}
815 
816 			for (j = 0; j < nsops; j++)
817 				semaptr->_sem_base[sops[j].sem_num].semval -=
818 				    sops[j].sem_op;
819 
820 			SEM_PRINTF(("eval = %d from semundo_adjust\n", eval));
821 			return(eval);
822 		} /* loop through the sops */
823 	} /* if (do_undos) */
824 
825 	/* We're definitely done - set the sempid's */
826 	for (i = 0; i < nsops; i++) {
827 		sopptr = &sops[i];
828 		semptr = &semaptr->_sem_base[sopptr->sem_num];
829 		semptr->sempid = p->p_pid;
830 	}
831 
832 	/* Do a wakeup if any semaphore was up'd. */
833 	if (do_wakeup) {
834 		SEM_PRINTF(("semop:  doing wakeup\n"));
835 #ifdef SEM_WAKEUP
836 		sem_wakeup((caddr_t)semaptr);
837 #else
838 		wakeup((caddr_t)semaptr);
839 #endif
840 		SEM_PRINTF(("semop:  back from wakeup\n"));
841 	}
842 	SEM_PRINTF(("semop:  done\n"));
843 	*retval = 0;
844 	return(0);
845 }
846 
847 /*
848  * Go through the undo structures for this process and apply the adjustments to
849  * semaphores.
850  */
851 void
852 semexit(p)
853 	struct proc *p;
854 {
855 	register struct sem_undo *suptr;
856 	register struct sem_undo **supptr;
857 
858 	/*
859 	 * Go through the chain of undo vectors looking for one associated with
860 	 * this process.
861 	 */
862 
863 	for (supptr = &semu_list; (suptr = *supptr) != NULL;
864 	    supptr = &suptr->un_next) {
865 		if (suptr->un_proc == p)
866 			break;
867 	}
868 
869 	/*
870 	 * There are a few possibilities to consider here ...
871 	 *
872 	 * 1) The semaphore facility isn't currently locked.  In this case,
873 	 *    this call should proceed normally.
874 	 * 2) The semaphore facility is locked by this process (i.e. the one
875 	 *    that is exiting).  In this case, this call should proceed as
876 	 *    usual and the facility should be unlocked at the end of this
877 	 *    routine (since the locker is exiting).
878 	 * 3) The semaphore facility is locked by some other process and this
879 	 *    process doesn't have an undo structure allocated for it.  In this
880 	 *    case, this call should proceed normally (i.e. not accomplish
881 	 *    anything and, most importantly, not block since that is
882 	 *    unnecessary and could result in a LOT of processes blocking in
883 	 *    here if the facility is locked for a long time).
884 	 * 4) The semaphore facility is locked by some other process and this
885 	 *    process has an undo structure allocated for it.  In this case,
886 	 *    this call should block until the facility has been unlocked since
887 	 *    the holder of the lock may be examining this process's proc entry
888 	 *    (the ipcs utility does this when printing out the information
889 	 *    from the allocated sem undo elements).
890 	 *
891 	 * This leads to the conclusion that we should not block unless we
892 	 * discover that the someone else has the semaphore facility locked and
893 	 * this process has an undo structure.  Let's do that...
894 	 *
895 	 * Note that we do this in a separate pass from the one that processes
896 	 * any existing undo structure since we don't want to risk blocking at
897 	 * that time (it would make the actual unlinking of the element from
898 	 * the chain of allocated undo structures rather messy).
899 	 */
900 
901 	/*
902 	 * Does someone else hold the semaphore facility's lock?
903 	 */
904 
905 	if (semlock_holder != NULL && semlock_holder != p) {
906 		/*
907 		 * Yes (i.e. we are in case 3 or 4).
908 		 *
909 		 * If we didn't find an undo vector associated with this
910 		 * process than we can just return (i.e. we are in case 3).
911 		 *
912 		 * Note that we know that someone else is holding the lock so
913 		 * we don't even have to see if we're holding it...
914 		 */
915 
916 		if (suptr == NULL)
917 			return;
918 
919 		/*
920 		 * We are in case 4.
921 		 *
922 		 * Go to sleep as long as someone else is locking the semaphore
923 		 * facility (note that we won't get here if we are holding the
924 		 * lock so we don't need to check for that possibility).
925 		 */
926 
927 		while (semlock_holder != NULL)
928 			sleep((caddr_t)&semlock_holder, (PZERO - 4));
929 
930 		/*
931 		 * Nobody is holding the facility (i.e. we are now in case 1).
932 		 * We can proceed safely according to the argument outlined
933 		 * above.
934 		 *
935 		 * We look up the undo vector again, in case the list changed
936 		 * while we were asleep, and the parent is now different.
937 		 */
938 
939 		for (supptr = &semu_list; (suptr = *supptr) != NULL;
940 		    supptr = &suptr->un_next) {
941 			if (suptr->un_proc == p)
942 				break;
943 		}
944 
945 		if (suptr == NULL)
946 			panic("semexit: undo vector disappeared");
947 	} else {
948 		/*
949 		 * No (i.e. we are in case 1 or 2).
950 		 *
951 		 * If there is no undo vector, skip to the end and unlock the
952 		 * semaphore facility if necessary.
953 		 */
954 
955 		if (suptr == NULL)
956 			goto unlock;
957 	}
958 
959 	/*
960 	 * We are now in case 1 or 2, and we have an undo vector for this
961 	 * process.
962 	 */
963 
964 	SEM_PRINTF(("proc @%p has undo structure with %d entries\n", p,
965 	    suptr->un_cnt));
966 
967 	/*
968 	 * If there are any active undo elements then process them.
969 	 */
970 	if (suptr->un_cnt > 0) {
971 		int ix;
972 
973 		for (ix = 0; ix < suptr->un_cnt; ix++) {
974 			int semid = suptr->un_ent[ix].un_id;
975 			int semnum = suptr->un_ent[ix].un_num;
976 			int adjval = suptr->un_ent[ix].un_adjval;
977 			struct semid_ds *semaptr;
978 
979 			semaptr = &sema[semid];
980 			if ((semaptr->sem_perm.mode & SEM_ALLOC) == 0)
981 				panic("semexit - semid not allocated");
982 			if (semnum >= semaptr->sem_nsems)
983 				panic("semexit - semnum out of range");
984 
985 			SEM_PRINTF(("semexit:  %p id=%d num=%d(adj=%d) ; sem=%d\n",
986 			    suptr->un_proc, suptr->un_ent[ix].un_id,
987 			    suptr->un_ent[ix].un_num,
988 			    suptr->un_ent[ix].un_adjval,
989 			    semaptr->_sem_base[semnum].semval));
990 
991 			if (adjval < 0 &&
992 			    semaptr->_sem_base[semnum].semval < -adjval)
993 				semaptr->_sem_base[semnum].semval = 0;
994 			else
995 				semaptr->_sem_base[semnum].semval += adjval;
996 
997 #ifdef SEM_WAKEUP
998 			sem_wakeup((caddr_t)semaptr);
999 #else
1000 			wakeup((caddr_t)semaptr);
1001 #endif
1002 			SEM_PRINTF(("semexit:  back from wakeup\n"));
1003 		}
1004 	}
1005 
1006 	/*
1007 	 * Deallocate the undo vector.
1008 	 */
1009 	SEM_PRINTF(("removing vector\n"));
1010 	suptr->un_proc = NULL;
1011 	*supptr = suptr->un_next;
1012 
1013 unlock:
1014 	/*
1015 	 * If the exiting process is holding the global semaphore facility
1016 	 * lock (i.e. we are in case 2) then release it.
1017 	 */
1018 	if (semlock_holder == p) {
1019 		semlock_holder = NULL;
1020 		wakeup((caddr_t)&semlock_holder);
1021 	}
1022 }
1023