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