xref: /freebsd/sys/kern/uipc_sem.c (revision 271c3a9060f2ee55607ebe146523f888e1db2654)
1 /*-
2  * Copyright (c) 2002 Alfred Perlstein <alfred@FreeBSD.org>
3  * Copyright (c) 2003-2005 SPARTA, Inc.
4  * Copyright (c) 2005 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * This software was developed for the FreeBSD Project in part by Network
8  * Associates Laboratories, the Security Research Division of Network
9  * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"),
10  * as part of the DARPA CHATS research program.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_mac.h"
38 #include "opt_posix.h"
39 
40 #include <sys/param.h>
41 #include <sys/condvar.h>
42 #include <sys/fcntl.h>
43 #include <sys/file.h>
44 #include <sys/filedesc.h>
45 #include <sys/fnv_hash.h>
46 #include <sys/kernel.h>
47 #include <sys/ksem.h>
48 #include <sys/lock.h>
49 #include <sys/malloc.h>
50 #include <sys/module.h>
51 #include <sys/mutex.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/posix4.h>
55 #include <sys/semaphore.h>
56 #include <sys/_semaphore.h>
57 #include <sys/stat.h>
58 #include <sys/syscall.h>
59 #include <sys/syscallsubr.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysent.h>
62 #include <sys/sysproto.h>
63 #include <sys/systm.h>
64 #include <sys/sx.h>
65 #include <sys/vnode.h>
66 
67 #include <security/mac/mac_framework.h>
68 
69 /*
70  * TODO
71  *
72  * - Resource limits?
73  * - Update fstat(1)
74  * - Replace global sem_lock with mtx_pool locks?
75  * - Add a MAC check_create() hook for creating new named semaphores.
76  */
77 
78 #ifndef SEM_MAX
79 #define	SEM_MAX	30
80 #endif
81 
82 #ifdef SEM_DEBUG
83 #define	DP(x)	printf x
84 #else
85 #define	DP(x)
86 #endif
87 
88 struct ksem_mapping {
89 	char		*km_path;
90 	Fnv32_t		km_fnv;
91 	struct ksem	*km_ksem;
92 	LIST_ENTRY(ksem_mapping) km_link;
93 };
94 
95 static MALLOC_DEFINE(M_KSEM, "ksem", "semaphore file descriptor");
96 static LIST_HEAD(, ksem_mapping) *ksem_dictionary;
97 static struct sx ksem_dict_lock;
98 static struct mtx ksem_count_lock;
99 static struct mtx sem_lock;
100 static u_long ksem_hash;
101 static int ksem_dead;
102 
103 #define	KSEM_HASH(fnv)	(&ksem_dictionary[(fnv) & ksem_hash])
104 
105 static int nsems = 0;
106 SYSCTL_DECL(_p1003_1b);
107 SYSCTL_INT(_p1003_1b, OID_AUTO, nsems, CTLFLAG_RD, &nsems, 0,
108     "Number of active kernel POSIX semaphores");
109 
110 static int	kern_sem_wait(struct thread *td, semid_t id, int tryflag,
111 		    struct timespec *abstime);
112 static int	ksem_access(struct ksem *ks, struct ucred *ucred);
113 static struct ksem *ksem_alloc(struct ucred *ucred, mode_t mode,
114 		    unsigned int value);
115 static int	ksem_create(struct thread *td, const char *path,
116 		    semid_t *semidp, mode_t mode, unsigned int value,
117 		    int flags);
118 static void	ksem_drop(struct ksem *ks);
119 static int	ksem_get(struct thread *td, semid_t id, struct file **fpp);
120 static struct ksem *ksem_hold(struct ksem *ks);
121 static void	ksem_insert(char *path, Fnv32_t fnv, struct ksem *ks);
122 static struct ksem *ksem_lookup(char *path, Fnv32_t fnv);
123 static void	ksem_module_destroy(void);
124 static int	ksem_module_init(void);
125 static int	ksem_remove(char *path, Fnv32_t fnv, struct ucred *ucred);
126 static int	sem_modload(struct module *module, int cmd, void *arg);
127 
128 static fo_rdwr_t	ksem_read;
129 static fo_rdwr_t	ksem_write;
130 static fo_truncate_t	ksem_truncate;
131 static fo_ioctl_t	ksem_ioctl;
132 static fo_poll_t	ksem_poll;
133 static fo_kqfilter_t	ksem_kqfilter;
134 static fo_stat_t	ksem_stat;
135 static fo_close_t	ksem_closef;
136 
137 /* File descriptor operations. */
138 static struct fileops ksem_ops = {
139 	.fo_read = ksem_read,
140 	.fo_write = ksem_write,
141 	.fo_truncate = ksem_truncate,
142 	.fo_ioctl = ksem_ioctl,
143 	.fo_poll = ksem_poll,
144 	.fo_kqfilter = ksem_kqfilter,
145 	.fo_stat = ksem_stat,
146 	.fo_close = ksem_closef,
147 	.fo_flags = DFLAG_PASSABLE
148 };
149 
150 FEATURE(posix_sem, "POSIX semaphores");
151 
152 static int
153 ksem_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
154     int flags, struct thread *td)
155 {
156 
157 	return (EOPNOTSUPP);
158 }
159 
160 static int
161 ksem_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
162     int flags, struct thread *td)
163 {
164 
165 	return (EOPNOTSUPP);
166 }
167 
168 static int
169 ksem_truncate(struct file *fp, off_t length, struct ucred *active_cred,
170     struct thread *td)
171 {
172 
173 	return (EINVAL);
174 }
175 
176 static int
177 ksem_ioctl(struct file *fp, u_long com, void *data,
178     struct ucred *active_cred, struct thread *td)
179 {
180 
181 	return (EOPNOTSUPP);
182 }
183 
184 static int
185 ksem_poll(struct file *fp, int events, struct ucred *active_cred,
186     struct thread *td)
187 {
188 
189 	return (EOPNOTSUPP);
190 }
191 
192 static int
193 ksem_kqfilter(struct file *fp, struct knote *kn)
194 {
195 
196 	return (EOPNOTSUPP);
197 }
198 
199 static int
200 ksem_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
201     struct thread *td)
202 {
203 	struct ksem *ks;
204 #ifdef MAC
205 	int error;
206 #endif
207 
208 	ks = fp->f_data;
209 
210 #ifdef MAC
211 	error = mac_posixsem_check_stat(active_cred, fp->f_cred, ks);
212 	if (error)
213 		return (error);
214 #endif
215 
216 	/*
217 	 * Attempt to return sanish values for fstat() on a semaphore
218 	 * file descriptor.
219 	 */
220 	bzero(sb, sizeof(*sb));
221 	sb->st_mode = S_IFREG | ks->ks_mode;		/* XXX */
222 
223 	sb->st_atimespec = ks->ks_atime;
224 	sb->st_ctimespec = ks->ks_ctime;
225 	sb->st_mtimespec = ks->ks_mtime;
226 	sb->st_birthtimespec = ks->ks_birthtime;
227 	sb->st_uid = ks->ks_uid;
228 	sb->st_gid = ks->ks_gid;
229 
230 	return (0);
231 }
232 
233 static int
234 ksem_closef(struct file *fp, struct thread *td)
235 {
236 	struct ksem *ks;
237 
238 	ks = fp->f_data;
239 	fp->f_data = NULL;
240 	ksem_drop(ks);
241 
242 	return (0);
243 }
244 
245 /*
246  * ksem object management including creation and reference counting
247  * routines.
248  */
249 static struct ksem *
250 ksem_alloc(struct ucred *ucred, mode_t mode, unsigned int value)
251 {
252 	struct ksem *ks;
253 
254 	mtx_lock(&ksem_count_lock);
255 	if (nsems == p31b_getcfg(CTL_P1003_1B_SEM_NSEMS_MAX) || ksem_dead) {
256 		mtx_unlock(&ksem_count_lock);
257 		return (NULL);
258 	}
259 	nsems++;
260 	mtx_unlock(&ksem_count_lock);
261 	ks = malloc(sizeof(*ks), M_KSEM, M_WAITOK | M_ZERO);
262 	ks->ks_uid = ucred->cr_uid;
263 	ks->ks_gid = ucred->cr_gid;
264 	ks->ks_mode = mode;
265 	ks->ks_value = value;
266 	cv_init(&ks->ks_cv, "ksem");
267 	vfs_timestamp(&ks->ks_birthtime);
268 	ks->ks_atime = ks->ks_mtime = ks->ks_ctime = ks->ks_birthtime;
269 	refcount_init(&ks->ks_ref, 1);
270 #ifdef MAC
271 	mac_posixsem_init(ks);
272 	mac_posixsem_create(ucred, ks);
273 #endif
274 
275 	return (ks);
276 }
277 
278 static struct ksem *
279 ksem_hold(struct ksem *ks)
280 {
281 
282 	refcount_acquire(&ks->ks_ref);
283 	return (ks);
284 }
285 
286 static void
287 ksem_drop(struct ksem *ks)
288 {
289 
290 	if (refcount_release(&ks->ks_ref)) {
291 #ifdef MAC
292 		mac_posixsem_destroy(ks);
293 #endif
294 		cv_destroy(&ks->ks_cv);
295 		free(ks, M_KSEM);
296 		mtx_lock(&ksem_count_lock);
297 		nsems--;
298 		mtx_unlock(&ksem_count_lock);
299 	}
300 }
301 
302 /*
303  * Determine if the credentials have sufficient permissions for read
304  * and write access.
305  */
306 static int
307 ksem_access(struct ksem *ks, struct ucred *ucred)
308 {
309 	int error;
310 
311 	error = vaccess(VREG, ks->ks_mode, ks->ks_uid, ks->ks_gid,
312 	    VREAD | VWRITE, ucred, NULL);
313 	if (error)
314 		error = priv_check_cred(ucred, PRIV_SEM_WRITE, 0);
315 	return (error);
316 }
317 
318 /*
319  * Dictionary management.  We maintain an in-kernel dictionary to map
320  * paths to semaphore objects.  We use the FNV hash on the path to
321  * store the mappings in a hash table.
322  */
323 static struct ksem *
324 ksem_lookup(char *path, Fnv32_t fnv)
325 {
326 	struct ksem_mapping *map;
327 
328 	LIST_FOREACH(map, KSEM_HASH(fnv), km_link) {
329 		if (map->km_fnv != fnv)
330 			continue;
331 		if (strcmp(map->km_path, path) == 0)
332 			return (map->km_ksem);
333 	}
334 
335 	return (NULL);
336 }
337 
338 static void
339 ksem_insert(char *path, Fnv32_t fnv, struct ksem *ks)
340 {
341 	struct ksem_mapping *map;
342 
343 	map = malloc(sizeof(struct ksem_mapping), M_KSEM, M_WAITOK);
344 	map->km_path = path;
345 	map->km_fnv = fnv;
346 	map->km_ksem = ksem_hold(ks);
347 	LIST_INSERT_HEAD(KSEM_HASH(fnv), map, km_link);
348 }
349 
350 static int
351 ksem_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
352 {
353 	struct ksem_mapping *map;
354 	int error;
355 
356 	LIST_FOREACH(map, KSEM_HASH(fnv), km_link) {
357 		if (map->km_fnv != fnv)
358 			continue;
359 		if (strcmp(map->km_path, path) == 0) {
360 #ifdef MAC
361 			error = mac_posixsem_check_unlink(ucred, map->km_ksem);
362 			if (error)
363 				return (error);
364 #endif
365 			error = ksem_access(map->km_ksem, ucred);
366 			if (error)
367 				return (error);
368 			LIST_REMOVE(map, km_link);
369 			ksem_drop(map->km_ksem);
370 			free(map->km_path, M_KSEM);
371 			free(map, M_KSEM);
372 			return (0);
373 		}
374 	}
375 
376 	return (ENOENT);
377 }
378 
379 /* Other helper routines. */
380 static int
381 ksem_create(struct thread *td, const char *name, semid_t *semidp, mode_t mode,
382     unsigned int value, int flags)
383 {
384 	struct filedesc *fdp;
385 	struct ksem *ks;
386 	struct file *fp;
387 	char *path;
388 	semid_t semid;
389 	Fnv32_t fnv;
390 	int error, fd;
391 
392 	if (value > SEM_VALUE_MAX)
393 		return (EINVAL);
394 
395 	fdp = td->td_proc->p_fd;
396 	mode = (mode & ~fdp->fd_cmask) & ACCESSPERMS;
397 	error = falloc(td, &fp, &fd);
398 	if (error) {
399 		if (name == NULL)
400 			error = ENOSPC;
401 		return (error);
402 	}
403 
404 	/*
405 	 * Go ahead and copyout the file descriptor now.  This is a bit
406 	 * premature, but it is a lot easier to handle errors as opposed
407 	 * to later when we've possibly created a new semaphore, etc.
408 	 */
409 	semid = fd;
410 	error = copyout(&semid, semidp, sizeof(semid));
411 	if (error) {
412 		fdclose(fdp, fp, fd, td);
413 		fdrop(fp, td);
414 		return (error);
415 	}
416 
417 	if (name == NULL) {
418 		/* Create an anonymous semaphore. */
419 		ks = ksem_alloc(td->td_ucred, mode, value);
420 		if (ks == NULL)
421 			error = ENOSPC;
422 		else
423 			ks->ks_flags |= KS_ANONYMOUS;
424 	} else {
425 		path = malloc(MAXPATHLEN, M_KSEM, M_WAITOK);
426 		error = copyinstr(name, path, MAXPATHLEN, NULL);
427 
428 		/* Require paths to start with a '/' character. */
429 		if (error == 0 && path[0] != '/')
430 			error = EINVAL;
431 		if (error) {
432 			fdclose(fdp, fp, fd, td);
433 			fdrop(fp, td);
434 			free(path, M_KSEM);
435 			return (error);
436 		}
437 
438 		fnv = fnv_32_str(path, FNV1_32_INIT);
439 		sx_xlock(&ksem_dict_lock);
440 		ks = ksem_lookup(path, fnv);
441 		if (ks == NULL) {
442 			/* Object does not exist, create it if requested. */
443 			if (flags & O_CREAT) {
444 				ks = ksem_alloc(td->td_ucred, mode, value);
445 				if (ks == NULL)
446 					error = ENFILE;
447 				else {
448 					ksem_insert(path, fnv, ks);
449 					path = NULL;
450 				}
451 			} else
452 				error = ENOENT;
453 		} else {
454 			/*
455 			 * Object already exists, obtain a new
456 			 * reference if requested and permitted.
457 			 */
458 			if ((flags & (O_CREAT | O_EXCL)) ==
459 			    (O_CREAT | O_EXCL))
460 				error = EEXIST;
461 			else {
462 #ifdef MAC
463 				error = mac_posixsem_check_open(td->td_ucred,
464 				    ks);
465 				if (error == 0)
466 #endif
467 				error = ksem_access(ks, td->td_ucred);
468 			}
469 			if (error == 0)
470 				ksem_hold(ks);
471 #ifdef INVARIANTS
472 			else
473 				ks = NULL;
474 #endif
475 		}
476 		sx_xunlock(&ksem_dict_lock);
477 		if (path)
478 			free(path, M_KSEM);
479 	}
480 
481 	if (error) {
482 		KASSERT(ks == NULL, ("ksem_create error with a ksem"));
483 		fdclose(fdp, fp, fd, td);
484 		fdrop(fp, td);
485 		return (error);
486 	}
487 	KASSERT(ks != NULL, ("ksem_create w/o a ksem"));
488 
489 	finit(fp, FREAD | FWRITE, DTYPE_SEM, ks, &ksem_ops);
490 
491 	FILEDESC_XLOCK(fdp);
492 	if (fdp->fd_ofiles[fd] == fp)
493 		fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
494 	FILEDESC_XUNLOCK(fdp);
495 	fdrop(fp, td);
496 
497 	return (0);
498 }
499 
500 static int
501 ksem_get(struct thread *td, semid_t id, struct file **fpp)
502 {
503 	struct ksem *ks;
504 	struct file *fp;
505 	int error;
506 
507 	error = fget(td, id, &fp);
508 	if (error)
509 		return (EINVAL);
510 	if (fp->f_type != DTYPE_SEM) {
511 		fdrop(fp, td);
512 		return (EINVAL);
513 	}
514 	ks = fp->f_data;
515 	if (ks->ks_flags & KS_DEAD) {
516 		fdrop(fp, td);
517 		return (EINVAL);
518 	}
519 	*fpp = fp;
520 	return (0);
521 }
522 
523 /* System calls. */
524 #ifndef _SYS_SYSPROTO_H_
525 struct ksem_init_args {
526 	unsigned int	value;
527 	semid_t		*idp;
528 };
529 #endif
530 int
531 ksem_init(struct thread *td, struct ksem_init_args *uap)
532 {
533 
534 	return (ksem_create(td, NULL, uap->idp, S_IRWXU | S_IRWXG, uap->value,
535 	    0));
536 }
537 
538 #ifndef _SYS_SYSPROTO_H_
539 struct ksem_open_args {
540 	char		*name;
541 	int		oflag;
542 	mode_t		mode;
543 	unsigned int	value;
544 	semid_t		*idp;
545 };
546 #endif
547 int
548 ksem_open(struct thread *td, struct ksem_open_args *uap)
549 {
550 
551 	if ((uap->oflag & ~(O_CREAT | O_EXCL)) != 0)
552 		return (EINVAL);
553 	return (ksem_create(td, uap->name, uap->idp, uap->mode, uap->value,
554 	    uap->oflag));
555 }
556 
557 #ifndef _SYS_SYSPROTO_H_
558 struct ksem_unlink_args {
559 	char		*name;
560 };
561 #endif
562 int
563 ksem_unlink(struct thread *td, struct ksem_unlink_args *uap)
564 {
565 	char *path;
566 	Fnv32_t fnv;
567 	int error;
568 
569 	path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
570 	error = copyinstr(uap->name, path, MAXPATHLEN, NULL);
571 	if (error) {
572 		free(path, M_TEMP);
573 		return (error);
574 	}
575 
576 	fnv = fnv_32_str(path, FNV1_32_INIT);
577 	sx_xlock(&ksem_dict_lock);
578 	error = ksem_remove(path, fnv, td->td_ucred);
579 	sx_xunlock(&ksem_dict_lock);
580 	free(path, M_TEMP);
581 
582 	return (error);
583 }
584 
585 #ifndef _SYS_SYSPROTO_H_
586 struct ksem_close_args {
587 	semid_t		id;
588 };
589 #endif
590 int
591 ksem_close(struct thread *td, struct ksem_close_args *uap)
592 {
593 	struct ksem *ks;
594 	struct file *fp;
595 	int error;
596 
597 	error = ksem_get(td, uap->id, &fp);
598 	if (error)
599 		return (error);
600 	ks = fp->f_data;
601 	if (ks->ks_flags & KS_ANONYMOUS) {
602 		fdrop(fp, td);
603 		return (EINVAL);
604 	}
605 	error = kern_close(td, uap->id);
606 	fdrop(fp, td);
607 	return (error);
608 }
609 
610 #ifndef _SYS_SYSPROTO_H_
611 struct ksem_post_args {
612 	semid_t	id;
613 };
614 #endif
615 int
616 ksem_post(struct thread *td, struct ksem_post_args *uap)
617 {
618 	struct file *fp;
619 	struct ksem *ks;
620 	int error;
621 
622 	error = ksem_get(td, uap->id, &fp);
623 	if (error)
624 		return (error);
625 	ks = fp->f_data;
626 
627 	mtx_lock(&sem_lock);
628 #ifdef MAC
629 	error = mac_posixsem_check_post(td->td_ucred, fp->f_cred, ks);
630 	if (error)
631 		goto err;
632 #endif
633 	if (ks->ks_value == SEM_VALUE_MAX) {
634 		error = EOVERFLOW;
635 		goto err;
636 	}
637 	++ks->ks_value;
638 	if (ks->ks_waiters > 0)
639 		cv_signal(&ks->ks_cv);
640 	error = 0;
641 	vfs_timestamp(&ks->ks_ctime);
642 err:
643 	mtx_unlock(&sem_lock);
644 	fdrop(fp, td);
645 	return (error);
646 }
647 
648 #ifndef _SYS_SYSPROTO_H_
649 struct ksem_wait_args {
650 	semid_t		id;
651 };
652 #endif
653 int
654 ksem_wait(struct thread *td, struct ksem_wait_args *uap)
655 {
656 
657 	return (kern_sem_wait(td, uap->id, 0, NULL));
658 }
659 
660 #ifndef _SYS_SYSPROTO_H_
661 struct ksem_timedwait_args {
662 	semid_t		id;
663 	const struct timespec *abstime;
664 };
665 #endif
666 int
667 ksem_timedwait(struct thread *td, struct ksem_timedwait_args *uap)
668 {
669 	struct timespec abstime;
670 	struct timespec *ts;
671 	int error;
672 
673 	/*
674 	 * We allow a null timespec (wait forever).
675 	 */
676 	if (uap->abstime == NULL)
677 		ts = NULL;
678 	else {
679 		error = copyin(uap->abstime, &abstime, sizeof(abstime));
680 		if (error != 0)
681 			return (error);
682 		if (abstime.tv_nsec >= 1000000000 || abstime.tv_nsec < 0)
683 			return (EINVAL);
684 		ts = &abstime;
685 	}
686 	return (kern_sem_wait(td, uap->id, 0, ts));
687 }
688 
689 #ifndef _SYS_SYSPROTO_H_
690 struct ksem_trywait_args {
691 	semid_t		id;
692 };
693 #endif
694 int
695 ksem_trywait(struct thread *td, struct ksem_trywait_args *uap)
696 {
697 
698 	return (kern_sem_wait(td, uap->id, 1, NULL));
699 }
700 
701 static int
702 kern_sem_wait(struct thread *td, semid_t id, int tryflag,
703     struct timespec *abstime)
704 {
705 	struct timespec ts1, ts2;
706 	struct timeval tv;
707 	struct file *fp;
708 	struct ksem *ks;
709 	int error;
710 
711 	DP((">>> kern_sem_wait entered!\n"));
712 	error = ksem_get(td, id, &fp);
713 	if (error)
714 		return (error);
715 	ks = fp->f_data;
716 	mtx_lock(&sem_lock);
717 #ifdef MAC
718 	error = mac_posixsem_check_wait(td->td_ucred, fp->f_cred, ks);
719 	if (error) {
720 		DP(("kern_sem_wait mac failed\n"));
721 		goto err;
722 	}
723 #endif
724 	DP(("kern_sem_wait value = %d, tryflag %d\n", ks->ks_value, tryflag));
725 	vfs_timestamp(&ks->ks_atime);
726 	if (ks->ks_value == 0) {
727 		ks->ks_waiters++;
728 		if (tryflag != 0)
729 			error = EAGAIN;
730 		else if (abstime == NULL)
731 			error = cv_wait_sig(&ks->ks_cv, &sem_lock);
732 		else {
733 			for (;;) {
734 				ts1 = *abstime;
735 				getnanotime(&ts2);
736 				timespecsub(&ts1, &ts2);
737 				TIMESPEC_TO_TIMEVAL(&tv, &ts1);
738 				if (tv.tv_sec < 0) {
739 					error = ETIMEDOUT;
740 					break;
741 				}
742 				error = cv_timedwait_sig(&ks->ks_cv,
743 				    &sem_lock, tvtohz(&tv));
744 				if (error != EWOULDBLOCK)
745 					break;
746 			}
747 		}
748 		ks->ks_waiters--;
749 		if (error)
750 			goto err;
751 	}
752 	ks->ks_value--;
753 	error = 0;
754 err:
755 	mtx_unlock(&sem_lock);
756 	fdrop(fp, td);
757 	DP(("<<< kern_sem_wait leaving, error = %d\n", error));
758 	return (error);
759 }
760 
761 #ifndef _SYS_SYSPROTO_H_
762 struct ksem_getvalue_args {
763 	semid_t		id;
764 	int		*val;
765 };
766 #endif
767 int
768 ksem_getvalue(struct thread *td, struct ksem_getvalue_args *uap)
769 {
770 	struct file *fp;
771 	struct ksem *ks;
772 	int error, val;
773 
774 	error = ksem_get(td, uap->id, &fp);
775 	if (error)
776 		return (error);
777 	ks = fp->f_data;
778 
779 	mtx_lock(&sem_lock);
780 #ifdef MAC
781 	error = mac_posixsem_check_getvalue(td->td_ucred, fp->f_cred, ks);
782 	if (error) {
783 		mtx_unlock(&sem_lock);
784 		fdrop(fp, td);
785 		return (error);
786 	}
787 #endif
788 	val = ks->ks_value;
789 	vfs_timestamp(&ks->ks_atime);
790 	mtx_unlock(&sem_lock);
791 	fdrop(fp, td);
792 	error = copyout(&val, uap->val, sizeof(val));
793 	return (error);
794 }
795 
796 #ifndef _SYS_SYSPROTO_H_
797 struct ksem_destroy_args {
798 	semid_t		id;
799 };
800 #endif
801 int
802 ksem_destroy(struct thread *td, struct ksem_destroy_args *uap)
803 {
804 	struct file *fp;
805 	struct ksem *ks;
806 	int error;
807 
808 	error = ksem_get(td, uap->id, &fp);
809 	if (error)
810 		return (error);
811 	ks = fp->f_data;
812 	if (!(ks->ks_flags & KS_ANONYMOUS)) {
813 		fdrop(fp, td);
814 		return (EINVAL);
815 	}
816 	mtx_lock(&sem_lock);
817 	if (ks->ks_waiters != 0) {
818 		mtx_unlock(&sem_lock);
819 		error = EBUSY;
820 		goto err;
821 	}
822 	ks->ks_flags |= KS_DEAD;
823 	mtx_unlock(&sem_lock);
824 
825 	error = kern_close(td, uap->id);
826 err:
827 	fdrop(fp, td);
828 	return (error);
829 }
830 
831 #define	SYSCALL_DATA(syscallname)				\
832 static int syscallname##_syscall = SYS_##syscallname;		\
833 static int syscallname##_registered;				\
834 static struct sysent syscallname##_old_sysent;			\
835 MAKE_SYSENT(syscallname);
836 
837 #define	SYSCALL_REGISTER(syscallname) do {				\
838 	error = syscall_register(& syscallname##_syscall,		\
839 	    & syscallname##_sysent, & syscallname##_old_sysent);	\
840 	if (error)							\
841 		return (error);						\
842 	syscallname##_registered = 1;					\
843 } while(0)
844 
845 #define	SYSCALL_DEREGISTER(syscallname) do {				\
846 	if (syscallname##_registered) {					\
847 		syscallname##_registered = 0;				\
848 		syscall_deregister(& syscallname##_syscall,		\
849 		    & syscallname##_old_sysent);			\
850 	}								\
851 } while(0)
852 
853 SYSCALL_DATA(ksem_init);
854 SYSCALL_DATA(ksem_open);
855 SYSCALL_DATA(ksem_unlink);
856 SYSCALL_DATA(ksem_close);
857 SYSCALL_DATA(ksem_post);
858 SYSCALL_DATA(ksem_wait);
859 SYSCALL_DATA(ksem_timedwait);
860 SYSCALL_DATA(ksem_trywait);
861 SYSCALL_DATA(ksem_getvalue);
862 SYSCALL_DATA(ksem_destroy);
863 
864 static int
865 ksem_module_init(void)
866 {
867 	int error;
868 
869 	mtx_init(&sem_lock, "sem", NULL, MTX_DEF);
870 	mtx_init(&ksem_count_lock, "ksem count", NULL, MTX_DEF);
871 	sx_init(&ksem_dict_lock, "ksem dictionary");
872 	ksem_dictionary = hashinit(1024, M_KSEM, &ksem_hash);
873 	p31b_setcfg(CTL_P1003_1B_SEM_NSEMS_MAX, SEM_MAX);
874 	p31b_setcfg(CTL_P1003_1B_SEM_VALUE_MAX, SEM_VALUE_MAX);
875 
876 	SYSCALL_REGISTER(ksem_init);
877 	SYSCALL_REGISTER(ksem_open);
878 	SYSCALL_REGISTER(ksem_unlink);
879 	SYSCALL_REGISTER(ksem_close);
880 	SYSCALL_REGISTER(ksem_post);
881 	SYSCALL_REGISTER(ksem_wait);
882 	SYSCALL_REGISTER(ksem_timedwait);
883 	SYSCALL_REGISTER(ksem_trywait);
884 	SYSCALL_REGISTER(ksem_getvalue);
885 	SYSCALL_REGISTER(ksem_destroy);
886 	return (0);
887 }
888 
889 static void
890 ksem_module_destroy(void)
891 {
892 
893 	SYSCALL_DEREGISTER(ksem_init);
894 	SYSCALL_DEREGISTER(ksem_open);
895 	SYSCALL_DEREGISTER(ksem_unlink);
896 	SYSCALL_DEREGISTER(ksem_close);
897 	SYSCALL_DEREGISTER(ksem_post);
898 	SYSCALL_DEREGISTER(ksem_wait);
899 	SYSCALL_DEREGISTER(ksem_timedwait);
900 	SYSCALL_DEREGISTER(ksem_trywait);
901 	SYSCALL_DEREGISTER(ksem_getvalue);
902 	SYSCALL_DEREGISTER(ksem_destroy);
903 
904 	hashdestroy(ksem_dictionary, M_KSEM, ksem_hash);
905 	sx_destroy(&ksem_dict_lock);
906 	mtx_destroy(&ksem_count_lock);
907 	mtx_destroy(&sem_lock);
908 }
909 
910 static int
911 sem_modload(struct module *module, int cmd, void *arg)
912 {
913         int error = 0;
914 
915         switch (cmd) {
916         case MOD_LOAD:
917 		error = ksem_module_init();
918 		if (error)
919 			ksem_module_destroy();
920                 break;
921 
922         case MOD_UNLOAD:
923 		mtx_lock(&ksem_count_lock);
924 		if (nsems != 0) {
925 			error = EOPNOTSUPP;
926 			mtx_unlock(&ksem_count_lock);
927 			break;
928 		}
929 		ksem_dead = 1;
930 		mtx_unlock(&ksem_count_lock);
931 		ksem_module_destroy();
932                 break;
933 
934         case MOD_SHUTDOWN:
935                 break;
936         default:
937                 error = EINVAL;
938                 break;
939         }
940         return (error);
941 }
942 
943 static moduledata_t sem_mod = {
944         "sem",
945         &sem_modload,
946         NULL
947 };
948 
949 DECLARE_MODULE(sem, sem_mod, SI_SUB_SYSV_SEM, SI_ORDER_FIRST);
950 MODULE_VERSION(sem, 1);
951