xref: /freebsd/sys/kern/uipc_sem.c (revision 884a2a699669ec61e2366e3e358342dbc94be24a)
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_compat.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/stat.h>
57 #include <sys/syscall.h>
58 #include <sys/syscallsubr.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysent.h>
61 #include <sys/sysproto.h>
62 #include <sys/systm.h>
63 #include <sys/sx.h>
64 #include <sys/vnode.h>
65 
66 #include <security/mac/mac_framework.h>
67 
68 FEATURE(p1003_1b_semaphores, "POSIX P1003.1B semaphores support");
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, int compat32);
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_atim = ks->ks_atime;
224 	sb->st_ctim = ks->ks_ctime;
225 	sb->st_mtim = ks->ks_mtime;
226 	sb->st_birthtim = 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 static int
380 ksem_create_copyout_semid(struct thread *td, semid_t *semidp, int fd,
381     int compat32)
382 {
383 	semid_t semid;
384 #ifdef COMPAT_FREEBSD32
385 	int32_t semid32;
386 #endif
387 	void *ptr;
388 	size_t ptrs;
389 
390 #ifdef COMPAT_FREEBSD32
391 	if (compat32) {
392 		semid32 = fd;
393 		ptr = &semid32;
394 		ptrs = sizeof(semid32);
395 	} else {
396 #endif
397 		semid = fd;
398 		ptr = &semid;
399 		ptrs = sizeof(semid);
400 		compat32 = 0; /* silence gcc */
401 #ifdef COMPAT_FREEBSD32
402 	}
403 #endif
404 
405 	return (copyout(ptr, semidp, ptrs));
406 }
407 
408 /* Other helper routines. */
409 static int
410 ksem_create(struct thread *td, const char *name, semid_t *semidp, mode_t mode,
411     unsigned int value, int flags, int compat32)
412 {
413 	struct filedesc *fdp;
414 	struct ksem *ks;
415 	struct file *fp;
416 	char *path;
417 	Fnv32_t fnv;
418 	int error, fd;
419 
420 	if (value > SEM_VALUE_MAX)
421 		return (EINVAL);
422 
423 	fdp = td->td_proc->p_fd;
424 	mode = (mode & ~fdp->fd_cmask) & ACCESSPERMS;
425 	error = falloc(td, &fp, &fd, 0);
426 	if (error) {
427 		if (name == NULL)
428 			error = ENOSPC;
429 		return (error);
430 	}
431 
432 	/*
433 	 * Go ahead and copyout the file descriptor now.  This is a bit
434 	 * premature, but it is a lot easier to handle errors as opposed
435 	 * to later when we've possibly created a new semaphore, etc.
436 	 */
437 	error = ksem_create_copyout_semid(td, semidp, fd, compat32);
438 	if (error) {
439 		fdclose(fdp, fp, fd, td);
440 		fdrop(fp, td);
441 		return (error);
442 	}
443 
444 	if (name == NULL) {
445 		/* Create an anonymous semaphore. */
446 		ks = ksem_alloc(td->td_ucred, mode, value);
447 		if (ks == NULL)
448 			error = ENOSPC;
449 		else
450 			ks->ks_flags |= KS_ANONYMOUS;
451 	} else {
452 		path = malloc(MAXPATHLEN, M_KSEM, M_WAITOK);
453 		error = copyinstr(name, path, MAXPATHLEN, NULL);
454 
455 		/* Require paths to start with a '/' character. */
456 		if (error == 0 && path[0] != '/')
457 			error = EINVAL;
458 		if (error) {
459 			fdclose(fdp, fp, fd, td);
460 			fdrop(fp, td);
461 			free(path, M_KSEM);
462 			return (error);
463 		}
464 
465 		fnv = fnv_32_str(path, FNV1_32_INIT);
466 		sx_xlock(&ksem_dict_lock);
467 		ks = ksem_lookup(path, fnv);
468 		if (ks == NULL) {
469 			/* Object does not exist, create it if requested. */
470 			if (flags & O_CREAT) {
471 				ks = ksem_alloc(td->td_ucred, mode, value);
472 				if (ks == NULL)
473 					error = ENFILE;
474 				else {
475 					ksem_insert(path, fnv, ks);
476 					path = NULL;
477 				}
478 			} else
479 				error = ENOENT;
480 		} else {
481 			/*
482 			 * Object already exists, obtain a new
483 			 * reference if requested and permitted.
484 			 */
485 			if ((flags & (O_CREAT | O_EXCL)) ==
486 			    (O_CREAT | O_EXCL))
487 				error = EEXIST;
488 			else {
489 #ifdef MAC
490 				error = mac_posixsem_check_open(td->td_ucred,
491 				    ks);
492 				if (error == 0)
493 #endif
494 				error = ksem_access(ks, td->td_ucred);
495 			}
496 			if (error == 0)
497 				ksem_hold(ks);
498 #ifdef INVARIANTS
499 			else
500 				ks = NULL;
501 #endif
502 		}
503 		sx_xunlock(&ksem_dict_lock);
504 		if (path)
505 			free(path, M_KSEM);
506 	}
507 
508 	if (error) {
509 		KASSERT(ks == NULL, ("ksem_create error with a ksem"));
510 		fdclose(fdp, fp, fd, td);
511 		fdrop(fp, td);
512 		return (error);
513 	}
514 	KASSERT(ks != NULL, ("ksem_create w/o a ksem"));
515 
516 	finit(fp, FREAD | FWRITE, DTYPE_SEM, ks, &ksem_ops);
517 
518 	FILEDESC_XLOCK(fdp);
519 	if (fdp->fd_ofiles[fd] == fp)
520 		fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
521 	FILEDESC_XUNLOCK(fdp);
522 	fdrop(fp, td);
523 
524 	return (0);
525 }
526 
527 static int
528 ksem_get(struct thread *td, semid_t id, struct file **fpp)
529 {
530 	struct ksem *ks;
531 	struct file *fp;
532 	int error;
533 
534 	error = fget(td, id, &fp);
535 	if (error)
536 		return (EINVAL);
537 	if (fp->f_type != DTYPE_SEM) {
538 		fdrop(fp, td);
539 		return (EINVAL);
540 	}
541 	ks = fp->f_data;
542 	if (ks->ks_flags & KS_DEAD) {
543 		fdrop(fp, td);
544 		return (EINVAL);
545 	}
546 	*fpp = fp;
547 	return (0);
548 }
549 
550 /* System calls. */
551 #ifndef _SYS_SYSPROTO_H_
552 struct ksem_init_args {
553 	unsigned int	value;
554 	semid_t		*idp;
555 };
556 #endif
557 int
558 ksem_init(struct thread *td, struct ksem_init_args *uap)
559 {
560 
561 	return (ksem_create(td, NULL, uap->idp, S_IRWXU | S_IRWXG, uap->value,
562 	    0, 0));
563 }
564 
565 #ifndef _SYS_SYSPROTO_H_
566 struct ksem_open_args {
567 	char		*name;
568 	int		oflag;
569 	mode_t		mode;
570 	unsigned int	value;
571 	semid_t		*idp;
572 };
573 #endif
574 int
575 ksem_open(struct thread *td, struct ksem_open_args *uap)
576 {
577 
578 	DP((">>> ksem_open start, pid=%d\n", (int)td->td_proc->p_pid));
579 
580 	if ((uap->oflag & ~(O_CREAT | O_EXCL)) != 0)
581 		return (EINVAL);
582 	return (ksem_create(td, uap->name, uap->idp, uap->mode, uap->value,
583 	    uap->oflag, 0));
584 }
585 
586 #ifndef _SYS_SYSPROTO_H_
587 struct ksem_unlink_args {
588 	char		*name;
589 };
590 #endif
591 int
592 ksem_unlink(struct thread *td, struct ksem_unlink_args *uap)
593 {
594 	char *path;
595 	Fnv32_t fnv;
596 	int error;
597 
598 	path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
599 	error = copyinstr(uap->name, path, MAXPATHLEN, NULL);
600 	if (error) {
601 		free(path, M_TEMP);
602 		return (error);
603 	}
604 
605 	fnv = fnv_32_str(path, FNV1_32_INIT);
606 	sx_xlock(&ksem_dict_lock);
607 	error = ksem_remove(path, fnv, td->td_ucred);
608 	sx_xunlock(&ksem_dict_lock);
609 	free(path, M_TEMP);
610 
611 	return (error);
612 }
613 
614 #ifndef _SYS_SYSPROTO_H_
615 struct ksem_close_args {
616 	semid_t		id;
617 };
618 #endif
619 int
620 ksem_close(struct thread *td, struct ksem_close_args *uap)
621 {
622 	struct ksem *ks;
623 	struct file *fp;
624 	int error;
625 
626 	error = ksem_get(td, uap->id, &fp);
627 	if (error)
628 		return (error);
629 	ks = fp->f_data;
630 	if (ks->ks_flags & KS_ANONYMOUS) {
631 		fdrop(fp, td);
632 		return (EINVAL);
633 	}
634 	error = kern_close(td, uap->id);
635 	fdrop(fp, td);
636 	return (error);
637 }
638 
639 #ifndef _SYS_SYSPROTO_H_
640 struct ksem_post_args {
641 	semid_t	id;
642 };
643 #endif
644 int
645 ksem_post(struct thread *td, struct ksem_post_args *uap)
646 {
647 	struct file *fp;
648 	struct ksem *ks;
649 	int error;
650 
651 	error = ksem_get(td, uap->id, &fp);
652 	if (error)
653 		return (error);
654 	ks = fp->f_data;
655 
656 	mtx_lock(&sem_lock);
657 #ifdef MAC
658 	error = mac_posixsem_check_post(td->td_ucred, fp->f_cred, ks);
659 	if (error)
660 		goto err;
661 #endif
662 	if (ks->ks_value == SEM_VALUE_MAX) {
663 		error = EOVERFLOW;
664 		goto err;
665 	}
666 	++ks->ks_value;
667 	if (ks->ks_waiters > 0)
668 		cv_signal(&ks->ks_cv);
669 	error = 0;
670 	vfs_timestamp(&ks->ks_ctime);
671 err:
672 	mtx_unlock(&sem_lock);
673 	fdrop(fp, td);
674 	return (error);
675 }
676 
677 #ifndef _SYS_SYSPROTO_H_
678 struct ksem_wait_args {
679 	semid_t		id;
680 };
681 #endif
682 int
683 ksem_wait(struct thread *td, struct ksem_wait_args *uap)
684 {
685 
686 	return (kern_sem_wait(td, uap->id, 0, NULL));
687 }
688 
689 #ifndef _SYS_SYSPROTO_H_
690 struct ksem_timedwait_args {
691 	semid_t		id;
692 	const struct timespec *abstime;
693 };
694 #endif
695 int
696 ksem_timedwait(struct thread *td, struct ksem_timedwait_args *uap)
697 {
698 	struct timespec abstime;
699 	struct timespec *ts;
700 	int error;
701 
702 	/*
703 	 * We allow a null timespec (wait forever).
704 	 */
705 	if (uap->abstime == NULL)
706 		ts = NULL;
707 	else {
708 		error = copyin(uap->abstime, &abstime, sizeof(abstime));
709 		if (error != 0)
710 			return (error);
711 		if (abstime.tv_nsec >= 1000000000 || abstime.tv_nsec < 0)
712 			return (EINVAL);
713 		ts = &abstime;
714 	}
715 	return (kern_sem_wait(td, uap->id, 0, ts));
716 }
717 
718 #ifndef _SYS_SYSPROTO_H_
719 struct ksem_trywait_args {
720 	semid_t		id;
721 };
722 #endif
723 int
724 ksem_trywait(struct thread *td, struct ksem_trywait_args *uap)
725 {
726 
727 	return (kern_sem_wait(td, uap->id, 1, NULL));
728 }
729 
730 static int
731 kern_sem_wait(struct thread *td, semid_t id, int tryflag,
732     struct timespec *abstime)
733 {
734 	struct timespec ts1, ts2;
735 	struct timeval tv;
736 	struct file *fp;
737 	struct ksem *ks;
738 	int error;
739 
740 	DP((">>> kern_sem_wait entered! pid=%d\n", (int)td->td_proc->p_pid));
741 	error = ksem_get(td, id, &fp);
742 	if (error)
743 		return (error);
744 	ks = fp->f_data;
745 	mtx_lock(&sem_lock);
746 	DP((">>> kern_sem_wait critical section entered! pid=%d\n",
747 	    (int)td->td_proc->p_pid));
748 #ifdef MAC
749 	error = mac_posixsem_check_wait(td->td_ucred, fp->f_cred, ks);
750 	if (error) {
751 		DP(("kern_sem_wait mac failed\n"));
752 		goto err;
753 	}
754 #endif
755 	DP(("kern_sem_wait value = %d, tryflag %d\n", ks->ks_value, tryflag));
756 	vfs_timestamp(&ks->ks_atime);
757 	while (ks->ks_value == 0) {
758 		ks->ks_waiters++;
759 		if (tryflag != 0)
760 			error = EAGAIN;
761 		else if (abstime == NULL)
762 			error = cv_wait_sig(&ks->ks_cv, &sem_lock);
763 		else {
764 			for (;;) {
765 				ts1 = *abstime;
766 				getnanotime(&ts2);
767 				timespecsub(&ts1, &ts2);
768 				TIMESPEC_TO_TIMEVAL(&tv, &ts1);
769 				if (tv.tv_sec < 0) {
770 					error = ETIMEDOUT;
771 					break;
772 				}
773 				error = cv_timedwait_sig(&ks->ks_cv,
774 				    &sem_lock, tvtohz(&tv));
775 				if (error != EWOULDBLOCK)
776 					break;
777 			}
778 		}
779 		ks->ks_waiters--;
780 		if (error)
781 			goto err;
782 	}
783 	ks->ks_value--;
784 	DP(("kern_sem_wait value post-decrement = %d\n", ks->ks_value));
785 	error = 0;
786 err:
787 	mtx_unlock(&sem_lock);
788 	fdrop(fp, td);
789 	DP(("<<< kern_sem_wait leaving, pid=%d, error = %d\n",
790 	    (int)td->td_proc->p_pid, error));
791 	return (error);
792 }
793 
794 #ifndef _SYS_SYSPROTO_H_
795 struct ksem_getvalue_args {
796 	semid_t		id;
797 	int		*val;
798 };
799 #endif
800 int
801 ksem_getvalue(struct thread *td, struct ksem_getvalue_args *uap)
802 {
803 	struct file *fp;
804 	struct ksem *ks;
805 	int error, val;
806 
807 	error = ksem_get(td, uap->id, &fp);
808 	if (error)
809 		return (error);
810 	ks = fp->f_data;
811 
812 	mtx_lock(&sem_lock);
813 #ifdef MAC
814 	error = mac_posixsem_check_getvalue(td->td_ucred, fp->f_cred, ks);
815 	if (error) {
816 		mtx_unlock(&sem_lock);
817 		fdrop(fp, td);
818 		return (error);
819 	}
820 #endif
821 	val = ks->ks_value;
822 	vfs_timestamp(&ks->ks_atime);
823 	mtx_unlock(&sem_lock);
824 	fdrop(fp, td);
825 	error = copyout(&val, uap->val, sizeof(val));
826 	return (error);
827 }
828 
829 #ifndef _SYS_SYSPROTO_H_
830 struct ksem_destroy_args {
831 	semid_t		id;
832 };
833 #endif
834 int
835 ksem_destroy(struct thread *td, struct ksem_destroy_args *uap)
836 {
837 	struct file *fp;
838 	struct ksem *ks;
839 	int error;
840 
841 	error = ksem_get(td, uap->id, &fp);
842 	if (error)
843 		return (error);
844 	ks = fp->f_data;
845 	if (!(ks->ks_flags & KS_ANONYMOUS)) {
846 		fdrop(fp, td);
847 		return (EINVAL);
848 	}
849 	mtx_lock(&sem_lock);
850 	if (ks->ks_waiters != 0) {
851 		mtx_unlock(&sem_lock);
852 		error = EBUSY;
853 		goto err;
854 	}
855 	ks->ks_flags |= KS_DEAD;
856 	mtx_unlock(&sem_lock);
857 
858 	error = kern_close(td, uap->id);
859 err:
860 	fdrop(fp, td);
861 	return (error);
862 }
863 
864 static struct syscall_helper_data ksem_syscalls[] = {
865 	SYSCALL_INIT_HELPER(ksem_init),
866 	SYSCALL_INIT_HELPER(ksem_open),
867 	SYSCALL_INIT_HELPER(ksem_unlink),
868 	SYSCALL_INIT_HELPER(ksem_close),
869 	SYSCALL_INIT_HELPER(ksem_post),
870 	SYSCALL_INIT_HELPER(ksem_wait),
871 	SYSCALL_INIT_HELPER(ksem_timedwait),
872 	SYSCALL_INIT_HELPER(ksem_trywait),
873 	SYSCALL_INIT_HELPER(ksem_getvalue),
874 	SYSCALL_INIT_HELPER(ksem_destroy),
875 	SYSCALL_INIT_LAST
876 };
877 
878 #ifdef COMPAT_FREEBSD32
879 #include <compat/freebsd32/freebsd32.h>
880 #include <compat/freebsd32/freebsd32_proto.h>
881 #include <compat/freebsd32/freebsd32_signal.h>
882 #include <compat/freebsd32/freebsd32_syscall.h>
883 #include <compat/freebsd32/freebsd32_util.h>
884 
885 int
886 freebsd32_ksem_init(struct thread *td, struct freebsd32_ksem_init_args *uap)
887 {
888 
889 	return (ksem_create(td, NULL, uap->idp, S_IRWXU | S_IRWXG, uap->value,
890 	    0, 1));
891 }
892 
893 int
894 freebsd32_ksem_open(struct thread *td, struct freebsd32_ksem_open_args *uap)
895 {
896 
897 	if ((uap->oflag & ~(O_CREAT | O_EXCL)) != 0)
898 		return (EINVAL);
899 	return (ksem_create(td, uap->name, uap->idp, uap->mode, uap->value,
900 	    uap->oflag, 1));
901 }
902 
903 int
904 freebsd32_ksem_timedwait(struct thread *td,
905     struct freebsd32_ksem_timedwait_args *uap)
906 {
907 	struct timespec32 abstime32;
908 	struct timespec *ts, abstime;
909 	int error;
910 
911 	/*
912 	 * We allow a null timespec (wait forever).
913 	 */
914 	if (uap->abstime == NULL)
915 		ts = NULL;
916 	else {
917 		error = copyin(uap->abstime, &abstime32, sizeof(abstime32));
918 		if (error != 0)
919 			return (error);
920 		CP(abstime32, abstime, tv_sec);
921 		CP(abstime32, abstime, tv_nsec);
922 		if (abstime.tv_nsec >= 1000000000 || abstime.tv_nsec < 0)
923 			return (EINVAL);
924 		ts = &abstime;
925 	}
926 	return (kern_sem_wait(td, uap->id, 0, ts));
927 }
928 
929 static struct syscall_helper_data ksem32_syscalls[] = {
930 	SYSCALL32_INIT_HELPER(freebsd32_ksem_init),
931 	SYSCALL32_INIT_HELPER(freebsd32_ksem_open),
932 	SYSCALL32_INIT_HELPER(ksem_unlink),
933 	SYSCALL32_INIT_HELPER(ksem_close),
934 	SYSCALL32_INIT_HELPER(ksem_post),
935 	SYSCALL32_INIT_HELPER(ksem_wait),
936 	SYSCALL32_INIT_HELPER(freebsd32_ksem_timedwait),
937 	SYSCALL32_INIT_HELPER(ksem_trywait),
938 	SYSCALL32_INIT_HELPER(ksem_getvalue),
939 	SYSCALL32_INIT_HELPER(ksem_destroy),
940 	SYSCALL_INIT_LAST
941 };
942 #endif
943 
944 static int
945 ksem_module_init(void)
946 {
947 	int error;
948 
949 	mtx_init(&sem_lock, "sem", NULL, MTX_DEF);
950 	mtx_init(&ksem_count_lock, "ksem count", NULL, MTX_DEF);
951 	sx_init(&ksem_dict_lock, "ksem dictionary");
952 	ksem_dictionary = hashinit(1024, M_KSEM, &ksem_hash);
953 	p31b_setcfg(CTL_P1003_1B_SEMAPHORES, 200112L);
954 	p31b_setcfg(CTL_P1003_1B_SEM_NSEMS_MAX, SEM_MAX);
955 	p31b_setcfg(CTL_P1003_1B_SEM_VALUE_MAX, SEM_VALUE_MAX);
956 
957 	error = syscall_helper_register(ksem_syscalls);
958 	if (error)
959 		return (error);
960 #ifdef COMPAT_FREEBSD32
961 	error = syscall32_helper_register(ksem32_syscalls);
962 	if (error)
963 		return (error);
964 #endif
965 	return (0);
966 }
967 
968 static void
969 ksem_module_destroy(void)
970 {
971 
972 #ifdef COMPAT_FREEBSD32
973 	syscall32_helper_unregister(ksem32_syscalls);
974 #endif
975 	syscall_helper_unregister(ksem_syscalls);
976 
977 	p31b_setcfg(CTL_P1003_1B_SEMAPHORES, 0);
978 	hashdestroy(ksem_dictionary, M_KSEM, ksem_hash);
979 	sx_destroy(&ksem_dict_lock);
980 	mtx_destroy(&ksem_count_lock);
981 	mtx_destroy(&sem_lock);
982 	p31b_unsetcfg(CTL_P1003_1B_SEM_VALUE_MAX);
983 	p31b_unsetcfg(CTL_P1003_1B_SEM_NSEMS_MAX);
984 }
985 
986 static int
987 sem_modload(struct module *module, int cmd, void *arg)
988 {
989         int error = 0;
990 
991         switch (cmd) {
992         case MOD_LOAD:
993 		error = ksem_module_init();
994 		if (error)
995 			ksem_module_destroy();
996                 break;
997 
998         case MOD_UNLOAD:
999 		mtx_lock(&ksem_count_lock);
1000 		if (nsems != 0) {
1001 			error = EOPNOTSUPP;
1002 			mtx_unlock(&ksem_count_lock);
1003 			break;
1004 		}
1005 		ksem_dead = 1;
1006 		mtx_unlock(&ksem_count_lock);
1007 		ksem_module_destroy();
1008                 break;
1009 
1010         case MOD_SHUTDOWN:
1011                 break;
1012         default:
1013                 error = EINVAL;
1014                 break;
1015         }
1016         return (error);
1017 }
1018 
1019 static moduledata_t sem_mod = {
1020         "sem",
1021         &sem_modload,
1022         NULL
1023 };
1024 
1025 DECLARE_MODULE(sem, sem_mod, SI_SUB_SYSV_SEM, SI_ORDER_FIRST);
1026 MODULE_VERSION(sem, 1);
1027