xref: /titanic_41/usr/src/uts/common/os/zone.c (revision caf05df5c10c960028f122b1b02a3f7d8f892c31)
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 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * Zones
29  *
30  *   A zone is a named collection of processes, namespace constraints,
31  *   and other system resources which comprise a secure and manageable
32  *   application containment facility.
33  *
34  *   Zones (represented by the reference counted zone_t) are tracked in
35  *   the kernel in the zonehash.  Elsewhere in the kernel, Zone IDs
36  *   (zoneid_t) are used to track zone association.  Zone IDs are
37  *   dynamically generated when the zone is created; if a persistent
38  *   identifier is needed (core files, accounting logs, audit trail,
39  *   etc.), the zone name should be used.
40  *
41  *
42  *   Global Zone:
43  *
44  *   The global zone (zoneid 0) is automatically associated with all
45  *   system resources that have not been bound to a user-created zone.
46  *   This means that even systems where zones are not in active use
47  *   have a global zone, and all processes, mounts, etc. are
48  *   associated with that zone.  The global zone is generally
49  *   unconstrained in terms of privileges and access, though the usual
50  *   credential and privilege based restrictions apply.
51  *
52  *
53  *   Zone States:
54  *
55  *   The states in which a zone may be in and the transitions are as
56  *   follows:
57  *
58  *   ZONE_IS_UNINITIALIZED: primordial state for a zone. The partially
59  *   initialized zone is added to the list of active zones on the system but
60  *   isn't accessible.
61  *
62  *   ZONE_IS_INITIALIZED: Initialization complete except the ZSD callbacks are
63  *   not yet completed. Not possible to enter the zone, but attributes can
64  *   be retrieved.
65  *
66  *   ZONE_IS_READY: zsched (the kernel dummy process for a zone) is
67  *   ready.  The zone is made visible after the ZSD constructor callbacks are
68  *   executed.  A zone remains in this state until it transitions into
69  *   the ZONE_IS_BOOTING state as a result of a call to zone_boot().
70  *
71  *   ZONE_IS_BOOTING: in this shortlived-state, zsched attempts to start
72  *   init.  Should that fail, the zone proceeds to the ZONE_IS_SHUTTING_DOWN
73  *   state.
74  *
75  *   ZONE_IS_RUNNING: The zone is open for business: zsched has
76  *   successfully started init.   A zone remains in this state until
77  *   zone_shutdown() is called.
78  *
79  *   ZONE_IS_SHUTTING_DOWN: zone_shutdown() has been called, the system is
80  *   killing all processes running in the zone. The zone remains
81  *   in this state until there are no more user processes running in the zone.
82  *   zone_create(), zone_enter(), and zone_destroy() on this zone will fail.
83  *   Since zone_shutdown() is restartable, it may be called successfully
84  *   multiple times for the same zone_t.  Setting of the zone's state to
85  *   ZONE_IS_SHUTTING_DOWN is synchronized with mounts, so VOP_MOUNT() may check
86  *   the zone's status without worrying about it being a moving target.
87  *
88  *   ZONE_IS_EMPTY: zone_shutdown() has been called, and there
89  *   are no more user processes in the zone.  The zone remains in this
90  *   state until there are no more kernel threads associated with the
91  *   zone.  zone_create(), zone_enter(), and zone_destroy() on this zone will
92  *   fail.
93  *
94  *   ZONE_IS_DOWN: All kernel threads doing work on behalf of the zone
95  *   have exited.  zone_shutdown() returns.  Henceforth it is not possible to
96  *   join the zone or create kernel threads therein.
97  *
98  *   ZONE_IS_DYING: zone_destroy() has been called on the zone; zone
99  *   remains in this state until zsched exits.  Calls to zone_find_by_*()
100  *   return NULL from now on.
101  *
102  *   ZONE_IS_DEAD: zsched has exited (zone_ntasks == 0).  There are no
103  *   processes or threads doing work on behalf of the zone.  The zone is
104  *   removed from the list of active zones.  zone_destroy() returns, and
105  *   the zone can be recreated.
106  *
107  *   ZONE_IS_FREE (internal state): zone_ref goes to 0, ZSD destructor
108  *   callbacks are executed, and all memory associated with the zone is
109  *   freed.
110  *
111  *   Threads can wait for the zone to enter a requested state by using
112  *   zone_status_wait() or zone_status_timedwait() with the desired
113  *   state passed in as an argument.  Zone state transitions are
114  *   uni-directional; it is not possible to move back to an earlier state.
115  *
116  *
117  *   Zone-Specific Data:
118  *
119  *   Subsystems needing to maintain zone-specific data can store that
120  *   data using the ZSD mechanism.  This provides a zone-specific data
121  *   store, similar to thread-specific data (see pthread_getspecific(3C)
122  *   or the TSD code in uts/common/disp/thread.c.  Also, ZSD can be used
123  *   to register callbacks to be invoked when a zone is created, shut
124  *   down, or destroyed.  This can be used to initialize zone-specific
125  *   data for new zones and to clean up when zones go away.
126  *
127  *
128  *   Data Structures:
129  *
130  *   The per-zone structure (zone_t) is reference counted, and freed
131  *   when all references are released.  zone_hold and zone_rele can be
132  *   used to adjust the reference count.  In addition, reference counts
133  *   associated with the cred_t structure are tracked separately using
134  *   zone_cred_hold and zone_cred_rele.
135  *
136  *   Pointers to active zone_t's are stored in two hash tables; one
137  *   for searching by id, the other for searching by name.  Lookups
138  *   can be performed on either basis, using zone_find_by_id and
139  *   zone_find_by_name.  Both return zone_t pointers with the zone
140  *   held, so zone_rele should be called when the pointer is no longer
141  *   needed.  Zones can also be searched by path; zone_find_by_path
142  *   returns the zone with which a path name is associated (global
143  *   zone if the path is not within some other zone's file system
144  *   hierarchy).  This currently requires iterating through each zone,
145  *   so it is slower than an id or name search via a hash table.
146  *
147  *
148  *   Locking:
149  *
150  *   zonehash_lock: This is a top-level global lock used to protect the
151  *       zone hash tables and lists.  Zones cannot be created or destroyed
152  *       while this lock is held.
153  *   zone_status_lock: This is a global lock protecting zone state.
154  *       Zones cannot change state while this lock is held.  It also
155  *       protects the list of kernel threads associated with a zone.
156  *   zone_lock: This is a per-zone lock used to protect several fields of
157  *       the zone_t (see <sys/zone.h> for details).  In addition, holding
158  *       this lock means that the zone cannot go away.
159  *   zone_nlwps_lock: This is a per-zone lock used to protect the fields
160  *	 related to the zone.max-lwps rctl.
161  *   zone_mem_lock: This is a per-zone lock used to protect the fields
162  *	 related to the zone.max-locked-memory and zone.max-swap rctls.
163  *   zsd_key_lock: This is a global lock protecting the key state for ZSD.
164  *   zone_deathrow_lock: This is a global lock protecting the "deathrow"
165  *       list (a list of zones in the ZONE_IS_DEAD state).
166  *
167  *   Ordering requirements:
168  *       pool_lock --> cpu_lock --> zonehash_lock --> zone_status_lock -->
169  *       	zone_lock --> zsd_key_lock --> pidlock --> p_lock
170  *
171  *   When taking zone_mem_lock or zone_nlwps_lock, the lock ordering is:
172  *	zonehash_lock --> a_lock --> pidlock --> p_lock --> zone_mem_lock
173  *	zonehash_lock --> a_lock --> pidlock --> p_lock --> zone_mem_lock
174  *
175  *   Blocking memory allocations are permitted while holding any of the
176  *   zone locks.
177  *
178  *
179  *   System Call Interface:
180  *
181  *   The zone subsystem can be managed and queried from user level with
182  *   the following system calls (all subcodes of the primary "zone"
183  *   system call):
184  *   - zone_create: creates a zone with selected attributes (name,
185  *     root path, privileges, resource controls, ZFS datasets)
186  *   - zone_enter: allows the current process to enter a zone
187  *   - zone_getattr: reports attributes of a zone
188  *   - zone_setattr: set attributes of a zone
189  *   - zone_boot: set 'init' running for the zone
190  *   - zone_list: lists all zones active in the system
191  *   - zone_lookup: looks up zone id based on name
192  *   - zone_shutdown: initiates shutdown process (see states above)
193  *   - zone_destroy: completes shutdown process (see states above)
194  *
195  */
196 
197 #include <sys/priv_impl.h>
198 #include <sys/cred.h>
199 #include <c2/audit.h>
200 #include <sys/debug.h>
201 #include <sys/file.h>
202 #include <sys/kmem.h>
203 #include <sys/kstat.h>
204 #include <sys/mutex.h>
205 #include <sys/note.h>
206 #include <sys/pathname.h>
207 #include <sys/proc.h>
208 #include <sys/project.h>
209 #include <sys/sysevent.h>
210 #include <sys/task.h>
211 #include <sys/systm.h>
212 #include <sys/types.h>
213 #include <sys/utsname.h>
214 #include <sys/vnode.h>
215 #include <sys/vfs.h>
216 #include <sys/systeminfo.h>
217 #include <sys/policy.h>
218 #include <sys/cred_impl.h>
219 #include <sys/contract_impl.h>
220 #include <sys/contract/process_impl.h>
221 #include <sys/class.h>
222 #include <sys/pool.h>
223 #include <sys/pool_pset.h>
224 #include <sys/pset.h>
225 #include <sys/sysmacros.h>
226 #include <sys/callb.h>
227 #include <sys/vmparam.h>
228 #include <sys/corectl.h>
229 #include <sys/ipc_impl.h>
230 
231 #include <sys/door.h>
232 #include <sys/cpuvar.h>
233 #include <sys/sdt.h>
234 
235 #include <sys/uadmin.h>
236 #include <sys/session.h>
237 #include <sys/cmn_err.h>
238 #include <sys/modhash.h>
239 #include <sys/sunddi.h>
240 #include <sys/nvpair.h>
241 #include <sys/rctl.h>
242 #include <sys/fss.h>
243 #include <sys/brand.h>
244 #include <sys/zone.h>
245 #include <net/if.h>
246 #include <sys/cpucaps.h>
247 #include <vm/seg.h>
248 #include <sys/mac.h>
249 
250 /* List of data link IDs which are accessible from the zone */
251 typedef struct zone_dl {
252 	datalink_id_t	zdl_id;
253 	list_node_t	zdl_linkage;
254 } zone_dl_t;
255 
256 /*
257  * cv used to signal that all references to the zone have been released.  This
258  * needs to be global since there may be multiple waiters, and the first to
259  * wake up will free the zone_t, hence we cannot use zone->zone_cv.
260  */
261 static kcondvar_t zone_destroy_cv;
262 /*
263  * Lock used to serialize access to zone_cv.  This could have been per-zone,
264  * but then we'd need another lock for zone_destroy_cv, and why bother?
265  */
266 static kmutex_t zone_status_lock;
267 
268 /*
269  * ZSD-related global variables.
270  */
271 static kmutex_t zsd_key_lock;	/* protects the following two */
272 /*
273  * The next caller of zone_key_create() will be assigned a key of ++zsd_keyval.
274  */
275 static zone_key_t zsd_keyval = 0;
276 /*
277  * Global list of registered keys.  We use this when a new zone is created.
278  */
279 static list_t zsd_registered_keys;
280 
281 int zone_hash_size = 256;
282 static mod_hash_t *zonehashbyname, *zonehashbyid, *zonehashbylabel;
283 static kmutex_t zonehash_lock;
284 static uint_t zonecount;
285 static id_space_t *zoneid_space;
286 
287 /*
288  * The global zone (aka zone0) is the all-seeing, all-knowing zone in which the
289  * kernel proper runs, and which manages all other zones.
290  *
291  * Although not declared as static, the variable "zone0" should not be used
292  * except for by code that needs to reference the global zone early on in boot,
293  * before it is fully initialized.  All other consumers should use
294  * 'global_zone'.
295  */
296 zone_t zone0;
297 zone_t *global_zone = NULL;	/* Set when the global zone is initialized */
298 
299 /*
300  * List of active zones, protected by zonehash_lock.
301  */
302 static list_t zone_active;
303 
304 /*
305  * List of destroyed zones that still have outstanding cred references.
306  * Used for debugging.  Uses a separate lock to avoid lock ordering
307  * problems in zone_free.
308  */
309 static list_t zone_deathrow;
310 static kmutex_t zone_deathrow_lock;
311 
312 /* number of zones is limited by virtual interface limit in IP */
313 uint_t maxzones = 8192;
314 
315 /* Event channel to sent zone state change notifications */
316 evchan_t *zone_event_chan;
317 
318 /*
319  * This table holds the mapping from kernel zone states to
320  * states visible in the state notification API.
321  * The idea is that we only expose "obvious" states and
322  * do not expose states which are just implementation details.
323  */
324 const char  *zone_status_table[] = {
325 	ZONE_EVENT_UNINITIALIZED,	/* uninitialized */
326 	ZONE_EVENT_INITIALIZED,		/* initialized */
327 	ZONE_EVENT_READY,		/* ready */
328 	ZONE_EVENT_READY,		/* booting */
329 	ZONE_EVENT_RUNNING,		/* running */
330 	ZONE_EVENT_SHUTTING_DOWN,	/* shutting_down */
331 	ZONE_EVENT_SHUTTING_DOWN,	/* empty */
332 	ZONE_EVENT_SHUTTING_DOWN,	/* down */
333 	ZONE_EVENT_SHUTTING_DOWN,	/* dying */
334 	ZONE_EVENT_UNINITIALIZED,	/* dead */
335 };
336 
337 /*
338  * This isn't static so lint doesn't complain.
339  */
340 rctl_hndl_t rc_zone_cpu_shares;
341 rctl_hndl_t rc_zone_locked_mem;
342 rctl_hndl_t rc_zone_max_swap;
343 rctl_hndl_t rc_zone_cpu_cap;
344 rctl_hndl_t rc_zone_nlwps;
345 rctl_hndl_t rc_zone_shmmax;
346 rctl_hndl_t rc_zone_shmmni;
347 rctl_hndl_t rc_zone_semmni;
348 rctl_hndl_t rc_zone_msgmni;
349 /*
350  * Synchronization primitives used to synchronize between mounts and zone
351  * creation/destruction.
352  */
353 static int mounts_in_progress;
354 static kcondvar_t mount_cv;
355 static kmutex_t mount_lock;
356 
357 const char * const zone_default_initname = "/sbin/init";
358 static char * const zone_prefix = "/zone/";
359 static int zone_shutdown(zoneid_t zoneid);
360 static int zone_add_datalink(zoneid_t, datalink_id_t);
361 static int zone_remove_datalink(zoneid_t, datalink_id_t);
362 static int zone_list_datalink(zoneid_t, int *, datalink_id_t *);
363 
364 typedef boolean_t zsd_applyfn_t(kmutex_t *, boolean_t, zone_t *, zone_key_t);
365 
366 static void zsd_apply_all_zones(zsd_applyfn_t *, zone_key_t);
367 static void zsd_apply_all_keys(zsd_applyfn_t *, zone_t *);
368 static boolean_t zsd_apply_create(kmutex_t *, boolean_t, zone_t *, zone_key_t);
369 static boolean_t zsd_apply_shutdown(kmutex_t *, boolean_t, zone_t *,
370     zone_key_t);
371 static boolean_t zsd_apply_destroy(kmutex_t *, boolean_t, zone_t *, zone_key_t);
372 static boolean_t zsd_wait_for_creator(zone_t *, struct zsd_entry *,
373     kmutex_t *);
374 static boolean_t zsd_wait_for_inprogress(zone_t *, struct zsd_entry *,
375     kmutex_t *);
376 
377 /*
378  * Bump this number when you alter the zone syscall interfaces; this is
379  * because we need to have support for previous API versions in libc
380  * to support patching; libc calls into the kernel to determine this number.
381  *
382  * Version 1 of the API is the version originally shipped with Solaris 10
383  * Version 2 alters the zone_create system call in order to support more
384  *     arguments by moving the args into a structure; and to do better
385  *     error reporting when zone_create() fails.
386  * Version 3 alters the zone_create system call in order to support the
387  *     import of ZFS datasets to zones.
388  * Version 4 alters the zone_create system call in order to support
389  *     Trusted Extensions.
390  * Version 5 alters the zone_boot system call, and converts its old
391  *     bootargs parameter to be set by the zone_setattr API instead.
392  * Version 6 adds the flag argument to zone_create.
393  */
394 static const int ZONE_SYSCALL_API_VERSION = 6;
395 
396 /*
397  * Certain filesystems (such as NFS and autofs) need to know which zone
398  * the mount is being placed in.  Because of this, we need to be able to
399  * ensure that a zone isn't in the process of being created such that
400  * nfs_mount() thinks it is in the global zone, while by the time it
401  * gets added the list of mounted zones, it ends up on zoneA's mount
402  * list.
403  *
404  * The following functions: block_mounts()/resume_mounts() and
405  * mount_in_progress()/mount_completed() are used by zones and the VFS
406  * layer (respectively) to synchronize zone creation and new mounts.
407  *
408  * The semantics are like a reader-reader lock such that there may
409  * either be multiple mounts (or zone creations, if that weren't
410  * serialized by zonehash_lock) in progress at the same time, but not
411  * both.
412  *
413  * We use cv's so the user can ctrl-C out of the operation if it's
414  * taking too long.
415  *
416  * The semantics are such that there is unfair bias towards the
417  * "current" operation.  This means that zone creations may starve if
418  * there is a rapid succession of new mounts coming in to the system, or
419  * there is a remote possibility that zones will be created at such a
420  * rate that new mounts will not be able to proceed.
421  */
422 /*
423  * Prevent new mounts from progressing to the point of calling
424  * VFS_MOUNT().  If there are already mounts in this "region", wait for
425  * them to complete.
426  */
427 static int
428 block_mounts(void)
429 {
430 	int retval = 0;
431 
432 	/*
433 	 * Since it may block for a long time, block_mounts() shouldn't be
434 	 * called with zonehash_lock held.
435 	 */
436 	ASSERT(MUTEX_NOT_HELD(&zonehash_lock));
437 	mutex_enter(&mount_lock);
438 	while (mounts_in_progress > 0) {
439 		if (cv_wait_sig(&mount_cv, &mount_lock) == 0)
440 			goto signaled;
441 	}
442 	/*
443 	 * A negative value of mounts_in_progress indicates that mounts
444 	 * have been blocked by (-mounts_in_progress) different callers.
445 	 */
446 	mounts_in_progress--;
447 	retval = 1;
448 signaled:
449 	mutex_exit(&mount_lock);
450 	return (retval);
451 }
452 
453 /*
454  * The VFS layer may progress with new mounts as far as we're concerned.
455  * Allow them to progress if we were the last obstacle.
456  */
457 static void
458 resume_mounts(void)
459 {
460 	mutex_enter(&mount_lock);
461 	if (++mounts_in_progress == 0)
462 		cv_broadcast(&mount_cv);
463 	mutex_exit(&mount_lock);
464 }
465 
466 /*
467  * The VFS layer is busy with a mount; zones should wait until all
468  * mounts are completed to progress.
469  */
470 void
471 mount_in_progress(void)
472 {
473 	mutex_enter(&mount_lock);
474 	while (mounts_in_progress < 0)
475 		cv_wait(&mount_cv, &mount_lock);
476 	mounts_in_progress++;
477 	mutex_exit(&mount_lock);
478 }
479 
480 /*
481  * VFS is done with one mount; wake up any waiting block_mounts()
482  * callers if this is the last mount.
483  */
484 void
485 mount_completed(void)
486 {
487 	mutex_enter(&mount_lock);
488 	if (--mounts_in_progress == 0)
489 		cv_broadcast(&mount_cv);
490 	mutex_exit(&mount_lock);
491 }
492 
493 /*
494  * ZSD routines.
495  *
496  * Zone Specific Data (ZSD) is modeled after Thread Specific Data as
497  * defined by the pthread_key_create() and related interfaces.
498  *
499  * Kernel subsystems may register one or more data items and/or
500  * callbacks to be executed when a zone is created, shutdown, or
501  * destroyed.
502  *
503  * Unlike the thread counterpart, destructor callbacks will be executed
504  * even if the data pointer is NULL and/or there are no constructor
505  * callbacks, so it is the responsibility of such callbacks to check for
506  * NULL data values if necessary.
507  *
508  * The locking strategy and overall picture is as follows:
509  *
510  * When someone calls zone_key_create(), a template ZSD entry is added to the
511  * global list "zsd_registered_keys", protected by zsd_key_lock.  While
512  * holding that lock all the existing zones are marked as
513  * ZSD_CREATE_NEEDED and a copy of the ZSD entry added to the per-zone
514  * zone_zsd list (protected by zone_lock). The global list is updated first
515  * (under zone_key_lock) to make sure that newly created zones use the
516  * most recent list of keys. Then under zonehash_lock we walk the zones
517  * and mark them.  Similar locking is used in zone_key_delete().
518  *
519  * The actual create, shutdown, and destroy callbacks are done without
520  * holding any lock. And zsd_flags are used to ensure that the operations
521  * completed so that when zone_key_create (and zone_create) is done, as well as
522  * zone_key_delete (and zone_destroy) is done, all the necessary callbacks
523  * are completed.
524  *
525  * When new zones are created constructor callbacks for all registered ZSD
526  * entries will be called. That also uses the above two phases of marking
527  * what needs to be done, and then running the callbacks without holding
528  * any locks.
529  *
530  * The framework does not provide any locking around zone_getspecific() and
531  * zone_setspecific() apart from that needed for internal consistency, so
532  * callers interested in atomic "test-and-set" semantics will need to provide
533  * their own locking.
534  */
535 
536 /*
537  * Helper function to find the zsd_entry associated with the key in the
538  * given list.
539  */
540 static struct zsd_entry *
541 zsd_find(list_t *l, zone_key_t key)
542 {
543 	struct zsd_entry *zsd;
544 
545 	for (zsd = list_head(l); zsd != NULL; zsd = list_next(l, zsd)) {
546 		if (zsd->zsd_key == key) {
547 			return (zsd);
548 		}
549 	}
550 	return (NULL);
551 }
552 
553 /*
554  * Helper function to find the zsd_entry associated with the key in the
555  * given list. Move it to the front of the list.
556  */
557 static struct zsd_entry *
558 zsd_find_mru(list_t *l, zone_key_t key)
559 {
560 	struct zsd_entry *zsd;
561 
562 	for (zsd = list_head(l); zsd != NULL; zsd = list_next(l, zsd)) {
563 		if (zsd->zsd_key == key) {
564 			/*
565 			 * Move to head of list to keep list in MRU order.
566 			 */
567 			if (zsd != list_head(l)) {
568 				list_remove(l, zsd);
569 				list_insert_head(l, zsd);
570 			}
571 			return (zsd);
572 		}
573 	}
574 	return (NULL);
575 }
576 
577 void
578 zone_key_create(zone_key_t *keyp, void *(*create)(zoneid_t),
579     void (*shutdown)(zoneid_t, void *), void (*destroy)(zoneid_t, void *))
580 {
581 	struct zsd_entry *zsdp;
582 	struct zsd_entry *t;
583 	struct zone *zone;
584 	zone_key_t  key;
585 
586 	zsdp = kmem_zalloc(sizeof (*zsdp), KM_SLEEP);
587 	zsdp->zsd_data = NULL;
588 	zsdp->zsd_create = create;
589 	zsdp->zsd_shutdown = shutdown;
590 	zsdp->zsd_destroy = destroy;
591 
592 	/*
593 	 * Insert in global list of callbacks. Makes future zone creations
594 	 * see it.
595 	 */
596 	mutex_enter(&zsd_key_lock);
597 	*keyp = key = zsdp->zsd_key = ++zsd_keyval;
598 	ASSERT(zsd_keyval != 0);
599 	list_insert_tail(&zsd_registered_keys, zsdp);
600 	mutex_exit(&zsd_key_lock);
601 
602 	/*
603 	 * Insert for all existing zones and mark them as needing
604 	 * a create callback.
605 	 */
606 	mutex_enter(&zonehash_lock);	/* stop the world */
607 	for (zone = list_head(&zone_active); zone != NULL;
608 	    zone = list_next(&zone_active, zone)) {
609 		zone_status_t status;
610 
611 		mutex_enter(&zone->zone_lock);
612 
613 		/* Skip zones that are on the way down or not yet up */
614 		status = zone_status_get(zone);
615 		if (status >= ZONE_IS_DOWN ||
616 		    status == ZONE_IS_UNINITIALIZED) {
617 			mutex_exit(&zone->zone_lock);
618 			continue;
619 		}
620 
621 		t = zsd_find_mru(&zone->zone_zsd, key);
622 		if (t != NULL) {
623 			/*
624 			 * A zsd_configure already inserted it after
625 			 * we dropped zsd_key_lock above.
626 			 */
627 			mutex_exit(&zone->zone_lock);
628 			continue;
629 		}
630 		t = kmem_zalloc(sizeof (*t), KM_SLEEP);
631 		t->zsd_key = key;
632 		t->zsd_create = create;
633 		t->zsd_shutdown = shutdown;
634 		t->zsd_destroy = destroy;
635 		if (create != NULL) {
636 			t->zsd_flags = ZSD_CREATE_NEEDED;
637 			DTRACE_PROBE2(zsd__create__needed,
638 			    zone_t *, zone, zone_key_t, key);
639 		}
640 		list_insert_tail(&zone->zone_zsd, t);
641 		mutex_exit(&zone->zone_lock);
642 	}
643 	mutex_exit(&zonehash_lock);
644 
645 	if (create != NULL) {
646 		/* Now call the create callback for this key */
647 		zsd_apply_all_zones(zsd_apply_create, key);
648 	}
649 }
650 
651 /*
652  * Function called when a module is being unloaded, or otherwise wishes
653  * to unregister its ZSD key and callbacks.
654  *
655  * Remove from the global list and determine the functions that need to
656  * be called under a global lock. Then call the functions without
657  * holding any locks. Finally free up the zone_zsd entries. (The apply
658  * functions need to access the zone_zsd entries to find zsd_data etc.)
659  */
660 int
661 zone_key_delete(zone_key_t key)
662 {
663 	struct zsd_entry *zsdp = NULL;
664 	zone_t *zone;
665 
666 	mutex_enter(&zsd_key_lock);
667 	zsdp = zsd_find_mru(&zsd_registered_keys, key);
668 	if (zsdp == NULL) {
669 		mutex_exit(&zsd_key_lock);
670 		return (-1);
671 	}
672 	list_remove(&zsd_registered_keys, zsdp);
673 	mutex_exit(&zsd_key_lock);
674 
675 	mutex_enter(&zonehash_lock);
676 	for (zone = list_head(&zone_active); zone != NULL;
677 	    zone = list_next(&zone_active, zone)) {
678 		struct zsd_entry *del;
679 
680 		mutex_enter(&zone->zone_lock);
681 		del = zsd_find_mru(&zone->zone_zsd, key);
682 		if (del == NULL) {
683 			/*
684 			 * Somebody else got here first e.g the zone going
685 			 * away.
686 			 */
687 			mutex_exit(&zone->zone_lock);
688 			continue;
689 		}
690 		ASSERT(del->zsd_shutdown == zsdp->zsd_shutdown);
691 		ASSERT(del->zsd_destroy == zsdp->zsd_destroy);
692 		if (del->zsd_shutdown != NULL &&
693 		    (del->zsd_flags & ZSD_SHUTDOWN_ALL) == 0) {
694 			del->zsd_flags |= ZSD_SHUTDOWN_NEEDED;
695 			DTRACE_PROBE2(zsd__shutdown__needed,
696 			    zone_t *, zone, zone_key_t, key);
697 		}
698 		if (del->zsd_destroy != NULL &&
699 		    (del->zsd_flags & ZSD_DESTROY_ALL) == 0) {
700 			del->zsd_flags |= ZSD_DESTROY_NEEDED;
701 			DTRACE_PROBE2(zsd__destroy__needed,
702 			    zone_t *, zone, zone_key_t, key);
703 		}
704 		mutex_exit(&zone->zone_lock);
705 	}
706 	mutex_exit(&zonehash_lock);
707 	kmem_free(zsdp, sizeof (*zsdp));
708 
709 	/* Now call the shutdown and destroy callback for this key */
710 	zsd_apply_all_zones(zsd_apply_shutdown, key);
711 	zsd_apply_all_zones(zsd_apply_destroy, key);
712 
713 	/* Now we can free up the zsdp structures in each zone */
714 	mutex_enter(&zonehash_lock);
715 	for (zone = list_head(&zone_active); zone != NULL;
716 	    zone = list_next(&zone_active, zone)) {
717 		struct zsd_entry *del;
718 
719 		mutex_enter(&zone->zone_lock);
720 		del = zsd_find(&zone->zone_zsd, key);
721 		if (del != NULL) {
722 			list_remove(&zone->zone_zsd, del);
723 			ASSERT(!(del->zsd_flags & ZSD_ALL_INPROGRESS));
724 			kmem_free(del, sizeof (*del));
725 		}
726 		mutex_exit(&zone->zone_lock);
727 	}
728 	mutex_exit(&zonehash_lock);
729 
730 	return (0);
731 }
732 
733 /*
734  * ZSD counterpart of pthread_setspecific().
735  *
736  * Since all zsd callbacks, including those with no create function,
737  * have an entry in zone_zsd, if the key is registered it is part of
738  * the zone_zsd list.
739  * Return an error if the key wasn't registerd.
740  */
741 int
742 zone_setspecific(zone_key_t key, zone_t *zone, const void *data)
743 {
744 	struct zsd_entry *t;
745 
746 	mutex_enter(&zone->zone_lock);
747 	t = zsd_find_mru(&zone->zone_zsd, key);
748 	if (t != NULL) {
749 		/*
750 		 * Replace old value with new
751 		 */
752 		t->zsd_data = (void *)data;
753 		mutex_exit(&zone->zone_lock);
754 		return (0);
755 	}
756 	mutex_exit(&zone->zone_lock);
757 	return (-1);
758 }
759 
760 /*
761  * ZSD counterpart of pthread_getspecific().
762  */
763 void *
764 zone_getspecific(zone_key_t key, zone_t *zone)
765 {
766 	struct zsd_entry *t;
767 	void *data;
768 
769 	mutex_enter(&zone->zone_lock);
770 	t = zsd_find_mru(&zone->zone_zsd, key);
771 	data = (t == NULL ? NULL : t->zsd_data);
772 	mutex_exit(&zone->zone_lock);
773 	return (data);
774 }
775 
776 /*
777  * Function used to initialize a zone's list of ZSD callbacks and data
778  * when the zone is being created.  The callbacks are initialized from
779  * the template list (zsd_registered_keys). The constructor callback is
780  * executed later (once the zone exists and with locks dropped).
781  */
782 static void
783 zone_zsd_configure(zone_t *zone)
784 {
785 	struct zsd_entry *zsdp;
786 	struct zsd_entry *t;
787 
788 	ASSERT(MUTEX_HELD(&zonehash_lock));
789 	ASSERT(list_head(&zone->zone_zsd) == NULL);
790 	mutex_enter(&zone->zone_lock);
791 	mutex_enter(&zsd_key_lock);
792 	for (zsdp = list_head(&zsd_registered_keys); zsdp != NULL;
793 	    zsdp = list_next(&zsd_registered_keys, zsdp)) {
794 		/*
795 		 * Since this zone is ZONE_IS_UNCONFIGURED, zone_key_create
796 		 * should not have added anything to it.
797 		 */
798 		ASSERT(zsd_find(&zone->zone_zsd, zsdp->zsd_key) == NULL);
799 
800 		t = kmem_zalloc(sizeof (*t), KM_SLEEP);
801 		t->zsd_key = zsdp->zsd_key;
802 		t->zsd_create = zsdp->zsd_create;
803 		t->zsd_shutdown = zsdp->zsd_shutdown;
804 		t->zsd_destroy = zsdp->zsd_destroy;
805 		if (zsdp->zsd_create != NULL) {
806 			t->zsd_flags = ZSD_CREATE_NEEDED;
807 			DTRACE_PROBE2(zsd__create__needed,
808 			    zone_t *, zone, zone_key_t, zsdp->zsd_key);
809 		}
810 		list_insert_tail(&zone->zone_zsd, t);
811 	}
812 	mutex_exit(&zsd_key_lock);
813 	mutex_exit(&zone->zone_lock);
814 }
815 
816 enum zsd_callback_type { ZSD_CREATE, ZSD_SHUTDOWN, ZSD_DESTROY };
817 
818 /*
819  * Helper function to execute shutdown or destructor callbacks.
820  */
821 static void
822 zone_zsd_callbacks(zone_t *zone, enum zsd_callback_type ct)
823 {
824 	struct zsd_entry *t;
825 
826 	ASSERT(ct == ZSD_SHUTDOWN || ct == ZSD_DESTROY);
827 	ASSERT(ct != ZSD_SHUTDOWN || zone_status_get(zone) >= ZONE_IS_EMPTY);
828 	ASSERT(ct != ZSD_DESTROY || zone_status_get(zone) >= ZONE_IS_DOWN);
829 
830 	/*
831 	 * Run the callback solely based on what is registered for the zone
832 	 * in zone_zsd. The global list can change independently of this
833 	 * as keys are registered and unregistered and we don't register new
834 	 * callbacks for a zone that is in the process of going away.
835 	 */
836 	mutex_enter(&zone->zone_lock);
837 	for (t = list_head(&zone->zone_zsd); t != NULL;
838 	    t = list_next(&zone->zone_zsd, t)) {
839 		zone_key_t key = t->zsd_key;
840 
841 		/* Skip if no callbacks registered */
842 
843 		if (ct == ZSD_SHUTDOWN) {
844 			if (t->zsd_shutdown != NULL &&
845 			    (t->zsd_flags & ZSD_SHUTDOWN_ALL) == 0) {
846 				t->zsd_flags |= ZSD_SHUTDOWN_NEEDED;
847 				DTRACE_PROBE2(zsd__shutdown__needed,
848 				    zone_t *, zone, zone_key_t, key);
849 			}
850 		} else {
851 			if (t->zsd_destroy != NULL &&
852 			    (t->zsd_flags & ZSD_DESTROY_ALL) == 0) {
853 				t->zsd_flags |= ZSD_DESTROY_NEEDED;
854 				DTRACE_PROBE2(zsd__destroy__needed,
855 				    zone_t *, zone, zone_key_t, key);
856 			}
857 		}
858 	}
859 	mutex_exit(&zone->zone_lock);
860 
861 	/* Now call the shutdown and destroy callback for this key */
862 	zsd_apply_all_keys(zsd_apply_shutdown, zone);
863 	zsd_apply_all_keys(zsd_apply_destroy, zone);
864 
865 }
866 
867 /*
868  * Called when the zone is going away; free ZSD-related memory, and
869  * destroy the zone_zsd list.
870  */
871 static void
872 zone_free_zsd(zone_t *zone)
873 {
874 	struct zsd_entry *t, *next;
875 
876 	/*
877 	 * Free all the zsd_entry's we had on this zone.
878 	 */
879 	mutex_enter(&zone->zone_lock);
880 	for (t = list_head(&zone->zone_zsd); t != NULL; t = next) {
881 		next = list_next(&zone->zone_zsd, t);
882 		list_remove(&zone->zone_zsd, t);
883 		ASSERT(!(t->zsd_flags & ZSD_ALL_INPROGRESS));
884 		kmem_free(t, sizeof (*t));
885 	}
886 	list_destroy(&zone->zone_zsd);
887 	mutex_exit(&zone->zone_lock);
888 
889 }
890 
891 /*
892  * Apply a function to all zones for particular key value.
893  *
894  * The applyfn has to drop zonehash_lock if it does some work, and
895  * then reacquire it before it returns.
896  * When the lock is dropped we don't follow list_next even
897  * if it is possible to do so without any hazards. This is
898  * because we want the design to allow for the list of zones
899  * to change in any arbitrary way during the time the
900  * lock was dropped.
901  *
902  * It is safe to restart the loop at list_head since the applyfn
903  * changes the zsd_flags as it does work, so a subsequent
904  * pass through will have no effect in applyfn, hence the loop will terminate
905  * in at worst O(N^2).
906  */
907 static void
908 zsd_apply_all_zones(zsd_applyfn_t *applyfn, zone_key_t key)
909 {
910 	zone_t *zone;
911 
912 	mutex_enter(&zonehash_lock);
913 	zone = list_head(&zone_active);
914 	while (zone != NULL) {
915 		if ((applyfn)(&zonehash_lock, B_FALSE, zone, key)) {
916 			/* Lock dropped - restart at head */
917 			zone = list_head(&zone_active);
918 		} else {
919 			zone = list_next(&zone_active, zone);
920 		}
921 	}
922 	mutex_exit(&zonehash_lock);
923 }
924 
925 /*
926  * Apply a function to all keys for a particular zone.
927  *
928  * The applyfn has to drop zonehash_lock if it does some work, and
929  * then reacquire it before it returns.
930  * When the lock is dropped we don't follow list_next even
931  * if it is possible to do so without any hazards. This is
932  * because we want the design to allow for the list of zsd callbacks
933  * to change in any arbitrary way during the time the
934  * lock was dropped.
935  *
936  * It is safe to restart the loop at list_head since the applyfn
937  * changes the zsd_flags as it does work, so a subsequent
938  * pass through will have no effect in applyfn, hence the loop will terminate
939  * in at worst O(N^2).
940  */
941 static void
942 zsd_apply_all_keys(zsd_applyfn_t *applyfn, zone_t *zone)
943 {
944 	struct zsd_entry *t;
945 
946 	mutex_enter(&zone->zone_lock);
947 	t = list_head(&zone->zone_zsd);
948 	while (t != NULL) {
949 		if ((applyfn)(NULL, B_TRUE, zone, t->zsd_key)) {
950 			/* Lock dropped - restart at head */
951 			t = list_head(&zone->zone_zsd);
952 		} else {
953 			t = list_next(&zone->zone_zsd, t);
954 		}
955 	}
956 	mutex_exit(&zone->zone_lock);
957 }
958 
959 /*
960  * Call the create function for the zone and key if CREATE_NEEDED
961  * is set.
962  * If some other thread gets here first and sets CREATE_INPROGRESS, then
963  * we wait for that thread to complete so that we can ensure that
964  * all the callbacks are done when we've looped over all zones/keys.
965  *
966  * When we call the create function, we drop the global held by the
967  * caller, and return true to tell the caller it needs to re-evalute the
968  * state.
969  * If the caller holds zone_lock then zone_lock_held is set, and zone_lock
970  * remains held on exit.
971  */
972 static boolean_t
973 zsd_apply_create(kmutex_t *lockp, boolean_t zone_lock_held,
974     zone_t *zone, zone_key_t key)
975 {
976 	void *result;
977 	struct zsd_entry *t;
978 	boolean_t dropped;
979 
980 	if (lockp != NULL) {
981 		ASSERT(MUTEX_HELD(lockp));
982 	}
983 	if (zone_lock_held) {
984 		ASSERT(MUTEX_HELD(&zone->zone_lock));
985 	} else {
986 		mutex_enter(&zone->zone_lock);
987 	}
988 
989 	t = zsd_find(&zone->zone_zsd, key);
990 	if (t == NULL) {
991 		/*
992 		 * Somebody else got here first e.g the zone going
993 		 * away.
994 		 */
995 		if (!zone_lock_held)
996 			mutex_exit(&zone->zone_lock);
997 		return (B_FALSE);
998 	}
999 	dropped = B_FALSE;
1000 	if (zsd_wait_for_inprogress(zone, t, lockp))
1001 		dropped = B_TRUE;
1002 
1003 	if (t->zsd_flags & ZSD_CREATE_NEEDED) {
1004 		t->zsd_flags &= ~ZSD_CREATE_NEEDED;
1005 		t->zsd_flags |= ZSD_CREATE_INPROGRESS;
1006 		DTRACE_PROBE2(zsd__create__inprogress,
1007 		    zone_t *, zone, zone_key_t, key);
1008 		mutex_exit(&zone->zone_lock);
1009 		if (lockp != NULL)
1010 			mutex_exit(lockp);
1011 
1012 		dropped = B_TRUE;
1013 		ASSERT(t->zsd_create != NULL);
1014 		DTRACE_PROBE2(zsd__create__start,
1015 		    zone_t *, zone, zone_key_t, key);
1016 
1017 		result = (*t->zsd_create)(zone->zone_id);
1018 
1019 		DTRACE_PROBE2(zsd__create__end,
1020 		    zone_t *, zone, voidn *, result);
1021 
1022 		ASSERT(result != NULL);
1023 		if (lockp != NULL)
1024 			mutex_enter(lockp);
1025 		mutex_enter(&zone->zone_lock);
1026 		t->zsd_data = result;
1027 		t->zsd_flags &= ~ZSD_CREATE_INPROGRESS;
1028 		t->zsd_flags |= ZSD_CREATE_COMPLETED;
1029 		cv_broadcast(&t->zsd_cv);
1030 		DTRACE_PROBE2(zsd__create__completed,
1031 		    zone_t *, zone, zone_key_t, key);
1032 	}
1033 	if (!zone_lock_held)
1034 		mutex_exit(&zone->zone_lock);
1035 	return (dropped);
1036 }
1037 
1038 /*
1039  * Call the shutdown function for the zone and key if SHUTDOWN_NEEDED
1040  * is set.
1041  * If some other thread gets here first and sets *_INPROGRESS, then
1042  * we wait for that thread to complete so that we can ensure that
1043  * all the callbacks are done when we've looped over all zones/keys.
1044  *
1045  * When we call the shutdown function, we drop the global held by the
1046  * caller, and return true to tell the caller it needs to re-evalute the
1047  * state.
1048  * If the caller holds zone_lock then zone_lock_held is set, and zone_lock
1049  * remains held on exit.
1050  */
1051 static boolean_t
1052 zsd_apply_shutdown(kmutex_t *lockp, boolean_t zone_lock_held,
1053     zone_t *zone, zone_key_t key)
1054 {
1055 	struct zsd_entry *t;
1056 	void *data;
1057 	boolean_t dropped;
1058 
1059 	if (lockp != NULL) {
1060 		ASSERT(MUTEX_HELD(lockp));
1061 	}
1062 	if (zone_lock_held) {
1063 		ASSERT(MUTEX_HELD(&zone->zone_lock));
1064 	} else {
1065 		mutex_enter(&zone->zone_lock);
1066 	}
1067 
1068 	t = zsd_find(&zone->zone_zsd, key);
1069 	if (t == NULL) {
1070 		/*
1071 		 * Somebody else got here first e.g the zone going
1072 		 * away.
1073 		 */
1074 		if (!zone_lock_held)
1075 			mutex_exit(&zone->zone_lock);
1076 		return (B_FALSE);
1077 	}
1078 	dropped = B_FALSE;
1079 	if (zsd_wait_for_creator(zone, t, lockp))
1080 		dropped = B_TRUE;
1081 
1082 	if (zsd_wait_for_inprogress(zone, t, lockp))
1083 		dropped = B_TRUE;
1084 
1085 	if (t->zsd_flags & ZSD_SHUTDOWN_NEEDED) {
1086 		t->zsd_flags &= ~ZSD_SHUTDOWN_NEEDED;
1087 		t->zsd_flags |= ZSD_SHUTDOWN_INPROGRESS;
1088 		DTRACE_PROBE2(zsd__shutdown__inprogress,
1089 		    zone_t *, zone, zone_key_t, key);
1090 		mutex_exit(&zone->zone_lock);
1091 		if (lockp != NULL)
1092 			mutex_exit(lockp);
1093 		dropped = B_TRUE;
1094 
1095 		ASSERT(t->zsd_shutdown != NULL);
1096 		data = t->zsd_data;
1097 
1098 		DTRACE_PROBE2(zsd__shutdown__start,
1099 		    zone_t *, zone, zone_key_t, key);
1100 
1101 		(t->zsd_shutdown)(zone->zone_id, data);
1102 		DTRACE_PROBE2(zsd__shutdown__end,
1103 		    zone_t *, zone, zone_key_t, key);
1104 
1105 		if (lockp != NULL)
1106 			mutex_enter(lockp);
1107 		mutex_enter(&zone->zone_lock);
1108 		t->zsd_flags &= ~ZSD_SHUTDOWN_INPROGRESS;
1109 		t->zsd_flags |= ZSD_SHUTDOWN_COMPLETED;
1110 		cv_broadcast(&t->zsd_cv);
1111 		DTRACE_PROBE2(zsd__shutdown__completed,
1112 		    zone_t *, zone, zone_key_t, key);
1113 	}
1114 	if (!zone_lock_held)
1115 		mutex_exit(&zone->zone_lock);
1116 	return (dropped);
1117 }
1118 
1119 /*
1120  * Call the destroy function for the zone and key if DESTROY_NEEDED
1121  * is set.
1122  * If some other thread gets here first and sets *_INPROGRESS, then
1123  * we wait for that thread to complete so that we can ensure that
1124  * all the callbacks are done when we've looped over all zones/keys.
1125  *
1126  * When we call the destroy function, we drop the global held by the
1127  * caller, and return true to tell the caller it needs to re-evalute the
1128  * state.
1129  * If the caller holds zone_lock then zone_lock_held is set, and zone_lock
1130  * remains held on exit.
1131  */
1132 static boolean_t
1133 zsd_apply_destroy(kmutex_t *lockp, boolean_t zone_lock_held,
1134     zone_t *zone, zone_key_t key)
1135 {
1136 	struct zsd_entry *t;
1137 	void *data;
1138 	boolean_t dropped;
1139 
1140 	if (lockp != NULL) {
1141 		ASSERT(MUTEX_HELD(lockp));
1142 	}
1143 	if (zone_lock_held) {
1144 		ASSERT(MUTEX_HELD(&zone->zone_lock));
1145 	} else {
1146 		mutex_enter(&zone->zone_lock);
1147 	}
1148 
1149 	t = zsd_find(&zone->zone_zsd, key);
1150 	if (t == NULL) {
1151 		/*
1152 		 * Somebody else got here first e.g the zone going
1153 		 * away.
1154 		 */
1155 		if (!zone_lock_held)
1156 			mutex_exit(&zone->zone_lock);
1157 		return (B_FALSE);
1158 	}
1159 	dropped = B_FALSE;
1160 	if (zsd_wait_for_creator(zone, t, lockp))
1161 		dropped = B_TRUE;
1162 
1163 	if (zsd_wait_for_inprogress(zone, t, lockp))
1164 		dropped = B_TRUE;
1165 
1166 	if (t->zsd_flags & ZSD_DESTROY_NEEDED) {
1167 		t->zsd_flags &= ~ZSD_DESTROY_NEEDED;
1168 		t->zsd_flags |= ZSD_DESTROY_INPROGRESS;
1169 		DTRACE_PROBE2(zsd__destroy__inprogress,
1170 		    zone_t *, zone, zone_key_t, key);
1171 		mutex_exit(&zone->zone_lock);
1172 		if (lockp != NULL)
1173 			mutex_exit(lockp);
1174 		dropped = B_TRUE;
1175 
1176 		ASSERT(t->zsd_destroy != NULL);
1177 		data = t->zsd_data;
1178 		DTRACE_PROBE2(zsd__destroy__start,
1179 		    zone_t *, zone, zone_key_t, key);
1180 
1181 		(t->zsd_destroy)(zone->zone_id, data);
1182 		DTRACE_PROBE2(zsd__destroy__end,
1183 		    zone_t *, zone, zone_key_t, key);
1184 
1185 		if (lockp != NULL)
1186 			mutex_enter(lockp);
1187 		mutex_enter(&zone->zone_lock);
1188 		t->zsd_data = NULL;
1189 		t->zsd_flags &= ~ZSD_DESTROY_INPROGRESS;
1190 		t->zsd_flags |= ZSD_DESTROY_COMPLETED;
1191 		cv_broadcast(&t->zsd_cv);
1192 		DTRACE_PROBE2(zsd__destroy__completed,
1193 		    zone_t *, zone, zone_key_t, key);
1194 	}
1195 	if (!zone_lock_held)
1196 		mutex_exit(&zone->zone_lock);
1197 	return (dropped);
1198 }
1199 
1200 /*
1201  * Wait for any CREATE_NEEDED flag to be cleared.
1202  * Returns true if lockp was temporarily dropped while waiting.
1203  */
1204 static boolean_t
1205 zsd_wait_for_creator(zone_t *zone, struct zsd_entry *t, kmutex_t *lockp)
1206 {
1207 	boolean_t dropped = B_FALSE;
1208 
1209 	while (t->zsd_flags & ZSD_CREATE_NEEDED) {
1210 		DTRACE_PROBE2(zsd__wait__for__creator,
1211 		    zone_t *, zone, struct zsd_entry *, t);
1212 		if (lockp != NULL) {
1213 			dropped = B_TRUE;
1214 			mutex_exit(lockp);
1215 		}
1216 		cv_wait(&t->zsd_cv, &zone->zone_lock);
1217 		if (lockp != NULL) {
1218 			/* First drop zone_lock to preserve order */
1219 			mutex_exit(&zone->zone_lock);
1220 			mutex_enter(lockp);
1221 			mutex_enter(&zone->zone_lock);
1222 		}
1223 	}
1224 	return (dropped);
1225 }
1226 
1227 /*
1228  * Wait for any INPROGRESS flag to be cleared.
1229  * Returns true if lockp was temporarily dropped while waiting.
1230  */
1231 static boolean_t
1232 zsd_wait_for_inprogress(zone_t *zone, struct zsd_entry *t, kmutex_t *lockp)
1233 {
1234 	boolean_t dropped = B_FALSE;
1235 
1236 	while (t->zsd_flags & ZSD_ALL_INPROGRESS) {
1237 		DTRACE_PROBE2(zsd__wait__for__inprogress,
1238 		    zone_t *, zone, struct zsd_entry *, t);
1239 		if (lockp != NULL) {
1240 			dropped = B_TRUE;
1241 			mutex_exit(lockp);
1242 		}
1243 		cv_wait(&t->zsd_cv, &zone->zone_lock);
1244 		if (lockp != NULL) {
1245 			/* First drop zone_lock to preserve order */
1246 			mutex_exit(&zone->zone_lock);
1247 			mutex_enter(lockp);
1248 			mutex_enter(&zone->zone_lock);
1249 		}
1250 	}
1251 	return (dropped);
1252 }
1253 
1254 /*
1255  * Frees memory associated with the zone dataset list.
1256  */
1257 static void
1258 zone_free_datasets(zone_t *zone)
1259 {
1260 	zone_dataset_t *t, *next;
1261 
1262 	for (t = list_head(&zone->zone_datasets); t != NULL; t = next) {
1263 		next = list_next(&zone->zone_datasets, t);
1264 		list_remove(&zone->zone_datasets, t);
1265 		kmem_free(t->zd_dataset, strlen(t->zd_dataset) + 1);
1266 		kmem_free(t, sizeof (*t));
1267 	}
1268 	list_destroy(&zone->zone_datasets);
1269 }
1270 
1271 /*
1272  * zone.cpu-shares resource control support.
1273  */
1274 /*ARGSUSED*/
1275 static rctl_qty_t
1276 zone_cpu_shares_usage(rctl_t *rctl, struct proc *p)
1277 {
1278 	ASSERT(MUTEX_HELD(&p->p_lock));
1279 	return (p->p_zone->zone_shares);
1280 }
1281 
1282 /*ARGSUSED*/
1283 static int
1284 zone_cpu_shares_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e,
1285     rctl_qty_t nv)
1286 {
1287 	ASSERT(MUTEX_HELD(&p->p_lock));
1288 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1289 	if (e->rcep_p.zone == NULL)
1290 		return (0);
1291 
1292 	e->rcep_p.zone->zone_shares = nv;
1293 	return (0);
1294 }
1295 
1296 static rctl_ops_t zone_cpu_shares_ops = {
1297 	rcop_no_action,
1298 	zone_cpu_shares_usage,
1299 	zone_cpu_shares_set,
1300 	rcop_no_test
1301 };
1302 
1303 /*
1304  * zone.cpu-cap resource control support.
1305  */
1306 /*ARGSUSED*/
1307 static rctl_qty_t
1308 zone_cpu_cap_get(rctl_t *rctl, struct proc *p)
1309 {
1310 	ASSERT(MUTEX_HELD(&p->p_lock));
1311 	return (cpucaps_zone_get(p->p_zone));
1312 }
1313 
1314 /*ARGSUSED*/
1315 static int
1316 zone_cpu_cap_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e,
1317     rctl_qty_t nv)
1318 {
1319 	zone_t *zone = e->rcep_p.zone;
1320 
1321 	ASSERT(MUTEX_HELD(&p->p_lock));
1322 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1323 
1324 	if (zone == NULL)
1325 		return (0);
1326 
1327 	/*
1328 	 * set cap to the new value.
1329 	 */
1330 	return (cpucaps_zone_set(zone, nv));
1331 }
1332 
1333 static rctl_ops_t zone_cpu_cap_ops = {
1334 	rcop_no_action,
1335 	zone_cpu_cap_get,
1336 	zone_cpu_cap_set,
1337 	rcop_no_test
1338 };
1339 
1340 /*ARGSUSED*/
1341 static rctl_qty_t
1342 zone_lwps_usage(rctl_t *r, proc_t *p)
1343 {
1344 	rctl_qty_t nlwps;
1345 	zone_t *zone = p->p_zone;
1346 
1347 	ASSERT(MUTEX_HELD(&p->p_lock));
1348 
1349 	mutex_enter(&zone->zone_nlwps_lock);
1350 	nlwps = zone->zone_nlwps;
1351 	mutex_exit(&zone->zone_nlwps_lock);
1352 
1353 	return (nlwps);
1354 }
1355 
1356 /*ARGSUSED*/
1357 static int
1358 zone_lwps_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e, rctl_val_t *rcntl,
1359     rctl_qty_t incr, uint_t flags)
1360 {
1361 	rctl_qty_t nlwps;
1362 
1363 	ASSERT(MUTEX_HELD(&p->p_lock));
1364 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1365 	if (e->rcep_p.zone == NULL)
1366 		return (0);
1367 	ASSERT(MUTEX_HELD(&(e->rcep_p.zone->zone_nlwps_lock)));
1368 	nlwps = e->rcep_p.zone->zone_nlwps;
1369 
1370 	if (nlwps + incr > rcntl->rcv_value)
1371 		return (1);
1372 
1373 	return (0);
1374 }
1375 
1376 /*ARGSUSED*/
1377 static int
1378 zone_lwps_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e, rctl_qty_t nv)
1379 {
1380 	ASSERT(MUTEX_HELD(&p->p_lock));
1381 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1382 	if (e->rcep_p.zone == NULL)
1383 		return (0);
1384 	e->rcep_p.zone->zone_nlwps_ctl = nv;
1385 	return (0);
1386 }
1387 
1388 static rctl_ops_t zone_lwps_ops = {
1389 	rcop_no_action,
1390 	zone_lwps_usage,
1391 	zone_lwps_set,
1392 	zone_lwps_test,
1393 };
1394 
1395 /*ARGSUSED*/
1396 static int
1397 zone_shmmax_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e, rctl_val_t *rval,
1398     rctl_qty_t incr, uint_t flags)
1399 {
1400 	rctl_qty_t v;
1401 	ASSERT(MUTEX_HELD(&p->p_lock));
1402 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1403 	v = e->rcep_p.zone->zone_shmmax + incr;
1404 	if (v > rval->rcv_value)
1405 		return (1);
1406 	return (0);
1407 }
1408 
1409 static rctl_ops_t zone_shmmax_ops = {
1410 	rcop_no_action,
1411 	rcop_no_usage,
1412 	rcop_no_set,
1413 	zone_shmmax_test
1414 };
1415 
1416 /*ARGSUSED*/
1417 static int
1418 zone_shmmni_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e, rctl_val_t *rval,
1419     rctl_qty_t incr, uint_t flags)
1420 {
1421 	rctl_qty_t v;
1422 	ASSERT(MUTEX_HELD(&p->p_lock));
1423 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1424 	v = e->rcep_p.zone->zone_ipc.ipcq_shmmni + incr;
1425 	if (v > rval->rcv_value)
1426 		return (1);
1427 	return (0);
1428 }
1429 
1430 static rctl_ops_t zone_shmmni_ops = {
1431 	rcop_no_action,
1432 	rcop_no_usage,
1433 	rcop_no_set,
1434 	zone_shmmni_test
1435 };
1436 
1437 /*ARGSUSED*/
1438 static int
1439 zone_semmni_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e, rctl_val_t *rval,
1440     rctl_qty_t incr, uint_t flags)
1441 {
1442 	rctl_qty_t v;
1443 	ASSERT(MUTEX_HELD(&p->p_lock));
1444 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1445 	v = e->rcep_p.zone->zone_ipc.ipcq_semmni + incr;
1446 	if (v > rval->rcv_value)
1447 		return (1);
1448 	return (0);
1449 }
1450 
1451 static rctl_ops_t zone_semmni_ops = {
1452 	rcop_no_action,
1453 	rcop_no_usage,
1454 	rcop_no_set,
1455 	zone_semmni_test
1456 };
1457 
1458 /*ARGSUSED*/
1459 static int
1460 zone_msgmni_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e, rctl_val_t *rval,
1461     rctl_qty_t incr, uint_t flags)
1462 {
1463 	rctl_qty_t v;
1464 	ASSERT(MUTEX_HELD(&p->p_lock));
1465 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1466 	v = e->rcep_p.zone->zone_ipc.ipcq_msgmni + incr;
1467 	if (v > rval->rcv_value)
1468 		return (1);
1469 	return (0);
1470 }
1471 
1472 static rctl_ops_t zone_msgmni_ops = {
1473 	rcop_no_action,
1474 	rcop_no_usage,
1475 	rcop_no_set,
1476 	zone_msgmni_test
1477 };
1478 
1479 /*ARGSUSED*/
1480 static rctl_qty_t
1481 zone_locked_mem_usage(rctl_t *rctl, struct proc *p)
1482 {
1483 	rctl_qty_t q;
1484 	ASSERT(MUTEX_HELD(&p->p_lock));
1485 	mutex_enter(&p->p_zone->zone_mem_lock);
1486 	q = p->p_zone->zone_locked_mem;
1487 	mutex_exit(&p->p_zone->zone_mem_lock);
1488 	return (q);
1489 }
1490 
1491 /*ARGSUSED*/
1492 static int
1493 zone_locked_mem_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e,
1494     rctl_val_t *rcntl, rctl_qty_t incr, uint_t flags)
1495 {
1496 	rctl_qty_t q;
1497 	zone_t *z;
1498 
1499 	z = e->rcep_p.zone;
1500 	ASSERT(MUTEX_HELD(&p->p_lock));
1501 	ASSERT(MUTEX_HELD(&z->zone_mem_lock));
1502 	q = z->zone_locked_mem;
1503 	if (q + incr > rcntl->rcv_value)
1504 		return (1);
1505 	return (0);
1506 }
1507 
1508 /*ARGSUSED*/
1509 static int
1510 zone_locked_mem_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e,
1511     rctl_qty_t nv)
1512 {
1513 	ASSERT(MUTEX_HELD(&p->p_lock));
1514 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1515 	if (e->rcep_p.zone == NULL)
1516 		return (0);
1517 	e->rcep_p.zone->zone_locked_mem_ctl = nv;
1518 	return (0);
1519 }
1520 
1521 static rctl_ops_t zone_locked_mem_ops = {
1522 	rcop_no_action,
1523 	zone_locked_mem_usage,
1524 	zone_locked_mem_set,
1525 	zone_locked_mem_test
1526 };
1527 
1528 /*ARGSUSED*/
1529 static rctl_qty_t
1530 zone_max_swap_usage(rctl_t *rctl, struct proc *p)
1531 {
1532 	rctl_qty_t q;
1533 	zone_t *z = p->p_zone;
1534 
1535 	ASSERT(MUTEX_HELD(&p->p_lock));
1536 	mutex_enter(&z->zone_mem_lock);
1537 	q = z->zone_max_swap;
1538 	mutex_exit(&z->zone_mem_lock);
1539 	return (q);
1540 }
1541 
1542 /*ARGSUSED*/
1543 static int
1544 zone_max_swap_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e,
1545     rctl_val_t *rcntl, rctl_qty_t incr, uint_t flags)
1546 {
1547 	rctl_qty_t q;
1548 	zone_t *z;
1549 
1550 	z = e->rcep_p.zone;
1551 	ASSERT(MUTEX_HELD(&p->p_lock));
1552 	ASSERT(MUTEX_HELD(&z->zone_mem_lock));
1553 	q = z->zone_max_swap;
1554 	if (q + incr > rcntl->rcv_value)
1555 		return (1);
1556 	return (0);
1557 }
1558 
1559 /*ARGSUSED*/
1560 static int
1561 zone_max_swap_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e,
1562     rctl_qty_t nv)
1563 {
1564 	ASSERT(MUTEX_HELD(&p->p_lock));
1565 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1566 	if (e->rcep_p.zone == NULL)
1567 		return (0);
1568 	e->rcep_p.zone->zone_max_swap_ctl = nv;
1569 	return (0);
1570 }
1571 
1572 static rctl_ops_t zone_max_swap_ops = {
1573 	rcop_no_action,
1574 	zone_max_swap_usage,
1575 	zone_max_swap_set,
1576 	zone_max_swap_test
1577 };
1578 
1579 /*
1580  * Helper function to brand the zone with a unique ID.
1581  */
1582 static void
1583 zone_uniqid(zone_t *zone)
1584 {
1585 	static uint64_t uniqid = 0;
1586 
1587 	ASSERT(MUTEX_HELD(&zonehash_lock));
1588 	zone->zone_uniqid = uniqid++;
1589 }
1590 
1591 /*
1592  * Returns a held pointer to the "kcred" for the specified zone.
1593  */
1594 struct cred *
1595 zone_get_kcred(zoneid_t zoneid)
1596 {
1597 	zone_t *zone;
1598 	cred_t *cr;
1599 
1600 	if ((zone = zone_find_by_id(zoneid)) == NULL)
1601 		return (NULL);
1602 	cr = zone->zone_kcred;
1603 	crhold(cr);
1604 	zone_rele(zone);
1605 	return (cr);
1606 }
1607 
1608 static int
1609 zone_lockedmem_kstat_update(kstat_t *ksp, int rw)
1610 {
1611 	zone_t *zone = ksp->ks_private;
1612 	zone_kstat_t *zk = ksp->ks_data;
1613 
1614 	if (rw == KSTAT_WRITE)
1615 		return (EACCES);
1616 
1617 	zk->zk_usage.value.ui64 = zone->zone_locked_mem;
1618 	zk->zk_value.value.ui64 = zone->zone_locked_mem_ctl;
1619 	return (0);
1620 }
1621 
1622 static int
1623 zone_swapresv_kstat_update(kstat_t *ksp, int rw)
1624 {
1625 	zone_t *zone = ksp->ks_private;
1626 	zone_kstat_t *zk = ksp->ks_data;
1627 
1628 	if (rw == KSTAT_WRITE)
1629 		return (EACCES);
1630 
1631 	zk->zk_usage.value.ui64 = zone->zone_max_swap;
1632 	zk->zk_value.value.ui64 = zone->zone_max_swap_ctl;
1633 	return (0);
1634 }
1635 
1636 static void
1637 zone_kstat_create(zone_t *zone)
1638 {
1639 	kstat_t *ksp;
1640 	zone_kstat_t *zk;
1641 
1642 	ksp = rctl_kstat_create_zone(zone, "lockedmem", KSTAT_TYPE_NAMED,
1643 	    sizeof (zone_kstat_t) / sizeof (kstat_named_t),
1644 	    KSTAT_FLAG_VIRTUAL);
1645 
1646 	if (ksp == NULL)
1647 		return;
1648 
1649 	zk = ksp->ks_data = kmem_alloc(sizeof (zone_kstat_t), KM_SLEEP);
1650 	ksp->ks_data_size += strlen(zone->zone_name) + 1;
1651 	kstat_named_init(&zk->zk_zonename, "zonename", KSTAT_DATA_STRING);
1652 	kstat_named_setstr(&zk->zk_zonename, zone->zone_name);
1653 	kstat_named_init(&zk->zk_usage, "usage", KSTAT_DATA_UINT64);
1654 	kstat_named_init(&zk->zk_value, "value", KSTAT_DATA_UINT64);
1655 	ksp->ks_update = zone_lockedmem_kstat_update;
1656 	ksp->ks_private = zone;
1657 	kstat_install(ksp);
1658 
1659 	zone->zone_lockedmem_kstat = ksp;
1660 
1661 	ksp = rctl_kstat_create_zone(zone, "swapresv", KSTAT_TYPE_NAMED,
1662 	    sizeof (zone_kstat_t) / sizeof (kstat_named_t),
1663 	    KSTAT_FLAG_VIRTUAL);
1664 
1665 	if (ksp == NULL)
1666 		return;
1667 
1668 	zk = ksp->ks_data = kmem_alloc(sizeof (zone_kstat_t), KM_SLEEP);
1669 	ksp->ks_data_size += strlen(zone->zone_name) + 1;
1670 	kstat_named_init(&zk->zk_zonename, "zonename", KSTAT_DATA_STRING);
1671 	kstat_named_setstr(&zk->zk_zonename, zone->zone_name);
1672 	kstat_named_init(&zk->zk_usage, "usage", KSTAT_DATA_UINT64);
1673 	kstat_named_init(&zk->zk_value, "value", KSTAT_DATA_UINT64);
1674 	ksp->ks_update = zone_swapresv_kstat_update;
1675 	ksp->ks_private = zone;
1676 	kstat_install(ksp);
1677 
1678 	zone->zone_swapresv_kstat = ksp;
1679 }
1680 
1681 static void
1682 zone_kstat_delete(zone_t *zone)
1683 {
1684 	void *data;
1685 
1686 	if (zone->zone_lockedmem_kstat != NULL) {
1687 		data = zone->zone_lockedmem_kstat->ks_data;
1688 		kstat_delete(zone->zone_lockedmem_kstat);
1689 		kmem_free(data, sizeof (zone_kstat_t));
1690 	}
1691 	if (zone->zone_swapresv_kstat != NULL) {
1692 		data = zone->zone_swapresv_kstat->ks_data;
1693 		kstat_delete(zone->zone_swapresv_kstat);
1694 		kmem_free(data, sizeof (zone_kstat_t));
1695 	}
1696 }
1697 
1698 /*
1699  * Called very early on in boot to initialize the ZSD list so that
1700  * zone_key_create() can be called before zone_init().  It also initializes
1701  * portions of zone0 which may be used before zone_init() is called.  The
1702  * variable "global_zone" will be set when zone0 is fully initialized by
1703  * zone_init().
1704  */
1705 void
1706 zone_zsd_init(void)
1707 {
1708 	mutex_init(&zonehash_lock, NULL, MUTEX_DEFAULT, NULL);
1709 	mutex_init(&zsd_key_lock, NULL, MUTEX_DEFAULT, NULL);
1710 	list_create(&zsd_registered_keys, sizeof (struct zsd_entry),
1711 	    offsetof(struct zsd_entry, zsd_linkage));
1712 	list_create(&zone_active, sizeof (zone_t),
1713 	    offsetof(zone_t, zone_linkage));
1714 	list_create(&zone_deathrow, sizeof (zone_t),
1715 	    offsetof(zone_t, zone_linkage));
1716 
1717 	mutex_init(&zone0.zone_lock, NULL, MUTEX_DEFAULT, NULL);
1718 	mutex_init(&zone0.zone_nlwps_lock, NULL, MUTEX_DEFAULT, NULL);
1719 	mutex_init(&zone0.zone_mem_lock, NULL, MUTEX_DEFAULT, NULL);
1720 	zone0.zone_shares = 1;
1721 	zone0.zone_nlwps = 0;
1722 	zone0.zone_nlwps_ctl = INT_MAX;
1723 	zone0.zone_locked_mem = 0;
1724 	zone0.zone_locked_mem_ctl = UINT64_MAX;
1725 	ASSERT(zone0.zone_max_swap == 0);
1726 	zone0.zone_max_swap_ctl = UINT64_MAX;
1727 	zone0.zone_shmmax = 0;
1728 	zone0.zone_ipc.ipcq_shmmni = 0;
1729 	zone0.zone_ipc.ipcq_semmni = 0;
1730 	zone0.zone_ipc.ipcq_msgmni = 0;
1731 	zone0.zone_name = GLOBAL_ZONENAME;
1732 	zone0.zone_nodename = utsname.nodename;
1733 	zone0.zone_domain = srpc_domain;
1734 	zone0.zone_hostid = HW_INVALID_HOSTID;
1735 	zone0.zone_ref = 1;
1736 	zone0.zone_id = GLOBAL_ZONEID;
1737 	zone0.zone_status = ZONE_IS_RUNNING;
1738 	zone0.zone_rootpath = "/";
1739 	zone0.zone_rootpathlen = 2;
1740 	zone0.zone_psetid = ZONE_PS_INVAL;
1741 	zone0.zone_ncpus = 0;
1742 	zone0.zone_ncpus_online = 0;
1743 	zone0.zone_proc_initpid = 1;
1744 	zone0.zone_initname = initname;
1745 	zone0.zone_lockedmem_kstat = NULL;
1746 	zone0.zone_swapresv_kstat = NULL;
1747 	list_create(&zone0.zone_zsd, sizeof (struct zsd_entry),
1748 	    offsetof(struct zsd_entry, zsd_linkage));
1749 	list_insert_head(&zone_active, &zone0);
1750 
1751 	/*
1752 	 * The root filesystem is not mounted yet, so zone_rootvp cannot be set
1753 	 * to anything meaningful.  It is assigned to be 'rootdir' in
1754 	 * vfs_mountroot().
1755 	 */
1756 	zone0.zone_rootvp = NULL;
1757 	zone0.zone_vfslist = NULL;
1758 	zone0.zone_bootargs = initargs;
1759 	zone0.zone_privset = kmem_alloc(sizeof (priv_set_t), KM_SLEEP);
1760 	/*
1761 	 * The global zone has all privileges
1762 	 */
1763 	priv_fillset(zone0.zone_privset);
1764 	/*
1765 	 * Add p0 to the global zone
1766 	 */
1767 	zone0.zone_zsched = &p0;
1768 	p0.p_zone = &zone0;
1769 }
1770 
1771 /*
1772  * Compute a hash value based on the contents of the label and the DOI.  The
1773  * hash algorithm is somewhat arbitrary, but is based on the observation that
1774  * humans will likely pick labels that differ by amounts that work out to be
1775  * multiples of the number of hash chains, and thus stirring in some primes
1776  * should help.
1777  */
1778 static uint_t
1779 hash_bylabel(void *hdata, mod_hash_key_t key)
1780 {
1781 	const ts_label_t *lab = (ts_label_t *)key;
1782 	const uint32_t *up, *ue;
1783 	uint_t hash;
1784 	int i;
1785 
1786 	_NOTE(ARGUNUSED(hdata));
1787 
1788 	hash = lab->tsl_doi + (lab->tsl_doi << 1);
1789 	/* we depend on alignment of label, but not representation */
1790 	up = (const uint32_t *)&lab->tsl_label;
1791 	ue = up + sizeof (lab->tsl_label) / sizeof (*up);
1792 	i = 1;
1793 	while (up < ue) {
1794 		/* using 2^n + 1, 1 <= n <= 16 as source of many primes */
1795 		hash += *up + (*up << ((i % 16) + 1));
1796 		up++;
1797 		i++;
1798 	}
1799 	return (hash);
1800 }
1801 
1802 /*
1803  * All that mod_hash cares about here is zero (equal) versus non-zero (not
1804  * equal).  This may need to be changed if less than / greater than is ever
1805  * needed.
1806  */
1807 static int
1808 hash_labelkey_cmp(mod_hash_key_t key1, mod_hash_key_t key2)
1809 {
1810 	ts_label_t *lab1 = (ts_label_t *)key1;
1811 	ts_label_t *lab2 = (ts_label_t *)key2;
1812 
1813 	return (label_equal(lab1, lab2) ? 0 : 1);
1814 }
1815 
1816 /*
1817  * Called by main() to initialize the zones framework.
1818  */
1819 void
1820 zone_init(void)
1821 {
1822 	rctl_dict_entry_t *rde;
1823 	rctl_val_t *dval;
1824 	rctl_set_t *set;
1825 	rctl_alloc_gp_t *gp;
1826 	rctl_entity_p_t e;
1827 	int res;
1828 
1829 	ASSERT(curproc == &p0);
1830 
1831 	/*
1832 	 * Create ID space for zone IDs.  ID 0 is reserved for the
1833 	 * global zone.
1834 	 */
1835 	zoneid_space = id_space_create("zoneid_space", 1, MAX_ZONEID);
1836 
1837 	/*
1838 	 * Initialize generic zone resource controls, if any.
1839 	 */
1840 	rc_zone_cpu_shares = rctl_register("zone.cpu-shares",
1841 	    RCENTITY_ZONE, RCTL_GLOBAL_SIGNAL_NEVER | RCTL_GLOBAL_DENY_NEVER |
1842 	    RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_COUNT | RCTL_GLOBAL_SYSLOG_NEVER,
1843 	    FSS_MAXSHARES, FSS_MAXSHARES, &zone_cpu_shares_ops);
1844 
1845 	rc_zone_cpu_cap = rctl_register("zone.cpu-cap",
1846 	    RCENTITY_ZONE, RCTL_GLOBAL_SIGNAL_NEVER | RCTL_GLOBAL_DENY_ALWAYS |
1847 	    RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_COUNT |RCTL_GLOBAL_SYSLOG_NEVER |
1848 	    RCTL_GLOBAL_INFINITE,
1849 	    MAXCAP, MAXCAP, &zone_cpu_cap_ops);
1850 
1851 	rc_zone_nlwps = rctl_register("zone.max-lwps", RCENTITY_ZONE,
1852 	    RCTL_GLOBAL_NOACTION | RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_COUNT,
1853 	    INT_MAX, INT_MAX, &zone_lwps_ops);
1854 	/*
1855 	 * System V IPC resource controls
1856 	 */
1857 	rc_zone_msgmni = rctl_register("zone.max-msg-ids",
1858 	    RCENTITY_ZONE, RCTL_GLOBAL_DENY_ALWAYS | RCTL_GLOBAL_NOBASIC |
1859 	    RCTL_GLOBAL_COUNT, IPC_IDS_MAX, IPC_IDS_MAX, &zone_msgmni_ops);
1860 
1861 	rc_zone_semmni = rctl_register("zone.max-sem-ids",
1862 	    RCENTITY_ZONE, RCTL_GLOBAL_DENY_ALWAYS | RCTL_GLOBAL_NOBASIC |
1863 	    RCTL_GLOBAL_COUNT, IPC_IDS_MAX, IPC_IDS_MAX, &zone_semmni_ops);
1864 
1865 	rc_zone_shmmni = rctl_register("zone.max-shm-ids",
1866 	    RCENTITY_ZONE, RCTL_GLOBAL_DENY_ALWAYS | RCTL_GLOBAL_NOBASIC |
1867 	    RCTL_GLOBAL_COUNT, IPC_IDS_MAX, IPC_IDS_MAX, &zone_shmmni_ops);
1868 
1869 	rc_zone_shmmax = rctl_register("zone.max-shm-memory",
1870 	    RCENTITY_ZONE, RCTL_GLOBAL_DENY_ALWAYS | RCTL_GLOBAL_NOBASIC |
1871 	    RCTL_GLOBAL_BYTES, UINT64_MAX, UINT64_MAX, &zone_shmmax_ops);
1872 
1873 	/*
1874 	 * Create a rctl_val with PRIVILEGED, NOACTION, value = 1.  Then attach
1875 	 * this at the head of the rctl_dict_entry for ``zone.cpu-shares''.
1876 	 */
1877 	dval = kmem_cache_alloc(rctl_val_cache, KM_SLEEP);
1878 	bzero(dval, sizeof (rctl_val_t));
1879 	dval->rcv_value = 1;
1880 	dval->rcv_privilege = RCPRIV_PRIVILEGED;
1881 	dval->rcv_flagaction = RCTL_LOCAL_NOACTION;
1882 	dval->rcv_action_recip_pid = -1;
1883 
1884 	rde = rctl_dict_lookup("zone.cpu-shares");
1885 	(void) rctl_val_list_insert(&rde->rcd_default_value, dval);
1886 
1887 	rc_zone_locked_mem = rctl_register("zone.max-locked-memory",
1888 	    RCENTITY_ZONE, RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_BYTES |
1889 	    RCTL_GLOBAL_DENY_ALWAYS, UINT64_MAX, UINT64_MAX,
1890 	    &zone_locked_mem_ops);
1891 
1892 	rc_zone_max_swap = rctl_register("zone.max-swap",
1893 	    RCENTITY_ZONE, RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_BYTES |
1894 	    RCTL_GLOBAL_DENY_ALWAYS, UINT64_MAX, UINT64_MAX,
1895 	    &zone_max_swap_ops);
1896 
1897 	/*
1898 	 * Initialize the ``global zone''.
1899 	 */
1900 	set = rctl_set_create();
1901 	gp = rctl_set_init_prealloc(RCENTITY_ZONE);
1902 	mutex_enter(&p0.p_lock);
1903 	e.rcep_p.zone = &zone0;
1904 	e.rcep_t = RCENTITY_ZONE;
1905 	zone0.zone_rctls = rctl_set_init(RCENTITY_ZONE, &p0, &e, set,
1906 	    gp);
1907 
1908 	zone0.zone_nlwps = p0.p_lwpcnt;
1909 	zone0.zone_ntasks = 1;
1910 	mutex_exit(&p0.p_lock);
1911 	zone0.zone_restart_init = B_TRUE;
1912 	zone0.zone_brand = &native_brand;
1913 	rctl_prealloc_destroy(gp);
1914 	/*
1915 	 * pool_default hasn't been initialized yet, so we let pool_init()
1916 	 * take care of making sure the global zone is in the default pool.
1917 	 */
1918 
1919 	/*
1920 	 * Initialize global zone kstats
1921 	 */
1922 	zone_kstat_create(&zone0);
1923 
1924 	/*
1925 	 * Initialize zone label.
1926 	 * mlp are initialized when tnzonecfg is loaded.
1927 	 */
1928 	zone0.zone_slabel = l_admin_low;
1929 	rw_init(&zone0.zone_mlps.mlpl_rwlock, NULL, RW_DEFAULT, NULL);
1930 	label_hold(l_admin_low);
1931 
1932 	mutex_enter(&zonehash_lock);
1933 	zone_uniqid(&zone0);
1934 	ASSERT(zone0.zone_uniqid == GLOBAL_ZONEUNIQID);
1935 
1936 	zonehashbyid = mod_hash_create_idhash("zone_by_id", zone_hash_size,
1937 	    mod_hash_null_valdtor);
1938 	zonehashbyname = mod_hash_create_strhash("zone_by_name",
1939 	    zone_hash_size, mod_hash_null_valdtor);
1940 	/*
1941 	 * maintain zonehashbylabel only for labeled systems
1942 	 */
1943 	if (is_system_labeled())
1944 		zonehashbylabel = mod_hash_create_extended("zone_by_label",
1945 		    zone_hash_size, mod_hash_null_keydtor,
1946 		    mod_hash_null_valdtor, hash_bylabel, NULL,
1947 		    hash_labelkey_cmp, KM_SLEEP);
1948 	zonecount = 1;
1949 
1950 	(void) mod_hash_insert(zonehashbyid, (mod_hash_key_t)GLOBAL_ZONEID,
1951 	    (mod_hash_val_t)&zone0);
1952 	(void) mod_hash_insert(zonehashbyname, (mod_hash_key_t)zone0.zone_name,
1953 	    (mod_hash_val_t)&zone0);
1954 	if (is_system_labeled()) {
1955 		zone0.zone_flags |= ZF_HASHED_LABEL;
1956 		(void) mod_hash_insert(zonehashbylabel,
1957 		    (mod_hash_key_t)zone0.zone_slabel, (mod_hash_val_t)&zone0);
1958 	}
1959 	mutex_exit(&zonehash_lock);
1960 
1961 	/*
1962 	 * We avoid setting zone_kcred until now, since kcred is initialized
1963 	 * sometime after zone_zsd_init() and before zone_init().
1964 	 */
1965 	zone0.zone_kcred = kcred;
1966 	/*
1967 	 * The global zone is fully initialized (except for zone_rootvp which
1968 	 * will be set when the root filesystem is mounted).
1969 	 */
1970 	global_zone = &zone0;
1971 
1972 	/*
1973 	 * Setup an event channel to send zone status change notifications on
1974 	 */
1975 	res = sysevent_evc_bind(ZONE_EVENT_CHANNEL, &zone_event_chan,
1976 	    EVCH_CREAT);
1977 
1978 	if (res)
1979 		panic("Sysevent_evc_bind failed during zone setup.\n");
1980 
1981 }
1982 
1983 static void
1984 zone_free(zone_t *zone)
1985 {
1986 	ASSERT(zone != global_zone);
1987 	ASSERT(zone->zone_ntasks == 0);
1988 	ASSERT(zone->zone_nlwps == 0);
1989 	ASSERT(zone->zone_cred_ref == 0);
1990 	ASSERT(zone->zone_kcred == NULL);
1991 	ASSERT(zone_status_get(zone) == ZONE_IS_DEAD ||
1992 	    zone_status_get(zone) == ZONE_IS_UNINITIALIZED);
1993 
1994 	/*
1995 	 * Remove any zone caps.
1996 	 */
1997 	cpucaps_zone_remove(zone);
1998 
1999 	ASSERT(zone->zone_cpucap == NULL);
2000 
2001 	/* remove from deathrow list */
2002 	if (zone_status_get(zone) == ZONE_IS_DEAD) {
2003 		ASSERT(zone->zone_ref == 0);
2004 		mutex_enter(&zone_deathrow_lock);
2005 		list_remove(&zone_deathrow, zone);
2006 		mutex_exit(&zone_deathrow_lock);
2007 	}
2008 
2009 	zone_free_zsd(zone);
2010 	zone_free_datasets(zone);
2011 	list_destroy(&zone->zone_dl_list);
2012 
2013 	if (zone->zone_rootvp != NULL)
2014 		VN_RELE(zone->zone_rootvp);
2015 	if (zone->zone_rootpath)
2016 		kmem_free(zone->zone_rootpath, zone->zone_rootpathlen);
2017 	if (zone->zone_name != NULL)
2018 		kmem_free(zone->zone_name, ZONENAME_MAX);
2019 	if (zone->zone_slabel != NULL)
2020 		label_rele(zone->zone_slabel);
2021 	if (zone->zone_nodename != NULL)
2022 		kmem_free(zone->zone_nodename, _SYS_NMLN);
2023 	if (zone->zone_domain != NULL)
2024 		kmem_free(zone->zone_domain, _SYS_NMLN);
2025 	if (zone->zone_privset != NULL)
2026 		kmem_free(zone->zone_privset, sizeof (priv_set_t));
2027 	if (zone->zone_rctls != NULL)
2028 		rctl_set_free(zone->zone_rctls);
2029 	if (zone->zone_bootargs != NULL)
2030 		kmem_free(zone->zone_bootargs, strlen(zone->zone_bootargs) + 1);
2031 	if (zone->zone_initname != NULL)
2032 		kmem_free(zone->zone_initname, strlen(zone->zone_initname) + 1);
2033 	id_free(zoneid_space, zone->zone_id);
2034 	mutex_destroy(&zone->zone_lock);
2035 	cv_destroy(&zone->zone_cv);
2036 	rw_destroy(&zone->zone_mlps.mlpl_rwlock);
2037 	kmem_free(zone, sizeof (zone_t));
2038 }
2039 
2040 /*
2041  * See block comment at the top of this file for information about zone
2042  * status values.
2043  */
2044 /*
2045  * Convenience function for setting zone status.
2046  */
2047 static void
2048 zone_status_set(zone_t *zone, zone_status_t status)
2049 {
2050 
2051 	nvlist_t *nvl = NULL;
2052 	ASSERT(MUTEX_HELD(&zone_status_lock));
2053 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE &&
2054 	    status >= zone_status_get(zone));
2055 
2056 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) ||
2057 	    nvlist_add_string(nvl, ZONE_CB_NAME, zone->zone_name) ||
2058 	    nvlist_add_string(nvl, ZONE_CB_NEWSTATE,
2059 	    zone_status_table[status]) ||
2060 	    nvlist_add_string(nvl, ZONE_CB_OLDSTATE,
2061 	    zone_status_table[zone->zone_status]) ||
2062 	    nvlist_add_int32(nvl, ZONE_CB_ZONEID, zone->zone_id) ||
2063 	    nvlist_add_uint64(nvl, ZONE_CB_TIMESTAMP, (uint64_t)gethrtime()) ||
2064 	    sysevent_evc_publish(zone_event_chan, ZONE_EVENT_STATUS_CLASS,
2065 	    ZONE_EVENT_STATUS_SUBCLASS, "sun.com", "kernel", nvl, EVCH_SLEEP)) {
2066 #ifdef DEBUG
2067 		(void) printf(
2068 		    "Failed to allocate and send zone state change event.\n");
2069 #endif
2070 	}
2071 	nvlist_free(nvl);
2072 
2073 	zone->zone_status = status;
2074 
2075 	cv_broadcast(&zone->zone_cv);
2076 }
2077 
2078 /*
2079  * Public function to retrieve the zone status.  The zone status may
2080  * change after it is retrieved.
2081  */
2082 zone_status_t
2083 zone_status_get(zone_t *zone)
2084 {
2085 	return (zone->zone_status);
2086 }
2087 
2088 static int
2089 zone_set_bootargs(zone_t *zone, const char *zone_bootargs)
2090 {
2091 	char *bootargs = kmem_zalloc(BOOTARGS_MAX, KM_SLEEP);
2092 	int err = 0;
2093 
2094 	ASSERT(zone != global_zone);
2095 	if ((err = copyinstr(zone_bootargs, bootargs, BOOTARGS_MAX, NULL)) != 0)
2096 		goto done;	/* EFAULT or ENAMETOOLONG */
2097 
2098 	if (zone->zone_bootargs != NULL)
2099 		kmem_free(zone->zone_bootargs, strlen(zone->zone_bootargs) + 1);
2100 
2101 	zone->zone_bootargs = kmem_alloc(strlen(bootargs) + 1, KM_SLEEP);
2102 	(void) strcpy(zone->zone_bootargs, bootargs);
2103 
2104 done:
2105 	kmem_free(bootargs, BOOTARGS_MAX);
2106 	return (err);
2107 }
2108 
2109 static int
2110 zone_set_brand(zone_t *zone, const char *brand)
2111 {
2112 	struct brand_attr *attrp;
2113 	brand_t *bp;
2114 
2115 	attrp = kmem_alloc(sizeof (struct brand_attr), KM_SLEEP);
2116 	if (copyin(brand, attrp, sizeof (struct brand_attr)) != 0) {
2117 		kmem_free(attrp, sizeof (struct brand_attr));
2118 		return (EFAULT);
2119 	}
2120 
2121 	bp = brand_register_zone(attrp);
2122 	kmem_free(attrp, sizeof (struct brand_attr));
2123 	if (bp == NULL)
2124 		return (EINVAL);
2125 
2126 	/*
2127 	 * This is the only place where a zone can change it's brand.
2128 	 * We already need to hold zone_status_lock to check the zone
2129 	 * status, so we'll just use that lock to serialize zone
2130 	 * branding requests as well.
2131 	 */
2132 	mutex_enter(&zone_status_lock);
2133 
2134 	/* Re-Branding is not allowed and the zone can't be booted yet */
2135 	if ((ZONE_IS_BRANDED(zone)) ||
2136 	    (zone_status_get(zone) >= ZONE_IS_BOOTING)) {
2137 		mutex_exit(&zone_status_lock);
2138 		brand_unregister_zone(bp);
2139 		return (EINVAL);
2140 	}
2141 
2142 	/* set up the brand specific data */
2143 	zone->zone_brand = bp;
2144 	ZBROP(zone)->b_init_brand_data(zone);
2145 
2146 	mutex_exit(&zone_status_lock);
2147 	return (0);
2148 }
2149 
2150 static int
2151 zone_set_initname(zone_t *zone, const char *zone_initname)
2152 {
2153 	char initname[INITNAME_SZ];
2154 	size_t len;
2155 	int err = 0;
2156 
2157 	ASSERT(zone != global_zone);
2158 	if ((err = copyinstr(zone_initname, initname, INITNAME_SZ, &len)) != 0)
2159 		return (err);	/* EFAULT or ENAMETOOLONG */
2160 
2161 	if (zone->zone_initname != NULL)
2162 		kmem_free(zone->zone_initname, strlen(zone->zone_initname) + 1);
2163 
2164 	zone->zone_initname = kmem_alloc(strlen(initname) + 1, KM_SLEEP);
2165 	(void) strcpy(zone->zone_initname, initname);
2166 	return (0);
2167 }
2168 
2169 static int
2170 zone_set_phys_mcap(zone_t *zone, const uint64_t *zone_mcap)
2171 {
2172 	uint64_t mcap;
2173 	int err = 0;
2174 
2175 	if ((err = copyin(zone_mcap, &mcap, sizeof (uint64_t))) == 0)
2176 		zone->zone_phys_mcap = mcap;
2177 
2178 	return (err);
2179 }
2180 
2181 static int
2182 zone_set_sched_class(zone_t *zone, const char *new_class)
2183 {
2184 	char sched_class[PC_CLNMSZ];
2185 	id_t classid;
2186 	int err;
2187 
2188 	ASSERT(zone != global_zone);
2189 	if ((err = copyinstr(new_class, sched_class, PC_CLNMSZ, NULL)) != 0)
2190 		return (err);	/* EFAULT or ENAMETOOLONG */
2191 
2192 	if (getcid(sched_class, &classid) != 0 || classid == syscid)
2193 		return (set_errno(EINVAL));
2194 	zone->zone_defaultcid = classid;
2195 	ASSERT(zone->zone_defaultcid > 0 &&
2196 	    zone->zone_defaultcid < loaded_classes);
2197 
2198 	return (0);
2199 }
2200 
2201 /*
2202  * Block indefinitely waiting for (zone_status >= status)
2203  */
2204 void
2205 zone_status_wait(zone_t *zone, zone_status_t status)
2206 {
2207 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE);
2208 
2209 	mutex_enter(&zone_status_lock);
2210 	while (zone->zone_status < status) {
2211 		cv_wait(&zone->zone_cv, &zone_status_lock);
2212 	}
2213 	mutex_exit(&zone_status_lock);
2214 }
2215 
2216 /*
2217  * Private CPR-safe version of zone_status_wait().
2218  */
2219 static void
2220 zone_status_wait_cpr(zone_t *zone, zone_status_t status, char *str)
2221 {
2222 	callb_cpr_t cprinfo;
2223 
2224 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE);
2225 
2226 	CALLB_CPR_INIT(&cprinfo, &zone_status_lock, callb_generic_cpr,
2227 	    str);
2228 	mutex_enter(&zone_status_lock);
2229 	while (zone->zone_status < status) {
2230 		CALLB_CPR_SAFE_BEGIN(&cprinfo);
2231 		cv_wait(&zone->zone_cv, &zone_status_lock);
2232 		CALLB_CPR_SAFE_END(&cprinfo, &zone_status_lock);
2233 	}
2234 	/*
2235 	 * zone_status_lock is implicitly released by the following.
2236 	 */
2237 	CALLB_CPR_EXIT(&cprinfo);
2238 }
2239 
2240 /*
2241  * Block until zone enters requested state or signal is received.  Return (0)
2242  * if signaled, non-zero otherwise.
2243  */
2244 int
2245 zone_status_wait_sig(zone_t *zone, zone_status_t status)
2246 {
2247 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE);
2248 
2249 	mutex_enter(&zone_status_lock);
2250 	while (zone->zone_status < status) {
2251 		if (!cv_wait_sig(&zone->zone_cv, &zone_status_lock)) {
2252 			mutex_exit(&zone_status_lock);
2253 			return (0);
2254 		}
2255 	}
2256 	mutex_exit(&zone_status_lock);
2257 	return (1);
2258 }
2259 
2260 /*
2261  * Block until the zone enters the requested state or the timeout expires,
2262  * whichever happens first.  Return (-1) if operation timed out, time remaining
2263  * otherwise.
2264  */
2265 clock_t
2266 zone_status_timedwait(zone_t *zone, clock_t tim, zone_status_t status)
2267 {
2268 	clock_t timeleft = 0;
2269 
2270 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE);
2271 
2272 	mutex_enter(&zone_status_lock);
2273 	while (zone->zone_status < status && timeleft != -1) {
2274 		timeleft = cv_timedwait(&zone->zone_cv, &zone_status_lock, tim);
2275 	}
2276 	mutex_exit(&zone_status_lock);
2277 	return (timeleft);
2278 }
2279 
2280 /*
2281  * Block until the zone enters the requested state, the current process is
2282  * signaled,  or the timeout expires, whichever happens first.  Return (-1) if
2283  * operation timed out, 0 if signaled, time remaining otherwise.
2284  */
2285 clock_t
2286 zone_status_timedwait_sig(zone_t *zone, clock_t tim, zone_status_t status)
2287 {
2288 	clock_t timeleft = tim - lbolt;
2289 
2290 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE);
2291 
2292 	mutex_enter(&zone_status_lock);
2293 	while (zone->zone_status < status) {
2294 		timeleft = cv_timedwait_sig(&zone->zone_cv, &zone_status_lock,
2295 		    tim);
2296 		if (timeleft <= 0)
2297 			break;
2298 	}
2299 	mutex_exit(&zone_status_lock);
2300 	return (timeleft);
2301 }
2302 
2303 /*
2304  * Zones have two reference counts: one for references from credential
2305  * structures (zone_cred_ref), and one (zone_ref) for everything else.
2306  * This is so we can allow a zone to be rebooted while there are still
2307  * outstanding cred references, since certain drivers cache dblks (which
2308  * implicitly results in cached creds).  We wait for zone_ref to drop to
2309  * 0 (actually 1), but not zone_cred_ref.  The zone structure itself is
2310  * later freed when the zone_cred_ref drops to 0, though nothing other
2311  * than the zone id and privilege set should be accessed once the zone
2312  * is "dead".
2313  *
2314  * A debugging flag, zone_wait_for_cred, can be set to a non-zero value
2315  * to force halt/reboot to block waiting for the zone_cred_ref to drop
2316  * to 0.  This can be useful to flush out other sources of cached creds
2317  * that may be less innocuous than the driver case.
2318  */
2319 
2320 int zone_wait_for_cred = 0;
2321 
2322 static void
2323 zone_hold_locked(zone_t *z)
2324 {
2325 	ASSERT(MUTEX_HELD(&z->zone_lock));
2326 	z->zone_ref++;
2327 	ASSERT(z->zone_ref != 0);
2328 }
2329 
2330 void
2331 zone_hold(zone_t *z)
2332 {
2333 	mutex_enter(&z->zone_lock);
2334 	zone_hold_locked(z);
2335 	mutex_exit(&z->zone_lock);
2336 }
2337 
2338 /*
2339  * If the non-cred ref count drops to 1 and either the cred ref count
2340  * is 0 or we aren't waiting for cred references, the zone is ready to
2341  * be destroyed.
2342  */
2343 #define	ZONE_IS_UNREF(zone)	((zone)->zone_ref == 1 && \
2344 	    (!zone_wait_for_cred || (zone)->zone_cred_ref == 0))
2345 
2346 void
2347 zone_rele(zone_t *z)
2348 {
2349 	boolean_t wakeup;
2350 
2351 	mutex_enter(&z->zone_lock);
2352 	ASSERT(z->zone_ref != 0);
2353 	z->zone_ref--;
2354 	if (z->zone_ref == 0 && z->zone_cred_ref == 0) {
2355 		/* no more refs, free the structure */
2356 		mutex_exit(&z->zone_lock);
2357 		zone_free(z);
2358 		return;
2359 	}
2360 	/* signal zone_destroy so the zone can finish halting */
2361 	wakeup = (ZONE_IS_UNREF(z) && zone_status_get(z) >= ZONE_IS_DEAD);
2362 	mutex_exit(&z->zone_lock);
2363 
2364 	if (wakeup) {
2365 		/*
2366 		 * Grabbing zonehash_lock here effectively synchronizes with
2367 		 * zone_destroy() to avoid missed signals.
2368 		 */
2369 		mutex_enter(&zonehash_lock);
2370 		cv_broadcast(&zone_destroy_cv);
2371 		mutex_exit(&zonehash_lock);
2372 	}
2373 }
2374 
2375 void
2376 zone_cred_hold(zone_t *z)
2377 {
2378 	mutex_enter(&z->zone_lock);
2379 	z->zone_cred_ref++;
2380 	ASSERT(z->zone_cred_ref != 0);
2381 	mutex_exit(&z->zone_lock);
2382 }
2383 
2384 void
2385 zone_cred_rele(zone_t *z)
2386 {
2387 	boolean_t wakeup;
2388 
2389 	mutex_enter(&z->zone_lock);
2390 	ASSERT(z->zone_cred_ref != 0);
2391 	z->zone_cred_ref--;
2392 	if (z->zone_ref == 0 && z->zone_cred_ref == 0) {
2393 		/* no more refs, free the structure */
2394 		mutex_exit(&z->zone_lock);
2395 		zone_free(z);
2396 		return;
2397 	}
2398 	/*
2399 	 * If zone_destroy is waiting for the cred references to drain
2400 	 * out, and they have, signal it.
2401 	 */
2402 	wakeup = (zone_wait_for_cred && ZONE_IS_UNREF(z) &&
2403 	    zone_status_get(z) >= ZONE_IS_DEAD);
2404 	mutex_exit(&z->zone_lock);
2405 
2406 	if (wakeup) {
2407 		/*
2408 		 * Grabbing zonehash_lock here effectively synchronizes with
2409 		 * zone_destroy() to avoid missed signals.
2410 		 */
2411 		mutex_enter(&zonehash_lock);
2412 		cv_broadcast(&zone_destroy_cv);
2413 		mutex_exit(&zonehash_lock);
2414 	}
2415 }
2416 
2417 void
2418 zone_task_hold(zone_t *z)
2419 {
2420 	mutex_enter(&z->zone_lock);
2421 	z->zone_ntasks++;
2422 	ASSERT(z->zone_ntasks != 0);
2423 	mutex_exit(&z->zone_lock);
2424 }
2425 
2426 void
2427 zone_task_rele(zone_t *zone)
2428 {
2429 	uint_t refcnt;
2430 
2431 	mutex_enter(&zone->zone_lock);
2432 	ASSERT(zone->zone_ntasks != 0);
2433 	refcnt = --zone->zone_ntasks;
2434 	if (refcnt > 1)	{	/* Common case */
2435 		mutex_exit(&zone->zone_lock);
2436 		return;
2437 	}
2438 	zone_hold_locked(zone);	/* so we can use the zone_t later */
2439 	mutex_exit(&zone->zone_lock);
2440 	if (refcnt == 1) {
2441 		/*
2442 		 * See if the zone is shutting down.
2443 		 */
2444 		mutex_enter(&zone_status_lock);
2445 		if (zone_status_get(zone) != ZONE_IS_SHUTTING_DOWN) {
2446 			goto out;
2447 		}
2448 
2449 		/*
2450 		 * Make sure the ntasks didn't change since we
2451 		 * dropped zone_lock.
2452 		 */
2453 		mutex_enter(&zone->zone_lock);
2454 		if (refcnt != zone->zone_ntasks) {
2455 			mutex_exit(&zone->zone_lock);
2456 			goto out;
2457 		}
2458 		mutex_exit(&zone->zone_lock);
2459 
2460 		/*
2461 		 * No more user processes in the zone.  The zone is empty.
2462 		 */
2463 		zone_status_set(zone, ZONE_IS_EMPTY);
2464 		goto out;
2465 	}
2466 
2467 	ASSERT(refcnt == 0);
2468 	/*
2469 	 * zsched has exited; the zone is dead.
2470 	 */
2471 	zone->zone_zsched = NULL;		/* paranoia */
2472 	mutex_enter(&zone_status_lock);
2473 	zone_status_set(zone, ZONE_IS_DEAD);
2474 out:
2475 	mutex_exit(&zone_status_lock);
2476 	zone_rele(zone);
2477 }
2478 
2479 zoneid_t
2480 getzoneid(void)
2481 {
2482 	return (curproc->p_zone->zone_id);
2483 }
2484 
2485 /*
2486  * Internal versions of zone_find_by_*().  These don't zone_hold() or
2487  * check the validity of a zone's state.
2488  */
2489 static zone_t *
2490 zone_find_all_by_id(zoneid_t zoneid)
2491 {
2492 	mod_hash_val_t hv;
2493 	zone_t *zone = NULL;
2494 
2495 	ASSERT(MUTEX_HELD(&zonehash_lock));
2496 
2497 	if (mod_hash_find(zonehashbyid,
2498 	    (mod_hash_key_t)(uintptr_t)zoneid, &hv) == 0)
2499 		zone = (zone_t *)hv;
2500 	return (zone);
2501 }
2502 
2503 static zone_t *
2504 zone_find_all_by_label(const ts_label_t *label)
2505 {
2506 	mod_hash_val_t hv;
2507 	zone_t *zone = NULL;
2508 
2509 	ASSERT(MUTEX_HELD(&zonehash_lock));
2510 
2511 	/*
2512 	 * zonehashbylabel is not maintained for unlabeled systems
2513 	 */
2514 	if (!is_system_labeled())
2515 		return (NULL);
2516 	if (mod_hash_find(zonehashbylabel, (mod_hash_key_t)label, &hv) == 0)
2517 		zone = (zone_t *)hv;
2518 	return (zone);
2519 }
2520 
2521 static zone_t *
2522 zone_find_all_by_name(char *name)
2523 {
2524 	mod_hash_val_t hv;
2525 	zone_t *zone = NULL;
2526 
2527 	ASSERT(MUTEX_HELD(&zonehash_lock));
2528 
2529 	if (mod_hash_find(zonehashbyname, (mod_hash_key_t)name, &hv) == 0)
2530 		zone = (zone_t *)hv;
2531 	return (zone);
2532 }
2533 
2534 /*
2535  * Public interface for looking up a zone by zoneid.  Only returns the zone if
2536  * it is fully initialized, and has not yet begun the zone_destroy() sequence.
2537  * Caller must call zone_rele() once it is done with the zone.
2538  *
2539  * The zone may begin the zone_destroy() sequence immediately after this
2540  * function returns, but may be safely used until zone_rele() is called.
2541  */
2542 zone_t *
2543 zone_find_by_id(zoneid_t zoneid)
2544 {
2545 	zone_t *zone;
2546 	zone_status_t status;
2547 
2548 	mutex_enter(&zonehash_lock);
2549 	if ((zone = zone_find_all_by_id(zoneid)) == NULL) {
2550 		mutex_exit(&zonehash_lock);
2551 		return (NULL);
2552 	}
2553 	status = zone_status_get(zone);
2554 	if (status < ZONE_IS_READY || status > ZONE_IS_DOWN) {
2555 		/*
2556 		 * For all practical purposes the zone doesn't exist.
2557 		 */
2558 		mutex_exit(&zonehash_lock);
2559 		return (NULL);
2560 	}
2561 	zone_hold(zone);
2562 	mutex_exit(&zonehash_lock);
2563 	return (zone);
2564 }
2565 
2566 /*
2567  * Similar to zone_find_by_id, but using zone label as the key.
2568  */
2569 zone_t *
2570 zone_find_by_label(const ts_label_t *label)
2571 {
2572 	zone_t *zone;
2573 	zone_status_t status;
2574 
2575 	mutex_enter(&zonehash_lock);
2576 	if ((zone = zone_find_all_by_label(label)) == NULL) {
2577 		mutex_exit(&zonehash_lock);
2578 		return (NULL);
2579 	}
2580 
2581 	status = zone_status_get(zone);
2582 	if (status > ZONE_IS_DOWN) {
2583 		/*
2584 		 * For all practical purposes the zone doesn't exist.
2585 		 */
2586 		mutex_exit(&zonehash_lock);
2587 		return (NULL);
2588 	}
2589 	zone_hold(zone);
2590 	mutex_exit(&zonehash_lock);
2591 	return (zone);
2592 }
2593 
2594 /*
2595  * Similar to zone_find_by_id, but using zone name as the key.
2596  */
2597 zone_t *
2598 zone_find_by_name(char *name)
2599 {
2600 	zone_t *zone;
2601 	zone_status_t status;
2602 
2603 	mutex_enter(&zonehash_lock);
2604 	if ((zone = zone_find_all_by_name(name)) == NULL) {
2605 		mutex_exit(&zonehash_lock);
2606 		return (NULL);
2607 	}
2608 	status = zone_status_get(zone);
2609 	if (status < ZONE_IS_READY || status > ZONE_IS_DOWN) {
2610 		/*
2611 		 * For all practical purposes the zone doesn't exist.
2612 		 */
2613 		mutex_exit(&zonehash_lock);
2614 		return (NULL);
2615 	}
2616 	zone_hold(zone);
2617 	mutex_exit(&zonehash_lock);
2618 	return (zone);
2619 }
2620 
2621 /*
2622  * Similar to zone_find_by_id(), using the path as a key.  For instance,
2623  * if there is a zone "foo" rooted at /foo/root, and the path argument
2624  * is "/foo/root/proc", it will return the held zone_t corresponding to
2625  * zone "foo".
2626  *
2627  * zone_find_by_path() always returns a non-NULL value, since at the
2628  * very least every path will be contained in the global zone.
2629  *
2630  * As with the other zone_find_by_*() functions, the caller is
2631  * responsible for zone_rele()ing the return value of this function.
2632  */
2633 zone_t *
2634 zone_find_by_path(const char *path)
2635 {
2636 	zone_t *zone;
2637 	zone_t *zret = NULL;
2638 	zone_status_t status;
2639 
2640 	if (path == NULL) {
2641 		/*
2642 		 * Call from rootconf().
2643 		 */
2644 		zone_hold(global_zone);
2645 		return (global_zone);
2646 	}
2647 	ASSERT(*path == '/');
2648 	mutex_enter(&zonehash_lock);
2649 	for (zone = list_head(&zone_active); zone != NULL;
2650 	    zone = list_next(&zone_active, zone)) {
2651 		if (ZONE_PATH_VISIBLE(path, zone))
2652 			zret = zone;
2653 	}
2654 	ASSERT(zret != NULL);
2655 	status = zone_status_get(zret);
2656 	if (status < ZONE_IS_READY || status > ZONE_IS_DOWN) {
2657 		/*
2658 		 * Zone practically doesn't exist.
2659 		 */
2660 		zret = global_zone;
2661 	}
2662 	zone_hold(zret);
2663 	mutex_exit(&zonehash_lock);
2664 	return (zret);
2665 }
2666 
2667 /*
2668  * Get the number of cpus visible to this zone.  The system-wide global
2669  * 'ncpus' is returned if pools are disabled, the caller is in the
2670  * global zone, or a NULL zone argument is passed in.
2671  */
2672 int
2673 zone_ncpus_get(zone_t *zone)
2674 {
2675 	int myncpus = zone == NULL ? 0 : zone->zone_ncpus;
2676 
2677 	return (myncpus != 0 ? myncpus : ncpus);
2678 }
2679 
2680 /*
2681  * Get the number of online cpus visible to this zone.  The system-wide
2682  * global 'ncpus_online' is returned if pools are disabled, the caller
2683  * is in the global zone, or a NULL zone argument is passed in.
2684  */
2685 int
2686 zone_ncpus_online_get(zone_t *zone)
2687 {
2688 	int myncpus_online = zone == NULL ? 0 : zone->zone_ncpus_online;
2689 
2690 	return (myncpus_online != 0 ? myncpus_online : ncpus_online);
2691 }
2692 
2693 /*
2694  * Return the pool to which the zone is currently bound.
2695  */
2696 pool_t *
2697 zone_pool_get(zone_t *zone)
2698 {
2699 	ASSERT(pool_lock_held());
2700 
2701 	return (zone->zone_pool);
2702 }
2703 
2704 /*
2705  * Set the zone's pool pointer and update the zone's visibility to match
2706  * the resources in the new pool.
2707  */
2708 void
2709 zone_pool_set(zone_t *zone, pool_t *pool)
2710 {
2711 	ASSERT(pool_lock_held());
2712 	ASSERT(MUTEX_HELD(&cpu_lock));
2713 
2714 	zone->zone_pool = pool;
2715 	zone_pset_set(zone, pool->pool_pset->pset_id);
2716 }
2717 
2718 /*
2719  * Return the cached value of the id of the processor set to which the
2720  * zone is currently bound.  The value will be ZONE_PS_INVAL if the pools
2721  * facility is disabled.
2722  */
2723 psetid_t
2724 zone_pset_get(zone_t *zone)
2725 {
2726 	ASSERT(MUTEX_HELD(&cpu_lock));
2727 
2728 	return (zone->zone_psetid);
2729 }
2730 
2731 /*
2732  * Set the cached value of the id of the processor set to which the zone
2733  * is currently bound.  Also update the zone's visibility to match the
2734  * resources in the new processor set.
2735  */
2736 void
2737 zone_pset_set(zone_t *zone, psetid_t newpsetid)
2738 {
2739 	psetid_t oldpsetid;
2740 
2741 	ASSERT(MUTEX_HELD(&cpu_lock));
2742 	oldpsetid = zone_pset_get(zone);
2743 
2744 	if (oldpsetid == newpsetid)
2745 		return;
2746 	/*
2747 	 * Global zone sees all.
2748 	 */
2749 	if (zone != global_zone) {
2750 		zone->zone_psetid = newpsetid;
2751 		if (newpsetid != ZONE_PS_INVAL)
2752 			pool_pset_visibility_add(newpsetid, zone);
2753 		if (oldpsetid != ZONE_PS_INVAL)
2754 			pool_pset_visibility_remove(oldpsetid, zone);
2755 	}
2756 	/*
2757 	 * Disabling pools, so we should start using the global values
2758 	 * for ncpus and ncpus_online.
2759 	 */
2760 	if (newpsetid == ZONE_PS_INVAL) {
2761 		zone->zone_ncpus = 0;
2762 		zone->zone_ncpus_online = 0;
2763 	}
2764 }
2765 
2766 /*
2767  * Walk the list of active zones and issue the provided callback for
2768  * each of them.
2769  *
2770  * Caller must not be holding any locks that may be acquired under
2771  * zonehash_lock.  See comment at the beginning of the file for a list of
2772  * common locks and their interactions with zones.
2773  */
2774 int
2775 zone_walk(int (*cb)(zone_t *, void *), void *data)
2776 {
2777 	zone_t *zone;
2778 	int ret = 0;
2779 	zone_status_t status;
2780 
2781 	mutex_enter(&zonehash_lock);
2782 	for (zone = list_head(&zone_active); zone != NULL;
2783 	    zone = list_next(&zone_active, zone)) {
2784 		/*
2785 		 * Skip zones that shouldn't be externally visible.
2786 		 */
2787 		status = zone_status_get(zone);
2788 		if (status < ZONE_IS_READY || status > ZONE_IS_DOWN)
2789 			continue;
2790 		/*
2791 		 * Bail immediately if any callback invocation returns a
2792 		 * non-zero value.
2793 		 */
2794 		ret = (*cb)(zone, data);
2795 		if (ret != 0)
2796 			break;
2797 	}
2798 	mutex_exit(&zonehash_lock);
2799 	return (ret);
2800 }
2801 
2802 static int
2803 zone_set_root(zone_t *zone, const char *upath)
2804 {
2805 	vnode_t *vp;
2806 	int trycount;
2807 	int error = 0;
2808 	char *path;
2809 	struct pathname upn, pn;
2810 	size_t pathlen;
2811 
2812 	if ((error = pn_get((char *)upath, UIO_USERSPACE, &upn)) != 0)
2813 		return (error);
2814 
2815 	pn_alloc(&pn);
2816 
2817 	/* prevent infinite loop */
2818 	trycount = 10;
2819 	for (;;) {
2820 		if (--trycount <= 0) {
2821 			error = ESTALE;
2822 			goto out;
2823 		}
2824 
2825 		if ((error = lookuppn(&upn, &pn, FOLLOW, NULLVPP, &vp)) == 0) {
2826 			/*
2827 			 * VOP_ACCESS() may cover 'vp' with a new
2828 			 * filesystem, if 'vp' is an autoFS vnode.
2829 			 * Get the new 'vp' if so.
2830 			 */
2831 			if ((error =
2832 			    VOP_ACCESS(vp, VEXEC, 0, CRED(), NULL)) == 0 &&
2833 			    (!vn_ismntpt(vp) ||
2834 			    (error = traverse(&vp)) == 0)) {
2835 				pathlen = pn.pn_pathlen + 2;
2836 				path = kmem_alloc(pathlen, KM_SLEEP);
2837 				(void) strncpy(path, pn.pn_path,
2838 				    pn.pn_pathlen + 1);
2839 				path[pathlen - 2] = '/';
2840 				path[pathlen - 1] = '\0';
2841 				pn_free(&pn);
2842 				pn_free(&upn);
2843 
2844 				/* Success! */
2845 				break;
2846 			}
2847 			VN_RELE(vp);
2848 		}
2849 		if (error != ESTALE)
2850 			goto out;
2851 	}
2852 
2853 	ASSERT(error == 0);
2854 	zone->zone_rootvp = vp;		/* we hold a reference to vp */
2855 	zone->zone_rootpath = path;
2856 	zone->zone_rootpathlen = pathlen;
2857 	if (pathlen > 5 && strcmp(path + pathlen - 5, "/lu/") == 0)
2858 		zone->zone_flags |= ZF_IS_SCRATCH;
2859 	return (0);
2860 
2861 out:
2862 	pn_free(&pn);
2863 	pn_free(&upn);
2864 	return (error);
2865 }
2866 
2867 #define	isalnum(c)	(((c) >= '0' && (c) <= '9') || \
2868 			((c) >= 'a' && (c) <= 'z') || \
2869 			((c) >= 'A' && (c) <= 'Z'))
2870 
2871 static int
2872 zone_set_name(zone_t *zone, const char *uname)
2873 {
2874 	char *kname = kmem_zalloc(ZONENAME_MAX, KM_SLEEP);
2875 	size_t len;
2876 	int i, err;
2877 
2878 	if ((err = copyinstr(uname, kname, ZONENAME_MAX, &len)) != 0) {
2879 		kmem_free(kname, ZONENAME_MAX);
2880 		return (err);	/* EFAULT or ENAMETOOLONG */
2881 	}
2882 
2883 	/* must be less than ZONENAME_MAX */
2884 	if (len == ZONENAME_MAX && kname[ZONENAME_MAX - 1] != '\0') {
2885 		kmem_free(kname, ZONENAME_MAX);
2886 		return (EINVAL);
2887 	}
2888 
2889 	/*
2890 	 * Name must start with an alphanumeric and must contain only
2891 	 * alphanumerics, '-', '_' and '.'.
2892 	 */
2893 	if (!isalnum(kname[0])) {
2894 		kmem_free(kname, ZONENAME_MAX);
2895 		return (EINVAL);
2896 	}
2897 	for (i = 1; i < len - 1; i++) {
2898 		if (!isalnum(kname[i]) && kname[i] != '-' && kname[i] != '_' &&
2899 		    kname[i] != '.') {
2900 			kmem_free(kname, ZONENAME_MAX);
2901 			return (EINVAL);
2902 		}
2903 	}
2904 
2905 	zone->zone_name = kname;
2906 	return (0);
2907 }
2908 
2909 /*
2910  * Gets the 32-bit hostid of the specified zone as an unsigned int.  If 'zonep'
2911  * is NULL or it points to a zone with no hostid emulation, then the machine's
2912  * hostid (i.e., the global zone's hostid) is returned.  This function returns
2913  * zero if neither the zone nor the host machine (global zone) have hostids.  It
2914  * returns HW_INVALID_HOSTID if the function attempts to return the machine's
2915  * hostid and the machine's hostid is invalid.
2916  */
2917 uint32_t
2918 zone_get_hostid(zone_t *zonep)
2919 {
2920 	unsigned long machine_hostid;
2921 
2922 	if (zonep == NULL || zonep->zone_hostid == HW_INVALID_HOSTID) {
2923 		if (ddi_strtoul(hw_serial, NULL, 10, &machine_hostid) != 0)
2924 			return (HW_INVALID_HOSTID);
2925 		return ((uint32_t)machine_hostid);
2926 	}
2927 	return (zonep->zone_hostid);
2928 }
2929 
2930 /*
2931  * Similar to thread_create(), but makes sure the thread is in the appropriate
2932  * zone's zsched process (curproc->p_zone->zone_zsched) before returning.
2933  */
2934 /*ARGSUSED*/
2935 kthread_t *
2936 zthread_create(
2937     caddr_t stk,
2938     size_t stksize,
2939     void (*proc)(),
2940     void *arg,
2941     size_t len,
2942     pri_t pri)
2943 {
2944 	kthread_t *t;
2945 	zone_t *zone = curproc->p_zone;
2946 	proc_t *pp = zone->zone_zsched;
2947 
2948 	zone_hold(zone);	/* Reference to be dropped when thread exits */
2949 
2950 	/*
2951 	 * No-one should be trying to create threads if the zone is shutting
2952 	 * down and there aren't any kernel threads around.  See comment
2953 	 * in zthread_exit().
2954 	 */
2955 	ASSERT(!(zone->zone_kthreads == NULL &&
2956 	    zone_status_get(zone) >= ZONE_IS_EMPTY));
2957 	/*
2958 	 * Create a thread, but don't let it run until we've finished setting
2959 	 * things up.
2960 	 */
2961 	t = thread_create(stk, stksize, proc, arg, len, pp, TS_STOPPED, pri);
2962 	ASSERT(t->t_forw == NULL);
2963 	mutex_enter(&zone_status_lock);
2964 	if (zone->zone_kthreads == NULL) {
2965 		t->t_forw = t->t_back = t;
2966 	} else {
2967 		kthread_t *tx = zone->zone_kthreads;
2968 
2969 		t->t_forw = tx;
2970 		t->t_back = tx->t_back;
2971 		tx->t_back->t_forw = t;
2972 		tx->t_back = t;
2973 	}
2974 	zone->zone_kthreads = t;
2975 	mutex_exit(&zone_status_lock);
2976 
2977 	mutex_enter(&pp->p_lock);
2978 	t->t_proc_flag |= TP_ZTHREAD;
2979 	project_rele(t->t_proj);
2980 	t->t_proj = project_hold(pp->p_task->tk_proj);
2981 
2982 	/*
2983 	 * Setup complete, let it run.
2984 	 */
2985 	thread_lock(t);
2986 	t->t_schedflag |= TS_ALLSTART;
2987 	setrun_locked(t);
2988 	thread_unlock(t);
2989 
2990 	mutex_exit(&pp->p_lock);
2991 
2992 	return (t);
2993 }
2994 
2995 /*
2996  * Similar to thread_exit().  Must be called by threads created via
2997  * zthread_exit().
2998  */
2999 void
3000 zthread_exit(void)
3001 {
3002 	kthread_t *t = curthread;
3003 	proc_t *pp = curproc;
3004 	zone_t *zone = pp->p_zone;
3005 
3006 	mutex_enter(&zone_status_lock);
3007 
3008 	/*
3009 	 * Reparent to p0
3010 	 */
3011 	kpreempt_disable();
3012 	mutex_enter(&pp->p_lock);
3013 	t->t_proc_flag &= ~TP_ZTHREAD;
3014 	t->t_procp = &p0;
3015 	hat_thread_exit(t);
3016 	mutex_exit(&pp->p_lock);
3017 	kpreempt_enable();
3018 
3019 	if (t->t_back == t) {
3020 		ASSERT(t->t_forw == t);
3021 		/*
3022 		 * If the zone is empty, once the thread count
3023 		 * goes to zero no further kernel threads can be
3024 		 * created.  This is because if the creator is a process
3025 		 * in the zone, then it must have exited before the zone
3026 		 * state could be set to ZONE_IS_EMPTY.
3027 		 * Otherwise, if the creator is a kernel thread in the
3028 		 * zone, the thread count is non-zero.
3029 		 *
3030 		 * This really means that non-zone kernel threads should
3031 		 * not create zone kernel threads.
3032 		 */
3033 		zone->zone_kthreads = NULL;
3034 		if (zone_status_get(zone) == ZONE_IS_EMPTY) {
3035 			zone_status_set(zone, ZONE_IS_DOWN);
3036 			/*
3037 			 * Remove any CPU caps on this zone.
3038 			 */
3039 			cpucaps_zone_remove(zone);
3040 		}
3041 	} else {
3042 		t->t_forw->t_back = t->t_back;
3043 		t->t_back->t_forw = t->t_forw;
3044 		if (zone->zone_kthreads == t)
3045 			zone->zone_kthreads = t->t_forw;
3046 	}
3047 	mutex_exit(&zone_status_lock);
3048 	zone_rele(zone);
3049 	thread_exit();
3050 	/* NOTREACHED */
3051 }
3052 
3053 static void
3054 zone_chdir(vnode_t *vp, vnode_t **vpp, proc_t *pp)
3055 {
3056 	vnode_t *oldvp;
3057 
3058 	/* we're going to hold a reference here to the directory */
3059 	VN_HOLD(vp);
3060 
3061 	if (audit_active)	/* update abs cwd/root path see c2audit.c */
3062 		audit_chdirec(vp, vpp);
3063 
3064 	mutex_enter(&pp->p_lock);
3065 	oldvp = *vpp;
3066 	*vpp = vp;
3067 	mutex_exit(&pp->p_lock);
3068 	if (oldvp != NULL)
3069 		VN_RELE(oldvp);
3070 }
3071 
3072 /*
3073  * Convert an rctl value represented by an nvlist_t into an rctl_val_t.
3074  */
3075 static int
3076 nvlist2rctlval(nvlist_t *nvl, rctl_val_t *rv)
3077 {
3078 	nvpair_t *nvp = NULL;
3079 	boolean_t priv_set = B_FALSE;
3080 	boolean_t limit_set = B_FALSE;
3081 	boolean_t action_set = B_FALSE;
3082 
3083 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
3084 		const char *name;
3085 		uint64_t ui64;
3086 
3087 		name = nvpair_name(nvp);
3088 		if (nvpair_type(nvp) != DATA_TYPE_UINT64)
3089 			return (EINVAL);
3090 		(void) nvpair_value_uint64(nvp, &ui64);
3091 		if (strcmp(name, "privilege") == 0) {
3092 			/*
3093 			 * Currently only privileged values are allowed, but
3094 			 * this may change in the future.
3095 			 */
3096 			if (ui64 != RCPRIV_PRIVILEGED)
3097 				return (EINVAL);
3098 			rv->rcv_privilege = ui64;
3099 			priv_set = B_TRUE;
3100 		} else if (strcmp(name, "limit") == 0) {
3101 			rv->rcv_value = ui64;
3102 			limit_set = B_TRUE;
3103 		} else if (strcmp(name, "action") == 0) {
3104 			if (ui64 != RCTL_LOCAL_NOACTION &&
3105 			    ui64 != RCTL_LOCAL_DENY)
3106 				return (EINVAL);
3107 			rv->rcv_flagaction = ui64;
3108 			action_set = B_TRUE;
3109 		} else {
3110 			return (EINVAL);
3111 		}
3112 	}
3113 
3114 	if (!(priv_set && limit_set && action_set))
3115 		return (EINVAL);
3116 	rv->rcv_action_signal = 0;
3117 	rv->rcv_action_recipient = NULL;
3118 	rv->rcv_action_recip_pid = -1;
3119 	rv->rcv_firing_time = 0;
3120 
3121 	return (0);
3122 }
3123 
3124 /*
3125  * Non-global zone version of start_init.
3126  */
3127 void
3128 zone_start_init(void)
3129 {
3130 	proc_t *p = ttoproc(curthread);
3131 	zone_t *z = p->p_zone;
3132 
3133 	ASSERT(!INGLOBALZONE(curproc));
3134 
3135 	/*
3136 	 * For all purposes (ZONE_ATTR_INITPID and restart_init),
3137 	 * storing just the pid of init is sufficient.
3138 	 */
3139 	z->zone_proc_initpid = p->p_pid;
3140 
3141 	/*
3142 	 * We maintain zone_boot_err so that we can return the cause of the
3143 	 * failure back to the caller of the zone_boot syscall.
3144 	 */
3145 	p->p_zone->zone_boot_err = start_init_common();
3146 
3147 	/*
3148 	 * We will prevent booting zones from becoming running zones if the
3149 	 * global zone is shutting down.
3150 	 */
3151 	mutex_enter(&zone_status_lock);
3152 	if (z->zone_boot_err != 0 || zone_status_get(global_zone) >=
3153 	    ZONE_IS_SHUTTING_DOWN) {
3154 		/*
3155 		 * Make sure we are still in the booting state-- we could have
3156 		 * raced and already be shutting down, or even further along.
3157 		 */
3158 		if (zone_status_get(z) == ZONE_IS_BOOTING) {
3159 			zone_status_set(z, ZONE_IS_SHUTTING_DOWN);
3160 		}
3161 		mutex_exit(&zone_status_lock);
3162 		/* It's gone bad, dispose of the process */
3163 		if (proc_exit(CLD_EXITED, z->zone_boot_err) != 0) {
3164 			mutex_enter(&p->p_lock);
3165 			ASSERT(p->p_flag & SEXITLWPS);
3166 			lwp_exit();
3167 		}
3168 	} else {
3169 		if (zone_status_get(z) == ZONE_IS_BOOTING)
3170 			zone_status_set(z, ZONE_IS_RUNNING);
3171 		mutex_exit(&zone_status_lock);
3172 		/* cause the process to return to userland. */
3173 		lwp_rtt();
3174 	}
3175 }
3176 
3177 struct zsched_arg {
3178 	zone_t *zone;
3179 	nvlist_t *nvlist;
3180 };
3181 
3182 /*
3183  * Per-zone "sched" workalike.  The similarity to "sched" doesn't have
3184  * anything to do with scheduling, but rather with the fact that
3185  * per-zone kernel threads are parented to zsched, just like regular
3186  * kernel threads are parented to sched (p0).
3187  *
3188  * zsched is also responsible for launching init for the zone.
3189  */
3190 static void
3191 zsched(void *arg)
3192 {
3193 	struct zsched_arg *za = arg;
3194 	proc_t *pp = curproc;
3195 	proc_t *initp = proc_init;
3196 	zone_t *zone = za->zone;
3197 	cred_t *cr, *oldcred;
3198 	rctl_set_t *set;
3199 	rctl_alloc_gp_t *gp;
3200 	contract_t *ct = NULL;
3201 	task_t *tk, *oldtk;
3202 	rctl_entity_p_t e;
3203 	kproject_t *pj;
3204 
3205 	nvlist_t *nvl = za->nvlist;
3206 	nvpair_t *nvp = NULL;
3207 
3208 	bcopy("zsched", PTOU(pp)->u_psargs, sizeof ("zsched"));
3209 	bcopy("zsched", PTOU(pp)->u_comm, sizeof ("zsched"));
3210 	PTOU(pp)->u_argc = 0;
3211 	PTOU(pp)->u_argv = NULL;
3212 	PTOU(pp)->u_envp = NULL;
3213 	closeall(P_FINFO(pp));
3214 
3215 	/*
3216 	 * We are this zone's "zsched" process.  As the zone isn't generally
3217 	 * visible yet we don't need to grab any locks before initializing its
3218 	 * zone_proc pointer.
3219 	 */
3220 	zone_hold(zone);  /* this hold is released by zone_destroy() */
3221 	zone->zone_zsched = pp;
3222 	mutex_enter(&pp->p_lock);
3223 	pp->p_zone = zone;
3224 	mutex_exit(&pp->p_lock);
3225 
3226 	/*
3227 	 * Disassociate process from its 'parent'; parent ourselves to init
3228 	 * (pid 1) and change other values as needed.
3229 	 */
3230 	sess_create();
3231 
3232 	mutex_enter(&pidlock);
3233 	proc_detach(pp);
3234 	pp->p_ppid = 1;
3235 	pp->p_flag |= SZONETOP;
3236 	pp->p_ancpid = 1;
3237 	pp->p_parent = initp;
3238 	pp->p_psibling = NULL;
3239 	if (initp->p_child)
3240 		initp->p_child->p_psibling = pp;
3241 	pp->p_sibling = initp->p_child;
3242 	initp->p_child = pp;
3243 
3244 	/* Decrement what newproc() incremented. */
3245 	upcount_dec(crgetruid(CRED()), GLOBAL_ZONEID);
3246 	/*
3247 	 * Our credentials are about to become kcred-like, so we don't care
3248 	 * about the caller's ruid.
3249 	 */
3250 	upcount_inc(crgetruid(kcred), zone->zone_id);
3251 	mutex_exit(&pidlock);
3252 
3253 	/*
3254 	 * getting out of global zone, so decrement lwp counts
3255 	 */
3256 	pj = pp->p_task->tk_proj;
3257 	mutex_enter(&global_zone->zone_nlwps_lock);
3258 	pj->kpj_nlwps -= pp->p_lwpcnt;
3259 	global_zone->zone_nlwps -= pp->p_lwpcnt;
3260 	mutex_exit(&global_zone->zone_nlwps_lock);
3261 
3262 	/*
3263 	 * Decrement locked memory counts on old zone and project.
3264 	 */
3265 	mutex_enter(&global_zone->zone_mem_lock);
3266 	global_zone->zone_locked_mem -= pp->p_locked_mem;
3267 	pj->kpj_data.kpd_locked_mem -= pp->p_locked_mem;
3268 	mutex_exit(&global_zone->zone_mem_lock);
3269 
3270 	/*
3271 	 * Create and join a new task in project '0' of this zone.
3272 	 *
3273 	 * We don't need to call holdlwps() since we know we're the only lwp in
3274 	 * this process.
3275 	 *
3276 	 * task_join() returns with p_lock held.
3277 	 */
3278 	tk = task_create(0, zone);
3279 	mutex_enter(&cpu_lock);
3280 	oldtk = task_join(tk, 0);
3281 
3282 	pj = pp->p_task->tk_proj;
3283 
3284 	mutex_enter(&zone->zone_mem_lock);
3285 	zone->zone_locked_mem += pp->p_locked_mem;
3286 	pj->kpj_data.kpd_locked_mem += pp->p_locked_mem;
3287 	mutex_exit(&zone->zone_mem_lock);
3288 
3289 	/*
3290 	 * add lwp counts to zsched's zone, and increment project's task count
3291 	 * due to the task created in the above tasksys_settaskid
3292 	 */
3293 
3294 	mutex_enter(&zone->zone_nlwps_lock);
3295 	pj->kpj_nlwps += pp->p_lwpcnt;
3296 	pj->kpj_ntasks += 1;
3297 	zone->zone_nlwps += pp->p_lwpcnt;
3298 	mutex_exit(&zone->zone_nlwps_lock);
3299 
3300 	mutex_exit(&curproc->p_lock);
3301 	mutex_exit(&cpu_lock);
3302 	task_rele(oldtk);
3303 
3304 	/*
3305 	 * The process was created by a process in the global zone, hence the
3306 	 * credentials are wrong.  We might as well have kcred-ish credentials.
3307 	 */
3308 	cr = zone->zone_kcred;
3309 	crhold(cr);
3310 	mutex_enter(&pp->p_crlock);
3311 	oldcred = pp->p_cred;
3312 	pp->p_cred = cr;
3313 	mutex_exit(&pp->p_crlock);
3314 	crfree(oldcred);
3315 
3316 	/*
3317 	 * Hold credentials again (for thread)
3318 	 */
3319 	crhold(cr);
3320 
3321 	/*
3322 	 * p_lwpcnt can't change since this is a kernel process.
3323 	 */
3324 	crset(pp, cr);
3325 
3326 	/*
3327 	 * Chroot
3328 	 */
3329 	zone_chdir(zone->zone_rootvp, &PTOU(pp)->u_cdir, pp);
3330 	zone_chdir(zone->zone_rootvp, &PTOU(pp)->u_rdir, pp);
3331 
3332 	/*
3333 	 * Initialize zone's rctl set.
3334 	 */
3335 	set = rctl_set_create();
3336 	gp = rctl_set_init_prealloc(RCENTITY_ZONE);
3337 	mutex_enter(&pp->p_lock);
3338 	e.rcep_p.zone = zone;
3339 	e.rcep_t = RCENTITY_ZONE;
3340 	zone->zone_rctls = rctl_set_init(RCENTITY_ZONE, pp, &e, set, gp);
3341 	mutex_exit(&pp->p_lock);
3342 	rctl_prealloc_destroy(gp);
3343 
3344 	/*
3345 	 * Apply the rctls passed in to zone_create().  This is basically a list
3346 	 * assignment: all of the old values are removed and the new ones
3347 	 * inserted.  That is, if an empty list is passed in, all values are
3348 	 * removed.
3349 	 */
3350 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
3351 		rctl_dict_entry_t *rde;
3352 		rctl_hndl_t hndl;
3353 		char *name;
3354 		nvlist_t **nvlarray;
3355 		uint_t i, nelem;
3356 		int error;	/* For ASSERT()s */
3357 
3358 		name = nvpair_name(nvp);
3359 		hndl = rctl_hndl_lookup(name);
3360 		ASSERT(hndl != -1);
3361 		rde = rctl_dict_lookup_hndl(hndl);
3362 		ASSERT(rde != NULL);
3363 
3364 		for (; /* ever */; ) {
3365 			rctl_val_t oval;
3366 
3367 			mutex_enter(&pp->p_lock);
3368 			error = rctl_local_get(hndl, NULL, &oval, pp);
3369 			mutex_exit(&pp->p_lock);
3370 			ASSERT(error == 0);	/* Can't fail for RCTL_FIRST */
3371 			ASSERT(oval.rcv_privilege != RCPRIV_BASIC);
3372 			if (oval.rcv_privilege == RCPRIV_SYSTEM)
3373 				break;
3374 			mutex_enter(&pp->p_lock);
3375 			error = rctl_local_delete(hndl, &oval, pp);
3376 			mutex_exit(&pp->p_lock);
3377 			ASSERT(error == 0);
3378 		}
3379 		error = nvpair_value_nvlist_array(nvp, &nvlarray, &nelem);
3380 		ASSERT(error == 0);
3381 		for (i = 0; i < nelem; i++) {
3382 			rctl_val_t *nvalp;
3383 
3384 			nvalp = kmem_cache_alloc(rctl_val_cache, KM_SLEEP);
3385 			error = nvlist2rctlval(nvlarray[i], nvalp);
3386 			ASSERT(error == 0);
3387 			/*
3388 			 * rctl_local_insert can fail if the value being
3389 			 * inserted is a duplicate; this is OK.
3390 			 */
3391 			mutex_enter(&pp->p_lock);
3392 			if (rctl_local_insert(hndl, nvalp, pp) != 0)
3393 				kmem_cache_free(rctl_val_cache, nvalp);
3394 			mutex_exit(&pp->p_lock);
3395 		}
3396 	}
3397 	/*
3398 	 * Tell the world that we're done setting up.
3399 	 *
3400 	 * At this point we want to set the zone status to ZONE_IS_INITIALIZED
3401 	 * and atomically set the zone's processor set visibility.  Once
3402 	 * we drop pool_lock() this zone will automatically get updated
3403 	 * to reflect any future changes to the pools configuration.
3404 	 *
3405 	 * Note that after we drop the locks below (zonehash_lock in
3406 	 * particular) other operations such as a zone_getattr call can
3407 	 * now proceed and observe the zone. That is the reason for doing a
3408 	 * state transition to the INITIALIZED state.
3409 	 */
3410 	pool_lock();
3411 	mutex_enter(&cpu_lock);
3412 	mutex_enter(&zonehash_lock);
3413 	zone_uniqid(zone);
3414 	zone_zsd_configure(zone);
3415 	if (pool_state == POOL_ENABLED)
3416 		zone_pset_set(zone, pool_default->pool_pset->pset_id);
3417 	mutex_enter(&zone_status_lock);
3418 	ASSERT(zone_status_get(zone) == ZONE_IS_UNINITIALIZED);
3419 	zone_status_set(zone, ZONE_IS_INITIALIZED);
3420 	mutex_exit(&zone_status_lock);
3421 	mutex_exit(&zonehash_lock);
3422 	mutex_exit(&cpu_lock);
3423 	pool_unlock();
3424 
3425 	/* Now call the create callback for this key */
3426 	zsd_apply_all_keys(zsd_apply_create, zone);
3427 
3428 	/* The callbacks are complete. Mark ZONE_IS_READY */
3429 	mutex_enter(&zone_status_lock);
3430 	ASSERT(zone_status_get(zone) == ZONE_IS_INITIALIZED);
3431 	zone_status_set(zone, ZONE_IS_READY);
3432 	mutex_exit(&zone_status_lock);
3433 
3434 	/*
3435 	 * Once we see the zone transition to the ZONE_IS_BOOTING state,
3436 	 * we launch init, and set the state to running.
3437 	 */
3438 	zone_status_wait_cpr(zone, ZONE_IS_BOOTING, "zsched");
3439 
3440 	if (zone_status_get(zone) == ZONE_IS_BOOTING) {
3441 		id_t cid;
3442 
3443 		/*
3444 		 * Ok, this is a little complicated.  We need to grab the
3445 		 * zone's pool's scheduling class ID; note that by now, we
3446 		 * are already bound to a pool if we need to be (zoneadmd
3447 		 * will have done that to us while we're in the READY
3448 		 * state).  *But* the scheduling class for the zone's 'init'
3449 		 * must be explicitly passed to newproc, which doesn't
3450 		 * respect pool bindings.
3451 		 *
3452 		 * We hold the pool_lock across the call to newproc() to
3453 		 * close the obvious race: the pool's scheduling class
3454 		 * could change before we manage to create the LWP with
3455 		 * classid 'cid'.
3456 		 */
3457 		pool_lock();
3458 		if (zone->zone_defaultcid > 0)
3459 			cid = zone->zone_defaultcid;
3460 		else
3461 			cid = pool_get_class(zone->zone_pool);
3462 		if (cid == -1)
3463 			cid = defaultcid;
3464 
3465 		/*
3466 		 * If this fails, zone_boot will ultimately fail.  The
3467 		 * state of the zone will be set to SHUTTING_DOWN-- userland
3468 		 * will have to tear down the zone, and fail, or try again.
3469 		 */
3470 		if ((zone->zone_boot_err = newproc(zone_start_init, NULL, cid,
3471 		    minclsyspri - 1, &ct)) != 0) {
3472 			mutex_enter(&zone_status_lock);
3473 			zone_status_set(zone, ZONE_IS_SHUTTING_DOWN);
3474 			mutex_exit(&zone_status_lock);
3475 		}
3476 		pool_unlock();
3477 	}
3478 
3479 	/*
3480 	 * Wait for zone_destroy() to be called.  This is what we spend
3481 	 * most of our life doing.
3482 	 */
3483 	zone_status_wait_cpr(zone, ZONE_IS_DYING, "zsched");
3484 
3485 	if (ct)
3486 		/*
3487 		 * At this point the process contract should be empty.
3488 		 * (Though if it isn't, it's not the end of the world.)
3489 		 */
3490 		VERIFY(contract_abandon(ct, curproc, B_TRUE) == 0);
3491 
3492 	/*
3493 	 * Allow kcred to be freed when all referring processes
3494 	 * (including this one) go away.  We can't just do this in
3495 	 * zone_free because we need to wait for the zone_cred_ref to
3496 	 * drop to 0 before calling zone_free, and the existence of
3497 	 * zone_kcred will prevent that.  Thus, we call crfree here to
3498 	 * balance the crdup in zone_create.  The crhold calls earlier
3499 	 * in zsched will be dropped when the thread and process exit.
3500 	 */
3501 	crfree(zone->zone_kcred);
3502 	zone->zone_kcred = NULL;
3503 
3504 	exit(CLD_EXITED, 0);
3505 }
3506 
3507 /*
3508  * Helper function to determine if there are any submounts of the
3509  * provided path.  Used to make sure the zone doesn't "inherit" any
3510  * mounts from before it is created.
3511  */
3512 static uint_t
3513 zone_mount_count(const char *rootpath)
3514 {
3515 	vfs_t *vfsp;
3516 	uint_t count = 0;
3517 	size_t rootpathlen = strlen(rootpath);
3518 
3519 	/*
3520 	 * Holding zonehash_lock prevents race conditions with
3521 	 * vfs_list_add()/vfs_list_remove() since we serialize with
3522 	 * zone_find_by_path().
3523 	 */
3524 	ASSERT(MUTEX_HELD(&zonehash_lock));
3525 	/*
3526 	 * The rootpath must end with a '/'
3527 	 */
3528 	ASSERT(rootpath[rootpathlen - 1] == '/');
3529 
3530 	/*
3531 	 * This intentionally does not count the rootpath itself if that
3532 	 * happens to be a mount point.
3533 	 */
3534 	vfs_list_read_lock();
3535 	vfsp = rootvfs;
3536 	do {
3537 		if (strncmp(rootpath, refstr_value(vfsp->vfs_mntpt),
3538 		    rootpathlen) == 0)
3539 			count++;
3540 		vfsp = vfsp->vfs_next;
3541 	} while (vfsp != rootvfs);
3542 	vfs_list_unlock();
3543 	return (count);
3544 }
3545 
3546 /*
3547  * Helper function to make sure that a zone created on 'rootpath'
3548  * wouldn't end up containing other zones' rootpaths.
3549  */
3550 static boolean_t
3551 zone_is_nested(const char *rootpath)
3552 {
3553 	zone_t *zone;
3554 	size_t rootpathlen = strlen(rootpath);
3555 	size_t len;
3556 
3557 	ASSERT(MUTEX_HELD(&zonehash_lock));
3558 
3559 	/*
3560 	 * zone_set_root() appended '/' and '\0' at the end of rootpath
3561 	 */
3562 	if ((rootpathlen <= 3) && (rootpath[0] == '/') &&
3563 	    (rootpath[1] == '/') && (rootpath[2] == '\0'))
3564 		return (B_TRUE);
3565 
3566 	for (zone = list_head(&zone_active); zone != NULL;
3567 	    zone = list_next(&zone_active, zone)) {
3568 		if (zone == global_zone)
3569 			continue;
3570 		len = strlen(zone->zone_rootpath);
3571 		if (strncmp(rootpath, zone->zone_rootpath,
3572 		    MIN(rootpathlen, len)) == 0)
3573 			return (B_TRUE);
3574 	}
3575 	return (B_FALSE);
3576 }
3577 
3578 static int
3579 zone_set_privset(zone_t *zone, const priv_set_t *zone_privs,
3580     size_t zone_privssz)
3581 {
3582 	priv_set_t *privs = kmem_alloc(sizeof (priv_set_t), KM_SLEEP);
3583 
3584 	if (zone_privssz < sizeof (priv_set_t))
3585 		return (set_errno(ENOMEM));
3586 
3587 	if (copyin(zone_privs, privs, sizeof (priv_set_t))) {
3588 		kmem_free(privs, sizeof (priv_set_t));
3589 		return (EFAULT);
3590 	}
3591 
3592 	zone->zone_privset = privs;
3593 	return (0);
3594 }
3595 
3596 /*
3597  * We make creative use of nvlists to pass in rctls from userland.  The list is
3598  * a list of the following structures:
3599  *
3600  * (name = rctl_name, value = nvpair_list_array)
3601  *
3602  * Where each element of the nvpair_list_array is of the form:
3603  *
3604  * [(name = "privilege", value = RCPRIV_PRIVILEGED),
3605  * 	(name = "limit", value = uint64_t),
3606  * 	(name = "action", value = (RCTL_LOCAL_NOACTION || RCTL_LOCAL_DENY))]
3607  */
3608 static int
3609 parse_rctls(caddr_t ubuf, size_t buflen, nvlist_t **nvlp)
3610 {
3611 	nvpair_t *nvp = NULL;
3612 	nvlist_t *nvl = NULL;
3613 	char *kbuf;
3614 	int error;
3615 	rctl_val_t rv;
3616 
3617 	*nvlp = NULL;
3618 
3619 	if (buflen == 0)
3620 		return (0);
3621 
3622 	if ((kbuf = kmem_alloc(buflen, KM_NOSLEEP)) == NULL)
3623 		return (ENOMEM);
3624 	if (copyin(ubuf, kbuf, buflen)) {
3625 		error = EFAULT;
3626 		goto out;
3627 	}
3628 	if (nvlist_unpack(kbuf, buflen, &nvl, KM_SLEEP) != 0) {
3629 		/*
3630 		 * nvl may have been allocated/free'd, but the value set to
3631 		 * non-NULL, so we reset it here.
3632 		 */
3633 		nvl = NULL;
3634 		error = EINVAL;
3635 		goto out;
3636 	}
3637 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
3638 		rctl_dict_entry_t *rde;
3639 		rctl_hndl_t hndl;
3640 		nvlist_t **nvlarray;
3641 		uint_t i, nelem;
3642 		char *name;
3643 
3644 		error = EINVAL;
3645 		name = nvpair_name(nvp);
3646 		if (strncmp(nvpair_name(nvp), "zone.", sizeof ("zone.") - 1)
3647 		    != 0 || nvpair_type(nvp) != DATA_TYPE_NVLIST_ARRAY) {
3648 			goto out;
3649 		}
3650 		if ((hndl = rctl_hndl_lookup(name)) == -1) {
3651 			goto out;
3652 		}
3653 		rde = rctl_dict_lookup_hndl(hndl);
3654 		error = nvpair_value_nvlist_array(nvp, &nvlarray, &nelem);
3655 		ASSERT(error == 0);
3656 		for (i = 0; i < nelem; i++) {
3657 			if (error = nvlist2rctlval(nvlarray[i], &rv))
3658 				goto out;
3659 		}
3660 		if (rctl_invalid_value(rde, &rv)) {
3661 			error = EINVAL;
3662 			goto out;
3663 		}
3664 	}
3665 	error = 0;
3666 	*nvlp = nvl;
3667 out:
3668 	kmem_free(kbuf, buflen);
3669 	if (error && nvl != NULL)
3670 		nvlist_free(nvl);
3671 	return (error);
3672 }
3673 
3674 int
3675 zone_create_error(int er_error, int er_ext, int *er_out) {
3676 	if (er_out != NULL) {
3677 		if (copyout(&er_ext, er_out, sizeof (int))) {
3678 			return (set_errno(EFAULT));
3679 		}
3680 	}
3681 	return (set_errno(er_error));
3682 }
3683 
3684 static int
3685 zone_set_label(zone_t *zone, const bslabel_t *lab, uint32_t doi)
3686 {
3687 	ts_label_t *tsl;
3688 	bslabel_t blab;
3689 
3690 	/* Get label from user */
3691 	if (copyin(lab, &blab, sizeof (blab)) != 0)
3692 		return (EFAULT);
3693 	tsl = labelalloc(&blab, doi, KM_NOSLEEP);
3694 	if (tsl == NULL)
3695 		return (ENOMEM);
3696 
3697 	zone->zone_slabel = tsl;
3698 	return (0);
3699 }
3700 
3701 /*
3702  * Parses a comma-separated list of ZFS datasets into a per-zone dictionary.
3703  */
3704 static int
3705 parse_zfs(zone_t *zone, caddr_t ubuf, size_t buflen)
3706 {
3707 	char *kbuf;
3708 	char *dataset, *next;
3709 	zone_dataset_t *zd;
3710 	size_t len;
3711 
3712 	if (ubuf == NULL || buflen == 0)
3713 		return (0);
3714 
3715 	if ((kbuf = kmem_alloc(buflen, KM_NOSLEEP)) == NULL)
3716 		return (ENOMEM);
3717 
3718 	if (copyin(ubuf, kbuf, buflen) != 0) {
3719 		kmem_free(kbuf, buflen);
3720 		return (EFAULT);
3721 	}
3722 
3723 	dataset = next = kbuf;
3724 	for (;;) {
3725 		zd = kmem_alloc(sizeof (zone_dataset_t), KM_SLEEP);
3726 
3727 		next = strchr(dataset, ',');
3728 
3729 		if (next == NULL)
3730 			len = strlen(dataset);
3731 		else
3732 			len = next - dataset;
3733 
3734 		zd->zd_dataset = kmem_alloc(len + 1, KM_SLEEP);
3735 		bcopy(dataset, zd->zd_dataset, len);
3736 		zd->zd_dataset[len] = '\0';
3737 
3738 		list_insert_head(&zone->zone_datasets, zd);
3739 
3740 		if (next == NULL)
3741 			break;
3742 
3743 		dataset = next + 1;
3744 	}
3745 
3746 	kmem_free(kbuf, buflen);
3747 	return (0);
3748 }
3749 
3750 /*
3751  * System call to create/initialize a new zone named 'zone_name', rooted
3752  * at 'zone_root', with a zone-wide privilege limit set of 'zone_privs',
3753  * and initialized with the zone-wide rctls described in 'rctlbuf', and
3754  * with labeling set by 'match', 'doi', and 'label'.
3755  *
3756  * If extended error is non-null, we may use it to return more detailed
3757  * error information.
3758  */
3759 static zoneid_t
3760 zone_create(const char *zone_name, const char *zone_root,
3761     const priv_set_t *zone_privs, size_t zone_privssz,
3762     caddr_t rctlbuf, size_t rctlbufsz,
3763     caddr_t zfsbuf, size_t zfsbufsz, int *extended_error,
3764     int match, uint32_t doi, const bslabel_t *label,
3765     int flags)
3766 {
3767 	struct zsched_arg zarg;
3768 	nvlist_t *rctls = NULL;
3769 	proc_t *pp = curproc;
3770 	zone_t *zone, *ztmp;
3771 	zoneid_t zoneid;
3772 	int error;
3773 	int error2 = 0;
3774 	char *str;
3775 	cred_t *zkcr;
3776 	boolean_t insert_label_hash;
3777 
3778 	if (secpolicy_zone_config(CRED()) != 0)
3779 		return (set_errno(EPERM));
3780 
3781 	/* can't boot zone from within chroot environment */
3782 	if (PTOU(pp)->u_rdir != NULL && PTOU(pp)->u_rdir != rootdir)
3783 		return (zone_create_error(ENOTSUP, ZE_CHROOTED,
3784 		    extended_error));
3785 
3786 	zone = kmem_zalloc(sizeof (zone_t), KM_SLEEP);
3787 	zoneid = zone->zone_id = id_alloc(zoneid_space);
3788 	zone->zone_status = ZONE_IS_UNINITIALIZED;
3789 	zone->zone_pool = pool_default;
3790 	zone->zone_pool_mod = gethrtime();
3791 	zone->zone_psetid = ZONE_PS_INVAL;
3792 	zone->zone_ncpus = 0;
3793 	zone->zone_ncpus_online = 0;
3794 	zone->zone_restart_init = B_TRUE;
3795 	zone->zone_brand = &native_brand;
3796 	zone->zone_initname = NULL;
3797 	mutex_init(&zone->zone_lock, NULL, MUTEX_DEFAULT, NULL);
3798 	mutex_init(&zone->zone_nlwps_lock, NULL, MUTEX_DEFAULT, NULL);
3799 	mutex_init(&zone->zone_mem_lock, NULL, MUTEX_DEFAULT, NULL);
3800 	cv_init(&zone->zone_cv, NULL, CV_DEFAULT, NULL);
3801 	list_create(&zone->zone_zsd, sizeof (struct zsd_entry),
3802 	    offsetof(struct zsd_entry, zsd_linkage));
3803 	list_create(&zone->zone_datasets, sizeof (zone_dataset_t),
3804 	    offsetof(zone_dataset_t, zd_linkage));
3805 	list_create(&zone->zone_dl_list, sizeof (zone_dl_t),
3806 	    offsetof(zone_dl_t, zdl_linkage));
3807 	rw_init(&zone->zone_mlps.mlpl_rwlock, NULL, RW_DEFAULT, NULL);
3808 
3809 	if (flags & ZCF_NET_EXCL) {
3810 		zone->zone_flags |= ZF_NET_EXCL;
3811 	}
3812 
3813 	if ((error = zone_set_name(zone, zone_name)) != 0) {
3814 		zone_free(zone);
3815 		return (zone_create_error(error, 0, extended_error));
3816 	}
3817 
3818 	if ((error = zone_set_root(zone, zone_root)) != 0) {
3819 		zone_free(zone);
3820 		return (zone_create_error(error, 0, extended_error));
3821 	}
3822 	if ((error = zone_set_privset(zone, zone_privs, zone_privssz)) != 0) {
3823 		zone_free(zone);
3824 		return (zone_create_error(error, 0, extended_error));
3825 	}
3826 
3827 	/* initialize node name to be the same as zone name */
3828 	zone->zone_nodename = kmem_alloc(_SYS_NMLN, KM_SLEEP);
3829 	(void) strncpy(zone->zone_nodename, zone->zone_name, _SYS_NMLN);
3830 	zone->zone_nodename[_SYS_NMLN - 1] = '\0';
3831 
3832 	zone->zone_domain = kmem_alloc(_SYS_NMLN, KM_SLEEP);
3833 	zone->zone_domain[0] = '\0';
3834 	zone->zone_hostid = HW_INVALID_HOSTID;
3835 	zone->zone_shares = 1;
3836 	zone->zone_shmmax = 0;
3837 	zone->zone_ipc.ipcq_shmmni = 0;
3838 	zone->zone_ipc.ipcq_semmni = 0;
3839 	zone->zone_ipc.ipcq_msgmni = 0;
3840 	zone->zone_bootargs = NULL;
3841 	zone->zone_initname =
3842 	    kmem_alloc(strlen(zone_default_initname) + 1, KM_SLEEP);
3843 	(void) strcpy(zone->zone_initname, zone_default_initname);
3844 	zone->zone_nlwps = 0;
3845 	zone->zone_nlwps_ctl = INT_MAX;
3846 	zone->zone_locked_mem = 0;
3847 	zone->zone_locked_mem_ctl = UINT64_MAX;
3848 	zone->zone_max_swap = 0;
3849 	zone->zone_max_swap_ctl = UINT64_MAX;
3850 	zone0.zone_lockedmem_kstat = NULL;
3851 	zone0.zone_swapresv_kstat = NULL;
3852 
3853 	/*
3854 	 * Zsched initializes the rctls.
3855 	 */
3856 	zone->zone_rctls = NULL;
3857 
3858 	if ((error = parse_rctls(rctlbuf, rctlbufsz, &rctls)) != 0) {
3859 		zone_free(zone);
3860 		return (zone_create_error(error, 0, extended_error));
3861 	}
3862 
3863 	if ((error = parse_zfs(zone, zfsbuf, zfsbufsz)) != 0) {
3864 		zone_free(zone);
3865 		return (set_errno(error));
3866 	}
3867 
3868 	/*
3869 	 * Read in the trusted system parameters:
3870 	 * match flag and sensitivity label.
3871 	 */
3872 	zone->zone_match = match;
3873 	if (is_system_labeled() && !(zone->zone_flags & ZF_IS_SCRATCH)) {
3874 		/* Fail if requested to set doi to anything but system's doi */
3875 		if (doi != 0 && doi != default_doi) {
3876 			zone_free(zone);
3877 			return (set_errno(EINVAL));
3878 		}
3879 		/* Always apply system's doi to the zone */
3880 		error = zone_set_label(zone, label, default_doi);
3881 		if (error != 0) {
3882 			zone_free(zone);
3883 			return (set_errno(error));
3884 		}
3885 		insert_label_hash = B_TRUE;
3886 	} else {
3887 		/* all zones get an admin_low label if system is not labeled */
3888 		zone->zone_slabel = l_admin_low;
3889 		label_hold(l_admin_low);
3890 		insert_label_hash = B_FALSE;
3891 	}
3892 
3893 	/*
3894 	 * Stop all lwps since that's what normally happens as part of fork().
3895 	 * This needs to happen before we grab any locks to avoid deadlock
3896 	 * (another lwp in the process could be waiting for the held lock).
3897 	 */
3898 	if (curthread != pp->p_agenttp && !holdlwps(SHOLDFORK)) {
3899 		zone_free(zone);
3900 		if (rctls)
3901 			nvlist_free(rctls);
3902 		return (zone_create_error(error, 0, extended_error));
3903 	}
3904 
3905 	if (block_mounts() == 0) {
3906 		mutex_enter(&pp->p_lock);
3907 		if (curthread != pp->p_agenttp)
3908 			continuelwps(pp);
3909 		mutex_exit(&pp->p_lock);
3910 		zone_free(zone);
3911 		if (rctls)
3912 			nvlist_free(rctls);
3913 		return (zone_create_error(error, 0, extended_error));
3914 	}
3915 
3916 	/*
3917 	 * Set up credential for kernel access.  After this, any errors
3918 	 * should go through the dance in errout rather than calling
3919 	 * zone_free directly.
3920 	 */
3921 	zone->zone_kcred = crdup(kcred);
3922 	crsetzone(zone->zone_kcred, zone);
3923 	priv_intersect(zone->zone_privset, &CR_PPRIV(zone->zone_kcred));
3924 	priv_intersect(zone->zone_privset, &CR_EPRIV(zone->zone_kcred));
3925 	priv_intersect(zone->zone_privset, &CR_IPRIV(zone->zone_kcred));
3926 	priv_intersect(zone->zone_privset, &CR_LPRIV(zone->zone_kcred));
3927 
3928 	mutex_enter(&zonehash_lock);
3929 	/*
3930 	 * Make sure zone doesn't already exist.
3931 	 *
3932 	 * If the system and zone are labeled,
3933 	 * make sure no other zone exists that has the same label.
3934 	 */
3935 	if ((ztmp = zone_find_all_by_name(zone->zone_name)) != NULL ||
3936 	    (insert_label_hash &&
3937 	    (ztmp = zone_find_all_by_label(zone->zone_slabel)) != NULL)) {
3938 		zone_status_t status;
3939 
3940 		status = zone_status_get(ztmp);
3941 		if (status == ZONE_IS_READY || status == ZONE_IS_RUNNING)
3942 			error = EEXIST;
3943 		else
3944 			error = EBUSY;
3945 
3946 		if (insert_label_hash)
3947 			error2 = ZE_LABELINUSE;
3948 
3949 		goto errout;
3950 	}
3951 
3952 	/*
3953 	 * Don't allow zone creations which would cause one zone's rootpath to
3954 	 * be accessible from that of another (non-global) zone.
3955 	 */
3956 	if (zone_is_nested(zone->zone_rootpath)) {
3957 		error = EBUSY;
3958 		goto errout;
3959 	}
3960 
3961 	ASSERT(zonecount != 0);		/* check for leaks */
3962 	if (zonecount + 1 > maxzones) {
3963 		error = ENOMEM;
3964 		goto errout;
3965 	}
3966 
3967 	if (zone_mount_count(zone->zone_rootpath) != 0) {
3968 		error = EBUSY;
3969 		error2 = ZE_AREMOUNTS;
3970 		goto errout;
3971 	}
3972 
3973 	/*
3974 	 * Zone is still incomplete, but we need to drop all locks while
3975 	 * zsched() initializes this zone's kernel process.  We
3976 	 * optimistically add the zone to the hashtable and associated
3977 	 * lists so a parallel zone_create() doesn't try to create the
3978 	 * same zone.
3979 	 */
3980 	zonecount++;
3981 	(void) mod_hash_insert(zonehashbyid,
3982 	    (mod_hash_key_t)(uintptr_t)zone->zone_id,
3983 	    (mod_hash_val_t)(uintptr_t)zone);
3984 	str = kmem_alloc(strlen(zone->zone_name) + 1, KM_SLEEP);
3985 	(void) strcpy(str, zone->zone_name);
3986 	(void) mod_hash_insert(zonehashbyname, (mod_hash_key_t)str,
3987 	    (mod_hash_val_t)(uintptr_t)zone);
3988 	if (insert_label_hash) {
3989 		(void) mod_hash_insert(zonehashbylabel,
3990 		    (mod_hash_key_t)zone->zone_slabel, (mod_hash_val_t)zone);
3991 		zone->zone_flags |= ZF_HASHED_LABEL;
3992 	}
3993 
3994 	/*
3995 	 * Insert into active list.  At this point there are no 'hold's
3996 	 * on the zone, but everyone else knows not to use it, so we can
3997 	 * continue to use it.  zsched() will do a zone_hold() if the
3998 	 * newproc() is successful.
3999 	 */
4000 	list_insert_tail(&zone_active, zone);
4001 	mutex_exit(&zonehash_lock);
4002 
4003 	zarg.zone = zone;
4004 	zarg.nvlist = rctls;
4005 	/*
4006 	 * The process, task, and project rctls are probably wrong;
4007 	 * we need an interface to get the default values of all rctls,
4008 	 * and initialize zsched appropriately.  I'm not sure that that
4009 	 * makes much of a difference, though.
4010 	 */
4011 	if (error = newproc(zsched, (void *)&zarg, syscid, minclsyspri, NULL)) {
4012 		/*
4013 		 * We need to undo all globally visible state.
4014 		 */
4015 		mutex_enter(&zonehash_lock);
4016 		list_remove(&zone_active, zone);
4017 		if (zone->zone_flags & ZF_HASHED_LABEL) {
4018 			ASSERT(zone->zone_slabel != NULL);
4019 			(void) mod_hash_destroy(zonehashbylabel,
4020 			    (mod_hash_key_t)zone->zone_slabel);
4021 		}
4022 		(void) mod_hash_destroy(zonehashbyname,
4023 		    (mod_hash_key_t)(uintptr_t)zone->zone_name);
4024 		(void) mod_hash_destroy(zonehashbyid,
4025 		    (mod_hash_key_t)(uintptr_t)zone->zone_id);
4026 		ASSERT(zonecount > 1);
4027 		zonecount--;
4028 		goto errout;
4029 	}
4030 
4031 	/*
4032 	 * Zone creation can't fail from now on.
4033 	 */
4034 
4035 	/*
4036 	 * Create zone kstats
4037 	 */
4038 	zone_kstat_create(zone);
4039 
4040 	/*
4041 	 * Let the other lwps continue.
4042 	 */
4043 	mutex_enter(&pp->p_lock);
4044 	if (curthread != pp->p_agenttp)
4045 		continuelwps(pp);
4046 	mutex_exit(&pp->p_lock);
4047 
4048 	/*
4049 	 * Wait for zsched to finish initializing the zone.
4050 	 */
4051 	zone_status_wait(zone, ZONE_IS_READY);
4052 	/*
4053 	 * The zone is fully visible, so we can let mounts progress.
4054 	 */
4055 	resume_mounts();
4056 	if (rctls)
4057 		nvlist_free(rctls);
4058 
4059 	return (zoneid);
4060 
4061 errout:
4062 	mutex_exit(&zonehash_lock);
4063 	/*
4064 	 * Let the other lwps continue.
4065 	 */
4066 	mutex_enter(&pp->p_lock);
4067 	if (curthread != pp->p_agenttp)
4068 		continuelwps(pp);
4069 	mutex_exit(&pp->p_lock);
4070 
4071 	resume_mounts();
4072 	if (rctls)
4073 		nvlist_free(rctls);
4074 	/*
4075 	 * There is currently one reference to the zone, a cred_ref from
4076 	 * zone_kcred.  To free the zone, we call crfree, which will call
4077 	 * zone_cred_rele, which will call zone_free.
4078 	 */
4079 	ASSERT(zone->zone_cred_ref == 1);	/* for zone_kcred */
4080 	ASSERT(zone->zone_kcred->cr_ref == 1);
4081 	ASSERT(zone->zone_ref == 0);
4082 	zkcr = zone->zone_kcred;
4083 	zone->zone_kcred = NULL;
4084 	crfree(zkcr);				/* triggers call to zone_free */
4085 	return (zone_create_error(error, error2, extended_error));
4086 }
4087 
4088 /*
4089  * Cause the zone to boot.  This is pretty simple, since we let zoneadmd do
4090  * the heavy lifting.  initname is the path to the program to launch
4091  * at the "top" of the zone; if this is NULL, we use the system default,
4092  * which is stored at zone_default_initname.
4093  */
4094 static int
4095 zone_boot(zoneid_t zoneid)
4096 {
4097 	int err;
4098 	zone_t *zone;
4099 
4100 	if (secpolicy_zone_config(CRED()) != 0)
4101 		return (set_errno(EPERM));
4102 	if (zoneid < MIN_USERZONEID || zoneid > MAX_ZONEID)
4103 		return (set_errno(EINVAL));
4104 
4105 	mutex_enter(&zonehash_lock);
4106 	/*
4107 	 * Look for zone under hash lock to prevent races with calls to
4108 	 * zone_shutdown, zone_destroy, etc.
4109 	 */
4110 	if ((zone = zone_find_all_by_id(zoneid)) == NULL) {
4111 		mutex_exit(&zonehash_lock);
4112 		return (set_errno(EINVAL));
4113 	}
4114 
4115 	mutex_enter(&zone_status_lock);
4116 	if (zone_status_get(zone) != ZONE_IS_READY) {
4117 		mutex_exit(&zone_status_lock);
4118 		mutex_exit(&zonehash_lock);
4119 		return (set_errno(EINVAL));
4120 	}
4121 	zone_status_set(zone, ZONE_IS_BOOTING);
4122 	mutex_exit(&zone_status_lock);
4123 
4124 	zone_hold(zone);	/* so we can use the zone_t later */
4125 	mutex_exit(&zonehash_lock);
4126 
4127 	if (zone_status_wait_sig(zone, ZONE_IS_RUNNING) == 0) {
4128 		zone_rele(zone);
4129 		return (set_errno(EINTR));
4130 	}
4131 
4132 	/*
4133 	 * Boot (starting init) might have failed, in which case the zone
4134 	 * will go to the SHUTTING_DOWN state; an appropriate errno will
4135 	 * be placed in zone->zone_boot_err, and so we return that.
4136 	 */
4137 	err = zone->zone_boot_err;
4138 	zone_rele(zone);
4139 	return (err ? set_errno(err) : 0);
4140 }
4141 
4142 /*
4143  * Kills all user processes in the zone, waiting for them all to exit
4144  * before returning.
4145  */
4146 static int
4147 zone_empty(zone_t *zone)
4148 {
4149 	int waitstatus;
4150 
4151 	/*
4152 	 * We need to drop zonehash_lock before killing all
4153 	 * processes, otherwise we'll deadlock with zone_find_*
4154 	 * which can be called from the exit path.
4155 	 */
4156 	ASSERT(MUTEX_NOT_HELD(&zonehash_lock));
4157 	while ((waitstatus = zone_status_timedwait_sig(zone, lbolt + hz,
4158 	    ZONE_IS_EMPTY)) == -1) {
4159 		killall(zone->zone_id);
4160 	}
4161 	/*
4162 	 * return EINTR if we were signaled
4163 	 */
4164 	if (waitstatus == 0)
4165 		return (EINTR);
4166 	return (0);
4167 }
4168 
4169 /*
4170  * This function implements the policy for zone visibility.
4171  *
4172  * In standard Solaris, a non-global zone can only see itself.
4173  *
4174  * In Trusted Extensions, a labeled zone can lookup any zone whose label
4175  * it dominates. For this test, the label of the global zone is treated as
4176  * admin_high so it is special-cased instead of being checked for dominance.
4177  *
4178  * Returns true if zone attributes are viewable, false otherwise.
4179  */
4180 static boolean_t
4181 zone_list_access(zone_t *zone)
4182 {
4183 
4184 	if (curproc->p_zone == global_zone ||
4185 	    curproc->p_zone == zone) {
4186 		return (B_TRUE);
4187 	} else if (is_system_labeled() && !(zone->zone_flags & ZF_IS_SCRATCH)) {
4188 		bslabel_t *curproc_label;
4189 		bslabel_t *zone_label;
4190 
4191 		curproc_label = label2bslabel(curproc->p_zone->zone_slabel);
4192 		zone_label = label2bslabel(zone->zone_slabel);
4193 
4194 		if (zone->zone_id != GLOBAL_ZONEID &&
4195 		    bldominates(curproc_label, zone_label)) {
4196 			return (B_TRUE);
4197 		} else {
4198 			return (B_FALSE);
4199 		}
4200 	} else {
4201 		return (B_FALSE);
4202 	}
4203 }
4204 
4205 /*
4206  * Systemcall to start the zone's halt sequence.  By the time this
4207  * function successfully returns, all user processes and kernel threads
4208  * executing in it will have exited, ZSD shutdown callbacks executed,
4209  * and the zone status set to ZONE_IS_DOWN.
4210  *
4211  * It is possible that the call will interrupt itself if the caller is the
4212  * parent of any process running in the zone, and doesn't have SIGCHLD blocked.
4213  */
4214 static int
4215 zone_shutdown(zoneid_t zoneid)
4216 {
4217 	int error;
4218 	zone_t *zone;
4219 	zone_status_t status;
4220 
4221 	if (secpolicy_zone_config(CRED()) != 0)
4222 		return (set_errno(EPERM));
4223 	if (zoneid < MIN_USERZONEID || zoneid > MAX_ZONEID)
4224 		return (set_errno(EINVAL));
4225 
4226 	/*
4227 	 * Block mounts so that VFS_MOUNT() can get an accurate view of
4228 	 * the zone's status with regards to ZONE_IS_SHUTTING down.
4229 	 *
4230 	 * e.g. NFS can fail the mount if it determines that the zone
4231 	 * has already begun the shutdown sequence.
4232 	 */
4233 	if (block_mounts() == 0)
4234 		return (set_errno(EINTR));
4235 	mutex_enter(&zonehash_lock);
4236 	/*
4237 	 * Look for zone under hash lock to prevent races with other
4238 	 * calls to zone_shutdown and zone_destroy.
4239 	 */
4240 	if ((zone = zone_find_all_by_id(zoneid)) == NULL) {
4241 		mutex_exit(&zonehash_lock);
4242 		resume_mounts();
4243 		return (set_errno(EINVAL));
4244 	}
4245 	mutex_enter(&zone_status_lock);
4246 	status = zone_status_get(zone);
4247 	/*
4248 	 * Fail if the zone isn't fully initialized yet.
4249 	 */
4250 	if (status < ZONE_IS_READY) {
4251 		mutex_exit(&zone_status_lock);
4252 		mutex_exit(&zonehash_lock);
4253 		resume_mounts();
4254 		return (set_errno(EINVAL));
4255 	}
4256 	/*
4257 	 * If conditions required for zone_shutdown() to return have been met,
4258 	 * return success.
4259 	 */
4260 	if (status >= ZONE_IS_DOWN) {
4261 		mutex_exit(&zone_status_lock);
4262 		mutex_exit(&zonehash_lock);
4263 		resume_mounts();
4264 		return (0);
4265 	}
4266 	/*
4267 	 * If zone_shutdown() hasn't been called before, go through the motions.
4268 	 * If it has, there's nothing to do but wait for the kernel threads to
4269 	 * drain.
4270 	 */
4271 	if (status < ZONE_IS_EMPTY) {
4272 		uint_t ntasks;
4273 
4274 		mutex_enter(&zone->zone_lock);
4275 		if ((ntasks = zone->zone_ntasks) != 1) {
4276 			/*
4277 			 * There's still stuff running.
4278 			 */
4279 			zone_status_set(zone, ZONE_IS_SHUTTING_DOWN);
4280 		}
4281 		mutex_exit(&zone->zone_lock);
4282 		if (ntasks == 1) {
4283 			/*
4284 			 * The only way to create another task is through
4285 			 * zone_enter(), which will block until we drop
4286 			 * zonehash_lock.  The zone is empty.
4287 			 */
4288 			if (zone->zone_kthreads == NULL) {
4289 				/*
4290 				 * Skip ahead to ZONE_IS_DOWN
4291 				 */
4292 				zone_status_set(zone, ZONE_IS_DOWN);
4293 			} else {
4294 				zone_status_set(zone, ZONE_IS_EMPTY);
4295 			}
4296 		}
4297 	}
4298 	zone_hold(zone);	/* so we can use the zone_t later */
4299 	mutex_exit(&zone_status_lock);
4300 	mutex_exit(&zonehash_lock);
4301 	resume_mounts();
4302 
4303 	if (error = zone_empty(zone)) {
4304 		zone_rele(zone);
4305 		return (set_errno(error));
4306 	}
4307 	/*
4308 	 * After the zone status goes to ZONE_IS_DOWN this zone will no
4309 	 * longer be notified of changes to the pools configuration, so
4310 	 * in order to not end up with a stale pool pointer, we point
4311 	 * ourselves at the default pool and remove all resource
4312 	 * visibility.  This is especially important as the zone_t may
4313 	 * languish on the deathrow for a very long time waiting for
4314 	 * cred's to drain out.
4315 	 *
4316 	 * This rebinding of the zone can happen multiple times
4317 	 * (presumably due to interrupted or parallel systemcalls)
4318 	 * without any adverse effects.
4319 	 */
4320 	if (pool_lock_intr() != 0) {
4321 		zone_rele(zone);
4322 		return (set_errno(EINTR));
4323 	}
4324 	if (pool_state == POOL_ENABLED) {
4325 		mutex_enter(&cpu_lock);
4326 		zone_pool_set(zone, pool_default);
4327 		/*
4328 		 * The zone no longer needs to be able to see any cpus.
4329 		 */
4330 		zone_pset_set(zone, ZONE_PS_INVAL);
4331 		mutex_exit(&cpu_lock);
4332 	}
4333 	pool_unlock();
4334 
4335 	/*
4336 	 * ZSD shutdown callbacks can be executed multiple times, hence
4337 	 * it is safe to not be holding any locks across this call.
4338 	 */
4339 	zone_zsd_callbacks(zone, ZSD_SHUTDOWN);
4340 
4341 	mutex_enter(&zone_status_lock);
4342 	if (zone->zone_kthreads == NULL && zone_status_get(zone) < ZONE_IS_DOWN)
4343 		zone_status_set(zone, ZONE_IS_DOWN);
4344 	mutex_exit(&zone_status_lock);
4345 
4346 	/*
4347 	 * Wait for kernel threads to drain.
4348 	 */
4349 	if (!zone_status_wait_sig(zone, ZONE_IS_DOWN)) {
4350 		zone_rele(zone);
4351 		return (set_errno(EINTR));
4352 	}
4353 
4354 	/*
4355 	 * Zone can be become down/destroyable even if the above wait
4356 	 * returns EINTR, so any code added here may never execute.
4357 	 * (i.e. don't add code here)
4358 	 */
4359 
4360 	zone_rele(zone);
4361 	return (0);
4362 }
4363 
4364 /*
4365  * Systemcall entry point to finalize the zone halt process.  The caller
4366  * must have already successfully called zone_shutdown().
4367  *
4368  * Upon successful completion, the zone will have been fully destroyed:
4369  * zsched will have exited, destructor callbacks executed, and the zone
4370  * removed from the list of active zones.
4371  */
4372 static int
4373 zone_destroy(zoneid_t zoneid)
4374 {
4375 	uint64_t uniqid;
4376 	zone_t *zone;
4377 	zone_status_t status;
4378 
4379 	if (secpolicy_zone_config(CRED()) != 0)
4380 		return (set_errno(EPERM));
4381 	if (zoneid < MIN_USERZONEID || zoneid > MAX_ZONEID)
4382 		return (set_errno(EINVAL));
4383 
4384 	mutex_enter(&zonehash_lock);
4385 	/*
4386 	 * Look for zone under hash lock to prevent races with other
4387 	 * calls to zone_destroy.
4388 	 */
4389 	if ((zone = zone_find_all_by_id(zoneid)) == NULL) {
4390 		mutex_exit(&zonehash_lock);
4391 		return (set_errno(EINVAL));
4392 	}
4393 
4394 	if (zone_mount_count(zone->zone_rootpath) != 0) {
4395 		mutex_exit(&zonehash_lock);
4396 		return (set_errno(EBUSY));
4397 	}
4398 	mutex_enter(&zone_status_lock);
4399 	status = zone_status_get(zone);
4400 	if (status < ZONE_IS_DOWN) {
4401 		mutex_exit(&zone_status_lock);
4402 		mutex_exit(&zonehash_lock);
4403 		return (set_errno(EBUSY));
4404 	} else if (status == ZONE_IS_DOWN) {
4405 		zone_status_set(zone, ZONE_IS_DYING); /* Tell zsched to exit */
4406 	}
4407 	mutex_exit(&zone_status_lock);
4408 	zone_hold(zone);
4409 	mutex_exit(&zonehash_lock);
4410 
4411 	/*
4412 	 * wait for zsched to exit
4413 	 */
4414 	zone_status_wait(zone, ZONE_IS_DEAD);
4415 	zone_zsd_callbacks(zone, ZSD_DESTROY);
4416 	zone->zone_netstack = NULL;
4417 	uniqid = zone->zone_uniqid;
4418 	zone_rele(zone);
4419 	zone = NULL;	/* potentially free'd */
4420 
4421 	mutex_enter(&zonehash_lock);
4422 	for (; /* ever */; ) {
4423 		boolean_t unref;
4424 
4425 		if ((zone = zone_find_all_by_id(zoneid)) == NULL ||
4426 		    zone->zone_uniqid != uniqid) {
4427 			/*
4428 			 * The zone has gone away.  Necessary conditions
4429 			 * are met, so we return success.
4430 			 */
4431 			mutex_exit(&zonehash_lock);
4432 			return (0);
4433 		}
4434 		mutex_enter(&zone->zone_lock);
4435 		unref = ZONE_IS_UNREF(zone);
4436 		mutex_exit(&zone->zone_lock);
4437 		if (unref) {
4438 			/*
4439 			 * There is only one reference to the zone -- that
4440 			 * added when the zone was added to the hashtables --
4441 			 * and things will remain this way until we drop
4442 			 * zonehash_lock... we can go ahead and cleanup the
4443 			 * zone.
4444 			 */
4445 			break;
4446 		}
4447 
4448 		if (cv_wait_sig(&zone_destroy_cv, &zonehash_lock) == 0) {
4449 			/* Signaled */
4450 			mutex_exit(&zonehash_lock);
4451 			return (set_errno(EINTR));
4452 		}
4453 
4454 	}
4455 
4456 	/*
4457 	 * Remove CPU cap for this zone now since we're not going to
4458 	 * fail below this point.
4459 	 */
4460 	cpucaps_zone_remove(zone);
4461 
4462 	/* Get rid of the zone's kstats */
4463 	zone_kstat_delete(zone);
4464 
4465 	/* free brand specific data */
4466 	if (ZONE_IS_BRANDED(zone))
4467 		ZBROP(zone)->b_free_brand_data(zone);
4468 
4469 	/* Say goodbye to brand framework. */
4470 	brand_unregister_zone(zone->zone_brand);
4471 
4472 	/*
4473 	 * It is now safe to let the zone be recreated; remove it from the
4474 	 * lists.  The memory will not be freed until the last cred
4475 	 * reference goes away.
4476 	 */
4477 	ASSERT(zonecount > 1);	/* must be > 1; can't destroy global zone */
4478 	zonecount--;
4479 	/* remove from active list and hash tables */
4480 	list_remove(&zone_active, zone);
4481 	(void) mod_hash_destroy(zonehashbyname,
4482 	    (mod_hash_key_t)zone->zone_name);
4483 	(void) mod_hash_destroy(zonehashbyid,
4484 	    (mod_hash_key_t)(uintptr_t)zone->zone_id);
4485 	if (zone->zone_flags & ZF_HASHED_LABEL)
4486 		(void) mod_hash_destroy(zonehashbylabel,
4487 		    (mod_hash_key_t)zone->zone_slabel);
4488 	mutex_exit(&zonehash_lock);
4489 
4490 	/*
4491 	 * Release the root vnode; we're not using it anymore.  Nor should any
4492 	 * other thread that might access it exist.
4493 	 */
4494 	if (zone->zone_rootvp != NULL) {
4495 		VN_RELE(zone->zone_rootvp);
4496 		zone->zone_rootvp = NULL;
4497 	}
4498 
4499 	/* add to deathrow list */
4500 	mutex_enter(&zone_deathrow_lock);
4501 	list_insert_tail(&zone_deathrow, zone);
4502 	mutex_exit(&zone_deathrow_lock);
4503 
4504 	/*
4505 	 * Drop last reference (which was added by zsched()), this will
4506 	 * free the zone unless there are outstanding cred references.
4507 	 */
4508 	zone_rele(zone);
4509 	return (0);
4510 }
4511 
4512 /*
4513  * Systemcall entry point for zone_getattr(2).
4514  */
4515 static ssize_t
4516 zone_getattr(zoneid_t zoneid, int attr, void *buf, size_t bufsize)
4517 {
4518 	size_t size;
4519 	int error = 0, err;
4520 	zone_t *zone;
4521 	char *zonepath;
4522 	char *outstr;
4523 	zone_status_t zone_status;
4524 	pid_t initpid;
4525 	boolean_t global = (curzone == global_zone);
4526 	boolean_t inzone = (curzone->zone_id == zoneid);
4527 	ushort_t flags;
4528 
4529 	mutex_enter(&zonehash_lock);
4530 	if ((zone = zone_find_all_by_id(zoneid)) == NULL) {
4531 		mutex_exit(&zonehash_lock);
4532 		return (set_errno(EINVAL));
4533 	}
4534 	zone_status = zone_status_get(zone);
4535 	if (zone_status < ZONE_IS_INITIALIZED) {
4536 		mutex_exit(&zonehash_lock);
4537 		return (set_errno(EINVAL));
4538 	}
4539 	zone_hold(zone);
4540 	mutex_exit(&zonehash_lock);
4541 
4542 	/*
4543 	 * If not in the global zone, don't show information about other zones,
4544 	 * unless the system is labeled and the local zone's label dominates
4545 	 * the other zone.
4546 	 */
4547 	if (!zone_list_access(zone)) {
4548 		zone_rele(zone);
4549 		return (set_errno(EINVAL));
4550 	}
4551 
4552 	switch (attr) {
4553 	case ZONE_ATTR_ROOT:
4554 		if (global) {
4555 			/*
4556 			 * Copy the path to trim the trailing "/" (except for
4557 			 * the global zone).
4558 			 */
4559 			if (zone != global_zone)
4560 				size = zone->zone_rootpathlen - 1;
4561 			else
4562 				size = zone->zone_rootpathlen;
4563 			zonepath = kmem_alloc(size, KM_SLEEP);
4564 			bcopy(zone->zone_rootpath, zonepath, size);
4565 			zonepath[size - 1] = '\0';
4566 		} else {
4567 			if (inzone || !is_system_labeled()) {
4568 				/*
4569 				 * Caller is not in the global zone.
4570 				 * if the query is on the current zone
4571 				 * or the system is not labeled,
4572 				 * just return faked-up path for current zone.
4573 				 */
4574 				zonepath = "/";
4575 				size = 2;
4576 			} else {
4577 				/*
4578 				 * Return related path for current zone.
4579 				 */
4580 				int prefix_len = strlen(zone_prefix);
4581 				int zname_len = strlen(zone->zone_name);
4582 
4583 				size = prefix_len + zname_len + 1;
4584 				zonepath = kmem_alloc(size, KM_SLEEP);
4585 				bcopy(zone_prefix, zonepath, prefix_len);
4586 				bcopy(zone->zone_name, zonepath +
4587 				    prefix_len, zname_len);
4588 				zonepath[size - 1] = '\0';
4589 			}
4590 		}
4591 		if (bufsize > size)
4592 			bufsize = size;
4593 		if (buf != NULL) {
4594 			err = copyoutstr(zonepath, buf, bufsize, NULL);
4595 			if (err != 0 && err != ENAMETOOLONG)
4596 				error = EFAULT;
4597 		}
4598 		if (global || (is_system_labeled() && !inzone))
4599 			kmem_free(zonepath, size);
4600 		break;
4601 
4602 	case ZONE_ATTR_NAME:
4603 		size = strlen(zone->zone_name) + 1;
4604 		if (bufsize > size)
4605 			bufsize = size;
4606 		if (buf != NULL) {
4607 			err = copyoutstr(zone->zone_name, buf, bufsize, NULL);
4608 			if (err != 0 && err != ENAMETOOLONG)
4609 				error = EFAULT;
4610 		}
4611 		break;
4612 
4613 	case ZONE_ATTR_STATUS:
4614 		/*
4615 		 * Since we're not holding zonehash_lock, the zone status
4616 		 * may be anything; leave it up to userland to sort it out.
4617 		 */
4618 		size = sizeof (zone_status);
4619 		if (bufsize > size)
4620 			bufsize = size;
4621 		zone_status = zone_status_get(zone);
4622 		if (buf != NULL &&
4623 		    copyout(&zone_status, buf, bufsize) != 0)
4624 			error = EFAULT;
4625 		break;
4626 	case ZONE_ATTR_FLAGS:
4627 		size = sizeof (zone->zone_flags);
4628 		if (bufsize > size)
4629 			bufsize = size;
4630 		flags = zone->zone_flags;
4631 		if (buf != NULL &&
4632 		    copyout(&flags, buf, bufsize) != 0)
4633 			error = EFAULT;
4634 		break;
4635 	case ZONE_ATTR_PRIVSET:
4636 		size = sizeof (priv_set_t);
4637 		if (bufsize > size)
4638 			bufsize = size;
4639 		if (buf != NULL &&
4640 		    copyout(zone->zone_privset, buf, bufsize) != 0)
4641 			error = EFAULT;
4642 		break;
4643 	case ZONE_ATTR_UNIQID:
4644 		size = sizeof (zone->zone_uniqid);
4645 		if (bufsize > size)
4646 			bufsize = size;
4647 		if (buf != NULL &&
4648 		    copyout(&zone->zone_uniqid, buf, bufsize) != 0)
4649 			error = EFAULT;
4650 		break;
4651 	case ZONE_ATTR_POOLID:
4652 		{
4653 			pool_t *pool;
4654 			poolid_t poolid;
4655 
4656 			if (pool_lock_intr() != 0) {
4657 				error = EINTR;
4658 				break;
4659 			}
4660 			pool = zone_pool_get(zone);
4661 			poolid = pool->pool_id;
4662 			pool_unlock();
4663 			size = sizeof (poolid);
4664 			if (bufsize > size)
4665 				bufsize = size;
4666 			if (buf != NULL && copyout(&poolid, buf, size) != 0)
4667 				error = EFAULT;
4668 		}
4669 		break;
4670 	case ZONE_ATTR_SLBL:
4671 		size = sizeof (bslabel_t);
4672 		if (bufsize > size)
4673 			bufsize = size;
4674 		if (zone->zone_slabel == NULL)
4675 			error = EINVAL;
4676 		else if (buf != NULL &&
4677 		    copyout(label2bslabel(zone->zone_slabel), buf,
4678 		    bufsize) != 0)
4679 			error = EFAULT;
4680 		break;
4681 	case ZONE_ATTR_INITPID:
4682 		size = sizeof (initpid);
4683 		if (bufsize > size)
4684 			bufsize = size;
4685 		initpid = zone->zone_proc_initpid;
4686 		if (initpid == -1) {
4687 			error = ESRCH;
4688 			break;
4689 		}
4690 		if (buf != NULL &&
4691 		    copyout(&initpid, buf, bufsize) != 0)
4692 			error = EFAULT;
4693 		break;
4694 	case ZONE_ATTR_BRAND:
4695 		size = strlen(zone->zone_brand->b_name) + 1;
4696 
4697 		if (bufsize > size)
4698 			bufsize = size;
4699 		if (buf != NULL) {
4700 			err = copyoutstr(zone->zone_brand->b_name, buf,
4701 			    bufsize, NULL);
4702 			if (err != 0 && err != ENAMETOOLONG)
4703 				error = EFAULT;
4704 		}
4705 		break;
4706 	case ZONE_ATTR_INITNAME:
4707 		size = strlen(zone->zone_initname) + 1;
4708 		if (bufsize > size)
4709 			bufsize = size;
4710 		if (buf != NULL) {
4711 			err = copyoutstr(zone->zone_initname, buf, bufsize,
4712 			    NULL);
4713 			if (err != 0 && err != ENAMETOOLONG)
4714 				error = EFAULT;
4715 		}
4716 		break;
4717 	case ZONE_ATTR_BOOTARGS:
4718 		if (zone->zone_bootargs == NULL)
4719 			outstr = "";
4720 		else
4721 			outstr = zone->zone_bootargs;
4722 		size = strlen(outstr) + 1;
4723 		if (bufsize > size)
4724 			bufsize = size;
4725 		if (buf != NULL) {
4726 			err = copyoutstr(outstr, buf, bufsize, NULL);
4727 			if (err != 0 && err != ENAMETOOLONG)
4728 				error = EFAULT;
4729 		}
4730 		break;
4731 	case ZONE_ATTR_PHYS_MCAP:
4732 		size = sizeof (zone->zone_phys_mcap);
4733 		if (bufsize > size)
4734 			bufsize = size;
4735 		if (buf != NULL &&
4736 		    copyout(&zone->zone_phys_mcap, buf, bufsize) != 0)
4737 			error = EFAULT;
4738 		break;
4739 	case ZONE_ATTR_SCHED_CLASS:
4740 		mutex_enter(&class_lock);
4741 
4742 		if (zone->zone_defaultcid >= loaded_classes)
4743 			outstr = "";
4744 		else
4745 			outstr = sclass[zone->zone_defaultcid].cl_name;
4746 		size = strlen(outstr) + 1;
4747 		if (bufsize > size)
4748 			bufsize = size;
4749 		if (buf != NULL) {
4750 			err = copyoutstr(outstr, buf, bufsize, NULL);
4751 			if (err != 0 && err != ENAMETOOLONG)
4752 				error = EFAULT;
4753 		}
4754 
4755 		mutex_exit(&class_lock);
4756 		break;
4757 	case ZONE_ATTR_HOSTID:
4758 		if (zone->zone_hostid != HW_INVALID_HOSTID &&
4759 		    bufsize == sizeof (zone->zone_hostid)) {
4760 			size = sizeof (zone->zone_hostid);
4761 			if (buf != NULL && copyout(&zone->zone_hostid, buf,
4762 			    bufsize) != 0)
4763 				error = EFAULT;
4764 		} else {
4765 			error = EINVAL;
4766 		}
4767 		break;
4768 	default:
4769 		if ((attr >= ZONE_ATTR_BRAND_ATTRS) && ZONE_IS_BRANDED(zone)) {
4770 			size = bufsize;
4771 			error = ZBROP(zone)->b_getattr(zone, attr, buf, &size);
4772 		} else {
4773 			error = EINVAL;
4774 		}
4775 	}
4776 	zone_rele(zone);
4777 
4778 	if (error)
4779 		return (set_errno(error));
4780 	return ((ssize_t)size);
4781 }
4782 
4783 /*
4784  * Systemcall entry point for zone_setattr(2).
4785  */
4786 /*ARGSUSED*/
4787 static int
4788 zone_setattr(zoneid_t zoneid, int attr, void *buf, size_t bufsize)
4789 {
4790 	zone_t *zone;
4791 	zone_status_t zone_status;
4792 	int err;
4793 
4794 	if (secpolicy_zone_config(CRED()) != 0)
4795 		return (set_errno(EPERM));
4796 
4797 	/*
4798 	 * Only the ZONE_ATTR_PHYS_MCAP attribute can be set on the
4799 	 * global zone.
4800 	 */
4801 	if (zoneid == GLOBAL_ZONEID && attr != ZONE_ATTR_PHYS_MCAP) {
4802 		return (set_errno(EINVAL));
4803 	}
4804 
4805 	mutex_enter(&zonehash_lock);
4806 	if ((zone = zone_find_all_by_id(zoneid)) == NULL) {
4807 		mutex_exit(&zonehash_lock);
4808 		return (set_errno(EINVAL));
4809 	}
4810 	zone_hold(zone);
4811 	mutex_exit(&zonehash_lock);
4812 
4813 	/*
4814 	 * At present most attributes can only be set on non-running,
4815 	 * non-global zones.
4816 	 */
4817 	zone_status = zone_status_get(zone);
4818 	if (attr != ZONE_ATTR_PHYS_MCAP && zone_status > ZONE_IS_READY)
4819 		goto done;
4820 
4821 	switch (attr) {
4822 	case ZONE_ATTR_INITNAME:
4823 		err = zone_set_initname(zone, (const char *)buf);
4824 		break;
4825 	case ZONE_ATTR_BOOTARGS:
4826 		err = zone_set_bootargs(zone, (const char *)buf);
4827 		break;
4828 	case ZONE_ATTR_BRAND:
4829 		err = zone_set_brand(zone, (const char *)buf);
4830 		break;
4831 	case ZONE_ATTR_PHYS_MCAP:
4832 		err = zone_set_phys_mcap(zone, (const uint64_t *)buf);
4833 		break;
4834 	case ZONE_ATTR_SCHED_CLASS:
4835 		err = zone_set_sched_class(zone, (const char *)buf);
4836 		break;
4837 	case ZONE_ATTR_HOSTID:
4838 		if (bufsize == sizeof (zone->zone_hostid)) {
4839 			if (copyin(buf, &zone->zone_hostid, bufsize) == 0)
4840 				err = 0;
4841 			else
4842 				err = EFAULT;
4843 		} else {
4844 			err = EINVAL;
4845 		}
4846 		break;
4847 	default:
4848 		if ((attr >= ZONE_ATTR_BRAND_ATTRS) && ZONE_IS_BRANDED(zone))
4849 			err = ZBROP(zone)->b_setattr(zone, attr, buf, bufsize);
4850 		else
4851 			err = EINVAL;
4852 	}
4853 
4854 done:
4855 	zone_rele(zone);
4856 	return (err != 0 ? set_errno(err) : 0);
4857 }
4858 
4859 /*
4860  * Return zero if the process has at least one vnode mapped in to its
4861  * address space which shouldn't be allowed to change zones.
4862  *
4863  * Also return zero if the process has any shared mappings which reserve
4864  * swap.  This is because the counting for zone.max-swap does not allow swap
4865  * reservation to be shared between zones.  zone swap reservation is counted
4866  * on zone->zone_max_swap.
4867  */
4868 static int
4869 as_can_change_zones(void)
4870 {
4871 	proc_t *pp = curproc;
4872 	struct seg *seg;
4873 	struct as *as = pp->p_as;
4874 	vnode_t *vp;
4875 	int allow = 1;
4876 
4877 	ASSERT(pp->p_as != &kas);
4878 	AS_LOCK_ENTER(as, &as->a_lock, RW_READER);
4879 	for (seg = AS_SEGFIRST(as); seg != NULL; seg = AS_SEGNEXT(as, seg)) {
4880 
4881 		/*
4882 		 * Cannot enter zone with shared anon memory which
4883 		 * reserves swap.  See comment above.
4884 		 */
4885 		if (seg_can_change_zones(seg) == B_FALSE) {
4886 			allow = 0;
4887 			break;
4888 		}
4889 		/*
4890 		 * if we can't get a backing vnode for this segment then skip
4891 		 * it.
4892 		 */
4893 		vp = NULL;
4894 		if (SEGOP_GETVP(seg, seg->s_base, &vp) != 0 || vp == NULL)
4895 			continue;
4896 		if (!vn_can_change_zones(vp)) { /* bail on first match */
4897 			allow = 0;
4898 			break;
4899 		}
4900 	}
4901 	AS_LOCK_EXIT(as, &as->a_lock);
4902 	return (allow);
4903 }
4904 
4905 /*
4906  * Count swap reserved by curproc's address space
4907  */
4908 static size_t
4909 as_swresv(void)
4910 {
4911 	proc_t *pp = curproc;
4912 	struct seg *seg;
4913 	struct as *as = pp->p_as;
4914 	size_t swap = 0;
4915 
4916 	ASSERT(pp->p_as != &kas);
4917 	ASSERT(AS_WRITE_HELD(as, &as->a_lock));
4918 	for (seg = AS_SEGFIRST(as); seg != NULL; seg = AS_SEGNEXT(as, seg))
4919 		swap += seg_swresv(seg);
4920 
4921 	return (swap);
4922 }
4923 
4924 /*
4925  * Systemcall entry point for zone_enter().
4926  *
4927  * The current process is injected into said zone.  In the process
4928  * it will change its project membership, privileges, rootdir/cwd,
4929  * zone-wide rctls, and pool association to match those of the zone.
4930  *
4931  * The first zone_enter() called while the zone is in the ZONE_IS_READY
4932  * state will transition it to ZONE_IS_RUNNING.  Processes may only
4933  * enter a zone that is "ready" or "running".
4934  */
4935 static int
4936 zone_enter(zoneid_t zoneid)
4937 {
4938 	zone_t *zone;
4939 	vnode_t *vp;
4940 	proc_t *pp = curproc;
4941 	contract_t *ct;
4942 	cont_process_t *ctp;
4943 	task_t *tk, *oldtk;
4944 	kproject_t *zone_proj0;
4945 	cred_t *cr, *newcr;
4946 	pool_t *oldpool, *newpool;
4947 	sess_t *sp;
4948 	uid_t uid;
4949 	zone_status_t status;
4950 	int err = 0;
4951 	rctl_entity_p_t e;
4952 	size_t swap;
4953 	kthread_id_t t;
4954 
4955 	if (secpolicy_zone_config(CRED()) != 0)
4956 		return (set_errno(EPERM));
4957 	if (zoneid < MIN_USERZONEID || zoneid > MAX_ZONEID)
4958 		return (set_errno(EINVAL));
4959 
4960 	/*
4961 	 * Stop all lwps so we don't need to hold a lock to look at
4962 	 * curproc->p_zone.  This needs to happen before we grab any
4963 	 * locks to avoid deadlock (another lwp in the process could
4964 	 * be waiting for the held lock).
4965 	 */
4966 	if (curthread != pp->p_agenttp && !holdlwps(SHOLDFORK))
4967 		return (set_errno(EINTR));
4968 
4969 	/*
4970 	 * Make sure we're not changing zones with files open or mapped in
4971 	 * to our address space which shouldn't be changing zones.
4972 	 */
4973 	if (!files_can_change_zones()) {
4974 		err = EBADF;
4975 		goto out;
4976 	}
4977 	if (!as_can_change_zones()) {
4978 		err = EFAULT;
4979 		goto out;
4980 	}
4981 
4982 	mutex_enter(&zonehash_lock);
4983 	if (pp->p_zone != global_zone) {
4984 		mutex_exit(&zonehash_lock);
4985 		err = EINVAL;
4986 		goto out;
4987 	}
4988 
4989 	zone = zone_find_all_by_id(zoneid);
4990 	if (zone == NULL) {
4991 		mutex_exit(&zonehash_lock);
4992 		err = EINVAL;
4993 		goto out;
4994 	}
4995 
4996 	/*
4997 	 * To prevent processes in a zone from holding contracts on
4998 	 * extrazonal resources, and to avoid process contract
4999 	 * memberships which span zones, contract holders and processes
5000 	 * which aren't the sole members of their encapsulating process
5001 	 * contracts are not allowed to zone_enter.
5002 	 */
5003 	ctp = pp->p_ct_process;
5004 	ct = &ctp->conp_contract;
5005 	mutex_enter(&ct->ct_lock);
5006 	mutex_enter(&pp->p_lock);
5007 	if ((avl_numnodes(&pp->p_ct_held) != 0) || (ctp->conp_nmembers != 1)) {
5008 		mutex_exit(&pp->p_lock);
5009 		mutex_exit(&ct->ct_lock);
5010 		mutex_exit(&zonehash_lock);
5011 		err = EINVAL;
5012 		goto out;
5013 	}
5014 
5015 	/*
5016 	 * Moreover, we don't allow processes whose encapsulating
5017 	 * process contracts have inherited extrazonal contracts.
5018 	 * While it would be easier to eliminate all process contracts
5019 	 * with inherited contracts, we need to be able to give a
5020 	 * restarted init (or other zone-penetrating process) its
5021 	 * predecessor's contracts.
5022 	 */
5023 	if (ctp->conp_ninherited != 0) {
5024 		contract_t *next;
5025 		for (next = list_head(&ctp->conp_inherited); next;
5026 		    next = list_next(&ctp->conp_inherited, next)) {
5027 			if (contract_getzuniqid(next) != zone->zone_uniqid) {
5028 				mutex_exit(&pp->p_lock);
5029 				mutex_exit(&ct->ct_lock);
5030 				mutex_exit(&zonehash_lock);
5031 				err = EINVAL;
5032 				goto out;
5033 			}
5034 		}
5035 	}
5036 
5037 	mutex_exit(&pp->p_lock);
5038 	mutex_exit(&ct->ct_lock);
5039 
5040 	status = zone_status_get(zone);
5041 	if (status < ZONE_IS_READY || status >= ZONE_IS_SHUTTING_DOWN) {
5042 		/*
5043 		 * Can't join
5044 		 */
5045 		mutex_exit(&zonehash_lock);
5046 		err = EINVAL;
5047 		goto out;
5048 	}
5049 
5050 	/*
5051 	 * Make sure new priv set is within the permitted set for caller
5052 	 */
5053 	if (!priv_issubset(zone->zone_privset, &CR_OPPRIV(CRED()))) {
5054 		mutex_exit(&zonehash_lock);
5055 		err = EPERM;
5056 		goto out;
5057 	}
5058 	/*
5059 	 * We want to momentarily drop zonehash_lock while we optimistically
5060 	 * bind curproc to the pool it should be running in.  This is safe
5061 	 * since the zone can't disappear (we have a hold on it).
5062 	 */
5063 	zone_hold(zone);
5064 	mutex_exit(&zonehash_lock);
5065 
5066 	/*
5067 	 * Grab pool_lock to keep the pools configuration from changing
5068 	 * and to stop ourselves from getting rebound to another pool
5069 	 * until we join the zone.
5070 	 */
5071 	if (pool_lock_intr() != 0) {
5072 		zone_rele(zone);
5073 		err = EINTR;
5074 		goto out;
5075 	}
5076 	ASSERT(secpolicy_pool(CRED()) == 0);
5077 	/*
5078 	 * Bind ourselves to the pool currently associated with the zone.
5079 	 */
5080 	oldpool = curproc->p_pool;
5081 	newpool = zone_pool_get(zone);
5082 	if (pool_state == POOL_ENABLED && newpool != oldpool &&
5083 	    (err = pool_do_bind(newpool, P_PID, P_MYID,
5084 	    POOL_BIND_ALL)) != 0) {
5085 		pool_unlock();
5086 		zone_rele(zone);
5087 		goto out;
5088 	}
5089 
5090 	/*
5091 	 * Grab cpu_lock now; we'll need it later when we call
5092 	 * task_join().
5093 	 */
5094 	mutex_enter(&cpu_lock);
5095 	mutex_enter(&zonehash_lock);
5096 	/*
5097 	 * Make sure the zone hasn't moved on since we dropped zonehash_lock.
5098 	 */
5099 	if (zone_status_get(zone) >= ZONE_IS_SHUTTING_DOWN) {
5100 		/*
5101 		 * Can't join anymore.
5102 		 */
5103 		mutex_exit(&zonehash_lock);
5104 		mutex_exit(&cpu_lock);
5105 		if (pool_state == POOL_ENABLED &&
5106 		    newpool != oldpool)
5107 			(void) pool_do_bind(oldpool, P_PID, P_MYID,
5108 			    POOL_BIND_ALL);
5109 		pool_unlock();
5110 		zone_rele(zone);
5111 		err = EINVAL;
5112 		goto out;
5113 	}
5114 
5115 	/*
5116 	 * a_lock must be held while transfering locked memory and swap
5117 	 * reservation from the global zone to the non global zone because
5118 	 * asynchronous faults on the processes' address space can lock
5119 	 * memory and reserve swap via MCL_FUTURE and MAP_NORESERVE
5120 	 * segments respectively.
5121 	 */
5122 	AS_LOCK_ENTER(pp->as, &pp->p_as->a_lock, RW_WRITER);
5123 	swap = as_swresv();
5124 	mutex_enter(&pp->p_lock);
5125 	zone_proj0 = zone->zone_zsched->p_task->tk_proj;
5126 	/* verify that we do not exceed and task or lwp limits */
5127 	mutex_enter(&zone->zone_nlwps_lock);
5128 	/* add new lwps to zone and zone's proj0 */
5129 	zone_proj0->kpj_nlwps += pp->p_lwpcnt;
5130 	zone->zone_nlwps += pp->p_lwpcnt;
5131 	/* add 1 task to zone's proj0 */
5132 	zone_proj0->kpj_ntasks += 1;
5133 	mutex_exit(&zone->zone_nlwps_lock);
5134 
5135 	mutex_enter(&zone->zone_mem_lock);
5136 	zone->zone_locked_mem += pp->p_locked_mem;
5137 	zone_proj0->kpj_data.kpd_locked_mem += pp->p_locked_mem;
5138 	zone->zone_max_swap += swap;
5139 	mutex_exit(&zone->zone_mem_lock);
5140 
5141 	mutex_enter(&(zone_proj0->kpj_data.kpd_crypto_lock));
5142 	zone_proj0->kpj_data.kpd_crypto_mem += pp->p_crypto_mem;
5143 	mutex_exit(&(zone_proj0->kpj_data.kpd_crypto_lock));
5144 
5145 	/* remove lwps from proc's old zone and old project */
5146 	mutex_enter(&pp->p_zone->zone_nlwps_lock);
5147 	pp->p_zone->zone_nlwps -= pp->p_lwpcnt;
5148 	pp->p_task->tk_proj->kpj_nlwps -= pp->p_lwpcnt;
5149 	mutex_exit(&pp->p_zone->zone_nlwps_lock);
5150 
5151 	mutex_enter(&pp->p_zone->zone_mem_lock);
5152 	pp->p_zone->zone_locked_mem -= pp->p_locked_mem;
5153 	pp->p_task->tk_proj->kpj_data.kpd_locked_mem -= pp->p_locked_mem;
5154 	pp->p_zone->zone_max_swap -= swap;
5155 	mutex_exit(&pp->p_zone->zone_mem_lock);
5156 
5157 	mutex_enter(&(pp->p_task->tk_proj->kpj_data.kpd_crypto_lock));
5158 	pp->p_task->tk_proj->kpj_data.kpd_crypto_mem -= pp->p_crypto_mem;
5159 	mutex_exit(&(pp->p_task->tk_proj->kpj_data.kpd_crypto_lock));
5160 
5161 	pp->p_flag |= SZONETOP;
5162 	pp->p_zone = zone;
5163 	mutex_exit(&pp->p_lock);
5164 	AS_LOCK_EXIT(pp->p_as, &pp->p_as->a_lock);
5165 
5166 	/*
5167 	 * Joining the zone cannot fail from now on.
5168 	 *
5169 	 * This means that a lot of the following code can be commonized and
5170 	 * shared with zsched().
5171 	 */
5172 
5173 	/*
5174 	 * If the process contract fmri was inherited, we need to
5175 	 * flag this so that any contract status will not leak
5176 	 * extra zone information, svc_fmri in this case
5177 	 */
5178 	if (ctp->conp_svc_ctid != ct->ct_id) {
5179 		mutex_enter(&ct->ct_lock);
5180 		ctp->conp_svc_zone_enter = ct->ct_id;
5181 		mutex_exit(&ct->ct_lock);
5182 	}
5183 
5184 	/*
5185 	 * Reset the encapsulating process contract's zone.
5186 	 */
5187 	ASSERT(ct->ct_mzuniqid == GLOBAL_ZONEUNIQID);
5188 	contract_setzuniqid(ct, zone->zone_uniqid);
5189 
5190 	/*
5191 	 * Create a new task and associate the process with the project keyed
5192 	 * by (projid,zoneid).
5193 	 *
5194 	 * We might as well be in project 0; the global zone's projid doesn't
5195 	 * make much sense in a zone anyhow.
5196 	 *
5197 	 * This also increments zone_ntasks, and returns with p_lock held.
5198 	 */
5199 	tk = task_create(0, zone);
5200 	oldtk = task_join(tk, 0);
5201 	mutex_exit(&cpu_lock);
5202 
5203 	/*
5204 	 * call RCTLOP_SET functions on this proc
5205 	 */
5206 	e.rcep_p.zone = zone;
5207 	e.rcep_t = RCENTITY_ZONE;
5208 	(void) rctl_set_dup(NULL, NULL, pp, &e, zone->zone_rctls, NULL,
5209 	    RCD_CALLBACK);
5210 	mutex_exit(&pp->p_lock);
5211 
5212 	/*
5213 	 * We don't need to hold any of zsched's locks here; not only do we know
5214 	 * the process and zone aren't going away, we know its session isn't
5215 	 * changing either.
5216 	 *
5217 	 * By joining zsched's session here, we mimic the behavior in the
5218 	 * global zone of init's sid being the pid of sched.  We extend this
5219 	 * to all zlogin-like zone_enter()'ing processes as well.
5220 	 */
5221 	mutex_enter(&pidlock);
5222 	sp = zone->zone_zsched->p_sessp;
5223 	sess_hold(zone->zone_zsched);
5224 	mutex_enter(&pp->p_lock);
5225 	pgexit(pp);
5226 	sess_rele(pp->p_sessp, B_TRUE);
5227 	pp->p_sessp = sp;
5228 	pgjoin(pp, zone->zone_zsched->p_pidp);
5229 
5230 	/*
5231 	 * If any threads are scheduled to be placed on zone wait queue they
5232 	 * should abandon the idea since the wait queue is changing.
5233 	 * We need to be holding pidlock & p_lock to do this.
5234 	 */
5235 	if ((t = pp->p_tlist) != NULL) {
5236 		do {
5237 			thread_lock(t);
5238 			/*
5239 			 * Kick this thread so that he doesn't sit
5240 			 * on a wrong wait queue.
5241 			 */
5242 			if (ISWAITING(t))
5243 				setrun_locked(t);
5244 
5245 			if (t->t_schedflag & TS_ANYWAITQ)
5246 				t->t_schedflag &= ~ TS_ANYWAITQ;
5247 
5248 			thread_unlock(t);
5249 		} while ((t = t->t_forw) != pp->p_tlist);
5250 	}
5251 
5252 	/*
5253 	 * If there is a default scheduling class for the zone and it is not
5254 	 * the class we are currently in, change all of the threads in the
5255 	 * process to the new class.  We need to be holding pidlock & p_lock
5256 	 * when we call parmsset so this is a good place to do it.
5257 	 */
5258 	if (zone->zone_defaultcid > 0 &&
5259 	    zone->zone_defaultcid != curthread->t_cid) {
5260 		pcparms_t pcparms;
5261 
5262 		pcparms.pc_cid = zone->zone_defaultcid;
5263 		pcparms.pc_clparms[0] = 0;
5264 
5265 		/*
5266 		 * If setting the class fails, we still want to enter the zone.
5267 		 */
5268 		if ((t = pp->p_tlist) != NULL) {
5269 			do {
5270 				(void) parmsset(&pcparms, t);
5271 			} while ((t = t->t_forw) != pp->p_tlist);
5272 		}
5273 	}
5274 
5275 	mutex_exit(&pp->p_lock);
5276 	mutex_exit(&pidlock);
5277 
5278 	mutex_exit(&zonehash_lock);
5279 	/*
5280 	 * We're firmly in the zone; let pools progress.
5281 	 */
5282 	pool_unlock();
5283 	task_rele(oldtk);
5284 	/*
5285 	 * We don't need to retain a hold on the zone since we already
5286 	 * incremented zone_ntasks, so the zone isn't going anywhere.
5287 	 */
5288 	zone_rele(zone);
5289 
5290 	/*
5291 	 * Chroot
5292 	 */
5293 	vp = zone->zone_rootvp;
5294 	zone_chdir(vp, &PTOU(pp)->u_cdir, pp);
5295 	zone_chdir(vp, &PTOU(pp)->u_rdir, pp);
5296 
5297 	/*
5298 	 * Change process credentials
5299 	 */
5300 	newcr = cralloc();
5301 	mutex_enter(&pp->p_crlock);
5302 	cr = pp->p_cred;
5303 	crcopy_to(cr, newcr);
5304 	crsetzone(newcr, zone);
5305 	pp->p_cred = newcr;
5306 
5307 	/*
5308 	 * Restrict all process privilege sets to zone limit
5309 	 */
5310 	priv_intersect(zone->zone_privset, &CR_PPRIV(newcr));
5311 	priv_intersect(zone->zone_privset, &CR_EPRIV(newcr));
5312 	priv_intersect(zone->zone_privset, &CR_IPRIV(newcr));
5313 	priv_intersect(zone->zone_privset, &CR_LPRIV(newcr));
5314 	mutex_exit(&pp->p_crlock);
5315 	crset(pp, newcr);
5316 
5317 	/*
5318 	 * Adjust upcount to reflect zone entry.
5319 	 */
5320 	uid = crgetruid(newcr);
5321 	mutex_enter(&pidlock);
5322 	upcount_dec(uid, GLOBAL_ZONEID);
5323 	upcount_inc(uid, zoneid);
5324 	mutex_exit(&pidlock);
5325 
5326 	/*
5327 	 * Set up core file path and content.
5328 	 */
5329 	set_core_defaults();
5330 
5331 out:
5332 	/*
5333 	 * Let the other lwps continue.
5334 	 */
5335 	mutex_enter(&pp->p_lock);
5336 	if (curthread != pp->p_agenttp)
5337 		continuelwps(pp);
5338 	mutex_exit(&pp->p_lock);
5339 
5340 	return (err != 0 ? set_errno(err) : 0);
5341 }
5342 
5343 /*
5344  * Systemcall entry point for zone_list(2).
5345  *
5346  * Processes running in a (non-global) zone only see themselves.
5347  * On labeled systems, they see all zones whose label they dominate.
5348  */
5349 static int
5350 zone_list(zoneid_t *zoneidlist, uint_t *numzones)
5351 {
5352 	zoneid_t *zoneids;
5353 	zone_t *zone, *myzone;
5354 	uint_t user_nzones, real_nzones;
5355 	uint_t domi_nzones;
5356 	int error;
5357 
5358 	if (copyin(numzones, &user_nzones, sizeof (uint_t)) != 0)
5359 		return (set_errno(EFAULT));
5360 
5361 	myzone = curproc->p_zone;
5362 	if (myzone != global_zone) {
5363 		bslabel_t *mybslab;
5364 
5365 		if (!is_system_labeled()) {
5366 			/* just return current zone */
5367 			real_nzones = domi_nzones = 1;
5368 			zoneids = kmem_alloc(sizeof (zoneid_t), KM_SLEEP);
5369 			zoneids[0] = myzone->zone_id;
5370 		} else {
5371 			/* return all zones that are dominated */
5372 			mutex_enter(&zonehash_lock);
5373 			real_nzones = zonecount;
5374 			domi_nzones = 0;
5375 			if (real_nzones > 0) {
5376 				zoneids = kmem_alloc(real_nzones *
5377 				    sizeof (zoneid_t), KM_SLEEP);
5378 				mybslab = label2bslabel(myzone->zone_slabel);
5379 				for (zone = list_head(&zone_active);
5380 				    zone != NULL;
5381 				    zone = list_next(&zone_active, zone)) {
5382 					if (zone->zone_id == GLOBAL_ZONEID)
5383 						continue;
5384 					if (zone != myzone &&
5385 					    (zone->zone_flags & ZF_IS_SCRATCH))
5386 						continue;
5387 					/*
5388 					 * Note that a label always dominates
5389 					 * itself, so myzone is always included
5390 					 * in the list.
5391 					 */
5392 					if (bldominates(mybslab,
5393 					    label2bslabel(zone->zone_slabel))) {
5394 						zoneids[domi_nzones++] =
5395 						    zone->zone_id;
5396 					}
5397 				}
5398 			}
5399 			mutex_exit(&zonehash_lock);
5400 		}
5401 	} else {
5402 		mutex_enter(&zonehash_lock);
5403 		real_nzones = zonecount;
5404 		domi_nzones = 0;
5405 		if (real_nzones > 0) {
5406 			zoneids = kmem_alloc(real_nzones * sizeof (zoneid_t),
5407 			    KM_SLEEP);
5408 			for (zone = list_head(&zone_active); zone != NULL;
5409 			    zone = list_next(&zone_active, zone))
5410 				zoneids[domi_nzones++] = zone->zone_id;
5411 			ASSERT(domi_nzones == real_nzones);
5412 		}
5413 		mutex_exit(&zonehash_lock);
5414 	}
5415 
5416 	/*
5417 	 * If user has allocated space for fewer entries than we found, then
5418 	 * return only up to his limit.  Either way, tell him exactly how many
5419 	 * we found.
5420 	 */
5421 	if (domi_nzones < user_nzones)
5422 		user_nzones = domi_nzones;
5423 	error = 0;
5424 	if (copyout(&domi_nzones, numzones, sizeof (uint_t)) != 0) {
5425 		error = EFAULT;
5426 	} else if (zoneidlist != NULL && user_nzones != 0) {
5427 		if (copyout(zoneids, zoneidlist,
5428 		    user_nzones * sizeof (zoneid_t)) != 0)
5429 			error = EFAULT;
5430 	}
5431 
5432 	if (real_nzones > 0)
5433 		kmem_free(zoneids, real_nzones * sizeof (zoneid_t));
5434 
5435 	if (error != 0)
5436 		return (set_errno(error));
5437 	else
5438 		return (0);
5439 }
5440 
5441 /*
5442  * Systemcall entry point for zone_lookup(2).
5443  *
5444  * Non-global zones are only able to see themselves and (on labeled systems)
5445  * the zones they dominate.
5446  */
5447 static zoneid_t
5448 zone_lookup(const char *zone_name)
5449 {
5450 	char *kname;
5451 	zone_t *zone;
5452 	zoneid_t zoneid;
5453 	int err;
5454 
5455 	if (zone_name == NULL) {
5456 		/* return caller's zone id */
5457 		return (getzoneid());
5458 	}
5459 
5460 	kname = kmem_zalloc(ZONENAME_MAX, KM_SLEEP);
5461 	if ((err = copyinstr(zone_name, kname, ZONENAME_MAX, NULL)) != 0) {
5462 		kmem_free(kname, ZONENAME_MAX);
5463 		return (set_errno(err));
5464 	}
5465 
5466 	mutex_enter(&zonehash_lock);
5467 	zone = zone_find_all_by_name(kname);
5468 	kmem_free(kname, ZONENAME_MAX);
5469 	/*
5470 	 * In a non-global zone, can only lookup global and own name.
5471 	 * In Trusted Extensions zone label dominance rules apply.
5472 	 */
5473 	if (zone == NULL ||
5474 	    zone_status_get(zone) < ZONE_IS_READY ||
5475 	    !zone_list_access(zone)) {
5476 		mutex_exit(&zonehash_lock);
5477 		return (set_errno(EINVAL));
5478 	} else {
5479 		zoneid = zone->zone_id;
5480 		mutex_exit(&zonehash_lock);
5481 		return (zoneid);
5482 	}
5483 }
5484 
5485 static int
5486 zone_version(int *version_arg)
5487 {
5488 	int version = ZONE_SYSCALL_API_VERSION;
5489 
5490 	if (copyout(&version, version_arg, sizeof (int)) != 0)
5491 		return (set_errno(EFAULT));
5492 	return (0);
5493 }
5494 
5495 /* ARGSUSED */
5496 long
5497 zone(int cmd, void *arg1, void *arg2, void *arg3, void *arg4)
5498 {
5499 	zone_def zs;
5500 	int err;
5501 
5502 	switch (cmd) {
5503 	case ZONE_CREATE:
5504 		if (get_udatamodel() == DATAMODEL_NATIVE) {
5505 			if (copyin(arg1, &zs, sizeof (zone_def))) {
5506 				return (set_errno(EFAULT));
5507 			}
5508 		} else {
5509 #ifdef _SYSCALL32_IMPL
5510 			zone_def32 zs32;
5511 
5512 			if (copyin(arg1, &zs32, sizeof (zone_def32))) {
5513 				return (set_errno(EFAULT));
5514 			}
5515 			zs.zone_name =
5516 			    (const char *)(unsigned long)zs32.zone_name;
5517 			zs.zone_root =
5518 			    (const char *)(unsigned long)zs32.zone_root;
5519 			zs.zone_privs =
5520 			    (const struct priv_set *)
5521 			    (unsigned long)zs32.zone_privs;
5522 			zs.zone_privssz = zs32.zone_privssz;
5523 			zs.rctlbuf = (caddr_t)(unsigned long)zs32.rctlbuf;
5524 			zs.rctlbufsz = zs32.rctlbufsz;
5525 			zs.zfsbuf = (caddr_t)(unsigned long)zs32.zfsbuf;
5526 			zs.zfsbufsz = zs32.zfsbufsz;
5527 			zs.extended_error =
5528 			    (int *)(unsigned long)zs32.extended_error;
5529 			zs.match = zs32.match;
5530 			zs.doi = zs32.doi;
5531 			zs.label = (const bslabel_t *)(uintptr_t)zs32.label;
5532 			zs.flags = zs32.flags;
5533 #else
5534 			panic("get_udatamodel() returned bogus result\n");
5535 #endif
5536 		}
5537 
5538 		return (zone_create(zs.zone_name, zs.zone_root,
5539 		    zs.zone_privs, zs.zone_privssz,
5540 		    (caddr_t)zs.rctlbuf, zs.rctlbufsz,
5541 		    (caddr_t)zs.zfsbuf, zs.zfsbufsz,
5542 		    zs.extended_error, zs.match, zs.doi,
5543 		    zs.label, zs.flags));
5544 	case ZONE_BOOT:
5545 		return (zone_boot((zoneid_t)(uintptr_t)arg1));
5546 	case ZONE_DESTROY:
5547 		return (zone_destroy((zoneid_t)(uintptr_t)arg1));
5548 	case ZONE_GETATTR:
5549 		return (zone_getattr((zoneid_t)(uintptr_t)arg1,
5550 		    (int)(uintptr_t)arg2, arg3, (size_t)arg4));
5551 	case ZONE_SETATTR:
5552 		return (zone_setattr((zoneid_t)(uintptr_t)arg1,
5553 		    (int)(uintptr_t)arg2, arg3, (size_t)arg4));
5554 	case ZONE_ENTER:
5555 		return (zone_enter((zoneid_t)(uintptr_t)arg1));
5556 	case ZONE_LIST:
5557 		return (zone_list((zoneid_t *)arg1, (uint_t *)arg2));
5558 	case ZONE_SHUTDOWN:
5559 		return (zone_shutdown((zoneid_t)(uintptr_t)arg1));
5560 	case ZONE_LOOKUP:
5561 		return (zone_lookup((const char *)arg1));
5562 	case ZONE_VERSION:
5563 		return (zone_version((int *)arg1));
5564 	case ZONE_ADD_DATALINK:
5565 		return (zone_add_datalink((zoneid_t)(uintptr_t)arg1,
5566 		    (datalink_id_t)(uintptr_t)arg2));
5567 	case ZONE_DEL_DATALINK:
5568 		return (zone_remove_datalink((zoneid_t)(uintptr_t)arg1,
5569 		    (datalink_id_t)(uintptr_t)arg2));
5570 	case ZONE_CHECK_DATALINK: {
5571 		zoneid_t	zoneid;
5572 		boolean_t	need_copyout;
5573 
5574 		if (copyin(arg1, &zoneid, sizeof (zoneid)) != 0)
5575 			return (EFAULT);
5576 		need_copyout = (zoneid == ALL_ZONES);
5577 		err = zone_check_datalink(&zoneid,
5578 		    (datalink_id_t)(uintptr_t)arg2);
5579 		if (err == 0 && need_copyout) {
5580 			if (copyout(&zoneid, arg1, sizeof (zoneid)) != 0)
5581 				err = EFAULT;
5582 		}
5583 		return (err == 0 ? 0 : set_errno(err));
5584 	}
5585 	case ZONE_LIST_DATALINK:
5586 		return (zone_list_datalink((zoneid_t)(uintptr_t)arg1,
5587 		    (int *)arg2, (datalink_id_t *)(uintptr_t)arg3));
5588 	default:
5589 		return (set_errno(EINVAL));
5590 	}
5591 }
5592 
5593 struct zarg {
5594 	zone_t *zone;
5595 	zone_cmd_arg_t arg;
5596 };
5597 
5598 static int
5599 zone_lookup_door(const char *zone_name, door_handle_t *doorp)
5600 {
5601 	char *buf;
5602 	size_t buflen;
5603 	int error;
5604 
5605 	buflen = sizeof (ZONE_DOOR_PATH) + strlen(zone_name);
5606 	buf = kmem_alloc(buflen, KM_SLEEP);
5607 	(void) snprintf(buf, buflen, ZONE_DOOR_PATH, zone_name);
5608 	error = door_ki_open(buf, doorp);
5609 	kmem_free(buf, buflen);
5610 	return (error);
5611 }
5612 
5613 static void
5614 zone_release_door(door_handle_t *doorp)
5615 {
5616 	door_ki_rele(*doorp);
5617 	*doorp = NULL;
5618 }
5619 
5620 static void
5621 zone_ki_call_zoneadmd(struct zarg *zargp)
5622 {
5623 	door_handle_t door = NULL;
5624 	door_arg_t darg, save_arg;
5625 	char *zone_name;
5626 	size_t zone_namelen;
5627 	zoneid_t zoneid;
5628 	zone_t *zone;
5629 	zone_cmd_arg_t arg;
5630 	uint64_t uniqid;
5631 	size_t size;
5632 	int error;
5633 	int retry;
5634 
5635 	zone = zargp->zone;
5636 	arg = zargp->arg;
5637 	kmem_free(zargp, sizeof (*zargp));
5638 
5639 	zone_namelen = strlen(zone->zone_name) + 1;
5640 	zone_name = kmem_alloc(zone_namelen, KM_SLEEP);
5641 	bcopy(zone->zone_name, zone_name, zone_namelen);
5642 	zoneid = zone->zone_id;
5643 	uniqid = zone->zone_uniqid;
5644 	/*
5645 	 * zoneadmd may be down, but at least we can empty out the zone.
5646 	 * We can ignore the return value of zone_empty() since we're called
5647 	 * from a kernel thread and know we won't be delivered any signals.
5648 	 */
5649 	ASSERT(curproc == &p0);
5650 	(void) zone_empty(zone);
5651 	ASSERT(zone_status_get(zone) >= ZONE_IS_EMPTY);
5652 	zone_rele(zone);
5653 
5654 	size = sizeof (arg);
5655 	darg.rbuf = (char *)&arg;
5656 	darg.data_ptr = (char *)&arg;
5657 	darg.rsize = size;
5658 	darg.data_size = size;
5659 	darg.desc_ptr = NULL;
5660 	darg.desc_num = 0;
5661 
5662 	save_arg = darg;
5663 	/*
5664 	 * Since we're not holding a reference to the zone, any number of
5665 	 * things can go wrong, including the zone disappearing before we get a
5666 	 * chance to talk to zoneadmd.
5667 	 */
5668 	for (retry = 0; /* forever */; retry++) {
5669 		if (door == NULL &&
5670 		    (error = zone_lookup_door(zone_name, &door)) != 0) {
5671 			goto next;
5672 		}
5673 		ASSERT(door != NULL);
5674 
5675 		if ((error = door_ki_upcall_limited(door, &darg, NULL,
5676 		    SIZE_MAX, 0)) == 0) {
5677 			break;
5678 		}
5679 		switch (error) {
5680 		case EINTR:
5681 			/* FALLTHROUGH */
5682 		case EAGAIN:	/* process may be forking */
5683 			/*
5684 			 * Back off for a bit
5685 			 */
5686 			break;
5687 		case EBADF:
5688 			zone_release_door(&door);
5689 			if (zone_lookup_door(zone_name, &door) != 0) {
5690 				/*
5691 				 * zoneadmd may be dead, but it may come back to
5692 				 * life later.
5693 				 */
5694 				break;
5695 			}
5696 			break;
5697 		default:
5698 			cmn_err(CE_WARN,
5699 			    "zone_ki_call_zoneadmd: door_ki_upcall error %d\n",
5700 			    error);
5701 			goto out;
5702 		}
5703 next:
5704 		/*
5705 		 * If this isn't the same zone_t that we originally had in mind,
5706 		 * then this is the same as if two kadmin requests come in at
5707 		 * the same time: the first one wins.  This means we lose, so we
5708 		 * bail.
5709 		 */
5710 		if ((zone = zone_find_by_id(zoneid)) == NULL) {
5711 			/*
5712 			 * Problem is solved.
5713 			 */
5714 			break;
5715 		}
5716 		if (zone->zone_uniqid != uniqid) {
5717 			/*
5718 			 * zoneid recycled
5719 			 */
5720 			zone_rele(zone);
5721 			break;
5722 		}
5723 		/*
5724 		 * We could zone_status_timedwait(), but there doesn't seem to
5725 		 * be much point in doing that (plus, it would mean that
5726 		 * zone_free() isn't called until this thread exits).
5727 		 */
5728 		zone_rele(zone);
5729 		delay(hz);
5730 		darg = save_arg;
5731 	}
5732 out:
5733 	if (door != NULL) {
5734 		zone_release_door(&door);
5735 	}
5736 	kmem_free(zone_name, zone_namelen);
5737 	thread_exit();
5738 }
5739 
5740 /*
5741  * Entry point for uadmin() to tell the zone to go away or reboot.  Analog to
5742  * kadmin().  The caller is a process in the zone.
5743  *
5744  * In order to shutdown the zone, we will hand off control to zoneadmd
5745  * (running in the global zone) via a door.  We do a half-hearted job at
5746  * killing all processes in the zone, create a kernel thread to contact
5747  * zoneadmd, and make note of the "uniqid" of the zone.  The uniqid is
5748  * a form of generation number used to let zoneadmd (as well as
5749  * zone_destroy()) know exactly which zone they're re talking about.
5750  */
5751 int
5752 zone_kadmin(int cmd, int fcn, const char *mdep, cred_t *credp)
5753 {
5754 	struct zarg *zargp;
5755 	zone_cmd_t zcmd;
5756 	zone_t *zone;
5757 
5758 	zone = curproc->p_zone;
5759 	ASSERT(getzoneid() != GLOBAL_ZONEID);
5760 
5761 	switch (cmd) {
5762 	case A_SHUTDOWN:
5763 		switch (fcn) {
5764 		case AD_HALT:
5765 		case AD_POWEROFF:
5766 			zcmd = Z_HALT;
5767 			break;
5768 		case AD_BOOT:
5769 			zcmd = Z_REBOOT;
5770 			break;
5771 		case AD_IBOOT:
5772 		case AD_SBOOT:
5773 		case AD_SIBOOT:
5774 		case AD_NOSYNC:
5775 			return (ENOTSUP);
5776 		default:
5777 			return (EINVAL);
5778 		}
5779 		break;
5780 	case A_REBOOT:
5781 		zcmd = Z_REBOOT;
5782 		break;
5783 	case A_FTRACE:
5784 	case A_REMOUNT:
5785 	case A_FREEZE:
5786 	case A_DUMP:
5787 	case A_CONFIG:
5788 		return (ENOTSUP);
5789 	default:
5790 		ASSERT(cmd != A_SWAPCTL);	/* handled by uadmin() */
5791 		return (EINVAL);
5792 	}
5793 
5794 	if (secpolicy_zone_admin(credp, B_FALSE))
5795 		return (EPERM);
5796 	mutex_enter(&zone_status_lock);
5797 
5798 	/*
5799 	 * zone_status can't be ZONE_IS_EMPTY or higher since curproc
5800 	 * is in the zone.
5801 	 */
5802 	ASSERT(zone_status_get(zone) < ZONE_IS_EMPTY);
5803 	if (zone_status_get(zone) > ZONE_IS_RUNNING) {
5804 		/*
5805 		 * This zone is already on its way down.
5806 		 */
5807 		mutex_exit(&zone_status_lock);
5808 		return (0);
5809 	}
5810 	/*
5811 	 * Prevent future zone_enter()s
5812 	 */
5813 	zone_status_set(zone, ZONE_IS_SHUTTING_DOWN);
5814 	mutex_exit(&zone_status_lock);
5815 
5816 	/*
5817 	 * Kill everyone now and call zoneadmd later.
5818 	 * zone_ki_call_zoneadmd() will do a more thorough job of this
5819 	 * later.
5820 	 */
5821 	killall(zone->zone_id);
5822 	/*
5823 	 * Now, create the thread to contact zoneadmd and do the rest of the
5824 	 * work.  This thread can't be created in our zone otherwise
5825 	 * zone_destroy() would deadlock.
5826 	 */
5827 	zargp = kmem_zalloc(sizeof (*zargp), KM_SLEEP);
5828 	zargp->arg.cmd = zcmd;
5829 	zargp->arg.uniqid = zone->zone_uniqid;
5830 	zargp->zone = zone;
5831 	(void) strcpy(zargp->arg.locale, "C");
5832 	/* mdep was already copied in for us by uadmin */
5833 	if (mdep != NULL)
5834 		(void) strlcpy(zargp->arg.bootbuf, mdep,
5835 		    sizeof (zargp->arg.bootbuf));
5836 	zone_hold(zone);
5837 
5838 	(void) thread_create(NULL, 0, zone_ki_call_zoneadmd, zargp, 0, &p0,
5839 	    TS_RUN, minclsyspri);
5840 	exit(CLD_EXITED, 0);
5841 
5842 	return (EINVAL);
5843 }
5844 
5845 /*
5846  * Entry point so kadmin(A_SHUTDOWN, ...) can set the global zone's
5847  * status to ZONE_IS_SHUTTING_DOWN.
5848  *
5849  * This function also shuts down all running zones to ensure that they won't
5850  * fork new processes.
5851  */
5852 void
5853 zone_shutdown_global(void)
5854 {
5855 	zone_t *current_zonep;
5856 
5857 	ASSERT(INGLOBALZONE(curproc));
5858 	mutex_enter(&zonehash_lock);
5859 	mutex_enter(&zone_status_lock);
5860 
5861 	/* Modify the global zone's status first. */
5862 	ASSERT(zone_status_get(global_zone) == ZONE_IS_RUNNING);
5863 	zone_status_set(global_zone, ZONE_IS_SHUTTING_DOWN);
5864 
5865 	/*
5866 	 * Now change the states of all running zones to ZONE_IS_SHUTTING_DOWN.
5867 	 * We don't mark all zones with ZONE_IS_SHUTTING_DOWN because doing so
5868 	 * could cause assertions to fail (e.g., assertions about a zone's
5869 	 * state during initialization, readying, or booting) or produce races.
5870 	 * We'll let threads continue to initialize and ready new zones: they'll
5871 	 * fail to boot the new zones when they see that the global zone is
5872 	 * shutting down.
5873 	 */
5874 	for (current_zonep = list_head(&zone_active); current_zonep != NULL;
5875 	    current_zonep = list_next(&zone_active, current_zonep)) {
5876 		if (zone_status_get(current_zonep) == ZONE_IS_RUNNING)
5877 			zone_status_set(current_zonep, ZONE_IS_SHUTTING_DOWN);
5878 	}
5879 	mutex_exit(&zone_status_lock);
5880 	mutex_exit(&zonehash_lock);
5881 }
5882 
5883 /*
5884  * Returns true if the named dataset is visible in the current zone.
5885  * The 'write' parameter is set to 1 if the dataset is also writable.
5886  */
5887 int
5888 zone_dataset_visible(const char *dataset, int *write)
5889 {
5890 	zone_dataset_t *zd;
5891 	size_t len;
5892 	zone_t *zone = curproc->p_zone;
5893 
5894 	if (dataset[0] == '\0')
5895 		return (0);
5896 
5897 	/*
5898 	 * Walk the list once, looking for datasets which match exactly, or
5899 	 * specify a dataset underneath an exported dataset.  If found, return
5900 	 * true and note that it is writable.
5901 	 */
5902 	for (zd = list_head(&zone->zone_datasets); zd != NULL;
5903 	    zd = list_next(&zone->zone_datasets, zd)) {
5904 
5905 		len = strlen(zd->zd_dataset);
5906 		if (strlen(dataset) >= len &&
5907 		    bcmp(dataset, zd->zd_dataset, len) == 0 &&
5908 		    (dataset[len] == '\0' || dataset[len] == '/' ||
5909 		    dataset[len] == '@')) {
5910 			if (write)
5911 				*write = 1;
5912 			return (1);
5913 		}
5914 	}
5915 
5916 	/*
5917 	 * Walk the list a second time, searching for datasets which are parents
5918 	 * of exported datasets.  These should be visible, but read-only.
5919 	 *
5920 	 * Note that we also have to support forms such as 'pool/dataset/', with
5921 	 * a trailing slash.
5922 	 */
5923 	for (zd = list_head(&zone->zone_datasets); zd != NULL;
5924 	    zd = list_next(&zone->zone_datasets, zd)) {
5925 
5926 		len = strlen(dataset);
5927 		if (dataset[len - 1] == '/')
5928 			len--;	/* Ignore trailing slash */
5929 		if (len < strlen(zd->zd_dataset) &&
5930 		    bcmp(dataset, zd->zd_dataset, len) == 0 &&
5931 		    zd->zd_dataset[len] == '/') {
5932 			if (write)
5933 				*write = 0;
5934 			return (1);
5935 		}
5936 	}
5937 
5938 	return (0);
5939 }
5940 
5941 /*
5942  * zone_find_by_any_path() -
5943  *
5944  * kernel-private routine similar to zone_find_by_path(), but which
5945  * effectively compares against zone paths rather than zonerootpath
5946  * (i.e., the last component of zonerootpaths, which should be "root/",
5947  * are not compared.)  This is done in order to accurately identify all
5948  * paths, whether zone-visible or not, including those which are parallel
5949  * to /root/, such as /dev/, /home/, etc...
5950  *
5951  * If the specified path does not fall under any zone path then global
5952  * zone is returned.
5953  *
5954  * The treat_abs parameter indicates whether the path should be treated as
5955  * an absolute path although it does not begin with "/".  (This supports
5956  * nfs mount syntax such as host:any/path.)
5957  *
5958  * The caller is responsible for zone_rele of the returned zone.
5959  */
5960 zone_t *
5961 zone_find_by_any_path(const char *path, boolean_t treat_abs)
5962 {
5963 	zone_t *zone;
5964 	int path_offset = 0;
5965 
5966 	if (path == NULL) {
5967 		zone_hold(global_zone);
5968 		return (global_zone);
5969 	}
5970 
5971 	if (*path != '/') {
5972 		ASSERT(treat_abs);
5973 		path_offset = 1;
5974 	}
5975 
5976 	mutex_enter(&zonehash_lock);
5977 	for (zone = list_head(&zone_active); zone != NULL;
5978 	    zone = list_next(&zone_active, zone)) {
5979 		char	*c;
5980 		size_t	pathlen;
5981 		char *rootpath_start;
5982 
5983 		if (zone == global_zone)	/* skip global zone */
5984 			continue;
5985 
5986 		/* scan backwards to find start of last component */
5987 		c = zone->zone_rootpath + zone->zone_rootpathlen - 2;
5988 		do {
5989 			c--;
5990 		} while (*c != '/');
5991 
5992 		pathlen = c - zone->zone_rootpath + 1 - path_offset;
5993 		rootpath_start = (zone->zone_rootpath + path_offset);
5994 		if (strncmp(path, rootpath_start, pathlen) == 0)
5995 			break;
5996 	}
5997 	if (zone == NULL)
5998 		zone = global_zone;
5999 	zone_hold(zone);
6000 	mutex_exit(&zonehash_lock);
6001 	return (zone);
6002 }
6003 
6004 /*
6005  * Finds a zone_dl_t with the given linkid in the given zone.  Returns the
6006  * zone_dl_t pointer if found, and NULL otherwise.
6007  */
6008 static zone_dl_t *
6009 zone_find_dl(zone_t *zone, datalink_id_t linkid)
6010 {
6011 	zone_dl_t *zdl;
6012 
6013 	ASSERT(mutex_owned(&zone->zone_lock));
6014 	for (zdl = list_head(&zone->zone_dl_list); zdl != NULL;
6015 	    zdl = list_next(&zone->zone_dl_list, zdl)) {
6016 		if (zdl->zdl_id == linkid)
6017 			break;
6018 	}
6019 	return (zdl);
6020 }
6021 
6022 static boolean_t
6023 zone_dl_exists(zone_t *zone, datalink_id_t linkid)
6024 {
6025 	boolean_t exists;
6026 
6027 	mutex_enter(&zone->zone_lock);
6028 	exists = (zone_find_dl(zone, linkid) != NULL);
6029 	mutex_exit(&zone->zone_lock);
6030 	return (exists);
6031 }
6032 
6033 /*
6034  * Add an data link name for the zone.
6035  */
6036 static int
6037 zone_add_datalink(zoneid_t zoneid, datalink_id_t linkid)
6038 {
6039 	zone_dl_t *zdl;
6040 	zone_t *zone;
6041 	zone_t *thiszone;
6042 
6043 	if ((thiszone = zone_find_by_id(zoneid)) == NULL)
6044 		return (set_errno(ENXIO));
6045 
6046 	/* Verify that the datalink ID doesn't already belong to a zone. */
6047 	mutex_enter(&zonehash_lock);
6048 	for (zone = list_head(&zone_active); zone != NULL;
6049 	    zone = list_next(&zone_active, zone)) {
6050 		if (zone_dl_exists(zone, linkid)) {
6051 			mutex_exit(&zonehash_lock);
6052 			zone_rele(thiszone);
6053 			return (set_errno((zone == thiszone) ? EEXIST : EPERM));
6054 		}
6055 	}
6056 
6057 	zdl = kmem_zalloc(sizeof (*zdl), KM_SLEEP);
6058 	zdl->zdl_id = linkid;
6059 	mutex_enter(&thiszone->zone_lock);
6060 	list_insert_head(&thiszone->zone_dl_list, zdl);
6061 	mutex_exit(&thiszone->zone_lock);
6062 	mutex_exit(&zonehash_lock);
6063 	zone_rele(thiszone);
6064 	return (0);
6065 }
6066 
6067 static int
6068 zone_remove_datalink(zoneid_t zoneid, datalink_id_t linkid)
6069 {
6070 	zone_dl_t *zdl;
6071 	zone_t *zone;
6072 	int err = 0;
6073 
6074 	if ((zone = zone_find_by_id(zoneid)) == NULL)
6075 		return (set_errno(EINVAL));
6076 
6077 	mutex_enter(&zone->zone_lock);
6078 	if ((zdl = zone_find_dl(zone, linkid)) == NULL) {
6079 		err = ENXIO;
6080 	} else {
6081 		list_remove(&zone->zone_dl_list, zdl);
6082 		kmem_free(zdl, sizeof (zone_dl_t));
6083 	}
6084 	mutex_exit(&zone->zone_lock);
6085 	zone_rele(zone);
6086 	return (err == 0 ? 0 : set_errno(err));
6087 }
6088 
6089 /*
6090  * Using the zoneidp as ALL_ZONES, we can lookup which zone has been assigned
6091  * the linkid.  Otherwise we just check if the specified zoneidp has been
6092  * assigned the supplied linkid.
6093  */
6094 int
6095 zone_check_datalink(zoneid_t *zoneidp, datalink_id_t linkid)
6096 {
6097 	zone_t *zone;
6098 	int err = ENXIO;
6099 
6100 	if (*zoneidp != ALL_ZONES) {
6101 		if ((zone = zone_find_by_id(*zoneidp)) != NULL) {
6102 			if (zone_dl_exists(zone, linkid))
6103 				err = 0;
6104 			zone_rele(zone);
6105 		}
6106 		return (err);
6107 	}
6108 
6109 	mutex_enter(&zonehash_lock);
6110 	for (zone = list_head(&zone_active); zone != NULL;
6111 	    zone = list_next(&zone_active, zone)) {
6112 		if (zone_dl_exists(zone, linkid)) {
6113 			*zoneidp = zone->zone_id;
6114 			err = 0;
6115 			break;
6116 		}
6117 	}
6118 	mutex_exit(&zonehash_lock);
6119 	return (err);
6120 }
6121 
6122 /*
6123  * Get the list of datalink IDs assigned to a zone.
6124  *
6125  * On input, *nump is the number of datalink IDs that can fit in the supplied
6126  * idarray.  Upon return, *nump is either set to the number of datalink IDs
6127  * that were placed in the array if the array was large enough, or to the
6128  * number of datalink IDs that the function needs to place in the array if the
6129  * array is too small.
6130  */
6131 static int
6132 zone_list_datalink(zoneid_t zoneid, int *nump, datalink_id_t *idarray)
6133 {
6134 	uint_t num, dlcount;
6135 	zone_t *zone;
6136 	zone_dl_t *zdl;
6137 	datalink_id_t *idptr = idarray;
6138 
6139 	if (copyin(nump, &dlcount, sizeof (dlcount)) != 0)
6140 		return (set_errno(EFAULT));
6141 	if ((zone = zone_find_by_id(zoneid)) == NULL)
6142 		return (set_errno(ENXIO));
6143 
6144 	num = 0;
6145 	mutex_enter(&zone->zone_lock);
6146 	for (zdl = list_head(&zone->zone_dl_list); zdl != NULL;
6147 	    zdl = list_next(&zone->zone_dl_list, zdl)) {
6148 		/*
6149 		 * If the list is bigger than what the caller supplied, just
6150 		 * count, don't do copyout.
6151 		 */
6152 		if (++num > dlcount)
6153 			continue;
6154 		if (copyout(&zdl->zdl_id, idptr, sizeof (*idptr)) != 0) {
6155 			mutex_exit(&zone->zone_lock);
6156 			zone_rele(zone);
6157 			return (set_errno(EFAULT));
6158 		}
6159 		idptr++;
6160 	}
6161 	mutex_exit(&zone->zone_lock);
6162 	zone_rele(zone);
6163 
6164 	/* Increased or decreased, caller should be notified. */
6165 	if (num != dlcount) {
6166 		if (copyout(&num, nump, sizeof (num)) != 0)
6167 			return (set_errno(EFAULT));
6168 	}
6169 	return (0);
6170 }
6171 
6172 /*
6173  * Public interface for looking up a zone by zoneid. It's a customized version
6174  * for netstack_zone_create(). It can only be called from the zsd create
6175  * callbacks, since it doesn't have reference on the zone structure hence if
6176  * it is called elsewhere the zone could disappear after the zonehash_lock
6177  * is dropped.
6178  *
6179  * Furthermore it
6180  * 1. Doesn't check the status of the zone.
6181  * 2. It will be called even before zone_init is called, in that case the
6182  *    address of zone0 is returned directly, and netstack_zone_create()
6183  *    will only assign a value to zone0.zone_netstack, won't break anything.
6184  * 3. Returns without the zone being held.
6185  */
6186 zone_t *
6187 zone_find_by_id_nolock(zoneid_t zoneid)
6188 {
6189 	zone_t *zone;
6190 
6191 	mutex_enter(&zonehash_lock);
6192 	if (zonehashbyid == NULL)
6193 		zone = &zone0;
6194 	else
6195 		zone = zone_find_all_by_id(zoneid);
6196 	mutex_exit(&zonehash_lock);
6197 	return (zone);
6198 }
6199 
6200 /*
6201  * Walk the datalinks for a given zone
6202  */
6203 int
6204 zone_datalink_walk(zoneid_t zoneid, int (*cb)(datalink_id_t, void *),
6205     void *data)
6206 {
6207 	zone_t		*zone;
6208 	zone_dl_t	*zdl;
6209 	datalink_id_t	*idarray;
6210 	uint_t		idcount = 0;
6211 	int		i, ret = 0;
6212 
6213 	if ((zone = zone_find_by_id(zoneid)) == NULL)
6214 		return (ENOENT);
6215 
6216 	/*
6217 	 * We first build an array of linkid's so that we can walk these and
6218 	 * execute the callback with the zone_lock dropped.
6219 	 */
6220 	mutex_enter(&zone->zone_lock);
6221 	for (zdl = list_head(&zone->zone_dl_list); zdl != NULL;
6222 	    zdl = list_next(&zone->zone_dl_list, zdl)) {
6223 		idcount++;
6224 	}
6225 
6226 	if (idcount == 0) {
6227 		mutex_exit(&zone->zone_lock);
6228 		zone_rele(zone);
6229 		return (0);
6230 	}
6231 
6232 	idarray = kmem_alloc(sizeof (datalink_id_t) * idcount, KM_NOSLEEP);
6233 	if (idarray == NULL) {
6234 		mutex_exit(&zone->zone_lock);
6235 		zone_rele(zone);
6236 		return (ENOMEM);
6237 	}
6238 
6239 	for (i = 0, zdl = list_head(&zone->zone_dl_list); zdl != NULL;
6240 	    i++, zdl = list_next(&zone->zone_dl_list, zdl)) {
6241 		idarray[i] = zdl->zdl_id;
6242 	}
6243 
6244 	mutex_exit(&zone->zone_lock);
6245 
6246 	for (i = 0; i < idcount && ret == 0; i++) {
6247 		if ((ret = (*cb)(idarray[i], data)) != 0)
6248 			break;
6249 	}
6250 
6251 	zone_rele(zone);
6252 	kmem_free(idarray, sizeof (datalink_id_t) * idcount);
6253 	return (ret);
6254 }
6255