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