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