Home | History | Annotate | Line # | Download | only in kern
sys_mqueue.c revision 1.23
      1 /*	$NetBSD: sys_mqueue.c,v 1.23 2009/07/19 02:26:49 rmind Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2007-2009 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 <sys/cdefs.h>
     45 __KERNEL_RCSID(0, "$NetBSD: sys_mqueue.c,v 1.23 2009/07/19 02:26:49 rmind Exp $");
     46 
     47 #include <sys/param.h>
     48 #include <sys/types.h>
     49 #include <sys/condvar.h>
     50 #include <sys/errno.h>
     51 #include <sys/fcntl.h>
     52 #include <sys/file.h>
     53 #include <sys/filedesc.h>
     54 #include <sys/kauth.h>
     55 #include <sys/kernel.h>
     56 #include <sys/kmem.h>
     57 #include <sys/lwp.h>
     58 #include <sys/mqueue.h>
     59 #include <sys/mutex.h>
     60 #include <sys/pool.h>
     61 #include <sys/poll.h>
     62 #include <sys/proc.h>
     63 #include <sys/queue.h>
     64 #include <sys/select.h>
     65 #include <sys/signal.h>
     66 #include <sys/signalvar.h>
     67 #include <sys/stat.h>
     68 #include <sys/sysctl.h>
     69 #include <sys/syscallargs.h>
     70 #include <sys/systm.h>
     71 #include <sys/unistd.h>
     72 
     73 #include <miscfs/genfs/genfs.h>
     74 
     75 /* System-wide limits. */
     76 static u_int			mq_open_max = MQ_OPEN_MAX;
     77 static u_int			mq_prio_max = MQ_PRIO_MAX;
     78 
     79 static u_int			mq_max_msgsize = 16 * MQ_DEF_MSGSIZE;
     80 static u_int			mq_def_maxmsg = 32;
     81 
     82 static kmutex_t			mqlist_mtx;
     83 static pool_cache_t		mqmsg_cache;
     84 static LIST_HEAD(, mqueue)	mqueue_head;
     85 
     86 static int	mq_poll_fop(file_t *, int);
     87 static int	mq_stat_fop(file_t *, struct stat *);
     88 static int	mq_close_fop(file_t *);
     89 
     90 static const struct fileops mqops = {
     91 	.fo_read = fbadop_read,
     92 	.fo_write = fbadop_write,
     93 	.fo_ioctl = fbadop_ioctl,
     94 	.fo_fcntl = fnullop_fcntl,
     95 	.fo_poll = mq_poll_fop,
     96 	.fo_stat = mq_stat_fop,
     97 	.fo_close = mq_close_fop,
     98 	.fo_kqfilter = fnullop_kqfilter,
     99 	.fo_drain = fnullop_drain,
    100 };
    101 
    102 /*
    103  * Initialize POSIX message queue subsystem.
    104  */
    105 void
    106 mqueue_sysinit(void)
    107 {
    108 
    109 	mqmsg_cache = pool_cache_init(MQ_DEF_MSGSIZE, coherency_unit,
    110 	    0, 0, "mqmsgpl", NULL, IPL_NONE, NULL, NULL, NULL);
    111 	mutex_init(&mqlist_mtx, MUTEX_DEFAULT, IPL_NONE);
    112 	LIST_INIT(&mqueue_head);
    113 }
    114 
    115 /*
    116  * Free the message.
    117  */
    118 static void
    119 mqueue_freemsg(struct mq_msg *msg, const size_t size)
    120 {
    121 
    122 	if (size > MQ_DEF_MSGSIZE) {
    123 		kmem_free(msg, size);
    124 	} else {
    125 		pool_cache_put(mqmsg_cache, msg);
    126 	}
    127 }
    128 
    129 /*
    130  * Destroy the message queue.
    131  */
    132 static void
    133 mqueue_destroy(struct mqueue *mq)
    134 {
    135 	struct mq_msg *msg;
    136 	size_t msz;
    137 	u_int i;
    138 
    139 	/* Note MQ_PQSIZE + 1. */
    140 	for (i = 0; i <= MQ_PQSIZE; i++) {
    141 		while ((msg = TAILQ_FIRST(&mq->mq_head[i])) != NULL) {
    142 			TAILQ_REMOVE(&mq->mq_head[i], msg, msg_queue);
    143 			msz = sizeof(struct mq_msg) + msg->msg_len;
    144 			mqueue_freemsg(msg, msz);
    145 		}
    146 	}
    147 	seldestroy(&mq->mq_rsel);
    148 	seldestroy(&mq->mq_wsel);
    149 	cv_destroy(&mq->mq_send_cv);
    150 	cv_destroy(&mq->mq_recv_cv);
    151 	mutex_destroy(&mq->mq_mtx);
    152 	kmem_free(mq, sizeof(struct mqueue));
    153 }
    154 
    155 /*
    156  * Lookup for file name in general list of message queues.
    157  *  => locks the message queue
    158  */
    159 static void *
    160 mqueue_lookup(char *name)
    161 {
    162 	struct mqueue *mq;
    163 	KASSERT(mutex_owned(&mqlist_mtx));
    164 
    165 	LIST_FOREACH(mq, &mqueue_head, mq_list) {
    166 		if (strncmp(mq->mq_name, name, MQ_NAMELEN) == 0) {
    167 			mutex_enter(&mq->mq_mtx);
    168 			return mq;
    169 		}
    170 	}
    171 
    172 	return NULL;
    173 }
    174 
    175 /*
    176  * mqueue_get: get the mqueue from the descriptor.
    177  *  => locks the message queue, if found.
    178  *  => holds a reference on the file descriptor.
    179  */
    180 static int
    181 mqueue_get(mqd_t mqd, file_t **fpr)
    182 {
    183 	struct mqueue *mq;
    184 	file_t *fp;
    185 
    186 	fp = fd_getfile((int)mqd);
    187 	if (__predict_false(fp == NULL)) {
    188 		return EBADF;
    189 	}
    190 	if (__predict_false(fp->f_type != DTYPE_MQUEUE)) {
    191 		fd_putfile((int)mqd);
    192 		return EBADF;
    193 	}
    194 	mq = fp->f_data;
    195 	mutex_enter(&mq->mq_mtx);
    196 
    197 	*fpr = fp;
    198 	return 0;
    199 }
    200 
    201 /*
    202  * mqueue_linear_insert: perform linear insert according to the message
    203  * priority into the reserved queue (MQ_PQRESQ).  Reserved queue is a
    204  * sorted list used only when mq_prio_max is increased via sysctl.
    205  */
    206 static inline void
    207 mqueue_linear_insert(struct mqueue *mq, struct mq_msg *msg)
    208 {
    209 	struct mq_msg *mit;
    210 
    211 	TAILQ_FOREACH(mit, &mq->mq_head[MQ_PQRESQ], msg_queue) {
    212 		if (msg->msg_prio > mit->msg_prio)
    213 			break;
    214 	}
    215 	if (mit == NULL) {
    216 		TAILQ_INSERT_TAIL(&mq->mq_head[MQ_PQRESQ], msg, msg_queue);
    217 	} else {
    218 		TAILQ_INSERT_BEFORE(mit, msg, msg_queue);
    219 	}
    220 }
    221 
    222 /*
    223  * Converter from struct timespec to the ticks.
    224  * Used by mq_timedreceive(), mq_timedsend().
    225  */
    226 int
    227 abstimeout2timo(struct timespec *ts, int *timo)
    228 {
    229 	int error;
    230 
    231 	/*
    232 	 * According to POSIX, validation check is needed only in case of
    233 	 * blocking.  Thus, set the invalid value right now, and fail latter.
    234 	 */
    235 	error = itimespecfix(ts);
    236 	*timo = (error == 0) ? tstohz(ts) : -1;
    237 
    238 	return 0;
    239 }
    240 
    241 static int
    242 mq_stat_fop(file_t *fp, struct stat *st)
    243 {
    244 	struct mqueue *mq = fp->f_data;
    245 
    246 	memset(st, 0, sizeof(*st));
    247 
    248 	mutex_enter(&mq->mq_mtx);
    249 	st->st_mode = mq->mq_mode;
    250 	st->st_uid = mq->mq_euid;
    251 	st->st_gid = mq->mq_egid;
    252 	st->st_atimespec = mq->mq_atime;
    253 	st->st_mtimespec = mq->mq_mtime;
    254 	st->st_ctimespec = st->st_birthtimespec = mq->mq_btime;
    255 	st->st_uid = kauth_cred_geteuid(fp->f_cred);
    256 	st->st_gid = kauth_cred_getegid(fp->f_cred);
    257 	mutex_exit(&mq->mq_mtx);
    258 
    259 	return 0;
    260 }
    261 
    262 static int
    263 mq_poll_fop(file_t *fp, int events)
    264 {
    265 	struct mqueue *mq = fp->f_data;
    266 	struct mq_attr *mqattr;
    267 	int revents = 0;
    268 
    269 	mutex_enter(&mq->mq_mtx);
    270 	mqattr = &mq->mq_attrib;
    271 	if (events & (POLLIN | POLLRDNORM)) {
    272 		/* Ready for receiving, if there are messages in the queue */
    273 		if (mqattr->mq_curmsgs)
    274 			revents |= (POLLIN | POLLRDNORM);
    275 		else
    276 			selrecord(curlwp, &mq->mq_rsel);
    277 	}
    278 	if (events & (POLLOUT | POLLWRNORM)) {
    279 		/* Ready for sending, if the message queue is not full */
    280 		if (mqattr->mq_curmsgs < mqattr->mq_maxmsg)
    281 			revents |= (POLLOUT | POLLWRNORM);
    282 		else
    283 			selrecord(curlwp, &mq->mq_wsel);
    284 	}
    285 	mutex_exit(&mq->mq_mtx);
    286 
    287 	return revents;
    288 }
    289 
    290 static int
    291 mq_close_fop(file_t *fp)
    292 {
    293 	struct proc *p = curproc;
    294 	struct mqueue *mq = fp->f_data;
    295 	bool destroy;
    296 
    297 	mutex_enter(&mqlist_mtx);
    298 	mutex_enter(&mq->mq_mtx);
    299 
    300 	/* Decrease the counters */
    301 	p->p_mqueue_cnt--;
    302 	mq->mq_refcnt--;
    303 
    304 	/* Remove notification if registered for this process */
    305 	if (mq->mq_notify_proc == p)
    306 		mq->mq_notify_proc = NULL;
    307 
    308 	/*
    309 	 * If this is the last reference and mqueue is marked for unlink,
    310 	 * remove and later destroy the message queue.
    311 	 */
    312 	if (mq->mq_refcnt == 0 && (mq->mq_attrib.mq_flags & MQ_UNLINK)) {
    313 		LIST_REMOVE(mq, mq_list);
    314 		destroy = true;
    315 	} else
    316 		destroy = false;
    317 
    318 	mutex_exit(&mq->mq_mtx);
    319 	mutex_exit(&mqlist_mtx);
    320 
    321 	if (destroy)
    322 		mqueue_destroy(mq);
    323 
    324 	return 0;
    325 }
    326 
    327 static int
    328 mqueue_access(struct mqueue *mq, mode_t mode, kauth_cred_t cred)
    329 {
    330 
    331 	if (genfs_can_access(VNON, mq->mq_mode, mq->mq_euid,
    332 	    mq->mq_egid, mode, cred)) {
    333 		return EACCES;
    334 	}
    335 
    336 	return 0;
    337 }
    338 
    339 /*
    340  * General mqueue system calls.
    341  */
    342 
    343 int
    344 sys_mq_open(struct lwp *l, const struct sys_mq_open_args *uap,
    345     register_t *retval)
    346 {
    347 	/* {
    348 		syscallarg(const char *) name;
    349 		syscallarg(int) oflag;
    350 		syscallarg(mode_t) mode;
    351 		syscallarg(struct mq_attr) attr;
    352 	} */
    353 	struct proc *p = l->l_proc;
    354 	struct mqueue *mq, *mq_new = NULL;
    355 	file_t *fp;
    356 	char *name;
    357 	int mqd, error, oflag;
    358 
    359 	oflag = SCARG(uap, oflag);
    360 
    361 	/* Get the name from the user-space */
    362 	name = kmem_zalloc(MQ_NAMELEN, KM_SLEEP);
    363 	error = copyinstr(SCARG(uap, name), name, MQ_NAMELEN - 1, NULL);
    364 	if (error) {
    365 		kmem_free(name, MQ_NAMELEN);
    366 		return error;
    367 	}
    368 
    369 	if (oflag & O_CREAT) {
    370 		struct cwdinfo *cwdi = p->p_cwdi;
    371 		struct mq_attr attr;
    372 		u_int i;
    373 
    374 		/* Check the limit */
    375 		if (p->p_mqueue_cnt == mq_open_max) {
    376 			kmem_free(name, MQ_NAMELEN);
    377 			return EMFILE;
    378 		}
    379 
    380 		/* Empty name is invalid */
    381 		if (name[0] == '\0') {
    382 			kmem_free(name, MQ_NAMELEN);
    383 			return EINVAL;
    384 		}
    385 
    386 		/* Check for mqueue attributes */
    387 		if (SCARG(uap, attr)) {
    388 			error = copyin(SCARG(uap, attr), &attr,
    389 			    sizeof(struct mq_attr));
    390 			if (error) {
    391 				kmem_free(name, MQ_NAMELEN);
    392 				return error;
    393 			}
    394 			if (attr.mq_maxmsg <= 0 || attr.mq_msgsize <= 0 ||
    395 			    attr.mq_msgsize > mq_max_msgsize) {
    396 				kmem_free(name, MQ_NAMELEN);
    397 				return EINVAL;
    398 			}
    399 			attr.mq_curmsgs = 0;
    400 		} else {
    401 			memset(&attr, 0, sizeof(struct mq_attr));
    402 			attr.mq_maxmsg = mq_def_maxmsg;
    403 			attr.mq_msgsize =
    404 			    MQ_DEF_MSGSIZE - sizeof(struct mq_msg);
    405 		}
    406 
    407 		/*
    408 		 * Allocate new mqueue, initialize data structures,
    409 		 * copy the name, attributes and set the flag.
    410 		 */
    411 		mq_new = kmem_zalloc(sizeof(struct mqueue), KM_SLEEP);
    412 
    413 		mutex_init(&mq_new->mq_mtx, MUTEX_DEFAULT, IPL_NONE);
    414 		cv_init(&mq_new->mq_send_cv, "mqsendcv");
    415 		cv_init(&mq_new->mq_recv_cv, "mqrecvcv");
    416 		for (i = 0; i < (MQ_PQSIZE + 1); i++) {
    417 			TAILQ_INIT(&mq_new->mq_head[i]);
    418 		}
    419 		selinit(&mq_new->mq_rsel);
    420 		selinit(&mq_new->mq_wsel);
    421 
    422 		strlcpy(mq_new->mq_name, name, MQ_NAMELEN);
    423 		memcpy(&mq_new->mq_attrib, &attr, sizeof(struct mq_attr));
    424 
    425 		CTASSERT((O_MASK & (MQ_UNLINK | MQ_RECEIVE)) == 0);
    426 		mq_new->mq_attrib.mq_flags = (O_MASK & oflag);
    427 
    428 		/* Store mode and effective UID with GID */
    429 		mq_new->mq_mode = ((SCARG(uap, mode) &
    430 		    ~cwdi->cwdi_cmask) & ALLPERMS) & ~S_ISTXT;
    431 		mq_new->mq_euid = kauth_cred_geteuid(l->l_cred);
    432 		mq_new->mq_egid = kauth_cred_getegid(l->l_cred);
    433 	}
    434 
    435 	/* Allocate file structure and descriptor */
    436 	error = fd_allocfile(&fp, &mqd);
    437 	if (error) {
    438 		if (mq_new)
    439 			mqueue_destroy(mq_new);
    440 		kmem_free(name, MQ_NAMELEN);
    441 		return error;
    442 	}
    443 	fp->f_type = DTYPE_MQUEUE;
    444 	fp->f_flag = FFLAGS(oflag) & (FREAD | FWRITE);
    445 	fp->f_ops = &mqops;
    446 
    447 	/* Look up for mqueue with such name */
    448 	mutex_enter(&mqlist_mtx);
    449 	mq = mqueue_lookup(name);
    450 	if (mq) {
    451 		mode_t acc_mode;
    452 
    453 		KASSERT(mutex_owned(&mq->mq_mtx));
    454 
    455 		/* Check if mqueue is not marked as unlinking */
    456 		if (mq->mq_attrib.mq_flags & MQ_UNLINK) {
    457 			error = EACCES;
    458 			goto exit;
    459 		}
    460 
    461 		/* Fail if O_EXCL is set, and mqueue already exists */
    462 		if ((oflag & O_CREAT) && (oflag & O_EXCL)) {
    463 			error = EEXIST;
    464 			goto exit;
    465 		}
    466 
    467 		/*
    468 		 * Check the permissions.  Note the difference between
    469 		 * VREAD/VWRITE and FREAD/FWRITE.
    470 		 */
    471 		acc_mode = 0;
    472 		if (fp->f_flag & FREAD) {
    473 			acc_mode |= VREAD;
    474 		}
    475 		if (fp->f_flag & FWRITE) {
    476 			acc_mode |= VWRITE;
    477 		}
    478 		if (mqueue_access(mq, acc_mode, l->l_cred) != 0) {
    479 			error = EACCES;
    480 			goto exit;
    481 		}
    482 	} else {
    483 		/* Fail if mqueue neither exists, nor we create it */
    484 		if ((oflag & O_CREAT) == 0) {
    485 			mutex_exit(&mqlist_mtx);
    486 			KASSERT(mq_new == NULL);
    487 			fd_abort(p, fp, mqd);
    488 			kmem_free(name, MQ_NAMELEN);
    489 			return ENOENT;
    490 		}
    491 
    492 		/* Check the limit */
    493 		if (p->p_mqueue_cnt == mq_open_max) {
    494 			error = EMFILE;
    495 			goto exit;
    496 		}
    497 
    498 		/* Insert the queue to the list */
    499 		mq = mq_new;
    500 		mutex_enter(&mq->mq_mtx);
    501 		LIST_INSERT_HEAD(&mqueue_head, mq, mq_list);
    502 		mq_new = NULL;
    503 		getnanotime(&mq->mq_btime);
    504 		mq->mq_atime = mq->mq_mtime = mq->mq_btime;
    505 	}
    506 
    507 	/* Increase the counters, and make descriptor ready */
    508 	p->p_mqueue_cnt++;
    509 	mq->mq_refcnt++;
    510 	fp->f_data = mq;
    511 exit:
    512 	mutex_exit(&mq->mq_mtx);
    513 	mutex_exit(&mqlist_mtx);
    514 
    515 	if (mq_new)
    516 		mqueue_destroy(mq_new);
    517 	if (error) {
    518 		fd_abort(p, fp, mqd);
    519 	} else {
    520 		fd_affix(p, fp, mqd);
    521 		*retval = mqd;
    522 	}
    523 	kmem_free(name, MQ_NAMELEN);
    524 
    525 	return error;
    526 }
    527 
    528 int
    529 sys_mq_close(struct lwp *l, const struct sys_mq_close_args *uap,
    530     register_t *retval)
    531 {
    532 
    533 	return sys_close(l, (const void *)uap, retval);
    534 }
    535 
    536 /*
    537  * Primary mq_receive1() function.
    538  */
    539 int
    540 mq_receive1(lwp_t *l, mqd_t mqdes, void *msg_ptr, size_t msg_len,
    541     unsigned *msg_prio, int t, ssize_t *mlen)
    542 {
    543 	file_t *fp = NULL;
    544 	struct mqueue *mq;
    545 	struct mq_msg *msg = NULL;
    546 	struct mq_attr *mqattr;
    547 	u_int idx;
    548 	int error;
    549 
    550 	/* Get the message queue */
    551 	error = mqueue_get(mqdes, &fp);
    552 	if (error) {
    553 		return error;
    554 	}
    555 	mq = fp->f_data;
    556 	if ((fp->f_flag & FREAD) == 0) {
    557 		error = EBADF;
    558 		goto error;
    559 	}
    560 	getnanotime(&mq->mq_atime);
    561 	mqattr = &mq->mq_attrib;
    562 
    563 	/* Check the message size limits */
    564 	if (msg_len < mqattr->mq_msgsize) {
    565 		error = EMSGSIZE;
    566 		goto error;
    567 	}
    568 
    569 	/* Check if queue is empty */
    570 	while (mqattr->mq_curmsgs == 0) {
    571 		if (mqattr->mq_flags & O_NONBLOCK) {
    572 			error = EAGAIN;
    573 			goto error;
    574 		}
    575 		if (t < 0) {
    576 			error = EINVAL;
    577 			goto error;
    578 		}
    579 		/*
    580 		 * Block until someone sends the message.
    581 		 * While doing this, notification should not be sent.
    582 		 */
    583 		mqattr->mq_flags |= MQ_RECEIVE;
    584 		error = cv_timedwait_sig(&mq->mq_send_cv, &mq->mq_mtx, t);
    585 		mqattr->mq_flags &= ~MQ_RECEIVE;
    586 		if (error || (mqattr->mq_flags & MQ_UNLINK)) {
    587 			error = (error == EWOULDBLOCK) ? ETIMEDOUT : EINTR;
    588 			goto error;
    589 		}
    590 	}
    591 
    592 	/*
    593 	 * Find the highest priority message, and remove it from the queue.
    594 	 * At first, reserved queue is checked, bitmap is next.
    595 	 */
    596 	msg = TAILQ_FIRST(&mq->mq_head[MQ_PQRESQ]);
    597 	if (__predict_true(msg == NULL)) {
    598 		idx = ffs(mq->mq_bitmap);
    599 		msg = TAILQ_FIRST(&mq->mq_head[idx]);
    600 		KASSERT(msg != NULL);
    601 	} else {
    602 		idx = MQ_PQRESQ;
    603 	}
    604 	TAILQ_REMOVE(&mq->mq_head[idx], msg, msg_queue);
    605 
    606 	/* Unmark the bit, if last message. */
    607 	if (__predict_true(idx) && TAILQ_EMPTY(&mq->mq_head[idx])) {
    608 		KASSERT((MQ_PQSIZE - idx) == msg->msg_prio);
    609 		mq->mq_bitmap &= ~(1 << --idx);
    610 	}
    611 
    612 	/* Decrement the counter and signal waiter, if any */
    613 	mqattr->mq_curmsgs--;
    614 	cv_signal(&mq->mq_recv_cv);
    615 
    616 	/* Ready for sending now */
    617 	selnotify(&mq->mq_wsel, POLLOUT | POLLWRNORM, 0);
    618 error:
    619 	mutex_exit(&mq->mq_mtx);
    620 	fd_putfile((int)mqdes);
    621 	if (error)
    622 		return error;
    623 
    624 	/*
    625 	 * Copy the data to the user-space.
    626 	 * Note: According to POSIX, no message should be removed from the
    627 	 * queue in case of fail - this would be violated.
    628 	 */
    629 	*mlen = msg->msg_len;
    630 	error = copyout(msg->msg_ptr, msg_ptr, msg->msg_len);
    631 	if (error == 0 && msg_prio)
    632 		error = copyout(&msg->msg_prio, msg_prio, sizeof(unsigned));
    633 	mqueue_freemsg(msg, sizeof(struct mq_msg) + msg->msg_len);
    634 
    635 	return error;
    636 }
    637 
    638 int
    639 sys_mq_receive(struct lwp *l, const struct sys_mq_receive_args *uap,
    640     register_t *retval)
    641 {
    642 	/* {
    643 		syscallarg(mqd_t) mqdes;
    644 		syscallarg(char *) msg_ptr;
    645 		syscallarg(size_t) msg_len;
    646 		syscallarg(unsigned *) msg_prio;
    647 	} */
    648 	int error;
    649 	ssize_t mlen;
    650 
    651 	error = mq_receive1(l, SCARG(uap, mqdes), SCARG(uap, msg_ptr),
    652 	    SCARG(uap, msg_len), SCARG(uap, msg_prio), 0, &mlen);
    653 	if (error == 0)
    654 		*retval = mlen;
    655 
    656 	return error;
    657 }
    658 
    659 int
    660 sys___mq_timedreceive50(struct lwp *l,
    661     const struct sys___mq_timedreceive50_args *uap, register_t *retval)
    662 {
    663 	/* {
    664 		syscallarg(mqd_t) mqdes;
    665 		syscallarg(char *) msg_ptr;
    666 		syscallarg(size_t) msg_len;
    667 		syscallarg(unsigned *) msg_prio;
    668 		syscallarg(const struct timespec *) abs_timeout;
    669 	} */
    670 	int error, t;
    671 	ssize_t mlen;
    672 	struct timespec ts;
    673 
    674 	/* Get and convert time value */
    675 	if (SCARG(uap, abs_timeout)) {
    676 		error = copyin(SCARG(uap, abs_timeout), &ts, sizeof(ts));
    677 		if (error)
    678 			return error;
    679 
    680 		error = abstimeout2timo(&ts, &t);
    681 		if (error)
    682 			return error;
    683 	} else
    684 		t = 0;
    685 
    686 	error = mq_receive1(l, SCARG(uap, mqdes), SCARG(uap, msg_ptr),
    687 	    SCARG(uap, msg_len), SCARG(uap, msg_prio), t, &mlen);
    688 	if (error == 0)
    689 		*retval = mlen;
    690 
    691 	return error;
    692 }
    693 
    694 /*
    695  * Primary mq_send1() function.
    696  */
    697 int
    698 mq_send1(lwp_t *l, mqd_t mqdes, const char *msg_ptr, size_t msg_len,
    699     unsigned msg_prio, int t)
    700 {
    701 	file_t *fp = NULL;
    702 	struct mqueue *mq;
    703 	struct mq_msg *msg;
    704 	struct mq_attr *mqattr;
    705 	struct proc *notify = NULL;
    706 	ksiginfo_t ksi;
    707 	size_t size;
    708 	int error;
    709 
    710 	/* Check the priority range */
    711 	if (msg_prio >= mq_prio_max)
    712 		return EINVAL;
    713 
    714 	/* Allocate a new message */
    715 	size = sizeof(struct mq_msg) + msg_len;
    716 	if (size > mq_max_msgsize)
    717 		return EMSGSIZE;
    718 
    719 	if (size > MQ_DEF_MSGSIZE) {
    720 		msg = kmem_alloc(size, KM_SLEEP);
    721 	} else {
    722 		msg = pool_cache_get(mqmsg_cache, PR_WAITOK);
    723 	}
    724 
    725 	/* Get the data from user-space */
    726 	error = copyin(msg_ptr, msg->msg_ptr, msg_len);
    727 	if (error) {
    728 		mqueue_freemsg(msg, size);
    729 		return error;
    730 	}
    731 	msg->msg_len = msg_len;
    732 	msg->msg_prio = msg_prio;
    733 
    734 	/* Get the mqueue */
    735 	error = mqueue_get(mqdes, &fp);
    736 	if (error) {
    737 		mqueue_freemsg(msg, size);
    738 		return error;
    739 	}
    740 	mq = fp->f_data;
    741 	if ((fp->f_flag & FWRITE) == 0) {
    742 		error = EBADF;
    743 		goto error;
    744 	}
    745 	getnanotime(&mq->mq_mtime);
    746 	mqattr = &mq->mq_attrib;
    747 
    748 	/* Check the message size limit */
    749 	if (msg_len <= 0 || msg_len > mqattr->mq_msgsize) {
    750 		error = EMSGSIZE;
    751 		goto error;
    752 	}
    753 
    754 	/* Check if queue is full */
    755 	while (mqattr->mq_curmsgs >= mqattr->mq_maxmsg) {
    756 		if (mqattr->mq_flags & O_NONBLOCK) {
    757 			error = EAGAIN;
    758 			goto error;
    759 		}
    760 		if (t < 0) {
    761 			error = EINVAL;
    762 			goto error;
    763 		}
    764 		/* Block until queue becomes available */
    765 		error = cv_timedwait_sig(&mq->mq_recv_cv, &mq->mq_mtx, t);
    766 		if (error || (mqattr->mq_flags & MQ_UNLINK)) {
    767 			error = (error == EWOULDBLOCK) ? ETIMEDOUT : error;
    768 			goto error;
    769 		}
    770 	}
    771 	KASSERT(mqattr->mq_curmsgs < mqattr->mq_maxmsg);
    772 
    773 	/*
    774 	 * Insert message into the queue, according to the priority.
    775 	 * Note the difference between index and priority.
    776 	 */
    777 	if (__predict_true(msg_prio < MQ_PQSIZE)) {
    778 		u_int idx = MQ_PQSIZE - msg_prio;
    779 
    780 		KASSERT(idx != MQ_PQRESQ);
    781 		TAILQ_INSERT_TAIL(&mq->mq_head[idx], msg, msg_queue);
    782 		mq->mq_bitmap |= (1 << --idx);
    783 	} else {
    784 		mqueue_linear_insert(mq, msg);
    785 	}
    786 
    787 	/* Check for the notify */
    788 	if (mqattr->mq_curmsgs == 0 && mq->mq_notify_proc &&
    789 	    (mqattr->mq_flags & MQ_RECEIVE) == 0) {
    790 		/* Initialize the signal */
    791 		KSI_INIT(&ksi);
    792 		ksi.ksi_signo = mq->mq_sig_notify.sigev_signo;
    793 		ksi.ksi_code = SI_MESGQ;
    794 		ksi.ksi_value = mq->mq_sig_notify.sigev_value;
    795 		/* Unregister the process */
    796 		notify = mq->mq_notify_proc;
    797 		mq->mq_notify_proc = NULL;
    798 	}
    799 
    800 	/* Increment the counter and signal waiter, if any */
    801 	mqattr->mq_curmsgs++;
    802 	cv_signal(&mq->mq_send_cv);
    803 
    804 	/* Ready for receiving now */
    805 	selnotify(&mq->mq_rsel, POLLIN | POLLRDNORM, 0);
    806 error:
    807 	mutex_exit(&mq->mq_mtx);
    808 	fd_putfile((int)mqdes);
    809 
    810 	if (error) {
    811 		mqueue_freemsg(msg, size);
    812 	} else if (notify) {
    813 		/* Send the notify, if needed */
    814 		mutex_enter(proc_lock);
    815 		kpsignal(notify, &ksi, NULL);
    816 		mutex_exit(proc_lock);
    817 	}
    818 	return error;
    819 }
    820 
    821 int
    822 sys_mq_send(struct lwp *l, const struct sys_mq_send_args *uap,
    823     register_t *retval)
    824 {
    825 	/* {
    826 		syscallarg(mqd_t) mqdes;
    827 		syscallarg(const char *) msg_ptr;
    828 		syscallarg(size_t) msg_len;
    829 		syscallarg(unsigned) msg_prio;
    830 	} */
    831 
    832 	return mq_send1(l, SCARG(uap, mqdes), SCARG(uap, msg_ptr),
    833 	    SCARG(uap, msg_len), SCARG(uap, msg_prio), 0);
    834 }
    835 
    836 int
    837 sys___mq_timedsend50(struct lwp *l, const struct sys___mq_timedsend50_args *uap,
    838     register_t *retval)
    839 {
    840 	/* {
    841 		syscallarg(mqd_t) mqdes;
    842 		syscallarg(const char *) msg_ptr;
    843 		syscallarg(size_t) msg_len;
    844 		syscallarg(unsigned) msg_prio;
    845 		syscallarg(const struct timespec *) abs_timeout;
    846 	} */
    847 	int t;
    848 	struct timespec ts;
    849 	int error;
    850 
    851 	/* Get and convert time value */
    852 	if (SCARG(uap, abs_timeout)) {
    853 		error = copyin(SCARG(uap, abs_timeout), &ts, sizeof(ts));
    854 		if (error)
    855 			return error;
    856 		error = abstimeout2timo(&ts, &t);
    857 		if (error)
    858 			return error;
    859 	} else
    860 		t = 0;
    861 
    862 	return mq_send1(l, SCARG(uap, mqdes), SCARG(uap, msg_ptr),
    863 	    SCARG(uap, msg_len), SCARG(uap, msg_prio), t);
    864 }
    865 
    866 int
    867 sys_mq_notify(struct lwp *l, const struct sys_mq_notify_args *uap,
    868     register_t *retval)
    869 {
    870 	/* {
    871 		syscallarg(mqd_t) mqdes;
    872 		syscallarg(const struct sigevent *) notification;
    873 	} */
    874 	file_t *fp = NULL;
    875 	struct mqueue *mq;
    876 	struct sigevent sig;
    877 	int error;
    878 
    879 	if (SCARG(uap, notification)) {
    880 		/* Get the signal from user-space */
    881 		error = copyin(SCARG(uap, notification), &sig,
    882 		    sizeof(struct sigevent));
    883 		if (error)
    884 			return error;
    885 	}
    886 
    887 	error = mqueue_get(SCARG(uap, mqdes), &fp);
    888 	if (error)
    889 		return error;
    890 	mq = fp->f_data;
    891 
    892 	if (SCARG(uap, notification)) {
    893 		/* Register notification: set the signal and target process */
    894 		if (mq->mq_notify_proc == NULL) {
    895 			memcpy(&mq->mq_sig_notify, &sig,
    896 			    sizeof(struct sigevent));
    897 			mq->mq_notify_proc = l->l_proc;
    898 		} else {
    899 			/* Fail if someone else already registered */
    900 			error = EBUSY;
    901 		}
    902 	} else {
    903 		/* Unregister the notification */
    904 		mq->mq_notify_proc = NULL;
    905 	}
    906 	mutex_exit(&mq->mq_mtx);
    907 	fd_putfile((int)SCARG(uap, mqdes));
    908 
    909 	return error;
    910 }
    911 
    912 int
    913 sys_mq_getattr(struct lwp *l, const struct sys_mq_getattr_args *uap,
    914     register_t *retval)
    915 {
    916 	/* {
    917 		syscallarg(mqd_t) mqdes;
    918 		syscallarg(struct mq_attr *) mqstat;
    919 	} */
    920 	file_t *fp = NULL;
    921 	struct mqueue *mq;
    922 	struct mq_attr attr;
    923 	int error;
    924 
    925 	/* Get the message queue */
    926 	error = mqueue_get(SCARG(uap, mqdes), &fp);
    927 	if (error)
    928 		return error;
    929 	mq = fp->f_data;
    930 	memcpy(&attr, &mq->mq_attrib, sizeof(struct mq_attr));
    931 	mutex_exit(&mq->mq_mtx);
    932 	fd_putfile((int)SCARG(uap, mqdes));
    933 
    934 	return copyout(&attr, SCARG(uap, mqstat), sizeof(struct mq_attr));
    935 }
    936 
    937 int
    938 sys_mq_setattr(struct lwp *l, const struct sys_mq_setattr_args *uap,
    939     register_t *retval)
    940 {
    941 	/* {
    942 		syscallarg(mqd_t) mqdes;
    943 		syscallarg(const struct mq_attr *) mqstat;
    944 		syscallarg(struct mq_attr *) omqstat;
    945 	} */
    946 	file_t *fp = NULL;
    947 	struct mqueue *mq;
    948 	struct mq_attr attr;
    949 	int error, nonblock;
    950 
    951 	error = copyin(SCARG(uap, mqstat), &attr, sizeof(struct mq_attr));
    952 	if (error)
    953 		return error;
    954 	nonblock = (attr.mq_flags & O_NONBLOCK);
    955 
    956 	/* Get the message queue */
    957 	error = mqueue_get(SCARG(uap, mqdes), &fp);
    958 	if (error)
    959 		return error;
    960 	mq = fp->f_data;
    961 
    962 	/* Copy the old attributes, if needed */
    963 	if (SCARG(uap, omqstat)) {
    964 		memcpy(&attr, &mq->mq_attrib, sizeof(struct mq_attr));
    965 	}
    966 
    967 	/* Ignore everything, except O_NONBLOCK */
    968 	if (nonblock)
    969 		mq->mq_attrib.mq_flags |= O_NONBLOCK;
    970 	else
    971 		mq->mq_attrib.mq_flags &= ~O_NONBLOCK;
    972 
    973 	mutex_exit(&mq->mq_mtx);
    974 	fd_putfile((int)SCARG(uap, mqdes));
    975 
    976 	/*
    977 	 * Copy the data to the user-space.
    978 	 * Note: According to POSIX, the new attributes should not be set in
    979 	 * case of fail - this would be violated.
    980 	 */
    981 	if (SCARG(uap, omqstat))
    982 		error = copyout(&attr, SCARG(uap, omqstat),
    983 		    sizeof(struct mq_attr));
    984 
    985 	return error;
    986 }
    987 
    988 int
    989 sys_mq_unlink(struct lwp *l, const struct sys_mq_unlink_args *uap,
    990     register_t *retval)
    991 {
    992 	/* {
    993 		syscallarg(const char *) name;
    994 	} */
    995 	struct mqueue *mq;
    996 	char *name;
    997 	int error, refcnt = 0;
    998 
    999 	/* Get the name from the user-space */
   1000 	name = kmem_zalloc(MQ_NAMELEN, KM_SLEEP);
   1001 	error = copyinstr(SCARG(uap, name), name, MQ_NAMELEN - 1, NULL);
   1002 	if (error) {
   1003 		kmem_free(name, MQ_NAMELEN);
   1004 		return error;
   1005 	}
   1006 
   1007 	/* Lookup for this file */
   1008 	mutex_enter(&mqlist_mtx);
   1009 	mq = mqueue_lookup(name);
   1010 	if (mq == NULL) {
   1011 		error = ENOENT;
   1012 		goto error;
   1013 	}
   1014 
   1015 	/* Check the permissions */
   1016 	if (kauth_cred_geteuid(l->l_cred) != mq->mq_euid &&
   1017 	    kauth_authorize_generic(l->l_cred, KAUTH_GENERIC_ISSUSER, NULL)) {
   1018 		mutex_exit(&mq->mq_mtx);
   1019 		error = EACCES;
   1020 		goto error;
   1021 	}
   1022 
   1023 	/* Mark message queue as unlinking, before leaving the window */
   1024 	mq->mq_attrib.mq_flags |= MQ_UNLINK;
   1025 
   1026 	/* Wake up all waiters, if there are such */
   1027 	cv_broadcast(&mq->mq_send_cv);
   1028 	cv_broadcast(&mq->mq_recv_cv);
   1029 
   1030 	selnotify(&mq->mq_rsel, POLLHUP, 0);
   1031 	selnotify(&mq->mq_wsel, POLLHUP, 0);
   1032 
   1033 	refcnt = mq->mq_refcnt;
   1034 	if (refcnt == 0)
   1035 		LIST_REMOVE(mq, mq_list);
   1036 
   1037 	mutex_exit(&mq->mq_mtx);
   1038 error:
   1039 	mutex_exit(&mqlist_mtx);
   1040 
   1041 	/*
   1042 	 * If there are no references - destroy the message
   1043 	 * queue, otherwise, the last mq_close() will do that.
   1044 	 */
   1045 	if (error == 0 && refcnt == 0)
   1046 		mqueue_destroy(mq);
   1047 
   1048 	kmem_free(name, MQ_NAMELEN);
   1049 	return error;
   1050 }
   1051 
   1052 /*
   1053  * System control nodes.
   1054  */
   1055 
   1056 SYSCTL_SETUP(sysctl_mqueue_setup, "sysctl mqueue setup")
   1057 {
   1058 	const struct sysctlnode *node = NULL;
   1059 
   1060 	sysctl_createv(clog, 0, NULL, NULL,
   1061 		CTLFLAG_PERMANENT,
   1062 		CTLTYPE_NODE, "kern", NULL,
   1063 		NULL, 0, NULL, 0,
   1064 		CTL_KERN, CTL_EOL);
   1065 	sysctl_createv(clog, 0, NULL, NULL,
   1066 		CTLFLAG_PERMANENT|CTLFLAG_IMMEDIATE,
   1067 		CTLTYPE_INT, "posix_msg",
   1068 		SYSCTL_DESCR("Version of IEEE Std 1003.1 and its "
   1069 			     "Message Passing option to which the "
   1070 			     "system attempts to conform"),
   1071 		NULL, _POSIX_MESSAGE_PASSING, NULL, 0,
   1072 		CTL_KERN, CTL_CREATE, CTL_EOL);
   1073 	sysctl_createv(clog, 0, NULL, &node,
   1074 		CTLFLAG_PERMANENT,
   1075 		CTLTYPE_NODE, "mqueue",
   1076 		SYSCTL_DESCR("Message queue options"),
   1077 		NULL, 0, NULL, 0,
   1078 		CTL_KERN, CTL_CREATE, CTL_EOL);
   1079 
   1080 	if (node == NULL)
   1081 		return;
   1082 
   1083 	sysctl_createv(clog, 0, &node, NULL,
   1084 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1085 		CTLTYPE_INT, "mq_open_max",
   1086 		SYSCTL_DESCR("Maximal number of message queue descriptors "
   1087 			     "that process could open"),
   1088 		NULL, 0, &mq_open_max, 0,
   1089 		CTL_CREATE, CTL_EOL);
   1090 	sysctl_createv(clog, 0, &node, NULL,
   1091 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1092 		CTLTYPE_INT, "mq_prio_max",
   1093 		SYSCTL_DESCR("Maximal priority of the message"),
   1094 		NULL, 0, &mq_prio_max, 0,
   1095 		CTL_CREATE, CTL_EOL);
   1096 	sysctl_createv(clog, 0, &node, NULL,
   1097 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1098 		CTLTYPE_INT, "mq_max_msgsize",
   1099 		SYSCTL_DESCR("Maximal allowed size of the message"),
   1100 		NULL, 0, &mq_max_msgsize, 0,
   1101 		CTL_CREATE, CTL_EOL);
   1102 	sysctl_createv(clog, 0, &node, NULL,
   1103 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   1104 		CTLTYPE_INT, "mq_def_maxmsg",
   1105 		SYSCTL_DESCR("Default maximal message count"),
   1106 		NULL, 0, &mq_def_maxmsg, 0,
   1107 		CTL_CREATE, CTL_EOL);
   1108 }
   1109 
   1110 /*
   1111  * Debugging.
   1112  */
   1113 #if defined(DDB)
   1114 
   1115 void
   1116 mqueue_print_list(void (*pr)(const char *, ...))
   1117 {
   1118 	struct mqueue *mq;
   1119 
   1120 	(*pr)("Global list of the message queues:\n");
   1121 	(*pr)("%20s %10s %8s %8s %3s %4s %4s %4s\n",
   1122 	    "Name", "Ptr", "Mode", "Flags",  "Ref",
   1123 	    "MaxMsg", "MsgSze", "CurMsg");
   1124 	LIST_FOREACH(mq, &mqueue_head, mq_list) {
   1125 		(*pr)("%20s %10p %8x %8x %3u %6lu %6lu %6lu\n",
   1126 		    mq->mq_name, mq, mq->mq_mode,
   1127 		    mq->mq_attrib.mq_flags, mq->mq_refcnt,
   1128 		    mq->mq_attrib.mq_maxmsg, mq->mq_attrib.mq_msgsize,
   1129 		    mq->mq_attrib.mq_curmsgs);
   1130 	}
   1131 }
   1132 
   1133 #endif /* defined(DDB) */
   1134