1 /*
   2  * CDDL HEADER START
   3  *
   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 
  22 /*
  23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
  24  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
  25  * Copyright (c) 2012 by Delphix. All rights reserved.
  26  */
  27 
  28 /*
  29  * DTrace - Dynamic Tracing for Solaris
  30  *
  31  * This is the implementation of the Solaris Dynamic Tracing framework
  32  * (DTrace).  The user-visible interface to DTrace is described at length in
  33  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
  34  * library, the in-kernel DTrace framework, and the DTrace providers are
  35  * described in the block comments in the <sys/dtrace.h> header file.  The
  36  * internal architecture of DTrace is described in the block comments in the
  37  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
  38  * implementation very much assume mastery of all of these sources; if one has
  39  * an unanswered question about the implementation, one should consult them
  40  * first.
  41  *
  42  * The functions here are ordered roughly as follows:
  43  *
  44  *   - Probe context functions
  45  *   - Probe hashing functions
  46  *   - Non-probe context utility functions
  47  *   - Matching functions
  48  *   - Provider-to-Framework API functions
  49  *   - Probe management functions
  50  *   - DIF object functions
  51  *   - Format functions
  52  *   - Predicate functions
  53  *   - ECB functions
  54  *   - Buffer functions
  55  *   - Enabling functions
  56  *   - DOF functions
  57  *   - Anonymous enabling functions
  58  *   - Consumer state functions
  59  *   - Helper functions
  60  *   - Hook functions
  61  *   - Driver cookbook functions
  62  *
  63  * Each group of functions begins with a block comment labelled the "DTrace
  64  * [Group] Functions", allowing one to find each block by searching forward
  65  * on capital-f functions.
  66  */
  67 #include <sys/errno.h>
  68 #include <sys/stat.h>
  69 #include <sys/modctl.h>
  70 #include <sys/conf.h>
  71 #include <sys/systm.h>
  72 #include <sys/ddi.h>
  73 #include <sys/sunddi.h>
  74 #include <sys/cpuvar.h>
  75 #include <sys/kmem.h>
  76 #include <sys/strsubr.h>
  77 #include <sys/sysmacros.h>
  78 #include <sys/dtrace_impl.h>
  79 #include <sys/atomic.h>
  80 #include <sys/cmn_err.h>
  81 #include <sys/mutex_impl.h>
  82 #include <sys/rwlock_impl.h>
  83 #include <sys/ctf_api.h>
  84 #include <sys/panic.h>
  85 #include <sys/priv_impl.h>
  86 #include <sys/policy.h>
  87 #include <sys/cred_impl.h>
  88 #include <sys/procfs_isa.h>
  89 #include <sys/taskq.h>
  90 #include <sys/mkdev.h>
  91 #include <sys/kdi.h>
  92 #include <sys/zone.h>
  93 #include <sys/socket.h>
  94 #include <netinet/in.h>
  95 #include "strtolctype.h"
  96 
  97 /*
  98  * DTrace Tunable Variables
  99  *
 100  * The following variables may be tuned by adding a line to /etc/system that
 101  * includes both the name of the DTrace module ("dtrace") and the name of the
 102  * variable.  For example:
 103  *
 104  *   set dtrace:dtrace_destructive_disallow = 1
 105  *
 106  * In general, the only variables that one should be tuning this way are those
 107  * that affect system-wide DTrace behavior, and for which the default behavior
 108  * is undesirable.  Most of these variables are tunable on a per-consumer
 109  * basis using DTrace options, and need not be tuned on a system-wide basis.
 110  * When tuning these variables, avoid pathological values; while some attempt
 111  * is made to verify the integrity of these variables, they are not considered
 112  * part of the supported interface to DTrace, and they are therefore not
 113  * checked comprehensively.  Further, these variables should not be tuned
 114  * dynamically via "mdb -kw" or other means; they should only be tuned via
 115  * /etc/system.
 116  */
 117 int             dtrace_destructive_disallow = 0;
 118 dtrace_optval_t dtrace_nonroot_maxsize = (16 * 1024 * 1024);
 119 size_t          dtrace_difo_maxsize = (256 * 1024);
 120 dtrace_optval_t dtrace_dof_maxsize = (8 * 1024 * 1024);
 121 size_t          dtrace_global_maxsize = (16 * 1024);
 122 size_t          dtrace_actions_max = (16 * 1024);
 123 size_t          dtrace_retain_max = 1024;
 124 dtrace_optval_t dtrace_helper_actions_max = 1024;
 125 dtrace_optval_t dtrace_helper_providers_max = 32;
 126 dtrace_optval_t dtrace_dstate_defsize = (1 * 1024 * 1024);
 127 size_t          dtrace_strsize_default = 256;
 128 dtrace_optval_t dtrace_cleanrate_default = 9900990;             /* 101 hz */
 129 dtrace_optval_t dtrace_cleanrate_min = 200000;                  /* 5000 hz */
 130 dtrace_optval_t dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;  /* 1/minute */
 131 dtrace_optval_t dtrace_aggrate_default = NANOSEC;               /* 1 hz */
 132 dtrace_optval_t dtrace_statusrate_default = NANOSEC;            /* 1 hz */
 133 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;  /* 6/minute */
 134 dtrace_optval_t dtrace_switchrate_default = NANOSEC;            /* 1 hz */
 135 dtrace_optval_t dtrace_nspec_default = 1;
 136 dtrace_optval_t dtrace_specsize_default = 32 * 1024;
 137 dtrace_optval_t dtrace_stackframes_default = 20;
 138 dtrace_optval_t dtrace_ustackframes_default = 20;
 139 dtrace_optval_t dtrace_jstackframes_default = 50;
 140 dtrace_optval_t dtrace_jstackstrsize_default = 512;
 141 int             dtrace_msgdsize_max = 128;
 142 hrtime_t        dtrace_chill_max = 500 * (NANOSEC / MILLISEC);  /* 500 ms */
 143 hrtime_t        dtrace_chill_interval = NANOSEC;                /* 1000 ms */
 144 int             dtrace_devdepth_max = 32;
 145 int             dtrace_err_verbose;
 146 hrtime_t        dtrace_deadman_interval = NANOSEC;
 147 hrtime_t        dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
 148 hrtime_t        dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
 149 hrtime_t        dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
 150 
 151 /*
 152  * DTrace External Variables
 153  *
 154  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
 155  * available to DTrace consumers via the backtick (`) syntax.  One of these,
 156  * dtrace_zero, is made deliberately so:  it is provided as a source of
 157  * well-known, zero-filled memory.  While this variable is not documented,
 158  * it is used by some translators as an implementation detail.
 159  */
 160 const char      dtrace_zero[256] = { 0 };       /* zero-filled memory */
 161 
 162 /*
 163  * DTrace Internal Variables
 164  */
 165 static dev_info_t       *dtrace_devi;           /* device info */
 166 static vmem_t           *dtrace_arena;          /* probe ID arena */
 167 static vmem_t           *dtrace_minor;          /* minor number arena */
 168 static taskq_t          *dtrace_taskq;          /* task queue */
 169 static dtrace_probe_t   **dtrace_probes;        /* array of all probes */
 170 static int              dtrace_nprobes;         /* number of probes */
 171 static dtrace_provider_t *dtrace_provider;      /* provider list */
 172 static dtrace_meta_t    *dtrace_meta_pid;       /* user-land meta provider */
 173 static int              dtrace_opens;           /* number of opens */
 174 static int              dtrace_helpers;         /* number of helpers */
 175 static int              dtrace_getf;            /* number of unpriv getf()s */
 176 static void             *dtrace_softstate;      /* softstate pointer */
 177 static dtrace_hash_t    *dtrace_bymod;          /* probes hashed by module */
 178 static dtrace_hash_t    *dtrace_byfunc;         /* probes hashed by function */
 179 static dtrace_hash_t    *dtrace_byname;         /* probes hashed by name */
 180 static dtrace_toxrange_t *dtrace_toxrange;      /* toxic range array */
 181 static int              dtrace_toxranges;       /* number of toxic ranges */
 182 static int              dtrace_toxranges_max;   /* size of toxic range array */
 183 static dtrace_anon_t    dtrace_anon;            /* anonymous enabling */
 184 static kmem_cache_t     *dtrace_state_cache;    /* cache for dynamic state */
 185 static uint64_t         dtrace_vtime_references; /* number of vtimestamp refs */
 186 static kthread_t        *dtrace_panicked;       /* panicking thread */
 187 static dtrace_ecb_t     *dtrace_ecb_create_cache; /* cached created ECB */
 188 static dtrace_genid_t   dtrace_probegen;        /* current probe generation */
 189 static dtrace_helpers_t *dtrace_deferred_pid;   /* deferred helper list */
 190 static dtrace_enabling_t *dtrace_retained;      /* list of retained enablings */
 191 static dtrace_genid_t   dtrace_retained_gen;    /* current retained enab gen */
 192 static dtrace_dynvar_t  dtrace_dynhash_sink;    /* end of dynamic hash chains */
 193 static int              dtrace_dynvar_failclean; /* dynvars failed to clean */
 194 
 195 /*
 196  * DTrace Locking
 197  * DTrace is protected by three (relatively coarse-grained) locks:
 198  *
 199  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
 200  *     including enabling state, probes, ECBs, consumer state, helper state,
 201  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
 202  *     probe context is lock-free -- synchronization is handled via the
 203  *     dtrace_sync() cross call mechanism.
 204  *
 205  * (2) dtrace_provider_lock is required when manipulating provider state, or
 206  *     when provider state must be held constant.
 207  *
 208  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
 209  *     when meta provider state must be held constant.
 210  *
 211  * The lock ordering between these three locks is dtrace_meta_lock before
 212  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
 213  * several places where dtrace_provider_lock is held by the framework as it
 214  * calls into the providers -- which then call back into the framework,
 215  * grabbing dtrace_lock.)
 216  *
 217  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
 218  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
 219  * role as a coarse-grained lock; it is acquired before both of these locks.
 220  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
 221  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
 222  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
 223  * acquired _between_ dtrace_provider_lock and dtrace_lock.
 224  */
 225 static kmutex_t         dtrace_lock;            /* probe state lock */
 226 static kmutex_t         dtrace_provider_lock;   /* provider state lock */
 227 static kmutex_t         dtrace_meta_lock;       /* meta-provider state lock */
 228 
 229 /*
 230  * DTrace Provider Variables
 231  *
 232  * These are the variables relating to DTrace as a provider (that is, the
 233  * provider of the BEGIN, END, and ERROR probes).
 234  */
 235 static dtrace_pattr_t   dtrace_provider_attr = {
 236 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
 237 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
 238 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
 239 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
 240 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
 241 };
 242 
 243 static void
 244 dtrace_nullop(void)
 245 {}
 246 
 247 static int
 248 dtrace_enable_nullop(void)
 249 {
 250         return (0);
 251 }
 252 
 253 static dtrace_pops_t    dtrace_provider_ops = {
 254         (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
 255         (void (*)(void *, struct modctl *))dtrace_nullop,
 256         (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
 257         (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
 258         (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
 259         (void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
 260         NULL,
 261         NULL,
 262         NULL,
 263         (void (*)(void *, dtrace_id_t, void *))dtrace_nullop
 264 };
 265 
 266 static dtrace_id_t      dtrace_probeid_begin;   /* special BEGIN probe */
 267 static dtrace_id_t      dtrace_probeid_end;     /* special END probe */
 268 dtrace_id_t             dtrace_probeid_error;   /* special ERROR probe */
 269 
 270 /*
 271  * DTrace Helper Tracing Variables
 272  *
 273  * These variables should be set dynamically to enable helper tracing.  The
 274  * only variables that should be set are dtrace_helptrace_enable (which should
 275  * be set to a non-zero value to allocate helper tracing buffers on the next
 276  * open of /dev/dtrace) and dtrace_helptrace_disable (which should be set to a
 277  * non-zero value to deallocate helper tracing buffers on the next close of
 278  * /dev/dtrace).  When (and only when) helper tracing is disabled, the
 279  * buffer size may also be set via dtrace_helptrace_bufsize.
 280  */
 281 int                     dtrace_helptrace_enable = 0;
 282 int                     dtrace_helptrace_disable = 0;
 283 int                     dtrace_helptrace_bufsize = 16 * 1024 * 1024;
 284 uint32_t                dtrace_helptrace_nlocals;
 285 static dtrace_helptrace_t *dtrace_helptrace_buffer;
 286 static uint32_t         dtrace_helptrace_next = 0;
 287 static int              dtrace_helptrace_wrapped = 0;
 288 
 289 /*
 290  * DTrace Error Hashing
 291  *
 292  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
 293  * table.  This is very useful for checking coverage of tests that are
 294  * expected to induce DIF or DOF processing errors, and may be useful for
 295  * debugging problems in the DIF code generator or in DOF generation .  The
 296  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
 297  */
 298 #ifdef DEBUG
 299 static dtrace_errhash_t dtrace_errhash[DTRACE_ERRHASHSZ];
 300 static const char *dtrace_errlast;
 301 static kthread_t *dtrace_errthread;
 302 static kmutex_t dtrace_errlock;
 303 #endif
 304 
 305 /*
 306  * DTrace Macros and Constants
 307  *
 308  * These are various macros that are useful in various spots in the
 309  * implementation, along with a few random constants that have no meaning
 310  * outside of the implementation.  There is no real structure to this cpp
 311  * mishmash -- but is there ever?
 312  */
 313 #define DTRACE_HASHSTR(hash, probe)     \
 314         dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
 315 
 316 #define DTRACE_HASHNEXT(hash, probe)    \
 317         (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
 318 
 319 #define DTRACE_HASHPREV(hash, probe)    \
 320         (dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
 321 
 322 #define DTRACE_HASHEQ(hash, lhs, rhs)   \
 323         (strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
 324             *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
 325 
 326 #define DTRACE_AGGHASHSIZE_SLEW         17
 327 
 328 #define DTRACE_V4MAPPED_OFFSET          (sizeof (uint32_t) * 3)
 329 
 330 /*
 331  * The key for a thread-local variable consists of the lower 61 bits of the
 332  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
 333  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
 334  * equal to a variable identifier.  This is necessary (but not sufficient) to
 335  * assure that global associative arrays never collide with thread-local
 336  * variables.  To guarantee that they cannot collide, we must also define the
 337  * order for keying dynamic variables.  That order is:
 338  *
 339  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
 340  *
 341  * Because the variable-key and the tls-key are in orthogonal spaces, there is
 342  * no way for a global variable key signature to match a thread-local key
 343  * signature.
 344  */
 345 #define DTRACE_TLS_THRKEY(where) { \
 346         uint_t intr = 0; \
 347         uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
 348         for (; actv; actv >>= 1) \
 349                 intr++; \
 350         ASSERT(intr < (1 << 3)); \
 351         (where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
 352             (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
 353 }
 354 
 355 #define DT_BSWAP_8(x)   ((x) & 0xff)
 356 #define DT_BSWAP_16(x)  ((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
 357 #define DT_BSWAP_32(x)  ((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
 358 #define DT_BSWAP_64(x)  ((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
 359 
 360 #define DT_MASK_LO 0x00000000FFFFFFFFULL
 361 
 362 #define DTRACE_STORE(type, tomax, offset, what) \
 363         *((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
 364 
 365 #ifndef __i386
 366 #define DTRACE_ALIGNCHECK(addr, size, flags)                            \
 367         if (addr & (size - 1)) {                                    \
 368                 *flags |= CPU_DTRACE_BADALIGN;                          \
 369                 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;     \
 370                 return (0);                                             \
 371         }
 372 #else
 373 #define DTRACE_ALIGNCHECK(addr, size, flags)
 374 #endif
 375 
 376 /*
 377  * Test whether a range of memory starting at testaddr of size testsz falls
 378  * within the range of memory described by addr, sz.  We take care to avoid
 379  * problems with overflow and underflow of the unsigned quantities, and
 380  * disallow all negative sizes.  Ranges of size 0 are allowed.
 381  */
 382 #define DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
 383         ((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
 384         (testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
 385         (testaddr) + (testsz) >= (testaddr))
 386 
 387 /*
 388  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
 389  * alloc_sz on the righthand side of the comparison in order to avoid overflow
 390  * or underflow in the comparison with it.  This is simpler than the INRANGE
 391  * check above, because we know that the dtms_scratch_ptr is valid in the
 392  * range.  Allocations of size zero are allowed.
 393  */
 394 #define DTRACE_INSCRATCH(mstate, alloc_sz) \
 395         ((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
 396         (mstate)->dtms_scratch_ptr >= (alloc_sz))
 397 
 398 #define DTRACE_LOADFUNC(bits)                                           \
 399 /*CSTYLED*/                                                             \
 400 uint##bits##_t                                                          \
 401 dtrace_load##bits(uintptr_t addr)                                       \
 402 {                                                                       \
 403         size_t size = bits / NBBY;                                      \
 404         /*CSTYLED*/                                                     \
 405         uint##bits##_t rval;                                            \
 406         int i;                                                          \
 407         volatile uint16_t *flags = (volatile uint16_t *)                \
 408             &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;                    \
 409                                                                         \
 410         DTRACE_ALIGNCHECK(addr, size, flags);                           \
 411                                                                         \
 412         for (i = 0; i < dtrace_toxranges; i++) {                     \
 413                 if (addr >= dtrace_toxrange[i].dtt_limit)            \
 414                         continue;                                       \
 415                                                                         \
 416                 if (addr + size <= dtrace_toxrange[i].dtt_base)              \
 417                         continue;                                       \
 418                                                                         \
 419                 /*                                                      \
 420                  * This address falls within a toxic region; return 0.  \
 421                  */                                                     \
 422                 *flags |= CPU_DTRACE_BADADDR;                           \
 423                 cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;     \
 424                 return (0);                                             \
 425         }                                                               \
 426                                                                         \
 427         *flags |= CPU_DTRACE_NOFAULT;                                   \
 428         /*CSTYLED*/                                                     \
 429         rval = *((volatile uint##bits##_t *)addr);                      \
 430         *flags &= ~CPU_DTRACE_NOFAULT;                                      \
 431                                                                         \
 432         return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);           \
 433 }
 434 
 435 #ifdef _LP64
 436 #define dtrace_loadptr  dtrace_load64
 437 #else
 438 #define dtrace_loadptr  dtrace_load32
 439 #endif
 440 
 441 #define DTRACE_DYNHASH_FREE     0
 442 #define DTRACE_DYNHASH_SINK     1
 443 #define DTRACE_DYNHASH_VALID    2
 444 
 445 #define DTRACE_MATCH_FAIL       -1
 446 #define DTRACE_MATCH_NEXT       0
 447 #define DTRACE_MATCH_DONE       1
 448 #define DTRACE_ANCHORED(probe)  ((probe)->dtpr_func[0] != '\0')
 449 #define DTRACE_STATE_ALIGN      64
 450 
 451 #define DTRACE_FLAGS2FLT(flags)                                         \
 452         (((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :               \
 453         ((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :            \
 454         ((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :                \
 455         ((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :            \
 456         ((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :            \
 457         ((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :             \
 458         ((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :             \
 459         ((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :   \
 460         ((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :             \
 461         DTRACEFLT_UNKNOWN)
 462 
 463 #define DTRACEACT_ISSTRING(act)                                         \
 464         ((act)->dta_kind == DTRACEACT_DIFEXPR &&                     \
 465         (act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
 466 
 467 static size_t dtrace_strlen(const char *, size_t);
 468 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
 469 static void dtrace_enabling_provide(dtrace_provider_t *);
 470 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
 471 static void dtrace_enabling_matchall(void);
 472 static void dtrace_enabling_reap(void);
 473 static dtrace_state_t *dtrace_anon_grab(void);
 474 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
 475     dtrace_state_t *, uint64_t, uint64_t);
 476 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
 477 static void dtrace_buffer_drop(dtrace_buffer_t *);
 478 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
 479 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
 480     dtrace_state_t *, dtrace_mstate_t *);
 481 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
 482     dtrace_optval_t);
 483 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
 484 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
 485 static int dtrace_priv_proc(dtrace_state_t *, dtrace_mstate_t *);
 486 static void dtrace_getf_barrier(void);
 487 
 488 /*
 489  * DTrace Probe Context Functions
 490  *
 491  * These functions are called from probe context.  Because probe context is
 492  * any context in which C may be called, arbitrarily locks may be held,
 493  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
 494  * As a result, functions called from probe context may only call other DTrace
 495  * support functions -- they may not interact at all with the system at large.
 496  * (Note that the ASSERT macro is made probe-context safe by redefining it in
 497  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
 498  * loads are to be performed from probe context, they _must_ be in terms of
 499  * the safe dtrace_load*() variants.
 500  *
 501  * Some functions in this block are not actually called from probe context;
 502  * for these functions, there will be a comment above the function reading
 503  * "Note:  not called from probe context."
 504  */
 505 void
 506 dtrace_panic(const char *format, ...)
 507 {
 508         va_list alist;
 509 
 510         va_start(alist, format);
 511         dtrace_vpanic(format, alist);
 512         va_end(alist);
 513 }
 514 
 515 int
 516 dtrace_assfail(const char *a, const char *f, int l)
 517 {
 518         dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
 519 
 520         /*
 521          * We just need something here that even the most clever compiler
 522          * cannot optimize away.
 523          */
 524         return (a[(uintptr_t)f]);
 525 }
 526 
 527 /*
 528  * Atomically increment a specified error counter from probe context.
 529  */
 530 static void
 531 dtrace_error(uint32_t *counter)
 532 {
 533         /*
 534          * Most counters stored to in probe context are per-CPU counters.
 535          * However, there are some error conditions that are sufficiently
 536          * arcane that they don't merit per-CPU storage.  If these counters
 537          * are incremented concurrently on different CPUs, scalability will be
 538          * adversely affected -- but we don't expect them to be white-hot in a
 539          * correctly constructed enabling...
 540          */
 541         uint32_t oval, nval;
 542 
 543         do {
 544                 oval = *counter;
 545 
 546                 if ((nval = oval + 1) == 0) {
 547                         /*
 548                          * If the counter would wrap, set it to 1 -- assuring
 549                          * that the counter is never zero when we have seen
 550                          * errors.  (The counter must be 32-bits because we
 551                          * aren't guaranteed a 64-bit compare&swap operation.)
 552                          * To save this code both the infamy of being fingered
 553                          * by a priggish news story and the indignity of being
 554                          * the target of a neo-puritan witch trial, we're
 555                          * carefully avoiding any colorful description of the
 556                          * likelihood of this condition -- but suffice it to
 557                          * say that it is only slightly more likely than the
 558                          * overflow of predicate cache IDs, as discussed in
 559                          * dtrace_predicate_create().
 560                          */
 561                         nval = 1;
 562                 }
 563         } while (dtrace_cas32(counter, oval, nval) != oval);
 564 }
 565 
 566 /*
 567  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
 568  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
 569  */
 570 DTRACE_LOADFUNC(8)
 571 DTRACE_LOADFUNC(16)
 572 DTRACE_LOADFUNC(32)
 573 DTRACE_LOADFUNC(64)
 574 
 575 static int
 576 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
 577 {
 578         if (dest < mstate->dtms_scratch_base)
 579                 return (0);
 580 
 581         if (dest + size < dest)
 582                 return (0);
 583 
 584         if (dest + size > mstate->dtms_scratch_ptr)
 585                 return (0);
 586 
 587         return (1);
 588 }
 589 
 590 static int
 591 dtrace_canstore_statvar(uint64_t addr, size_t sz,
 592     dtrace_statvar_t **svars, int nsvars)
 593 {
 594         int i;
 595 
 596         for (i = 0; i < nsvars; i++) {
 597                 dtrace_statvar_t *svar = svars[i];
 598 
 599                 if (svar == NULL || svar->dtsv_size == 0)
 600                         continue;
 601 
 602                 if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
 603                         return (1);
 604         }
 605 
 606         return (0);
 607 }
 608 
 609 /*
 610  * Check to see if the address is within a memory region to which a store may
 611  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
 612  * region.  The caller of dtrace_canstore() is responsible for performing any
 613  * alignment checks that are needed before stores are actually executed.
 614  */
 615 static int
 616 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
 617     dtrace_vstate_t *vstate)
 618 {
 619         /*
 620          * First, check to see if the address is in scratch space...
 621          */
 622         if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
 623             mstate->dtms_scratch_size))
 624                 return (1);
 625 
 626         /*
 627          * Now check to see if it's a dynamic variable.  This check will pick
 628          * up both thread-local variables and any global dynamically-allocated
 629          * variables.
 630          */
 631         if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
 632             vstate->dtvs_dynvars.dtds_size)) {
 633                 dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
 634                 uintptr_t base = (uintptr_t)dstate->dtds_base +
 635                     (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
 636                 uintptr_t chunkoffs;
 637 
 638                 /*
 639                  * Before we assume that we can store here, we need to make
 640                  * sure that it isn't in our metadata -- storing to our
 641                  * dynamic variable metadata would corrupt our state.  For
 642                  * the range to not include any dynamic variable metadata,
 643                  * it must:
 644                  *
 645                  *      (1) Start above the hash table that is at the base of
 646                  *      the dynamic variable space
 647                  *
 648                  *      (2) Have a starting chunk offset that is beyond the
 649                  *      dtrace_dynvar_t that is at the base of every chunk
 650                  *
 651                  *      (3) Not span a chunk boundary
 652                  *
 653                  */
 654                 if (addr < base)
 655                         return (0);
 656 
 657                 chunkoffs = (addr - base) % dstate->dtds_chunksize;
 658 
 659                 if (chunkoffs < sizeof (dtrace_dynvar_t))
 660                         return (0);
 661 
 662                 if (chunkoffs + sz > dstate->dtds_chunksize)
 663                         return (0);
 664 
 665                 return (1);
 666         }
 667 
 668         /*
 669          * Finally, check the static local and global variables.  These checks
 670          * take the longest, so we perform them last.
 671          */
 672         if (dtrace_canstore_statvar(addr, sz,
 673             vstate->dtvs_locals, vstate->dtvs_nlocals))
 674                 return (1);
 675 
 676         if (dtrace_canstore_statvar(addr, sz,
 677             vstate->dtvs_globals, vstate->dtvs_nglobals))
 678                 return (1);
 679 
 680         return (0);
 681 }
 682 
 683 
 684 /*
 685  * Convenience routine to check to see if the address is within a memory
 686  * region in which a load may be issued given the user's privilege level;
 687  * if not, it sets the appropriate error flags and loads 'addr' into the
 688  * illegal value slot.
 689  *
 690  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
 691  * appropriate memory access protection.
 692  */
 693 static int
 694 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
 695     dtrace_vstate_t *vstate)
 696 {
 697         volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
 698         file_t *fp;
 699 
 700         /*
 701          * If we hold the privilege to read from kernel memory, then
 702          * everything is readable.
 703          */
 704         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
 705                 return (1);
 706 
 707         /*
 708          * You can obviously read that which you can store.
 709          */
 710         if (dtrace_canstore(addr, sz, mstate, vstate))
 711                 return (1);
 712 
 713         /*
 714          * We're allowed to read from our own string table.
 715          */
 716         if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
 717             mstate->dtms_difo->dtdo_strlen))
 718                 return (1);
 719 
 720         if (vstate->dtvs_state != NULL &&
 721             dtrace_priv_proc(vstate->dtvs_state, mstate)) {
 722                 proc_t *p;
 723 
 724                 /*
 725                  * When we have privileges to the current process, there are
 726                  * several context-related kernel structures that are safe to
 727                  * read, even absent the privilege to read from kernel memory.
 728                  * These reads are safe because these structures contain only
 729                  * state that (1) we're permitted to read, (2) is harmless or
 730                  * (3) contains pointers to additional kernel state that we're
 731                  * not permitted to read (and as such, do not present an
 732                  * opportunity for privilege escalation).  Finally (and
 733                  * critically), because of the nature of their relation with
 734                  * the current thread context, the memory associated with these
 735                  * structures cannot change over the duration of probe context,
 736                  * and it is therefore impossible for this memory to be
 737                  * deallocated and reallocated as something else while it's
 738                  * being operated upon.
 739                  */
 740                 if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t)))
 741                         return (1);
 742 
 743                 if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
 744                     sz, curthread->t_procp, sizeof (proc_t))) {
 745                         return (1);
 746                 }
 747 
 748                 if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
 749                     curthread->t_cred, sizeof (cred_t))) {
 750                         return (1);
 751                 }
 752 
 753                 if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
 754                     &(p->p_pidp->pid_id), sizeof (pid_t))) {
 755                         return (1);
 756                 }
 757 
 758                 if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
 759                     curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
 760                         return (1);
 761                 }
 762         }
 763 
 764         if ((fp = mstate->dtms_getf) != NULL) {
 765                 uintptr_t psz = sizeof (void *);
 766                 vnode_t *vp;
 767                 vnodeops_t *op;
 768 
 769                 /*
 770                  * When getf() returns a file_t, the enabling is implicitly
 771                  * granted the (transient) right to read the returned file_t
 772                  * as well as the v_path and v_op->vnop_name of the underlying
 773                  * vnode.  These accesses are allowed after a successful
 774                  * getf() because the members that they refer to cannot change
 775                  * once set -- and the barrier logic in the kernel's closef()
 776                  * path assures that the file_t and its referenced vode_t
 777                  * cannot themselves be stale (that is, it impossible for
 778                  * either dtms_getf itself or its f_vnode member to reference
 779                  * freed memory).
 780                  */
 781                 if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t)))
 782                         return (1);
 783 
 784                 if ((vp = fp->f_vnode) != NULL) {
 785                         if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz))
 786                                 return (1);
 787 
 788                         if (vp->v_path != NULL && DTRACE_INRANGE(addr, sz,
 789                             vp->v_path, strlen(vp->v_path) + 1)) {
 790                                 return (1);
 791                         }
 792 
 793                         if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz))
 794                                 return (1);
 795 
 796                         if ((op = vp->v_op) != NULL &&
 797                             DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
 798                                 return (1);
 799                         }
 800 
 801                         if (op != NULL && op->vnop_name != NULL &&
 802                             DTRACE_INRANGE(addr, sz, op->vnop_name,
 803                             strlen(op->vnop_name) + 1)) {
 804                                 return (1);
 805                         }
 806                 }
 807         }
 808 
 809         DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
 810         *illval = addr;
 811         return (0);
 812 }
 813 
 814 /*
 815  * Convenience routine to check to see if a given string is within a memory
 816  * region in which a load may be issued given the user's privilege level;
 817  * this exists so that we don't need to issue unnecessary dtrace_strlen()
 818  * calls in the event that the user has all privileges.
 819  */
 820 static int
 821 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
 822     dtrace_vstate_t *vstate)
 823 {
 824         size_t strsz;
 825 
 826         /*
 827          * If we hold the privilege to read from kernel memory, then
 828          * everything is readable.
 829          */
 830         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
 831                 return (1);
 832 
 833         strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
 834         if (dtrace_canload(addr, strsz, mstate, vstate))
 835                 return (1);
 836 
 837         return (0);
 838 }
 839 
 840 /*
 841  * Convenience routine to check to see if a given variable is within a memory
 842  * region in which a load may be issued given the user's privilege level.
 843  */
 844 static int
 845 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
 846     dtrace_vstate_t *vstate)
 847 {
 848         size_t sz, strsize;
 849         ASSERT(type->dtdt_flags & DIF_TF_BYREF);
 850 
 851         /*
 852          * If we hold the privilege to read from kernel memory, then
 853          * everything is readable.
 854          */
 855         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
 856                 return (1);
 857 
 858         if (type->dtdt_kind == DIF_TYPE_STRING) {
 859                 dtrace_state_t *state = vstate->dtvs_state;
 860 
 861                 if (state != NULL) {
 862                         strsize = state->dts_options[DTRACEOPT_STRSIZE];
 863                 } else {
 864                         /*
 865                          * In helper context, we have a NULL state; fall back
 866                          * to using the system-wide default for the string size
 867                          * in this case.
 868                          */
 869                         strsize = dtrace_strsize_default;
 870                 }
 871 
 872                 sz = dtrace_strlen(src, strsize) + 1;
 873         } else {
 874                 sz = type->dtdt_size;
 875         }
 876 
 877         return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
 878 }
 879 
 880 /*
 881  * Convert a string to a signed integer using safe loads.
 882  *
 883  * NOTE: This function uses various macros from strtolctype.h to manipulate
 884  * digit values, etc -- these have all been checked to ensure they make
 885  * no additional function calls.
 886  */
 887 static int64_t
 888 dtrace_strtoll(char *input, int base, size_t limit)
 889 {
 890         uintptr_t pos = (uintptr_t)input;
 891         int64_t val = 0;
 892         int x;
 893         boolean_t neg = B_FALSE;
 894         char c, cc, ccc;
 895         uintptr_t end = pos + limit;
 896 
 897         /*
 898          * Consume any whitespace preceding digits.
 899          */
 900         while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
 901                 pos++;
 902 
 903         /*
 904          * Handle an explicit sign if one is present.
 905          */
 906         if (c == '-' || c == '+') {
 907                 if (c == '-')
 908                         neg = B_TRUE;
 909                 c = dtrace_load8(++pos);
 910         }
 911 
 912         /*
 913          * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
 914          * if present.
 915          */
 916         if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
 917             cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
 918                 pos += 2;
 919                 c = ccc;
 920         }
 921 
 922         /*
 923          * Read in contiguous digits until the first non-digit character.
 924          */
 925         for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
 926             c = dtrace_load8(++pos))
 927                 val = val * base + x;
 928 
 929         return (neg ? -val : val);
 930 }
 931 
 932 /*
 933  * Compare two strings using safe loads.
 934  */
 935 static int
 936 dtrace_strncmp(char *s1, char *s2, size_t limit)
 937 {
 938         uint8_t c1, c2;
 939         volatile uint16_t *flags;
 940 
 941         if (s1 == s2 || limit == 0)
 942                 return (0);
 943 
 944         flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
 945 
 946         do {
 947                 if (s1 == NULL) {
 948                         c1 = '\0';
 949                 } else {
 950                         c1 = dtrace_load8((uintptr_t)s1++);
 951                 }
 952 
 953                 if (s2 == NULL) {
 954                         c2 = '\0';
 955                 } else {
 956                         c2 = dtrace_load8((uintptr_t)s2++);
 957                 }
 958 
 959                 if (c1 != c2)
 960                         return (c1 - c2);
 961         } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
 962 
 963         return (0);
 964 }
 965 
 966 /*
 967  * Compute strlen(s) for a string using safe memory accesses.  The additional
 968  * len parameter is used to specify a maximum length to ensure completion.
 969  */
 970 static size_t
 971 dtrace_strlen(const char *s, size_t lim)
 972 {
 973         uint_t len;
 974 
 975         for (len = 0; len != lim; len++) {
 976                 if (dtrace_load8((uintptr_t)s++) == '\0')
 977                         break;
 978         }
 979 
 980         return (len);
 981 }
 982 
 983 /*
 984  * Check if an address falls within a toxic region.
 985  */
 986 static int
 987 dtrace_istoxic(uintptr_t kaddr, size_t size)
 988 {
 989         uintptr_t taddr, tsize;
 990         int i;
 991 
 992         for (i = 0; i < dtrace_toxranges; i++) {
 993                 taddr = dtrace_toxrange[i].dtt_base;
 994                 tsize = dtrace_toxrange[i].dtt_limit - taddr;
 995 
 996                 if (kaddr - taddr < tsize) {
 997                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
 998                         cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
 999                         return (1);
1000                 }
1001 
1002                 if (taddr - kaddr < size) {
1003                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1004                         cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1005                         return (1);
1006                 }
1007         }
1008 
1009         return (0);
1010 }
1011 
1012 /*
1013  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1014  * memory specified by the DIF program.  The dst is assumed to be safe memory
1015  * that we can store to directly because it is managed by DTrace.  As with
1016  * standard bcopy, overlapping copies are handled properly.
1017  */
1018 static void
1019 dtrace_bcopy(const void *src, void *dst, size_t len)
1020 {
1021         if (len != 0) {
1022                 uint8_t *s1 = dst;
1023                 const uint8_t *s2 = src;
1024 
1025                 if (s1 <= s2) {
1026                         do {
1027                                 *s1++ = dtrace_load8((uintptr_t)s2++);
1028                         } while (--len != 0);
1029                 } else {
1030                         s2 += len;
1031                         s1 += len;
1032 
1033                         do {
1034                                 *--s1 = dtrace_load8((uintptr_t)--s2);
1035                         } while (--len != 0);
1036                 }
1037         }
1038 }
1039 
1040 /*
1041  * Copy src to dst using safe memory accesses, up to either the specified
1042  * length, or the point that a nul byte is encountered.  The src is assumed to
1043  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1044  * safe memory that we can store to directly because it is managed by DTrace.
1045  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1046  */
1047 static void
1048 dtrace_strcpy(const void *src, void *dst, size_t len)
1049 {
1050         if (len != 0) {
1051                 uint8_t *s1 = dst, c;
1052                 const uint8_t *s2 = src;
1053 
1054                 do {
1055                         *s1++ = c = dtrace_load8((uintptr_t)s2++);
1056                 } while (--len != 0 && c != '\0');
1057         }
1058 }
1059 
1060 /*
1061  * Copy src to dst, deriving the size and type from the specified (BYREF)
1062  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1063  * program.  The dst is assumed to be DTrace variable memory that is of the
1064  * specified type; we assume that we can store to directly.
1065  */
1066 static void
1067 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1068 {
1069         ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1070 
1071         if (type->dtdt_kind == DIF_TYPE_STRING) {
1072                 dtrace_strcpy(src, dst, type->dtdt_size);
1073         } else {
1074                 dtrace_bcopy(src, dst, type->dtdt_size);
1075         }
1076 }
1077 
1078 /*
1079  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1080  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1081  * safe memory that we can access directly because it is managed by DTrace.
1082  */
1083 static int
1084 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1085 {
1086         volatile uint16_t *flags;
1087 
1088         flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1089 
1090         if (s1 == s2)
1091                 return (0);
1092 
1093         if (s1 == NULL || s2 == NULL)
1094                 return (1);
1095 
1096         if (s1 != s2 && len != 0) {
1097                 const uint8_t *ps1 = s1;
1098                 const uint8_t *ps2 = s2;
1099 
1100                 do {
1101                         if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1102                                 return (1);
1103                 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1104         }
1105         return (0);
1106 }
1107 
1108 /*
1109  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1110  * is for safe DTrace-managed memory only.
1111  */
1112 static void
1113 dtrace_bzero(void *dst, size_t len)
1114 {
1115         uchar_t *cp;
1116 
1117         for (cp = dst; len != 0; len--)
1118                 *cp++ = 0;
1119 }
1120 
1121 static void
1122 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1123 {
1124         uint64_t result[2];
1125 
1126         result[0] = addend1[0] + addend2[0];
1127         result[1] = addend1[1] + addend2[1] +
1128             (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1129 
1130         sum[0] = result[0];
1131         sum[1] = result[1];
1132 }
1133 
1134 /*
1135  * Shift the 128-bit value in a by b. If b is positive, shift left.
1136  * If b is negative, shift right.
1137  */
1138 static void
1139 dtrace_shift_128(uint64_t *a, int b)
1140 {
1141         uint64_t mask;
1142 
1143         if (b == 0)
1144                 return;
1145 
1146         if (b < 0) {
1147                 b = -b;
1148                 if (b >= 64) {
1149                         a[0] = a[1] >> (b - 64);
1150                         a[1] = 0;
1151                 } else {
1152                         a[0] >>= b;
1153                         mask = 1LL << (64 - b);
1154                         mask -= 1;
1155                         a[0] |= ((a[1] & mask) << (64 - b));
1156                         a[1] >>= b;
1157                 }
1158         } else {
1159                 if (b >= 64) {
1160                         a[1] = a[0] << (b - 64);
1161                         a[0] = 0;
1162                 } else {
1163                         a[1] <<= b;
1164                         mask = a[0] >> (64 - b);
1165                         a[1] |= mask;
1166                         a[0] <<= b;
1167                 }
1168         }
1169 }
1170 
1171 /*
1172  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1173  * use native multiplication on those, and then re-combine into the
1174  * resulting 128-bit value.
1175  *
1176  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1177  *     hi1 * hi2 << 64 +
1178  *     hi1 * lo2 << 32 +
1179  *     hi2 * lo1 << 32 +
1180  *     lo1 * lo2
1181  */
1182 static void
1183 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1184 {
1185         uint64_t hi1, hi2, lo1, lo2;
1186         uint64_t tmp[2];
1187 
1188         hi1 = factor1 >> 32;
1189         hi2 = factor2 >> 32;
1190 
1191         lo1 = factor1 & DT_MASK_LO;
1192         lo2 = factor2 & DT_MASK_LO;
1193 
1194         product[0] = lo1 * lo2;
1195         product[1] = hi1 * hi2;
1196 
1197         tmp[0] = hi1 * lo2;
1198         tmp[1] = 0;
1199         dtrace_shift_128(tmp, 32);
1200         dtrace_add_128(product, tmp, product);
1201 
1202         tmp[0] = hi2 * lo1;
1203         tmp[1] = 0;
1204         dtrace_shift_128(tmp, 32);
1205         dtrace_add_128(product, tmp, product);
1206 }
1207 
1208 /*
1209  * This privilege check should be used by actions and subroutines to
1210  * verify that the user credentials of the process that enabled the
1211  * invoking ECB match the target credentials
1212  */
1213 static int
1214 dtrace_priv_proc_common_user(dtrace_state_t *state)
1215 {
1216         cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1217 
1218         /*
1219          * We should always have a non-NULL state cred here, since if cred
1220          * is null (anonymous tracing), we fast-path bypass this routine.
1221          */
1222         ASSERT(s_cr != NULL);
1223 
1224         if ((cr = CRED()) != NULL &&
1225             s_cr->cr_uid == cr->cr_uid &&
1226             s_cr->cr_uid == cr->cr_ruid &&
1227             s_cr->cr_uid == cr->cr_suid &&
1228             s_cr->cr_gid == cr->cr_gid &&
1229             s_cr->cr_gid == cr->cr_rgid &&
1230             s_cr->cr_gid == cr->cr_sgid)
1231                 return (1);
1232 
1233         return (0);
1234 }
1235 
1236 /*
1237  * This privilege check should be used by actions and subroutines to
1238  * verify that the zone of the process that enabled the invoking ECB
1239  * matches the target credentials
1240  */
1241 static int
1242 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1243 {
1244         cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1245 
1246         /*
1247          * We should always have a non-NULL state cred here, since if cred
1248          * is null (anonymous tracing), we fast-path bypass this routine.
1249          */
1250         ASSERT(s_cr != NULL);
1251 
1252         if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1253                 return (1);
1254 
1255         return (0);
1256 }
1257 
1258 /*
1259  * This privilege check should be used by actions and subroutines to
1260  * verify that the process has not setuid or changed credentials.
1261  */
1262 static int
1263 dtrace_priv_proc_common_nocd()
1264 {
1265         proc_t *proc;
1266 
1267         if ((proc = ttoproc(curthread)) != NULL &&
1268             !(proc->p_flag & SNOCD))
1269                 return (1);
1270 
1271         return (0);
1272 }
1273 
1274 static int
1275 dtrace_priv_proc_destructive(dtrace_state_t *state, dtrace_mstate_t *mstate)
1276 {
1277         int action = state->dts_cred.dcr_action;
1278 
1279         if (!(mstate->dtms_access & DTRACE_ACCESS_PROC))
1280                 goto bad;
1281 
1282         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1283             dtrace_priv_proc_common_zone(state) == 0)
1284                 goto bad;
1285 
1286         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1287             dtrace_priv_proc_common_user(state) == 0)
1288                 goto bad;
1289 
1290         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1291             dtrace_priv_proc_common_nocd() == 0)
1292                 goto bad;
1293 
1294         return (1);
1295 
1296 bad:
1297         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1298 
1299         return (0);
1300 }
1301 
1302 static int
1303 dtrace_priv_proc_control(dtrace_state_t *state, dtrace_mstate_t *mstate)
1304 {
1305         if (mstate->dtms_access & DTRACE_ACCESS_PROC) {
1306                 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1307                         return (1);
1308 
1309                 if (dtrace_priv_proc_common_zone(state) &&
1310                     dtrace_priv_proc_common_user(state) &&
1311                     dtrace_priv_proc_common_nocd())
1312                         return (1);
1313         }
1314 
1315         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1316 
1317         return (0);
1318 }
1319 
1320 static int
1321 dtrace_priv_proc(dtrace_state_t *state, dtrace_mstate_t *mstate)
1322 {
1323         if ((mstate->dtms_access & DTRACE_ACCESS_PROC) &&
1324             (state->dts_cred.dcr_action & DTRACE_CRA_PROC))
1325                 return (1);
1326 
1327         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1328 
1329         return (0);
1330 }
1331 
1332 static int
1333 dtrace_priv_kernel(dtrace_state_t *state)
1334 {
1335         if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1336                 return (1);
1337 
1338         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1339 
1340         return (0);
1341 }
1342 
1343 static int
1344 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1345 {
1346         if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1347                 return (1);
1348 
1349         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1350 
1351         return (0);
1352 }
1353 
1354 /*
1355  * Determine if the dte_cond of the specified ECB allows for processing of
1356  * the current probe to continue.  Note that this routine may allow continued
1357  * processing, but with access(es) stripped from the mstate's dtms_access
1358  * field.
1359  */
1360 static int
1361 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1362     dtrace_ecb_t *ecb)
1363 {
1364         dtrace_probe_t *probe = ecb->dte_probe;
1365         dtrace_provider_t *prov = probe->dtpr_provider;
1366         dtrace_pops_t *pops = &prov->dtpv_pops;
1367         int mode = DTRACE_MODE_NOPRIV_DROP;
1368 
1369         ASSERT(ecb->dte_cond);
1370 
1371         if (pops->dtps_mode != NULL) {
1372                 mode = pops->dtps_mode(prov->dtpv_arg,
1373                     probe->dtpr_id, probe->dtpr_arg);
1374 
1375                 ASSERT(mode & (DTRACE_MODE_USER | DTRACE_MODE_KERNEL));
1376                 ASSERT(mode & (DTRACE_MODE_NOPRIV_RESTRICT |
1377                     DTRACE_MODE_NOPRIV_DROP));
1378         }
1379 
1380         /*
1381          * If the dte_cond bits indicate that this consumer is only allowed to
1382          * see user-mode firings of this probe, check that the probe was fired
1383          * while in a user context.  If that's not the case, use the policy
1384          * specified by the provider to determine if we drop the probe or
1385          * merely restrict operation.
1386          */
1387         if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1388                 ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1389 
1390                 if (!(mode & DTRACE_MODE_USER)) {
1391                         if (mode & DTRACE_MODE_NOPRIV_DROP)
1392                                 return (0);
1393 
1394                         mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1395                 }
1396         }
1397 
1398         /*
1399          * This is more subtle than it looks. We have to be absolutely certain
1400          * that CRED() isn't going to change out from under us so it's only
1401          * legit to examine that structure if we're in constrained situations.
1402          * Currently, the only times we'll this check is if a non-super-user
1403          * has enabled the profile or syscall providers -- providers that
1404          * allow visibility of all processes. For the profile case, the check
1405          * above will ensure that we're examining a user context.
1406          */
1407         if (ecb->dte_cond & DTRACE_COND_OWNER) {
1408                 cred_t *cr;
1409                 cred_t *s_cr = state->dts_cred.dcr_cred;
1410                 proc_t *proc;
1411 
1412                 ASSERT(s_cr != NULL);
1413 
1414                 if ((cr = CRED()) == NULL ||
1415                     s_cr->cr_uid != cr->cr_uid ||
1416                     s_cr->cr_uid != cr->cr_ruid ||
1417                     s_cr->cr_uid != cr->cr_suid ||
1418                     s_cr->cr_gid != cr->cr_gid ||
1419                     s_cr->cr_gid != cr->cr_rgid ||
1420                     s_cr->cr_gid != cr->cr_sgid ||
1421                     (proc = ttoproc(curthread)) == NULL ||
1422                     (proc->p_flag & SNOCD)) {
1423                         if (mode & DTRACE_MODE_NOPRIV_DROP)
1424                                 return (0);
1425 
1426                         mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1427                 }
1428         }
1429 
1430         /*
1431          * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1432          * in our zone, check to see if our mode policy is to restrict rather
1433          * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1434          * and DTRACE_ACCESS_ARGS
1435          */
1436         if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1437                 cred_t *cr;
1438                 cred_t *s_cr = state->dts_cred.dcr_cred;
1439 
1440                 ASSERT(s_cr != NULL);
1441 
1442                 if ((cr = CRED()) == NULL ||
1443                     s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1444                         if (mode & DTRACE_MODE_NOPRIV_DROP)
1445                                 return (0);
1446 
1447                         mstate->dtms_access &=
1448                             ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1449                 }
1450         }
1451 
1452         /*
1453          * By merits of being in this code path at all, we have limited
1454          * privileges.  If the provider has indicated that limited privileges
1455          * are to denote restricted operation, strip off the ability to access
1456          * arguments.
1457          */
1458         if (mode & DTRACE_MODE_LIMITEDPRIV_RESTRICT)
1459                 mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1460 
1461         return (1);
1462 }
1463 
1464 /*
1465  * Note:  not called from probe context.  This function is called
1466  * asynchronously (and at a regular interval) from outside of probe context to
1467  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1468  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1469  */
1470 void
1471 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1472 {
1473         dtrace_dynvar_t *dirty;
1474         dtrace_dstate_percpu_t *dcpu;
1475         dtrace_dynvar_t **rinsep;
1476         int i, j, work = 0;
1477 
1478         for (i = 0; i < NCPU; i++) {
1479                 dcpu = &dstate->dtds_percpu[i];
1480                 rinsep = &dcpu->dtdsc_rinsing;
1481 
1482                 /*
1483                  * If the dirty list is NULL, there is no dirty work to do.
1484                  */
1485                 if (dcpu->dtdsc_dirty == NULL)
1486                         continue;
1487 
1488                 if (dcpu->dtdsc_rinsing != NULL) {
1489                         /*
1490                          * If the rinsing list is non-NULL, then it is because
1491                          * this CPU was selected to accept another CPU's
1492                          * dirty list -- and since that time, dirty buffers
1493                          * have accumulated.  This is a highly unlikely
1494                          * condition, but we choose to ignore the dirty
1495                          * buffers -- they'll be picked up a future cleanse.
1496                          */
1497                         continue;
1498                 }
1499 
1500                 if (dcpu->dtdsc_clean != NULL) {
1501                         /*
1502                          * If the clean list is non-NULL, then we're in a
1503                          * situation where a CPU has done deallocations (we
1504                          * have a non-NULL dirty list) but no allocations (we
1505                          * also have a non-NULL clean list).  We can't simply
1506                          * move the dirty list into the clean list on this
1507                          * CPU, yet we also don't want to allow this condition
1508                          * to persist, lest a short clean list prevent a
1509                          * massive dirty list from being cleaned (which in
1510                          * turn could lead to otherwise avoidable dynamic
1511                          * drops).  To deal with this, we look for some CPU
1512                          * with a NULL clean list, NULL dirty list, and NULL
1513                          * rinsing list -- and then we borrow this CPU to
1514                          * rinse our dirty list.
1515                          */
1516                         for (j = 0; j < NCPU; j++) {
1517                                 dtrace_dstate_percpu_t *rinser;
1518 
1519                                 rinser = &dstate->dtds_percpu[j];
1520 
1521                                 if (rinser->dtdsc_rinsing != NULL)
1522                                         continue;
1523 
1524                                 if (rinser->dtdsc_dirty != NULL)
1525                                         continue;
1526 
1527                                 if (rinser->dtdsc_clean != NULL)
1528                                         continue;
1529 
1530                                 rinsep = &rinser->dtdsc_rinsing;
1531                                 break;
1532                         }
1533 
1534                         if (j == NCPU) {
1535                                 /*
1536                                  * We were unable to find another CPU that
1537                                  * could accept this dirty list -- we are
1538                                  * therefore unable to clean it now.
1539                                  */
1540                                 dtrace_dynvar_failclean++;
1541                                 continue;
1542                         }
1543                 }
1544 
1545                 work = 1;
1546 
1547                 /*
1548                  * Atomically move the dirty list aside.
1549                  */
1550                 do {
1551                         dirty = dcpu->dtdsc_dirty;
1552 
1553                         /*
1554                          * Before we zap the dirty list, set the rinsing list.
1555                          * (This allows for a potential assertion in
1556                          * dtrace_dynvar():  if a free dynamic variable appears
1557                          * on a hash chain, either the dirty list or the
1558                          * rinsing list for some CPU must be non-NULL.)
1559                          */
1560                         *rinsep = dirty;
1561                         dtrace_membar_producer();
1562                 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1563                     dirty, NULL) != dirty);
1564         }
1565 
1566         if (!work) {
1567                 /*
1568                  * We have no work to do; we can simply return.
1569                  */
1570                 return;
1571         }
1572 
1573         dtrace_sync();
1574 
1575         for (i = 0; i < NCPU; i++) {
1576                 dcpu = &dstate->dtds_percpu[i];
1577 
1578                 if (dcpu->dtdsc_rinsing == NULL)
1579                         continue;
1580 
1581                 /*
1582                  * We are now guaranteed that no hash chain contains a pointer
1583                  * into this dirty list; we can make it clean.
1584                  */
1585                 ASSERT(dcpu->dtdsc_clean == NULL);
1586                 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1587                 dcpu->dtdsc_rinsing = NULL;
1588         }
1589 
1590         /*
1591          * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1592          * sure that all CPUs have seen all of the dtdsc_clean pointers.
1593          * This prevents a race whereby a CPU incorrectly decides that
1594          * the state should be something other than DTRACE_DSTATE_CLEAN
1595          * after dtrace_dynvar_clean() has completed.
1596          */
1597         dtrace_sync();
1598 
1599         dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1600 }
1601 
1602 /*
1603  * Depending on the value of the op parameter, this function looks-up,
1604  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1605  * allocation is requested, this function will return a pointer to a
1606  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1607  * variable can be allocated.  If NULL is returned, the appropriate counter
1608  * will be incremented.
1609  */
1610 dtrace_dynvar_t *
1611 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1612     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1613     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1614 {
1615         uint64_t hashval = DTRACE_DYNHASH_VALID;
1616         dtrace_dynhash_t *hash = dstate->dtds_hash;
1617         dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1618         processorid_t me = CPU->cpu_id, cpu = me;
1619         dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1620         size_t bucket, ksize;
1621         size_t chunksize = dstate->dtds_chunksize;
1622         uintptr_t kdata, lock, nstate;
1623         uint_t i;
1624 
1625         ASSERT(nkeys != 0);
1626 
1627         /*
1628          * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1629          * algorithm.  For the by-value portions, we perform the algorithm in
1630          * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1631          * bit, and seems to have only a minute effect on distribution.  For
1632          * the by-reference data, we perform "One-at-a-time" iterating (safely)
1633          * over each referenced byte.  It's painful to do this, but it's much
1634          * better than pathological hash distribution.  The efficacy of the
1635          * hashing algorithm (and a comparison with other algorithms) may be
1636          * found by running the ::dtrace_dynstat MDB dcmd.
1637          */
1638         for (i = 0; i < nkeys; i++) {
1639                 if (key[i].dttk_size == 0) {
1640                         uint64_t val = key[i].dttk_value;
1641 
1642                         hashval += (val >> 48) & 0xffff;
1643                         hashval += (hashval << 10);
1644                         hashval ^= (hashval >> 6);
1645 
1646                         hashval += (val >> 32) & 0xffff;
1647                         hashval += (hashval << 10);
1648                         hashval ^= (hashval >> 6);
1649 
1650                         hashval += (val >> 16) & 0xffff;
1651                         hashval += (hashval << 10);
1652                         hashval ^= (hashval >> 6);
1653 
1654                         hashval += val & 0xffff;
1655                         hashval += (hashval << 10);
1656                         hashval ^= (hashval >> 6);
1657                 } else {
1658                         /*
1659                          * This is incredibly painful, but it beats the hell
1660                          * out of the alternative.
1661                          */
1662                         uint64_t j, size = key[i].dttk_size;
1663                         uintptr_t base = (uintptr_t)key[i].dttk_value;
1664 
1665                         if (!dtrace_canload(base, size, mstate, vstate))
1666                                 break;
1667 
1668                         for (j = 0; j < size; j++) {
1669                                 hashval += dtrace_load8(base + j);
1670                                 hashval += (hashval << 10);
1671                                 hashval ^= (hashval >> 6);
1672                         }
1673                 }
1674         }
1675 
1676         if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1677                 return (NULL);
1678 
1679         hashval += (hashval << 3);
1680         hashval ^= (hashval >> 11);
1681         hashval += (hashval << 15);
1682 
1683         /*
1684          * There is a remote chance (ideally, 1 in 2^31) that our hashval
1685          * comes out to be one of our two sentinel hash values.  If this
1686          * actually happens, we set the hashval to be a value known to be a
1687          * non-sentinel value.
1688          */
1689         if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1690                 hashval = DTRACE_DYNHASH_VALID;
1691 
1692         /*
1693          * Yes, it's painful to do a divide here.  If the cycle count becomes
1694          * important here, tricks can be pulled to reduce it.  (However, it's
1695          * critical that hash collisions be kept to an absolute minimum;
1696          * they're much more painful than a divide.)  It's better to have a
1697          * solution that generates few collisions and still keeps things
1698          * relatively simple.
1699          */
1700         bucket = hashval % dstate->dtds_hashsize;
1701 
1702         if (op == DTRACE_DYNVAR_DEALLOC) {
1703                 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1704 
1705                 for (;;) {
1706                         while ((lock = *lockp) & 1)
1707                                 continue;
1708 
1709                         if (dtrace_casptr((void *)lockp,
1710                             (void *)lock, (void *)(lock + 1)) == (void *)lock)
1711                                 break;
1712                 }
1713 
1714                 dtrace_membar_producer();
1715         }
1716 
1717 top:
1718         prev = NULL;
1719         lock = hash[bucket].dtdh_lock;
1720 
1721         dtrace_membar_consumer();
1722 
1723         start = hash[bucket].dtdh_chain;
1724         ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1725             start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1726             op != DTRACE_DYNVAR_DEALLOC));
1727 
1728         for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1729                 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1730                 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1731 
1732                 if (dvar->dtdv_hashval != hashval) {
1733                         if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1734                                 /*
1735                                  * We've reached the sink, and therefore the
1736                                  * end of the hash chain; we can kick out of
1737                                  * the loop knowing that we have seen a valid
1738                                  * snapshot of state.
1739                                  */
1740                                 ASSERT(dvar->dtdv_next == NULL);
1741                                 ASSERT(dvar == &dtrace_dynhash_sink);
1742                                 break;
1743                         }
1744 
1745                         if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1746                                 /*
1747                                  * We've gone off the rails:  somewhere along
1748                                  * the line, one of the members of this hash
1749                                  * chain was deleted.  Note that we could also
1750                                  * detect this by simply letting this loop run
1751                                  * to completion, as we would eventually hit
1752                                  * the end of the dirty list.  However, we
1753                                  * want to avoid running the length of the
1754                                  * dirty list unnecessarily (it might be quite
1755                                  * long), so we catch this as early as
1756                                  * possible by detecting the hash marker.  In
1757                                  * this case, we simply set dvar to NULL and
1758                                  * break; the conditional after the loop will
1759                                  * send us back to top.
1760                                  */
1761                                 dvar = NULL;
1762                                 break;
1763                         }
1764 
1765                         goto next;
1766                 }
1767 
1768                 if (dtuple->dtt_nkeys != nkeys)
1769                         goto next;
1770 
1771                 for (i = 0; i < nkeys; i++, dkey++) {
1772                         if (dkey->dttk_size != key[i].dttk_size)
1773                                 goto next; /* size or type mismatch */
1774 
1775                         if (dkey->dttk_size != 0) {
1776                                 if (dtrace_bcmp(
1777                                     (void *)(uintptr_t)key[i].dttk_value,
1778                                     (void *)(uintptr_t)dkey->dttk_value,
1779                                     dkey->dttk_size))
1780                                         goto next;
1781                         } else {
1782                                 if (dkey->dttk_value != key[i].dttk_value)
1783                                         goto next;
1784                         }
1785                 }
1786 
1787                 if (op != DTRACE_DYNVAR_DEALLOC)
1788                         return (dvar);
1789 
1790                 ASSERT(dvar->dtdv_next == NULL ||
1791                     dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1792 
1793                 if (prev != NULL) {
1794                         ASSERT(hash[bucket].dtdh_chain != dvar);
1795                         ASSERT(start != dvar);
1796                         ASSERT(prev->dtdv_next == dvar);
1797                         prev->dtdv_next = dvar->dtdv_next;
1798                 } else {
1799                         if (dtrace_casptr(&hash[bucket].dtdh_chain,
1800                             start, dvar->dtdv_next) != start) {
1801                                 /*
1802                                  * We have failed to atomically swing the
1803                                  * hash table head pointer, presumably because
1804                                  * of a conflicting allocation on another CPU.
1805                                  * We need to reread the hash chain and try
1806                                  * again.
1807                                  */
1808                                 goto top;
1809                         }
1810                 }
1811 
1812                 dtrace_membar_producer();
1813 
1814                 /*
1815                  * Now set the hash value to indicate that it's free.
1816                  */
1817                 ASSERT(hash[bucket].dtdh_chain != dvar);
1818                 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1819 
1820                 dtrace_membar_producer();
1821 
1822                 /*
1823                  * Set the next pointer to point at the dirty list, and
1824                  * atomically swing the dirty pointer to the newly freed dvar.
1825                  */
1826                 do {
1827                         next = dcpu->dtdsc_dirty;
1828                         dvar->dtdv_next = next;
1829                 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1830 
1831                 /*
1832                  * Finally, unlock this hash bucket.
1833                  */
1834                 ASSERT(hash[bucket].dtdh_lock == lock);
1835                 ASSERT(lock & 1);
1836                 hash[bucket].dtdh_lock++;
1837 
1838                 return (NULL);
1839 next:
1840                 prev = dvar;
1841                 continue;
1842         }
1843 
1844         if (dvar == NULL) {
1845                 /*
1846                  * If dvar is NULL, it is because we went off the rails:
1847                  * one of the elements that we traversed in the hash chain
1848                  * was deleted while we were traversing it.  In this case,
1849                  * we assert that we aren't doing a dealloc (deallocs lock
1850                  * the hash bucket to prevent themselves from racing with
1851                  * one another), and retry the hash chain traversal.
1852                  */
1853                 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1854                 goto top;
1855         }
1856 
1857         if (op != DTRACE_DYNVAR_ALLOC) {
1858                 /*
1859                  * If we are not to allocate a new variable, we want to
1860                  * return NULL now.  Before we return, check that the value
1861                  * of the lock word hasn't changed.  If it has, we may have
1862                  * seen an inconsistent snapshot.
1863                  */
1864                 if (op == DTRACE_DYNVAR_NOALLOC) {
1865                         if (hash[bucket].dtdh_lock != lock)
1866                                 goto top;
1867                 } else {
1868                         ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1869                         ASSERT(hash[bucket].dtdh_lock == lock);
1870                         ASSERT(lock & 1);
1871                         hash[bucket].dtdh_lock++;
1872                 }
1873 
1874                 return (NULL);
1875         }
1876 
1877         /*
1878          * We need to allocate a new dynamic variable.  The size we need is the
1879          * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1880          * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1881          * the size of any referred-to data (dsize).  We then round the final
1882          * size up to the chunksize for allocation.
1883          */
1884         for (ksize = 0, i = 0; i < nkeys; i++)
1885                 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1886 
1887         /*
1888          * This should be pretty much impossible, but could happen if, say,
1889          * strange DIF specified the tuple.  Ideally, this should be an
1890          * assertion and not an error condition -- but that requires that the
1891          * chunksize calculation in dtrace_difo_chunksize() be absolutely
1892          * bullet-proof.  (That is, it must not be able to be fooled by
1893          * malicious DIF.)  Given the lack of backwards branches in DIF,
1894          * solving this would presumably not amount to solving the Halting
1895          * Problem -- but it still seems awfully hard.
1896          */
1897         if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1898             ksize + dsize > chunksize) {
1899                 dcpu->dtdsc_drops++;
1900                 return (NULL);
1901         }
1902 
1903         nstate = DTRACE_DSTATE_EMPTY;
1904 
1905         do {
1906 retry:
1907                 free = dcpu->dtdsc_free;
1908 
1909                 if (free == NULL) {
1910                         dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1911                         void *rval;
1912 
1913                         if (clean == NULL) {
1914                                 /*
1915                                  * We're out of dynamic variable space on
1916                                  * this CPU.  Unless we have tried all CPUs,
1917                                  * we'll try to allocate from a different
1918                                  * CPU.
1919                                  */
1920                                 switch (dstate->dtds_state) {
1921                                 case DTRACE_DSTATE_CLEAN: {
1922                                         void *sp = &dstate->dtds_state;
1923 
1924                                         if (++cpu >= NCPU)
1925                                                 cpu = 0;
1926 
1927                                         if (dcpu->dtdsc_dirty != NULL &&
1928                                             nstate == DTRACE_DSTATE_EMPTY)
1929                                                 nstate = DTRACE_DSTATE_DIRTY;
1930 
1931                                         if (dcpu->dtdsc_rinsing != NULL)
1932                                                 nstate = DTRACE_DSTATE_RINSING;
1933 
1934                                         dcpu = &dstate->dtds_percpu[cpu];
1935 
1936                                         if (cpu != me)
1937                                                 goto retry;
1938 
1939                                         (void) dtrace_cas32(sp,
1940                                             DTRACE_DSTATE_CLEAN, nstate);
1941 
1942                                         /*
1943                                          * To increment the correct bean
1944                                          * counter, take another lap.
1945                                          */
1946                                         goto retry;
1947                                 }
1948 
1949                                 case DTRACE_DSTATE_DIRTY:
1950                                         dcpu->dtdsc_dirty_drops++;
1951                                         break;
1952 
1953                                 case DTRACE_DSTATE_RINSING:
1954                                         dcpu->dtdsc_rinsing_drops++;
1955                                         break;
1956 
1957                                 case DTRACE_DSTATE_EMPTY:
1958                                         dcpu->dtdsc_drops++;
1959                                         break;
1960                                 }
1961 
1962                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1963                                 return (NULL);
1964                         }
1965 
1966                         /*
1967                          * The clean list appears to be non-empty.  We want to
1968                          * move the clean list to the free list; we start by
1969                          * moving the clean pointer aside.
1970                          */
1971                         if (dtrace_casptr(&dcpu->dtdsc_clean,
1972                             clean, NULL) != clean) {
1973                                 /*
1974                                  * We are in one of two situations:
1975                                  *
1976                                  *  (a) The clean list was switched to the
1977                                  *      free list by another CPU.
1978                                  *
1979                                  *  (b) The clean list was added to by the
1980                                  *      cleansing cyclic.
1981                                  *
1982                                  * In either of these situations, we can
1983                                  * just reattempt the free list allocation.
1984                                  */
1985                                 goto retry;
1986                         }
1987 
1988                         ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1989 
1990                         /*
1991                          * Now we'll move the clean list to our free list.
1992                          * It's impossible for this to fail:  the only way
1993                          * the free list can be updated is through this
1994                          * code path, and only one CPU can own the clean list.
1995                          * Thus, it would only be possible for this to fail if
1996                          * this code were racing with dtrace_dynvar_clean().
1997                          * (That is, if dtrace_dynvar_clean() updated the clean
1998                          * list, and we ended up racing to update the free
1999                          * list.)  This race is prevented by the dtrace_sync()
2000                          * in dtrace_dynvar_clean() -- which flushes the
2001                          * owners of the clean lists out before resetting
2002                          * the clean lists.
2003                          */
2004                         dcpu = &dstate->dtds_percpu[me];
2005                         rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2006                         ASSERT(rval == NULL);
2007                         goto retry;
2008                 }
2009 
2010                 dvar = free;
2011                 new_free = dvar->dtdv_next;
2012         } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2013 
2014         /*
2015          * We have now allocated a new chunk.  We copy the tuple keys into the
2016          * tuple array and copy any referenced key data into the data space
2017          * following the tuple array.  As we do this, we relocate dttk_value
2018          * in the final tuple to point to the key data address in the chunk.
2019          */
2020         kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2021         dvar->dtdv_data = (void *)(kdata + ksize);
2022         dvar->dtdv_tuple.dtt_nkeys = nkeys;
2023 
2024         for (i = 0; i < nkeys; i++) {
2025                 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2026                 size_t kesize = key[i].dttk_size;
2027 
2028                 if (kesize != 0) {
2029                         dtrace_bcopy(
2030                             (const void *)(uintptr_t)key[i].dttk_value,
2031                             (void *)kdata, kesize);
2032                         dkey->dttk_value = kdata;
2033                         kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2034                 } else {
2035                         dkey->dttk_value = key[i].dttk_value;
2036                 }
2037 
2038                 dkey->dttk_size = kesize;
2039         }
2040 
2041         ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2042         dvar->dtdv_hashval = hashval;
2043         dvar->dtdv_next = start;
2044 
2045         if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2046                 return (dvar);
2047 
2048         /*
2049          * The cas has failed.  Either another CPU is adding an element to
2050          * this hash chain, or another CPU is deleting an element from this
2051          * hash chain.  The simplest way to deal with both of these cases
2052          * (though not necessarily the most efficient) is to free our
2053          * allocated block and tail-call ourselves.  Note that the free is
2054          * to the dirty list and _not_ to the free list.  This is to prevent
2055          * races with allocators, above.
2056          */
2057         dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2058 
2059         dtrace_membar_producer();
2060 
2061         do {
2062                 free = dcpu->dtdsc_dirty;
2063                 dvar->dtdv_next = free;
2064         } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2065 
2066         return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2067 }
2068 
2069 /*ARGSUSED*/
2070 static void
2071 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2072 {
2073         if ((int64_t)nval < (int64_t)*oval)
2074                 *oval = nval;
2075 }
2076 
2077 /*ARGSUSED*/
2078 static void
2079 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2080 {
2081         if ((int64_t)nval > (int64_t)*oval)
2082                 *oval = nval;
2083 }
2084 
2085 static void
2086 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2087 {
2088         int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2089         int64_t val = (int64_t)nval;
2090 
2091         if (val < 0) {
2092                 for (i = 0; i < zero; i++) {
2093                         if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2094                                 quanta[i] += incr;
2095                                 return;
2096                         }
2097                 }
2098         } else {
2099                 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2100                         if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2101                                 quanta[i - 1] += incr;
2102                                 return;
2103                         }
2104                 }
2105 
2106                 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2107                 return;
2108         }
2109 
2110         ASSERT(0);
2111 }
2112 
2113 static void
2114 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2115 {
2116         uint64_t arg = *lquanta++;
2117         int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2118         uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2119         uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2120         int32_t val = (int32_t)nval, level;
2121 
2122         ASSERT(step != 0);
2123         ASSERT(levels != 0);
2124 
2125         if (val < base) {
2126                 /*
2127                  * This is an underflow.
2128                  */
2129                 lquanta[0] += incr;
2130                 return;
2131         }
2132 
2133         level = (val - base) / step;
2134 
2135         if (level < levels) {
2136                 lquanta[level + 1] += incr;
2137                 return;
2138         }
2139 
2140         /*
2141          * This is an overflow.
2142          */
2143         lquanta[levels + 1] += incr;
2144 }
2145 
2146 static int
2147 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2148     uint16_t high, uint16_t nsteps, int64_t value)
2149 {
2150         int64_t this = 1, last, next;
2151         int base = 1, order;
2152 
2153         ASSERT(factor <= nsteps);
2154         ASSERT(nsteps % factor == 0);
2155 
2156         for (order = 0; order < low; order++)
2157                 this *= factor;
2158 
2159         /*
2160          * If our value is less than our factor taken to the power of the
2161          * low order of magnitude, it goes into the zeroth bucket.
2162          */
2163         if (value < (last = this))
2164                 return (0);
2165 
2166         for (this *= factor; order <= high; order++) {
2167                 int nbuckets = this > nsteps ? nsteps : this;
2168 
2169                 if ((next = this * factor) < this) {
2170                         /*
2171                          * We should not generally get log/linear quantizations
2172                          * with a high magnitude that allows 64-bits to
2173                          * overflow, but we nonetheless protect against this
2174                          * by explicitly checking for overflow, and clamping
2175                          * our value accordingly.
2176                          */
2177                         value = this - 1;
2178                 }
2179 
2180                 if (value < this) {
2181                         /*
2182                          * If our value lies within this order of magnitude,
2183                          * determine its position by taking the offset within
2184                          * the order of magnitude, dividing by the bucket
2185                          * width, and adding to our (accumulated) base.
2186                          */
2187                         return (base + (value - last) / (this / nbuckets));
2188                 }
2189 
2190                 base += nbuckets - (nbuckets / factor);
2191                 last = this;
2192                 this = next;
2193         }
2194 
2195         /*
2196          * Our value is greater than or equal to our factor taken to the
2197          * power of one plus the high magnitude -- return the top bucket.
2198          */
2199         return (base);
2200 }
2201 
2202 static void
2203 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2204 {
2205         uint64_t arg = *llquanta++;
2206         uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2207         uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2208         uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2209         uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2210 
2211         llquanta[dtrace_aggregate_llquantize_bucket(factor,
2212             low, high, nsteps, nval)] += incr;
2213 }
2214 
2215 /*ARGSUSED*/
2216 static void
2217 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2218 {
2219         data[0]++;
2220         data[1] += nval;
2221 }
2222 
2223 /*ARGSUSED*/
2224 static void
2225 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2226 {
2227         int64_t snval = (int64_t)nval;
2228         uint64_t tmp[2];
2229 
2230         data[0]++;
2231         data[1] += nval;
2232 
2233         /*
2234          * What we want to say here is:
2235          *
2236          * data[2] += nval * nval;
2237          *
2238          * But given that nval is 64-bit, we could easily overflow, so
2239          * we do this as 128-bit arithmetic.
2240          */
2241         if (snval < 0)
2242                 snval = -snval;
2243 
2244         dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2245         dtrace_add_128(data + 2, tmp, data + 2);
2246 }
2247 
2248 /*ARGSUSED*/
2249 static void
2250 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2251 {
2252         *oval = *oval + 1;
2253 }
2254 
2255 /*ARGSUSED*/
2256 static void
2257 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2258 {
2259         *oval += nval;
2260 }
2261 
2262 /*
2263  * Aggregate given the tuple in the principal data buffer, and the aggregating
2264  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2265  * buffer is specified as the buf parameter.  This routine does not return
2266  * failure; if there is no space in the aggregation buffer, the data will be
2267  * dropped, and a corresponding counter incremented.
2268  */
2269 static void
2270 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2271     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2272 {
2273         dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2274         uint32_t i, ndx, size, fsize;
2275         uint32_t align = sizeof (uint64_t) - 1;
2276         dtrace_aggbuffer_t *agb;
2277         dtrace_aggkey_t *key;
2278         uint32_t hashval = 0, limit, isstr;
2279         caddr_t tomax, data, kdata;
2280         dtrace_actkind_t action;
2281         dtrace_action_t *act;
2282         uintptr_t offs;
2283 
2284         if (buf == NULL)
2285                 return;
2286 
2287         if (!agg->dtag_hasarg) {
2288                 /*
2289                  * Currently, only quantize() and lquantize() take additional
2290                  * arguments, and they have the same semantics:  an increment
2291                  * value that defaults to 1 when not present.  If additional
2292                  * aggregating actions take arguments, the setting of the
2293                  * default argument value will presumably have to become more
2294                  * sophisticated...
2295                  */
2296                 arg = 1;
2297         }
2298 
2299         action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2300         size = rec->dtrd_offset - agg->dtag_base;
2301         fsize = size + rec->dtrd_size;
2302 
2303         ASSERT(dbuf->dtb_tomax != NULL);
2304         data = dbuf->dtb_tomax + offset + agg->dtag_base;
2305 
2306         if ((tomax = buf->dtb_tomax) == NULL) {
2307                 dtrace_buffer_drop(buf);
2308                 return;
2309         }
2310 
2311         /*
2312          * The metastructure is always at the bottom of the buffer.
2313          */
2314         agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2315             sizeof (dtrace_aggbuffer_t));
2316 
2317         if (buf->dtb_offset == 0) {
2318                 /*
2319                  * We just kludge up approximately 1/8th of the size to be
2320                  * buckets.  If this guess ends up being routinely
2321                  * off-the-mark, we may need to dynamically readjust this
2322                  * based on past performance.
2323                  */
2324                 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2325 
2326                 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2327                     (uintptr_t)tomax || hashsize == 0) {
2328                         /*
2329                          * We've been given a ludicrously small buffer;
2330                          * increment our drop count and leave.
2331                          */
2332                         dtrace_buffer_drop(buf);
2333                         return;
2334                 }
2335 
2336                 /*
2337                  * And now, a pathetic attempt to try to get a an odd (or
2338                  * perchance, a prime) hash size for better hash distribution.
2339                  */
2340                 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2341                         hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2342 
2343                 agb->dtagb_hashsize = hashsize;
2344                 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2345                     agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2346                 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2347 
2348                 for (i = 0; i < agb->dtagb_hashsize; i++)
2349                         agb->dtagb_hash[i] = NULL;
2350         }
2351 
2352         ASSERT(agg->dtag_first != NULL);
2353         ASSERT(agg->dtag_first->dta_intuple);
2354 
2355         /*
2356          * Calculate the hash value based on the key.  Note that we _don't_
2357          * include the aggid in the hashing (but we will store it as part of
2358          * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2359          * algorithm: a simple, quick algorithm that has no known funnels, and
2360          * gets good distribution in practice.  The efficacy of the hashing
2361          * algorithm (and a comparison with other algorithms) may be found by
2362          * running the ::dtrace_aggstat MDB dcmd.
2363          */
2364         for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2365                 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2366                 limit = i + act->dta_rec.dtrd_size;
2367                 ASSERT(limit <= size);
2368                 isstr = DTRACEACT_ISSTRING(act);
2369 
2370                 for (; i < limit; i++) {
2371                         hashval += data[i];
2372                         hashval += (hashval << 10);
2373                         hashval ^= (hashval >> 6);
2374 
2375                         if (isstr && data[i] == '\0')
2376                                 break;
2377                 }
2378         }
2379 
2380         hashval += (hashval << 3);
2381         hashval ^= (hashval >> 11);
2382         hashval += (hashval << 15);
2383 
2384         /*
2385          * Yes, the divide here is expensive -- but it's generally the least
2386          * of the performance issues given the amount of data that we iterate
2387          * over to compute hash values, compare data, etc.
2388          */
2389         ndx = hashval % agb->dtagb_hashsize;
2390 
2391         for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2392                 ASSERT((caddr_t)key >= tomax);
2393                 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2394 
2395                 if (hashval != key->dtak_hashval || key->dtak_size != size)
2396                         continue;
2397 
2398                 kdata = key->dtak_data;
2399                 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2400 
2401                 for (act = agg->dtag_first; act->dta_intuple;
2402                     act = act->dta_next) {
2403                         i = act->dta_rec.dtrd_offset - agg->dtag_base;
2404                         limit = i + act->dta_rec.dtrd_size;
2405                         ASSERT(limit <= size);
2406                         isstr = DTRACEACT_ISSTRING(act);
2407 
2408                         for (; i < limit; i++) {
2409                                 if (kdata[i] != data[i])
2410                                         goto next;
2411 
2412                                 if (isstr && data[i] == '\0')
2413                                         break;
2414                         }
2415                 }
2416 
2417                 if (action != key->dtak_action) {
2418                         /*
2419                          * We are aggregating on the same value in the same
2420                          * aggregation with two different aggregating actions.
2421                          * (This should have been picked up in the compiler,
2422                          * so we may be dealing with errant or devious DIF.)
2423                          * This is an error condition; we indicate as much,
2424                          * and return.
2425                          */
2426                         DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2427                         return;
2428                 }
2429 
2430                 /*
2431                  * This is a hit:  we need to apply the aggregator to
2432                  * the value at this key.
2433                  */
2434                 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2435                 return;
2436 next:
2437                 continue;
2438         }
2439 
2440         /*
2441          * We didn't find it.  We need to allocate some zero-filled space,
2442          * link it into the hash table appropriately, and apply the aggregator
2443          * to the (zero-filled) value.
2444          */
2445         offs = buf->dtb_offset;
2446         while (offs & (align - 1))
2447                 offs += sizeof (uint32_t);
2448 
2449         /*
2450          * If we don't have enough room to both allocate a new key _and_
2451          * its associated data, increment the drop count and return.
2452          */
2453         if ((uintptr_t)tomax + offs + fsize >
2454             agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2455                 dtrace_buffer_drop(buf);
2456                 return;
2457         }
2458 
2459         /*CONSTCOND*/
2460         ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2461         key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2462         agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2463 
2464         key->dtak_data = kdata = tomax + offs;
2465         buf->dtb_offset = offs + fsize;
2466 
2467         /*
2468          * Now copy the data across.
2469          */
2470         *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2471 
2472         for (i = sizeof (dtrace_aggid_t); i < size; i++)
2473                 kdata[i] = data[i];
2474 
2475         /*
2476          * Because strings are not zeroed out by default, we need to iterate
2477          * looking for actions that store strings, and we need to explicitly
2478          * pad these strings out with zeroes.
2479          */
2480         for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2481                 int nul;
2482 
2483                 if (!DTRACEACT_ISSTRING(act))
2484                         continue;
2485 
2486                 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2487                 limit = i + act->dta_rec.dtrd_size;
2488                 ASSERT(limit <= size);
2489 
2490                 for (nul = 0; i < limit; i++) {
2491                         if (nul) {
2492                                 kdata[i] = '\0';
2493                                 continue;
2494                         }
2495 
2496                         if (data[i] != '\0')
2497                                 continue;
2498 
2499                         nul = 1;
2500                 }
2501         }
2502 
2503         for (i = size; i < fsize; i++)
2504                 kdata[i] = 0;
2505 
2506         key->dtak_hashval = hashval;
2507         key->dtak_size = size;
2508         key->dtak_action = action;
2509         key->dtak_next = agb->dtagb_hash[ndx];
2510         agb->dtagb_hash[ndx] = key;
2511 
2512         /*
2513          * Finally, apply the aggregator.
2514          */
2515         *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2516         agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2517 }
2518 
2519 /*
2520  * Given consumer state, this routine finds a speculation in the INACTIVE
2521  * state and transitions it into the ACTIVE state.  If there is no speculation
2522  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2523  * incremented -- it is up to the caller to take appropriate action.
2524  */
2525 static int
2526 dtrace_speculation(dtrace_state_t *state)
2527 {
2528         int i = 0;
2529         dtrace_speculation_state_t current;
2530         uint32_t *stat = &state->dts_speculations_unavail, count;
2531 
2532         while (i < state->dts_nspeculations) {
2533                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2534 
2535                 current = spec->dtsp_state;
2536 
2537                 if (current != DTRACESPEC_INACTIVE) {
2538                         if (current == DTRACESPEC_COMMITTINGMANY ||
2539                             current == DTRACESPEC_COMMITTING ||
2540                             current == DTRACESPEC_DISCARDING)
2541                                 stat = &state->dts_speculations_busy;
2542                         i++;
2543                         continue;
2544                 }
2545 
2546                 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2547                     current, DTRACESPEC_ACTIVE) == current)
2548                         return (i + 1);
2549         }
2550 
2551         /*
2552          * We couldn't find a speculation.  If we found as much as a single
2553          * busy speculation buffer, we'll attribute this failure as "busy"
2554          * instead of "unavail".
2555          */
2556         do {
2557                 count = *stat;
2558         } while (dtrace_cas32(stat, count, count + 1) != count);
2559 
2560         return (0);
2561 }
2562 
2563 /*
2564  * This routine commits an active speculation.  If the specified speculation
2565  * is not in a valid state to perform a commit(), this routine will silently do
2566  * nothing.  The state of the specified speculation is transitioned according
2567  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2568  */
2569 static void
2570 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2571     dtrace_specid_t which)
2572 {
2573         dtrace_speculation_t *spec;
2574         dtrace_buffer_t *src, *dest;
2575         uintptr_t daddr, saddr, dlimit, slimit;
2576         dtrace_speculation_state_t current, new;
2577         intptr_t offs;
2578         uint64_t timestamp;
2579 
2580         if (which == 0)
2581                 return;
2582 
2583         if (which > state->dts_nspeculations) {
2584                 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2585                 return;
2586         }
2587 
2588         spec = &state->dts_speculations[which - 1];
2589         src = &spec->dtsp_buffer[cpu];
2590         dest = &state->dts_buffer[cpu];
2591 
2592         do {
2593                 current = spec->dtsp_state;
2594 
2595                 if (current == DTRACESPEC_COMMITTINGMANY)
2596                         break;
2597 
2598                 switch (current) {
2599                 case DTRACESPEC_INACTIVE:
2600                 case DTRACESPEC_DISCARDING:
2601                         return;
2602 
2603                 case DTRACESPEC_COMMITTING:
2604                         /*
2605                          * This is only possible if we are (a) commit()'ing
2606                          * without having done a prior speculate() on this CPU
2607                          * and (b) racing with another commit() on a different
2608                          * CPU.  There's nothing to do -- we just assert that
2609                          * our offset is 0.
2610                          */
2611                         ASSERT(src->dtb_offset == 0);
2612                         return;
2613 
2614                 case DTRACESPEC_ACTIVE:
2615                         new = DTRACESPEC_COMMITTING;
2616                         break;
2617 
2618                 case DTRACESPEC_ACTIVEONE:
2619                         /*
2620                          * This speculation is active on one CPU.  If our
2621                          * buffer offset is non-zero, we know that the one CPU
2622                          * must be us.  Otherwise, we are committing on a
2623                          * different CPU from the speculate(), and we must
2624                          * rely on being asynchronously cleaned.
2625                          */
2626                         if (src->dtb_offset != 0) {
2627                                 new = DTRACESPEC_COMMITTING;
2628                                 break;
2629                         }
2630                         /*FALLTHROUGH*/
2631 
2632                 case DTRACESPEC_ACTIVEMANY:
2633                         new = DTRACESPEC_COMMITTINGMANY;
2634                         break;
2635 
2636                 default:
2637                         ASSERT(0);
2638                 }
2639         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2640             current, new) != current);
2641 
2642         /*
2643          * We have set the state to indicate that we are committing this
2644          * speculation.  Now reserve the necessary space in the destination
2645          * buffer.
2646          */
2647         if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2648             sizeof (uint64_t), state, NULL)) < 0) {
2649                 dtrace_buffer_drop(dest);
2650                 goto out;
2651         }
2652 
2653         /*
2654          * We have sufficient space to copy the speculative buffer into the
2655          * primary buffer.  First, modify the speculative buffer, filling
2656          * in the timestamp of all entries with the current time.  The data
2657          * must have the commit() time rather than the time it was traced,
2658          * so that all entries in the primary buffer are in timestamp order.
2659          */
2660         timestamp = dtrace_gethrtime();
2661         saddr = (uintptr_t)src->dtb_tomax;
2662         slimit = saddr + src->dtb_offset;
2663         while (saddr < slimit) {
2664                 size_t size;
2665                 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2666 
2667                 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2668                         saddr += sizeof (dtrace_epid_t);
2669                         continue;
2670                 }
2671                 ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2672                 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2673 
2674                 ASSERT3U(saddr + size, <=, slimit);
2675                 ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2676                 ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2677 
2678                 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2679 
2680                 saddr += size;
2681         }
2682 
2683         /*
2684          * Copy the buffer across.  (Note that this is a
2685          * highly subobtimal bcopy(); in the unlikely event that this becomes
2686          * a serious performance issue, a high-performance DTrace-specific
2687          * bcopy() should obviously be invented.)
2688          */
2689         daddr = (uintptr_t)dest->dtb_tomax + offs;
2690         dlimit = daddr + src->dtb_offset;
2691         saddr = (uintptr_t)src->dtb_tomax;
2692 
2693         /*
2694          * First, the aligned portion.
2695          */
2696         while (dlimit - daddr >= sizeof (uint64_t)) {
2697                 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2698 
2699                 daddr += sizeof (uint64_t);
2700                 saddr += sizeof (uint64_t);
2701         }
2702 
2703         /*
2704          * Now any left-over bit...
2705          */
2706         while (dlimit - daddr)
2707                 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2708 
2709         /*
2710          * Finally, commit the reserved space in the destination buffer.
2711          */
2712         dest->dtb_offset = offs + src->dtb_offset;
2713 
2714 out:
2715         /*
2716          * If we're lucky enough to be the only active CPU on this speculation
2717          * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2718          */
2719         if (current == DTRACESPEC_ACTIVE ||
2720             (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2721                 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2722                     DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2723 
2724                 ASSERT(rval == DTRACESPEC_COMMITTING);
2725         }
2726 
2727         src->dtb_offset = 0;
2728         src->dtb_xamot_drops += src->dtb_drops;
2729         src->dtb_drops = 0;
2730 }
2731 
2732 /*
2733  * This routine discards an active speculation.  If the specified speculation
2734  * is not in a valid state to perform a discard(), this routine will silently
2735  * do nothing.  The state of the specified speculation is transitioned
2736  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2737  */
2738 static void
2739 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2740     dtrace_specid_t which)
2741 {
2742         dtrace_speculation_t *spec;
2743         dtrace_speculation_state_t current, new;
2744         dtrace_buffer_t *buf;
2745 
2746         if (which == 0)
2747                 return;
2748 
2749         if (which > state->dts_nspeculations) {
2750                 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2751                 return;
2752         }
2753 
2754         spec = &state->dts_speculations[which - 1];
2755         buf = &spec->dtsp_buffer[cpu];
2756 
2757         do {
2758                 current = spec->dtsp_state;
2759 
2760                 switch (current) {
2761                 case DTRACESPEC_INACTIVE:
2762                 case DTRACESPEC_COMMITTINGMANY:
2763                 case DTRACESPEC_COMMITTING:
2764                 case DTRACESPEC_DISCARDING:
2765                         return;
2766 
2767                 case DTRACESPEC_ACTIVE:
2768                 case DTRACESPEC_ACTIVEMANY:
2769                         new = DTRACESPEC_DISCARDING;
2770                         break;
2771 
2772                 case DTRACESPEC_ACTIVEONE:
2773                         if (buf->dtb_offset != 0) {
2774                                 new = DTRACESPEC_INACTIVE;
2775                         } else {
2776                                 new = DTRACESPEC_DISCARDING;
2777                         }
2778                         break;
2779 
2780                 default:
2781                         ASSERT(0);
2782                 }
2783         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2784             current, new) != current);
2785 
2786         buf->dtb_offset = 0;
2787         buf->dtb_drops = 0;
2788 }
2789 
2790 /*
2791  * Note:  not called from probe context.  This function is called
2792  * asynchronously from cross call context to clean any speculations that are
2793  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2794  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2795  * speculation.
2796  */
2797 static void
2798 dtrace_speculation_clean_here(dtrace_state_t *state)
2799 {
2800         dtrace_icookie_t cookie;
2801         processorid_t cpu = CPU->cpu_id;
2802         dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2803         dtrace_specid_t i;
2804 
2805         cookie = dtrace_interrupt_disable();
2806 
2807         if (dest->dtb_tomax == NULL) {
2808                 dtrace_interrupt_enable(cookie);
2809                 return;
2810         }
2811 
2812         for (i = 0; i < state->dts_nspeculations; i++) {
2813                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2814                 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2815 
2816                 if (src->dtb_tomax == NULL)
2817                         continue;
2818 
2819                 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2820                         src->dtb_offset = 0;
2821                         continue;
2822                 }
2823 
2824                 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2825                         continue;
2826 
2827                 if (src->dtb_offset == 0)
2828                         continue;
2829 
2830                 dtrace_speculation_commit(state, cpu, i + 1);
2831         }
2832 
2833         dtrace_interrupt_enable(cookie);
2834 }
2835 
2836 /*
2837  * Note:  not called from probe context.  This function is called
2838  * asynchronously (and at a regular interval) to clean any speculations that
2839  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2840  * is work to be done, it cross calls all CPUs to perform that work;
2841  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2842  * INACTIVE state until they have been cleaned by all CPUs.
2843  */
2844 static void
2845 dtrace_speculation_clean(dtrace_state_t *state)
2846 {
2847         int work = 0, rv;
2848         dtrace_specid_t i;
2849 
2850         for (i = 0; i < state->dts_nspeculations; i++) {
2851                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2852 
2853                 ASSERT(!spec->dtsp_cleaning);
2854 
2855                 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2856                     spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2857                         continue;
2858 
2859                 work++;
2860                 spec->dtsp_cleaning = 1;
2861         }
2862 
2863         if (!work)
2864                 return;
2865 
2866         dtrace_xcall(DTRACE_CPUALL,
2867             (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2868 
2869         /*
2870          * We now know that all CPUs have committed or discarded their
2871          * speculation buffers, as appropriate.  We can now set the state
2872          * to inactive.
2873          */
2874         for (i = 0; i < state->dts_nspeculations; i++) {
2875                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2876                 dtrace_speculation_state_t current, new;
2877 
2878                 if (!spec->dtsp_cleaning)
2879                         continue;
2880 
2881                 current = spec->dtsp_state;
2882                 ASSERT(current == DTRACESPEC_DISCARDING ||
2883                     current == DTRACESPEC_COMMITTINGMANY);
2884 
2885                 new = DTRACESPEC_INACTIVE;
2886 
2887                 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2888                 ASSERT(rv == current);
2889                 spec->dtsp_cleaning = 0;
2890         }
2891 }
2892 
2893 /*
2894  * Called as part of a speculate() to get the speculative buffer associated
2895  * with a given speculation.  Returns NULL if the specified speculation is not
2896  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2897  * the active CPU is not the specified CPU -- the speculation will be
2898  * atomically transitioned into the ACTIVEMANY state.
2899  */
2900 static dtrace_buffer_t *
2901 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2902     dtrace_specid_t which)
2903 {
2904         dtrace_speculation_t *spec;
2905         dtrace_speculation_state_t current, new;
2906         dtrace_buffer_t *buf;
2907 
2908         if (which == 0)
2909                 return (NULL);
2910 
2911         if (which > state->dts_nspeculations) {
2912                 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2913                 return (NULL);
2914         }
2915 
2916         spec = &state->dts_speculations[which - 1];
2917         buf = &spec->dtsp_buffer[cpuid];
2918 
2919         do {
2920                 current = spec->dtsp_state;
2921 
2922                 switch (current) {
2923                 case DTRACESPEC_INACTIVE:
2924                 case DTRACESPEC_COMMITTINGMANY:
2925                 case DTRACESPEC_DISCARDING:
2926                         return (NULL);
2927 
2928                 case DTRACESPEC_COMMITTING:
2929                         ASSERT(buf->dtb_offset == 0);
2930                         return (NULL);
2931 
2932                 case DTRACESPEC_ACTIVEONE:
2933                         /*
2934                          * This speculation is currently active on one CPU.
2935                          * Check the offset in the buffer; if it's non-zero,
2936                          * that CPU must be us (and we leave the state alone).
2937                          * If it's zero, assume that we're starting on a new
2938                          * CPU -- and change the state to indicate that the
2939                          * speculation is active on more than one CPU.
2940                          */
2941                         if (buf->dtb_offset != 0)
2942                                 return (buf);
2943 
2944                         new = DTRACESPEC_ACTIVEMANY;
2945                         break;
2946 
2947                 case DTRACESPEC_ACTIVEMANY:
2948                         return (buf);
2949 
2950                 case DTRACESPEC_ACTIVE:
2951                         new = DTRACESPEC_ACTIVEONE;
2952                         break;
2953 
2954                 default:
2955                         ASSERT(0);
2956                 }
2957         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2958             current, new) != current);
2959 
2960         ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2961         return (buf);
2962 }
2963 
2964 /*
2965  * Return a string.  In the event that the user lacks the privilege to access
2966  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2967  * don't fail access checking.
2968  *
2969  * dtrace_dif_variable() uses this routine as a helper for various
2970  * builtin values such as 'execname' and 'probefunc.'
2971  */
2972 uintptr_t
2973 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2974     dtrace_mstate_t *mstate)
2975 {
2976         uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2977         uintptr_t ret;
2978         size_t strsz;
2979 
2980         /*
2981          * The easy case: this probe is allowed to read all of memory, so
2982          * we can just return this as a vanilla pointer.
2983          */
2984         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2985                 return (addr);
2986 
2987         /*
2988          * This is the tougher case: we copy the string in question from
2989          * kernel memory into scratch memory and return it that way: this
2990          * ensures that we won't trip up when access checking tests the
2991          * BYREF return value.
2992          */
2993         strsz = dtrace_strlen((char *)addr, size) + 1;
2994 
2995         if (mstate->dtms_scratch_ptr + strsz >
2996             mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2997                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2998                 return (NULL);
2999         }
3000 
3001         dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3002             strsz);
3003         ret = mstate->dtms_scratch_ptr;
3004         mstate->dtms_scratch_ptr += strsz;
3005         return (ret);
3006 }
3007 
3008 /*
3009  * This function implements the DIF emulator's variable lookups.  The emulator
3010  * passes a reserved variable identifier and optional built-in array index.
3011  */
3012 static uint64_t
3013 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3014     uint64_t ndx)
3015 {
3016         /*
3017          * If we're accessing one of the uncached arguments, we'll turn this
3018          * into a reference in the args array.
3019          */
3020         if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3021                 ndx = v - DIF_VAR_ARG0;
3022                 v = DIF_VAR_ARGS;
3023         }
3024 
3025         switch (v) {
3026         case DIF_VAR_ARGS:
3027                 if (!(mstate->dtms_access & DTRACE_ACCESS_ARGS)) {
3028                         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |=
3029                             CPU_DTRACE_KPRIV;
3030                         return (0);
3031                 }
3032 
3033                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3034                 if (ndx >= sizeof (mstate->dtms_arg) /
3035                     sizeof (mstate->dtms_arg[0])) {
3036                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3037                         dtrace_provider_t *pv;
3038                         uint64_t val;
3039 
3040                         pv = mstate->dtms_probe->dtpr_provider;
3041                         if (pv->dtpv_pops.dtps_getargval != NULL)
3042                                 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3043                                     mstate->dtms_probe->dtpr_id,
3044                                     mstate->dtms_probe->dtpr_arg, ndx, aframes);
3045                         else
3046                                 val = dtrace_getarg(ndx, aframes);
3047 
3048                         /*
3049                          * This is regrettably required to keep the compiler
3050                          * from tail-optimizing the call to dtrace_getarg().
3051                          * The condition always evaluates to true, but the
3052                          * compiler has no way of figuring that out a priori.
3053                          * (None of this would be necessary if the compiler
3054                          * could be relied upon to _always_ tail-optimize
3055                          * the call to dtrace_getarg() -- but it can't.)
3056                          */
3057                         if (mstate->dtms_probe != NULL)
3058                                 return (val);
3059 
3060                         ASSERT(0);
3061                 }
3062 
3063                 return (mstate->dtms_arg[ndx]);
3064 
3065         case DIF_VAR_UREGS: {
3066                 klwp_t *lwp;
3067 
3068                 if (!dtrace_priv_proc(state, mstate))
3069                         return (0);
3070 
3071                 if ((lwp = curthread->t_lwp) == NULL) {
3072                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3073                         cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
3074                         return (0);
3075                 }
3076 
3077                 return (dtrace_getreg(lwp->lwp_regs, ndx));
3078         }
3079 
3080         case DIF_VAR_VMREGS: {
3081                 uint64_t rval;
3082 
3083                 if (!dtrace_priv_kernel(state))
3084                         return (0);
3085 
3086                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3087 
3088                 rval = dtrace_getvmreg(ndx,
3089                     &cpu_core[CPU->cpu_id].cpuc_dtrace_flags);
3090 
3091                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3092 
3093                 return (rval);
3094         }
3095 
3096         case DIF_VAR_CURTHREAD:
3097                 if (!dtrace_priv_proc(state, mstate))
3098                         return (0);
3099                 return ((uint64_t)(uintptr_t)curthread);
3100 
3101         case DIF_VAR_TIMESTAMP:
3102                 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3103                         mstate->dtms_timestamp = dtrace_gethrtime();
3104                         mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3105                 }
3106                 return (mstate->dtms_timestamp);
3107 
3108         case DIF_VAR_VTIMESTAMP:
3109                 ASSERT(dtrace_vtime_references != 0);
3110                 return (curthread->t_dtrace_vtime);
3111 
3112         case DIF_VAR_WALLTIMESTAMP:
3113                 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3114                         mstate->dtms_walltimestamp = dtrace_gethrestime();
3115                         mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3116                 }
3117                 return (mstate->dtms_walltimestamp);
3118 
3119         case DIF_VAR_IPL:
3120                 if (!dtrace_priv_kernel(state))
3121                         return (0);
3122                 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3123                         mstate->dtms_ipl = dtrace_getipl();
3124                         mstate->dtms_present |= DTRACE_MSTATE_IPL;
3125                 }
3126                 return (mstate->dtms_ipl);
3127 
3128         case DIF_VAR_EPID:
3129                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3130                 return (mstate->dtms_epid);
3131 
3132         case DIF_VAR_ID:
3133                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3134                 return (mstate->dtms_probe->dtpr_id);
3135 
3136         case DIF_VAR_STACKDEPTH:
3137                 if (!dtrace_priv_kernel(state))
3138                         return (0);
3139                 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3140                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3141 
3142                         mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3143                         mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3144                 }
3145                 return (mstate->dtms_stackdepth);
3146 
3147         case DIF_VAR_USTACKDEPTH:
3148                 if (!dtrace_priv_proc(state, mstate))
3149                         return (0);
3150                 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3151                         /*
3152                          * See comment in DIF_VAR_PID.
3153                          */
3154                         if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3155                             CPU_ON_INTR(CPU)) {
3156                                 mstate->dtms_ustackdepth = 0;
3157                         } else {
3158                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3159                                 mstate->dtms_ustackdepth =
3160                                     dtrace_getustackdepth();
3161                                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3162                         }
3163                         mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3164                 }
3165                 return (mstate->dtms_ustackdepth);
3166 
3167         case DIF_VAR_CALLER:
3168                 if (!dtrace_priv_kernel(state))
3169                         return (0);
3170                 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3171                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3172 
3173                         if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3174                                 /*
3175                                  * If this is an unanchored probe, we are
3176                                  * required to go through the slow path:
3177                                  * dtrace_caller() only guarantees correct
3178                                  * results for anchored probes.
3179                                  */
3180                                 pc_t caller[2];
3181 
3182                                 dtrace_getpcstack(caller, 2, aframes,
3183                                     (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3184                                 mstate->dtms_caller = caller[1];
3185                         } else if ((mstate->dtms_caller =
3186                             dtrace_caller(aframes)) == -1) {
3187                                 /*
3188                                  * We have failed to do this the quick way;
3189                                  * we must resort to the slower approach of
3190                                  * calling dtrace_getpcstack().
3191                                  */
3192                                 pc_t caller;
3193 
3194                                 dtrace_getpcstack(&caller, 1, aframes, NULL);
3195                                 mstate->dtms_caller = caller;
3196                         }
3197 
3198                         mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3199                 }
3200                 return (mstate->dtms_caller);
3201 
3202         case DIF_VAR_UCALLER:
3203                 if (!dtrace_priv_proc(state, mstate))
3204                         return (0);
3205 
3206                 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3207                         uint64_t ustack[3];
3208 
3209                         /*
3210                          * dtrace_getupcstack() fills in the first uint64_t
3211                          * with the current PID.  The second uint64_t will
3212                          * be the program counter at user-level.  The third
3213                          * uint64_t will contain the caller, which is what
3214                          * we're after.
3215                          */
3216                         ustack[2] = NULL;
3217                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3218                         dtrace_getupcstack(ustack, 3);
3219                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3220                         mstate->dtms_ucaller = ustack[2];
3221                         mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3222                 }
3223 
3224                 return (mstate->dtms_ucaller);
3225 
3226         case DIF_VAR_PROBEPROV:
3227                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3228                 return (dtrace_dif_varstr(
3229                     (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3230                     state, mstate));
3231 
3232         case DIF_VAR_PROBEMOD:
3233                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3234                 return (dtrace_dif_varstr(
3235                     (uintptr_t)mstate->dtms_probe->dtpr_mod,
3236                     state, mstate));
3237 
3238         case DIF_VAR_PROBEFUNC:
3239                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3240                 return (dtrace_dif_varstr(
3241                     (uintptr_t)mstate->dtms_probe->dtpr_func,
3242                     state, mstate));
3243 
3244         case DIF_VAR_PROBENAME:
3245                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3246                 return (dtrace_dif_varstr(
3247                     (uintptr_t)mstate->dtms_probe->dtpr_name,
3248                     state, mstate));
3249 
3250         case DIF_VAR_PID:
3251                 if (!dtrace_priv_proc(state, mstate))
3252                         return (0);
3253 
3254                 /*
3255                  * Note that we are assuming that an unanchored probe is
3256                  * always due to a high-level interrupt.  (And we're assuming
3257                  * that there is only a single high level interrupt.)
3258                  */
3259                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3260                         return (pid0.pid_id);
3261 
3262                 /*
3263                  * It is always safe to dereference one's own t_procp pointer:
3264                  * it always points to a valid, allocated proc structure.
3265                  * Further, it is always safe to dereference the p_pidp member
3266                  * of one's own proc structure.  (These are truisms becuase
3267                  * threads and processes don't clean up their own state --
3268                  * they leave that task to whomever reaps them.)
3269                  */
3270                 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3271 
3272         case DIF_VAR_PPID:
3273                 if (!dtrace_priv_proc(state, mstate))
3274                         return (0);
3275 
3276                 /*
3277                  * See comment in DIF_VAR_PID.
3278                  */
3279                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3280                         return (pid0.pid_id);
3281 
3282                 /*
3283                  * It is always safe to dereference one's own t_procp pointer:
3284                  * it always points to a valid, allocated proc structure.
3285                  * (This is true because threads don't clean up their own
3286                  * state -- they leave that task to whomever reaps them.)
3287                  */
3288                 return ((uint64_t)curthread->t_procp->p_ppid);
3289 
3290         case DIF_VAR_TID:
3291                 /*
3292                  * See comment in DIF_VAR_PID.
3293                  */
3294                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3295                         return (0);
3296 
3297                 return ((uint64_t)curthread->t_tid);
3298 
3299         case DIF_VAR_EXECNAME:
3300                 if (!dtrace_priv_proc(state, mstate))
3301                         return (0);
3302 
3303                 /*
3304                  * See comment in DIF_VAR_PID.
3305                  */
3306                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3307                         return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3308 
3309                 /*
3310                  * It is always safe to dereference one's own t_procp pointer:
3311                  * it always points to a valid, allocated proc structure.
3312                  * (This is true because threads don't clean up their own
3313                  * state -- they leave that task to whomever reaps them.)
3314                  */
3315                 return (dtrace_dif_varstr(
3316                     (uintptr_t)curthread->t_procp->p_user.u_comm,
3317                     state, mstate));
3318 
3319         case DIF_VAR_ZONENAME:
3320                 if (!dtrace_priv_proc(state, mstate))
3321                         return (0);
3322 
3323                 /*
3324                  * See comment in DIF_VAR_PID.
3325                  */
3326                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3327                         return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3328 
3329                 /*
3330                  * It is always safe to dereference one's own t_procp pointer:
3331                  * it always points to a valid, allocated proc structure.
3332                  * (This is true because threads don't clean up their own
3333                  * state -- they leave that task to whomever reaps them.)
3334                  */
3335                 return (dtrace_dif_varstr(
3336                     (uintptr_t)curthread->t_procp->p_zone->zone_name,
3337                     state, mstate));
3338 
3339         case DIF_VAR_UID:
3340                 if (!dtrace_priv_proc(state, mstate))
3341                         return (0);
3342 
3343                 /*
3344                  * See comment in DIF_VAR_PID.
3345                  */
3346                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3347                         return ((uint64_t)p0.p_cred->cr_uid);
3348 
3349                 /*
3350                  * It is always safe to dereference one's own t_procp pointer:
3351                  * it always points to a valid, allocated proc structure.
3352                  * (This is true because threads don't clean up their own
3353                  * state -- they leave that task to whomever reaps them.)
3354                  *
3355                  * Additionally, it is safe to dereference one's own process
3356                  * credential, since this is never NULL after process birth.
3357                  */
3358                 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3359 
3360         case DIF_VAR_GID:
3361                 if (!dtrace_priv_proc(state, mstate))
3362                         return (0);
3363 
3364                 /*
3365                  * See comment in DIF_VAR_PID.
3366                  */
3367                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3368                         return ((uint64_t)p0.p_cred->cr_gid);
3369 
3370                 /*
3371                  * It is always safe to dereference one's own t_procp pointer:
3372                  * it always points to a valid, allocated proc structure.
3373                  * (This is true because threads don't clean up their own
3374                  * state -- they leave that task to whomever reaps them.)
3375                  *
3376                  * Additionally, it is safe to dereference one's own process
3377                  * credential, since this is never NULL after process birth.
3378                  */
3379                 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3380 
3381         case DIF_VAR_ERRNO: {
3382                 klwp_t *lwp;
3383                 if (!dtrace_priv_proc(state, mstate))
3384                         return (0);
3385 
3386                 /*
3387                  * See comment in DIF_VAR_PID.
3388                  */
3389                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3390                         return (0);
3391 
3392                 /*
3393                  * It is always safe to dereference one's own t_lwp pointer in
3394                  * the event that this pointer is non-NULL.  (This is true
3395                  * because threads and lwps don't clean up their own state --
3396                  * they leave that task to whomever reaps them.)
3397                  */
3398                 if ((lwp = curthread->t_lwp) == NULL)
3399                         return (0);
3400 
3401                 return ((uint64_t)lwp->lwp_errno);
3402         }
3403         default:
3404                 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3405                 return (0);
3406         }
3407 }
3408 
3409 
3410 typedef enum dtrace_json_state {
3411         DTRACE_JSON_REST = 1,
3412         DTRACE_JSON_OBJECT,
3413         DTRACE_JSON_STRING,
3414         DTRACE_JSON_STRING_ESCAPE,
3415         DTRACE_JSON_STRING_ESCAPE_UNICODE,
3416         DTRACE_JSON_COLON,
3417         DTRACE_JSON_COMMA,
3418         DTRACE_JSON_VALUE,
3419         DTRACE_JSON_IDENTIFIER,
3420         DTRACE_JSON_NUMBER,
3421         DTRACE_JSON_NUMBER_FRAC,
3422         DTRACE_JSON_NUMBER_EXP,
3423         DTRACE_JSON_COLLECT_OBJECT
3424 } dtrace_json_state_t;
3425 
3426 /*
3427  * This function possesses just enough knowledge about JSON to extract a single
3428  * value from a JSON string and store it in the scratch buffer.  It is able
3429  * to extract nested object values, and members of arrays by index.
3430  *
3431  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3432  * be looked up as we descend into the object tree.  e.g.
3433  *
3434  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3435  *       with nelems = 5.
3436  *
3437  * The run time of this function must be bounded above by strsize to limit the
3438  * amount of work done in probe context.  As such, it is implemented as a
3439  * simple state machine, reading one character at a time using safe loads
3440  * until we find the requested element, hit a parsing error or run off the
3441  * end of the object or string.
3442  *
3443  * As there is no way for a subroutine to return an error without interrupting
3444  * clause execution, we simply return NULL in the event of a missing key or any
3445  * other error condition.  Each NULL return in this function is commented with
3446  * the error condition it represents -- parsing or otherwise.
3447  *
3448  * The set of states for the state machine closely matches the JSON
3449  * specification (http://json.org/).  Briefly:
3450  *
3451  *   DTRACE_JSON_REST:
3452  *     Skip whitespace until we find either a top-level Object, moving
3453  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3454  *
3455  *   DTRACE_JSON_OBJECT:
3456  *     Locate the next key String in an Object.  Sets a flag to denote
3457  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3458  *
3459  *   DTRACE_JSON_COLON:
3460  *     Skip whitespace until we find the colon that separates key Strings
3461  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3462  *
3463  *   DTRACE_JSON_VALUE:
3464  *     Detects the type of the next value (String, Number, Identifier, Object
3465  *     or Array) and routes to the states that process that type.  Here we also
3466  *     deal with the element selector list if we are requested to traverse down
3467  *     into the object tree.
3468  *
3469  *   DTRACE_JSON_COMMA:
3470  *     Skip whitespace until we find the comma that separates key-value pairs
3471  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3472  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3473  *     states return to this state at the end of their value, unless otherwise
3474  *     noted.
3475  *
3476  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3477  *     Processes a Number literal from the JSON, including any exponent
3478  *     component that may be present.  Numbers are returned as strings, which
3479  *     may be passed to strtoll() if an integer is required.
3480  *
3481  *   DTRACE_JSON_IDENTIFIER:
3482  *     Processes a "true", "false" or "null" literal in the JSON.
3483  *
3484  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3485  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3486  *     Processes a String literal from the JSON, whether the String denotes
3487  *     a key, a value or part of a larger Object.  Handles all escape sequences
3488  *     present in the specification, including four-digit unicode characters,
3489  *     but merely includes the escape sequence without converting it to the
3490  *     actual escaped character.  If the String is flagged as a key, we
3491  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3492  *
3493  *   DTRACE_JSON_COLLECT_OBJECT:
3494  *     This state collects an entire Object (or Array), correctly handling
3495  *     embedded strings.  If the full element selector list matches this nested
3496  *     object, we return the Object in full as a string.  If not, we use this
3497  *     state to skip to the next value at this level and continue processing.
3498  *
3499  * NOTE: This function uses various macros from strtolctype.h to manipulate
3500  * digit values, etc -- these have all been checked to ensure they make
3501  * no additional function calls.
3502  */
3503 static char *
3504 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3505     char *dest)
3506 {
3507         dtrace_json_state_t state = DTRACE_JSON_REST;
3508         uint64_t i;
3509         int64_t array_elem = INT64_MIN;
3510         int64_t array_pos = 0;
3511         uint8_t escape_unicount = 0;
3512         boolean_t string_is_key = B_FALSE;
3513         boolean_t collect_object = B_FALSE;
3514         boolean_t found_key = B_FALSE;
3515         boolean_t in_array = B_FALSE;
3516         uint32_t braces = 0, brackets = 0;
3517         char *elem = elemlist;
3518         char *dd = dest;
3519         uintptr_t cur;
3520 
3521         for (cur = json; cur < json + size; cur++) {
3522                 char cc = dtrace_load8(cur);
3523                 if (cc == '\0')
3524                         return (NULL);
3525 
3526                 switch (state) {
3527                 case DTRACE_JSON_REST:
3528                         if (isspace(cc))
3529                                 break;
3530 
3531                         if (cc == '{') {
3532                                 state = DTRACE_JSON_OBJECT;
3533                                 break;
3534                         }
3535 
3536                         if (cc == '[') {
3537                                 in_array = B_TRUE;
3538                                 array_pos = 0;
3539                                 array_elem = dtrace_strtoll(elem, 10, size);
3540                                 found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3541                                 state = DTRACE_JSON_VALUE;
3542                                 break;
3543                         }
3544 
3545                         /*
3546                          * ERROR: expected to find a top-level object or array.
3547                          */
3548                         return (NULL);
3549                 case DTRACE_JSON_OBJECT:
3550                         if (isspace(cc))
3551                                 break;
3552 
3553                         if (cc == '"') {
3554                                 state = DTRACE_JSON_STRING;
3555                                 string_is_key = B_TRUE;
3556                                 break;
3557                         }
3558 
3559                         /*
3560                          * ERROR: either the object did not start with a key
3561                          * string, or we've run off the end of the object
3562                          * without finding the requested key.
3563                          */
3564                         return (NULL);
3565                 case DTRACE_JSON_STRING:
3566                         if (cc == '\\') {
3567                                 *dd++ = '\\';
3568                                 state = DTRACE_JSON_STRING_ESCAPE;
3569                                 break;
3570                         }
3571 
3572                         if (cc == '"') {
3573                                 if (collect_object) {
3574                                         /*
3575                                          * We don't reset the dest here, as
3576                                          * the string is part of a larger
3577                                          * object being collected.
3578                                          */
3579                                         *dd++ = cc;
3580                                         collect_object = B_FALSE;
3581                                         state = DTRACE_JSON_COLLECT_OBJECT;
3582                                         break;
3583                                 }
3584                                 *dd = '\0';
3585                                 dd = dest; /* reset string buffer */
3586                                 if (string_is_key) {
3587                                         if (dtrace_strncmp(dest, elem,
3588                                             size) == 0)
3589                                                 found_key = B_TRUE;
3590                                 } else if (found_key) {
3591                                         if (nelems > 1) {
3592                                                 /*
3593                                                  * We expected an object, not
3594                                                  * this string.
3595                                                  */
3596                                                 return (NULL);
3597                                         }
3598                                         return (dest);
3599                                 }
3600                                 state = string_is_key ? DTRACE_JSON_COLON :
3601                                     DTRACE_JSON_COMMA;
3602                                 string_is_key = B_FALSE;
3603                                 break;
3604                         }
3605 
3606                         *dd++ = cc;
3607                         break;
3608                 case DTRACE_JSON_STRING_ESCAPE:
3609                         *dd++ = cc;
3610                         if (cc == 'u') {
3611                                 escape_unicount = 0;
3612                                 state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3613                         } else {
3614                                 state = DTRACE_JSON_STRING;
3615                         }
3616                         break;
3617                 case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3618                         if (!isxdigit(cc)) {
3619                                 /*
3620                                  * ERROR: invalid unicode escape, expected
3621                                  * four valid hexidecimal digits.
3622                                  */ 
3623                                 return (NULL);
3624                         }
3625 
3626                         *dd++ = cc;
3627                         if (++escape_unicount == 4)
3628                                 state = DTRACE_JSON_STRING;
3629                         break;
3630                 case DTRACE_JSON_COLON:
3631                         if (isspace(cc))
3632                                 break;
3633 
3634                         if (cc == ':') {
3635                                 state = DTRACE_JSON_VALUE;
3636                                 break;
3637                         }
3638 
3639                         /*
3640                          * ERROR: expected a colon.
3641                          */
3642                         return (NULL);
3643                 case DTRACE_JSON_COMMA:
3644                         if (isspace(cc))
3645                                 break;
3646 
3647                         if (cc == ',') {
3648                                 if (in_array) {
3649                                         state = DTRACE_JSON_VALUE;
3650                                         if (++array_pos == array_elem)
3651                                                 found_key = B_TRUE;
3652                                 } else {
3653                                         state = DTRACE_JSON_OBJECT;
3654                                 }
3655                                 break;
3656                         }
3657 
3658                         /*
3659                          * ERROR: either we hit an unexpected character, or
3660                          * we reached the end of the object or array without
3661                          * finding the requested key.
3662                          */
3663                         return (NULL);
3664                 case DTRACE_JSON_IDENTIFIER:
3665                         if (islower(cc)) {
3666                                 *dd++ = cc;
3667                                 break;
3668                         }
3669 
3670                         *dd = '\0';
3671                         dd = dest; /* reset string buffer */
3672 
3673                         if (dtrace_strncmp(dest, "true", 5) == 0 ||
3674                             dtrace_strncmp(dest, "false", 6) == 0 ||
3675                             dtrace_strncmp(dest, "null", 5) == 0) {
3676                                 if (found_key) {
3677                                         if (nelems > 1) {
3678                                                 /*
3679                                                  * ERROR: We expected an object,
3680                                                  * not this identifier.
3681                                                  */
3682                                                 return (NULL);
3683                                         }
3684                                         return (dest);
3685                                 } else {
3686                                         cur--;
3687                                         state = DTRACE_JSON_COMMA;
3688                                         break;
3689                                 }
3690                         }
3691 
3692                         /*
3693                          * ERROR: we did not recognise the identifier as one
3694                          * of those in the JSON specification.
3695                          */
3696                         return (NULL);
3697                 case DTRACE_JSON_NUMBER:
3698                         if (cc == '.') {
3699                                 *dd++ = cc;
3700                                 state = DTRACE_JSON_NUMBER_FRAC;
3701                                 break;
3702                         }
3703 
3704                         if (cc == 'x' || cc == 'X') {
3705                                 /*
3706                                  * ERROR: specification explicitly excludes
3707                                  * hexidecimal or octal numbers.
3708                                  */
3709                                 return (NULL);
3710                         }
3711 
3712                         /* FALLTHRU */
3713                 case DTRACE_JSON_NUMBER_FRAC:
3714                         if (cc == 'e' || cc == 'E') {
3715                                 *dd++ = cc;
3716                                 state = DTRACE_JSON_NUMBER_EXP;
3717                                 break;
3718                         }
3719 
3720                         if (cc == '+' || cc == '-') {
3721                                 /*
3722                                  * ERROR: expect sign as part of exponent only.
3723                                  */
3724                                 return (NULL);
3725                         }
3726                         /* FALLTHRU */
3727                 case DTRACE_JSON_NUMBER_EXP:
3728                         if (isdigit(cc) || cc == '+' || cc == '-') {
3729                                 *dd++ = cc;
3730                                 break;
3731                         }
3732 
3733                         *dd = '\0';
3734                         dd = dest; /* reset string buffer */
3735                         if (found_key) {
3736                                 if (nelems > 1) {
3737                                         /*
3738                                          * ERROR: We expected an object, not
3739                                          * this number.
3740                                          */
3741                                         return (NULL);
3742                                 }
3743                                 return (dest);
3744                         }
3745 
3746                         cur--;
3747                         state = DTRACE_JSON_COMMA;
3748                         break;
3749                 case DTRACE_JSON_VALUE:
3750                         if (isspace(cc))
3751                                 break;
3752 
3753                         if (cc == '{' || cc == '[') {
3754                                 if (nelems > 1 && found_key) {
3755                                         in_array = cc == '[' ? B_TRUE : B_FALSE;
3756                                         /*
3757                                          * If our element selector directs us
3758                                          * to descend into this nested object,
3759                                          * then move to the next selector
3760                                          * element in the list and restart the
3761                                          * state machine.
3762                                          */
3763                                         while (*elem != '\0')
3764                                                 elem++;
3765                                         elem++; /* skip the inter-element NUL */
3766                                         nelems--;
3767                                         dd = dest;
3768                                         if (in_array) {
3769                                                 state = DTRACE_JSON_VALUE;
3770                                                 array_pos = 0;
3771                                                 array_elem = dtrace_strtoll(
3772                                                     elem, 10, size);
3773                                                 found_key = array_elem == 0 ?
3774                                                     B_TRUE : B_FALSE;
3775                                         } else {
3776                                                 found_key = B_FALSE;
3777                                                 state = DTRACE_JSON_OBJECT;
3778                                         }
3779                                         break;
3780                                 }
3781 
3782                                 /*
3783                                  * Otherwise, we wish to either skip this
3784                                  * nested object or return it in full.
3785                                  */
3786                                 if (cc == '[')
3787                                         brackets = 1;
3788                                 else
3789                                         braces = 1;
3790                                 *dd++ = cc;
3791                                 state = DTRACE_JSON_COLLECT_OBJECT;
3792                                 break;
3793                         }
3794 
3795                         if (cc == '"') {
3796                                 state = DTRACE_JSON_STRING;
3797                                 break;
3798                         }
3799 
3800                         if (islower(cc)) {
3801                                 /*
3802                                  * Here we deal with true, false and null.
3803                                  */
3804                                 *dd++ = cc;
3805                                 state = DTRACE_JSON_IDENTIFIER;
3806                                 break;
3807                         }
3808 
3809                         if (cc == '-' || isdigit(cc)) {
3810                                 *dd++ = cc;
3811                                 state = DTRACE_JSON_NUMBER;
3812                                 break;
3813                         }
3814 
3815                         /*
3816                          * ERROR: unexpected character at start of value.
3817                          */
3818                         return (NULL);
3819                 case DTRACE_JSON_COLLECT_OBJECT:
3820                         if (cc == '\0')
3821                                 /*
3822                                  * ERROR: unexpected end of input.
3823                                  */
3824                                 return (NULL);
3825 
3826                         *dd++ = cc;
3827                         if (cc == '"') {
3828                                 collect_object = B_TRUE;
3829                                 state = DTRACE_JSON_STRING;
3830                                 break;
3831                         }
3832 
3833                         if (cc == ']') {
3834                                 if (brackets-- == 0) {
3835                                         /*
3836                                          * ERROR: unbalanced brackets.
3837                                          */
3838                                         return (NULL);
3839                                 }
3840                         } else if (cc == '}') {
3841                                 if (braces-- == 0) {
3842                                         /*
3843                                          * ERROR: unbalanced braces.
3844                                          */
3845                                         return (NULL);
3846                                 }
3847                         } else if (cc == '{') {
3848                                 braces++;
3849                         } else if (cc == '[') {
3850                                 brackets++;
3851                         }
3852 
3853                         if (brackets == 0 && braces == 0) {
3854                                 if (found_key) {
3855                                         *dd = '\0';
3856                                         return (dest);
3857                                 }
3858                                 dd = dest; /* reset string buffer */
3859                                 state = DTRACE_JSON_COMMA;
3860                         }
3861                         break;
3862                 }
3863         }
3864         return (NULL);
3865 }
3866 
3867 /*
3868  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3869  * Notice that we don't bother validating the proper number of arguments or
3870  * their types in the tuple stack.  This isn't needed because all argument
3871  * interpretation is safe because of our load safety -- the worst that can
3872  * happen is that a bogus program can obtain bogus results.
3873  */
3874 static void
3875 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3876     dtrace_key_t *tupregs, int nargs,
3877     dtrace_mstate_t *mstate, dtrace_state_t *state)
3878 {
3879         volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3880         volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3881         dtrace_vstate_t *vstate = &state->dts_vstate;
3882 
3883         union {
3884                 mutex_impl_t mi;
3885                 uint64_t mx;
3886         } m;
3887 
3888         union {
3889                 krwlock_t ri;
3890                 uintptr_t rw;
3891         } r;
3892 
3893         switch (subr) {
3894         case DIF_SUBR_RAND:
3895                 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3896                 break;
3897 
3898         case DIF_SUBR_MUTEX_OWNED:
3899                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3900                     mstate, vstate)) {
3901                         regs[rd] = NULL;
3902                         break;
3903                 }
3904 
3905                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3906                 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3907                         regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3908                 else
3909                         regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3910                 break;
3911 
3912         case DIF_SUBR_MUTEX_OWNER:
3913                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3914                     mstate, vstate)) {
3915                         regs[rd] = NULL;
3916                         break;
3917                 }
3918 
3919                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3920                 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3921                     MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3922                         regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3923                 else
3924                         regs[rd] = 0;
3925                 break;
3926 
3927         case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3928                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3929                     mstate, vstate)) {
3930                         regs[rd] = NULL;
3931                         break;
3932                 }
3933 
3934                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3935                 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3936                 break;
3937 
3938         case DIF_SUBR_MUTEX_TYPE_SPIN:
3939                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3940                     mstate, vstate)) {
3941                         regs[rd] = NULL;
3942                         break;
3943                 }
3944 
3945                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3946                 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3947                 break;
3948 
3949         case DIF_SUBR_RW_READ_HELD: {
3950                 uintptr_t tmp;
3951 
3952                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3953                     mstate, vstate)) {
3954                         regs[rd] = NULL;
3955                         break;
3956                 }
3957 
3958                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3959                 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3960                 break;
3961         }
3962 
3963         case DIF_SUBR_RW_WRITE_HELD:
3964                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3965                     mstate, vstate)) {
3966                         regs[rd] = NULL;
3967                         break;
3968                 }
3969 
3970                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3971                 regs[rd] = _RW_WRITE_HELD(&r.ri);
3972                 break;
3973 
3974         case DIF_SUBR_RW_ISWRITER:
3975                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3976                     mstate, vstate)) {
3977                         regs[rd] = NULL;
3978                         break;
3979                 }
3980 
3981                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3982                 regs[rd] = _RW_ISWRITER(&r.ri);
3983                 break;
3984 
3985         case DIF_SUBR_BCOPY: {
3986                 /*
3987                  * We need to be sure that the destination is in the scratch
3988                  * region -- no other region is allowed.
3989                  */
3990                 uintptr_t src = tupregs[0].dttk_value;
3991                 uintptr_t dest = tupregs[1].dttk_value;
3992                 size_t size = tupregs[2].dttk_value;
3993 
3994                 if (!dtrace_inscratch(dest, size, mstate)) {
3995                         *flags |= CPU_DTRACE_BADADDR;
3996                         *illval = regs[rd];
3997                         break;
3998                 }
3999 
4000                 if (!dtrace_canload(src, size, mstate, vstate)) {
4001                         regs[rd] = NULL;
4002                         break;
4003                 }
4004 
4005                 dtrace_bcopy((void *)src, (void *)dest, size);
4006                 break;
4007         }
4008 
4009         case DIF_SUBR_ALLOCA:
4010         case DIF_SUBR_COPYIN: {
4011                 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4012                 uint64_t size =
4013                     tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4014                 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4015 
4016                 /*
4017                  * This action doesn't require any credential checks since
4018                  * probes will not activate in user contexts to which the
4019                  * enabling user does not have permissions.
4020                  */
4021 
4022                 /*
4023                  * Rounding up the user allocation size could have overflowed
4024                  * a large, bogus allocation (like -1ULL) to 0.
4025                  */
4026                 if (scratch_size < size ||
4027                     !DTRACE_INSCRATCH(mstate, scratch_size)) {
4028                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4029                         regs[rd] = NULL;
4030                         break;
4031                 }
4032 
4033                 if (subr == DIF_SUBR_COPYIN) {
4034                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4035                         dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4036                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4037                 }
4038 
4039                 mstate->dtms_scratch_ptr += scratch_size;
4040                 regs[rd] = dest;
4041                 break;
4042         }
4043 
4044         case DIF_SUBR_COPYINTO: {
4045                 uint64_t size = tupregs[1].dttk_value;
4046                 uintptr_t dest = tupregs[2].dttk_value;
4047 
4048                 /*
4049                  * This action doesn't require any credential checks since
4050                  * probes will not activate in user contexts to which the
4051                  * enabling user does not have permissions.
4052                  */
4053                 if (!dtrace_inscratch(dest, size, mstate)) {
4054                         *flags |= CPU_DTRACE_BADADDR;
4055                         *illval = regs[rd];
4056                         break;
4057                 }
4058 
4059                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4060                 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4061                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4062                 break;
4063         }
4064 
4065         case DIF_SUBR_COPYINSTR: {
4066                 uintptr_t dest = mstate->dtms_scratch_ptr;
4067                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4068 
4069                 if (nargs > 1 && tupregs[1].dttk_value < size)
4070                         size = tupregs[1].dttk_value + 1;
4071 
4072                 /*
4073                  * This action doesn't require any credential checks since
4074                  * probes will not activate in user contexts to which the
4075                  * enabling user does not have permissions.
4076                  */
4077                 if (!DTRACE_INSCRATCH(mstate, size)) {
4078                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4079                         regs[rd] = NULL;
4080                         break;
4081                 }
4082 
4083                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4084                 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4085                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4086 
4087                 ((char *)dest)[size - 1] = '\0';
4088                 mstate->dtms_scratch_ptr += size;
4089                 regs[rd] = dest;
4090                 break;
4091         }
4092 
4093         case DIF_SUBR_MSGSIZE:
4094         case DIF_SUBR_MSGDSIZE: {
4095                 uintptr_t baddr = tupregs[0].dttk_value, daddr;
4096                 uintptr_t wptr, rptr;
4097                 size_t count = 0;
4098                 int cont = 0;
4099 
4100                 while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4101 
4102                         if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4103                             vstate)) {
4104                                 regs[rd] = NULL;
4105                                 break;
4106                         }
4107 
4108                         wptr = dtrace_loadptr(baddr +
4109                             offsetof(mblk_t, b_wptr));
4110 
4111                         rptr = dtrace_loadptr(baddr +
4112                             offsetof(mblk_t, b_rptr));
4113 
4114                         if (wptr < rptr) {
4115                                 *flags |= CPU_DTRACE_BADADDR;
4116                                 *illval = tupregs[0].dttk_value;
4117                                 break;
4118                         }
4119 
4120                         daddr = dtrace_loadptr(baddr +
4121                             offsetof(mblk_t, b_datap));
4122 
4123                         baddr = dtrace_loadptr(baddr +
4124                             offsetof(mblk_t, b_cont));
4125 
4126                         /*
4127                          * We want to prevent against denial-of-service here,
4128                          * so we're only going to search the list for
4129                          * dtrace_msgdsize_max mblks.
4130                          */
4131                         if (cont++ > dtrace_msgdsize_max) {
4132                                 *flags |= CPU_DTRACE_ILLOP;
4133                                 break;
4134                         }
4135 
4136                         if (subr == DIF_SUBR_MSGDSIZE) {
4137                                 if (dtrace_load8(daddr +
4138                                     offsetof(dblk_t, db_type)) != M_DATA)
4139                                         continue;
4140                         }
4141 
4142                         count += wptr - rptr;
4143                 }
4144 
4145                 if (!(*flags & CPU_DTRACE_FAULT))
4146                         regs[rd] = count;
4147 
4148                 break;
4149         }
4150 
4151         case DIF_SUBR_PROGENYOF: {
4152                 pid_t pid = tupregs[0].dttk_value;
4153                 proc_t *p;
4154                 int rval = 0;
4155 
4156                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4157 
4158                 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4159                         if (p->p_pidp->pid_id == pid) {
4160                                 rval = 1;
4161                                 break;
4162                         }
4163                 }
4164 
4165                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4166 
4167                 regs[rd] = rval;
4168                 break;
4169         }
4170 
4171         case DIF_SUBR_SPECULATION:
4172                 regs[rd] = dtrace_speculation(state);
4173                 break;
4174 
4175         case DIF_SUBR_COPYOUT: {
4176                 uintptr_t kaddr = tupregs[0].dttk_value;
4177                 uintptr_t uaddr = tupregs[1].dttk_value;
4178                 uint64_t size = tupregs[2].dttk_value;
4179 
4180                 if (!dtrace_destructive_disallow &&
4181                     dtrace_priv_proc_control(state, mstate) &&
4182                     !dtrace_istoxic(kaddr, size)) {
4183                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4184                         dtrace_copyout(kaddr, uaddr, size, flags);
4185                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4186                 }
4187                 break;
4188         }
4189 
4190         case DIF_SUBR_COPYOUTSTR: {
4191                 uintptr_t kaddr = tupregs[0].dttk_value;
4192                 uintptr_t uaddr = tupregs[1].dttk_value;
4193                 uint64_t size = tupregs[2].dttk_value;
4194 
4195                 if (!dtrace_destructive_disallow &&
4196                     dtrace_priv_proc_control(state, mstate) &&
4197                     !dtrace_istoxic(kaddr, size)) {
4198                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4199                         dtrace_copyoutstr(kaddr, uaddr, size, flags);
4200                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4201                 }
4202                 break;
4203         }
4204 
4205         case DIF_SUBR_STRLEN: {
4206                 size_t sz;
4207                 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4208                 sz = dtrace_strlen((char *)addr,
4209                     state->dts_options[DTRACEOPT_STRSIZE]);
4210 
4211                 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
4212                         regs[rd] = NULL;
4213                         break;
4214                 }
4215 
4216                 regs[rd] = sz;
4217 
4218                 break;
4219         }
4220 
4221         case DIF_SUBR_STRCHR:
4222         case DIF_SUBR_STRRCHR: {
4223                 /*
4224                  * We're going to iterate over the string looking for the
4225                  * specified character.  We will iterate until we have reached
4226                  * the string length or we have found the character.  If this
4227                  * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4228                  * of the specified character instead of the first.
4229                  */
4230                 uintptr_t saddr = tupregs[0].dttk_value;
4231                 uintptr_t addr = tupregs[0].dttk_value;
4232                 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
4233                 char c, target = (char)tupregs[1].dttk_value;
4234 
4235                 for (regs[rd] = NULL; addr < limit; addr++) {
4236                         if ((c = dtrace_load8(addr)) == target) {
4237                                 regs[rd] = addr;
4238 
4239                                 if (subr == DIF_SUBR_STRCHR)
4240                                         break;
4241                         }
4242 
4243                         if (c == '\0')
4244                                 break;
4245                 }
4246 
4247                 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
4248                         regs[rd] = NULL;
4249                         break;
4250                 }
4251 
4252                 break;
4253         }
4254 
4255         case DIF_SUBR_STRSTR:
4256         case DIF_SUBR_INDEX:
4257         case DIF_SUBR_RINDEX: {
4258                 /*
4259                  * We're going to iterate over the string looking for the
4260                  * specified string.  We will iterate until we have reached
4261                  * the string length or we have found the string.  (Yes, this
4262                  * is done in the most naive way possible -- but considering
4263                  * that the string we're searching for is likely to be
4264                  * relatively short, the complexity of Rabin-Karp or similar
4265                  * hardly seems merited.)
4266                  */
4267                 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4268                 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4269                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4270                 size_t len = dtrace_strlen(addr, size);
4271                 size_t sublen = dtrace_strlen(substr, size);
4272                 char *limit = addr + len, *orig = addr;
4273                 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4274                 int inc = 1;
4275 
4276                 regs[rd] = notfound;
4277 
4278                 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4279                         regs[rd] = NULL;
4280                         break;
4281                 }
4282 
4283                 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4284                     vstate)) {
4285                         regs[rd] = NULL;
4286                         break;
4287                 }
4288 
4289                 /*
4290                  * strstr() and index()/rindex() have similar semantics if
4291                  * both strings are the empty string: strstr() returns a
4292                  * pointer to the (empty) string, and index() and rindex()
4293                  * both return index 0 (regardless of any position argument).
4294                  */
4295                 if (sublen == 0 && len == 0) {
4296                         if (subr == DIF_SUBR_STRSTR)
4297                                 regs[rd] = (uintptr_t)addr;
4298                         else
4299                                 regs[rd] = 0;
4300                         break;
4301                 }
4302 
4303                 if (subr != DIF_SUBR_STRSTR) {
4304                         if (subr == DIF_SUBR_RINDEX) {
4305                                 limit = orig - 1;
4306                                 addr += len;
4307                                 inc = -1;
4308                         }
4309 
4310                         /*
4311                          * Both index() and rindex() take an optional position
4312                          * argument that denotes the starting position.
4313                          */
4314                         if (nargs == 3) {
4315                                 int64_t pos = (int64_t)tupregs[2].dttk_value;
4316 
4317                                 /*
4318                                  * If the position argument to index() is
4319                                  * negative, Perl implicitly clamps it at
4320                                  * zero.  This semantic is a little surprising
4321                                  * given the special meaning of negative
4322                                  * positions to similar Perl functions like
4323                                  * substr(), but it appears to reflect a
4324                                  * notion that index() can start from a
4325                                  * negative index and increment its way up to
4326                                  * the string.  Given this notion, Perl's
4327                                  * rindex() is at least self-consistent in
4328                                  * that it implicitly clamps positions greater
4329                                  * than the string length to be the string
4330                                  * length.  Where Perl completely loses
4331                                  * coherence, however, is when the specified
4332                                  * substring is the empty string ("").  In
4333                                  * this case, even if the position is
4334                                  * negative, rindex() returns 0 -- and even if
4335                                  * the position is greater than the length,
4336                                  * index() returns the string length.  These
4337                                  * semantics violate the notion that index()
4338                                  * should never return a value less than the
4339                                  * specified position and that rindex() should
4340                                  * never return a value greater than the
4341                                  * specified position.  (One assumes that
4342                                  * these semantics are artifacts of Perl's
4343                                  * implementation and not the results of
4344                                  * deliberate design -- it beggars belief that
4345                                  * even Larry Wall could desire such oddness.)
4346                                  * While in the abstract one would wish for
4347                                  * consistent position semantics across
4348                                  * substr(), index() and rindex() -- or at the
4349                                  * very least self-consistent position
4350                                  * semantics for index() and rindex() -- we
4351                                  * instead opt to keep with the extant Perl
4352                                  * semantics, in all their broken glory.  (Do
4353                                  * we have more desire to maintain Perl's
4354                                  * semantics than Perl does?  Probably.)
4355                                  */
4356                                 if (subr == DIF_SUBR_RINDEX) {
4357                                         if (pos < 0) {
4358                                                 if (sublen == 0)
4359                                                         regs[rd] = 0;
4360                                                 break;
4361                                         }
4362 
4363                                         if (pos > len)
4364                                                 pos = len;
4365                                 } else {
4366                                         if (pos < 0)
4367                                                 pos = 0;
4368 
4369                                         if (pos >= len) {
4370                                                 if (sublen == 0)
4371                                                         regs[rd] = len;
4372                                                 break;
4373                                         }
4374                                 }
4375 
4376                                 addr = orig + pos;
4377                         }
4378                 }
4379 
4380                 for (regs[rd] = notfound; addr != limit; addr += inc) {
4381                         if (dtrace_strncmp(addr, substr, sublen) == 0) {
4382                                 if (subr != DIF_SUBR_STRSTR) {
4383                                         /*
4384                                          * As D index() and rindex() are
4385                                          * modeled on Perl (and not on awk),
4386                                          * we return a zero-based (and not a
4387                                          * one-based) index.  (For you Perl
4388                                          * weenies: no, we're not going to add
4389                                          * $[ -- and shouldn't you be at a con
4390                                          * or something?)
4391                                          */
4392                                         regs[rd] = (uintptr_t)(addr - orig);
4393                                         break;
4394                                 }
4395 
4396                                 ASSERT(subr == DIF_SUBR_STRSTR);
4397                                 regs[rd] = (uintptr_t)addr;
4398                                 break;
4399                         }
4400                 }
4401 
4402                 break;
4403         }
4404 
4405         case DIF_SUBR_STRTOK: {
4406                 uintptr_t addr = tupregs[0].dttk_value;
4407                 uintptr_t tokaddr = tupregs[1].dttk_value;
4408                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4409                 uintptr_t limit, toklimit = tokaddr + size;
4410                 uint8_t c, tokmap[32];   /* 256 / 8 */
4411                 char *dest = (char *)mstate->dtms_scratch_ptr;
4412                 int i;
4413 
4414                 /*
4415                  * Check both the token buffer and (later) the input buffer,
4416                  * since both could be non-scratch addresses.
4417                  */
4418                 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
4419                         regs[rd] = NULL;
4420                         break;
4421                 }
4422 
4423                 if (!DTRACE_INSCRATCH(mstate, size)) {
4424                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4425                         regs[rd] = NULL;
4426                         break;
4427                 }
4428 
4429                 if (addr == NULL) {
4430                         /*
4431                          * If the address specified is NULL, we use our saved
4432                          * strtok pointer from the mstate.  Note that this
4433                          * means that the saved strtok pointer is _only_
4434                          * valid within multiple enablings of the same probe --
4435                          * it behaves like an implicit clause-local variable.
4436                          */
4437                         addr = mstate->dtms_strtok;
4438                 } else {
4439                         /*
4440                          * If the user-specified address is non-NULL we must
4441                          * access check it.  This is the only time we have
4442                          * a chance to do so, since this address may reside
4443                          * in the string table of this clause-- future calls
4444                          * (when we fetch addr from mstate->dtms_strtok)
4445                          * would fail this access check.
4446                          */
4447                         if (!dtrace_strcanload(addr, size, mstate, vstate)) {
4448                                 regs[rd] = NULL;
4449                                 break;
4450                         }
4451                 }
4452 
4453                 /*
4454                  * First, zero the token map, and then process the token
4455                  * string -- setting a bit in the map for every character
4456                  * found in the token string.
4457                  */
4458                 for (i = 0; i < sizeof (tokmap); i++)
4459                         tokmap[i] = 0;
4460 
4461                 for (; tokaddr < toklimit; tokaddr++) {
4462                         if ((c = dtrace_load8(tokaddr)) == '\0')
4463                                 break;
4464 
4465                         ASSERT((c >> 3) < sizeof (tokmap));
4466                         tokmap[c >> 3] |= (1 << (c & 0x7));
4467                 }
4468 
4469                 for (limit = addr + size; addr < limit; addr++) {
4470                         /*
4471                          * We're looking for a character that is _not_ contained
4472                          * in the token string.
4473                          */
4474                         if ((c = dtrace_load8(addr)) == '\0')
4475                                 break;
4476 
4477                         if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4478                                 break;
4479                 }
4480 
4481                 if (c == '\0') {
4482                         /*
4483                          * We reached the end of the string without finding
4484                          * any character that was not in the token string.
4485                          * We return NULL in this case, and we set the saved
4486                          * address to NULL as well.
4487                          */
4488                         regs[rd] = NULL;
4489                         mstate->dtms_strtok = NULL;
4490                         break;
4491                 }
4492 
4493                 /*
4494                  * From here on, we're copying into the destination string.
4495                  */
4496                 for (i = 0; addr < limit && i < size - 1; addr++) {
4497                         if ((c = dtrace_load8(addr)) == '\0')
4498                                 break;
4499 
4500                         if (tokmap[c >> 3] & (1 << (c & 0x7)))
4501                                 break;
4502 
4503                         ASSERT(i < size);
4504                         dest[i++] = c;
4505                 }
4506 
4507                 ASSERT(i < size);
4508                 dest[i] = '\0';
4509                 regs[rd] = (uintptr_t)dest;
4510                 mstate->dtms_scratch_ptr += size;
4511                 mstate->dtms_strtok = addr;
4512                 break;
4513         }
4514 
4515         case DIF_SUBR_SUBSTR: {
4516                 uintptr_t s = tupregs[0].dttk_value;
4517                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4518                 char *d = (char *)mstate->dtms_scratch_ptr;
4519                 int64_t index = (int64_t)tupregs[1].dttk_value;
4520                 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4521                 size_t len = dtrace_strlen((char *)s, size);
4522                 int64_t i;
4523 
4524                 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4525                         regs[rd] = NULL;
4526                         break;
4527                 }
4528 
4529                 if (!DTRACE_INSCRATCH(mstate, size)) {
4530                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4531                         regs[rd] = NULL;
4532                         break;
4533                 }
4534 
4535                 if (nargs <= 2)
4536                         remaining = (int64_t)size;
4537 
4538                 if (index < 0) {
4539                         index += len;
4540 
4541                         if (index < 0 && index + remaining > 0) {
4542                                 remaining += index;
4543                                 index = 0;
4544                         }
4545                 }
4546 
4547                 if (index >= len || index < 0) {
4548                         remaining = 0;
4549                 } else if (remaining < 0) {
4550                         remaining += len - index;
4551                 } else if (index + remaining > size) {
4552                         remaining = size - index;
4553                 }
4554 
4555                 for (i = 0; i < remaining; i++) {
4556                         if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4557                                 break;
4558                 }
4559 
4560                 d[i] = '\0';
4561 
4562                 mstate->dtms_scratch_ptr += size;
4563                 regs[rd] = (uintptr_t)d;
4564                 break;
4565         }
4566 
4567         case DIF_SUBR_JSON: {
4568                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4569                 uintptr_t json = tupregs[0].dttk_value;
4570                 size_t jsonlen = dtrace_strlen((char *)json, size);
4571                 uintptr_t elem = tupregs[1].dttk_value;
4572                 size_t elemlen = dtrace_strlen((char *)elem, size);
4573 
4574                 char *dest = (char *)mstate->dtms_scratch_ptr;
4575                 char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
4576                 char *ee = elemlist;
4577                 int nelems = 1;
4578                 uintptr_t cur;
4579 
4580                 if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
4581                     !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
4582                         regs[rd] = NULL;
4583                         break;
4584                 }
4585 
4586                 if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
4587                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4588                         regs[rd] = NULL;
4589                         break;
4590                 }
4591 
4592                 /*
4593                  * Read the element selector and split it up into a packed list
4594                  * of strings.
4595                  */
4596                 for (cur = elem; cur < elem + elemlen; cur++) {
4597                         char cc = dtrace_load8(cur);
4598 
4599                         if (cur == elem && cc == '[') {
4600                                 /*
4601                                  * If the first element selector key is
4602                                  * actually an array index then ignore the
4603                                  * bracket.
4604                                  */
4605                                 continue;
4606                         }
4607 
4608                         if (cc == ']')
4609                                 continue;
4610 
4611                         if (cc == '.' || cc == '[') {
4612                                 nelems++;
4613                                 cc = '\0';
4614                         }
4615 
4616                         *ee++ = cc;
4617                 }
4618                 *ee++ = '\0';
4619 
4620                 if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
4621                     nelems, dest)) != NULL)
4622                         mstate->dtms_scratch_ptr += jsonlen + 1;
4623                 break;
4624         }
4625 
4626         case DIF_SUBR_TOUPPER:
4627         case DIF_SUBR_TOLOWER: {
4628                 uintptr_t s = tupregs[0].dttk_value;
4629                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4630                 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4631                 size_t len = dtrace_strlen((char *)s, size);
4632                 char lower, upper, convert;
4633                 int64_t i;
4634 
4635                 if (subr == DIF_SUBR_TOUPPER) {
4636                         lower = 'a';
4637                         upper = 'z';
4638                         convert = 'A';
4639                 } else {
4640                         lower = 'A';
4641                         upper = 'Z';
4642                         convert = 'a';
4643                 }
4644 
4645                 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4646                         regs[rd] = NULL;
4647                         break;
4648                 }
4649 
4650                 if (!DTRACE_INSCRATCH(mstate, size)) {
4651                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4652                         regs[rd] = NULL;
4653                         break;
4654                 }
4655 
4656                 for (i = 0; i < size - 1; i++) {
4657                         if ((c = dtrace_load8(s + i)) == '\0')
4658                                 break;
4659 
4660                         if (c >= lower && c <= upper)
4661                                 c = convert + (c - lower);
4662 
4663                         dest[i] = c;
4664                 }
4665 
4666                 ASSERT(i < size);
4667                 dest[i] = '\0';
4668                 regs[rd] = (uintptr_t)dest;
4669                 mstate->dtms_scratch_ptr += size;
4670                 break;
4671         }
4672 
4673 case DIF_SUBR_GETMAJOR:
4674 #ifdef _LP64
4675                 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4676 #else
4677                 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4678 #endif
4679                 break;
4680 
4681         case DIF_SUBR_GETMINOR:
4682 #ifdef _LP64
4683                 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4684 #else
4685                 regs[rd] = tupregs[0].dttk_value & MAXMIN;
4686 #endif
4687                 break;
4688 
4689         case DIF_SUBR_DDI_PATHNAME: {
4690                 /*
4691                  * This one is a galactic mess.  We are going to roughly
4692                  * emulate ddi_pathname(), but it's made more complicated
4693                  * by the fact that we (a) want to include the minor name and
4694                  * (b) must proceed iteratively instead of recursively.
4695                  */
4696                 uintptr_t dest = mstate->dtms_scratch_ptr;
4697                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4698                 char *start = (char *)dest, *end = start + size - 1;
4699                 uintptr_t daddr = tupregs[0].dttk_value;
4700                 int64_t minor = (int64_t)tupregs[1].dttk_value;
4701                 char *s;
4702                 int i, len, depth = 0;
4703 
4704                 /*
4705                  * Due to all the pointer jumping we do and context we must
4706                  * rely upon, we just mandate that the user must have kernel
4707                  * read privileges to use this routine.
4708                  */
4709                 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4710                         *flags |= CPU_DTRACE_KPRIV;
4711                         *illval = daddr;
4712                         regs[rd] = NULL;
4713                 }
4714 
4715                 if (!DTRACE_INSCRATCH(mstate, size)) {
4716                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4717                         regs[rd] = NULL;
4718                         break;
4719                 }
4720 
4721                 *end = '\0';
4722 
4723                 /*
4724                  * We want to have a name for the minor.  In order to do this,
4725                  * we need to walk the minor list from the devinfo.  We want
4726                  * to be sure that we don't infinitely walk a circular list,
4727                  * so we check for circularity by sending a scout pointer
4728                  * ahead two elements for every element that we iterate over;
4729                  * if the list is circular, these will ultimately point to the
4730                  * same element.  You may recognize this little trick as the
4731                  * answer to a stupid interview question -- one that always
4732                  * seems to be asked by those who had to have it laboriously
4733                  * explained to them, and who can't even concisely describe
4734                  * the conditions under which one would be forced to resort to
4735                  * this technique.  Needless to say, those conditions are
4736                  * found here -- and probably only here.  Is this the only use
4737                  * of this infamous trick in shipping, production code?  If it
4738                  * isn't, it probably should be...
4739                  */
4740                 if (minor != -1) {
4741                         uintptr_t maddr = dtrace_loadptr(daddr +
4742                             offsetof(struct dev_info, devi_minor));
4743 
4744                         uintptr_t next = offsetof(struct ddi_minor_data, next);
4745                         uintptr_t name = offsetof(struct ddi_minor_data,
4746                             d_minor) + offsetof(struct ddi_minor, name);
4747                         uintptr_t dev = offsetof(struct ddi_minor_data,
4748                             d_minor) + offsetof(struct ddi_minor, dev);
4749                         uintptr_t scout;
4750 
4751                         if (maddr != NULL)
4752                                 scout = dtrace_loadptr(maddr + next);
4753 
4754                         while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4755                                 uint64_t m;
4756 #ifdef _LP64
4757                                 m = dtrace_load64(maddr + dev) & MAXMIN64;
4758 #else
4759                                 m = dtrace_load32(maddr + dev) & MAXMIN;
4760 #endif
4761                                 if (m != minor) {
4762                                         maddr = dtrace_loadptr(maddr + next);
4763 
4764                                         if (scout == NULL)
4765                                                 continue;
4766 
4767                                         scout = dtrace_loadptr(scout + next);
4768 
4769                                         if (scout == NULL)
4770                                                 continue;
4771 
4772                                         scout = dtrace_loadptr(scout + next);
4773 
4774                                         if (scout == NULL)
4775                                                 continue;
4776 
4777                                         if (scout == maddr) {
4778                                                 *flags |= CPU_DTRACE_ILLOP;
4779                                                 break;
4780                                         }
4781 
4782                                         continue;
4783                                 }
4784 
4785                                 /*
4786                                  * We have the minor data.  Now we need to
4787                                  * copy the minor's name into the end of the
4788                                  * pathname.
4789                                  */
4790                                 s = (char *)dtrace_loadptr(maddr + name);
4791                                 len = dtrace_strlen(s, size);
4792 
4793                                 if (*flags & CPU_DTRACE_FAULT)
4794                                         break;
4795 
4796                                 if (len != 0) {
4797                                         if ((end -= (len + 1)) < start)
4798                                                 break;
4799 
4800                                         *end = ':';
4801                                 }
4802 
4803                                 for (i = 1; i <= len; i++)
4804                                         end[i] = dtrace_load8((uintptr_t)s++);
4805                                 break;
4806                         }
4807                 }
4808 
4809                 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4810                         ddi_node_state_t devi_state;
4811 
4812                         devi_state = dtrace_load32(daddr +
4813                             offsetof(struct dev_info, devi_node_state));
4814 
4815                         if (*flags & CPU_DTRACE_FAULT)
4816                                 break;
4817 
4818                         if (devi_state >= DS_INITIALIZED) {
4819                                 s = (char *)dtrace_loadptr(daddr +
4820                                     offsetof(struct dev_info, devi_addr));
4821                                 len = dtrace_strlen(s, size);
4822 
4823                                 if (*flags & CPU_DTRACE_FAULT)
4824                                         break;
4825 
4826                                 if (len != 0) {
4827                                         if ((end -= (len + 1)) < start)
4828                                                 break;
4829 
4830                                         *end = '@';
4831                                 }
4832 
4833                                 for (i = 1; i <= len; i++)
4834                                         end[i] = dtrace_load8((uintptr_t)s++);
4835                         }
4836 
4837                         /*
4838                          * Now for the node name...
4839                          */
4840                         s = (char *)dtrace_loadptr(daddr +
4841                             offsetof(struct dev_info, devi_node_name));
4842 
4843                         daddr = dtrace_loadptr(daddr +
4844                             offsetof(struct dev_info, devi_parent));
4845 
4846                         /*
4847                          * If our parent is NULL (that is, if we're the root
4848                          * node), we're going to use the special path
4849                          * "devices".
4850                          */
4851                         if (daddr == NULL)
4852                                 s = "devices";
4853 
4854                         len = dtrace_strlen(s, size);
4855                         if (*flags & CPU_DTRACE_FAULT)
4856                                 break;
4857 
4858                         if ((end -= (len + 1)) < start)
4859                                 break;
4860 
4861                         for (i = 1; i <= len; i++)
4862                                 end[i] = dtrace_load8((uintptr_t)s++);
4863                         *end = '/';
4864 
4865                         if (depth++ > dtrace_devdepth_max) {
4866                                 *flags |= CPU_DTRACE_ILLOP;
4867                                 break;
4868                         }
4869                 }
4870 
4871                 if (end < start)
4872                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4873 
4874                 if (daddr == NULL) {
4875                         regs[rd] = (uintptr_t)end;
4876                         mstate->dtms_scratch_ptr += size;
4877                 }
4878 
4879                 break;
4880         }
4881 
4882         case DIF_SUBR_STRJOIN: {
4883                 char *d = (char *)mstate->dtms_scratch_ptr;
4884                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4885                 uintptr_t s1 = tupregs[0].dttk_value;
4886                 uintptr_t s2 = tupregs[1].dttk_value;
4887                 int i = 0;
4888 
4889                 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4890                     !dtrace_strcanload(s2, size, mstate, vstate)) {
4891                         regs[rd] = NULL;
4892                         break;
4893                 }
4894 
4895                 if (!DTRACE_INSCRATCH(mstate, size)) {
4896                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4897                         regs[rd] = NULL;
4898                         break;
4899                 }
4900 
4901                 for (;;) {
4902                         if (i >= size) {
4903                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4904                                 regs[rd] = NULL;
4905                                 break;
4906                         }
4907 
4908                         if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4909                                 i--;
4910                                 break;
4911                         }
4912                 }
4913 
4914                 for (;;) {
4915                         if (i >= size) {
4916                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4917                                 regs[rd] = NULL;
4918                                 break;
4919                         }
4920 
4921                         if ((d[i++] = dtrace_load8(s2++)) == '\0')
4922                                 break;
4923                 }
4924 
4925                 if (i < size) {
4926                         mstate->dtms_scratch_ptr += i;
4927                         regs[rd] = (uintptr_t)d;
4928                 }
4929 
4930                 break;
4931         }
4932 
4933         case DIF_SUBR_STRTOLL: {
4934                 uintptr_t s = tupregs[0].dttk_value;
4935                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4936                 int base = 10;
4937 
4938                 if (nargs > 1) {
4939                         if ((base = tupregs[1].dttk_value) <= 1 ||
4940                             base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4941                                 *flags |= CPU_DTRACE_ILLOP;
4942                                 break;
4943                         }
4944                 }
4945 
4946                 if (!dtrace_strcanload(s, size, mstate, vstate)) {
4947                         regs[rd] = INT64_MIN;
4948                         break;
4949                 }
4950 
4951                 regs[rd] = dtrace_strtoll((char *)s, base, size);
4952                 break;
4953         }
4954 
4955         case DIF_SUBR_LLTOSTR: {
4956                 int64_t i = (int64_t)tupregs[0].dttk_value;
4957                 uint64_t val, digit;
4958                 uint64_t size = 65;     /* enough room for 2^64 in binary */
4959                 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4960                 int base = 10;
4961 
4962                 if (nargs > 1) {
4963                         if ((base = tupregs[1].dttk_value) <= 1 ||
4964                             base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4965                                 *flags |= CPU_DTRACE_ILLOP;
4966                                 break;
4967                         }
4968                 }
4969 
4970                 val = (base == 10 && i < 0) ? i * -1 : i;
4971 
4972                 if (!DTRACE_INSCRATCH(mstate, size)) {
4973                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4974                         regs[rd] = NULL;
4975                         break;
4976                 }
4977 
4978                 for (*end-- = '\0'; val; val /= base) {
4979                         if ((digit = val % base) <= '9' - '0') {
4980                                 *end-- = '0' + digit;
4981                         } else {
4982                                 *end-- = 'a' + (digit - ('9' - '0') - 1);
4983                         }
4984                 }
4985 
4986                 if (i == 0 && base == 16)
4987                         *end-- = '0';
4988 
4989                 if (base == 16)
4990                         *end-- = 'x';
4991 
4992                 if (i == 0 || base == 8 || base == 16)
4993                         *end-- = '0';
4994 
4995                 if (i < 0 && base == 10)
4996                         *end-- = '-';
4997 
4998                 regs[rd] = (uintptr_t)end + 1;
4999                 mstate->dtms_scratch_ptr += size;
5000                 break;
5001         }
5002 
5003         case DIF_SUBR_HTONS:
5004         case DIF_SUBR_NTOHS:
5005 #ifdef _BIG_ENDIAN
5006                 regs[rd] = (uint16_t)tupregs[0].dttk_value;
5007 #else
5008                 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5009 #endif
5010                 break;
5011 
5012 
5013         case DIF_SUBR_HTONL:
5014         case DIF_SUBR_NTOHL:
5015 #ifdef _BIG_ENDIAN
5016                 regs[rd] = (uint32_t)tupregs[0].dttk_value;
5017 #else
5018                 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5019 #endif
5020                 break;
5021 
5022 
5023         case DIF_SUBR_HTONLL:
5024         case DIF_SUBR_NTOHLL:
5025 #ifdef _BIG_ENDIAN
5026                 regs[rd] = (uint64_t)tupregs[0].dttk_value;
5027 #else
5028                 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5029 #endif
5030                 break;
5031 
5032 
5033         case DIF_SUBR_DIRNAME:
5034         case DIF_SUBR_BASENAME: {
5035                 char *dest = (char *)mstate->dtms_scratch_ptr;
5036                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5037                 uintptr_t src = tupregs[0].dttk_value;
5038                 int i, j, len = dtrace_strlen((char *)src, size);
5039                 int lastbase = -1, firstbase = -1, lastdir = -1;
5040                 int start, end;
5041 
5042                 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5043                         regs[rd] = NULL;
5044                         break;
5045                 }
5046 
5047                 if (!DTRACE_INSCRATCH(mstate, size)) {
5048                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5049                         regs[rd] = NULL;
5050                         break;
5051                 }
5052 
5053                 /*
5054                  * The basename and dirname for a zero-length string is
5055                  * defined to be "."
5056                  */
5057                 if (len == 0) {
5058                         len = 1;
5059                         src = (uintptr_t)".";
5060                 }
5061 
5062                 /*
5063                  * Start from the back of the string, moving back toward the
5064                  * front until we see a character that isn't a slash.  That
5065                  * character is the last character in the basename.
5066                  */
5067                 for (i = len - 1; i >= 0; i--) {
5068                         if (dtrace_load8(src + i) != '/')
5069                                 break;
5070                 }
5071 
5072                 if (i >= 0)
5073                         lastbase = i;
5074 
5075                 /*
5076                  * Starting from the last character in the basename, move
5077                  * towards the front until we find a slash.  The character
5078                  * that we processed immediately before that is the first
5079                  * character in the basename.
5080                  */
5081                 for (; i >= 0; i--) {
5082                         if (dtrace_load8(src + i) == '/')
5083                                 break;
5084                 }
5085 
5086                 if (i >= 0)
5087                         firstbase = i + 1;
5088 
5089                 /*
5090                  * Now keep going until we find a non-slash character.  That
5091                  * character is the last character in the dirname.
5092                  */
5093                 for (; i >= 0; i--) {
5094                         if (dtrace_load8(src + i) != '/')
5095                                 break;
5096                 }
5097 
5098                 if (i >= 0)
5099                         lastdir = i;
5100 
5101                 ASSERT(!(lastbase == -1 && firstbase != -1));
5102                 ASSERT(!(firstbase == -1 && lastdir != -1));
5103 
5104                 if (lastbase == -1) {
5105                         /*
5106                          * We didn't find a non-slash character.  We know that
5107                          * the length is non-zero, so the whole string must be
5108                          * slashes.  In either the dirname or the basename
5109                          * case, we return '/'.
5110                          */
5111                         ASSERT(firstbase == -1);
5112                         firstbase = lastbase = lastdir = 0;
5113                 }
5114 
5115                 if (firstbase == -1) {
5116                         /*
5117                          * The entire string consists only of a basename
5118                          * component.  If we're looking for dirname, we need
5119                          * to change our string to be just "."; if we're
5120                          * looking for a basename, we'll just set the first
5121                          * character of the basename to be 0.
5122                          */
5123                         if (subr == DIF_SUBR_DIRNAME) {
5124                                 ASSERT(lastdir == -1);
5125                                 src = (uintptr_t)".";
5126                                 lastdir = 0;
5127                         } else {
5128                                 firstbase = 0;
5129                         }
5130                 }
5131 
5132                 if (subr == DIF_SUBR_DIRNAME) {
5133                         if (lastdir == -1) {
5134                                 /*
5135                                  * We know that we have a slash in the name --
5136                                  * or lastdir would be set to 0, above.  And
5137                                  * because lastdir is -1, we know that this
5138                                  * slash must be the first character.  (That
5139                                  * is, the full string must be of the form
5140                                  * "/basename".)  In this case, the last
5141                                  * character of the directory name is 0.
5142                                  */
5143                                 lastdir = 0;
5144                         }
5145 
5146                         start = 0;
5147                         end = lastdir;
5148                 } else {
5149                         ASSERT(subr == DIF_SUBR_BASENAME);
5150                         ASSERT(firstbase != -1 && lastbase != -1);
5151                         start = firstbase;
5152                         end = lastbase;
5153                 }
5154 
5155                 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5156                         dest[j] = dtrace_load8(src + i);
5157 
5158                 dest[j] = '\0';
5159                 regs[rd] = (uintptr_t)dest;
5160                 mstate->dtms_scratch_ptr += size;
5161                 break;
5162         }
5163 
5164         case DIF_SUBR_GETF: {
5165                 uintptr_t fd = tupregs[0].dttk_value;
5166                 uf_info_t *finfo = &curthread->t_procp->p_user.u_finfo;
5167                 file_t *fp;
5168 
5169                 if (!dtrace_priv_proc(state, mstate)) {
5170                         regs[rd] = NULL;
5171                         break;
5172                 }
5173 
5174                 /*
5175                  * This is safe because fi_nfiles only increases, and the
5176                  * fi_list array is not freed when the array size doubles.
5177                  * (See the comment in flist_grow() for details on the
5178                  * management of the u_finfo structure.)
5179                  */
5180                 fp = fd < finfo->fi_nfiles ? finfo->fi_list[fd].uf_file : NULL;
5181 
5182                 mstate->dtms_getf = fp;
5183                 regs[rd] = (uintptr_t)fp;
5184                 break;
5185         }
5186 
5187         case DIF_SUBR_CLEANPATH: {
5188                 char *dest = (char *)mstate->dtms_scratch_ptr, c;
5189                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5190                 uintptr_t src = tupregs[0].dttk_value;
5191                 int i = 0, j = 0;
5192                 zone_t *z;
5193 
5194                 if (!dtrace_strcanload(src, size, mstate, vstate)) {
5195                         regs[rd] = NULL;
5196                         break;
5197                 }
5198 
5199                 if (!DTRACE_INSCRATCH(mstate, size)) {
5200                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5201                         regs[rd] = NULL;
5202                         break;
5203                 }
5204 
5205                 /*
5206                  * Move forward, loading each character.
5207                  */
5208                 do {
5209                         c = dtrace_load8(src + i++);
5210 next:
5211                         if (j + 5 >= size)   /* 5 = strlen("/..c\0") */
5212                                 break;
5213 
5214                         if (c != '/') {
5215                                 dest[j++] = c;
5216                                 continue;
5217                         }
5218 
5219                         c = dtrace_load8(src + i++);
5220 
5221                         if (c == '/') {
5222                                 /*
5223                                  * We have two slashes -- we can just advance
5224                                  * to the next character.
5225                                  */
5226                                 goto next;
5227                         }
5228 
5229                         if (c != '.') {
5230                                 /*
5231                                  * This is not "." and it's not ".." -- we can
5232                                  * just store the "/" and this character and
5233                                  * drive on.
5234                                  */
5235                                 dest[j++] = '/';
5236                                 dest[j++] = c;
5237                                 continue;
5238                         }
5239 
5240                         c = dtrace_load8(src + i++);
5241 
5242                         if (c == '/') {
5243                                 /*
5244                                  * This is a "/./" component.  We're not going
5245                                  * to store anything in the destination buffer;
5246                                  * we're just going to go to the next component.
5247                                  */
5248                                 goto next;
5249                         }
5250 
5251                         if (c != '.') {
5252                                 /*
5253                                  * This is not ".." -- we can just store the
5254                                  * "/." and this character and continue
5255                                  * processing.
5256                                  */
5257                                 dest[j++] = '/';
5258                                 dest[j++] = '.';
5259                                 dest[j++] = c;
5260                                 continue;
5261                         }
5262 
5263                         c = dtrace_load8(src + i++);
5264 
5265                         if (c != '/' && c != '\0') {
5266                                 /*
5267                                  * This is not ".." -- it's "..[mumble]".
5268                                  * We'll store the "/.." and this character
5269                                  * and continue processing.
5270                                  */
5271                                 dest[j++] = '/';
5272                                 dest[j++] = '.';
5273                                 dest[j++] = '.';
5274                                 dest[j++] = c;
5275                                 continue;
5276                         }
5277 
5278                         /*
5279                          * This is "/../" or "/..\0".  We need to back up
5280                          * our destination pointer until we find a "/".
5281                          */
5282                         i--;
5283                         while (j != 0 && dest[--j] != '/')
5284                                 continue;
5285 
5286                         if (c == '\0')
5287                                 dest[++j] = '/';
5288                 } while (c != '\0');
5289 
5290                 dest[j] = '\0';
5291 
5292                 if (mstate->dtms_getf != NULL &&
5293                     !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5294                     (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5295                         /*
5296                          * If we've done a getf() as a part of this ECB and we
5297                          * don't have kernel access (and we're not in the global
5298                          * zone), check if the path we cleaned up begins with
5299                          * the zone's root path, and trim it off if so.  Note
5300                          * that this is an output cleanliness issue, not a
5301                          * security issue: knowing one's zone root path does
5302                          * not enable privilege escalation.
5303                          */
5304                         if (strstr(dest, z->zone_rootpath) == dest)
5305                                 dest += strlen(z->zone_rootpath) - 1;
5306                 }
5307 
5308                 regs[rd] = (uintptr_t)dest;
5309                 mstate->dtms_scratch_ptr += size;
5310                 break;
5311         }
5312 
5313         case DIF_SUBR_INET_NTOA:
5314         case DIF_SUBR_INET_NTOA6:
5315         case DIF_SUBR_INET_NTOP: {
5316                 size_t size;
5317                 int af, argi, i;
5318                 char *base, *end;
5319 
5320                 if (subr == DIF_SUBR_INET_NTOP) {
5321                         af = (int)tupregs[0].dttk_value;
5322                         argi = 1;
5323                 } else {
5324                         af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5325                         argi = 0;
5326                 }
5327 
5328                 if (af == AF_INET) {
5329                         ipaddr_t ip4;
5330                         uint8_t *ptr8, val;
5331 
5332                         /*
5333                          * Safely load the IPv4 address.
5334                          */
5335                         ip4 = dtrace_load32(tupregs[argi].dttk_value);
5336 
5337                         /*
5338                          * Check an IPv4 string will fit in scratch.
5339                          */
5340                         size = INET_ADDRSTRLEN;
5341                         if (!DTRACE_INSCRATCH(mstate, size)) {
5342                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5343                                 regs[rd] = NULL;
5344                                 break;
5345                         }
5346                         base = (char *)mstate->dtms_scratch_ptr;
5347                         end = (char *)mstate->dtms_scratch_ptr + size - 1;
5348 
5349                         /*
5350                          * Stringify as a dotted decimal quad.
5351                          */
5352                         *end-- = '\0';
5353                         ptr8 = (uint8_t *)&ip4;
5354                         for (i = 3; i >= 0; i--) {
5355                                 val = ptr8[i];
5356 
5357                                 if (val == 0) {
5358                                         *end-- = '0';
5359                                 } else {
5360                                         for (; val; val /= 10) {
5361                                                 *end-- = '0' + (val % 10);
5362                                         }
5363                                 }
5364 
5365                                 if (i > 0)
5366                                         *end-- = '.';
5367                         }
5368                         ASSERT(end + 1 >= base);
5369 
5370                 } else if (af == AF_INET6) {
5371                         struct in6_addr ip6;
5372                         int firstzero, tryzero, numzero, v6end;
5373                         uint16_t val;
5374                         const char digits[] = "0123456789abcdef";
5375 
5376                         /*
5377                          * Stringify using RFC 1884 convention 2 - 16 bit
5378                          * hexadecimal values with a zero-run compression.
5379                          * Lower case hexadecimal digits are used.
5380                          *      eg, fe80::214:4fff:fe0b:76c8.
5381                          * The IPv4 embedded form is returned for inet_ntop,
5382                          * just the IPv4 string is returned for inet_ntoa6.
5383                          */
5384 
5385                         /*
5386                          * Safely load the IPv6 address.
5387                          */
5388                         dtrace_bcopy(
5389                             (void *)(uintptr_t)tupregs[argi].dttk_value,
5390                             (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5391 
5392                         /*
5393                          * Check an IPv6 string will fit in scratch.
5394                          */
5395                         size = INET6_ADDRSTRLEN;
5396                         if (!DTRACE_INSCRATCH(mstate, size)) {
5397                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5398                                 regs[rd] = NULL;
5399                                 break;
5400                         }
5401                         base = (char *)mstate->dtms_scratch_ptr;
5402                         end = (char *)mstate->dtms_scratch_ptr + size - 1;
5403                         *end-- = '\0';
5404 
5405                         /*
5406                          * Find the longest run of 16 bit zero values
5407                          * for the single allowed zero compression - "::".
5408                          */
5409                         firstzero = -1;
5410                         tryzero = -1;
5411                         numzero = 1;
5412                         for (i = 0; i < sizeof (struct in6_addr); i++) {
5413                                 if (ip6._S6_un._S6_u8[i] == 0 &&
5414                                     tryzero == -1 && i % 2 == 0) {
5415                                         tryzero = i;
5416                                         continue;
5417                                 }
5418 
5419                                 if (tryzero != -1 &&
5420                                     (ip6._S6_un._S6_u8[i] != 0 ||
5421                                     i == sizeof (struct in6_addr) - 1)) {
5422 
5423                                         if (i - tryzero <= numzero) {
5424                                                 tryzero = -1;
5425                                                 continue;
5426                                         }
5427 
5428                                         firstzero = tryzero;
5429                                         numzero = i - i % 2 - tryzero;
5430                                         tryzero = -1;
5431 
5432                                         if (ip6._S6_un._S6_u8[i] == 0 &&
5433                                             i == sizeof (struct in6_addr) - 1)
5434                                                 numzero += 2;
5435                                 }
5436                         }
5437                         ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5438 
5439                         /*
5440                          * Check for an IPv4 embedded address.
5441                          */
5442                         v6end = sizeof (struct in6_addr) - 2;
5443                         if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5444                             IN6_IS_ADDR_V4COMPAT(&ip6)) {
5445                                 for (i = sizeof (struct in6_addr) - 1;
5446                                     i >= DTRACE_V4MAPPED_OFFSET; i--) {
5447                                         ASSERT(end >= base);
5448 
5449                                         val = ip6._S6_un._S6_u8[i];
5450 
5451                                         if (val == 0) {
5452                                                 *end-- = '0';
5453                                         } else {
5454                                                 for (; val; val /= 10) {
5455                                                         *end-- = '0' + val % 10;
5456                                                 }
5457                                         }
5458 
5459                                         if (i > DTRACE_V4MAPPED_OFFSET)
5460                                                 *end-- = '.';
5461                                 }
5462 
5463                                 if (subr == DIF_SUBR_INET_NTOA6)
5464                                         goto inetout;
5465 
5466                                 /*
5467                                  * Set v6end to skip the IPv4 address that
5468                                  * we have already stringified.
5469                                  */
5470                                 v6end = 10;
5471                         }
5472 
5473                         /*
5474                          * Build the IPv6 string by working through the
5475                          * address in reverse.
5476                          */
5477                         for (i = v6end; i >= 0; i -= 2) {
5478                                 ASSERT(end >= base);
5479 
5480                                 if (i == firstzero + numzero - 2) {
5481                                         *end-- = ':';
5482                                         *end-- = ':';
5483                                         i -= numzero - 2;
5484                                         continue;
5485                                 }
5486 
5487                                 if (i < 14 && i != firstzero - 2)
5488                                         *end-- = ':';
5489 
5490                                 val = (ip6._S6_un._S6_u8[i] << 8) +
5491                                     ip6._S6_un._S6_u8[i + 1];
5492 
5493                                 if (val == 0) {
5494                                         *end-- = '0';
5495                                 } else {
5496                                         for (; val; val /= 16) {
5497                                                 *end-- = digits[val % 16];
5498                                         }
5499                                 }
5500                         }
5501                         ASSERT(end + 1 >= base);
5502 
5503                 } else {
5504                         /*
5505                          * The user didn't use AH_INET or AH_INET6.
5506                          */
5507                         DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5508                         regs[rd] = NULL;
5509                         break;
5510                 }
5511 
5512 inetout:        regs[rd] = (uintptr_t)end + 1;
5513                 mstate->dtms_scratch_ptr += size;
5514                 break;
5515         }
5516 
5517         }
5518 }
5519 
5520 /*
5521  * Emulate the execution of DTrace IR instructions specified by the given
5522  * DIF object.  This function is deliberately void of assertions as all of
5523  * the necessary checks are handled by a call to dtrace_difo_validate().
5524  */
5525 static uint64_t
5526 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5527     dtrace_vstate_t *vstate, dtrace_state_t *state)
5528 {
5529         const dif_instr_t *text = difo->dtdo_buf;
5530         const uint_t textlen = difo->dtdo_len;
5531         const char *strtab = difo->dtdo_strtab;
5532         const uint64_t *inttab = difo->dtdo_inttab;
5533 
5534         uint64_t rval = 0;
5535         dtrace_statvar_t *svar;
5536         dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5537         dtrace_difv_t *v;
5538         volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5539         volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
5540 
5541         dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5542         uint64_t regs[DIF_DIR_NREGS];
5543         uint64_t *tmp;
5544 
5545         uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5546         int64_t cc_r;
5547         uint_t pc = 0, id, opc;
5548         uint8_t ttop = 0;
5549         dif_instr_t instr;
5550         uint_t r1, r2, rd;
5551 
5552         /*
5553          * We stash the current DIF object into the machine state: we need it
5554          * for subsequent access checking.
5555          */
5556         mstate->dtms_difo = difo;
5557 
5558         regs[DIF_REG_R0] = 0;           /* %r0 is fixed at zero */
5559 
5560         while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5561                 opc = pc;
5562 
5563                 instr = text[pc++];
5564                 r1 = DIF_INSTR_R1(instr);
5565                 r2 = DIF_INSTR_R2(instr);
5566                 rd = DIF_INSTR_RD(instr);
5567 
5568                 switch (DIF_INSTR_OP(instr)) {
5569                 case DIF_OP_OR:
5570                         regs[rd] = regs[r1] | regs[r2];
5571                         break;
5572                 case DIF_OP_XOR:
5573                         regs[rd] = regs[r1] ^ regs[r2];
5574                         break;
5575                 case DIF_OP_AND:
5576                         regs[rd] = regs[r1] & regs[r2];
5577                         break;
5578                 case DIF_OP_SLL:
5579                         regs[rd] = regs[r1] << regs[r2];
5580                         break;
5581                 case DIF_OP_SRL:
5582                         regs[rd] = regs[r1] >> regs[r2];
5583                         break;
5584                 case DIF_OP_SUB:
5585                         regs[rd] = regs[r1] - regs[r2];
5586                         break;
5587                 case DIF_OP_ADD:
5588                         regs[rd] = regs[r1] + regs[r2];
5589                         break;
5590                 case DIF_OP_MUL:
5591                         regs[rd] = regs[r1] * regs[r2];
5592                         break;
5593                 case DIF_OP_SDIV:
5594                         if (regs[r2] == 0) {
5595                                 regs[rd] = 0;
5596                                 *flags |= CPU_DTRACE_DIVZERO;
5597                         } else {
5598                                 regs[rd] = (int64_t)regs[r1] /
5599                                     (int64_t)regs[r2];
5600                         }
5601                         break;
5602 
5603                 case DIF_OP_UDIV:
5604                         if (regs[r2] == 0) {
5605                                 regs[rd] = 0;
5606                                 *flags |= CPU_DTRACE_DIVZERO;
5607                         } else {
5608                                 regs[rd] = regs[r1] / regs[r2];
5609                         }
5610                         break;
5611 
5612                 case DIF_OP_SREM:
5613                         if (regs[r2] == 0) {
5614                                 regs[rd] = 0;
5615                                 *flags |= CPU_DTRACE_DIVZERO;
5616                         } else {
5617                                 regs[rd] = (int64_t)regs[r1] %
5618                                     (int64_t)regs[r2];
5619                         }
5620                         break;
5621 
5622                 case DIF_OP_UREM:
5623                         if (regs[r2] == 0) {
5624                                 regs[rd] = 0;
5625                                 *flags |= CPU_DTRACE_DIVZERO;
5626                         } else {
5627                                 regs[rd] = regs[r1] % regs[r2];
5628                         }
5629                         break;
5630 
5631                 case DIF_OP_NOT:
5632                         regs[rd] = ~regs[r1];
5633                         break;
5634                 case DIF_OP_MOV:
5635                         regs[rd] = regs[r1];
5636                         break;
5637                 case DIF_OP_CMP:
5638                         cc_r = regs[r1] - regs[r2];
5639                         cc_n = cc_r < 0;
5640                         cc_z = cc_r == 0;
5641                         cc_v = 0;
5642                         cc_c = regs[r1] < regs[r2];
5643                         break;
5644                 case DIF_OP_TST:
5645                         cc_n = cc_v = cc_c = 0;
5646                         cc_z = regs[r1] == 0;
5647                         break;
5648                 case DIF_OP_BA:
5649                         pc = DIF_INSTR_LABEL(instr);
5650                         break;
5651                 case DIF_OP_BE:
5652                         if (cc_z)
5653                                 pc = DIF_INSTR_LABEL(instr);
5654                         break;
5655                 case DIF_OP_BNE:
5656                         if (cc_z == 0)
5657                                 pc = DIF_INSTR_LABEL(instr);
5658                         break;
5659                 case DIF_OP_BG:
5660                         if ((cc_z | (cc_n ^ cc_v)) == 0)
5661                                 pc = DIF_INSTR_LABEL(instr);
5662                         break;
5663                 case DIF_OP_BGU:
5664                         if ((cc_c | cc_z) == 0)
5665                                 pc = DIF_INSTR_LABEL(instr);
5666                         break;
5667                 case DIF_OP_BGE:
5668                         if ((cc_n ^ cc_v) == 0)
5669                                 pc = DIF_INSTR_LABEL(instr);
5670                         break;
5671                 case DIF_OP_BGEU:
5672                         if (cc_c == 0)
5673                                 pc = DIF_INSTR_LABEL(instr);
5674                         break;
5675                 case DIF_OP_BL:
5676                         if (cc_n ^ cc_v)
5677                                 pc = DIF_INSTR_LABEL(instr);
5678                         break;
5679                 case DIF_OP_BLU:
5680                         if (cc_c)
5681                                 pc = DIF_INSTR_LABEL(instr);
5682                         break;
5683                 case DIF_OP_BLE:
5684                         if (cc_z | (cc_n ^ cc_v))
5685                                 pc = DIF_INSTR_LABEL(instr);
5686                         break;
5687                 case DIF_OP_BLEU:
5688                         if (cc_c | cc_z)
5689                                 pc = DIF_INSTR_LABEL(instr);
5690                         break;
5691                 case DIF_OP_RLDSB:
5692                         if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5693                                 break;
5694                         /*FALLTHROUGH*/
5695                 case DIF_OP_LDSB:
5696                         regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5697                         break;
5698                 case DIF_OP_RLDSH:
5699                         if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5700                                 break;
5701                         /*FALLTHROUGH*/
5702                 case DIF_OP_LDSH:
5703                         regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5704                         break;
5705                 case DIF_OP_RLDSW:
5706                         if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5707                                 break;
5708                         /*FALLTHROUGH*/
5709                 case DIF_OP_LDSW:
5710                         regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5711                         break;
5712                 case DIF_OP_RLDUB:
5713                         if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5714                                 break;
5715                         /*FALLTHROUGH*/
5716                 case DIF_OP_LDUB:
5717                         regs[rd] = dtrace_load8(regs[r1]);
5718                         break;
5719                 case DIF_OP_RLDUH:
5720                         if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5721                                 break;
5722                         /*FALLTHROUGH*/
5723                 case DIF_OP_LDUH:
5724                         regs[rd] = dtrace_load16(regs[r1]);
5725                         break;
5726                 case DIF_OP_RLDUW:
5727                         if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5728                                 break;
5729                         /*FALLTHROUGH*/
5730                 case DIF_OP_LDUW:
5731                         regs[rd] = dtrace_load32(regs[r1]);
5732                         break;
5733                 case DIF_OP_RLDX:
5734                         if (!dtrace_canload(regs[r1], 8, mstate, vstate))
5735                                 break;
5736                         /*FALLTHROUGH*/
5737                 case DIF_OP_LDX:
5738                         regs[rd] = dtrace_load64(regs[r1]);
5739                         break;
5740                 case DIF_OP_ULDSB:
5741                         regs[rd] = (int8_t)
5742                             dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5743                         break;
5744                 case DIF_OP_ULDSH:
5745                         regs[rd] = (int16_t)
5746                             dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5747                         break;
5748                 case DIF_OP_ULDSW:
5749                         regs[rd] = (int32_t)
5750                             dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5751                         break;
5752                 case DIF_OP_ULDUB:
5753                         regs[rd] =
5754                             dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5755                         break;
5756                 case DIF_OP_ULDUH:
5757                         regs[rd] =
5758                             dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5759                         break;
5760                 case DIF_OP_ULDUW:
5761                         regs[rd] =
5762                             dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5763                         break;
5764                 case DIF_OP_ULDX:
5765                         regs[rd] =
5766                             dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5767                         break;
5768                 case DIF_OP_RET:
5769                         rval = regs[rd];
5770                         pc = textlen;
5771                         break;
5772                 case DIF_OP_NOP:
5773                         break;
5774                 case DIF_OP_SETX:
5775                         regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5776                         break;
5777                 case DIF_OP_SETS:
5778                         regs[rd] = (uint64_t)(uintptr_t)
5779                             (strtab + DIF_INSTR_STRING(instr));
5780                         break;
5781                 case DIF_OP_SCMP: {
5782                         size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5783                         uintptr_t s1 = regs[r1];
5784                         uintptr_t s2 = regs[r2];
5785 
5786                         if (s1 != NULL &&
5787                             !dtrace_strcanload(s1, sz, mstate, vstate))
5788                                 break;
5789                         if (s2 != NULL &&
5790                             !dtrace_strcanload(s2, sz, mstate, vstate))
5791                                 break;
5792 
5793                         cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5794 
5795                         cc_n = cc_r < 0;
5796                         cc_z = cc_r == 0;
5797                         cc_v = cc_c = 0;
5798                         break;
5799                 }
5800                 case DIF_OP_LDGA:
5801                         regs[rd] = dtrace_dif_variable(mstate, state,
5802                             r1, regs[r2]);
5803                         break;
5804                 case DIF_OP_LDGS:
5805                         id = DIF_INSTR_VAR(instr);
5806 
5807                         if (id >= DIF_VAR_OTHER_UBASE) {
5808                                 uintptr_t a;
5809 
5810                                 id -= DIF_VAR_OTHER_UBASE;
5811                                 svar = vstate->dtvs_globals[id];
5812                                 ASSERT(svar != NULL);
5813                                 v = &svar->dtsv_var;
5814 
5815                                 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5816                                         regs[rd] = svar->dtsv_data;
5817                                         break;
5818                                 }
5819 
5820                                 a = (uintptr_t)svar->dtsv_data;
5821 
5822                                 if (*(uint8_t *)a == UINT8_MAX) {
5823                                         /*
5824                                          * If the 0th byte is set to UINT8_MAX
5825                                          * then this is to be treated as a
5826                                          * reference to a NULL variable.
5827                                          */
5828                                         regs[rd] = NULL;
5829                                 } else {
5830                                         regs[rd] = a + sizeof (uint64_t);
5831                                 }
5832 
5833                                 break;
5834                         }
5835 
5836                         regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5837                         break;
5838 
5839                 case DIF_OP_STGS:
5840                         id = DIF_INSTR_VAR(instr);
5841 
5842                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5843                         id -= DIF_VAR_OTHER_UBASE;
5844 
5845                         svar = vstate->dtvs_globals[id];
5846                         ASSERT(svar != NULL);
5847                         v = &svar->dtsv_var;
5848 
5849                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5850                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5851 
5852                                 ASSERT(a != NULL);
5853                                 ASSERT(svar->dtsv_size != 0);
5854 
5855                                 if (regs[rd] == NULL) {
5856                                         *(uint8_t *)a = UINT8_MAX;
5857                                         break;
5858                                 } else {
5859                                         *(uint8_t *)a = 0;
5860                                         a += sizeof (uint64_t);
5861                                 }
5862                                 if (!dtrace_vcanload(
5863                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5864                                     mstate, vstate))
5865                                         break;
5866 
5867                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5868                                     (void *)a, &v->dtdv_type);
5869                                 break;
5870                         }
5871 
5872                         svar->dtsv_data = regs[rd];
5873                         break;
5874 
5875                 case DIF_OP_LDTA:
5876                         /*
5877                          * There are no DTrace built-in thread-local arrays at
5878                          * present.  This opcode is saved for future work.
5879                          */
5880                         *flags |= CPU_DTRACE_ILLOP;
5881                         regs[rd] = 0;
5882                         break;
5883 
5884                 case DIF_OP_LDLS:
5885                         id = DIF_INSTR_VAR(instr);
5886 
5887                         if (id < DIF_VAR_OTHER_UBASE) {
5888                                 /*
5889                                  * For now, this has no meaning.
5890                                  */
5891                                 regs[rd] = 0;
5892                                 break;
5893                         }
5894 
5895                         id -= DIF_VAR_OTHER_UBASE;
5896 
5897                         ASSERT(id < vstate->dtvs_nlocals);
5898                         ASSERT(vstate->dtvs_locals != NULL);
5899 
5900                         svar = vstate->dtvs_locals[id];
5901                         ASSERT(svar != NULL);
5902                         v = &svar->dtsv_var;
5903 
5904                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5905                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5906                                 size_t sz = v->dtdv_type.dtdt_size;
5907 
5908                                 sz += sizeof (uint64_t);
5909                                 ASSERT(svar->dtsv_size == NCPU * sz);
5910                                 a += CPU->cpu_id * sz;
5911 
5912                                 if (*(uint8_t *)a == UINT8_MAX) {
5913                                         /*
5914                                          * If the 0th byte is set to UINT8_MAX
5915                                          * then this is to be treated as a
5916                                          * reference to a NULL variable.
5917                                          */
5918                                         regs[rd] = NULL;
5919                                 } else {
5920                                         regs[rd] = a + sizeof (uint64_t);
5921                                 }
5922 
5923                                 break;
5924                         }
5925 
5926                         ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5927                         tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5928                         regs[rd] = tmp[CPU->cpu_id];
5929                         break;
5930 
5931                 case DIF_OP_STLS:
5932                         id = DIF_INSTR_VAR(instr);
5933 
5934                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5935                         id -= DIF_VAR_OTHER_UBASE;
5936                         ASSERT(id < vstate->dtvs_nlocals);
5937 
5938                         ASSERT(vstate->dtvs_locals != NULL);
5939                         svar = vstate->dtvs_locals[id];
5940                         ASSERT(svar != NULL);
5941                         v = &svar->dtsv_var;
5942 
5943                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5944                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5945                                 size_t sz = v->dtdv_type.dtdt_size;
5946 
5947                                 sz += sizeof (uint64_t);
5948                                 ASSERT(svar->dtsv_size == NCPU * sz);
5949                                 a += CPU->cpu_id * sz;
5950 
5951                                 if (regs[rd] == NULL) {
5952                                         *(uint8_t *)a = UINT8_MAX;
5953                                         break;
5954                                 } else {
5955                                         *(uint8_t *)a = 0;
5956                                         a += sizeof (uint64_t);
5957                                 }
5958 
5959                                 if (!dtrace_vcanload(
5960                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5961                                     mstate, vstate))
5962                                         break;
5963 
5964                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5965                                     (void *)a, &v->dtdv_type);
5966                                 break;
5967                         }
5968 
5969                         ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5970                         tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5971                         tmp[CPU->cpu_id] = regs[rd];
5972                         break;
5973 
5974                 case DIF_OP_LDTS: {
5975                         dtrace_dynvar_t *dvar;
5976                         dtrace_key_t *key;
5977 
5978                         id = DIF_INSTR_VAR(instr);
5979                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5980                         id -= DIF_VAR_OTHER_UBASE;
5981                         v = &vstate->dtvs_tlocals[id];
5982 
5983                         key = &tupregs[DIF_DTR_NREGS];
5984                         key[0].dttk_value = (uint64_t)id;
5985                         key[0].dttk_size = 0;
5986                         DTRACE_TLS_THRKEY(key[1].dttk_value);
5987                         key[1].dttk_size = 0;
5988 
5989                         dvar = dtrace_dynvar(dstate, 2, key,
5990                             sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5991                             mstate, vstate);
5992 
5993                         if (dvar == NULL) {
5994                                 regs[rd] = 0;
5995                                 break;
5996                         }
5997 
5998                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5999                                 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6000                         } else {
6001                                 regs[rd] = *((uint64_t *)dvar->dtdv_data);
6002                         }
6003 
6004                         break;
6005                 }
6006 
6007                 case DIF_OP_STTS: {
6008                         dtrace_dynvar_t *dvar;
6009                         dtrace_key_t *key;
6010 
6011                         id = DIF_INSTR_VAR(instr);
6012                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
6013                         id -= DIF_VAR_OTHER_UBASE;
6014 
6015                         key = &tupregs[DIF_DTR_NREGS];
6016                         key[0].dttk_value = (uint64_t)id;
6017                         key[0].dttk_size = 0;
6018                         DTRACE_TLS_THRKEY(key[1].dttk_value);
6019                         key[1].dttk_size = 0;
6020                         v = &vstate->dtvs_tlocals[id];
6021 
6022                         dvar = dtrace_dynvar(dstate, 2, key,
6023                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6024                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
6025                             regs[rd] ? DTRACE_DYNVAR_ALLOC :
6026                             DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6027 
6028                         /*
6029                          * Given that we're storing to thread-local data,
6030                          * we need to flush our predicate cache.
6031                          */
6032                         curthread->t_predcache = NULL;
6033 
6034                         if (dvar == NULL)
6035                                 break;
6036 
6037                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6038                                 if (!dtrace_vcanload(
6039                                     (void *)(uintptr_t)regs[rd],
6040                                     &v->dtdv_type, mstate, vstate))
6041                                         break;
6042 
6043                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6044                                     dvar->dtdv_data, &v->dtdv_type);
6045                         } else {
6046                                 *((uint64_t *)dvar->dtdv_data) = regs[rd];
6047                         }
6048 
6049                         break;
6050                 }
6051 
6052                 case DIF_OP_SRA:
6053                         regs[rd] = (int64_t)regs[r1] >> regs[r2];
6054                         break;
6055 
6056                 case DIF_OP_CALL:
6057                         dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6058                             regs, tupregs, ttop, mstate, state);
6059                         break;
6060 
6061                 case DIF_OP_PUSHTR:
6062                         if (ttop == DIF_DTR_NREGS) {
6063                                 *flags |= CPU_DTRACE_TUPOFLOW;
6064                                 break;
6065                         }
6066 
6067                         if (r1 == DIF_TYPE_STRING) {
6068                                 /*
6069                                  * If this is a string type and the size is 0,
6070                                  * we'll use the system-wide default string
6071                                  * size.  Note that we are _not_ looking at
6072                                  * the value of the DTRACEOPT_STRSIZE option;
6073                                  * had this been set, we would expect to have
6074                                  * a non-zero size value in the "pushtr".
6075                                  */
6076                                 tupregs[ttop].dttk_size =
6077                                     dtrace_strlen((char *)(uintptr_t)regs[rd],
6078                                     regs[r2] ? regs[r2] :
6079                                     dtrace_strsize_default) + 1;
6080                         } else {
6081                                 tupregs[ttop].dttk_size = regs[r2];
6082                         }
6083 
6084                         tupregs[ttop++].dttk_value = regs[rd];
6085                         break;
6086 
6087                 case DIF_OP_PUSHTV:
6088                         if (ttop == DIF_DTR_NREGS) {
6089                                 *flags |= CPU_DTRACE_TUPOFLOW;
6090                                 break;
6091                         }
6092 
6093                         tupregs[ttop].dttk_value = regs[rd];
6094                         tupregs[ttop++].dttk_size = 0;
6095                         break;
6096 
6097                 case DIF_OP_POPTS:
6098                         if (ttop != 0)
6099                                 ttop--;
6100                         break;
6101 
6102                 case DIF_OP_FLUSHTS:
6103                         ttop = 0;
6104                         break;
6105 
6106                 case DIF_OP_LDGAA:
6107                 case DIF_OP_LDTAA: {
6108                         dtrace_dynvar_t *dvar;
6109                         dtrace_key_t *key = tupregs;
6110                         uint_t nkeys = ttop;
6111 
6112                         id = DIF_INSTR_VAR(instr);
6113                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
6114                         id -= DIF_VAR_OTHER_UBASE;
6115 
6116                         key[nkeys].dttk_value = (uint64_t)id;
6117                         key[nkeys++].dttk_size = 0;
6118 
6119                         if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6120                                 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6121                                 key[nkeys++].dttk_size = 0;
6122                                 v = &vstate->dtvs_tlocals[id];
6123                         } else {
6124                                 v = &vstate->dtvs_globals[id]->dtsv_var;
6125                         }
6126 
6127                         dvar = dtrace_dynvar(dstate, nkeys, key,
6128                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6129                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
6130                             DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6131 
6132                         if (dvar == NULL) {
6133                                 regs[rd] = 0;
6134                                 break;
6135                         }
6136 
6137                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6138                                 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6139                         } else {
6140                                 regs[rd] = *((uint64_t *)dvar->dtdv_data);
6141                         }
6142 
6143                         break;
6144                 }
6145 
6146                 case DIF_OP_STGAA:
6147                 case DIF_OP_STTAA: {
6148                         dtrace_dynvar_t *dvar;
6149                         dtrace_key_t *key = tupregs;
6150                         uint_t nkeys = ttop;
6151 
6152                         id = DIF_INSTR_VAR(instr);
6153                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
6154                         id -= DIF_VAR_OTHER_UBASE;
6155 
6156                         key[nkeys].dttk_value = (uint64_t)id;
6157                         key[nkeys++].dttk_size = 0;
6158 
6159                         if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6160                                 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6161                                 key[nkeys++].dttk_size = 0;
6162                                 v = &vstate->dtvs_tlocals[id];
6163                         } else {
6164                                 v = &vstate->dtvs_globals[id]->dtsv_var;
6165                         }
6166 
6167                         dvar = dtrace_dynvar(dstate, nkeys, key,
6168                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6169                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
6170                             regs[rd] ? DTRACE_DYNVAR_ALLOC :
6171                             DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6172 
6173                         if (dvar == NULL)
6174                                 break;
6175 
6176                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6177                                 if (!dtrace_vcanload(
6178                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6179                                     mstate, vstate))
6180                                         break;
6181 
6182                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6183                                     dvar->dtdv_data, &v->dtdv_type);
6184                         } else {
6185                                 *((uint64_t *)dvar->dtdv_data) = regs[rd];
6186                         }
6187 
6188                         break;
6189                 }
6190 
6191                 case DIF_OP_ALLOCS: {
6192                         uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6193                         size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6194 
6195                         /*
6196                          * Rounding up the user allocation size could have
6197                          * overflowed large, bogus allocations (like -1ULL) to
6198                          * 0.
6199                          */
6200                         if (size < regs[r1] ||
6201                             !DTRACE_INSCRATCH(mstate, size)) {
6202                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6203                                 regs[rd] = NULL;
6204                                 break;
6205                         }
6206 
6207                         dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6208                         mstate->dtms_scratch_ptr += size;
6209                         regs[rd] = ptr;
6210                         break;
6211                 }
6212 
6213                 case DIF_OP_COPYS:
6214                         if (!dtrace_canstore(regs[rd], regs[r2],
6215                             mstate, vstate)) {
6216                                 *flags |= CPU_DTRACE_BADADDR;
6217                                 *illval = regs[rd];
6218                                 break;
6219                         }
6220 
6221                         if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6222                                 break;
6223 
6224                         dtrace_bcopy((void *)(uintptr_t)regs[r1],
6225                             (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6226                         break;
6227 
6228                 case DIF_OP_STB:
6229                         if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6230                                 *flags |= CPU_DTRACE_BADADDR;
6231                                 *illval = regs[rd];
6232                                 break;
6233                         }
6234                         *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6235                         break;
6236 
6237                 case DIF_OP_STH:
6238                         if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6239                                 *flags |= CPU_DTRACE_BADADDR;
6240                                 *illval = regs[rd];
6241                                 break;
6242                         }
6243                         if (regs[rd] & 1) {
6244                                 *flags |= CPU_DTRACE_BADALIGN;
6245                                 *illval = regs[rd];
6246                                 break;
6247                         }
6248                         *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6249                         break;
6250 
6251                 case DIF_OP_STW:
6252                         if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6253                                 *flags |= CPU_DTRACE_BADADDR;
6254                                 *illval = regs[rd];
6255                                 break;
6256                         }
6257                         if (regs[rd] & 3) {
6258                                 *flags |= CPU_DTRACE_BADALIGN;
6259                                 *illval = regs[rd];
6260                                 break;
6261                         }
6262                         *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6263                         break;
6264 
6265                 case DIF_OP_STX:
6266                         if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6267                                 *flags |= CPU_DTRACE_BADADDR;
6268                                 *illval = regs[rd];
6269                                 break;
6270                         }
6271                         if (regs[rd] & 7) {
6272                                 *flags |= CPU_DTRACE_BADALIGN;
6273                                 *illval = regs[rd];
6274                                 break;
6275                         }
6276                         *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6277                         break;
6278                 }
6279         }
6280 
6281         if (!(*flags & CPU_DTRACE_FAULT))
6282                 return (rval);
6283 
6284         mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6285         mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6286 
6287         return (0);
6288 }
6289 
6290 static void
6291 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6292 {
6293         dtrace_probe_t *probe = ecb->dte_probe;
6294         dtrace_provider_t *prov = probe->dtpr_provider;
6295         char c[DTRACE_FULLNAMELEN + 80], *str;
6296         char *msg = "dtrace: breakpoint action at probe ";
6297         char *ecbmsg = " (ecb ";
6298         uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6299         uintptr_t val = (uintptr_t)ecb;
6300         int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6301 
6302         if (dtrace_destructive_disallow)
6303                 return;
6304 
6305         /*
6306          * It's impossible to be taking action on the NULL probe.
6307          */
6308         ASSERT(probe != NULL);
6309 
6310         /*
6311          * This is a poor man's (destitute man's?) sprintf():  we want to
6312          * print the provider name, module name, function name and name of
6313          * the probe, along with the hex address of the ECB with the breakpoint
6314          * action -- all of which we must place in the character buffer by
6315          * hand.
6316          */
6317         while (*msg != '\0')
6318                 c[i++] = *msg++;
6319 
6320         for (str = prov->dtpv_name; *str != '\0'; str++)
6321                 c[i++] = *str;
6322         c[i++] = ':';
6323 
6324         for (str = probe->dtpr_mod; *str != '\0'; str++)
6325                 c[i++] = *str;
6326         c[i++] = ':';
6327 
6328         for (str = probe->dtpr_func; *str != '\0'; str++)
6329                 c[i++] = *str;
6330         c[i++] = ':';
6331 
6332         for (str = probe->dtpr_name; *str != '\0'; str++)
6333                 c[i++] = *str;
6334 
6335         while (*ecbmsg != '\0')
6336                 c[i++] = *ecbmsg++;
6337 
6338         while (shift >= 0) {
6339                 mask = (uintptr_t)0xf << shift;
6340 
6341                 if (val >= ((uintptr_t)1 << shift))
6342                         c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6343                 shift -= 4;
6344         }
6345 
6346         c[i++] = ')';
6347         c[i] = '\0';
6348 
6349         debug_enter(c);
6350 }
6351 
6352 static void
6353 dtrace_action_panic(dtrace_ecb_t *ecb)
6354 {
6355         dtrace_probe_t *probe = ecb->dte_probe;
6356 
6357         /*
6358          * It's impossible to be taking action on the NULL probe.
6359          */
6360         ASSERT(probe != NULL);
6361 
6362         if (dtrace_destructive_disallow)
6363                 return;
6364 
6365         if (dtrace_panicked != NULL)
6366                 return;
6367 
6368         if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6369                 return;
6370 
6371         /*
6372          * We won the right to panic.  (We want to be sure that only one
6373          * thread calls panic() from dtrace_probe(), and that panic() is
6374          * called exactly once.)
6375          */
6376         dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6377             probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6378             probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6379 }
6380 
6381 static void
6382 dtrace_action_raise(uint64_t sig)
6383 {
6384         if (dtrace_destructive_disallow)
6385                 return;
6386 
6387         if (sig >= NSIG) {
6388                 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6389                 return;
6390         }
6391 
6392         /*
6393          * raise() has a queue depth of 1 -- we ignore all subsequent
6394          * invocations of the raise() action.
6395          */
6396         if (curthread->t_dtrace_sig == 0)
6397                 curthread->t_dtrace_sig = (uint8_t)sig;
6398 
6399         curthread->t_sig_check = 1;
6400         aston(curthread);
6401 }
6402 
6403 static void
6404 dtrace_action_stop(void)
6405 {
6406         if (dtrace_destructive_disallow)
6407                 return;
6408 
6409         if (!curthread->t_dtrace_stop) {
6410                 curthread->t_dtrace_stop = 1;
6411                 curthread->t_sig_check = 1;
6412                 aston(curthread);
6413         }
6414 }
6415 
6416 static void
6417 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6418 {
6419         hrtime_t now;
6420         volatile uint16_t *flags;
6421         cpu_t *cpu = CPU;
6422 
6423         if (dtrace_destructive_disallow)
6424                 return;
6425 
6426         flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6427 
6428         now = dtrace_gethrtime();
6429 
6430         if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6431                 /*
6432                  * We need to advance the mark to the current time.
6433                  */
6434                 cpu->cpu_dtrace_chillmark = now;
6435                 cpu->cpu_dtrace_chilled = 0;
6436         }
6437 
6438         /*
6439          * Now check to see if the requested chill time would take us over
6440          * the maximum amount of time allowed in the chill interval.  (Or
6441          * worse, if the calculation itself induces overflow.)
6442          */
6443         if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6444             cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6445                 *flags |= CPU_DTRACE_ILLOP;
6446                 return;
6447         }
6448 
6449         while (dtrace_gethrtime() - now < val)
6450                 continue;
6451 
6452         /*
6453          * Normally, we assure that the value of the variable "timestamp" does
6454          * not change within an ECB.  The presence of chill() represents an
6455          * exception to this rule, however.
6456          */
6457         mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6458         cpu->cpu_dtrace_chilled += val;
6459 }
6460 
6461 static void
6462 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6463     uint64_t *buf, uint64_t arg)
6464 {
6465         int nframes = DTRACE_USTACK_NFRAMES(arg);
6466         int strsize = DTRACE_USTACK_STRSIZE(arg);
6467         uint64_t *pcs = &buf[1], *fps;
6468         char *str = (char *)&pcs[nframes];
6469         int size, offs = 0, i, j;
6470         uintptr_t old = mstate->dtms_scratch_ptr, saved;
6471         uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6472         char *sym;
6473 
6474         /*
6475          * Should be taking a faster path if string space has not been
6476          * allocated.
6477          */
6478         ASSERT(strsize != 0);
6479 
6480         /*
6481          * We will first allocate some temporary space for the frame pointers.
6482          */
6483         fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6484         size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6485             (nframes * sizeof (uint64_t));
6486 
6487         if (!DTRACE_INSCRATCH(mstate, size)) {
6488                 /*
6489                  * Not enough room for our frame pointers -- need to indicate
6490                  * that we ran out of scratch space.
6491                  */
6492                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6493                 return;
6494         }
6495 
6496         mstate->dtms_scratch_ptr += size;
6497         saved = mstate->dtms_scratch_ptr;
6498 
6499         /*
6500          * Now get a stack with both program counters and frame pointers.
6501          */
6502         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6503         dtrace_getufpstack(buf, fps, nframes + 1);
6504         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6505 
6506         /*
6507          * If that faulted, we're cooked.
6508          */
6509         if (*flags & CPU_DTRACE_FAULT)
6510                 goto out;
6511 
6512         /*
6513          * Now we want to walk up the stack, calling the USTACK helper.  For
6514          * each iteration, we restore the scratch pointer.
6515          */
6516         for (i = 0; i < nframes; i++) {
6517                 mstate->dtms_scratch_ptr = saved;
6518 
6519                 if (offs >= strsize)
6520                         break;
6521 
6522                 sym = (char *)(uintptr_t)dtrace_helper(
6523                     DTRACE_HELPER_ACTION_USTACK,
6524                     mstate, state, pcs[i], fps[i]);
6525 
6526                 /*
6527                  * If we faulted while running the helper, we're going to
6528                  * clear the fault and null out the corresponding string.
6529                  */
6530                 if (*flags & CPU_DTRACE_FAULT) {
6531                         *flags &= ~CPU_DTRACE_FAULT;
6532                         str[offs++] = '\0';
6533                         continue;
6534                 }
6535 
6536                 if (sym == NULL) {
6537                         str[offs++] = '\0';
6538                         continue;
6539                 }
6540 
6541                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6542 
6543                 /*
6544                  * Now copy in the string that the helper returned to us.
6545                  */
6546                 for (j = 0; offs + j < strsize; j++) {
6547                         if ((str[offs + j] = sym[j]) == '\0')
6548                                 break;
6549                 }
6550 
6551                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6552 
6553                 offs += j + 1;
6554         }
6555 
6556         if (offs >= strsize) {
6557                 /*
6558                  * If we didn't have room for all of the strings, we don't
6559                  * abort processing -- this needn't be a fatal error -- but we
6560                  * still want to increment a counter (dts_stkstroverflows) to
6561                  * allow this condition to be warned about.  (If this is from
6562                  * a jstack() action, it is easily tuned via jstackstrsize.)
6563                  */
6564                 dtrace_error(&state->dts_stkstroverflows);
6565         }
6566 
6567         while (offs < strsize)
6568                 str[offs++] = '\0';
6569 
6570 out:
6571         mstate->dtms_scratch_ptr = old;
6572 }
6573 
6574 /*
6575  * If you're looking for the epicenter of DTrace, you just found it.  This
6576  * is the function called by the provider to fire a probe -- from which all
6577  * subsequent probe-context DTrace activity emanates.
6578  */
6579 void
6580 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6581     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6582 {
6583         processorid_t cpuid;
6584         dtrace_icookie_t cookie;
6585         dtrace_probe_t *probe;
6586         dtrace_mstate_t mstate;
6587         dtrace_ecb_t *ecb;
6588         dtrace_action_t *act;
6589         intptr_t offs;
6590         size_t size;
6591         int vtime, onintr;
6592         volatile uint16_t *flags;
6593         hrtime_t now;
6594 
6595         /*
6596          * Kick out immediately if this CPU is still being born (in which case
6597          * curthread will be set to -1) or the current thread can't allow
6598          * probes in its current context.
6599          */
6600         if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6601                 return;
6602 
6603         cookie = dtrace_interrupt_disable();
6604         probe = dtrace_probes[id - 1];
6605         cpuid = CPU->cpu_id;
6606         onintr = CPU_ON_INTR(CPU);
6607 
6608         if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6609             probe->dtpr_predcache == curthread->t_predcache) {
6610                 /*
6611                  * We have hit in the predicate cache; we know that
6612                  * this predicate would evaluate to be false.
6613                  */
6614                 dtrace_interrupt_enable(cookie);
6615                 return;
6616         }
6617 
6618         if (panic_quiesce) {
6619                 /*
6620                  * We don't trace anything if we're panicking.
6621                  */
6622                 dtrace_interrupt_enable(cookie);
6623                 return;
6624         }
6625 
6626         now = dtrace_gethrtime();
6627         vtime = dtrace_vtime_references != 0;
6628 
6629         if (vtime && curthread->t_dtrace_start)
6630                 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6631 
6632         mstate.dtms_difo = NULL;
6633         mstate.dtms_probe = probe;
6634         mstate.dtms_strtok = NULL;
6635         mstate.dtms_arg[0] = arg0;
6636         mstate.dtms_arg[1] = arg1;
6637         mstate.dtms_arg[2] = arg2;
6638         mstate.dtms_arg[3] = arg3;
6639         mstate.dtms_arg[4] = arg4;
6640 
6641         flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6642 
6643         for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6644                 dtrace_predicate_t *pred = ecb->dte_predicate;
6645                 dtrace_state_t *state = ecb->dte_state;
6646                 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6647                 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6648                 dtrace_vstate_t *vstate = &state->dts_vstate;
6649                 dtrace_provider_t *prov = probe->dtpr_provider;
6650                 uint64_t tracememsize = 0;
6651                 int committed = 0;
6652                 caddr_t tomax;
6653 
6654                 /*
6655                  * A little subtlety with the following (seemingly innocuous)
6656                  * declaration of the automatic 'val':  by looking at the
6657                  * code, you might think that it could be declared in the
6658                  * action processing loop, below.  (That is, it's only used in
6659                  * the action processing loop.)  However, it must be declared
6660                  * out of that scope because in the case of DIF expression
6661                  * arguments to aggregating actions, one iteration of the
6662                  * action loop will use the last iteration's value.
6663                  */
6664 #ifdef lint
6665                 uint64_t val = 0;
6666 #else
6667                 uint64_t val;
6668 #endif
6669 
6670                 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6671                 mstate.dtms_access = DTRACE_ACCESS_ARGS | DTRACE_ACCESS_PROC;
6672                 mstate.dtms_getf = NULL;
6673 
6674                 *flags &= ~CPU_DTRACE_ERROR;
6675 
6676                 if (prov == dtrace_provider) {
6677                         /*
6678                          * If dtrace itself is the provider of this probe,
6679                          * we're only going to continue processing the ECB if
6680                          * arg0 (the dtrace_state_t) is equal to the ECB's
6681                          * creating state.  (This prevents disjoint consumers
6682                          * from seeing one another's metaprobes.)
6683                          */
6684                         if (arg0 != (uint64_t)(uintptr_t)state)
6685                                 continue;
6686                 }
6687 
6688                 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6689                         /*
6690                          * We're not currently active.  If our provider isn't
6691                          * the dtrace pseudo provider, we're not interested.
6692                          */
6693                         if (prov != dtrace_provider)
6694                                 continue;
6695 
6696                         /*
6697                          * Now we must further check if we are in the BEGIN
6698                          * probe.  If we are, we will only continue processing
6699                          * if we're still in WARMUP -- if one BEGIN enabling
6700                          * has invoked the exit() action, we don't want to
6701                          * evaluate subsequent BEGIN enablings.
6702                          */
6703                         if (probe->dtpr_id == dtrace_probeid_begin &&
6704                             state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6705                                 ASSERT(state->dts_activity ==
6706                                     DTRACE_ACTIVITY_DRAINING);
6707                                 continue;
6708                         }
6709                 }
6710 
6711                 if (ecb->dte_cond && !dtrace_priv_probe(state, &mstate, ecb))
6712                         continue;
6713 
6714                 if (now - state->dts_alive > dtrace_deadman_timeout) {
6715                         /*
6716                          * We seem to be dead.  Unless we (a) have kernel
6717                          * destructive permissions (b) have explicitly enabled
6718                          * destructive actions and (c) destructive actions have
6719                          * not been disabled, we're going to transition into
6720                          * the KILLED state, from which no further processing
6721                          * on this state will be performed.
6722                          */
6723                         if (!dtrace_priv_kernel_destructive(state) ||
6724                             !state->dts_cred.dcr_destructive ||
6725                             dtrace_destructive_disallow) {
6726                                 void *activity = &state->dts_activity;
6727                                 dtrace_activity_t current;
6728 
6729                                 do {
6730                                         current = state->dts_activity;
6731                                 } while (dtrace_cas32(activity, current,
6732                                     DTRACE_ACTIVITY_KILLED) != current);
6733 
6734                                 continue;
6735                         }
6736                 }
6737 
6738                 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6739                     ecb->dte_alignment, state, &mstate)) < 0)
6740                         continue;
6741 
6742                 tomax = buf->dtb_tomax;
6743                 ASSERT(tomax != NULL);
6744 
6745                 if (ecb->dte_size != 0) {
6746                         dtrace_rechdr_t dtrh;
6747                         if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6748                                 mstate.dtms_timestamp = dtrace_gethrtime();
6749                                 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6750                         }
6751                         ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
6752                         dtrh.dtrh_epid = ecb->dte_epid;
6753                         DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
6754                             mstate.dtms_timestamp);
6755                         *((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
6756                 }
6757 
6758                 mstate.dtms_epid = ecb->dte_epid;
6759                 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6760 
6761                 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6762                         mstate.dtms_access |= DTRACE_ACCESS_KERNEL;
6763 
6764                 if (pred != NULL) {
6765                         dtrace_difo_t *dp = pred->dtp_difo;
6766                         int rval;
6767 
6768                         rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6769 
6770                         if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6771                                 dtrace_cacheid_t cid = probe->dtpr_predcache;
6772 
6773                                 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6774                                         /*
6775                                          * Update the predicate cache...
6776                                          */
6777                                         ASSERT(cid == pred->dtp_cacheid);
6778                                         curthread->t_predcache = cid;
6779                                 }
6780 
6781                                 continue;
6782                         }
6783                 }
6784 
6785                 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6786                     act != NULL; act = act->dta_next) {
6787                         size_t valoffs;
6788                         dtrace_difo_t *dp;
6789                         dtrace_recdesc_t *rec = &act->dta_rec;
6790 
6791                         size = rec->dtrd_size;
6792                         valoffs = offs + rec->dtrd_offset;
6793 
6794                         if (DTRACEACT_ISAGG(act->dta_kind)) {
6795                                 uint64_t v = 0xbad;
6796                                 dtrace_aggregation_t *agg;
6797 
6798                                 agg = (dtrace_aggregation_t *)act;
6799 
6800                                 if ((dp = act->dta_difo) != NULL)
6801                                         v = dtrace_dif_emulate(dp,
6802                                             &mstate, vstate, state);
6803 
6804                                 if (*flags & CPU_DTRACE_ERROR)
6805                                         continue;
6806 
6807                                 /*
6808                                  * Note that we always pass the expression
6809                                  * value from the previous iteration of the
6810                                  * action loop.  This value will only be used
6811                                  * if there is an expression argument to the
6812                                  * aggregating action, denoted by the
6813                                  * dtag_hasarg field.
6814                                  */
6815                                 dtrace_aggregate(agg, buf,
6816                                     offs, aggbuf, v, val);
6817                                 continue;
6818                         }
6819 
6820                         switch (act->dta_kind) {
6821                         case DTRACEACT_STOP:
6822                                 if (dtrace_priv_proc_destructive(state,
6823                                     &mstate))
6824                                         dtrace_action_stop();
6825                                 continue;
6826 
6827                         case DTRACEACT_BREAKPOINT:
6828                                 if (dtrace_priv_kernel_destructive(state))
6829                                         dtrace_action_breakpoint(ecb);
6830                                 continue;
6831 
6832                         case DTRACEACT_PANIC:
6833                                 if (dtrace_priv_kernel_destructive(state))
6834                                         dtrace_action_panic(ecb);
6835                                 continue;
6836 
6837                         case DTRACEACT_STACK:
6838                                 if (!dtrace_priv_kernel(state))
6839                                         continue;
6840 
6841                                 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6842                                     size / sizeof (pc_t), probe->dtpr_aframes,
6843                                     DTRACE_ANCHORED(probe) ? NULL :
6844                                     (uint32_t *)arg0);
6845 
6846                                 continue;
6847 
6848                         case DTRACEACT_JSTACK:
6849                         case DTRACEACT_USTACK:
6850                                 if (!dtrace_priv_proc(state, &mstate))
6851                                         continue;
6852 
6853                                 /*
6854                                  * See comment in DIF_VAR_PID.
6855                                  */
6856                                 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6857                                     CPU_ON_INTR(CPU)) {
6858                                         int depth = DTRACE_USTACK_NFRAMES(
6859                                             rec->dtrd_arg) + 1;
6860 
6861                                         dtrace_bzero((void *)(tomax + valoffs),
6862                                             DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6863                                             + depth * sizeof (uint64_t));
6864 
6865                                         continue;
6866                                 }
6867 
6868                                 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6869                                     curproc->p_dtrace_helpers != NULL) {
6870                                         /*
6871                                          * This is the slow path -- we have
6872                                          * allocated string space, and we're
6873                                          * getting the stack of a process that
6874                                          * has helpers.  Call into a separate
6875                                          * routine to perform this processing.
6876                                          */
6877                                         dtrace_action_ustack(&mstate, state,
6878                                             (uint64_t *)(tomax + valoffs),
6879                                             rec->dtrd_arg);
6880                                         continue;
6881                                 }
6882 
6883                                 /*
6884                                  * Clear the string space, since there's no
6885                                  * helper to do it for us.
6886                                  */
6887                                 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0) {
6888                                         int depth = DTRACE_USTACK_NFRAMES(
6889                                             rec->dtrd_arg);
6890                                         size_t strsize = DTRACE_USTACK_STRSIZE(
6891                                             rec->dtrd_arg);
6892                                         uint64_t *buf = (uint64_t *)(tomax +
6893                                             valoffs);
6894                                         void *strspace = &buf[depth + 1];
6895 
6896                                         dtrace_bzero(strspace,
6897                                             MIN(depth, strsize));
6898                                 }
6899 
6900                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6901                                 dtrace_getupcstack((uint64_t *)
6902                                     (tomax + valoffs),
6903                                     DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6904                                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6905                                 continue;
6906 
6907                         default:
6908                                 break;
6909                         }
6910 
6911                         dp = act->dta_difo;
6912                         ASSERT(dp != NULL);
6913 
6914                         val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6915 
6916                         if (*flags & CPU_DTRACE_ERROR)
6917                                 continue;
6918 
6919                         switch (act->dta_kind) {
6920                         case DTRACEACT_SPECULATE: {
6921                                 dtrace_rechdr_t *dtrh;
6922 
6923                                 ASSERT(buf == &state->dts_buffer[cpuid]);
6924                                 buf = dtrace_speculation_buffer(state,
6925                                     cpuid, val);
6926 
6927                                 if (buf == NULL) {
6928                                         *flags |= CPU_DTRACE_DROP;
6929                                         continue;
6930                                 }
6931 
6932                                 offs = dtrace_buffer_reserve(buf,
6933                                     ecb->dte_needed, ecb->dte_alignment,
6934                                     state, NULL);
6935 
6936                                 if (offs < 0) {
6937                                         *flags |= CPU_DTRACE_DROP;
6938                                         continue;
6939                                 }
6940 
6941                                 tomax = buf->dtb_tomax;
6942                                 ASSERT(tomax != NULL);
6943 
6944                                 if (ecb->dte_size == 0)
6945                                         continue;
6946 
6947                                 ASSERT3U(ecb->dte_size, >=,
6948                                     sizeof (dtrace_rechdr_t));
6949                                 dtrh = ((void *)(tomax + offs));
6950                                 dtrh->dtrh_epid = ecb->dte_epid;
6951                                 /*
6952                                  * When the speculation is committed, all of
6953                                  * the records in the speculative buffer will
6954                                  * have their timestamps set to the commit
6955                                  * time.  Until then, it is set to a sentinel
6956                                  * value, for debugability.
6957                                  */
6958                                 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6959                                 continue;
6960                         }
6961 
6962                         case DTRACEACT_CHILL:
6963                                 if (dtrace_priv_kernel_destructive(state))
6964                                         dtrace_action_chill(&mstate, val);
6965                                 continue;
6966 
6967                         case DTRACEACT_RAISE:
6968                                 if (dtrace_priv_proc_destructive(state,
6969                                     &mstate))
6970                                         dtrace_action_raise(val);
6971                                 continue;
6972 
6973                         case DTRACEACT_COMMIT:
6974                                 ASSERT(!committed);
6975 
6976                                 /*
6977                                  * We need to commit our buffer state.
6978                                  */
6979                                 if (ecb->dte_size)
6980                                         buf->dtb_offset = offs + ecb->dte_size;
6981                                 buf = &state->dts_buffer[cpuid];
6982                                 dtrace_speculation_commit(state, cpuid, val);
6983                                 committed = 1;
6984                                 continue;
6985 
6986                         case DTRACEACT_DISCARD:
6987                                 dtrace_speculation_discard(state, cpuid, val);
6988                                 continue;
6989 
6990                         case DTRACEACT_DIFEXPR:
6991                         case DTRACEACT_LIBACT:
6992                         case DTRACEACT_PRINTF:
6993                         case DTRACEACT_PRINTA:
6994                         case DTRACEACT_SYSTEM:
6995                         case DTRACEACT_FREOPEN:
6996                         case DTRACEACT_TRACEMEM:
6997                                 break;
6998 
6999                         case DTRACEACT_TRACEMEM_DYNSIZE:
7000                                 tracememsize = val;
7001                                 break;
7002 
7003                         case DTRACEACT_SYM:
7004                         case DTRACEACT_MOD:
7005                                 if (!dtrace_priv_kernel(state))
7006                                         continue;
7007                                 break;
7008 
7009                         case DTRACEACT_USYM:
7010                         case DTRACEACT_UMOD:
7011                         case DTRACEACT_UADDR: {
7012                                 struct pid *pid = curthread->t_procp->p_pidp;
7013 
7014                                 if (!dtrace_priv_proc(state, &mstate))
7015                                         continue;
7016 
7017                                 DTRACE_STORE(uint64_t, tomax,
7018                                     valoffs, (uint64_t)pid->pid_id);
7019                                 DTRACE_STORE(uint64_t, tomax,
7020                                     valoffs + sizeof (uint64_t), val);
7021 
7022                                 continue;
7023                         }
7024 
7025                         case DTRACEACT_EXIT: {
7026                                 /*
7027                                  * For the exit action, we are going to attempt
7028                                  * to atomically set our activity to be
7029                                  * draining.  If this fails (either because
7030                                  * another CPU has beat us to the exit action,
7031                                  * or because our current activity is something
7032                                  * other than ACTIVE or WARMUP), we will
7033                                  * continue.  This assures that the exit action
7034                                  * can be successfully recorded at most once
7035                                  * when we're in the ACTIVE state.  If we're
7036                                  * encountering the exit() action while in
7037                                  * COOLDOWN, however, we want to honor the new
7038                                  * status code.  (We know that we're the only
7039                                  * thread in COOLDOWN, so there is no race.)
7040                                  */
7041                                 void *activity = &state->dts_activity;
7042                                 dtrace_activity_t current = state->dts_activity;
7043 
7044                                 if (current == DTRACE_ACTIVITY_COOLDOWN)
7045                                         break;
7046 
7047                                 if (current != DTRACE_ACTIVITY_WARMUP)
7048                                         current = DTRACE_ACTIVITY_ACTIVE;
7049 
7050                                 if (dtrace_cas32(activity, current,
7051                                     DTRACE_ACTIVITY_DRAINING) != current) {
7052                                         *flags |= CPU_DTRACE_DROP;
7053                                         continue;
7054                                 }
7055 
7056                                 break;
7057                         }
7058 
7059                         default:
7060                                 ASSERT(0);
7061                         }
7062 
7063                         if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
7064                                 uintptr_t end = valoffs + size;
7065 
7066                                 if (tracememsize != 0 &&
7067                                     valoffs + tracememsize < end) {
7068                                         end = valoffs + tracememsize;
7069                                         tracememsize = 0;
7070                                 }
7071 
7072                                 if (!dtrace_vcanload((void *)(uintptr_t)val,
7073                                     &dp->dtdo_rtype, &mstate, vstate))
7074                                         continue;
7075 
7076                                 /*
7077                                  * If this is a string, we're going to only
7078                                  * load until we find the zero byte -- after
7079                                  * which we'll store zero bytes.
7080                                  */
7081                                 if (dp->dtdo_rtype.dtdt_kind ==
7082                                     DIF_TYPE_STRING) {
7083                                         char c = '\0' + 1;
7084                                         int intuple = act->dta_intuple;
7085                                         size_t s;
7086 
7087                                         for (s = 0; s < size; s++) {
7088                                                 if (c != '\0')
7089                                                         c = dtrace_load8(val++);
7090 
7091                                                 DTRACE_STORE(uint8_t, tomax,
7092                                                     valoffs++, c);
7093 
7094                                                 if (c == '\0' && intuple)
7095                                                         break;
7096                                         }
7097 
7098                                         continue;
7099                                 }
7100 
7101                                 while (valoffs < end) {
7102                                         DTRACE_STORE(uint8_t, tomax, valoffs++,
7103                                             dtrace_load8(val++));
7104                                 }
7105 
7106                                 continue;
7107                         }
7108 
7109                         switch (size) {
7110                         case 0:
7111                                 break;
7112 
7113                         case sizeof (uint8_t):
7114                                 DTRACE_STORE(uint8_t, tomax, valoffs, val);
7115                                 break;
7116                         case sizeof (uint16_t):
7117                                 DTRACE_STORE(uint16_t, tomax, valoffs, val);
7118                                 break;
7119                         case sizeof (uint32_t):
7120                                 DTRACE_STORE(uint32_t, tomax, valoffs, val);
7121                                 break;
7122                         case sizeof (uint64_t):
7123                                 DTRACE_STORE(uint64_t, tomax, valoffs, val);
7124                                 break;
7125                         default:
7126                                 /*
7127                                  * Any other size should have been returned by
7128                                  * reference, not by value.
7129                                  */
7130                                 ASSERT(0);
7131                                 break;
7132                         }
7133                 }
7134 
7135                 if (*flags & CPU_DTRACE_DROP)
7136                         continue;
7137 
7138                 if (*flags & CPU_DTRACE_FAULT) {
7139                         int ndx;
7140                         dtrace_action_t *err;
7141 
7142                         buf->dtb_errors++;
7143 
7144                         if (probe->dtpr_id == dtrace_probeid_error) {
7145                                 /*
7146                                  * There's nothing we can do -- we had an
7147                                  * error on the error probe.  We bump an
7148                                  * error counter to at least indicate that
7149                                  * this condition happened.
7150                                  */
7151                                 dtrace_error(&state->dts_dblerrors);
7152                                 continue;
7153                         }
7154 
7155                         if (vtime) {
7156                                 /*
7157                                  * Before recursing on dtrace_probe(), we
7158                                  * need to explicitly clear out our start
7159                                  * time to prevent it from being accumulated
7160                                  * into t_dtrace_vtime.
7161                                  */
7162                                 curthread->t_dtrace_start = 0;
7163                         }
7164 
7165                         /*
7166                          * Iterate over the actions to figure out which action
7167                          * we were processing when we experienced the error.
7168                          * Note that act points _past_ the faulting action; if
7169                          * act is ecb->dte_action, the fault was in the
7170                          * predicate, if it's ecb->dte_action->dta_next it's
7171                          * in action #1, and so on.
7172                          */
7173                         for (err = ecb->dte_action, ndx = 0;
7174                             err != act; err = err->dta_next, ndx++)
7175                                 continue;
7176 
7177                         dtrace_probe_error(state, ecb->dte_epid, ndx,
7178                             (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7179                             mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7180                             cpu_core[cpuid].cpuc_dtrace_illval);
7181 
7182                         continue;
7183                 }
7184 
7185                 if (!committed)
7186                         buf->dtb_offset = offs + ecb->dte_size;
7187         }
7188 
7189         if (vtime)
7190                 curthread->t_dtrace_start = dtrace_gethrtime();
7191 
7192         dtrace_interrupt_enable(cookie);
7193 }
7194 
7195 /*
7196  * DTrace Probe Hashing Functions
7197  *
7198  * The functions in this section (and indeed, the functions in remaining
7199  * sections) are not _called_ from probe context.  (Any exceptions to this are
7200  * marked with a "Note:".)  Rather, they are called from elsewhere in the
7201  * DTrace framework to look-up probes in, add probes to and remove probes from
7202  * the DTrace probe hashes.  (Each probe is hashed by each element of the
7203  * probe tuple -- allowing for fast lookups, regardless of what was
7204  * specified.)
7205  */
7206 static uint_t
7207 dtrace_hash_str(char *p)
7208 {
7209         unsigned int g;
7210         uint_t hval = 0;
7211 
7212         while (*p) {
7213                 hval = (hval << 4) + *p++;
7214                 if ((g = (hval & 0xf0000000)) != 0)
7215                         hval ^= g >> 24;
7216                 hval &= ~g;
7217         }
7218         return (hval);
7219 }
7220 
7221 static dtrace_hash_t *
7222 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7223 {
7224         dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7225 
7226         hash->dth_stroffs = stroffs;
7227         hash->dth_nextoffs = nextoffs;
7228         hash->dth_prevoffs = prevoffs;
7229 
7230         hash->dth_size = 1;
7231         hash->dth_mask = hash->dth_size - 1;
7232 
7233         hash->dth_tab = kmem_zalloc(hash->dth_size *
7234             sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7235 
7236         return (hash);
7237 }
7238 
7239 static void
7240 dtrace_hash_destroy(dtrace_hash_t *hash)
7241 {
7242 #ifdef DEBUG
7243         int i;
7244 
7245         for (i = 0; i < hash->dth_size; i++)
7246                 ASSERT(hash->dth_tab[i] == NULL);
7247 #endif
7248 
7249         kmem_free(hash->dth_tab,
7250             hash->dth_size * sizeof (dtrace_hashbucket_t *));
7251         kmem_free(hash, sizeof (dtrace_hash_t));
7252 }
7253 
7254 static void
7255 dtrace_hash_resize(dtrace_hash_t *hash)
7256 {
7257         int size = hash->dth_size, i, ndx;
7258         int new_size = hash->dth_size << 1;
7259         int new_mask = new_size - 1;
7260         dtrace_hashbucket_t **new_tab, *bucket, *next;
7261 
7262         ASSERT((new_size & new_mask) == 0);
7263 
7264         new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7265 
7266         for (i = 0; i < size; i++) {
7267                 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7268                         dtrace_probe_t *probe = bucket->dthb_chain;
7269 
7270                         ASSERT(probe != NULL);
7271                         ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7272 
7273                         next = bucket->dthb_next;
7274                         bucket->dthb_next = new_tab[ndx];
7275                         new_tab[ndx] = bucket;
7276                 }
7277         }
7278 
7279         kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7280         hash->dth_tab = new_tab;
7281         hash->dth_size = new_size;
7282         hash->dth_mask = new_mask;
7283 }
7284 
7285 static void
7286 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7287 {
7288         int hashval = DTRACE_HASHSTR(hash, new);
7289         int ndx = hashval & hash->dth_mask;
7290         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7291         dtrace_probe_t **nextp, **prevp;
7292 
7293         for (; bucket != NULL; bucket = bucket->dthb_next) {
7294                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7295                         goto add;
7296         }
7297 
7298         if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7299                 dtrace_hash_resize(hash);
7300                 dtrace_hash_add(hash, new);
7301                 return;
7302         }
7303 
7304         bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7305         bucket->dthb_next = hash->dth_tab[ndx];
7306         hash->dth_tab[ndx] = bucket;
7307         hash->dth_nbuckets++;
7308 
7309 add:
7310         nextp = DTRACE_HASHNEXT(hash, new);
7311         ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7312         *nextp = bucket->dthb_chain;
7313 
7314         if (bucket->dthb_chain != NULL) {
7315                 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7316                 ASSERT(*prevp == NULL);
7317                 *prevp = new;
7318         }
7319 
7320         bucket->dthb_chain = new;
7321         bucket->dthb_len++;
7322 }
7323 
7324 static dtrace_probe_t *
7325 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7326 {
7327         int hashval = DTRACE_HASHSTR(hash, template);
7328         int ndx = hashval & hash->dth_mask;
7329         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7330 
7331         for (; bucket != NULL; bucket = bucket->dthb_next) {
7332                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7333                         return (bucket->dthb_chain);
7334         }
7335 
7336         return (NULL);
7337 }
7338 
7339 static int
7340 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7341 {
7342         int hashval = DTRACE_HASHSTR(hash, template);
7343         int ndx = hashval & hash->dth_mask;
7344         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7345 
7346         for (; bucket != NULL; bucket = bucket->dthb_next) {
7347                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7348                         return (bucket->dthb_len);
7349         }
7350 
7351         return (NULL);
7352 }
7353 
7354 static void
7355 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7356 {
7357         int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7358         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7359 
7360         dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7361         dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7362 
7363         /*
7364          * Find the bucket that we're removing this probe from.
7365          */
7366         for (; bucket != NULL; bucket = bucket->dthb_next) {
7367                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7368                         break;
7369         }
7370 
7371         ASSERT(bucket != NULL);
7372 
7373         if (*prevp == NULL) {
7374                 if (*nextp == NULL) {
7375                         /*
7376                          * The removed probe was the only probe on this
7377                          * bucket; we need to remove the bucket.
7378                          */
7379                         dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7380 
7381                         ASSERT(bucket->dthb_chain == probe);
7382                         ASSERT(b != NULL);
7383 
7384                         if (b == bucket) {
7385                                 hash->dth_tab[ndx] = bucket->dthb_next;
7386                         } else {
7387                                 while (b->dthb_next != bucket)
7388                                         b = b->dthb_next;
7389                                 b->dthb_next = bucket->dthb_next;
7390                         }
7391 
7392                         ASSERT(hash->dth_nbuckets > 0);
7393                         hash->dth_nbuckets--;
7394                         kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7395                         return;
7396                 }
7397 
7398                 bucket->dthb_chain = *nextp;
7399         } else {
7400                 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7401         }
7402 
7403         if (*nextp != NULL)
7404                 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7405 }
7406 
7407 /*
7408  * DTrace Utility Functions
7409  *
7410  * These are random utility functions that are _not_ called from probe context.
7411  */
7412 static int
7413 dtrace_badattr(const dtrace_attribute_t *a)
7414 {
7415         return (a->dtat_name > DTRACE_STABILITY_MAX ||
7416             a->dtat_data > DTRACE_STABILITY_MAX ||
7417             a->dtat_class > DTRACE_CLASS_MAX);
7418 }
7419 
7420 /*
7421  * Return a duplicate copy of a string.  If the specified string is NULL,
7422  * this function returns a zero-length string.
7423  */
7424 static char *
7425 dtrace_strdup(const char *str)
7426 {
7427         char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7428 
7429         if (str != NULL)
7430                 (void) strcpy(new, str);
7431 
7432         return (new);
7433 }
7434 
7435 #define DTRACE_ISALPHA(c)       \
7436         (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7437 
7438 static int
7439 dtrace_badname(const char *s)
7440 {
7441         char c;
7442 
7443         if (s == NULL || (c = *s++) == '\0')
7444                 return (0);
7445 
7446         if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7447                 return (1);
7448 
7449         while ((c = *s++) != '\0') {
7450                 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7451                     c != '-' && c != '_' && c != '.' && c != '`')
7452                         return (1);
7453         }
7454 
7455         return (0);
7456 }
7457 
7458 static void
7459 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7460 {
7461         uint32_t priv;
7462 
7463         if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7464                 /*
7465                  * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7466                  */
7467                 priv = DTRACE_PRIV_ALL;
7468         } else {
7469                 *uidp = crgetuid(cr);
7470                 *zoneidp = crgetzonedid(cr);
7471 
7472                 priv = 0;
7473                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7474                         priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7475                 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7476                         priv |= DTRACE_PRIV_USER;
7477                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7478                         priv |= DTRACE_PRIV_PROC;
7479                 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7480                         priv |= DTRACE_PRIV_OWNER;
7481                 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7482                         priv |= DTRACE_PRIV_ZONEOWNER;
7483         }
7484 
7485         *privp = priv;
7486 }
7487 
7488 #ifdef DTRACE_ERRDEBUG
7489 static void
7490 dtrace_errdebug(const char *str)
7491 {
7492         int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
7493         int occupied = 0;
7494 
7495         mutex_enter(&dtrace_errlock);
7496         dtrace_errlast = str;
7497         dtrace_errthread = curthread;
7498 
7499         while (occupied++ < DTRACE_ERRHASHSZ) {
7500                 if (dtrace_errhash[hval].dter_msg == str) {
7501                         dtrace_errhash[hval].dter_count++;
7502                         goto out;
7503                 }
7504 
7505                 if (dtrace_errhash[hval].dter_msg != NULL) {
7506                         hval = (hval + 1) % DTRACE_ERRHASHSZ;
7507                         continue;
7508                 }
7509 
7510                 dtrace_errhash[hval].dter_msg = str;
7511                 dtrace_errhash[hval].dter_count = 1;
7512                 goto out;
7513         }
7514 
7515         panic("dtrace: undersized error hash");
7516 out:
7517         mutex_exit(&dtrace_errlock);
7518 }
7519 #endif
7520 
7521 /*
7522  * DTrace Matching Functions
7523  *
7524  * These functions are used to match groups of probes, given some elements of
7525  * a probe tuple, or some globbed expressions for elements of a probe tuple.
7526  */
7527 static int
7528 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7529     zoneid_t zoneid)
7530 {
7531         if (priv != DTRACE_PRIV_ALL) {
7532                 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7533                 uint32_t match = priv & ppriv;
7534 
7535                 /*
7536                  * No PRIV_DTRACE_* privileges...
7537                  */
7538                 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7539                     DTRACE_PRIV_KERNEL)) == 0)
7540                         return (0);
7541 
7542                 /*
7543                  * No matching bits, but there were bits to match...
7544                  */
7545                 if (match == 0 && ppriv != 0)
7546                         return (0);
7547 
7548                 /*
7549                  * Need to have permissions to the process, but don't...
7550                  */
7551                 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7552                     uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7553                         return (0);
7554                 }
7555 
7556                 /*
7557                  * Need to be in the same zone unless we possess the
7558                  * privilege to examine all zones.
7559                  */
7560                 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7561                     zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7562                         return (0);
7563                 }
7564         }
7565 
7566         return (1);
7567 }
7568 
7569 /*
7570  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7571  * consists of input pattern strings and an ops-vector to evaluate them.
7572  * This function returns >0 for match, 0 for no match, and <0 for error.
7573  */
7574 static int
7575 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7576     uint32_t priv, uid_t uid, zoneid_t zoneid)
7577 {
7578         dtrace_provider_t *pvp = prp->dtpr_provider;
7579         int rv;
7580 
7581         if (pvp->dtpv_defunct)
7582                 return (0);
7583 
7584         if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7585                 return (rv);
7586 
7587         if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7588                 return (rv);
7589 
7590         if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7591                 return (rv);
7592 
7593         if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7594                 return (rv);
7595 
7596         if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7597                 return (0);
7598 
7599         return (rv);
7600 }
7601 
7602 /*
7603  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7604  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
7605  * libc's version, the kernel version only applies to 8-bit ASCII strings.
7606  * In addition, all of the recursion cases except for '*' matching have been
7607  * unwound.  For '*', we still implement recursive evaluation, but a depth
7608  * counter is maintained and matching is aborted if we recurse too deep.
7609  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7610  */
7611 static int
7612 dtrace_match_glob(const char *s, const char *p, int depth)
7613 {
7614         const char *olds;
7615         char s1, c;
7616         int gs;
7617 
7618         if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7619                 return (-1);
7620 
7621         if (s == NULL)
7622                 s = ""; /* treat NULL as empty string */
7623 
7624 top:
7625         olds = s;
7626         s1 = *s++;
7627 
7628         if (p == NULL)
7629                 return (0);
7630 
7631         if ((c = *p++) == '\0')
7632                 return (s1 == '\0');
7633 
7634         switch (c) {
7635         case '[': {
7636                 int ok = 0, notflag = 0;
7637                 char lc = '\0';
7638 
7639                 if (s1 == '\0')
7640                         return (0);
7641 
7642                 if (*p == '!') {
7643                         notflag = 1;
7644                         p++;
7645                 }
7646 
7647                 if ((c = *p++) == '\0')
7648                         return (0);
7649 
7650                 do {
7651                         if (c == '-' && lc != '\0' && *p != ']') {
7652                                 if ((c = *p++) == '\0')
7653                                         return (0);
7654                                 if (c == '\\' && (c = *p++) == '\0')
7655                                         return (0);
7656 
7657                                 if (notflag) {
7658                                         if (s1 < lc || s1 > c)
7659                                                 ok++;
7660                                         else
7661                                                 return (0);
7662                                 } else if (lc <= s1 && s1 <= c)
7663                                         ok++;
7664 
7665                         } else if (c == '\\' && (c = *p++) == '\0')
7666                                 return (0);
7667 
7668                         lc = c; /* save left-hand 'c' for next iteration */
7669 
7670                         if (notflag) {
7671                                 if (s1 != c)
7672                                         ok++;
7673                                 else
7674                                         return (0);
7675                         } else if (s1 == c)
7676                                 ok++;
7677 
7678                         if ((c = *p++) == '\0')
7679                                 return (0);
7680 
7681                 } while (c != ']');
7682 
7683                 if (ok)
7684                         goto top;
7685 
7686                 return (0);
7687         }
7688 
7689         case '\\':
7690                 if ((c = *p++) == '\0')
7691                         return (0);
7692                 /*FALLTHRU*/
7693 
7694         default:
7695                 if (c != s1)
7696                         return (0);
7697                 /*FALLTHRU*/
7698 
7699         case '?':
7700                 if (s1 != '\0')
7701                         goto top;
7702                 return (0);
7703 
7704         case '*':
7705                 while (*p == '*')
7706                         p++; /* consecutive *'s are identical to a single one */
7707 
7708                 if (*p == '\0')
7709                         return (1);
7710 
7711                 for (s = olds; *s != '\0'; s++) {
7712                         if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7713                                 return (gs);
7714                 }
7715 
7716                 return (0);
7717         }
7718 }
7719 
7720 /*ARGSUSED*/
7721 static int
7722 dtrace_match_string(const char *s, const char *p, int depth)
7723 {
7724         return (s != NULL && strcmp(s, p) == 0);
7725 }
7726 
7727 /*ARGSUSED*/
7728 static int
7729 dtrace_match_nul(const char *s, const char *p, int depth)
7730 {
7731         return (1); /* always match the empty pattern */
7732 }
7733 
7734 /*ARGSUSED*/
7735 static int
7736 dtrace_match_nonzero(const char *s, const char *p, int depth)
7737 {
7738         return (s != NULL && s[0] != '\0');
7739 }
7740 
7741 static int
7742 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7743     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7744 {
7745         dtrace_probe_t template, *probe;
7746         dtrace_hash_t *hash = NULL;
7747         int len, rc, best = INT_MAX, nmatched = 0;
7748         dtrace_id_t i;
7749 
7750         ASSERT(MUTEX_HELD(&dtrace_lock));
7751 
7752         /*
7753          * If the probe ID is specified in the key, just lookup by ID and
7754          * invoke the match callback once if a matching probe is found.
7755          */
7756         if (pkp->dtpk_id != DTRACE_IDNONE) {
7757                 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7758                     dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7759                         if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
7760                                 return (DTRACE_MATCH_FAIL);
7761                         nmatched++;
7762                 }
7763                 return (nmatched);
7764         }
7765 
7766         template.dtpr_mod = (char *)pkp->dtpk_mod;
7767         template.dtpr_func = (char *)pkp->dtpk_func;
7768         template.dtpr_name = (char *)pkp->dtpk_name;
7769 
7770         /*
7771          * We want to find the most distinct of the module name, function
7772          * name, and name.  So for each one that is not a glob pattern or
7773          * empty string, we perform a lookup in the corresponding hash and
7774          * use the hash table with the fewest collisions to do our search.
7775          */
7776         if (pkp->dtpk_mmatch == &dtrace_match_string &&
7777             (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7778                 best = len;
7779                 hash = dtrace_bymod;
7780         }
7781 
7782         if (pkp->dtpk_fmatch == &dtrace_match_string &&
7783             (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7784                 best = len;
7785                 hash = dtrace_byfunc;
7786         }
7787 
7788         if (pkp->dtpk_nmatch == &dtrace_match_string &&
7789             (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7790                 best = len;
7791                 hash = dtrace_byname;
7792         }
7793 
7794         /*
7795          * If we did not select a hash table, iterate over every probe and
7796          * invoke our callback for each one that matches our input probe key.
7797          */
7798         if (hash == NULL) {
7799                 for (i = 0; i < dtrace_nprobes; i++) {
7800                         if ((probe = dtrace_probes[i]) == NULL ||
7801                             dtrace_match_probe(probe, pkp, priv, uid,
7802                             zoneid) <= 0)
7803                                 continue;
7804 
7805                         nmatched++;
7806 
7807                         if ((rc = (*matched)(probe, arg)) !=
7808                             DTRACE_MATCH_NEXT) {
7809                                 if (rc == DTRACE_MATCH_FAIL)
7810                                         return (DTRACE_MATCH_FAIL);
7811                                 break;
7812                         }
7813                 }
7814 
7815                 return (nmatched);
7816         }
7817 
7818         /*
7819          * If we selected a hash table, iterate over each probe of the same key
7820          * name and invoke the callback for every probe that matches the other
7821          * attributes of our input probe key.
7822          */
7823         for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7824             probe = *(DTRACE_HASHNEXT(hash, probe))) {
7825 
7826                 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7827                         continue;
7828 
7829                 nmatched++;
7830 
7831                 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7832                         if (rc == DTRACE_MATCH_FAIL)
7833                                 return (DTRACE_MATCH_FAIL);
7834                         break;
7835                 }
7836         }
7837 
7838         return (nmatched);
7839 }
7840 
7841 /*
7842  * Return the function pointer dtrace_probecmp() should use to compare the
7843  * specified pattern with a string.  For NULL or empty patterns, we select
7844  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
7845  * For non-empty non-glob strings, we use dtrace_match_string().
7846  */
7847 static dtrace_probekey_f *
7848 dtrace_probekey_func(const char *p)
7849 {
7850         char c;
7851 
7852         if (p == NULL || *p == '\0')
7853                 return (&dtrace_match_nul);
7854 
7855         while ((c = *p++) != '\0') {
7856                 if (c == '[' || c == '?' || c == '*' || c == '\\')
7857                         return (&dtrace_match_glob);
7858         }
7859 
7860         return (&dtrace_match_string);
7861 }
7862 
7863 /*
7864  * Build a probe comparison key for use with dtrace_match_probe() from the
7865  * given probe description.  By convention, a null key only matches anchored
7866  * probes: if each field is the empty string, reset dtpk_fmatch to
7867  * dtrace_match_nonzero().
7868  */
7869 static void
7870 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7871 {
7872         pkp->dtpk_prov = pdp->dtpd_provider;
7873         pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7874 
7875         pkp->dtpk_mod = pdp->dtpd_mod;
7876         pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7877 
7878         pkp->dtpk_func = pdp->dtpd_func;
7879         pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7880 
7881         pkp->dtpk_name = pdp->dtpd_name;
7882         pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7883 
7884         pkp->dtpk_id = pdp->dtpd_id;
7885 
7886         if (pkp->dtpk_id == DTRACE_IDNONE &&
7887             pkp->dtpk_pmatch == &dtrace_match_nul &&
7888             pkp->dtpk_mmatch == &dtrace_match_nul &&
7889             pkp->dtpk_fmatch == &dtrace_match_nul &&
7890             pkp->dtpk_nmatch == &dtrace_match_nul)
7891                 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7892 }
7893 
7894 /*
7895  * DTrace Provider-to-Framework API Functions
7896  *
7897  * These functions implement much of the Provider-to-Framework API, as
7898  * described in <sys/dtrace.h>.  The parts of the API not in this section are
7899  * the functions in the API for probe management (found below), and
7900  * dtrace_probe() itself (found above).
7901  */
7902 
7903 /*
7904  * Register the calling provider with the DTrace framework.  This should
7905  * generally be called by DTrace providers in their attach(9E) entry point.
7906  */
7907 int
7908 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7909     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7910 {
7911         dtrace_provider_t *provider;
7912 
7913         if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7914                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7915                     "arguments", name ? name : "<NULL>");
7916                 return (EINVAL);
7917         }
7918 
7919         if (name[0] == '\0' || dtrace_badname(name)) {
7920                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7921                     "provider name", name);
7922                 return (EINVAL);
7923         }
7924 
7925         if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7926             pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7927             pops->dtps_destroy == NULL ||
7928             ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7929                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7930                     "provider ops", name);
7931                 return (EINVAL);
7932         }
7933 
7934         if (dtrace_badattr(&pap->dtpa_provider) ||
7935             dtrace_badattr(&pap->dtpa_mod) ||
7936             dtrace_badattr(&pap->dtpa_func) ||
7937             dtrace_badattr(&pap->dtpa_name) ||
7938             dtrace_badattr(&pap->dtpa_args)) {
7939                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7940                     "provider attributes", name);
7941                 return (EINVAL);
7942         }
7943 
7944         if (priv & ~DTRACE_PRIV_ALL) {
7945                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7946                     "privilege attributes", name);
7947                 return (EINVAL);
7948         }
7949 
7950         if ((priv & DTRACE_PRIV_KERNEL) &&
7951             (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7952             pops->dtps_mode == NULL) {
7953                 cmn_err(CE_WARN, "failed to register provider '%s': need "
7954                     "dtps_mode() op for given privilege attributes", name);
7955                 return (EINVAL);
7956         }
7957 
7958         provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7959         provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7960         (void) strcpy(provider->dtpv_name, name);
7961 
7962         provider->dtpv_attr = *pap;
7963         provider->dtpv_priv.dtpp_flags = priv;
7964         if (cr != NULL) {
7965                 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7966                 provider->dtpv_priv.dtpp_zoneid = crgetzonedid(cr);
7967         }
7968         provider->dtpv_pops = *pops;
7969 
7970         if (pops->dtps_provide == NULL) {
7971                 ASSERT(pops->dtps_provide_module != NULL);
7972                 provider->dtpv_pops.dtps_provide =
7973                     (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
7974         }
7975 
7976         if (pops->dtps_provide_module == NULL) {
7977                 ASSERT(pops->dtps_provide != NULL);
7978                 provider->dtpv_pops.dtps_provide_module =
7979                     (void (*)(void *, struct modctl *))dtrace_nullop;
7980         }
7981 
7982         if (pops->dtps_suspend == NULL) {
7983                 ASSERT(pops->dtps_resume == NULL);
7984                 provider->dtpv_pops.dtps_suspend =
7985                     (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7986                 provider->dtpv_pops.dtps_resume =
7987                     (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7988         }
7989 
7990         provider->dtpv_arg = arg;
7991         *idp = (dtrace_provider_id_t)provider;
7992 
7993         if (pops == &dtrace_provider_ops) {
7994                 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7995                 ASSERT(MUTEX_HELD(&dtrace_lock));
7996                 ASSERT(dtrace_anon.dta_enabling == NULL);
7997 
7998                 /*
7999                  * We make sure that the DTrace provider is at the head of
8000                  * the provider chain.
8001                  */
8002                 provider->dtpv_next = dtrace_provider;
8003                 dtrace_provider = provider;
8004                 return (0);
8005         }
8006 
8007         mutex_enter(&dtrace_provider_lock);
8008         mutex_enter(&dtrace_lock);
8009 
8010         /*
8011          * If there is at least one provider registered, we'll add this
8012          * provider after the first provider.
8013          */
8014         if (dtrace_provider != NULL) {
8015                 provider->dtpv_next = dtrace_provider->dtpv_next;
8016                 dtrace_provider->dtpv_next = provider;
8017         } else {
8018                 dtrace_provider = provider;
8019         }
8020 
8021         if (dtrace_retained != NULL) {
8022                 dtrace_enabling_provide(provider);
8023 
8024                 /*
8025                  * Now we need to call dtrace_enabling_matchall() -- which
8026                  * will acquire cpu_lock and dtrace_lock.  We therefore need
8027                  * to drop all of our locks before calling into it...
8028                  */
8029                 mutex_exit(&dtrace_lock);
8030                 mutex_exit(&dtrace_provider_lock);
8031                 dtrace_enabling_matchall();
8032 
8033                 return (0);
8034         }
8035 
8036         mutex_exit(&dtrace_lock);
8037         mutex_exit(&dtrace_provider_lock);
8038 
8039         return (0);
8040 }
8041 
8042 /*
8043  * Unregister the specified provider from the DTrace framework.  This should
8044  * generally be called by DTrace providers in their detach(9E) entry point.
8045  */
8046 int
8047 dtrace_unregister(dtrace_provider_id_t id)
8048 {
8049         dtrace_provider_t *old = (dtrace_provider_t *)id;
8050         dtrace_provider_t *prev = NULL;
8051         int i, self = 0, noreap = 0;
8052         dtrace_probe_t *probe, *first = NULL;
8053 
8054         if (old->dtpv_pops.dtps_enable ==
8055             (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
8056                 /*
8057                  * If DTrace itself is the provider, we're called with locks
8058                  * already held.
8059                  */
8060                 ASSERT(old == dtrace_provider);
8061                 ASSERT(dtrace_devi != NULL);
8062                 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8063                 ASSERT(MUTEX_HELD(&dtrace_lock));
8064                 self = 1;
8065 
8066                 if (dtrace_provider->dtpv_next != NULL) {
8067                         /*
8068                          * There's another provider here; return failure.
8069                          */
8070                         return (EBUSY);
8071                 }
8072         } else {
8073                 mutex_enter(&dtrace_provider_lock);
8074                 mutex_enter(&mod_lock);
8075                 mutex_enter(&dtrace_lock);
8076         }
8077 
8078         /*
8079          * If anyone has /dev/dtrace open, or if there are anonymous enabled
8080          * probes, we refuse to let providers slither away, unless this
8081          * provider has already been explicitly invalidated.
8082          */
8083         if (!old->dtpv_defunct &&
8084             (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8085             dtrace_anon.dta_state->dts_necbs > 0))) {
8086                 if (!self) {
8087                         mutex_exit(&dtrace_lock);
8088                         mutex_exit(&mod_lock);
8089                         mutex_exit(&dtrace_provider_lock);
8090                 }
8091                 return (EBUSY);
8092         }
8093 
8094         /*
8095          * Attempt to destroy the probes associated with this provider.
8096          */
8097         for (i = 0; i < dtrace_nprobes; i++) {
8098                 if ((probe = dtrace_probes[i]) == NULL)
8099                         continue;
8100 
8101                 if (probe->dtpr_provider != old)
8102                         continue;
8103 
8104                 if (probe->dtpr_ecb == NULL)
8105                         continue;
8106 
8107                 /*
8108                  * If we are trying to unregister a defunct provider, and the
8109                  * provider was made defunct within the interval dictated by
8110                  * dtrace_unregister_defunct_reap, we'll (asynchronously)
8111                  * attempt to reap our enablings.  To denote that the provider
8112                  * should reattempt to unregister itself at some point in the
8113                  * future, we will return a differentiable error code (EAGAIN
8114                  * instead of EBUSY) in this case.
8115                  */
8116                 if (dtrace_gethrtime() - old->dtpv_defunct >
8117                     dtrace_unregister_defunct_reap)
8118                         noreap = 1;
8119 
8120                 if (!self) {
8121                         mutex_exit(&dtrace_lock);
8122                         mutex_exit(&mod_lock);
8123                         mutex_exit(&dtrace_provider_lock);
8124                 }
8125 
8126                 if (noreap)
8127                         return (EBUSY);
8128 
8129                 (void) taskq_dispatch(dtrace_taskq,
8130                     (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8131 
8132                 return (EAGAIN);
8133         }
8134 
8135         /*
8136          * All of the probes for this provider are disabled; we can safely
8137          * remove all of them from their hash chains and from the probe array.
8138          */
8139         for (i = 0; i < dtrace_nprobes; i++) {
8140                 if ((probe = dtrace_probes[i]) == NULL)
8141                         continue;
8142 
8143                 if (probe->dtpr_provider != old)
8144                         continue;
8145 
8146                 dtrace_probes[i] = NULL;
8147 
8148                 dtrace_hash_remove(dtrace_bymod, probe);
8149                 dtrace_hash_remove(dtrace_byfunc, probe);
8150                 dtrace_hash_remove(dtrace_byname, probe);
8151 
8152                 if (first == NULL) {
8153                         first = probe;
8154                         probe->dtpr_nextmod = NULL;
8155                 } else {
8156                         probe->dtpr_nextmod = first;
8157                         first = probe;
8158                 }
8159         }
8160 
8161         /*
8162          * The provider's probes have been removed from the hash chains and
8163          * from the probe array.  Now issue a dtrace_sync() to be sure that
8164          * everyone has cleared out from any probe array processing.
8165          */
8166         dtrace_sync();
8167 
8168         for (probe = first; probe != NULL; probe = first) {
8169                 first = probe->dtpr_nextmod;
8170 
8171                 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8172                     probe->dtpr_arg);
8173                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8174                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8175                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8176                 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8177                 kmem_free(probe, sizeof (dtrace_probe_t));
8178         }
8179 
8180         if ((prev = dtrace_provider) == old) {
8181                 ASSERT(self || dtrace_devi == NULL);
8182                 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8183                 dtrace_provider = old->dtpv_next;
8184         } else {
8185                 while (prev != NULL && prev->dtpv_next != old)
8186                         prev = prev->dtpv_next;
8187 
8188                 if (prev == NULL) {
8189                         panic("attempt to unregister non-existent "
8190                             "dtrace provider %p\n", (void *)id);
8191                 }
8192 
8193                 prev->dtpv_next = old->dtpv_next;
8194         }
8195 
8196         if (!self) {
8197                 mutex_exit(&dtrace_lock);
8198                 mutex_exit(&mod_lock);
8199                 mutex_exit(&dtrace_provider_lock);
8200         }
8201 
8202         kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8203         kmem_free(old, sizeof (dtrace_provider_t));
8204 
8205         return (0);
8206 }
8207 
8208 /*
8209  * Invalidate the specified provider.  All subsequent probe lookups for the
8210  * specified provider will fail, but its probes will not be removed.
8211  */
8212 void
8213 dtrace_invalidate(dtrace_provider_id_t id)
8214 {
8215         dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8216 
8217         ASSERT(pvp->dtpv_pops.dtps_enable !=
8218             (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8219 
8220         mutex_enter(&dtrace_provider_lock);
8221         mutex_enter(&dtrace_lock);
8222 
8223         pvp->dtpv_defunct = dtrace_gethrtime();
8224 
8225         mutex_exit(&dtrace_lock);
8226         mutex_exit(&dtrace_provider_lock);
8227 }
8228 
8229 /*
8230  * Indicate whether or not DTrace has attached.
8231  */
8232 int
8233 dtrace_attached(void)
8234 {
8235         /*
8236          * dtrace_provider will be non-NULL iff the DTrace driver has
8237          * attached.  (It's non-NULL because DTrace is always itself a
8238          * provider.)
8239          */
8240         return (dtrace_provider != NULL);
8241 }
8242 
8243 /*
8244  * Remove all the unenabled probes for the given provider.  This function is
8245  * not unlike dtrace_unregister(), except that it doesn't remove the provider
8246  * -- just as many of its associated probes as it can.
8247  */
8248 int
8249 dtrace_condense(dtrace_provider_id_t id)
8250 {
8251         dtrace_provider_t *prov = (dtrace_provider_t *)id;
8252         int i;
8253         dtrace_probe_t *probe;
8254 
8255         /*
8256          * Make sure this isn't the dtrace provider itself.
8257          */
8258         ASSERT(prov->dtpv_pops.dtps_enable !=
8259             (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8260 
8261         mutex_enter(&dtrace_provider_lock);
8262         mutex_enter(&dtrace_lock);
8263 
8264         /*
8265          * Attempt to destroy the probes associated with this provider.
8266          */
8267         for (i = 0; i < dtrace_nprobes; i++) {
8268                 if ((probe = dtrace_probes[i]) == NULL)
8269                         continue;
8270 
8271                 if (probe->dtpr_provider != prov)
8272                         continue;
8273 
8274                 if (probe->dtpr_ecb != NULL)
8275                         continue;
8276 
8277                 dtrace_probes[i] = NULL;
8278 
8279                 dtrace_hash_remove(dtrace_bymod, probe);
8280                 dtrace_hash_remove(dtrace_byfunc, probe);
8281                 dtrace_hash_remove(dtrace_byname, probe);
8282 
8283                 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8284                     probe->dtpr_arg);
8285                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8286                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8287                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8288                 kmem_free(probe, sizeof (dtrace_probe_t));
8289                 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8290         }
8291 
8292         mutex_exit(&dtrace_lock);
8293         mutex_exit(&dtrace_provider_lock);
8294 
8295         return (0);
8296 }
8297 
8298 /*
8299  * DTrace Probe Management Functions
8300  *
8301  * The functions in this section perform the DTrace probe management,
8302  * including functions to create probes, look-up probes, and call into the
8303  * providers to request that probes be provided.  Some of these functions are
8304  * in the Provider-to-Framework API; these functions can be identified by the
8305  * fact that they are not declared "static".
8306  */
8307 
8308 /*
8309  * Create a probe with the specified module name, function name, and name.
8310  */
8311 dtrace_id_t
8312 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8313     const char *func, const char *name, int aframes, void *arg)
8314 {
8315         dtrace_probe_t *probe, **probes;
8316         dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8317         dtrace_id_t id;
8318 
8319         if (provider == dtrace_provider) {
8320                 ASSERT(MUTEX_HELD(&dtrace_lock));
8321         } else {
8322                 mutex_enter(&dtrace_lock);
8323         }
8324 
8325         id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8326             VM_BESTFIT | VM_SLEEP);
8327         probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8328 
8329         probe->dtpr_id = id;
8330         probe->dtpr_gen = dtrace_probegen++;
8331         probe->dtpr_mod = dtrace_strdup(mod);
8332         probe->dtpr_func = dtrace_strdup(func);
8333         probe->dtpr_name = dtrace_strdup(name);
8334         probe->dtpr_arg = arg;
8335         probe->dtpr_aframes = aframes;
8336         probe->dtpr_provider = provider;
8337 
8338         dtrace_hash_add(dtrace_bymod, probe);
8339         dtrace_hash_add(dtrace_byfunc, probe);
8340         dtrace_hash_add(dtrace_byname, probe);
8341 
8342         if (id - 1 >= dtrace_nprobes) {
8343                 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8344                 size_t nsize = osize << 1;
8345 
8346                 if (nsize == 0) {
8347                         ASSERT(osize == 0);
8348                         ASSERT(dtrace_probes == NULL);
8349                         nsize = sizeof (dtrace_probe_t *);
8350                 }
8351 
8352                 probes = kmem_zalloc(nsize, KM_SLEEP);
8353 
8354                 if (dtrace_probes == NULL) {
8355                         ASSERT(osize == 0);
8356                         dtrace_probes = probes;
8357                         dtrace_nprobes = 1;
8358                 } else {
8359                         dtrace_probe_t **oprobes = dtrace_probes;
8360 
8361                         bcopy(oprobes, probes, osize);
8362                         dtrace_membar_producer();
8363                         dtrace_probes = probes;
8364 
8365                         dtrace_sync();
8366 
8367                         /*
8368                          * All CPUs are now seeing the new probes array; we can
8369                          * safely free the old array.
8370                          */
8371                         kmem_free(oprobes, osize);
8372                         dtrace_nprobes <<= 1;
8373                 }
8374 
8375                 ASSERT(id - 1 < dtrace_nprobes);
8376         }
8377 
8378         ASSERT(dtrace_probes[id - 1] == NULL);
8379         dtrace_probes[id - 1] = probe;
8380 
8381         if (provider != dtrace_provider)
8382                 mutex_exit(&dtrace_lock);
8383 
8384         return (id);
8385 }
8386 
8387 static dtrace_probe_t *
8388 dtrace_probe_lookup_id(dtrace_id_t id)
8389 {
8390         ASSERT(MUTEX_HELD(&dtrace_lock));
8391 
8392         if (id == 0 || id > dtrace_nprobes)
8393                 return (NULL);
8394 
8395         return (dtrace_probes[id - 1]);
8396 }
8397 
8398 static int
8399 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8400 {
8401         *((dtrace_id_t *)arg) = probe->dtpr_id;
8402 
8403         return (DTRACE_MATCH_DONE);
8404 }
8405 
8406 /*
8407  * Look up a probe based on provider and one or more of module name, function
8408  * name and probe name.
8409  */
8410 dtrace_id_t
8411 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
8412     const char *func, const char *name)
8413 {
8414         dtrace_probekey_t pkey;
8415         dtrace_id_t id;
8416         int match;
8417 
8418         pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8419         pkey.dtpk_pmatch = &dtrace_match_string;
8420         pkey.dtpk_mod = mod;
8421         pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8422         pkey.dtpk_func = func;
8423         pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8424         pkey.dtpk_name = name;
8425         pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8426         pkey.dtpk_id = DTRACE_IDNONE;
8427 
8428         mutex_enter(&dtrace_lock);
8429         match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8430             dtrace_probe_lookup_match, &id);
8431         mutex_exit(&dtrace_lock);
8432 
8433         ASSERT(match == 1 || match == 0);
8434         return (match ? id : 0);
8435 }
8436 
8437 /*
8438  * Returns the probe argument associated with the specified probe.
8439  */
8440 void *
8441 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8442 {
8443         dtrace_probe_t *probe;
8444         void *rval = NULL;
8445 
8446         mutex_enter(&dtrace_lock);
8447 
8448         if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8449             probe->dtpr_provider == (dtrace_provider_t *)id)
8450                 rval = probe->dtpr_arg;
8451 
8452         mutex_exit(&dtrace_lock);
8453 
8454         return (rval);
8455 }
8456 
8457 /*
8458  * Copy a probe into a probe description.
8459  */
8460 static void
8461 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8462 {
8463         bzero(pdp, sizeof (dtrace_probedesc_t));
8464         pdp->dtpd_id = prp->dtpr_id;
8465 
8466         (void) strncpy(pdp->dtpd_provider,
8467             prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8468 
8469         (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8470         (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8471         (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8472 }
8473 
8474 /*
8475  * Called to indicate that a probe -- or probes -- should be provided by a
8476  * specfied provider.  If the specified description is NULL, the provider will
8477  * be told to provide all of its probes.  (This is done whenever a new
8478  * consumer comes along, or whenever a retained enabling is to be matched.) If
8479  * the specified description is non-NULL, the provider is given the
8480  * opportunity to dynamically provide the specified probe, allowing providers
8481  * to support the creation of probes on-the-fly.  (So-called _autocreated_
8482  * probes.)  If the provider is NULL, the operations will be applied to all
8483  * providers; if the provider is non-NULL the operations will only be applied
8484  * to the specified provider.  The dtrace_provider_lock must be held, and the
8485  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8486  * will need to grab the dtrace_lock when it reenters the framework through
8487  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8488  */
8489 static void
8490 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8491 {
8492         struct modctl *ctl;
8493         int all = 0;
8494 
8495         ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8496 
8497         if (prv == NULL) {
8498                 all = 1;
8499                 prv = dtrace_provider;
8500         }
8501 
8502         do {
8503                 /*
8504                  * First, call the blanket provide operation.
8505                  */
8506                 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8507 
8508                 /*
8509                  * Now call the per-module provide operation.  We will grab
8510                  * mod_lock to prevent the list from being modified.  Note
8511                  * that this also prevents the mod_busy bits from changing.
8512                  * (mod_busy can only be changed with mod_lock held.)
8513                  */
8514                 mutex_enter(&mod_lock);
8515 
8516                 ctl = &modules;
8517                 do {
8518                         if (ctl->mod_busy || ctl->mod_mp == NULL)
8519                                 continue;
8520 
8521                         prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8522 
8523                 } while ((ctl = ctl->mod_next) != &modules);
8524 
8525                 mutex_exit(&mod_lock);
8526         } while (all && (prv = prv->dtpv_next) != NULL);
8527 }
8528 
8529 /*
8530  * Iterate over each probe, and call the Framework-to-Provider API function
8531  * denoted by offs.
8532  */
8533 static void
8534 dtrace_probe_foreach(uintptr_t offs)
8535 {
8536         dtrace_provider_t *prov;
8537         void (*func)(void *, dtrace_id_t, void *);
8538         dtrace_probe_t *probe;
8539         dtrace_icookie_t cookie;
8540         int i;
8541 
8542         /*
8543          * We disable interrupts to walk through the probe array.  This is
8544          * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8545          * won't see stale data.
8546          */
8547         cookie = dtrace_interrupt_disable();
8548 
8549         for (i = 0; i < dtrace_nprobes; i++) {
8550                 if ((probe = dtrace_probes[i]) == NULL)
8551                         continue;
8552 
8553                 if (probe->dtpr_ecb == NULL) {
8554                         /*
8555                          * This probe isn't enabled -- don't call the function.
8556                          */
8557                         continue;
8558                 }
8559 
8560                 prov = probe->dtpr_provider;
8561                 func = *((void(**)(void *, dtrace_id_t, void *))
8562                     ((uintptr_t)&prov->dtpv_pops + offs));
8563 
8564                 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8565         }
8566 
8567         dtrace_interrupt_enable(cookie);
8568 }
8569 
8570 static int
8571 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8572 {
8573         dtrace_probekey_t pkey;
8574         uint32_t priv;
8575         uid_t uid;
8576         zoneid_t zoneid;
8577         dtrace_state_t *state = enab->dten_vstate->dtvs_state;
8578 
8579         ASSERT(MUTEX_HELD(&dtrace_lock));
8580         dtrace_ecb_create_cache = NULL;
8581 
8582         if (desc == NULL) {
8583                 /*
8584                  * If we're passed a NULL description, we're being asked to
8585                  * create an ECB with a NULL probe.
8586                  */
8587                 (void) dtrace_ecb_create_enable(NULL, enab);
8588                 return (0);
8589         }
8590 
8591         dtrace_probekey(desc, &pkey);
8592         dtrace_cred2priv(state->dts_cred.dcr_cred, &priv, &uid, &zoneid);
8593 
8594         if ((priv & DTRACE_PRIV_ZONEOWNER) &&
8595             state->dts_options[DTRACEOPT_ZONE] != DTRACEOPT_UNSET) {
8596                 /*
8597                  * If we have the privilege of instrumenting all zones but we
8598                  * have been told to instrument but one, we will spoof this up
8599                  * depriving ourselves of DTRACE_PRIV_ZONEOWNER for purposes
8600                  * of dtrace_match().  (Note that DTRACEOPT_ZONE is not for
8601                  * security but rather for performance: it allows the global
8602                  * zone to instrument USDT probes in a local zone without
8603                  * requiring all zones to be instrumented.)
8604                  */
8605                 priv &= ~DTRACE_PRIV_ZONEOWNER;
8606                 zoneid = state->dts_options[DTRACEOPT_ZONE];
8607         }
8608 
8609         return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8610             enab));
8611 }
8612 
8613 /*
8614  * DTrace Helper Provider Functions
8615  */
8616 static void
8617 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8618 {
8619         attr->dtat_name = DOF_ATTR_NAME(dofattr);
8620         attr->dtat_data = DOF_ATTR_DATA(dofattr);
8621         attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8622 }
8623 
8624 static void
8625 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8626     const dof_provider_t *dofprov, char *strtab)
8627 {
8628         hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8629         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8630             dofprov->dofpv_provattr);
8631         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8632             dofprov->dofpv_modattr);
8633         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8634             dofprov->dofpv_funcattr);
8635         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8636             dofprov->dofpv_nameattr);
8637         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8638             dofprov->dofpv_argsattr);
8639 }
8640 
8641 static void
8642 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8643 {
8644         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8645         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8646         dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8647         dof_provider_t *provider;
8648         dof_probe_t *probe;
8649         uint32_t *off, *enoff;
8650         uint8_t *arg;
8651         char *strtab;
8652         uint_t i, nprobes;
8653         dtrace_helper_provdesc_t dhpv;
8654         dtrace_helper_probedesc_t dhpb;
8655         dtrace_meta_t *meta = dtrace_meta_pid;
8656         dtrace_mops_t *mops = &meta->dtm_mops;
8657         void *parg;
8658 
8659         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8660         str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8661             provider->dofpv_strtab * dof->dofh_secsize);
8662         prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8663             provider->dofpv_probes * dof->dofh_secsize);
8664         arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8665             provider->dofpv_prargs * dof->dofh_secsize);
8666         off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8667             provider->dofpv_proffs * dof->dofh_secsize);
8668 
8669         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8670         off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8671         arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8672         enoff = NULL;
8673 
8674         /*
8675          * See dtrace_helper_provider_validate().
8676          */
8677         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8678             provider->dofpv_prenoffs != DOF_SECT_NONE) {
8679                 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8680                     provider->dofpv_prenoffs * dof->dofh_secsize);
8681                 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8682         }
8683 
8684         nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8685 
8686         /*
8687          * Create the provider.
8688          */
8689         dtrace_dofprov2hprov(&dhpv, provider, strtab);
8690 
8691         if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8692                 return;
8693 
8694         meta->dtm_count++;
8695 
8696         /*
8697          * Create the probes.
8698          */
8699         for (i = 0; i < nprobes; i++) {
8700                 probe = (dof_probe_t *)(uintptr_t)(daddr +
8701                     prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8702 
8703                 dhpb.dthpb_mod = dhp->dofhp_mod;
8704                 dhpb.dthpb_func = strtab + probe->dofpr_func;
8705                 dhpb.dthpb_name = strtab + probe->dofpr_name;
8706                 dhpb.dthpb_base = probe->dofpr_addr;
8707                 dhpb.dthpb_offs = off + probe->dofpr_offidx;
8708                 dhpb.dthpb_noffs = probe->dofpr_noffs;
8709                 if (enoff != NULL) {
8710                         dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8711                         dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8712                 } else {
8713                         dhpb.dthpb_enoffs = NULL;
8714                         dhpb.dthpb_nenoffs = 0;
8715                 }
8716                 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8717                 dhpb.dthpb_nargc = probe->dofpr_nargc;
8718                 dhpb.dthpb_xargc = probe->dofpr_xargc;
8719                 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8720                 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8721 
8722                 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8723         }
8724 }
8725 
8726 static void
8727 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8728 {
8729         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8730         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8731         int i;
8732 
8733         ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8734 
8735         for (i = 0; i < dof->dofh_secnum; i++) {
8736                 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8737                     dof->dofh_secoff + i * dof->dofh_secsize);
8738 
8739                 if (sec->dofs_type != DOF_SECT_PROVIDER)
8740                         continue;
8741 
8742                 dtrace_helper_provide_one(dhp, sec, pid);
8743         }
8744 
8745         /*
8746          * We may have just created probes, so we must now rematch against
8747          * any retained enablings.  Note that this call will acquire both
8748          * cpu_lock and dtrace_lock; the fact that we are holding
8749          * dtrace_meta_lock now is what defines the ordering with respect to
8750          * these three locks.
8751          */
8752         dtrace_enabling_matchall();
8753 }
8754 
8755 static void
8756 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8757 {
8758         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8759         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8760         dof_sec_t *str_sec;
8761         dof_provider_t *provider;
8762         char *strtab;
8763         dtrace_helper_provdesc_t dhpv;
8764         dtrace_meta_t *meta = dtrace_meta_pid;
8765         dtrace_mops_t *mops = &meta->dtm_mops;
8766 
8767         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8768         str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8769             provider->dofpv_strtab * dof->dofh_secsize);
8770 
8771         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8772 
8773         /*
8774          * Create the provider.
8775          */
8776         dtrace_dofprov2hprov(&dhpv, provider, strtab);
8777 
8778         mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8779 
8780         meta->dtm_count--;
8781 }
8782 
8783 static void
8784 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8785 {
8786         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8787         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8788         int i;
8789 
8790         ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8791 
8792         for (i = 0; i < dof->dofh_secnum; i++) {
8793                 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8794                     dof->dofh_secoff + i * dof->dofh_secsize);
8795 
8796                 if (sec->dofs_type != DOF_SECT_PROVIDER)
8797                         continue;
8798 
8799                 dtrace_helper_provider_remove_one(dhp, sec, pid);
8800         }
8801 }
8802 
8803 /*
8804  * DTrace Meta Provider-to-Framework API Functions
8805  *
8806  * These functions implement the Meta Provider-to-Framework API, as described
8807  * in <sys/dtrace.h>.
8808  */
8809 int
8810 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8811     dtrace_meta_provider_id_t *idp)
8812 {
8813         dtrace_meta_t *meta;
8814         dtrace_helpers_t *help, *next;
8815         int i;
8816 
8817         *idp = DTRACE_METAPROVNONE;
8818 
8819         /*
8820          * We strictly don't need the name, but we hold onto it for
8821          * debuggability. All hail error queues!
8822          */
8823         if (name == NULL) {
8824                 cmn_err(CE_WARN, "failed to register meta-provider: "
8825                     "invalid name");
8826                 return (EINVAL);
8827         }
8828 
8829         if (mops == NULL ||
8830             mops->dtms_create_probe == NULL ||
8831             mops->dtms_provide_pid == NULL ||
8832             mops->dtms_remove_pid == NULL) {
8833                 cmn_err(CE_WARN, "failed to register meta-register %s: "
8834                     "invalid ops", name);
8835                 return (EINVAL);
8836         }
8837 
8838         meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8839         meta->dtm_mops = *mops;
8840         meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8841         (void) strcpy(meta->dtm_name, name);
8842         meta->dtm_arg = arg;
8843 
8844         mutex_enter(&dtrace_meta_lock);
8845         mutex_enter(&dtrace_lock);
8846 
8847         if (dtrace_meta_pid != NULL) {
8848                 mutex_exit(&dtrace_lock);
8849                 mutex_exit(&dtrace_meta_lock);
8850                 cmn_err(CE_WARN, "failed to register meta-register %s: "
8851                     "user-land meta-provider exists", name);
8852                 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8853                 kmem_free(meta, sizeof (dtrace_meta_t));
8854                 return (EINVAL);
8855         }
8856 
8857         dtrace_meta_pid = meta;
8858         *idp = (dtrace_meta_provider_id_t)meta;
8859 
8860         /*
8861          * If there are providers and probes ready to go, pass them
8862          * off to the new meta provider now.
8863          */
8864 
8865         help = dtrace_deferred_pid;
8866         dtrace_deferred_pid = NULL;
8867 
8868         mutex_exit(&dtrace_lock);
8869 
8870         while (help != NULL) {
8871                 for (i = 0; i < help->dthps_nprovs; i++) {
8872                         dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8873                             help->dthps_pid);
8874                 }
8875 
8876                 next = help->dthps_next;
8877                 help->dthps_next = NULL;
8878                 help->dthps_prev = NULL;
8879                 help->dthps_deferred = 0;
8880                 help = next;
8881         }
8882 
8883         mutex_exit(&dtrace_meta_lock);
8884 
8885         return (0);
8886 }
8887 
8888 int
8889 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8890 {
8891         dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8892 
8893         mutex_enter(&dtrace_meta_lock);
8894         mutex_enter(&dtrace_lock);
8895 
8896         if (old == dtrace_meta_pid) {
8897                 pp = &dtrace_meta_pid;
8898         } else {
8899                 panic("attempt to unregister non-existent "
8900                     "dtrace meta-provider %p\n", (void *)old);
8901         }
8902 
8903         if (old->dtm_count != 0) {
8904                 mutex_exit(&dtrace_lock);
8905                 mutex_exit(&dtrace_meta_lock);
8906                 return (EBUSY);
8907         }
8908 
8909         *pp = NULL;
8910 
8911         mutex_exit(&dtrace_lock);
8912         mutex_exit(&dtrace_meta_lock);
8913 
8914         kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8915         kmem_free(old, sizeof (dtrace_meta_t));
8916 
8917         return (0);
8918 }
8919 
8920 
8921 /*
8922  * DTrace DIF Object Functions
8923  */
8924 static int
8925 dtrace_difo_err(uint_t pc, const char *format, ...)
8926 {
8927         if (dtrace_err_verbose) {
8928                 va_list alist;
8929 
8930                 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8931                 va_start(alist, format);
8932                 (void) vuprintf(format, alist);
8933                 va_end(alist);
8934         }
8935 
8936 #ifdef DTRACE_ERRDEBUG
8937         dtrace_errdebug(format);
8938 #endif
8939         return (1);
8940 }
8941 
8942 /*
8943  * Validate a DTrace DIF object by checking the IR instructions.  The following
8944  * rules are currently enforced by dtrace_difo_validate():
8945  *
8946  * 1. Each instruction must have a valid opcode
8947  * 2. Each register, string, variable, or subroutine reference must be valid
8948  * 3. No instruction can modify register %r0 (must be zero)
8949  * 4. All instruction reserved bits must be set to zero
8950  * 5. The last instruction must be a "ret" instruction
8951  * 6. All branch targets must reference a valid instruction _after_ the branch
8952  */
8953 static int
8954 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8955     cred_t *cr)
8956 {
8957         int err = 0, i;
8958         int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8959         int kcheckload;
8960         uint_t pc;
8961 
8962         kcheckload = cr == NULL ||
8963             (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8964 
8965         dp->dtdo_destructive = 0;
8966 
8967         for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8968                 dif_instr_t instr = dp->dtdo_buf[pc];
8969 
8970                 uint_t r1 = DIF_INSTR_R1(instr);
8971                 uint_t r2 = DIF_INSTR_R2(instr);
8972                 uint_t rd = DIF_INSTR_RD(instr);
8973                 uint_t rs = DIF_INSTR_RS(instr);
8974                 uint_t label = DIF_INSTR_LABEL(instr);
8975                 uint_t v = DIF_INSTR_VAR(instr);
8976                 uint_t subr = DIF_INSTR_SUBR(instr);
8977                 uint_t type = DIF_INSTR_TYPE(instr);
8978                 uint_t op = DIF_INSTR_OP(instr);
8979 
8980                 switch (op) {
8981                 case DIF_OP_OR:
8982                 case DIF_OP_XOR:
8983                 case DIF_OP_AND:
8984                 case DIF_OP_SLL:
8985                 case DIF_OP_SRL:
8986                 case DIF_OP_SRA:
8987                 case DIF_OP_SUB:
8988                 case DIF_OP_ADD:
8989                 case DIF_OP_MUL:
8990                 case DIF_OP_SDIV:
8991                 case DIF_OP_UDIV:
8992                 case DIF_OP_SREM:
8993                 case DIF_OP_UREM:
8994                 case DIF_OP_COPYS:
8995                         if (r1 >= nregs)
8996                                 err += efunc(pc, "invalid register %u\n", r1);
8997                         if (r2 >= nregs)
8998                                 err += efunc(pc, "invalid register %u\n", r2);
8999                         if (rd >= nregs)
9000                                 err += efunc(pc, "invalid register %u\n", rd);
9001                         if (rd == 0)
9002                                 err += efunc(pc, "cannot write to %r0\n");
9003                         break;
9004                 case DIF_OP_NOT:
9005                 case DIF_OP_MOV:
9006                 case DIF_OP_ALLOCS:
9007                         if (r1 >= nregs)
9008                                 err += efunc(pc, "invalid register %u\n", r1);
9009                         if (r2 != 0)
9010                                 err += efunc(pc, "non-zero reserved bits\n");
9011                         if (rd >= nregs)
9012                                 err += efunc(pc, "invalid register %u\n", rd);
9013                         if (rd == 0)
9014                                 err += efunc(pc, "cannot write to %r0\n");
9015                         break;
9016                 case DIF_OP_LDSB:
9017                 case DIF_OP_LDSH:
9018                 case DIF_OP_LDSW:
9019                 case DIF_OP_LDUB:
9020                 case DIF_OP_LDUH:
9021                 case DIF_OP_LDUW:
9022                 case DIF_OP_LDX:
9023                         if (r1 >= nregs)
9024                                 err += efunc(pc, "invalid register %u\n", r1);
9025                         if (r2 != 0)
9026                                 err += efunc(pc, "non-zero reserved bits\n");
9027                         if (rd >= nregs)
9028                                 err += efunc(pc, "invalid register %u\n", rd);
9029                         if (rd == 0)
9030                                 err += efunc(pc, "cannot write to %r0\n");
9031                         if (kcheckload)
9032                                 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9033                                     DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9034                         break;
9035                 case DIF_OP_RLDSB:
9036                 case DIF_OP_RLDSH:
9037                 case DIF_OP_RLDSW:
9038                 case DIF_OP_RLDUB:
9039                 case DIF_OP_RLDUH:
9040                 case DIF_OP_RLDUW:
9041                 case DIF_OP_RLDX:
9042                         if (r1 >= nregs)
9043                                 err += efunc(pc, "invalid register %u\n", r1);
9044                         if (r2 != 0)
9045                                 err += efunc(pc, "non-zero reserved bits\n");
9046                         if (rd >= nregs)
9047                                 err += efunc(pc, "invalid register %u\n", rd);
9048                         if (rd == 0)
9049                                 err += efunc(pc, "cannot write to %r0\n");
9050                         break;
9051                 case DIF_OP_ULDSB:
9052                 case DIF_OP_ULDSH:
9053                 case DIF_OP_ULDSW:
9054                 case DIF_OP_ULDUB:
9055                 case DIF_OP_ULDUH:
9056                 case DIF_OP_ULDUW:
9057                 case DIF_OP_ULDX:
9058                         if (r1 >= nregs)
9059                                 err += efunc(pc, "invalid register %u\n", r1);
9060                         if (r2 != 0)
9061                                 err += efunc(pc, "non-zero reserved bits\n");
9062                         if (rd >= nregs)
9063                                 err += efunc(pc, "invalid register %u\n", rd);
9064                         if (rd == 0)
9065                                 err += efunc(pc, "cannot write to %r0\n");
9066                         break;
9067                 case DIF_OP_STB:
9068                 case DIF_OP_STH:
9069                 case DIF_OP_STW:
9070                 case DIF_OP_STX:
9071                         if (r1 >= nregs)
9072                                 err += efunc(pc, "invalid register %u\n", r1);
9073                         if (r2 != 0)
9074                                 err += efunc(pc, "non-zero reserved bits\n");
9075                         if (rd >= nregs)
9076                                 err += efunc(pc, "invalid register %u\n", rd);
9077                         if (rd == 0)
9078                                 err += efunc(pc, "cannot write to 0 address\n");
9079                         break;
9080                 case DIF_OP_CMP:
9081                 case DIF_OP_SCMP:
9082                         if (r1 >= nregs)
9083                                 err += efunc(pc, "invalid register %u\n", r1);
9084                         if (r2 >= nregs)
9085                                 err += efunc(pc, "invalid register %u\n", r2);
9086                         if (rd != 0)
9087                                 err += efunc(pc, "non-zero reserved bits\n");
9088                         break;
9089                 case DIF_OP_TST:
9090                         if (r1 >= nregs)
9091                                 err += efunc(pc, "invalid register %u\n", r1);
9092                         if (r2 != 0 || rd != 0)
9093                                 err += efunc(pc, "non-zero reserved bits\n");
9094                         break;
9095                 case DIF_OP_BA:
9096                 case DIF_OP_BE:
9097                 case DIF_OP_BNE:
9098                 case DIF_OP_BG:
9099                 case DIF_OP_BGU:
9100                 case DIF_OP_BGE:
9101                 case DIF_OP_BGEU:
9102                 case DIF_OP_BL:
9103                 case DIF_OP_BLU:
9104                 case DIF_OP_BLE:
9105                 case DIF_OP_BLEU:
9106                         if (label >= dp->dtdo_len) {
9107                                 err += efunc(pc, "invalid branch target %u\n",
9108                                     label);
9109                         }
9110                         if (label <= pc) {
9111                                 err += efunc(pc, "backward branch to %u\n",
9112                                     label);
9113                         }
9114                         break;
9115                 case DIF_OP_RET:
9116                         if (r1 != 0 || r2 != 0)
9117                                 err += efunc(pc, "non-zero reserved bits\n");
9118                         if (rd >= nregs)
9119                                 err += efunc(pc, "invalid register %u\n", rd);
9120                         break;
9121                 case DIF_OP_NOP:
9122                 case DIF_OP_POPTS:
9123                 case DIF_OP_FLUSHTS:
9124                         if (r1 != 0 || r2 != 0 || rd != 0)
9125                                 err += efunc(pc, "non-zero reserved bits\n");
9126                         break;
9127                 case DIF_OP_SETX:
9128                         if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9129                                 err += efunc(pc, "invalid integer ref %u\n",
9130                                     DIF_INSTR_INTEGER(instr));
9131                         }
9132                         if (rd >= nregs)
9133                                 err += efunc(pc, "invalid register %u\n", rd);
9134                         if (rd == 0)
9135                                 err += efunc(pc, "cannot write to %r0\n");
9136                         break;
9137                 case DIF_OP_SETS:
9138                         if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9139                                 err += efunc(pc, "invalid string ref %u\n",
9140                                     DIF_INSTR_STRING(instr));
9141                         }
9142                         if (rd >= nregs)
9143                                 err += efunc(pc, "invalid register %u\n", rd);
9144                         if (rd == 0)
9145                                 err += efunc(pc, "cannot write to %r0\n");
9146                         break;
9147                 case DIF_OP_LDGA:
9148                 case DIF_OP_LDTA:
9149                         if (r1 > DIF_VAR_ARRAY_MAX)
9150                                 err += efunc(pc, "invalid array %u\n", r1);
9151                         if (r2 >= nregs)
9152                                 err += efunc(pc, "invalid register %u\n", r2);
9153                         if (rd >= nregs)
9154                                 err += efunc(pc, "invalid register %u\n", rd);
9155                         if (rd == 0)
9156                                 err += efunc(pc, "cannot write to %r0\n");
9157                         break;
9158                 case DIF_OP_LDGS:
9159                 case DIF_OP_LDTS:
9160                 case DIF_OP_LDLS:
9161                 case DIF_OP_LDGAA:
9162                 case DIF_OP_LDTAA:
9163                         if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9164                                 err += efunc(pc, "invalid variable %u\n", v);
9165                         if (rd >= nregs)
9166                                 err += efunc(pc, "invalid register %u\n", rd);
9167                         if (rd == 0)
9168                                 err += efunc(pc, "cannot write to %r0\n");
9169                         break;
9170                 case DIF_OP_STGS:
9171                 case DIF_OP_STTS:
9172                 case DIF_OP_STLS:
9173                 case DIF_OP_STGAA:
9174                 case DIF_OP_STTAA:
9175                         if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9176                                 err += efunc(pc, "invalid variable %u\n", v);
9177                         if (rs >= nregs)
9178                                 err += efunc(pc, "invalid register %u\n", rd);
9179                         break;
9180                 case DIF_OP_CALL:
9181                         if (subr > DIF_SUBR_MAX)
9182                                 err += efunc(pc, "invalid subr %u\n", subr);
9183                         if (rd >= nregs)
9184                                 err += efunc(pc, "invalid register %u\n", rd);
9185                         if (rd == 0)
9186                                 err += efunc(pc, "cannot write to %r0\n");
9187 
9188                         if (subr == DIF_SUBR_COPYOUT ||
9189                             subr == DIF_SUBR_COPYOUTSTR) {
9190                                 dp->dtdo_destructive = 1;
9191                         }
9192 
9193                         if (subr == DIF_SUBR_GETF) {
9194                                 /*
9195                                  * If we have a getf() we need to record that
9196                                  * in our state.  Note that our state can be
9197                                  * NULL if this is a helper -- but in that
9198                                  * case, the call to getf() is itself illegal,
9199                                  * and will be caught (slightly later) when
9200                                  * the helper is validated.
9201                                  */
9202                                 if (vstate->dtvs_state != NULL)
9203                                         vstate->dtvs_state->dts_getf++;
9204                         }
9205 
9206                         break;
9207                 case DIF_OP_PUSHTR:
9208                         if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9209                                 err += efunc(pc, "invalid ref type %u\n", type);
9210                         if (r2 >= nregs)
9211                                 err += efunc(pc, "invalid register %u\n", r2);
9212                         if (rs >= nregs)
9213                                 err += efunc(pc, "invalid register %u\n", rs);
9214                         break;
9215                 case DIF_OP_PUSHTV:
9216                         if (type != DIF_TYPE_CTF)
9217                                 err += efunc(pc, "invalid val type %u\n", type);
9218                         if (r2 >= nregs)
9219                                 err += efunc(pc, "invalid register %u\n", r2);
9220                         if (rs >= nregs)
9221                                 err += efunc(pc, "invalid register %u\n", rs);
9222                         break;
9223                 default:
9224                         err += efunc(pc, "invalid opcode %u\n",
9225                             DIF_INSTR_OP(instr));
9226                 }
9227         }
9228 
9229         if (dp->dtdo_len != 0 &&
9230             DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9231                 err += efunc(dp->dtdo_len - 1,
9232                     "expected 'ret' as last DIF instruction\n");
9233         }
9234 
9235         if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
9236                 /*
9237                  * If we're not returning by reference, the size must be either
9238                  * 0 or the size of one of the base types.
9239                  */
9240                 switch (dp->dtdo_rtype.dtdt_size) {
9241                 case 0:
9242                 case sizeof (uint8_t):
9243                 case sizeof (uint16_t):
9244                 case sizeof (uint32_t):
9245                 case sizeof (uint64_t):
9246                         break;
9247 
9248                 default:
9249                         err += efunc(dp->dtdo_len - 1, "bad return size\n");
9250                 }
9251         }
9252 
9253         for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9254                 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9255                 dtrace_diftype_t *vt, *et;
9256                 uint_t id, ndx;
9257 
9258                 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9259                     v->dtdv_scope != DIFV_SCOPE_THREAD &&
9260                     v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9261                         err += efunc(i, "unrecognized variable scope %d\n",
9262                             v->dtdv_scope);
9263                         break;
9264                 }
9265 
9266                 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9267                     v->dtdv_kind != DIFV_KIND_SCALAR) {
9268                         err += efunc(i, "unrecognized variable type %d\n",
9269                             v->dtdv_kind);
9270                         break;
9271                 }
9272 
9273                 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9274                         err += efunc(i, "%d exceeds variable id limit\n", id);
9275                         break;
9276                 }
9277 
9278                 if (id < DIF_VAR_OTHER_UBASE)
9279                         continue;
9280 
9281                 /*
9282                  * For user-defined variables, we need to check that this
9283                  * definition is identical to any previous definition that we
9284                  * encountered.
9285                  */
9286                 ndx = id - DIF_VAR_OTHER_UBASE;
9287 
9288                 switch (v->dtdv_scope) {
9289                 case DIFV_SCOPE_GLOBAL:
9290                         if (ndx < vstate->dtvs_nglobals) {
9291                                 dtrace_statvar_t *svar;
9292 
9293                                 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9294                                         existing = &svar->dtsv_var;
9295                         }
9296 
9297                         break;
9298 
9299                 case DIFV_SCOPE_THREAD:
9300                         if (ndx < vstate->dtvs_ntlocals)
9301                                 existing = &vstate->dtvs_tlocals[ndx];
9302                         break;
9303 
9304                 case DIFV_SCOPE_LOCAL:
9305                         if (ndx < vstate->dtvs_nlocals) {
9306                                 dtrace_statvar_t *svar;
9307 
9308                                 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9309                                         existing = &svar->dtsv_var;
9310                         }
9311 
9312                         break;
9313                 }
9314 
9315                 vt = &v->dtdv_type;
9316 
9317                 if (vt->dtdt_flags & DIF_TF_BYREF) {
9318                         if (vt->dtdt_size == 0) {
9319                                 err += efunc(i, "zero-sized variable\n");
9320                                 break;
9321                         }
9322 
9323                         if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
9324                             vt->dtdt_size > dtrace_global_maxsize) {
9325                                 err += efunc(i, "oversized by-ref global\n");
9326                                 break;
9327                         }
9328                 }
9329 
9330                 if (existing == NULL || existing->dtdv_id == 0)
9331                         continue;
9332 
9333                 ASSERT(existing->dtdv_id == v->dtdv_id);
9334                 ASSERT(existing->dtdv_scope == v->dtdv_scope);
9335 
9336                 if (existing->dtdv_kind != v->dtdv_kind)
9337                         err += efunc(i, "%d changed variable kind\n", id);
9338 
9339                 et = &existing->dtdv_type;
9340 
9341                 if (vt->dtdt_flags != et->dtdt_flags) {
9342                         err += efunc(i, "%d changed variable type flags\n", id);
9343                         break;
9344                 }
9345 
9346                 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9347                         err += efunc(i, "%d changed variable type size\n", id);
9348                         break;
9349                 }
9350         }
9351 
9352         return (err);
9353 }
9354 
9355 /*
9356  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
9357  * are much more constrained than normal DIFOs.  Specifically, they may
9358  * not:
9359  *
9360  * 1. Make calls to subroutines other than copyin(), copyinstr() or
9361  *    miscellaneous string routines
9362  * 2. Access DTrace variables other than the args[] array, and the
9363  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9364  * 3. Have thread-local variables.
9365  * 4. Have dynamic variables.
9366  */
9367 static int
9368 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9369 {
9370         int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9371         int err = 0;
9372         uint_t pc;
9373 
9374         for (pc = 0; pc < dp->dtdo_len; pc++) {
9375                 dif_instr_t instr = dp->dtdo_buf[pc];
9376 
9377                 uint_t v = DIF_INSTR_VAR(instr);
9378                 uint_t subr = DIF_INSTR_SUBR(instr);
9379                 uint_t op = DIF_INSTR_OP(instr);
9380 
9381                 switch (op) {
9382                 case DIF_OP_OR:
9383                 case DIF_OP_XOR:
9384                 case DIF_OP_AND:
9385                 case DIF_OP_SLL:
9386                 case DIF_OP_SRL:
9387                 case DIF_OP_SRA:
9388                 case DIF_OP_SUB:
9389                 case DIF_OP_ADD:
9390                 case DIF_OP_MUL:
9391                 case DIF_OP_SDIV:
9392                 case DIF_OP_UDIV:
9393                 case DIF_OP_SREM:
9394                 case DIF_OP_UREM:
9395                 case DIF_OP_COPYS:
9396                 case DIF_OP_NOT:
9397                 case DIF_OP_MOV:
9398                 case DIF_OP_RLDSB:
9399                 case DIF_OP_RLDSH:
9400                 case DIF_OP_RLDSW:
9401                 case DIF_OP_RLDUB:
9402                 case DIF_OP_RLDUH:
9403                 case DIF_OP_RLDUW:
9404                 case DIF_OP_RLDX:
9405                 case DIF_OP_ULDSB:
9406                 case DIF_OP_ULDSH:
9407                 case DIF_OP_ULDSW:
9408                 case DIF_OP_ULDUB:
9409                 case DIF_OP_ULDUH:
9410                 case DIF_OP_ULDUW:
9411                 case DIF_OP_ULDX:
9412                 case DIF_OP_STB:
9413                 case DIF_OP_STH:
9414                 case DIF_OP_STW:
9415                 case DIF_OP_STX:
9416                 case DIF_OP_ALLOCS:
9417                 case DIF_OP_CMP:
9418                 case DIF_OP_SCMP:
9419                 case DIF_OP_TST:
9420                 case DIF_OP_BA:
9421                 case DIF_OP_BE:
9422                 case DIF_OP_BNE:
9423                 case DIF_OP_BG:
9424                 case DIF_OP_BGU:
9425                 case DIF_OP_BGE:
9426                 case DIF_OP_BGEU:
9427                 case DIF_OP_BL:
9428                 case DIF_OP_BLU:
9429                 case DIF_OP_BLE:
9430                 case DIF_OP_BLEU:
9431                 case DIF_OP_RET:
9432                 case DIF_OP_NOP:
9433                 case DIF_OP_POPTS:
9434                 case DIF_OP_FLUSHTS:
9435                 case DIF_OP_SETX:
9436                 case DIF_OP_SETS:
9437                 case DIF_OP_LDGA:
9438                 case DIF_OP_LDLS:
9439                 case DIF_OP_STGS:
9440                 case DIF_OP_STLS:
9441                 case DIF_OP_PUSHTR:
9442                 case DIF_OP_PUSHTV:
9443                         break;
9444 
9445                 case DIF_OP_LDGS:
9446                         if (v >= DIF_VAR_OTHER_UBASE)
9447                                 break;
9448 
9449                         if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9450                                 break;
9451 
9452                         if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9453                             v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9454                             v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9455                             v == DIF_VAR_UID || v == DIF_VAR_GID)
9456                                 break;
9457 
9458                         err += efunc(pc, "illegal variable %u\n", v);
9459                         break;
9460 
9461                 case DIF_OP_LDTA:
9462                 case DIF_OP_LDTS:
9463                 case DIF_OP_LDGAA:
9464                 case DIF_OP_LDTAA:
9465                         err += efunc(pc, "illegal dynamic variable load\n");
9466                         break;
9467 
9468                 case DIF_OP_STTS:
9469                 case DIF_OP_STGAA:
9470                 case DIF_OP_STTAA:
9471                         err += efunc(pc, "illegal dynamic variable store\n");
9472                         break;
9473 
9474                 case DIF_OP_CALL:
9475                         if (subr == DIF_SUBR_ALLOCA ||
9476                             subr == DIF_SUBR_BCOPY ||
9477                             subr == DIF_SUBR_COPYIN ||
9478                             subr == DIF_SUBR_COPYINTO ||
9479                             subr == DIF_SUBR_COPYINSTR ||
9480                             subr == DIF_SUBR_INDEX ||
9481                             subr == DIF_SUBR_INET_NTOA ||
9482                             subr == DIF_SUBR_INET_NTOA6 ||
9483                             subr == DIF_SUBR_INET_NTOP ||
9484                             subr == DIF_SUBR_LLTOSTR ||
9485                             subr == DIF_SUBR_STRTOLL ||
9486                             subr == DIF_SUBR_RINDEX ||
9487                             subr == DIF_SUBR_STRCHR ||
9488                             subr == DIF_SUBR_STRJOIN ||
9489                             subr == DIF_SUBR_STRRCHR ||
9490                             subr == DIF_SUBR_STRSTR ||
9491                             subr == DIF_SUBR_HTONS ||
9492                             subr == DIF_SUBR_HTONL ||
9493                             subr == DIF_SUBR_HTONLL ||
9494                             subr == DIF_SUBR_NTOHS ||
9495                             subr == DIF_SUBR_NTOHL ||
9496                             subr == DIF_SUBR_NTOHLL)
9497                                 break;
9498 
9499                         err += efunc(pc, "invalid subr %u\n", subr);
9500                         break;
9501 
9502                 default:
9503                         err += efunc(pc, "invalid opcode %u\n",
9504                             DIF_INSTR_OP(instr));
9505                 }
9506         }
9507 
9508         return (err);
9509 }
9510 
9511 /*
9512  * Returns 1 if the expression in the DIF object can be cached on a per-thread
9513  * basis; 0 if not.
9514  */
9515 static int
9516 dtrace_difo_cacheable(dtrace_difo_t *dp)
9517 {
9518         int i;
9519 
9520         if (dp == NULL)
9521                 return (0);
9522 
9523         for (i = 0; i < dp->dtdo_varlen; i++) {
9524                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9525 
9526                 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9527                         continue;
9528 
9529                 switch (v->dtdv_id) {
9530                 case DIF_VAR_CURTHREAD:
9531                 case DIF_VAR_PID:
9532                 case DIF_VAR_TID:
9533                 case DIF_VAR_EXECNAME:
9534                 case DIF_VAR_ZONENAME:
9535                         break;
9536 
9537                 default:
9538                         return (0);
9539                 }
9540         }
9541 
9542         /*
9543          * This DIF object may be cacheable.  Now we need to look for any
9544          * array loading instructions, any memory loading instructions, or
9545          * any stores to thread-local variables.
9546          */
9547         for (i = 0; i < dp->dtdo_len; i++) {
9548                 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9549 
9550                 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9551                     (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9552                     (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9553                     op == DIF_OP_LDGA || op == DIF_OP_STTS)
9554                         return (0);
9555         }
9556 
9557         return (1);
9558 }
9559 
9560 static void
9561 dtrace_difo_hold(dtrace_difo_t *dp)
9562 {
9563         int i;
9564 
9565         ASSERT(MUTEX_HELD(&dtrace_lock));
9566 
9567         dp->dtdo_refcnt++;
9568         ASSERT(dp->dtdo_refcnt != 0);
9569 
9570         /*
9571          * We need to check this DIF object for references to the variable
9572          * DIF_VAR_VTIMESTAMP.
9573          */
9574         for (i = 0; i < dp->dtdo_varlen; i++) {
9575                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9576 
9577                 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9578                         continue;
9579 
9580                 if (dtrace_vtime_references++ == 0)
9581                         dtrace_vtime_enable();
9582         }
9583 }
9584 
9585 /*
9586  * This routine calculates the dynamic variable chunksize for a given DIF
9587  * object.  The calculation is not fool-proof, and can probably be tricked by
9588  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
9589  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9590  * if a dynamic variable size exceeds the chunksize.
9591  */
9592 static void
9593 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9594 {
9595         uint64_t sval;
9596         dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9597         const dif_instr_t *text = dp->dtdo_buf;
9598         uint_t pc, srd = 0;
9599         uint_t ttop = 0;
9600         size_t size, ksize;
9601         uint_t id, i;
9602 
9603         for (pc = 0; pc < dp->dtdo_len; pc++) {
9604                 dif_instr_t instr = text[pc];
9605                 uint_t op = DIF_INSTR_OP(instr);
9606                 uint_t rd = DIF_INSTR_RD(instr);
9607                 uint_t r1 = DIF_INSTR_R1(instr);
9608                 uint_t nkeys = 0;
9609                 uchar_t scope;
9610 
9611                 dtrace_key_t *key = tupregs;
9612 
9613                 switch (op) {
9614                 case DIF_OP_SETX:
9615                         sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9616                         srd = rd;
9617                         continue;
9618 
9619                 case DIF_OP_STTS:
9620                         key = &tupregs[DIF_DTR_NREGS];
9621                         key[0].dttk_size = 0;
9622                         key[1].dttk_size = 0;
9623                         nkeys = 2;
9624                         scope = DIFV_SCOPE_THREAD;
9625                         break;
9626 
9627                 case DIF_OP_STGAA:
9628                 case DIF_OP_STTAA:
9629                         nkeys = ttop;
9630 
9631                         if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9632                                 key[nkeys++].dttk_size = 0;
9633 
9634                         key[nkeys++].dttk_size = 0;
9635 
9636                         if (op == DIF_OP_STTAA) {
9637                                 scope = DIFV_SCOPE_THREAD;
9638                         } else {
9639                                 scope = DIFV_SCOPE_GLOBAL;
9640                         }
9641 
9642                         break;
9643 
9644                 case DIF_OP_PUSHTR:
9645                         if (ttop == DIF_DTR_NREGS)
9646                                 return;
9647 
9648                         if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9649                                 /*
9650                                  * If the register for the size of the "pushtr"
9651                                  * is %r0 (or the value is 0) and the type is
9652                                  * a string, we'll use the system-wide default
9653                                  * string size.
9654                                  */
9655                                 tupregs[ttop++].dttk_size =
9656                                     dtrace_strsize_default;
9657                         } else {
9658                                 if (srd == 0)
9659                                         return;
9660 
9661                                 tupregs[ttop++].dttk_size = sval;
9662                         }
9663 
9664                         break;
9665 
9666                 case DIF_OP_PUSHTV:
9667                         if (ttop == DIF_DTR_NREGS)
9668                                 return;
9669 
9670                         tupregs[ttop++].dttk_size = 0;
9671                         break;
9672 
9673                 case DIF_OP_FLUSHTS:
9674                         ttop = 0;
9675                         break;
9676 
9677                 case DIF_OP_POPTS:
9678                         if (ttop != 0)
9679                                 ttop--;
9680                         break;
9681                 }
9682 
9683                 sval = 0;
9684                 srd = 0;
9685 
9686                 if (nkeys == 0)
9687                         continue;
9688 
9689                 /*
9690                  * We have a dynamic variable allocation; calculate its size.
9691                  */
9692                 for (ksize = 0, i = 0; i < nkeys; i++)
9693                         ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9694 
9695                 size = sizeof (dtrace_dynvar_t);
9696                 size += sizeof (dtrace_key_t) * (nkeys - 1);
9697                 size += ksize;
9698 
9699                 /*
9700                  * Now we need to determine the size of the stored data.
9701                  */
9702                 id = DIF_INSTR_VAR(instr);
9703 
9704                 for (i = 0; i < dp->dtdo_varlen; i++) {
9705                         dtrace_difv_t *v = &dp->dtdo_vartab[i];
9706 
9707                         if (v->dtdv_id == id && v->dtdv_scope == scope) {
9708                                 size += v->dtdv_type.dtdt_size;
9709                                 break;
9710                         }
9711                 }
9712 
9713                 if (i == dp->dtdo_varlen)
9714                         return;
9715 
9716                 /*
9717                  * We have the size.  If this is larger than the chunk size
9718                  * for our dynamic variable state, reset the chunk size.
9719                  */
9720                 size = P2ROUNDUP(size, sizeof (uint64_t));
9721 
9722                 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9723                         vstate->dtvs_dynvars.dtds_chunksize = size;
9724         }
9725 }
9726 
9727 static void
9728 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9729 {
9730         int i, oldsvars, osz, nsz, otlocals, ntlocals;
9731         uint_t id;
9732 
9733         ASSERT(MUTEX_HELD(&dtrace_lock));
9734         ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9735 
9736         for (i = 0; i < dp->dtdo_varlen; i++) {
9737                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9738                 dtrace_statvar_t *svar, ***svarp;
9739                 size_t dsize = 0;
9740                 uint8_t scope = v->dtdv_scope;
9741                 int *np;
9742 
9743                 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9744                         continue;
9745 
9746                 id -= DIF_VAR_OTHER_UBASE;
9747 
9748                 switch (scope) {
9749                 case DIFV_SCOPE_THREAD:
9750                         while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9751                                 dtrace_difv_t *tlocals;
9752 
9753                                 if ((ntlocals = (otlocals << 1)) == 0)
9754                                         ntlocals = 1;
9755 
9756                                 osz = otlocals * sizeof (dtrace_difv_t);
9757                                 nsz = ntlocals * sizeof (dtrace_difv_t);
9758 
9759                                 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9760 
9761                                 if (osz != 0) {
9762                                         bcopy(vstate->dtvs_tlocals,
9763                                             tlocals, osz);
9764                                         kmem_free(vstate->dtvs_tlocals, osz);
9765                                 }
9766 
9767                                 vstate->dtvs_tlocals = tlocals;
9768                                 vstate->dtvs_ntlocals = ntlocals;
9769                         }
9770 
9771                         vstate->dtvs_tlocals[id] = *v;
9772                         continue;
9773 
9774                 case DIFV_SCOPE_LOCAL:
9775                         np = &vstate->dtvs_nlocals;
9776                         svarp = &vstate->dtvs_locals;
9777 
9778                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9779                                 dsize = NCPU * (v->dtdv_type.dtdt_size +
9780                                     sizeof (uint64_t));
9781                         else
9782                                 dsize = NCPU * sizeof (uint64_t);
9783 
9784                         break;
9785 
9786                 case DIFV_SCOPE_GLOBAL:
9787                         np = &vstate->dtvs_nglobals;
9788                         svarp = &vstate->dtvs_globals;
9789 
9790                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9791                                 dsize = v->dtdv_type.dtdt_size +
9792                                     sizeof (uint64_t);
9793 
9794                         break;
9795 
9796                 default:
9797                         ASSERT(0);
9798                 }
9799 
9800                 while (id >= (oldsvars = *np)) {
9801                         dtrace_statvar_t **statics;
9802                         int newsvars, oldsize, newsize;
9803 
9804                         if ((newsvars = (oldsvars << 1)) == 0)
9805                                 newsvars = 1;
9806 
9807                         oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9808                         newsize = newsvars * sizeof (dtrace_statvar_t *);
9809 
9810                         statics = kmem_zalloc(newsize, KM_SLEEP);
9811 
9812                         if (oldsize != 0) {
9813                                 bcopy(*svarp, statics, oldsize);
9814                                 kmem_free(*svarp, oldsize);
9815                         }
9816 
9817                         *svarp = statics;
9818                         *np = newsvars;
9819                 }
9820 
9821                 if ((svar = (*svarp)[id]) == NULL) {
9822                         svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9823                         svar->dtsv_var = *v;
9824 
9825                         if ((svar->dtsv_size = dsize) != 0) {
9826                                 svar->dtsv_data = (uint64_t)(uintptr_t)
9827                                     kmem_zalloc(dsize, KM_SLEEP);
9828                         }
9829 
9830                         (*svarp)[id] = svar;
9831                 }
9832 
9833                 svar->dtsv_refcnt++;
9834         }
9835 
9836         dtrace_difo_chunksize(dp, vstate);
9837         dtrace_difo_hold(dp);
9838 }
9839 
9840 static dtrace_difo_t *
9841 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9842 {
9843         dtrace_difo_t *new;
9844         size_t sz;
9845 
9846         ASSERT(dp->dtdo_buf != NULL);
9847         ASSERT(dp->dtdo_refcnt != 0);
9848 
9849         new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9850 
9851         ASSERT(dp->dtdo_buf != NULL);
9852         sz = dp->dtdo_len * sizeof (dif_instr_t);
9853         new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9854         bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9855         new->dtdo_len = dp->dtdo_len;
9856 
9857         if (dp->dtdo_strtab != NULL) {
9858                 ASSERT(dp->dtdo_strlen != 0);
9859                 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9860                 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9861                 new->dtdo_strlen = dp->dtdo_strlen;
9862         }
9863 
9864         if (dp->dtdo_inttab != NULL) {
9865                 ASSERT(dp->dtdo_intlen != 0);
9866                 sz = dp->dtdo_intlen * sizeof (uint64_t);
9867                 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9868                 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9869                 new->dtdo_intlen = dp->dtdo_intlen;
9870         }
9871 
9872         if (dp->dtdo_vartab != NULL) {
9873                 ASSERT(dp->dtdo_varlen != 0);
9874                 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9875                 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9876                 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9877                 new->dtdo_varlen = dp->dtdo_varlen;
9878         }
9879 
9880         dtrace_difo_init(new, vstate);
9881         return (new);
9882 }
9883 
9884 static void
9885 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9886 {
9887         int i;
9888 
9889         ASSERT(dp->dtdo_refcnt == 0);
9890 
9891         for (i = 0; i < dp->dtdo_varlen; i++) {
9892                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9893                 dtrace_statvar_t *svar, **svarp;
9894                 uint_t id;
9895                 uint8_t scope = v->dtdv_scope;
9896                 int *np;
9897 
9898                 switch (scope) {
9899                 case DIFV_SCOPE_THREAD:
9900                         continue;
9901 
9902                 case DIFV_SCOPE_LOCAL:
9903                         np = &vstate->dtvs_nlocals;
9904                         svarp = vstate->dtvs_locals;
9905                         break;
9906 
9907                 case DIFV_SCOPE_GLOBAL:
9908                         np = &vstate->dtvs_nglobals;
9909                         svarp = vstate->dtvs_globals;
9910                         break;
9911 
9912                 default:
9913                         ASSERT(0);
9914                 }
9915 
9916                 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9917                         continue;
9918 
9919                 id -= DIF_VAR_OTHER_UBASE;
9920                 ASSERT(id < *np);
9921 
9922                 svar = svarp[id];
9923                 ASSERT(svar != NULL);
9924                 ASSERT(svar->dtsv_refcnt > 0);
9925 
9926                 if (--svar->dtsv_refcnt > 0)
9927                         continue;
9928 
9929                 if (svar->dtsv_size != 0) {
9930                         ASSERT(svar->dtsv_data != NULL);
9931                         kmem_free((void *)(uintptr_t)svar->dtsv_data,
9932                             svar->dtsv_size);
9933                 }
9934 
9935                 kmem_free(svar, sizeof (dtrace_statvar_t));
9936                 svarp[id] = NULL;
9937         }
9938 
9939         kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9940         kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9941         kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9942         kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9943 
9944         kmem_free(dp, sizeof (dtrace_difo_t));
9945 }
9946 
9947 static void
9948 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9949 {
9950         int i;
9951 
9952         ASSERT(MUTEX_HELD(&dtrace_lock));
9953         ASSERT(dp->dtdo_refcnt != 0);
9954 
9955         for (i = 0; i < dp->dtdo_varlen; i++) {
9956                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9957 
9958                 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9959                         continue;
9960 
9961                 ASSERT(dtrace_vtime_references > 0);
9962                 if (--dtrace_vtime_references == 0)
9963                         dtrace_vtime_disable();
9964         }
9965 
9966         if (--dp->dtdo_refcnt == 0)
9967                 dtrace_difo_destroy(dp, vstate);
9968 }
9969 
9970 /*
9971  * DTrace Format Functions
9972  */
9973 static uint16_t
9974 dtrace_format_add(dtrace_state_t *state, char *str)
9975 {
9976         char *fmt, **new;
9977         uint16_t ndx, len = strlen(str) + 1;
9978 
9979         fmt = kmem_zalloc(len, KM_SLEEP);
9980         bcopy(str, fmt, len);
9981 
9982         for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9983                 if (state->dts_formats[ndx] == NULL) {
9984                         state->dts_formats[ndx] = fmt;
9985                         return (ndx + 1);
9986                 }
9987         }
9988 
9989         if (state->dts_nformats == USHRT_MAX) {
9990                 /*
9991                  * This is only likely if a denial-of-service attack is being
9992                  * attempted.  As such, it's okay to fail silently here.
9993                  */
9994                 kmem_free(fmt, len);
9995                 return (0);
9996         }
9997 
9998         /*
9999          * For simplicity, we always resize the formats array to be exactly the
10000          * number of formats.
10001          */
10002         ndx = state->dts_nformats++;
10003         new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10004 
10005         if (state->dts_formats != NULL) {
10006                 ASSERT(ndx != 0);
10007                 bcopy(state->dts_formats, new, ndx * sizeof (char *));
10008                 kmem_free(state->dts_formats, ndx * sizeof (char *));
10009         }
10010 
10011         state->dts_formats = new;
10012         state->dts_formats[ndx] = fmt;
10013 
10014         return (ndx + 1);
10015 }
10016 
10017 static void
10018 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10019 {
10020         char *fmt;
10021 
10022         ASSERT(state->dts_formats != NULL);
10023         ASSERT(format <= state->dts_nformats);
10024         ASSERT(state->dts_formats[format - 1] != NULL);
10025 
10026         fmt = state->dts_formats[format - 1];
10027         kmem_free(fmt, strlen(fmt) + 1);
10028         state->dts_formats[format - 1] = NULL;
10029 }
10030 
10031 static void
10032 dtrace_format_destroy(dtrace_state_t *state)
10033 {
10034         int i;
10035 
10036         if (state->dts_nformats == 0) {
10037                 ASSERT(state->dts_formats == NULL);
10038                 return;
10039         }
10040 
10041         ASSERT(state->dts_formats != NULL);
10042 
10043         for (i = 0; i < state->dts_nformats; i++) {
10044                 char *fmt = state->dts_formats[i];
10045 
10046                 if (fmt == NULL)
10047                         continue;
10048 
10049                 kmem_free(fmt, strlen(fmt) + 1);
10050         }
10051 
10052         kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10053         state->dts_nformats = 0;
10054         state->dts_formats = NULL;
10055 }
10056 
10057 /*
10058  * DTrace Predicate Functions
10059  */
10060 static dtrace_predicate_t *
10061 dtrace_predicate_create(dtrace_difo_t *dp)
10062 {
10063         dtrace_predicate_t *pred;
10064 
10065         ASSERT(MUTEX_HELD(&dtrace_lock));
10066         ASSERT(dp->dtdo_refcnt != 0);
10067 
10068         pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10069         pred->dtp_difo = dp;
10070         pred->dtp_refcnt = 1;
10071 
10072         if (!dtrace_difo_cacheable(dp))
10073                 return (pred);
10074 
10075         if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10076                 /*
10077                  * This is only theoretically possible -- we have had 2^32
10078                  * cacheable predicates on this machine.  We cannot allow any
10079                  * more predicates to become cacheable:  as unlikely as it is,
10080                  * there may be a thread caching a (now stale) predicate cache
10081                  * ID. (N.B.: the temptation is being successfully resisted to
10082                  * have this cmn_err() "Holy shit -- we executed this code!")
10083                  */
10084                 return (pred);
10085         }
10086 
10087         pred->dtp_cacheid = dtrace_predcache_id++;
10088 
10089         return (pred);
10090 }
10091 
10092 static void
10093 dtrace_predicate_hold(dtrace_predicate_t *pred)
10094 {
10095         ASSERT(MUTEX_HELD(&dtrace_lock));
10096         ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10097         ASSERT(pred->dtp_refcnt > 0);
10098 
10099         pred->dtp_refcnt++;
10100 }
10101 
10102 static void
10103 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10104 {
10105         dtrace_difo_t *dp = pred->dtp_difo;
10106 
10107         ASSERT(MUTEX_HELD(&dtrace_lock));
10108         ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10109         ASSERT(pred->dtp_refcnt > 0);
10110 
10111         if (--pred->dtp_refcnt == 0) {
10112                 dtrace_difo_release(pred->dtp_difo, vstate);
10113                 kmem_free(pred, sizeof (dtrace_predicate_t));
10114         }
10115 }
10116 
10117 /*
10118  * DTrace Action Description Functions
10119  */
10120 static dtrace_actdesc_t *
10121 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10122     uint64_t uarg, uint64_t arg)
10123 {
10124         dtrace_actdesc_t *act;
10125 
10126         ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
10127             arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
10128 
10129         act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10130         act->dtad_kind = kind;
10131         act->dtad_ntuple = ntuple;
10132         act->dtad_uarg = uarg;
10133         act->dtad_arg = arg;
10134         act->dtad_refcnt = 1;
10135 
10136         return (act);
10137 }
10138 
10139 static void
10140 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10141 {
10142         ASSERT(act->dtad_refcnt >= 1);
10143         act->dtad_refcnt++;
10144 }
10145 
10146 static void
10147 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10148 {
10149         dtrace_actkind_t kind = act->dtad_kind;
10150         dtrace_difo_t *dp;
10151 
10152         ASSERT(act->dtad_refcnt >= 1);
10153 
10154         if (--act->dtad_refcnt != 0)
10155                 return;
10156 
10157         if ((dp = act->dtad_difo) != NULL)
10158                 dtrace_difo_release(dp, vstate);
10159 
10160         if (DTRACEACT_ISPRINTFLIKE(kind)) {
10161                 char *str = (char *)(uintptr_t)act->dtad_arg;
10162 
10163                 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10164                     (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10165 
10166                 if (str != NULL)
10167                         kmem_free(str, strlen(str) + 1);
10168         }
10169 
10170         kmem_free(act, sizeof (dtrace_actdesc_t));
10171 }
10172 
10173 /*
10174  * DTrace ECB Functions
10175  */
10176 static dtrace_ecb_t *
10177 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10178 {
10179         dtrace_ecb_t *ecb;
10180         dtrace_epid_t epid;
10181 
10182         ASSERT(MUTEX_HELD(&dtrace_lock));
10183 
10184         ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10185         ecb->dte_predicate = NULL;
10186         ecb->dte_probe = probe;
10187 
10188         /*
10189          * The default size is the size of the default action: recording
10190          * the header.
10191          */
10192         ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10193         ecb->dte_alignment = sizeof (dtrace_epid_t);
10194 
10195         epid = state->dts_epid++;
10196 
10197         if (epid - 1 >= state->dts_necbs) {
10198                 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10199                 int necbs = state->dts_necbs << 1;
10200 
10201                 ASSERT(epid == state->dts_necbs + 1);
10202 
10203                 if (necbs == 0) {
10204                         ASSERT(oecbs == NULL);
10205                         necbs = 1;
10206                 }
10207 
10208                 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10209 
10210                 if (oecbs != NULL)
10211                         bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10212 
10213                 dtrace_membar_producer();
10214                 state->dts_ecbs = ecbs;
10215 
10216                 if (oecbs != NULL) {
10217                         /*
10218                          * If this state is active, we must dtrace_sync()
10219                          * before we can free the old dts_ecbs array:  we're
10220                          * coming in hot, and there may be active ring
10221                          * buffer processing (which indexes into the dts_ecbs
10222                          * array) on another CPU.
10223                          */
10224                         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10225                                 dtrace_sync();
10226 
10227                         kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10228                 }
10229 
10230                 dtrace_membar_producer();
10231                 state->dts_necbs = necbs;
10232         }
10233 
10234         ecb->dte_state = state;
10235 
10236         ASSERT(state->dts_ecbs[epid - 1] == NULL);
10237         dtrace_membar_producer();
10238         state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10239 
10240         return (ecb);
10241 }
10242 
10243 static int
10244 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10245 {
10246         dtrace_probe_t *probe = ecb->dte_probe;
10247 
10248         ASSERT(MUTEX_HELD(&cpu_lock));
10249         ASSERT(MUTEX_HELD(&dtrace_lock));
10250         ASSERT(ecb->dte_next == NULL);
10251 
10252         if (probe == NULL) {
10253                 /*
10254                  * This is the NULL probe -- there's nothing to do.
10255                  */
10256                 return (0);
10257         }
10258 
10259         if (probe->dtpr_ecb == NULL) {
10260                 dtrace_provider_t *prov = probe->dtpr_provider;
10261 
10262                 /*
10263                  * We're the first ECB on this probe.
10264                  */
10265                 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10266 
10267                 if (ecb->dte_predicate != NULL)
10268                         probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10269 
10270                 return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10271                     probe->dtpr_id, probe->dtpr_arg));
10272         } else {
10273                 /*
10274                  * This probe is already active.  Swing the last pointer to
10275                  * point to the new ECB, and issue a dtrace_sync() to assure
10276                  * that all CPUs have seen the change.
10277                  */
10278                 ASSERT(probe->dtpr_ecb_last != NULL);
10279                 probe->dtpr_ecb_last->dte_next = ecb;
10280                 probe->dtpr_ecb_last = ecb;
10281                 probe->dtpr_predcache = 0;
10282 
10283                 dtrace_sync();
10284                 return (0);
10285         }
10286 }
10287 
10288 static void
10289 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10290 {
10291         dtrace_action_t *act;
10292         uint32_t curneeded = UINT32_MAX;
10293         uint32_t aggbase = UINT32_MAX;
10294 
10295         /*
10296          * If we record anything, we always record the dtrace_rechdr_t.  (And
10297          * we always record it first.)
10298          */
10299         ecb->dte_size = sizeof (dtrace_rechdr_t);
10300         ecb->dte_alignment = sizeof (dtrace_epid_t);
10301 
10302         for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10303                 dtrace_recdesc_t *rec = &act->dta_rec;
10304                 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10305 
10306                 ecb->dte_alignment = MAX(ecb->dte_alignment,
10307                     rec->dtrd_alignment);
10308 
10309                 if (DTRACEACT_ISAGG(act->dta_kind)) {
10310                         dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10311 
10312                         ASSERT(rec->dtrd_size != 0);
10313                         ASSERT(agg->dtag_first != NULL);
10314                         ASSERT(act->dta_prev->dta_intuple);
10315                         ASSERT(aggbase != UINT32_MAX);
10316                         ASSERT(curneeded != UINT32_MAX);
10317 
10318                         agg->dtag_base = aggbase;
10319 
10320                         curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10321                         rec->dtrd_offset = curneeded;
10322                         curneeded += rec->dtrd_size;
10323                         ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10324 
10325                         aggbase = UINT32_MAX;
10326                         curneeded = UINT32_MAX;
10327                 } else if (act->dta_intuple) {
10328                         if (curneeded == UINT32_MAX) {
10329                                 /*
10330                                  * This is the first record in a tuple.  Align
10331                                  * curneeded to be at offset 4 in an 8-byte
10332                                  * aligned block.
10333                                  */
10334                                 ASSERT(act->dta_prev == NULL ||
10335                                     !act->dta_prev->dta_intuple);
10336                                 ASSERT3U(aggbase, ==, UINT32_MAX);
10337                                 curneeded = P2PHASEUP(ecb->dte_size,
10338                                     sizeof (uint64_t), sizeof (dtrace_aggid_t));
10339 
10340                                 aggbase = curneeded - sizeof (dtrace_aggid_t);
10341                                 ASSERT(IS_P2ALIGNED(aggbase,
10342                                     sizeof (uint64_t)));
10343                         }
10344                         curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10345                         rec->dtrd_offset = curneeded;
10346                         curneeded += rec->dtrd_size;
10347                 } else {
10348                         /* tuples must be followed by an aggregation */
10349                         ASSERT(act->dta_prev == NULL ||
10350                             !act->dta_prev->dta_intuple);
10351 
10352                         ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10353                             rec->dtrd_alignment);
10354                         rec->dtrd_offset = ecb->dte_size;
10355                         ecb->dte_size += rec->dtrd_size;
10356                         ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10357                 }
10358         }
10359 
10360         if ((act = ecb->dte_action) != NULL &&
10361             !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10362             ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10363                 /*
10364                  * If the size is still sizeof (dtrace_rechdr_t), then all
10365                  * actions store no data; set the size to 0.
10366                  */
10367                 ecb->dte_size = 0;
10368         }
10369 
10370         ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10371         ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10372         ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10373             ecb->dte_needed);
10374 }
10375 
10376 static dtrace_action_t *
10377 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10378 {
10379         dtrace_aggregation_t *agg;
10380         size_t size = sizeof (uint64_t);
10381         int ntuple = desc->dtad_ntuple;
10382         dtrace_action_t *act;
10383         dtrace_recdesc_t *frec;
10384         dtrace_aggid_t aggid;
10385         dtrace_state_t *state = ecb->dte_state;
10386 
10387         agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10388         agg->dtag_ecb = ecb;
10389 
10390         ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10391 
10392         switch (desc->dtad_kind) {
10393         case DTRACEAGG_MIN:
10394                 agg->dtag_initial = INT64_MAX;
10395                 agg->dtag_aggregate = dtrace_aggregate_min;
10396                 break;
10397 
10398         case DTRACEAGG_MAX:
10399                 agg->dtag_initial = INT64_MIN;
10400                 agg->dtag_aggregate = dtrace_aggregate_max;
10401                 break;
10402 
10403         case DTRACEAGG_COUNT:
10404                 agg->dtag_aggregate = dtrace_aggregate_count;
10405                 break;
10406 
10407         case DTRACEAGG_QUANTIZE:
10408                 agg->dtag_aggregate = dtrace_aggregate_quantize;
10409                 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10410                     sizeof (uint64_t);
10411                 break;
10412 
10413         case DTRACEAGG_LQUANTIZE: {
10414                 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10415                 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10416 
10417                 agg->dtag_initial = desc->dtad_arg;
10418                 agg->dtag_aggregate = dtrace_aggregate_lquantize;
10419 
10420                 if (step == 0 || levels == 0)
10421                         goto err;
10422 
10423                 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10424                 break;
10425         }
10426 
10427         case DTRACEAGG_LLQUANTIZE: {
10428                 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10429                 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10430                 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10431                 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10432                 int64_t v;
10433 
10434                 agg->dtag_initial = desc->dtad_arg;
10435                 agg->dtag_aggregate = dtrace_aggregate_llquantize;
10436 
10437                 if (factor < 2 || low >= high || nsteps < factor)
10438                         goto err;
10439 
10440                 /*
10441                  * Now check that the number of steps evenly divides a power
10442                  * of the factor.  (This assures both integer bucket size and
10443                  * linearity within each magnitude.)
10444                  */
10445                 for (v = factor; v < nsteps; v *= factor)
10446                         continue;
10447 
10448                 if ((v % nsteps) || (nsteps % factor))
10449                         goto err;
10450 
10451                 size = (dtrace_aggregate_llquantize_bucket(factor,
10452                     low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10453                 break;
10454         }
10455 
10456         case DTRACEAGG_AVG:
10457                 agg->dtag_aggregate = dtrace_aggregate_avg;
10458                 size = sizeof (uint64_t) * 2;
10459                 break;
10460 
10461         case DTRACEAGG_STDDEV:
10462                 agg->dtag_aggregate = dtrace_aggregate_stddev;
10463                 size = sizeof (uint64_t) * 4;
10464                 break;
10465 
10466         case DTRACEAGG_SUM:
10467                 agg->dtag_aggregate = dtrace_aggregate_sum;
10468                 break;
10469 
10470         default:
10471                 goto err;
10472         }
10473 
10474         agg->dtag_action.dta_rec.dtrd_size = size;
10475 
10476         if (ntuple == 0)
10477                 goto err;
10478 
10479         /*
10480          * We must make sure that we have enough actions for the n-tuple.
10481          */
10482         for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10483                 if (DTRACEACT_ISAGG(act->dta_kind))
10484                         break;
10485 
10486                 if (--ntuple == 0) {
10487                         /*
10488                          * This is the action with which our n-tuple begins.
10489                          */
10490                         agg->dtag_first = act;
10491                         goto success;
10492                 }
10493         }
10494 
10495         /*
10496          * This n-tuple is short by ntuple elements.  Return failure.
10497          */
10498         ASSERT(ntuple != 0);
10499 err:
10500         kmem_free(agg, sizeof (dtrace_aggregation_t));
10501         return (NULL);
10502 
10503 success:
10504         /*
10505          * If the last action in the tuple has a size of zero, it's actually
10506          * an expression argument for the aggregating action.
10507          */
10508         ASSERT(ecb->dte_action_last != NULL);
10509         act = ecb->dte_action_last;
10510 
10511         if (act->dta_kind == DTRACEACT_DIFEXPR) {
10512                 ASSERT(act->dta_difo != NULL);
10513 
10514                 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10515                         agg->dtag_hasarg = 1;
10516         }
10517 
10518         /*
10519          * We need to allocate an id for this aggregation.
10520          */
10521         aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10522             VM_BESTFIT | VM_SLEEP);
10523 
10524         if (aggid - 1 >= state->dts_naggregations) {
10525                 dtrace_aggregation_t **oaggs = state->dts_aggregations;
10526                 dtrace_aggregation_t **aggs;
10527                 int naggs = state->dts_naggregations << 1;
10528                 int onaggs = state->dts_naggregations;
10529 
10530                 ASSERT(aggid == state->dts_naggregations + 1);
10531 
10532                 if (naggs == 0) {
10533                         ASSERT(oaggs == NULL);
10534                         naggs = 1;
10535                 }
10536 
10537                 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10538 
10539                 if (oaggs != NULL) {
10540                         bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10541                         kmem_free(oaggs, onaggs * sizeof (*aggs));
10542                 }
10543 
10544                 state->dts_aggregations = aggs;
10545                 state->dts_naggregations = naggs;
10546         }
10547 
10548         ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10549         state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10550 
10551         frec = &agg->dtag_first->dta_rec;
10552         if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10553                 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10554 
10555         for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10556                 ASSERT(!act->dta_intuple);
10557                 act->dta_intuple = 1;
10558         }
10559 
10560         return (&agg->dtag_action);
10561 }
10562 
10563 static void
10564 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10565 {
10566         dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10567         dtrace_state_t *state = ecb->dte_state;
10568         dtrace_aggid_t aggid = agg->dtag_id;
10569 
10570         ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10571         vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10572 
10573         ASSERT(state->dts_aggregations[aggid - 1] == agg);
10574         state->dts_aggregations[aggid - 1] = NULL;
10575 
10576         kmem_free(agg, sizeof (dtrace_aggregation_t));
10577 }
10578 
10579 static int
10580 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10581 {
10582         dtrace_action_t *action, *last;
10583         dtrace_difo_t *dp = desc->dtad_difo;
10584         uint32_t size = 0, align = sizeof (uint8_t), mask;
10585         uint16_t format = 0;
10586         dtrace_recdesc_t *rec;
10587         dtrace_state_t *state = ecb->dte_state;
10588         dtrace_optval_t *opt = state->dts_options, nframes, strsize;
10589         uint64_t arg = desc->dtad_arg;
10590 
10591         ASSERT(MUTEX_HELD(&dtrace_lock));
10592         ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10593 
10594         if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10595                 /*
10596                  * If this is an aggregating action, there must be neither
10597                  * a speculate nor a commit on the action chain.
10598                  */
10599                 dtrace_action_t *act;
10600 
10601                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10602                         if (act->dta_kind == DTRACEACT_COMMIT)
10603                                 return (EINVAL);
10604 
10605                         if (act->dta_kind == DTRACEACT_SPECULATE)
10606                                 return (EINVAL);
10607                 }
10608 
10609                 action = dtrace_ecb_aggregation_create(ecb, desc);
10610 
10611                 if (action == NULL)
10612                         return (EINVAL);
10613         } else {
10614                 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10615                     (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10616                     dp != NULL && dp->dtdo_destructive)) {
10617                         state->dts_destructive = 1;
10618                 }
10619 
10620                 switch (desc->dtad_kind) {
10621                 case DTRACEACT_PRINTF:
10622                 case DTRACEACT_PRINTA:
10623                 case DTRACEACT_SYSTEM:
10624                 case DTRACEACT_FREOPEN:
10625                 case DTRACEACT_DIFEXPR:
10626                         /*
10627                          * We know that our arg is a string -- turn it into a
10628                          * format.
10629                          */
10630                         if (arg == NULL) {
10631                                 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10632                                     desc->dtad_kind == DTRACEACT_DIFEXPR);
10633                                 format = 0;
10634                         } else {
10635                                 ASSERT(arg != NULL);
10636                                 ASSERT(arg > KERNELBASE);
10637                                 format = dtrace_format_add(state,
10638                                     (char *)(uintptr_t)arg);
10639                         }
10640 
10641                         /*FALLTHROUGH*/
10642                 case DTRACEACT_LIBACT:
10643                 case DTRACEACT_TRACEMEM:
10644                 case DTRACEACT_TRACEMEM_DYNSIZE:
10645                         if (dp == NULL)
10646                                 return (EINVAL);
10647 
10648                         if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10649                                 break;
10650 
10651                         if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10652                                 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10653                                         return (EINVAL);
10654 
10655                                 size = opt[DTRACEOPT_STRSIZE];
10656                         }
10657 
10658                         break;
10659 
10660                 case DTRACEACT_STACK:
10661                         if ((nframes = arg) == 0) {
10662                                 nframes = opt[DTRACEOPT_STACKFRAMES];
10663                                 ASSERT(nframes > 0);
10664                                 arg = nframes;
10665                         }
10666 
10667                         size = nframes * sizeof (pc_t);
10668                         break;
10669 
10670                 case DTRACEACT_JSTACK:
10671                         if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10672                                 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10673 
10674                         if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10675                                 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10676 
10677                         arg = DTRACE_USTACK_ARG(nframes, strsize);
10678 
10679                         /*FALLTHROUGH*/
10680                 case DTRACEACT_USTACK:
10681                         if (desc->dtad_kind != DTRACEACT_JSTACK &&
10682                             (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10683                                 strsize = DTRACE_USTACK_STRSIZE(arg);
10684                                 nframes = opt[DTRACEOPT_USTACKFRAMES];
10685                                 ASSERT(nframes > 0);
10686                                 arg = DTRACE_USTACK_ARG(nframes, strsize);
10687                         }
10688 
10689                         /*
10690                          * Save a slot for the pid.
10691                          */
10692                         size = (nframes + 1) * sizeof (uint64_t);
10693                         size += DTRACE_USTACK_STRSIZE(arg);
10694                         size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10695 
10696                         break;
10697 
10698                 case DTRACEACT_SYM:
10699                 case DTRACEACT_MOD:
10700                         if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10701                             sizeof (uint64_t)) ||
10702                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10703                                 return (EINVAL);
10704                         break;
10705 
10706                 case DTRACEACT_USYM:
10707                 case DTRACEACT_UMOD:
10708                 case DTRACEACT_UADDR:
10709                         if (dp == NULL ||
10710                             (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10711                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10712                                 return (EINVAL);
10713 
10714                         /*
10715                          * We have a slot for the pid, plus a slot for the
10716                          * argument.  To keep things simple (aligned with
10717                          * bitness-neutral sizing), we store each as a 64-bit
10718                          * quantity.
10719                          */
10720                         size = 2 * sizeof (uint64_t);
10721                         break;
10722 
10723                 case DTRACEACT_STOP:
10724                 case DTRACEACT_BREAKPOINT:
10725                 case DTRACEACT_PANIC:
10726                         break;
10727 
10728                 case DTRACEACT_CHILL:
10729                 case DTRACEACT_DISCARD:
10730                 case DTRACEACT_RAISE:
10731                         if (dp == NULL)
10732                                 return (EINVAL);
10733                         break;
10734 
10735                 case DTRACEACT_EXIT:
10736                         if (dp == NULL ||
10737                             (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10738                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10739                                 return (EINVAL);
10740                         break;
10741 
10742                 case DTRACEACT_SPECULATE:
10743                         if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10744                                 return (EINVAL);
10745 
10746                         if (dp == NULL)
10747                                 return (EINVAL);
10748 
10749                         state->dts_speculates = 1;
10750                         break;
10751 
10752                 case DTRACEACT_COMMIT: {
10753                         dtrace_action_t *act = ecb->dte_action;
10754 
10755                         for (; act != NULL; act = act->dta_next) {
10756                                 if (act->dta_kind == DTRACEACT_COMMIT)
10757                                         return (EINVAL);
10758                         }
10759 
10760                         if (dp == NULL)
10761                                 return (EINVAL);
10762                         break;
10763                 }
10764 
10765                 default:
10766                         return (EINVAL);
10767                 }
10768 
10769                 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10770                         /*
10771                          * If this is a data-storing action or a speculate,
10772                          * we must be sure that there isn't a commit on the
10773                          * action chain.
10774                          */
10775                         dtrace_action_t *act = ecb->dte_action;
10776 
10777                         for (; act != NULL; act = act->dta_next) {
10778                                 if (act->dta_kind == DTRACEACT_COMMIT)
10779                                         return (EINVAL);
10780                         }
10781                 }
10782 
10783                 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10784                 action->dta_rec.dtrd_size = size;
10785         }
10786 
10787         action->dta_refcnt = 1;
10788         rec = &action->dta_rec;
10789         size = rec->dtrd_size;
10790 
10791         for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10792                 if (!(size & mask)) {
10793                         align = mask + 1;
10794                         break;
10795                 }
10796         }
10797 
10798         action->dta_kind = desc->dtad_kind;
10799 
10800         if ((action->dta_difo = dp) != NULL)
10801                 dtrace_difo_hold(dp);
10802 
10803         rec->dtrd_action = action->dta_kind;
10804         rec->dtrd_arg = arg;
10805         rec->dtrd_uarg = desc->dtad_uarg;
10806         rec->dtrd_alignment = (uint16_t)align;
10807         rec->dtrd_format = format;
10808 
10809         if ((last = ecb->dte_action_last) != NULL) {
10810                 ASSERT(ecb->dte_action != NULL);
10811                 action->dta_prev = last;
10812                 last->dta_next = action;
10813         } else {
10814                 ASSERT(ecb->dte_action == NULL);
10815                 ecb->dte_action = action;
10816         }
10817 
10818         ecb->dte_action_last = action;
10819 
10820         return (0);
10821 }
10822 
10823 static void
10824 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10825 {
10826         dtrace_action_t *act = ecb->dte_action, *next;
10827         dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10828         dtrace_difo_t *dp;
10829         uint16_t format;
10830 
10831         if (act != NULL && act->dta_refcnt > 1) {
10832                 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10833                 act->dta_refcnt--;
10834         } else {
10835                 for (; act != NULL; act = next) {
10836                         next = act->dta_next;
10837                         ASSERT(next != NULL || act == ecb->dte_action_last);
10838                         ASSERT(act->dta_refcnt == 1);
10839 
10840                         if ((format = act->dta_rec.dtrd_format) != 0)
10841                                 dtrace_format_remove(ecb->dte_state, format);
10842 
10843                         if ((dp = act->dta_difo) != NULL)
10844                                 dtrace_difo_release(dp, vstate);
10845 
10846                         if (DTRACEACT_ISAGG(act->dta_kind)) {
10847                                 dtrace_ecb_aggregation_destroy(ecb, act);
10848                         } else {
10849                                 kmem_free(act, sizeof (dtrace_action_t));
10850                         }
10851                 }
10852         }
10853 
10854         ecb->dte_action = NULL;
10855         ecb->dte_action_last = NULL;
10856         ecb->dte_size = 0;
10857 }
10858 
10859 static void
10860 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10861 {
10862         /*
10863          * We disable the ECB by removing it from its probe.
10864          */
10865         dtrace_ecb_t *pecb, *prev = NULL;
10866         dtrace_probe_t *probe = ecb->dte_probe;
10867 
10868         ASSERT(MUTEX_HELD(&dtrace_lock));
10869 
10870         if (probe == NULL) {
10871                 /*
10872                  * This is the NULL probe; there is nothing to disable.
10873                  */
10874                 return;
10875         }
10876 
10877         for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10878                 if (pecb == ecb)
10879                         break;
10880                 prev = pecb;
10881         }
10882 
10883         ASSERT(pecb != NULL);
10884 
10885         if (prev == NULL) {
10886                 probe->dtpr_ecb = ecb->dte_next;
10887         } else {
10888                 prev->dte_next = ecb->dte_next;
10889         }
10890 
10891         if (ecb == probe->dtpr_ecb_last) {
10892                 ASSERT(ecb->dte_next == NULL);
10893                 probe->dtpr_ecb_last = prev;
10894         }
10895 
10896         /*
10897          * The ECB has been disconnected from the probe; now sync to assure
10898          * that all CPUs have seen the change before returning.
10899          */
10900         dtrace_sync();
10901 
10902         if (probe->dtpr_ecb == NULL) {
10903                 /*
10904                  * That was the last ECB on the probe; clear the predicate
10905                  * cache ID for the probe, disable it and sync one more time
10906                  * to assure that we'll never hit it again.
10907                  */
10908                 dtrace_provider_t *prov = probe->dtpr_provider;
10909 
10910                 ASSERT(ecb->dte_next == NULL);
10911                 ASSERT(probe->dtpr_ecb_last == NULL);
10912                 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10913                 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10914                     probe->dtpr_id, probe->dtpr_arg);
10915                 dtrace_sync();
10916         } else {
10917                 /*
10918                  * There is at least one ECB remaining on the probe.  If there
10919                  * is _exactly_ one, set the probe's predicate cache ID to be
10920                  * the predicate cache ID of the remaining ECB.
10921                  */
10922                 ASSERT(probe->dtpr_ecb_last != NULL);
10923                 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10924 
10925                 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10926                         dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10927 
10928                         ASSERT(probe->dtpr_ecb->dte_next == NULL);
10929 
10930                         if (p != NULL)
10931                                 probe->dtpr_predcache = p->dtp_cacheid;
10932                 }
10933 
10934                 ecb->dte_next = NULL;
10935         }
10936 }
10937 
10938 static void
10939 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10940 {
10941         dtrace_state_t *state = ecb->dte_state;
10942         dtrace_vstate_t *vstate = &state->dts_vstate;
10943         dtrace_predicate_t *pred;
10944         dtrace_epid_t epid = ecb->dte_epid;
10945 
10946         ASSERT(MUTEX_HELD(&dtrace_lock));
10947         ASSERT(ecb->dte_next == NULL);
10948         ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10949 
10950         if ((pred = ecb->dte_predicate) != NULL)
10951                 dtrace_predicate_release(pred, vstate);
10952 
10953         dtrace_ecb_action_remove(ecb);
10954 
10955         ASSERT(state->dts_ecbs[epid - 1] == ecb);
10956         state->dts_ecbs[epid - 1] = NULL;
10957 
10958         kmem_free(ecb, sizeof (dtrace_ecb_t));
10959 }
10960 
10961 static dtrace_ecb_t *
10962 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10963     dtrace_enabling_t *enab)
10964 {
10965         dtrace_ecb_t *ecb;
10966         dtrace_predicate_t *pred;
10967         dtrace_actdesc_t *act;
10968         dtrace_provider_t *prov;
10969         dtrace_ecbdesc_t *desc = enab->dten_current;
10970 
10971         ASSERT(MUTEX_HELD(&dtrace_lock));
10972         ASSERT(state != NULL);
10973 
10974         ecb = dtrace_ecb_add(state, probe);
10975         ecb->dte_uarg = desc->dted_uarg;
10976 
10977         if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10978                 dtrace_predicate_hold(pred);
10979                 ecb->dte_predicate = pred;
10980         }
10981 
10982         if (probe != NULL) {
10983                 /*
10984                  * If the provider shows more leg than the consumer is old
10985                  * enough to see, we need to enable the appropriate implicit
10986                  * predicate bits to prevent the ecb from activating at
10987                  * revealing times.
10988                  *
10989                  * Providers specifying DTRACE_PRIV_USER at register time
10990                  * are stating that they need the /proc-style privilege
10991                  * model to be enforced, and this is what DTRACE_COND_OWNER
10992                  * and DTRACE_COND_ZONEOWNER will then do at probe time.
10993                  */
10994                 prov = probe->dtpr_provider;
10995                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10996                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10997                         ecb->dte_cond |= DTRACE_COND_OWNER;
10998 
10999                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11000                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11001                         ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11002 
11003                 /*
11004                  * If the provider shows us kernel innards and the user
11005                  * is lacking sufficient privilege, enable the
11006                  * DTRACE_COND_USERMODE implicit predicate.
11007                  */
11008                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11009                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11010                         ecb->dte_cond |= DTRACE_COND_USERMODE;
11011         }
11012 
11013         if (dtrace_ecb_create_cache != NULL) {
11014                 /*
11015                  * If we have a cached ecb, we'll use its action list instead
11016                  * of creating our own (saving both time and space).
11017                  */
11018                 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11019                 dtrace_action_t *act = cached->dte_action;
11020 
11021                 if (act != NULL) {
11022                         ASSERT(act->dta_refcnt > 0);
11023                         act->dta_refcnt++;
11024                         ecb->dte_action = act;
11025                         ecb->dte_action_last = cached->dte_action_last;
11026                         ecb->dte_needed = cached->dte_needed;
11027                         ecb->dte_size = cached->dte_size;
11028                         ecb->dte_alignment = cached->dte_alignment;
11029                 }
11030 
11031                 return (ecb);
11032         }
11033 
11034         for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11035                 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11036                         dtrace_ecb_destroy(ecb);
11037                         return (NULL);
11038                 }
11039         }
11040 
11041         dtrace_ecb_resize(ecb);
11042 
11043         return (dtrace_ecb_create_cache = ecb);
11044 }
11045 
11046 static int
11047 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11048 {
11049         dtrace_ecb_t *ecb;
11050         dtrace_enabling_t *enab = arg;
11051         dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11052 
11053         ASSERT(state != NULL);
11054 
11055         if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11056                 /*
11057                  * This probe was created in a generation for which this
11058                  * enabling has previously created ECBs; we don't want to
11059                  * enable it again, so just kick out.
11060                  */
11061                 return (DTRACE_MATCH_NEXT);
11062         }
11063 
11064         if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11065                 return (DTRACE_MATCH_DONE);
11066 
11067         if (dtrace_ecb_enable(ecb) < 0)
11068                 return (DTRACE_MATCH_FAIL);
11069 
11070         return (DTRACE_MATCH_NEXT);
11071 }
11072 
11073 static dtrace_ecb_t *
11074 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11075 {
11076         dtrace_ecb_t *ecb;
11077 
11078         ASSERT(MUTEX_HELD(&dtrace_lock));
11079 
11080         if (id == 0 || id > state->dts_necbs)
11081                 return (NULL);
11082 
11083         ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11084         ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11085 
11086         return (state->dts_ecbs[id - 1]);
11087 }
11088 
11089 static dtrace_aggregation_t *
11090 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11091 {
11092         dtrace_aggregation_t *agg;
11093 
11094         ASSERT(MUTEX_HELD(&dtrace_lock));
11095 
11096         if (id == 0 || id > state->dts_naggregations)
11097                 return (NULL);
11098 
11099         ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11100         ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11101             agg->dtag_id == id);
11102 
11103         return (state->dts_aggregations[id - 1]);
11104 }
11105 
11106 /*
11107  * DTrace Buffer Functions
11108  *
11109  * The following functions manipulate DTrace buffers.  Most of these functions
11110  * are called in the context of establishing or processing consumer state;
11111  * exceptions are explicitly noted.
11112  */
11113 
11114 /*
11115  * Note:  called from cross call context.  This function switches the two
11116  * buffers on a given CPU.  The atomicity of this operation is assured by
11117  * disabling interrupts while the actual switch takes place; the disabling of
11118  * interrupts serializes the execution with any execution of dtrace_probe() on
11119  * the same CPU.
11120  */
11121 static void
11122 dtrace_buffer_switch(dtrace_buffer_t *buf)
11123 {
11124         caddr_t tomax = buf->dtb_tomax;
11125         caddr_t xamot = buf->dtb_xamot;
11126         dtrace_icookie_t cookie;
11127         hrtime_t now;
11128 
11129         ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11130         ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11131 
11132         cookie = dtrace_interrupt_disable();
11133         now = dtrace_gethrtime();
11134         buf->dtb_tomax = xamot;
11135         buf->dtb_xamot = tomax;
11136         buf->dtb_xamot_drops = buf->dtb_drops;
11137         buf->dtb_xamot_offset = buf->dtb_offset;
11138         buf->dtb_xamot_errors = buf->dtb_errors;
11139         buf->dtb_xamot_flags = buf->dtb_flags;
11140         buf->dtb_offset = 0;
11141         buf->dtb_drops = 0;
11142         buf->dtb_errors = 0;
11143         buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11144         buf->dtb_interval = now - buf->dtb_switched;
11145         buf->dtb_switched = now;
11146         dtrace_interrupt_enable(cookie);
11147 }
11148 
11149 /*
11150  * Note:  called from cross call context.  This function activates a buffer
11151  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
11152  * is guaranteed by the disabling of interrupts.
11153  */
11154 static void
11155 dtrace_buffer_activate(dtrace_state_t *state)
11156 {
11157         dtrace_buffer_t *buf;
11158         dtrace_icookie_t cookie = dtrace_interrupt_disable();
11159 
11160         buf = &state->dts_buffer[CPU->cpu_id];
11161 
11162         if (buf->dtb_tomax != NULL) {
11163                 /*
11164                  * We might like to assert that the buffer is marked inactive,
11165                  * but this isn't necessarily true:  the buffer for the CPU
11166                  * that processes the BEGIN probe has its buffer activated
11167                  * manually.  In this case, we take the (harmless) action
11168                  * re-clearing the bit INACTIVE bit.
11169                  */
11170                 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11171         }
11172 
11173         dtrace_interrupt_enable(cookie);
11174 }
11175 
11176 static int
11177 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11178     processorid_t cpu, int *factor)
11179 {
11180         cpu_t *cp;
11181         dtrace_buffer_t *buf;
11182         int allocated = 0, desired = 0;
11183 
11184         ASSERT(MUTEX_HELD(&cpu_lock));
11185         ASSERT(MUTEX_HELD(&dtrace_lock));
11186 
11187         *factor = 1;
11188 
11189         if (size > dtrace_nonroot_maxsize &&
11190             !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11191                 return (EFBIG);
11192 
11193         cp = cpu_list;
11194 
11195         do {
11196                 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11197                         continue;
11198 
11199                 buf = &bufs[cp->cpu_id];
11200 
11201                 /*
11202                  * If there is already a buffer allocated for this CPU, it
11203                  * is only possible that this is a DR event.  In this case,
11204                  * the buffer size must match our specified size.
11205                  */
11206                 if (buf->dtb_tomax != NULL) {
11207                         ASSERT(buf->dtb_size == size);
11208                         continue;
11209                 }
11210 
11211                 ASSERT(buf->dtb_xamot == NULL);
11212 
11213                 if ((buf->dtb_tomax = kmem_zalloc(size,
11214                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11215                         goto err;
11216 
11217                 buf->dtb_size = size;
11218                 buf->dtb_flags = flags;
11219                 buf->dtb_offset = 0;
11220                 buf->dtb_drops = 0;
11221 
11222                 if (flags & DTRACEBUF_NOSWITCH)
11223                         continue;
11224 
11225                 if ((buf->dtb_xamot = kmem_zalloc(size,
11226                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11227                         goto err;
11228         } while ((cp = cp->cpu_next) != cpu_list);
11229 
11230         return (0);
11231 
11232 err:
11233         cp = cpu_list;
11234 
11235         do {
11236                 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11237                         continue;
11238 
11239                 buf = &bufs[cp->cpu_id];
11240                 desired += 2;
11241 
11242                 if (buf->dtb_xamot != NULL) {
11243                         ASSERT(buf->dtb_tomax != NULL);
11244                         ASSERT(buf->dtb_size == size);
11245                         kmem_free(buf->dtb_xamot, size);
11246                         allocated++;
11247                 }
11248 
11249                 if (buf->dtb_tomax != NULL) {
11250                         ASSERT(buf->dtb_size == size);
11251                         kmem_free(buf->dtb_tomax, size);
11252                         allocated++;
11253                 }
11254 
11255                 buf->dtb_tomax = NULL;
11256                 buf->dtb_xamot = NULL;
11257                 buf->dtb_size = 0;
11258         } while ((cp = cp->cpu_next) != cpu_list);
11259 
11260         *factor = desired / (allocated > 0 ? allocated : 1);
11261 
11262         return (ENOMEM);
11263 }
11264 
11265 /*
11266  * Note:  called from probe context.  This function just increments the drop
11267  * count on a buffer.  It has been made a function to allow for the
11268  * possibility of understanding the source of mysterious drop counts.  (A
11269  * problem for which one may be particularly disappointed that DTrace cannot
11270  * be used to understand DTrace.)
11271  */
11272 static void
11273 dtrace_buffer_drop(dtrace_buffer_t *buf)
11274 {
11275         buf->dtb_drops++;
11276 }
11277 
11278 /*
11279  * Note:  called from probe context.  This function is called to reserve space
11280  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
11281  * mstate.  Returns the new offset in the buffer, or a negative value if an
11282  * error has occurred.
11283  */
11284 static intptr_t
11285 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11286     dtrace_state_t *state, dtrace_mstate_t *mstate)
11287 {
11288         intptr_t offs = buf->dtb_offset, soffs;
11289         intptr_t woffs;
11290         caddr_t tomax;
11291         size_t total;
11292 
11293         if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11294                 return (-1);
11295 
11296         if ((tomax = buf->dtb_tomax) == NULL) {
11297                 dtrace_buffer_drop(buf);
11298                 return (-1);
11299         }
11300 
11301         if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11302                 while (offs & (align - 1)) {
11303                         /*
11304                          * Assert that our alignment is off by a number which
11305                          * is itself sizeof (uint32_t) aligned.
11306                          */
11307                         ASSERT(!((align - (offs & (align - 1))) &
11308                             (sizeof (uint32_t) - 1)));
11309                         DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11310                         offs += sizeof (uint32_t);
11311                 }
11312 
11313                 if ((soffs = offs + needed) > buf->dtb_size) {
11314                         dtrace_buffer_drop(buf);
11315                         return (-1);
11316                 }
11317 
11318                 if (mstate == NULL)
11319                         return (offs);
11320 
11321                 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11322                 mstate->dtms_scratch_size = buf->dtb_size - soffs;
11323                 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11324 
11325                 return (offs);
11326         }
11327 
11328         if (buf->dtb_flags & DTRACEBUF_FILL) {
11329                 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11330                     (buf->dtb_flags & DTRACEBUF_FULL))
11331                         return (-1);
11332                 goto out;
11333         }
11334 
11335         total = needed + (offs & (align - 1));
11336 
11337         /*
11338          * For a ring buffer, life is quite a bit more complicated.  Before
11339          * we can store any padding, we need to adjust our wrapping offset.
11340          * (If we've never before wrapped or we're not about to, no adjustment
11341          * is required.)
11342          */
11343         if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11344             offs + total > buf->dtb_size) {
11345                 woffs = buf->dtb_xamot_offset;
11346 
11347                 if (offs + total > buf->dtb_size) {
11348                         /*
11349                          * We can't fit in the end of the buffer.  First, a
11350                          * sanity check that we can fit in the buffer at all.
11351                          */
11352                         if (total > buf->dtb_size) {
11353                                 dtrace_buffer_drop(buf);
11354                                 return (-1);
11355                         }
11356 
11357                         /*
11358                          * We're going to be storing at the top of the buffer,
11359                          * so now we need to deal with the wrapped offset.  We
11360                          * only reset our wrapped offset to 0 if it is
11361                          * currently greater than the current offset.  If it
11362                          * is less than the current offset, it is because a
11363                          * previous allocation induced a wrap -- but the
11364                          * allocation didn't subsequently take the space due
11365                          * to an error or false predicate evaluation.  In this
11366                          * case, we'll just leave the wrapped offset alone: if
11367                          * the wrapped offset hasn't been advanced far enough
11368                          * for this allocation, it will be adjusted in the
11369                          * lower loop.
11370                          */
11371                         if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11372                                 if (woffs >= offs)
11373                                         woffs = 0;
11374                         } else {
11375                                 woffs = 0;
11376                         }
11377 
11378                         /*
11379                          * Now we know that we're going to be storing to the
11380                          * top of the buffer and that there is room for us
11381                          * there.  We need to clear the buffer from the current
11382                          * offset to the end (there may be old gunk there).
11383                          */
11384                         while (offs < buf->dtb_size)
11385                                 tomax[offs++] = 0;
11386 
11387                         /*
11388                          * We need to set our offset to zero.  And because we
11389                          * are wrapping, we need to set the bit indicating as
11390                          * much.  We can also adjust our needed space back
11391                          * down to the space required by the ECB -- we know
11392                          * that the top of the buffer is aligned.
11393                          */
11394                         offs = 0;
11395                         total = needed;
11396                         buf->dtb_flags |= DTRACEBUF_WRAPPED;
11397                 } else {
11398                         /*
11399                          * There is room for us in the buffer, so we simply
11400                          * need to check the wrapped offset.
11401                          */
11402                         if (woffs < offs) {
11403                                 /*
11404                                  * The wrapped offset is less than the offset.
11405                                  * This can happen if we allocated buffer space
11406                                  * that induced a wrap, but then we didn't
11407                                  * subsequently take the space due to an error
11408                                  * or false predicate evaluation.  This is
11409                                  * okay; we know that _this_ allocation isn't
11410                                  * going to induce a wrap.  We still can't
11411                                  * reset the wrapped offset to be zero,
11412                                  * however: the space may have been trashed in
11413                                  * the previous failed probe attempt.  But at
11414                                  * least the wrapped offset doesn't need to
11415                                  * be adjusted at all...
11416                                  */
11417                                 goto out;
11418                         }
11419                 }
11420 
11421                 while (offs + total > woffs) {
11422                         dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11423                         size_t size;
11424 
11425                         if (epid == DTRACE_EPIDNONE) {
11426                                 size = sizeof (uint32_t);
11427                         } else {
11428                                 ASSERT3U(epid, <=, state->dts_necbs);
11429                                 ASSERT(state->dts_ecbs[epid - 1] != NULL);
11430 
11431                                 size = state->dts_ecbs[epid - 1]->dte_size;
11432                         }
11433 
11434                         ASSERT(woffs + size <= buf->dtb_size);
11435                         ASSERT(size != 0);
11436 
11437                         if (woffs + size == buf->dtb_size) {
11438                                 /*
11439                                  * We've reached the end of the buffer; we want
11440                                  * to set the wrapped offset to 0 and break
11441                                  * out.  However, if the offs is 0, then we're
11442                                  * in a strange edge-condition:  the amount of
11443                                  * space that we want to reserve plus the size
11444                                  * of the record that we're overwriting is
11445                                  * greater than the size of the buffer.  This
11446                                  * is problematic because if we reserve the
11447                                  * space but subsequently don't consume it (due
11448                                  * to a failed predicate or error) the wrapped
11449                                  * offset will be 0 -- yet the EPID at offset 0
11450                                  * will not be committed.  This situation is
11451                                  * relatively easy to deal with:  if we're in
11452                                  * this case, the buffer is indistinguishable
11453                                  * from one that hasn't wrapped; we need only
11454                                  * finish the job by clearing the wrapped bit,
11455                                  * explicitly setting the offset to be 0, and
11456                                  * zero'ing out the old data in the buffer.
11457                                  */
11458                                 if (offs == 0) {
11459                                         buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11460                                         buf->dtb_offset = 0;
11461                                         woffs = total;
11462 
11463                                         while (woffs < buf->dtb_size)
11464                                                 tomax[woffs++] = 0;
11465                                 }
11466 
11467                                 woffs = 0;
11468                                 break;
11469                         }
11470 
11471                         woffs += size;
11472                 }
11473 
11474                 /*
11475                  * We have a wrapped offset.  It may be that the wrapped offset
11476                  * has become zero -- that's okay.
11477                  */
11478                 buf->dtb_xamot_offset = woffs;
11479         }
11480 
11481 out:
11482         /*
11483          * Now we can plow the buffer with any necessary padding.
11484          */
11485         while (offs & (align - 1)) {
11486                 /*
11487                  * Assert that our alignment is off by a number which
11488                  * is itself sizeof (uint32_t) aligned.
11489                  */
11490                 ASSERT(!((align - (offs & (align - 1))) &
11491                     (sizeof (uint32_t) - 1)));
11492                 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11493                 offs += sizeof (uint32_t);
11494         }
11495 
11496         if (buf->dtb_flags & DTRACEBUF_FILL) {
11497                 if (offs + needed > buf->dtb_size - state->dts_reserve) {
11498                         buf->dtb_flags |= DTRACEBUF_FULL;
11499                         return (-1);
11500                 }
11501         }
11502 
11503         if (mstate == NULL)
11504                 return (offs);
11505 
11506         /*
11507          * For ring buffers and fill buffers, the scratch space is always
11508          * the inactive buffer.
11509          */
11510         mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11511         mstate->dtms_scratch_size = buf->dtb_size;
11512         mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11513 
11514         return (offs);
11515 }
11516 
11517 static void
11518 dtrace_buffer_polish(dtrace_buffer_t *buf)
11519 {
11520         ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11521         ASSERT(MUTEX_HELD(&dtrace_lock));
11522 
11523         if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11524                 return;
11525 
11526         /*
11527          * We need to polish the ring buffer.  There are three cases:
11528          *
11529          * - The first (and presumably most common) is that there is no gap
11530          *   between the buffer offset and the wrapped offset.  In this case,
11531          *   there is nothing in the buffer that isn't valid data; we can
11532          *   mark the buffer as polished and return.
11533          *
11534          * - The second (less common than the first but still more common
11535          *   than the third) is that there is a gap between the buffer offset
11536          *   and the wrapped offset, and the wrapped offset is larger than the
11537          *   buffer offset.  This can happen because of an alignment issue, or
11538          *   can happen because of a call to dtrace_buffer_reserve() that
11539          *   didn't subsequently consume the buffer space.  In this case,
11540          *   we need to zero the data from the buffer offset to the wrapped
11541          *   offset.
11542          *
11543          * - The third (and least common) is that there is a gap between the
11544          *   buffer offset and the wrapped offset, but the wrapped offset is
11545          *   _less_ than the buffer offset.  This can only happen because a
11546          *   call to dtrace_buffer_reserve() induced a wrap, but the space
11547          *   was not subsequently consumed.  In this case, we need to zero the
11548          *   space from the offset to the end of the buffer _and_ from the
11549          *   top of the buffer to the wrapped offset.
11550          */
11551         if (buf->dtb_offset < buf->dtb_xamot_offset) {
11552                 bzero(buf->dtb_tomax + buf->dtb_offset,
11553                     buf->dtb_xamot_offset - buf->dtb_offset);
11554         }
11555 
11556         if (buf->dtb_offset > buf->dtb_xamot_offset) {
11557                 bzero(buf->dtb_tomax + buf->dtb_offset,
11558                     buf->dtb_size - buf->dtb_offset);
11559                 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11560         }
11561 }
11562 
11563 /*
11564  * This routine determines if data generated at the specified time has likely
11565  * been entirely consumed at user-level.  This routine is called to determine
11566  * if an ECB on a defunct probe (but for an active enabling) can be safely
11567  * disabled and destroyed.
11568  */
11569 static int
11570 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
11571 {
11572         int i;
11573 
11574         for (i = 0; i < NCPU; i++) {
11575                 dtrace_buffer_t *buf = &bufs[i];
11576 
11577                 if (buf->dtb_size == 0)
11578                         continue;
11579 
11580                 if (buf->dtb_flags & DTRACEBUF_RING)
11581                         return (0);
11582 
11583                 if (!buf->dtb_switched && buf->dtb_offset != 0)
11584                         return (0);
11585 
11586                 if (buf->dtb_switched - buf->dtb_interval < when)
11587                         return (0);
11588         }
11589 
11590         return (1);
11591 }
11592 
11593 static void
11594 dtrace_buffer_free(dtrace_buffer_t *bufs)
11595 {
11596         int i;
11597 
11598         for (i = 0; i < NCPU; i++) {
11599                 dtrace_buffer_t *buf = &bufs[i];
11600 
11601                 if (buf->dtb_tomax == NULL) {
11602                         ASSERT(buf->dtb_xamot == NULL);
11603                         ASSERT(buf->dtb_size == 0);
11604                         continue;
11605                 }
11606 
11607                 if (buf->dtb_xamot != NULL) {
11608                         ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11609                         kmem_free(buf->dtb_xamot, buf->dtb_size);
11610                 }
11611 
11612                 kmem_free(buf->dtb_tomax, buf->dtb_size);
11613                 buf->dtb_size = 0;
11614                 buf->dtb_tomax = NULL;
11615                 buf->dtb_xamot = NULL;
11616         }
11617 }
11618 
11619 /*
11620  * DTrace Enabling Functions
11621  */
11622 static dtrace_enabling_t *
11623 dtrace_enabling_create(dtrace_vstate_t *vstate)
11624 {
11625         dtrace_enabling_t *enab;
11626 
11627         enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11628         enab->dten_vstate = vstate;
11629 
11630         return (enab);
11631 }
11632 
11633 static void
11634 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11635 {
11636         dtrace_ecbdesc_t **ndesc;
11637         size_t osize, nsize;
11638 
11639         /*
11640          * We can't add to enablings after we've enabled them, or after we've
11641          * retained them.
11642          */
11643         ASSERT(enab->dten_probegen == 0);
11644         ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11645 
11646         if (enab->dten_ndesc < enab->dten_maxdesc) {
11647                 enab->dten_desc[enab->dten_ndesc++] = ecb;
11648                 return;
11649         }
11650 
11651         osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11652 
11653         if (enab->dten_maxdesc == 0) {
11654                 enab->dten_maxdesc = 1;
11655         } else {
11656                 enab->dten_maxdesc <<= 1;
11657         }
11658 
11659         ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11660 
11661         nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11662         ndesc = kmem_zalloc(nsize, KM_SLEEP);
11663         bcopy(enab->dten_desc, ndesc, osize);
11664         kmem_free(enab->dten_desc, osize);
11665 
11666         enab->dten_desc = ndesc;
11667         enab->dten_desc[enab->dten_ndesc++] = ecb;
11668 }
11669 
11670 static void
11671 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11672     dtrace_probedesc_t *pd)
11673 {
11674         dtrace_ecbdesc_t *new;
11675         dtrace_predicate_t *pred;
11676         dtrace_actdesc_t *act;
11677 
11678         /*
11679          * We're going to create a new ECB description that matches the
11680          * specified ECB in every way, but has the specified probe description.
11681          */
11682         new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11683 
11684         if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11685                 dtrace_predicate_hold(pred);
11686 
11687         for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11688                 dtrace_actdesc_hold(act);
11689 
11690         new->dted_action = ecb->dted_action;
11691         new->dted_pred = ecb->dted_pred;
11692         new->dted_probe = *pd;
11693         new->dted_uarg = ecb->dted_uarg;
11694 
11695         dtrace_enabling_add(enab, new);
11696 }
11697 
11698 static void
11699 dtrace_enabling_dump(dtrace_enabling_t *enab)
11700 {
11701         int i;
11702 
11703         for (i = 0; i < enab->dten_ndesc; i++) {
11704                 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11705 
11706                 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11707                     desc->dtpd_provider, desc->dtpd_mod,
11708                     desc->dtpd_func, desc->dtpd_name);
11709         }
11710 }
11711 
11712 static void
11713 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11714 {
11715         int i;
11716         dtrace_ecbdesc_t *ep;
11717         dtrace_vstate_t *vstate = enab->dten_vstate;
11718 
11719         ASSERT(MUTEX_HELD(&dtrace_lock));
11720 
11721         for (i = 0; i < enab->dten_ndesc; i++) {
11722                 dtrace_actdesc_t *act, *next;
11723                 dtrace_predicate_t *pred;
11724 
11725                 ep = enab->dten_desc[i];
11726 
11727                 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11728                         dtrace_predicate_release(pred, vstate);
11729 
11730                 for (act = ep->dted_action; act != NULL; act = next) {
11731                         next = act->dtad_next;
11732                         dtrace_actdesc_release(act, vstate);
11733                 }
11734 
11735                 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11736         }
11737 
11738         kmem_free(enab->dten_desc,
11739             enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11740 
11741         /*
11742          * If this was a retained enabling, decrement the dts_nretained count
11743          * and take it off of the dtrace_retained list.
11744          */
11745         if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11746             dtrace_retained == enab) {
11747                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11748                 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11749                 enab->dten_vstate->dtvs_state->dts_nretained--;
11750                 dtrace_retained_gen++;
11751         }
11752 
11753         if (enab->dten_prev == NULL) {
11754                 if (dtrace_retained == enab) {
11755                         dtrace_retained = enab->dten_next;
11756 
11757                         if (dtrace_retained != NULL)
11758                                 dtrace_retained->dten_prev = NULL;
11759                 }
11760         } else {
11761                 ASSERT(enab != dtrace_retained);
11762                 ASSERT(dtrace_retained != NULL);
11763                 enab->dten_prev->dten_next = enab->dten_next;
11764         }
11765 
11766         if (enab->dten_next != NULL) {
11767                 ASSERT(dtrace_retained != NULL);
11768                 enab->dten_next->dten_prev = enab->dten_prev;
11769         }
11770 
11771         kmem_free(enab, sizeof (dtrace_enabling_t));
11772 }
11773 
11774 static int
11775 dtrace_enabling_retain(dtrace_enabling_t *enab)
11776 {
11777         dtrace_state_t *state;
11778 
11779         ASSERT(MUTEX_HELD(&dtrace_lock));
11780         ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11781         ASSERT(enab->dten_vstate != NULL);
11782 
11783         state = enab->dten_vstate->dtvs_state;
11784         ASSERT(state != NULL);
11785 
11786         /*
11787          * We only allow each state to retain dtrace_retain_max enablings.
11788          */
11789         if (state->dts_nretained >= dtrace_retain_max)
11790                 return (ENOSPC);
11791 
11792         state->dts_nretained++;
11793         dtrace_retained_gen++;
11794 
11795         if (dtrace_retained == NULL) {
11796                 dtrace_retained = enab;
11797                 return (0);
11798         }
11799 
11800         enab->dten_next = dtrace_retained;
11801         dtrace_retained->dten_prev = enab;
11802         dtrace_retained = enab;
11803 
11804         return (0);
11805 }
11806 
11807 static int
11808 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11809     dtrace_probedesc_t *create)
11810 {
11811         dtrace_enabling_t *new, *enab;
11812         int found = 0, err = ENOENT;
11813 
11814         ASSERT(MUTEX_HELD(&dtrace_lock));
11815         ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11816         ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11817         ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11818         ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11819 
11820         new = dtrace_enabling_create(&state->dts_vstate);
11821 
11822         /*
11823          * Iterate over all retained enablings, looking for enablings that
11824          * match the specified state.
11825          */
11826         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11827                 int i;
11828 
11829                 /*
11830                  * dtvs_state can only be NULL for helper enablings -- and
11831                  * helper enablings can't be retained.
11832                  */
11833                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11834 
11835                 if (enab->dten_vstate->dtvs_state != state)
11836                         continue;
11837 
11838                 /*
11839                  * Now iterate over each probe description; we're looking for
11840                  * an exact match to the specified probe description.
11841                  */
11842                 for (i = 0; i < enab->dten_ndesc; i++) {
11843                         dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11844                         dtrace_probedesc_t *pd = &ep->dted_probe;
11845 
11846                         if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11847                                 continue;
11848 
11849                         if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11850                                 continue;
11851 
11852                         if (strcmp(pd->dtpd_func, match->dtpd_func))
11853                                 continue;
11854 
11855                         if (strcmp(pd->dtpd_name, match->dtpd_name))
11856                                 continue;
11857 
11858                         /*
11859                          * We have a winning probe!  Add it to our growing
11860                          * enabling.
11861                          */
11862                         found = 1;
11863                         dtrace_enabling_addlike(new, ep, create);
11864                 }
11865         }
11866 
11867         if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11868                 dtrace_enabling_destroy(new);
11869                 return (err);
11870         }
11871 
11872         return (0);
11873 }
11874 
11875 static void
11876 dtrace_enabling_retract(dtrace_state_t *state)
11877 {
11878         dtrace_enabling_t *enab, *next;
11879 
11880         ASSERT(MUTEX_HELD(&dtrace_lock));
11881 
11882         /*
11883          * Iterate over all retained enablings, destroy the enablings retained
11884          * for the specified state.
11885          */
11886         for (enab = dtrace_retained; enab != NULL; enab = next) {
11887                 next = enab->dten_next;
11888 
11889                 /*
11890                  * dtvs_state can only be NULL for helper enablings -- and
11891                  * helper enablings can't be retained.
11892                  */
11893                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11894 
11895                 if (enab->dten_vstate->dtvs_state == state) {
11896                         ASSERT(state->dts_nretained > 0);
11897                         dtrace_enabling_destroy(enab);
11898                 }
11899         }
11900 
11901         ASSERT(state->dts_nretained == 0);
11902 }
11903 
11904 static int
11905 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11906 {
11907         int i = 0;
11908         int total_matched = 0, matched = 0;
11909 
11910         ASSERT(MUTEX_HELD(&cpu_lock));
11911         ASSERT(MUTEX_HELD(&dtrace_lock));
11912 
11913         for (i = 0; i < enab->dten_ndesc; i++) {
11914                 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11915 
11916                 enab->dten_current = ep;
11917                 enab->dten_error = 0;
11918 
11919                 /*
11920                  * If a provider failed to enable a probe then get out and
11921                  * let the consumer know we failed.
11922                  */
11923                 if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
11924                         return (EBUSY);
11925 
11926                 total_matched += matched;
11927 
11928                 if (enab->dten_error != 0) {
11929                         /*
11930                          * If we get an error half-way through enabling the
11931                          * probes, we kick out -- perhaps with some number of
11932                          * them enabled.  Leaving enabled probes enabled may
11933                          * be slightly confusing for user-level, but we expect
11934                          * that no one will attempt to actually drive on in
11935                          * the face of such errors.  If this is an anonymous
11936                          * enabling (indicated with a NULL nmatched pointer),
11937                          * we cmn_err() a message.  We aren't expecting to
11938                          * get such an error -- such as it can exist at all,
11939                          * it would be a result of corrupted DOF in the driver
11940                          * properties.
11941                          */
11942                         if (nmatched == NULL) {
11943                                 cmn_err(CE_WARN, "dtrace_enabling_match() "
11944                                     "error on %p: %d", (void *)ep,
11945                                     enab->dten_error);
11946                         }
11947 
11948                         return (enab->dten_error);
11949                 }
11950         }
11951 
11952         enab->dten_probegen = dtrace_probegen;
11953         if (nmatched != NULL)
11954                 *nmatched = total_matched;
11955 
11956         return (0);
11957 }
11958 
11959 static void
11960 dtrace_enabling_matchall(void)
11961 {
11962         dtrace_enabling_t *enab;
11963 
11964         mutex_enter(&cpu_lock);
11965         mutex_enter(&dtrace_lock);
11966 
11967         /*
11968          * Iterate over all retained enablings to see if any probes match
11969          * against them.  We only perform this operation on enablings for which
11970          * we have sufficient permissions by virtue of being in the global zone
11971          * or in the same zone as the DTrace client.  Because we can be called
11972          * after dtrace_detach() has been called, we cannot assert that there
11973          * are retained enablings.  We can safely load from dtrace_retained,
11974          * however:  the taskq_destroy() at the end of dtrace_detach() will
11975          * block pending our completion.
11976          */
11977         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11978                 dtrace_cred_t *dcr = &enab->dten_vstate->dtvs_state->dts_cred;
11979                 cred_t *cr = dcr->dcr_cred;
11980                 zoneid_t zone = cr != NULL ? crgetzoneid(cr) : 0;
11981 
11982                 if ((dcr->dcr_visible & DTRACE_CRV_ALLZONE) || (cr != NULL &&
11983                     (zone == GLOBAL_ZONEID || getzoneid() == zone)))
11984                         (void) dtrace_enabling_match(enab, NULL);
11985         }
11986 
11987         mutex_exit(&dtrace_lock);
11988         mutex_exit(&cpu_lock);
11989 }
11990 
11991 /*
11992  * If an enabling is to be enabled without having matched probes (that is, if
11993  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11994  * enabling must be _primed_ by creating an ECB for every ECB description.
11995  * This must be done to assure that we know the number of speculations, the
11996  * number of aggregations, the minimum buffer size needed, etc. before we
11997  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
11998  * enabling any probes, we create ECBs for every ECB decription, but with a
11999  * NULL probe -- which is exactly what this function does.
12000  */
12001 static void
12002 dtrace_enabling_prime(dtrace_state_t *state)
12003 {
12004         dtrace_enabling_t *enab;
12005         int i;
12006 
12007         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12008                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
12009 
12010                 if (enab->dten_vstate->dtvs_state != state)
12011                         continue;
12012 
12013                 /*
12014                  * We don't want to prime an enabling more than once, lest
12015                  * we allow a malicious user to induce resource exhaustion.
12016                  * (The ECBs that result from priming an enabling aren't
12017                  * leaked -- but they also aren't deallocated until the
12018                  * consumer state is destroyed.)
12019                  */
12020                 if (enab->dten_primed)
12021                         continue;
12022 
12023                 for (i = 0; i < enab->dten_ndesc; i++) {
12024                         enab->dten_current = enab->dten_desc[i];
12025                         (void) dtrace_probe_enable(NULL, enab);
12026                 }
12027 
12028                 enab->dten_primed = 1;
12029         }
12030 }
12031 
12032 /*
12033  * Called to indicate that probes should be provided due to retained
12034  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
12035  * must take an initial lap through the enabling calling the dtps_provide()
12036  * entry point explicitly to allow for autocreated probes.
12037  */
12038 static void
12039 dtrace_enabling_provide(dtrace_provider_t *prv)
12040 {
12041         int i, all = 0;
12042         dtrace_probedesc_t desc;
12043         dtrace_genid_t gen;
12044 
12045         ASSERT(MUTEX_HELD(&dtrace_lock));
12046         ASSERT(MUTEX_HELD(&dtrace_provider_lock));
12047 
12048         if (prv == NULL) {
12049                 all = 1;
12050                 prv = dtrace_provider;
12051         }
12052 
12053         do {
12054                 dtrace_enabling_t *enab;
12055                 void *parg = prv->dtpv_arg;
12056 
12057 retry:
12058                 gen = dtrace_retained_gen;
12059                 for (enab = dtrace_retained; enab != NULL;
12060                     enab = enab->dten_next) {
12061                         for (i = 0; i < enab->dten_ndesc; i++) {
12062                                 desc = enab->dten_desc[i]->dted_probe;
12063                                 mutex_exit(&dtrace_lock);
12064                                 prv->dtpv_pops.dtps_provide(parg, &desc);
12065                                 mutex_enter(&dtrace_lock);
12066                                 /*
12067                                  * Process the retained enablings again if
12068                                  * they have changed while we weren't holding
12069                                  * dtrace_lock.
12070                                  */
12071                                 if (gen != dtrace_retained_gen)
12072                                         goto retry;
12073                         }
12074                 }
12075         } while (all && (prv = prv->dtpv_next) != NULL);
12076 
12077         mutex_exit(&dtrace_lock);
12078         dtrace_probe_provide(NULL, all ? NULL : prv);
12079         mutex_enter(&dtrace_lock);
12080 }
12081 
12082 /*
12083  * Called to reap ECBs that are attached to probes from defunct providers.
12084  */
12085 static void
12086 dtrace_enabling_reap(void)
12087 {
12088         dtrace_provider_t *prov;
12089         dtrace_probe_t *probe;
12090         dtrace_ecb_t *ecb;
12091         hrtime_t when;
12092         int i;
12093 
12094         mutex_enter(&cpu_lock);
12095         mutex_enter(&dtrace_lock);
12096 
12097         for (i = 0; i < dtrace_nprobes; i++) {
12098                 if ((probe = dtrace_probes[i]) == NULL)
12099                         continue;
12100 
12101                 if (probe->dtpr_ecb == NULL)
12102                         continue;
12103 
12104                 prov = probe->dtpr_provider;
12105 
12106                 if ((when = prov->dtpv_defunct) == 0)
12107                         continue;
12108 
12109                 /*
12110                  * We have ECBs on a defunct provider:  we want to reap these
12111                  * ECBs to allow the provider to unregister.  The destruction
12112                  * of these ECBs must be done carefully:  if we destroy the ECB
12113                  * and the consumer later wishes to consume an EPID that
12114                  * corresponds to the destroyed ECB (and if the EPID metadata
12115                  * has not been previously consumed), the consumer will abort
12116                  * processing on the unknown EPID.  To reduce (but not, sadly,
12117                  * eliminate) the possibility of this, we will only destroy an
12118                  * ECB for a defunct provider if, for the state that
12119                  * corresponds to the ECB:
12120                  *
12121                  *  (a) There is no speculative tracing (which can effectively
12122                  *      cache an EPID for an arbitrary amount of time).
12123                  *
12124                  *  (b) The principal buffers have been switched twice since the
12125                  *      provider became defunct.
12126                  *
12127                  *  (c) The aggregation buffers are of zero size or have been
12128                  *      switched twice since the provider became defunct.
12129                  *
12130                  * We use dts_speculates to determine (a) and call a function
12131                  * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
12132                  * that as soon as we've been unable to destroy one of the ECBs
12133                  * associated with the probe, we quit trying -- reaping is only
12134                  * fruitful in as much as we can destroy all ECBs associated
12135                  * with the defunct provider's probes.
12136                  */
12137                 while ((ecb = probe->dtpr_ecb) != NULL) {
12138                         dtrace_state_t *state = ecb->dte_state;
12139                         dtrace_buffer_t *buf = state->dts_buffer;
12140                         dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12141 
12142                         if (state->dts_speculates)
12143                                 break;
12144 
12145                         if (!dtrace_buffer_consumed(buf, when))
12146                                 break;
12147 
12148                         if (!dtrace_buffer_consumed(aggbuf, when))
12149                                 break;
12150 
12151                         dtrace_ecb_disable(ecb);
12152                         ASSERT(probe->dtpr_ecb != ecb);
12153                         dtrace_ecb_destroy(ecb);
12154                 }
12155         }
12156 
12157         mutex_exit(&dtrace_lock);
12158         mutex_exit(&cpu_lock);
12159 }
12160 
12161 /*
12162  * DTrace DOF Functions
12163  */
12164 /*ARGSUSED*/
12165 static void
12166 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12167 {
12168         if (dtrace_err_verbose)
12169                 cmn_err(CE_WARN, "failed to process DOF: %s", str);
12170 
12171 #ifdef DTRACE_ERRDEBUG
12172         dtrace_errdebug(str);
12173 #endif
12174 }
12175 
12176 /*
12177  * Create DOF out of a currently enabled state.  Right now, we only create
12178  * DOF containing the run-time options -- but this could be expanded to create
12179  * complete DOF representing the enabled state.
12180  */
12181 static dof_hdr_t *
12182 dtrace_dof_create(dtrace_state_t *state)
12183 {
12184         dof_hdr_t *dof;
12185         dof_sec_t *sec;
12186         dof_optdesc_t *opt;
12187         int i, len = sizeof (dof_hdr_t) +
12188             roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12189             sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12190 
12191         ASSERT(MUTEX_HELD(&dtrace_lock));
12192 
12193         dof = kmem_zalloc(len, KM_SLEEP);
12194         dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12195         dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12196         dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12197         dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12198 
12199         dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12200         dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12201         dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12202         dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12203         dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12204         dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12205 
12206         dof->dofh_flags = 0;
12207         dof->dofh_hdrsize = sizeof (dof_hdr_t);
12208         dof->dofh_secsize = sizeof (dof_sec_t);
12209         dof->dofh_secnum = 1;        /* only DOF_SECT_OPTDESC */
12210         dof->dofh_secoff = sizeof (dof_hdr_t);
12211         dof->dofh_loadsz = len;
12212         dof->dofh_filesz = len;
12213         dof->dofh_pad = 0;
12214 
12215         /*
12216          * Fill in the option section header...
12217          */
12218         sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12219         sec->dofs_type = DOF_SECT_OPTDESC;
12220         sec->dofs_align = sizeof (uint64_t);
12221         sec->dofs_flags = DOF_SECF_LOAD;
12222         sec->dofs_entsize = sizeof (dof_optdesc_t);
12223 
12224         opt = (dof_optdesc_t *)((uintptr_t)sec +
12225             roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12226 
12227         sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12228         sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12229 
12230         for (i = 0; i < DTRACEOPT_MAX; i++) {
12231                 opt[i].dofo_option = i;
12232                 opt[i].dofo_strtab = DOF_SECIDX_NONE;
12233                 opt[i].dofo_value = state->dts_options[i];
12234         }
12235 
12236         return (dof);
12237 }
12238 
12239 static dof_hdr_t *
12240 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12241 {
12242         dof_hdr_t hdr, *dof;
12243 
12244         ASSERT(!MUTEX_HELD(&dtrace_lock));
12245 
12246         /*
12247          * First, we're going to copyin() the sizeof (dof_hdr_t).
12248          */
12249         if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
12250                 dtrace_dof_error(NULL, "failed to copyin DOF header");
12251                 *errp = EFAULT;
12252                 return (NULL);
12253         }
12254 
12255         /*
12256          * Now we'll allocate the entire DOF and copy it in -- provided
12257          * that the length isn't outrageous.
12258          */
12259         if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12260                 dtrace_dof_error(&hdr, "load size exceeds maximum");
12261                 *errp = E2BIG;
12262                 return (NULL);
12263         }
12264 
12265         if (hdr.dofh_loadsz < sizeof (hdr)) {
12266                 dtrace_dof_error(&hdr, "invalid load size");
12267                 *errp = EINVAL;
12268                 return (NULL);
12269         }
12270 
12271         dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12272 
12273         if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
12274             dof->dofh_loadsz != hdr.dofh_loadsz) {
12275                 kmem_free(dof, hdr.dofh_loadsz);
12276                 *errp = EFAULT;
12277                 return (NULL);
12278         }
12279 
12280         return (dof);
12281 }
12282 
12283 static dof_hdr_t *
12284 dtrace_dof_property(const char *name)
12285 {
12286         uchar_t *buf;
12287         uint64_t loadsz;
12288         unsigned int len, i;
12289         dof_hdr_t *dof;
12290 
12291         /*
12292          * Unfortunately, array of values in .conf files are always (and
12293          * only) interpreted to be integer arrays.  We must read our DOF
12294          * as an integer array, and then squeeze it into a byte array.
12295          */
12296         if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12297             (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12298                 return (NULL);
12299 
12300         for (i = 0; i < len; i++)
12301                 buf[i] = (uchar_t)(((int *)buf)[i]);
12302 
12303         if (len < sizeof (dof_hdr_t)) {
12304                 ddi_prop_free(buf);
12305                 dtrace_dof_error(NULL, "truncated header");
12306                 return (NULL);
12307         }
12308 
12309         if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12310                 ddi_prop_free(buf);
12311                 dtrace_dof_error(NULL, "truncated DOF");
12312                 return (NULL);
12313         }
12314 
12315         if (loadsz >= dtrace_dof_maxsize) {
12316                 ddi_prop_free(buf);
12317                 dtrace_dof_error(NULL, "oversized DOF");
12318                 return (NULL);
12319         }
12320 
12321         dof = kmem_alloc(loadsz, KM_SLEEP);
12322         bcopy(buf, dof, loadsz);
12323         ddi_prop_free(buf);
12324 
12325         return (dof);
12326 }
12327 
12328 static void
12329 dtrace_dof_destroy(dof_hdr_t *dof)
12330 {
12331         kmem_free(dof, dof->dofh_loadsz);
12332 }
12333 
12334 /*
12335  * Return the dof_sec_t pointer corresponding to a given section index.  If the
12336  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
12337  * a type other than DOF_SECT_NONE is specified, the header is checked against
12338  * this type and NULL is returned if the types do not match.
12339  */
12340 static dof_sec_t *
12341 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12342 {
12343         dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12344             ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12345 
12346         if (i >= dof->dofh_secnum) {
12347                 dtrace_dof_error(dof, "referenced section index is invalid");
12348                 return (NULL);
12349         }
12350 
12351         if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12352                 dtrace_dof_error(dof, "referenced section is not loadable");
12353                 return (NULL);
12354         }
12355 
12356         if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12357                 dtrace_dof_error(dof, "referenced section is the wrong type");
12358                 return (NULL);
12359         }
12360 
12361         return (sec);
12362 }
12363 
12364 static dtrace_probedesc_t *
12365 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12366 {
12367         dof_probedesc_t *probe;
12368         dof_sec_t *strtab;
12369         uintptr_t daddr = (uintptr_t)dof;
12370         uintptr_t str;
12371         size_t size;
12372 
12373         if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12374                 dtrace_dof_error(dof, "invalid probe section");
12375                 return (NULL);
12376         }
12377 
12378         if (sec->dofs_align != sizeof (dof_secidx_t)) {
12379                 dtrace_dof_error(dof, "bad alignment in probe description");
12380                 return (NULL);
12381         }
12382 
12383         if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12384                 dtrace_dof_error(dof, "truncated probe description");
12385                 return (NULL);
12386         }
12387 
12388         probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12389         strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12390 
12391         if (strtab == NULL)
12392                 return (NULL);
12393 
12394         str = daddr + strtab->dofs_offset;
12395         size = strtab->dofs_size;
12396 
12397         if (probe->dofp_provider >= strtab->dofs_size) {
12398                 dtrace_dof_error(dof, "corrupt probe provider");
12399                 return (NULL);
12400         }
12401 
12402         (void) strncpy(desc->dtpd_provider,
12403             (char *)(str + probe->dofp_provider),
12404             MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12405 
12406         if (probe->dofp_mod >= strtab->dofs_size) {
12407                 dtrace_dof_error(dof, "corrupt probe module");
12408                 return (NULL);
12409         }
12410 
12411         (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12412             MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12413 
12414         if (probe->dofp_func >= strtab->dofs_size) {
12415                 dtrace_dof_error(dof, "corrupt probe function");
12416                 return (NULL);
12417         }
12418 
12419         (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12420             MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12421 
12422         if (probe->dofp_name >= strtab->dofs_size) {
12423                 dtrace_dof_error(dof, "corrupt probe name");
12424                 return (NULL);
12425         }
12426 
12427         (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12428             MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12429 
12430         return (desc);
12431 }
12432 
12433 static dtrace_difo_t *
12434 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12435     cred_t *cr)
12436 {
12437         dtrace_difo_t *dp;
12438         size_t ttl = 0;
12439         dof_difohdr_t *dofd;
12440         uintptr_t daddr = (uintptr_t)dof;
12441         size_t max = dtrace_difo_maxsize;
12442         int i, l, n;
12443 
12444         static const struct {
12445                 int section;
12446                 int bufoffs;
12447                 int lenoffs;
12448                 int entsize;
12449                 int align;
12450                 const char *msg;
12451         } difo[] = {
12452                 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12453                 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12454                 sizeof (dif_instr_t), "multiple DIF sections" },
12455 
12456                 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12457                 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12458                 sizeof (uint64_t), "multiple integer tables" },
12459 
12460                 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12461                 offsetof(dtrace_difo_t, dtdo_strlen), 0,
12462                 sizeof (char), "multiple string tables" },
12463 
12464                 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12465                 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12466                 sizeof (uint_t), "multiple variable tables" },
12467 
12468                 { DOF_SECT_NONE, 0, 0, 0, NULL }
12469         };
12470 
12471         if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12472                 dtrace_dof_error(dof, "invalid DIFO header section");
12473                 return (NULL);
12474         }
12475 
12476         if (sec->dofs_align != sizeof (dof_secidx_t)) {
12477                 dtrace_dof_error(dof, "bad alignment in DIFO header");
12478                 return (NULL);
12479         }
12480 
12481         if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12482             sec->dofs_size % sizeof (dof_secidx_t)) {
12483                 dtrace_dof_error(dof, "bad size in DIFO header");
12484                 return (NULL);
12485         }
12486 
12487         dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12488         n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12489 
12490         dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12491         dp->dtdo_rtype = dofd->dofd_rtype;
12492 
12493         for (l = 0; l < n; l++) {
12494                 dof_sec_t *subsec;
12495                 void **bufp;
12496                 uint32_t *lenp;
12497 
12498                 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12499                     dofd->dofd_links[l])) == NULL)
12500                         goto err; /* invalid section link */
12501 
12502                 if (ttl + subsec->dofs_size > max) {
12503                         dtrace_dof_error(dof, "exceeds maximum size");
12504                         goto err;
12505                 }
12506 
12507                 ttl += subsec->dofs_size;
12508 
12509                 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12510                         if (subsec->dofs_type != difo[i].section)
12511                                 continue;
12512 
12513                         if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12514                                 dtrace_dof_error(dof, "section not loaded");
12515                                 goto err;
12516                         }
12517 
12518                         if (subsec->dofs_align != difo[i].align) {
12519                                 dtrace_dof_error(dof, "bad alignment");
12520                                 goto err;
12521                         }
12522 
12523                         bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12524                         lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12525 
12526                         if (*bufp != NULL) {
12527                                 dtrace_dof_error(dof, difo[i].msg);
12528                                 goto err;
12529                         }
12530 
12531                         if (difo[i].entsize != subsec->dofs_entsize) {
12532                                 dtrace_dof_error(dof, "entry size mismatch");
12533                                 goto err;
12534                         }
12535 
12536                         if (subsec->dofs_entsize != 0 &&
12537                             (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12538                                 dtrace_dof_error(dof, "corrupt entry size");
12539                                 goto err;
12540                         }
12541 
12542                         *lenp = subsec->dofs_size;
12543                         *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12544                         bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12545                             *bufp, subsec->dofs_size);
12546 
12547                         if (subsec->dofs_entsize != 0)
12548                                 *lenp /= subsec->dofs_entsize;
12549 
12550                         break;
12551                 }
12552 
12553                 /*
12554                  * If we encounter a loadable DIFO sub-section that is not
12555                  * known to us, assume this is a broken program and fail.
12556                  */
12557                 if (difo[i].section == DOF_SECT_NONE &&
12558                     (subsec->dofs_flags & DOF_SECF_LOAD)) {
12559                         dtrace_dof_error(dof, "unrecognized DIFO subsection");
12560                         goto err;
12561                 }
12562         }
12563 
12564         if (dp->dtdo_buf == NULL) {
12565                 /*
12566                  * We can't have a DIF object without DIF text.
12567                  */
12568                 dtrace_dof_error(dof, "missing DIF text");
12569                 goto err;
12570         }
12571 
12572         /*
12573          * Before we validate the DIF object, run through the variable table
12574          * looking for the strings -- if any of their size are under, we'll set
12575          * their size to be the system-wide default string size.  Note that
12576          * this should _not_ happen if the "strsize" option has been set --
12577          * in this case, the compiler should have set the size to reflect the
12578          * setting of the option.
12579          */
12580         for (i = 0; i < dp->dtdo_varlen; i++) {
12581                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
12582                 dtrace_diftype_t *t = &v->dtdv_type;
12583 
12584                 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12585                         continue;
12586 
12587                 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12588                         t->dtdt_size = dtrace_strsize_default;
12589         }
12590 
12591         if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12592                 goto err;
12593 
12594         dtrace_difo_init(dp, vstate);
12595         return (dp);
12596 
12597 err:
12598         kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12599         kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12600         kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12601         kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12602 
12603         kmem_free(dp, sizeof (dtrace_difo_t));
12604         return (NULL);
12605 }
12606 
12607 static dtrace_predicate_t *
12608 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12609     cred_t *cr)
12610 {
12611         dtrace_difo_t *dp;
12612 
12613         if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12614                 return (NULL);
12615 
12616         return (dtrace_predicate_create(dp));
12617 }
12618 
12619 static dtrace_actdesc_t *
12620 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12621     cred_t *cr)
12622 {
12623         dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12624         dof_actdesc_t *desc;
12625         dof_sec_t *difosec;
12626         size_t offs;
12627         uintptr_t daddr = (uintptr_t)dof;
12628         uint64_t arg;
12629         dtrace_actkind_t kind;
12630 
12631         if (sec->dofs_type != DOF_SECT_ACTDESC) {
12632                 dtrace_dof_error(dof, "invalid action section");
12633                 return (NULL);
12634         }
12635 
12636         if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12637                 dtrace_dof_error(dof, "truncated action description");
12638                 return (NULL);
12639         }
12640 
12641         if (sec->dofs_align != sizeof (uint64_t)) {
12642                 dtrace_dof_error(dof, "bad alignment in action description");
12643                 return (NULL);
12644         }
12645 
12646         if (sec->dofs_size < sec->dofs_entsize) {
12647                 dtrace_dof_error(dof, "section entry size exceeds total size");
12648                 return (NULL);
12649         }
12650 
12651         if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12652                 dtrace_dof_error(dof, "bad entry size in action description");
12653                 return (NULL);
12654         }
12655 
12656         if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12657                 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12658                 return (NULL);
12659         }
12660 
12661         for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12662                 desc = (dof_actdesc_t *)(daddr +
12663                     (uintptr_t)sec->dofs_offset + offs);
12664                 kind = (dtrace_actkind_t)desc->dofa_kind;
12665 
12666                 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12667                     (kind != DTRACEACT_PRINTA ||
12668                     desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12669                     (kind == DTRACEACT_DIFEXPR &&
12670                     desc->dofa_strtab != DOF_SECIDX_NONE)) {
12671                         dof_sec_t *strtab;
12672                         char *str, *fmt;
12673                         uint64_t i;
12674 
12675                         /*
12676                          * The argument to these actions is an index into the
12677                          * DOF string table.  For printf()-like actions, this
12678                          * is the format string.  For print(), this is the
12679                          * CTF type of the expression result.
12680                          */
12681                         if ((strtab = dtrace_dof_sect(dof,
12682                             DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12683                                 goto err;
12684 
12685                         str = (char *)((uintptr_t)dof +
12686                             (uintptr_t)strtab->dofs_offset);
12687 
12688                         for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12689                                 if (str[i] == '\0')
12690                                         break;
12691                         }
12692 
12693                         if (i >= strtab->dofs_size) {
12694                                 dtrace_dof_error(dof, "bogus format string");
12695                                 goto err;
12696                         }
12697 
12698                         if (i == desc->dofa_arg) {
12699                                 dtrace_dof_error(dof, "empty format string");
12700                                 goto err;
12701                         }
12702 
12703                         i -= desc->dofa_arg;
12704                         fmt = kmem_alloc(i + 1, KM_SLEEP);
12705                         bcopy(&str[desc->dofa_arg], fmt, i + 1);
12706                         arg = (uint64_t)(uintptr_t)fmt;
12707                 } else {
12708                         if (kind == DTRACEACT_PRINTA) {
12709                                 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12710                                 arg = 0;
12711                         } else {
12712                                 arg = desc->dofa_arg;
12713                         }
12714                 }
12715 
12716                 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12717                     desc->dofa_uarg, arg);
12718 
12719                 if (last != NULL) {
12720                         last->dtad_next = act;
12721                 } else {
12722                         first = act;
12723                 }
12724 
12725                 last = act;
12726 
12727                 if (desc->dofa_difo == DOF_SECIDX_NONE)
12728                         continue;
12729 
12730                 if ((difosec = dtrace_dof_sect(dof,
12731                     DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12732                         goto err;
12733 
12734                 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12735 
12736                 if (act->dtad_difo == NULL)
12737                         goto err;
12738         }
12739 
12740         ASSERT(first != NULL);
12741         return (first);
12742 
12743 err:
12744         for (act = first; act != NULL; act = next) {
12745                 next = act->dtad_next;
12746                 dtrace_actdesc_release(act, vstate);
12747         }
12748 
12749         return (NULL);
12750 }
12751 
12752 static dtrace_ecbdesc_t *
12753 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12754     cred_t *cr)
12755 {
12756         dtrace_ecbdesc_t *ep;
12757         dof_ecbdesc_t *ecb;
12758         dtrace_probedesc_t *desc;
12759         dtrace_predicate_t *pred = NULL;
12760 
12761         if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12762                 dtrace_dof_error(dof, "truncated ECB description");
12763                 return (NULL);
12764         }
12765 
12766         if (sec->dofs_align != sizeof (uint64_t)) {
12767                 dtrace_dof_error(dof, "bad alignment in ECB description");
12768                 return (NULL);
12769         }
12770 
12771         ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12772         sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12773 
12774         if (sec == NULL)
12775                 return (NULL);
12776 
12777         ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12778         ep->dted_uarg = ecb->dofe_uarg;
12779         desc = &ep->dted_probe;
12780 
12781         if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12782                 goto err;
12783 
12784         if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12785                 if ((sec = dtrace_dof_sect(dof,
12786                     DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12787                         goto err;
12788 
12789                 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12790                         goto err;
12791 
12792                 ep->dted_pred.dtpdd_predicate = pred;
12793         }
12794 
12795         if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12796                 if ((sec = dtrace_dof_sect(dof,
12797                     DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12798                         goto err;
12799 
12800                 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12801 
12802                 if (ep->dted_action == NULL)
12803                         goto err;
12804         }
12805 
12806         return (ep);
12807 
12808 err:
12809         if (pred != NULL)
12810                 dtrace_predicate_release(pred, vstate);
12811         kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12812         return (NULL);
12813 }
12814 
12815 /*
12816  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12817  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
12818  * site of any user SETX relocations to account for load object base address.
12819  * In the future, if we need other relocations, this function can be extended.
12820  */
12821 static int
12822 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12823 {
12824         uintptr_t daddr = (uintptr_t)dof;
12825         dof_relohdr_t *dofr =
12826             (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12827         dof_sec_t *ss, *rs, *ts;
12828         dof_relodesc_t *r;
12829         uint_t i, n;
12830 
12831         if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12832             sec->dofs_align != sizeof (dof_secidx_t)) {
12833                 dtrace_dof_error(dof, "invalid relocation header");
12834                 return (-1);
12835         }
12836 
12837         ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12838         rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12839         ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12840 
12841         if (ss == NULL || rs == NULL || ts == NULL)
12842                 return (-1); /* dtrace_dof_error() has been called already */
12843 
12844         if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12845             rs->dofs_align != sizeof (uint64_t)) {
12846                 dtrace_dof_error(dof, "invalid relocation section");
12847                 return (-1);
12848         }
12849 
12850         r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12851         n = rs->dofs_size / rs->dofs_entsize;
12852 
12853         for (i = 0; i < n; i++) {
12854                 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12855 
12856                 switch (r->dofr_type) {
12857                 case DOF_RELO_NONE:
12858                         break;
12859                 case DOF_RELO_SETX:
12860                         if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12861                             sizeof (uint64_t) > ts->dofs_size) {
12862                                 dtrace_dof_error(dof, "bad relocation offset");
12863                                 return (-1);
12864                         }
12865 
12866                         if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12867                                 dtrace_dof_error(dof, "misaligned setx relo");
12868                                 return (-1);
12869                         }
12870 
12871                         *(uint64_t *)taddr += ubase;
12872                         break;
12873                 default:
12874                         dtrace_dof_error(dof, "invalid relocation type");
12875                         return (-1);
12876                 }
12877 
12878                 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12879         }
12880 
12881         return (0);
12882 }
12883 
12884 /*
12885  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12886  * header:  it should be at the front of a memory region that is at least
12887  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12888  * size.  It need not be validated in any other way.
12889  */
12890 static int
12891 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12892     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12893 {
12894         uint64_t len = dof->dofh_loadsz, seclen;
12895         uintptr_t daddr = (uintptr_t)dof;
12896         dtrace_ecbdesc_t *ep;
12897         dtrace_enabling_t *enab;
12898         uint_t i;
12899 
12900         ASSERT(MUTEX_HELD(&dtrace_lock));
12901         ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12902 
12903         /*
12904          * Check the DOF header identification bytes.  In addition to checking
12905          * valid settings, we also verify that unused bits/bytes are zeroed so
12906          * we can use them later without fear of regressing existing binaries.
12907          */
12908         if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12909             DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12910                 dtrace_dof_error(dof, "DOF magic string mismatch");
12911                 return (-1);
12912         }
12913 
12914         if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12915             dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12916                 dtrace_dof_error(dof, "DOF has invalid data model");
12917                 return (-1);
12918         }
12919 
12920         if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12921                 dtrace_dof_error(dof, "DOF encoding mismatch");
12922                 return (-1);
12923         }
12924 
12925         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12926             dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12927                 dtrace_dof_error(dof, "DOF version mismatch");
12928                 return (-1);
12929         }
12930 
12931         if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12932                 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12933                 return (-1);
12934         }
12935 
12936         if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12937                 dtrace_dof_error(dof, "DOF uses too many integer registers");
12938                 return (-1);
12939         }
12940 
12941         if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12942                 dtrace_dof_error(dof, "DOF uses too many tuple registers");
12943                 return (-1);
12944         }
12945 
12946         for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12947                 if (dof->dofh_ident[i] != 0) {
12948                         dtrace_dof_error(dof, "DOF has invalid ident byte set");
12949                         return (-1);
12950                 }
12951         }
12952 
12953         if (dof->dofh_flags & ~DOF_FL_VALID) {
12954                 dtrace_dof_error(dof, "DOF has invalid flag bits set");
12955                 return (-1);
12956         }
12957 
12958         if (dof->dofh_secsize == 0) {
12959                 dtrace_dof_error(dof, "zero section header size");
12960                 return (-1);
12961         }
12962 
12963         /*
12964          * Check that the section headers don't exceed the amount of DOF
12965          * data.  Note that we cast the section size and number of sections
12966          * to uint64_t's to prevent possible overflow in the multiplication.
12967          */
12968         seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12969 
12970         if (dof->dofh_secoff > len || seclen > len ||
12971             dof->dofh_secoff + seclen > len) {
12972                 dtrace_dof_error(dof, "truncated section headers");
12973                 return (-1);
12974         }
12975 
12976         if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12977                 dtrace_dof_error(dof, "misaligned section headers");
12978                 return (-1);
12979         }
12980 
12981         if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12982                 dtrace_dof_error(dof, "misaligned section size");
12983                 return (-1);
12984         }
12985 
12986         /*
12987          * Take an initial pass through the section headers to be sure that
12988          * the headers don't have stray offsets.  If the 'noprobes' flag is
12989          * set, do not permit sections relating to providers, probes, or args.
12990          */
12991         for (i = 0; i < dof->dofh_secnum; i++) {
12992                 dof_sec_t *sec = (dof_sec_t *)(daddr +
12993                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12994 
12995                 if (noprobes) {
12996                         switch (sec->dofs_type) {
12997                         case DOF_SECT_PROVIDER:
12998                         case DOF_SECT_PROBES:
12999                         case DOF_SECT_PRARGS:
13000                         case DOF_SECT_PROFFS:
13001                                 dtrace_dof_error(dof, "illegal sections "
13002                                     "for enabling");
13003                                 return (-1);
13004                         }
13005                 }
13006 
13007                 if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
13008                     !(sec->dofs_flags & DOF_SECF_LOAD)) {
13009                         dtrace_dof_error(dof, "loadable section with load "
13010                             "flag unset");
13011                         return (-1);
13012                 }
13013 
13014                 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13015                         continue; /* just ignore non-loadable sections */
13016 
13017                 if (sec->dofs_align & (sec->dofs_align - 1)) {
13018                         dtrace_dof_error(dof, "bad section alignment");
13019                         return (-1);
13020                 }
13021 
13022                 if (sec->dofs_offset & (sec->dofs_align - 1)) {
13023                         dtrace_dof_error(dof, "misaligned section");
13024                         return (-1);
13025                 }
13026 
13027                 if (sec->dofs_offset > len || sec->dofs_size > len ||
13028                     sec->dofs_offset + sec->dofs_size > len) {
13029                         dtrace_dof_error(dof, "corrupt section header");
13030                         return (-1);
13031                 }
13032 
13033                 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13034                     sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13035                         dtrace_dof_error(dof, "non-terminating string table");
13036                         return (-1);
13037                 }
13038         }
13039 
13040         /*
13041          * Take a second pass through the sections and locate and perform any
13042          * relocations that are present.  We do this after the first pass to
13043          * be sure that all sections have had their headers validated.
13044          */
13045         for (i = 0; i < dof->dofh_secnum; i++) {
13046                 dof_sec_t *sec = (dof_sec_t *)(daddr +
13047                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13048 
13049                 if (!(sec->dofs_flags & DOF_SECF_LOAD))
13050                         continue; /* skip sections that are not loadable */
13051 
13052                 switch (sec->dofs_type) {
13053                 case DOF_SECT_URELHDR:
13054                         if (dtrace_dof_relocate(dof, sec, ubase) != 0)
13055                                 return (-1);
13056                         break;
13057                 }
13058         }
13059 
13060         if ((enab = *enabp) == NULL)
13061                 enab = *enabp = dtrace_enabling_create(vstate);
13062 
13063         for (i = 0; i < dof->dofh_secnum; i++) {
13064                 dof_sec_t *sec = (dof_sec_t *)(daddr +
13065                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13066 
13067                 if (sec->dofs_type != DOF_SECT_ECBDESC)
13068                         continue;
13069 
13070                 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
13071                         dtrace_enabling_destroy(enab);
13072                         *enabp = NULL;
13073                         return (-1);
13074                 }
13075 
13076                 dtrace_enabling_add(enab, ep);
13077         }
13078 
13079         return (0);
13080 }
13081 
13082 /*
13083  * Process DOF for any options.  This routine assumes that the DOF has been
13084  * at least processed by dtrace_dof_slurp().
13085  */
13086 static int
13087 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13088 {
13089         int i, rval;
13090         uint32_t entsize;
13091         size_t offs;
13092         dof_optdesc_t *desc;
13093 
13094         for (i = 0; i < dof->dofh_secnum; i++) {
13095                 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13096                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13097 
13098                 if (sec->dofs_type != DOF_SECT_OPTDESC)
13099                         continue;
13100 
13101                 if (sec->dofs_align != sizeof (uint64_t)) {
13102                         dtrace_dof_error(dof, "bad alignment in "
13103                             "option description");
13104                         return (EINVAL);
13105                 }
13106 
13107                 if ((entsize = sec->dofs_entsize) == 0) {
13108                         dtrace_dof_error(dof, "zeroed option entry size");
13109                         return (EINVAL);
13110                 }
13111 
13112                 if (entsize < sizeof (dof_optdesc_t)) {
13113                         dtrace_dof_error(dof, "bad option entry size");
13114                         return (EINVAL);
13115                 }
13116 
13117                 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13118                         desc = (dof_optdesc_t *)((uintptr_t)dof +
13119                             (uintptr_t)sec->dofs_offset + offs);
13120 
13121                         if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13122                                 dtrace_dof_error(dof, "non-zero option string");
13123                                 return (EINVAL);
13124                         }
13125 
13126                         if (desc->dofo_value == DTRACEOPT_UNSET) {
13127                                 dtrace_dof_error(dof, "unset option");
13128                                 return (EINVAL);
13129                         }
13130 
13131                         if ((rval = dtrace_state_option(state,
13132                             desc->dofo_option, desc->dofo_value)) != 0) {
13133                                 dtrace_dof_error(dof, "rejected option");
13134                                 return (rval);
13135                         }
13136                 }
13137         }
13138 
13139         return (0);
13140 }
13141 
13142 /*
13143  * DTrace Consumer State Functions
13144  */
13145 int
13146 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13147 {
13148         size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
13149         void *base;
13150         uintptr_t limit;
13151         dtrace_dynvar_t *dvar, *next, *start;
13152         int i;
13153 
13154         ASSERT(MUTEX_HELD(&dtrace_lock));
13155         ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13156 
13157         bzero(dstate, sizeof (dtrace_dstate_t));
13158 
13159         if ((dstate->dtds_chunksize = chunksize) == 0)
13160                 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13161 
13162         if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13163                 size = min;
13164 
13165         if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
13166                 return (ENOMEM);
13167 
13168         dstate->dtds_size = size;
13169         dstate->dtds_base = base;
13170         dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
13171         bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
13172 
13173         hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13174 
13175         if (hashsize != 1 && (hashsize & 1))
13176                 hashsize--;
13177 
13178         dstate->dtds_hashsize = hashsize;
13179         dstate->dtds_hash = dstate->dtds_base;
13180 
13181         /*
13182          * Set all of our hash buckets to point to the single sink, and (if
13183          * it hasn't already been set), set the sink's hash value to be the
13184          * sink sentinel value.  The sink is needed for dynamic variable
13185          * lookups to know that they have iterated over an entire, valid hash
13186          * chain.
13187          */
13188         for (i = 0; i < hashsize; i++)
13189                 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13190 
13191         if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13192                 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13193 
13194         /*
13195          * Determine number of active CPUs.  Divide free list evenly among
13196          * active CPUs.
13197          */
13198         start = (dtrace_dynvar_t *)
13199             ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13200         limit = (uintptr_t)base + size;
13201 
13202         maxper = (limit - (uintptr_t)start) / NCPU;
13203         maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13204 
13205         for (i = 0; i < NCPU; i++) {
13206                 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13207 
13208                 /*
13209                  * If we don't even have enough chunks to make it once through
13210                  * NCPUs, we're just going to allocate everything to the first
13211                  * CPU.  And if we're on the last CPU, we're going to allocate
13212                  * whatever is left over.  In either case, we set the limit to
13213                  * be the limit of the dynamic variable space.
13214                  */
13215                 if (maxper == 0 || i == NCPU - 1) {
13216                         limit = (uintptr_t)base + size;
13217                         start = NULL;
13218                 } else {
13219                         limit = (uintptr_t)start + maxper;
13220                         start = (dtrace_dynvar_t *)limit;
13221                 }
13222 
13223                 ASSERT(limit <= (uintptr_t)base + size);
13224 
13225                 for (;;) {
13226                         next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13227                             dstate->dtds_chunksize);
13228 
13229                         if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13230                                 break;
13231 
13232                         dvar->dtdv_next = next;
13233                         dvar = next;
13234                 }
13235 
13236                 if (maxper == 0)
13237                         break;
13238         }
13239 
13240         return (0);
13241 }
13242 
13243 void
13244 dtrace_dstate_fini(dtrace_dstate_t *dstate)
13245 {
13246         ASSERT(MUTEX_HELD(&cpu_lock));
13247 
13248         if (dstate->dtds_base == NULL)
13249                 return;
13250 
13251         kmem_free(dstate->dtds_base, dstate->dtds_size);
13252         kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13253 }
13254 
13255 static void
13256 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13257 {
13258         /*
13259          * Logical XOR, where are you?
13260          */
13261         ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13262 
13263         if (vstate->dtvs_nglobals > 0) {
13264                 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13265                     sizeof (dtrace_statvar_t *));
13266         }
13267 
13268         if (vstate->dtvs_ntlocals > 0) {
13269                 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13270                     sizeof (dtrace_difv_t));
13271         }
13272 
13273         ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13274 
13275         if (vstate->dtvs_nlocals > 0) {
13276                 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13277                     sizeof (dtrace_statvar_t *));
13278         }
13279 }
13280 
13281 static void
13282 dtrace_state_clean(dtrace_state_t *state)
13283 {
13284         if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13285                 return;
13286 
13287         dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13288         dtrace_speculation_clean(state);
13289 }
13290 
13291 static void
13292 dtrace_state_deadman(dtrace_state_t *state)
13293 {
13294         hrtime_t now;
13295 
13296         dtrace_sync();
13297 
13298         now = dtrace_gethrtime();
13299 
13300         if (state != dtrace_anon.dta_state &&
13301             now - state->dts_laststatus >= dtrace_deadman_user)
13302                 return;
13303 
13304         /*
13305          * We must be sure that dts_alive never appears to be less than the
13306          * value upon entry to dtrace_state_deadman(), and because we lack a
13307          * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13308          * store INT64_MAX to it, followed by a memory barrier, followed by
13309          * the new value.  This assures that dts_alive never appears to be
13310          * less than its true value, regardless of the order in which the
13311          * stores to the underlying storage are issued.
13312          */
13313         state->dts_alive = INT64_MAX;
13314         dtrace_membar_producer();
13315         state->dts_alive = now;
13316 }
13317 
13318 dtrace_state_t *
13319 dtrace_state_create(dev_t *devp, cred_t *cr)
13320 {
13321         minor_t minor;
13322         major_t major;
13323         char c[30];
13324         dtrace_state_t *state;
13325         dtrace_optval_t *opt;
13326         int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13327 
13328         ASSERT(MUTEX_HELD(&dtrace_lock));
13329         ASSERT(MUTEX_HELD(&cpu_lock));
13330 
13331         minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13332             VM_BESTFIT | VM_SLEEP);
13333 
13334         if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13335                 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13336                 return (NULL);
13337         }
13338 
13339         state = ddi_get_soft_state(dtrace_softstate, minor);
13340         state->dts_epid = DTRACE_EPIDNONE + 1;
13341 
13342         (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
13343         state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13344             NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13345 
13346         if (devp != NULL) {
13347                 major = getemajor(*devp);
13348         } else {
13349                 major = ddi_driver_major(dtrace_devi);
13350         }
13351 
13352         state->dts_dev = makedevice(major, minor);
13353 
13354         if (devp != NULL)
13355                 *devp = state->dts_dev;
13356 
13357         /*
13358          * We allocate NCPU buffers.  On the one hand, this can be quite
13359          * a bit of memory per instance (nearly 36K on a Starcat).  On the
13360          * other hand, it saves an additional memory reference in the probe
13361          * path.
13362          */
13363         state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13364         state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13365         state->dts_cleaner = CYCLIC_NONE;
13366         state->dts_deadman = CYCLIC_NONE;
13367         state->dts_vstate.dtvs_state = state;
13368 
13369         for (i = 0; i < DTRACEOPT_MAX; i++)
13370                 state->dts_options[i] = DTRACEOPT_UNSET;
13371 
13372         /*
13373          * Set the default options.
13374          */
13375         opt = state->dts_options;
13376         opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13377         opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13378         opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13379         opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13380         opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13381         opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13382         opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13383         opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13384         opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13385         opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13386         opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13387         opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13388         opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13389         opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13390 
13391         state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13392 
13393         /*
13394          * Depending on the user credentials, we set flag bits which alter probe
13395          * visibility or the amount of destructiveness allowed.  In the case of
13396          * actual anonymous tracing, or the possession of all privileges, all of
13397          * the normal checks are bypassed.
13398          */
13399         if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13400                 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13401                 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13402         } else {
13403                 /*
13404                  * Set up the credentials for this instantiation.  We take a
13405                  * hold on the credential to prevent it from disappearing on
13406                  * us; this in turn prevents the zone_t referenced by this
13407                  * credential from disappearing.  This means that we can
13408                  * examine the credential and the zone from probe context.
13409                  */
13410                 crhold(cr);
13411                 state->dts_cred.dcr_cred = cr;
13412 
13413                 /*
13414                  * CRA_PROC means "we have *some* privilege for dtrace" and
13415                  * unlocks the use of variables like pid, zonename, etc.
13416                  */
13417                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13418                     PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13419                         state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13420                 }
13421 
13422                 /*
13423                  * dtrace_user allows use of syscall and profile providers.
13424                  * If the user also has proc_owner and/or proc_zone, we
13425                  * extend the scope to include additional visibility and
13426                  * destructive power.
13427                  */
13428                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13429                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13430                                 state->dts_cred.dcr_visible |=
13431                                     DTRACE_CRV_ALLPROC;
13432 
13433                                 state->dts_cred.dcr_action |=
13434                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13435                         }
13436 
13437                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13438                                 state->dts_cred.dcr_visible |=
13439                                     DTRACE_CRV_ALLZONE;
13440 
13441                                 state->dts_cred.dcr_action |=
13442                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13443                         }
13444 
13445                         /*
13446                          * If we have all privs in whatever zone this is,
13447                          * we can do destructive things to processes which
13448                          * have altered credentials.
13449                          */
13450                         if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13451                             cr->cr_zone->zone_privset)) {
13452                                 state->dts_cred.dcr_action |=
13453                                     DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13454                         }
13455                 }
13456 
13457                 /*
13458                  * Holding the dtrace_kernel privilege also implies that
13459                  * the user has the dtrace_user privilege from a visibility
13460                  * perspective.  But without further privileges, some
13461                  * destructive actions are not available.
13462                  */
13463                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13464                         /*
13465                          * Make all probes in all zones visible.  However,
13466                          * this doesn't mean that all actions become available
13467                          * to all zones.
13468                          */
13469                         state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13470                             DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13471 
13472                         state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13473                             DTRACE_CRA_PROC;
13474                         /*
13475                          * Holding proc_owner means that destructive actions
13476                          * for *this* zone are allowed.
13477                          */
13478                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13479                                 state->dts_cred.dcr_action |=
13480                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13481 
13482                         /*
13483                          * Holding proc_zone means that destructive actions
13484                          * for this user/group ID in all zones is allowed.
13485                          */
13486                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13487                                 state->dts_cred.dcr_action |=
13488                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13489 
13490                         /*
13491                          * If we have all privs in whatever zone this is,
13492                          * we can do destructive things to processes which
13493                          * have altered credentials.
13494                          */
13495                         if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13496                             cr->cr_zone->zone_privset)) {
13497                                 state->dts_cred.dcr_action |=
13498                                     DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13499                         }
13500                 }
13501 
13502                 /*
13503                  * Holding the dtrace_proc privilege gives control over fasttrap
13504                  * and pid providers.  We need to grant wider destructive
13505                  * privileges in the event that the user has proc_owner and/or
13506                  * proc_zone.
13507                  */
13508                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13509                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13510                                 state->dts_cred.dcr_action |=
13511                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13512 
13513                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13514                                 state->dts_cred.dcr_action |=
13515                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13516                 }
13517         }
13518 
13519         return (state);
13520 }
13521 
13522 static int
13523 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13524 {
13525         dtrace_optval_t *opt = state->dts_options, size;
13526         processorid_t cpu;
13527         int flags = 0, rval, factor, divisor = 1;
13528 
13529         ASSERT(MUTEX_HELD(&dtrace_lock));
13530         ASSERT(MUTEX_HELD(&cpu_lock));
13531         ASSERT(which < DTRACEOPT_MAX);
13532         ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13533             (state == dtrace_anon.dta_state &&
13534             state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13535 
13536         if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13537                 return (0);
13538 
13539         if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13540                 cpu = opt[DTRACEOPT_CPU];
13541 
13542         if (which == DTRACEOPT_SPECSIZE)
13543                 flags |= DTRACEBUF_NOSWITCH;
13544 
13545         if (which == DTRACEOPT_BUFSIZE) {
13546                 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13547                         flags |= DTRACEBUF_RING;
13548 
13549                 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13550                         flags |= DTRACEBUF_FILL;
13551 
13552                 if (state != dtrace_anon.dta_state ||
13553                     state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13554                         flags |= DTRACEBUF_INACTIVE;
13555         }
13556 
13557         for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
13558                 /*
13559                  * The size must be 8-byte aligned.  If the size is not 8-byte
13560                  * aligned, drop it down by the difference.
13561                  */
13562                 if (size & (sizeof (uint64_t) - 1))
13563                         size -= size & (sizeof (uint64_t) - 1);
13564 
13565                 if (size < state->dts_reserve) {
13566                         /*
13567                          * Buffers always must be large enough to accommodate
13568                          * their prereserved space.  We return E2BIG instead
13569                          * of ENOMEM in this case to allow for user-level
13570                          * software to differentiate the cases.
13571                          */
13572                         return (E2BIG);
13573                 }
13574 
13575                 rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
13576 
13577                 if (rval != ENOMEM) {
13578                         opt[which] = size;
13579                         return (rval);
13580                 }
13581 
13582                 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13583                         return (rval);
13584 
13585                 for (divisor = 2; divisor < factor; divisor <<= 1)
13586                         continue;
13587         }
13588 
13589         return (ENOMEM);
13590 }
13591 
13592 static int
13593 dtrace_state_buffers(dtrace_state_t *state)
13594 {
13595         dtrace_speculation_t *spec = state->dts_speculations;
13596         int rval, i;
13597 
13598         if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13599             DTRACEOPT_BUFSIZE)) != 0)
13600                 return (rval);
13601 
13602         if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13603             DTRACEOPT_AGGSIZE)) != 0)
13604                 return (rval);
13605 
13606         for (i = 0; i < state->dts_nspeculations; i++) {
13607                 if ((rval = dtrace_state_buffer(state,
13608                     spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13609                         return (rval);
13610         }
13611 
13612         return (0);
13613 }
13614 
13615 static void
13616 dtrace_state_prereserve(dtrace_state_t *state)
13617 {
13618         dtrace_ecb_t *ecb;
13619         dtrace_probe_t *probe;
13620 
13621         state->dts_reserve = 0;
13622 
13623         if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13624                 return;
13625 
13626         /*
13627          * If our buffer policy is a "fill" buffer policy, we need to set the
13628          * prereserved space to be the space required by the END probes.
13629          */
13630         probe = dtrace_probes[dtrace_probeid_end - 1];
13631         ASSERT(probe != NULL);
13632 
13633         for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13634                 if (ecb->dte_state != state)
13635                         continue;
13636 
13637                 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13638         }
13639 }
13640 
13641 static int
13642 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13643 {
13644         dtrace_optval_t *opt = state->dts_options, sz, nspec;
13645         dtrace_speculation_t *spec;
13646         dtrace_buffer_t *buf;
13647         cyc_handler_t hdlr;
13648         cyc_time_t when;
13649         int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13650         dtrace_icookie_t cookie;
13651 
13652         mutex_enter(&cpu_lock);
13653         mutex_enter(&dtrace_lock);
13654 
13655         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13656                 rval = EBUSY;
13657                 goto out;
13658         }
13659 
13660         /*
13661          * Before we can perform any checks, we must prime all of the
13662          * retained enablings that correspond to this state.
13663          */
13664         dtrace_enabling_prime(state);
13665 
13666         if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13667                 rval = EACCES;
13668                 goto out;
13669         }
13670 
13671         dtrace_state_prereserve(state);
13672 
13673         /*
13674          * Now we want to do is try to allocate our speculations.
13675          * We do not automatically resize the number of speculations; if
13676          * this fails, we will fail the operation.
13677          */
13678         nspec = opt[DTRACEOPT_NSPEC];
13679         ASSERT(nspec != DTRACEOPT_UNSET);
13680 
13681         if (nspec > INT_MAX) {
13682                 rval = ENOMEM;
13683                 goto out;
13684         }
13685 
13686         spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
13687             KM_NOSLEEP | KM_NORMALPRI);
13688 
13689         if (spec == NULL) {
13690                 rval = ENOMEM;
13691                 goto out;
13692         }
13693 
13694         state->dts_speculations = spec;
13695         state->dts_nspeculations = (int)nspec;
13696 
13697         for (i = 0; i < nspec; i++) {
13698                 if ((buf = kmem_zalloc(bufsize,
13699                     KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
13700                         rval = ENOMEM;
13701                         goto err;
13702                 }
13703 
13704                 spec[i].dtsp_buffer = buf;
13705         }
13706 
13707         if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13708                 if (dtrace_anon.dta_state == NULL) {
13709                         rval = ENOENT;
13710                         goto out;
13711                 }
13712 
13713                 if (state->dts_necbs != 0) {
13714                         rval = EALREADY;
13715                         goto out;
13716                 }
13717 
13718                 state->dts_anon = dtrace_anon_grab();
13719                 ASSERT(state->dts_anon != NULL);
13720                 state = state->dts_anon;
13721 
13722                 /*
13723                  * We want "grabanon" to be set in the grabbed state, so we'll
13724                  * copy that option value from the grabbing state into the
13725                  * grabbed state.
13726                  */
13727                 state->dts_options[DTRACEOPT_GRABANON] =
13728                     opt[DTRACEOPT_GRABANON];
13729 
13730                 *cpu = dtrace_anon.dta_beganon;
13731 
13732                 /*
13733                  * If the anonymous state is active (as it almost certainly
13734                  * is if the anonymous enabling ultimately matched anything),
13735                  * we don't allow any further option processing -- but we
13736                  * don't return failure.
13737                  */
13738                 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13739                         goto out;
13740         }
13741 
13742         if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13743             opt[DTRACEOPT_AGGSIZE] != 0) {
13744                 if (state->dts_aggregations == NULL) {
13745                         /*
13746                          * We're not going to create an aggregation buffer
13747                          * because we don't have any ECBs that contain
13748                          * aggregations -- set this option to 0.
13749                          */
13750                         opt[DTRACEOPT_AGGSIZE] = 0;
13751                 } else {
13752                         /*
13753                          * If we have an aggregation buffer, we must also have
13754                          * a buffer to use as scratch.
13755                          */
13756                         if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13757                             opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13758                                 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13759                         }
13760                 }
13761         }
13762 
13763         if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13764             opt[DTRACEOPT_SPECSIZE] != 0) {
13765                 if (!state->dts_speculates) {
13766                         /*
13767                          * We're not going to create speculation buffers
13768                          * because we don't have any ECBs that actually
13769                          * speculate -- set the speculation size to 0.
13770                          */
13771                         opt[DTRACEOPT_SPECSIZE] = 0;
13772                 }
13773         }
13774 
13775         /*
13776          * The bare minimum size for any buffer that we're actually going to
13777          * do anything to is sizeof (uint64_t).
13778          */
13779         sz = sizeof (uint64_t);
13780 
13781         if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13782             (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13783             (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13784                 /*
13785                  * A buffer size has been explicitly set to 0 (or to a size
13786                  * that will be adjusted to 0) and we need the space -- we
13787                  * need to return failure.  We return ENOSPC to differentiate
13788                  * it from failing to allocate a buffer due to failure to meet
13789                  * the reserve (for which we return E2BIG).
13790                  */
13791                 rval = ENOSPC;
13792                 goto out;
13793         }
13794 
13795         if ((rval = dtrace_state_buffers(state)) != 0)
13796                 goto err;
13797 
13798         if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13799                 sz = dtrace_dstate_defsize;
13800 
13801         do {
13802                 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13803 
13804                 if (rval == 0)
13805                         break;
13806 
13807                 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13808                         goto err;
13809         } while (sz >>= 1);
13810 
13811         opt[DTRACEOPT_DYNVARSIZE] = sz;
13812 
13813         if (rval != 0)
13814                 goto err;
13815 
13816         if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13817                 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13818 
13819         if (opt[DTRACEOPT_CLEANRATE] == 0)
13820                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13821 
13822         if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13823                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13824 
13825         if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13826                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13827 
13828         hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13829         hdlr.cyh_arg = state;
13830         hdlr.cyh_level = CY_LOW_LEVEL;
13831 
13832         when.cyt_when = 0;
13833         when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13834 
13835         state->dts_cleaner = cyclic_add(&hdlr, &when);
13836 
13837         hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13838         hdlr.cyh_arg = state;
13839         hdlr.cyh_level = CY_LOW_LEVEL;
13840 
13841         when.cyt_when = 0;
13842         when.cyt_interval = dtrace_deadman_interval;
13843 
13844         state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13845         state->dts_deadman = cyclic_add(&hdlr, &when);
13846 
13847         state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13848 
13849         if (state->dts_getf != 0 &&
13850             !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
13851                 /*
13852                  * We don't have kernel privs but we have at least one call
13853                  * to getf(); we need to bump our zone's count, and (if
13854                  * this is the first enabling to have an unprivileged call
13855                  * to getf()) we need to hook into closef().
13856                  */
13857                 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
13858 
13859                 if (dtrace_getf++ == 0) {
13860                         ASSERT(dtrace_closef == NULL);
13861                         dtrace_closef = dtrace_getf_barrier;
13862                 }
13863         }
13864 
13865         /*
13866          * Now it's time to actually fire the BEGIN probe.  We need to disable
13867          * interrupts here both to record the CPU on which we fired the BEGIN
13868          * probe (the data from this CPU will be processed first at user
13869          * level) and to manually activate the buffer for this CPU.
13870          */
13871         cookie = dtrace_interrupt_disable();
13872         *cpu = CPU->cpu_id;
13873         ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13874         state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13875 
13876         dtrace_probe(dtrace_probeid_begin,
13877             (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13878         dtrace_interrupt_enable(cookie);
13879         /*
13880          * We may have had an exit action from a BEGIN probe; only change our
13881          * state to ACTIVE if we're still in WARMUP.
13882          */
13883         ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13884             state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13885 
13886         if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13887                 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13888 
13889         /*
13890          * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13891          * want each CPU to transition its principal buffer out of the
13892          * INACTIVE state.  Doing this assures that no CPU will suddenly begin
13893          * processing an ECB halfway down a probe's ECB chain; all CPUs will
13894          * atomically transition from processing none of a state's ECBs to
13895          * processing all of them.
13896          */
13897         dtrace_xcall(DTRACE_CPUALL,
13898             (dtrace_xcall_t)dtrace_buffer_activate, state);
13899         goto out;
13900 
13901 err:
13902         dtrace_buffer_free(state->dts_buffer);
13903         dtrace_buffer_free(state->dts_aggbuffer);
13904 
13905         if ((nspec = state->dts_nspeculations) == 0) {
13906                 ASSERT(state->dts_speculations == NULL);
13907                 goto out;
13908         }
13909 
13910         spec = state->dts_speculations;
13911         ASSERT(spec != NULL);
13912 
13913         for (i = 0; i < state->dts_nspeculations; i++) {
13914                 if ((buf = spec[i].dtsp_buffer) == NULL)
13915                         break;
13916 
13917                 dtrace_buffer_free(buf);
13918                 kmem_free(buf, bufsize);
13919         }
13920 
13921         kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13922         state->dts_nspeculations = 0;
13923         state->dts_speculations = NULL;
13924 
13925 out:
13926         mutex_exit(&dtrace_lock);
13927         mutex_exit(&cpu_lock);
13928 
13929         return (rval);
13930 }
13931 
13932 static int
13933 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13934 {
13935         dtrace_icookie_t cookie;
13936 
13937         ASSERT(MUTEX_HELD(&dtrace_lock));
13938 
13939         if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13940             state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13941                 return (EINVAL);
13942 
13943         /*
13944          * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13945          * to be sure that every CPU has seen it.  See below for the details
13946          * on why this is done.
13947          */
13948         state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13949         dtrace_sync();
13950 
13951         /*
13952          * By this point, it is impossible for any CPU to be still processing
13953          * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
13954          * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13955          * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
13956          * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13957          * iff we're in the END probe.
13958          */
13959         state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13960         dtrace_sync();
13961         ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13962 
13963         /*
13964          * Finally, we can release the reserve and call the END probe.  We
13965          * disable interrupts across calling the END probe to allow us to
13966          * return the CPU on which we actually called the END probe.  This
13967          * allows user-land to be sure that this CPU's principal buffer is
13968          * processed last.
13969          */
13970         state->dts_reserve = 0;
13971 
13972         cookie = dtrace_interrupt_disable();
13973         *cpu = CPU->cpu_id;
13974         dtrace_probe(dtrace_probeid_end,
13975             (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13976         dtrace_interrupt_enable(cookie);
13977 
13978         state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13979         dtrace_sync();
13980 
13981         if (state->dts_getf != 0 &&
13982             !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
13983                 /*
13984                  * We don't have kernel privs but we have at least one call
13985                  * to getf(); we need to lower our zone's count, and (if
13986                  * this is the last enabling to have an unprivileged call
13987                  * to getf()) we need to clear the closef() hook.
13988                  */
13989                 ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
13990                 ASSERT(dtrace_closef == dtrace_getf_barrier);
13991                 ASSERT(dtrace_getf > 0);
13992 
13993                 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
13994 
13995                 if (--dtrace_getf == 0)
13996                         dtrace_closef = NULL;
13997         }
13998 
13999         return (0);
14000 }
14001 
14002 static int
14003 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14004     dtrace_optval_t val)
14005 {
14006         ASSERT(MUTEX_HELD(&dtrace_lock));
14007 
14008         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14009                 return (EBUSY);
14010 
14011         if (option >= DTRACEOPT_MAX)
14012                 return (EINVAL);
14013 
14014         if (option != DTRACEOPT_CPU && val < 0)
14015                 return (EINVAL);
14016 
14017         switch (option) {
14018         case DTRACEOPT_DESTRUCTIVE:
14019                 if (dtrace_destructive_disallow)
14020                         return (EACCES);
14021 
14022                 state->dts_cred.dcr_destructive = 1;
14023                 break;
14024 
14025         case DTRACEOPT_BUFSIZE:
14026         case DTRACEOPT_DYNVARSIZE:
14027         case DTRACEOPT_AGGSIZE:
14028         case DTRACEOPT_SPECSIZE:
14029         case DTRACEOPT_STRSIZE:
14030                 if (val < 0)
14031                         return (EINVAL);
14032 
14033                 if (val >= LONG_MAX) {
14034                         /*
14035                          * If this is an otherwise negative value, set it to
14036                          * the highest multiple of 128m less than LONG_MAX.
14037                          * Technically, we're adjusting the size without
14038                          * regard to the buffer resizing policy, but in fact,
14039                          * this has no effect -- if we set the buffer size to
14040                          * ~LONG_MAX and the buffer policy is ultimately set to
14041                          * be "manual", the buffer allocation is guaranteed to
14042                          * fail, if only because the allocation requires two
14043                          * buffers.  (We set the the size to the highest
14044                          * multiple of 128m because it ensures that the size
14045                          * will remain a multiple of a megabyte when
14046                          * repeatedly halved -- all the way down to 15m.)
14047                          */
14048                         val = LONG_MAX - (1 << 27) + 1;
14049                 }
14050         }
14051 
14052         state->dts_options[option] = val;
14053 
14054         return (0);
14055 }
14056 
14057 static void
14058 dtrace_state_destroy(dtrace_state_t *state)
14059 {
14060         dtrace_ecb_t *ecb;
14061         dtrace_vstate_t *vstate = &state->dts_vstate;
14062         minor_t minor = getminor(state->dts_dev);
14063         int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14064         dtrace_speculation_t *spec = state->dts_speculations;
14065         int nspec = state->dts_nspeculations;
14066         uint32_t match;
14067 
14068         ASSERT(MUTEX_HELD(&dtrace_lock));
14069         ASSERT(MUTEX_HELD(&cpu_lock));
14070 
14071         /*
14072          * First, retract any retained enablings for this state.
14073          */
14074         dtrace_enabling_retract(state);
14075         ASSERT(state->dts_nretained == 0);
14076 
14077         if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14078             state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14079                 /*
14080                  * We have managed to come into dtrace_state_destroy() on a
14081                  * hot enabling -- almost certainly because of a disorderly
14082                  * shutdown of a consumer.  (That is, a consumer that is
14083                  * exiting without having called dtrace_stop().) In this case,
14084                  * we're going to set our activity to be KILLED, and then
14085                  * issue a sync to be sure that everyone is out of probe
14086                  * context before we start blowing away ECBs.
14087                  */
14088                 state->dts_activity = DTRACE_ACTIVITY_KILLED;
14089                 dtrace_sync();
14090         }
14091 
14092         /*
14093          * Release the credential hold we took in dtrace_state_create().
14094          */
14095         if (state->dts_cred.dcr_cred != NULL)
14096                 crfree(state->dts_cred.dcr_cred);
14097 
14098         /*
14099          * Now we can safely disable and destroy any enabled probes.  Because
14100          * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
14101          * (especially if they're all enabled), we take two passes through the
14102          * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
14103          * in the second we disable whatever is left over.
14104          */
14105         for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
14106                 for (i = 0; i < state->dts_necbs; i++) {
14107                         if ((ecb = state->dts_ecbs[i]) == NULL)
14108                                 continue;
14109 
14110                         if (match && ecb->dte_probe != NULL) {
14111                                 dtrace_probe_t *probe = ecb->dte_probe;
14112                                 dtrace_provider_t *prov = probe->dtpr_provider;
14113 
14114                                 if (!(prov->dtpv_priv.dtpp_flags & match))
14115                                         continue;
14116                         }
14117 
14118                         dtrace_ecb_disable(ecb);
14119                         dtrace_ecb_destroy(ecb);
14120                 }
14121 
14122                 if (!match)
14123                         break;
14124         }
14125 
14126         /*
14127          * Before we free the buffers, perform one more sync to assure that
14128          * every CPU is out of probe context.
14129          */
14130         dtrace_sync();
14131 
14132         dtrace_buffer_free(state->dts_buffer);
14133         dtrace_buffer_free(state->dts_aggbuffer);
14134 
14135         for (i = 0; i < nspec; i++)
14136                 dtrace_buffer_free(spec[i].dtsp_buffer);
14137 
14138         if (state->dts_cleaner != CYCLIC_NONE)
14139                 cyclic_remove(state->dts_cleaner);
14140 
14141         if (state->dts_deadman != CYCLIC_NONE)
14142                 cyclic_remove(state->dts_deadman);
14143 
14144         dtrace_dstate_fini(&vstate->dtvs_dynvars);
14145         dtrace_vstate_fini(vstate);
14146         kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14147 
14148         if (state->dts_aggregations != NULL) {
14149 #ifdef DEBUG
14150                 for (i = 0; i < state->dts_naggregations; i++)
14151                         ASSERT(state->dts_aggregations[i] == NULL);
14152 #endif
14153                 ASSERT(state->dts_naggregations > 0);
14154                 kmem_free(state->dts_aggregations,
14155                     state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14156         }
14157 
14158         kmem_free(state->dts_buffer, bufsize);
14159         kmem_free(state->dts_aggbuffer, bufsize);
14160 
14161         for (i = 0; i < nspec; i++)
14162                 kmem_free(spec[i].dtsp_buffer, bufsize);
14163 
14164         kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14165 
14166         dtrace_format_destroy(state);
14167 
14168         vmem_destroy(state->dts_aggid_arena);
14169         ddi_soft_state_free(dtrace_softstate, minor);
14170         vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14171 }
14172 
14173 /*
14174  * DTrace Anonymous Enabling Functions
14175  */
14176 static dtrace_state_t *
14177 dtrace_anon_grab(void)
14178 {
14179         dtrace_state_t *state;
14180 
14181         ASSERT(MUTEX_HELD(&dtrace_lock));
14182 
14183         if ((state = dtrace_anon.dta_state) == NULL) {
14184                 ASSERT(dtrace_anon.dta_enabling == NULL);
14185                 return (NULL);
14186         }
14187 
14188         ASSERT(dtrace_anon.dta_enabling != NULL);
14189         ASSERT(dtrace_retained != NULL);
14190 
14191         dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14192         dtrace_anon.dta_enabling = NULL;
14193         dtrace_anon.dta_state = NULL;
14194 
14195         return (state);
14196 }
14197 
14198 static void
14199 dtrace_anon_property(void)
14200 {
14201         int i, rv;
14202         dtrace_state_t *state;
14203         dof_hdr_t *dof;
14204         char c[32];             /* enough for "dof-data-" + digits */
14205 
14206         ASSERT(MUTEX_HELD(&dtrace_lock));
14207         ASSERT(MUTEX_HELD(&cpu_lock));
14208 
14209         for (i = 0; ; i++) {
14210                 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
14211 
14212                 dtrace_err_verbose = 1;
14213 
14214                 if ((dof = dtrace_dof_property(c)) == NULL) {
14215                         dtrace_err_verbose = 0;
14216                         break;
14217                 }
14218 
14219                 /*
14220                  * We want to create anonymous state, so we need to transition
14221                  * the kernel debugger to indicate that DTrace is active.  If
14222                  * this fails (e.g. because the debugger has modified text in
14223                  * some way), we won't continue with the processing.
14224                  */
14225                 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14226                         cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14227                             "enabling ignored.");
14228                         dtrace_dof_destroy(dof);
14229                         break;
14230                 }
14231 
14232                 /*
14233                  * If we haven't allocated an anonymous state, we'll do so now.
14234                  */
14235                 if ((state = dtrace_anon.dta_state) == NULL) {
14236                         state = dtrace_state_create(NULL, NULL);
14237                         dtrace_anon.dta_state = state;
14238 
14239                         if (state == NULL) {
14240                                 /*
14241                                  * This basically shouldn't happen:  the only
14242                                  * failure mode from dtrace_state_create() is a
14243                                  * failure of ddi_soft_state_zalloc() that
14244                                  * itself should never happen.  Still, the
14245                                  * interface allows for a failure mode, and
14246                                  * we want to fail as gracefully as possible:
14247                                  * we'll emit an error message and cease
14248                                  * processing anonymous state in this case.
14249                                  */
14250                                 cmn_err(CE_WARN, "failed to create "
14251                                     "anonymous state");
14252                                 dtrace_dof_destroy(dof);
14253                                 break;
14254                         }
14255                 }
14256 
14257                 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14258                     &dtrace_anon.dta_enabling, 0, B_TRUE);
14259 
14260                 if (rv == 0)
14261                         rv = dtrace_dof_options(dof, state);
14262 
14263                 dtrace_err_verbose = 0;
14264                 dtrace_dof_destroy(dof);
14265 
14266                 if (rv != 0) {
14267                         /*
14268                          * This is malformed DOF; chuck any anonymous state
14269                          * that we created.
14270                          */
14271                         ASSERT(dtrace_anon.dta_enabling == NULL);
14272                         dtrace_state_destroy(state);
14273                         dtrace_anon.dta_state = NULL;
14274                         break;
14275                 }
14276 
14277                 ASSERT(dtrace_anon.dta_enabling != NULL);
14278         }
14279 
14280         if (dtrace_anon.dta_enabling != NULL) {
14281                 int rval;
14282 
14283                 /*
14284                  * dtrace_enabling_retain() can only fail because we are
14285                  * trying to retain more enablings than are allowed -- but
14286                  * we only have one anonymous enabling, and we are guaranteed
14287                  * to be allowed at least one retained enabling; we assert
14288                  * that dtrace_enabling_retain() returns success.
14289                  */
14290                 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14291                 ASSERT(rval == 0);
14292 
14293                 dtrace_enabling_dump(dtrace_anon.dta_enabling);
14294         }
14295 }
14296 
14297 /*
14298  * DTrace Helper Functions
14299  */
14300 static void
14301 dtrace_helper_trace(dtrace_helper_action_t *helper,
14302     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14303 {
14304         uint32_t size, next, nnext, i;
14305         dtrace_helptrace_t *ent, *buffer;
14306         uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14307 
14308         if ((buffer = dtrace_helptrace_buffer) == NULL)
14309                 return;
14310 
14311         ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14312 
14313         /*
14314          * What would a tracing framework be without its own tracing
14315          * framework?  (Well, a hell of a lot simpler, for starters...)
14316          */
14317         size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14318             sizeof (uint64_t) - sizeof (uint64_t);
14319 
14320         /*
14321          * Iterate until we can allocate a slot in the trace buffer.
14322          */
14323         do {
14324                 next = dtrace_helptrace_next;
14325 
14326                 if (next + size < dtrace_helptrace_bufsize) {
14327                         nnext = next + size;
14328                 } else {
14329                         nnext = size;
14330                 }
14331         } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14332 
14333         /*
14334          * We have our slot; fill it in.
14335          */
14336         if (nnext == size) {
14337                 dtrace_helptrace_wrapped++;
14338                 next = 0;
14339         }
14340 
14341         ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
14342         ent->dtht_helper = helper;
14343         ent->dtht_where = where;
14344         ent->dtht_nlocals = vstate->dtvs_nlocals;
14345 
14346         ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14347             mstate->dtms_fltoffs : -1;
14348         ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14349         ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
14350 
14351         for (i = 0; i < vstate->dtvs_nlocals; i++) {
14352                 dtrace_statvar_t *svar;
14353 
14354                 if ((svar = vstate->dtvs_locals[i]) == NULL)
14355                         continue;
14356 
14357                 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14358                 ent->dtht_locals[i] =
14359                     ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
14360         }
14361 }
14362 
14363 static uint64_t
14364 dtrace_helper(int which, dtrace_mstate_t *mstate,
14365     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14366 {
14367         uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14368         uint64_t sarg0 = mstate->dtms_arg[0];
14369         uint64_t sarg1 = mstate->dtms_arg[1];
14370         uint64_t rval;
14371         dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14372         dtrace_helper_action_t *helper;
14373         dtrace_vstate_t *vstate;
14374         dtrace_difo_t *pred;
14375         int i, trace = dtrace_helptrace_buffer != NULL;
14376 
14377         ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14378 
14379         if (helpers == NULL)
14380                 return (0);
14381 
14382         if ((helper = helpers->dthps_actions[which]) == NULL)
14383                 return (0);
14384 
14385         vstate = &helpers->dthps_vstate;
14386         mstate->dtms_arg[0] = arg0;
14387         mstate->dtms_arg[1] = arg1;
14388 
14389         /*
14390          * Now iterate over each helper.  If its predicate evaluates to 'true',
14391          * we'll call the corresponding actions.  Note that the below calls
14392          * to dtrace_dif_emulate() may set faults in machine state.  This is
14393          * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
14394          * the stored DIF offset with its own (which is the desired behavior).
14395          * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14396          * from machine state; this is okay, too.
14397          */
14398         for (; helper != NULL; helper = helper->dtha_next) {
14399                 if ((pred = helper->dtha_predicate) != NULL) {
14400                         if (trace)
14401                                 dtrace_helper_trace(helper, mstate, vstate, 0);
14402 
14403                         if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14404                                 goto next;
14405 
14406                         if (*flags & CPU_DTRACE_FAULT)
14407                                 goto err;
14408                 }
14409 
14410                 for (i = 0; i < helper->dtha_nactions; i++) {
14411                         if (trace)
14412                                 dtrace_helper_trace(helper,
14413                                     mstate, vstate, i + 1);
14414 
14415                         rval = dtrace_dif_emulate(helper->dtha_actions[i],
14416                             mstate, vstate, state);
14417 
14418                         if (*flags & CPU_DTRACE_FAULT)
14419                                 goto err;
14420                 }
14421 
14422 next:
14423                 if (trace)
14424                         dtrace_helper_trace(helper, mstate, vstate,
14425                             DTRACE_HELPTRACE_NEXT);
14426         }
14427 
14428         if (trace)
14429                 dtrace_helper_trace(helper, mstate, vstate,
14430                     DTRACE_HELPTRACE_DONE);
14431 
14432         /*
14433          * Restore the arg0 that we saved upon entry.
14434          */
14435         mstate->dtms_arg[0] = sarg0;
14436         mstate->dtms_arg[1] = sarg1;
14437 
14438         return (rval);
14439 
14440 err:
14441         if (trace)
14442                 dtrace_helper_trace(helper, mstate, vstate,
14443                     DTRACE_HELPTRACE_ERR);
14444 
14445         /*
14446          * Restore the arg0 that we saved upon entry.
14447          */
14448         mstate->dtms_arg[0] = sarg0;
14449         mstate->dtms_arg[1] = sarg1;
14450 
14451         return (NULL);
14452 }
14453 
14454 static void
14455 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14456     dtrace_vstate_t *vstate)
14457 {
14458         int i;
14459 
14460         if (helper->dtha_predicate != NULL)
14461                 dtrace_difo_release(helper->dtha_predicate, vstate);
14462 
14463         for (i = 0; i < helper->dtha_nactions; i++) {
14464                 ASSERT(helper->dtha_actions[i] != NULL);
14465                 dtrace_difo_release(helper->dtha_actions[i], vstate);
14466         }
14467 
14468         kmem_free(helper->dtha_actions,
14469             helper->dtha_nactions * sizeof (dtrace_difo_t *));
14470         kmem_free(helper, sizeof (dtrace_helper_action_t));
14471 }
14472 
14473 static int
14474 dtrace_helper_destroygen(int gen)
14475 {
14476         proc_t *p = curproc;
14477         dtrace_helpers_t *help = p->p_dtrace_helpers;
14478         dtrace_vstate_t *vstate;
14479         int i;
14480 
14481         ASSERT(MUTEX_HELD(&dtrace_lock));
14482 
14483         if (help == NULL || gen > help->dthps_generation)
14484                 return (EINVAL);
14485 
14486         vstate = &help->dthps_vstate;
14487 
14488         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14489                 dtrace_helper_action_t *last = NULL, *h, *next;
14490 
14491                 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14492                         next = h->dtha_next;
14493 
14494                         if (h->dtha_generation == gen) {
14495                                 if (last != NULL) {
14496                                         last->dtha_next = next;
14497                                 } else {
14498                                         help->dthps_actions[i] = next;
14499                                 }
14500 
14501                                 dtrace_helper_action_destroy(h, vstate);
14502                         } else {
14503                                 last = h;
14504                         }
14505                 }
14506         }
14507 
14508         /*
14509          * Interate until we've cleared out all helper providers with the
14510          * given generation number.
14511          */
14512         for (;;) {
14513                 dtrace_helper_provider_t *prov;
14514 
14515                 /*
14516                  * Look for a helper provider with the right generation. We
14517                  * have to start back at the beginning of the list each time
14518                  * because we drop dtrace_lock. It's unlikely that we'll make
14519                  * more than two passes.
14520                  */
14521                 for (i = 0; i < help->dthps_nprovs; i++) {
14522                         prov = help->dthps_provs[i];
14523 
14524                         if (prov->dthp_generation == gen)
14525                                 break;
14526                 }
14527 
14528                 /*
14529                  * If there were no matches, we're done.
14530                  */
14531                 if (i == help->dthps_nprovs)
14532                         break;
14533 
14534                 /*
14535                  * Move the last helper provider into this slot.
14536                  */
14537                 help->dthps_nprovs--;
14538                 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14539                 help->dthps_provs[help->dthps_nprovs] = NULL;
14540 
14541                 mutex_exit(&dtrace_lock);
14542 
14543                 /*
14544                  * If we have a meta provider, remove this helper provider.
14545                  */
14546                 mutex_enter(&dtrace_meta_lock);
14547                 if (dtrace_meta_pid != NULL) {
14548                         ASSERT(dtrace_deferred_pid == NULL);
14549                         dtrace_helper_provider_remove(&prov->dthp_prov,
14550                             p->p_pid);
14551                 }
14552                 mutex_exit(&dtrace_meta_lock);
14553 
14554                 dtrace_helper_provider_destroy(prov);
14555 
14556                 mutex_enter(&dtrace_lock);
14557         }
14558 
14559         return (0);
14560 }
14561 
14562 static int
14563 dtrace_helper_validate(dtrace_helper_action_t *helper)
14564 {
14565         int err = 0, i;
14566         dtrace_difo_t *dp;
14567 
14568         if ((dp = helper->dtha_predicate) != NULL)
14569                 err += dtrace_difo_validate_helper(dp);
14570 
14571         for (i = 0; i < helper->dtha_nactions; i++)
14572                 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14573 
14574         return (err == 0);
14575 }
14576 
14577 static int
14578 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14579 {
14580         dtrace_helpers_t *help;
14581         dtrace_helper_action_t *helper, *last;
14582         dtrace_actdesc_t *act;
14583         dtrace_vstate_t *vstate;
14584         dtrace_predicate_t *pred;
14585         int count = 0, nactions = 0, i;
14586 
14587         if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14588                 return (EINVAL);
14589 
14590         help = curproc->p_dtrace_helpers;
14591         last = help->dthps_actions[which];
14592         vstate = &help->dthps_vstate;
14593 
14594         for (count = 0; last != NULL; last = last->dtha_next) {
14595                 count++;
14596                 if (last->dtha_next == NULL)
14597                         break;
14598         }
14599 
14600         /*
14601          * If we already have dtrace_helper_actions_max helper actions for this
14602          * helper action type, we'll refuse to add a new one.
14603          */
14604         if (count >= dtrace_helper_actions_max)
14605                 return (ENOSPC);
14606 
14607         helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14608         helper->dtha_generation = help->dthps_generation;
14609 
14610         if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14611                 ASSERT(pred->dtp_difo != NULL);
14612                 dtrace_difo_hold(pred->dtp_difo);
14613                 helper->dtha_predicate = pred->dtp_difo;
14614         }
14615 
14616         for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14617                 if (act->dtad_kind != DTRACEACT_DIFEXPR)
14618                         goto err;
14619 
14620                 if (act->dtad_difo == NULL)
14621                         goto err;
14622 
14623                 nactions++;
14624         }
14625 
14626         helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14627             (helper->dtha_nactions = nactions), KM_SLEEP);
14628 
14629         for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14630                 dtrace_difo_hold(act->dtad_difo);
14631                 helper->dtha_actions[i++] = act->dtad_difo;
14632         }
14633 
14634         if (!dtrace_helper_validate(helper))
14635                 goto err;
14636 
14637         if (last == NULL) {
14638                 help->dthps_actions[which] = helper;
14639         } else {
14640                 last->dtha_next = helper;
14641         }
14642 
14643         if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14644                 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14645                 dtrace_helptrace_next = 0;
14646         }
14647 
14648         return (0);
14649 err:
14650         dtrace_helper_action_destroy(helper, vstate);
14651         return (EINVAL);
14652 }
14653 
14654 static void
14655 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14656     dof_helper_t *dofhp)
14657 {
14658         ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
14659 
14660         mutex_enter(&dtrace_meta_lock);
14661         mutex_enter(&dtrace_lock);
14662 
14663         if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14664                 /*
14665                  * If the dtrace module is loaded but not attached, or if
14666                  * there aren't isn't a meta provider registered to deal with
14667                  * these provider descriptions, we need to postpone creating
14668                  * the actual providers until later.
14669                  */
14670 
14671                 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14672                     dtrace_deferred_pid != help) {
14673                         help->dthps_deferred = 1;
14674                         help->dthps_pid = p->p_pid;
14675                         help->dthps_next = dtrace_deferred_pid;
14676                         help->dthps_prev = NULL;
14677                         if (dtrace_deferred_pid != NULL)
14678                                 dtrace_deferred_pid->dthps_prev = help;
14679                         dtrace_deferred_pid = help;
14680                 }
14681 
14682                 mutex_exit(&dtrace_lock);
14683 
14684         } else if (dofhp != NULL) {
14685                 /*
14686                  * If the dtrace module is loaded and we have a particular
14687                  * helper provider description, pass that off to the
14688                  * meta provider.
14689                  */
14690 
14691                 mutex_exit(&dtrace_lock);
14692 
14693                 dtrace_helper_provide(dofhp, p->p_pid);
14694 
14695         } else {
14696                 /*
14697                  * Otherwise, just pass all the helper provider descriptions
14698                  * off to the meta provider.
14699                  */
14700 
14701                 int i;
14702                 mutex_exit(&dtrace_lock);
14703 
14704                 for (i = 0; i < help->dthps_nprovs; i++) {
14705                         dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14706                             p->p_pid);
14707                 }
14708         }
14709 
14710         mutex_exit(&dtrace_meta_lock);
14711 }
14712 
14713 static int
14714 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14715 {
14716         dtrace_helpers_t *help;
14717         dtrace_helper_provider_t *hprov, **tmp_provs;
14718         uint_t tmp_maxprovs, i;
14719 
14720         ASSERT(MUTEX_HELD(&dtrace_lock));
14721 
14722         help = curproc->p_dtrace_helpers;
14723         ASSERT(help != NULL);
14724 
14725         /*
14726          * If we already have dtrace_helper_providers_max helper providers,
14727          * we're refuse to add a new one.
14728          */
14729         if (help->dthps_nprovs >= dtrace_helper_providers_max)
14730                 return (ENOSPC);
14731 
14732         /*
14733          * Check to make sure this isn't a duplicate.
14734          */
14735         for (i = 0; i < help->dthps_nprovs; i++) {
14736                 if (dofhp->dofhp_addr ==
14737                     help->dthps_provs[i]->dthp_prov.dofhp_addr)
14738                         return (EALREADY);
14739         }
14740 
14741         hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14742         hprov->dthp_prov = *dofhp;
14743         hprov->dthp_ref = 1;
14744         hprov->dthp_generation = gen;
14745 
14746         /*
14747          * Allocate a bigger table for helper providers if it's already full.
14748          */
14749         if (help->dthps_maxprovs == help->dthps_nprovs) {
14750                 tmp_maxprovs = help->dthps_maxprovs;
14751                 tmp_provs = help->dthps_provs;
14752 
14753                 if (help->dthps_maxprovs == 0)
14754                         help->dthps_maxprovs = 2;
14755                 else
14756                         help->dthps_maxprovs *= 2;
14757                 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14758                         help->dthps_maxprovs = dtrace_helper_providers_max;
14759 
14760                 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14761 
14762                 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14763                     sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14764 
14765                 if (tmp_provs != NULL) {
14766                         bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14767                             sizeof (dtrace_helper_provider_t *));
14768                         kmem_free(tmp_provs, tmp_maxprovs *
14769                             sizeof (dtrace_helper_provider_t *));
14770                 }
14771         }
14772 
14773         help->dthps_provs[help->dthps_nprovs] = hprov;
14774         help->dthps_nprovs++;
14775 
14776         return (0);
14777 }
14778 
14779 static void
14780 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14781 {
14782         mutex_enter(&dtrace_lock);
14783 
14784         if (--hprov->dthp_ref == 0) {
14785                 dof_hdr_t *dof;
14786                 mutex_exit(&dtrace_lock);
14787                 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14788                 dtrace_dof_destroy(dof);
14789                 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14790         } else {
14791                 mutex_exit(&dtrace_lock);
14792         }
14793 }
14794 
14795 static int
14796 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14797 {
14798         uintptr_t daddr = (uintptr_t)dof;
14799         dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14800         dof_provider_t *provider;
14801         dof_probe_t *probe;
14802         uint8_t *arg;
14803         char *strtab, *typestr;
14804         dof_stridx_t typeidx;
14805         size_t typesz;
14806         uint_t nprobes, j, k;
14807 
14808         ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14809 
14810         if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14811                 dtrace_dof_error(dof, "misaligned section offset");
14812                 return (-1);
14813         }
14814 
14815         /*
14816          * The section needs to be large enough to contain the DOF provider
14817          * structure appropriate for the given version.
14818          */
14819         if (sec->dofs_size <
14820             ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14821             offsetof(dof_provider_t, dofpv_prenoffs) :
14822             sizeof (dof_provider_t))) {
14823                 dtrace_dof_error(dof, "provider section too small");
14824                 return (-1);
14825         }
14826 
14827         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14828         str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14829         prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14830         arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14831         off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14832 
14833         if (str_sec == NULL || prb_sec == NULL ||
14834             arg_sec == NULL || off_sec == NULL)
14835                 return (-1);
14836 
14837         enoff_sec = NULL;
14838 
14839         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14840             provider->dofpv_prenoffs != DOF_SECT_NONE &&
14841             (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14842             provider->dofpv_prenoffs)) == NULL)
14843                 return (-1);
14844 
14845         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14846 
14847         if (provider->dofpv_name >= str_sec->dofs_size ||
14848             strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14849                 dtrace_dof_error(dof, "invalid provider name");
14850                 return (-1);
14851         }
14852 
14853         if (prb_sec->dofs_entsize == 0 ||
14854             prb_sec->dofs_entsize > prb_sec->dofs_size) {
14855                 dtrace_dof_error(dof, "invalid entry size");
14856                 return (-1);
14857         }
14858 
14859         if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14860                 dtrace_dof_error(dof, "misaligned entry size");
14861                 return (-1);
14862         }
14863 
14864         if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14865                 dtrace_dof_error(dof, "invalid entry size");
14866                 return (-1);
14867         }
14868 
14869         if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14870                 dtrace_dof_error(dof, "misaligned section offset");
14871                 return (-1);
14872         }
14873 
14874         if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14875                 dtrace_dof_error(dof, "invalid entry size");
14876                 return (-1);
14877         }
14878 
14879         arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14880 
14881         nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14882 
14883         /*
14884          * Take a pass through the probes to check for errors.
14885          */
14886         for (j = 0; j < nprobes; j++) {
14887                 probe = (dof_probe_t *)(uintptr_t)(daddr +
14888                     prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14889 
14890                 if (probe->dofpr_func >= str_sec->dofs_size) {
14891                         dtrace_dof_error(dof, "invalid function name");
14892                         return (-1);
14893                 }
14894 
14895                 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14896                         dtrace_dof_error(dof, "function name too long");
14897                         return (-1);
14898                 }
14899 
14900                 if (probe->dofpr_name >= str_sec->dofs_size ||
14901                     strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14902                         dtrace_dof_error(dof, "invalid probe name");
14903                         return (-1);
14904                 }
14905 
14906                 /*
14907                  * The offset count must not wrap the index, and the offsets
14908                  * must also not overflow the section's data.
14909                  */
14910                 if (probe->dofpr_offidx + probe->dofpr_noffs <
14911                     probe->dofpr_offidx ||
14912                     (probe->dofpr_offidx + probe->dofpr_noffs) *
14913                     off_sec->dofs_entsize > off_sec->dofs_size) {
14914                         dtrace_dof_error(dof, "invalid probe offset");
14915                         return (-1);
14916                 }
14917 
14918                 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14919                         /*
14920                          * If there's no is-enabled offset section, make sure
14921                          * there aren't any is-enabled offsets. Otherwise
14922                          * perform the same checks as for probe offsets
14923                          * (immediately above).
14924                          */
14925                         if (enoff_sec == NULL) {
14926                                 if (probe->dofpr_enoffidx != 0 ||
14927                                     probe->dofpr_nenoffs != 0) {
14928                                         dtrace_dof_error(dof, "is-enabled "
14929                                             "offsets with null section");
14930                                         return (-1);
14931                                 }
14932                         } else if (probe->dofpr_enoffidx +
14933                             probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14934                             (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14935                             enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14936                                 dtrace_dof_error(dof, "invalid is-enabled "
14937                                     "offset");
14938                                 return (-1);
14939                         }
14940 
14941                         if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14942                                 dtrace_dof_error(dof, "zero probe and "
14943                                     "is-enabled offsets");
14944                                 return (-1);
14945                         }
14946                 } else if (probe->dofpr_noffs == 0) {
14947                         dtrace_dof_error(dof, "zero probe offsets");
14948                         return (-1);
14949                 }
14950 
14951                 if (probe->dofpr_argidx + probe->dofpr_xargc <
14952                     probe->dofpr_argidx ||
14953                     (probe->dofpr_argidx + probe->dofpr_xargc) *
14954                     arg_sec->dofs_entsize > arg_sec->dofs_size) {
14955                         dtrace_dof_error(dof, "invalid args");
14956                         return (-1);
14957                 }
14958 
14959                 typeidx = probe->dofpr_nargv;
14960                 typestr = strtab + probe->dofpr_nargv;
14961                 for (k = 0; k < probe->dofpr_nargc; k++) {
14962                         if (typeidx >= str_sec->dofs_size) {
14963                                 dtrace_dof_error(dof, "bad "
14964                                     "native argument type");
14965                                 return (-1);
14966                         }
14967 
14968                         typesz = strlen(typestr) + 1;
14969                         if (typesz > DTRACE_ARGTYPELEN) {
14970                                 dtrace_dof_error(dof, "native "
14971                                     "argument type too long");
14972                                 return (-1);
14973                         }
14974                         typeidx += typesz;
14975                         typestr += typesz;
14976                 }
14977 
14978                 typeidx = probe->dofpr_xargv;
14979                 typestr = strtab + probe->dofpr_xargv;
14980                 for (k = 0; k < probe->dofpr_xargc; k++) {
14981                         if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14982                                 dtrace_dof_error(dof, "bad "
14983                                     "native argument index");
14984                                 return (-1);
14985                         }
14986 
14987                         if (typeidx >= str_sec->dofs_size) {
14988                                 dtrace_dof_error(dof, "bad "
14989                                     "translated argument type");
14990                                 return (-1);
14991                         }
14992 
14993                         typesz = strlen(typestr) + 1;
14994                         if (typesz > DTRACE_ARGTYPELEN) {
14995                                 dtrace_dof_error(dof, "translated argument "
14996                                     "type too long");
14997                                 return (-1);
14998                         }
14999 
15000                         typeidx += typesz;
15001                         typestr += typesz;
15002                 }
15003         }
15004 
15005         return (0);
15006 }
15007 
15008 static int
15009 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
15010 {
15011         dtrace_helpers_t *help;
15012         dtrace_vstate_t *vstate;
15013         dtrace_enabling_t *enab = NULL;
15014         int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15015         uintptr_t daddr = (uintptr_t)dof;
15016 
15017         ASSERT(MUTEX_HELD(&dtrace_lock));
15018 
15019         if ((help = curproc->p_dtrace_helpers) == NULL)
15020                 help = dtrace_helpers_create(curproc);
15021 
15022         vstate = &help->dthps_vstate;
15023 
15024         if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15025             dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15026                 dtrace_dof_destroy(dof);
15027                 return (rv);
15028         }
15029 
15030         /*
15031          * Look for helper providers and validate their descriptions.
15032          */
15033         if (dhp != NULL) {
15034                 for (i = 0; i < dof->dofh_secnum; i++) {
15035                         dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15036                             dof->dofh_secoff + i * dof->dofh_secsize);
15037 
15038                         if (sec->dofs_type != DOF_SECT_PROVIDER)
15039                                 continue;
15040 
15041                         if (dtrace_helper_provider_validate(dof, sec) != 0) {
15042                                 dtrace_enabling_destroy(enab);
15043                                 dtrace_dof_destroy(dof);
15044                                 return (-1);
15045                         }
15046 
15047                         nprovs++;
15048                 }
15049         }
15050 
15051         /*
15052          * Now we need to walk through the ECB descriptions in the enabling.
15053          */
15054         for (i = 0; i < enab->dten_ndesc; i++) {
15055                 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15056                 dtrace_probedesc_t *desc = &ep->dted_probe;
15057 
15058                 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
15059                         continue;
15060 
15061                 if (strcmp(desc->dtpd_mod, "helper") != 0)
15062                         continue;
15063 
15064                 if (strcmp(desc->dtpd_func, "ustack") != 0)
15065                         continue;
15066 
15067                 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
15068                     ep)) != 0) {
15069                         /*
15070                          * Adding this helper action failed -- we are now going
15071                          * to rip out the entire generation and return failure.
15072                          */
15073                         (void) dtrace_helper_destroygen(help->dthps_generation);
15074                         dtrace_enabling_destroy(enab);
15075                         dtrace_dof_destroy(dof);
15076                         return (-1);
15077                 }
15078 
15079                 nhelpers++;
15080         }
15081 
15082         if (nhelpers < enab->dten_ndesc)
15083                 dtrace_dof_error(dof, "unmatched helpers");
15084 
15085         gen = help->dthps_generation++;
15086         dtrace_enabling_destroy(enab);
15087 
15088         if (dhp != NULL && nprovs > 0) {
15089                 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15090                 if (dtrace_helper_provider_add(dhp, gen) == 0) {
15091                         mutex_exit(&dtrace_lock);
15092                         dtrace_helper_provider_register(curproc, help, dhp);
15093                         mutex_enter(&dtrace_lock);
15094 
15095                         destroy = 0;
15096                 }
15097         }
15098 
15099         if (destroy)
15100                 dtrace_dof_destroy(dof);
15101 
15102         return (gen);
15103 }
15104 
15105 static dtrace_helpers_t *
15106 dtrace_helpers_create(proc_t *p)
15107 {
15108         dtrace_helpers_t *help;
15109 
15110         ASSERT(MUTEX_HELD(&dtrace_lock));
15111         ASSERT(p->p_dtrace_helpers == NULL);
15112 
15113         help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15114         help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15115             DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15116 
15117         p->p_dtrace_helpers = help;
15118         dtrace_helpers++;
15119 
15120         return (help);
15121 }
15122 
15123 static void
15124 dtrace_helpers_destroy(void)
15125 {
15126         dtrace_helpers_t *help;
15127         dtrace_vstate_t *vstate;
15128         proc_t *p = curproc;
15129         int i;
15130 
15131         mutex_enter(&dtrace_lock);
15132 
15133         ASSERT(p->p_dtrace_helpers != NULL);
15134         ASSERT(dtrace_helpers > 0);
15135 
15136         help = p->p_dtrace_helpers;
15137         vstate = &help->dthps_vstate;
15138 
15139         /*
15140          * We're now going to lose the help from this process.
15141          */
15142         p->p_dtrace_helpers = NULL;
15143         dtrace_sync();
15144 
15145         /*
15146          * Destory the helper actions.
15147          */
15148         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15149                 dtrace_helper_action_t *h, *next;
15150 
15151                 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15152                         next = h->dtha_next;
15153                         dtrace_helper_action_destroy(h, vstate);
15154                         h = next;
15155                 }
15156         }
15157 
15158         mutex_exit(&dtrace_lock);
15159 
15160         /*
15161          * Destroy the helper providers.
15162          */
15163         if (help->dthps_maxprovs > 0) {
15164                 mutex_enter(&dtrace_meta_lock);
15165                 if (dtrace_meta_pid != NULL) {
15166                         ASSERT(dtrace_deferred_pid == NULL);
15167 
15168                         for (i = 0; i < help->dthps_nprovs; i++) {
15169                                 dtrace_helper_provider_remove(
15170                                     &help->dthps_provs[i]->dthp_prov, p->p_pid);
15171                         }
15172                 } else {
15173                         mutex_enter(&dtrace_lock);
15174                         ASSERT(help->dthps_deferred == 0 ||
15175                             help->dthps_next != NULL ||
15176                             help->dthps_prev != NULL ||
15177                             help == dtrace_deferred_pid);
15178 
15179                         /*
15180                          * Remove the helper from the deferred list.
15181                          */
15182                         if (help->dthps_next != NULL)
15183                                 help->dthps_next->dthps_prev = help->dthps_prev;
15184                         if (help->dthps_prev != NULL)
15185                                 help->dthps_prev->dthps_next = help->dthps_next;
15186                         if (dtrace_deferred_pid == help) {
15187                                 dtrace_deferred_pid = help->dthps_next;
15188                                 ASSERT(help->dthps_prev == NULL);
15189                         }
15190 
15191                         mutex_exit(&dtrace_lock);
15192                 }
15193 
15194                 mutex_exit(&dtrace_meta_lock);
15195 
15196                 for (i = 0; i < help->dthps_nprovs; i++) {
15197                         dtrace_helper_provider_destroy(help->dthps_provs[i]);
15198                 }
15199 
15200                 kmem_free(help->dthps_provs, help->dthps_maxprovs *
15201                     sizeof (dtrace_helper_provider_t *));
15202         }
15203 
15204         mutex_enter(&dtrace_lock);
15205 
15206         dtrace_vstate_fini(&help->dthps_vstate);
15207         kmem_free(help->dthps_actions,
15208             sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15209         kmem_free(help, sizeof (dtrace_helpers_t));
15210 
15211         --dtrace_helpers;
15212         mutex_exit(&dtrace_lock);
15213 }
15214 
15215 static void
15216 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15217 {
15218         dtrace_helpers_t *help, *newhelp;
15219         dtrace_helper_action_t *helper, *new, *last;
15220         dtrace_difo_t *dp;
15221         dtrace_vstate_t *vstate;
15222         int i, j, sz, hasprovs = 0;
15223 
15224         mutex_enter(&dtrace_lock);
15225         ASSERT(from->p_dtrace_helpers != NULL);
15226         ASSERT(dtrace_helpers > 0);
15227 
15228         help = from->p_dtrace_helpers;
15229         newhelp = dtrace_helpers_create(to);
15230         ASSERT(to->p_dtrace_helpers != NULL);
15231 
15232         newhelp->dthps_generation = help->dthps_generation;
15233         vstate = &newhelp->dthps_vstate;
15234 
15235         /*
15236          * Duplicate the helper actions.
15237          */
15238         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15239                 if ((helper = help->dthps_actions[i]) == NULL)
15240                         continue;
15241 
15242                 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15243                         new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15244                             KM_SLEEP);
15245                         new->dtha_generation = helper->dtha_generation;
15246 
15247                         if ((dp = helper->dtha_predicate) != NULL) {
15248                                 dp = dtrace_difo_duplicate(dp, vstate);
15249                                 new->dtha_predicate = dp;
15250                         }
15251 
15252                         new->dtha_nactions = helper->dtha_nactions;
15253                         sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15254                         new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15255 
15256                         for (j = 0; j < new->dtha_nactions; j++) {
15257                                 dtrace_difo_t *dp = helper->dtha_actions[j];
15258 
15259                                 ASSERT(dp != NULL);
15260                                 dp = dtrace_difo_duplicate(dp, vstate);
15261                                 new->dtha_actions[j] = dp;
15262                         }
15263 
15264                         if (last != NULL) {
15265                                 last->dtha_next = new;
15266                         } else {
15267                                 newhelp->dthps_actions[i] = new;
15268                         }
15269 
15270                         last = new;
15271                 }
15272         }
15273 
15274         /*
15275          * Duplicate the helper providers and register them with the
15276          * DTrace framework.
15277          */
15278         if (help->dthps_nprovs > 0) {
15279                 newhelp->dthps_nprovs = help->dthps_nprovs;
15280                 newhelp->dthps_maxprovs = help->dthps_nprovs;
15281                 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15282                     sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15283                 for (i = 0; i < newhelp->dthps_nprovs; i++) {
15284                         newhelp->dthps_provs[i] = help->dthps_provs[i];
15285                         newhelp->dthps_provs[i]->dthp_ref++;
15286                 }
15287 
15288                 hasprovs = 1;
15289         }
15290 
15291         mutex_exit(&dtrace_lock);
15292 
15293         if (hasprovs)
15294                 dtrace_helper_provider_register(to, newhelp, NULL);
15295 }
15296 
15297 /*
15298  * DTrace Hook Functions
15299  */
15300 static void
15301 dtrace_module_loaded(struct modctl *ctl)
15302 {
15303         dtrace_provider_t *prv;
15304 
15305         mutex_enter(&dtrace_provider_lock);
15306         mutex_enter(&mod_lock);
15307 
15308         ASSERT(ctl->mod_busy);
15309 
15310         /*
15311          * We're going to call each providers per-module provide operation
15312          * specifying only this module.
15313          */
15314         for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15315                 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15316 
15317         mutex_exit(&mod_lock);
15318         mutex_exit(&dtrace_provider_lock);
15319 
15320         /*
15321          * If we have any retained enablings, we need to match against them.
15322          * Enabling probes requires that cpu_lock be held, and we cannot hold
15323          * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15324          * module.  (In particular, this happens when loading scheduling
15325          * classes.)  So if we have any retained enablings, we need to dispatch
15326          * our task queue to do the match for us.
15327          */
15328         mutex_enter(&dtrace_lock);
15329 
15330         if (dtrace_retained == NULL) {
15331                 mutex_exit(&dtrace_lock);
15332                 return;
15333         }
15334 
15335         (void) taskq_dispatch(dtrace_taskq,
15336             (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15337 
15338         mutex_exit(&dtrace_lock);
15339 
15340         /*
15341          * And now, for a little heuristic sleaze:  in general, we want to
15342          * match modules as soon as they load.  However, we cannot guarantee
15343          * this, because it would lead us to the lock ordering violation
15344          * outlined above.  The common case, of course, is that cpu_lock is
15345          * _not_ held -- so we delay here for a clock tick, hoping that that's
15346          * long enough for the task queue to do its work.  If it's not, it's
15347          * not a serious problem -- it just means that the module that we
15348          * just loaded may not be immediately instrumentable.
15349          */
15350         delay(1);
15351 }
15352 
15353 static void
15354 dtrace_module_unloaded(struct modctl *ctl)
15355 {
15356         dtrace_probe_t template, *probe, *first, *next;
15357         dtrace_provider_t *prov;
15358 
15359         template.dtpr_mod = ctl->mod_modname;
15360 
15361         mutex_enter(&dtrace_provider_lock);
15362         mutex_enter(&mod_lock);
15363         mutex_enter(&dtrace_lock);
15364 
15365         if (dtrace_bymod == NULL) {
15366                 /*
15367                  * The DTrace module is loaded (obviously) but not attached;
15368                  * we don't have any work to do.
15369                  */
15370                 mutex_exit(&dtrace_provider_lock);
15371                 mutex_exit(&mod_lock);
15372                 mutex_exit(&dtrace_lock);
15373                 return;
15374         }
15375 
15376         for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15377             probe != NULL; probe = probe->dtpr_nextmod) {
15378                 if (probe->dtpr_ecb != NULL) {
15379                         mutex_exit(&dtrace_provider_lock);
15380                         mutex_exit(&mod_lock);
15381                         mutex_exit(&dtrace_lock);
15382 
15383                         /*
15384                          * This shouldn't _actually_ be possible -- we're
15385                          * unloading a module that has an enabled probe in it.
15386                          * (It's normally up to the provider to make sure that
15387                          * this can't happen.)  However, because dtps_enable()
15388                          * doesn't have a failure mode, there can be an
15389                          * enable/unload race.  Upshot:  we don't want to
15390                          * assert, but we're not going to disable the
15391                          * probe, either.
15392                          */
15393                         if (dtrace_err_verbose) {
15394                                 cmn_err(CE_WARN, "unloaded module '%s' had "
15395                                     "enabled probes", ctl->mod_modname);
15396                         }
15397 
15398                         return;
15399                 }
15400         }
15401 
15402         probe = first;
15403 
15404         for (first = NULL; probe != NULL; probe = next) {
15405                 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15406 
15407                 dtrace_probes[probe->dtpr_id - 1] = NULL;
15408 
15409                 next = probe->dtpr_nextmod;
15410                 dtrace_hash_remove(dtrace_bymod, probe);
15411                 dtrace_hash_remove(dtrace_byfunc, probe);
15412                 dtrace_hash_remove(dtrace_byname, probe);
15413 
15414                 if (first == NULL) {
15415                         first = probe;
15416                         probe->dtpr_nextmod = NULL;
15417                 } else {
15418                         probe->dtpr_nextmod = first;
15419                         first = probe;
15420                 }
15421         }
15422 
15423         /*
15424          * We've removed all of the module's probes from the hash chains and
15425          * from the probe array.  Now issue a dtrace_sync() to be sure that
15426          * everyone has cleared out from any probe array processing.
15427          */
15428         dtrace_sync();
15429 
15430         for (probe = first; probe != NULL; probe = first) {
15431                 first = probe->dtpr_nextmod;
15432                 prov = probe->dtpr_provider;
15433                 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15434                     probe->dtpr_arg);
15435                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15436                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15437                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15438                 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15439                 kmem_free(probe, sizeof (dtrace_probe_t));
15440         }
15441 
15442         mutex_exit(&dtrace_lock);
15443         mutex_exit(&mod_lock);
15444         mutex_exit(&dtrace_provider_lock);
15445 }
15446 
15447 void
15448 dtrace_suspend(void)
15449 {
15450         dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15451 }
15452 
15453 void
15454 dtrace_resume(void)
15455 {
15456         dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15457 }
15458 
15459 static int
15460 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15461 {
15462         ASSERT(MUTEX_HELD(&cpu_lock));
15463         mutex_enter(&dtrace_lock);
15464 
15465         switch (what) {
15466         case CPU_CONFIG: {
15467                 dtrace_state_t *state;
15468                 dtrace_optval_t *opt, rs, c;
15469 
15470                 /*
15471                  * For now, we only allocate a new buffer for anonymous state.
15472                  */
15473                 if ((state = dtrace_anon.dta_state) == NULL)
15474                         break;
15475 
15476                 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15477                         break;
15478 
15479                 opt = state->dts_options;
15480                 c = opt[DTRACEOPT_CPU];
15481 
15482                 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15483                         break;
15484 
15485                 /*
15486                  * Regardless of what the actual policy is, we're going to
15487                  * temporarily set our resize policy to be manual.  We're
15488                  * also going to temporarily set our CPU option to denote
15489                  * the newly configured CPU.
15490                  */
15491                 rs = opt[DTRACEOPT_BUFRESIZE];
15492                 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15493                 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15494 
15495                 (void) dtrace_state_buffers(state);
15496 
15497                 opt[DTRACEOPT_BUFRESIZE] = rs;
15498                 opt[DTRACEOPT_CPU] = c;
15499 
15500                 break;
15501         }
15502 
15503         case CPU_UNCONFIG:
15504                 /*
15505                  * We don't free the buffer in the CPU_UNCONFIG case.  (The
15506                  * buffer will be freed when the consumer exits.)
15507                  */
15508                 break;
15509 
15510         default:
15511                 break;
15512         }
15513 
15514         mutex_exit(&dtrace_lock);
15515         return (0);
15516 }
15517 
15518 static void
15519 dtrace_cpu_setup_initial(processorid_t cpu)
15520 {
15521         (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15522 }
15523 
15524 static void
15525 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15526 {
15527         if (dtrace_toxranges >= dtrace_toxranges_max) {
15528                 int osize, nsize;
15529                 dtrace_toxrange_t *range;
15530 
15531                 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15532 
15533                 if (osize == 0) {
15534                         ASSERT(dtrace_toxrange == NULL);
15535                         ASSERT(dtrace_toxranges_max == 0);
15536                         dtrace_toxranges_max = 1;
15537                 } else {
15538                         dtrace_toxranges_max <<= 1;
15539                 }
15540 
15541                 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15542                 range = kmem_zalloc(nsize, KM_SLEEP);
15543 
15544                 if (dtrace_toxrange != NULL) {
15545                         ASSERT(osize != 0);
15546                         bcopy(dtrace_toxrange, range, osize);
15547                         kmem_free(dtrace_toxrange, osize);
15548                 }
15549 
15550                 dtrace_toxrange = range;
15551         }
15552 
15553         ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
15554         ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
15555 
15556         dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15557         dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15558         dtrace_toxranges++;
15559 }
15560 
15561 static void
15562 dtrace_getf_barrier()
15563 {
15564         /*
15565          * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
15566          * that contain calls to getf(), this routine will be called on every
15567          * closef() before either the underlying vnode is released or the
15568          * file_t itself is freed.  By the time we are here, it is essential
15569          * that the file_t can no longer be accessed from a call to getf()
15570          * in probe context -- that assures that a dtrace_sync() can be used
15571          * to clear out any enablings referring to the old structures.
15572          */
15573         if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
15574             kcred->cr_zone->zone_dtrace_getf != 0)
15575                 dtrace_sync();
15576 }
15577 
15578 /*
15579  * DTrace Driver Cookbook Functions
15580  */
15581 /*ARGSUSED*/
15582 static int
15583 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15584 {
15585         dtrace_provider_id_t id;
15586         dtrace_state_t *state = NULL;
15587         dtrace_enabling_t *enab;
15588 
15589         mutex_enter(&cpu_lock);
15590         mutex_enter(&dtrace_provider_lock);
15591         mutex_enter(&dtrace_lock);
15592 
15593         if (ddi_soft_state_init(&dtrace_softstate,
15594             sizeof (dtrace_state_t), 0) != 0) {
15595                 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15596                 mutex_exit(&cpu_lock);
15597                 mutex_exit(&dtrace_provider_lock);
15598                 mutex_exit(&dtrace_lock);
15599                 return (DDI_FAILURE);
15600         }
15601 
15602         if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
15603             DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
15604             ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
15605             DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
15606                 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
15607                 ddi_remove_minor_node(devi, NULL);
15608                 ddi_soft_state_fini(&dtrace_softstate);
15609                 mutex_exit(&cpu_lock);
15610                 mutex_exit(&dtrace_provider_lock);
15611                 mutex_exit(&dtrace_lock);
15612                 return (DDI_FAILURE);
15613         }
15614 
15615         ddi_report_dev(devi);
15616         dtrace_devi = devi;
15617 
15618         dtrace_modload = dtrace_module_loaded;
15619         dtrace_modunload = dtrace_module_unloaded;
15620         dtrace_cpu_init = dtrace_cpu_setup_initial;
15621         dtrace_helpers_cleanup = dtrace_helpers_destroy;
15622         dtrace_helpers_fork = dtrace_helpers_duplicate;
15623         dtrace_cpustart_init = dtrace_suspend;
15624         dtrace_cpustart_fini = dtrace_resume;
15625         dtrace_debugger_init = dtrace_suspend;
15626         dtrace_debugger_fini = dtrace_resume;
15627 
15628         register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15629 
15630         ASSERT(MUTEX_HELD(&cpu_lock));
15631 
15632         dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15633             NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15634         dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15635             UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15636             VM_SLEEP | VMC_IDENTIFIER);
15637         dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15638             1, INT_MAX, 0);
15639 
15640         dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15641             sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
15642             NULL, NULL, NULL, NULL, NULL, 0);
15643 
15644         ASSERT(MUTEX_HELD(&cpu_lock));
15645         dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15646             offsetof(dtrace_probe_t, dtpr_nextmod),
15647             offsetof(dtrace_probe_t, dtpr_prevmod));
15648 
15649         dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15650             offsetof(dtrace_probe_t, dtpr_nextfunc),
15651             offsetof(dtrace_probe_t, dtpr_prevfunc));
15652 
15653         dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15654             offsetof(dtrace_probe_t, dtpr_nextname),
15655             offsetof(dtrace_probe_t, dtpr_prevname));
15656 
15657         if (dtrace_retain_max < 1) {
15658                 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15659                     "setting to 1", dtrace_retain_max);
15660                 dtrace_retain_max = 1;
15661         }
15662 
15663         /*
15664          * Now discover our toxic ranges.
15665          */
15666         dtrace_toxic_ranges(dtrace_toxrange_add);
15667 
15668         /*
15669          * Before we register ourselves as a provider to our own framework,
15670          * we would like to assert that dtrace_provider is NULL -- but that's
15671          * not true if we were loaded as a dependency of a DTrace provider.
15672          * Once we've registered, we can assert that dtrace_provider is our
15673          * pseudo provider.
15674          */
15675         (void) dtrace_register("dtrace", &dtrace_provider_attr,
15676             DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15677 
15678         ASSERT(dtrace_provider != NULL);
15679         ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15680 
15681         dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15682             dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
15683         dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15684             dtrace_provider, NULL, NULL, "END", 0, NULL);
15685         dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15686             dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15687 
15688         dtrace_anon_property();
15689         mutex_exit(&cpu_lock);
15690 
15691         /*
15692          * If there are already providers, we must ask them to provide their
15693          * probes, and then match any anonymous enabling against them.  Note
15694          * that there should be no other retained enablings at this time:
15695          * the only retained enablings at this time should be the anonymous
15696          * enabling.
15697          */
15698         if (dtrace_anon.dta_enabling != NULL) {
15699                 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15700 
15701                 dtrace_enabling_provide(NULL);
15702                 state = dtrace_anon.dta_state;
15703 
15704                 /*
15705                  * We couldn't hold cpu_lock across the above call to
15706                  * dtrace_enabling_provide(), but we must hold it to actually
15707                  * enable the probes.  We have to drop all of our locks, pick
15708                  * up cpu_lock, and regain our locks before matching the
15709                  * retained anonymous enabling.
15710                  */
15711                 mutex_exit(&dtrace_lock);
15712                 mutex_exit(&dtrace_provider_lock);
15713 
15714                 mutex_enter(&cpu_lock);
15715                 mutex_enter(&dtrace_provider_lock);
15716                 mutex_enter(&dtrace_lock);
15717 
15718                 if ((enab = dtrace_anon.dta_enabling) != NULL)
15719                         (void) dtrace_enabling_match(enab, NULL);
15720 
15721                 mutex_exit(&cpu_lock);
15722         }
15723 
15724         mutex_exit(&dtrace_lock);
15725         mutex_exit(&dtrace_provider_lock);
15726 
15727         if (state != NULL) {
15728                 /*
15729                  * If we created any anonymous state, set it going now.
15730                  */
15731                 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15732         }
15733 
15734         return (DDI_SUCCESS);
15735 }
15736 
15737 /*ARGSUSED*/
15738 static int
15739 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15740 {
15741         dtrace_state_t *state;
15742         uint32_t priv;
15743         uid_t uid;
15744         zoneid_t zoneid;
15745 
15746         if (getminor(*devp) == DTRACEMNRN_HELPER)
15747                 return (0);
15748 
15749         /*
15750          * If this wasn't an open with the "helper" minor, then it must be
15751          * the "dtrace" minor.
15752          */
15753         if (getminor(*devp) != DTRACEMNRN_DTRACE)
15754                 return (ENXIO);
15755 
15756         /*
15757          * If no DTRACE_PRIV_* bits are set in the credential, then the
15758          * caller lacks sufficient permission to do anything with DTrace.
15759          */
15760         dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15761         if (priv == DTRACE_PRIV_NONE)
15762                 return (EACCES);
15763 
15764         /*
15765          * Ask all providers to provide all their probes.
15766          */
15767         mutex_enter(&dtrace_provider_lock);
15768         dtrace_probe_provide(NULL, NULL);
15769         mutex_exit(&dtrace_provider_lock);
15770 
15771         mutex_enter(&cpu_lock);
15772         mutex_enter(&dtrace_lock);
15773         dtrace_opens++;
15774         dtrace_membar_producer();
15775 
15776         /*
15777          * If the kernel debugger is active (that is, if the kernel debugger
15778          * modified text in some way), we won't allow the open.
15779          */
15780         if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15781                 dtrace_opens--;
15782                 mutex_exit(&cpu_lock);
15783                 mutex_exit(&dtrace_lock);
15784                 return (EBUSY);
15785         }
15786 
15787         if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
15788                 /*
15789                  * If DTrace helper tracing is enabled, we need to allocate the
15790                  * trace buffer and initialize the values.
15791                  */
15792                 dtrace_helptrace_buffer =
15793                     kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15794                 dtrace_helptrace_next = 0;
15795                 dtrace_helptrace_wrapped = 0;
15796                 dtrace_helptrace_enable = 0;
15797         }
15798 
15799         state = dtrace_state_create(devp, cred_p);
15800         mutex_exit(&cpu_lock);
15801 
15802         if (state == NULL) {
15803                 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15804                         (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15805                 mutex_exit(&dtrace_lock);
15806                 return (EAGAIN);
15807         }
15808 
15809         mutex_exit(&dtrace_lock);
15810 
15811         return (0);
15812 }
15813 
15814 /*ARGSUSED*/
15815 static int
15816 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15817 {
15818         minor_t minor = getminor(dev);
15819         dtrace_state_t *state;
15820         dtrace_helptrace_t *buf = NULL;
15821 
15822         if (minor == DTRACEMNRN_HELPER)
15823                 return (0);
15824 
15825         state = ddi_get_soft_state(dtrace_softstate, minor);
15826 
15827         mutex_enter(&cpu_lock);
15828         mutex_enter(&dtrace_lock);
15829 
15830         if (state->dts_anon) {
15831                 /*
15832                  * There is anonymous state. Destroy that first.
15833                  */
15834                 ASSERT(dtrace_anon.dta_state == NULL);
15835                 dtrace_state_destroy(state->dts_anon);
15836         }
15837 
15838         if (dtrace_helptrace_disable) {
15839                 /*
15840                  * If we have been told to disable helper tracing, set the
15841                  * buffer to NULL before calling into dtrace_state_destroy();
15842                  * we take advantage of its dtrace_sync() to know that no
15843                  * CPU is in probe context with enabled helper tracing
15844                  * after it returns.
15845                  */
15846                 buf = dtrace_helptrace_buffer;
15847                 dtrace_helptrace_buffer = NULL;
15848         }
15849 
15850         dtrace_state_destroy(state);
15851         ASSERT(dtrace_opens > 0);
15852 
15853         /*
15854          * Only relinquish control of the kernel debugger interface when there
15855          * are no consumers and no anonymous enablings.
15856          */
15857         if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15858                 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15859 
15860         if (buf != NULL) {
15861                 kmem_free(buf, dtrace_helptrace_bufsize);
15862                 dtrace_helptrace_disable = 0;
15863         }
15864 
15865         mutex_exit(&dtrace_lock);
15866         mutex_exit(&cpu_lock);
15867 
15868         return (0);
15869 }
15870 
15871 /*ARGSUSED*/
15872 static int
15873 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
15874 {
15875         int rval;
15876         dof_helper_t help, *dhp = NULL;
15877 
15878         switch (cmd) {
15879         case DTRACEHIOC_ADDDOF:
15880                 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
15881                         dtrace_dof_error(NULL, "failed to copyin DOF helper");
15882                         return (EFAULT);
15883                 }
15884 
15885                 dhp = &help;
15886                 arg = (intptr_t)help.dofhp_dof;
15887                 /*FALLTHROUGH*/
15888 
15889         case DTRACEHIOC_ADD: {
15890                 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
15891 
15892                 if (dof == NULL)
15893                         return (rval);
15894 
15895                 mutex_enter(&dtrace_lock);
15896 
15897                 /*
15898                  * dtrace_helper_slurp() takes responsibility for the dof --
15899                  * it may free it now or it may save it and free it later.
15900                  */
15901                 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
15902                         *rv = rval;
15903                         rval = 0;
15904                 } else {
15905                         rval = EINVAL;
15906                 }
15907 
15908                 mutex_exit(&dtrace_lock);
15909                 return (rval);
15910         }
15911 
15912         case DTRACEHIOC_REMOVE: {
15913                 mutex_enter(&dtrace_lock);
15914                 rval = dtrace_helper_destroygen(arg);
15915                 mutex_exit(&dtrace_lock);
15916 
15917                 return (rval);
15918         }
15919 
15920         default:
15921                 break;
15922         }
15923 
15924         return (ENOTTY);
15925 }
15926 
15927 /*ARGSUSED*/
15928 static int
15929 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
15930 {
15931         minor_t minor = getminor(dev);
15932         dtrace_state_t *state;
15933         int rval;
15934 
15935         if (minor == DTRACEMNRN_HELPER)
15936                 return (dtrace_ioctl_helper(cmd, arg, rv));
15937 
15938         state = ddi_get_soft_state(dtrace_softstate, minor);
15939 
15940         if (state->dts_anon) {
15941                 ASSERT(dtrace_anon.dta_state == NULL);
15942                 state = state->dts_anon;
15943         }
15944 
15945         switch (cmd) {
15946         case DTRACEIOC_PROVIDER: {
15947                 dtrace_providerdesc_t pvd;
15948                 dtrace_provider_t *pvp;
15949 
15950                 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
15951                         return (EFAULT);
15952 
15953                 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
15954                 mutex_enter(&dtrace_provider_lock);
15955 
15956                 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
15957                         if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
15958                                 break;
15959                 }
15960 
15961                 mutex_exit(&dtrace_provider_lock);
15962 
15963                 if (pvp == NULL)
15964                         return (ESRCH);
15965 
15966                 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
15967                 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
15968                 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
15969                         return (EFAULT);
15970 
15971                 return (0);
15972         }
15973 
15974         case DTRACEIOC_EPROBE: {
15975                 dtrace_eprobedesc_t epdesc;
15976                 dtrace_ecb_t *ecb;
15977                 dtrace_action_t *act;
15978                 void *buf;
15979                 size_t size;
15980                 uintptr_t dest;
15981                 int nrecs;
15982 
15983                 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
15984                         return (EFAULT);
15985 
15986                 mutex_enter(&dtrace_lock);
15987 
15988                 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
15989                         mutex_exit(&dtrace_lock);
15990                         return (EINVAL);
15991                 }
15992 
15993                 if (ecb->dte_probe == NULL) {
15994                         mutex_exit(&dtrace_lock);
15995                         return (EINVAL);
15996                 }
15997 
15998                 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
15999                 epdesc.dtepd_uarg = ecb->dte_uarg;
16000                 epdesc.dtepd_size = ecb->dte_size;
16001 
16002                 nrecs = epdesc.dtepd_nrecs;
16003                 epdesc.dtepd_nrecs = 0;
16004                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16005                         if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16006                                 continue;
16007 
16008                         epdesc.dtepd_nrecs++;
16009                 }
16010 
16011                 /*
16012                  * Now that we have the size, we need to allocate a temporary
16013                  * buffer in which to store the complete description.  We need
16014                  * the temporary buffer to be able to drop dtrace_lock()
16015                  * across the copyout(), below.
16016                  */
16017                 size = sizeof (dtrace_eprobedesc_t) +
16018                     (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16019 
16020                 buf = kmem_alloc(size, KM_SLEEP);
16021                 dest = (uintptr_t)buf;
16022 
16023                 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16024                 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16025 
16026                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16027                         if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16028                                 continue;
16029 
16030                         if (nrecs-- == 0)
16031                                 break;
16032 
16033                         bcopy(&act->dta_rec, (void *)dest,
16034                             sizeof (dtrace_recdesc_t));
16035                         dest += sizeof (dtrace_recdesc_t);
16036                 }
16037 
16038                 mutex_exit(&dtrace_lock);
16039 
16040                 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16041                         kmem_free(buf, size);
16042                         return (EFAULT);
16043                 }
16044 
16045                 kmem_free(buf, size);
16046                 return (0);
16047         }
16048 
16049         case DTRACEIOC_AGGDESC: {
16050                 dtrace_aggdesc_t aggdesc;
16051                 dtrace_action_t *act;
16052                 dtrace_aggregation_t *agg;
16053                 int nrecs;
16054                 uint32_t offs;
16055                 dtrace_recdesc_t *lrec;
16056                 void *buf;
16057                 size_t size;
16058                 uintptr_t dest;
16059 
16060                 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
16061                         return (EFAULT);
16062 
16063                 mutex_enter(&dtrace_lock);
16064 
16065                 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16066                         mutex_exit(&dtrace_lock);
16067                         return (EINVAL);
16068                 }
16069 
16070                 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16071 
16072                 nrecs = aggdesc.dtagd_nrecs;
16073                 aggdesc.dtagd_nrecs = 0;
16074 
16075                 offs = agg->dtag_base;
16076                 lrec = &agg->dtag_action.dta_rec;
16077                 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16078 
16079                 for (act = agg->dtag_first; ; act = act->dta_next) {
16080                         ASSERT(act->dta_intuple ||
16081                             DTRACEACT_ISAGG(act->dta_kind));
16082 
16083                         /*
16084                          * If this action has a record size of zero, it
16085                          * denotes an argument to the aggregating action.
16086                          * Because the presence of this record doesn't (or
16087                          * shouldn't) affect the way the data is interpreted,
16088                          * we don't copy it out to save user-level the
16089                          * confusion of dealing with a zero-length record.
16090                          */
16091                         if (act->dta_rec.dtrd_size == 0) {
16092                                 ASSERT(agg->dtag_hasarg);
16093                                 continue;
16094                         }
16095 
16096                         aggdesc.dtagd_nrecs++;
16097 
16098                         if (act == &agg->dtag_action)
16099                                 break;
16100                 }
16101 
16102                 /*
16103                  * Now that we have the size, we need to allocate a temporary
16104                  * buffer in which to store the complete description.  We need
16105                  * the temporary buffer to be able to drop dtrace_lock()
16106                  * across the copyout(), below.
16107                  */
16108                 size = sizeof (dtrace_aggdesc_t) +
16109                     (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16110 
16111                 buf = kmem_alloc(size, KM_SLEEP);
16112                 dest = (uintptr_t)buf;
16113 
16114                 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16115                 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16116 
16117                 for (act = agg->dtag_first; ; act = act->dta_next) {
16118                         dtrace_recdesc_t rec = act->dta_rec;
16119 
16120                         /*
16121                          * See the comment in the above loop for why we pass
16122                          * over zero-length records.
16123                          */
16124                         if (rec.dtrd_size == 0) {
16125                                 ASSERT(agg->dtag_hasarg);
16126                                 continue;
16127                         }
16128 
16129                         if (nrecs-- == 0)
16130                                 break;
16131 
16132                         rec.dtrd_offset -= offs;
16133                         bcopy(&rec, (void *)dest, sizeof (rec));
16134                         dest += sizeof (dtrace_recdesc_t);
16135 
16136                         if (act == &agg->dtag_action)
16137                                 break;
16138                 }
16139 
16140                 mutex_exit(&dtrace_lock);
16141 
16142                 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16143                         kmem_free(buf, size);
16144                         return (EFAULT);
16145                 }
16146 
16147                 kmem_free(buf, size);
16148                 return (0);
16149         }
16150 
16151         case DTRACEIOC_ENABLE: {
16152                 dof_hdr_t *dof;
16153                 dtrace_enabling_t *enab = NULL;
16154                 dtrace_vstate_t *vstate;
16155                 int err = 0;
16156 
16157                 *rv = 0;
16158 
16159                 /*
16160                  * If a NULL argument has been passed, we take this as our
16161                  * cue to reevaluate our enablings.
16162                  */
16163                 if (arg == NULL) {
16164                         dtrace_enabling_matchall();
16165 
16166                         return (0);
16167                 }
16168 
16169                 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16170                         return (rval);
16171 
16172                 mutex_enter(&cpu_lock);
16173                 mutex_enter(&dtrace_lock);
16174                 vstate = &state->dts_vstate;
16175 
16176                 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16177                         mutex_exit(&dtrace_lock);
16178                         mutex_exit(&cpu_lock);
16179                         dtrace_dof_destroy(dof);
16180                         return (EBUSY);
16181                 }
16182 
16183                 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16184                         mutex_exit(&dtrace_lock);
16185                         mutex_exit(&cpu_lock);
16186                         dtrace_dof_destroy(dof);
16187                         return (EINVAL);
16188                 }
16189 
16190                 if ((rval = dtrace_dof_options(dof, state)) != 0) {
16191                         dtrace_enabling_destroy(enab);
16192                         mutex_exit(&dtrace_lock);
16193                         mutex_exit(&cpu_lock);
16194                         dtrace_dof_destroy(dof);
16195                         return (rval);
16196                 }
16197 
16198                 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16199                         err = dtrace_enabling_retain(enab);
16200                 } else {
16201                         dtrace_enabling_destroy(enab);
16202                 }
16203 
16204                 mutex_exit(&cpu_lock);
16205                 mutex_exit(&dtrace_lock);
16206                 dtrace_dof_destroy(dof);
16207 
16208                 return (err);
16209         }
16210 
16211         case DTRACEIOC_REPLICATE: {
16212                 dtrace_repldesc_t desc;
16213                 dtrace_probedesc_t *match = &desc.dtrpd_match;
16214                 dtrace_probedesc_t *create = &desc.dtrpd_create;
16215                 int err;
16216 
16217                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16218                         return (EFAULT);
16219 
16220                 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16221                 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16222                 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16223                 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16224 
16225                 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16226                 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16227                 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16228                 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16229 
16230                 mutex_enter(&dtrace_lock);
16231                 err = dtrace_enabling_replicate(state, match, create);
16232                 mutex_exit(&dtrace_lock);
16233 
16234                 return (err);
16235         }
16236 
16237         case DTRACEIOC_PROBEMATCH:
16238         case DTRACEIOC_PROBES: {
16239                 dtrace_probe_t *probe = NULL;
16240                 dtrace_probedesc_t desc;
16241                 dtrace_probekey_t pkey;
16242                 dtrace_id_t i;
16243                 int m = 0;
16244                 uint32_t priv;
16245                 uid_t uid;
16246                 zoneid_t zoneid;
16247 
16248                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16249                         return (EFAULT);
16250 
16251                 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16252                 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16253                 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16254                 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16255 
16256                 /*
16257                  * Before we attempt to match this probe, we want to give
16258                  * all providers the opportunity to provide it.
16259                  */
16260                 if (desc.dtpd_id == DTRACE_IDNONE) {
16261                         mutex_enter(&dtrace_provider_lock);
16262                         dtrace_probe_provide(&desc, NULL);
16263                         mutex_exit(&dtrace_provider_lock);
16264                         desc.dtpd_id++;
16265                 }
16266 
16267                 if (cmd == DTRACEIOC_PROBEMATCH)  {
16268                         dtrace_probekey(&desc, &pkey);
16269                         pkey.dtpk_id = DTRACE_IDNONE;
16270                 }
16271 
16272                 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16273 
16274                 mutex_enter(&dtrace_lock);
16275 
16276                 if (cmd == DTRACEIOC_PROBEMATCH) {
16277                         for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16278                                 if ((probe = dtrace_probes[i - 1]) != NULL &&
16279                                     (m = dtrace_match_probe(probe, &pkey,
16280                                     priv, uid, zoneid)) != 0)
16281                                         break;
16282                         }
16283 
16284                         if (m < 0) {
16285                                 mutex_exit(&dtrace_lock);
16286                                 return (EINVAL);
16287                         }
16288 
16289                 } else {
16290                         for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16291                                 if ((probe = dtrace_probes[i - 1]) != NULL &&
16292                                     dtrace_match_priv(probe, priv, uid, zoneid))
16293                                         break;
16294                         }
16295                 }
16296 
16297                 if (probe == NULL) {
16298                         mutex_exit(&dtrace_lock);
16299                         return (ESRCH);
16300                 }
16301 
16302                 dtrace_probe_description(probe, &desc);
16303                 mutex_exit(&dtrace_lock);
16304 
16305                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16306                         return (EFAULT);
16307 
16308                 return (0);
16309         }
16310 
16311         case DTRACEIOC_PROBEARG: {
16312                 dtrace_argdesc_t desc;
16313                 dtrace_probe_t *probe;
16314                 dtrace_provider_t *prov;
16315 
16316                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16317                         return (EFAULT);
16318 
16319                 if (desc.dtargd_id == DTRACE_IDNONE)
16320                         return (EINVAL);
16321 
16322                 if (desc.dtargd_ndx == DTRACE_ARGNONE)
16323                         return (EINVAL);
16324 
16325                 mutex_enter(&dtrace_provider_lock);
16326                 mutex_enter(&mod_lock);
16327                 mutex_enter(&dtrace_lock);
16328 
16329                 if (desc.dtargd_id > dtrace_nprobes) {
16330                         mutex_exit(&dtrace_lock);
16331                         mutex_exit(&mod_lock);
16332                         mutex_exit(&dtrace_provider_lock);
16333                         return (EINVAL);
16334                 }
16335 
16336                 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16337                         mutex_exit(&dtrace_lock);
16338                         mutex_exit(&mod_lock);
16339                         mutex_exit(&dtrace_provider_lock);
16340                         return (EINVAL);
16341                 }
16342 
16343                 mutex_exit(&dtrace_lock);
16344 
16345                 prov = probe->dtpr_provider;
16346 
16347                 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16348                         /*
16349                          * There isn't any typed information for this probe.
16350                          * Set the argument number to DTRACE_ARGNONE.
16351                          */
16352                         desc.dtargd_ndx = DTRACE_ARGNONE;
16353                 } else {
16354                         desc.dtargd_native[0] = '\0';
16355                         desc.dtargd_xlate[0] = '\0';
16356                         desc.dtargd_mapping = desc.dtargd_ndx;
16357 
16358                         prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16359                             probe->dtpr_id, probe->dtpr_arg, &desc);
16360                 }
16361 
16362                 mutex_exit(&mod_lock);
16363                 mutex_exit(&dtrace_provider_lock);
16364 
16365                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16366                         return (EFAULT);
16367 
16368                 return (0);
16369         }
16370 
16371         case DTRACEIOC_GO: {
16372                 processorid_t cpuid;
16373                 rval = dtrace_state_go(state, &cpuid);
16374 
16375                 if (rval != 0)
16376                         return (rval);
16377 
16378                 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16379                         return (EFAULT);
16380 
16381                 return (0);
16382         }
16383 
16384         case DTRACEIOC_STOP: {
16385                 processorid_t cpuid;
16386 
16387                 mutex_enter(&dtrace_lock);
16388                 rval = dtrace_state_stop(state, &cpuid);
16389                 mutex_exit(&dtrace_lock);
16390 
16391                 if (rval != 0)
16392                         return (rval);
16393 
16394                 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16395                         return (EFAULT);
16396 
16397                 return (0);
16398         }
16399 
16400         case DTRACEIOC_DOFGET: {
16401                 dof_hdr_t hdr, *dof;
16402                 uint64_t len;
16403 
16404                 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16405                         return (EFAULT);
16406 
16407                 mutex_enter(&dtrace_lock);
16408                 dof = dtrace_dof_create(state);
16409                 mutex_exit(&dtrace_lock);
16410 
16411                 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16412                 rval = copyout(dof, (void *)arg, len);
16413                 dtrace_dof_destroy(dof);
16414 
16415                 return (rval == 0 ? 0 : EFAULT);
16416         }
16417 
16418         case DTRACEIOC_AGGSNAP:
16419         case DTRACEIOC_BUFSNAP: {
16420                 dtrace_bufdesc_t desc;
16421                 caddr_t cached;
16422                 dtrace_buffer_t *buf;
16423 
16424                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16425                         return (EFAULT);
16426 
16427                 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16428                         return (EINVAL);
16429 
16430                 mutex_enter(&dtrace_lock);
16431 
16432                 if (cmd == DTRACEIOC_BUFSNAP) {
16433                         buf = &state->dts_buffer[desc.dtbd_cpu];
16434                 } else {
16435                         buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16436                 }
16437 
16438                 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16439                         size_t sz = buf->dtb_offset;
16440 
16441                         if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16442                                 mutex_exit(&dtrace_lock);
16443                                 return (EBUSY);
16444                         }
16445 
16446                         /*
16447                          * If this buffer has already been consumed, we're
16448                          * going to indicate that there's nothing left here
16449                          * to consume.
16450                          */
16451                         if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16452                                 mutex_exit(&dtrace_lock);
16453 
16454                                 desc.dtbd_size = 0;
16455                                 desc.dtbd_drops = 0;
16456                                 desc.dtbd_errors = 0;
16457                                 desc.dtbd_oldest = 0;
16458                                 sz = sizeof (desc);
16459 
16460                                 if (copyout(&desc, (void *)arg, sz) != 0)
16461                                         return (EFAULT);
16462 
16463                                 return (0);
16464                         }
16465 
16466                         /*
16467                          * If this is a ring buffer that has wrapped, we want
16468                          * to copy the whole thing out.
16469                          */
16470                         if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16471                                 dtrace_buffer_polish(buf);
16472                                 sz = buf->dtb_size;
16473                         }
16474 
16475                         if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
16476                                 mutex_exit(&dtrace_lock);
16477                                 return (EFAULT);
16478                         }
16479 
16480                         desc.dtbd_size = sz;
16481                         desc.dtbd_drops = buf->dtb_drops;
16482                         desc.dtbd_errors = buf->dtb_errors;
16483                         desc.dtbd_oldest = buf->dtb_xamot_offset;
16484                         desc.dtbd_timestamp = dtrace_gethrtime();
16485 
16486                         mutex_exit(&dtrace_lock);
16487 
16488                         if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16489                                 return (EFAULT);
16490 
16491                         buf->dtb_flags |= DTRACEBUF_CONSUMED;
16492 
16493                         return (0);
16494                 }
16495 
16496                 if (buf->dtb_tomax == NULL) {
16497                         ASSERT(buf->dtb_xamot == NULL);
16498                         mutex_exit(&dtrace_lock);
16499                         return (ENOENT);
16500                 }
16501 
16502                 cached = buf->dtb_tomax;
16503                 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16504 
16505                 dtrace_xcall(desc.dtbd_cpu,
16506                     (dtrace_xcall_t)dtrace_buffer_switch, buf);
16507 
16508                 state->dts_errors += buf->dtb_xamot_errors;
16509 
16510                 /*
16511                  * If the buffers did not actually switch, then the cross call
16512                  * did not take place -- presumably because the given CPU is
16513                  * not in the ready set.  If this is the case, we'll return
16514                  * ENOENT.
16515                  */
16516                 if (buf->dtb_tomax == cached) {
16517                         ASSERT(buf->dtb_xamot != cached);
16518                         mutex_exit(&dtrace_lock);
16519                         return (ENOENT);
16520                 }
16521 
16522                 ASSERT(cached == buf->dtb_xamot);
16523 
16524                 /*
16525                  * We have our snapshot; now copy it out.
16526                  */
16527                 if (copyout(buf->dtb_xamot, desc.dtbd_data,
16528                     buf->dtb_xamot_offset) != 0) {
16529                         mutex_exit(&dtrace_lock);
16530                         return (EFAULT);
16531                 }
16532 
16533                 desc.dtbd_size = buf->dtb_xamot_offset;
16534                 desc.dtbd_drops = buf->dtb_xamot_drops;
16535                 desc.dtbd_errors = buf->dtb_xamot_errors;
16536                 desc.dtbd_oldest = 0;
16537                 desc.dtbd_timestamp = buf->dtb_switched;
16538 
16539                 mutex_exit(&dtrace_lock);
16540 
16541                 /*
16542                  * Finally, copy out the buffer description.
16543                  */
16544                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16545                         return (EFAULT);
16546 
16547                 return (0);
16548         }
16549 
16550         case DTRACEIOC_CONF: {
16551                 dtrace_conf_t conf;
16552 
16553                 bzero(&conf, sizeof (conf));
16554                 conf.dtc_difversion = DIF_VERSION;
16555                 conf.dtc_difintregs = DIF_DIR_NREGS;
16556                 conf.dtc_diftupregs = DIF_DTR_NREGS;
16557                 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16558 
16559                 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
16560                         return (EFAULT);
16561 
16562                 return (0);
16563         }
16564 
16565         case DTRACEIOC_STATUS: {
16566                 dtrace_status_t stat;
16567                 dtrace_dstate_t *dstate;
16568                 int i, j;
16569                 uint64_t nerrs;
16570 
16571                 /*
16572                  * See the comment in dtrace_state_deadman() for the reason
16573                  * for setting dts_laststatus to INT64_MAX before setting
16574                  * it to the correct value.
16575                  */
16576                 state->dts_laststatus = INT64_MAX;
16577                 dtrace_membar_producer();
16578                 state->dts_laststatus = dtrace_gethrtime();
16579 
16580                 bzero(&stat, sizeof (stat));
16581 
16582                 mutex_enter(&dtrace_lock);
16583 
16584                 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16585                         mutex_exit(&dtrace_lock);
16586                         return (ENOENT);
16587                 }
16588 
16589                 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16590                         stat.dtst_exiting = 1;
16591 
16592                 nerrs = state->dts_errors;
16593                 dstate = &state->dts_vstate.dtvs_dynvars;
16594 
16595                 for (i = 0; i < NCPU; i++) {
16596                         dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16597 
16598                         stat.dtst_dyndrops += dcpu->dtdsc_drops;
16599                         stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16600                         stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16601 
16602                         if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16603                                 stat.dtst_filled++;
16604 
16605                         nerrs += state->dts_buffer[i].dtb_errors;
16606 
16607                         for (j = 0; j < state->dts_nspeculations; j++) {
16608                                 dtrace_speculation_t *spec;
16609                                 dtrace_buffer_t *buf;
16610 
16611                                 spec = &state->dts_speculations[j];
16612                                 buf = &spec->dtsp_buffer[i];
16613                                 stat.dtst_specdrops += buf->dtb_xamot_drops;
16614                         }
16615                 }
16616 
16617                 stat.dtst_specdrops_busy = state->dts_speculations_busy;
16618                 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16619                 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16620                 stat.dtst_dblerrors = state->dts_dblerrors;
16621                 stat.dtst_killed =
16622                     (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16623                 stat.dtst_errors = nerrs;
16624 
16625                 mutex_exit(&dtrace_lock);
16626 
16627                 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
16628                         return (EFAULT);
16629 
16630                 return (0);
16631         }
16632 
16633         case DTRACEIOC_FORMAT: {
16634                 dtrace_fmtdesc_t fmt;
16635                 char *str;
16636                 int len;
16637 
16638                 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
16639                         return (EFAULT);
16640 
16641                 mutex_enter(&dtrace_lock);
16642 
16643                 if (fmt.dtfd_format == 0 ||
16644                     fmt.dtfd_format > state->dts_nformats) {
16645                         mutex_exit(&dtrace_lock);
16646                         return (EINVAL);
16647                 }
16648 
16649                 /*
16650                  * Format strings are allocated contiguously and they are
16651                  * never freed; if a format index is less than the number
16652                  * of formats, we can assert that the format map is non-NULL
16653                  * and that the format for the specified index is non-NULL.
16654                  */
16655                 ASSERT(state->dts_formats != NULL);
16656                 str = state->dts_formats[fmt.dtfd_format - 1];
16657                 ASSERT(str != NULL);
16658 
16659                 len = strlen(str) + 1;
16660 
16661                 if (len > fmt.dtfd_length) {
16662                         fmt.dtfd_length = len;
16663 
16664                         if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16665                                 mutex_exit(&dtrace_lock);
16666                                 return (EINVAL);
16667                         }
16668                 } else {
16669                         if (copyout(str, fmt.dtfd_string, len) != 0) {
16670                                 mutex_exit(&dtrace_lock);
16671                                 return (EINVAL);
16672                         }
16673                 }
16674 
16675                 mutex_exit(&dtrace_lock);
16676                 return (0);
16677         }
16678 
16679         default:
16680                 break;
16681         }
16682 
16683         return (ENOTTY);
16684 }
16685 
16686 /*ARGSUSED*/
16687 static int
16688 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16689 {
16690         dtrace_state_t *state;
16691 
16692         switch (cmd) {
16693         case DDI_DETACH:
16694                 break;
16695 
16696         case DDI_SUSPEND:
16697                 return (DDI_SUCCESS);
16698 
16699         default:
16700                 return (DDI_FAILURE);
16701         }
16702 
16703         mutex_enter(&cpu_lock);
16704         mutex_enter(&dtrace_provider_lock);
16705         mutex_enter(&dtrace_lock);
16706 
16707         ASSERT(dtrace_opens == 0);
16708 
16709         if (dtrace_helpers > 0) {
16710                 mutex_exit(&dtrace_provider_lock);
16711                 mutex_exit(&dtrace_lock);
16712                 mutex_exit(&cpu_lock);
16713                 return (DDI_FAILURE);
16714         }
16715 
16716         if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
16717                 mutex_exit(&dtrace_provider_lock);
16718                 mutex_exit(&dtrace_lock);
16719                 mutex_exit(&cpu_lock);
16720                 return (DDI_FAILURE);
16721         }
16722 
16723         dtrace_provider = NULL;
16724 
16725         if ((state = dtrace_anon_grab()) != NULL) {
16726                 /*
16727                  * If there were ECBs on this state, the provider should
16728                  * have not been allowed to detach; assert that there is
16729                  * none.
16730                  */
16731                 ASSERT(state->dts_necbs == 0);
16732                 dtrace_state_destroy(state);
16733 
16734                 /*
16735                  * If we're being detached with anonymous state, we need to
16736                  * indicate to the kernel debugger that DTrace is now inactive.
16737                  */
16738                 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16739         }
16740 
16741         bzero(&dtrace_anon, sizeof (dtrace_anon_t));
16742         unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16743         dtrace_cpu_init = NULL;
16744         dtrace_helpers_cleanup = NULL;
16745         dtrace_helpers_fork = NULL;
16746         dtrace_cpustart_init = NULL;
16747         dtrace_cpustart_fini = NULL;
16748         dtrace_debugger_init = NULL;
16749         dtrace_debugger_fini = NULL;
16750         dtrace_modload = NULL;
16751         dtrace_modunload = NULL;
16752 
16753         ASSERT(dtrace_getf == 0);
16754         ASSERT(dtrace_closef == NULL);
16755 
16756         mutex_exit(&cpu_lock);
16757 
16758         kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
16759         dtrace_probes = NULL;
16760         dtrace_nprobes = 0;
16761 
16762         dtrace_hash_destroy(dtrace_bymod);
16763         dtrace_hash_destroy(dtrace_byfunc);
16764         dtrace_hash_destroy(dtrace_byname);
16765         dtrace_bymod = NULL;
16766         dtrace_byfunc = NULL;
16767         dtrace_byname = NULL;
16768 
16769         kmem_cache_destroy(dtrace_state_cache);
16770         vmem_destroy(dtrace_minor);
16771         vmem_destroy(dtrace_arena);
16772 
16773         if (dtrace_toxrange != NULL) {
16774                 kmem_free(dtrace_toxrange,
16775                     dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
16776                 dtrace_toxrange = NULL;
16777                 dtrace_toxranges = 0;
16778                 dtrace_toxranges_max = 0;
16779         }
16780 
16781         ddi_remove_minor_node(dtrace_devi, NULL);
16782         dtrace_devi = NULL;
16783 
16784         ddi_soft_state_fini(&dtrace_softstate);
16785 
16786         ASSERT(dtrace_vtime_references == 0);
16787         ASSERT(dtrace_opens == 0);
16788         ASSERT(dtrace_retained == NULL);
16789 
16790         mutex_exit(&dtrace_lock);
16791         mutex_exit(&dtrace_provider_lock);
16792 
16793         /*
16794          * We don't destroy the task queue until after we have dropped our
16795          * locks (taskq_destroy() may block on running tasks).  To prevent
16796          * attempting to do work after we have effectively detached but before
16797          * the task queue has been destroyed, all tasks dispatched via the
16798          * task queue must check that DTrace is still attached before
16799          * performing any operation.
16800          */
16801         taskq_destroy(dtrace_taskq);
16802         dtrace_taskq = NULL;
16803 
16804         return (DDI_SUCCESS);
16805 }
16806 
16807 /*ARGSUSED*/
16808 static int
16809 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
16810 {
16811         int error;
16812 
16813         switch (infocmd) {
16814         case DDI_INFO_DEVT2DEVINFO:
16815                 *result = (void *)dtrace_devi;
16816                 error = DDI_SUCCESS;
16817                 break;
16818         case DDI_INFO_DEVT2INSTANCE:
16819                 *result = (void *)0;
16820                 error = DDI_SUCCESS;
16821                 break;
16822         default:
16823                 error = DDI_FAILURE;
16824         }
16825         return (error);
16826 }
16827 
16828 static struct cb_ops dtrace_cb_ops = {
16829         dtrace_open,            /* open */
16830         dtrace_close,           /* close */
16831         nulldev,                /* strategy */
16832         nulldev,                /* print */
16833         nodev,                  /* dump */
16834         nodev,                  /* read */
16835         nodev,                  /* write */
16836         dtrace_ioctl,           /* ioctl */
16837         nodev,                  /* devmap */
16838         nodev,                  /* mmap */
16839         nodev,                  /* segmap */
16840         nochpoll,               /* poll */
16841         ddi_prop_op,            /* cb_prop_op */
16842         0,                      /* streamtab  */
16843         D_NEW | D_MP            /* Driver compatibility flag */
16844 };
16845 
16846 static struct dev_ops dtrace_ops = {
16847         DEVO_REV,               /* devo_rev */
16848         0,                      /* refcnt */
16849         dtrace_info,            /* get_dev_info */
16850         nulldev,                /* identify */
16851         nulldev,                /* probe */
16852         dtrace_attach,          /* attach */
16853         dtrace_detach,          /* detach */
16854         nodev,                  /* reset */
16855         &dtrace_cb_ops,             /* driver operations */
16856         NULL,                   /* bus operations */
16857         nodev,                  /* dev power */
16858         ddi_quiesce_not_needed,         /* quiesce */
16859 };
16860 
16861 static struct modldrv modldrv = {
16862         &mod_driverops,             /* module type (this is a pseudo driver) */
16863         "Dynamic Tracing",      /* name of module */
16864         &dtrace_ops,                /* driver ops */
16865 };
16866 
16867 static struct modlinkage modlinkage = {
16868         MODREV_1,
16869         (void *)&modldrv,
16870         NULL
16871 };
16872 
16873 int
16874 _init(void)
16875 {
16876         return (mod_install(&modlinkage));
16877 }
16878 
16879 int
16880 _info(struct modinfo *modinfop)
16881 {
16882         return (mod_info(&modlinkage, modinfop));
16883 }
16884 
16885 int
16886 _fini(void)
16887 {
16888         return (mod_remove(&modlinkage));
16889 }