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