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