xref: /illumos-gate/usr/src/uts/common/os/zone.c (revision 6a634c9d)
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  */
25 
26 /*
27  * Zones
28  *
29  *   A zone is a named collection of processes, namespace constraints,
30  *   and other system resources which comprise a secure and manageable
31  *   application containment facility.
32  *
33  *   Zones (represented by the reference counted zone_t) are tracked in
34  *   the kernel in the zonehash.  Elsewhere in the kernel, Zone IDs
35  *   (zoneid_t) are used to track zone association.  Zone IDs are
36  *   dynamically generated when the zone is created; if a persistent
37  *   identifier is needed (core files, accounting logs, audit trail,
38  *   etc.), the zone name should be used.
39  *
40  *
41  *   Global Zone:
42  *
43  *   The global zone (zoneid 0) is automatically associated with all
44  *   system resources that have not been bound to a user-created zone.
45  *   This means that even systems where zones are not in active use
46  *   have a global zone, and all processes, mounts, etc. are
47  *   associated with that zone.  The global zone is generally
48  *   unconstrained in terms of privileges and access, though the usual
49  *   credential and privilege based restrictions apply.
50  *
51  *
52  *   Zone States:
53  *
54  *   The states in which a zone may be in and the transitions are as
55  *   follows:
56  *
57  *   ZONE_IS_UNINITIALIZED: primordial state for a zone. The partially
58  *   initialized zone is added to the list of active zones on the system but
59  *   isn't accessible.
60  *
61  *   ZONE_IS_INITIALIZED: Initialization complete except the ZSD callbacks are
62  *   not yet completed. Not possible to enter the zone, but attributes can
63  *   be retrieved.
64  *
65  *   ZONE_IS_READY: zsched (the kernel dummy process for a zone) is
66  *   ready.  The zone is made visible after the ZSD constructor callbacks are
67  *   executed.  A zone remains in this state until it transitions into
68  *   the ZONE_IS_BOOTING state as a result of a call to zone_boot().
69  *
70  *   ZONE_IS_BOOTING: in this shortlived-state, zsched attempts to start
71  *   init.  Should that fail, the zone proceeds to the ZONE_IS_SHUTTING_DOWN
72  *   state.
73  *
74  *   ZONE_IS_RUNNING: The zone is open for business: zsched has
75  *   successfully started init.   A zone remains in this state until
76  *   zone_shutdown() is called.
77  *
78  *   ZONE_IS_SHUTTING_DOWN: zone_shutdown() has been called, the system is
79  *   killing all processes running in the zone. The zone remains
80  *   in this state until there are no more user processes running in the zone.
81  *   zone_create(), zone_enter(), and zone_destroy() on this zone will fail.
82  *   Since zone_shutdown() is restartable, it may be called successfully
83  *   multiple times for the same zone_t.  Setting of the zone's state to
84  *   ZONE_IS_SHUTTING_DOWN is synchronized with mounts, so VOP_MOUNT() may check
85  *   the zone's status without worrying about it being a moving target.
86  *
87  *   ZONE_IS_EMPTY: zone_shutdown() has been called, and there
88  *   are no more user processes in the zone.  The zone remains in this
89  *   state until there are no more kernel threads associated with the
90  *   zone.  zone_create(), zone_enter(), and zone_destroy() on this zone will
91  *   fail.
92  *
93  *   ZONE_IS_DOWN: All kernel threads doing work on behalf of the zone
94  *   have exited.  zone_shutdown() returns.  Henceforth it is not possible to
95  *   join the zone or create kernel threads therein.
96  *
97  *   ZONE_IS_DYING: zone_destroy() has been called on the zone; zone
98  *   remains in this state until zsched exits.  Calls to zone_find_by_*()
99  *   return NULL from now on.
100  *
101  *   ZONE_IS_DEAD: zsched has exited (zone_ntasks == 0).  There are no
102  *   processes or threads doing work on behalf of the zone.  The zone is
103  *   removed from the list of active zones.  zone_destroy() returns, and
104  *   the zone can be recreated.
105  *
106  *   ZONE_IS_FREE (internal state): zone_ref goes to 0, ZSD destructor
107  *   callbacks are executed, and all memory associated with the zone is
108  *   freed.
109  *
110  *   Threads can wait for the zone to enter a requested state by using
111  *   zone_status_wait() or zone_status_timedwait() with the desired
112  *   state passed in as an argument.  Zone state transitions are
113  *   uni-directional; it is not possible to move back to an earlier state.
114  *
115  *
116  *   Zone-Specific Data:
117  *
118  *   Subsystems needing to maintain zone-specific data can store that
119  *   data using the ZSD mechanism.  This provides a zone-specific data
120  *   store, similar to thread-specific data (see pthread_getspecific(3C)
121  *   or the TSD code in uts/common/disp/thread.c.  Also, ZSD can be used
122  *   to register callbacks to be invoked when a zone is created, shut
123  *   down, or destroyed.  This can be used to initialize zone-specific
124  *   data for new zones and to clean up when zones go away.
125  *
126  *
127  *   Data Structures:
128  *
129  *   The per-zone structure (zone_t) is reference counted, and freed
130  *   when all references are released.  zone_hold and zone_rele can be
131  *   used to adjust the reference count.  In addition, reference counts
132  *   associated with the cred_t structure are tracked separately using
133  *   zone_cred_hold and zone_cred_rele.
134  *
135  *   Pointers to active zone_t's are stored in two hash tables; one
136  *   for searching by id, the other for searching by name.  Lookups
137  *   can be performed on either basis, using zone_find_by_id and
138  *   zone_find_by_name.  Both return zone_t pointers with the zone
139  *   held, so zone_rele should be called when the pointer is no longer
140  *   needed.  Zones can also be searched by path; zone_find_by_path
141  *   returns the zone with which a path name is associated (global
142  *   zone if the path is not within some other zone's file system
143  *   hierarchy).  This currently requires iterating through each zone,
144  *   so it is slower than an id or name search via a hash table.
145  *
146  *
147  *   Locking:
148  *
149  *   zonehash_lock: This is a top-level global lock used to protect the
150  *       zone hash tables and lists.  Zones cannot be created or destroyed
151  *       while this lock is held.
152  *   zone_status_lock: This is a global lock protecting zone state.
153  *       Zones cannot change state while this lock is held.  It also
154  *       protects the list of kernel threads associated with a zone.
155  *   zone_lock: This is a per-zone lock used to protect several fields of
156  *       the zone_t (see <sys/zone.h> for details).  In addition, holding
157  *       this lock means that the zone cannot go away.
158  *   zone_nlwps_lock: This is a per-zone lock used to protect the fields
159  *	 related to the zone.max-lwps rctl.
160  *   zone_mem_lock: This is a per-zone lock used to protect the fields
161  *	 related to the zone.max-locked-memory and zone.max-swap rctls.
162  *   zone_rctl_lock: This is a per-zone lock used to protect other rctls,
163  *       currently just max_lofi
164  *   zsd_key_lock: This is a global lock protecting the key state for ZSD.
165  *   zone_deathrow_lock: This is a global lock protecting the "deathrow"
166  *       list (a list of zones in the ZONE_IS_DEAD state).
167  *
168  *   Ordering requirements:
169  *       pool_lock --> cpu_lock --> zonehash_lock --> zone_status_lock -->
170  *       	zone_lock --> zsd_key_lock --> pidlock --> p_lock
171  *
172  *   When taking zone_mem_lock or zone_nlwps_lock, the lock ordering is:
173  *	zonehash_lock --> a_lock --> pidlock --> p_lock --> zone_mem_lock
174  *	zonehash_lock --> a_lock --> pidlock --> p_lock --> zone_nlwps_lock
175  *
176  *   Blocking memory allocations are permitted while holding any of the
177  *   zone locks.
178  *
179  *
180  *   System Call Interface:
181  *
182  *   The zone subsystem can be managed and queried from user level with
183  *   the following system calls (all subcodes of the primary "zone"
184  *   system call):
185  *   - zone_create: creates a zone with selected attributes (name,
186  *     root path, privileges, resource controls, ZFS datasets)
187  *   - zone_enter: allows the current process to enter a zone
188  *   - zone_getattr: reports attributes of a zone
189  *   - zone_setattr: set attributes of a zone
190  *   - zone_boot: set 'init' running for the zone
191  *   - zone_list: lists all zones active in the system
192  *   - zone_lookup: looks up zone id based on name
193  *   - zone_shutdown: initiates shutdown process (see states above)
194  *   - zone_destroy: completes shutdown process (see states above)
195  *
196  */
197 
198 #include <sys/priv_impl.h>
199 #include <sys/cred.h>
200 #include <c2/audit.h>
201 #include <sys/debug.h>
202 #include <sys/file.h>
203 #include <sys/kmem.h>
204 #include <sys/kstat.h>
205 #include <sys/mutex.h>
206 #include <sys/note.h>
207 #include <sys/pathname.h>
208 #include <sys/proc.h>
209 #include <sys/project.h>
210 #include <sys/sysevent.h>
211 #include <sys/task.h>
212 #include <sys/systm.h>
213 #include <sys/types.h>
214 #include <sys/utsname.h>
215 #include <sys/vnode.h>
216 #include <sys/vfs.h>
217 #include <sys/systeminfo.h>
218 #include <sys/policy.h>
219 #include <sys/cred_impl.h>
220 #include <sys/contract_impl.h>
221 #include <sys/contract/process_impl.h>
222 #include <sys/class.h>
223 #include <sys/pool.h>
224 #include <sys/pool_pset.h>
225 #include <sys/pset.h>
226 #include <sys/strlog.h>
227 #include <sys/sysmacros.h>
228 #include <sys/callb.h>
229 #include <sys/vmparam.h>
230 #include <sys/corectl.h>
231 #include <sys/ipc_impl.h>
232 #include <sys/klpd.h>
233 
234 #include <sys/door.h>
235 #include <sys/cpuvar.h>
236 #include <sys/sdt.h>
237 
238 #include <sys/uadmin.h>
239 #include <sys/session.h>
240 #include <sys/cmn_err.h>
241 #include <sys/modhash.h>
242 #include <sys/sunddi.h>
243 #include <sys/nvpair.h>
244 #include <sys/rctl.h>
245 #include <sys/fss.h>
246 #include <sys/brand.h>
247 #include <sys/zone.h>
248 #include <net/if.h>
249 #include <sys/cpucaps.h>
250 #include <vm/seg.h>
251 #include <sys/mac.h>
252 
253 /*
254  * This constant specifies the number of seconds that threads waiting for
255  * subsystems to release a zone's general-purpose references will wait before
256  * they log the zone's reference counts.  The constant's value shouldn't
257  * be so small that reference counts are unnecessarily reported for zones
258  * whose references are slowly released.  On the other hand, it shouldn't be so
259  * large that users reboot their systems out of frustration over hung zones
260  * before the system logs the zones' reference counts.
261  */
262 #define	ZONE_DESTROY_TIMEOUT_SECS	60
263 
264 /* List of data link IDs which are accessible from the zone */
265 typedef struct zone_dl {
266 	datalink_id_t	zdl_id;
267 	nvlist_t	*zdl_net;
268 	list_node_t	zdl_linkage;
269 } zone_dl_t;
270 
271 /*
272  * cv used to signal that all references to the zone have been released.  This
273  * needs to be global since there may be multiple waiters, and the first to
274  * wake up will free the zone_t, hence we cannot use zone->zone_cv.
275  */
276 static kcondvar_t zone_destroy_cv;
277 /*
278  * Lock used to serialize access to zone_cv.  This could have been per-zone,
279  * but then we'd need another lock for zone_destroy_cv, and why bother?
280  */
281 static kmutex_t zone_status_lock;
282 
283 /*
284  * ZSD-related global variables.
285  */
286 static kmutex_t zsd_key_lock;	/* protects the following two */
287 /*
288  * The next caller of zone_key_create() will be assigned a key of ++zsd_keyval.
289  */
290 static zone_key_t zsd_keyval = 0;
291 /*
292  * Global list of registered keys.  We use this when a new zone is created.
293  */
294 static list_t zsd_registered_keys;
295 
296 int zone_hash_size = 256;
297 static mod_hash_t *zonehashbyname, *zonehashbyid, *zonehashbylabel;
298 static kmutex_t zonehash_lock;
299 static uint_t zonecount;
300 static id_space_t *zoneid_space;
301 
302 /*
303  * The global zone (aka zone0) is the all-seeing, all-knowing zone in which the
304  * kernel proper runs, and which manages all other zones.
305  *
306  * Although not declared as static, the variable "zone0" should not be used
307  * except for by code that needs to reference the global zone early on in boot,
308  * before it is fully initialized.  All other consumers should use
309  * 'global_zone'.
310  */
311 zone_t zone0;
312 zone_t *global_zone = NULL;	/* Set when the global zone is initialized */
313 
314 /*
315  * List of active zones, protected by zonehash_lock.
316  */
317 static list_t zone_active;
318 
319 /*
320  * List of destroyed zones that still have outstanding cred references.
321  * Used for debugging.  Uses a separate lock to avoid lock ordering
322  * problems in zone_free.
323  */
324 static list_t zone_deathrow;
325 static kmutex_t zone_deathrow_lock;
326 
327 /* number of zones is limited by virtual interface limit in IP */
328 uint_t maxzones = 8192;
329 
330 /* Event channel to sent zone state change notifications */
331 evchan_t *zone_event_chan;
332 
333 /*
334  * This table holds the mapping from kernel zone states to
335  * states visible in the state notification API.
336  * The idea is that we only expose "obvious" states and
337  * do not expose states which are just implementation details.
338  */
339 const char  *zone_status_table[] = {
340 	ZONE_EVENT_UNINITIALIZED,	/* uninitialized */
341 	ZONE_EVENT_INITIALIZED,		/* initialized */
342 	ZONE_EVENT_READY,		/* ready */
343 	ZONE_EVENT_READY,		/* booting */
344 	ZONE_EVENT_RUNNING,		/* running */
345 	ZONE_EVENT_SHUTTING_DOWN,	/* shutting_down */
346 	ZONE_EVENT_SHUTTING_DOWN,	/* empty */
347 	ZONE_EVENT_SHUTTING_DOWN,	/* down */
348 	ZONE_EVENT_SHUTTING_DOWN,	/* dying */
349 	ZONE_EVENT_UNINITIALIZED,	/* dead */
350 };
351 
352 /*
353  * This array contains the names of the subsystems listed in zone_ref_subsys_t
354  * (see sys/zone.h).
355  */
356 static char *zone_ref_subsys_names[] = {
357 	"NFS",		/* ZONE_REF_NFS */
358 	"NFSv4",	/* ZONE_REF_NFSV4 */
359 	"SMBFS",	/* ZONE_REF_SMBFS */
360 	"MNTFS",	/* ZONE_REF_MNTFS */
361 	"LOFI",		/* ZONE_REF_LOFI */
362 	"VFS",		/* ZONE_REF_VFS */
363 	"IPC"		/* ZONE_REF_IPC */
364 };
365 
366 /*
367  * This isn't static so lint doesn't complain.
368  */
369 rctl_hndl_t rc_zone_cpu_shares;
370 rctl_hndl_t rc_zone_locked_mem;
371 rctl_hndl_t rc_zone_max_swap;
372 rctl_hndl_t rc_zone_max_lofi;
373 rctl_hndl_t rc_zone_cpu_cap;
374 rctl_hndl_t rc_zone_nlwps;
375 rctl_hndl_t rc_zone_nprocs;
376 rctl_hndl_t rc_zone_shmmax;
377 rctl_hndl_t rc_zone_shmmni;
378 rctl_hndl_t rc_zone_semmni;
379 rctl_hndl_t rc_zone_msgmni;
380 /*
381  * Synchronization primitives used to synchronize between mounts and zone
382  * creation/destruction.
383  */
384 static int mounts_in_progress;
385 static kcondvar_t mount_cv;
386 static kmutex_t mount_lock;
387 
388 const char * const zone_default_initname = "/sbin/init";
389 static char * const zone_prefix = "/zone/";
390 static int zone_shutdown(zoneid_t zoneid);
391 static int zone_add_datalink(zoneid_t, datalink_id_t);
392 static int zone_remove_datalink(zoneid_t, datalink_id_t);
393 static int zone_list_datalink(zoneid_t, int *, datalink_id_t *);
394 static int zone_set_network(zoneid_t, zone_net_data_t *);
395 static int zone_get_network(zoneid_t, zone_net_data_t *);
396 
397 typedef boolean_t zsd_applyfn_t(kmutex_t *, boolean_t, zone_t *, zone_key_t);
398 
399 static void zsd_apply_all_zones(zsd_applyfn_t *, zone_key_t);
400 static void zsd_apply_all_keys(zsd_applyfn_t *, zone_t *);
401 static boolean_t zsd_apply_create(kmutex_t *, boolean_t, zone_t *, zone_key_t);
402 static boolean_t zsd_apply_shutdown(kmutex_t *, boolean_t, zone_t *,
403     zone_key_t);
404 static boolean_t zsd_apply_destroy(kmutex_t *, boolean_t, zone_t *, zone_key_t);
405 static boolean_t zsd_wait_for_creator(zone_t *, struct zsd_entry *,
406     kmutex_t *);
407 static boolean_t zsd_wait_for_inprogress(zone_t *, struct zsd_entry *,
408     kmutex_t *);
409 
410 /*
411  * Bump this number when you alter the zone syscall interfaces; this is
412  * because we need to have support for previous API versions in libc
413  * to support patching; libc calls into the kernel to determine this number.
414  *
415  * Version 1 of the API is the version originally shipped with Solaris 10
416  * Version 2 alters the zone_create system call in order to support more
417  *     arguments by moving the args into a structure; and to do better
418  *     error reporting when zone_create() fails.
419  * Version 3 alters the zone_create system call in order to support the
420  *     import of ZFS datasets to zones.
421  * Version 4 alters the zone_create system call in order to support
422  *     Trusted Extensions.
423  * Version 5 alters the zone_boot system call, and converts its old
424  *     bootargs parameter to be set by the zone_setattr API instead.
425  * Version 6 adds the flag argument to zone_create.
426  */
427 static const int ZONE_SYSCALL_API_VERSION = 6;
428 
429 /*
430  * Certain filesystems (such as NFS and autofs) need to know which zone
431  * the mount is being placed in.  Because of this, we need to be able to
432  * ensure that a zone isn't in the process of being created such that
433  * nfs_mount() thinks it is in the global zone, while by the time it
434  * gets added the list of mounted zones, it ends up on zoneA's mount
435  * list.
436  *
437  * The following functions: block_mounts()/resume_mounts() and
438  * mount_in_progress()/mount_completed() are used by zones and the VFS
439  * layer (respectively) to synchronize zone creation and new mounts.
440  *
441  * The semantics are like a reader-reader lock such that there may
442  * either be multiple mounts (or zone creations, if that weren't
443  * serialized by zonehash_lock) in progress at the same time, but not
444  * both.
445  *
446  * We use cv's so the user can ctrl-C out of the operation if it's
447  * taking too long.
448  *
449  * The semantics are such that there is unfair bias towards the
450  * "current" operation.  This means that zone creations may starve if
451  * there is a rapid succession of new mounts coming in to the system, or
452  * there is a remote possibility that zones will be created at such a
453  * rate that new mounts will not be able to proceed.
454  */
455 /*
456  * Prevent new mounts from progressing to the point of calling
457  * VFS_MOUNT().  If there are already mounts in this "region", wait for
458  * them to complete.
459  */
460 static int
461 block_mounts(void)
462 {
463 	int retval = 0;
464 
465 	/*
466 	 * Since it may block for a long time, block_mounts() shouldn't be
467 	 * called with zonehash_lock held.
468 	 */
469 	ASSERT(MUTEX_NOT_HELD(&zonehash_lock));
470 	mutex_enter(&mount_lock);
471 	while (mounts_in_progress > 0) {
472 		if (cv_wait_sig(&mount_cv, &mount_lock) == 0)
473 			goto signaled;
474 	}
475 	/*
476 	 * A negative value of mounts_in_progress indicates that mounts
477 	 * have been blocked by (-mounts_in_progress) different callers.
478 	 */
479 	mounts_in_progress--;
480 	retval = 1;
481 signaled:
482 	mutex_exit(&mount_lock);
483 	return (retval);
484 }
485 
486 /*
487  * The VFS layer may progress with new mounts as far as we're concerned.
488  * Allow them to progress if we were the last obstacle.
489  */
490 static void
491 resume_mounts(void)
492 {
493 	mutex_enter(&mount_lock);
494 	if (++mounts_in_progress == 0)
495 		cv_broadcast(&mount_cv);
496 	mutex_exit(&mount_lock);
497 }
498 
499 /*
500  * The VFS layer is busy with a mount; zones should wait until all
501  * mounts are completed to progress.
502  */
503 void
504 mount_in_progress(void)
505 {
506 	mutex_enter(&mount_lock);
507 	while (mounts_in_progress < 0)
508 		cv_wait(&mount_cv, &mount_lock);
509 	mounts_in_progress++;
510 	mutex_exit(&mount_lock);
511 }
512 
513 /*
514  * VFS is done with one mount; wake up any waiting block_mounts()
515  * callers if this is the last mount.
516  */
517 void
518 mount_completed(void)
519 {
520 	mutex_enter(&mount_lock);
521 	if (--mounts_in_progress == 0)
522 		cv_broadcast(&mount_cv);
523 	mutex_exit(&mount_lock);
524 }
525 
526 /*
527  * ZSD routines.
528  *
529  * Zone Specific Data (ZSD) is modeled after Thread Specific Data as
530  * defined by the pthread_key_create() and related interfaces.
531  *
532  * Kernel subsystems may register one or more data items and/or
533  * callbacks to be executed when a zone is created, shutdown, or
534  * destroyed.
535  *
536  * Unlike the thread counterpart, destructor callbacks will be executed
537  * even if the data pointer is NULL and/or there are no constructor
538  * callbacks, so it is the responsibility of such callbacks to check for
539  * NULL data values if necessary.
540  *
541  * The locking strategy and overall picture is as follows:
542  *
543  * When someone calls zone_key_create(), a template ZSD entry is added to the
544  * global list "zsd_registered_keys", protected by zsd_key_lock.  While
545  * holding that lock all the existing zones are marked as
546  * ZSD_CREATE_NEEDED and a copy of the ZSD entry added to the per-zone
547  * zone_zsd list (protected by zone_lock). The global list is updated first
548  * (under zone_key_lock) to make sure that newly created zones use the
549  * most recent list of keys. Then under zonehash_lock we walk the zones
550  * and mark them.  Similar locking is used in zone_key_delete().
551  *
552  * The actual create, shutdown, and destroy callbacks are done without
553  * holding any lock. And zsd_flags are used to ensure that the operations
554  * completed so that when zone_key_create (and zone_create) is done, as well as
555  * zone_key_delete (and zone_destroy) is done, all the necessary callbacks
556  * are completed.
557  *
558  * When new zones are created constructor callbacks for all registered ZSD
559  * entries will be called. That also uses the above two phases of marking
560  * what needs to be done, and then running the callbacks without holding
561  * any locks.
562  *
563  * The framework does not provide any locking around zone_getspecific() and
564  * zone_setspecific() apart from that needed for internal consistency, so
565  * callers interested in atomic "test-and-set" semantics will need to provide
566  * their own locking.
567  */
568 
569 /*
570  * Helper function to find the zsd_entry associated with the key in the
571  * given list.
572  */
573 static struct zsd_entry *
574 zsd_find(list_t *l, zone_key_t key)
575 {
576 	struct zsd_entry *zsd;
577 
578 	for (zsd = list_head(l); zsd != NULL; zsd = list_next(l, zsd)) {
579 		if (zsd->zsd_key == key) {
580 			return (zsd);
581 		}
582 	}
583 	return (NULL);
584 }
585 
586 /*
587  * Helper function to find the zsd_entry associated with the key in the
588  * given list. Move it to the front of the list.
589  */
590 static struct zsd_entry *
591 zsd_find_mru(list_t *l, zone_key_t key)
592 {
593 	struct zsd_entry *zsd;
594 
595 	for (zsd = list_head(l); zsd != NULL; zsd = list_next(l, zsd)) {
596 		if (zsd->zsd_key == key) {
597 			/*
598 			 * Move to head of list to keep list in MRU order.
599 			 */
600 			if (zsd != list_head(l)) {
601 				list_remove(l, zsd);
602 				list_insert_head(l, zsd);
603 			}
604 			return (zsd);
605 		}
606 	}
607 	return (NULL);
608 }
609 
610 void
611 zone_key_create(zone_key_t *keyp, void *(*create)(zoneid_t),
612     void (*shutdown)(zoneid_t, void *), void (*destroy)(zoneid_t, void *))
613 {
614 	struct zsd_entry *zsdp;
615 	struct zsd_entry *t;
616 	struct zone *zone;
617 	zone_key_t  key;
618 
619 	zsdp = kmem_zalloc(sizeof (*zsdp), KM_SLEEP);
620 	zsdp->zsd_data = NULL;
621 	zsdp->zsd_create = create;
622 	zsdp->zsd_shutdown = shutdown;
623 	zsdp->zsd_destroy = destroy;
624 
625 	/*
626 	 * Insert in global list of callbacks. Makes future zone creations
627 	 * see it.
628 	 */
629 	mutex_enter(&zsd_key_lock);
630 	key = zsdp->zsd_key = ++zsd_keyval;
631 	ASSERT(zsd_keyval != 0);
632 	list_insert_tail(&zsd_registered_keys, zsdp);
633 	mutex_exit(&zsd_key_lock);
634 
635 	/*
636 	 * Insert for all existing zones and mark them as needing
637 	 * a create callback.
638 	 */
639 	mutex_enter(&zonehash_lock);	/* stop the world */
640 	for (zone = list_head(&zone_active); zone != NULL;
641 	    zone = list_next(&zone_active, zone)) {
642 		zone_status_t status;
643 
644 		mutex_enter(&zone->zone_lock);
645 
646 		/* Skip zones that are on the way down or not yet up */
647 		status = zone_status_get(zone);
648 		if (status >= ZONE_IS_DOWN ||
649 		    status == ZONE_IS_UNINITIALIZED) {
650 			mutex_exit(&zone->zone_lock);
651 			continue;
652 		}
653 
654 		t = zsd_find_mru(&zone->zone_zsd, key);
655 		if (t != NULL) {
656 			/*
657 			 * A zsd_configure already inserted it after
658 			 * we dropped zsd_key_lock above.
659 			 */
660 			mutex_exit(&zone->zone_lock);
661 			continue;
662 		}
663 		t = kmem_zalloc(sizeof (*t), KM_SLEEP);
664 		t->zsd_key = key;
665 		t->zsd_create = create;
666 		t->zsd_shutdown = shutdown;
667 		t->zsd_destroy = destroy;
668 		if (create != NULL) {
669 			t->zsd_flags = ZSD_CREATE_NEEDED;
670 			DTRACE_PROBE2(zsd__create__needed,
671 			    zone_t *, zone, zone_key_t, key);
672 		}
673 		list_insert_tail(&zone->zone_zsd, t);
674 		mutex_exit(&zone->zone_lock);
675 	}
676 	mutex_exit(&zonehash_lock);
677 
678 	if (create != NULL) {
679 		/* Now call the create callback for this key */
680 		zsd_apply_all_zones(zsd_apply_create, key);
681 	}
682 	/*
683 	 * It is safe for consumers to use the key now, make it
684 	 * globally visible. Specifically zone_getspecific() will
685 	 * always successfully return the zone specific data associated
686 	 * with the key.
687 	 */
688 	*keyp = key;
689 
690 }
691 
692 /*
693  * Function called when a module is being unloaded, or otherwise wishes
694  * to unregister its ZSD key and callbacks.
695  *
696  * Remove from the global list and determine the functions that need to
697  * be called under a global lock. Then call the functions without
698  * holding any locks. Finally free up the zone_zsd entries. (The apply
699  * functions need to access the zone_zsd entries to find zsd_data etc.)
700  */
701 int
702 zone_key_delete(zone_key_t key)
703 {
704 	struct zsd_entry *zsdp = NULL;
705 	zone_t *zone;
706 
707 	mutex_enter(&zsd_key_lock);
708 	zsdp = zsd_find_mru(&zsd_registered_keys, key);
709 	if (zsdp == NULL) {
710 		mutex_exit(&zsd_key_lock);
711 		return (-1);
712 	}
713 	list_remove(&zsd_registered_keys, zsdp);
714 	mutex_exit(&zsd_key_lock);
715 
716 	mutex_enter(&zonehash_lock);
717 	for (zone = list_head(&zone_active); zone != NULL;
718 	    zone = list_next(&zone_active, zone)) {
719 		struct zsd_entry *del;
720 
721 		mutex_enter(&zone->zone_lock);
722 		del = zsd_find_mru(&zone->zone_zsd, key);
723 		if (del == NULL) {
724 			/*
725 			 * Somebody else got here first e.g the zone going
726 			 * away.
727 			 */
728 			mutex_exit(&zone->zone_lock);
729 			continue;
730 		}
731 		ASSERT(del->zsd_shutdown == zsdp->zsd_shutdown);
732 		ASSERT(del->zsd_destroy == zsdp->zsd_destroy);
733 		if (del->zsd_shutdown != NULL &&
734 		    (del->zsd_flags & ZSD_SHUTDOWN_ALL) == 0) {
735 			del->zsd_flags |= ZSD_SHUTDOWN_NEEDED;
736 			DTRACE_PROBE2(zsd__shutdown__needed,
737 			    zone_t *, zone, zone_key_t, key);
738 		}
739 		if (del->zsd_destroy != NULL &&
740 		    (del->zsd_flags & ZSD_DESTROY_ALL) == 0) {
741 			del->zsd_flags |= ZSD_DESTROY_NEEDED;
742 			DTRACE_PROBE2(zsd__destroy__needed,
743 			    zone_t *, zone, zone_key_t, key);
744 		}
745 		mutex_exit(&zone->zone_lock);
746 	}
747 	mutex_exit(&zonehash_lock);
748 	kmem_free(zsdp, sizeof (*zsdp));
749 
750 	/* Now call the shutdown and destroy callback for this key */
751 	zsd_apply_all_zones(zsd_apply_shutdown, key);
752 	zsd_apply_all_zones(zsd_apply_destroy, key);
753 
754 	/* Now we can free up the zsdp structures in each zone */
755 	mutex_enter(&zonehash_lock);
756 	for (zone = list_head(&zone_active); zone != NULL;
757 	    zone = list_next(&zone_active, zone)) {
758 		struct zsd_entry *del;
759 
760 		mutex_enter(&zone->zone_lock);
761 		del = zsd_find(&zone->zone_zsd, key);
762 		if (del != NULL) {
763 			list_remove(&zone->zone_zsd, del);
764 			ASSERT(!(del->zsd_flags & ZSD_ALL_INPROGRESS));
765 			kmem_free(del, sizeof (*del));
766 		}
767 		mutex_exit(&zone->zone_lock);
768 	}
769 	mutex_exit(&zonehash_lock);
770 
771 	return (0);
772 }
773 
774 /*
775  * ZSD counterpart of pthread_setspecific().
776  *
777  * Since all zsd callbacks, including those with no create function,
778  * have an entry in zone_zsd, if the key is registered it is part of
779  * the zone_zsd list.
780  * Return an error if the key wasn't registerd.
781  */
782 int
783 zone_setspecific(zone_key_t key, zone_t *zone, const void *data)
784 {
785 	struct zsd_entry *t;
786 
787 	mutex_enter(&zone->zone_lock);
788 	t = zsd_find_mru(&zone->zone_zsd, key);
789 	if (t != NULL) {
790 		/*
791 		 * Replace old value with new
792 		 */
793 		t->zsd_data = (void *)data;
794 		mutex_exit(&zone->zone_lock);
795 		return (0);
796 	}
797 	mutex_exit(&zone->zone_lock);
798 	return (-1);
799 }
800 
801 /*
802  * ZSD counterpart of pthread_getspecific().
803  */
804 void *
805 zone_getspecific(zone_key_t key, zone_t *zone)
806 {
807 	struct zsd_entry *t;
808 	void *data;
809 
810 	mutex_enter(&zone->zone_lock);
811 	t = zsd_find_mru(&zone->zone_zsd, key);
812 	data = (t == NULL ? NULL : t->zsd_data);
813 	mutex_exit(&zone->zone_lock);
814 	return (data);
815 }
816 
817 /*
818  * Function used to initialize a zone's list of ZSD callbacks and data
819  * when the zone is being created.  The callbacks are initialized from
820  * the template list (zsd_registered_keys). The constructor callback is
821  * executed later (once the zone exists and with locks dropped).
822  */
823 static void
824 zone_zsd_configure(zone_t *zone)
825 {
826 	struct zsd_entry *zsdp;
827 	struct zsd_entry *t;
828 
829 	ASSERT(MUTEX_HELD(&zonehash_lock));
830 	ASSERT(list_head(&zone->zone_zsd) == NULL);
831 	mutex_enter(&zone->zone_lock);
832 	mutex_enter(&zsd_key_lock);
833 	for (zsdp = list_head(&zsd_registered_keys); zsdp != NULL;
834 	    zsdp = list_next(&zsd_registered_keys, zsdp)) {
835 		/*
836 		 * Since this zone is ZONE_IS_UNCONFIGURED, zone_key_create
837 		 * should not have added anything to it.
838 		 */
839 		ASSERT(zsd_find(&zone->zone_zsd, zsdp->zsd_key) == NULL);
840 
841 		t = kmem_zalloc(sizeof (*t), KM_SLEEP);
842 		t->zsd_key = zsdp->zsd_key;
843 		t->zsd_create = zsdp->zsd_create;
844 		t->zsd_shutdown = zsdp->zsd_shutdown;
845 		t->zsd_destroy = zsdp->zsd_destroy;
846 		if (zsdp->zsd_create != NULL) {
847 			t->zsd_flags = ZSD_CREATE_NEEDED;
848 			DTRACE_PROBE2(zsd__create__needed,
849 			    zone_t *, zone, zone_key_t, zsdp->zsd_key);
850 		}
851 		list_insert_tail(&zone->zone_zsd, t);
852 	}
853 	mutex_exit(&zsd_key_lock);
854 	mutex_exit(&zone->zone_lock);
855 }
856 
857 enum zsd_callback_type { ZSD_CREATE, ZSD_SHUTDOWN, ZSD_DESTROY };
858 
859 /*
860  * Helper function to execute shutdown or destructor callbacks.
861  */
862 static void
863 zone_zsd_callbacks(zone_t *zone, enum zsd_callback_type ct)
864 {
865 	struct zsd_entry *t;
866 
867 	ASSERT(ct == ZSD_SHUTDOWN || ct == ZSD_DESTROY);
868 	ASSERT(ct != ZSD_SHUTDOWN || zone_status_get(zone) >= ZONE_IS_EMPTY);
869 	ASSERT(ct != ZSD_DESTROY || zone_status_get(zone) >= ZONE_IS_DOWN);
870 
871 	/*
872 	 * Run the callback solely based on what is registered for the zone
873 	 * in zone_zsd. The global list can change independently of this
874 	 * as keys are registered and unregistered and we don't register new
875 	 * callbacks for a zone that is in the process of going away.
876 	 */
877 	mutex_enter(&zone->zone_lock);
878 	for (t = list_head(&zone->zone_zsd); t != NULL;
879 	    t = list_next(&zone->zone_zsd, t)) {
880 		zone_key_t key = t->zsd_key;
881 
882 		/* Skip if no callbacks registered */
883 
884 		if (ct == ZSD_SHUTDOWN) {
885 			if (t->zsd_shutdown != NULL &&
886 			    (t->zsd_flags & ZSD_SHUTDOWN_ALL) == 0) {
887 				t->zsd_flags |= ZSD_SHUTDOWN_NEEDED;
888 				DTRACE_PROBE2(zsd__shutdown__needed,
889 				    zone_t *, zone, zone_key_t, key);
890 			}
891 		} else {
892 			if (t->zsd_destroy != NULL &&
893 			    (t->zsd_flags & ZSD_DESTROY_ALL) == 0) {
894 				t->zsd_flags |= ZSD_DESTROY_NEEDED;
895 				DTRACE_PROBE2(zsd__destroy__needed,
896 				    zone_t *, zone, zone_key_t, key);
897 			}
898 		}
899 	}
900 	mutex_exit(&zone->zone_lock);
901 
902 	/* Now call the shutdown and destroy callback for this key */
903 	zsd_apply_all_keys(zsd_apply_shutdown, zone);
904 	zsd_apply_all_keys(zsd_apply_destroy, zone);
905 
906 }
907 
908 /*
909  * Called when the zone is going away; free ZSD-related memory, and
910  * destroy the zone_zsd list.
911  */
912 static void
913 zone_free_zsd(zone_t *zone)
914 {
915 	struct zsd_entry *t, *next;
916 
917 	/*
918 	 * Free all the zsd_entry's we had on this zone.
919 	 */
920 	mutex_enter(&zone->zone_lock);
921 	for (t = list_head(&zone->zone_zsd); t != NULL; t = next) {
922 		next = list_next(&zone->zone_zsd, t);
923 		list_remove(&zone->zone_zsd, t);
924 		ASSERT(!(t->zsd_flags & ZSD_ALL_INPROGRESS));
925 		kmem_free(t, sizeof (*t));
926 	}
927 	list_destroy(&zone->zone_zsd);
928 	mutex_exit(&zone->zone_lock);
929 
930 }
931 
932 /*
933  * Apply a function to all zones for particular key value.
934  *
935  * The applyfn has to drop zonehash_lock if it does some work, and
936  * then reacquire it before it returns.
937  * When the lock is dropped we don't follow list_next even
938  * if it is possible to do so without any hazards. This is
939  * because we want the design to allow for the list of zones
940  * to change in any arbitrary way during the time the
941  * lock was dropped.
942  *
943  * It is safe to restart the loop at list_head since the applyfn
944  * changes the zsd_flags as it does work, so a subsequent
945  * pass through will have no effect in applyfn, hence the loop will terminate
946  * in at worst O(N^2).
947  */
948 static void
949 zsd_apply_all_zones(zsd_applyfn_t *applyfn, zone_key_t key)
950 {
951 	zone_t *zone;
952 
953 	mutex_enter(&zonehash_lock);
954 	zone = list_head(&zone_active);
955 	while (zone != NULL) {
956 		if ((applyfn)(&zonehash_lock, B_FALSE, zone, key)) {
957 			/* Lock dropped - restart at head */
958 			zone = list_head(&zone_active);
959 		} else {
960 			zone = list_next(&zone_active, zone);
961 		}
962 	}
963 	mutex_exit(&zonehash_lock);
964 }
965 
966 /*
967  * Apply a function to all keys for a particular zone.
968  *
969  * The applyfn has to drop zonehash_lock if it does some work, and
970  * then reacquire it before it returns.
971  * When the lock is dropped we don't follow list_next even
972  * if it is possible to do so without any hazards. This is
973  * because we want the design to allow for the list of zsd callbacks
974  * to change in any arbitrary way during the time the
975  * lock was dropped.
976  *
977  * It is safe to restart the loop at list_head since the applyfn
978  * changes the zsd_flags as it does work, so a subsequent
979  * pass through will have no effect in applyfn, hence the loop will terminate
980  * in at worst O(N^2).
981  */
982 static void
983 zsd_apply_all_keys(zsd_applyfn_t *applyfn, zone_t *zone)
984 {
985 	struct zsd_entry *t;
986 
987 	mutex_enter(&zone->zone_lock);
988 	t = list_head(&zone->zone_zsd);
989 	while (t != NULL) {
990 		if ((applyfn)(NULL, B_TRUE, zone, t->zsd_key)) {
991 			/* Lock dropped - restart at head */
992 			t = list_head(&zone->zone_zsd);
993 		} else {
994 			t = list_next(&zone->zone_zsd, t);
995 		}
996 	}
997 	mutex_exit(&zone->zone_lock);
998 }
999 
1000 /*
1001  * Call the create function for the zone and key if CREATE_NEEDED
1002  * is set.
1003  * If some other thread gets here first and sets CREATE_INPROGRESS, then
1004  * we wait for that thread to complete so that we can ensure that
1005  * all the callbacks are done when we've looped over all zones/keys.
1006  *
1007  * When we call the create function, we drop the global held by the
1008  * caller, and return true to tell the caller it needs to re-evalute the
1009  * state.
1010  * If the caller holds zone_lock then zone_lock_held is set, and zone_lock
1011  * remains held on exit.
1012  */
1013 static boolean_t
1014 zsd_apply_create(kmutex_t *lockp, boolean_t zone_lock_held,
1015     zone_t *zone, zone_key_t key)
1016 {
1017 	void *result;
1018 	struct zsd_entry *t;
1019 	boolean_t dropped;
1020 
1021 	if (lockp != NULL) {
1022 		ASSERT(MUTEX_HELD(lockp));
1023 	}
1024 	if (zone_lock_held) {
1025 		ASSERT(MUTEX_HELD(&zone->zone_lock));
1026 	} else {
1027 		mutex_enter(&zone->zone_lock);
1028 	}
1029 
1030 	t = zsd_find(&zone->zone_zsd, key);
1031 	if (t == NULL) {
1032 		/*
1033 		 * Somebody else got here first e.g the zone going
1034 		 * away.
1035 		 */
1036 		if (!zone_lock_held)
1037 			mutex_exit(&zone->zone_lock);
1038 		return (B_FALSE);
1039 	}
1040 	dropped = B_FALSE;
1041 	if (zsd_wait_for_inprogress(zone, t, lockp))
1042 		dropped = B_TRUE;
1043 
1044 	if (t->zsd_flags & ZSD_CREATE_NEEDED) {
1045 		t->zsd_flags &= ~ZSD_CREATE_NEEDED;
1046 		t->zsd_flags |= ZSD_CREATE_INPROGRESS;
1047 		DTRACE_PROBE2(zsd__create__inprogress,
1048 		    zone_t *, zone, zone_key_t, key);
1049 		mutex_exit(&zone->zone_lock);
1050 		if (lockp != NULL)
1051 			mutex_exit(lockp);
1052 
1053 		dropped = B_TRUE;
1054 		ASSERT(t->zsd_create != NULL);
1055 		DTRACE_PROBE2(zsd__create__start,
1056 		    zone_t *, zone, zone_key_t, key);
1057 
1058 		result = (*t->zsd_create)(zone->zone_id);
1059 
1060 		DTRACE_PROBE2(zsd__create__end,
1061 		    zone_t *, zone, voidn *, result);
1062 
1063 		ASSERT(result != NULL);
1064 		if (lockp != NULL)
1065 			mutex_enter(lockp);
1066 		mutex_enter(&zone->zone_lock);
1067 		t->zsd_data = result;
1068 		t->zsd_flags &= ~ZSD_CREATE_INPROGRESS;
1069 		t->zsd_flags |= ZSD_CREATE_COMPLETED;
1070 		cv_broadcast(&t->zsd_cv);
1071 		DTRACE_PROBE2(zsd__create__completed,
1072 		    zone_t *, zone, zone_key_t, key);
1073 	}
1074 	if (!zone_lock_held)
1075 		mutex_exit(&zone->zone_lock);
1076 	return (dropped);
1077 }
1078 
1079 /*
1080  * Call the shutdown function for the zone and key if SHUTDOWN_NEEDED
1081  * is set.
1082  * If some other thread gets here first and sets *_INPROGRESS, then
1083  * we wait for that thread to complete so that we can ensure that
1084  * all the callbacks are done when we've looped over all zones/keys.
1085  *
1086  * When we call the shutdown function, we drop the global held by the
1087  * caller, and return true to tell the caller it needs to re-evalute the
1088  * state.
1089  * If the caller holds zone_lock then zone_lock_held is set, and zone_lock
1090  * remains held on exit.
1091  */
1092 static boolean_t
1093 zsd_apply_shutdown(kmutex_t *lockp, boolean_t zone_lock_held,
1094     zone_t *zone, zone_key_t key)
1095 {
1096 	struct zsd_entry *t;
1097 	void *data;
1098 	boolean_t dropped;
1099 
1100 	if (lockp != NULL) {
1101 		ASSERT(MUTEX_HELD(lockp));
1102 	}
1103 	if (zone_lock_held) {
1104 		ASSERT(MUTEX_HELD(&zone->zone_lock));
1105 	} else {
1106 		mutex_enter(&zone->zone_lock);
1107 	}
1108 
1109 	t = zsd_find(&zone->zone_zsd, key);
1110 	if (t == NULL) {
1111 		/*
1112 		 * Somebody else got here first e.g the zone going
1113 		 * away.
1114 		 */
1115 		if (!zone_lock_held)
1116 			mutex_exit(&zone->zone_lock);
1117 		return (B_FALSE);
1118 	}
1119 	dropped = B_FALSE;
1120 	if (zsd_wait_for_creator(zone, t, lockp))
1121 		dropped = B_TRUE;
1122 
1123 	if (zsd_wait_for_inprogress(zone, t, lockp))
1124 		dropped = B_TRUE;
1125 
1126 	if (t->zsd_flags & ZSD_SHUTDOWN_NEEDED) {
1127 		t->zsd_flags &= ~ZSD_SHUTDOWN_NEEDED;
1128 		t->zsd_flags |= ZSD_SHUTDOWN_INPROGRESS;
1129 		DTRACE_PROBE2(zsd__shutdown__inprogress,
1130 		    zone_t *, zone, zone_key_t, key);
1131 		mutex_exit(&zone->zone_lock);
1132 		if (lockp != NULL)
1133 			mutex_exit(lockp);
1134 		dropped = B_TRUE;
1135 
1136 		ASSERT(t->zsd_shutdown != NULL);
1137 		data = t->zsd_data;
1138 
1139 		DTRACE_PROBE2(zsd__shutdown__start,
1140 		    zone_t *, zone, zone_key_t, key);
1141 
1142 		(t->zsd_shutdown)(zone->zone_id, data);
1143 		DTRACE_PROBE2(zsd__shutdown__end,
1144 		    zone_t *, zone, zone_key_t, key);
1145 
1146 		if (lockp != NULL)
1147 			mutex_enter(lockp);
1148 		mutex_enter(&zone->zone_lock);
1149 		t->zsd_flags &= ~ZSD_SHUTDOWN_INPROGRESS;
1150 		t->zsd_flags |= ZSD_SHUTDOWN_COMPLETED;
1151 		cv_broadcast(&t->zsd_cv);
1152 		DTRACE_PROBE2(zsd__shutdown__completed,
1153 		    zone_t *, zone, zone_key_t, key);
1154 	}
1155 	if (!zone_lock_held)
1156 		mutex_exit(&zone->zone_lock);
1157 	return (dropped);
1158 }
1159 
1160 /*
1161  * Call the destroy function for the zone and key if DESTROY_NEEDED
1162  * is set.
1163  * If some other thread gets here first and sets *_INPROGRESS, then
1164  * we wait for that thread to complete so that we can ensure that
1165  * all the callbacks are done when we've looped over all zones/keys.
1166  *
1167  * When we call the destroy function, we drop the global held by the
1168  * caller, and return true to tell the caller it needs to re-evalute the
1169  * state.
1170  * If the caller holds zone_lock then zone_lock_held is set, and zone_lock
1171  * remains held on exit.
1172  */
1173 static boolean_t
1174 zsd_apply_destroy(kmutex_t *lockp, boolean_t zone_lock_held,
1175     zone_t *zone, zone_key_t key)
1176 {
1177 	struct zsd_entry *t;
1178 	void *data;
1179 	boolean_t dropped;
1180 
1181 	if (lockp != NULL) {
1182 		ASSERT(MUTEX_HELD(lockp));
1183 	}
1184 	if (zone_lock_held) {
1185 		ASSERT(MUTEX_HELD(&zone->zone_lock));
1186 	} else {
1187 		mutex_enter(&zone->zone_lock);
1188 	}
1189 
1190 	t = zsd_find(&zone->zone_zsd, key);
1191 	if (t == NULL) {
1192 		/*
1193 		 * Somebody else got here first e.g the zone going
1194 		 * away.
1195 		 */
1196 		if (!zone_lock_held)
1197 			mutex_exit(&zone->zone_lock);
1198 		return (B_FALSE);
1199 	}
1200 	dropped = B_FALSE;
1201 	if (zsd_wait_for_creator(zone, t, lockp))
1202 		dropped = B_TRUE;
1203 
1204 	if (zsd_wait_for_inprogress(zone, t, lockp))
1205 		dropped = B_TRUE;
1206 
1207 	if (t->zsd_flags & ZSD_DESTROY_NEEDED) {
1208 		t->zsd_flags &= ~ZSD_DESTROY_NEEDED;
1209 		t->zsd_flags |= ZSD_DESTROY_INPROGRESS;
1210 		DTRACE_PROBE2(zsd__destroy__inprogress,
1211 		    zone_t *, zone, zone_key_t, key);
1212 		mutex_exit(&zone->zone_lock);
1213 		if (lockp != NULL)
1214 			mutex_exit(lockp);
1215 		dropped = B_TRUE;
1216 
1217 		ASSERT(t->zsd_destroy != NULL);
1218 		data = t->zsd_data;
1219 		DTRACE_PROBE2(zsd__destroy__start,
1220 		    zone_t *, zone, zone_key_t, key);
1221 
1222 		(t->zsd_destroy)(zone->zone_id, data);
1223 		DTRACE_PROBE2(zsd__destroy__end,
1224 		    zone_t *, zone, zone_key_t, key);
1225 
1226 		if (lockp != NULL)
1227 			mutex_enter(lockp);
1228 		mutex_enter(&zone->zone_lock);
1229 		t->zsd_data = NULL;
1230 		t->zsd_flags &= ~ZSD_DESTROY_INPROGRESS;
1231 		t->zsd_flags |= ZSD_DESTROY_COMPLETED;
1232 		cv_broadcast(&t->zsd_cv);
1233 		DTRACE_PROBE2(zsd__destroy__completed,
1234 		    zone_t *, zone, zone_key_t, key);
1235 	}
1236 	if (!zone_lock_held)
1237 		mutex_exit(&zone->zone_lock);
1238 	return (dropped);
1239 }
1240 
1241 /*
1242  * Wait for any CREATE_NEEDED flag to be cleared.
1243  * Returns true if lockp was temporarily dropped while waiting.
1244  */
1245 static boolean_t
1246 zsd_wait_for_creator(zone_t *zone, struct zsd_entry *t, kmutex_t *lockp)
1247 {
1248 	boolean_t dropped = B_FALSE;
1249 
1250 	while (t->zsd_flags & ZSD_CREATE_NEEDED) {
1251 		DTRACE_PROBE2(zsd__wait__for__creator,
1252 		    zone_t *, zone, struct zsd_entry *, t);
1253 		if (lockp != NULL) {
1254 			dropped = B_TRUE;
1255 			mutex_exit(lockp);
1256 		}
1257 		cv_wait(&t->zsd_cv, &zone->zone_lock);
1258 		if (lockp != NULL) {
1259 			/* First drop zone_lock to preserve order */
1260 			mutex_exit(&zone->zone_lock);
1261 			mutex_enter(lockp);
1262 			mutex_enter(&zone->zone_lock);
1263 		}
1264 	}
1265 	return (dropped);
1266 }
1267 
1268 /*
1269  * Wait for any INPROGRESS flag to be cleared.
1270  * Returns true if lockp was temporarily dropped while waiting.
1271  */
1272 static boolean_t
1273 zsd_wait_for_inprogress(zone_t *zone, struct zsd_entry *t, kmutex_t *lockp)
1274 {
1275 	boolean_t dropped = B_FALSE;
1276 
1277 	while (t->zsd_flags & ZSD_ALL_INPROGRESS) {
1278 		DTRACE_PROBE2(zsd__wait__for__inprogress,
1279 		    zone_t *, zone, struct zsd_entry *, t);
1280 		if (lockp != NULL) {
1281 			dropped = B_TRUE;
1282 			mutex_exit(lockp);
1283 		}
1284 		cv_wait(&t->zsd_cv, &zone->zone_lock);
1285 		if (lockp != NULL) {
1286 			/* First drop zone_lock to preserve order */
1287 			mutex_exit(&zone->zone_lock);
1288 			mutex_enter(lockp);
1289 			mutex_enter(&zone->zone_lock);
1290 		}
1291 	}
1292 	return (dropped);
1293 }
1294 
1295 /*
1296  * Frees memory associated with the zone dataset list.
1297  */
1298 static void
1299 zone_free_datasets(zone_t *zone)
1300 {
1301 	zone_dataset_t *t, *next;
1302 
1303 	for (t = list_head(&zone->zone_datasets); t != NULL; t = next) {
1304 		next = list_next(&zone->zone_datasets, t);
1305 		list_remove(&zone->zone_datasets, t);
1306 		kmem_free(t->zd_dataset, strlen(t->zd_dataset) + 1);
1307 		kmem_free(t, sizeof (*t));
1308 	}
1309 	list_destroy(&zone->zone_datasets);
1310 }
1311 
1312 /*
1313  * zone.cpu-shares resource control support.
1314  */
1315 /*ARGSUSED*/
1316 static rctl_qty_t
1317 zone_cpu_shares_usage(rctl_t *rctl, struct proc *p)
1318 {
1319 	ASSERT(MUTEX_HELD(&p->p_lock));
1320 	return (p->p_zone->zone_shares);
1321 }
1322 
1323 /*ARGSUSED*/
1324 static int
1325 zone_cpu_shares_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e,
1326     rctl_qty_t nv)
1327 {
1328 	ASSERT(MUTEX_HELD(&p->p_lock));
1329 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1330 	if (e->rcep_p.zone == NULL)
1331 		return (0);
1332 
1333 	e->rcep_p.zone->zone_shares = nv;
1334 	return (0);
1335 }
1336 
1337 static rctl_ops_t zone_cpu_shares_ops = {
1338 	rcop_no_action,
1339 	zone_cpu_shares_usage,
1340 	zone_cpu_shares_set,
1341 	rcop_no_test
1342 };
1343 
1344 /*
1345  * zone.cpu-cap resource control support.
1346  */
1347 /*ARGSUSED*/
1348 static rctl_qty_t
1349 zone_cpu_cap_get(rctl_t *rctl, struct proc *p)
1350 {
1351 	ASSERT(MUTEX_HELD(&p->p_lock));
1352 	return (cpucaps_zone_get(p->p_zone));
1353 }
1354 
1355 /*ARGSUSED*/
1356 static int
1357 zone_cpu_cap_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e,
1358     rctl_qty_t nv)
1359 {
1360 	zone_t *zone = e->rcep_p.zone;
1361 
1362 	ASSERT(MUTEX_HELD(&p->p_lock));
1363 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1364 
1365 	if (zone == NULL)
1366 		return (0);
1367 
1368 	/*
1369 	 * set cap to the new value.
1370 	 */
1371 	return (cpucaps_zone_set(zone, nv));
1372 }
1373 
1374 static rctl_ops_t zone_cpu_cap_ops = {
1375 	rcop_no_action,
1376 	zone_cpu_cap_get,
1377 	zone_cpu_cap_set,
1378 	rcop_no_test
1379 };
1380 
1381 /*ARGSUSED*/
1382 static rctl_qty_t
1383 zone_lwps_usage(rctl_t *r, proc_t *p)
1384 {
1385 	rctl_qty_t nlwps;
1386 	zone_t *zone = p->p_zone;
1387 
1388 	ASSERT(MUTEX_HELD(&p->p_lock));
1389 
1390 	mutex_enter(&zone->zone_nlwps_lock);
1391 	nlwps = zone->zone_nlwps;
1392 	mutex_exit(&zone->zone_nlwps_lock);
1393 
1394 	return (nlwps);
1395 }
1396 
1397 /*ARGSUSED*/
1398 static int
1399 zone_lwps_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e, rctl_val_t *rcntl,
1400     rctl_qty_t incr, uint_t flags)
1401 {
1402 	rctl_qty_t nlwps;
1403 
1404 	ASSERT(MUTEX_HELD(&p->p_lock));
1405 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1406 	if (e->rcep_p.zone == NULL)
1407 		return (0);
1408 	ASSERT(MUTEX_HELD(&(e->rcep_p.zone->zone_nlwps_lock)));
1409 	nlwps = e->rcep_p.zone->zone_nlwps;
1410 
1411 	if (nlwps + incr > rcntl->rcv_value)
1412 		return (1);
1413 
1414 	return (0);
1415 }
1416 
1417 /*ARGSUSED*/
1418 static int
1419 zone_lwps_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e, rctl_qty_t nv)
1420 {
1421 	ASSERT(MUTEX_HELD(&p->p_lock));
1422 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1423 	if (e->rcep_p.zone == NULL)
1424 		return (0);
1425 	e->rcep_p.zone->zone_nlwps_ctl = nv;
1426 	return (0);
1427 }
1428 
1429 static rctl_ops_t zone_lwps_ops = {
1430 	rcop_no_action,
1431 	zone_lwps_usage,
1432 	zone_lwps_set,
1433 	zone_lwps_test,
1434 };
1435 
1436 /*ARGSUSED*/
1437 static rctl_qty_t
1438 zone_procs_usage(rctl_t *r, proc_t *p)
1439 {
1440 	rctl_qty_t nprocs;
1441 	zone_t *zone = p->p_zone;
1442 
1443 	ASSERT(MUTEX_HELD(&p->p_lock));
1444 
1445 	mutex_enter(&zone->zone_nlwps_lock);
1446 	nprocs = zone->zone_nprocs;
1447 	mutex_exit(&zone->zone_nlwps_lock);
1448 
1449 	return (nprocs);
1450 }
1451 
1452 /*ARGSUSED*/
1453 static int
1454 zone_procs_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e, rctl_val_t *rcntl,
1455     rctl_qty_t incr, uint_t flags)
1456 {
1457 	rctl_qty_t nprocs;
1458 
1459 	ASSERT(MUTEX_HELD(&p->p_lock));
1460 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1461 	if (e->rcep_p.zone == NULL)
1462 		return (0);
1463 	ASSERT(MUTEX_HELD(&(e->rcep_p.zone->zone_nlwps_lock)));
1464 	nprocs = e->rcep_p.zone->zone_nprocs;
1465 
1466 	if (nprocs + incr > rcntl->rcv_value)
1467 		return (1);
1468 
1469 	return (0);
1470 }
1471 
1472 /*ARGSUSED*/
1473 static int
1474 zone_procs_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e, rctl_qty_t nv)
1475 {
1476 	ASSERT(MUTEX_HELD(&p->p_lock));
1477 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1478 	if (e->rcep_p.zone == NULL)
1479 		return (0);
1480 	e->rcep_p.zone->zone_nprocs_ctl = nv;
1481 	return (0);
1482 }
1483 
1484 static rctl_ops_t zone_procs_ops = {
1485 	rcop_no_action,
1486 	zone_procs_usage,
1487 	zone_procs_set,
1488 	zone_procs_test,
1489 };
1490 
1491 /*ARGSUSED*/
1492 static int
1493 zone_shmmax_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e, rctl_val_t *rval,
1494     rctl_qty_t incr, uint_t flags)
1495 {
1496 	rctl_qty_t v;
1497 	ASSERT(MUTEX_HELD(&p->p_lock));
1498 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1499 	v = e->rcep_p.zone->zone_shmmax + incr;
1500 	if (v > rval->rcv_value)
1501 		return (1);
1502 	return (0);
1503 }
1504 
1505 static rctl_ops_t zone_shmmax_ops = {
1506 	rcop_no_action,
1507 	rcop_no_usage,
1508 	rcop_no_set,
1509 	zone_shmmax_test
1510 };
1511 
1512 /*ARGSUSED*/
1513 static int
1514 zone_shmmni_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e, rctl_val_t *rval,
1515     rctl_qty_t incr, uint_t flags)
1516 {
1517 	rctl_qty_t v;
1518 	ASSERT(MUTEX_HELD(&p->p_lock));
1519 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1520 	v = e->rcep_p.zone->zone_ipc.ipcq_shmmni + incr;
1521 	if (v > rval->rcv_value)
1522 		return (1);
1523 	return (0);
1524 }
1525 
1526 static rctl_ops_t zone_shmmni_ops = {
1527 	rcop_no_action,
1528 	rcop_no_usage,
1529 	rcop_no_set,
1530 	zone_shmmni_test
1531 };
1532 
1533 /*ARGSUSED*/
1534 static int
1535 zone_semmni_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e, rctl_val_t *rval,
1536     rctl_qty_t incr, uint_t flags)
1537 {
1538 	rctl_qty_t v;
1539 	ASSERT(MUTEX_HELD(&p->p_lock));
1540 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1541 	v = e->rcep_p.zone->zone_ipc.ipcq_semmni + incr;
1542 	if (v > rval->rcv_value)
1543 		return (1);
1544 	return (0);
1545 }
1546 
1547 static rctl_ops_t zone_semmni_ops = {
1548 	rcop_no_action,
1549 	rcop_no_usage,
1550 	rcop_no_set,
1551 	zone_semmni_test
1552 };
1553 
1554 /*ARGSUSED*/
1555 static int
1556 zone_msgmni_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e, rctl_val_t *rval,
1557     rctl_qty_t incr, uint_t flags)
1558 {
1559 	rctl_qty_t v;
1560 	ASSERT(MUTEX_HELD(&p->p_lock));
1561 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1562 	v = e->rcep_p.zone->zone_ipc.ipcq_msgmni + incr;
1563 	if (v > rval->rcv_value)
1564 		return (1);
1565 	return (0);
1566 }
1567 
1568 static rctl_ops_t zone_msgmni_ops = {
1569 	rcop_no_action,
1570 	rcop_no_usage,
1571 	rcop_no_set,
1572 	zone_msgmni_test
1573 };
1574 
1575 /*ARGSUSED*/
1576 static rctl_qty_t
1577 zone_locked_mem_usage(rctl_t *rctl, struct proc *p)
1578 {
1579 	rctl_qty_t q;
1580 	ASSERT(MUTEX_HELD(&p->p_lock));
1581 	mutex_enter(&p->p_zone->zone_mem_lock);
1582 	q = p->p_zone->zone_locked_mem;
1583 	mutex_exit(&p->p_zone->zone_mem_lock);
1584 	return (q);
1585 }
1586 
1587 /*ARGSUSED*/
1588 static int
1589 zone_locked_mem_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e,
1590     rctl_val_t *rcntl, rctl_qty_t incr, uint_t flags)
1591 {
1592 	rctl_qty_t q;
1593 	zone_t *z;
1594 
1595 	z = e->rcep_p.zone;
1596 	ASSERT(MUTEX_HELD(&p->p_lock));
1597 	ASSERT(MUTEX_HELD(&z->zone_mem_lock));
1598 	q = z->zone_locked_mem;
1599 	if (q + incr > rcntl->rcv_value)
1600 		return (1);
1601 	return (0);
1602 }
1603 
1604 /*ARGSUSED*/
1605 static int
1606 zone_locked_mem_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e,
1607     rctl_qty_t nv)
1608 {
1609 	ASSERT(MUTEX_HELD(&p->p_lock));
1610 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1611 	if (e->rcep_p.zone == NULL)
1612 		return (0);
1613 	e->rcep_p.zone->zone_locked_mem_ctl = nv;
1614 	return (0);
1615 }
1616 
1617 static rctl_ops_t zone_locked_mem_ops = {
1618 	rcop_no_action,
1619 	zone_locked_mem_usage,
1620 	zone_locked_mem_set,
1621 	zone_locked_mem_test
1622 };
1623 
1624 /*ARGSUSED*/
1625 static rctl_qty_t
1626 zone_max_swap_usage(rctl_t *rctl, struct proc *p)
1627 {
1628 	rctl_qty_t q;
1629 	zone_t *z = p->p_zone;
1630 
1631 	ASSERT(MUTEX_HELD(&p->p_lock));
1632 	mutex_enter(&z->zone_mem_lock);
1633 	q = z->zone_max_swap;
1634 	mutex_exit(&z->zone_mem_lock);
1635 	return (q);
1636 }
1637 
1638 /*ARGSUSED*/
1639 static int
1640 zone_max_swap_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e,
1641     rctl_val_t *rcntl, rctl_qty_t incr, uint_t flags)
1642 {
1643 	rctl_qty_t q;
1644 	zone_t *z;
1645 
1646 	z = e->rcep_p.zone;
1647 	ASSERT(MUTEX_HELD(&p->p_lock));
1648 	ASSERT(MUTEX_HELD(&z->zone_mem_lock));
1649 	q = z->zone_max_swap;
1650 	if (q + incr > rcntl->rcv_value)
1651 		return (1);
1652 	return (0);
1653 }
1654 
1655 /*ARGSUSED*/
1656 static int
1657 zone_max_swap_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e,
1658     rctl_qty_t nv)
1659 {
1660 	ASSERT(MUTEX_HELD(&p->p_lock));
1661 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1662 	if (e->rcep_p.zone == NULL)
1663 		return (0);
1664 	e->rcep_p.zone->zone_max_swap_ctl = nv;
1665 	return (0);
1666 }
1667 
1668 static rctl_ops_t zone_max_swap_ops = {
1669 	rcop_no_action,
1670 	zone_max_swap_usage,
1671 	zone_max_swap_set,
1672 	zone_max_swap_test
1673 };
1674 
1675 /*ARGSUSED*/
1676 static rctl_qty_t
1677 zone_max_lofi_usage(rctl_t *rctl, struct proc *p)
1678 {
1679 	rctl_qty_t q;
1680 	zone_t *z = p->p_zone;
1681 
1682 	ASSERT(MUTEX_HELD(&p->p_lock));
1683 	mutex_enter(&z->zone_rctl_lock);
1684 	q = z->zone_max_lofi;
1685 	mutex_exit(&z->zone_rctl_lock);
1686 	return (q);
1687 }
1688 
1689 /*ARGSUSED*/
1690 static int
1691 zone_max_lofi_test(rctl_t *r, proc_t *p, rctl_entity_p_t *e,
1692     rctl_val_t *rcntl, rctl_qty_t incr, uint_t flags)
1693 {
1694 	rctl_qty_t q;
1695 	zone_t *z;
1696 
1697 	z = e->rcep_p.zone;
1698 	ASSERT(MUTEX_HELD(&p->p_lock));
1699 	ASSERT(MUTEX_HELD(&z->zone_rctl_lock));
1700 	q = z->zone_max_lofi;
1701 	if (q + incr > rcntl->rcv_value)
1702 		return (1);
1703 	return (0);
1704 }
1705 
1706 /*ARGSUSED*/
1707 static int
1708 zone_max_lofi_set(rctl_t *rctl, struct proc *p, rctl_entity_p_t *e,
1709     rctl_qty_t nv)
1710 {
1711 	ASSERT(MUTEX_HELD(&p->p_lock));
1712 	ASSERT(e->rcep_t == RCENTITY_ZONE);
1713 	if (e->rcep_p.zone == NULL)
1714 		return (0);
1715 	e->rcep_p.zone->zone_max_lofi_ctl = nv;
1716 	return (0);
1717 }
1718 
1719 static rctl_ops_t zone_max_lofi_ops = {
1720 	rcop_no_action,
1721 	zone_max_lofi_usage,
1722 	zone_max_lofi_set,
1723 	zone_max_lofi_test
1724 };
1725 
1726 /*
1727  * Helper function to brand the zone with a unique ID.
1728  */
1729 static void
1730 zone_uniqid(zone_t *zone)
1731 {
1732 	static uint64_t uniqid = 0;
1733 
1734 	ASSERT(MUTEX_HELD(&zonehash_lock));
1735 	zone->zone_uniqid = uniqid++;
1736 }
1737 
1738 /*
1739  * Returns a held pointer to the "kcred" for the specified zone.
1740  */
1741 struct cred *
1742 zone_get_kcred(zoneid_t zoneid)
1743 {
1744 	zone_t *zone;
1745 	cred_t *cr;
1746 
1747 	if ((zone = zone_find_by_id(zoneid)) == NULL)
1748 		return (NULL);
1749 	cr = zone->zone_kcred;
1750 	crhold(cr);
1751 	zone_rele(zone);
1752 	return (cr);
1753 }
1754 
1755 static int
1756 zone_lockedmem_kstat_update(kstat_t *ksp, int rw)
1757 {
1758 	zone_t *zone = ksp->ks_private;
1759 	zone_kstat_t *zk = ksp->ks_data;
1760 
1761 	if (rw == KSTAT_WRITE)
1762 		return (EACCES);
1763 
1764 	zk->zk_usage.value.ui64 = zone->zone_locked_mem;
1765 	zk->zk_value.value.ui64 = zone->zone_locked_mem_ctl;
1766 	return (0);
1767 }
1768 
1769 static int
1770 zone_nprocs_kstat_update(kstat_t *ksp, int rw)
1771 {
1772 	zone_t *zone = ksp->ks_private;
1773 	zone_kstat_t *zk = ksp->ks_data;
1774 
1775 	if (rw == KSTAT_WRITE)
1776 		return (EACCES);
1777 
1778 	zk->zk_usage.value.ui64 = zone->zone_nprocs;
1779 	zk->zk_value.value.ui64 = zone->zone_nprocs_ctl;
1780 	return (0);
1781 }
1782 
1783 static int
1784 zone_swapresv_kstat_update(kstat_t *ksp, int rw)
1785 {
1786 	zone_t *zone = ksp->ks_private;
1787 	zone_kstat_t *zk = ksp->ks_data;
1788 
1789 	if (rw == KSTAT_WRITE)
1790 		return (EACCES);
1791 
1792 	zk->zk_usage.value.ui64 = zone->zone_max_swap;
1793 	zk->zk_value.value.ui64 = zone->zone_max_swap_ctl;
1794 	return (0);
1795 }
1796 
1797 static kstat_t *
1798 zone_kstat_create_common(zone_t *zone, char *name,
1799     int (*updatefunc) (kstat_t *, int))
1800 {
1801 	kstat_t *ksp;
1802 	zone_kstat_t *zk;
1803 
1804 	ksp = rctl_kstat_create_zone(zone, name, KSTAT_TYPE_NAMED,
1805 	    sizeof (zone_kstat_t) / sizeof (kstat_named_t),
1806 	    KSTAT_FLAG_VIRTUAL);
1807 
1808 	if (ksp == NULL)
1809 		return (NULL);
1810 
1811 	zk = ksp->ks_data = kmem_alloc(sizeof (zone_kstat_t), KM_SLEEP);
1812 	ksp->ks_data_size += strlen(zone->zone_name) + 1;
1813 	kstat_named_init(&zk->zk_zonename, "zonename", KSTAT_DATA_STRING);
1814 	kstat_named_setstr(&zk->zk_zonename, zone->zone_name);
1815 	kstat_named_init(&zk->zk_usage, "usage", KSTAT_DATA_UINT64);
1816 	kstat_named_init(&zk->zk_value, "value", KSTAT_DATA_UINT64);
1817 	ksp->ks_update = updatefunc;
1818 	ksp->ks_private = zone;
1819 	kstat_install(ksp);
1820 	return (ksp);
1821 }
1822 
1823 static void
1824 zone_kstat_create(zone_t *zone)
1825 {
1826 	zone->zone_lockedmem_kstat = zone_kstat_create_common(zone,
1827 	    "lockedmem", zone_lockedmem_kstat_update);
1828 	zone->zone_swapresv_kstat = zone_kstat_create_common(zone,
1829 	    "swapresv", zone_swapresv_kstat_update);
1830 	zone->zone_nprocs_kstat = zone_kstat_create_common(zone,
1831 	    "nprocs", zone_nprocs_kstat_update);
1832 }
1833 
1834 static void
1835 zone_kstat_delete_common(kstat_t **pkstat)
1836 {
1837 	void *data;
1838 
1839 	if (*pkstat != NULL) {
1840 		data = (*pkstat)->ks_data;
1841 		kstat_delete(*pkstat);
1842 		kmem_free(data, sizeof (zone_kstat_t));
1843 		*pkstat = NULL;
1844 	}
1845 }
1846 
1847 static void
1848 zone_kstat_delete(zone_t *zone)
1849 {
1850 	zone_kstat_delete_common(&zone->zone_lockedmem_kstat);
1851 	zone_kstat_delete_common(&zone->zone_swapresv_kstat);
1852 	zone_kstat_delete_common(&zone->zone_nprocs_kstat);
1853 }
1854 
1855 /*
1856  * Called very early on in boot to initialize the ZSD list so that
1857  * zone_key_create() can be called before zone_init().  It also initializes
1858  * portions of zone0 which may be used before zone_init() is called.  The
1859  * variable "global_zone" will be set when zone0 is fully initialized by
1860  * zone_init().
1861  */
1862 void
1863 zone_zsd_init(void)
1864 {
1865 	mutex_init(&zonehash_lock, NULL, MUTEX_DEFAULT, NULL);
1866 	mutex_init(&zsd_key_lock, NULL, MUTEX_DEFAULT, NULL);
1867 	list_create(&zsd_registered_keys, sizeof (struct zsd_entry),
1868 	    offsetof(struct zsd_entry, zsd_linkage));
1869 	list_create(&zone_active, sizeof (zone_t),
1870 	    offsetof(zone_t, zone_linkage));
1871 	list_create(&zone_deathrow, sizeof (zone_t),
1872 	    offsetof(zone_t, zone_linkage));
1873 
1874 	mutex_init(&zone0.zone_lock, NULL, MUTEX_DEFAULT, NULL);
1875 	mutex_init(&zone0.zone_nlwps_lock, NULL, MUTEX_DEFAULT, NULL);
1876 	mutex_init(&zone0.zone_mem_lock, NULL, MUTEX_DEFAULT, NULL);
1877 	zone0.zone_shares = 1;
1878 	zone0.zone_nlwps = 0;
1879 	zone0.zone_nlwps_ctl = INT_MAX;
1880 	zone0.zone_nprocs = 0;
1881 	zone0.zone_nprocs_ctl = INT_MAX;
1882 	zone0.zone_locked_mem = 0;
1883 	zone0.zone_locked_mem_ctl = UINT64_MAX;
1884 	ASSERT(zone0.zone_max_swap == 0);
1885 	zone0.zone_max_swap_ctl = UINT64_MAX;
1886 	zone0.zone_max_lofi = 0;
1887 	zone0.zone_max_lofi_ctl = UINT64_MAX;
1888 	zone0.zone_shmmax = 0;
1889 	zone0.zone_ipc.ipcq_shmmni = 0;
1890 	zone0.zone_ipc.ipcq_semmni = 0;
1891 	zone0.zone_ipc.ipcq_msgmni = 0;
1892 	zone0.zone_name = GLOBAL_ZONENAME;
1893 	zone0.zone_nodename = utsname.nodename;
1894 	zone0.zone_domain = srpc_domain;
1895 	zone0.zone_hostid = HW_INVALID_HOSTID;
1896 	zone0.zone_fs_allowed = NULL;
1897 	zone0.zone_ref = 1;
1898 	zone0.zone_id = GLOBAL_ZONEID;
1899 	zone0.zone_status = ZONE_IS_RUNNING;
1900 	zone0.zone_rootpath = "/";
1901 	zone0.zone_rootpathlen = 2;
1902 	zone0.zone_psetid = ZONE_PS_INVAL;
1903 	zone0.zone_ncpus = 0;
1904 	zone0.zone_ncpus_online = 0;
1905 	zone0.zone_proc_initpid = 1;
1906 	zone0.zone_initname = initname;
1907 	zone0.zone_lockedmem_kstat = NULL;
1908 	zone0.zone_swapresv_kstat = NULL;
1909 	zone0.zone_nprocs_kstat = NULL;
1910 	list_create(&zone0.zone_ref_list, sizeof (zone_ref_t),
1911 	    offsetof(zone_ref_t, zref_linkage));
1912 	list_create(&zone0.zone_zsd, sizeof (struct zsd_entry),
1913 	    offsetof(struct zsd_entry, zsd_linkage));
1914 	list_insert_head(&zone_active, &zone0);
1915 
1916 	/*
1917 	 * The root filesystem is not mounted yet, so zone_rootvp cannot be set
1918 	 * to anything meaningful.  It is assigned to be 'rootdir' in
1919 	 * vfs_mountroot().
1920 	 */
1921 	zone0.zone_rootvp = NULL;
1922 	zone0.zone_vfslist = NULL;
1923 	zone0.zone_bootargs = initargs;
1924 	zone0.zone_privset = kmem_alloc(sizeof (priv_set_t), KM_SLEEP);
1925 	/*
1926 	 * The global zone has all privileges
1927 	 */
1928 	priv_fillset(zone0.zone_privset);
1929 	/*
1930 	 * Add p0 to the global zone
1931 	 */
1932 	zone0.zone_zsched = &p0;
1933 	p0.p_zone = &zone0;
1934 }
1935 
1936 /*
1937  * Compute a hash value based on the contents of the label and the DOI.  The
1938  * hash algorithm is somewhat arbitrary, but is based on the observation that
1939  * humans will likely pick labels that differ by amounts that work out to be
1940  * multiples of the number of hash chains, and thus stirring in some primes
1941  * should help.
1942  */
1943 static uint_t
1944 hash_bylabel(void *hdata, mod_hash_key_t key)
1945 {
1946 	const ts_label_t *lab = (ts_label_t *)key;
1947 	const uint32_t *up, *ue;
1948 	uint_t hash;
1949 	int i;
1950 
1951 	_NOTE(ARGUNUSED(hdata));
1952 
1953 	hash = lab->tsl_doi + (lab->tsl_doi << 1);
1954 	/* we depend on alignment of label, but not representation */
1955 	up = (const uint32_t *)&lab->tsl_label;
1956 	ue = up + sizeof (lab->tsl_label) / sizeof (*up);
1957 	i = 1;
1958 	while (up < ue) {
1959 		/* using 2^n + 1, 1 <= n <= 16 as source of many primes */
1960 		hash += *up + (*up << ((i % 16) + 1));
1961 		up++;
1962 		i++;
1963 	}
1964 	return (hash);
1965 }
1966 
1967 /*
1968  * All that mod_hash cares about here is zero (equal) versus non-zero (not
1969  * equal).  This may need to be changed if less than / greater than is ever
1970  * needed.
1971  */
1972 static int
1973 hash_labelkey_cmp(mod_hash_key_t key1, mod_hash_key_t key2)
1974 {
1975 	ts_label_t *lab1 = (ts_label_t *)key1;
1976 	ts_label_t *lab2 = (ts_label_t *)key2;
1977 
1978 	return (label_equal(lab1, lab2) ? 0 : 1);
1979 }
1980 
1981 /*
1982  * Called by main() to initialize the zones framework.
1983  */
1984 void
1985 zone_init(void)
1986 {
1987 	rctl_dict_entry_t *rde;
1988 	rctl_val_t *dval;
1989 	rctl_set_t *set;
1990 	rctl_alloc_gp_t *gp;
1991 	rctl_entity_p_t e;
1992 	int res;
1993 
1994 	ASSERT(curproc == &p0);
1995 
1996 	/*
1997 	 * Create ID space for zone IDs.  ID 0 is reserved for the
1998 	 * global zone.
1999 	 */
2000 	zoneid_space = id_space_create("zoneid_space", 1, MAX_ZONEID);
2001 
2002 	/*
2003 	 * Initialize generic zone resource controls, if any.
2004 	 */
2005 	rc_zone_cpu_shares = rctl_register("zone.cpu-shares",
2006 	    RCENTITY_ZONE, RCTL_GLOBAL_SIGNAL_NEVER | RCTL_GLOBAL_DENY_NEVER |
2007 	    RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_COUNT | RCTL_GLOBAL_SYSLOG_NEVER,
2008 	    FSS_MAXSHARES, FSS_MAXSHARES, &zone_cpu_shares_ops);
2009 
2010 	rc_zone_cpu_cap = rctl_register("zone.cpu-cap",
2011 	    RCENTITY_ZONE, RCTL_GLOBAL_SIGNAL_NEVER | RCTL_GLOBAL_DENY_ALWAYS |
2012 	    RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_COUNT |RCTL_GLOBAL_SYSLOG_NEVER |
2013 	    RCTL_GLOBAL_INFINITE,
2014 	    MAXCAP, MAXCAP, &zone_cpu_cap_ops);
2015 
2016 	rc_zone_nlwps = rctl_register("zone.max-lwps", RCENTITY_ZONE,
2017 	    RCTL_GLOBAL_NOACTION | RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_COUNT,
2018 	    INT_MAX, INT_MAX, &zone_lwps_ops);
2019 
2020 	rc_zone_nprocs = rctl_register("zone.max-processes", RCENTITY_ZONE,
2021 	    RCTL_GLOBAL_NOACTION | RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_COUNT,
2022 	    INT_MAX, INT_MAX, &zone_procs_ops);
2023 
2024 	/*
2025 	 * System V IPC resource controls
2026 	 */
2027 	rc_zone_msgmni = rctl_register("zone.max-msg-ids",
2028 	    RCENTITY_ZONE, RCTL_GLOBAL_DENY_ALWAYS | RCTL_GLOBAL_NOBASIC |
2029 	    RCTL_GLOBAL_COUNT, IPC_IDS_MAX, IPC_IDS_MAX, &zone_msgmni_ops);
2030 
2031 	rc_zone_semmni = rctl_register("zone.max-sem-ids",
2032 	    RCENTITY_ZONE, RCTL_GLOBAL_DENY_ALWAYS | RCTL_GLOBAL_NOBASIC |
2033 	    RCTL_GLOBAL_COUNT, IPC_IDS_MAX, IPC_IDS_MAX, &zone_semmni_ops);
2034 
2035 	rc_zone_shmmni = rctl_register("zone.max-shm-ids",
2036 	    RCENTITY_ZONE, RCTL_GLOBAL_DENY_ALWAYS | RCTL_GLOBAL_NOBASIC |
2037 	    RCTL_GLOBAL_COUNT, IPC_IDS_MAX, IPC_IDS_MAX, &zone_shmmni_ops);
2038 
2039 	rc_zone_shmmax = rctl_register("zone.max-shm-memory",
2040 	    RCENTITY_ZONE, RCTL_GLOBAL_DENY_ALWAYS | RCTL_GLOBAL_NOBASIC |
2041 	    RCTL_GLOBAL_BYTES, UINT64_MAX, UINT64_MAX, &zone_shmmax_ops);
2042 
2043 	/*
2044 	 * Create a rctl_val with PRIVILEGED, NOACTION, value = 1.  Then attach
2045 	 * this at the head of the rctl_dict_entry for ``zone.cpu-shares''.
2046 	 */
2047 	dval = kmem_cache_alloc(rctl_val_cache, KM_SLEEP);
2048 	bzero(dval, sizeof (rctl_val_t));
2049 	dval->rcv_value = 1;
2050 	dval->rcv_privilege = RCPRIV_PRIVILEGED;
2051 	dval->rcv_flagaction = RCTL_LOCAL_NOACTION;
2052 	dval->rcv_action_recip_pid = -1;
2053 
2054 	rde = rctl_dict_lookup("zone.cpu-shares");
2055 	(void) rctl_val_list_insert(&rde->rcd_default_value, dval);
2056 
2057 	rc_zone_locked_mem = rctl_register("zone.max-locked-memory",
2058 	    RCENTITY_ZONE, RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_BYTES |
2059 	    RCTL_GLOBAL_DENY_ALWAYS, UINT64_MAX, UINT64_MAX,
2060 	    &zone_locked_mem_ops);
2061 
2062 	rc_zone_max_swap = rctl_register("zone.max-swap",
2063 	    RCENTITY_ZONE, RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_BYTES |
2064 	    RCTL_GLOBAL_DENY_ALWAYS, UINT64_MAX, UINT64_MAX,
2065 	    &zone_max_swap_ops);
2066 
2067 	rc_zone_max_lofi = rctl_register("zone.max-lofi",
2068 	    RCENTITY_ZONE, RCTL_GLOBAL_NOBASIC | RCTL_GLOBAL_COUNT |
2069 	    RCTL_GLOBAL_DENY_ALWAYS, UINT64_MAX, UINT64_MAX,
2070 	    &zone_max_lofi_ops);
2071 
2072 	/*
2073 	 * Initialize the ``global zone''.
2074 	 */
2075 	set = rctl_set_create();
2076 	gp = rctl_set_init_prealloc(RCENTITY_ZONE);
2077 	mutex_enter(&p0.p_lock);
2078 	e.rcep_p.zone = &zone0;
2079 	e.rcep_t = RCENTITY_ZONE;
2080 	zone0.zone_rctls = rctl_set_init(RCENTITY_ZONE, &p0, &e, set,
2081 	    gp);
2082 
2083 	zone0.zone_nlwps = p0.p_lwpcnt;
2084 	zone0.zone_nprocs = 1;
2085 	zone0.zone_ntasks = 1;
2086 	mutex_exit(&p0.p_lock);
2087 	zone0.zone_restart_init = B_TRUE;
2088 	zone0.zone_brand = &native_brand;
2089 	rctl_prealloc_destroy(gp);
2090 	/*
2091 	 * pool_default hasn't been initialized yet, so we let pool_init()
2092 	 * take care of making sure the global zone is in the default pool.
2093 	 */
2094 
2095 	/*
2096 	 * Initialize global zone kstats
2097 	 */
2098 	zone_kstat_create(&zone0);
2099 
2100 	/*
2101 	 * Initialize zone label.
2102 	 * mlp are initialized when tnzonecfg is loaded.
2103 	 */
2104 	zone0.zone_slabel = l_admin_low;
2105 	rw_init(&zone0.zone_mlps.mlpl_rwlock, NULL, RW_DEFAULT, NULL);
2106 	label_hold(l_admin_low);
2107 
2108 	/*
2109 	 * Initialise the lock for the database structure used by mntfs.
2110 	 */
2111 	rw_init(&zone0.zone_mntfs_db_lock, NULL, RW_DEFAULT, NULL);
2112 
2113 	mutex_enter(&zonehash_lock);
2114 	zone_uniqid(&zone0);
2115 	ASSERT(zone0.zone_uniqid == GLOBAL_ZONEUNIQID);
2116 
2117 	zonehashbyid = mod_hash_create_idhash("zone_by_id", zone_hash_size,
2118 	    mod_hash_null_valdtor);
2119 	zonehashbyname = mod_hash_create_strhash("zone_by_name",
2120 	    zone_hash_size, mod_hash_null_valdtor);
2121 	/*
2122 	 * maintain zonehashbylabel only for labeled systems
2123 	 */
2124 	if (is_system_labeled())
2125 		zonehashbylabel = mod_hash_create_extended("zone_by_label",
2126 		    zone_hash_size, mod_hash_null_keydtor,
2127 		    mod_hash_null_valdtor, hash_bylabel, NULL,
2128 		    hash_labelkey_cmp, KM_SLEEP);
2129 	zonecount = 1;
2130 
2131 	(void) mod_hash_insert(zonehashbyid, (mod_hash_key_t)GLOBAL_ZONEID,
2132 	    (mod_hash_val_t)&zone0);
2133 	(void) mod_hash_insert(zonehashbyname, (mod_hash_key_t)zone0.zone_name,
2134 	    (mod_hash_val_t)&zone0);
2135 	if (is_system_labeled()) {
2136 		zone0.zone_flags |= ZF_HASHED_LABEL;
2137 		(void) mod_hash_insert(zonehashbylabel,
2138 		    (mod_hash_key_t)zone0.zone_slabel, (mod_hash_val_t)&zone0);
2139 	}
2140 	mutex_exit(&zonehash_lock);
2141 
2142 	/*
2143 	 * We avoid setting zone_kcred until now, since kcred is initialized
2144 	 * sometime after zone_zsd_init() and before zone_init().
2145 	 */
2146 	zone0.zone_kcred = kcred;
2147 	/*
2148 	 * The global zone is fully initialized (except for zone_rootvp which
2149 	 * will be set when the root filesystem is mounted).
2150 	 */
2151 	global_zone = &zone0;
2152 
2153 	/*
2154 	 * Setup an event channel to send zone status change notifications on
2155 	 */
2156 	res = sysevent_evc_bind(ZONE_EVENT_CHANNEL, &zone_event_chan,
2157 	    EVCH_CREAT);
2158 
2159 	if (res)
2160 		panic("Sysevent_evc_bind failed during zone setup.\n");
2161 
2162 }
2163 
2164 static void
2165 zone_free(zone_t *zone)
2166 {
2167 	ASSERT(zone != global_zone);
2168 	ASSERT(zone->zone_ntasks == 0);
2169 	ASSERT(zone->zone_nlwps == 0);
2170 	ASSERT(zone->zone_nprocs == 0);
2171 	ASSERT(zone->zone_cred_ref == 0);
2172 	ASSERT(zone->zone_kcred == NULL);
2173 	ASSERT(zone_status_get(zone) == ZONE_IS_DEAD ||
2174 	    zone_status_get(zone) == ZONE_IS_UNINITIALIZED);
2175 	ASSERT(list_is_empty(&zone->zone_ref_list));
2176 
2177 	/*
2178 	 * Remove any zone caps.
2179 	 */
2180 	cpucaps_zone_remove(zone);
2181 
2182 	ASSERT(zone->zone_cpucap == NULL);
2183 
2184 	/* remove from deathrow list */
2185 	if (zone_status_get(zone) == ZONE_IS_DEAD) {
2186 		ASSERT(zone->zone_ref == 0);
2187 		mutex_enter(&zone_deathrow_lock);
2188 		list_remove(&zone_deathrow, zone);
2189 		mutex_exit(&zone_deathrow_lock);
2190 	}
2191 
2192 	list_destroy(&zone->zone_ref_list);
2193 	zone_free_zsd(zone);
2194 	zone_free_datasets(zone);
2195 	list_destroy(&zone->zone_dl_list);
2196 
2197 	if (zone->zone_rootvp != NULL)
2198 		VN_RELE(zone->zone_rootvp);
2199 	if (zone->zone_rootpath)
2200 		kmem_free(zone->zone_rootpath, zone->zone_rootpathlen);
2201 	if (zone->zone_name != NULL)
2202 		kmem_free(zone->zone_name, ZONENAME_MAX);
2203 	if (zone->zone_slabel != NULL)
2204 		label_rele(zone->zone_slabel);
2205 	if (zone->zone_nodename != NULL)
2206 		kmem_free(zone->zone_nodename, _SYS_NMLN);
2207 	if (zone->zone_domain != NULL)
2208 		kmem_free(zone->zone_domain, _SYS_NMLN);
2209 	if (zone->zone_privset != NULL)
2210 		kmem_free(zone->zone_privset, sizeof (priv_set_t));
2211 	if (zone->zone_rctls != NULL)
2212 		rctl_set_free(zone->zone_rctls);
2213 	if (zone->zone_bootargs != NULL)
2214 		strfree(zone->zone_bootargs);
2215 	if (zone->zone_initname != NULL)
2216 		strfree(zone->zone_initname);
2217 	if (zone->zone_fs_allowed != NULL)
2218 		strfree(zone->zone_fs_allowed);
2219 	if (zone->zone_pfexecd != NULL)
2220 		klpd_freelist(&zone->zone_pfexecd);
2221 	id_free(zoneid_space, zone->zone_id);
2222 	mutex_destroy(&zone->zone_lock);
2223 	cv_destroy(&zone->zone_cv);
2224 	rw_destroy(&zone->zone_mlps.mlpl_rwlock);
2225 	rw_destroy(&zone->zone_mntfs_db_lock);
2226 	kmem_free(zone, sizeof (zone_t));
2227 }
2228 
2229 /*
2230  * See block comment at the top of this file for information about zone
2231  * status values.
2232  */
2233 /*
2234  * Convenience function for setting zone status.
2235  */
2236 static void
2237 zone_status_set(zone_t *zone, zone_status_t status)
2238 {
2239 
2240 	nvlist_t *nvl = NULL;
2241 	ASSERT(MUTEX_HELD(&zone_status_lock));
2242 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE &&
2243 	    status >= zone_status_get(zone));
2244 
2245 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) ||
2246 	    nvlist_add_string(nvl, ZONE_CB_NAME, zone->zone_name) ||
2247 	    nvlist_add_string(nvl, ZONE_CB_NEWSTATE,
2248 	    zone_status_table[status]) ||
2249 	    nvlist_add_string(nvl, ZONE_CB_OLDSTATE,
2250 	    zone_status_table[zone->zone_status]) ||
2251 	    nvlist_add_int32(nvl, ZONE_CB_ZONEID, zone->zone_id) ||
2252 	    nvlist_add_uint64(nvl, ZONE_CB_TIMESTAMP, (uint64_t)gethrtime()) ||
2253 	    sysevent_evc_publish(zone_event_chan, ZONE_EVENT_STATUS_CLASS,
2254 	    ZONE_EVENT_STATUS_SUBCLASS, "sun.com", "kernel", nvl, EVCH_SLEEP)) {
2255 #ifdef DEBUG
2256 		(void) printf(
2257 		    "Failed to allocate and send zone state change event.\n");
2258 #endif
2259 	}
2260 	nvlist_free(nvl);
2261 
2262 	zone->zone_status = status;
2263 
2264 	cv_broadcast(&zone->zone_cv);
2265 }
2266 
2267 /*
2268  * Public function to retrieve the zone status.  The zone status may
2269  * change after it is retrieved.
2270  */
2271 zone_status_t
2272 zone_status_get(zone_t *zone)
2273 {
2274 	return (zone->zone_status);
2275 }
2276 
2277 static int
2278 zone_set_bootargs(zone_t *zone, const char *zone_bootargs)
2279 {
2280 	char *buf = kmem_zalloc(BOOTARGS_MAX, KM_SLEEP);
2281 	int err = 0;
2282 
2283 	ASSERT(zone != global_zone);
2284 	if ((err = copyinstr(zone_bootargs, buf, BOOTARGS_MAX, NULL)) != 0)
2285 		goto done;	/* EFAULT or ENAMETOOLONG */
2286 
2287 	if (zone->zone_bootargs != NULL)
2288 		strfree(zone->zone_bootargs);
2289 
2290 	zone->zone_bootargs = strdup(buf);
2291 
2292 done:
2293 	kmem_free(buf, BOOTARGS_MAX);
2294 	return (err);
2295 }
2296 
2297 static int
2298 zone_set_brand(zone_t *zone, const char *brand)
2299 {
2300 	struct brand_attr *attrp;
2301 	brand_t *bp;
2302 
2303 	attrp = kmem_alloc(sizeof (struct brand_attr), KM_SLEEP);
2304 	if (copyin(brand, attrp, sizeof (struct brand_attr)) != 0) {
2305 		kmem_free(attrp, sizeof (struct brand_attr));
2306 		return (EFAULT);
2307 	}
2308 
2309 	bp = brand_register_zone(attrp);
2310 	kmem_free(attrp, sizeof (struct brand_attr));
2311 	if (bp == NULL)
2312 		return (EINVAL);
2313 
2314 	/*
2315 	 * This is the only place where a zone can change it's brand.
2316 	 * We already need to hold zone_status_lock to check the zone
2317 	 * status, so we'll just use that lock to serialize zone
2318 	 * branding requests as well.
2319 	 */
2320 	mutex_enter(&zone_status_lock);
2321 
2322 	/* Re-Branding is not allowed and the zone can't be booted yet */
2323 	if ((ZONE_IS_BRANDED(zone)) ||
2324 	    (zone_status_get(zone) >= ZONE_IS_BOOTING)) {
2325 		mutex_exit(&zone_status_lock);
2326 		brand_unregister_zone(bp);
2327 		return (EINVAL);
2328 	}
2329 
2330 	/* set up the brand specific data */
2331 	zone->zone_brand = bp;
2332 	ZBROP(zone)->b_init_brand_data(zone);
2333 
2334 	mutex_exit(&zone_status_lock);
2335 	return (0);
2336 }
2337 
2338 static int
2339 zone_set_fs_allowed(zone_t *zone, const char *zone_fs_allowed)
2340 {
2341 	char *buf = kmem_zalloc(ZONE_FS_ALLOWED_MAX, KM_SLEEP);
2342 	int err = 0;
2343 
2344 	ASSERT(zone != global_zone);
2345 	if ((err = copyinstr(zone_fs_allowed, buf,
2346 	    ZONE_FS_ALLOWED_MAX, NULL)) != 0)
2347 		goto done;
2348 
2349 	if (zone->zone_fs_allowed != NULL)
2350 		strfree(zone->zone_fs_allowed);
2351 
2352 	zone->zone_fs_allowed = strdup(buf);
2353 
2354 done:
2355 	kmem_free(buf, ZONE_FS_ALLOWED_MAX);
2356 	return (err);
2357 }
2358 
2359 static int
2360 zone_set_initname(zone_t *zone, const char *zone_initname)
2361 {
2362 	char initname[INITNAME_SZ];
2363 	size_t len;
2364 	int err = 0;
2365 
2366 	ASSERT(zone != global_zone);
2367 	if ((err = copyinstr(zone_initname, initname, INITNAME_SZ, &len)) != 0)
2368 		return (err);	/* EFAULT or ENAMETOOLONG */
2369 
2370 	if (zone->zone_initname != NULL)
2371 		strfree(zone->zone_initname);
2372 
2373 	zone->zone_initname = kmem_alloc(strlen(initname) + 1, KM_SLEEP);
2374 	(void) strcpy(zone->zone_initname, initname);
2375 	return (0);
2376 }
2377 
2378 static int
2379 zone_set_phys_mcap(zone_t *zone, const uint64_t *zone_mcap)
2380 {
2381 	uint64_t mcap;
2382 	int err = 0;
2383 
2384 	if ((err = copyin(zone_mcap, &mcap, sizeof (uint64_t))) == 0)
2385 		zone->zone_phys_mcap = mcap;
2386 
2387 	return (err);
2388 }
2389 
2390 static int
2391 zone_set_sched_class(zone_t *zone, const char *new_class)
2392 {
2393 	char sched_class[PC_CLNMSZ];
2394 	id_t classid;
2395 	int err;
2396 
2397 	ASSERT(zone != global_zone);
2398 	if ((err = copyinstr(new_class, sched_class, PC_CLNMSZ, NULL)) != 0)
2399 		return (err);	/* EFAULT or ENAMETOOLONG */
2400 
2401 	if (getcid(sched_class, &classid) != 0 || CLASS_KERNEL(classid))
2402 		return (set_errno(EINVAL));
2403 	zone->zone_defaultcid = classid;
2404 	ASSERT(zone->zone_defaultcid > 0 &&
2405 	    zone->zone_defaultcid < loaded_classes);
2406 
2407 	return (0);
2408 }
2409 
2410 /*
2411  * Block indefinitely waiting for (zone_status >= status)
2412  */
2413 void
2414 zone_status_wait(zone_t *zone, zone_status_t status)
2415 {
2416 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE);
2417 
2418 	mutex_enter(&zone_status_lock);
2419 	while (zone->zone_status < status) {
2420 		cv_wait(&zone->zone_cv, &zone_status_lock);
2421 	}
2422 	mutex_exit(&zone_status_lock);
2423 }
2424 
2425 /*
2426  * Private CPR-safe version of zone_status_wait().
2427  */
2428 static void
2429 zone_status_wait_cpr(zone_t *zone, zone_status_t status, char *str)
2430 {
2431 	callb_cpr_t cprinfo;
2432 
2433 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE);
2434 
2435 	CALLB_CPR_INIT(&cprinfo, &zone_status_lock, callb_generic_cpr,
2436 	    str);
2437 	mutex_enter(&zone_status_lock);
2438 	while (zone->zone_status < status) {
2439 		CALLB_CPR_SAFE_BEGIN(&cprinfo);
2440 		cv_wait(&zone->zone_cv, &zone_status_lock);
2441 		CALLB_CPR_SAFE_END(&cprinfo, &zone_status_lock);
2442 	}
2443 	/*
2444 	 * zone_status_lock is implicitly released by the following.
2445 	 */
2446 	CALLB_CPR_EXIT(&cprinfo);
2447 }
2448 
2449 /*
2450  * Block until zone enters requested state or signal is received.  Return (0)
2451  * if signaled, non-zero otherwise.
2452  */
2453 int
2454 zone_status_wait_sig(zone_t *zone, zone_status_t status)
2455 {
2456 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE);
2457 
2458 	mutex_enter(&zone_status_lock);
2459 	while (zone->zone_status < status) {
2460 		if (!cv_wait_sig(&zone->zone_cv, &zone_status_lock)) {
2461 			mutex_exit(&zone_status_lock);
2462 			return (0);
2463 		}
2464 	}
2465 	mutex_exit(&zone_status_lock);
2466 	return (1);
2467 }
2468 
2469 /*
2470  * Block until the zone enters the requested state or the timeout expires,
2471  * whichever happens first.  Return (-1) if operation timed out, time remaining
2472  * otherwise.
2473  */
2474 clock_t
2475 zone_status_timedwait(zone_t *zone, clock_t tim, zone_status_t status)
2476 {
2477 	clock_t timeleft = 0;
2478 
2479 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE);
2480 
2481 	mutex_enter(&zone_status_lock);
2482 	while (zone->zone_status < status && timeleft != -1) {
2483 		timeleft = cv_timedwait(&zone->zone_cv, &zone_status_lock, tim);
2484 	}
2485 	mutex_exit(&zone_status_lock);
2486 	return (timeleft);
2487 }
2488 
2489 /*
2490  * Block until the zone enters the requested state, the current process is
2491  * signaled,  or the timeout expires, whichever happens first.  Return (-1) if
2492  * operation timed out, 0 if signaled, time remaining otherwise.
2493  */
2494 clock_t
2495 zone_status_timedwait_sig(zone_t *zone, clock_t tim, zone_status_t status)
2496 {
2497 	clock_t timeleft = tim - ddi_get_lbolt();
2498 
2499 	ASSERT(status > ZONE_MIN_STATE && status <= ZONE_MAX_STATE);
2500 
2501 	mutex_enter(&zone_status_lock);
2502 	while (zone->zone_status < status) {
2503 		timeleft = cv_timedwait_sig(&zone->zone_cv, &zone_status_lock,
2504 		    tim);
2505 		if (timeleft <= 0)
2506 			break;
2507 	}
2508 	mutex_exit(&zone_status_lock);
2509 	return (timeleft);
2510 }
2511 
2512 /*
2513  * Zones have two reference counts: one for references from credential
2514  * structures (zone_cred_ref), and one (zone_ref) for everything else.
2515  * This is so we can allow a zone to be rebooted while there are still
2516  * outstanding cred references, since certain drivers cache dblks (which
2517  * implicitly results in cached creds).  We wait for zone_ref to drop to
2518  * 0 (actually 1), but not zone_cred_ref.  The zone structure itself is
2519  * later freed when the zone_cred_ref drops to 0, though nothing other
2520  * than the zone id and privilege set should be accessed once the zone
2521  * is "dead".
2522  *
2523  * A debugging flag, zone_wait_for_cred, can be set to a non-zero value
2524  * to force halt/reboot to block waiting for the zone_cred_ref to drop
2525  * to 0.  This can be useful to flush out other sources of cached creds
2526  * that may be less innocuous than the driver case.
2527  *
2528  * Zones also provide a tracked reference counting mechanism in which zone
2529  * references are represented by "crumbs" (zone_ref structures).  Crumbs help
2530  * debuggers determine the sources of leaked zone references.  See
2531  * zone_hold_ref() and zone_rele_ref() below for more information.
2532  */
2533 
2534 int zone_wait_for_cred = 0;
2535 
2536 static void
2537 zone_hold_locked(zone_t *z)
2538 {
2539 	ASSERT(MUTEX_HELD(&z->zone_lock));
2540 	z->zone_ref++;
2541 	ASSERT(z->zone_ref != 0);
2542 }
2543 
2544 /*
2545  * Increment the specified zone's reference count.  The zone's zone_t structure
2546  * will not be freed as long as the zone's reference count is nonzero.
2547  * Decrement the zone's reference count via zone_rele().
2548  *
2549  * NOTE: This function should only be used to hold zones for short periods of
2550  * time.  Use zone_hold_ref() if the zone must be held for a long time.
2551  */
2552 void
2553 zone_hold(zone_t *z)
2554 {
2555 	mutex_enter(&z->zone_lock);
2556 	zone_hold_locked(z);
2557 	mutex_exit(&z->zone_lock);
2558 }
2559 
2560 /*
2561  * If the non-cred ref count drops to 1 and either the cred ref count
2562  * is 0 or we aren't waiting for cred references, the zone is ready to
2563  * be destroyed.
2564  */
2565 #define	ZONE_IS_UNREF(zone)	((zone)->zone_ref == 1 && \
2566 	    (!zone_wait_for_cred || (zone)->zone_cred_ref == 0))
2567 
2568 /*
2569  * Common zone reference release function invoked by zone_rele() and
2570  * zone_rele_ref().  If subsys is ZONE_REF_NUM_SUBSYS, then the specified
2571  * zone's subsystem-specific reference counters are not affected by the
2572  * release.  If ref is not NULL, then the zone_ref_t to which it refers is
2573  * removed from the specified zone's reference list.  ref must be non-NULL iff
2574  * subsys is not ZONE_REF_NUM_SUBSYS.
2575  */
2576 static void
2577 zone_rele_common(zone_t *z, zone_ref_t *ref, zone_ref_subsys_t subsys)
2578 {
2579 	boolean_t wakeup;
2580 
2581 	mutex_enter(&z->zone_lock);
2582 	ASSERT(z->zone_ref != 0);
2583 	z->zone_ref--;
2584 	if (subsys != ZONE_REF_NUM_SUBSYS) {
2585 		ASSERT(z->zone_subsys_ref[subsys] != 0);
2586 		z->zone_subsys_ref[subsys]--;
2587 		list_remove(&z->zone_ref_list, ref);
2588 	}
2589 	if (z->zone_ref == 0 && z->zone_cred_ref == 0) {
2590 		/* no more refs, free the structure */
2591 		mutex_exit(&z->zone_lock);
2592 		zone_free(z);
2593 		return;
2594 	}
2595 	/* signal zone_destroy so the zone can finish halting */
2596 	wakeup = (ZONE_IS_UNREF(z) && zone_status_get(z) >= ZONE_IS_DEAD);
2597 	mutex_exit(&z->zone_lock);
2598 
2599 	if (wakeup) {
2600 		/*
2601 		 * Grabbing zonehash_lock here effectively synchronizes with
2602 		 * zone_destroy() to avoid missed signals.
2603 		 */
2604 		mutex_enter(&zonehash_lock);
2605 		cv_broadcast(&zone_destroy_cv);
2606 		mutex_exit(&zonehash_lock);
2607 	}
2608 }
2609 
2610 /*
2611  * Decrement the specified zone's reference count.  The specified zone will
2612  * cease to exist after this function returns if the reference count drops to
2613  * zero.  This function should be paired with zone_hold().
2614  */
2615 void
2616 zone_rele(zone_t *z)
2617 {
2618 	zone_rele_common(z, NULL, ZONE_REF_NUM_SUBSYS);
2619 }
2620 
2621 /*
2622  * Initialize a zone reference structure.  This function must be invoked for
2623  * a reference structure before the structure is passed to zone_hold_ref().
2624  */
2625 void
2626 zone_init_ref(zone_ref_t *ref)
2627 {
2628 	ref->zref_zone = NULL;
2629 	list_link_init(&ref->zref_linkage);
2630 }
2631 
2632 /*
2633  * Acquire a reference to zone z.  The caller must specify the
2634  * zone_ref_subsys_t constant associated with its subsystem.  The specified
2635  * zone_ref_t structure will represent a reference to the specified zone.  Use
2636  * zone_rele_ref() to release the reference.
2637  *
2638  * The referenced zone_t structure will not be freed as long as the zone_t's
2639  * zone_status field is not ZONE_IS_DEAD and the zone has outstanding
2640  * references.
2641  *
2642  * NOTE: The zone_ref_t structure must be initialized before it is used.
2643  * See zone_init_ref() above.
2644  */
2645 void
2646 zone_hold_ref(zone_t *z, zone_ref_t *ref, zone_ref_subsys_t subsys)
2647 {
2648 	ASSERT(subsys >= 0 && subsys < ZONE_REF_NUM_SUBSYS);
2649 
2650 	/*
2651 	 * Prevent consumers from reusing a reference structure before
2652 	 * releasing it.
2653 	 */
2654 	VERIFY(ref->zref_zone == NULL);
2655 
2656 	ref->zref_zone = z;
2657 	mutex_enter(&z->zone_lock);
2658 	zone_hold_locked(z);
2659 	z->zone_subsys_ref[subsys]++;
2660 	ASSERT(z->zone_subsys_ref[subsys] != 0);
2661 	list_insert_head(&z->zone_ref_list, ref);
2662 	mutex_exit(&z->zone_lock);
2663 }
2664 
2665 /*
2666  * Release the zone reference represented by the specified zone_ref_t.
2667  * The reference is invalid after it's released; however, the zone_ref_t
2668  * structure can be reused without having to invoke zone_init_ref().
2669  * subsys should be the same value that was passed to zone_hold_ref()
2670  * when the reference was acquired.
2671  */
2672 void
2673 zone_rele_ref(zone_ref_t *ref, zone_ref_subsys_t subsys)
2674 {
2675 	zone_rele_common(ref->zref_zone, ref, subsys);
2676 
2677 	/*
2678 	 * Set the zone_ref_t's zref_zone field to NULL to generate panics
2679 	 * when consumers dereference the reference.  This helps us catch
2680 	 * consumers who use released references.  Furthermore, this lets
2681 	 * consumers reuse the zone_ref_t structure without having to
2682 	 * invoke zone_init_ref().
2683 	 */
2684 	ref->zref_zone = NULL;
2685 }
2686 
2687 void
2688 zone_cred_hold(zone_t *z)
2689 {
2690 	mutex_enter(&z->zone_lock);
2691 	z->zone_cred_ref++;
2692 	ASSERT(z->zone_cred_ref != 0);
2693 	mutex_exit(&z->zone_lock);
2694 }
2695 
2696 void
2697 zone_cred_rele(zone_t *z)
2698 {
2699 	boolean_t wakeup;
2700 
2701 	mutex_enter(&z->zone_lock);
2702 	ASSERT(z->zone_cred_ref != 0);
2703 	z->zone_cred_ref--;
2704 	if (z->zone_ref == 0 && z->zone_cred_ref == 0) {
2705 		/* no more refs, free the structure */
2706 		mutex_exit(&z->zone_lock);
2707 		zone_free(z);
2708 		return;
2709 	}
2710 	/*
2711 	 * If zone_destroy is waiting for the cred references to drain
2712 	 * out, and they have, signal it.
2713 	 */
2714 	wakeup = (zone_wait_for_cred && ZONE_IS_UNREF(z) &&
2715 	    zone_status_get(z) >= ZONE_IS_DEAD);
2716 	mutex_exit(&z->zone_lock);
2717 
2718 	if (wakeup) {
2719 		/*
2720 		 * Grabbing zonehash_lock here effectively synchronizes with
2721 		 * zone_destroy() to avoid missed signals.
2722 		 */
2723 		mutex_enter(&zonehash_lock);
2724 		cv_broadcast(&zone_destroy_cv);
2725 		mutex_exit(&zonehash_lock);
2726 	}
2727 }
2728 
2729 void
2730 zone_task_hold(zone_t *z)
2731 {
2732 	mutex_enter(&z->zone_lock);
2733 	z->zone_ntasks++;
2734 	ASSERT(z->zone_ntasks != 0);
2735 	mutex_exit(&z->zone_lock);
2736 }
2737 
2738 void
2739 zone_task_rele(zone_t *zone)
2740 {
2741 	uint_t refcnt;
2742 
2743 	mutex_enter(&zone->zone_lock);
2744 	ASSERT(zone->zone_ntasks != 0);
2745 	refcnt = --zone->zone_ntasks;
2746 	if (refcnt > 1)	{	/* Common case */
2747 		mutex_exit(&zone->zone_lock);
2748 		return;
2749 	}
2750 	zone_hold_locked(zone);	/* so we can use the zone_t later */
2751 	mutex_exit(&zone->zone_lock);
2752 	if (refcnt == 1) {
2753 		/*
2754 		 * See if the zone is shutting down.
2755 		 */
2756 		mutex_enter(&zone_status_lock);
2757 		if (zone_status_get(zone) != ZONE_IS_SHUTTING_DOWN) {
2758 			goto out;
2759 		}
2760 
2761 		/*
2762 		 * Make sure the ntasks didn't change since we
2763 		 * dropped zone_lock.
2764 		 */
2765 		mutex_enter(&zone->zone_lock);
2766 		if (refcnt != zone->zone_ntasks) {
2767 			mutex_exit(&zone->zone_lock);
2768 			goto out;
2769 		}
2770 		mutex_exit(&zone->zone_lock);
2771 
2772 		/*
2773 		 * No more user processes in the zone.  The zone is empty.
2774 		 */
2775 		zone_status_set(zone, ZONE_IS_EMPTY);
2776 		goto out;
2777 	}
2778 
2779 	ASSERT(refcnt == 0);
2780 	/*
2781 	 * zsched has exited; the zone is dead.
2782 	 */
2783 	zone->zone_zsched = NULL;		/* paranoia */
2784 	mutex_enter(&zone_status_lock);
2785 	zone_status_set(zone, ZONE_IS_DEAD);
2786 out:
2787 	mutex_exit(&zone_status_lock);
2788 	zone_rele(zone);
2789 }
2790 
2791 zoneid_t
2792 getzoneid(void)
2793 {
2794 	return (curproc->p_zone->zone_id);
2795 }
2796 
2797 /*
2798  * Internal versions of zone_find_by_*().  These don't zone_hold() or
2799  * check the validity of a zone's state.
2800  */
2801 static zone_t *
2802 zone_find_all_by_id(zoneid_t zoneid)
2803 {
2804 	mod_hash_val_t hv;
2805 	zone_t *zone = NULL;
2806 
2807 	ASSERT(MUTEX_HELD(&zonehash_lock));
2808 
2809 	if (mod_hash_find(zonehashbyid,
2810 	    (mod_hash_key_t)(uintptr_t)zoneid, &hv) == 0)
2811 		zone = (zone_t *)hv;
2812 	return (zone);
2813 }
2814 
2815 static zone_t *
2816 zone_find_all_by_label(const ts_label_t *label)
2817 {
2818 	mod_hash_val_t hv;
2819 	zone_t *zone = NULL;
2820 
2821 	ASSERT(MUTEX_HELD(&zonehash_lock));
2822 
2823 	/*
2824 	 * zonehashbylabel is not maintained for unlabeled systems
2825 	 */
2826 	if (!is_system_labeled())
2827 		return (NULL);
2828 	if (mod_hash_find(zonehashbylabel, (mod_hash_key_t)label, &hv) == 0)
2829 		zone = (zone_t *)hv;
2830 	return (zone);
2831 }
2832 
2833 static zone_t *
2834 zone_find_all_by_name(char *name)
2835 {
2836 	mod_hash_val_t hv;
2837 	zone_t *zone = NULL;
2838 
2839 	ASSERT(MUTEX_HELD(&zonehash_lock));
2840 
2841 	if (mod_hash_find(zonehashbyname, (mod_hash_key_t)name, &hv) == 0)
2842 		zone = (zone_t *)hv;
2843 	return (zone);
2844 }
2845 
2846 /*
2847  * Public interface for looking up a zone by zoneid.  Only returns the zone if
2848  * it is fully initialized, and has not yet begun the zone_destroy() sequence.
2849  * Caller must call zone_rele() once it is done with the zone.
2850  *
2851  * The zone may begin the zone_destroy() sequence immediately after this
2852  * function returns, but may be safely used until zone_rele() is called.
2853  */
2854 zone_t *
2855 zone_find_by_id(zoneid_t zoneid)
2856 {
2857 	zone_t *zone;
2858 	zone_status_t status;
2859 
2860 	mutex_enter(&zonehash_lock);
2861 	if ((zone = zone_find_all_by_id(zoneid)) == NULL) {
2862 		mutex_exit(&zonehash_lock);
2863 		return (NULL);
2864 	}
2865 	status = zone_status_get(zone);
2866 	if (status < ZONE_IS_READY || status > ZONE_IS_DOWN) {
2867 		/*
2868 		 * For all practical purposes the zone doesn't exist.
2869 		 */
2870 		mutex_exit(&zonehash_lock);
2871 		return (NULL);
2872 	}
2873 	zone_hold(zone);
2874 	mutex_exit(&zonehash_lock);
2875 	return (zone);
2876 }
2877 
2878 /*
2879  * Similar to zone_find_by_id, but using zone label as the key.
2880  */
2881 zone_t *
2882 zone_find_by_label(const ts_label_t *label)
2883 {
2884 	zone_t *zone;
2885 	zone_status_t status;
2886 
2887 	mutex_enter(&zonehash_lock);
2888 	if ((zone = zone_find_all_by_label(label)) == NULL) {
2889 		mutex_exit(&zonehash_lock);
2890 		return (NULL);
2891 	}
2892 
2893 	status = zone_status_get(zone);
2894 	if (status > ZONE_IS_DOWN) {
2895 		/*
2896 		 * For all practical purposes the zone doesn't exist.
2897 		 */
2898 		mutex_exit(&zonehash_lock);
2899 		return (NULL);
2900 	}
2901 	zone_hold(zone);
2902 	mutex_exit(&zonehash_lock);
2903 	return (zone);
2904 }
2905 
2906 /*
2907  * Similar to zone_find_by_id, but using zone name as the key.
2908  */
2909 zone_t *
2910 zone_find_by_name(char *name)
2911 {
2912 	zone_t *zone;
2913 	zone_status_t status;
2914 
2915 	mutex_enter(&zonehash_lock);
2916 	if ((zone = zone_find_all_by_name(name)) == NULL) {
2917 		mutex_exit(&zonehash_lock);
2918 		return (NULL);
2919 	}
2920 	status = zone_status_get(zone);
2921 	if (status < ZONE_IS_READY || status > ZONE_IS_DOWN) {
2922 		/*
2923 		 * For all practical purposes the zone doesn't exist.
2924 		 */
2925 		mutex_exit(&zonehash_lock);
2926 		return (NULL);
2927 	}
2928 	zone_hold(zone);
2929 	mutex_exit(&zonehash_lock);
2930 	return (zone);
2931 }
2932 
2933 /*
2934  * Similar to zone_find_by_id(), using the path as a key.  For instance,
2935  * if there is a zone "foo" rooted at /foo/root, and the path argument
2936  * is "/foo/root/proc", it will return the held zone_t corresponding to
2937  * zone "foo".
2938  *
2939  * zone_find_by_path() always returns a non-NULL value, since at the
2940  * very least every path will be contained in the global zone.
2941  *
2942  * As with the other zone_find_by_*() functions, the caller is
2943  * responsible for zone_rele()ing the return value of this function.
2944  */
2945 zone_t *
2946 zone_find_by_path(const char *path)
2947 {
2948 	zone_t *zone;
2949 	zone_t *zret = NULL;
2950 	zone_status_t status;
2951 
2952 	if (path == NULL) {
2953 		/*
2954 		 * Call from rootconf().
2955 		 */
2956 		zone_hold(global_zone);
2957 		return (global_zone);
2958 	}
2959 	ASSERT(*path == '/');
2960 	mutex_enter(&zonehash_lock);
2961 	for (zone = list_head(&zone_active); zone != NULL;
2962 	    zone = list_next(&zone_active, zone)) {
2963 		if (ZONE_PATH_VISIBLE(path, zone))
2964 			zret = zone;
2965 	}
2966 	ASSERT(zret != NULL);
2967 	status = zone_status_get(zret);
2968 	if (status < ZONE_IS_READY || status > ZONE_IS_DOWN) {
2969 		/*
2970 		 * Zone practically doesn't exist.
2971 		 */
2972 		zret = global_zone;
2973 	}
2974 	zone_hold(zret);
2975 	mutex_exit(&zonehash_lock);
2976 	return (zret);
2977 }
2978 
2979 /*
2980  * Get the number of cpus visible to this zone.  The system-wide global
2981  * 'ncpus' is returned if pools are disabled, the caller is in the
2982  * global zone, or a NULL zone argument is passed in.
2983  */
2984 int
2985 zone_ncpus_get(zone_t *zone)
2986 {
2987 	int myncpus = zone == NULL ? 0 : zone->zone_ncpus;
2988 
2989 	return (myncpus != 0 ? myncpus : ncpus);
2990 }
2991 
2992 /*
2993  * Get the number of online cpus visible to this zone.  The system-wide
2994  * global 'ncpus_online' is returned if pools are disabled, the caller
2995  * is in the global zone, or a NULL zone argument is passed in.
2996  */
2997 int
2998 zone_ncpus_online_get(zone_t *zone)
2999 {
3000 	int myncpus_online = zone == NULL ? 0 : zone->zone_ncpus_online;
3001 
3002 	return (myncpus_online != 0 ? myncpus_online : ncpus_online);
3003 }
3004 
3005 /*
3006  * Return the pool to which the zone is currently bound.
3007  */
3008 pool_t *
3009 zone_pool_get(zone_t *zone)
3010 {
3011 	ASSERT(pool_lock_held());
3012 
3013 	return (zone->zone_pool);
3014 }
3015 
3016 /*
3017  * Set the zone's pool pointer and update the zone's visibility to match
3018  * the resources in the new pool.
3019  */
3020 void
3021 zone_pool_set(zone_t *zone, pool_t *pool)
3022 {
3023 	ASSERT(pool_lock_held());
3024 	ASSERT(MUTEX_HELD(&cpu_lock));
3025 
3026 	zone->zone_pool = pool;
3027 	zone_pset_set(zone, pool->pool_pset->pset_id);
3028 }
3029 
3030 /*
3031  * Return the cached value of the id of the processor set to which the
3032  * zone is currently bound.  The value will be ZONE_PS_INVAL if the pools
3033  * facility is disabled.
3034  */
3035 psetid_t
3036 zone_pset_get(zone_t *zone)
3037 {
3038 	ASSERT(MUTEX_HELD(&cpu_lock));
3039 
3040 	return (zone->zone_psetid);
3041 }
3042 
3043 /*
3044  * Set the cached value of the id of the processor set to which the zone
3045  * is currently bound.  Also update the zone's visibility to match the
3046  * resources in the new processor set.
3047  */
3048 void
3049 zone_pset_set(zone_t *zone, psetid_t newpsetid)
3050 {
3051 	psetid_t oldpsetid;
3052 
3053 	ASSERT(MUTEX_HELD(&cpu_lock));
3054 	oldpsetid = zone_pset_get(zone);
3055 
3056 	if (oldpsetid == newpsetid)
3057 		return;
3058 	/*
3059 	 * Global zone sees all.
3060 	 */
3061 	if (zone != global_zone) {
3062 		zone->zone_psetid = newpsetid;
3063 		if (newpsetid != ZONE_PS_INVAL)
3064 			pool_pset_visibility_add(newpsetid, zone);
3065 		if (oldpsetid != ZONE_PS_INVAL)
3066 			pool_pset_visibility_remove(oldpsetid, zone);
3067 	}
3068 	/*
3069 	 * Disabling pools, so we should start using the global values
3070 	 * for ncpus and ncpus_online.
3071 	 */
3072 	if (newpsetid == ZONE_PS_INVAL) {
3073 		zone->zone_ncpus = 0;
3074 		zone->zone_ncpus_online = 0;
3075 	}
3076 }
3077 
3078 /*
3079  * Walk the list of active zones and issue the provided callback for
3080  * each of them.
3081  *
3082  * Caller must not be holding any locks that may be acquired under
3083  * zonehash_lock.  See comment at the beginning of the file for a list of
3084  * common locks and their interactions with zones.
3085  */
3086 int
3087 zone_walk(int (*cb)(zone_t *, void *), void *data)
3088 {
3089 	zone_t *zone;
3090 	int ret = 0;
3091 	zone_status_t status;
3092 
3093 	mutex_enter(&zonehash_lock);
3094 	for (zone = list_head(&zone_active); zone != NULL;
3095 	    zone = list_next(&zone_active, zone)) {
3096 		/*
3097 		 * Skip zones that shouldn't be externally visible.
3098 		 */
3099 		status = zone_status_get(zone);
3100 		if (status < ZONE_IS_READY || status > ZONE_IS_DOWN)
3101 			continue;
3102 		/*
3103 		 * Bail immediately if any callback invocation returns a
3104 		 * non-zero value.
3105 		 */
3106 		ret = (*cb)(zone, data);
3107 		if (ret != 0)
3108 			break;
3109 	}
3110 	mutex_exit(&zonehash_lock);
3111 	return (ret);
3112 }
3113 
3114 static int
3115 zone_set_root(zone_t *zone, const char *upath)
3116 {
3117 	vnode_t *vp;
3118 	int trycount;
3119 	int error = 0;
3120 	char *path;
3121 	struct pathname upn, pn;
3122 	size_t pathlen;
3123 
3124 	if ((error = pn_get((char *)upath, UIO_USERSPACE, &upn)) != 0)
3125 		return (error);
3126 
3127 	pn_alloc(&pn);
3128 
3129 	/* prevent infinite loop */
3130 	trycount = 10;
3131 	for (;;) {
3132 		if (--trycount <= 0) {
3133 			error = ESTALE;
3134 			goto out;
3135 		}
3136 
3137 		if ((error = lookuppn(&upn, &pn, FOLLOW, NULLVPP, &vp)) == 0) {
3138 			/*
3139 			 * VOP_ACCESS() may cover 'vp' with a new
3140 			 * filesystem, if 'vp' is an autoFS vnode.
3141 			 * Get the new 'vp' if so.
3142 			 */
3143 			if ((error =
3144 			    VOP_ACCESS(vp, VEXEC, 0, CRED(), NULL)) == 0 &&
3145 			    (!vn_ismntpt(vp) ||
3146 			    (error = traverse(&vp)) == 0)) {
3147 				pathlen = pn.pn_pathlen + 2;
3148 				path = kmem_alloc(pathlen, KM_SLEEP);
3149 				(void) strncpy(path, pn.pn_path,
3150 				    pn.pn_pathlen + 1);
3151 				path[pathlen - 2] = '/';
3152 				path[pathlen - 1] = '\0';
3153 				pn_free(&pn);
3154 				pn_free(&upn);
3155 
3156 				/* Success! */
3157 				break;
3158 			}
3159 			VN_RELE(vp);
3160 		}
3161 		if (error != ESTALE)
3162 			goto out;
3163 	}
3164 
3165 	ASSERT(error == 0);
3166 	zone->zone_rootvp = vp;		/* we hold a reference to vp */
3167 	zone->zone_rootpath = path;
3168 	zone->zone_rootpathlen = pathlen;
3169 	if (pathlen > 5 && strcmp(path + pathlen - 5, "/lu/") == 0)
3170 		zone->zone_flags |= ZF_IS_SCRATCH;
3171 	return (0);
3172 
3173 out:
3174 	pn_free(&pn);
3175 	pn_free(&upn);
3176 	return (error);
3177 }
3178 
3179 #define	isalnum(c)	(((c) >= '0' && (c) <= '9') || \
3180 			((c) >= 'a' && (c) <= 'z') || \
3181 			((c) >= 'A' && (c) <= 'Z'))
3182 
3183 static int
3184 zone_set_name(zone_t *zone, const char *uname)
3185 {
3186 	char *kname = kmem_zalloc(ZONENAME_MAX, KM_SLEEP);
3187 	size_t len;
3188 	int i, err;
3189 
3190 	if ((err = copyinstr(uname, kname, ZONENAME_MAX, &len)) != 0) {
3191 		kmem_free(kname, ZONENAME_MAX);
3192 		return (err);	/* EFAULT or ENAMETOOLONG */
3193 	}
3194 
3195 	/* must be less than ZONENAME_MAX */
3196 	if (len == ZONENAME_MAX && kname[ZONENAME_MAX - 1] != '\0') {
3197 		kmem_free(kname, ZONENAME_MAX);
3198 		return (EINVAL);
3199 	}
3200 
3201 	/*
3202 	 * Name must start with an alphanumeric and must contain only
3203 	 * alphanumerics, '-', '_' and '.'.
3204 	 */
3205 	if (!isalnum(kname[0])) {
3206 		kmem_free(kname, ZONENAME_MAX);
3207 		return (EINVAL);
3208 	}
3209 	for (i = 1; i < len - 1; i++) {
3210 		if (!isalnum(kname[i]) && kname[i] != '-' && kname[i] != '_' &&
3211 		    kname[i] != '.') {
3212 			kmem_free(kname, ZONENAME_MAX);
3213 			return (EINVAL);
3214 		}
3215 	}
3216 
3217 	zone->zone_name = kname;
3218 	return (0);
3219 }
3220 
3221 /*
3222  * Gets the 32-bit hostid of the specified zone as an unsigned int.  If 'zonep'
3223  * is NULL or it points to a zone with no hostid emulation, then the machine's
3224  * hostid (i.e., the global zone's hostid) is returned.  This function returns
3225  * zero if neither the zone nor the host machine (global zone) have hostids.  It
3226  * returns HW_INVALID_HOSTID if the function attempts to return the machine's
3227  * hostid and the machine's hostid is invalid.
3228  */
3229 uint32_t
3230 zone_get_hostid(zone_t *zonep)
3231 {
3232 	unsigned long machine_hostid;
3233 
3234 	if (zonep == NULL || zonep->zone_hostid == HW_INVALID_HOSTID) {
3235 		if (ddi_strtoul(hw_serial, NULL, 10, &machine_hostid) != 0)
3236 			return (HW_INVALID_HOSTID);
3237 		return ((uint32_t)machine_hostid);
3238 	}
3239 	return (zonep->zone_hostid);
3240 }
3241 
3242 /*
3243  * Similar to thread_create(), but makes sure the thread is in the appropriate
3244  * zone's zsched process (curproc->p_zone->zone_zsched) before returning.
3245  */
3246 /*ARGSUSED*/
3247 kthread_t *
3248 zthread_create(
3249     caddr_t stk,
3250     size_t stksize,
3251     void (*proc)(),
3252     void *arg,
3253     size_t len,
3254     pri_t pri)
3255 {
3256 	kthread_t *t;
3257 	zone_t *zone = curproc->p_zone;
3258 	proc_t *pp = zone->zone_zsched;
3259 
3260 	zone_hold(zone);	/* Reference to be dropped when thread exits */
3261 
3262 	/*
3263 	 * No-one should be trying to create threads if the zone is shutting
3264 	 * down and there aren't any kernel threads around.  See comment
3265 	 * in zthread_exit().
3266 	 */
3267 	ASSERT(!(zone->zone_kthreads == NULL &&
3268 	    zone_status_get(zone) >= ZONE_IS_EMPTY));
3269 	/*
3270 	 * Create a thread, but don't let it run until we've finished setting
3271 	 * things up.
3272 	 */
3273 	t = thread_create(stk, stksize, proc, arg, len, pp, TS_STOPPED, pri);
3274 	ASSERT(t->t_forw == NULL);
3275 	mutex_enter(&zone_status_lock);
3276 	if (zone->zone_kthreads == NULL) {
3277 		t->t_forw = t->t_back = t;
3278 	} else {
3279 		kthread_t *tx = zone->zone_kthreads;
3280 
3281 		t->t_forw = tx;
3282 		t->t_back = tx->t_back;
3283 		tx->t_back->t_forw = t;
3284 		tx->t_back = t;
3285 	}
3286 	zone->zone_kthreads = t;
3287 	mutex_exit(&zone_status_lock);
3288 
3289 	mutex_enter(&pp->p_lock);
3290 	t->t_proc_flag |= TP_ZTHREAD;
3291 	project_rele(t->t_proj);
3292 	t->t_proj = project_hold(pp->p_task->tk_proj);
3293 
3294 	/*
3295 	 * Setup complete, let it run.
3296 	 */
3297 	thread_lock(t);
3298 	t->t_schedflag |= TS_ALLSTART;
3299 	setrun_locked(t);
3300 	thread_unlock(t);
3301 
3302 	mutex_exit(&pp->p_lock);
3303 
3304 	return (t);
3305 }
3306 
3307 /*
3308  * Similar to thread_exit().  Must be called by threads created via
3309  * zthread_exit().
3310  */
3311 void
3312 zthread_exit(void)
3313 {
3314 	kthread_t *t = curthread;
3315 	proc_t *pp = curproc;
3316 	zone_t *zone = pp->p_zone;
3317 
3318 	mutex_enter(&zone_status_lock);
3319 
3320 	/*
3321 	 * Reparent to p0
3322 	 */
3323 	kpreempt_disable();
3324 	mutex_enter(&pp->p_lock);
3325 	t->t_proc_flag &= ~TP_ZTHREAD;
3326 	t->t_procp = &p0;
3327 	hat_thread_exit(t);
3328 	mutex_exit(&pp->p_lock);
3329 	kpreempt_enable();
3330 
3331 	if (t->t_back == t) {
3332 		ASSERT(t->t_forw == t);
3333 		/*
3334 		 * If the zone is empty, once the thread count
3335 		 * goes to zero no further kernel threads can be
3336 		 * created.  This is because if the creator is a process
3337 		 * in the zone, then it must have exited before the zone
3338 		 * state could be set to ZONE_IS_EMPTY.
3339 		 * Otherwise, if the creator is a kernel thread in the
3340 		 * zone, the thread count is non-zero.
3341 		 *
3342 		 * This really means that non-zone kernel threads should
3343 		 * not create zone kernel threads.
3344 		 */
3345 		zone->zone_kthreads = NULL;
3346 		if (zone_status_get(zone) == ZONE_IS_EMPTY) {
3347 			zone_status_set(zone, ZONE_IS_DOWN);
3348 			/*
3349 			 * Remove any CPU caps on this zone.
3350 			 */
3351 			cpucaps_zone_remove(zone);
3352 		}
3353 	} else {
3354 		t->t_forw->t_back = t->t_back;
3355 		t->t_back->t_forw = t->t_forw;
3356 		if (zone->zone_kthreads == t)
3357 			zone->zone_kthreads = t->t_forw;
3358 	}
3359 	mutex_exit(&zone_status_lock);
3360 	zone_rele(zone);
3361 	thread_exit();
3362 	/* NOTREACHED */
3363 }
3364 
3365 static void
3366 zone_chdir(vnode_t *vp, vnode_t **vpp, proc_t *pp)
3367 {
3368 	vnode_t *oldvp;
3369 
3370 	/* we're going to hold a reference here to the directory */
3371 	VN_HOLD(vp);
3372 
3373 	/* update abs cwd/root path see c2/audit.c */
3374 	if (AU_AUDITING())
3375 		audit_chdirec(vp, vpp);
3376 
3377 	mutex_enter(&pp->p_lock);
3378 	oldvp = *vpp;
3379 	*vpp = vp;
3380 	mutex_exit(&pp->p_lock);
3381 	if (oldvp != NULL)
3382 		VN_RELE(oldvp);
3383 }
3384 
3385 /*
3386  * Convert an rctl value represented by an nvlist_t into an rctl_val_t.
3387  */
3388 static int
3389 nvlist2rctlval(nvlist_t *nvl, rctl_val_t *rv)
3390 {
3391 	nvpair_t *nvp = NULL;
3392 	boolean_t priv_set = B_FALSE;
3393 	boolean_t limit_set = B_FALSE;
3394 	boolean_t action_set = B_FALSE;
3395 
3396 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
3397 		const char *name;
3398 		uint64_t ui64;
3399 
3400 		name = nvpair_name(nvp);
3401 		if (nvpair_type(nvp) != DATA_TYPE_UINT64)
3402 			return (EINVAL);
3403 		(void) nvpair_value_uint64(nvp, &ui64);
3404 		if (strcmp(name, "privilege") == 0) {
3405 			/*
3406 			 * Currently only privileged values are allowed, but
3407 			 * this may change in the future.
3408 			 */
3409 			if (ui64 != RCPRIV_PRIVILEGED)
3410 				return (EINVAL);
3411 			rv->rcv_privilege = ui64;
3412 			priv_set = B_TRUE;
3413 		} else if (strcmp(name, "limit") == 0) {
3414 			rv->rcv_value = ui64;
3415 			limit_set = B_TRUE;
3416 		} else if (strcmp(name, "action") == 0) {
3417 			if (ui64 != RCTL_LOCAL_NOACTION &&
3418 			    ui64 != RCTL_LOCAL_DENY)
3419 				return (EINVAL);
3420 			rv->rcv_flagaction = ui64;
3421 			action_set = B_TRUE;
3422 		} else {
3423 			return (EINVAL);
3424 		}
3425 	}
3426 
3427 	if (!(priv_set && limit_set && action_set))
3428 		return (EINVAL);
3429 	rv->rcv_action_signal = 0;
3430 	rv->rcv_action_recipient = NULL;
3431 	rv->rcv_action_recip_pid = -1;
3432 	rv->rcv_firing_time = 0;
3433 
3434 	return (0);
3435 }
3436 
3437 /*
3438  * Non-global zone version of start_init.
3439  */
3440 void
3441 zone_start_init(void)
3442 {
3443 	proc_t *p = ttoproc(curthread);
3444 	zone_t *z = p->p_zone;
3445 
3446 	ASSERT(!INGLOBALZONE(curproc));
3447 
3448 	/*
3449 	 * For all purposes (ZONE_ATTR_INITPID and restart_init),
3450 	 * storing just the pid of init is sufficient.
3451 	 */
3452 	z->zone_proc_initpid = p->p_pid;
3453 
3454 	/*
3455 	 * We maintain zone_boot_err so that we can return the cause of the
3456 	 * failure back to the caller of the zone_boot syscall.
3457 	 */
3458 	p->p_zone->zone_boot_err = start_init_common();
3459 
3460 	/*
3461 	 * We will prevent booting zones from becoming running zones if the
3462 	 * global zone is shutting down.
3463 	 */
3464 	mutex_enter(&zone_status_lock);
3465 	if (z->zone_boot_err != 0 || zone_status_get(global_zone) >=
3466 	    ZONE_IS_SHUTTING_DOWN) {
3467 		/*
3468 		 * Make sure we are still in the booting state-- we could have
3469 		 * raced and already be shutting down, or even further along.
3470 		 */
3471 		if (zone_status_get(z) == ZONE_IS_BOOTING) {
3472 			zone_status_set(z, ZONE_IS_SHUTTING_DOWN);
3473 		}
3474 		mutex_exit(&zone_status_lock);
3475 		/* It's gone bad, dispose of the process */
3476 		if (proc_exit(CLD_EXITED, z->zone_boot_err) != 0) {
3477 			mutex_enter(&p->p_lock);
3478 			ASSERT(p->p_flag & SEXITLWPS);
3479 			lwp_exit();
3480 		}
3481 	} else {
3482 		if (zone_status_get(z) == ZONE_IS_BOOTING)
3483 			zone_status_set(z, ZONE_IS_RUNNING);
3484 		mutex_exit(&zone_status_lock);
3485 		/* cause the process to return to userland. */
3486 		lwp_rtt();
3487 	}
3488 }
3489 
3490 struct zsched_arg {
3491 	zone_t *zone;
3492 	nvlist_t *nvlist;
3493 };
3494 
3495 /*
3496  * Per-zone "sched" workalike.  The similarity to "sched" doesn't have
3497  * anything to do with scheduling, but rather with the fact that
3498  * per-zone kernel threads are parented to zsched, just like regular
3499  * kernel threads are parented to sched (p0).
3500  *
3501  * zsched is also responsible for launching init for the zone.
3502  */
3503 static void
3504 zsched(void *arg)
3505 {
3506 	struct zsched_arg *za = arg;
3507 	proc_t *pp = curproc;
3508 	proc_t *initp = proc_init;
3509 	zone_t *zone = za->zone;
3510 	cred_t *cr, *oldcred;
3511 	rctl_set_t *set;
3512 	rctl_alloc_gp_t *gp;
3513 	contract_t *ct = NULL;
3514 	task_t *tk, *oldtk;
3515 	rctl_entity_p_t e;
3516 	kproject_t *pj;
3517 
3518 	nvlist_t *nvl = za->nvlist;
3519 	nvpair_t *nvp = NULL;
3520 
3521 	bcopy("zsched", PTOU(pp)->u_psargs, sizeof ("zsched"));
3522 	bcopy("zsched", PTOU(pp)->u_comm, sizeof ("zsched"));
3523 	PTOU(pp)->u_argc = 0;
3524 	PTOU(pp)->u_argv = NULL;
3525 	PTOU(pp)->u_envp = NULL;
3526 	closeall(P_FINFO(pp));
3527 
3528 	/*
3529 	 * We are this zone's "zsched" process.  As the zone isn't generally
3530 	 * visible yet we don't need to grab any locks before initializing its
3531 	 * zone_proc pointer.
3532 	 */
3533 	zone_hold(zone);  /* this hold is released by zone_destroy() */
3534 	zone->zone_zsched = pp;
3535 	mutex_enter(&pp->p_lock);
3536 	pp->p_zone = zone;
3537 	mutex_exit(&pp->p_lock);
3538 
3539 	/*
3540 	 * Disassociate process from its 'parent'; parent ourselves to init
3541 	 * (pid 1) and change other values as needed.
3542 	 */
3543 	sess_create();
3544 
3545 	mutex_enter(&pidlock);
3546 	proc_detach(pp);
3547 	pp->p_ppid = 1;
3548 	pp->p_flag |= SZONETOP;
3549 	pp->p_ancpid = 1;
3550 	pp->p_parent = initp;
3551 	pp->p_psibling = NULL;
3552 	if (initp->p_child)
3553 		initp->p_child->