xref: /freebsd/sys/kern/uipc_mqueue.c (revision f0a75d274af375d15b97b830966b99a02b7db911)
1 /*-
2  * Copyright (c) 2005 David Xu <davidxu@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  */
27 
28 /*
29  * POSIX message queue implementation.
30  *
31  * 1) A mqueue filesystem can be mounted, each message queue appears
32  *    in mounted directory, user can change queue's permission and
33  *    ownership, or remove a queue. Manually creating a file in the
34  *    directory causes a message queue to be created in the kernel with
35  *    default message queue attributes applied and same name used, this
36  *    method is not advocated since mq_open syscall allows user to specify
37  *    different attributes. Also the file system can be mounted multiple
38  *    times at different mount points but shows same contents.
39  *
40  * 2) Standard POSIX message queue API. The syscalls do not use vfs layer,
41  *    but directly operate on internal data structure, this allows user to
42  *    use the IPC facility without having to mount mqueue file system.
43  */
44 
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47 
48 #include <sys/param.h>
49 #include <sys/kernel.h>
50 #include <sys/systm.h>
51 #include <sys/limits.h>
52 #include <sys/buf.h>
53 #include <sys/dirent.h>
54 #include <sys/event.h>
55 #include <sys/eventhandler.h>
56 #include <sys/fcntl.h>
57 #include <sys/file.h>
58 #include <sys/filedesc.h>
59 #include <sys/limits.h>
60 #include <sys/lock.h>
61 #include <sys/malloc.h>
62 #include <sys/module.h>
63 #include <sys/mount.h>
64 #include <sys/mqueue.h>
65 #include <sys/mutex.h>
66 #include <sys/namei.h>
67 #include <sys/posix4.h>
68 #include <sys/poll.h>
69 #include <sys/priv.h>
70 #include <sys/proc.h>
71 #include <sys/queue.h>
72 #include <sys/sysproto.h>
73 #include <sys/stat.h>
74 #include <sys/syscall.h>
75 #include <sys/syscallsubr.h>
76 #include <sys/sysent.h>
77 #include <sys/sx.h>
78 #include <sys/sysctl.h>
79 #include <sys/taskqueue.h>
80 #include <sys/unistd.h>
81 #include <sys/vnode.h>
82 #include <machine/atomic.h>
83 
84 /*
85  * Limits and constants
86  */
87 #define	MQFS_NAMELEN		NAME_MAX
88 #define MQFS_DELEN		(8 + MQFS_NAMELEN)
89 
90 /* node types */
91 typedef enum {
92 	mqfstype_none = 0,
93 	mqfstype_root,
94 	mqfstype_dir,
95 	mqfstype_this,
96 	mqfstype_parent,
97 	mqfstype_file,
98 	mqfstype_symlink,
99 } mqfs_type_t;
100 
101 struct mqfs_node;
102 
103 /*
104  * mqfs_info: describes a mqfs instance
105  */
106 struct mqfs_info {
107 	struct sx		mi_lock;
108 	struct mqfs_node	*mi_root;
109 	struct unrhdr		*mi_unrhdr;
110 };
111 
112 struct mqfs_vdata {
113 	LIST_ENTRY(mqfs_vdata)	mv_link;
114 	struct mqfs_node	*mv_node;
115 	struct vnode		*mv_vnode;
116 	struct task		mv_task;
117 };
118 
119 /*
120  * mqfs_node: describes a node (file or directory) within a mqfs
121  */
122 struct mqfs_node {
123 	char			mn_name[MQFS_NAMELEN+1];
124 	struct mqfs_info	*mn_info;
125 	struct mqfs_node	*mn_parent;
126 	LIST_HEAD(,mqfs_node)	mn_children;
127 	LIST_ENTRY(mqfs_node)	mn_sibling;
128 	LIST_HEAD(,mqfs_vdata)	mn_vnodes;
129 	int			mn_refcount;
130 	mqfs_type_t		mn_type;
131 	int			mn_deleted;
132 	u_int32_t		mn_fileno;
133 	void			*mn_data;
134 	struct timespec		mn_birth;
135 	struct timespec		mn_ctime;
136 	struct timespec		mn_atime;
137 	struct timespec		mn_mtime;
138 	uid_t			mn_uid;
139 	gid_t			mn_gid;
140 	int			mn_mode;
141 };
142 
143 #define	VTON(vp)	(((struct mqfs_vdata *)((vp)->v_data))->mv_node)
144 #define VTOMQ(vp) 	((struct mqueue *)(VTON(vp)->mn_data))
145 #define	VFSTOMQFS(m)	((struct mqfs_info *)((m)->mnt_data))
146 #define	FPTOMQ(fp)	((struct mqueue *)(((struct mqfs_node *) \
147 				(fp)->f_data)->mn_data))
148 
149 TAILQ_HEAD(msgq, mqueue_msg);
150 
151 struct mqueue;
152 
153 struct mqueue_notifier {
154 	LIST_ENTRY(mqueue_notifier)	nt_link;
155 	struct sigevent			nt_sigev;
156 	ksiginfo_t			nt_ksi;
157 	struct proc			*nt_proc;
158 };
159 
160 struct mqueue {
161 	struct mtx	mq_mutex;
162 	int		mq_flags;
163 	long		mq_maxmsg;
164 	long		mq_msgsize;
165 	long		mq_curmsgs;
166 	long		mq_totalbytes;
167 	struct msgq	mq_msgq;
168 	int		mq_receivers;
169 	int		mq_senders;
170 	struct selinfo	mq_rsel;
171 	struct selinfo	mq_wsel;
172 	struct mqueue_notifier	*mq_notifier;
173 };
174 
175 #define	MQ_RSEL		0x01
176 #define	MQ_WSEL		0x02
177 
178 struct mqueue_msg {
179 	TAILQ_ENTRY(mqueue_msg)	msg_link;
180 	unsigned int	msg_prio;
181 	unsigned int	msg_size;
182 	/* following real data... */
183 };
184 
185 SYSCTL_NODE(_kern, OID_AUTO, mqueue, CTLFLAG_RW, 0,
186 	"POSIX real time message queue");
187 
188 static int	default_maxmsg  = 10;
189 static int	default_msgsize = 1024;
190 
191 static int	maxmsg = 100;
192 SYSCTL_INT(_kern_mqueue, OID_AUTO, maxmsg, CTLFLAG_RW,
193     &maxmsg, 0, "Default maximum messages in queue");
194 static int	maxmsgsize = 16384;
195 SYSCTL_INT(_kern_mqueue, OID_AUTO, maxmsgsize, CTLFLAG_RW,
196     &maxmsgsize, 0, "Default maximum message size");
197 static int	maxmq = 100;
198 SYSCTL_INT(_kern_mqueue, OID_AUTO, maxmq, CTLFLAG_RW,
199     &maxmq, 0, "maximum message queues");
200 static int	curmq = 0;
201 SYSCTL_INT(_kern_mqueue, OID_AUTO, curmq, CTLFLAG_RW,
202     &curmq, 0, "current message queue number");
203 static int	unloadable = 0;
204 static MALLOC_DEFINE(M_MQUEUEDATA, "mqdata", "mqueue data");
205 
206 static eventhandler_tag exit_tag;
207 
208 /* Only one instance per-system */
209 static struct mqfs_info		mqfs_data;
210 static uma_zone_t		mqnode_zone;
211 static uma_zone_t		mqueue_zone;
212 static uma_zone_t		mvdata_zone;
213 static uma_zone_t		mqnoti_zone;
214 static struct vop_vector	mqfs_vnodeops;
215 static struct fileops		mqueueops;
216 
217 /*
218  * Directory structure construction and manipulation
219  */
220 #ifdef notyet
221 static struct mqfs_node	*mqfs_create_dir(struct mqfs_node *parent,
222 	const char *name, int namelen, struct ucred *cred, int mode);
223 static struct mqfs_node	*mqfs_create_link(struct mqfs_node *parent,
224 	const char *name, int namelen, struct ucred *cred, int mode);
225 #endif
226 
227 static struct mqfs_node	*mqfs_create_file(struct mqfs_node *parent,
228 	const char *name, int namelen, struct ucred *cred, int mode);
229 static int	mqfs_destroy(struct mqfs_node *mn);
230 static void	mqfs_fileno_alloc(struct mqfs_info *mi, struct mqfs_node *mn);
231 static void	mqfs_fileno_free(struct mqfs_info *mi, struct mqfs_node *mn);
232 static int	mqfs_allocv(struct mount *mp, struct vnode **vpp, struct mqfs_node *pn);
233 
234 /*
235  * Message queue construction and maniplation
236  */
237 static struct mqueue	*mqueue_alloc(const struct mq_attr *attr);
238 static void	mqueue_free(struct mqueue *mq);
239 static int	mqueue_send(struct mqueue *mq, const char *msg_ptr,
240 			size_t msg_len, unsigned msg_prio, int waitok,
241 			const struct timespec *abs_timeout);
242 static int	mqueue_receive(struct mqueue *mq, char *msg_ptr,
243 			size_t msg_len, unsigned *msg_prio, int waitok,
244 			const struct timespec *abs_timeout);
245 static int	_mqueue_send(struct mqueue *mq, struct mqueue_msg *msg,
246 			int timo);
247 static int	_mqueue_recv(struct mqueue *mq, struct mqueue_msg **msg,
248 			int timo);
249 static void	mqueue_send_notification(struct mqueue *mq);
250 static void	mqueue_fdclose(struct thread *td, int fd, struct file *fp);
251 static void	mq_proc_exit(void *arg, struct proc *p);
252 
253 /*
254  * kqueue filters
255  */
256 static void	filt_mqdetach(struct knote *kn);
257 static int	filt_mqread(struct knote *kn, long hint);
258 static int	filt_mqwrite(struct knote *kn, long hint);
259 
260 struct filterops mq_rfiltops =
261 	{ 1, NULL, filt_mqdetach, filt_mqread };
262 struct filterops mq_wfiltops =
263 	{ 1, NULL, filt_mqdetach, filt_mqwrite };
264 
265 /*
266  * Initialize fileno bitmap
267  */
268 static void
269 mqfs_fileno_init(struct mqfs_info *mi)
270 {
271 	struct unrhdr *up;
272 
273 	up = new_unrhdr(1, INT_MAX, NULL);
274 	mi->mi_unrhdr = up;
275 }
276 
277 /*
278  * Tear down fileno bitmap
279  */
280 static void
281 mqfs_fileno_uninit(struct mqfs_info *mi)
282 {
283 	struct unrhdr *up;
284 
285 	up = mi->mi_unrhdr;
286 	mi->mi_unrhdr = NULL;
287 	delete_unrhdr(up);
288 }
289 
290 /*
291  * Allocate a file number
292  */
293 static void
294 mqfs_fileno_alloc(struct mqfs_info *mi, struct mqfs_node *mn)
295 {
296 	/* make sure our parent has a file number */
297 	if (mn->mn_parent && !mn->mn_parent->mn_fileno)
298 		mqfs_fileno_alloc(mi, mn->mn_parent);
299 
300 	switch (mn->mn_type) {
301 	case mqfstype_root:
302 	case mqfstype_dir:
303 	case mqfstype_file:
304 	case mqfstype_symlink:
305 		mn->mn_fileno = alloc_unr(mi->mi_unrhdr);
306 		break;
307 	case mqfstype_this:
308 		KASSERT(mn->mn_parent != NULL,
309 		    ("mqfstype_this node has no parent"));
310 		mn->mn_fileno = mn->mn_parent->mn_fileno;
311 		break;
312 	case mqfstype_parent:
313 		KASSERT(mn->mn_parent != NULL,
314 		    ("mqfstype_parent node has no parent"));
315 		if (mn->mn_parent == mi->mi_root) {
316 			mn->mn_fileno = mn->mn_parent->mn_fileno;
317 			break;
318 		}
319 		KASSERT(mn->mn_parent->mn_parent != NULL,
320 		    ("mqfstype_parent node has no grandparent"));
321 		mn->mn_fileno = mn->mn_parent->mn_parent->mn_fileno;
322 		break;
323 	default:
324 		KASSERT(0,
325 		    ("mqfs_fileno_alloc() called for unknown type node: %d",
326 			mn->mn_type));
327 		break;
328 	}
329 }
330 
331 /*
332  * Release a file number
333  */
334 static void
335 mqfs_fileno_free(struct mqfs_info *mi, struct mqfs_node *mn)
336 {
337 	switch (mn->mn_type) {
338 	case mqfstype_root:
339 	case mqfstype_dir:
340 	case mqfstype_file:
341 	case mqfstype_symlink:
342 		free_unr(mi->mi_unrhdr, mn->mn_fileno);
343 		break;
344 	case mqfstype_this:
345 	case mqfstype_parent:
346 		/* ignore these, as they don't "own" their file number */
347 		break;
348 	default:
349 		KASSERT(0,
350 		    ("mqfs_fileno_free() called for unknown type node: %d",
351 			mn->mn_type));
352 		break;
353 	}
354 }
355 
356 static __inline struct mqfs_node *
357 mqnode_alloc(void)
358 {
359 	return uma_zalloc(mqnode_zone, M_WAITOK | M_ZERO);
360 }
361 
362 static __inline void
363 mqnode_free(struct mqfs_node *node)
364 {
365 	uma_zfree(mqnode_zone, node);
366 }
367 
368 static __inline void
369 mqnode_addref(struct mqfs_node *node)
370 {
371 	atomic_fetchadd_int(&node->mn_refcount, 1);
372 }
373 
374 static __inline void
375 mqnode_release(struct mqfs_node *node)
376 {
377 	int old, exp;
378 
379 	old = atomic_fetchadd_int(&node->mn_refcount, -1);
380 	if (node->mn_type == mqfstype_dir ||
381 	    node->mn_type == mqfstype_root)
382 		exp = 3; /* include . and .. */
383 	else
384 		exp = 1;
385 	if (old == exp)
386 		mqfs_destroy(node);
387 }
388 
389 /*
390  * Add a node to a directory
391  */
392 static int
393 mqfs_add_node(struct mqfs_node *parent, struct mqfs_node *node)
394 {
395 	KASSERT(parent != NULL, ("%s(): parent is NULL", __func__));
396 	KASSERT(parent->mn_info != NULL,
397 	    ("%s(): parent has no mn_info", __func__));
398 	KASSERT(parent->mn_type == mqfstype_dir ||
399 	    parent->mn_type == mqfstype_root,
400 	    ("%s(): parent is not a directory", __func__));
401 
402 	node->mn_info = parent->mn_info;
403 	node->mn_parent = parent;
404 	LIST_INIT(&node->mn_children);
405 	LIST_INIT(&node->mn_vnodes);
406 	LIST_INSERT_HEAD(&parent->mn_children, node, mn_sibling);
407 	mqnode_addref(parent);
408 	return (0);
409 }
410 
411 static struct mqfs_node *
412 mqfs_create_node(const char *name, int namelen, struct ucred *cred, int mode,
413 	int nodetype)
414 {
415 	struct mqfs_node *node;
416 
417 	node = mqnode_alloc();
418 	strncpy(node->mn_name, name, namelen);
419 	node->mn_type = nodetype;
420 	node->mn_refcount = 1;
421 	getnanotime(&node->mn_birth);
422 	node->mn_ctime = node->mn_atime = node->mn_mtime
423 		= node->mn_birth;
424 	node->mn_uid = cred->cr_uid;
425 	node->mn_gid = cred->cr_gid;
426 	node->mn_mode = mode;
427 	return (node);
428 }
429 
430 /*
431  * Create a file
432  */
433 static struct mqfs_node *
434 mqfs_create_file(struct mqfs_node *parent, const char *name, int namelen,
435 	struct ucred *cred, int mode)
436 {
437 	struct mqfs_node *node;
438 
439 	node = mqfs_create_node(name, namelen, cred, mode, mqfstype_file);
440 	if (mqfs_add_node(parent, node) != 0) {
441 		mqnode_free(node);
442 		return (NULL);
443 	}
444 	return (node);
445 }
446 
447 /*
448  * Add . and .. to a directory
449  */
450 static int
451 mqfs_fixup_dir(struct mqfs_node *parent)
452 {
453 	struct mqfs_node *dir;
454 
455 	dir = mqnode_alloc();
456 	dir->mn_name[0] = '.';
457 	dir->mn_type = mqfstype_this;
458 	dir->mn_refcount = 1;
459 	if (mqfs_add_node(parent, dir) != 0) {
460 		mqnode_free(dir);
461 		return (-1);
462 	}
463 
464 	dir = mqnode_alloc();
465 	dir->mn_name[0] = dir->mn_name[1] = '.';
466 	dir->mn_type = mqfstype_parent;
467 	dir->mn_refcount = 1;
468 
469 	if (mqfs_add_node(parent, dir) != 0) {
470 		mqnode_free(dir);
471 		return (-1);
472 	}
473 
474 	return (0);
475 }
476 
477 #ifdef notyet
478 
479 /*
480  * Create a directory
481  */
482 static struct mqfs_node *
483 mqfs_create_dir(struct mqfs_node *parent, const char *name, int namelen,
484 	struct ucred *cred, int mode)
485 {
486 	struct mqfs_node *node;
487 
488 	node = mqfs_create_node(name, namelen, cred, mode, mqfstype_dir);
489 	if (mqfs_add_node(parent, node) != 0) {
490 		mqnode_free(node);
491 		return (NULL);
492 	}
493 
494 	if (mqfs_fixup_dir(node) != 0) {
495 		mqfs_destroy(node);
496 		return (NULL);
497 	}
498 	return (node);
499 }
500 
501 /*
502  * Create a symlink
503  */
504 static struct mqfs_node *
505 mqfs_create_link(struct mqfs_node *parent, const char *name, int namelen,
506 	struct ucred *cred, int mode)
507 {
508 	struct mqfs_node *node;
509 
510 	node = mqfs_create_node(name, namelen, cred, mode, mqfstype_symlink);
511 	if (mqfs_add_node(parent, node) != 0) {
512 		mqnode_free(node);
513 		return (NULL);
514 	}
515 	return (node);
516 }
517 
518 #endif
519 
520 /*
521  * Destroy a node or a tree of nodes
522  */
523 static int
524 mqfs_destroy(struct mqfs_node *node)
525 {
526 	struct mqfs_node *parent;
527 
528 	KASSERT(node != NULL,
529 	    ("%s(): node is NULL", __func__));
530 	KASSERT(node->mn_info != NULL,
531 	    ("%s(): node has no mn_info", __func__));
532 
533 	/* destroy children */
534 	if (node->mn_type == mqfstype_dir || node->mn_type == mqfstype_root)
535 		while (! LIST_EMPTY(&node->mn_children))
536 			mqfs_destroy(LIST_FIRST(&node->mn_children));
537 
538 	/* unlink from parent */
539 	if ((parent = node->mn_parent) != NULL) {
540 		KASSERT(parent->mn_info == node->mn_info,
541 		    ("%s(): parent has different mn_info", __func__));
542 		LIST_REMOVE(node, mn_sibling);
543 	}
544 
545 	if (node->mn_fileno != 0)
546 		mqfs_fileno_free(node->mn_info, node);
547 	if (node->mn_data != NULL)
548 		mqueue_free(node->mn_data);
549 	mqnode_free(node);
550 	return (0);
551 }
552 
553 /*
554  * Mount a mqfs instance
555  */
556 static int
557 mqfs_mount(struct mount *mp, struct thread *td)
558 {
559 	struct statfs *sbp;
560 
561 	if (mp->mnt_flag & MNT_UPDATE)
562 		return (EOPNOTSUPP);
563 
564 	mp->mnt_data = &mqfs_data;
565 	MNT_ILOCK(mp);
566 	mp->mnt_flag |= MNT_LOCAL;
567 	mp->mnt_kern_flag |= MNTK_MPSAFE;
568 	MNT_IUNLOCK(mp);
569 	vfs_getnewfsid(mp);
570 
571 	sbp = &mp->mnt_stat;
572 	vfs_mountedfrom(mp, "mqueue");
573 	sbp->f_bsize = PAGE_SIZE;
574 	sbp->f_iosize = PAGE_SIZE;
575 	sbp->f_blocks = 1;
576 	sbp->f_bfree = 0;
577 	sbp->f_bavail = 0;
578 	sbp->f_files = 1;
579 	sbp->f_ffree = 0;
580 	return (0);
581 }
582 
583 /*
584  * Unmount a mqfs instance
585  */
586 static int
587 mqfs_unmount(struct mount *mp, int mntflags, struct thread *td)
588 {
589 	int error;
590 
591 	error = vflush(mp, 0, (mntflags & MNT_FORCE) ?  FORCECLOSE : 0, td);
592 	return (error);
593 }
594 
595 /*
596  * Return a root vnode
597  */
598 static int
599 mqfs_root(struct mount *mp, int flags, struct vnode **vpp, struct thread *td)
600 {
601 	struct mqfs_info *mqfs;
602 	int ret;
603 
604 	mqfs = VFSTOMQFS(mp);
605 	sx_xlock(&mqfs->mi_lock);
606 	ret = mqfs_allocv(mp, vpp, mqfs->mi_root);
607 	sx_xunlock(&mqfs->mi_lock);
608 	return (ret);
609 }
610 
611 /*
612  * Return filesystem stats
613  */
614 static int
615 mqfs_statfs(struct mount *mp, struct statfs *sbp, struct thread *td)
616 {
617 	/* XXX update statistics */
618 	return (0);
619 }
620 
621 /*
622  * Initialize a mqfs instance
623  */
624 static int
625 mqfs_init(struct vfsconf *vfc)
626 {
627 	struct mqfs_node *root;
628 	struct mqfs_info *mi;
629 
630 	mqnode_zone = uma_zcreate("mqnode", sizeof(struct mqfs_node),
631 		NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
632 	mqueue_zone = uma_zcreate("mqueue", sizeof(struct mqueue),
633 		NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
634 	mvdata_zone = uma_zcreate("mvdata",
635 		sizeof(struct mqfs_vdata), NULL, NULL, NULL,
636 		NULL, UMA_ALIGN_PTR, 0);
637 	mqnoti_zone = uma_zcreate("mqnotifier", sizeof(struct mqueue_notifier),
638 		NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
639 	mi = &mqfs_data;
640 	sx_init(&mi->mi_lock, "mqfs lock");
641 	/* set up the root diretory */
642 	root = mqfs_create_node("/", 1, curthread->td_ucred, 01777,
643 		mqfstype_root);
644 	root->mn_info = mi;
645 	LIST_INIT(&root->mn_children);
646 	LIST_INIT(&root->mn_vnodes);
647 	mi->mi_root = root;
648 	mqfs_fileno_init(mi);
649 	mqfs_fileno_alloc(mi, root);
650 	mqfs_fixup_dir(root);
651 	exit_tag = EVENTHANDLER_REGISTER(process_exit, mq_proc_exit, NULL,
652 	    EVENTHANDLER_PRI_ANY);
653 	mq_fdclose = mqueue_fdclose;
654 	p31b_setcfg(CTL_P1003_1B_MESSAGE_PASSING, _POSIX_MESSAGE_PASSING);
655 	return (0);
656 }
657 
658 /*
659  * Destroy a mqfs instance
660  */
661 static int
662 mqfs_uninit(struct vfsconf *vfc)
663 {
664 	struct mqfs_info *mi;
665 
666 	if (!unloadable)
667 		return (EOPNOTSUPP);
668 	EVENTHANDLER_DEREGISTER(process_exit, exit_tag);
669 	mi = &mqfs_data;
670 	mqfs_destroy(mi->mi_root);
671 	mi->mi_root = NULL;
672 	mqfs_fileno_uninit(mi);
673 	sx_destroy(&mi->mi_lock);
674 	uma_zdestroy(mqnode_zone);
675 	uma_zdestroy(mqueue_zone);
676 	uma_zdestroy(mvdata_zone);
677 	uma_zdestroy(mqnoti_zone);
678 	return (0);
679 }
680 
681 /*
682  * task routine
683  */
684 static void
685 do_recycle(void *context, int pending __unused)
686 {
687 	struct vnode *vp = (struct vnode *)context;
688 
689 	vrecycle(vp, curthread);
690 	vdrop(vp);
691 }
692 
693 /*
694  * Allocate a vnode
695  */
696 static int
697 mqfs_allocv(struct mount *mp, struct vnode **vpp, struct mqfs_node *pn)
698 {
699 	struct mqfs_vdata *vd;
700 	int error;
701 
702 	LIST_FOREACH(vd, &pn->mn_vnodes, mv_link) {
703 		if (vd->mv_vnode->v_mount == mp)
704 			break;
705 	}
706 
707 	if (vd != NULL) {
708 		if (vget(vd->mv_vnode, 0, curthread) == 0) {
709 			*vpp = vd->mv_vnode;
710 			vn_lock(*vpp, LK_RETRY | LK_EXCLUSIVE,
711 			    curthread);
712 			return (0);
713 		}
714 		/* XXX if this can happen, we're in trouble */
715 	}
716 
717 	error = getnewvnode("mqueue", mp, &mqfs_vnodeops, vpp);
718 	if (error)
719 		return (error);
720 	vn_lock(*vpp, LK_EXCLUSIVE | LK_RETRY, curthread);
721 	error = insmntque(*vpp, mp);
722 	if (error != 0) {
723 		*vpp = NULLVP;
724 		return (error);
725 	}
726 	vd = uma_zalloc(mvdata_zone, M_WAITOK);
727 	(*vpp)->v_data = vd;
728 	vd->mv_vnode = *vpp;
729 	vd->mv_node = pn;
730 	TASK_INIT(&vd->mv_task, 0, do_recycle, *vpp);
731 	LIST_INSERT_HEAD(&pn->mn_vnodes, vd, mv_link);
732 	mqnode_addref(pn);
733 	switch (pn->mn_type) {
734 	case mqfstype_root:
735 		(*vpp)->v_vflag = VV_ROOT;
736 		/* fall through */
737 	case mqfstype_dir:
738 	case mqfstype_this:
739 	case mqfstype_parent:
740 		(*vpp)->v_type = VDIR;
741 		break;
742 	case mqfstype_file:
743 		(*vpp)->v_type = VREG;
744 		break;
745 	case mqfstype_symlink:
746 		(*vpp)->v_type = VLNK;
747 		break;
748 	case mqfstype_none:
749 		KASSERT(0, ("mqfs_allocf called for null node\n"));
750 	default:
751 		panic("%s has unexpected type: %d", pn->mn_name, pn->mn_type);
752 	}
753 	return (0);
754 }
755 
756 /*
757  * Search a directory entry
758  */
759 static struct mqfs_node *
760 mqfs_search(struct mqfs_node *pd, const char *name, int len)
761 {
762 	struct mqfs_node *pn;
763 
764 	LIST_FOREACH(pn, &pd->mn_children, mn_sibling) {
765 		if (strncmp(pn->mn_name, name, len) == 0)
766 			return (pn);
767 	}
768 	return (NULL);
769 }
770 
771 /*
772  * Look up a file or directory.
773  */
774 static int
775 mqfs_lookupx(struct vop_cachedlookup_args *ap)
776 {
777 	struct componentname *cnp;
778 	struct vnode *dvp, **vpp;
779 	struct mqfs_node *pd;
780 	struct mqfs_node *pn;
781 	int nameiop, flags, error, namelen;
782 	char *pname;
783 	struct thread *td;
784 
785 	cnp = ap->a_cnp;
786 	vpp = ap->a_vpp;
787 	dvp = ap->a_dvp;
788 	pname = cnp->cn_nameptr;
789 	namelen = cnp->cn_namelen;
790 	td = cnp->cn_thread;
791 	flags = cnp->cn_flags;
792 	nameiop = cnp->cn_nameiop;
793 	pd = VTON(dvp);
794 	pn = NULL;
795 	*vpp = NULLVP;
796 
797 	if (dvp->v_type != VDIR)
798 		return (ENOTDIR);
799 
800 	error = VOP_ACCESS(dvp, VEXEC, cnp->cn_cred, cnp->cn_thread);
801 	if (error)
802 		return (error);
803 
804 	/* shortcut: check if the name is too long */
805 	if (cnp->cn_namelen >= MQFS_NAMELEN)
806 		return (ENOENT);
807 
808 	/* self */
809 	if (namelen == 1 && pname[0] == '.') {
810 		if ((flags & ISLASTCN) && nameiop != LOOKUP)
811 			return (EINVAL);
812 		pn = pd;
813 		*vpp = dvp;
814 		VREF(dvp);
815 		return (0);
816 	}
817 
818 	/* parent */
819 	if (cnp->cn_flags & ISDOTDOT) {
820 		if (dvp->v_vflag & VV_ROOT)
821 			return (EIO);
822 		if ((flags & ISLASTCN) && nameiop != LOOKUP)
823 			return (EINVAL);
824 		VOP_UNLOCK(dvp, 0, cnp->cn_thread);
825 		KASSERT(pd->mn_parent, ("non-root directory has no parent"));
826 		pn = pd->mn_parent;
827 		error = mqfs_allocv(dvp->v_mount, vpp, pn);
828 		vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY, td);
829 		return (error);
830 	}
831 
832 	/* named node */
833 	pn = mqfs_search(pd, pname, namelen);
834 
835 	/* found */
836 	if (pn != NULL) {
837 		/* DELETE */
838 		if (nameiop == DELETE && (flags & ISLASTCN)) {
839 			error = VOP_ACCESS(dvp, VWRITE, cnp->cn_cred, td);
840 			if (error)
841 				return (error);
842 			if (*vpp == dvp) {
843 				VREF(dvp);
844 				*vpp = dvp;
845 				return (0);
846 			}
847 		}
848 
849 		/* allocate vnode */
850 		error = mqfs_allocv(dvp->v_mount, vpp, pn);
851 		if (error == 0 && cnp->cn_flags & MAKEENTRY)
852 			cache_enter(dvp, *vpp, cnp);
853 		return (error);
854 	}
855 
856 	/* not found */
857 
858 	/* will create a new entry in the directory ? */
859 	if ((nameiop == CREATE || nameiop == RENAME) && (flags & LOCKPARENT)
860 	    && (flags & ISLASTCN)) {
861 		error = VOP_ACCESS(dvp, VWRITE, cnp->cn_cred, td);
862 		if (error)
863 			return (error);
864 		cnp->cn_flags |= SAVENAME;
865 		return (EJUSTRETURN);
866 	}
867 	return (ENOENT);
868 }
869 
870 #if 0
871 struct vop_lookup_args {
872 	struct vop_generic_args a_gen;
873 	struct vnode *a_dvp;
874 	struct vnode **a_vpp;
875 	struct componentname *a_cnp;
876 };
877 #endif
878 
879 /*
880  * vnode lookup operation
881  */
882 static int
883 mqfs_lookup(struct vop_cachedlookup_args *ap)
884 {
885 	struct mqfs_info *mqfs = VFSTOMQFS(ap->a_dvp->v_mount);
886 	int rc;
887 
888 	sx_xlock(&mqfs->mi_lock);
889 	rc = mqfs_lookupx(ap);
890 	sx_xunlock(&mqfs->mi_lock);
891 	return (rc);
892 }
893 
894 #if 0
895 struct vop_create_args {
896 	struct vnode *a_dvp;
897 	struct vnode **a_vpp;
898 	struct componentname *a_cnp;
899 	struct vattr *a_vap;
900 };
901 #endif
902 
903 /*
904  * vnode creation operation
905  */
906 static int
907 mqfs_create(struct vop_create_args *ap)
908 {
909 	struct mqfs_info *mqfs = VFSTOMQFS(ap->a_dvp->v_mount);
910 	struct componentname *cnp = ap->a_cnp;
911 	struct mqfs_node *pd;
912 	struct mqfs_node *pn;
913 	struct mqueue *mq;
914 	int error;
915 
916 	pd = VTON(ap->a_dvp);
917 	if (pd->mn_type != mqfstype_root && pd->mn_type != mqfstype_dir)
918 		return (ENOTDIR);
919 	mq = mqueue_alloc(NULL);
920 	if (mq == NULL)
921 		return (EAGAIN);
922 	sx_xlock(&mqfs->mi_lock);
923 #if 0
924 	/* named node */
925 	pn = mqfs_search(pd, cnp->cn_nameptr, cnp->cn_namelen);
926 	if (pn != NULL) {
927 		mqueue_free(mq);
928 		sx_xunlock(&mqfs->mi_lock);
929 		return (EEXIST);
930 	}
931 #else
932 	if ((cnp->cn_flags & HASBUF) == 0)
933 		panic("%s: no name", __func__);
934 #endif
935 	pn = mqfs_create_file(pd, cnp->cn_nameptr, cnp->cn_namelen,
936 		cnp->cn_cred, ap->a_vap->va_mode);
937 	if (pn == NULL)
938 		error = ENOSPC;
939 	else {
940 		error = mqfs_allocv(ap->a_dvp->v_mount, ap->a_vpp, pn);
941 		if (error)
942 			mqfs_destroy(pn);
943 		else
944 			pn->mn_data = mq;
945 	}
946 	sx_xunlock(&mqfs->mi_lock);
947 	if (error)
948 		mqueue_free(mq);
949 	return (error);
950 }
951 
952 /*
953  * Remove an entry
954  */
955 static
956 int do_unlink(struct mqfs_node *pn, struct ucred *ucred)
957 {
958 	struct mqfs_node *parent;
959 	struct mqfs_vdata *vd;
960 	int error = 0;
961 
962 	sx_assert(&pn->mn_info->mi_lock, SX_LOCKED);
963 
964 	/*
965 	 * XXXRW: Other instances of the message queue primitive are
966 	 * allowed in jail?
967 	 */
968 	if (ucred->cr_uid != pn->mn_uid &&
969 	    (error = priv_check_cred(ucred, PRIV_MQ_ADMIN, 0)) != 0)
970 		error = EACCES;
971 	else if (!pn->mn_deleted) {
972 		parent = pn->mn_parent;
973 		pn->mn_parent = NULL;
974 		pn->mn_deleted = 1;
975 		LIST_REMOVE(pn, mn_sibling);
976 		LIST_FOREACH(vd, &pn->mn_vnodes, mv_link) {
977 			cache_purge(vd->mv_vnode);
978 			vhold(vd->mv_vnode);
979 			taskqueue_enqueue(taskqueue_thread, &vd->mv_task);
980 		}
981 		mqnode_release(pn);
982 		mqnode_release(parent);
983 	} else
984 		error = ENOENT;
985 	return (error);
986 }
987 
988 #if 0
989 struct vop_remove_args {
990 	struct vnode *a_dvp;
991 	struct vnode *a_vp;
992 	struct componentname *a_cnp;
993 };
994 #endif
995 
996 /*
997  * vnode removal operation
998  */
999 static int
1000 mqfs_remove(struct vop_remove_args *ap)
1001 {
1002 	struct mqfs_info *mqfs = VFSTOMQFS(ap->a_dvp->v_mount);
1003 	struct mqfs_node *pn;
1004 	int error;
1005 
1006 	if (ap->a_vp->v_type == VDIR)
1007                 return (EPERM);
1008 	pn = VTON(ap->a_vp);
1009 	sx_xlock(&mqfs->mi_lock);
1010 	error = do_unlink(pn, ap->a_cnp->cn_cred);
1011 	sx_xunlock(&mqfs->mi_lock);
1012 	return (error);
1013 }
1014 
1015 #if 0
1016 struct vop_inactive_args {
1017 	struct vnode *a_vp;
1018 	struct thread *a_td;
1019 };
1020 #endif
1021 
1022 static int
1023 mqfs_inactive(struct vop_inactive_args *ap)
1024 {
1025 	struct mqfs_node *pn = VTON(ap->a_vp);
1026 
1027 	if (pn->mn_deleted)
1028 		vrecycle(ap->a_vp, ap->a_td);
1029 	return (0);
1030 }
1031 
1032 #if 0
1033 struct vop_reclaim_args {
1034 	struct vop_generic_args a_gen;
1035 	struct vnode *a_vp;
1036 	struct thread *a_td;
1037 };
1038 #endif
1039 
1040 static int
1041 mqfs_reclaim(struct vop_reclaim_args *ap)
1042 {
1043 	struct mqfs_info *mqfs = VFSTOMQFS(ap->a_vp->v_mount);
1044 	struct vnode *vp = ap->a_vp;
1045 	struct mqfs_node *pn;
1046 	struct mqfs_vdata *vd;
1047 
1048 	vd = vp->v_data;
1049 	pn = vd->mv_node;
1050 	sx_xlock(&mqfs->mi_lock);
1051 	vp->v_data = NULL;
1052 	LIST_REMOVE(vd, mv_link);
1053 	uma_zfree(mvdata_zone, vd);
1054 	mqnode_release(pn);
1055 	sx_xunlock(&mqfs->mi_lock);
1056 	return (0);
1057 }
1058 
1059 #if 0
1060 struct vop_open_args {
1061 	struct vop_generic_args a_gen;
1062 	struct vnode *a_vp;
1063 	int a_mode;
1064 	struct ucred *a_cred;
1065 	struct thread *a_td;
1066 	int a_fdidx;
1067 };
1068 #endif
1069 
1070 static int
1071 mqfs_open(struct vop_open_args *ap)
1072 {
1073 	return (0);
1074 }
1075 
1076 #if 0
1077 struct vop_close_args {
1078 	struct vop_generic_args a_gen;
1079 	struct vnode *a_vp;
1080 	int a_fflag;
1081 	struct ucred *a_cred;
1082 	struct thread *a_td;
1083 };
1084 #endif
1085 
1086 static int
1087 mqfs_close(struct vop_close_args *ap)
1088 {
1089 	return (0);
1090 }
1091 
1092 #if 0
1093 struct vop_access_args {
1094 	struct vop_generic_args a_gen;
1095 	struct vnode *a_vp;
1096 	int a_mode;
1097 	struct ucred *a_cred;
1098 	struct thread *a_td;
1099 };
1100 #endif
1101 
1102 /*
1103  * Verify permissions
1104  */
1105 static int
1106 mqfs_access(struct vop_access_args *ap)
1107 {
1108 	struct vnode *vp = ap->a_vp;
1109 	struct vattr vattr;
1110 	int error;
1111 
1112 	error = VOP_GETATTR(vp, &vattr, ap->a_cred, ap->a_td);
1113 	if (error)
1114 		return (error);
1115 	error = vaccess(vp->v_type, vattr.va_mode, vattr.va_uid,
1116 	    vattr.va_gid, ap->a_mode, ap->a_cred, NULL);
1117 	return (error);
1118 }
1119 
1120 #if 0
1121 struct vop_getattr_args {
1122 	struct vop_generic_args a_gen;
1123 	struct vnode *a_vp;
1124 	struct vattr *a_vap;
1125 	struct ucred *a_cred;
1126 	struct thread *a_td;
1127 };
1128 #endif
1129 
1130 /*
1131  * Get file attributes
1132  */
1133 static int
1134 mqfs_getattr(struct vop_getattr_args *ap)
1135 {
1136 	struct vnode *vp = ap->a_vp;
1137 	struct mqfs_node *pn = VTON(vp);
1138 	struct vattr *vap = ap->a_vap;
1139 	int error = 0;
1140 
1141 	VATTR_NULL(vap);
1142 	vap->va_type = vp->v_type;
1143 	vap->va_mode = pn->mn_mode;
1144 	vap->va_nlink = 1;
1145 	vap->va_uid = pn->mn_uid;
1146 	vap->va_gid = pn->mn_gid;
1147 	vap->va_fsid = vp->v_mount->mnt_stat.f_fsid.val[0];
1148 	vap->va_fileid = pn->mn_fileno;
1149 	vap->va_size = 0;
1150 	vap->va_blocksize = PAGE_SIZE;
1151 	vap->va_bytes = vap->va_size = 0;
1152 	vap->va_atime = pn->mn_atime;
1153 	vap->va_mtime = pn->mn_mtime;
1154 	vap->va_ctime = pn->mn_ctime;
1155 	vap->va_birthtime = pn->mn_birth;
1156 	vap->va_gen = 0;
1157 	vap->va_flags = 0;
1158 	vap->va_rdev = 0;
1159 	vap->va_bytes = 0;
1160 	vap->va_filerev = 0;
1161 	vap->va_vaflags = 0;
1162 	return (error);
1163 }
1164 
1165 #if 0
1166 struct vop_setattr_args {
1167 	struct vop_generic_args a_gen;
1168 	struct vnode *a_vp;
1169 	struct vattr *a_vap;
1170 	struct ucred *a_cred;
1171 	struct thread *a_td;
1172 };
1173 #endif
1174 /*
1175  * Set attributes
1176  */
1177 static int
1178 mqfs_setattr(struct vop_setattr_args *ap)
1179 {
1180 	struct mqfs_node *pn;
1181 	struct vattr *vap;
1182 	struct vnode *vp;
1183 	int c, error;
1184 	uid_t uid;
1185 	gid_t gid;
1186 
1187 	vap = ap->a_vap;
1188 	vp = ap->a_vp;
1189 	if ((vap->va_type != VNON) ||
1190 	    (vap->va_nlink != VNOVAL) ||
1191 	    (vap->va_fsid != VNOVAL) ||
1192 	    (vap->va_fileid != VNOVAL) ||
1193 	    (vap->va_blocksize != VNOVAL) ||
1194 	    (vap->va_flags != VNOVAL && vap->va_flags != 0) ||
1195 	    (vap->va_rdev != VNOVAL) ||
1196 	    ((int)vap->va_bytes != VNOVAL) ||
1197 	    (vap->va_gen != VNOVAL)) {
1198 		return (EINVAL);
1199 	}
1200 
1201 	pn = VTON(vp);
1202 
1203 	error = c = 0;
1204 	if (vap->va_uid == (uid_t)VNOVAL)
1205 		uid = pn->mn_uid;
1206 	else
1207 		uid = vap->va_uid;
1208 	if (vap->va_gid == (gid_t)VNOVAL)
1209 		gid = pn->mn_gid;
1210 	else
1211 		gid = vap->va_gid;
1212 
1213 	if (uid != pn->mn_uid || gid != pn->mn_gid) {
1214 		/*
1215 		 * To modify the ownership of a file, must possess VADMIN
1216 		 * for that file.
1217 		 */
1218 		if ((error = VOP_ACCESS(vp, VADMIN, ap->a_cred, ap->a_td)))
1219 			return (error);
1220 
1221 		/*
1222 		 * XXXRW: Why is there a privilege check here: shouldn't the
1223 		 * check in VOP_ACCESS() be enough?  Also, are the group bits
1224 		 * below definitely right?
1225 		 */
1226 		if (((ap->a_cred->cr_uid != pn->mn_uid) || uid != pn->mn_uid ||
1227 		    (gid != pn->mn_gid && !groupmember(gid, ap->a_cred))) &&
1228 		    (error = priv_check_cred(ap->a_td->td_ucred,
1229 		    PRIV_MQ_ADMIN, SUSER_ALLOWJAIL)) != 0)
1230 			return (error);
1231 		pn->mn_uid = uid;
1232 		pn->mn_gid = gid;
1233 		c = 1;
1234 	}
1235 
1236 	if (vap->va_mode != (mode_t)VNOVAL) {
1237 		if ((ap->a_cred->cr_uid != pn->mn_uid) &&
1238 		    (error = priv_check_cred(ap->a_td->td_ucred,
1239 		    PRIV_MQ_ADMIN, SUSER_ALLOWJAIL)))
1240 			return (error);
1241 		pn->mn_mode = vap->va_mode;
1242 		c = 1;
1243 	}
1244 
1245 	if (vap->va_atime.tv_sec != VNOVAL || vap->va_mtime.tv_sec != VNOVAL) {
1246 		/* See the comment in ufs_vnops::ufs_setattr(). */
1247 		if ((error = VOP_ACCESS(vp, VADMIN, ap->a_cred, ap->a_td)) &&
1248 		    ((vap->va_vaflags & VA_UTIMES_NULL) == 0 ||
1249 		    (error = VOP_ACCESS(vp, VWRITE, ap->a_cred, ap->a_td))))
1250 			return (error);
1251 		if (vap->va_atime.tv_sec != VNOVAL) {
1252 			pn->mn_atime = vap->va_atime;
1253 		}
1254 		if (vap->va_mtime.tv_sec != VNOVAL) {
1255 			pn->mn_mtime = vap->va_mtime;
1256 		}
1257 		c = 1;
1258 	}
1259 	if (c) {
1260 		vfs_timestamp(&pn->mn_ctime);
1261 	}
1262 	return (0);
1263 }
1264 
1265 #if 0
1266 struct vop_read_args {
1267 	struct vop_generic_args a_gen;
1268 	struct vnode *a_vp;
1269 	struct uio *a_uio;
1270 	int a_ioflag;
1271 	struct ucred *a_cred;
1272 };
1273 #endif
1274 
1275 /*
1276  * Read from a file
1277  */
1278 static int
1279 mqfs_read(struct vop_read_args *ap)
1280 {
1281 	char buf[80];
1282 	struct vnode *vp = ap->a_vp;
1283 	struct uio *uio = ap->a_uio;
1284 	struct mqfs_node *pn;
1285 	struct mqueue *mq;
1286 	int len, error;
1287 
1288 	if (vp->v_type != VREG)
1289 		return (EINVAL);
1290 
1291 	pn = VTON(vp);
1292 	mq = VTOMQ(vp);
1293 	snprintf(buf, sizeof(buf),
1294 		"QSIZE:%-10ld MAXMSG:%-10ld CURMSG:%-10ld MSGSIZE:%-10ld\n",
1295 		mq->mq_totalbytes,
1296 		mq->mq_maxmsg,
1297 		mq->mq_curmsgs,
1298 		mq->mq_msgsize);
1299 	buf[sizeof(buf)-1] = '\0';
1300 	len = strlen(buf);
1301 	error = uiomove_frombuf(buf, len, uio);
1302 	return (error);
1303 }
1304 
1305 #if 0
1306 struct vop_readdir_args {
1307 	struct vop_generic_args a_gen;
1308 	struct vnode *a_vp;
1309 	struct uio *a_uio;
1310 	struct ucred *a_cred;
1311 	int *a_eofflag;
1312 	int *a_ncookies;
1313 	u_long **a_cookies;
1314 };
1315 #endif
1316 
1317 /*
1318  * Return directory entries.
1319  */
1320 static int
1321 mqfs_readdir(struct vop_readdir_args *ap)
1322 {
1323 	struct vnode *vp;
1324 	struct mqfs_info *mi;
1325 	struct mqfs_node *pd;
1326 	struct mqfs_node *pn;
1327 	struct dirent entry;
1328 	struct uio *uio;
1329 	int *tmp_ncookies = NULL;
1330 	off_t offset;
1331 	int error, i;
1332 
1333 	vp = ap->a_vp;
1334 	mi = VFSTOMQFS(vp->v_mount);
1335 	pd = VTON(vp);
1336 	uio = ap->a_uio;
1337 
1338 	if (vp->v_type != VDIR)
1339 		return (ENOTDIR);
1340 
1341 	if (uio->uio_offset < 0)
1342 		return (EINVAL);
1343 
1344 	if (ap->a_ncookies != NULL) {
1345 		tmp_ncookies = ap->a_ncookies;
1346 		*ap->a_ncookies = 0;
1347 		ap->a_ncookies = NULL;
1348         }
1349 
1350 	error = 0;
1351 	offset = 0;
1352 
1353 	sx_xlock(&mi->mi_lock);
1354 
1355 	LIST_FOREACH(pn, &pd->mn_children, mn_sibling) {
1356 		entry.d_reclen = sizeof(entry);
1357 		if (!pn->mn_fileno)
1358 			mqfs_fileno_alloc(mi, pn);
1359 		entry.d_fileno = pn->mn_fileno;
1360 		for (i = 0; i < MQFS_NAMELEN - 1 && pn->mn_name[i] != '\0'; ++i)
1361 			entry.d_name[i] = pn->mn_name[i];
1362 		entry.d_name[i] = 0;
1363 		entry.d_namlen = i;
1364 		switch (pn->mn_type) {
1365 		case mqfstype_root:
1366 		case mqfstype_dir:
1367 		case mqfstype_this:
1368 		case mqfstype_parent:
1369 			entry.d_type = DT_DIR;
1370 			break;
1371 		case mqfstype_file:
1372 			entry.d_type = DT_REG;
1373 			break;
1374 		case mqfstype_symlink:
1375 			entry.d_type = DT_LNK;
1376 			break;
1377 		default:
1378 			panic("%s has unexpected node type: %d", pn->mn_name,
1379 				pn->mn_type);
1380 		}
1381 		if (entry.d_reclen > uio->uio_resid)
1382                         break;
1383 		if (offset >= uio->uio_offset) {
1384 			error = vfs_read_dirent(ap, &entry, offset);
1385                         if (error)
1386                                 break;
1387                 }
1388                 offset += entry.d_reclen;
1389 	}
1390 	sx_xunlock(&mi->mi_lock);
1391 
1392 	uio->uio_offset = offset;
1393 
1394 	if (tmp_ncookies != NULL)
1395 		ap->a_ncookies = tmp_ncookies;
1396 
1397 	return (error);
1398 }
1399 
1400 #ifdef notyet
1401 
1402 #if 0
1403 struct vop_mkdir_args {
1404 	struct vnode *a_dvp;
1405 	struvt vnode **a_vpp;
1406 	struvt componentname *a_cnp;
1407 	struct vattr *a_vap;
1408 };
1409 #endif
1410 
1411 /*
1412  * Create a directory.
1413  */
1414 static int
1415 mqfs_mkdir(struct vop_mkdir_args *ap)
1416 {
1417 	struct mqfs_info *mqfs = VFSTOMQFS(ap->a_dvp->v_mount);
1418 	struct componentname *cnp = ap->a_cnp;
1419 	struct mqfs_node *pd = VTON(ap->a_dvp);
1420 	struct mqfs_node *pn;
1421 	int error;
1422 
1423 	if (pd->mn_type != mqfstype_root && pd->mn_type != mqfstype_dir)
1424 		return (ENOTDIR);
1425 	sx_xlock(&mqfs->mi_lock);
1426 #if 0
1427 	/* named node */
1428 	pn = mqfs_search(pd, cnp->cn_nameptr, cnp->cn_namelen);
1429 	if (pn != NULL) {
1430 		sx_xunlock(&mqfs->mi_lock);
1431 		return (EEXIST);
1432 	}
1433 #else
1434 	if ((cnp->cn_flags & HASBUF) == 0)
1435 		panic("%s: no name", __func__);
1436 #endif
1437 	pn = mqfs_create_dir(pd, cnp->cn_nameptr, cnp->cn_namelen,
1438 		ap->a_vap->cn_cred, ap->a_vap->va_mode);
1439 	if (pn == NULL)
1440 		error = ENOSPC;
1441 	else
1442 		error = mqfs_allocv(ap->a_dvp->v_mount, ap->a_vpp, pn);
1443 	sx_xunlock(&mqfs->mi_lock);
1444 	return (error);
1445 }
1446 
1447 #if 0
1448 struct vop_rmdir_args {
1449 	struct vnode *a_dvp;
1450 	struct vnode *a_vp;
1451 	struct componentname *a_cnp;
1452 };
1453 #endif
1454 
1455 /*
1456  * Remove a directory.
1457  */
1458 static int
1459 mqfs_rmdir(struct vop_rmdir_args *ap)
1460 {
1461 	struct mqfs_info *mqfs = VFSTOMQFS(ap->a_dvp->v_mount);
1462 	struct mqfs_node *pn = VTON(ap->a_vp);
1463 	struct mqfs_node *pt;
1464 
1465 	if (pn->mn_type != mqfstype_dir)
1466 		return (ENOTDIR);
1467 
1468 	sx_xlock(&mqfs->mi_lock);
1469 	if (pn->mn_deleted) {
1470 		sx_xunlock(&mqfs->mi_lock);
1471 		return (ENOENT);
1472 	}
1473 
1474 	pt = LIST_FIRST(&pn->mn_children);
1475 	pt = LIST_NEXT(pt, mn_sibling);
1476 	pt = LIST_NEXT(pt, mn_sibling);
1477 	if (pt != NULL) {
1478 		sx_xunlock(&mqfs->mi_lock);
1479 		return (ENOTEMPTY);
1480 	}
1481 	pt = pn->mn_parent;
1482 	pn->mn_parent = NULL;
1483 	pn->mn_deleted = 1;
1484 	LIST_REMOVE(pn, mn_sibling);
1485 	mqnode_release(pn);
1486 	mqnode_release(pt);
1487 	sx_xunlock(&mqfs->mi_lock);
1488 	cache_purge(ap->a_vp);
1489 	return (0);
1490 }
1491 
1492 #endif /* notyet */
1493 
1494 /*
1495  * Allocate a message queue
1496  */
1497 static struct mqueue *
1498 mqueue_alloc(const struct mq_attr *attr)
1499 {
1500 	struct mqueue *mq;
1501 
1502 	if (curmq >= maxmq)
1503 		return (NULL);
1504 	mq = uma_zalloc(mqueue_zone, M_WAITOK | M_ZERO);
1505 	TAILQ_INIT(&mq->mq_msgq);
1506 	if (attr != NULL) {
1507 		mq->mq_maxmsg = attr->mq_maxmsg;
1508 		mq->mq_msgsize = attr->mq_msgsize;
1509 	} else {
1510 		mq->mq_maxmsg = default_maxmsg;
1511 		mq->mq_msgsize = default_msgsize;
1512 	}
1513 	mtx_init(&mq->mq_mutex, "mqueue", NULL, MTX_DEF);
1514 	knlist_init(&mq->mq_rsel.si_note, &mq->mq_mutex, NULL, NULL, NULL);
1515 	knlist_init(&mq->mq_wsel.si_note, &mq->mq_mutex, NULL, NULL, NULL);
1516 	atomic_add_int(&curmq, 1);
1517 	return (mq);
1518 }
1519 
1520 /*
1521  * Destroy a message queue
1522  */
1523 static void
1524 mqueue_free(struct mqueue *mq)
1525 {
1526 	struct mqueue_msg *msg;
1527 
1528 	while ((msg = TAILQ_FIRST(&mq->mq_msgq)) != NULL) {
1529 		TAILQ_REMOVE(&mq->mq_msgq, msg, msg_link);
1530 		FREE(msg, M_MQUEUEDATA);
1531 	}
1532 
1533 	mtx_destroy(&mq->mq_mutex);
1534 	knlist_destroy(&mq->mq_rsel.si_note);
1535 	knlist_destroy(&mq->mq_wsel.si_note);
1536 	uma_zfree(mqueue_zone, mq);
1537 	atomic_add_int(&curmq, -1);
1538 }
1539 
1540 /*
1541  * Load a message from user space
1542  */
1543 static struct mqueue_msg *
1544 mqueue_loadmsg(const char *msg_ptr, size_t msg_size, int msg_prio)
1545 {
1546 	struct mqueue_msg *msg;
1547 	size_t len;
1548 	int error;
1549 
1550 	len = sizeof(struct mqueue_msg) + msg_size;
1551 	MALLOC(msg, struct mqueue_msg *, len, M_MQUEUEDATA, M_WAITOK);
1552 	error = copyin(msg_ptr, ((char *)msg) + sizeof(struct mqueue_msg),
1553 	    msg_size);
1554 	if (error) {
1555 		FREE(msg, M_MQUEUEDATA);
1556 		msg = NULL;
1557 	} else {
1558 		msg->msg_size = msg_size;
1559 		msg->msg_prio = msg_prio;
1560 	}
1561 	return (msg);
1562 }
1563 
1564 /*
1565  * Save a message to user space
1566  */
1567 static int
1568 mqueue_savemsg(struct mqueue_msg *msg, char *msg_ptr, int *msg_prio)
1569 {
1570 	int error;
1571 
1572 	error = copyout(((char *)msg) + sizeof(*msg), msg_ptr,
1573 		msg->msg_size);
1574 	if (error == 0 && msg_prio != NULL)
1575 		error = copyout(&msg->msg_prio, msg_prio, sizeof(int));
1576 	return (error);
1577 }
1578 
1579 /*
1580  * Free a message's memory
1581  */
1582 static __inline void
1583 mqueue_freemsg(struct mqueue_msg *msg)
1584 {
1585 	FREE(msg, M_MQUEUEDATA);
1586 }
1587 
1588 /*
1589  * Send a message. if waitok is false, thread will not be
1590  * blocked if there is no data in queue, otherwise, absolute
1591  * time will be checked.
1592  */
1593 int
1594 mqueue_send(struct mqueue *mq, const char *msg_ptr,
1595 	size_t msg_len, unsigned msg_prio, int waitok,
1596 	const struct timespec *abs_timeout)
1597 {
1598 	struct mqueue_msg *msg;
1599 	struct timespec ets, ts, ts2;
1600 	struct timeval tv;
1601 	int error;
1602 
1603 	if (msg_prio >= MQ_PRIO_MAX)
1604 		return (EINVAL);
1605 	if (msg_len > mq->mq_msgsize)
1606 		return (EMSGSIZE);
1607 	msg = mqueue_loadmsg(msg_ptr, msg_len, msg_prio);
1608 	if (msg == NULL)
1609 		return (EFAULT);
1610 
1611 	/* O_NONBLOCK case */
1612 	if (!waitok) {
1613 		error = _mqueue_send(mq, msg, -1);
1614 		if (error)
1615 			goto bad;
1616 		return (0);
1617 	}
1618 
1619 	/* we allow a null timeout (wait forever) */
1620 	if (abs_timeout == NULL) {
1621 		error = _mqueue_send(mq, msg, 0);
1622 		if (error)
1623 			goto bad;
1624 		return (0);
1625 	}
1626 
1627 	/* send it before checking time */
1628 	error = _mqueue_send(mq, msg, -1);
1629 	if (error == 0)
1630 		return (0);
1631 
1632 	if (error != EAGAIN)
1633 		goto bad;
1634 
1635 	error = copyin(abs_timeout, &ets, sizeof(ets));
1636 	if (error != 0)
1637 		goto bad;
1638 	if (ets.tv_nsec >= 1000000000 || ets.tv_nsec < 0) {
1639 		error = EINVAL;
1640 		goto bad;
1641 	}
1642 	for (;;) {
1643 		ts2 = ets;
1644 		getnanotime(&ts);
1645 		timespecsub(&ts2, &ts);
1646 		if (ts2.tv_sec < 0 || (ts2.tv_sec == 0 && ts2.tv_nsec <= 0)) {
1647 			error = ETIMEDOUT;
1648 			break;
1649 		}
1650 		TIMESPEC_TO_TIMEVAL(&tv, &ts2);
1651 		error = _mqueue_send(mq, msg, tvtohz(&tv));
1652 		if (error != ETIMEDOUT)
1653 			break;
1654 	}
1655 	if (error == 0)
1656 		return (0);
1657 bad:
1658 	mqueue_freemsg(msg);
1659 	return (error);
1660 }
1661 
1662 /*
1663  * Common routine to send a message
1664  */
1665 static int
1666 _mqueue_send(struct mqueue *mq, struct mqueue_msg *msg, int timo)
1667 {
1668 	struct mqueue_msg *msg2;
1669 	int error = 0;
1670 
1671 	mtx_lock(&mq->mq_mutex);
1672 	while (mq->mq_curmsgs >= mq->mq_maxmsg && error == 0) {
1673 		if (timo < 0) {
1674 			mtx_unlock(&mq->mq_mutex);
1675 			return (EAGAIN);
1676 		}
1677 		mq->mq_senders++;
1678 		error = msleep(&mq->mq_senders, &mq->mq_mutex,
1679 			    PCATCH, "mqsend", timo);
1680 		mq->mq_senders--;
1681 		if (error == EAGAIN)
1682 			error = ETIMEDOUT;
1683 	}
1684 	if (mq->mq_curmsgs >= mq->mq_maxmsg) {
1685 		mtx_unlock(&mq->mq_mutex);
1686 		return (error);
1687 	}
1688 	error = 0;
1689 	if (TAILQ_EMPTY(&mq->mq_msgq)) {
1690 		TAILQ_INSERT_HEAD(&mq->mq_msgq, msg, msg_link);
1691 	} else {
1692 		if (msg->msg_prio <= TAILQ_LAST(&mq->mq_msgq, msgq)->msg_prio) {
1693 			TAILQ_INSERT_TAIL(&mq->mq_msgq, msg, msg_link);
1694 		} else {
1695 			TAILQ_FOREACH(msg2, &mq->mq_msgq, msg_link) {
1696 				if (msg2->msg_prio < msg->msg_prio)
1697 					break;
1698 			}
1699 			TAILQ_INSERT_BEFORE(msg2, msg, msg_link);
1700 		}
1701 	}
1702 	mq->mq_curmsgs++;
1703 	mq->mq_totalbytes += msg->msg_size;
1704 	if (mq->mq_receivers)
1705 		wakeup_one(&mq->mq_receivers);
1706 	else if (mq->mq_notifier != NULL)
1707 		mqueue_send_notification(mq);
1708 	if (mq->mq_flags & MQ_RSEL) {
1709 		mq->mq_flags &= ~MQ_RSEL;
1710 		selwakeup(&mq->mq_rsel);
1711 	}
1712 	KNOTE_LOCKED(&mq->mq_rsel.si_note, 0);
1713 	mtx_unlock(&mq->mq_mutex);
1714 	return (0);
1715 }
1716 
1717 /*
1718  * Send realtime a signal to process which registered itself
1719  * successfully by mq_notify.
1720  */
1721 static void
1722 mqueue_send_notification(struct mqueue *mq)
1723 {
1724 	struct mqueue_notifier *nt;
1725 	struct proc *p;
1726 
1727 	mtx_assert(&mq->mq_mutex, MA_OWNED);
1728 	nt = mq->mq_notifier;
1729 	if (nt->nt_sigev.sigev_notify != SIGEV_NONE) {
1730 		p = nt->nt_proc;
1731 		PROC_LOCK(p);
1732 		if (!KSI_ONQ(&nt->nt_ksi))
1733 			psignal_event(p, &nt->nt_sigev, &nt->nt_ksi);
1734 		PROC_UNLOCK(p);
1735 	}
1736 	mq->mq_notifier = NULL;
1737 }
1738 
1739 /*
1740  * Get a message. if waitok is false, thread will not be
1741  * blocked if there is no data in queue, otherwise, absolute
1742  * time will be checked.
1743  */
1744 int
1745 mqueue_receive(struct mqueue *mq, char *msg_ptr,
1746 	size_t msg_len, unsigned *msg_prio, int waitok,
1747 	const struct timespec *abs_timeout)
1748 {
1749 	struct mqueue_msg *msg;
1750 	struct timespec ets, ts, ts2;
1751 	struct timeval tv;
1752 	int error;
1753 
1754 	if (msg_len < mq->mq_msgsize)
1755 		return (EMSGSIZE);
1756 
1757 	/* O_NONBLOCK case */
1758 	if (!waitok) {
1759 		error = _mqueue_recv(mq, &msg, -1);
1760 		if (error)
1761 			return (error);
1762 		goto received;
1763 	}
1764 
1765 	/* we allow a null timeout (wait forever). */
1766 	if (abs_timeout == NULL) {
1767 		error = _mqueue_recv(mq, &msg, 0);
1768 		if (error)
1769 			return (error);
1770 		goto received;
1771 	}
1772 
1773 	/* try to get a message before checking time */
1774 	error = _mqueue_recv(mq, &msg, -1);
1775 	if (error == 0)
1776 		goto received;
1777 
1778 	if (error != EAGAIN)
1779 		return (error);
1780 
1781 	error = copyin(abs_timeout, &ets, sizeof(ets));
1782 	if (error != 0)
1783 		return (error);
1784 	if (ets.tv_nsec >= 1000000000 || ets.tv_nsec < 0) {
1785 		error = EINVAL;
1786 		return (error);
1787 	}
1788 
1789 	for (;;) {
1790 		ts2 = ets;
1791 		getnanotime(&ts);
1792 		timespecsub(&ts2, &ts);
1793 		if (ts2.tv_sec < 0 || (ts2.tv_sec == 0 && ts2.tv_nsec <= 0)) {
1794 			error = ETIMEDOUT;
1795 			return (error);
1796 		}
1797 		TIMESPEC_TO_TIMEVAL(&tv, &ts2);
1798 		error = _mqueue_recv(mq, &msg, tvtohz(&tv));
1799 		if (error == 0)
1800 			break;
1801 		if (error != ETIMEDOUT)
1802 			return (error);
1803 	}
1804 
1805 received:
1806 	error = mqueue_savemsg(msg, msg_ptr, msg_prio);
1807 	if (error == 0) {
1808 		curthread->td_retval[0] = msg->msg_size;
1809 		curthread->td_retval[1] = 0;
1810 	}
1811 	mqueue_freemsg(msg);
1812 	return (error);
1813 }
1814 
1815 /*
1816  * Common routine to receive a message
1817  */
1818 static int
1819 _mqueue_recv(struct mqueue *mq, struct mqueue_msg **msg, int timo)
1820 {
1821 	int error = 0;
1822 
1823 	mtx_lock(&mq->mq_mutex);
1824 	while ((*msg = TAILQ_FIRST(&mq->mq_msgq)) == NULL && error == 0) {
1825 		if (timo < 0) {
1826 			mtx_unlock(&mq->mq_mutex);
1827 			return (EAGAIN);
1828 		}
1829 		mq->mq_receivers++;
1830 		error = msleep(&mq->mq_receivers, &mq->mq_mutex,
1831 			    PCATCH, "mqrecv", timo);
1832 		mq->mq_receivers--;
1833 		if (error == EAGAIN)
1834 			error = ETIMEDOUT;
1835 	}
1836 	if (*msg != NULL) {
1837 		error = 0;
1838 		TAILQ_REMOVE(&mq->mq_msgq, *msg, msg_link);
1839 		mq->mq_curmsgs--;
1840 		mq->mq_totalbytes -= (*msg)->msg_size;
1841 		if (mq->mq_senders)
1842 			wakeup_one(&mq->mq_senders);
1843 		if (mq->mq_flags & MQ_WSEL) {
1844 			mq->mq_flags &= ~MQ_WSEL;
1845 			selwakeup(&mq->mq_wsel);
1846 		}
1847 		KNOTE_LOCKED(&mq->mq_wsel.si_note, 0);
1848 	}
1849 	if (mq->mq_notifier != NULL && mq->mq_receivers == 0 &&
1850 	    !TAILQ_EMPTY(&mq->mq_msgq)) {
1851 		mqueue_send_notification(mq);
1852 	}
1853 	mtx_unlock(&mq->mq_mutex);
1854 	return (error);
1855 }
1856 
1857 static __inline struct mqueue_notifier *
1858 notifier_alloc(void)
1859 {
1860 	return (uma_zalloc(mqnoti_zone, M_WAITOK | M_ZERO));
1861 }
1862 
1863 static __inline void
1864 notifier_free(struct mqueue_notifier *p)
1865 {
1866 	uma_zfree(mqnoti_zone, p);
1867 }
1868 
1869 static struct mqueue_notifier *
1870 notifier_search(struct proc *p, int fd)
1871 {
1872 	struct mqueue_notifier *nt;
1873 
1874 	LIST_FOREACH(nt, &p->p_mqnotifier, nt_link) {
1875 		if (nt->nt_ksi.ksi_mqd == fd)
1876 			break;
1877 	}
1878 	return (nt);
1879 }
1880 
1881 static __inline void
1882 notifier_insert(struct proc *p, struct mqueue_notifier *nt)
1883 {
1884 	LIST_INSERT_HEAD(&p->p_mqnotifier, nt, nt_link);
1885 }
1886 
1887 static __inline void
1888 notifier_delete(struct proc *p, struct mqueue_notifier *nt)
1889 {
1890 	LIST_REMOVE(nt, nt_link);
1891 	notifier_free(nt);
1892 }
1893 
1894 static void
1895 notifier_remove(struct proc *p, struct mqueue *mq, int fd)
1896 {
1897 	struct mqueue_notifier *nt;
1898 
1899 	mtx_assert(&mq->mq_mutex, MA_OWNED);
1900 	PROC_LOCK(p);
1901 	nt = notifier_search(p, fd);
1902 	if (nt != NULL) {
1903 		if (mq->mq_notifier == nt)
1904 			mq->mq_notifier = NULL;
1905 		sigqueue_take(&nt->nt_ksi);
1906 		notifier_delete(p, nt);
1907 	}
1908 	PROC_UNLOCK(p);
1909 }
1910 
1911 /*
1912  * Syscall to open a message queue.
1913  */
1914 int
1915 kmq_open(struct thread *td, struct kmq_open_args *uap)
1916 {
1917 	char path[MQFS_NAMELEN + 1];
1918 	struct mq_attr attr, *pattr;
1919 	struct mqfs_node *pn;
1920 	struct filedesc *fdp;
1921 	struct file *fp;
1922 	struct mqueue *mq;
1923 	int fd, error, len, flags, cmode;
1924 
1925 	if ((uap->flags & O_ACCMODE) == O_ACCMODE)
1926 		return (EINVAL);
1927 
1928 	fdp = td->td_proc->p_fd;
1929 	flags = FFLAGS(uap->flags);
1930 	cmode = (((uap->mode & ~fdp->fd_cmask) & ALLPERMS) & ~S_ISTXT);
1931 	mq = NULL;
1932 	if ((flags & O_CREAT) && (uap->attr != NULL)) {
1933 		error = copyin(uap->attr, &attr, sizeof(attr));
1934 		if (error)
1935 			return (error);
1936 		if (attr.mq_maxmsg <= 0 || attr.mq_maxmsg > maxmsg)
1937 			return (EINVAL);
1938 		if (attr.mq_msgsize <= 0 || attr.mq_msgsize > maxmsgsize)
1939 			return (EINVAL);
1940 		pattr = &attr;
1941 	} else
1942 		pattr = NULL;
1943 
1944 	error = copyinstr(uap->path, path, MQFS_NAMELEN + 1, NULL);
1945         if (error)
1946 		return (error);
1947 
1948 	/*
1949 	 * The first character of name must be a slash  (/) character
1950 	 * and the remaining characters of name cannot include any slash
1951 	 * characters.
1952 	 */
1953 	len = strlen(path);
1954 	if (len < 2  || path[0] != '/' || index(path + 1, '/') != NULL)
1955 		return (EINVAL);
1956 
1957 	error = falloc(td, &fp, &fd);
1958 	if (error)
1959 		return (error);
1960 
1961 	sx_xlock(&mqfs_data.mi_lock);
1962 	pn = mqfs_search(mqfs_data.mi_root, path + 1, len - 1);
1963 	if (pn == NULL) {
1964 		if (!(flags & O_CREAT)) {
1965 			error = ENOENT;
1966 		} else {
1967 			mq = mqueue_alloc(pattr);
1968 			if (mq == NULL) {
1969 				error = ENFILE;
1970 			} else {
1971 				pn = mqfs_create_file(mqfs_data.mi_root,
1972 				         path + 1, len - 1, td->td_ucred,
1973 					 cmode);
1974 				if (pn == NULL) {
1975 					error = ENOSPC;
1976 					mqueue_free(mq);
1977 				}
1978 			}
1979 		}
1980 
1981 		if (error == 0) {
1982 			pn->mn_data = mq;
1983 		}
1984 	} else {
1985 		if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) {
1986 			error = EEXIST;
1987 		} else {
1988 			int acc_mode = 0;
1989 
1990 			if (flags & FREAD)
1991 				acc_mode |= VREAD;
1992 			if (flags & FWRITE)
1993 				acc_mode |= VWRITE;
1994 			error = vaccess(VREG, pn->mn_mode, pn->mn_uid,
1995 				    pn->mn_gid, acc_mode, td->td_ucred, NULL);
1996 		}
1997 	}
1998 
1999 	if (error) {
2000 		sx_xunlock(&mqfs_data.mi_lock);
2001 		fdclose(fdp, fp, fd, td);
2002 		fdrop(fp, td);
2003 		return (error);
2004 	}
2005 
2006 	mqnode_addref(pn);
2007 	sx_xunlock(&mqfs_data.mi_lock);
2008 
2009 	FILE_LOCK(fp);
2010 	fp->f_flag = (flags & (FREAD | FWRITE | O_NONBLOCK));
2011 	fp->f_type = DTYPE_MQUEUE;
2012 	fp->f_data = pn;
2013 	fp->f_ops = &mqueueops;
2014 	FILE_UNLOCK(fp);
2015 
2016 	FILEDESC_XLOCK(fdp);
2017 	if (fdp->fd_ofiles[fd] == fp)
2018 		fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
2019 	FILEDESC_XUNLOCK(fdp);
2020 	td->td_retval[0] = fd;
2021 	fdrop(fp, td);
2022 	return (0);
2023 }
2024 
2025 /*
2026  * Syscall to unlink a message queue.
2027  */
2028 int
2029 kmq_unlink(struct thread *td, struct kmq_unlink_args *uap)
2030 {
2031 	char path[MQFS_NAMELEN+1];
2032 	struct mqfs_node *pn;
2033 	int error, len;
2034 
2035 	error = copyinstr(uap->path, path, MQFS_NAMELEN + 1, NULL);
2036         if (error)
2037 		return (error);
2038 
2039 	len = strlen(path);
2040 	if (len < 2  || path[0] != '/' || index(path + 1, '/') != NULL)
2041 		return (EINVAL);
2042 
2043 	sx_xlock(&mqfs_data.mi_lock);
2044 	pn = mqfs_search(mqfs_data.mi_root, path + 1, len - 1);
2045 	if (pn != NULL)
2046 		error = do_unlink(pn, td->td_ucred);
2047 	else
2048 		error = ENOENT;
2049 	sx_xunlock(&mqfs_data.mi_lock);
2050 	return (error);
2051 }
2052 
2053 typedef int (*_fgetf)(struct thread *, int, struct file **);
2054 
2055 /*
2056  * Get message queue by giving file slot
2057  */
2058 static int
2059 _getmq(struct thread *td, int fd, _fgetf func,
2060        struct file **fpp, struct mqfs_node **ppn, struct mqueue **pmq)
2061 {
2062 	struct mqfs_node *pn;
2063 	int error;
2064 
2065 	error = func(td, fd, fpp);
2066 	if (error)
2067 		return (error);
2068 	if (&mqueueops != (*fpp)->f_ops) {
2069 		fdrop(*fpp, td);
2070 		return (EBADF);
2071 	}
2072 	pn = (*fpp)->f_data;
2073 	if (ppn)
2074 		*ppn = pn;
2075 	if (pmq)
2076 		*pmq = pn->mn_data;
2077 	return (0);
2078 }
2079 
2080 static __inline int
2081 getmq(struct thread *td, int fd, struct file **fpp, struct mqfs_node **ppn,
2082 	struct mqueue **pmq)
2083 {
2084 	return _getmq(td, fd, fget, fpp, ppn, pmq);
2085 }
2086 
2087 static __inline int
2088 getmq_read(struct thread *td, int fd, struct file **fpp,
2089 	 struct mqfs_node **ppn, struct mqueue **pmq)
2090 {
2091 	return _getmq(td, fd, fget_read, fpp, ppn, pmq);
2092 }
2093 
2094 static __inline int
2095 getmq_write(struct thread *td, int fd, struct file **fpp,
2096 	struct mqfs_node **ppn, struct mqueue **pmq)
2097 {
2098 	return _getmq(td, fd, fget_write, fpp, ppn, pmq);
2099 }
2100 
2101 int
2102 kmq_setattr(struct thread *td, struct kmq_setattr_args *uap)
2103 {
2104 	struct mqueue *mq;
2105 	struct file *fp;
2106 	struct mq_attr attr, oattr;
2107 	int error;
2108 
2109 	if (uap->attr) {
2110 		error = copyin(uap->attr, &attr, sizeof(attr));
2111 		if (error)
2112 			return (error);
2113 		if (attr.mq_flags & ~O_NONBLOCK)
2114 			return (EINVAL);
2115 	}
2116 	error = getmq(td, uap->mqd, &fp, NULL, &mq);
2117 	if (error)
2118 		return (error);
2119 	oattr.mq_maxmsg  = mq->mq_maxmsg;
2120 	oattr.mq_msgsize = mq->mq_msgsize;
2121 	oattr.mq_curmsgs = mq->mq_curmsgs;
2122 	FILE_LOCK(fp);
2123 	oattr.mq_flags = (O_NONBLOCK & fp->f_flag);
2124 	if (uap->attr) {
2125 		fp->f_flag &= ~O_NONBLOCK;
2126 		fp->f_flag |= (attr.mq_flags & O_NONBLOCK);
2127 	}
2128 	FILE_UNLOCK(fp);
2129 	fdrop(fp, td);
2130 	if (uap->oattr)
2131 		error = copyout(&oattr, uap->oattr, sizeof(oattr));
2132 	return (error);
2133 }
2134 
2135 int
2136 kmq_timedreceive(struct thread *td, struct kmq_timedreceive_args *uap)
2137 {
2138 	struct mqueue *mq;
2139 	struct file *fp;
2140 	int error;
2141 	int waitok;
2142 
2143 	error = getmq_read(td, uap->mqd, &fp, NULL, &mq);
2144 	if (error)
2145 		return (error);
2146 	waitok = !(fp->f_flag & O_NONBLOCK);
2147 	error = mqueue_receive(mq, uap->msg_ptr, uap->msg_len,
2148 		uap->msg_prio, waitok, uap->abs_timeout);
2149 	fdrop(fp, td);
2150 	return (error);
2151 }
2152 
2153 int
2154 kmq_timedsend(struct thread *td, struct kmq_timedsend_args *uap)
2155 {
2156 	struct mqueue *mq;
2157 	struct file *fp;
2158 	int error, waitok;
2159 
2160 	error = getmq_write(td, uap->mqd, &fp, NULL, &mq);
2161 	if (error)
2162 		return (error);
2163 	waitok = !(fp->f_flag & O_NONBLOCK);
2164 	error = mqueue_send(mq, uap->msg_ptr, uap->msg_len,
2165 		uap->msg_prio, waitok, uap->abs_timeout);
2166 	fdrop(fp, td);
2167 	return (error);
2168 }
2169 
2170 int
2171 kmq_notify(struct thread *td, struct kmq_notify_args *uap)
2172 {
2173 	struct sigevent ev;
2174 	struct filedesc *fdp;
2175 	struct proc *p;
2176 	struct mqueue *mq;
2177 	struct file *fp;
2178 	struct mqueue_notifier *nt, *newnt = NULL;
2179 	int error;
2180 
2181 	p = td->td_proc;
2182 	fdp = td->td_proc->p_fd;
2183 	if (uap->sigev) {
2184 		error = copyin(uap->sigev, &ev, sizeof(ev));
2185 		if (error)
2186 			return (error);
2187 		if (ev.sigev_notify != SIGEV_SIGNAL &&
2188 		    ev.sigev_notify != SIGEV_THREAD_ID &&
2189 		    ev.sigev_notify != SIGEV_NONE)
2190 			return (EINVAL);
2191 		if ((ev.sigev_notify == SIGEV_SIGNAL ||
2192 		     ev.sigev_notify == SIGEV_THREAD_ID) &&
2193 			!_SIG_VALID(ev.sigev_signo))
2194 			return (EINVAL);
2195 	}
2196 	error = getmq(td, uap->mqd, &fp, NULL, &mq);
2197 	if (error)
2198 		return (error);
2199 again:
2200 	FILEDESC_SLOCK(fdp);
2201 	if (fget_locked(fdp, uap->mqd) != fp) {
2202 		FILEDESC_SUNLOCK(fdp);
2203 		error = EBADF;
2204 		goto out;
2205 	}
2206 	mtx_lock(&mq->mq_mutex);
2207 	FILEDESC_SUNLOCK(fdp);
2208 	if (uap->sigev != NULL) {
2209 		if (mq->mq_notifier != NULL) {
2210 			error = EBUSY;
2211 		} else {
2212 			PROC_LOCK(p);
2213 			nt = notifier_search(p, uap->mqd);
2214 			if (nt == NULL) {
2215 				if (newnt == NULL) {
2216 					PROC_UNLOCK(p);
2217 					mtx_unlock(&mq->mq_mutex);
2218 					newnt = notifier_alloc();
2219 					goto again;
2220 				}
2221 			}
2222 
2223 			if (nt != NULL) {
2224 				sigqueue_take(&nt->nt_ksi);
2225 				if (newnt != NULL) {
2226 					notifier_free(newnt);
2227 					newnt = NULL;
2228 				}
2229 			} else {
2230 				nt = newnt;
2231 				newnt = NULL;
2232 				ksiginfo_init(&nt->nt_ksi);
2233 				nt->nt_ksi.ksi_flags |= KSI_INS | KSI_EXT;
2234 				nt->nt_ksi.ksi_code = SI_MESGQ;
2235 				nt->nt_proc = p;
2236 				nt->nt_ksi.ksi_mqd = uap->mqd;
2237 				notifier_insert(p, nt);
2238 			}
2239 			nt->nt_sigev = ev;
2240 			mq->mq_notifier = nt;
2241 			PROC_UNLOCK(p);
2242 			/*
2243 			 * if there is no receivers and message queue
2244 			 * is not empty, we should send notification
2245 			 * as soon as possible.
2246 			 */
2247 			if (mq->mq_receivers == 0 &&
2248 			    !TAILQ_EMPTY(&mq->mq_msgq))
2249 				mqueue_send_notification(mq);
2250 		}
2251 	} else {
2252 		notifier_remove(p, mq, uap->mqd);
2253 	}
2254 	mtx_unlock(&mq->mq_mutex);
2255 
2256 out:
2257 	fdrop(fp, td);
2258 	if (newnt != NULL)
2259 		notifier_free(newnt);
2260 	return (error);
2261 }
2262 
2263 static void
2264 mqueue_fdclose(struct thread *td, int fd, struct file *fp)
2265 {
2266 	struct filedesc *fdp;
2267 	struct mqueue *mq;
2268 
2269 	fdp = td->td_proc->p_fd;
2270 	FILEDESC_LOCK_ASSERT(fdp);
2271 
2272 	if (fp->f_ops == &mqueueops) {
2273 		mq = FPTOMQ(fp);
2274 		mtx_lock(&mq->mq_mutex);
2275 		notifier_remove(td->td_proc, mq, fd);
2276 
2277 		/* have to wakeup thread in same process */
2278 		if (mq->mq_flags & MQ_RSEL) {
2279 			mq->mq_flags &= ~MQ_RSEL;
2280 			selwakeup(&mq->mq_rsel);
2281 		}
2282 		if (mq->mq_flags & MQ_WSEL) {
2283 			mq->mq_flags &= ~MQ_WSEL;
2284 			selwakeup(&mq->mq_wsel);
2285 		}
2286 		mtx_unlock(&mq->mq_mutex);
2287 	}
2288 }
2289 
2290 static void
2291 mq_proc_exit(void *arg __unused, struct proc *p)
2292 {
2293 	struct filedesc *fdp;
2294 	struct file *fp;
2295 	struct mqueue *mq;
2296 	int i;
2297 
2298 	fdp = p->p_fd;
2299 	FILEDESC_SLOCK(fdp);
2300 	for (i = 0; i < fdp->fd_nfiles; ++i) {
2301 		fp = fget_locked(fdp, i);
2302 		if (fp != NULL && fp->f_ops == &mqueueops) {
2303 			mq = FPTOMQ(fp);
2304 			mtx_lock(&mq->mq_mutex);
2305 			notifier_remove(p, FPTOMQ(fp), i);
2306 			mtx_unlock(&mq->mq_mutex);
2307 		}
2308 	}
2309 	FILEDESC_SUNLOCK(fdp);
2310 	KASSERT(LIST_EMPTY(&p->p_mqnotifier), ("mq notifiers left"));
2311 }
2312 
2313 static int
2314 mqf_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
2315 	int flags, struct thread *td)
2316 {
2317 	return (EOPNOTSUPP);
2318 }
2319 
2320 static int
2321 mqf_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
2322 	int flags, struct thread *td)
2323 {
2324 	return (EOPNOTSUPP);
2325 }
2326 
2327 static int
2328 mqf_ioctl(struct file *fp, u_long cmd, void *data,
2329 	struct ucred *active_cred, struct thread *td)
2330 {
2331 	return (ENOTTY);
2332 }
2333 
2334 static int
2335 mqf_poll(struct file *fp, int events, struct ucred *active_cred,
2336 	struct thread *td)
2337 {
2338 	struct mqueue *mq = FPTOMQ(fp);
2339 	int revents = 0;
2340 
2341 	mtx_lock(&mq->mq_mutex);
2342 	if (events & (POLLIN | POLLRDNORM)) {
2343 		if (mq->mq_curmsgs) {
2344 			revents |= events & (POLLIN | POLLRDNORM);
2345 		} else {
2346 			mq->mq_flags |= MQ_RSEL;
2347 			selrecord(td, &mq->mq_rsel);
2348  		}
2349 	}
2350 	if (events & POLLOUT) {
2351 		if (mq->mq_curmsgs < mq->mq_maxmsg)
2352 			revents |= POLLOUT;
2353 		else {
2354 			mq->mq_flags |= MQ_WSEL;
2355 			selrecord(td, &mq->mq_wsel);
2356 		}
2357 	}
2358 	mtx_unlock(&mq->mq_mutex);
2359 	return (revents);
2360 }
2361 
2362 static int
2363 mqf_close(struct file *fp, struct thread *td)
2364 {
2365 	struct mqfs_node *pn;
2366 
2367 	fp->f_ops = &badfileops;
2368 	pn = fp->f_data;
2369 	fp->f_data = NULL;
2370 	sx_xlock(&mqfs_data.mi_lock);
2371 	mqnode_release(pn);
2372 	sx_xunlock(&mqfs_data.mi_lock);
2373 	return (0);
2374 }
2375 
2376 static int
2377 mqf_stat(struct file *fp, struct stat *st, struct ucred *active_cred,
2378 	struct thread *td)
2379 {
2380 	struct mqfs_node *pn = fp->f_data;
2381 
2382 	bzero(st, sizeof *st);
2383 	st->st_atimespec = pn->mn_atime;
2384 	st->st_mtimespec = pn->mn_mtime;
2385 	st->st_ctimespec = pn->mn_ctime;
2386 	st->st_birthtimespec = pn->mn_birth;
2387 	st->st_uid = pn->mn_uid;
2388 	st->st_gid = pn->mn_gid;
2389 	st->st_mode = S_IFIFO | pn->mn_mode;
2390 	return (0);
2391 }
2392 
2393 static int
2394 mqf_kqfilter(struct file *fp, struct knote *kn)
2395 {
2396 	struct mqueue *mq = FPTOMQ(fp);
2397 	int error = 0;
2398 
2399 	if (kn->kn_filter == EVFILT_READ) {
2400 		kn->kn_fop = &mq_rfiltops;
2401 		knlist_add(&mq->mq_rsel.si_note, kn, 0);
2402 	} else if (kn->kn_filter == EVFILT_WRITE) {
2403 		kn->kn_fop = &mq_wfiltops;
2404 		knlist_add(&mq->mq_wsel.si_note, kn, 0);
2405 	} else
2406 		error = EINVAL;
2407 	return (error);
2408 }
2409 
2410 static void
2411 filt_mqdetach(struct knote *kn)
2412 {
2413 	struct mqueue *mq = FPTOMQ(kn->kn_fp);
2414 
2415 	if (kn->kn_filter == EVFILT_READ)
2416 		knlist_remove(&mq->mq_rsel.si_note, kn, 0);
2417 	else if (kn->kn_filter == EVFILT_WRITE)
2418 		knlist_remove(&mq->mq_wsel.si_note, kn, 0);
2419 	else
2420 		panic("filt_mqdetach");
2421 }
2422 
2423 static int
2424 filt_mqread(struct knote *kn, long hint)
2425 {
2426 	struct mqueue *mq = FPTOMQ(kn->kn_fp);
2427 
2428 	mtx_assert(&mq->mq_mutex, MA_OWNED);
2429 	return (mq->mq_curmsgs != 0);
2430 }
2431 
2432 static int
2433 filt_mqwrite(struct knote *kn, long hint)
2434 {
2435 	struct mqueue *mq = FPTOMQ(kn->kn_fp);
2436 
2437 	mtx_assert(&mq->mq_mutex, MA_OWNED);
2438 	return (mq->mq_curmsgs < mq->mq_maxmsg);
2439 }
2440 
2441 static struct fileops mqueueops = {
2442 	.fo_read		= mqf_read,
2443 	.fo_write		= mqf_write,
2444 	.fo_ioctl		= mqf_ioctl,
2445 	.fo_poll		= mqf_poll,
2446 	.fo_kqfilter		= mqf_kqfilter,
2447 	.fo_stat		= mqf_stat,
2448 	.fo_close		= mqf_close
2449 };
2450 
2451 static struct vop_vector mqfs_vnodeops = {
2452 	.vop_default 		= &default_vnodeops,
2453 	.vop_access		= mqfs_access,
2454 	.vop_cachedlookup	= mqfs_lookup,
2455 	.vop_lookup		= vfs_cache_lookup,
2456 	.vop_reclaim		= mqfs_reclaim,
2457 	.vop_create		= mqfs_create,
2458 	.vop_remove		= mqfs_remove,
2459 	.vop_inactive		= mqfs_inactive,
2460 	.vop_open		= mqfs_open,
2461 	.vop_close		= mqfs_close,
2462 	.vop_getattr		= mqfs_getattr,
2463 	.vop_setattr		= mqfs_setattr,
2464 	.vop_read		= mqfs_read,
2465 	.vop_write		= VOP_EOPNOTSUPP,
2466 	.vop_readdir		= mqfs_readdir,
2467 	.vop_mkdir		= VOP_EOPNOTSUPP,
2468 	.vop_rmdir		= VOP_EOPNOTSUPP
2469 };
2470 
2471 static struct vfsops mqfs_vfsops = {
2472 	.vfs_init 		= mqfs_init,
2473 	.vfs_uninit		= mqfs_uninit,
2474 	.vfs_mount		= mqfs_mount,
2475 	.vfs_unmount		= mqfs_unmount,
2476 	.vfs_root		= mqfs_root,
2477 	.vfs_statfs		= mqfs_statfs,
2478 };
2479 
2480 SYSCALL_MODULE_HELPER(kmq_open);
2481 SYSCALL_MODULE_HELPER(kmq_setattr);
2482 SYSCALL_MODULE_HELPER(kmq_timedsend);
2483 SYSCALL_MODULE_HELPER(kmq_timedreceive);
2484 SYSCALL_MODULE_HELPER(kmq_notify);
2485 SYSCALL_MODULE_HELPER(kmq_unlink);
2486 
2487 VFS_SET(mqfs_vfsops, mqueuefs, VFCF_SYNTHETIC);
2488 MODULE_VERSION(mqueuefs, 1);
2489