xref: /titanic_50/usr/src/uts/common/os/msg.c (revision 672986541be54a7a471bb088e60780c37e371d7e)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
27 /*	  All Rights Reserved  	*/
28 
29 
30 #pragma ident	"%Z%%M%	%I%	%E% SMI"
31 
32 /*
33  * Inter-Process Communication Message Facility.
34  *
35  * See os/ipc.c for a description of common IPC functionality.
36  *
37  * Resource controls
38  * -----------------
39  *
40  * Control:      zone.max-msg-ids (rc_zone_msgmni)
41  * Description:  Maximum number of message queue ids allowed a zone.
42  *
43  *   When msgget() is used to allocate a message queue, one id is
44  *   allocated.  If the id allocation doesn't succeed, msgget() fails
45  *   and errno is set to ENOSPC.  Upon successful msgctl(, IPC_RMID)
46  *   the id is deallocated.
47  *
48  * Control:      project.max-msg-ids (rc_project_msgmni)
49  * Description:  Maximum number of message queue ids allowed a project.
50  *
51  *   When msgget() is used to allocate a message queue, one id is
52  *   allocated.  If the id allocation doesn't succeed, msgget() fails
53  *   and errno is set to ENOSPC.  Upon successful msgctl(, IPC_RMID)
54  *   the id is deallocated.
55  *
56  * Control:      process.max-msg-qbytes (rc_process_msgmnb)
57  * Description:  Maximum number of bytes of messages on a message queue.
58  *
59  *   When msgget() successfully allocates a message queue, the minimum
60  *   enforced value of this limit is used to initialize msg_qbytes.
61  *
62  * Control:      process.max-msg-messages (rc_process_msgtql)
63  * Description:  Maximum number of messages on a message queue.
64  *
65  *   When msgget() successfully allocates a message queue, the minimum
66  *   enforced value of this limit is used to initialize a per-queue
67  *   limit on the number of messages.
68  */
69 
70 #include <sys/types.h>
71 #include <sys/t_lock.h>
72 #include <sys/param.h>
73 #include <sys/cred.h>
74 #include <sys/user.h>
75 #include <sys/proc.h>
76 #include <sys/time.h>
77 #include <sys/ipc.h>
78 #include <sys/ipc_impl.h>
79 #include <sys/msg.h>
80 #include <sys/msg_impl.h>
81 #include <sys/list.h>
82 #include <sys/systm.h>
83 #include <sys/sysmacros.h>
84 #include <sys/cpuvar.h>
85 #include <sys/kmem.h>
86 #include <sys/ddi.h>
87 #include <sys/errno.h>
88 #include <sys/cmn_err.h>
89 #include <sys/debug.h>
90 #include <sys/project.h>
91 #include <sys/modctl.h>
92 #include <sys/syscall.h>
93 #include <sys/policy.h>
94 #include <sys/zone.h>
95 
96 #include <c2/audit.h>
97 
98 /*
99  * The following tunables are obsolete.  Though for compatibility we
100  * still read and interpret msginfo_msgmnb, msginfo_msgmni, and
101  * msginfo_msgtql (see os/project.c and os/rctl_proc.c), the preferred
102  * mechanism for administrating the IPC Message facility is through the
103  * resource controls described at the top of this file.
104  */
105 size_t	msginfo_msgmax = 2048;	/* (obsolete) */
106 size_t	msginfo_msgmnb = 4096;	/* (obsolete) */
107 int	msginfo_msgmni = 50;	/* (obsolete) */
108 int	msginfo_msgtql = 40;	/* (obsolete) */
109 int	msginfo_msgssz = 8;	/* (obsolete) */
110 int	msginfo_msgmap = 0;	/* (obsolete) */
111 ushort_t msginfo_msgseg = 1024;	/* (obsolete) */
112 
113 extern rctl_hndl_t rc_zone_msgmni;
114 extern rctl_hndl_t rc_project_msgmni;
115 extern rctl_hndl_t rc_process_msgmnb;
116 extern rctl_hndl_t rc_process_msgtql;
117 static ipc_service_t *msq_svc;
118 static zone_key_t msg_zone_key;
119 
120 static void msg_dtor(kipc_perm_t *);
121 static void msg_rmid(kipc_perm_t *);
122 static void msg_remove_zone(zoneid_t, void *);
123 
124 /*
125  * Module linkage information for the kernel.
126  */
127 static ssize_t msgsys(int opcode, uintptr_t a0, uintptr_t a1, uintptr_t a2,
128 	uintptr_t a4, uintptr_t a5);
129 
130 static struct sysent ipcmsg_sysent = {
131 	6,
132 #ifdef	_LP64
133 	SE_ARGC | SE_NOUNLOAD | SE_64RVAL,
134 #else
135 	SE_ARGC | SE_NOUNLOAD | SE_32RVAL1,
136 #endif
137 	(int (*)())msgsys
138 };
139 
140 #ifdef	_SYSCALL32_IMPL
141 static ssize32_t msgsys32(int opcode, uint32_t a0, uint32_t a1, uint32_t a2,
142 	uint32_t a4, uint32_t a5);
143 
144 static struct sysent ipcmsg_sysent32 = {
145 	6,
146 	SE_ARGC | SE_NOUNLOAD | SE_32RVAL1,
147 	(int (*)())msgsys32
148 };
149 #endif	/* _SYSCALL32_IMPL */
150 
151 static struct modlsys modlsys = {
152 	&mod_syscallops, "System V message facility", &ipcmsg_sysent
153 };
154 
155 #ifdef _SYSCALL32_IMPL
156 static struct modlsys modlsys32 = {
157 	&mod_syscallops32, "32-bit System V message facility", &ipcmsg_sysent32
158 };
159 #endif
160 
161 /*
162  *      Big Theory statement for message queue correctness
163  *
164  * The msgrcv and msgsnd functions no longer uses cv_broadcast to wake up
165  * receivers who are waiting for an event.  Using the cv_broadcast method
166  * resulted in negative scaling when the number of waiting receivers are large
167  * (the thundering herd problem).  Instead, the receivers waiting to receive a
168  * message are now linked in a queue-like fashion and awaken one at a time in
169  * a controlled manner.
170  *
171  * Receivers can block on two different classes of waiting list:
172  *    1) "sendwait" list, which is the more complex list of the two.  The
173  *	  receiver will be awakened by a sender posting a new message.  There
174  *	  are two types of "sendwait" list used:
175  *		a) msg_wait_snd: handles all receivers who are looking for
176  *		   a message type >= 0, but was unable to locate a match.
177  *
178  *		   slot 0: reserved for receivers that have designated they
179  *			   will take any message type.
180  *		   rest:   consist of receivers requesting a specific type
181  *			   but the type was not present.  The entries are
182  *			   hashed into a bucket in an attempt to keep
183  *			   any list search relatively short.
184  * 		b) msg_wait_snd_ngt: handles all receivers that have designated
185  *		   a negative message type. Unlike msg_wait_snd, the hash bucket
186  *		   serves a range of negative message types (-1 to -5, -6 to -10
187  *		   and so forth), where the last bucket is reserved for all the
188  *		   negative message types that hash outside of MSG_MAX_QNUM - 1.
189  *		   This is done this way to simplify the operation of locating a
190  *		   negative message type.
191  *
192  *    2) "copyout" list, where the receiver is awakened by another
193  *	 receiver after a message is copied out.  This is a linked list
194  *	 of waiters that are awakened one at a time.  Although the solution is
195  *	 not optimal, the complexity that would be added in for waking
196  *	 up the right entry far exceeds any potential pay back (too many
197  *	 correctness and corner case issues).
198  *
199  * The lists are doubly linked.  In the case of the "sendwait"
200  * list, this allows the thread to remove itself from the list without having
201  * to traverse the list.  In the case of the "copyout" list it simply allows
202  * us to use common functions with the "sendwait" list.
203  *
204  * To make sure receivers are not hung out to dry, we must guarantee:
205  *    1. If any queued message matches any receiver, then at least one
206  *       matching receiver must be processing the request.
207  *    2. Blocking on the copyout queue is only temporary while messages
208  *	 are being copied out.  The process is guaranted to wakeup
209  *	 when it gets to front of the queue (copyout is a FIFO).
210  *
211  * Rules for blocking and waking up:
212  *   1. A receiver entering msgrcv must examine all messages for a match
213  *      before blocking on a sendwait queue.
214  *   2. If the receiver blocks because the message it chose is already
215  *	being copied out, then when it wakes up needs to start start
216  *	checking the messages from the beginning.
217  *   3) When ever a process returns from msgrcv for any reason, if it
218  *	had attempted to copy a message or blocked waiting for a copy
219  *	to complete it needs to wakeup the next receiver blocked on
220  *	a copy out.
221  *   4) When a message is sent, the sender selects a process waiting
222  *	for that type of message.  This selection process rotates between
223  *	receivers types of 0, negative and positive to prevent starvation of
224  *	any one particular receiver type.
225  *   5) The following are the scenarios for processes that are awakened
226  *	by a msgsnd:
227  *		a) The process finds the message and is able to copy
228  *		   it out.  Once complete, the process returns.
229  *		b) The message that was sent that triggered the wakeup is no
230  *		   longer available (another process found the message first).
231  *		   We issue a wakeup on copy queue and then go back to
232  *		   sleep waiting for another matching message to be sent.
233  *		c) The message that was supposed to be processed was
234  *		   already serviced by another process.  However a different
235  *		   message is present which we can service.  The message
236  *		   is copied and the process returns.
237  *		d) The message is found, but some sort of error occurs that
238  *		   prevents the message from being copied.  The receiver
239  *		   wakes up the next sender that can service this message
240  *		   type and returns an error to the caller.
241  *		e) The message is found, but it is marked as being copied
242  *		   out.  The receiver then goes to sleep on the copyout
243  *		   queue where it will be awakened again sometime in the future.
244  *
245  *
246  *   6) Whenever a message is found that matches the message type designated,
247  * 	but is being copied out we have to block on the copyout queue.
248  *	After process copying finishes the copy out, it  must wakeup (either
249  *	directly or indirectly) all receivers who blocked on its copyout,
250  *	so they are guaranteed a chance to examine the remaining messages.
251  *	This is implemented via a chain of wakeups: Y wakes X, who wakes Z,
252  *	and so on.  The chain cannot be broken.  This leads to the following
253  *	cases:
254  *		a) A receiver is finished copying the message (or encountered)
255  *		   an error), the first entry on the copyout queue is woken
256  *		   up.
257  *		b) When the receiver is woken up, it attempts to locate
258  *		   a message type match.
259  *		c) If a message type is found and
260  *			-- MSG_RCVCOPY flag is not set, the message is
261  *			   marked for copying out.  Regardless of the copyout
262  *			   success the next entry on the copyout queue is
263  *			   awakened and the operation is completed.
264  *			-- MSG_RCVCOPY is set, we simply go back to sleep again
265  *			   on the copyout queue.
266  *		d) If the message type is not found then we wakeup the next
267  *		   process on the copyout queue.
268  */
269 
270 static ulong_t msg_type_hash(long);
271 static int msgq_check_err(kmsqid_t *qp, int cvres);
272 static int msg_rcvq_sleep(list_t *, msgq_wakeup_t *, kmutex_t **,
273     kmsqid_t *);
274 static int msg_copyout(kmsqid_t *, long, kmutex_t **, size_t *, size_t,
275     struct msg *, struct ipcmsgbuf *, int);
276 static void msg_rcvq_wakeup_all(list_t *);
277 static void msg_wakeup_rdr(kmsqid_t *, msg_select_t **, long);
278 static msgq_wakeup_t *msg_fnd_any_snd(kmsqid_t *, int, long);
279 static msgq_wakeup_t *msg_fnd_any_rdr(kmsqid_t *, int, long);
280 static msgq_wakeup_t *msg_fnd_neg_snd(kmsqid_t *, int, long);
281 static msgq_wakeup_t *msg_fnd_spc_snd(kmsqid_t *, int, long);
282 static struct msg *msgrcv_lookup(kmsqid_t *, long);
283 
284 msg_select_t msg_fnd_sndr[] = {
285 	{ msg_fnd_any_snd, &msg_fnd_sndr[1] },
286 	{ msg_fnd_spc_snd, &msg_fnd_sndr[2] },
287 	{ msg_fnd_neg_snd, &msg_fnd_sndr[0] }
288 };
289 
290 msg_select_t msg_fnd_rdr[1] = {
291 	{ msg_fnd_any_rdr, &msg_fnd_rdr[0] },
292 };
293 
294 static struct modlinkage modlinkage = {
295 	MODREV_1,
296 	&modlsys,
297 #ifdef _SYSCALL32_IMPL
298 	&modlsys32,
299 #endif
300 	NULL
301 };
302 
303 
304 int
305 _init(void)
306 {
307 	int result;
308 
309 	msq_svc = ipcs_create("msqids", rc_project_msgmni, rc_zone_msgmni,
310 	    sizeof (kmsqid_t), msg_dtor, msg_rmid, AT_IPC_MSG,
311 	    offsetof(ipc_rqty_t, ipcq_msgmni));
312 	zone_key_create(&msg_zone_key, NULL, msg_remove_zone, NULL);
313 
314 	if ((result = mod_install(&modlinkage)) == 0)
315 		return (0);
316 
317 	(void) zone_key_delete(msg_zone_key);
318 	ipcs_destroy(msq_svc);
319 
320 	return (result);
321 }
322 
323 int
324 _fini(void)
325 {
326 	return (EBUSY);
327 }
328 
329 int
330 _info(struct modinfo *modinfop)
331 {
332 	return (mod_info(&modlinkage, modinfop));
333 }
334 
335 static void
336 msg_dtor(kipc_perm_t *perm)
337 {
338 	kmsqid_t *qp = (kmsqid_t *)perm;
339 	int		ii;
340 
341 	for (ii = 0; ii <= MSG_MAX_QNUM; ii++) {
342 		ASSERT(list_is_empty(&qp->msg_wait_snd[ii]));
343 		ASSERT(list_is_empty(&qp->msg_wait_snd_ngt[ii]));
344 		list_destroy(&qp->msg_wait_snd[ii]);
345 		list_destroy(&qp->msg_wait_snd_ngt[ii]);
346 	}
347 	ASSERT(list_is_empty(&qp->msg_cpy_block));
348 	list_destroy(&qp->msg_cpy_block);
349 	ASSERT(qp->msg_snd_cnt == 0);
350 	ASSERT(qp->msg_cbytes == 0);
351 	list_destroy(&qp->msg_list);
352 }
353 
354 
355 #define	msg_hold(mp)	(mp)->msg_copycnt++
356 
357 /*
358  * msg_rele - decrement the reference count on the message.  When count
359  * reaches zero, free message header and contents.
360  */
361 static void
362 msg_rele(struct msg *mp)
363 {
364 	ASSERT(mp->msg_copycnt > 0);
365 	if (mp->msg_copycnt-- == 1) {
366 		if (mp->msg_addr)
367 			kmem_free(mp->msg_addr, mp->msg_size);
368 		kmem_free(mp, sizeof (struct msg));
369 	}
370 }
371 
372 /*
373  * msgunlink - Unlink msg from queue, decrement byte count and wake up anyone
374  * waiting for free bytes on queue.
375  *
376  * Called with queue locked.
377  */
378 static void
379 msgunlink(kmsqid_t *qp, struct msg *mp)
380 {
381 	list_remove(&qp->msg_list, mp);
382 	qp->msg_qnum--;
383 	qp->msg_cbytes -= mp->msg_size;
384 	msg_rele(mp);
385 
386 	/* Wake up waiting writers */
387 	if (qp->msg_snd_cnt)
388 		cv_broadcast(&qp->msg_snd_cv);
389 }
390 
391 static void
392 msg_rmid(kipc_perm_t *perm)
393 {
394 	kmsqid_t *qp = (kmsqid_t *)perm;
395 	struct msg *mp;
396 	int		ii;
397 
398 
399 	while ((mp = list_head(&qp->msg_list)) != NULL)
400 		msgunlink(qp, mp);
401 	ASSERT(qp->msg_cbytes == 0);
402 
403 	/*
404 	 * Wake up everyone who is in a wait state of some sort
405 	 * for this message queue.
406 	 */
407 	for (ii = 0; ii <= MSG_MAX_QNUM; ii++) {
408 		msg_rcvq_wakeup_all(&qp->msg_wait_snd[ii]);
409 		msg_rcvq_wakeup_all(&qp->msg_wait_snd_ngt[ii]);
410 	}
411 	msg_rcvq_wakeup_all(&qp->msg_cpy_block);
412 	if (qp->msg_snd_cnt)
413 		cv_broadcast(&qp->msg_snd_cv);
414 }
415 
416 /*
417  * msgctl system call.
418  *
419  * gets q lock (via ipc_lookup), releases before return.
420  * may call users of msg_lock
421  */
422 static int
423 msgctl(int msgid, int cmd, void *arg)
424 {
425 	STRUCT_DECL(msqid_ds, ds);		/* SVR4 queue work area */
426 	kmsqid_t		*qp;		/* ptr to associated q */
427 	int			error;
428 	struct	cred		*cr;
429 	model_t	mdl = get_udatamodel();
430 	struct msqid_ds64	ds64;
431 	kmutex_t		*lock;
432 	proc_t			*pp = curproc;
433 
434 	STRUCT_INIT(ds, mdl);
435 	cr = CRED();
436 
437 	/*
438 	 * Perform pre- or non-lookup actions (e.g. copyins, RMID).
439 	 */
440 	switch (cmd) {
441 	case IPC_SET:
442 		if (copyin(arg, STRUCT_BUF(ds), STRUCT_SIZE(ds)))
443 			return (set_errno(EFAULT));
444 		break;
445 
446 	case IPC_SET64:
447 		if (copyin(arg, &ds64, sizeof (struct msqid_ds64)))
448 			return (set_errno(EFAULT));
449 		break;
450 
451 	case IPC_RMID:
452 		if (error = ipc_rmid(msq_svc, msgid, cr))
453 			return (set_errno(error));
454 		return (0);
455 	}
456 
457 	/*
458 	 * get msqid_ds for this msgid
459 	 */
460 	if ((lock = ipc_lookup(msq_svc, msgid, (kipc_perm_t **)&qp)) == NULL)
461 		return (set_errno(EINVAL));
462 
463 	switch (cmd) {
464 	case IPC_SET:
465 		if (STRUCT_FGET(ds, msg_qbytes) > qp->msg_qbytes &&
466 		    secpolicy_ipc_config(cr) != 0) {
467 			mutex_exit(lock);
468 			return (set_errno(EPERM));
469 		}
470 		if (error = ipcperm_set(msq_svc, cr, &qp->msg_perm,
471 		    &STRUCT_BUF(ds)->msg_perm, mdl)) {
472 			mutex_exit(lock);
473 			return (set_errno(error));
474 		}
475 		qp->msg_qbytes = STRUCT_FGET(ds, msg_qbytes);
476 		qp->msg_ctime = gethrestime_sec();
477 		break;
478 
479 	case IPC_STAT:
480 		if (error = ipcperm_access(&qp->msg_perm, MSG_R, cr)) {
481 			mutex_exit(lock);
482 			return (set_errno(error));
483 		}
484 
485 		if (qp->msg_rcv_cnt)
486 			qp->msg_perm.ipc_mode |= MSG_RWAIT;
487 		if (qp->msg_snd_cnt)
488 			qp->msg_perm.ipc_mode |= MSG_WWAIT;
489 		ipcperm_stat(&STRUCT_BUF(ds)->msg_perm, &qp->msg_perm, mdl);
490 		qp->msg_perm.ipc_mode &= ~(MSG_RWAIT|MSG_WWAIT);
491 		STRUCT_FSETP(ds, msg_first, NULL); 	/* kernel addr */
492 		STRUCT_FSETP(ds, msg_last, NULL);
493 		STRUCT_FSET(ds, msg_cbytes, qp->msg_cbytes);
494 		STRUCT_FSET(ds, msg_qnum, qp->msg_qnum);
495 		STRUCT_FSET(ds, msg_qbytes, qp->msg_qbytes);
496 		STRUCT_FSET(ds, msg_lspid, qp->msg_lspid);
497 		STRUCT_FSET(ds, msg_lrpid, qp->msg_lrpid);
498 		STRUCT_FSET(ds, msg_stime, qp->msg_stime);
499 		STRUCT_FSET(ds, msg_rtime, qp->msg_rtime);
500 		STRUCT_FSET(ds, msg_ctime, qp->msg_ctime);
501 		break;
502 
503 	case IPC_SET64:
504 		mutex_enter(&pp->p_lock);
505 		if ((ds64.msgx_qbytes > qp->msg_qbytes) &&
506 		    secpolicy_ipc_config(cr) != 0 &&
507 		    rctl_test(rc_process_msgmnb, pp->p_rctls, pp,
508 		    ds64.msgx_qbytes, RCA_SAFE) & RCT_DENY) {
509 			mutex_exit(&pp->p_lock);
510 			mutex_exit(lock);
511 			return (set_errno(EPERM));
512 		}
513 		mutex_exit(&pp->p_lock);
514 		if (error = ipcperm_set64(msq_svc, cr, &qp->msg_perm,
515 		    &ds64.msgx_perm)) {
516 			mutex_exit(lock);
517 			return (set_errno(error));
518 		}
519 		qp->msg_qbytes = ds64.msgx_qbytes;
520 		qp->msg_ctime = gethrestime_sec();
521 		break;
522 
523 	case IPC_STAT64:
524 		if (qp->msg_rcv_cnt)
525 			qp->msg_perm.ipc_mode |= MSG_RWAIT;
526 		if (qp->msg_snd_cnt)
527 			qp->msg_perm.ipc_mode |= MSG_WWAIT;
528 		ipcperm_stat64(&ds64.msgx_perm, &qp->msg_perm);
529 		qp->msg_perm.ipc_mode &= ~(MSG_RWAIT|MSG_WWAIT);
530 		ds64.msgx_cbytes = qp->msg_cbytes;
531 		ds64.msgx_qnum = qp->msg_qnum;
532 		ds64.msgx_qbytes = qp->msg_qbytes;
533 		ds64.msgx_lspid = qp->msg_lspid;
534 		ds64.msgx_lrpid = qp->msg_lrpid;
535 		ds64.msgx_stime = qp->msg_stime;
536 		ds64.msgx_rtime = qp->msg_rtime;
537 		ds64.msgx_ctime = qp->msg_ctime;
538 		break;
539 
540 	default:
541 		mutex_exit(lock);
542 		return (set_errno(EINVAL));
543 	}
544 
545 	mutex_exit(lock);
546 
547 	/*
548 	 * Do copyout last (after releasing mutex).
549 	 */
550 	switch (cmd) {
551 	case IPC_STAT:
552 		if (copyout(STRUCT_BUF(ds), arg, STRUCT_SIZE(ds)))
553 			return (set_errno(EFAULT));
554 		break;
555 
556 	case IPC_STAT64:
557 		if (copyout(&ds64, arg, sizeof (struct msqid_ds64)))
558 			return (set_errno(EFAULT));
559 		break;
560 	}
561 
562 	return (0);
563 }
564 
565 /*
566  * Remove all message queues associated with a given zone.  Called by
567  * zone_shutdown when the zone is halted.
568  */
569 /*ARGSUSED1*/
570 static void
571 msg_remove_zone(zoneid_t zoneid, void *arg)
572 {
573 	ipc_remove_zone(msq_svc, zoneid);
574 }
575 
576 /*
577  * msgget system call.
578  */
579 static int
580 msgget(key_t key, int msgflg)
581 {
582 	kmsqid_t	*qp;
583 	kmutex_t	*lock;
584 	int		id, error;
585 	int		ii;
586 	proc_t		*pp = curproc;
587 
588 top:
589 	if (error = ipc_get(msq_svc, key, msgflg, (kipc_perm_t **)&qp, &lock))
590 		return (set_errno(error));
591 
592 	if (IPC_FREE(&qp->msg_perm)) {
593 		mutex_exit(lock);
594 		mutex_exit(&pp->p_lock);
595 
596 		list_create(&qp->msg_list, sizeof (struct msg),
597 		    offsetof(struct msg, msg_node));
598 		qp->msg_qnum = 0;
599 		qp->msg_lspid = qp->msg_lrpid = 0;
600 		qp->msg_stime = qp->msg_rtime = 0;
601 		qp->msg_ctime = gethrestime_sec();
602 		qp->msg_ngt_cnt = 0;
603 		qp->msg_neg_copy = 0;
604 		for (ii = 0; ii <= MSG_MAX_QNUM; ii++) {
605 			list_create(&qp->msg_wait_snd[ii],
606 			    sizeof (msgq_wakeup_t),
607 			    offsetof(msgq_wakeup_t, msgw_list));
608 			list_create(&qp->msg_wait_snd_ngt[ii],
609 			    sizeof (msgq_wakeup_t),
610 			    offsetof(msgq_wakeup_t, msgw_list));
611 		}
612 		/*
613 		 * The proper initialization of msg_lowest_type is to the
614 		 * highest possible value.  By doing this we guarantee that
615 		 * when the first send happens, the lowest type will be set
616 		 * properly.
617 		 */
618 		qp->msg_lowest_type = -1;
619 		list_create(&qp->msg_cpy_block,
620 		    sizeof (msgq_wakeup_t),
621 		    offsetof(msgq_wakeup_t, msgw_list));
622 		qp->msg_fnd_sndr = &msg_fnd_sndr[0];
623 		qp->msg_fnd_rdr = &msg_fnd_rdr[0];
624 		qp->msg_rcv_cnt = 0;
625 		qp->msg_snd_cnt = 0;
626 
627 		if (error = ipc_commit_begin(msq_svc, key, msgflg,
628 		    (kipc_perm_t *)qp)) {
629 			if (error == EAGAIN)
630 				goto top;
631 			return (set_errno(error));
632 		}
633 		qp->msg_qbytes = rctl_enforced_value(rc_process_msgmnb,
634 		    pp->p_rctls, pp);
635 		qp->msg_qmax = rctl_enforced_value(rc_process_msgtql,
636 		    pp->p_rctls, pp);
637 		lock = ipc_commit_end(msq_svc, &qp->msg_perm);
638 	}
639 #ifdef C2_AUDIT
640 	if (audit_active)
641 		audit_ipcget(AT_IPC_MSG, (void *)qp);
642 #endif
643 	id = qp->msg_perm.ipc_id;
644 	mutex_exit(lock);
645 	return (id);
646 }
647 
648 static ssize_t
649 msgrcv(int msqid, struct ipcmsgbuf *msgp, size_t msgsz, long msgtyp, int msgflg)
650 {
651 	struct msg	*smp;	/* ptr to best msg on q */
652 	kmsqid_t	*qp;	/* ptr to associated q */
653 	kmutex_t	*lock;
654 	size_t		xtsz;	/* transfer byte count */
655 	int		error = 0;
656 	int		cvres;
657 	ulong_t		msg_hash;
658 	msgq_wakeup_t	msg_entry;
659 
660 	CPU_STATS_ADDQ(CPU, sys, msg, 1);	/* bump msg send/rcv count */
661 
662 	msg_hash = msg_type_hash(msgtyp);
663 	if ((lock = ipc_lookup(msq_svc, msqid, (kipc_perm_t **)&qp)) == NULL) {
664 		return ((ssize_t)set_errno(EINVAL));
665 	}
666 	ipc_hold(msq_svc, (kipc_perm_t *)qp);
667 
668 	if (error = ipcperm_access(&qp->msg_perm, MSG_R, CRED())) {
669 		goto msgrcv_out;
670 	}
671 
672 	/*
673 	 * Various information (including the condvar_t) required for the
674 	 * process to sleep is provided by it's stack.
675 	 */
676 	msg_entry.msgw_thrd = curthread;
677 	msg_entry.msgw_snd_wake = 0;
678 	msg_entry.msgw_type = msgtyp;
679 findmsg:
680 	smp = msgrcv_lookup(qp, msgtyp);
681 
682 	if (smp) {
683 		/*
684 		 * We found a possible message to copy out.
685 		 */
686 		if ((smp->msg_flags & MSG_RCVCOPY) == 0) {
687 			/*
688 			 * It is available, attempt to copy it.
689 			 */
690 			error = msg_copyout(qp, msgtyp, &lock, &xtsz, msgsz,
691 			    smp, msgp, msgflg);
692 			/*
693 			 * Don't forget to wakeup a sleeper that blocked because
694 			 * we were copying things out.
695 			 */
696 			msg_wakeup_rdr(qp, &qp->msg_fnd_rdr, 0);
697 			goto msgrcv_out;
698 		}
699 		/*
700 		 * The selected message is being copied out, so block.  We do
701 		 * not need to wake the next person up on the msg_cpy_block list
702 		 * due to the fact some one is copying out and they will get
703 		 * things moving again once the copy is completed.
704 		 */
705 		cvres = msg_rcvq_sleep(&qp->msg_cpy_block,
706 		    &msg_entry, &lock, qp);
707 		error = msgq_check_err(qp, cvres);
708 		if (error) {
709 			goto msgrcv_out;
710 		}
711 		goto findmsg;
712 	}
713 	/*
714 	 * There isn't a message to copy out that matches the designated
715 	 * criteria.
716 	 */
717 	if (msgflg & IPC_NOWAIT) {
718 		error = ENOMSG;
719 		goto msgrcv_out;
720 	}
721 	msg_wakeup_rdr(qp,  &qp->msg_fnd_rdr, 0);
722 
723 	/*
724 	 * Wait for new message.  We keep the negative and positive types
725 	 * separate for performance reasons.
726 	 */
727 	msg_entry.msgw_snd_wake = 0;
728 	if (msgtyp >= 0) {
729 		cvres = msg_rcvq_sleep(&qp->msg_wait_snd[msg_hash],
730 		    &msg_entry, &lock, qp);
731 	} else {
732 		qp->msg_ngt_cnt++;
733 		cvres = msg_rcvq_sleep(&qp->msg_wait_snd_ngt[msg_hash],
734 		    &msg_entry, &lock, qp);
735 		qp->msg_ngt_cnt--;
736 	}
737 
738 	if (!(error = msgq_check_err(qp, cvres))) {
739 		goto findmsg;
740 	}
741 
742 msgrcv_out:
743 	if (error) {
744 		msg_wakeup_rdr(qp,  &qp->msg_fnd_rdr, 0);
745 		if (msg_entry.msgw_snd_wake) {
746 			msg_wakeup_rdr(qp, &qp->msg_fnd_sndr,
747 			    msg_entry.msgw_snd_wake);
748 		}
749 		ipc_rele(msq_svc, (kipc_perm_t *)qp);
750 		return ((ssize_t)set_errno(error));
751 	}
752 	ipc_rele(msq_svc, (kipc_perm_t *)qp);
753 	return ((ssize_t)xtsz);
754 }
755 
756 static int
757 msgq_check_err(kmsqid_t *qp, int cvres)
758 {
759 	if (IPC_FREE(&qp->msg_perm)) {
760 		return (EIDRM);
761 	}
762 
763 	if (cvres == 0) {
764 		return (EINTR);
765 	}
766 
767 	return (0);
768 }
769 
770 static int
771 msg_copyout(kmsqid_t *qp, long msgtyp, kmutex_t **lock, size_t *xtsz_ret,
772     size_t msgsz, struct msg *smp, struct ipcmsgbuf *msgp, int msgflg)
773 {
774 	size_t		xtsz;
775 	STRUCT_HANDLE(ipcmsgbuf, umsgp);
776 	model_t		mdl = get_udatamodel();
777 	int		copyerror = 0;
778 
779 	STRUCT_SET_HANDLE(umsgp, mdl, msgp);
780 	if (msgsz < smp->msg_size) {
781 		if ((msgflg & MSG_NOERROR) == 0) {
782 			return (E2BIG);
783 		} else {
784 			xtsz = msgsz;
785 		}
786 	} else {
787 		xtsz = smp->msg_size;
788 	}
789 	*xtsz_ret = xtsz;
790 
791 	/*
792 	 * To prevent a DOS attack we mark the message as being
793 	 * copied out and release mutex.  When the copy is completed
794 	 * we need to acquire the mutex and make the appropriate updates.
795 	 */
796 	ASSERT((smp->msg_flags & MSG_RCVCOPY) == 0);
797 	smp->msg_flags |= MSG_RCVCOPY;
798 	msg_hold(smp);
799 	if (msgtyp < 0) {
800 		ASSERT(qp->msg_neg_copy == 0);
801 		qp->msg_neg_copy = 1;
802 	}
803 	mutex_exit(*lock);
804 
805 	if (mdl == DATAMODEL_NATIVE) {
806 		copyerror = copyout(&smp->msg_type, msgp,
807 		    sizeof (smp->msg_type));
808 	} else {
809 		/*
810 		 * 32-bit callers need an imploded msg type.
811 		 */
812 		int32_t	msg_type32 = smp->msg_type;
813 
814 		copyerror = copyout(&msg_type32, msgp,
815 		    sizeof (msg_type32));
816 	}
817 
818 	if (copyerror == 0 && xtsz) {
819 		copyerror = copyout(smp->msg_addr,
820 		    STRUCT_FADDR(umsgp, mtext), xtsz);
821 	}
822 
823 	/*
824 	 * Reclaim the mutex and make sure the message queue still exists.
825 	 */
826 
827 	*lock = ipc_lock(msq_svc, qp->msg_perm.ipc_id);
828 	if (msgtyp < 0) {
829 		qp->msg_neg_copy = 0;
830 	}
831 	ASSERT(smp->msg_flags & MSG_RCVCOPY);
832 	smp->msg_flags &= ~MSG_RCVCOPY;
833 	msg_rele(smp);
834 	if (IPC_FREE(&qp->msg_perm)) {
835 		return (EIDRM);
836 	}
837 	if (copyerror) {
838 		return (EFAULT);
839 	}
840 	qp->msg_lrpid = ttoproc(curthread)->p_pid;
841 	qp->msg_rtime = gethrestime_sec();
842 	msgunlink(qp, smp);
843 	return (0);
844 }
845 
846 static struct msg *
847 msgrcv_lookup(kmsqid_t *qp, long msgtyp)
848 {
849 	struct msg 		*smp = NULL;
850 	int			qp_low;
851 	struct msg		*mp;	/* ptr to msg on q */
852 	int			low_msgtype;
853 	static struct msg	neg_copy_smp;
854 
855 	mp = list_head(&qp->msg_list);
856 	if (msgtyp == 0) {
857 		smp = mp;
858 	} else {
859 		qp_low = qp->msg_lowest_type;
860 		if (msgtyp > 0) {
861 			/*
862 			 * If our lowest possible message type is larger than
863 			 * the message type desired, then we know there is
864 			 * no entry present.
865 			 */
866 			if (qp_low > msgtyp) {
867 				return (NULL);
868 			}
869 
870 			for (; mp; mp = list_next(&qp->msg_list, mp)) {
871 				if (msgtyp == mp->msg_type) {
872 					smp = mp;
873 					break;
874 				}
875 			}
876 		} else {
877 			/*
878 			 * We have kept track of the lowest possible message
879 			 * type on the send queue.  This allows us to terminate
880 			 * the search early if we find a message type of that
881 			 * type.  Note, the lowest type may not be the actual
882 			 * lowest value in the system, it is only guaranteed
883 			 * that there isn't a value lower than that.
884 			 */
885 			low_msgtype = -msgtyp;
886 			if (low_msgtype++ < qp_low) {
887 				return (NULL);
888 			}
889 			if (qp->msg_neg_copy) {
890 				neg_copy_smp.msg_flags = MSG_RCVCOPY;
891 				return (&neg_copy_smp);
892 			}
893 			for (; mp; mp = list_next(&qp->msg_list, mp)) {
894 				if (mp->msg_type < low_msgtype) {
895 					smp = mp;
896 					low_msgtype = mp->msg_type;
897 					if (low_msgtype == qp_low) {
898 						break;
899 					}
900 				}
901 			}
902 			if (smp) {
903 				/*
904 				 * Update the lowest message type.
905 				 */
906 				qp->msg_lowest_type = smp->msg_type;
907 			}
908 		}
909 	}
910 	return (smp);
911 }
912 
913 /*
914  * msgids system call.
915  */
916 static int
917 msgids(int *buf, uint_t nids, uint_t *pnids)
918 {
919 	int error;
920 
921 	if (error = ipc_ids(msq_svc, buf, nids, pnids))
922 		return (set_errno(error));
923 
924 	return (0);
925 }
926 
927 #define	RND(x)		roundup((x), sizeof (size_t))
928 #define	RND32(x)	roundup((x), sizeof (size32_t))
929 
930 /*
931  * msgsnap system call.
932  */
933 static int
934 msgsnap(int msqid, caddr_t buf, size_t bufsz, long msgtyp)
935 {
936 	struct msg	*mp;	/* ptr to msg on q */
937 	kmsqid_t	*qp;	/* ptr to associated q */
938 	kmutex_t	*lock;
939 	size_t		size;
940 	size_t		nmsg;
941 	struct msg	**snaplist;
942 	int		error, i;
943 	model_t		mdl = get_udatamodel();
944 	STRUCT_DECL(msgsnap_head, head);
945 	STRUCT_DECL(msgsnap_mhead, mhead);
946 
947 	STRUCT_INIT(head, mdl);
948 	STRUCT_INIT(mhead, mdl);
949 
950 	if (bufsz < STRUCT_SIZE(head))
951 		return (set_errno(EINVAL));
952 
953 	if ((lock = ipc_lookup(msq_svc, msqid, (kipc_perm_t **)&qp)) == NULL)
954 		return (set_errno(EINVAL));
955 
956 	if (error = ipcperm_access(&qp->msg_perm, MSG_R, CRED())) {
957 		mutex_exit(lock);
958 		return (set_errno(error));
959 	}
960 	ipc_hold(msq_svc, (kipc_perm_t *)qp);
961 
962 	/*
963 	 * First compute the required buffer size and
964 	 * the number of messages on the queue.
965 	 */
966 	size = nmsg = 0;
967 	for (mp = list_head(&qp->msg_list); mp;
968 	    mp = list_next(&qp->msg_list, mp)) {
969 		if (msgtyp == 0 ||
970 		    (msgtyp > 0 && msgtyp == mp->msg_type) ||
971 		    (msgtyp < 0 && mp->msg_type <= -msgtyp)) {
972 			nmsg++;
973 			if (mdl == DATAMODEL_NATIVE)
974 				size += RND(mp->msg_size);
975 			else
976 				size += RND32(mp->msg_size);
977 		}
978 	}
979 
980 	size += STRUCT_SIZE(head) + nmsg * STRUCT_SIZE(mhead);
981 	if (size > bufsz)
982 		nmsg = 0;
983 
984 	if (nmsg > 0) {
985 		/*
986 		 * Mark the messages as being copied.
987 		 */
988 		snaplist = (struct msg **)kmem_alloc(nmsg *
989 		    sizeof (struct msg *), KM_SLEEP);
990 		i = 0;
991 		for (mp = list_head(&qp->msg_list); mp;
992 		    mp = list_next(&qp->msg_list, mp)) {
993 			if (msgtyp == 0 ||
994 			    (msgtyp > 0 && msgtyp == mp->msg_type) ||
995 			    (msgtyp < 0 && mp->msg_type <= -msgtyp)) {
996 				msg_hold(mp);
997 				snaplist[i] = mp;
998 				i++;
999 			}
1000 		}
1001 	}
1002 	mutex_exit(lock);
1003 
1004 	/*
1005 	 * Copy out the buffer header.
1006 	 */
1007 	STRUCT_FSET(head, msgsnap_size, size);
1008 	STRUCT_FSET(head, msgsnap_nmsg, nmsg);
1009 	if (copyout(STRUCT_BUF(head), buf, STRUCT_SIZE(head)))
1010 		error = EFAULT;
1011 
1012 	buf += STRUCT_SIZE(head);
1013 
1014 	/*
1015 	 * Now copy out the messages one by one.
1016 	 */
1017 	for (i = 0; i < nmsg; i++) {
1018 		mp = snaplist[i];
1019 		if (error == 0) {
1020 			STRUCT_FSET(mhead, msgsnap_mlen, mp->msg_size);
1021 			STRUCT_FSET(mhead, msgsnap_mtype, mp->msg_type);
1022 			if (copyout(STRUCT_BUF(mhead), buf, STRUCT_SIZE(mhead)))
1023 				error = EFAULT;
1024 			buf += STRUCT_SIZE(mhead);
1025 
1026 			if (error == 0 &&
1027 			    mp->msg_size != 0 &&
1028 			    copyout(mp->msg_addr, buf, mp->msg_size))
1029 				error = EFAULT;
1030 			if (mdl == DATAMODEL_NATIVE)
1031 				buf += RND(mp->msg_size);
1032 			else
1033 				buf += RND32(mp->msg_size);
1034 		}
1035 		lock = ipc_lock(msq_svc, qp->msg_perm.ipc_id);
1036 		msg_rele(mp);
1037 		/* Check for msg q deleted or reallocated */
1038 		if (IPC_FREE(&qp->msg_perm))
1039 			error = EIDRM;
1040 		mutex_exit(lock);
1041 	}
1042 
1043 	(void) ipc_lock(msq_svc, qp->msg_perm.ipc_id);
1044 	ipc_rele(msq_svc, (kipc_perm_t *)qp);
1045 
1046 	if (nmsg > 0)
1047 		kmem_free(snaplist, nmsg * sizeof (struct msg *));
1048 
1049 	if (error)
1050 		return (set_errno(error));
1051 	return (0);
1052 }
1053 
1054 #define	MSG_PREALLOC_LIMIT 8192
1055 
1056 /*
1057  * msgsnd system call.
1058  */
1059 static int
1060 msgsnd(int msqid, struct ipcmsgbuf *msgp, size_t msgsz, int msgflg)
1061 {
1062 	kmsqid_t	*qp;
1063 	kmutex_t	*lock = NULL;
1064 	struct msg	*mp = NULL;
1065 	long		type;
1066 	int		error = 0;
1067 	model_t		mdl = get_udatamodel();
1068 	STRUCT_HANDLE(ipcmsgbuf, umsgp);
1069 
1070 	CPU_STATS_ADDQ(CPU, sys, msg, 1);	/* bump msg send/rcv count */
1071 	STRUCT_SET_HANDLE(umsgp, mdl, msgp);
1072 
1073 	if (mdl == DATAMODEL_NATIVE) {
1074 		if (copyin(msgp, &type, sizeof (type)))
1075 			return (set_errno(EFAULT));
1076 	} else {
1077 		int32_t	type32;
1078 		if (copyin(msgp, &type32, sizeof (type32)))
1079 			return (set_errno(EFAULT));
1080 		type = type32;
1081 	}
1082 
1083 	if (type < 1)
1084 		return (set_errno(EINVAL));
1085 
1086 	/*
1087 	 * We want the value here large enough that most of the
1088 	 * the message operations will use the "lockless" path,
1089 	 * but small enough that a user can not reserve large
1090 	 * chunks of kernel memory unless they have a valid
1091 	 * reason to.
1092 	 */
1093 	if (msgsz <= MSG_PREALLOC_LIMIT) {
1094 		/*
1095 		 * We are small enough that we can afford to do the
1096 		 * allocation now.  This saves dropping the lock
1097 		 * and then reacquiring the lock.
1098 		 */
1099 		mp = kmem_zalloc(sizeof (struct msg), KM_SLEEP);
1100 		mp->msg_copycnt = 1;
1101 		mp->msg_size = msgsz;
1102 		if (msgsz) {
1103 			mp->msg_addr = kmem_alloc(msgsz, KM_SLEEP);
1104 			if (copyin(STRUCT_FADDR(umsgp, mtext),
1105 			    mp->msg_addr, msgsz) == -1) {
1106 				error = EFAULT;
1107 				goto msgsnd_out;
1108 			}
1109 		}
1110 	}
1111 
1112 	if ((lock = ipc_lookup(msq_svc, msqid, (kipc_perm_t **)&qp)) == NULL) {
1113 		error = EINVAL;
1114 		goto msgsnd_out;
1115 	}
1116 
1117 	ipc_hold(msq_svc, (kipc_perm_t *)qp);
1118 
1119 	if (msgsz > qp->msg_qbytes) {
1120 		error = EINVAL;
1121 		goto msgsnd_out;
1122 	}
1123 
1124 	if (error = ipcperm_access(&qp->msg_perm, MSG_W, CRED()))
1125 		goto msgsnd_out;
1126 
1127 top:
1128 	/*
1129 	 * Allocate space on q, message header, & buffer space.
1130 	 */
1131 	ASSERT(qp->msg_qnum <= qp->msg_qmax);
1132 	while ((msgsz > qp->msg_qbytes - qp->msg_cbytes) ||
1133 	    (qp->msg_qnum == qp->msg_qmax)) {
1134 		int cvres;
1135 
1136 		if (msgflg & IPC_NOWAIT) {
1137 			error = EAGAIN;
1138 			goto msgsnd_out;
1139 		}
1140 
1141 		qp->msg_snd_cnt++;
1142 		cvres = cv_wait_sig(&qp->msg_snd_cv, lock);
1143 		lock = ipc_relock(msq_svc, qp->msg_perm.ipc_id, lock);
1144 		qp->msg_snd_cnt--;
1145 
1146 		if (error = msgq_check_err(qp, cvres)) {
1147 			goto msgsnd_out;
1148 		}
1149 	}
1150 
1151 	if (mp == NULL) {
1152 		int failure;
1153 
1154 		mutex_exit(lock);
1155 		ASSERT(msgsz > 0);
1156 		mp = kmem_zalloc(sizeof (struct msg), KM_SLEEP);
1157 		mp->msg_addr = kmem_alloc(msgsz, KM_SLEEP);
1158 		mp->msg_size = msgsz;
1159 		mp->msg_copycnt = 1;
1160 
1161 		failure = (copyin(STRUCT_FADDR(umsgp, mtext),
1162 		    mp->msg_addr, msgsz) == -1);
1163 		lock = ipc_lock(msq_svc, qp->msg_perm.ipc_id);
1164 		if (IPC_FREE(&qp->msg_perm)) {
1165 			error = EIDRM;
1166 			goto msgsnd_out;
1167 		}
1168 		if (failure) {
1169 			error = EFAULT;
1170 			goto msgsnd_out;
1171 		}
1172 		goto top;
1173 	}
1174 
1175 	/*
1176 	 * Everything is available, put msg on q.
1177 	 */
1178 	qp->msg_qnum++;
1179 	qp->msg_cbytes += msgsz;
1180 	qp->msg_lspid = curproc->p_pid;
1181 	qp->msg_stime = gethrestime_sec();
1182 	mp->msg_type = type;
1183 	if (qp->msg_lowest_type > type)
1184 		qp->msg_lowest_type = type;
1185 	list_insert_tail(&qp->msg_list, mp);
1186 	/*
1187 	 * Get the proper receiver going.
1188 	 */
1189 	msg_wakeup_rdr(qp, &qp->msg_fnd_sndr, type);
1190 
1191 msgsnd_out:
1192 	if (lock)
1193 		ipc_rele(msq_svc, (kipc_perm_t *)qp);	/* drops lock */
1194 
1195 	if (error) {
1196 		if (mp)
1197 			msg_rele(mp);
1198 		return (set_errno(error));
1199 	}
1200 
1201 	return (0);
1202 }
1203 
1204 static void
1205 msg_wakeup_rdr(kmsqid_t *qp, msg_select_t **flist, long type)
1206 {
1207 	msg_select_t	*walker = *flist;
1208 	msgq_wakeup_t	*wakeup;
1209 	ulong_t		msg_hash;
1210 
1211 	msg_hash = msg_type_hash(type);
1212 
1213 	do {
1214 		wakeup = walker->selection(qp, msg_hash, type);
1215 		walker = walker->next_selection;
1216 	} while (!wakeup && walker != *flist);
1217 
1218 	*flist = (*flist)->next_selection;
1219 	if (wakeup) {
1220 		if (type) {
1221 			wakeup->msgw_snd_wake = type;
1222 		}
1223 		cv_signal(&wakeup->msgw_wake_cv);
1224 	}
1225 }
1226 
1227 static ulong_t
1228 msg_type_hash(long msg_type)
1229 {
1230 	long	temp;
1231 	ulong_t	hash;
1232 
1233 	if (msg_type < 0) {
1234 		/*
1235 		 * Negative message types are hashed over an
1236 		 * interval.  Any message type that hashes
1237 		 * beyond MSG_MAX_QNUM is automatically placed
1238 		 * in the last bucket.
1239 		 */
1240 		temp = -msg_type;
1241 		hash = temp / MSG_NEG_INTERVAL;
1242 		if (hash > MSG_MAX_QNUM) {
1243 			hash = MSG_MAX_QNUM;
1244 		}
1245 		return (hash);
1246 	}
1247 
1248 	/*
1249 	 * 0 or positive message type.  The first bucket is reserved for
1250 	 * message receivers of type 0, the other buckets we hash into.
1251 	 */
1252 	if (msg_type) {
1253 		return (1 + (msg_type % (MSG_MAX_QNUM)));
1254 	}
1255 	return (0);
1256 }
1257 
1258 /*
1259  * Routines to see if we have a receiver of type 0 either blocked waiting
1260  * for a message.  Simply return the first guy on the list.
1261  */
1262 
1263 static msgq_wakeup_t *
1264 /* LINTED */
1265 msg_fnd_any_snd(kmsqid_t *qp, int msg_hash, long type)
1266 {
1267 	return (list_head(&qp->msg_wait_snd[0]));
1268 }
1269 
1270 static msgq_wakeup_t *
1271 /* LINTED */
1272 msg_fnd_any_rdr(kmsqid_t *qp, int msg_hash, long type)
1273 {
1274 	return (list_head(&qp->msg_cpy_block));
1275 }
1276 
1277 static msgq_wakeup_t *
1278 msg_fnd_spc_snd(kmsqid_t *qp, int msg_hash, long type)
1279 {
1280 	msgq_wakeup_t	*walker;
1281 
1282 	walker = list_head(&qp->msg_wait_snd[msg_hash]);
1283 
1284 	while (walker && walker->msgw_type != type &&
1285 	    (walker = list_next(&qp->msg_wait_snd[msg_hash], walker)));
1286 	return (walker);
1287 }
1288 
1289 static msgq_wakeup_t *
1290 msg_fnd_neg_snd(kmsqid_t *qp, int msg_hash, long type)
1291 {
1292 	msgq_wakeup_t	*qptr;
1293 	int		count;
1294 	int		check_index;
1295 	int		neg_index;
1296 	int		nbuckets;
1297 
1298 	if (!qp->msg_ngt_cnt) {
1299 		return (NULL);
1300 	}
1301 	neg_index = msg_type_hash(-type);
1302 
1303 	/*
1304 	 * Check for a match among the negative type queues.  Any buckets
1305 	 * at neg_index or larger can match the type.  Use the last send
1306 	 * time to randomize the starting bucket to prevent starvation.
1307 	 * Search all buckets from neg_index to MSG_MAX_QNUM, starting
1308 	 * from the random starting point, and wrapping around after
1309 	 * MSG_MAX_QNUM.
1310 	 */
1311 
1312 	nbuckets = MSG_MAX_QNUM - neg_index + 1;
1313 	check_index = neg_index + (qp->msg_stime % nbuckets);
1314 
1315 	for (count = nbuckets; count > 0; count--) {
1316 		qptr = list_head(&qp->msg_wait_snd_ngt[check_index]);
1317 		while (qptr) {
1318 			/*
1319 			 * The lowest hash bucket may actually contain
1320 			 * message types that are not valid for this
1321 			 * request.  This can happen due to the fact that
1322 			 * the message buckets actually contain a consecutive
1323 			 * range of types.
1324 			 */
1325 			if (-qptr->msgw_type >= type) {
1326 				return (qptr);
1327 			}
1328 			qptr = list_next(&qp->msg_wait_snd_ngt[msg_hash], qptr);
1329 		}
1330 
1331 		if (++check_index > MSG_MAX_QNUM) {
1332 			check_index = neg_index;
1333 		}
1334 	}
1335 	return (NULL);
1336 }
1337 
1338 static int
1339 msg_rcvq_sleep(list_t *queue, msgq_wakeup_t *entry, kmutex_t **lock,
1340     kmsqid_t *qp)
1341 {
1342 	int		cvres;
1343 
1344 	cv_init(&entry->msgw_wake_cv, NULL, 0, NULL);
1345 
1346 	list_insert_tail(queue, entry);
1347 
1348 	qp->msg_rcv_cnt++;
1349 	cvres = cv_wait_sig(&entry->msgw_wake_cv, *lock);
1350 	*lock = ipc_relock(msq_svc, qp->msg_perm.ipc_id, *lock);
1351 	qp->msg_rcv_cnt--;
1352 	/*
1353 	 * We have woken up, so remove ourselves from the waiter list.
1354 	 */
1355 	list_remove(queue, entry);
1356 
1357 	return (cvres);
1358 }
1359 
1360 static void
1361 msg_rcvq_wakeup_all(list_t *q_ptr)
1362 {
1363 	msgq_wakeup_t	*q_walk;
1364 
1365 	q_walk = (msgq_wakeup_t *)list_head(q_ptr);
1366 	while (q_walk) {
1367 		/*
1368 		 * Walk the entire list, wake every process up.
1369 		 */
1370 		cv_signal(&q_walk->msgw_wake_cv);
1371 		q_walk = list_next(q_ptr, q_walk);
1372 	}
1373 }
1374 
1375 /*
1376  * msgsys - System entry point for msgctl, msgget, msgrcv, and msgsnd
1377  * system calls.
1378  */
1379 static ssize_t
1380 msgsys(int opcode, uintptr_t a1, uintptr_t a2, uintptr_t a3,
1381 	uintptr_t a4, uintptr_t a5)
1382 {
1383 	ssize_t error;
1384 
1385 	switch (opcode) {
1386 	case MSGGET:
1387 		error = msgget((key_t)a1, (int)a2);
1388 		break;
1389 	case MSGCTL:
1390 		error = msgctl((int)a1, (int)a2, (void *)a3);
1391 		break;
1392 	case MSGRCV:
1393 		error = msgrcv((int)a1, (struct ipcmsgbuf *)a2,
1394 		    (size_t)a3, (long)a4, (int)a5);
1395 		break;
1396 	case MSGSND:
1397 		error = msgsnd((int)a1, (struct ipcmsgbuf *)a2,
1398 		    (size_t)a3, (int)a4);
1399 		break;
1400 	case MSGIDS:
1401 		error = msgids((int *)a1, (uint_t)a2, (uint_t *)a3);
1402 		break;
1403 	case MSGSNAP:
1404 		error = msgsnap((int)a1, (caddr_t)a2, (size_t)a3, (long)a4);
1405 		break;
1406 	default:
1407 		error = set_errno(EINVAL);
1408 		break;
1409 	}
1410 
1411 	return (error);
1412 }
1413 
1414 #ifdef	_SYSCALL32_IMPL
1415 /*
1416  * msgsys32 - System entry point for msgctl, msgget, msgrcv, and msgsnd
1417  * system calls for 32-bit callers on LP64 kernel.
1418  */
1419 static ssize32_t
1420 msgsys32(int opcode, uint32_t a1, uint32_t a2, uint32_t a3,
1421 	uint32_t a4, uint32_t a5)
1422 {
1423 	ssize_t error;
1424 
1425 	switch (opcode) {
1426 	case MSGGET:
1427 		error = msgget((key_t)a1, (int)a2);
1428 		break;
1429 	case MSGCTL:
1430 		error = msgctl((int)a1, (int)a2, (void *)(uintptr_t)a3);
1431 		break;
1432 	case MSGRCV:
1433 		error = msgrcv((int)a1, (struct ipcmsgbuf *)(uintptr_t)a2,
1434 		    (size_t)a3, (long)(int32_t)a4, (int)a5);
1435 		break;
1436 	case MSGSND:
1437 		error = msgsnd((int)a1, (struct ipcmsgbuf *)(uintptr_t)a2,
1438 		    (size_t)(int32_t)a3, (int)a4);
1439 		break;
1440 	case MSGIDS:
1441 		error = msgids((int *)(uintptr_t)a1, (uint_t)a2,
1442 		    (uint_t *)(uintptr_t)a3);
1443 		break;
1444 	case MSGSNAP:
1445 		error = msgsnap((int)a1, (caddr_t)(uintptr_t)a2, (size_t)a3,
1446 		    (long)(int32_t)a4);
1447 		break;
1448 	default:
1449 		error = set_errno(EINVAL);
1450 		break;
1451 	}
1452 
1453 	return (error);
1454 }
1455 #endif	/* SYSCALL32_IMPL */
1456