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