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