xref: /titanic_51/usr/src/uts/common/os/ipc.c (revision 45916cd2fec6e79bca5dee0421bd39e3c2910d1e)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
28 /*	  All Rights Reserved  	*/
29 
30 
31 #pragma ident	"%Z%%M%	%I%	%E% SMI"
32 
33 /*
34  * Common Inter-Process Communication routines.
35  *
36  * Overview
37  * --------
38  *
39  * The System V inter-process communication (IPC) facilities provide
40  * three services, message queues, semaphore arrays, and shared memory
41  * segments, which are mananged using filesystem-like namespaces.
42  * Unlike a filesystem, these namespaces aren't mounted and accessible
43  * via a path -- a special API is used to interact with the different
44  * facilities (nothing precludes a VFS-based interface, but the
45  * standards require the special APIs).  Furthermore, these special
46  * APIs don't use file descriptors, nor do they have an equivalent.
47  * This means that every operation which acts on an object needs to
48  * perform the quivalent of a lookup, which in turn means that every
49  * operation can fail if the specified object doesn't exist in the
50  * facility's namespace.
51  *
52  * Objects
53  * -------
54  *
55  * Each object in a namespace has a unique ID, which is assigned by the
56  * system and is used to identify the object when performing operations
57  * on it.  An object can also have a key, which is selected by the user
58  * at allocation time and is used as a primitive rendezvous mechanism.
59  * An object without a key is said to have a "private" key.
60  *
61  * To perform an operation on an object given its key, one must first
62  * perform a lookup and obtain its ID.  The ID is then used to identify
63  * the object when performing the operation.  If the object has a
64  * private key, the ID must be known or obtained by other means.
65  *
66  * Each object in the namespace has a creator uid and gid, as well as
67  * an owner uid and gid.  Both are initialized with the ruid and rgid
68  * of the process which created the object.  The creator or current
69  * owner has the ability to change the owner of the object.
70  *
71  * Each object in the namespace has a set of file-like permissions,
72  * which, in conjunction with the creator and owner uid and gid,
73  * control read and write access to the object (execute is ignored).
74  *
75  * Each object also has a creator project, which is used to account for
76  * its resource usage.
77  *
78  * Operations
79  * ----------
80  *
81  * There are five operations which all three facilities have in
82  * common: GET, SET, STAT, RMID, and IDS.
83  *
84  * GET, like open, is used to allocate a new object or obtain an
85  * existing one (using its key).  It takes a key, a set of flags and
86  * mode bits, and optionally facility-specific arguments.  If the key
87  * is IPC_PRIVATE, a new object with the requested mode bits and
88  * facility-specific attributes is created.  If the key isn't
89  * IPC_PRIVATE, the GET will attempt to look up the specified key and
90  * either return that or create a new key depending on the state of the
91  * IPC_CREAT and IPC_EXCL flags, much like open.  If GET needs to
92  * allocate an object, it can fail if there is insufficient space in
93  * the namespace (the maximum number of ids for the facility has been
94  * exceeded) or if the facility-specific initialization fails.  If GET
95  * finds an object it can return, it can still fail if that object's
96  * permissions or facility-specific attributes are less than those
97  * requested.
98  *
99  * SET is used to adjust facility-specific parameters of an object, in
100  * addition to the owner uid and gid, and mode bits.  It can fail if
101  * the caller isn't the creator or owner.
102  *
103  * STAT is used to obtain information about an object including the
104  * general attributes object described as well as facility-specific
105  * information.  It can fail if the caller doesn't have read
106  * permission.
107  *
108  * RMID removes an object from the namespace.  Subsequent operations
109  * using the object's ID or key will fail (until another object is
110  * created with the same key or ID).  Since an RMID may be performed
111  * asynchronously with other operations, it is possible that other
112  * threads and/or processes will have references to the object.  While
113  * a facility may have actions which need to be performed at RMID time,
114  * only when all references are dropped can the object be destroyed.
115  * RMID will fail if the caller isn't the creator or owner.
116  *
117  * IDS obtains a list of all IDs in a facility's namespace.  There are
118  * no facility-specific behaviors of IDS.
119  *
120  * Design
121  * ------
122  *
123  * Because some IPC facilities provide services whose operations must
124  * scale, a mechanism which allows fast, concurrent access to
125  * individual objects is needed.  Of primary importance is object
126  * lookup based on ID (SET, STAT, others).  Allocation (GET),
127  * deallocation (RMID), ID enumeration (IDS), and key lookups (GET) are
128  * lesser concerns, but should be implemented in such a way that ID
129  * lookup isn't affected (at least not in the common case).
130  *
131  * Starting from the bottom up, each object is represented by a
132  * structure, the first member of which must be a kipc_perm_t.  The
133  * kipc_perm_t contains the information described above in "Objects", a
134  * reference count (since the object may continue to exist after it has
135  * been removed from the namespace), as well as some additional
136  * metadata used to manage data structure membership.  These objects
137  * are dynamically allocated.
138  *
139  * Above the objects is a power-of-two sized table of ID slots.  Each
140  * slot contains a pointer to an object, a sequence number, and a
141  * lock.  An object's ID is a function of its slot's index in the table
142  * and its slot's sequence number.  Every time a slot is released (via
143  * RMID) its sequence number is increased.  Strictly speaking, the
144  * sequence number is unnecessary.  However, checking the sequence
145  * number after a lookup provides a certain degree of robustness
146  * against the use of stale IDs (useful since nothing else does).  When
147  * the table fills up, it is resized (see Locking, below).
148  *
149  * Of an ID's 31 bits (an ID is, as defined by the standards, a signed
150  * int) the top IPC_SEQ_BITS are used for the sequence number with the
151  * remainder holding the index into the table.  The size of the table
152  * is therefore bounded at 2 ^ (31 - IPC_SEQ_BITS) slots.
153  *
154  * Managing this table is the ipc_service structure.  It contains a
155  * pointer to the dynamically allocated ID table, a namespace-global
156  * lock, an id_space for managing the free space in the table, and
157  * sundry other metadata necessary for the maintenance of the
158  * namespace.  An AVL tree of all keyed objects in the table (sorted by
159  * key) is used for key lookups.  An unordered doubly linked list of
160  * all objects in the namespace (keyed or not) is maintained to
161  * facilitate ID enumeration.
162  *
163  * To help visualize these relationships, here's a picture of a
164  * namespace with a table of size 8 containing three objects
165  * (IPC_SEQ_BITS = 28):
166  *
167  *
168  * +-ipc_service_t--+
169  * | table          *---\
170  * | keys           *---+----------------------\
171  * | all ids        *--\|                      |
172  * |                |  ||                      |
173  * +----------------+  ||                      |
174  *                     ||                      |
175  * /-------------------/|                      |
176  * |    /---------------/                      |
177  * |    |                                      |
178  * |    v                                      |
179  * |  +-0------+-1------+-2------+-3------+-4--+---+-5------+-6------+-7------+
180  * |  | Seq=3  |        |        | Seq=1  |    :   |        |        | Seq=6  |
181  * |  |        |        |        |        |    :   |        |        |        |
182  * |  +-*------+--------+--------+-*------+----+---+--------+--------+-*------+
183  * |    |                          |           |                       |
184  * |    |                      /---/           |      /----------------/
185  * |    |                      |               |      |
186  * |    v                      v               |      v
187  * |  +-kipc_perm_t-+        +-kipc_perm_t-+   |    +-kipc_perm_t-+
188  * |  | id=0x30     |        | id=0x13     |   |    | id=0x67     |
189  * |  | key=0xfeed  |        | key=0xbeef  |   |    | key=0xcafe  |
190  * \->| [list]      |<------>| [list]      |<------>| [list]      |
191  * /->| [avl left]  x   /--->| [avl left]  x   \--->| [avl left]  *---\
192  * |  | [avl right] x   |    | [avl right] x        | [avl right] *---+-\
193  * |  |             |   |    |             |        |             |   | |
194  * |  +-------------+   |    +-------------+        +-------------+   | |
195  * |                    \---------------------------------------------/ |
196  * \--------------------------------------------------------------------/
197  *
198  * Locking
199  * -------
200  *
201  * There are three locks (or sets of locks) which are used to ensure
202  * correctness: the slot locks, the namespace lock, and p_lock (needed
203  * when checking resource controls).  Their ordering is
204  *
205  *   namespace lock -> slot lock 0 -> ... -> slot lock t -> p_lock
206  *
207  * Generally speaking, the namespace lock is used to protect allocation
208  * and removal from the namespace, ID enumeration, and resizing the ID
209  * table.  Specifically:
210  *
211  * - write access to all fields of the ipc_service structure
212  * - read access to all variable fields of ipc_service except
213  *   ipcs_tabsz (table size) and ipcs_table (the table pointer)
214  * - read/write access to ipc_avl, ipc_list in visible objects'
215  *   kipc_perm structures (i.e. objects which have been removed from
216  *   the namespace don't have this restriction)
217  * - write access to ipct_seq and ipct_data in the table entries
218  *
219  * A slot lock by itself is meaningless (except when resizing).  Of
220  * greater interest conceptually is the notion of an ID lock -- a
221  * "virtual lock" which refers to whichever slot lock an object's ID
222  * currently hashes to.
223  *
224  * An ID lock protects all objects with that ID.  Normally there will
225  * only be one such object: the one pointed to by the locked slot.
226  * However, if an object is removed from the namespace but retains
227  * references (e.g. an attached shared memory segment which has been
228  * RMIDed), it continues to use the lock associated with its original
229  * ID.  While this can result in increased contention, operations which
230  * require taking the ID lock of removed objects are infrequent.
231  *
232  * Specifically, an ID lock protects the contents of an object's
233  * structure, including the contents of the embedded kipc_perm
234  * structure (but excluding those fields protected by the namespace
235  * lock).  It also protects the ipct_seq and ipct_data fields in its
236  * slot (it is really a slot lock, after all).
237  *
238  * Recall that the table is resizable.  To avoid requiring every ID
239  * lookup to take a global lock, a scheme much like that employed for
240  * file descriptors (see the comment above UF_ENTER in user.h) is
241  * used.  Note that the sequence number and data pointer are protected
242  * by both the namespace lock and their slot lock.  When the table is
243  * resized, the following operations take place:
244  *
245  *   1) A new table is allocated.
246  *   2) The global lock is taken.
247  *   3) All old slots are locked, in order.
248  *   4) The first half of the new slots are locked.
249  *   5) All table entries are copied to the new table, and cleared from
250  *	the old table.
251  *   6) The ipc_service structure is updated to point to the new table.
252  *   7) The ipc_service structure is updated with the new table size.
253  *   8) All slot locks (old and new) are dropped.
254  *
255  * Because the slot locks are embedded in the table, ID lookups and
256  * other operations which require taking an slot lock need to verify
257  * that the lock taken wasn't part of a stale table.  This is
258  * accomplished by checking the table size before and after
259  * dereferencing the table pointer and taking the lock: if the size
260  * changes, the lock must be dropped and reacquired.  It is this
261  * additional work which distinguishes an ID lock from a slot lock.
262  *
263  * Because we can't guarantee that threads aren't accessing the old
264  * tables' locks, they are never deallocated.  To prevent spurious
265  * reports of memory leaks, a pointer to the discarded table is stored
266  * in the new one in step 5.  (Theoretically ipcs_destroy will delete
267  * the discarded tables, but it is only ever called from a failed _init
268  * invocation; i.e. when there aren't any.)
269  *
270  * Interfaces
271  * ----------
272  *
273  * The following interfaces are provided by the ipc module for use by
274  * the individual IPC facilities:
275  *
276  * ipcperm_access
277  *
278  *   Given an object and a cred structure, determines if the requested
279  *   access type is allowed.
280  *
281  * ipcperm_set, ipcperm_stat,
282  * ipcperm_set64, ipcperm_stat64
283  *
284  *   Performs the common portion of an STAT or SET operation.  All
285  *   (except stat and stat64) can fail, so they should be called before
286  *   any facility-specific non-reversible changes are made to an
287  *   object.  Similarly, the set operations have side effects, so they
288  *   should only be called once the possibility of a facility-specific
289  *   failure is eliminated.
290  *
291  * ipcs_create
292  *
293  *   Creates an IPC namespace for use by an IPC facility.
294  *
295  * ipcs_destroy
296  *
297  *   Destroys an IPC namespace.
298  *
299  * ipcs_lock, ipcs_unlock
300  *
301  *   Takes the namespace lock.  Ideally such access wouldn't be
302  *   necessary, but there may be facility-specific data protected by
303  *   this lock (e.g. project-wide resource consumption).
304  *
305  * ipc_lock
306  *
307  *   Takes the lock associated with an ID.  Can't fail.
308  *
309  * ipc_relock
310  *
311  *   Like ipc_lock, but takes a pointer to a held lock.  Drops the lock
312  *   unless it is the one that would have been returned by ipc_lock.
313  *   Used after calls to cv_wait.
314  *
315  * ipc_lookup
316  *
317  *   Performs an ID lookup, returns with the ID lock held.  Fails if
318  *   the ID doesn't exist in the namespace.
319  *
320  * ipc_hold
321  *
322  *   Takes a reference on an object.
323  *
324  * ipc_rele
325  *
326  *   Releases a reference on an object, and drops the object's lock.
327  *   Calls the object's destructor if last reference is being
328  *   released.
329  *
330  * ipc_rele_locked
331  *
332  *   Releases a reference on an object.  Doesn't drop lock, and may
333  *   only be called when there is more than one reference to the
334  *   object.
335  *
336  * ipc_get, ipc_commit_begin, ipc_commit_end, ipc_cleanup
337  *
338  *   Components of a GET operation.  ipc_get performs a key lookup,
339  *   allocating an object if the key isn't found (returning with the
340  *   namespace lock and p_lock held), and returning the existing object
341  *   if it is (with the object lock held).  ipc_get doesn't modify the
342  *   namespace.
343  *
344  *   ipc_commit_begin begins the process of inserting an object
345  *   allocated by ipc_get into the namespace, and can fail.  If
346  *   successful, it returns with the namespace lock and p_lock held.
347  *   ipc_commit_end completes the process of inserting an object into
348  *   the namespace and can't fail.  The facility can call ipc_cleanup
349  *   at any time following a successful ipc_get and before
350  *   ipc_commit_end or a failed ipc_commit_begin to fail the
351  *   allocation.  Pseudocode for the suggested GET implementation:
352  *
353  *   top:
354  *
355  *     ipc_get
356  *
357  *     if failure
358  *       return
359  *
360  *     if found {
361  *
362  *	 if object meets criteria
363  *	   unlock object and return success
364  *       else
365  *	   unlock object and return failure
366  *
367  *     } else {
368  *
369  *	 perform resource control tests
370  *	 drop namespace lock, p_lock
371  *	 if failure
372  *	   ipc_cleanup
373  *
374  *       perform facility-specific initialization
375  *	 if failure {
376  *	   facility-specific cleanup
377  *	   ipc_cleanup
378  *       }
379  *
380  *	 ( At this point the object should be destructible using the
381  *	   destructor given to ipcs_create )
382  *
383  *       ipc_commit_begin
384  *	 if retry
385  *	   goto top
386  *       else if failure
387  *         return
388  *
389  *       perform facility-specific resource control tests/allocations
390  *	 if failure
391  *	   ipc_cleanup
392  *
393  *	 ipc_commit_end
394  *	 perform any infallible post-creation actions, unlock, and return
395  *
396  *     }
397  *
398  * ipc_rmid
399  *
400  *   Performs the common portion of an RMID operation -- looks up an ID
401  *   removes it, and calls the a facility-specific function to do
402  *   RMID-time cleanup on the private portions of the object.
403  *
404  * ipc_ids
405  *
406  *   Performs the common portion of an IDS operation.
407  *
408  */
409 
410 #include <sys/types.h>
411 #include <sys/param.h>
412 #include <sys/cred.h>
413 #include <sys/policy.h>
414 #include <sys/proc.h>
415 #include <sys/user.h>
416 #include <sys/ipc.h>
417 #include <sys/ipc_impl.h>
418 #include <sys/errno.h>
419 #include <sys/systm.h>
420 #include <sys/list.h>
421 #include <sys/atomic.h>
422 #include <sys/zone.h>
423 #include <sys/task.h>
424 #include <sys/modctl.h>
425 
426 #include <c2/audit.h>
427 
428 static struct modlmisc modlmisc = {
429 	&mod_miscops,
430 	"common ipc code",
431 };
432 
433 static struct modlinkage modlinkage = {
434 	MODREV_1, (void *)&modlmisc, NULL
435 };
436 
437 
438 int
439 _init(void)
440 {
441 	return (mod_install(&modlinkage));
442 }
443 
444 int
445 _fini(void)
446 {
447 	return (mod_remove(&modlinkage));
448 }
449 
450 int
451 _info(struct modinfo *modinfop)
452 {
453 	return (mod_info(&modlinkage, modinfop));
454 }
455 
456 
457 /*
458  * Check message, semaphore, or shared memory access permissions.
459  *
460  * This routine verifies the requested access permission for the current
461  * process.  The zone ids are compared, and the appropriate bits are
462  * checked corresponding to owner, group (including the list of
463  * supplementary groups), or everyone.  Zero is returned on success.
464  * On failure, the security policy is asked to check to override the
465  * permissions check; the policy will either return 0 for access granted
466  * or EACCES.
467  *
468  * Access to objects in other zones requires that the caller be in the
469  * global zone and have the appropriate IPC_DAC_* privilege, regardless
470  * of whether the uid or gid match those of the object.  Note that
471  * cross-zone accesses will normally never get here since they'll
472  * fail in ipc_lookup or ipc_get.
473  *
474  * The arguments must be set up as follows:
475  * 	p - Pointer to permission structure to verify
476  * 	mode - Desired access permissions
477  */
478 int
479 ipcperm_access(kipc_perm_t *p, int mode, cred_t *cr)
480 {
481 	int shifts = 0;
482 	uid_t uid = crgetuid(cr);
483 	zoneid_t zoneid = getzoneid();
484 
485 	if (p->ipc_zoneid == zoneid) {
486 		if (uid != p->ipc_uid && uid != p->ipc_cuid) {
487 			shifts += 3;
488 			if (!groupmember(p->ipc_gid, cr) &&
489 			    !groupmember(p->ipc_cgid, cr))
490 				shifts += 3;
491 		}
492 
493 		mode &= ~(p->ipc_mode << shifts);
494 
495 		if (mode == 0)
496 			return (0);
497 	} else if (zoneid != GLOBAL_ZONEID)
498 		return (EACCES);
499 
500 	return (secpolicy_ipc_access(cr, p, mode));
501 }
502 
503 /*
504  * There are two versions of the ipcperm_set/stat functions:
505  *   ipcperm_???        - for use with IPC_SET/STAT
506  *   ipcperm_???_64     - for use with IPC_SET64/STAT64
507  *
508  * These functions encapsulate the common portions (copying, permission
509  * checks, and auditing) of the set/stat operations.  All, except for
510  * stat and stat_64 which are void, return 0 on success or a non-zero
511  * errno value on error.
512  */
513 
514 int
515 ipcperm_set(ipc_service_t *service, struct cred *cr,
516     kipc_perm_t *kperm, struct ipc_perm *perm, model_t model)
517 {
518 	STRUCT_HANDLE(ipc_perm, lperm);
519 	uid_t uid;
520 	gid_t gid;
521 	mode_t mode;
522 
523 	ASSERT(IPC_LOCKED(service, kperm));
524 
525 	STRUCT_SET_HANDLE(lperm, model, perm);
526 	uid = STRUCT_FGET(lperm, uid);
527 	gid = STRUCT_FGET(lperm, gid);
528 	mode = STRUCT_FGET(lperm, mode);
529 
530 	if (secpolicy_ipc_owner(cr, kperm) != 0)
531 		return (EPERM);
532 
533 	if ((uid < 0) || (uid > MAXUID) || (gid < 0) || (gid > MAXUID))
534 		return (EINVAL);
535 
536 	kperm->ipc_uid = uid;
537 	kperm->ipc_gid = gid;
538 	kperm->ipc_mode = (mode & 0777) | (kperm->ipc_mode & ~0777);
539 
540 #ifdef C2_AUDIT
541 	if (audit_active)
542 		audit_ipcget(service->ipcs_atype, kperm);
543 #endif
544 
545 	return (0);
546 }
547 
548 void
549 ipcperm_stat(struct ipc_perm *perm, kipc_perm_t *kperm, model_t model)
550 {
551 	STRUCT_HANDLE(ipc_perm, lperm);
552 
553 	STRUCT_SET_HANDLE(lperm, model, perm);
554 	STRUCT_FSET(lperm, uid, kperm->ipc_uid);
555 	STRUCT_FSET(lperm, gid, kperm->ipc_gid);
556 	STRUCT_FSET(lperm, cuid, kperm->ipc_cuid);
557 	STRUCT_FSET(lperm, cgid, kperm->ipc_cgid);
558 	STRUCT_FSET(lperm, mode, kperm->ipc_mode);
559 	STRUCT_FSET(lperm, seq, 0);
560 	STRUCT_FSET(lperm, key, kperm->ipc_key);
561 }
562 
563 int
564 ipcperm_set64(ipc_service_t *service, struct cred *cr,
565     kipc_perm_t *kperm, ipc_perm64_t *perm64)
566 {
567 	ASSERT(IPC_LOCKED(service, kperm));
568 
569 	if (secpolicy_ipc_owner(cr, kperm) != 0)
570 		return (EPERM);
571 
572 	if ((perm64->ipcx_uid < 0) || (perm64->ipcx_uid > MAXUID) ||
573 	    (perm64->ipcx_gid < 0) || (perm64->ipcx_gid > MAXUID))
574 		return (EINVAL);
575 
576 	kperm->ipc_uid = perm64->ipcx_uid;
577 	kperm->ipc_gid = perm64->ipcx_gid;
578 	kperm->ipc_mode = (perm64->ipcx_mode & 0777) |
579 	    (kperm->ipc_mode & ~0777);
580 
581 #ifdef C2_AUDIT
582 	if (audit_active)
583 		audit_ipcget(service->ipcs_atype, kperm);
584 #endif
585 
586 	return (0);
587 }
588 
589 void
590 ipcperm_stat64(ipc_perm64_t *perm64, kipc_perm_t *kperm)
591 {
592 	perm64->ipcx_uid = kperm->ipc_uid;
593 	perm64->ipcx_gid = kperm->ipc_gid;
594 	perm64->ipcx_cuid = kperm->ipc_cuid;
595 	perm64->ipcx_cgid = kperm->ipc_cgid;
596 	perm64->ipcx_mode = kperm->ipc_mode;
597 	perm64->ipcx_key = kperm->ipc_key;
598 	perm64->ipcx_projid = kperm->ipc_proj->kpj_id;
599 	perm64->ipcx_zoneid = kperm->ipc_zoneid;
600 }
601 
602 
603 /*
604  * ipc key comparator.
605  */
606 static int
607 ipc_key_compar(const void *a, const void *b)
608 {
609 	kipc_perm_t *aperm = (kipc_perm_t *)a;
610 	kipc_perm_t *bperm = (kipc_perm_t *)b;
611 	int ak = aperm->ipc_key;
612 	int bk = bperm->ipc_key;
613 	zoneid_t az;
614 	zoneid_t bz;
615 
616 	ASSERT(ak != IPC_PRIVATE);
617 	ASSERT(bk != IPC_PRIVATE);
618 
619 	/*
620 	 * Compare key first, then zoneid.  This optimizes performance for
621 	 * systems with only one zone, since the zone checks will only be
622 	 * made when the keys match.
623 	 */
624 	if (ak < bk)
625 		return (-1);
626 	if (ak > bk)
627 		return (1);
628 
629 	/* keys match */
630 	az = aperm->ipc_zoneid;
631 	bz = bperm->ipc_zoneid;
632 	if (az < bz)
633 		return (-1);
634 	if (az > bz)
635 		return (1);
636 	return (0);
637 }
638 
639 /*
640  * Create an ipc service.
641  */
642 ipc_service_t *
643 ipcs_create(const char *name, rctl_hndl_t rctl, size_t size, ipc_func_t *dtor,
644     ipc_func_t *rmid, int audit_type, size_t rctl_offset)
645 {
646 	ipc_service_t *result;
647 
648 	result = kmem_alloc(sizeof (ipc_service_t), KM_SLEEP);
649 
650 	mutex_init(&result->ipcs_lock, NULL, MUTEX_ADAPTIVE, NULL);
651 	result->ipcs_count = 0;
652 	avl_create(&result->ipcs_keys, ipc_key_compar, size, 0);
653 	result->ipcs_tabsz = IPC_IDS_MIN;
654 	result->ipcs_table =
655 	    kmem_zalloc(IPC_IDS_MIN * sizeof (ipc_slot_t), KM_SLEEP);
656 	result->ipcs_ssize = size;
657 	result->ipcs_ids = id_space_create(name, 0, IPC_IDS_MIN);
658 	result->ipcs_dtor = dtor;
659 	result->ipcs_rmid = rmid;
660 	result->ipcs_rctl = rctl;
661 	result->ipcs_atype = audit_type;
662 	ASSERT(rctl_offset < sizeof (kproject_data_t));
663 	result->ipcs_rctlofs = rctl_offset;
664 	list_create(&result->ipcs_usedids, sizeof (kipc_perm_t),
665 	    offsetof(kipc_perm_t, ipc_list));
666 
667 	return (result);
668 }
669 
670 /*
671  * Destroy an ipc service.
672  */
673 void
674 ipcs_destroy(ipc_service_t *service)
675 {
676 	ipc_slot_t *slot, *next;
677 
678 	mutex_enter(&service->ipcs_lock);
679 
680 	ASSERT(service->ipcs_count == 0);
681 	avl_destroy(&service->ipcs_keys);
682 	list_destroy(&service->ipcs_usedids);
683 	id_space_destroy(service->ipcs_ids);
684 
685 	for (slot = service->ipcs_table; slot; slot = next) {
686 		next = slot[0].ipct_chain;
687 		kmem_free(slot, service->ipcs_tabsz * sizeof (ipc_slot_t));
688 		service->ipcs_tabsz >>= 1;
689 	}
690 
691 	mutex_destroy(&service->ipcs_lock);
692 	kmem_free(service, sizeof (ipc_service_t));
693 }
694 
695 /*
696  * Takes the service lock.
697  */
698 void
699 ipcs_lock(ipc_service_t *service)
700 {
701 	mutex_enter(&service->ipcs_lock);
702 }
703 
704 /*
705  * Releases the service lock.
706  */
707 void
708 ipcs_unlock(ipc_service_t *service)
709 {
710 	mutex_exit(&service->ipcs_lock);
711 }
712 
713 
714 /*
715  * Locks the specified ID.  Returns the ID's ID table index.
716  */
717 static int
718 ipc_lock_internal(ipc_service_t *service, uint_t id)
719 {
720 	uint_t	tabsz;
721 	uint_t	index;
722 	kmutex_t *mutex;
723 
724 	for (;;) {
725 		tabsz = service->ipcs_tabsz;
726 		membar_consumer();
727 		index = id & (tabsz - 1);
728 		mutex = &service->ipcs_table[index].ipct_lock;
729 		mutex_enter(mutex);
730 		if (tabsz == service->ipcs_tabsz)
731 			break;
732 		mutex_exit(mutex);
733 	}
734 
735 	return (index);
736 }
737 
738 /*
739  * Locks the specified ID.  Returns a pointer to the ID's lock.
740  */
741 kmutex_t *
742 ipc_lock(ipc_service_t *service, int id)
743 {
744 	uint_t index;
745 
746 	/*
747 	 * These assertions don't reflect requirements of the code
748 	 * which follows, but they should never fail nonetheless.
749 	 */
750 	ASSERT(id >= 0);
751 	ASSERT(IPC_INDEX(id) < service->ipcs_tabsz);
752 	index = ipc_lock_internal(service, id);
753 
754 	return (&service->ipcs_table[index].ipct_lock);
755 }
756 
757 /*
758  * Checks to see if the held lock provided is the current lock for the
759  * specified id.  If so, we return it instead of dropping it and
760  * returning the result of ipc_lock.  This is intended to speed up cv
761  * wakeups where we are left holding a lock which could be stale, but
762  * probably isn't.
763  */
764 kmutex_t *
765 ipc_relock(ipc_service_t *service, int id, kmutex_t *lock)
766 {
767 	ASSERT(id >= 0);
768 	ASSERT(IPC_INDEX(id) < service->ipcs_tabsz);
769 	ASSERT(MUTEX_HELD(lock));
770 
771 	if (&service->ipcs_table[IPC_INDEX(id)].ipct_lock == lock)
772 		return (lock);
773 
774 	mutex_exit(lock);
775 	return (ipc_lock(service, id));
776 }
777 
778 /*
779  * Performs an ID lookup.  If the ID doesn't exist or has been removed,
780  * or isn't visible to the caller (because of zones), NULL is returned.
781  * Otherwise, a pointer to the ID's perm structure and held ID lock are
782  * returned.
783  */
784 kmutex_t *
785 ipc_lookup(ipc_service_t *service, int id, kipc_perm_t **perm)
786 {
787 	kipc_perm_t *result;
788 	uint_t index;
789 
790 	/*
791 	 * There is no need to check to see if id is in-range (i.e.
792 	 * positive and fits into the table).  If it is out-of-range,
793 	 * the id simply won't match the object's.
794 	 */
795 
796 	index = ipc_lock_internal(service, id);
797 	result = service->ipcs_table[index].ipct_data;
798 	if (result == NULL || result->ipc_id != (uint_t)id ||
799 	    !HASZONEACCESS(curproc, result->ipc_zoneid)) {
800 		mutex_exit(&service->ipcs_table[index].ipct_lock);
801 		return (NULL);
802 	}
803 
804 	ASSERT(IPC_SEQ(id) == service->ipcs_table[index].ipct_seq);
805 
806 	*perm = result;
807 #ifdef C2_AUDIT
808 	if (audit_active)
809 		audit_ipc(service->ipcs_atype, id, result);
810 #endif
811 
812 	return (&service->ipcs_table[index].ipct_lock);
813 }
814 
815 /*
816  * Increase the reference count on an ID.
817  */
818 /*ARGSUSED*/
819 void
820 ipc_hold(ipc_service_t *s, kipc_perm_t *perm)
821 {
822 	ASSERT(IPC_INDEX(perm->ipc_id) < s->ipcs_tabsz);
823 	ASSERT(IPC_LOCKED(s, perm));
824 	perm->ipc_ref++;
825 }
826 
827 /*
828  * Decrease the reference count on an ID and drops the ID's lock.
829  * Destroys the ID if the new reference count is zero.
830  */
831 void
832 ipc_rele(ipc_service_t *s, kipc_perm_t *perm)
833 {
834 	int nref;
835 
836 	ASSERT(IPC_INDEX(perm->ipc_id) < s->ipcs_tabsz);
837 	ASSERT(IPC_LOCKED(s, perm));
838 	ASSERT(perm->ipc_ref > 0);
839 
840 	nref = --perm->ipc_ref;
841 	mutex_exit(&s->ipcs_table[IPC_INDEX(perm->ipc_id)].ipct_lock);
842 
843 	if (nref == 0) {
844 		ASSERT(IPC_FREE(perm));		/* ipc_rmid clears IPC_ALLOC */
845 		s->ipcs_dtor(perm);
846 		project_rele(perm->ipc_proj);
847 		kmem_free(perm, s->ipcs_ssize);
848 	}
849 }
850 
851 /*
852  * Decrease the reference count on an ID, but don't drop the ID lock.
853  * Used in cases where one thread needs to remove many references (on
854  * behalf of other parties).
855  */
856 void
857 ipc_rele_locked(ipc_service_t *s, kipc_perm_t *perm)
858 {
859 	ASSERT(perm->ipc_ref > 1);
860 	ASSERT(IPC_INDEX(perm->ipc_id) < s->ipcs_tabsz);
861 	ASSERT(IPC_LOCKED(s, perm));
862 
863 	perm->ipc_ref--;
864 }
865 
866 
867 /*
868  * Internal function to grow the service ID table.
869  */
870 static int
871 ipc_grow(ipc_service_t *service)
872 {
873 	ipc_slot_t *new, *old;
874 	int i, oldsize, newsize;
875 
876 	ASSERT(MUTEX_HELD(&service->ipcs_lock));
877 	ASSERT(MUTEX_NOT_HELD(&curproc->p_lock));
878 
879 	if (service->ipcs_tabsz == IPC_IDS_MAX)
880 		return (ENOSPC);
881 
882 	oldsize = service->ipcs_tabsz;
883 	newsize = oldsize << 1;
884 	new = kmem_zalloc(newsize * sizeof (ipc_slot_t), KM_NOSLEEP);
885 	if (new == NULL)
886 		return (ENOSPC);
887 
888 	old = service->ipcs_table;
889 	for (i = 0; i < oldsize; i++) {
890 		mutex_enter(&old[i].ipct_lock);
891 		mutex_enter(&new[i].ipct_lock);
892 
893 		new[i].ipct_seq = old[i].ipct_seq;
894 		new[i].ipct_data = old[i].ipct_data;
895 		old[i].ipct_data = NULL;
896 	}
897 
898 	new[0].ipct_chain = old;
899 	service->ipcs_table = new;
900 	membar_producer();
901 	service->ipcs_tabsz = newsize;
902 
903 	for (i = 0; i < oldsize; i++) {
904 		mutex_exit(&old[i].ipct_lock);
905 		mutex_exit(&new[i].ipct_lock);
906 	}
907 
908 	id_space_extend(service->ipcs_ids, oldsize, service->ipcs_tabsz);
909 
910 	return (0);
911 }
912 
913 
914 static int
915 ipc_keylookup(ipc_service_t *service, key_t key, int flag, kipc_perm_t **permp)
916 {
917 	kipc_perm_t *perm = NULL;
918 	avl_index_t where;
919 	kipc_perm_t template;
920 
921 	ASSERT(MUTEX_HELD(&service->ipcs_lock));
922 
923 	template.ipc_key = key;
924 	template.ipc_zoneid = getzoneid();
925 	if (perm = avl_find(&service->ipcs_keys, &template, &where)) {
926 		ASSERT(!IPC_FREE(perm));
927 		if ((flag & (IPC_CREAT | IPC_EXCL)) == (IPC_CREAT | IPC_EXCL))
928 			return (EEXIST);
929 		if ((flag & 0777) & ~perm->ipc_mode) {
930 #ifdef C2_AUDIT
931 			if (audit_active)
932 				audit_ipcget(NULL, (void *)perm);
933 #endif
934 			return (EACCES);
935 		}
936 		*permp = perm;
937 		return (0);
938 	} else if (flag & IPC_CREAT) {
939 		*permp = NULL;
940 		return (0);
941 	}
942 	return (ENOENT);
943 }
944 
945 static int
946 ipc_alloc_test(ipc_service_t *service, proc_t *pp)
947 {
948 	ASSERT(MUTEX_HELD(&service->ipcs_lock));
949 
950 	/*
951 	 * Resizing the table first would result in a cleaner code
952 	 * path, but would also allow a user to (permanently) double
953 	 * the id table size in cases where the allocation would be
954 	 * denied.  Hence we test the rctl first.
955 	 */
956 retry:
957 	mutex_enter(&pp->p_lock);
958 	if (rctl_test(service->ipcs_rctl, pp->p_task->tk_proj->kpj_rctls, pp,
959 	    1, RCA_SAFE) & RCT_DENY) {
960 		mutex_exit(&pp->p_lock);
961 		return (ENOSPC);
962 	}
963 
964 	if (service->ipcs_count == service->ipcs_tabsz) {
965 		int error;
966 
967 		mutex_exit(&pp->p_lock);
968 		if (error = ipc_grow(service))
969 			return (error);
970 		goto retry;
971 	}
972 
973 	return (0);
974 }
975 
976 /*
977  * Given a key, search for or create the associated identifier.
978  *
979  * If IPC_CREAT is specified and the key isn't found, or if the key is
980  * equal to IPC_PRIVATE, we return 0 and place a pointer to a newly
981  * allocated object structure in permp.  A pointer to the held service
982  * lock is placed in lockp.  ipc_mode's IPC_ALLOC bit is clear.
983  *
984  * If the key is found and no error conditions arise, we return 0 and
985  * place a pointer to the existing object structure in permp.  A
986  * pointer to the held ID lock is placed in lockp.  ipc_mode's
987  * IPC_ALLOC bit is set.
988  *
989  * Otherwise, a non-zero errno value is returned.
990  */
991 int
992 ipc_get(ipc_service_t *service, key_t key, int flag, kipc_perm_t **permp,
993     kmutex_t **lockp)
994 {
995 	kipc_perm_t	*perm = NULL;
996 	proc_t		*pp = curproc;
997 	int		error, index;
998 	cred_t		*cr = CRED();
999 
1000 	if (key != IPC_PRIVATE) {
1001 
1002 		mutex_enter(&service->ipcs_lock);
1003 		error = ipc_keylookup(service, key, flag, &perm);
1004 		if (perm != NULL)
1005 			index = ipc_lock_internal(service, perm->ipc_id);
1006 		mutex_exit(&service->ipcs_lock);
1007 
1008 		if (error) {
1009 			ASSERT(perm == NULL);
1010 			return (error);
1011 		}
1012 
1013 		if (perm) {
1014 			ASSERT(!IPC_FREE(perm));
1015 			*permp = perm;
1016 			*lockp = &service->ipcs_table[index].ipct_lock;
1017 			return (0);
1018 		}
1019 
1020 		/* Key not found; fall through */
1021 	}
1022 
1023 	perm = kmem_zalloc(service->ipcs_ssize, KM_SLEEP);
1024 
1025 	mutex_enter(&service->ipcs_lock);
1026 	if (error = ipc_alloc_test(service, pp)) {
1027 		mutex_exit(&service->ipcs_lock);
1028 		kmem_free(perm, service->ipcs_ssize);
1029 		return (error);
1030 	}
1031 
1032 	perm->ipc_cuid = perm->ipc_uid = crgetuid(cr);
1033 	perm->ipc_cgid = perm->ipc_gid = crgetgid(cr);
1034 	perm->ipc_zoneid = getzoneid();
1035 	perm->ipc_mode = flag & 0777;
1036 	perm->ipc_key = key;
1037 	perm->ipc_ref = 1;
1038 	perm->ipc_id = IPC_ID_INVAL;
1039 	*permp = perm;
1040 	*lockp = &service->ipcs_lock;
1041 
1042 	return (0);
1043 }
1044 
1045 /*
1046  * Attempts to add the a newly created ID to the global namespace.  If
1047  * creating it would cause an error, we return the error.  If there is
1048  * the possibility that we could obtain the existing ID and return it
1049  * to the user, we return EAGAIN.  Otherwise, we return 0 with p_lock
1050  * and the service lock held.
1051  *
1052  * Since this should be only called after all initialization has been
1053  * completed, on failure we automatically invoke the destructor for the
1054  * object and deallocate the memory associated with it.
1055  */
1056 int
1057 ipc_commit_begin(ipc_service_t *service, key_t key, int flag,
1058     kipc_perm_t *newperm)
1059 {
1060 	kipc_perm_t *perm;
1061 	int error;
1062 	proc_t *pp = curproc;
1063 
1064 	ASSERT(newperm->ipc_ref == 1);
1065 	ASSERT(IPC_FREE(newperm));
1066 
1067 	mutex_enter(&service->ipcs_lock);
1068 	/*
1069 	 * Ensure that no-one has raced with us and created the key.
1070 	 */
1071 	if ((key != IPC_PRIVATE) &&
1072 	    (((error = ipc_keylookup(service, key, flag, &perm)) != 0) ||
1073 	    (perm != NULL))) {
1074 		error = error ? error : EAGAIN;
1075 		goto errout;
1076 	}
1077 
1078 	/*
1079 	 * Ensure that no-one has raced with us and used the last of
1080 	 * the permissible ids, or the last of the free spaces in the
1081 	 * id table.
1082 	 */
1083 	if (error = ipc_alloc_test(service, pp))
1084 		goto errout;
1085 
1086 	/*
1087 	 * Set ipc_proj so ipc_cleanup cleans up necessary state.
1088 	 */
1089 	newperm->ipc_proj = pp->p_task->tk_proj;
1090 
1091 	ASSERT(MUTEX_HELD(&service->ipcs_lock));
1092 	ASSERT(MUTEX_HELD(&pp->p_lock));
1093 
1094 	return (0);
1095 errout:
1096 	mutex_exit(&service->ipcs_lock);
1097 	service->ipcs_dtor(newperm);
1098 	kmem_free(newperm, service->ipcs_ssize);
1099 	return (error);
1100 }
1101 
1102 /*
1103  * Commit the ID allocation transaction.  Called with p_lock and the
1104  * service lock held, both of which are dropped.  Returns the held ID
1105  * lock so the caller can extract the ID and perform ipcget auditing.
1106  */
1107 kmutex_t *
1108 ipc_commit_end(ipc_service_t *service, kipc_perm_t *perm)
1109 {
1110 	ipc_slot_t *slot;
1111 	avl_index_t where;
1112 	int index;
1113 	void *loc;
1114 
1115 	ASSERT(MUTEX_HELD(&service->ipcs_lock));
1116 	ASSERT(MUTEX_HELD(&curproc->p_lock));
1117 
1118 	(void) project_hold(perm->ipc_proj);
1119 	mutex_exit(&curproc->p_lock);
1120 
1121 	/*
1122 	 * Pick out our slot.
1123 	 */
1124 	service->ipcs_count++;
1125 	index = id_alloc(service->ipcs_ids);
1126 	ASSERT(index < service->ipcs_tabsz);
1127 	slot = &service->ipcs_table[index];
1128 	mutex_enter(&slot->ipct_lock);
1129 	ASSERT(slot->ipct_data == NULL);
1130 
1131 	/*
1132 	 * Update the perm structure.
1133 	 */
1134 	perm->ipc_mode |= IPC_ALLOC;
1135 	perm->ipc_id = (slot->ipct_seq << IPC_SEQ_SHIFT) | index;
1136 
1137 	/*
1138 	 * Push into global visibility.
1139 	 */
1140 	slot->ipct_data = perm;
1141 	if (perm->ipc_key != IPC_PRIVATE) {
1142 		loc = avl_find(&service->ipcs_keys, perm, &where);
1143 		ASSERT(loc == NULL);
1144 		avl_insert(&service->ipcs_keys, perm, where);
1145 	}
1146 	list_insert_head(&service->ipcs_usedids, perm);
1147 
1148 	/*
1149 	 * Update resource consumption.
1150 	 */
1151 	IPC_USAGE(perm, service) += 1;
1152 
1153 	mutex_exit(&service->ipcs_lock);
1154 	return (&slot->ipct_lock);
1155 }
1156 
1157 /*
1158  * Clean up function, in case the allocation fails.  If called between
1159  * ipc_lookup and ipc_commit_begin, perm->ipc_proj will be 0 and we
1160  * merely free the perm structure.  If called after ipc_commit_begin,
1161  * we also drop locks and call the ID's destructor.
1162  */
1163 void
1164 ipc_cleanup(ipc_service_t *service, kipc_perm_t *perm)
1165 {
1166 	ASSERT(IPC_FREE(perm));
1167 	if (perm->ipc_proj) {
1168 		mutex_exit(&curproc->p_lock);
1169 		mutex_exit(&service->ipcs_lock);
1170 		service->ipcs_dtor(perm);
1171 	}
1172 	kmem_free(perm, service->ipcs_ssize);
1173 }
1174 
1175 
1176 /*
1177  * Common code to remove an IPC object.  This should be called after
1178  * all permissions checks have been performed, and with the service
1179  * and ID locked.  Note that this does not remove the object from
1180  * the ipcs_usedids list (this needs to be done by the caller before
1181  * dropping the service lock).
1182  */
1183 static void
1184 ipc_remove(ipc_service_t *service, kipc_perm_t *perm)
1185 {
1186 	int id = perm->ipc_id;
1187 	int index;
1188 
1189 	ASSERT(MUTEX_HELD(&service->ipcs_lock));
1190 	ASSERT(IPC_LOCKED(service, perm));
1191 
1192 	index = IPC_INDEX(id);
1193 
1194 	service->ipcs_table[index].ipct_data = NULL;
1195 
1196 	if (perm->ipc_key != IPC_PRIVATE)
1197 		avl_remove(&service->ipcs_keys, perm);
1198 	list_remove(&service->ipcs_usedids, perm);
1199 	perm->ipc_mode &= ~IPC_ALLOC;
1200 
1201 	id_free(service->ipcs_ids, index);
1202 
1203 	if (service->ipcs_table[index].ipct_seq++ == IPC_SEQ_MASK)
1204 		service->ipcs_table[index].ipct_seq = 0;
1205 	service->ipcs_count--;
1206 	ASSERT(IPC_USAGE(perm, service) > 0);
1207 	IPC_USAGE(perm, service) -= 1;
1208 	ASSERT(service->ipcs_count || (IPC_USAGE(perm, service) == 0));
1209 }
1210 
1211 
1212 /*
1213  * Common code to perform an IPC_RMID.  Returns an errno value on
1214  * failure, 0 on success.
1215  */
1216 int
1217 ipc_rmid(ipc_service_t *service, int id, cred_t *cr)
1218 {
1219 	kipc_perm_t *perm;
1220 	kmutex_t *lock;
1221 
1222 	mutex_enter(&service->ipcs_lock);
1223 
1224 	lock = ipc_lookup(service, id, &perm);
1225 	if (lock == NULL) {
1226 		mutex_exit(&service->ipcs_lock);
1227 		return (EINVAL);
1228 	}
1229 
1230 	ASSERT(service->ipcs_count > 0);
1231 
1232 	if (secpolicy_ipc_owner(cr, perm) != 0) {
1233 		mutex_exit(lock);
1234 		mutex_exit(&service->ipcs_lock);
1235 		return (EPERM);
1236 	}
1237 
1238 	/*
1239 	 * Nothing can fail from this point on.
1240 	 */
1241 	ipc_remove(service, perm);
1242 	mutex_exit(&service->ipcs_lock);
1243 
1244 	/* perform any per-service removal actions */
1245 	service->ipcs_rmid(perm);
1246 
1247 	ipc_rele(service, perm);
1248 
1249 	return (0);
1250 }
1251 
1252 /*
1253  * Implementation for shmids, semids, and msgids.  buf is the address
1254  * of the user buffer, nids is the size, and pnids is a pointer to
1255  * where we write the actual number of ids that [would] have been
1256  * copied out.
1257  */
1258 int
1259 ipc_ids(ipc_service_t *service, int *buf, uint_t nids, uint_t *pnids)
1260 {
1261 	kipc_perm_t *perm;
1262 	size_t	idsize = 0;
1263 	int	error = 0;
1264 	int	idcount;
1265 	int	*ids;
1266 	int	numids = 0;
1267 	zoneid_t zoneid = getzoneid();
1268 	int	global = INGLOBALZONE(curproc);
1269 
1270 	if (buf == NULL)
1271 		nids = 0;
1272 
1273 	/*
1274 	 * Get an accurate count of the total number of ids, and allocate a
1275 	 * staging buffer.  Since ipcs_count is always sane, we don't have
1276 	 * to take ipcs_lock for our first guess.  If there are no ids, or
1277 	 * we're in the global zone and the number of ids is greater than
1278 	 * the size of the specified buffer, we shunt to the end.  Otherwise,
1279 	 * we go through the id list looking for (and counting) what is
1280 	 * visible in the specified zone.
1281 	 */
1282 	idcount = service->ipcs_count;
1283 	for (;;) {
1284 		if ((global && idcount > nids) || idcount == 0) {
1285 			numids = idcount;
1286 			nids = 0;
1287 			goto out;
1288 		}
1289 
1290 		idsize = idcount * sizeof (int);
1291 		ids = kmem_alloc(idsize, KM_SLEEP);
1292 
1293 		mutex_enter(&service->ipcs_lock);
1294 		if (idcount >= service->ipcs_count)
1295 			break;
1296 		idcount = service->ipcs_count;
1297 		mutex_exit(&service->ipcs_lock);
1298 
1299 		if (idsize != 0) {
1300 			kmem_free(ids, idsize);
1301 			idsize = 0;
1302 		}
1303 	}
1304 
1305 	for (perm = list_head(&service->ipcs_usedids); perm != NULL;
1306 	    perm = list_next(&service->ipcs_usedids, perm)) {
1307 		ASSERT(!IPC_FREE(perm));
1308 		if (global || perm->ipc_zoneid == zoneid)
1309 			ids[numids++] = perm->ipc_id;
1310 	}
1311 	mutex_exit(&service->ipcs_lock);
1312 
1313 	/*
1314 	 * If there isn't enough space to hold all of the ids, just
1315 	 * return the number of ids without copying out any of them.
1316 	 */
1317 	if (nids < numids)
1318 		nids = 0;
1319 
1320 out:
1321 	if (suword32(pnids, (uint32_t)numids) ||
1322 	    (nids != 0 && copyout(ids, buf, numids * sizeof (int))))
1323 		error = EFAULT;
1324 	if (idsize != 0)
1325 		kmem_free(ids, idsize);
1326 	return (error);
1327 }
1328 
1329 /*
1330  * Destroy IPC objects from the given service that are associated with
1331  * the given zone.
1332  *
1333  * We can't hold on to the service lock when freeing objects, so we
1334  * first search the service and move all the objects to a private
1335  * list, then walk through and free them after dropping the lock.
1336  */
1337 void
1338 ipc_remove_zone(ipc_service_t *service, zoneid_t zoneid)
1339 {
1340 	kipc_perm_t *perm, *next;
1341 	list_t rmlist;
1342 	kmutex_t *lock;
1343 
1344 	list_create(&rmlist, sizeof (kipc_perm_t),
1345 	    offsetof(kipc_perm_t, ipc_list));
1346 
1347 	mutex_enter(&service->ipcs_lock);
1348 	for (perm = list_head(&service->ipcs_usedids); perm != NULL;
1349 	    perm = next) {
1350 		next = list_next(&service->ipcs_usedids, perm);
1351 		if (perm->ipc_zoneid != zoneid)
1352 			continue;
1353 
1354 		/*
1355 		 * Remove the object from the service, then put it on
1356 		 * the removal list so we can defer the call to
1357 		 * ipc_rele (which will actually free the structure).
1358 		 * We need to do this since the destructor may grab
1359 		 * the service lock.
1360 		 */
1361 		ASSERT(!IPC_FREE(perm));
1362 		lock = ipc_lock(service, perm->ipc_id);
1363 		ipc_remove(service, perm);
1364 		mutex_exit(lock);
1365 		list_insert_tail(&rmlist, perm);
1366 	}
1367 	mutex_exit(&service->ipcs_lock);
1368 
1369 	/*
1370 	 * Now that we've dropped the service lock, loop through the
1371 	 * private list freeing removed objects.
1372 	 */
1373 	for (perm = list_head(&rmlist); perm != NULL; perm = next) {
1374 		next = list_next(&rmlist, perm);
1375 		list_remove(&rmlist, perm);
1376 
1377 		(void) ipc_lock(service, perm->ipc_id);
1378 
1379 		/* perform any per-service removal actions */
1380 		service->ipcs_rmid(perm);
1381 
1382 		/* release reference */
1383 		ipc_rele(service, perm);
1384 	}
1385 
1386 	list_destroy(&rmlist);
1387 }
1388