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