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