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