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