sysv_msg.c revision 166829
1/*-
2 * Implementation of SVID messages
3 *
4 * Author:  Daniel Boulet
5 *
6 * Copyright 1993 Daniel Boulet and RTMX Inc.
7 *
8 * This system call was implemented by Daniel Boulet under contract from RTMX.
9 *
10 * Redistribution and use in source forms, with and without modification,
11 * are permitted provided that this entire comment appears intact.
12 *
13 * Redistribution in binary form may occur without any restrictions.
14 * Obviously, it would be nice if you gave credit where credit is due
15 * but requiring it would be too onerous.
16 *
17 * This software is provided ``AS IS'' without any warranties of any kind.
18 */
19/*-
20 * Copyright (c) 2003-2005 McAfee, Inc.
21 * All rights reserved.
22 *
23 * This software was developed for the FreeBSD Project in part by McAfee
24 * Research, the Security Research Division of McAfee, Inc under DARPA/SPAWAR
25 * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS research
26 * program.
27 *
28 * Redistribution and use in source and binary forms, with or without
29 * modification, are permitted provided that the following conditions
30 * are met:
31 * 1. Redistributions of source code must retain the above copyright
32 *    notice, this list of conditions and the following disclaimer.
33 * 2. Redistributions in binary form must reproduce the above copyright
34 *    notice, this list of conditions and the following disclaimer in the
35 *    documentation and/or other materials provided with the distribution.
36 *
37 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
38 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
41 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
42 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
43 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
45 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
46 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * SUCH DAMAGE.
48 */
49
50#include <sys/cdefs.h>
51__FBSDID("$FreeBSD: head/sys/kern/sysv_msg.c 166829 2007-02-19 13:23:45Z rwatson $");
52
53#include "opt_sysvipc.h"
54#include "opt_mac.h"
55
56#include <sys/param.h>
57#include <sys/systm.h>
58#include <sys/sysproto.h>
59#include <sys/kernel.h>
60#include <sys/priv.h>
61#include <sys/proc.h>
62#include <sys/lock.h>
63#include <sys/mutex.h>
64#include <sys/module.h>
65#include <sys/msg.h>
66#include <sys/syscall.h>
67#include <sys/syscallsubr.h>
68#include <sys/sysent.h>
69#include <sys/sysctl.h>
70#include <sys/malloc.h>
71#include <sys/jail.h>
72
73#include <security/mac/mac_framework.h>
74
75static MALLOC_DEFINE(M_MSG, "msg", "SVID compatible message queues");
76
77static void msginit(void);
78static int msgunload(void);
79static int sysvmsg_modload(struct module *, int, void *);
80
81#ifdef MSG_DEBUG
82#define DPRINTF(a)	printf a
83#else
84#define DPRINTF(a)
85#endif
86
87static void msg_freehdr(struct msg *msghdr);
88
89/* XXX casting to (sy_call_t *) is bogus, as usual. */
90static sy_call_t *msgcalls[] = {
91	(sy_call_t *)msgctl, (sy_call_t *)msgget,
92	(sy_call_t *)msgsnd, (sy_call_t *)msgrcv
93};
94
95#ifndef MSGSSZ
96#define MSGSSZ	8		/* Each segment must be 2^N long */
97#endif
98#ifndef MSGSEG
99#define MSGSEG	2048		/* must be less than 32767 */
100#endif
101#define MSGMAX	(MSGSSZ*MSGSEG)
102#ifndef MSGMNB
103#define MSGMNB	2048		/* max # of bytes in a queue */
104#endif
105#ifndef MSGMNI
106#define MSGMNI	40
107#endif
108#ifndef MSGTQL
109#define MSGTQL	40
110#endif
111
112/*
113 * Based on the configuration parameters described in an SVR2 (yes, two)
114 * config(1m) man page.
115 *
116 * Each message is broken up and stored in segments that are msgssz bytes
117 * long.  For efficiency reasons, this should be a power of two.  Also,
118 * it doesn't make sense if it is less than 8 or greater than about 256.
119 * Consequently, msginit in kern/sysv_msg.c checks that msgssz is a power of
120 * two between 8 and 1024 inclusive (and panic's if it isn't).
121 */
122struct msginfo msginfo = {
123                MSGMAX,         /* max chars in a message */
124                MSGMNI,         /* # of message queue identifiers */
125                MSGMNB,         /* max chars in a queue */
126                MSGTQL,         /* max messages in system */
127                MSGSSZ,         /* size of a message segment */
128                		/* (must be small power of 2 greater than 4) */
129                MSGSEG          /* number of message segments */
130};
131
132/*
133 * macros to convert between msqid_ds's and msqid's.
134 * (specific to this implementation)
135 */
136#define MSQID(ix,ds)	((ix) & 0xffff | (((ds).msg_perm.seq << 16) & 0xffff0000))
137#define MSQID_IX(id)	((id) & 0xffff)
138#define MSQID_SEQ(id)	(((id) >> 16) & 0xffff)
139
140/*
141 * The rest of this file is specific to this particular implementation.
142 */
143
144struct msgmap {
145	short	next;		/* next segment in buffer */
146    				/* -1 -> available */
147    				/* 0..(MSGSEG-1) -> index of next segment */
148};
149
150#define MSG_LOCKED	01000	/* Is this msqid_ds locked? */
151
152static int nfree_msgmaps;	/* # of free map entries */
153static short free_msgmaps;	/* head of linked list of free map entries */
154static struct msg *free_msghdrs;/* list of free msg headers */
155static char *msgpool;		/* MSGMAX byte long msg buffer pool */
156static struct msgmap *msgmaps;	/* MSGSEG msgmap structures */
157static struct msg *msghdrs;	/* MSGTQL msg headers */
158static struct msqid_kernel *msqids;	/* MSGMNI msqid_kernel struct's */
159static struct mtx msq_mtx;	/* global mutex for message queues. */
160
161static void
162msginit()
163{
164	register int i;
165
166	TUNABLE_INT_FETCH("kern.ipc.msgseg", &msginfo.msgseg);
167	TUNABLE_INT_FETCH("kern.ipc.msgssz", &msginfo.msgssz);
168	msginfo.msgmax = msginfo.msgseg * msginfo.msgssz;
169	TUNABLE_INT_FETCH("kern.ipc.msgmni", &msginfo.msgmni);
170	TUNABLE_INT_FETCH("kern.ipc.msgmnb", &msginfo.msgmnb);
171	TUNABLE_INT_FETCH("kern.ipc.msgtql", &msginfo.msgtql);
172
173	msgpool = malloc(msginfo.msgmax, M_MSG, M_WAITOK);
174	if (msgpool == NULL)
175		panic("msgpool is NULL");
176	msgmaps = malloc(sizeof(struct msgmap) * msginfo.msgseg, M_MSG, M_WAITOK);
177	if (msgmaps == NULL)
178		panic("msgmaps is NULL");
179	msghdrs = malloc(sizeof(struct msg) * msginfo.msgtql, M_MSG, M_WAITOK);
180	if (msghdrs == NULL)
181		panic("msghdrs is NULL");
182	msqids = malloc(sizeof(struct msqid_kernel) * msginfo.msgmni, M_MSG,
183	    M_WAITOK);
184	if (msqids == NULL)
185		panic("msqids is NULL");
186
187	/*
188	 * msginfo.msgssz should be a power of two for efficiency reasons.
189	 * It is also pretty silly if msginfo.msgssz is less than 8
190	 * or greater than about 256 so ...
191	 */
192
193	i = 8;
194	while (i < 1024 && i != msginfo.msgssz)
195		i <<= 1;
196    	if (i != msginfo.msgssz) {
197		DPRINTF(("msginfo.msgssz=%d (0x%x)\n", msginfo.msgssz,
198		    msginfo.msgssz));
199		panic("msginfo.msgssz not a small power of 2");
200	}
201
202	if (msginfo.msgseg > 32767) {
203		DPRINTF(("msginfo.msgseg=%d\n", msginfo.msgseg));
204		panic("msginfo.msgseg > 32767");
205	}
206
207	if (msgmaps == NULL)
208		panic("msgmaps is NULL");
209
210	for (i = 0; i < msginfo.msgseg; i++) {
211		if (i > 0)
212			msgmaps[i-1].next = i;
213		msgmaps[i].next = -1;	/* implies entry is available */
214	}
215	free_msgmaps = 0;
216	nfree_msgmaps = msginfo.msgseg;
217
218	if (msghdrs == NULL)
219		panic("msghdrs is NULL");
220
221	for (i = 0; i < msginfo.msgtql; i++) {
222		msghdrs[i].msg_type = 0;
223		if (i > 0)
224			msghdrs[i-1].msg_next = &msghdrs[i];
225		msghdrs[i].msg_next = NULL;
226#ifdef MAC
227		mac_init_sysv_msgmsg(&msghdrs[i]);
228#endif
229    	}
230	free_msghdrs = &msghdrs[0];
231
232	if (msqids == NULL)
233		panic("msqids is NULL");
234
235	for (i = 0; i < msginfo.msgmni; i++) {
236		msqids[i].u.msg_qbytes = 0;	/* implies entry is available */
237		msqids[i].u.msg_perm.seq = 0;	/* reset to a known value */
238		msqids[i].u.msg_perm.mode = 0;
239#ifdef MAC
240		mac_init_sysv_msgqueue(&msqids[i]);
241#endif
242	}
243	mtx_init(&msq_mtx, "msq", NULL, MTX_DEF);
244}
245
246static int
247msgunload()
248{
249	struct msqid_kernel *msqkptr;
250	int msqid;
251#ifdef MAC
252	int i;
253#endif
254
255	for (msqid = 0; msqid < msginfo.msgmni; msqid++) {
256		/*
257		 * Look for an unallocated and unlocked msqid_ds.
258		 * msqid_ds's can be locked by msgsnd or msgrcv while
259		 * they are copying the message in/out.  We can't
260		 * re-use the entry until they release it.
261		 */
262		msqkptr = &msqids[msqid];
263		if (msqkptr->u.msg_qbytes != 0 ||
264		    (msqkptr->u.msg_perm.mode & MSG_LOCKED) != 0)
265			break;
266	}
267	if (msqid != msginfo.msgmni)
268		return (EBUSY);
269
270#ifdef MAC
271	for (i = 0; i < msginfo.msgtql; i++)
272		mac_destroy_sysv_msgmsg(&msghdrs[i]);
273	for (msqid = 0; msqid < msginfo.msgmni; msqid++)
274		mac_destroy_sysv_msgqueue(&msqids[msqid]);
275#endif
276	free(msgpool, M_MSG);
277	free(msgmaps, M_MSG);
278	free(msghdrs, M_MSG);
279	free(msqids, M_MSG);
280	mtx_destroy(&msq_mtx);
281	return (0);
282}
283
284
285static int
286sysvmsg_modload(struct module *module, int cmd, void *arg)
287{
288	int error = 0;
289
290	switch (cmd) {
291	case MOD_LOAD:
292		msginit();
293		break;
294	case MOD_UNLOAD:
295		error = msgunload();
296		break;
297	case MOD_SHUTDOWN:
298		break;
299	default:
300		error = EINVAL;
301		break;
302	}
303	return (error);
304}
305
306static moduledata_t sysvmsg_mod = {
307	"sysvmsg",
308	&sysvmsg_modload,
309	NULL
310};
311
312SYSCALL_MODULE_HELPER(msgsys);
313SYSCALL_MODULE_HELPER(msgctl);
314SYSCALL_MODULE_HELPER(msgget);
315SYSCALL_MODULE_HELPER(msgsnd);
316SYSCALL_MODULE_HELPER(msgrcv);
317
318DECLARE_MODULE(sysvmsg, sysvmsg_mod,
319	SI_SUB_SYSV_MSG, SI_ORDER_FIRST);
320MODULE_VERSION(sysvmsg, 1);
321
322/*
323 * Entry point for all MSG calls
324 *
325 * MPSAFE
326 */
327int
328msgsys(td, uap)
329	struct thread *td;
330	/* XXX actually varargs. */
331	struct msgsys_args /* {
332		int	which;
333		int	a2;
334		int	a3;
335		int	a4;
336		int	a5;
337		int	a6;
338	} */ *uap;
339{
340	int error;
341
342	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
343		return (ENOSYS);
344	if (uap->which < 0 ||
345	    uap->which >= sizeof(msgcalls)/sizeof(msgcalls[0]))
346		return (EINVAL);
347	error = (*msgcalls[uap->which])(td, &uap->a2);
348	return (error);
349}
350
351static void
352msg_freehdr(msghdr)
353	struct msg *msghdr;
354{
355	while (msghdr->msg_ts > 0) {
356		short next;
357		if (msghdr->msg_spot < 0 || msghdr->msg_spot >= msginfo.msgseg)
358			panic("msghdr->msg_spot out of range");
359		next = msgmaps[msghdr->msg_spot].next;
360		msgmaps[msghdr->msg_spot].next = free_msgmaps;
361		free_msgmaps = msghdr->msg_spot;
362		nfree_msgmaps++;
363		msghdr->msg_spot = next;
364		if (msghdr->msg_ts >= msginfo.msgssz)
365			msghdr->msg_ts -= msginfo.msgssz;
366		else
367			msghdr->msg_ts = 0;
368	}
369	if (msghdr->msg_spot != -1)
370		panic("msghdr->msg_spot != -1");
371	msghdr->msg_next = free_msghdrs;
372	free_msghdrs = msghdr;
373#ifdef MAC
374	mac_cleanup_sysv_msgmsg(msghdr);
375#endif
376}
377
378#ifndef _SYS_SYSPROTO_H_
379struct msgctl_args {
380	int	msqid;
381	int	cmd;
382	struct	msqid_ds *buf;
383};
384#endif
385
386/*
387 * MPSAFE
388 */
389int
390msgctl(td, uap)
391	struct thread *td;
392	register struct msgctl_args *uap;
393{
394	int msqid = uap->msqid;
395	int cmd = uap->cmd;
396	struct msqid_ds msqbuf;
397	int error;
398
399	DPRINTF(("call to msgctl(%d, %d, %p)\n", msqid, cmd, uap->buf));
400	if (cmd == IPC_SET &&
401	    (error = copyin(uap->buf, &msqbuf, sizeof(msqbuf))) != 0)
402		return (error);
403	error = kern_msgctl(td, msqid, cmd, &msqbuf);
404	if (cmd == IPC_STAT && error == 0)
405		error = copyout(&msqbuf, uap->buf, sizeof(struct msqid_ds));
406	return (error);
407}
408
409int
410kern_msgctl(td, msqid, cmd, msqbuf)
411	struct thread *td;
412	int msqid;
413	int cmd;
414	struct msqid_ds *msqbuf;
415{
416	int rval, error, msqix;
417	register struct msqid_kernel *msqkptr;
418
419	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
420		return (ENOSYS);
421
422	msqix = IPCID_TO_IX(msqid);
423
424	if (msqix < 0 || msqix >= msginfo.msgmni) {
425		DPRINTF(("msqid (%d) out of range (0<=msqid<%d)\n", msqix,
426		    msginfo.msgmni));
427		return (EINVAL);
428	}
429
430	msqkptr = &msqids[msqix];
431
432	mtx_lock(&msq_mtx);
433	if (msqkptr->u.msg_qbytes == 0) {
434		DPRINTF(("no such msqid\n"));
435		error = EINVAL;
436		goto done2;
437	}
438	if (msqkptr->u.msg_perm.seq != IPCID_TO_SEQ(msqid)) {
439		DPRINTF(("wrong sequence number\n"));
440		error = EINVAL;
441		goto done2;
442	}
443#ifdef MAC
444	error = mac_check_sysv_msqctl(td->td_ucred, msqkptr, cmd);
445	if (error != 0)
446		goto done2;
447#endif
448
449	error = 0;
450	rval = 0;
451
452	switch (cmd) {
453
454	case IPC_RMID:
455	{
456		struct msg *msghdr;
457		if ((error = ipcperm(td, &msqkptr->u.msg_perm, IPC_M)))
458			goto done2;
459
460#ifdef MAC
461		/*
462		 * Check that the thread has MAC access permissions to
463		 * individual msghdrs.  Note: We need to do this in a
464		 * separate loop because the actual loop alters the
465		 * msq/msghdr info as it progresses, and there is no going
466		 * back if half the way through we discover that the
467		 * thread cannot free a certain msghdr.  The msq will get
468		 * into an inconsistent state.
469		 */
470		for (msghdr = msqkptr->u.msg_first; msghdr != NULL;
471		    msghdr = msghdr->msg_next) {
472			error = mac_check_sysv_msgrmid(td->td_ucred, msghdr);
473			if (error != 0)
474				goto done2;
475		}
476#endif
477
478		/* Free the message headers */
479		msghdr = msqkptr->u.msg_first;
480		while (msghdr != NULL) {
481			struct msg *msghdr_tmp;
482
483			/* Free the segments of each message */
484			msqkptr->u.msg_cbytes -= msghdr->msg_ts;
485			msqkptr->u.msg_qnum--;
486			msghdr_tmp = msghdr;
487			msghdr = msghdr->msg_next;
488			msg_freehdr(msghdr_tmp);
489		}
490
491		if (msqkptr->u.msg_cbytes != 0)
492			panic("msg_cbytes is screwed up");
493		if (msqkptr->u.msg_qnum != 0)
494			panic("msg_qnum is screwed up");
495
496		msqkptr->u.msg_qbytes = 0;	/* Mark it as free */
497
498#ifdef MAC
499		mac_cleanup_sysv_msgqueue(msqkptr);
500#endif
501
502		wakeup(msqkptr);
503	}
504
505		break;
506
507	case IPC_SET:
508		if ((error = ipcperm(td, &msqkptr->u.msg_perm, IPC_M)))
509			goto done2;
510		if (msqbuf->msg_qbytes > msqkptr->u.msg_qbytes) {
511			error = priv_check_cred(td->td_ucred,
512			    PRIV_IPC_MSGSIZE, SUSER_ALLOWJAIL);
513			if (error)
514				goto done2;
515		}
516		if (msqbuf->msg_qbytes > msginfo.msgmnb) {
517			DPRINTF(("can't increase msg_qbytes beyond %d"
518			    "(truncating)\n", msginfo.msgmnb));
519			msqbuf->msg_qbytes = msginfo.msgmnb;	/* silently restrict qbytes to system limit */
520		}
521		if (msqbuf->msg_qbytes == 0) {
522			DPRINTF(("can't reduce msg_qbytes to 0\n"));
523			error = EINVAL;		/* non-standard errno! */
524			goto done2;
525		}
526		msqkptr->u.msg_perm.uid = msqbuf->msg_perm.uid;	/* change the owner */
527		msqkptr->u.msg_perm.gid = msqbuf->msg_perm.gid;	/* change the owner */
528		msqkptr->u.msg_perm.mode = (msqkptr->u.msg_perm.mode & ~0777) |
529		    (msqbuf->msg_perm.mode & 0777);
530		msqkptr->u.msg_qbytes = msqbuf->msg_qbytes;
531		msqkptr->u.msg_ctime = time_second;
532		break;
533
534	case IPC_STAT:
535		if ((error = ipcperm(td, &msqkptr->u.msg_perm, IPC_R))) {
536			DPRINTF(("requester doesn't have read access\n"));
537			goto done2;
538		}
539		*msqbuf = msqkptr->u;
540		break;
541
542	default:
543		DPRINTF(("invalid command %d\n", cmd));
544		error = EINVAL;
545		goto done2;
546	}
547
548	if (error == 0)
549		td->td_retval[0] = rval;
550done2:
551	mtx_unlock(&msq_mtx);
552	return (error);
553}
554
555#ifndef _SYS_SYSPROTO_H_
556struct msgget_args {
557	key_t	key;
558	int	msgflg;
559};
560#endif
561
562/*
563 * MPSAFE
564 */
565int
566msgget(td, uap)
567	struct thread *td;
568	register struct msgget_args *uap;
569{
570	int msqid, error = 0;
571	int key = uap->key;
572	int msgflg = uap->msgflg;
573	struct ucred *cred = td->td_ucred;
574	register struct msqid_kernel *msqkptr = NULL;
575
576	DPRINTF(("msgget(0x%x, 0%o)\n", key, msgflg));
577
578	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
579		return (ENOSYS);
580
581	mtx_lock(&msq_mtx);
582	if (key != IPC_PRIVATE) {
583		for (msqid = 0; msqid < msginfo.msgmni; msqid++) {
584			msqkptr = &msqids[msqid];
585			if (msqkptr->u.msg_qbytes != 0 &&
586			    msqkptr->u.msg_perm.key == key)
587				break;
588		}
589		if (msqid < msginfo.msgmni) {
590			DPRINTF(("found public key\n"));
591			if ((msgflg & IPC_CREAT) && (msgflg & IPC_EXCL)) {
592				DPRINTF(("not exclusive\n"));
593				error = EEXIST;
594				goto done2;
595			}
596			if ((error = ipcperm(td, &msqkptr->u.msg_perm,
597			    msgflg & 0700))) {
598				DPRINTF(("requester doesn't have 0%o access\n",
599				    msgflg & 0700));
600				goto done2;
601			}
602#ifdef MAC
603			error = mac_check_sysv_msqget(cred, msqkptr);
604			if (error != 0)
605				goto done2;
606#endif
607			goto found;
608		}
609	}
610
611	DPRINTF(("need to allocate the msqid_ds\n"));
612	if (key == IPC_PRIVATE || (msgflg & IPC_CREAT)) {
613		for (msqid = 0; msqid < msginfo.msgmni; msqid++) {
614			/*
615			 * Look for an unallocated and unlocked msqid_ds.
616			 * msqid_ds's can be locked by msgsnd or msgrcv while
617			 * they are copying the message in/out.  We can't
618			 * re-use the entry until they release it.
619			 */
620			msqkptr = &msqids[msqid];
621			if (msqkptr->u.msg_qbytes == 0 &&
622			    (msqkptr->u.msg_perm.mode & MSG_LOCKED) == 0)
623				break;
624		}
625		if (msqid == msginfo.msgmni) {
626			DPRINTF(("no more msqid_ds's available\n"));
627			error = ENOSPC;
628			goto done2;
629		}
630		DPRINTF(("msqid %d is available\n", msqid));
631		msqkptr->u.msg_perm.key = key;
632		msqkptr->u.msg_perm.cuid = cred->cr_uid;
633		msqkptr->u.msg_perm.uid = cred->cr_uid;
634		msqkptr->u.msg_perm.cgid = cred->cr_gid;
635		msqkptr->u.msg_perm.gid = cred->cr_gid;
636		msqkptr->u.msg_perm.mode = (msgflg & 0777);
637		/* Make sure that the returned msqid is unique */
638		msqkptr->u.msg_perm.seq = (msqkptr->u.msg_perm.seq + 1) & 0x7fff;
639		msqkptr->u.msg_first = NULL;
640		msqkptr->u.msg_last = NULL;
641		msqkptr->u.msg_cbytes = 0;
642		msqkptr->u.msg_qnum = 0;
643		msqkptr->u.msg_qbytes = msginfo.msgmnb;
644		msqkptr->u.msg_lspid = 0;
645		msqkptr->u.msg_lrpid = 0;
646		msqkptr->u.msg_stime = 0;
647		msqkptr->u.msg_rtime = 0;
648		msqkptr->u.msg_ctime = time_second;
649#ifdef MAC
650		mac_create_sysv_msgqueue(cred, msqkptr);
651#endif
652	} else {
653		DPRINTF(("didn't find it and wasn't asked to create it\n"));
654		error = ENOENT;
655		goto done2;
656	}
657
658found:
659	/* Construct the unique msqid */
660	td->td_retval[0] = IXSEQ_TO_IPCID(msqid, msqkptr->u.msg_perm);
661done2:
662	mtx_unlock(&msq_mtx);
663	return (error);
664}
665
666#ifndef _SYS_SYSPROTO_H_
667struct msgsnd_args {
668	int	msqid;
669	const void	*msgp;
670	size_t	msgsz;
671	int	msgflg;
672};
673#endif
674
675int
676kern_msgsnd(td, msqid, msgp, msgsz, msgflg, mtype)
677	struct thread *td;
678	int msqid;
679	const void *msgp;	/* XXX msgp is actually mtext. */
680	size_t msgsz;
681	int msgflg;
682	long mtype;
683{
684	int msqix, segs_needed, error = 0;
685	register struct msqid_kernel *msqkptr;
686	register struct msg *msghdr;
687	short next;
688
689	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
690		return (ENOSYS);
691
692	mtx_lock(&msq_mtx);
693	msqix = IPCID_TO_IX(msqid);
694
695	if (msqix < 0 || msqix >= msginfo.msgmni) {
696		DPRINTF(("msqid (%d) out of range (0<=msqid<%d)\n", msqix,
697		    msginfo.msgmni));
698		error = EINVAL;
699		goto done2;
700	}
701
702	msqkptr = &msqids[msqix];
703	if (msqkptr->u.msg_qbytes == 0) {
704		DPRINTF(("no such message queue id\n"));
705		error = EINVAL;
706		goto done2;
707	}
708	if (msqkptr->u.msg_perm.seq != IPCID_TO_SEQ(msqid)) {
709		DPRINTF(("wrong sequence number\n"));
710		error = EINVAL;
711		goto done2;
712	}
713
714	if ((error = ipcperm(td, &msqkptr->u.msg_perm, IPC_W))) {
715		DPRINTF(("requester doesn't have write access\n"));
716		goto done2;
717	}
718
719#ifdef MAC
720	error = mac_check_sysv_msqsnd(td->td_ucred, msqkptr);
721	if (error != 0)
722		goto done2;
723#endif
724
725	segs_needed = (msgsz + msginfo.msgssz - 1) / msginfo.msgssz;
726	DPRINTF(("msgsz=%zu, msgssz=%d, segs_needed=%d\n", msgsz,
727	    msginfo.msgssz, segs_needed));
728	for (;;) {
729		int need_more_resources = 0;
730
731		/*
732		 * check msgsz
733		 * (inside this loop in case msg_qbytes changes while we sleep)
734		 */
735
736		if (msgsz > msqkptr->u.msg_qbytes) {
737			DPRINTF(("msgsz > msqkptr->u.msg_qbytes\n"));
738			error = EINVAL;
739			goto done2;
740		}
741
742		if (msqkptr->u.msg_perm.mode & MSG_LOCKED) {
743			DPRINTF(("msqid is locked\n"));
744			need_more_resources = 1;
745		}
746		if (msgsz + msqkptr->u.msg_cbytes > msqkptr->u.msg_qbytes) {
747			DPRINTF(("msgsz + msg_cbytes > msg_qbytes\n"));
748			need_more_resources = 1;
749		}
750		if (segs_needed > nfree_msgmaps) {
751			DPRINTF(("segs_needed > nfree_msgmaps\n"));
752			need_more_resources = 1;
753		}
754		if (free_msghdrs == NULL) {
755			DPRINTF(("no more msghdrs\n"));
756			need_more_resources = 1;
757		}
758
759		if (need_more_resources) {
760			int we_own_it;
761
762			if ((msgflg & IPC_NOWAIT) != 0) {
763				DPRINTF(("need more resources but caller "
764				    "doesn't want to wait\n"));
765				error = EAGAIN;
766				goto done2;
767			}
768
769			if ((msqkptr->u.msg_perm.mode & MSG_LOCKED) != 0) {
770				DPRINTF(("we don't own the msqid_ds\n"));
771				we_own_it = 0;
772			} else {
773				/* Force later arrivals to wait for our
774				   request */
775				DPRINTF(("we own the msqid_ds\n"));
776				msqkptr->u.msg_perm.mode |= MSG_LOCKED;
777				we_own_it = 1;
778			}
779			DPRINTF(("msgsnd:  goodnight\n"));
780			error = msleep(msqkptr, &msq_mtx, (PZERO - 4) | PCATCH,
781			    "msgsnd", hz);
782			DPRINTF(("msgsnd:  good morning, error=%d\n", error));
783			if (we_own_it)
784				msqkptr->u.msg_perm.mode &= ~MSG_LOCKED;
785			if (error == EWOULDBLOCK) {
786				DPRINTF(("msgsnd:  timed out\n"));
787				continue;
788			}
789			if (error != 0) {
790				DPRINTF(("msgsnd:  interrupted system call\n"));
791				error = EINTR;
792				goto done2;
793			}
794
795			/*
796			 * Make sure that the msq queue still exists
797			 */
798
799			if (msqkptr->u.msg_qbytes == 0) {
800				DPRINTF(("msqid deleted\n"));
801				error = EIDRM;
802				goto done2;
803			}
804
805		} else {
806			DPRINTF(("got all the resources that we need\n"));
807			break;
808		}
809	}
810
811	/*
812	 * We have the resources that we need.
813	 * Make sure!
814	 */
815
816	if (msqkptr->u.msg_perm.mode & MSG_LOCKED)
817		panic("msg_perm.mode & MSG_LOCKED");
818	if (segs_needed > nfree_msgmaps)
819		panic("segs_needed > nfree_msgmaps");
820	if (msgsz + msqkptr->u.msg_cbytes > msqkptr->u.msg_qbytes)
821		panic("msgsz + msg_cbytes > msg_qbytes");
822	if (free_msghdrs == NULL)
823		panic("no more msghdrs");
824
825	/*
826	 * Re-lock the msqid_ds in case we page-fault when copying in the
827	 * message
828	 */
829
830	if ((msqkptr->u.msg_perm.mode & MSG_LOCKED) != 0)
831		panic("msqid_ds is already locked");
832	msqkptr->u.msg_perm.mode |= MSG_LOCKED;
833
834	/*
835	 * Allocate a message header
836	 */
837
838	msghdr = free_msghdrs;
839	free_msghdrs = msghdr->msg_next;
840	msghdr->msg_spot = -1;
841	msghdr->msg_ts = msgsz;
842	msghdr->msg_type = mtype;
843#ifdef MAC
844	/*
845	 * XXXMAC: Should the mac_check_sysv_msgmsq check follow here
846	 * immediately?  Or, should it be checked just before the msg is
847	 * enqueued in the msgq (as it is done now)?
848	 */
849	mac_create_sysv_msgmsg(td->td_ucred, msqkptr, msghdr);
850#endif
851
852	/*
853	 * Allocate space for the message
854	 */
855
856	while (segs_needed > 0) {
857		if (nfree_msgmaps <= 0)
858			panic("not enough msgmaps");
859		if (free_msgmaps == -1)
860			panic("nil free_msgmaps");
861		next = free_msgmaps;
862		if (next <= -1)
863			panic("next too low #1");
864		if (next >= msginfo.msgseg)
865			panic("next out of range #1");
866		DPRINTF(("allocating segment %d to message\n", next));
867		free_msgmaps = msgmaps[next].next;
868		nfree_msgmaps--;
869		msgmaps[next].next = msghdr->msg_spot;
870		msghdr->msg_spot = next;
871		segs_needed--;
872	}
873
874	/*
875	 * Validate the message type
876	 */
877
878	if (msghdr->msg_type < 1) {
879		msg_freehdr(msghdr);
880		msqkptr->u.msg_perm.mode &= ~MSG_LOCKED;
881		wakeup(msqkptr);
882		DPRINTF(("mtype (%ld) < 1\n", msghdr->msg_type));
883		error = EINVAL;
884		goto done2;
885	}
886
887	/*
888	 * Copy in the message body
889	 */
890
891	next = msghdr->msg_spot;
892	while (msgsz > 0) {
893		size_t tlen;
894		if (msgsz > msginfo.msgssz)
895			tlen = msginfo.msgssz;
896		else
897			tlen = msgsz;
898		if (next <= -1)
899			panic("next too low #2");
900		if (next >= msginfo.msgseg)
901			panic("next out of range #2");
902		mtx_unlock(&msq_mtx);
903		if ((error = copyin(msgp, &msgpool[next * msginfo.msgssz],
904		    tlen)) != 0) {
905			mtx_lock(&msq_mtx);
906			DPRINTF(("error %d copying in message segment\n",
907			    error));
908			msg_freehdr(msghdr);
909			msqkptr->u.msg_perm.mode &= ~MSG_LOCKED;
910			wakeup(msqkptr);
911			goto done2;
912		}
913		mtx_lock(&msq_mtx);
914		msgsz -= tlen;
915		msgp = (const char *)msgp + tlen;
916		next = msgmaps[next].next;
917	}
918	if (next != -1)
919		panic("didn't use all the msg segments");
920
921	/*
922	 * We've got the message.  Unlock the msqid_ds.
923	 */
924
925	msqkptr->u.msg_perm.mode &= ~MSG_LOCKED;
926
927	/*
928	 * Make sure that the msqid_ds is still allocated.
929	 */
930
931	if (msqkptr->u.msg_qbytes == 0) {
932		msg_freehdr(msghdr);
933		wakeup(msqkptr);
934		error = EIDRM;
935		goto done2;
936	}
937
938#ifdef MAC
939	/*
940	 * Note: Since the task/thread allocates the msghdr and usually
941	 * primes it with its own MAC label, for a majority of policies, it
942	 * won't be necessary to check whether the msghdr has access
943	 * permissions to the msgq.  The mac_check_sysv_msqsnd check would
944	 * suffice in that case.  However, this hook may be required where
945	 * individual policies derive a non-identical label for the msghdr
946	 * from the current thread label and may want to check the msghdr
947	 * enqueue permissions, along with read/write permissions to the
948	 * msgq.
949	 */
950	error = mac_check_sysv_msgmsq(td->td_ucred, msghdr, msqkptr);
951	if (error != 0) {
952		msg_freehdr(msghdr);
953		wakeup(msqkptr);
954		goto done2;
955	}
956#endif
957
958	/*
959	 * Put the message into the queue
960	 */
961	if (msqkptr->u.msg_first == NULL) {
962		msqkptr->u.msg_first = msghdr;
963		msqkptr->u.msg_last = msghdr;
964	} else {
965		msqkptr->u.msg_last->msg_next = msghdr;
966		msqkptr->u.msg_last = msghdr;
967	}
968	msqkptr->u.msg_last->msg_next = NULL;
969
970	msqkptr->u.msg_cbytes += msghdr->msg_ts;
971	msqkptr->u.msg_qnum++;
972	msqkptr->u.msg_lspid = td->td_proc->p_pid;
973	msqkptr->u.msg_stime = time_second;
974
975	wakeup(msqkptr);
976	td->td_retval[0] = 0;
977done2:
978	mtx_unlock(&msq_mtx);
979	return (error);
980}
981
982/*
983 * MPSAFE
984 */
985int
986msgsnd(td, uap)
987	struct thread *td;
988	register struct msgsnd_args *uap;
989{
990	int error;
991	long mtype;
992
993	DPRINTF(("call to msgsnd(%d, %p, %zu, %d)\n", uap->msqid, uap->msgp,
994	    uap->msgsz, uap->msgflg));
995
996	if ((error = copyin(uap->msgp, &mtype, sizeof(mtype))) != 0) {
997		DPRINTF(("error %d copying the message type\n", error));
998		return (error);
999	}
1000	return (kern_msgsnd(td, uap->msqid,
1001	    (const char *)uap->msgp + sizeof(mtype),
1002	    uap->msgsz, uap->msgflg, mtype));
1003}
1004
1005#ifndef _SYS_SYSPROTO_H_
1006struct msgrcv_args {
1007	int	msqid;
1008	void	*msgp;
1009	size_t	msgsz;
1010	long	msgtyp;
1011	int	msgflg;
1012};
1013#endif
1014
1015int
1016kern_msgrcv(td, msqid, msgp, msgsz, msgtyp, msgflg, mtype)
1017	struct thread *td;
1018	int msqid;
1019	void *msgp;	/* XXX msgp is actually mtext. */
1020	size_t msgsz;
1021	long msgtyp;
1022	int msgflg;
1023	long *mtype;
1024{
1025	size_t len;
1026	register struct msqid_kernel *msqkptr;
1027	register struct msg *msghdr;
1028	int msqix, error = 0;
1029	short next;
1030
1031	if (!jail_sysvipc_allowed && jailed(td->td_ucred))
1032		return (ENOSYS);
1033
1034	msqix = IPCID_TO_IX(msqid);
1035
1036	if (msqix < 0 || msqix >= msginfo.msgmni) {
1037		DPRINTF(("msqid (%d) out of range (0<=msqid<%d)\n", msqix,
1038		    msginfo.msgmni));
1039		return (EINVAL);
1040	}
1041
1042	msqkptr = &msqids[msqix];
1043	mtx_lock(&msq_mtx);
1044	if (msqkptr->u.msg_qbytes == 0) {
1045		DPRINTF(("no such message queue id\n"));
1046		error = EINVAL;
1047		goto done2;
1048	}
1049	if (msqkptr->u.msg_perm.seq != IPCID_TO_SEQ(msqid)) {
1050		DPRINTF(("wrong sequence number\n"));
1051		error = EINVAL;
1052		goto done2;
1053	}
1054
1055	if ((error = ipcperm(td, &msqkptr->u.msg_perm, IPC_R))) {
1056		DPRINTF(("requester doesn't have read access\n"));
1057		goto done2;
1058	}
1059
1060#ifdef MAC
1061	error = mac_check_sysv_msqrcv(td->td_ucred, msqkptr);
1062	if (error != 0)
1063		goto done2;
1064#endif
1065
1066	msghdr = NULL;
1067	while (msghdr == NULL) {
1068		if (msgtyp == 0) {
1069			msghdr = msqkptr->u.msg_first;
1070			if (msghdr != NULL) {
1071				if (msgsz < msghdr->msg_ts &&
1072				    (msgflg & MSG_NOERROR) == 0) {
1073					DPRINTF(("first message on the queue "
1074					    "is too big (want %zu, got %d)\n",
1075					    msgsz, msghdr->msg_ts));
1076					error = E2BIG;
1077					goto done2;
1078				}
1079#ifdef MAC
1080				error = mac_check_sysv_msgrcv(td->td_ucred,
1081				    msghdr);
1082				if (error != 0)
1083					goto done2;
1084#endif
1085				if (msqkptr->u.msg_first == msqkptr->u.msg_last) {
1086					msqkptr->u.msg_first = NULL;
1087					msqkptr->u.msg_last = NULL;
1088				} else {
1089					msqkptr->u.msg_first = msghdr->msg_next;
1090					if (msqkptr->u.msg_first == NULL)
1091						panic("msg_first/last screwed up #1");
1092				}
1093			}
1094		} else {
1095			struct msg *previous;
1096			struct msg **prev;
1097
1098			previous = NULL;
1099			prev = &(msqkptr->u.msg_first);
1100			while ((msghdr = *prev) != NULL) {
1101				/*
1102				 * Is this message's type an exact match or is
1103				 * this message's type less than or equal to
1104				 * the absolute value of a negative msgtyp?
1105				 * Note that the second half of this test can
1106				 * NEVER be true if msgtyp is positive since
1107				 * msg_type is always positive!
1108				 */
1109
1110				if (msgtyp == msghdr->msg_type ||
1111				    msghdr->msg_type <= -msgtyp) {
1112					DPRINTF(("found message type %ld, "
1113					    "requested %ld\n",
1114					    msghdr->msg_type, msgtyp));
1115					if (msgsz < msghdr->msg_ts &&
1116					    (msgflg & MSG_NOERROR) == 0) {
1117						DPRINTF(("requested message "
1118						    "on the queue is too big "
1119						    "(want %zu, got %hu)\n",
1120						    msgsz, msghdr->msg_ts));
1121						error = E2BIG;
1122						goto done2;
1123					}
1124#ifdef MAC
1125					error = mac_check_sysv_msgrcv(
1126					    td->td_ucred, msghdr);
1127					if (error != 0)
1128						goto done2;
1129#endif
1130					*prev = msghdr->msg_next;
1131					if (msghdr == msqkptr->u.msg_last) {
1132						if (previous == NULL) {
1133							if (prev !=
1134							    &msqkptr->u.msg_first)
1135								panic("msg_first/last screwed up #2");
1136							msqkptr->u.msg_first =
1137							    NULL;
1138							msqkptr->u.msg_last =
1139							    NULL;
1140						} else {
1141							if (prev ==
1142							    &msqkptr->u.msg_first)
1143								panic("msg_first/last screwed up #3");
1144							msqkptr->u.msg_last =
1145							    previous;
1146						}
1147					}
1148					break;
1149				}
1150				previous = msghdr;
1151				prev = &(msghdr->msg_next);
1152			}
1153		}
1154
1155		/*
1156		 * We've either extracted the msghdr for the appropriate
1157		 * message or there isn't one.
1158		 * If there is one then bail out of this loop.
1159		 */
1160
1161		if (msghdr != NULL)
1162			break;
1163
1164		/*
1165		 * Hmph!  No message found.  Does the user want to wait?
1166		 */
1167
1168		if ((msgflg & IPC_NOWAIT) != 0) {
1169			DPRINTF(("no appropriate message found (msgtyp=%ld)\n",
1170			    msgtyp));
1171			/* The SVID says to return ENOMSG. */
1172			error = ENOMSG;
1173			goto done2;
1174		}
1175
1176		/*
1177		 * Wait for something to happen
1178		 */
1179
1180		DPRINTF(("msgrcv:  goodnight\n"));
1181		error = msleep(msqkptr, &msq_mtx, (PZERO - 4) | PCATCH,
1182		    "msgrcv", 0);
1183		DPRINTF(("msgrcv:  good morning (error=%d)\n", error));
1184
1185		if (error != 0) {
1186			DPRINTF(("msgrcv:  interrupted system call\n"));
1187			error = EINTR;
1188			goto done2;
1189		}
1190
1191		/*
1192		 * Make sure that the msq queue still exists
1193		 */
1194
1195		if (msqkptr->u.msg_qbytes == 0 ||
1196		    msqkptr->u.msg_perm.seq != IPCID_TO_SEQ(msqid)) {
1197			DPRINTF(("msqid deleted\n"));
1198			error = EIDRM;
1199			goto done2;
1200		}
1201	}
1202
1203	/*
1204	 * Return the message to the user.
1205	 *
1206	 * First, do the bookkeeping (before we risk being interrupted).
1207	 */
1208
1209	msqkptr->u.msg_cbytes -= msghdr->msg_ts;
1210	msqkptr->u.msg_qnum--;
1211	msqkptr->u.msg_lrpid = td->td_proc->p_pid;
1212	msqkptr->u.msg_rtime = time_second;
1213
1214	/*
1215	 * Make msgsz the actual amount that we'll be returning.
1216	 * Note that this effectively truncates the message if it is too long
1217	 * (since msgsz is never increased).
1218	 */
1219
1220	DPRINTF(("found a message, msgsz=%zu, msg_ts=%hu\n", msgsz,
1221	    msghdr->msg_ts));
1222	if (msgsz > msghdr->msg_ts)
1223		msgsz = msghdr->msg_ts;
1224	*mtype = msghdr->msg_type;
1225
1226	/*
1227	 * Return the segments to the user
1228	 */
1229
1230	next = msghdr->msg_spot;
1231	for (len = 0; len < msgsz; len += msginfo.msgssz) {
1232		size_t tlen;
1233
1234		if (msgsz - len > msginfo.msgssz)
1235			tlen = msginfo.msgssz;
1236		else
1237			tlen = msgsz - len;
1238		if (next <= -1)
1239			panic("next too low #3");
1240		if (next >= msginfo.msgseg)
1241			panic("next out of range #3");
1242		mtx_unlock(&msq_mtx);
1243		error = copyout(&msgpool[next * msginfo.msgssz], msgp, tlen);
1244		mtx_lock(&msq_mtx);
1245		if (error != 0) {
1246			DPRINTF(("error (%d) copying out message segment\n",
1247			    error));
1248			msg_freehdr(msghdr);
1249			wakeup(msqkptr);
1250			goto done2;
1251		}
1252		msgp = (char *)msgp + tlen;
1253		next = msgmaps[next].next;
1254	}
1255
1256	/*
1257	 * Done, return the actual number of bytes copied out.
1258	 */
1259
1260	msg_freehdr(msghdr);
1261	wakeup(msqkptr);
1262	td->td_retval[0] = msgsz;
1263done2:
1264	mtx_unlock(&msq_mtx);
1265	return (error);
1266}
1267
1268/*
1269 * MPSAFE
1270 */
1271int
1272msgrcv(td, uap)
1273	struct thread *td;
1274	register struct msgrcv_args *uap;
1275{
1276	int error;
1277	long mtype;
1278
1279	DPRINTF(("call to msgrcv(%d, %p, %zu, %ld, %d)\n", uap->msqid,
1280	    uap->msgp, uap->msgsz, uap->msgtyp, uap->msgflg));
1281
1282	if ((error = kern_msgrcv(td, uap->msqid,
1283	    (char *)uap->msgp + sizeof(mtype), uap->msgsz,
1284	    uap->msgtyp, uap->msgflg, &mtype)) != 0)
1285		return (error);
1286	if ((error = copyout(&mtype, uap->msgp, sizeof(mtype))) != 0)
1287		DPRINTF(("error %d copying the message type\n", error));
1288	return (error);
1289}
1290
1291static int
1292sysctl_msqids(SYSCTL_HANDLER_ARGS)
1293{
1294
1295	return (SYSCTL_OUT(req, msqids,
1296	    sizeof(struct msqid_kernel) * msginfo.msgmni));
1297}
1298
1299SYSCTL_INT(_kern_ipc, OID_AUTO, msgmax, CTLFLAG_RD, &msginfo.msgmax, 0,
1300    "Maximum message size");
1301SYSCTL_INT(_kern_ipc, OID_AUTO, msgmni, CTLFLAG_RDTUN, &msginfo.msgmni, 0,
1302    "Number of message queue identifiers");
1303SYSCTL_INT(_kern_ipc, OID_AUTO, msgmnb, CTLFLAG_RDTUN, &msginfo.msgmnb, 0,
1304    "Maximum number of bytes in a queue");
1305SYSCTL_INT(_kern_ipc, OID_AUTO, msgtql, CTLFLAG_RDTUN, &msginfo.msgtql, 0,
1306    "Maximum number of messages in the system");
1307SYSCTL_INT(_kern_ipc, OID_AUTO, msgssz, CTLFLAG_RDTUN, &msginfo.msgssz, 0,
1308    "Size of a message segment");
1309SYSCTL_INT(_kern_ipc, OID_AUTO, msgseg, CTLFLAG_RDTUN, &msginfo.msgseg, 0,
1310    "Number of message segments");
1311SYSCTL_PROC(_kern_ipc, OID_AUTO, msqids, CTLFLAG_RD,
1312    NULL, 0, sysctl_msqids, "", "Message queue IDs");
1313