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