kernel -- Prevent POSIX MQ from overflowing malloc zones.
[dragonfly.git] / sys / kern / sys_mqueue.c
1 /*      $NetBSD: sys_mqueue.c,v 1.16 2009/04/11 23:05:26 christos Exp $ */
2
3 /*
4  * Copyright (c) 2007, 2008 Mindaugas Rasiukevicius <rmind at NetBSD org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 /*
30  * Implementation of POSIX message queues.
31  * Defined in the Base Definitions volume of IEEE Std 1003.1-2001.
32  *
33  * Locking
34  *
35  * Global list of message queues (mqueue_head) and proc_t::p_mqueue_cnt
36  * counter are protected by mqlist_mtx lock.  The very message queue and
37  * its members are protected by mqueue::mq_mtx.
38  *
39  * Lock order:
40  *      mqlist_mtx
41  *        -> mqueue::mq_mtx
42  */
43
44 #include <stdbool.h>
45 #include <sys/param.h>
46 #include <sys/types.h>
47 #include <sys/errno.h>
48 #include <sys/fcntl.h>
49 #include <sys/file.h>
50 #include <sys/filedesc.h>
51 #include <sys/ucred.h>
52 #include <sys/priv.h>
53 #include <sys/kernel.h>
54 #include <sys/malloc.h>
55 #include <sys/mplock2.h>
56 #include <sys/mqueue.h>
57 #include <sys/objcache.h>
58 #include <sys/proc.h>
59 #include <sys/queue.h>
60 #include <sys/event.h>
61 #include <sys/serialize.h>
62 #include <sys/signal.h>
63 #include <sys/signalvar.h>
64 #include <sys/spinlock.h>
65 #include <sys/spinlock2.h>
66 #include <sys/stat.h>
67 #include <sys/sysctl.h>
68 #include <sys/sysproto.h>
69 #include <sys/systm.h>
70 #include <sys/lock.h>
71 #include <sys/unistd.h>
72 #include <sys/vnode.h>
73
74 /* System-wide limits. */
75 static u_int                    mq_open_max = MQ_OPEN_MAX;
76 static u_int                    mq_prio_max = MQ_PRIO_MAX;
77 static u_int                    mq_max_msgsize = 16 * MQ_DEF_MSGSIZE;
78 static u_int                    mq_def_maxmsg = 32;
79 static u_int                    mq_max_maxmsg = 16 * 32;
80
81 struct lock                     mqlist_mtx;
82 static struct objcache *        mqmsg_cache;
83 static LIST_HEAD(, mqueue)      mqueue_head =
84         LIST_HEAD_INITIALIZER(mqueue_head);
85
86 typedef struct  file file_t;    /* XXX: Should we put this in sys/types.h ? */
87
88 /* Function prototypes */
89 static int      mq_stat_fop(file_t *, struct stat *, struct ucred *cred);
90 static int      mq_close_fop(file_t *);
91 static int      mq_kqfilter_fop(struct file *fp, struct knote *kn);
92 static void     mqfilter_read_detach(struct knote *kn);
93 static void     mqfilter_write_detach(struct knote *kn);
94 static int      mqfilter_read(struct knote *kn, long hint);
95 static int      mqfilter_write(struct knote *kn, long hint);
96
97 /* Some time-related utility functions */
98 static int      itimespecfix(struct timespec *ts);
99 static int      tstohz(const struct timespec *ts);
100
101 /* File operations vector */
102 static struct fileops mqops = {
103         .fo_read = badfo_readwrite,
104         .fo_write = badfo_readwrite,
105         .fo_ioctl = badfo_ioctl,
106         .fo_stat = mq_stat_fop,
107         .fo_close = mq_close_fop,
108         .fo_kqfilter = mq_kqfilter_fop,
109         .fo_shutdown = badfo_shutdown
110 };
111
112 /* Define a new malloc type for message queues */
113 MALLOC_DECLARE(M_MQBUF);
114 MALLOC_DEFINE(M_MQBUF, "mqueues", "Buffers to message queues");
115
116 /* Malloc arguments for object cache */
117 struct objcache_malloc_args mqueue_malloc_args = {
118         sizeof(struct mqueue), M_MQBUF };
119
120 /*
121  * Initialize POSIX message queue subsystem.
122  */
123 void
124 mqueue_sysinit(void)
125 {
126         mqmsg_cache = objcache_create("mqmsg_cache",
127             0,          /* infinite depot's capacity */
128             0,          /* default magazine's capacity */
129             NULL,       /* constructor */
130             NULL,       /* deconstructor */
131             NULL,
132             objcache_malloc_alloc,
133             objcache_malloc_free,
134             &mqueue_malloc_args);
135
136         lockinit(&mqlist_mtx, "mqlist_mtx", 0, LK_CANRECURSE);
137 }
138
139 /*
140  * Free the message.
141  */
142 static void
143 mqueue_freemsg(struct mq_msg *msg, const size_t size)
144 {
145
146         if (size > MQ_DEF_MSGSIZE) {
147                 kfree(msg, M_MQBUF);
148         } else {
149                 objcache_put(mqmsg_cache, msg);
150         }
151 }
152
153 /*
154  * Destroy the message queue.
155  */
156 static void
157 mqueue_destroy(struct mqueue *mq)
158 {
159         struct mq_msg *msg;
160         size_t msz;
161         u_int i;
162
163         /* Note MQ_PQSIZE + 1. */
164         for (i = 0; i < MQ_PQSIZE + 1; i++) {
165                 while ((msg = TAILQ_FIRST(&mq->mq_head[i])) != NULL) {
166                         TAILQ_REMOVE(&mq->mq_head[i], msg, msg_queue);
167                         msz = sizeof(struct mq_msg) + msg->msg_len;
168                         mqueue_freemsg(msg, msz);
169                 }
170         }
171         lockuninit(&mq->mq_mtx);
172         kfree(mq, M_MQBUF);
173 }
174
175 /*
176  * Lookup for file name in general list of message queues.
177  *  => locks the message queue
178  */
179 static void *
180 mqueue_lookup(char *name)
181 {
182         struct mqueue *mq;
183
184         KKASSERT(lockstatus(&mqlist_mtx, curthread));
185
186         LIST_FOREACH(mq, &mqueue_head, mq_list) {
187                 if (strncmp(mq->mq_name, name, MQ_NAMELEN) == 0) {
188                         lockmgr(&mq->mq_mtx, LK_EXCLUSIVE);
189                         return mq;
190                 }
191         }
192
193         return NULL;
194 }
195
196 /*
197  * mqueue_get: get the mqueue from the descriptor.
198  *  => locks the message queue, if found.
199  *  => holds a reference on the file descriptor.
200  */
201 static int
202 mqueue_get(struct lwp *l, mqd_t mqd, file_t **fpr)
203 {
204         struct mqueue *mq;
205         file_t *fp;
206
207         fp = holdfp(curproc->p_fd, (int)mqd, -1);       /* XXX: Why -1 ? */
208         if (__predict_false(fp == NULL))
209                 return EBADF;
210
211         if (__predict_false(fp->f_type != DTYPE_MQUEUE)) {
212                 fdrop(fp);
213                 return EBADF;
214         }
215         mq = fp->f_data;
216         lockmgr(&mq->mq_mtx, LK_EXCLUSIVE);
217
218         *fpr = fp;
219         return 0;
220 }
221
222 /*
223  * mqueue_linear_insert: perform linear insert according to the message
224  * priority into the reserved queue (MQ_PQRESQ).  Reserved queue is a
225  * sorted list used only when mq_prio_max is increased via sysctl.
226  */
227 static inline void
228 mqueue_linear_insert(struct mqueue *mq, struct mq_msg *msg)
229 {
230         struct mq_msg *mit;
231
232         TAILQ_FOREACH(mit, &mq->mq_head[MQ_PQRESQ], msg_queue) {
233                 if (msg->msg_prio > mit->msg_prio)
234                         break;
235         }
236         if (mit == NULL) {
237                 TAILQ_INSERT_TAIL(&mq->mq_head[MQ_PQRESQ], msg, msg_queue);
238         } else {
239                 TAILQ_INSERT_BEFORE(mit, msg, msg_queue);
240         }
241 }
242
243 /*
244  * Validate input.
245  */
246 int
247 itimespecfix(struct timespec *ts)
248 {
249         if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
250                 return (EINVAL);
251         if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < nstick)
252                 ts->tv_nsec = nstick;
253         return (0);
254 }
255
256 /*
257  * Compute number of ticks in the specified amount of time.
258  */
259 int
260 tstohz(const struct timespec *ts)
261 {
262         struct timeval tv;
263
264         /*
265          * usec has great enough resolution for hz, so convert to a
266          * timeval and use tvtohz() above.
267          */
268         TIMESPEC_TO_TIMEVAL(&tv, ts);
269         return tvtohz_high(&tv);        /* XXX Why _high() and not _low() ? */
270 }
271
272 /*
273  * Converter from struct timespec to the ticks.
274  * Used by mq_timedreceive(), mq_timedsend().
275  */
276 int
277 abstimeout2timo(struct timespec *ts, int *timo)
278 {
279         struct timespec tsd;
280         int error;
281
282         error = itimespecfix(ts);
283         if (error) {
284                 return error;
285         }
286         getnanotime(&tsd);
287         timespecsub(ts, &tsd);
288         if (ts->tv_sec < 0 || (ts->tv_sec == 0 && ts->tv_nsec <= 0)) {
289                 return ETIMEDOUT;
290         }
291         *timo = tstohz(ts);
292         KKASSERT(*timo != 0);
293
294         return 0;
295 }
296
297 static int
298 mq_stat_fop(file_t *fp, struct stat *st, struct ucred *cred)
299 {
300         struct mqueue *mq = fp->f_data;
301
302         (void)memset(st, 0, sizeof(*st));
303
304         lockmgr(&mq->mq_mtx, LK_EXCLUSIVE);
305         st->st_mode = mq->mq_mode;
306         st->st_uid = mq->mq_euid;
307         st->st_gid = mq->mq_egid;
308         st->st_atimespec = mq->mq_atime;
309         st->st_mtimespec = mq->mq_mtime;
310         /*st->st_ctimespec = st->st_birthtimespec = mq->mq_btime;*/
311         st->st_uid = fp->f_cred->cr_uid;
312         st->st_gid = fp->f_cred->cr_svgid;
313         lockmgr(&mq->mq_mtx, LK_RELEASE);
314
315         return 0;
316 }
317
318 static struct filterops mqfiltops_read =
319         { FILTEROP_ISFD, NULL, mqfilter_read_detach, mqfilter_read };
320 static struct filterops mqfiltops_write =
321         { FILTEROP_ISFD, NULL, mqfilter_write_detach, mqfilter_write };
322
323 static int
324 mq_kqfilter_fop(struct file *fp, struct knote *kn)
325 {
326         struct mqueue *mq = fp->f_data;
327         struct klist *klist;
328
329         lockmgr(&mq->mq_mtx, LK_EXCLUSIVE);
330
331         switch (kn->kn_filter) {
332         case EVFILT_READ:
333                 kn->kn_fop = &mqfiltops_read;
334                 kn->kn_hook = (caddr_t)mq;
335                 klist = &mq->mq_rkq.ki_note;
336                 break;
337         case EVFILT_WRITE:
338                 kn->kn_fop = &mqfiltops_write;
339                 kn->kn_hook = (caddr_t)mq;
340                 klist = &mq->mq_wkq.ki_note;
341                 break;
342         default:
343                 lockmgr(&mq->mq_mtx, LK_RELEASE);
344                 return (EOPNOTSUPP);
345         }
346
347         knote_insert(klist, kn);
348         lockmgr(&mq->mq_mtx, LK_RELEASE);
349
350         return (0);
351 }
352
353 static void
354 mqfilter_read_detach(struct knote *kn)
355 {
356         struct mqueue *mq = (struct mqueue *)kn->kn_hook;
357
358         lockmgr(&mq->mq_mtx, LK_EXCLUSIVE);
359         struct klist *klist = &mq->mq_rkq.ki_note;
360         knote_remove(klist, kn);
361         lockmgr(&mq->mq_mtx, LK_RELEASE);
362 }
363
364 static void
365 mqfilter_write_detach(struct knote *kn)
366 {
367         struct mqueue *mq = (struct mqueue *)kn->kn_hook;
368
369         lockmgr(&mq->mq_mtx, LK_EXCLUSIVE);
370         struct klist *klist = &mq->mq_wkq.ki_note;
371         knote_remove(klist, kn);
372         lockmgr(&mq->mq_mtx, LK_RELEASE);
373 }
374
375 static int
376 mqfilter_read(struct knote *kn, long hint)
377 {
378         struct mqueue *mq = (struct mqueue *)kn->kn_hook;
379         struct mq_attr *mqattr;
380         int ready = 0;
381
382         lockmgr(&mq->mq_mtx, LK_EXCLUSIVE);
383         mqattr = &mq->mq_attrib;
384         /* Ready for receiving, if there are messages in the queue */
385         if (mqattr->mq_curmsgs)
386                 ready = 1;
387         lockmgr(&mq->mq_mtx, LK_RELEASE);
388
389         return (ready);
390 }
391
392 static int
393 mqfilter_write(struct knote *kn, long hint)
394 {
395         struct mqueue *mq = (struct mqueue *)kn->kn_hook;
396         struct mq_attr *mqattr;
397         int ready = 0;
398
399         lockmgr(&mq->mq_mtx, LK_EXCLUSIVE);
400         mqattr = &mq->mq_attrib;
401         /* Ready for sending, if the message queue is not full */
402         if (mqattr->mq_curmsgs < mqattr->mq_maxmsg)
403                 ready = 1;
404         lockmgr(&mq->mq_mtx, LK_RELEASE);
405
406         return (ready);
407 }
408
409 static int
410 mq_close_fop(file_t *fp)
411 {
412         struct proc *p = curproc;
413         struct mqueue *mq = fp->f_data;
414         bool destroy;
415
416         lockmgr(&mqlist_mtx, LK_EXCLUSIVE);
417         lockmgr(&mq->mq_mtx, LK_EXCLUSIVE);
418
419         /* Decrease the counters */
420         p->p_mqueue_cnt--;
421         mq->mq_refcnt--;
422
423         /* Remove notification if registered for this process */
424         if (mq->mq_notify_proc == p)
425                 mq->mq_notify_proc = NULL;
426
427         /*
428          * If this is the last reference and mqueue is marked for unlink,
429          * remove and later destroy the message queue.
430          */
431         if (mq->mq_refcnt == 0 && (mq->mq_attrib.mq_flags & MQ_UNLINK)) {
432                 LIST_REMOVE(mq, mq_list);
433                 destroy = true;
434         } else
435                 destroy = false;
436
437         lockmgr(&mq->mq_mtx, LK_RELEASE);
438         lockmgr(&mqlist_mtx, LK_RELEASE);
439
440         if (destroy)
441                 mqueue_destroy(mq);
442
443         return 0;
444 }
445
446 /*
447  * General mqueue system calls.
448  */
449
450 int
451 sys_mq_open(struct mq_open_args *uap)
452 {
453         /* {
454                 syscallarg(const char *) name;
455                 syscallarg(int) oflag;
456                 syscallarg(mode_t) mode;
457                 syscallarg(struct mq_attr) attr;
458         } */
459         struct thread *td = curthread;
460         struct proc *p = td->td_proc;
461         struct filedesc *fdp = p->p_fd;
462         struct mqueue *mq, *mq_new = NULL;
463         file_t *fp;
464         char *name;
465         int mqd, error, oflag;
466
467         /* Check access mode flags */
468         oflag = SCARG(uap, oflag);
469         if ((oflag & O_ACCMODE) == (O_WRONLY | O_RDWR)) {
470                 return EINVAL;
471         }
472
473         /* Get the name from the user-space */
474         name = kmalloc(MQ_NAMELEN, M_MQBUF, M_WAITOK | M_ZERO | M_NULLOK);
475         if (name == NULL)
476                 return (ENOMEM);
477         error = copyinstr(SCARG(uap, name), name, MQ_NAMELEN - 1, NULL);
478         if (error) {
479                 kfree(name, M_MQBUF);
480                 return error;
481         }
482
483         if (oflag & O_CREAT) {
484                 struct mq_attr attr;
485                 u_int i;
486
487                 /* Check the limit */
488                 if (p->p_mqueue_cnt == mq_open_max) {
489                         kfree(name, M_MQBUF);
490                         return EMFILE;
491                 }
492
493                 /* Empty name is invalid */
494                 if (name[0] == '\0') {
495                         kfree(name, M_MQBUF);
496                         return EINVAL;
497                 }
498
499                 /* Check for mqueue attributes */
500                 if (SCARG(uap, attr)) {
501                         error = copyin(SCARG(uap, attr), &attr,
502                                 sizeof(struct mq_attr));
503                         if (error) {
504                                 kfree(name, M_MQBUF);
505                                 return error;
506                         }
507                         if (attr.mq_maxmsg <= 0 ||
508                             attr.mq_maxmsg > mq_max_maxmsg ||
509                             attr.mq_msgsize <= 0 ||
510                             attr.mq_msgsize > mq_max_msgsize) {
511                                 kfree(name, M_MQBUF);
512                                 return EINVAL;
513                         }
514                         attr.mq_curmsgs = 0;
515                 } else {
516                         memset(&attr, 0, sizeof(struct mq_attr));
517                         attr.mq_maxmsg = mq_def_maxmsg;
518                         attr.mq_msgsize =
519                             MQ_DEF_MSGSIZE - sizeof(struct mq_msg);
520                 }
521
522                 /*
523                  * Allocate new mqueue, initialize data structures,
524                  * copy the name, attributes and set the flag.
525                  */
526                 mq_new = kmalloc(sizeof(struct mqueue), M_MQBUF, 
527                                         M_WAITOK | M_ZERO | M_NULLOK);
528                 if (mq_new == NULL) {
529                         kfree(name, M_MQBUF);
530                         return (ENOMEM);
531                 }
532
533                 lockinit(&mq_new->mq_mtx, "mq_new->mq_mtx", 0, LK_CANRECURSE);
534                 for (i = 0; i < (MQ_PQSIZE + 1); i++) {
535                         TAILQ_INIT(&mq_new->mq_head[i]);
536                 }
537
538                 strlcpy(mq_new->mq_name, name, MQ_NAMELEN);
539                 memcpy(&mq_new->mq_attrib, &attr, sizeof(struct mq_attr));
540
541                 /*CTASSERT((O_MASK & (MQ_UNLINK | MQ_RECEIVE)) == 0);*/
542                 /* mq_new->mq_attrib.mq_flags = (O_MASK & oflag); */
543                 mq_new->mq_attrib.mq_flags = oflag;
544
545                 /* Store mode and effective UID with GID */
546                 mq_new->mq_mode = ((SCARG(uap, mode) &
547                     ~p->p_fd->fd_cmask) & ALLPERMS) & ~S_ISTXT;
548                 mq_new->mq_euid = td->td_ucred->cr_uid;
549                 mq_new->mq_egid = td->td_ucred->cr_svgid;
550         }
551
552         /* Allocate file structure and descriptor */
553         error = falloc(td->td_lwp, &fp, &mqd);
554         if (error) {
555                 if (mq_new)
556                         mqueue_destroy(mq_new);
557                 kfree(name, M_MQBUF);
558                 return error;
559         }
560         fp->f_type = DTYPE_MQUEUE;
561         fp->f_flag = FFLAGS(oflag) & (FREAD | FWRITE);
562         fp->f_ops = &mqops;
563
564         /* Look up for mqueue with such name */
565         lockmgr(&mqlist_mtx, LK_EXCLUSIVE);
566         mq = mqueue_lookup(name);
567         if (mq) {
568                 int acc_mode;
569
570                 KKASSERT(lockstatus(&mq->mq_mtx, curthread));
571
572                 /* Check if mqueue is not marked as unlinking */
573                 if (mq->mq_attrib.mq_flags & MQ_UNLINK) {
574                         error = EACCES;
575                         goto exit;
576                 }
577                 /* Fail if O_EXCL is set, and mqueue already exists */
578                 if ((oflag & O_CREAT) && (oflag & O_EXCL)) {
579                         error = EEXIST;
580                         goto exit;
581                 }
582
583                 /*
584                  * Check the permissions. Note the difference between
585                  * VREAD/VWRITE and FREAD/FWRITE.
586                  */
587                 acc_mode = 0;
588                 if (fp->f_flag & FREAD) {
589                         acc_mode |= VREAD;
590                 }
591                 if (fp->f_flag & FWRITE) {
592                         acc_mode |= VWRITE;
593                 }
594                 if (vaccess(VNON, mq->mq_mode, mq->mq_euid, mq->mq_egid,
595                         acc_mode, td->td_ucred)) {
596
597                         error = EACCES;
598                         goto exit;
599                 }
600         } else {
601                 /* Fail if mqueue neither exists, nor we create it */
602                 if ((oflag & O_CREAT) == 0) {
603                         lockmgr(&mqlist_mtx, LK_RELEASE);
604                         KKASSERT(mq_new == NULL);
605                         fsetfd(fdp, NULL, mqd);
606                         fp->f_ops = &badfileops;
607                         fdrop(fp);
608                         kfree(name, M_MQBUF);
609                         return ENOENT;
610                 }
611
612                 /* Check the limit */
613                 if (p->p_mqueue_cnt == mq_open_max) {
614                         error = EMFILE;
615                         goto exit;
616                 }
617
618                 /* Insert the queue to the list */
619                 mq = mq_new;
620                 lockmgr(&mq->mq_mtx, LK_EXCLUSIVE);
621                 LIST_INSERT_HEAD(&mqueue_head, mq, mq_list);
622                 mq_new = NULL;
623                 getnanotime(&mq->mq_btime);
624                 mq->mq_atime = mq->mq_mtime = mq->mq_btime;
625         }
626
627         /* Increase the counters, and make descriptor ready */
628         p->p_mqueue_cnt++;
629         mq->mq_refcnt++;
630         fp->f_data = mq;
631 exit:
632         lockmgr(&mq->mq_mtx, LK_RELEASE);
633         lockmgr(&mqlist_mtx, LK_RELEASE);
634
635         if (mq_new)
636                 mqueue_destroy(mq_new);
637         if (error) {
638                 fsetfd(fdp, NULL, mqd);
639                 fp->f_ops = &badfileops;
640         } else {
641                 fsetfd(fdp, fp, mqd);
642                 uap->sysmsg_result = mqd;
643         }
644         fdrop(fp);
645         kfree(name, M_MQBUF);
646
647         return error;
648 }
649
650 int
651 sys_mq_close(struct mq_close_args *uap)
652 {
653         return sys_close((void *)uap);
654 }
655
656 /*
657  * Primary mq_receive1() function.
658  */
659 int
660 mq_receive1(struct lwp *l, mqd_t mqdes, void *msg_ptr, size_t msg_len,
661     unsigned *msg_prio, struct timespec *ts, ssize_t *mlen)
662 {
663         file_t *fp = NULL;
664         struct mqueue *mq;
665         struct mq_msg *msg = NULL;
666         struct mq_attr *mqattr;
667         u_int idx;
668         int error;
669
670         /* Get the message queue */
671         error = mqueue_get(l, mqdes, &fp);
672         if (error) {
673                 return error;
674         }
675         mq = fp->f_data;
676         if ((fp->f_flag & FREAD) == 0) {
677                 error = EBADF;
678                 goto error;
679         }
680         getnanotime(&mq->mq_atime);
681         mqattr = &mq->mq_attrib;
682
683         /* Check the message size limits */
684         if (msg_len < mqattr->mq_msgsize) {
685                 error = EMSGSIZE;
686                 goto error;
687         }
688
689         /* Check if queue is empty */
690         while (mqattr->mq_curmsgs == 0) {
691                 int t;
692
693                 if (mqattr->mq_flags & O_NONBLOCK) {
694                         error = EAGAIN;
695                         goto error;
696                 }
697                 if (ts) {
698                         error = abstimeout2timo(ts, &t);
699                         if (error)
700                                 goto error;
701                 } else
702                         t = 0;
703                 /*
704                  * Block until someone sends the message.
705                  * While doing this, notification should not be sent.
706                  */
707                 mqattr->mq_flags |= MQ_RECEIVE;
708                 error = lksleep(&mq->mq_send_cv, &mq->mq_mtx, PCATCH, "mqsend", t);
709                 mqattr->mq_flags &= ~MQ_RECEIVE;
710                 if (error || (mqattr->mq_flags & MQ_UNLINK)) {
711                         error = (error == EWOULDBLOCK) ? ETIMEDOUT : EINTR;
712                         goto error;
713                 }
714         }
715
716
717         /*
718          * Find the highest priority message, and remove it from the queue.
719          * At first, reserved queue is checked, bitmap is next.
720          */
721         msg = TAILQ_FIRST(&mq->mq_head[MQ_PQRESQ]);
722         if (__predict_true(msg == NULL)) {
723                 idx = ffs(mq->mq_bitmap);
724                 msg = TAILQ_FIRST(&mq->mq_head[idx]);
725                 KKASSERT(msg != NULL);
726         } else {
727                 idx = MQ_PQRESQ;
728         }
729         TAILQ_REMOVE(&mq->mq_head[idx], msg, msg_queue);
730
731         /* Unmark the bit, if last message. */
732         if (__predict_true(idx) && TAILQ_EMPTY(&mq->mq_head[idx])) {
733                 KKASSERT((MQ_PQSIZE - idx) == msg->msg_prio);
734                 mq->mq_bitmap &= ~(1 << --idx);
735         }
736
737         /* Decrement the counter and signal waiter, if any */
738         mqattr->mq_curmsgs--;
739         wakeup_one(&mq->mq_recv_cv);
740
741         /* Ready for sending now */
742         KNOTE(&mq->mq_wkq.ki_note, 0);
743 error:
744         lockmgr(&mq->mq_mtx, LK_RELEASE);
745         fdrop(fp);
746         if (error)
747                 return error;
748
749         /*
750          * Copy the data to the user-space.
751          * Note: According to POSIX, no message should be removed from the
752          * queue in case of fail - this would be violated.
753          */
754         *mlen = msg->msg_len;
755         error = copyout(msg->msg_ptr, msg_ptr, msg->msg_len);
756         if (error == 0 && msg_prio)
757                 error = copyout(&msg->msg_prio, msg_prio, sizeof(unsigned));
758         mqueue_freemsg(msg, sizeof(struct mq_msg) + msg->msg_len);
759
760         return error;
761 }
762
763 int
764 sys_mq_receive(struct mq_receive_args *uap)
765 {
766         /* {
767                 syscallarg(mqd_t) mqdes;
768                 syscallarg(char *) msg_ptr;
769                 syscallarg(size_t) msg_len;
770                 syscallarg(unsigned *) msg_prio;
771         } */
772         ssize_t mlen;
773         int error;
774
775         error = mq_receive1(curthread->td_lwp, SCARG(uap, mqdes), SCARG(uap, msg_ptr),
776             SCARG(uap, msg_len), SCARG(uap, msg_prio), 0, &mlen);
777         if (error == 0)
778                 uap->sysmsg_result = mlen;
779
780         return error;
781 }
782
783 int
784 sys_mq_timedreceive(struct mq_timedreceive_args *uap)
785 {
786         /* {
787                 syscallarg(mqd_t) mqdes;
788                 syscallarg(char *) msg_ptr;
789                 syscallarg(size_t) msg_len;
790                 syscallarg(unsigned *) msg_prio;
791                 syscallarg(const struct timespec *) abs_timeout;
792         } */
793         int error;
794         ssize_t mlen;
795         struct timespec ts, *tsp;
796
797         /* Get and convert time value */
798         if (SCARG(uap, abs_timeout)) {
799                 error = copyin(SCARG(uap, abs_timeout), &ts, sizeof(ts));
800                 if (error)
801                         return error;
802                 tsp = &ts;
803         } else {
804                 tsp = NULL;
805         }
806
807         error = mq_receive1(curthread->td_lwp, SCARG(uap, mqdes), SCARG(uap, msg_ptr),
808             SCARG(uap, msg_len), SCARG(uap, msg_prio), tsp, &mlen);
809         if (error == 0)
810                 uap->sysmsg_result = mlen;
811
812         return error;
813 }
814
815 /*
816  * Primary mq_send1() function.
817  */
818 int
819 mq_send1(struct lwp *l, mqd_t mqdes, const char *msg_ptr, size_t msg_len,
820     unsigned msg_prio, struct timespec *ts)
821 {
822         file_t *fp = NULL;
823         struct mqueue *mq;
824         struct mq_msg *msg;
825         struct mq_attr *mqattr;
826         struct proc *notify = NULL;
827         /*ksiginfo_t ksi;*/
828         size_t size;
829         int error;
830
831         /* Check the priority range */
832         if (msg_prio >= mq_prio_max)
833                 return EINVAL;
834
835         /* Allocate a new message */
836         size = sizeof(struct mq_msg) + msg_len;
837         if (size > mq_max_msgsize)
838                 return EMSGSIZE;
839
840         if (size > MQ_DEF_MSGSIZE) {
841                 msg = kmalloc(size, M_MQBUF, M_WAITOK | M_NULLOK);
842         } else {
843                 msg = objcache_get(mqmsg_cache, M_WAITOK | M_NULLOK);
844         }
845         if (msg == NULL)
846                 return (ENOMEM);
847
848
849         /* Get the data from user-space */
850         error = copyin(msg_ptr, msg->msg_ptr, msg_len);
851         if (error) {
852                 mqueue_freemsg(msg, size);
853                 return error;
854         }
855         msg->msg_len = msg_len;
856         msg->msg_prio = msg_prio;
857
858         /* Get the mqueue */
859         error = mqueue_get(l, mqdes, &fp);
860         if (error) {
861                 mqueue_freemsg(msg, size);
862                 return error;
863         }
864         mq = fp->f_data;
865         if ((fp->f_flag & FWRITE) == 0) {
866                 error = EBADF;
867                 goto error;
868         }
869         getnanotime(&mq->mq_mtime);
870         mqattr = &mq->mq_attrib;
871
872         /* Check the message size limit */
873         if (msg_len <= 0 || msg_len > mqattr->mq_msgsize) {
874                 error = EMSGSIZE;
875                 goto error;
876         }
877
878         /* Check if queue is full */
879         while (mqattr->mq_curmsgs >= mqattr->mq_maxmsg) {
880                 int t;
881
882                 if (mqattr->mq_flags & O_NONBLOCK) {
883                         error = EAGAIN;
884                         goto error;
885                 }
886                 if (ts) {
887                         error = abstimeout2timo(ts, &t);
888                         if (error)
889                                 goto error;
890                 } else
891                         t = 0;
892                 /* Block until queue becomes available */
893                 error = lksleep(&mq->mq_recv_cv, &mq->mq_mtx, PCATCH, "mqrecv", t);
894                 if (error || (mqattr->mq_flags & MQ_UNLINK)) {
895                         error = (error == EWOULDBLOCK) ? ETIMEDOUT : error;
896                         goto error;
897                 }
898         }
899         KKASSERT(mq->mq_attrib.mq_curmsgs < mq->mq_attrib.mq_maxmsg);
900
901         /*
902          * Insert message into the queue, according to the priority.
903          * Note the difference between index and priority.
904          */
905         if (__predict_true(msg_prio < MQ_PQSIZE)) {
906                 u_int idx = MQ_PQSIZE - msg_prio;
907
908                 KKASSERT(idx != MQ_PQRESQ);
909                 TAILQ_INSERT_TAIL(&mq->mq_head[idx], msg, msg_queue);
910                 mq->mq_bitmap |= (1 << --idx);
911         } else {
912                 mqueue_linear_insert(mq, msg);
913         }
914
915         /* Check for the notify */
916         if (mqattr->mq_curmsgs == 0 && mq->mq_notify_proc &&
917             (mqattr->mq_flags & MQ_RECEIVE) == 0 &&
918             mq->mq_sig_notify.sigev_notify == SIGEV_SIGNAL) {
919                 /* Initialize the signal */
920                 /*KSI_INIT(&ksi);*/
921                 /*ksi.ksi_signo = mq->mq_sig_notify.sigev_signo;*/
922                 /*ksi.ksi_code = SI_MESGQ;*/
923                 /*ksi.ksi_value = mq->mq_sig_notify.sigev_value;*/
924                 /* Unregister the process */
925                 notify = mq->mq_notify_proc;
926                 mq->mq_notify_proc = NULL;
927         }
928
929         /* Increment the counter and signal waiter, if any */
930         mqattr->mq_curmsgs++;
931         wakeup_one(&mq->mq_send_cv);
932
933         /* Ready for receiving now */
934         KNOTE(&mq->mq_rkq.ki_note, 0);
935 error:
936         lockmgr(&mq->mq_mtx, LK_RELEASE);
937         fdrop(fp);
938
939         if (error) {
940                 mqueue_freemsg(msg, size);
941         } else if (notify) {
942                 /* Send the notify, if needed */
943                 lwkt_gettoken(&proc_token);
944                 /*kpsignal(notify, &ksi, NULL);*/
945                 ksignal(notify, mq->mq_sig_notify.sigev_signo);
946                 lwkt_reltoken(&proc_token);
947         }
948
949         return error;
950 }
951
952 int
953 sys_mq_send(struct mq_send_args *uap)
954 {
955         /* {
956                 syscallarg(mqd_t) mqdes;
957                 syscallarg(const char *) msg_ptr;
958                 syscallarg(size_t) msg_len;
959                 syscallarg(unsigned) msg_prio;
960         } */
961
962         return mq_send1(curthread->td_lwp, SCARG(uap, mqdes), SCARG(uap, msg_ptr),
963             SCARG(uap, msg_len), SCARG(uap, msg_prio), 0);
964 }
965
966 int
967 sys_mq_timedsend(struct mq_timedsend_args *uap)
968 {
969         /* {
970                 syscallarg(mqd_t) mqdes;
971                 syscallarg(const char *) msg_ptr;
972                 syscallarg(size_t) msg_len;
973                 syscallarg(unsigned) msg_prio;
974                 syscallarg(const struct timespec *) abs_timeout;
975         } */
976         struct timespec ts, *tsp;
977         int error;
978
979         /* Get and convert time value */
980         if (SCARG(uap, abs_timeout)) {
981                 error = copyin(SCARG(uap, abs_timeout), &ts, sizeof(ts));
982                 if (error)
983                         return error;
984                 tsp = &ts;
985         } else {
986                 tsp = NULL;
987         }
988
989         return mq_send1(curthread->td_lwp, SCARG(uap, mqdes), SCARG(uap, msg_ptr),
990             SCARG(uap, msg_len), SCARG(uap, msg_prio), tsp);
991 }
992
993 int
994 sys_mq_notify(struct mq_notify_args *uap)
995 {
996         /* {
997                 syscallarg(mqd_t) mqdes;
998                 syscallarg(const struct sigevent *) notification;
999         } */
1000         file_t *fp = NULL;
1001         struct mqueue *mq;
1002         struct sigevent sig;
1003         int error;
1004
1005         if (SCARG(uap, notification)) {
1006                 /* Get the signal from user-space */
1007                 error = copyin(SCARG(uap, notification), &sig,
1008                     sizeof(struct sigevent));
1009                 if (error)
1010                         return error;
1011                 if (sig.sigev_notify == SIGEV_SIGNAL &&
1012                     (sig.sigev_signo <= 0 || sig.sigev_signo >= NSIG))
1013                         return EINVAL;
1014         }
1015
1016         error = mqueue_get(curthread->td_lwp, SCARG(uap, mqdes), &fp);
1017         if (error)
1018                 return error;
1019         mq = fp->f_data;
1020
1021         if (SCARG(uap, notification)) {
1022                 /* Register notification: set the signal and target process */
1023                 if (mq->mq_notify_proc == NULL) {
1024                         memcpy(&mq->mq_sig_notify, &sig,
1025                             sizeof(struct sigevent));
1026                         mq->mq_notify_proc = curproc;
1027                 } else {
1028                         /* Fail if someone else already registered */
1029                         error = EBUSY;
1030                 }
1031         } else {
1032                 /* Unregister the notification */
1033                 mq->mq_notify_proc = NULL;
1034         }
1035         lockmgr(&mq->mq_mtx, LK_RELEASE);
1036         fdrop(fp);
1037
1038         return error;
1039 }
1040
1041 int
1042 sys_mq_getattr(struct mq_getattr_args *uap)
1043 {
1044         /* {
1045                 syscallarg(mqd_t) mqdes;
1046                 syscallarg(struct mq_attr *) mqstat;
1047         } */
1048         file_t *fp = NULL;
1049         struct mqueue *mq;
1050         struct mq_attr attr;
1051         int error;
1052
1053         /* Get the message queue */
1054         error = mqueue_get(curthread->td_lwp, SCARG(uap, mqdes), &fp);
1055         if (error)
1056                 return error;
1057         mq = fp->f_data;
1058         memcpy(&attr, &mq->mq_attrib, sizeof(struct mq_attr));
1059         lockmgr(&mq->mq_mtx, LK_RELEASE);
1060         fdrop(fp);
1061
1062         return copyout(&attr, SCARG(uap, mqstat), sizeof(struct mq_attr));
1063 }
1064
1065 int
1066 sys_mq_setattr(struct mq_setattr_args *uap)
1067 {
1068         /* {
1069                 syscallarg(mqd_t) mqdes;
1070                 syscallarg(const struct mq_attr *) mqstat;
1071                 syscallarg(struct mq_attr *) omqstat;
1072         } */
1073         file_t *fp = NULL;
1074         struct mqueue *mq;
1075         struct mq_attr attr;
1076         int error, nonblock;
1077
1078         error = copyin(SCARG(uap, mqstat), &attr, sizeof(struct mq_attr));
1079         if (error)
1080                 return error;
1081         nonblock = (attr.mq_flags & O_NONBLOCK);
1082
1083         /* Get the message queue */
1084         error = mqueue_get(curthread->td_lwp, SCARG(uap, mqdes), &fp);
1085         if (error)
1086                 return error;
1087         mq = fp->f_data;
1088
1089         /* Copy the old attributes, if needed */
1090         if (SCARG(uap, omqstat)) {
1091                 memcpy(&attr, &mq->mq_attrib, sizeof(struct mq_attr));
1092         }
1093
1094         /* Ignore everything, except O_NONBLOCK */
1095         if (nonblock)
1096                 mq->mq_attrib.mq_flags |= O_NONBLOCK;
1097         else
1098                 mq->mq_attrib.mq_flags &= ~O_NONBLOCK;
1099
1100         lockmgr(&mq->mq_mtx, LK_RELEASE);
1101         fdrop(fp);
1102
1103         /*
1104          * Copy the data to the user-space.
1105          * Note: According to POSIX, the new attributes should not be set in
1106          * case of fail - this would be violated.
1107          */
1108         if (SCARG(uap, omqstat))
1109                 error = copyout(&attr, SCARG(uap, omqstat),
1110                     sizeof(struct mq_attr));
1111
1112         return error;
1113 }
1114
1115 int
1116 sys_mq_unlink(struct mq_unlink_args *uap)
1117 {
1118         /* {
1119                 syscallarg(const char *) name;
1120         } */
1121         struct thread *td = curthread;
1122         struct mqueue *mq;
1123         char *name;
1124         int error, refcnt = 0;
1125
1126         /* Get the name from the user-space */
1127         name = kmalloc(MQ_NAMELEN, M_MQBUF, M_WAITOK | M_ZERO | M_NULLOK);
1128         if (name == NULL)
1129                 return (ENOMEM);
1130         error = copyinstr(SCARG(uap, name), name, MQ_NAMELEN - 1, NULL);
1131         if (error) {
1132                 kfree(name, M_MQBUF);
1133                 return error;
1134         }
1135
1136         /* Lookup for this file */
1137         lockmgr(&mqlist_mtx, LK_EXCLUSIVE);
1138         mq = mqueue_lookup(name);
1139         if (mq == NULL) {
1140                 error = ENOENT;
1141                 goto error;
1142         }
1143
1144         /* Check the permissions */
1145         if (td->td_ucred->cr_uid != mq->mq_euid &&
1146             priv_check(td, PRIV_ROOT) != 0) {
1147                 lockmgr(&mq->mq_mtx, LK_RELEASE);
1148                 error = EACCES;
1149                 goto error;
1150         }
1151
1152         /* Mark message queue as unlinking, before leaving the window */
1153         mq->mq_attrib.mq_flags |= MQ_UNLINK;
1154
1155         /* Wake up all waiters, if there are such */
1156         wakeup(&mq->mq_send_cv);
1157         wakeup(&mq->mq_recv_cv);
1158
1159         KNOTE(&mq->mq_rkq.ki_note, 0);
1160         KNOTE(&mq->mq_wkq.ki_note, 0);
1161
1162         refcnt = mq->mq_refcnt;
1163         if (refcnt == 0)
1164                 LIST_REMOVE(mq, mq_list);
1165
1166         lockmgr(&mq->mq_mtx, LK_RELEASE);
1167 error:
1168         lockmgr(&mqlist_mtx, LK_RELEASE);
1169
1170         /*
1171          * If there are no references - destroy the message
1172          * queue, otherwise, the last mq_close() will do that.
1173          */
1174         if (error == 0 && refcnt == 0)
1175                 mqueue_destroy(mq);
1176
1177         kfree(name, M_MQBUF);
1178         return error;
1179 }
1180
1181 /*
1182  * SysCtl.
1183  */
1184 SYSCTL_NODE(_kern, OID_AUTO, mqueue,
1185     CTLFLAG_RW, 0, "Message queue options");
1186
1187 SYSCTL_INT(_kern_mqueue, OID_AUTO, mq_open_max,
1188     CTLFLAG_RW, &mq_open_max, 0,
1189     "Maximal number of message queue descriptors per process");
1190
1191 SYSCTL_INT(_kern_mqueue, OID_AUTO, mq_prio_max,
1192     CTLFLAG_RW, &mq_prio_max, 0,
1193     "Maximal priority of the message");
1194
1195 SYSCTL_INT(_kern_mqueue, OID_AUTO, mq_max_msgsize,
1196     CTLFLAG_RW, &mq_max_msgsize, 0,
1197     "Maximal allowed size of the message");
1198
1199 SYSCTL_INT(_kern_mqueue, OID_AUTO, mq_def_maxmsg,
1200     CTLFLAG_RW, &mq_def_maxmsg, 0,
1201     "Default maximal message count");
1202
1203 SYSCTL_INT(_kern_mqueue, OID_AUTO, mq_max_maxmsg,
1204     CTLFLAG_RW, &mq_max_maxmsg, 0,
1205     "Maximal allowed message count");
1206
1207 SYSINIT(sys_mqueue_init, SI_SUB_PRE_DRIVERS, SI_ORDER_ANY, mqueue_sysinit, NULL);