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