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