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