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