xref: /dragonfly/sys/kern/sysv_sem.c (revision 66fa3dc1)
1 /* $FreeBSD: src/sys/kern/sysv_sem.c,v 1.69 2004/03/17 09:37:13 cperciva Exp $ */
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/sysmsg.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 #include <sys/jail.h>
23 #include <sys/thread.h>
24 
25 static MALLOC_DEFINE(M_SEM, "sem", "SVID compatible semaphores");
26 
27 static void seminit (void *);
28 
29 static struct sem_undo *semu_alloc (struct proc *p);
30 static int semundo_adjust (struct proc *p, int semid, int semnum, int adjval);
31 static void semundo_clear (int semid, int semnum);
32 
33 static struct lwkt_token semu_token = LWKT_TOKEN_INITIALIZER(semu_token);
34 static int	semtot = 0;
35 static struct semid_pool *sema;	/* semaphore id pool */
36 static TAILQ_HEAD(, sem_undo) semu_list = TAILQ_HEAD_INITIALIZER(semu_list);
37 static struct lock sema_lk;
38 
39 struct sem {
40 	u_short	semval;		/* semaphore value */
41 	pid_t	sempid;		/* pid of last operation */
42 	u_short	semncnt;	/* # awaiting semval > cval */
43 	u_short	semzcnt;	/* # awaiting semval = 0 */
44 };
45 
46 /*
47  * Undo structure (one per process)
48  */
49 struct sem_undo {
50 	TAILQ_ENTRY(sem_undo) un_entry;	/* linked list for semundo_clear() */
51 	struct	proc *un_proc;		/* owner of this structure */
52 	int	un_refs;		/* prevent unlink/kfree */
53 	short	un_cnt;			/* # of active entries */
54 	short	un_unused;
55 	struct undo {
56 		short	un_adjval;	/* adjust on exit values */
57 		short	un_num;		/* semaphore # */
58 		int	un_id;		/* semid */
59 	} un_ent[1];			/* undo entries */
60 };
61 
62 /*
63  * Configuration parameters
64  */
65 #ifndef SEMMNI
66 #define SEMMNI	1024		/* # of semaphore identifiers */
67 #endif
68 #ifndef SEMMNS
69 #define SEMMNS	32767		/* # of semaphores in system */
70 #endif
71 #ifndef SEMUME
72 #define SEMUME	25		/* max # of undo entries per process */
73 #endif
74 #ifndef SEMMNU
75 #define SEMMNU	1024		/* # of undo structures in system */
76 				/* NO LONGER USED */
77 #endif
78 
79 /* shouldn't need tuning */
80 #ifndef SEMMAP
81 #define SEMMAP	128		/* # of entries in semaphore map */
82 #endif
83 #ifndef SEMMSL
84 #define SEMMSL	SEMMNS		/* max # of semaphores per id */
85 #endif
86 #ifndef SEMOPM
87 #define SEMOPM	100		/* max # of operations per semop call */
88 #endif
89 
90 #define SEMVMX	32767		/* semaphore maximum value */
91 #define SEMAEM	16384		/* adjust on exit max value */
92 
93 /*
94  * Due to the way semaphore memory is allocated, we have to ensure that
95  * SEMUSZ is properly aligned.
96  */
97 
98 #define SEM_ALIGN(bytes) roundup2(bytes, sizeof(long))
99 
100 /* actual size of an undo structure */
101 #define SEMUSZ(nent)	SEM_ALIGN(offsetof(struct sem_undo, un_ent[nent]))
102 
103 /*
104  * semaphore info struct
105  */
106 struct seminfo seminfo = {
107                 SEMMAP,         /* # of entries in semaphore map */
108                 SEMMNI,         /* # of semaphore identifiers */
109                 SEMMNS,         /* # of semaphores in system */
110                 SEMMNU,         /* # of undo structures in system */
111                 SEMMSL,         /* max # of semaphores per id */
112                 SEMOPM,         /* max # of operations per semop call */
113                 SEMUME,         /* max # of undo entries per process */
114                 SEMUSZ(SEMUME), /* size in bytes of undo structure */
115                 SEMVMX,         /* semaphore maximum value */
116                 SEMAEM          /* adjust on exit max value */
117 };
118 
119 TUNABLE_INT("kern.ipc.semmap", &seminfo.semmap);
120 TUNABLE_INT("kern.ipc.semmni", &seminfo.semmni);
121 TUNABLE_INT("kern.ipc.semmns", &seminfo.semmns);
122 TUNABLE_INT("kern.ipc.semmnu", &seminfo.semmnu);
123 TUNABLE_INT("kern.ipc.semmsl", &seminfo.semmsl);
124 TUNABLE_INT("kern.ipc.semopm", &seminfo.semopm);
125 TUNABLE_INT("kern.ipc.semume", &seminfo.semume);
126 TUNABLE_INT("kern.ipc.semusz", &seminfo.semusz);
127 TUNABLE_INT("kern.ipc.semvmx", &seminfo.semvmx);
128 TUNABLE_INT("kern.ipc.semaem", &seminfo.semaem);
129 
130 SYSCTL_INT(_kern_ipc, OID_AUTO, semmap, CTLFLAG_RW, &seminfo.semmap, 0,
131     "Number of entries in semaphore map");
132 SYSCTL_INT(_kern_ipc, OID_AUTO, semmni, CTLFLAG_RD, &seminfo.semmni, 0,
133     "Number of semaphore identifiers");
134 SYSCTL_INT(_kern_ipc, OID_AUTO, semmns, CTLFLAG_RD, &seminfo.semmns, 0,
135     "Total number of semaphores");
136 SYSCTL_INT(_kern_ipc, OID_AUTO, semmnu, CTLFLAG_RD, &seminfo.semmnu, 0,
137     "Total number of undo structures");
138 SYSCTL_INT(_kern_ipc, OID_AUTO, semmsl, CTLFLAG_RW, &seminfo.semmsl, 0,
139     "Max number of semaphores per id");
140 SYSCTL_INT(_kern_ipc, OID_AUTO, semopm, CTLFLAG_RD, &seminfo.semopm, 0,
141     "Max number of operations per semop call");
142 SYSCTL_INT(_kern_ipc, OID_AUTO, semume, CTLFLAG_RD, &seminfo.semume, 0,
143     "Max number of undo entries per process");
144 SYSCTL_INT(_kern_ipc, OID_AUTO, semusz, CTLFLAG_RD, &seminfo.semusz, 0,
145     "Size in bytes of undo structure");
146 SYSCTL_INT(_kern_ipc, OID_AUTO, semvmx, CTLFLAG_RW, &seminfo.semvmx, 0,
147     "Semaphore maximum value");
148 SYSCTL_INT(_kern_ipc, OID_AUTO, semaem, CTLFLAG_RW, &seminfo.semaem, 0,
149     "Adjust on exit max value");
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(void *dummy)
166 {
167 	int i;
168 
169 	sema = kmalloc(sizeof(struct semid_pool) * seminfo.semmni,
170 		      M_SEM, M_WAITOK | M_ZERO);
171 
172 	lockinit(&sema_lk, "semglb", 0, 0);
173 	for (i = 0; i < seminfo.semmni; i++) {
174 		struct semid_pool *semaptr = &sema[i];
175 
176 		lockinit(&semaptr->lk, "semary", 0, 0);
177 		semaptr->ds.sem_base = NULL;
178 		semaptr->ds.sem_perm.mode = 0;
179 	}
180 }
181 SYSINIT(sysv_sem, SI_SUB_SYSV_SEM, SI_ORDER_FIRST, seminit, NULL);
182 
183 /*
184  * Allocate a new sem_undo structure for a process
185  * (returns ptr to structure or NULL if no more room)
186  */
187 static struct sem_undo *
188 semu_alloc(struct proc *p)
189 {
190 	struct sem_undo *semu;
191 
192 	/*
193 	 * Allocate the semu structure and associate it with the process,
194 	 * as necessary.
195 	 */
196 	while ((semu = p->p_sem_undo) == NULL) {
197 		semu = kmalloc(SEMUSZ(seminfo.semume), M_SEM,
198 			       M_WAITOK | M_ZERO);
199 		lwkt_gettoken(&semu_token);
200 		lwkt_gettoken(&p->p_token);
201 		if (p->p_sem_undo == NULL) {
202 			p->p_sem_undo = semu;
203 			p->p_flags |= P_SYSVSEM;
204 			semu->un_proc = p;
205 			TAILQ_INSERT_TAIL(&semu_list, semu, un_entry);
206 		} else {
207 			kfree(semu, M_SEM);
208 		}
209 		lwkt_reltoken(&p->p_token);
210 		lwkt_reltoken(&semu_token);
211 	}
212 	return(semu);
213 }
214 
215 /*
216  * Adjust a particular entry for a particular proc
217  */
218 static int
219 semundo_adjust(struct proc *p, int semid, int semnum, int adjval)
220 {
221 	struct sem_undo *suptr;
222 	struct undo *sunptr;
223 	int i;
224 	int error = 0;
225 
226 	/*
227 	 * Look for and remember the sem_undo if the caller doesn't
228 	 * provide it.
229 	 */
230 	suptr = semu_alloc(p);
231 	lwkt_gettoken(&p->p_token);
232 
233 	/*
234 	 * Look for the requested entry and adjust it (delete if adjval becomes
235 	 * 0).
236 	 */
237 	sunptr = &suptr->un_ent[0];
238 	for (i = 0; i < suptr->un_cnt; i++, sunptr++) {
239 		if (sunptr->un_id != semid || sunptr->un_num != semnum)
240 			continue;
241 		if (adjval == 0)
242 			sunptr->un_adjval = 0;
243 		else
244 			sunptr->un_adjval += adjval;
245 		if (sunptr->un_adjval == 0) {
246 			suptr->un_cnt--;
247 			if (i < suptr->un_cnt)
248 				suptr->un_ent[i] = suptr->un_ent[suptr->un_cnt];
249 		}
250 		goto done;
251 	}
252 
253 	/* Didn't find the right entry - create it */
254 	if (adjval == 0)
255 		goto done;
256 	if (suptr->un_cnt != seminfo.semume) {
257 		sunptr = &suptr->un_ent[suptr->un_cnt];
258 		suptr->un_cnt++;
259 		sunptr->un_adjval = adjval;
260 		sunptr->un_id = semid;
261 		sunptr->un_num = semnum;
262 	} else {
263 		error = EINVAL;
264 	}
265 done:
266 	lwkt_reltoken(&p->p_token);
267 
268 	return (error);
269 }
270 
271 /*
272  * This is rather expensive
273  */
274 static void
275 semundo_clear(int semid, int semnum)
276 {
277 	struct proc *p;
278 	struct sem_undo *suptr;
279 	struct sem_undo *sunext;
280 	struct undo *sunptr;
281 	int i;
282 
283 	lwkt_gettoken(&semu_token);
284 	sunext = TAILQ_FIRST(&semu_list);
285 	while ((suptr = sunext) != NULL) {
286 		if ((p = suptr->un_proc) == NULL) {
287 			sunext = TAILQ_NEXT(suptr, un_entry);
288 			continue;
289 		}
290 		++suptr->un_refs;
291 		PHOLD(p);
292 		lwkt_gettoken(&p->p_token);
293 
294 		sunptr = &suptr->un_ent[0];
295 		i = 0;
296 
297 		while (i < suptr->un_cnt) {
298 			if (sunptr->un_id == semid) {
299 				if (semnum == -1 || sunptr->un_num == semnum) {
300 					suptr->un_cnt--;
301 					if (i < suptr->un_cnt) {
302 						suptr->un_ent[i] =
303 						  suptr->un_ent[suptr->un_cnt];
304 						/*
305 						 * do not increment i
306 						 * or sunptr after copydown.
307 						 */
308 						continue;
309 					}
310 				}
311 				if (semnum != -1)
312 					break;
313 			}
314 			++i;
315 			++sunptr;
316 		}
317 
318 		lwkt_reltoken(&p->p_token);
319 		PRELE(p);
320 
321 		/*
322 		 * Handle deletion races
323 		 */
324 		sunext = TAILQ_NEXT(suptr, un_entry);
325 		if (--suptr->un_refs == 0 && suptr->un_proc == NULL) {
326 			KKASSERT(suptr->un_cnt == 0);
327 			TAILQ_REMOVE(&semu_list, suptr, un_entry);
328 			kfree(suptr, M_SEM);
329 		}
330 	}
331 	lwkt_reltoken(&semu_token);
332 }
333 
334 /*
335  * Note that the user-mode half of this passes a union, not a pointer
336  *
337  * MPALMOSTSAFE
338  */
339 int
340 sys___semctl(struct sysmsg *sysmsg, const struct __semctl_args *uap)
341 {
342 	struct thread *td = curthread;
343 	struct prison *pr = td->td_proc->p_ucred->cr_prison;
344 	int semid = uap->semid;
345 	int semnum = uap->semnum;
346 	int cmd = uap->cmd;
347 	union semun *arg = uap->arg;
348 	union semun real_arg;
349 	struct ucred *cred = td->td_ucred;
350 	int i, rval, eval;
351 	struct semid_ds sbuf;
352 	struct semid_pool *semaptr;
353 	struct sem *semptr;
354 
355 #ifdef SEM_DEBUG
356 	kprintf("call to semctl(%d, %d, %d, 0x%x)\n", semid, semnum, cmd, arg);
357 #endif
358 
359 	if (pr && !PRISON_CAP_ISSET(pr->pr_caps, PRISON_CAP_SYS_SYSVIPC))
360 		return (ENOSYS);
361 
362 	semid = IPCID_TO_IX(semid);
363 	if (semid < 0 || semid >= seminfo.semmni) {
364 		return(EINVAL);
365 	}
366 	semaptr = &sema[semid];
367 	lockmgr(&semaptr->lk, LK_EXCLUSIVE);
368 
369 	if ((semaptr->ds.sem_perm.mode & SEM_ALLOC) == 0 ||
370 	    semaptr->ds.sem_perm.seq != IPCID_TO_SEQ(uap->semid)) {
371 		lockmgr(&semaptr->lk, LK_RELEASE);
372 		return(EINVAL);
373 	}
374 
375 	eval = 0;
376 	rval = 0;
377 
378 	switch (cmd) {
379 	case IPC_RMID:
380 		eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_M);
381 		if (eval != 0)
382 			break;
383 		semaptr->ds.sem_perm.cuid = cred->cr_uid;
384 		semaptr->ds.sem_perm.uid = cred->cr_uid;
385 
386 		/*
387 		 * NOTE: Nobody will be waiting on the semaphores since
388 		 *	 we have an exclusive lock on semaptr->lk).
389 		 */
390 		lockmgr(&sema_lk, LK_EXCLUSIVE);
391 		semtot -= semaptr->ds.sem_nsems;
392 		kfree(semaptr->ds.sem_base, M_SEM);
393 		semaptr->ds.sem_base = NULL;
394 		semaptr->ds.sem_perm.mode = 0;	/* clears SEM_ALLOC */
395 		lockmgr(&sema_lk, LK_RELEASE);
396 
397 		semundo_clear(semid, -1);
398 		break;
399 
400 	case IPC_SET:
401 		eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_M);
402 		if (eval)
403 			break;
404 		if ((eval = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
405 			break;
406 		if ((eval = copyin(real_arg.buf, (caddr_t)&sbuf,
407 				   sizeof(sbuf))) != 0) {
408 			break;
409 		}
410 		semaptr->ds.sem_perm.uid = sbuf.sem_perm.uid;
411 		semaptr->ds.sem_perm.gid = sbuf.sem_perm.gid;
412 		semaptr->ds.sem_perm.mode =
413 			(semaptr->ds.sem_perm.mode & ~0777) |
414 			(sbuf.sem_perm.mode & 0777);
415 		semaptr->ds.sem_ctime = time_second;
416 		break;
417 
418 	case IPC_STAT:
419 		eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_R);
420 		if (eval)
421 			break;
422 		if ((eval = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
423 			break;
424 		eval = copyout(&semaptr->ds, real_arg.buf,
425 			       sizeof(struct semid_ds));
426 		break;
427 	case SEM_STAT:
428 		/*
429 		 * For this command we assume semid is an array index
430 		 * rather than an IPC id.  However, the conversion is
431 		 * just a mask so just validate that the passed-in semid
432 		 * matches the masked semid.
433 		 */
434 		if (uap->semid != semid) {
435 			eval = EINVAL;
436 			break;
437 		}
438 		eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_R);
439 		if (eval)
440 			break;
441 		if ((eval = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
442 			break;
443 		eval = copyout(&semaptr->ds, real_arg.buf,
444 			       sizeof(struct semid_ds));
445 		rval = IXSEQ_TO_IPCID(semid, semaptr->ds.sem_perm);
446 		break;
447 
448 	case GETNCNT:
449 		eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_R);
450 		if (eval)
451 			break;
452 		if (semnum < 0 || semnum >= semaptr->ds.sem_nsems) {
453 			eval = EINVAL;
454 			break;
455 		}
456 		rval = semaptr->ds.sem_base[semnum].semncnt;
457 		break;
458 
459 	case GETPID:
460 		eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_R);
461 		if (eval)
462 			break;
463 		if (semnum < 0 || semnum >= semaptr->ds.sem_nsems) {
464 			eval = EINVAL;
465 			break;
466 		}
467 		rval = semaptr->ds.sem_base[semnum].sempid;
468 		break;
469 
470 	case GETVAL:
471 		eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_R);
472 		if (eval)
473 			break;
474 		if (semnum < 0 || semnum >= semaptr->ds.sem_nsems) {
475 			eval = EINVAL;
476 			break;
477 		}
478 		rval = semaptr->ds.sem_base[semnum].semval;
479 		break;
480 
481 	case GETALL:
482 		eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_R);
483 		if (eval)
484 			break;
485 		if ((eval = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
486 			break;
487 		for (i = 0; i < semaptr->ds.sem_nsems; i++) {
488 			eval = copyout(&semaptr->ds.sem_base[i].semval,
489 				       &real_arg.array[i],
490 				       sizeof(real_arg.array[0]));
491 			if (eval)
492 				break;
493 		}
494 		break;
495 
496 	case GETZCNT:
497 		eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_R);
498 		if (eval)
499 			break;
500 		if (semnum < 0 || semnum >= semaptr->ds.sem_nsems) {
501 			eval = EINVAL;
502 			break;
503 		}
504 		rval = semaptr->ds.sem_base[semnum].semzcnt;
505 		break;
506 
507 	case SETVAL:
508 		eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_W);
509 		if (eval)
510 			break;
511 		if (semnum < 0 || semnum >= semaptr->ds.sem_nsems) {
512 			eval = EINVAL;
513 			break;
514 		}
515 		if ((eval = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
516 			break;
517 
518 		/*
519 		 * Because we hold semaptr->lk exclusively we can safely
520 		 * modify any semptr content without acquiring its token.
521 		 */
522 		semptr = &semaptr->ds.sem_base[semnum];
523 		semptr->semval = real_arg.val;
524 		semundo_clear(semid, semnum);
525 		if (semptr->semzcnt || semptr->semncnt)
526 			wakeup(semptr);
527 		break;
528 
529 	case SETALL:
530 		eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_W);
531 		if (eval)
532 			break;
533 		if ((eval = copyin(arg, &real_arg, sizeof(real_arg))) != 0)
534 			break;
535 		/*
536 		 * Because we hold semaptr->lk exclusively we can safely
537 		 * modify any semptr content without acquiring its token.
538 		 */
539 		for (i = 0; i < semaptr->ds.sem_nsems; i++) {
540 			semptr = &semaptr->ds.sem_base[i];
541 			eval = copyin(&real_arg.array[i],
542 				      (caddr_t)&semptr->semval,
543 				      sizeof(real_arg.array[0]));
544 			if (semptr->semzcnt || semptr->semncnt)
545 				wakeup(semptr);
546 			if (eval != 0)
547 				break;
548 		}
549 		semundo_clear(semid, -1);
550 		break;
551 
552 	default:
553 		eval = EINVAL;
554 		break;
555 	}
556 	lockmgr(&semaptr->lk, LK_RELEASE);
557 
558 	if (eval == 0)
559 		sysmsg->sysmsg_result = rval;
560 	return(eval);
561 }
562 
563 /*
564  * MPALMOSTSAFE
565  */
566 int
567 sys_semget(struct sysmsg *sysmsg, const struct semget_args *uap)
568 {
569 	struct thread *td = curthread;
570 	struct prison *pr = td->td_proc->p_ucred->cr_prison;
571 	int semid, eval;
572 	int key = uap->key;
573 	int nsems = uap->nsems;
574 	int semflg = uap->semflg;
575 	struct ucred *cred = td->td_ucred;
576 
577 #ifdef SEM_DEBUG
578 	kprintf("semget(0x%x, %d, 0%o)\n", key, nsems, semflg);
579 #endif
580 
581 	if (pr && !PRISON_CAP_ISSET(pr->pr_caps, PRISON_CAP_SYS_SYSVIPC))
582 		return (ENOSYS);
583 
584 	eval = 0;
585 
586 	if (key != IPC_PRIVATE) {
587 		for (semid = 0; semid < seminfo.semmni; semid++) {
588 			if ((sema[semid].ds.sem_perm.mode & SEM_ALLOC) == 0 ||
589 			    sema[semid].ds.sem_perm.key != key) {
590 				continue;
591 			}
592 			lockmgr(&sema[semid].lk, LK_EXCLUSIVE);
593 			if ((sema[semid].ds.sem_perm.mode & SEM_ALLOC) == 0 ||
594 			    sema[semid].ds.sem_perm.key != key) {
595 				lockmgr(&sema[semid].lk, LK_RELEASE);
596 				continue;
597 			}
598 			break;
599 		}
600 		if (semid < seminfo.semmni) {
601 			/* sema[semid].lk still locked from above */
602 #ifdef SEM_DEBUG
603 			kprintf("found public key\n");
604 #endif
605 			if ((eval = ipcperm(td->td_proc,
606 					    &sema[semid].ds.sem_perm,
607 					    semflg & 0700))) {
608 				lockmgr(&sema[semid].lk, LK_RELEASE);
609 				goto done;
610 			}
611 			if (nsems > 0 && sema[semid].ds.sem_nsems < nsems) {
612 #ifdef SEM_DEBUG
613 				kprintf("too small\n");
614 #endif
615 				eval = EINVAL;
616 				lockmgr(&sema[semid].lk, LK_RELEASE);
617 				goto done;
618 			}
619 			if ((semflg & IPC_CREAT) && (semflg & IPC_EXCL)) {
620 #ifdef SEM_DEBUG
621 				kprintf("not exclusive\n");
622 #endif
623 				eval = EEXIST;
624 				lockmgr(&sema[semid].lk, LK_RELEASE);
625 				goto done;
626 			}
627 
628 			/*
629 			 * Return this one.
630 			 */
631 			lockmgr(&sema[semid].lk, LK_RELEASE);
632 			goto done;
633 		}
634 	}
635 
636 #ifdef SEM_DEBUG
637 	kprintf("need to allocate the semid_ds\n");
638 #endif
639 	if (key == IPC_PRIVATE || (semflg & IPC_CREAT)) {
640 		if (nsems <= 0 || nsems > seminfo.semmsl) {
641 #ifdef SEM_DEBUG
642 			kprintf("nsems out of range (0<%d<=%d)\n",
643 				nsems, seminfo.semmsl);
644 #endif
645 			eval = EINVAL;
646 			goto done;
647 		}
648 
649 		/*
650 		 * SEM_ALLOC flag cannot be set unless sema_lk is locked.
651 		 * semtot field also protected by sema_lk.
652 		 */
653 		lockmgr(&sema_lk, LK_EXCLUSIVE);
654 		if (nsems > seminfo.semmns - semtot) {
655 #ifdef SEM_DEBUG
656 			kprintf("not enough semaphores left "
657 				"(need %d, got %d)\n",
658 				nsems, seminfo.semmns - semtot);
659 #endif
660 			eval = ENOSPC;
661 			lockmgr(&sema_lk, LK_RELEASE);
662 			goto done;
663 		}
664 		for (semid = 0; semid < seminfo.semmni; semid++) {
665 			if ((sema[semid].ds.sem_perm.mode & SEM_ALLOC) == 0)
666 				break;
667 		}
668 		if (semid == seminfo.semmni) {
669 #ifdef SEM_DEBUG
670 			kprintf("no more semid_ds's available\n");
671 #endif
672 			eval = ENOSPC;
673 			lockmgr(&sema_lk, LK_RELEASE);
674 			goto done;
675 		}
676 #ifdef SEM_DEBUG
677 		kprintf("semid %d is available\n", semid);
678 #endif
679 		lockmgr(&sema[semid].lk, LK_EXCLUSIVE);
680 		sema[semid].ds.sem_perm.key = key;
681 		sema[semid].ds.sem_perm.cuid = cred->cr_uid;
682 		sema[semid].ds.sem_perm.uid = cred->cr_uid;
683 		sema[semid].ds.sem_perm.cgid = cred->cr_gid;
684 		sema[semid].ds.sem_perm.gid = cred->cr_gid;
685 		sema[semid].ds.sem_perm.mode = (semflg & 0777) | SEM_ALLOC;
686 		sema[semid].ds.sem_perm.seq =
687 		    (sema[semid].ds.sem_perm.seq + 1) & 0x7fff;
688 		sema[semid].ds.sem_nsems = nsems;
689 		sema[semid].ds.sem_otime = 0;
690 		sema[semid].ds.sem_ctime = time_second;
691 		sema[semid].ds.sem_base = kmalloc(sizeof(struct sem) * nsems,
692 					       M_SEM, M_WAITOK|M_ZERO);
693 		semtot += nsems;
694 		++sema[semid].gen;
695 		lockmgr(&sema[semid].lk, LK_RELEASE);
696 		lockmgr(&sema_lk, LK_RELEASE);
697 #ifdef SEM_DEBUG
698 		kprintf("sembase = 0x%x, next = 0x%x\n",
699 			sema[semid].ds.sem_base, &sem[semtot]);
700 #endif
701 		/* eval == 0 */
702 	} else {
703 #ifdef SEM_DEBUG
704 		kprintf("didn't find it and wasn't asked to create it\n");
705 #endif
706 		eval = ENOENT;
707 	}
708 
709 done:
710 	if (eval == 0) {
711 		sysmsg->sysmsg_result =
712 			IXSEQ_TO_IPCID(semid, sema[semid].ds.sem_perm);
713 	}
714 	return(eval);
715 }
716 
717 /*
718  * MPSAFE
719  */
720 int
721 sys_semop(struct sysmsg *sysmsg, const struct semop_args *uap)
722 {
723 	struct thread *td = curthread;
724 	struct prison *pr = td->td_proc->p_ucred->cr_prison;
725 	int semid = uap->semid;
726 	u_int nsops = uap->nsops;
727 	struct sembuf sops[MAX_SOPS];
728 	struct semid_pool *semaptr;
729 	struct sembuf *sopptr;
730 	struct sem *semptr;
731 	struct sem *xsemptr;
732 	int i, j, eval;
733 	int do_undos;
734 
735 #ifdef SEM_DEBUG
736 	kprintf("call to semop(%d, 0x%x, %u)\n", semid, sops, nsops);
737 #endif
738 	if (pr && !PRISON_CAP_ISSET(pr->pr_caps, PRISON_CAP_SYS_SYSVIPC))
739 		return (ENOSYS);
740 
741 	semid = IPCID_TO_IX(semid);	/* Convert back to zero origin */
742 
743 	if (semid < 0 || semid >= seminfo.semmni) {
744 		eval = EINVAL;
745 		goto done2;
746 	}
747 
748 	wakeup_start_delayed();
749 	semaptr = &sema[semid];
750 	lockmgr(&semaptr->lk, LK_SHARED);
751 
752 	if ((semaptr->ds.sem_perm.mode & SEM_ALLOC) == 0) {
753 		eval = EINVAL;
754 		goto done;
755 	}
756 	if (semaptr->ds.sem_perm.seq != IPCID_TO_SEQ(uap->semid)) {
757 		eval = EINVAL;
758 		goto done;
759 	}
760 
761 	if ((eval = ipcperm(td->td_proc, &semaptr->ds.sem_perm, IPC_W))) {
762 #ifdef SEM_DEBUG
763 		kprintf("eval = %d from ipaccess\n", eval);
764 #endif
765 		goto done;
766 	}
767 
768 	if (nsops > MAX_SOPS) {
769 #ifdef SEM_DEBUG
770 		kprintf("too many sops (max=%d, nsops=%u)\n", MAX_SOPS, nsops);
771 #endif
772 		eval = E2BIG;
773 		goto done;
774 	}
775 
776 	if ((eval = copyin(uap->sops, &sops, nsops * sizeof(sops[0]))) != 0) {
777 #ifdef SEM_DEBUG
778 		kprintf("eval = %d from copyin(%08x, %08x, %u)\n", eval,
779 		    uap->sops, &sops, nsops * sizeof(sops[0]));
780 #endif
781 		goto done;
782 	}
783 
784 	/*
785 	 * Loop trying to satisfy the vector of requests.
786 	 * If we reach a point where we must wait, any requests already
787 	 * performed are rolled back and we go to sleep until some other
788 	 * process wakes us up.  At this point, we start all over again.
789 	 *
790 	 * This ensures that from the perspective of other tasks, a set
791 	 * of requests is atomic (never partially satisfied).
792 	 */
793 	do_undos = 0;
794 
795 	for (;;) {
796 		long gen;
797 
798 		semptr = NULL;
799 
800 		for (i = 0; i < nsops; i++) {
801 			sopptr = &sops[i];
802 
803 			if (sopptr->sem_num >= semaptr->ds.sem_nsems) {
804 				eval = EFBIG;
805 				goto done;
806 			}
807 
808 			semptr = &semaptr->ds.sem_base[sopptr->sem_num];
809 			lwkt_getpooltoken(semptr);
810 
811 #ifdef SEM_DEBUG
812 			kprintf("semop:  semaptr=%x, sem_base=%x, semptr=%x, "
813 				"sem[%d]=%d : op=%d, flag=%s\n",
814 			    semaptr, semaptr->ds.sem_base, semptr,
815 			    sopptr->sem_num, semptr->semval, sopptr->sem_op,
816 			    (sopptr->sem_flg & IPC_NOWAIT) ? "nowait" : "wait");
817 #endif
818 
819 			if (sopptr->sem_op < 0) {
820 				if (semptr->semval + sopptr->sem_op < 0) {
821 #ifdef SEM_DEBUG
822 					kprintf("semop:  can't do it now\n");
823 #endif
824 					break;
825 				} else {
826 					semptr->semval += sopptr->sem_op;
827 					if (semptr->semval == 0 &&
828 					    semptr->semzcnt > 0) {
829 						wakeup(semptr);
830 					}
831 				}
832 				if (sopptr->sem_flg & SEM_UNDO)
833 					do_undos = 1;
834 			} else if (sopptr->sem_op == 0) {
835 				if (semptr->semval > 0) {
836 #ifdef SEM_DEBUG
837 					kprintf("semop:  not zero now\n");
838 #endif
839 					break;
840 				}
841 			} else {
842 				semptr->semval += sopptr->sem_op;
843 				if (sopptr->sem_flg & SEM_UNDO)
844 					do_undos = 1;
845 				if (semptr->semncnt > 0)
846 					wakeup(semptr);
847 			}
848 			lwkt_relpooltoken(semptr);
849 		}
850 
851 		/*
852 		 * Did we get through the entire vector?
853 		 */
854 		if (i >= nsops)
855 			goto donex;
856 
857 		/*
858 		 * No, protect the semaphore request which also flags that
859 		 * a wakeup is needed, then release semptr since we know
860 		 * another process is likely going to need to access it
861 		 * soon.
862 		 */
863 		if (sopptr->sem_op == 0)
864 			semptr->semzcnt++;
865 		else
866 			semptr->semncnt++;
867 		tsleep_interlock(semptr, PCATCH);
868 		lwkt_relpooltoken(semptr);
869 
870 		/*
871 		 * Rollback the semaphores we had acquired.
872 		 */
873 #ifdef SEM_DEBUG
874 		kprintf("semop:  rollback 0 through %d\n", i-1);
875 #endif
876 		for (j = 0; j < i; j++) {
877 			xsemptr = &semaptr->ds.sem_base[sops[j].sem_num];
878 			lwkt_getpooltoken(xsemptr);
879 			xsemptr->semval -= sops[j].sem_op;
880 			if (xsemptr->semval == 0 && xsemptr->semzcnt > 0)
881 				wakeup(xsemptr);
882 			if (xsemptr->semval <= 0 && xsemptr->semncnt > 0)
883 				wakeup(xsemptr);
884 			lwkt_relpooltoken(xsemptr);
885 		}
886 
887 		/*
888 		 * If the request that we couldn't satisfy has the
889 		 * NOWAIT flag set then return with EAGAIN.
890 		 */
891 		if (sopptr->sem_flg & IPC_NOWAIT) {
892 			eval = EAGAIN;
893 			goto done;
894 		}
895 
896 		/*
897 		 * Release semaptr->lk while sleeping, allowing other
898 		 * semops (like SETVAL, SETALL, etc), which require an
899 		 * exclusive lock and might wake us up.
900 		 *
901 		 * Reload and recheck the validity of semaptr on return.
902 		 * Note that semptr itself might have changed too, but
903 		 * we've already interlocked for semptr and that is what
904 		 * will be woken up if it wakes up the tsleep on a MP
905 		 * race.
906 		 *
907 		 * gen protects against destroy/re-create races where the
908 		 * creds match.
909 		 */
910 #ifdef SEM_DEBUG
911 		kprintf("semop:  good night!\n");
912 #endif
913 		gen = semaptr->gen;
914 		lockmgr(&semaptr->lk, LK_RELEASE);
915 		eval = tsleep(semptr, PCATCH | PINTERLOCKED, "semwait", hz);
916 		lockmgr(&semaptr->lk, LK_SHARED);
917 #ifdef SEM_DEBUG
918 		kprintf("semop:  good morning (eval=%d)!\n", eval);
919 #endif
920 
921 		/* return code is checked below, after sem[nz]cnt-- */
922 
923 		/*
924 		 * Make sure that the semaphore still exists
925 		 */
926 		if (semaptr->gen != gen ||
927 		    (semaptr->ds.sem_perm.mode & SEM_ALLOC) == 0 ||
928 		    semaptr->ds.sem_perm.seq != IPCID_TO_SEQ(uap->semid)) {
929 			eval = EIDRM;
930 			goto done;
931 		}
932 
933 		/*
934 		 * The semaphore is still alive.  Readjust the count of
935 		 * waiting processes.
936 		 */
937 		semptr = &semaptr->ds.sem_base[sopptr->sem_num];
938 		lwkt_getpooltoken(semptr);
939 		if (sopptr->sem_op == 0)
940 			semptr->semzcnt--;
941 		else
942 			semptr->semncnt--;
943 		lwkt_relpooltoken(semptr);
944 
945 		/*
946 		 * Is it really morning, or was our sleep interrupted?
947 		 * (Delayed check of tsleep() return code because we
948 		 * need to decrement sem[nz]cnt either way.)
949 		 */
950 		if (eval) {
951 			eval = EINTR;
952 			goto done;
953 		}
954 #ifdef SEM_DEBUG
955 		kprintf("semop:  good morning!\n");
956 #endif
957 		/* RETRY LOOP */
958 	}
959 
960 donex:
961 	/*
962 	 * Process any SEM_UNDO requests.
963 	 */
964 	if (do_undos) {
965 		for (i = 0; i < nsops; i++) {
966 			/*
967 			 * We only need to deal with SEM_UNDO's for non-zero
968 			 * op's.
969 			 */
970 			int adjval;
971 
972 			if ((sops[i].sem_flg & SEM_UNDO) == 0)
973 				continue;
974 			adjval = sops[i].sem_op;
975 			if (adjval == 0)
976 				continue;
977 			eval = semundo_adjust(td->td_proc, semid,
978 					      sops[i].sem_num, -adjval);
979 			if (eval == 0)
980 				continue;
981 
982 			/*
983 			 * Oh-Oh!  We ran out of either sem_undo's or undo's.
984 			 * Rollback the adjustments to this point and then
985 			 * rollback the semaphore ups and down so we can return
986 			 * with an error with all structures restored.  We
987 			 * rollback the undo's in the exact reverse order that
988 			 * we applied them.  This guarantees that we won't run
989 			 * out of space as we roll things back out.
990 			 */
991 			for (j = i - 1; j >= 0; j--) {
992 				if ((sops[j].sem_flg & SEM_UNDO) == 0)
993 					continue;
994 				adjval = sops[j].sem_op;
995 				if (adjval == 0)
996 					continue;
997 				if (semundo_adjust(td->td_proc, semid,
998 					       sops[j].sem_num, adjval) != 0)
999 					panic("semop - can't undo undos");
1000 			}
1001 
1002 			for (j = 0; j < nsops; j++) {
1003 				xsemptr = &semaptr->ds.sem_base[
1004 							sops[j].sem_num];
1005 				lwkt_getpooltoken(xsemptr);
1006 				xsemptr->semval -= sops[j].sem_op;
1007 				if (xsemptr->semval == 0 &&
1008 				    xsemptr->semzcnt > 0)
1009 					wakeup(xsemptr);
1010 				if (xsemptr->semval <= 0 &&
1011 				    xsemptr->semncnt > 0)
1012 					wakeup(xsemptr);
1013 				lwkt_relpooltoken(xsemptr);
1014 			}
1015 
1016 #ifdef SEM_DEBUG
1017 			kprintf("eval = %d from semundo_adjust\n", eval);
1018 #endif
1019 			goto done;
1020 		} /* loop through the sops */
1021 	} /* if (do_undos) */
1022 
1023 	/* We're definitely done - set the sempid's */
1024 	for (i = 0; i < nsops; i++) {
1025 		sopptr = &sops[i];
1026 		semptr = &semaptr->ds.sem_base[sopptr->sem_num];
1027 		lwkt_getpooltoken(semptr);
1028 		semptr->sempid = td->td_proc->p_pid;
1029 		lwkt_relpooltoken(semptr);
1030 	}
1031 
1032 	/* Do a wakeup if any semaphore was up'd. */
1033 #ifdef SEM_DEBUG
1034 	kprintf("semop:  done\n");
1035 #endif
1036 	sysmsg->sysmsg_result = 0;
1037 	eval = 0;
1038 done:
1039 	lockmgr(&semaptr->lk, LK_RELEASE);
1040 	wakeup_end_delayed();
1041 done2:
1042 	return(eval);
1043 }
1044 
1045 /*
1046  * Go through the undo structures for this process and apply the adjustments to
1047  * semaphores.
1048  *
1049  * (p->p_token is held by the caller)
1050  */
1051 void
1052 semexit(struct proc *p)
1053 {
1054 	struct sem_undo *suptr;
1055 	struct sem *semptr;
1056 
1057 	/*
1058 	 * We're getting a global token, don't do it if we couldn't
1059 	 * possibly have any semaphores.
1060 	 */
1061 	if ((p->p_flags & P_SYSVSEM) == 0)
1062 		return;
1063 	suptr = p->p_sem_undo;
1064 	KKASSERT(suptr != NULL);
1065 
1066 	/*
1067 	 * Disconnect suptr from the process and increment un_refs to
1068 	 * prevent anyone else from being able to destroy the structure.
1069 	 * Do not remove it from the linked list until after we are through
1070 	 * scanning it as other semaphore calls might still effect it.
1071 	 */
1072 	lwkt_gettoken(&semu_token);
1073 	p->p_sem_undo = NULL;
1074 	p->p_flags &= ~P_SYSVSEM;
1075 	suptr->un_proc = NULL;
1076 	++suptr->un_refs;
1077 	lwkt_reltoken(&semu_token);
1078 
1079 	while (suptr->un_cnt) {
1080 		struct semid_pool *semaptr;
1081 		int semid;
1082 		int semnum;
1083 		int adjval;
1084 		int ix;
1085 
1086 		/*
1087 		 * These values are stable because we hold p->p_token.
1088 		 * However, they can get ripped out from under us when
1089 		 * we block or obtain other tokens so we have to re-check.
1090 		 */
1091 		ix = suptr->un_cnt - 1;
1092 		semid = suptr->un_ent[ix].un_id;
1093 		semnum = suptr->un_ent[ix].un_num;
1094 		adjval = suptr->un_ent[ix].un_adjval;
1095 
1096 		semaptr = &sema[semid];
1097 
1098 		/*
1099 		 * Recheck after locking, then execute the undo
1100 		 * operation.  semptr remains valid due to the
1101 		 * semaptr->lk.
1102 		 */
1103 		lockmgr(&semaptr->lk, LK_SHARED);
1104 		semptr = &semaptr->ds.sem_base[semnum];
1105 		lwkt_getpooltoken(semptr);
1106 
1107 		if (ix == suptr->un_cnt - 1 &&
1108 		    semid == suptr->un_ent[ix].un_id &&
1109 		    semnum == suptr->un_ent[ix].un_num &&
1110 		    adjval == suptr->un_ent[ix].un_adjval) {
1111 			/*
1112 			 * Only do assertions when we aren't in a SMP race.
1113 			 */
1114 			if ((semaptr->ds.sem_perm.mode & SEM_ALLOC) == 0)
1115 				panic("semexit - semid not allocated");
1116 			if (semnum >= semaptr->ds.sem_nsems)
1117 				panic("semexit - semnum out of range");
1118 			--suptr->un_cnt;
1119 
1120 			if (adjval < 0) {
1121 				if (semptr->semval < -adjval)
1122 					semptr->semval = 0;
1123 				else
1124 					semptr->semval += adjval;
1125 			} else {
1126 				semptr->semval += adjval;
1127 			}
1128 			wakeup(semptr);
1129 		}
1130 		lwkt_relpooltoken(semptr);
1131 		lockmgr(&semaptr->lk, LK_RELEASE);
1132 	}
1133 
1134 	/*
1135 	 * Final cleanup, remove from the list and deallocate on the
1136 	 * last ref only.
1137 	 */
1138 	lwkt_gettoken(&semu_token);
1139 	if (--suptr->un_refs == 0) {
1140 		TAILQ_REMOVE(&semu_list, suptr, un_entry);
1141 		KKASSERT(suptr->un_cnt == 0);
1142 		kfree(suptr, M_SEM);
1143 	}
1144 	lwkt_reltoken(&semu_token);
1145 }
1146