xref: /freebsd/sys/kern/uipc_sem.c (revision 195ebc7e9e4b129de810833791a19dfb4349d6a9)
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 	DP((">>> ksem_open start, pid=%d\n", (int)td->td_proc->p_pid));
552 
553 	if ((uap->oflag & ~(O_CREAT | O_EXCL)) != 0)
554 		return (EINVAL);
555 	return (ksem_create(td, uap->name, uap->idp, uap->mode, uap->value,
556 	    uap->oflag));
557 }
558 
559 #ifndef _SYS_SYSPROTO_H_
560 struct ksem_unlink_args {
561 	char		*name;
562 };
563 #endif
564 int
565 ksem_unlink(struct thread *td, struct ksem_unlink_args *uap)
566 {
567 	char *path;
568 	Fnv32_t fnv;
569 	int error;
570 
571 	path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
572 	error = copyinstr(uap->name, path, MAXPATHLEN, NULL);
573 	if (error) {
574 		free(path, M_TEMP);
575 		return (error);
576 	}
577 
578 	fnv = fnv_32_str(path, FNV1_32_INIT);
579 	sx_xlock(&ksem_dict_lock);
580 	error = ksem_remove(path, fnv, td->td_ucred);
581 	sx_xunlock(&ksem_dict_lock);
582 	free(path, M_TEMP);
583 
584 	return (error);
585 }
586 
587 #ifndef _SYS_SYSPROTO_H_
588 struct ksem_close_args {
589 	semid_t		id;
590 };
591 #endif
592 int
593 ksem_close(struct thread *td, struct ksem_close_args *uap)
594 {
595 	struct ksem *ks;
596 	struct file *fp;
597 	int error;
598 
599 	error = ksem_get(td, uap->id, &fp);
600 	if (error)
601 		return (error);
602 	ks = fp->f_data;
603 	if (ks->ks_flags & KS_ANONYMOUS) {
604 		fdrop(fp, td);
605 		return (EINVAL);
606 	}
607 	error = kern_close(td, uap->id);
608 	fdrop(fp, td);
609 	return (error);
610 }
611 
612 #ifndef _SYS_SYSPROTO_H_
613 struct ksem_post_args {
614 	semid_t	id;
615 };
616 #endif
617 int
618 ksem_post(struct thread *td, struct ksem_post_args *uap)
619 {
620 	struct file *fp;
621 	struct ksem *ks;
622 	int error;
623 
624 	error = ksem_get(td, uap->id, &fp);
625 	if (error)
626 		return (error);
627 	ks = fp->f_data;
628 
629 	mtx_lock(&sem_lock);
630 #ifdef MAC
631 	error = mac_posixsem_check_post(td->td_ucred, fp->f_cred, ks);
632 	if (error)
633 		goto err;
634 #endif
635 	if (ks->ks_value == SEM_VALUE_MAX) {
636 		error = EOVERFLOW;
637 		goto err;
638 	}
639 	++ks->ks_value;
640 	if (ks->ks_waiters > 0)
641 		cv_signal(&ks->ks_cv);
642 	error = 0;
643 	vfs_timestamp(&ks->ks_ctime);
644 err:
645 	mtx_unlock(&sem_lock);
646 	fdrop(fp, td);
647 	return (error);
648 }
649 
650 #ifndef _SYS_SYSPROTO_H_
651 struct ksem_wait_args {
652 	semid_t		id;
653 };
654 #endif
655 int
656 ksem_wait(struct thread *td, struct ksem_wait_args *uap)
657 {
658 
659 	return (kern_sem_wait(td, uap->id, 0, NULL));
660 }
661 
662 #ifndef _SYS_SYSPROTO_H_
663 struct ksem_timedwait_args {
664 	semid_t		id;
665 	const struct timespec *abstime;
666 };
667 #endif
668 int
669 ksem_timedwait(struct thread *td, struct ksem_timedwait_args *uap)
670 {
671 	struct timespec abstime;
672 	struct timespec *ts;
673 	int error;
674 
675 	/*
676 	 * We allow a null timespec (wait forever).
677 	 */
678 	if (uap->abstime == NULL)
679 		ts = NULL;
680 	else {
681 		error = copyin(uap->abstime, &abstime, sizeof(abstime));
682 		if (error != 0)
683 			return (error);
684 		if (abstime.tv_nsec >= 1000000000 || abstime.tv_nsec < 0)
685 			return (EINVAL);
686 		ts = &abstime;
687 	}
688 	return (kern_sem_wait(td, uap->id, 0, ts));
689 }
690 
691 #ifndef _SYS_SYSPROTO_H_
692 struct ksem_trywait_args {
693 	semid_t		id;
694 };
695 #endif
696 int
697 ksem_trywait(struct thread *td, struct ksem_trywait_args *uap)
698 {
699 
700 	return (kern_sem_wait(td, uap->id, 1, NULL));
701 }
702 
703 static int
704 kern_sem_wait(struct thread *td, semid_t id, int tryflag,
705     struct timespec *abstime)
706 {
707 	struct timespec ts1, ts2;
708 	struct timeval tv;
709 	struct file *fp;
710 	struct ksem *ks;
711 	int error;
712 
713 	DP((">>> kern_sem_wait entered! pid=%d\n", (int)td->td_proc->p_pid));
714 	error = ksem_get(td, id, &fp);
715 	if (error)
716 		return (error);
717 	ks = fp->f_data;
718 	mtx_lock(&sem_lock);
719 	DP((">>> kern_sem_wait critical section entered! pid=%d\n",
720 	    (int)td->td_proc->p_pid));
721 #ifdef MAC
722 	error = mac_posixsem_check_wait(td->td_ucred, fp->f_cred, ks);
723 	if (error) {
724 		DP(("kern_sem_wait mac failed\n"));
725 		goto err;
726 	}
727 #endif
728 	DP(("kern_sem_wait value = %d, tryflag %d\n", ks->ks_value, tryflag));
729 	vfs_timestamp(&ks->ks_atime);
730 	while (ks->ks_value == 0) {
731 		ks->ks_waiters++;
732 		if (tryflag != 0)
733 			error = EAGAIN;
734 		else if (abstime == NULL)
735 			error = cv_wait_sig(&ks->ks_cv, &sem_lock);
736 		else {
737 			for (;;) {
738 				ts1 = *abstime;
739 				getnanotime(&ts2);
740 				timespecsub(&ts1, &ts2);
741 				TIMESPEC_TO_TIMEVAL(&tv, &ts1);
742 				if (tv.tv_sec < 0) {
743 					error = ETIMEDOUT;
744 					break;
745 				}
746 				error = cv_timedwait_sig(&ks->ks_cv,
747 				    &sem_lock, tvtohz(&tv));
748 				if (error != EWOULDBLOCK)
749 					break;
750 			}
751 		}
752 		ks->ks_waiters--;
753 		if (error)
754 			goto err;
755 	}
756 	ks->ks_value--;
757 	DP(("kern_sem_wait value post-decrement = %d\n", ks->ks_value));
758 	error = 0;
759 err:
760 	mtx_unlock(&sem_lock);
761 	fdrop(fp, td);
762 	DP(("<<< kern_sem_wait leaving, pid=%d, error = %d\n",
763 	    (int)td->td_proc->p_pid, error));
764 	return (error);
765 }
766 
767 #ifndef _SYS_SYSPROTO_H_
768 struct ksem_getvalue_args {
769 	semid_t		id;
770 	int		*val;
771 };
772 #endif
773 int
774 ksem_getvalue(struct thread *td, struct ksem_getvalue_args *uap)
775 {
776 	struct file *fp;
777 	struct ksem *ks;
778 	int error, val;
779 
780 	error = ksem_get(td, uap->id, &fp);
781 	if (error)
782 		return (error);
783 	ks = fp->f_data;
784 
785 	mtx_lock(&sem_lock);
786 #ifdef MAC
787 	error = mac_posixsem_check_getvalue(td->td_ucred, fp->f_cred, ks);
788 	if (error) {
789 		mtx_unlock(&sem_lock);
790 		fdrop(fp, td);
791 		return (error);
792 	}
793 #endif
794 	val = ks->ks_value;
795 	vfs_timestamp(&ks->ks_atime);
796 	mtx_unlock(&sem_lock);
797 	fdrop(fp, td);
798 	error = copyout(&val, uap->val, sizeof(val));
799 	return (error);
800 }
801 
802 #ifndef _SYS_SYSPROTO_H_
803 struct ksem_destroy_args {
804 	semid_t		id;
805 };
806 #endif
807 int
808 ksem_destroy(struct thread *td, struct ksem_destroy_args *uap)
809 {
810 	struct file *fp;
811 	struct ksem *ks;
812 	int error;
813 
814 	error = ksem_get(td, uap->id, &fp);
815 	if (error)
816 		return (error);
817 	ks = fp->f_data;
818 	if (!(ks->ks_flags & KS_ANONYMOUS)) {
819 		fdrop(fp, td);
820 		return (EINVAL);
821 	}
822 	mtx_lock(&sem_lock);
823 	if (ks->ks_waiters != 0) {
824 		mtx_unlock(&sem_lock);
825 		error = EBUSY;
826 		goto err;
827 	}
828 	ks->ks_flags |= KS_DEAD;
829 	mtx_unlock(&sem_lock);
830 
831 	error = kern_close(td, uap->id);
832 err:
833 	fdrop(fp, td);
834 	return (error);
835 }
836 
837 #define	SYSCALL_DATA(syscallname)				\
838 static int syscallname##_syscall = SYS_##syscallname;		\
839 static int syscallname##_registered;				\
840 static struct sysent syscallname##_old_sysent;			\
841 MAKE_SYSENT(syscallname);
842 
843 #define	SYSCALL_REGISTER(syscallname) do {				\
844 	error = syscall_register(& syscallname##_syscall,		\
845 	    & syscallname##_sysent, & syscallname##_old_sysent);	\
846 	if (error)							\
847 		return (error);						\
848 	syscallname##_registered = 1;					\
849 } while(0)
850 
851 #define	SYSCALL_DEREGISTER(syscallname) do {				\
852 	if (syscallname##_registered) {					\
853 		syscallname##_registered = 0;				\
854 		syscall_deregister(& syscallname##_syscall,		\
855 		    & syscallname##_old_sysent);			\
856 	}								\
857 } while(0)
858 
859 SYSCALL_DATA(ksem_init);
860 SYSCALL_DATA(ksem_open);
861 SYSCALL_DATA(ksem_unlink);
862 SYSCALL_DATA(ksem_close);
863 SYSCALL_DATA(ksem_post);
864 SYSCALL_DATA(ksem_wait);
865 SYSCALL_DATA(ksem_timedwait);
866 SYSCALL_DATA(ksem_trywait);
867 SYSCALL_DATA(ksem_getvalue);
868 SYSCALL_DATA(ksem_destroy);
869 
870 static int
871 ksem_module_init(void)
872 {
873 	int error;
874 
875 	mtx_init(&sem_lock, "sem", NULL, MTX_DEF);
876 	mtx_init(&ksem_count_lock, "ksem count", NULL, MTX_DEF);
877 	sx_init(&ksem_dict_lock, "ksem dictionary");
878 	ksem_dictionary = hashinit(1024, M_KSEM, &ksem_hash);
879 	p31b_setcfg(CTL_P1003_1B_SEM_NSEMS_MAX, SEM_MAX);
880 	p31b_setcfg(CTL_P1003_1B_SEM_VALUE_MAX, SEM_VALUE_MAX);
881 
882 	SYSCALL_REGISTER(ksem_init);
883 	SYSCALL_REGISTER(ksem_open);
884 	SYSCALL_REGISTER(ksem_unlink);
885 	SYSCALL_REGISTER(ksem_close);
886 	SYSCALL_REGISTER(ksem_post);
887 	SYSCALL_REGISTER(ksem_wait);
888 	SYSCALL_REGISTER(ksem_timedwait);
889 	SYSCALL_REGISTER(ksem_trywait);
890 	SYSCALL_REGISTER(ksem_getvalue);
891 	SYSCALL_REGISTER(ksem_destroy);
892 	return (0);
893 }
894 
895 static void
896 ksem_module_destroy(void)
897 {
898 
899 	SYSCALL_DEREGISTER(ksem_init);
900 	SYSCALL_DEREGISTER(ksem_open);
901 	SYSCALL_DEREGISTER(ksem_unlink);
902 	SYSCALL_DEREGISTER(ksem_close);
903 	SYSCALL_DEREGISTER(ksem_post);
904 	SYSCALL_DEREGISTER(ksem_wait);
905 	SYSCALL_DEREGISTER(ksem_timedwait);
906 	SYSCALL_DEREGISTER(ksem_trywait);
907 	SYSCALL_DEREGISTER(ksem_getvalue);
908 	SYSCALL_DEREGISTER(ksem_destroy);
909 
910 	hashdestroy(ksem_dictionary, M_KSEM, ksem_hash);
911 	sx_destroy(&ksem_dict_lock);
912 	mtx_destroy(&ksem_count_lock);
913 	mtx_destroy(&sem_lock);
914 }
915 
916 static int
917 sem_modload(struct module *module, int cmd, void *arg)
918 {
919         int error = 0;
920 
921         switch (cmd) {
922         case MOD_LOAD:
923 		error = ksem_module_init();
924 		if (error)
925 			ksem_module_destroy();
926                 break;
927 
928         case MOD_UNLOAD:
929 		mtx_lock(&ksem_count_lock);
930 		if (nsems != 0) {
931 			error = EOPNOTSUPP;
932 			mtx_unlock(&ksem_count_lock);
933 			break;
934 		}
935 		ksem_dead = 1;
936 		mtx_unlock(&ksem_count_lock);
937 		ksem_module_destroy();
938                 break;
939 
940         case MOD_SHUTDOWN:
941                 break;
942         default:
943                 error = EINVAL;
944                 break;
945         }
946         return (error);
947 }
948 
949 static moduledata_t sem_mod = {
950         "sem",
951         &sem_modload,
952         NULL
953 };
954 
955 DECLARE_MODULE(sem, sem_mod, SI_SUB_SYSV_SEM, SI_ORDER_FIRST);
956 MODULE_VERSION(sem, 1);
957