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