xref: /freebsd/sys/kern/uipc_sem.c (revision c243e4902be8df1e643c76b5f18b68bb77cc5268)
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/capability.h>
42 #include <sys/condvar.h>
43 #include <sys/fcntl.h>
44 #include <sys/file.h>
45 #include <sys/filedesc.h>
46 #include <sys/fnv_hash.h>
47 #include <sys/kernel.h>
48 #include <sys/ksem.h>
49 #include <sys/lock.h>
50 #include <sys/malloc.h>
51 #include <sys/module.h>
52 #include <sys/mutex.h>
53 #include <sys/priv.h>
54 #include <sys/proc.h>
55 #include <sys/posix4.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 FEATURE(p1003_1b_semaphores, "POSIX P1003.1B semaphores support");
70 /*
71  * TODO
72  *
73  * - Resource limits?
74  * - Update fstat(1)
75  * - Replace global sem_lock with mtx_pool locks?
76  * - Add a MAC check_create() hook for creating new named semaphores.
77  */
78 
79 #ifndef SEM_MAX
80 #define	SEM_MAX	30
81 #endif
82 
83 #ifdef SEM_DEBUG
84 #define	DP(x)	printf x
85 #else
86 #define	DP(x)
87 #endif
88 
89 struct ksem_mapping {
90 	char		*km_path;
91 	Fnv32_t		km_fnv;
92 	struct ksem	*km_ksem;
93 	LIST_ENTRY(ksem_mapping) km_link;
94 };
95 
96 static MALLOC_DEFINE(M_KSEM, "ksem", "semaphore file descriptor");
97 static LIST_HEAD(, ksem_mapping) *ksem_dictionary;
98 static struct sx ksem_dict_lock;
99 static struct mtx ksem_count_lock;
100 static struct mtx sem_lock;
101 static u_long ksem_hash;
102 static int ksem_dead;
103 
104 #define	KSEM_HASH(fnv)	(&ksem_dictionary[(fnv) & ksem_hash])
105 
106 static int nsems = 0;
107 SYSCTL_DECL(_p1003_1b);
108 SYSCTL_INT(_p1003_1b, OID_AUTO, nsems, CTLFLAG_RD, &nsems, 0,
109     "Number of active kernel POSIX semaphores");
110 
111 static int	kern_sem_wait(struct thread *td, semid_t id, int tryflag,
112 		    struct timespec *abstime);
113 static int	ksem_access(struct ksem *ks, struct ucred *ucred);
114 static struct ksem *ksem_alloc(struct ucred *ucred, mode_t mode,
115 		    unsigned int value);
116 static int	ksem_create(struct thread *td, const char *path,
117 		    semid_t *semidp, mode_t mode, unsigned int value,
118 		    int flags, int compat32);
119 static void	ksem_drop(struct ksem *ks);
120 static int	ksem_get(struct thread *td, semid_t id, cap_rights_t rights,
121     struct file **fpp);
122 static struct ksem *ksem_hold(struct ksem *ks);
123 static void	ksem_insert(char *path, Fnv32_t fnv, struct ksem *ks);
124 static struct ksem *ksem_lookup(char *path, Fnv32_t fnv);
125 static void	ksem_module_destroy(void);
126 static int	ksem_module_init(void);
127 static int	ksem_remove(char *path, Fnv32_t fnv, struct ucred *ucred);
128 static int	sem_modload(struct module *module, int cmd, void *arg);
129 
130 static fo_rdwr_t	ksem_read;
131 static fo_rdwr_t	ksem_write;
132 static fo_truncate_t	ksem_truncate;
133 static fo_ioctl_t	ksem_ioctl;
134 static fo_poll_t	ksem_poll;
135 static fo_kqfilter_t	ksem_kqfilter;
136 static fo_stat_t	ksem_stat;
137 static fo_close_t	ksem_closef;
138 static fo_chmod_t	ksem_chmod;
139 static fo_chown_t	ksem_chown;
140 
141 /* File descriptor operations. */
142 static struct fileops ksem_ops = {
143 	.fo_read = ksem_read,
144 	.fo_write = ksem_write,
145 	.fo_truncate = ksem_truncate,
146 	.fo_ioctl = ksem_ioctl,
147 	.fo_poll = ksem_poll,
148 	.fo_kqfilter = ksem_kqfilter,
149 	.fo_stat = ksem_stat,
150 	.fo_close = ksem_closef,
151 	.fo_chmod = ksem_chmod,
152 	.fo_chown = ksem_chown,
153 	.fo_flags = DFLAG_PASSABLE
154 };
155 
156 FEATURE(posix_sem, "POSIX semaphores");
157 
158 static int
159 ksem_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
160     int flags, struct thread *td)
161 {
162 
163 	return (EOPNOTSUPP);
164 }
165 
166 static int
167 ksem_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
168     int flags, struct thread *td)
169 {
170 
171 	return (EOPNOTSUPP);
172 }
173 
174 static int
175 ksem_truncate(struct file *fp, off_t length, struct ucred *active_cred,
176     struct thread *td)
177 {
178 
179 	return (EINVAL);
180 }
181 
182 static int
183 ksem_ioctl(struct file *fp, u_long com, void *data,
184     struct ucred *active_cred, struct thread *td)
185 {
186 
187 	return (EOPNOTSUPP);
188 }
189 
190 static int
191 ksem_poll(struct file *fp, int events, struct ucred *active_cred,
192     struct thread *td)
193 {
194 
195 	return (EOPNOTSUPP);
196 }
197 
198 static int
199 ksem_kqfilter(struct file *fp, struct knote *kn)
200 {
201 
202 	return (EOPNOTSUPP);
203 }
204 
205 static int
206 ksem_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
207     struct thread *td)
208 {
209 	struct ksem *ks;
210 #ifdef MAC
211 	int error;
212 #endif
213 
214 	ks = fp->f_data;
215 
216 #ifdef MAC
217 	error = mac_posixsem_check_stat(active_cred, fp->f_cred, ks);
218 	if (error)
219 		return (error);
220 #endif
221 
222 	/*
223 	 * Attempt to return sanish values for fstat() on a semaphore
224 	 * file descriptor.
225 	 */
226 	bzero(sb, sizeof(*sb));
227 
228 	mtx_lock(&sem_lock);
229 	sb->st_atim = ks->ks_atime;
230 	sb->st_ctim = ks->ks_ctime;
231 	sb->st_mtim = ks->ks_mtime;
232 	sb->st_birthtim = ks->ks_birthtime;
233 	sb->st_uid = ks->ks_uid;
234 	sb->st_gid = ks->ks_gid;
235 	sb->st_mode = S_IFREG | ks->ks_mode;		/* XXX */
236 	mtx_unlock(&sem_lock);
237 
238 	return (0);
239 }
240 
241 static int
242 ksem_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
243     struct thread *td)
244 {
245 	struct ksem *ks;
246 	int error;
247 
248 	error = 0;
249 	ks = fp->f_data;
250 	mtx_lock(&sem_lock);
251 #ifdef MAC
252 	error = mac_posixsem_check_setmode(active_cred, ks, mode);
253 	if (error != 0)
254 		goto out;
255 #endif
256 	error = vaccess(VREG, ks->ks_mode, ks->ks_uid, ks->ks_gid, VADMIN,
257 	    active_cred, NULL);
258 	if (error != 0)
259 		goto out;
260 	ks->ks_mode = mode & ACCESSPERMS;
261 out:
262 	mtx_unlock(&sem_lock);
263 	return (error);
264 }
265 
266 static int
267 ksem_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
268     struct thread *td)
269 {
270 	struct ksem *ks;
271 	int error;
272 
273 	error = 0;
274 	ks = fp->f_data;
275 	mtx_lock(&sem_lock);
276 #ifdef MAC
277 	error = mac_posixsem_check_setowner(active_cred, ks, uid, gid);
278 	if (error != 0)
279 		goto out;
280 #endif
281 	if (uid == (uid_t)-1)
282 		uid = ks->ks_uid;
283 	if (gid == (gid_t)-1)
284                  gid = ks->ks_gid;
285 	if (((uid != ks->ks_uid && uid != active_cred->cr_uid) ||
286 	    (gid != ks->ks_gid && !groupmember(gid, active_cred))) &&
287 	    (error = priv_check_cred(active_cred, PRIV_VFS_CHOWN, 0)))
288 		goto out;
289 	ks->ks_uid = uid;
290 	ks->ks_gid = gid;
291 out:
292 	mtx_unlock(&sem_lock);
293 	return (error);
294 }
295 
296 static int
297 ksem_closef(struct file *fp, struct thread *td)
298 {
299 	struct ksem *ks;
300 
301 	ks = fp->f_data;
302 	fp->f_data = NULL;
303 	ksem_drop(ks);
304 
305 	return (0);
306 }
307 
308 /*
309  * ksem object management including creation and reference counting
310  * routines.
311  */
312 static struct ksem *
313 ksem_alloc(struct ucred *ucred, mode_t mode, unsigned int value)
314 {
315 	struct ksem *ks;
316 
317 	mtx_lock(&ksem_count_lock);
318 	if (nsems == p31b_getcfg(CTL_P1003_1B_SEM_NSEMS_MAX) || ksem_dead) {
319 		mtx_unlock(&ksem_count_lock);
320 		return (NULL);
321 	}
322 	nsems++;
323 	mtx_unlock(&ksem_count_lock);
324 	ks = malloc(sizeof(*ks), M_KSEM, M_WAITOK | M_ZERO);
325 	ks->ks_uid = ucred->cr_uid;
326 	ks->ks_gid = ucred->cr_gid;
327 	ks->ks_mode = mode;
328 	ks->ks_value = value;
329 	cv_init(&ks->ks_cv, "ksem");
330 	vfs_timestamp(&ks->ks_birthtime);
331 	ks->ks_atime = ks->ks_mtime = ks->ks_ctime = ks->ks_birthtime;
332 	refcount_init(&ks->ks_ref, 1);
333 #ifdef MAC
334 	mac_posixsem_init(ks);
335 	mac_posixsem_create(ucred, ks);
336 #endif
337 
338 	return (ks);
339 }
340 
341 static struct ksem *
342 ksem_hold(struct ksem *ks)
343 {
344 
345 	refcount_acquire(&ks->ks_ref);
346 	return (ks);
347 }
348 
349 static void
350 ksem_drop(struct ksem *ks)
351 {
352 
353 	if (refcount_release(&ks->ks_ref)) {
354 #ifdef MAC
355 		mac_posixsem_destroy(ks);
356 #endif
357 		cv_destroy(&ks->ks_cv);
358 		free(ks, M_KSEM);
359 		mtx_lock(&ksem_count_lock);
360 		nsems--;
361 		mtx_unlock(&ksem_count_lock);
362 	}
363 }
364 
365 /*
366  * Determine if the credentials have sufficient permissions for read
367  * and write access.
368  */
369 static int
370 ksem_access(struct ksem *ks, struct ucred *ucred)
371 {
372 	int error;
373 
374 	error = vaccess(VREG, ks->ks_mode, ks->ks_uid, ks->ks_gid,
375 	    VREAD | VWRITE, ucred, NULL);
376 	if (error)
377 		error = priv_check_cred(ucred, PRIV_SEM_WRITE, 0);
378 	return (error);
379 }
380 
381 /*
382  * Dictionary management.  We maintain an in-kernel dictionary to map
383  * paths to semaphore objects.  We use the FNV hash on the path to
384  * store the mappings in a hash table.
385  */
386 static struct ksem *
387 ksem_lookup(char *path, Fnv32_t fnv)
388 {
389 	struct ksem_mapping *map;
390 
391 	LIST_FOREACH(map, KSEM_HASH(fnv), km_link) {
392 		if (map->km_fnv != fnv)
393 			continue;
394 		if (strcmp(map->km_path, path) == 0)
395 			return (map->km_ksem);
396 	}
397 
398 	return (NULL);
399 }
400 
401 static void
402 ksem_insert(char *path, Fnv32_t fnv, struct ksem *ks)
403 {
404 	struct ksem_mapping *map;
405 
406 	map = malloc(sizeof(struct ksem_mapping), M_KSEM, M_WAITOK);
407 	map->km_path = path;
408 	map->km_fnv = fnv;
409 	map->km_ksem = ksem_hold(ks);
410 	LIST_INSERT_HEAD(KSEM_HASH(fnv), map, km_link);
411 }
412 
413 static int
414 ksem_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
415 {
416 	struct ksem_mapping *map;
417 	int error;
418 
419 	LIST_FOREACH(map, KSEM_HASH(fnv), km_link) {
420 		if (map->km_fnv != fnv)
421 			continue;
422 		if (strcmp(map->km_path, path) == 0) {
423 #ifdef MAC
424 			error = mac_posixsem_check_unlink(ucred, map->km_ksem);
425 			if (error)
426 				return (error);
427 #endif
428 			error = ksem_access(map->km_ksem, ucred);
429 			if (error)
430 				return (error);
431 			LIST_REMOVE(map, km_link);
432 			ksem_drop(map->km_ksem);
433 			free(map->km_path, M_KSEM);
434 			free(map, M_KSEM);
435 			return (0);
436 		}
437 	}
438 
439 	return (ENOENT);
440 }
441 
442 static int
443 ksem_create_copyout_semid(struct thread *td, semid_t *semidp, int fd,
444     int compat32)
445 {
446 	semid_t semid;
447 #ifdef COMPAT_FREEBSD32
448 	int32_t semid32;
449 #endif
450 	void *ptr;
451 	size_t ptrs;
452 
453 #ifdef COMPAT_FREEBSD32
454 	if (compat32) {
455 		semid32 = fd;
456 		ptr = &semid32;
457 		ptrs = sizeof(semid32);
458 	} else {
459 #endif
460 		semid = fd;
461 		ptr = &semid;
462 		ptrs = sizeof(semid);
463 		compat32 = 0; /* silence gcc */
464 #ifdef COMPAT_FREEBSD32
465 	}
466 #endif
467 
468 	return (copyout(ptr, semidp, ptrs));
469 }
470 
471 /* Other helper routines. */
472 static int
473 ksem_create(struct thread *td, const char *name, semid_t *semidp, mode_t mode,
474     unsigned int value, int flags, int compat32)
475 {
476 	struct filedesc *fdp;
477 	struct ksem *ks;
478 	struct file *fp;
479 	char *path;
480 	Fnv32_t fnv;
481 	int error, fd;
482 
483 	if (value > SEM_VALUE_MAX)
484 		return (EINVAL);
485 
486 	fdp = td->td_proc->p_fd;
487 	mode = (mode & ~fdp->fd_cmask) & ACCESSPERMS;
488 	error = falloc(td, &fp, &fd, 0);
489 	if (error) {
490 		if (name == NULL)
491 			error = ENOSPC;
492 		return (error);
493 	}
494 
495 	/*
496 	 * Go ahead and copyout the file descriptor now.  This is a bit
497 	 * premature, but it is a lot easier to handle errors as opposed
498 	 * to later when we've possibly created a new semaphore, etc.
499 	 */
500 	error = ksem_create_copyout_semid(td, semidp, fd, compat32);
501 	if (error) {
502 		fdclose(fdp, fp, fd, td);
503 		fdrop(fp, td);
504 		return (error);
505 	}
506 
507 	if (name == NULL) {
508 		/* Create an anonymous semaphore. */
509 		ks = ksem_alloc(td->td_ucred, mode, value);
510 		if (ks == NULL)
511 			error = ENOSPC;
512 		else
513 			ks->ks_flags |= KS_ANONYMOUS;
514 	} else {
515 		path = malloc(MAXPATHLEN, M_KSEM, M_WAITOK);
516 		error = copyinstr(name, path, MAXPATHLEN, NULL);
517 
518 		/* Require paths to start with a '/' character. */
519 		if (error == 0 && path[0] != '/')
520 			error = EINVAL;
521 		if (error) {
522 			fdclose(fdp, fp, fd, td);
523 			fdrop(fp, td);
524 			free(path, M_KSEM);
525 			return (error);
526 		}
527 
528 		fnv = fnv_32_str(path, FNV1_32_INIT);
529 		sx_xlock(&ksem_dict_lock);
530 		ks = ksem_lookup(path, fnv);
531 		if (ks == NULL) {
532 			/* Object does not exist, create it if requested. */
533 			if (flags & O_CREAT) {
534 				ks = ksem_alloc(td->td_ucred, mode, value);
535 				if (ks == NULL)
536 					error = ENFILE;
537 				else {
538 					ksem_insert(path, fnv, ks);
539 					path = NULL;
540 				}
541 			} else
542 				error = ENOENT;
543 		} else {
544 			/*
545 			 * Object already exists, obtain a new
546 			 * reference if requested and permitted.
547 			 */
548 			if ((flags & (O_CREAT | O_EXCL)) ==
549 			    (O_CREAT | O_EXCL))
550 				error = EEXIST;
551 			else {
552 #ifdef MAC
553 				error = mac_posixsem_check_open(td->td_ucred,
554 				    ks);
555 				if (error == 0)
556 #endif
557 				error = ksem_access(ks, td->td_ucred);
558 			}
559 			if (error == 0)
560 				ksem_hold(ks);
561 #ifdef INVARIANTS
562 			else
563 				ks = NULL;
564 #endif
565 		}
566 		sx_xunlock(&ksem_dict_lock);
567 		if (path)
568 			free(path, M_KSEM);
569 	}
570 
571 	if (error) {
572 		KASSERT(ks == NULL, ("ksem_create error with a ksem"));
573 		fdclose(fdp, fp, fd, td);
574 		fdrop(fp, td);
575 		return (error);
576 	}
577 	KASSERT(ks != NULL, ("ksem_create w/o a ksem"));
578 
579 	finit(fp, FREAD | FWRITE, DTYPE_SEM, ks, &ksem_ops);
580 
581 	FILEDESC_XLOCK(fdp);
582 	if (fdp->fd_ofiles[fd] == fp)
583 		fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
584 	FILEDESC_XUNLOCK(fdp);
585 	fdrop(fp, td);
586 
587 	return (0);
588 }
589 
590 static int
591 ksem_get(struct thread *td, semid_t id, cap_rights_t rights, struct file **fpp)
592 {
593 	struct ksem *ks;
594 	struct file *fp;
595 	int error;
596 
597 	error = fget(td, id, rights, &fp);
598 	if (error)
599 		return (EINVAL);
600 	if (fp->f_type != DTYPE_SEM) {
601 		fdrop(fp, td);
602 		return (EINVAL);
603 	}
604 	ks = fp->f_data;
605 	if (ks->ks_flags & KS_DEAD) {
606 		fdrop(fp, td);
607 		return (EINVAL);
608 	}
609 	*fpp = fp;
610 	return (0);
611 }
612 
613 /* System calls. */
614 #ifndef _SYS_SYSPROTO_H_
615 struct ksem_init_args {
616 	unsigned int	value;
617 	semid_t		*idp;
618 };
619 #endif
620 int
621 sys_ksem_init(struct thread *td, struct ksem_init_args *uap)
622 {
623 
624 	return (ksem_create(td, NULL, uap->idp, S_IRWXU | S_IRWXG, uap->value,
625 	    0, 0));
626 }
627 
628 #ifndef _SYS_SYSPROTO_H_
629 struct ksem_open_args {
630 	char		*name;
631 	int		oflag;
632 	mode_t		mode;
633 	unsigned int	value;
634 	semid_t		*idp;
635 };
636 #endif
637 int
638 sys_ksem_open(struct thread *td, struct ksem_open_args *uap)
639 {
640 
641 	DP((">>> ksem_open start, pid=%d\n", (int)td->td_proc->p_pid));
642 
643 	if ((uap->oflag & ~(O_CREAT | O_EXCL)) != 0)
644 		return (EINVAL);
645 	return (ksem_create(td, uap->name, uap->idp, uap->mode, uap->value,
646 	    uap->oflag, 0));
647 }
648 
649 #ifndef _SYS_SYSPROTO_H_
650 struct ksem_unlink_args {
651 	char		*name;
652 };
653 #endif
654 int
655 sys_ksem_unlink(struct thread *td, struct ksem_unlink_args *uap)
656 {
657 	char *path;
658 	Fnv32_t fnv;
659 	int error;
660 
661 	path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
662 	error = copyinstr(uap->name, path, MAXPATHLEN, NULL);
663 	if (error) {
664 		free(path, M_TEMP);
665 		return (error);
666 	}
667 
668 	fnv = fnv_32_str(path, FNV1_32_INIT);
669 	sx_xlock(&ksem_dict_lock);
670 	error = ksem_remove(path, fnv, td->td_ucred);
671 	sx_xunlock(&ksem_dict_lock);
672 	free(path, M_TEMP);
673 
674 	return (error);
675 }
676 
677 #ifndef _SYS_SYSPROTO_H_
678 struct ksem_close_args {
679 	semid_t		id;
680 };
681 #endif
682 int
683 sys_ksem_close(struct thread *td, struct ksem_close_args *uap)
684 {
685 	struct ksem *ks;
686 	struct file *fp;
687 	int error;
688 
689 	/* No capability rights required to close a semaphore. */
690 	error = ksem_get(td, uap->id, 0, &fp);
691 	if (error)
692 		return (error);
693 	ks = fp->f_data;
694 	if (ks->ks_flags & KS_ANONYMOUS) {
695 		fdrop(fp, td);
696 		return (EINVAL);
697 	}
698 	error = kern_close(td, uap->id);
699 	fdrop(fp, td);
700 	return (error);
701 }
702 
703 #ifndef _SYS_SYSPROTO_H_
704 struct ksem_post_args {
705 	semid_t	id;
706 };
707 #endif
708 int
709 sys_ksem_post(struct thread *td, struct ksem_post_args *uap)
710 {
711 	struct file *fp;
712 	struct ksem *ks;
713 	int error;
714 
715 	error = ksem_get(td, uap->id, CAP_SEM_POST, &fp);
716 	if (error)
717 		return (error);
718 	ks = fp->f_data;
719 
720 	mtx_lock(&sem_lock);
721 #ifdef MAC
722 	error = mac_posixsem_check_post(td->td_ucred, fp->f_cred, ks);
723 	if (error)
724 		goto err;
725 #endif
726 	if (ks->ks_value == SEM_VALUE_MAX) {
727 		error = EOVERFLOW;
728 		goto err;
729 	}
730 	++ks->ks_value;
731 	if (ks->ks_waiters > 0)
732 		cv_signal(&ks->ks_cv);
733 	error = 0;
734 	vfs_timestamp(&ks->ks_ctime);
735 err:
736 	mtx_unlock(&sem_lock);
737 	fdrop(fp, td);
738 	return (error);
739 }
740 
741 #ifndef _SYS_SYSPROTO_H_
742 struct ksem_wait_args {
743 	semid_t		id;
744 };
745 #endif
746 int
747 sys_ksem_wait(struct thread *td, struct ksem_wait_args *uap)
748 {
749 
750 	return (kern_sem_wait(td, uap->id, 0, NULL));
751 }
752 
753 #ifndef _SYS_SYSPROTO_H_
754 struct ksem_timedwait_args {
755 	semid_t		id;
756 	const struct timespec *abstime;
757 };
758 #endif
759 int
760 sys_ksem_timedwait(struct thread *td, struct ksem_timedwait_args *uap)
761 {
762 	struct timespec abstime;
763 	struct timespec *ts;
764 	int error;
765 
766 	/*
767 	 * We allow a null timespec (wait forever).
768 	 */
769 	if (uap->abstime == NULL)
770 		ts = NULL;
771 	else {
772 		error = copyin(uap->abstime, &abstime, sizeof(abstime));
773 		if (error != 0)
774 			return (error);
775 		if (abstime.tv_nsec >= 1000000000 || abstime.tv_nsec < 0)
776 			return (EINVAL);
777 		ts = &abstime;
778 	}
779 	return (kern_sem_wait(td, uap->id, 0, ts));
780 }
781 
782 #ifndef _SYS_SYSPROTO_H_
783 struct ksem_trywait_args {
784 	semid_t		id;
785 };
786 #endif
787 int
788 sys_ksem_trywait(struct thread *td, struct ksem_trywait_args *uap)
789 {
790 
791 	return (kern_sem_wait(td, uap->id, 1, NULL));
792 }
793 
794 static int
795 kern_sem_wait(struct thread *td, semid_t id, int tryflag,
796     struct timespec *abstime)
797 {
798 	struct timespec ts1, ts2;
799 	struct timeval tv;
800 	struct file *fp;
801 	struct ksem *ks;
802 	int error;
803 
804 	DP((">>> kern_sem_wait entered! pid=%d\n", (int)td->td_proc->p_pid));
805 	error = ksem_get(td, id, CAP_SEM_WAIT, &fp);
806 	if (error)
807 		return (error);
808 	ks = fp->f_data;
809 	mtx_lock(&sem_lock);
810 	DP((">>> kern_sem_wait critical section entered! pid=%d\n",
811 	    (int)td->td_proc->p_pid));
812 #ifdef MAC
813 	error = mac_posixsem_check_wait(td->td_ucred, fp->f_cred, ks);
814 	if (error) {
815 		DP(("kern_sem_wait mac failed\n"));
816 		goto err;
817 	}
818 #endif
819 	DP(("kern_sem_wait value = %d, tryflag %d\n", ks->ks_value, tryflag));
820 	vfs_timestamp(&ks->ks_atime);
821 	while (ks->ks_value == 0) {
822 		ks->ks_waiters++;
823 		if (tryflag != 0)
824 			error = EAGAIN;
825 		else if (abstime == NULL)
826 			error = cv_wait_sig(&ks->ks_cv, &sem_lock);
827 		else {
828 			for (;;) {
829 				ts1 = *abstime;
830 				getnanotime(&ts2);
831 				timespecsub(&ts1, &ts2);
832 				TIMESPEC_TO_TIMEVAL(&tv, &ts1);
833 				if (tv.tv_sec < 0) {
834 					error = ETIMEDOUT;
835 					break;
836 				}
837 				error = cv_timedwait_sig(&ks->ks_cv,
838 				    &sem_lock, tvtohz(&tv));
839 				if (error != EWOULDBLOCK)
840 					break;
841 			}
842 		}
843 		ks->ks_waiters--;
844 		if (error)
845 			goto err;
846 	}
847 	ks->ks_value--;
848 	DP(("kern_sem_wait value post-decrement = %d\n", ks->ks_value));
849 	error = 0;
850 err:
851 	mtx_unlock(&sem_lock);
852 	fdrop(fp, td);
853 	DP(("<<< kern_sem_wait leaving, pid=%d, error = %d\n",
854 	    (int)td->td_proc->p_pid, error));
855 	return (error);
856 }
857 
858 #ifndef _SYS_SYSPROTO_H_
859 struct ksem_getvalue_args {
860 	semid_t		id;
861 	int		*val;
862 };
863 #endif
864 int
865 sys_ksem_getvalue(struct thread *td, struct ksem_getvalue_args *uap)
866 {
867 	struct file *fp;
868 	struct ksem *ks;
869 	int error, val;
870 
871 	error = ksem_get(td, uap->id, CAP_SEM_GETVALUE, &fp);
872 	if (error)
873 		return (error);
874 	ks = fp->f_data;
875 
876 	mtx_lock(&sem_lock);
877 #ifdef MAC
878 	error = mac_posixsem_check_getvalue(td->td_ucred, fp->f_cred, ks);
879 	if (error) {
880 		mtx_unlock(&sem_lock);
881 		fdrop(fp, td);
882 		return (error);
883 	}
884 #endif
885 	val = ks->ks_value;
886 	vfs_timestamp(&ks->ks_atime);
887 	mtx_unlock(&sem_lock);
888 	fdrop(fp, td);
889 	error = copyout(&val, uap->val, sizeof(val));
890 	return (error);
891 }
892 
893 #ifndef _SYS_SYSPROTO_H_
894 struct ksem_destroy_args {
895 	semid_t		id;
896 };
897 #endif
898 int
899 sys_ksem_destroy(struct thread *td, struct ksem_destroy_args *uap)
900 {
901 	struct file *fp;
902 	struct ksem *ks;
903 	int error;
904 
905 	/* No capability rights required to close a semaphore. */
906 	error = ksem_get(td, uap->id, 0, &fp);
907 	if (error)
908 		return (error);
909 	ks = fp->f_data;
910 	if (!(ks->ks_flags & KS_ANONYMOUS)) {
911 		fdrop(fp, td);
912 		return (EINVAL);
913 	}
914 	mtx_lock(&sem_lock);
915 	if (ks->ks_waiters != 0) {
916 		mtx_unlock(&sem_lock);
917 		error = EBUSY;
918 		goto err;
919 	}
920 	ks->ks_flags |= KS_DEAD;
921 	mtx_unlock(&sem_lock);
922 
923 	error = kern_close(td, uap->id);
924 err:
925 	fdrop(fp, td);
926 	return (error);
927 }
928 
929 static struct syscall_helper_data ksem_syscalls[] = {
930 	SYSCALL_INIT_HELPER(ksem_init),
931 	SYSCALL_INIT_HELPER(ksem_open),
932 	SYSCALL_INIT_HELPER(ksem_unlink),
933 	SYSCALL_INIT_HELPER(ksem_close),
934 	SYSCALL_INIT_HELPER(ksem_post),
935 	SYSCALL_INIT_HELPER(ksem_wait),
936 	SYSCALL_INIT_HELPER(ksem_timedwait),
937 	SYSCALL_INIT_HELPER(ksem_trywait),
938 	SYSCALL_INIT_HELPER(ksem_getvalue),
939 	SYSCALL_INIT_HELPER(ksem_destroy),
940 	SYSCALL_INIT_LAST
941 };
942 
943 #ifdef COMPAT_FREEBSD32
944 #include <compat/freebsd32/freebsd32.h>
945 #include <compat/freebsd32/freebsd32_proto.h>
946 #include <compat/freebsd32/freebsd32_signal.h>
947 #include <compat/freebsd32/freebsd32_syscall.h>
948 #include <compat/freebsd32/freebsd32_util.h>
949 
950 int
951 freebsd32_ksem_init(struct thread *td, struct freebsd32_ksem_init_args *uap)
952 {
953 
954 	return (ksem_create(td, NULL, uap->idp, S_IRWXU | S_IRWXG, uap->value,
955 	    0, 1));
956 }
957 
958 int
959 freebsd32_ksem_open(struct thread *td, struct freebsd32_ksem_open_args *uap)
960 {
961 
962 	if ((uap->oflag & ~(O_CREAT | O_EXCL)) != 0)
963 		return (EINVAL);
964 	return (ksem_create(td, uap->name, uap->idp, uap->mode, uap->value,
965 	    uap->oflag, 1));
966 }
967 
968 int
969 freebsd32_ksem_timedwait(struct thread *td,
970     struct freebsd32_ksem_timedwait_args *uap)
971 {
972 	struct timespec32 abstime32;
973 	struct timespec *ts, abstime;
974 	int error;
975 
976 	/*
977 	 * We allow a null timespec (wait forever).
978 	 */
979 	if (uap->abstime == NULL)
980 		ts = NULL;
981 	else {
982 		error = copyin(uap->abstime, &abstime32, sizeof(abstime32));
983 		if (error != 0)
984 			return (error);
985 		CP(abstime32, abstime, tv_sec);
986 		CP(abstime32, abstime, tv_nsec);
987 		if (abstime.tv_nsec >= 1000000000 || abstime.tv_nsec < 0)
988 			return (EINVAL);
989 		ts = &abstime;
990 	}
991 	return (kern_sem_wait(td, uap->id, 0, ts));
992 }
993 
994 static struct syscall_helper_data ksem32_syscalls[] = {
995 	SYSCALL32_INIT_HELPER(freebsd32_ksem_init),
996 	SYSCALL32_INIT_HELPER(freebsd32_ksem_open),
997 	SYSCALL32_INIT_HELPER_COMPAT(ksem_unlink),
998 	SYSCALL32_INIT_HELPER_COMPAT(ksem_close),
999 	SYSCALL32_INIT_HELPER_COMPAT(ksem_post),
1000 	SYSCALL32_INIT_HELPER_COMPAT(ksem_wait),
1001 	SYSCALL32_INIT_HELPER(freebsd32_ksem_timedwait),
1002 	SYSCALL32_INIT_HELPER_COMPAT(ksem_trywait),
1003 	SYSCALL32_INIT_HELPER_COMPAT(ksem_getvalue),
1004 	SYSCALL32_INIT_HELPER_COMPAT(ksem_destroy),
1005 	SYSCALL_INIT_LAST
1006 };
1007 #endif
1008 
1009 static int
1010 ksem_module_init(void)
1011 {
1012 	int error;
1013 
1014 	mtx_init(&sem_lock, "sem", NULL, MTX_DEF);
1015 	mtx_init(&ksem_count_lock, "ksem count", NULL, MTX_DEF);
1016 	sx_init(&ksem_dict_lock, "ksem dictionary");
1017 	ksem_dictionary = hashinit(1024, M_KSEM, &ksem_hash);
1018 	p31b_setcfg(CTL_P1003_1B_SEMAPHORES, 200112L);
1019 	p31b_setcfg(CTL_P1003_1B_SEM_NSEMS_MAX, SEM_MAX);
1020 	p31b_setcfg(CTL_P1003_1B_SEM_VALUE_MAX, SEM_VALUE_MAX);
1021 
1022 	error = syscall_helper_register(ksem_syscalls);
1023 	if (error)
1024 		return (error);
1025 #ifdef COMPAT_FREEBSD32
1026 	error = syscall32_helper_register(ksem32_syscalls);
1027 	if (error)
1028 		return (error);
1029 #endif
1030 	return (0);
1031 }
1032 
1033 static void
1034 ksem_module_destroy(void)
1035 {
1036 
1037 #ifdef COMPAT_FREEBSD32
1038 	syscall32_helper_unregister(ksem32_syscalls);
1039 #endif
1040 	syscall_helper_unregister(ksem_syscalls);
1041 
1042 	p31b_setcfg(CTL_P1003_1B_SEMAPHORES, 0);
1043 	hashdestroy(ksem_dictionary, M_KSEM, ksem_hash);
1044 	sx_destroy(&ksem_dict_lock);
1045 	mtx_destroy(&ksem_count_lock);
1046 	mtx_destroy(&sem_lock);
1047 	p31b_unsetcfg(CTL_P1003_1B_SEM_VALUE_MAX);
1048 	p31b_unsetcfg(CTL_P1003_1B_SEM_NSEMS_MAX);
1049 }
1050 
1051 static int
1052 sem_modload(struct module *module, int cmd, void *arg)
1053 {
1054         int error = 0;
1055 
1056         switch (cmd) {
1057         case MOD_LOAD:
1058 		error = ksem_module_init();
1059 		if (error)
1060 			ksem_module_destroy();
1061                 break;
1062 
1063         case MOD_UNLOAD:
1064 		mtx_lock(&ksem_count_lock);
1065 		if (nsems != 0) {
1066 			error = EOPNOTSUPP;
1067 			mtx_unlock(&ksem_count_lock);
1068 			break;
1069 		}
1070 		ksem_dead = 1;
1071 		mtx_unlock(&ksem_count_lock);
1072 		ksem_module_destroy();
1073                 break;
1074 
1075         case MOD_SHUTDOWN:
1076                 break;
1077         default:
1078                 error = EINVAL;
1079                 break;
1080         }
1081         return (error);
1082 }
1083 
1084 static moduledata_t sem_mod = {
1085         "sem",
1086         &sem_modload,
1087         NULL
1088 };
1089 
1090 DECLARE_MODULE(sem, sem_mod, SI_SUB_SYSV_SEM, SI_ORDER_FIRST);
1091 MODULE_VERSION(sem, 1);
1092