aboutsummaryrefslogtreecommitdiff
path: root/sys/kern/uipc_sem.c
blob: 917c343ed3a4278061966d24d57806cdac37666a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
/*-
 * Copyright (c) 2002 Alfred Perlstein <alfred@FreeBSD.org>
 * Copyright (c) 2003-2005 SPARTA, Inc.
 * Copyright (c) 2005 Robert N. M. Watson
 * All rights reserved.
 *
 * This software was developed for the FreeBSD Project in part by Network
 * Associates Laboratories, the Security Research Division of Network
 * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"),
 * as part of the DARPA CHATS research program.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_compat.h"
#include "opt_posix.h"

#include <sys/param.h>
#include <sys/condvar.h>
#include <sys/fcntl.h>
#include <sys/file.h>
#include <sys/filedesc.h>
#include <sys/fnv_hash.h>
#include <sys/kernel.h>
#include <sys/ksem.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/mutex.h>
#include <sys/priv.h>
#include <sys/proc.h>
#include <sys/posix4.h>
#include <sys/_semaphore.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/syscallsubr.h>
#include <sys/sysctl.h>
#include <sys/sysent.h>
#include <sys/sysproto.h>
#include <sys/systm.h>
#include <sys/sx.h>
#include <sys/vnode.h>

#include <security/mac/mac_framework.h>

FEATURE(p1003_1b_semaphores, "POSIX P1003.1B semaphores support");
/*
 * TODO
 *
 * - Resource limits?
 * - Update fstat(1)
 * - Replace global sem_lock with mtx_pool locks?
 * - Add a MAC check_create() hook for creating new named semaphores.
 */

#ifndef SEM_MAX
#define	SEM_MAX	30
#endif

#ifdef SEM_DEBUG
#define	DP(x)	printf x
#else
#define	DP(x)
#endif

struct ksem_mapping {
	char		*km_path;
	Fnv32_t		km_fnv;
	struct ksem	*km_ksem;
	LIST_ENTRY(ksem_mapping) km_link;
};

static MALLOC_DEFINE(M_KSEM, "ksem", "semaphore file descriptor");
static LIST_HEAD(, ksem_mapping) *ksem_dictionary;
static struct sx ksem_dict_lock;
static struct mtx ksem_count_lock;
static struct mtx sem_lock;
static u_long ksem_hash;
static int ksem_dead;

#define	KSEM_HASH(fnv)	(&ksem_dictionary[(fnv) & ksem_hash])

static int nsems = 0;
SYSCTL_DECL(_p1003_1b);
SYSCTL_INT(_p1003_1b, OID_AUTO, nsems, CTLFLAG_RD, &nsems, 0,
    "Number of active kernel POSIX semaphores");

static int	kern_sem_wait(struct thread *td, semid_t id, int tryflag,
		    struct timespec *abstime);
static int	ksem_access(struct ksem *ks, struct ucred *ucred);
static struct ksem *ksem_alloc(struct ucred *ucred, mode_t mode,
		    unsigned int value);
static int	ksem_create(struct thread *td, const char *path,
		    semid_t *semidp, mode_t mode, unsigned int value,
		    int flags, int compat32);
static void	ksem_drop(struct ksem *ks);
static int	ksem_get(struct thread *td, semid_t id, struct file **fpp);
static struct ksem *ksem_hold(struct ksem *ks);
static void	ksem_insert(char *path, Fnv32_t fnv, struct ksem *ks);
static struct ksem *ksem_lookup(char *path, Fnv32_t fnv);
static void	ksem_module_destroy(void);
static int	ksem_module_init(void);
static int	ksem_remove(char *path, Fnv32_t fnv, struct ucred *ucred);
static int	sem_modload(struct module *module, int cmd, void *arg);

static fo_rdwr_t	ksem_read;
static fo_rdwr_t	ksem_write;
static fo_truncate_t	ksem_truncate;
static fo_ioctl_t	ksem_ioctl;
static fo_poll_t	ksem_poll;
static fo_kqfilter_t	ksem_kqfilter;
static fo_stat_t	ksem_stat;
static fo_close_t	ksem_closef;

/* File descriptor operations. */
static struct fileops ksem_ops = {
	.fo_read = ksem_read,
	.fo_write = ksem_write,
	.fo_truncate = ksem_truncate,
	.fo_ioctl = ksem_ioctl,
	.fo_poll = ksem_poll,
	.fo_kqfilter = ksem_kqfilter,
	.fo_stat = ksem_stat,
	.fo_close = ksem_closef,
	.fo_flags = DFLAG_PASSABLE
};

FEATURE(posix_sem, "POSIX semaphores");

static int
ksem_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
    int flags, struct thread *td)
{

	return (EOPNOTSUPP);
}

static int
ksem_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
    int flags, struct thread *td)
{

	return (EOPNOTSUPP);
}

static int
ksem_truncate(struct file *fp, off_t length, struct ucred *active_cred,
    struct thread *td)
{

	return (EINVAL);
}

static int
ksem_ioctl(struct file *fp, u_long com, void *data,
    struct ucred *active_cred, struct thread *td)
{

	return (EOPNOTSUPP);
}

static int
ksem_poll(struct file *fp, int events, struct ucred *active_cred,
    struct thread *td)
{

	return (EOPNOTSUPP);
}

static int
ksem_kqfilter(struct file *fp, struct knote *kn)
{

	return (EOPNOTSUPP);
}

static int
ksem_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
    struct thread *td)
{
	struct ksem *ks;
#ifdef MAC
	int error;
#endif

	ks = fp->f_data;

#ifdef MAC
	error = mac_posixsem_check_stat(active_cred, fp->f_cred, ks);
	if (error)
		return (error);
#endif
	
	/*
	 * Attempt to return sanish values for fstat() on a semaphore
	 * file descriptor.
	 */
	bzero(sb, sizeof(*sb));
	sb->st_mode = S_IFREG | ks->ks_mode;		/* XXX */

	sb->st_atim = ks->ks_atime;
	sb->st_ctim = ks->ks_ctime;
	sb->st_mtim = ks->ks_mtime;
	sb->st_birthtim = ks->ks_birthtime;	
	sb->st_uid = ks->ks_uid;
	sb->st_gid = ks->ks_gid;

	return (0);
}

static int
ksem_closef(struct file *fp, struct thread *td)
{
	struct ksem *ks;

	ks = fp->f_data;
	fp->f_data = NULL;
	ksem_drop(ks);

	return (0);
}

/*
 * ksem object management including creation and reference counting
 * routines.
 */
static struct ksem *
ksem_alloc(struct ucred *ucred, mode_t mode, unsigned int value)
{
	struct ksem *ks;

	mtx_lock(&ksem_count_lock);
	if (nsems == p31b_getcfg(CTL_P1003_1B_SEM_NSEMS_MAX) || ksem_dead) {
		mtx_unlock(&ksem_count_lock);
		return (NULL);
	}
	nsems++;
	mtx_unlock(&ksem_count_lock);
	ks = malloc(sizeof(*ks), M_KSEM, M_WAITOK | M_ZERO);
	ks->ks_uid = ucred->cr_uid;
	ks->ks_gid = ucred->cr_gid;
	ks->ks_mode = mode;
	ks->ks_value = value;
	cv_init(&ks->ks_cv, "ksem");
	vfs_timestamp(&ks->ks_birthtime);
	ks->ks_atime = ks->ks_mtime = ks->ks_ctime = ks->ks_birthtime;
	refcount_init(&ks->ks_ref, 1);
#ifdef MAC
	mac_posixsem_init(ks);
	mac_posixsem_create(ucred, ks);
#endif

	return (ks);
}

static struct ksem *
ksem_hold(struct ksem *ks)
{

	refcount_acquire(&ks->ks_ref);
	return (ks);
}

static void
ksem_drop(struct ksem *ks)
{

	if (refcount_release(&ks->ks_ref)) {
#ifdef MAC
		mac_posixsem_destroy(ks);
#endif
		cv_destroy(&ks->ks_cv);
		free(ks, M_KSEM);
		mtx_lock(&ksem_count_lock);
		nsems--;
		mtx_unlock(&ksem_count_lock);
	}
}

/*
 * Determine if the credentials have sufficient permissions for read
 * and write access.
 */
static int
ksem_access(struct ksem *ks, struct ucred *ucred)
{
	int error;

	error = vaccess(VREG, ks->ks_mode, ks->ks_uid, ks->ks_gid,
	    VREAD | VWRITE, ucred, NULL);
	if (error)
		error = priv_check_cred(ucred, PRIV_SEM_WRITE, 0);
	return (error);
}

/*
 * Dictionary management.  We maintain an in-kernel dictionary to map
 * paths to semaphore objects.  We use the FNV hash on the path to
 * store the mappings in a hash table.
 */
static struct ksem *
ksem_lookup(char *path, Fnv32_t fnv)
{
	struct ksem_mapping *map;

	LIST_FOREACH(map, KSEM_HASH(fnv), km_link) {
		if (map->km_fnv != fnv)
			continue;
		if (strcmp(map->km_path, path) == 0)
			return (map->km_ksem);
	}

	return (NULL);
}

static void
ksem_insert(char *path, Fnv32_t fnv, struct ksem *ks)
{
	struct ksem_mapping *map;

	map = malloc(sizeof(struct ksem_mapping), M_KSEM, M_WAITOK);
	map->km_path = path;
	map->km_fnv = fnv;
	map->km_ksem = ksem_hold(ks);
	LIST_INSERT_HEAD(KSEM_HASH(fnv), map, km_link);
}

static int
ksem_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
{
	struct ksem_mapping *map;
	int error;

	LIST_FOREACH(map, KSEM_HASH(fnv), km_link) {
		if (map->km_fnv != fnv)
			continue;
		if (strcmp(map->km_path, path) == 0) {
#ifdef MAC
			error = mac_posixsem_check_unlink(ucred, map->km_ksem);
			if (error)
				return (error);
#endif
			error = ksem_access(map->km_ksem, ucred);
			if (error)
				return (error);
			LIST_REMOVE(map, km_link);
			ksem_drop(map->km_ksem);
			free(map->km_path, M_KSEM);
			free(map, M_KSEM);
			return (0);
		}
	}

	return (ENOENT);
}

static int
ksem_create_copyout_semid(struct thread *td, semid_t *semidp, int fd,
    int compat32)
{
	semid_t semid;
#ifdef COMPAT_FREEBSD32
	int32_t semid32;
#endif
	void *ptr;
	size_t ptrs;

#ifdef COMPAT_FREEBSD32
	if (compat32) {
		semid32 = fd;
		ptr = &semid32;
		ptrs = sizeof(semid32);
	} else {
#endif
		semid = fd;
		ptr = &semid;
		ptrs = sizeof(semid);
		compat32 = 0; /* silence gcc */
#ifdef COMPAT_FREEBSD32
	}
#endif

	return (copyout(ptr, semidp, ptrs));
}

/* Other helper routines. */
static int
ksem_create(struct thread *td, const char *name, semid_t *semidp, mode_t mode,
    unsigned int value, int flags, int compat32)
{
	struct filedesc *fdp;
	struct ksem *ks;
	struct file *fp;
	char *path;
	Fnv32_t fnv;
	int error, fd;

	if (value > SEM_VALUE_MAX)
		return (EINVAL);

	fdp = td->td_proc->p_fd;
	mode = (mode & ~fdp->fd_cmask) & ACCESSPERMS;
	error = falloc(td, &fp, &fd, 0);
	if (error) {
		if (name == NULL)
			error = ENOSPC;
		return (error);
	}

	/*
	 * Go ahead and copyout the file descriptor now.  This is a bit
	 * premature, but it is a lot easier to handle errors as opposed
	 * to later when we've possibly created a new semaphore, etc.
	 */
	error = ksem_create_copyout_semid(td, semidp, fd, compat32);
	if (error) {
		fdclose(fdp, fp, fd, td);
		fdrop(fp, td);
		return (error);
	}

	if (name == NULL) {
		/* Create an anonymous semaphore. */
		ks = ksem_alloc(td->td_ucred, mode, value);
		if (ks == NULL)
			error = ENOSPC;
		else
			ks->ks_flags |= KS_ANONYMOUS;
	} else {
		path = malloc(MAXPATHLEN, M_KSEM, M_WAITOK);
		error = copyinstr(name, path, MAXPATHLEN, NULL);

		/* Require paths to start with a '/' character. */
		if (error == 0 && path[0] != '/')
			error = EINVAL;
		if (error) {
			fdclose(fdp, fp, fd, td);
			fdrop(fp, td);
			free(path, M_KSEM);
			return (error);
		}

		fnv = fnv_32_str(path, FNV1_32_INIT);
		sx_xlock(&ksem_dict_lock);
		ks = ksem_lookup(path, fnv);
		if (ks == NULL) {
			/* Object does not exist, create it if requested. */
			if (flags & O_CREAT) {
				ks = ksem_alloc(td->td_ucred, mode, value);
				if (ks == NULL)
					error = ENFILE;
				else {
					ksem_insert(path, fnv, ks);
					path = NULL;
				}
			} else
				error = ENOENT;
		} else {
			/*
			 * Object already exists, obtain a new
			 * reference if requested and permitted.
			 */
			if ((flags & (O_CREAT | O_EXCL)) ==
			    (O_CREAT | O_EXCL))
				error = EEXIST;
			else {
#ifdef MAC
				error = mac_posixsem_check_open(td->td_ucred,
				    ks);
				if (error == 0)
#endif
				error = ksem_access(ks, td->td_ucred);
			}
			if (error == 0)
				ksem_hold(ks);
#ifdef INVARIANTS
			else
				ks = NULL;
#endif
		}
		sx_xunlock(&ksem_dict_lock);
		if (path)
			free(path, M_KSEM);
	}

	if (error) {
		KASSERT(ks == NULL, ("ksem_create error with a ksem"));
		fdclose(fdp, fp, fd, td);
		fdrop(fp, td);
		return (error);
	}
	KASSERT(ks != NULL, ("ksem_create w/o a ksem"));

	finit(fp, FREAD | FWRITE, DTYPE_SEM, ks, &ksem_ops);

	FILEDESC_XLOCK(fdp);
	if (fdp->fd_ofiles[fd] == fp)
		fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
	FILEDESC_XUNLOCK(fdp);
	fdrop(fp, td);

	return (0);
}

static int
ksem_get(struct thread *td, semid_t id, struct file **fpp)
{
	struct ksem *ks;
	struct file *fp;
	int error;

	error = fget(td, id, &fp);
	if (error)
		return (EINVAL);
	if (fp->f_type != DTYPE_SEM) {
		fdrop(fp, td);
		return (EINVAL);
	}
	ks = fp->f_data;
	if (ks->ks_flags & KS_DEAD) {
		fdrop(fp, td);
		return (EINVAL);
	}
	*fpp = fp;
	return (0);
}

/* System calls. */
#ifndef _SYS_SYSPROTO_H_
struct ksem_init_args {
	unsigned int	value;
	semid_t		*idp;
};
#endif
int
ksem_init(struct thread *td, struct ksem_init_args *uap)
{

	return (ksem_create(td, NULL, uap->idp, S_IRWXU | S_IRWXG, uap->value,
	    0, 0));
}

#ifndef _SYS_SYSPROTO_H_
struct ksem_open_args {
	char		*name;
	int		oflag;
	mode_t		mode;
	unsigned int	value;
	semid_t		*idp;	
};
#endif
int
ksem_open(struct thread *td, struct ksem_open_args *uap)
{

	DP((">>> ksem_open start, pid=%d\n", (int)td->td_proc->p_pid));

	if ((uap->oflag & ~(O_CREAT | O_EXCL)) != 0)
		return (EINVAL);
	return (ksem_create(td, uap->name, uap->idp, uap->mode, uap->value,
	    uap->oflag, 0));
}

#ifndef _SYS_SYSPROTO_H_
struct ksem_unlink_args {
	char		*name;
};
#endif
int
ksem_unlink(struct thread *td, struct ksem_unlink_args *uap)
{
	char *path;
	Fnv32_t fnv;
	int error;

	path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
	error = copyinstr(uap->name, path, MAXPATHLEN, NULL);
	if (error) {
		free(path, M_TEMP);
		return (error);
	}

	fnv = fnv_32_str(path, FNV1_32_INIT);
	sx_xlock(&ksem_dict_lock);
	error = ksem_remove(path, fnv, td->td_ucred);
	sx_xunlock(&ksem_dict_lock);
	free(path, M_TEMP);

	return (error);
}

#ifndef _SYS_SYSPROTO_H_
struct ksem_close_args {
	semid_t		id;
};
#endif
int
ksem_close(struct thread *td, struct ksem_close_args *uap)
{
	struct ksem *ks;
	struct file *fp;
	int error;

	error = ksem_get(td, uap->id, &fp);
	if (error)
		return (error);
	ks = fp->f_data;
	if (ks->ks_flags & KS_ANONYMOUS) {
		fdrop(fp, td);
		return (EINVAL);
	}
	error = kern_close(td, uap->id);
	fdrop(fp, td);
	return (error);
}

#ifndef _SYS_SYSPROTO_H_
struct ksem_post_args {
	semid_t	id;
};
#endif
int
ksem_post(struct thread *td, struct ksem_post_args *uap)
{
	struct file *fp;
	struct ksem *ks;
	int error;

	error = ksem_get(td, uap->id, &fp);
	if (error)
		return (error);
	ks = fp->f_data;

	mtx_lock(&sem_lock);
#ifdef MAC
	error = mac_posixsem_check_post(td->td_ucred, fp->f_cred, ks);
	if (error)
		goto err;
#endif
	if (ks->ks_value == SEM_VALUE_MAX) {
		error = EOVERFLOW;
		goto err;
	}
	++ks->ks_value;
	if (ks->ks_waiters > 0)
		cv_signal(&ks->ks_cv);
	error = 0;
	vfs_timestamp(&ks->ks_ctime);
err:
	mtx_unlock(&sem_lock);
	fdrop(fp, td);
	return (error);
}

#ifndef _SYS_SYSPROTO_H_
struct ksem_wait_args {
	semid_t		id;
};
#endif
int
ksem_wait(struct thread *td, struct ksem_wait_args *uap)
{

	return (kern_sem_wait(td, uap->id, 0, NULL));
}

#ifndef _SYS_SYSPROTO_H_
struct ksem_timedwait_args {
	semid_t		id;
	const struct timespec *abstime;
};
#endif
int
ksem_timedwait(struct thread *td, struct ksem_timedwait_args *uap)
{
	struct timespec abstime;
	struct timespec *ts;
	int error;

	/*
	 * We allow a null timespec (wait forever).
	 */
	if (uap->abstime == NULL)
		ts = NULL;
	else {
		error = copyin(uap->abstime, &abstime, sizeof(abstime));
		if (error != 0)
			return (error);
		if (abstime.tv_nsec >= 1000000000 || abstime.tv_nsec < 0)
			return (EINVAL);
		ts = &abstime;
	}
	return (kern_sem_wait(td, uap->id, 0, ts));
}

#ifndef _SYS_SYSPROTO_H_
struct ksem_trywait_args {
	semid_t		id;
};
#endif
int
ksem_trywait(struct thread *td, struct ksem_trywait_args *uap)
{

	return (kern_sem_wait(td, uap->id, 1, NULL));
}

static int
kern_sem_wait(struct thread *td, semid_t id, int tryflag,
    struct timespec *abstime)
{
	struct timespec ts1, ts2;
	struct timeval tv;
	struct file *fp;
	struct ksem *ks;
	int error;

	DP((">>> kern_sem_wait entered! pid=%d\n", (int)td->td_proc->p_pid));
	error = ksem_get(td, id, &fp);
	if (error)
		return (error);
	ks = fp->f_data;
	mtx_lock(&sem_lock);
	DP((">>> kern_sem_wait critical section entered! pid=%d\n",
	    (int)td->td_proc->p_pid));
#ifdef MAC
	error = mac_posixsem_check_wait(td->td_ucred, fp->f_cred, ks);
	if (error) {
		DP(("kern_sem_wait mac failed\n"));
		goto err;
	}
#endif
	DP(("kern_sem_wait value = %d, tryflag %d\n", ks->ks_value, tryflag));
	vfs_timestamp(&ks->ks_atime);
	while (ks->ks_value == 0) {
		ks->ks_waiters++;
		if (tryflag != 0)
			error = EAGAIN;
		else if (abstime == NULL)
			error = cv_wait_sig(&ks->ks_cv, &sem_lock);
		else {
			for (;;) {
				ts1 = *abstime;
				getnanotime(&ts2);
				timespecsub(&ts1, &ts2);
				TIMESPEC_TO_TIMEVAL(&tv, &ts1);
				if (tv.tv_sec < 0) {
					error = ETIMEDOUT;
					break;
				}
				error = cv_timedwait_sig(&ks->ks_cv,
				    &sem_lock, tvtohz(&tv));
				if (error != EWOULDBLOCK)
					break;
			}
		}
		ks->ks_waiters--;
		if (error)
			goto err;
	}
	ks->ks_value--;
	DP(("kern_sem_wait value post-decrement = %d\n", ks->ks_value));
	error = 0;
err:
	mtx_unlock(&sem_lock);
	fdrop(fp, td);
	DP(("<<< kern_sem_wait leaving, pid=%d, error = %d\n",
	    (int)td->td_proc->p_pid, error));
	return (error);
}

#ifndef _SYS_SYSPROTO_H_
struct ksem_getvalue_args {
	semid_t		id;
	int		*val;
};
#endif
int
ksem_getvalue(struct thread *td, struct ksem_getvalue_args *uap)
{
	struct file *fp;
	struct ksem *ks;
	int error, val;

	error = ksem_get(td, uap->id, &fp);
	if (error)
		return (error);
	ks = fp->f_data;

	mtx_lock(&sem_lock);
#ifdef MAC
	error = mac_posixsem_check_getvalue(td->td_ucred, fp->f_cred, ks);
	if (error) {
		mtx_unlock(&sem_lock);
		fdrop(fp, td);
		return (error);
	}
#endif
	val = ks->ks_value;
	vfs_timestamp(&ks->ks_atime);
	mtx_unlock(&sem_lock);
	fdrop(fp, td);
	error = copyout(&val, uap->val, sizeof(val));
	return (error);
}

#ifndef _SYS_SYSPROTO_H_
struct ksem_destroy_args {
	semid_t		id;
};
#endif
int
ksem_destroy(struct thread *td, struct ksem_destroy_args *uap)
{
	struct file *fp;
	struct ksem *ks;
	int error;

	error = ksem_get(td, uap->id, &fp);
	if (error)
		return (error);
	ks = fp->f_data;
	if (!(ks->ks_flags & KS_ANONYMOUS)) {
		fdrop(fp, td);
		return (EINVAL);
	}
	mtx_lock(&sem_lock);
	if (ks->ks_waiters != 0) {
		mtx_unlock(&sem_lock);
		error = EBUSY;
		goto err;
	}
	ks->ks_flags |= KS_DEAD;
	mtx_unlock(&sem_lock);

	error = kern_close(td, uap->id);
err:
	fdrop(fp, td);
	return (error);
}

static struct syscall_helper_data ksem_syscalls[] = {
	SYSCALL_INIT_HELPER(ksem_init),
	SYSCALL_INIT_HELPER(ksem_open),
	SYSCALL_INIT_HELPER(ksem_unlink),
	SYSCALL_INIT_HELPER(ksem_close),
	SYSCALL_INIT_HELPER(ksem_post),
	SYSCALL_INIT_HELPER(ksem_wait),
	SYSCALL_INIT_HELPER(ksem_timedwait),
	SYSCALL_INIT_HELPER(ksem_trywait),
	SYSCALL_INIT_HELPER(ksem_getvalue),
	SYSCALL_INIT_HELPER(ksem_destroy),
	SYSCALL_INIT_LAST
};

#ifdef COMPAT_FREEBSD32
#include <compat/freebsd32/freebsd32.h>
#include <compat/freebsd32/freebsd32_proto.h>
#include <compat/freebsd32/freebsd32_signal.h>
#include <compat/freebsd32/freebsd32_syscall.h>
#include <compat/freebsd32/freebsd32_util.h>

int
freebsd32_ksem_init(struct thread *td, struct freebsd32_ksem_init_args *uap)
{

	return (ksem_create(td, NULL, uap->idp, S_IRWXU | S_IRWXG, uap->value,
	    0, 1));
}

int
freebsd32_ksem_open(struct thread *td, struct freebsd32_ksem_open_args *uap)
{

	if ((uap->oflag & ~(O_CREAT | O_EXCL)) != 0)
		return (EINVAL);
	return (ksem_create(td, uap->name, uap->idp, uap->mode, uap->value,
	    uap->oflag, 1));
}

int
freebsd32_ksem_timedwait(struct thread *td,
    struct freebsd32_ksem_timedwait_args *uap)
{
	struct timespec32 abstime32;
	struct timespec *ts, abstime;
	int error;

	/*
	 * We allow a null timespec (wait forever).
	 */
	if (uap->abstime == NULL)
		ts = NULL;
	else {
		error = copyin(uap->abstime, &abstime32, sizeof(abstime32));
		if (error != 0)
			return (error);
		CP(abstime32, abstime, tv_sec);
		CP(abstime32, abstime, tv_nsec);
		if (abstime.tv_nsec >= 1000000000 || abstime.tv_nsec < 0)
			return (EINVAL);
		ts = &abstime;
	}
	return (kern_sem_wait(td, uap->id, 0, ts));
}

static struct syscall_helper_data ksem32_syscalls[] = {
	SYSCALL32_INIT_HELPER(freebsd32_ksem_init),
	SYSCALL32_INIT_HELPER(freebsd32_ksem_open),
	SYSCALL32_INIT_HELPER(ksem_unlink),
	SYSCALL32_INIT_HELPER(ksem_close),
	SYSCALL32_INIT_HELPER(ksem_post),
	SYSCALL32_INIT_HELPER(ksem_wait),
	SYSCALL32_INIT_HELPER(freebsd32_ksem_timedwait),
	SYSCALL32_INIT_HELPER(ksem_trywait),
	SYSCALL32_INIT_HELPER(ksem_getvalue),
	SYSCALL32_INIT_HELPER(ksem_destroy),
	SYSCALL_INIT_LAST
};
#endif

static int
ksem_module_init(void)
{
	int error;

	mtx_init(&sem_lock, "sem", NULL, MTX_DEF);
	mtx_init(&ksem_count_lock, "ksem count", NULL, MTX_DEF);
	sx_init(&ksem_dict_lock, "ksem dictionary");
	ksem_dictionary = hashinit(1024, M_KSEM, &ksem_hash);
	p31b_setcfg(CTL_P1003_1B_SEMAPHORES, 200112L);
	p31b_setcfg(CTL_P1003_1B_SEM_NSEMS_MAX, SEM_MAX);
	p31b_setcfg(CTL_P1003_1B_SEM_VALUE_MAX, SEM_VALUE_MAX);

	error = syscall_helper_register(ksem_syscalls);
	if (error)
		return (error);
#ifdef COMPAT_FREEBSD32
	error = syscall32_helper_register(ksem32_syscalls);
	if (error)
		return (error);
#endif
	return (0);
}

static void
ksem_module_destroy(void)
{

#ifdef COMPAT_FREEBSD32
	syscall32_helper_unregister(ksem32_syscalls);
#endif
	syscall_helper_unregister(ksem_syscalls);

	p31b_setcfg(CTL_P1003_1B_SEMAPHORES, 0);
	hashdestroy(ksem_dictionary, M_KSEM, ksem_hash);
	sx_destroy(&ksem_dict_lock);
	mtx_destroy(&ksem_count_lock);
	mtx_destroy(&sem_lock);
	p31b_unsetcfg(CTL_P1003_1B_SEM_VALUE_MAX);
	p31b_unsetcfg(CTL_P1003_1B_SEM_NSEMS_MAX);
}

static int
sem_modload(struct module *module, int cmd, void *arg)
{
        int error = 0;

        switch (cmd) {
        case MOD_LOAD:
		error = ksem_module_init();
		if (error)
			ksem_module_destroy();
                break;

        case MOD_UNLOAD:
		mtx_lock(&ksem_count_lock);
		if (nsems != 0) {
			error = EOPNOTSUPP;
			mtx_unlock(&ksem_count_lock);
			break;
		}
		ksem_dead = 1;
		mtx_unlock(&ksem_count_lock);
		ksem_module_destroy();
                break;

        case MOD_SHUTDOWN:
                break;
        default:
                error = EINVAL;
                break;
        }
        return (error);
}

static moduledata_t sem_mod = {
        "sem",
        &sem_modload,
        NULL
};

DECLARE_MODULE(sem, sem_mod, SI_SUB_SYSV_SEM, SI_ORDER_FIRST);
MODULE_VERSION(sem, 1);