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 static int64_t
 884 dtrace_strtoll(char *input, int base, size_t limit)
 885 {
 886         uintptr_t pos = (uintptr_t)input;
 887         int64_t val = 0;
 888         int x;
 889         boolean_t neg = B_FALSE;
 890         char c, cc, ccc;
 891         uintptr_t end = pos + limit;
 892 
 893         /* eat whitespace */
 894         while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
 895                 pos++;
 896 
 897         /* sign? */
 898         if (c == '-' || c == '+') {
 899                 if (c == '-')
 900                         neg = B_TRUE;
 901                 c = dtrace_load8(++pos);
 902         }
 903 
 904         /* hex prefix? */
 905         if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
 906             cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
 907                 pos += 2; /* skip over leading "0x" or "0X" */
 908                 c = ccc;
 909         }
 910 
 911         /* read in digits */
 912         for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
 913             c = dtrace_load8(++pos))
 914                 val = val * base + x;
 915 
 916         return (neg ? -val : val);
 917 }
 918 
 919 /*
 920  * Compare two strings using safe loads.
 921  */
 922 static int
 923 dtrace_strncmp(char *s1, char *s2, size_t limit)
 924 {
 925         uint8_t c1, c2;
 926         volatile uint16_t *flags;
 927 
 928         if (s1 == s2 || limit == 0)
 929                 return (0);
 930 
 931         flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
 932 
 933         do {
 934                 if (s1 == NULL) {
 935                         c1 = '\0';
 936                 } else {
 937                         c1 = dtrace_load8((uintptr_t)s1++);
 938                 }
 939 
 940                 if (s2 == NULL) {
 941                         c2 = '\0';
 942                 } else {
 943                         c2 = dtrace_load8((uintptr_t)s2++);
 944                 }
 945 
 946                 if (c1 != c2)
 947                         return (c1 - c2);
 948         } while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
 949 
 950         return (0);
 951 }
 952 
 953 /*
 954  * Compute strlen(s) for a string using safe memory accesses.  The additional
 955  * len parameter is used to specify a maximum length to ensure completion.
 956  */
 957 static size_t
 958 dtrace_strlen(const char *s, size_t lim)
 959 {
 960         uint_t len;
 961 
 962         for (len = 0; len != lim; len++) {
 963                 if (dtrace_load8((uintptr_t)s++) == '\0')
 964                         break;
 965         }
 966 
 967         return (len);
 968 }
 969 
 970 /*
 971  * Check if an address falls within a toxic region.
 972  */
 973 static int
 974 dtrace_istoxic(uintptr_t kaddr, size_t size)
 975 {
 976         uintptr_t taddr, tsize;
 977         int i;
 978 
 979         for (i = 0; i < dtrace_toxranges; i++) {
 980                 taddr = dtrace_toxrange[i].dtt_base;
 981                 tsize = dtrace_toxrange[i].dtt_limit - taddr;
 982 
 983                 if (kaddr - taddr < tsize) {
 984                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
 985                         cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
 986                         return (1);
 987                 }
 988 
 989                 if (taddr - kaddr < size) {
 990                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
 991                         cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
 992                         return (1);
 993                 }
 994         }
 995 
 996         return (0);
 997 }
 998 
 999 /*
1000  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1001  * memory specified by the DIF program.  The dst is assumed to be safe memory
1002  * that we can store to directly because it is managed by DTrace.  As with
1003  * standard bcopy, overlapping copies are handled properly.
1004  */
1005 static void
1006 dtrace_bcopy(const void *src, void *dst, size_t len)
1007 {
1008         if (len != 0) {
1009                 uint8_t *s1 = dst;
1010                 const uint8_t *s2 = src;
1011 
1012                 if (s1 <= s2) {
1013                         do {
1014                                 *s1++ = dtrace_load8((uintptr_t)s2++);
1015                         } while (--len != 0);
1016                 } else {
1017                         s2 += len;
1018                         s1 += len;
1019 
1020                         do {
1021                                 *--s1 = dtrace_load8((uintptr_t)--s2);
1022                         } while (--len != 0);
1023                 }
1024         }
1025 }
1026 
1027 /*
1028  * Copy src to dst using safe memory accesses, up to either the specified
1029  * length, or the point that a nul byte is encountered.  The src is assumed to
1030  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1031  * safe memory that we can store to directly because it is managed by DTrace.
1032  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1033  */
1034 static void
1035 dtrace_strcpy(const void *src, void *dst, size_t len)
1036 {
1037         if (len != 0) {
1038                 uint8_t *s1 = dst, c;
1039                 const uint8_t *s2 = src;
1040 
1041                 do {
1042                         *s1++ = c = dtrace_load8((uintptr_t)s2++);
1043                 } while (--len != 0 && c != '\0');
1044         }
1045 }
1046 
1047 /*
1048  * Copy src to dst, deriving the size and type from the specified (BYREF)
1049  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1050  * program.  The dst is assumed to be DTrace variable memory that is of the
1051  * specified type; we assume that we can store to directly.
1052  */
1053 static void
1054 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1055 {
1056         ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1057 
1058         if (type->dtdt_kind == DIF_TYPE_STRING) {
1059                 dtrace_strcpy(src, dst, type->dtdt_size);
1060         } else {
1061                 dtrace_bcopy(src, dst, type->dtdt_size);
1062         }
1063 }
1064 
1065 /*
1066  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1067  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1068  * safe memory that we can access directly because it is managed by DTrace.
1069  */
1070 static int
1071 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1072 {
1073         volatile uint16_t *flags;
1074 
1075         flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1076 
1077         if (s1 == s2)
1078                 return (0);
1079 
1080         if (s1 == NULL || s2 == NULL)
1081                 return (1);
1082 
1083         if (s1 != s2 && len != 0) {
1084                 const uint8_t *ps1 = s1;
1085                 const uint8_t *ps2 = s2;
1086 
1087                 do {
1088                         if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1089                                 return (1);
1090                 } while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1091         }
1092         return (0);
1093 }
1094 
1095 /*
1096  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1097  * is for safe DTrace-managed memory only.
1098  */
1099 static void
1100 dtrace_bzero(void *dst, size_t len)
1101 {
1102         uchar_t *cp;
1103 
1104         for (cp = dst; len != 0; len--)
1105                 *cp++ = 0;
1106 }
1107 
1108 static void
1109 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1110 {
1111         uint64_t result[2];
1112 
1113         result[0] = addend1[0] + addend2[0];
1114         result[1] = addend1[1] + addend2[1] +
1115             (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1116 
1117         sum[0] = result[0];
1118         sum[1] = result[1];
1119 }
1120 
1121 /*
1122  * Shift the 128-bit value in a by b. If b is positive, shift left.
1123  * If b is negative, shift right.
1124  */
1125 static void
1126 dtrace_shift_128(uint64_t *a, int b)
1127 {
1128         uint64_t mask;
1129 
1130         if (b == 0)
1131                 return;
1132 
1133         if (b < 0) {
1134                 b = -b;
1135                 if (b >= 64) {
1136                         a[0] = a[1] >> (b - 64);
1137                         a[1] = 0;
1138                 } else {
1139                         a[0] >>= b;
1140                         mask = 1LL << (64 - b);
1141                         mask -= 1;
1142                         a[0] |= ((a[1] & mask) << (64 - b));
1143                         a[1] >>= b;
1144                 }
1145         } else {
1146                 if (b >= 64) {
1147                         a[1] = a[0] << (b - 64);
1148                         a[0] = 0;
1149                 } else {
1150                         a[1] <<= b;
1151                         mask = a[0] >> (64 - b);
1152                         a[1] |= mask;
1153                         a[0] <<= b;
1154                 }
1155         }
1156 }
1157 
1158 /*
1159  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1160  * use native multiplication on those, and then re-combine into the
1161  * resulting 128-bit value.
1162  *
1163  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1164  *     hi1 * hi2 << 64 +
1165  *     hi1 * lo2 << 32 +
1166  *     hi2 * lo1 << 32 +
1167  *     lo1 * lo2
1168  */
1169 static void
1170 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1171 {
1172         uint64_t hi1, hi2, lo1, lo2;
1173         uint64_t tmp[2];
1174 
1175         hi1 = factor1 >> 32;
1176         hi2 = factor2 >> 32;
1177 
1178         lo1 = factor1 & DT_MASK_LO;
1179         lo2 = factor2 & DT_MASK_LO;
1180 
1181         product[0] = lo1 * lo2;
1182         product[1] = hi1 * hi2;
1183 
1184         tmp[0] = hi1 * lo2;
1185         tmp[1] = 0;
1186         dtrace_shift_128(tmp, 32);
1187         dtrace_add_128(product, tmp, product);
1188 
1189         tmp[0] = hi2 * lo1;
1190         tmp[1] = 0;
1191         dtrace_shift_128(tmp, 32);
1192         dtrace_add_128(product, tmp, product);
1193 }
1194 
1195 /*
1196  * This privilege check should be used by actions and subroutines to
1197  * verify that the user credentials of the process that enabled the
1198  * invoking ECB match the target credentials
1199  */
1200 static int
1201 dtrace_priv_proc_common_user(dtrace_state_t *state)
1202 {
1203         cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1204 
1205         /*
1206          * We should always have a non-NULL state cred here, since if cred
1207          * is null (anonymous tracing), we fast-path bypass this routine.
1208          */
1209         ASSERT(s_cr != NULL);
1210 
1211         if ((cr = CRED()) != NULL &&
1212             s_cr->cr_uid == cr->cr_uid &&
1213             s_cr->cr_uid == cr->cr_ruid &&
1214             s_cr->cr_uid == cr->cr_suid &&
1215             s_cr->cr_gid == cr->cr_gid &&
1216             s_cr->cr_gid == cr->cr_rgid &&
1217             s_cr->cr_gid == cr->cr_sgid)
1218                 return (1);
1219 
1220         return (0);
1221 }
1222 
1223 /*
1224  * This privilege check should be used by actions and subroutines to
1225  * verify that the zone of the process that enabled the invoking ECB
1226  * matches the target credentials
1227  */
1228 static int
1229 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1230 {
1231         cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1232 
1233         /*
1234          * We should always have a non-NULL state cred here, since if cred
1235          * is null (anonymous tracing), we fast-path bypass this routine.
1236          */
1237         ASSERT(s_cr != NULL);
1238 
1239         if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1240                 return (1);
1241 
1242         return (0);
1243 }
1244 
1245 /*
1246  * This privilege check should be used by actions and subroutines to
1247  * verify that the process has not setuid or changed credentials.
1248  */
1249 static int
1250 dtrace_priv_proc_common_nocd()
1251 {
1252         proc_t *proc;
1253 
1254         if ((proc = ttoproc(curthread)) != NULL &&
1255             !(proc->p_flag & SNOCD))
1256                 return (1);
1257 
1258         return (0);
1259 }
1260 
1261 static int
1262 dtrace_priv_proc_destructive(dtrace_state_t *state, dtrace_mstate_t *mstate)
1263 {
1264         int action = state->dts_cred.dcr_action;
1265 
1266         if (!(mstate->dtms_access & DTRACE_ACCESS_PROC))
1267                 goto bad;
1268 
1269         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1270             dtrace_priv_proc_common_zone(state) == 0)
1271                 goto bad;
1272 
1273         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1274             dtrace_priv_proc_common_user(state) == 0)
1275                 goto bad;
1276 
1277         if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1278             dtrace_priv_proc_common_nocd() == 0)
1279                 goto bad;
1280 
1281         return (1);
1282 
1283 bad:
1284         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1285 
1286         return (0);
1287 }
1288 
1289 static int
1290 dtrace_priv_proc_control(dtrace_state_t *state, dtrace_mstate_t *mstate)
1291 {
1292         if (mstate->dtms_access & DTRACE_ACCESS_PROC) {
1293                 if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1294                         return (1);
1295 
1296                 if (dtrace_priv_proc_common_zone(state) &&
1297                     dtrace_priv_proc_common_user(state) &&
1298                     dtrace_priv_proc_common_nocd())
1299                         return (1);
1300         }
1301 
1302         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1303 
1304         return (0);
1305 }
1306 
1307 static int
1308 dtrace_priv_proc(dtrace_state_t *state, dtrace_mstate_t *mstate)
1309 {
1310         if ((mstate->dtms_access & DTRACE_ACCESS_PROC) &&
1311             (state->dts_cred.dcr_action & DTRACE_CRA_PROC))
1312                 return (1);
1313 
1314         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1315 
1316         return (0);
1317 }
1318 
1319 static int
1320 dtrace_priv_kernel(dtrace_state_t *state)
1321 {
1322         if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1323                 return (1);
1324 
1325         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1326 
1327         return (0);
1328 }
1329 
1330 static int
1331 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1332 {
1333         if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1334                 return (1);
1335 
1336         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1337 
1338         return (0);
1339 }
1340 
1341 /*
1342  * Determine if the dte_cond of the specified ECB allows for processing of
1343  * the current probe to continue.  Note that this routine may allow continued
1344  * processing, but with access(es) stripped from the mstate's dtms_access
1345  * field.
1346  */
1347 static int
1348 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1349     dtrace_ecb_t *ecb)
1350 {
1351         dtrace_probe_t *probe = ecb->dte_probe;
1352         dtrace_provider_t *prov = probe->dtpr_provider;
1353         dtrace_pops_t *pops = &prov->dtpv_pops;
1354         int mode = DTRACE_MODE_NOPRIV_DROP;
1355 
1356         ASSERT(ecb->dte_cond);
1357 
1358         if (pops->dtps_mode != NULL) {
1359                 mode = pops->dtps_mode(prov->dtpv_arg,
1360                     probe->dtpr_id, probe->dtpr_arg);
1361 
1362                 ASSERT(mode & (DTRACE_MODE_USER | DTRACE_MODE_KERNEL));
1363                 ASSERT(mode & (DTRACE_MODE_NOPRIV_RESTRICT |
1364                     DTRACE_MODE_NOPRIV_DROP));
1365         }
1366 
1367         /*
1368          * If the dte_cond bits indicate that this consumer is only allowed to
1369          * see user-mode firings of this probe, check that the probe was fired
1370          * while in a user context.  If that's not the case, use the policy
1371          * specified by the provider to determine if we drop the probe or
1372          * merely restrict operation.
1373          */
1374         if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1375                 ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1376 
1377                 if (!(mode & DTRACE_MODE_USER)) {
1378                         if (mode & DTRACE_MODE_NOPRIV_DROP)
1379                                 return (0);
1380 
1381                         mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1382                 }
1383         }
1384 
1385         /*
1386          * This is more subtle than it looks. We have to be absolutely certain
1387          * that CRED() isn't going to change out from under us so it's only
1388          * legit to examine that structure if we're in constrained situations.
1389          * Currently, the only times we'll this check is if a non-super-user
1390          * has enabled the profile or syscall providers -- providers that
1391          * allow visibility of all processes. For the profile case, the check
1392          * above will ensure that we're examining a user context.
1393          */
1394         if (ecb->dte_cond & DTRACE_COND_OWNER) {
1395                 cred_t *cr;
1396                 cred_t *s_cr = state->dts_cred.dcr_cred;
1397                 proc_t *proc;
1398 
1399                 ASSERT(s_cr != NULL);
1400 
1401                 if ((cr = CRED()) == NULL ||
1402                     s_cr->cr_uid != cr->cr_uid ||
1403                     s_cr->cr_uid != cr->cr_ruid ||
1404                     s_cr->cr_uid != cr->cr_suid ||
1405                     s_cr->cr_gid != cr->cr_gid ||
1406                     s_cr->cr_gid != cr->cr_rgid ||
1407                     s_cr->cr_gid != cr->cr_sgid ||
1408                     (proc = ttoproc(curthread)) == NULL ||
1409                     (proc->p_flag & SNOCD)) {
1410                         if (mode & DTRACE_MODE_NOPRIV_DROP)
1411                                 return (0);
1412 
1413                         mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1414                 }
1415         }
1416 
1417         /*
1418          * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1419          * in our zone, check to see if our mode policy is to restrict rather
1420          * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1421          * and DTRACE_ACCESS_ARGS
1422          */
1423         if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1424                 cred_t *cr;
1425                 cred_t *s_cr = state->dts_cred.dcr_cred;
1426 
1427                 ASSERT(s_cr != NULL);
1428 
1429                 if ((cr = CRED()) == NULL ||
1430                     s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1431                         if (mode & DTRACE_MODE_NOPRIV_DROP)
1432                                 return (0);
1433 
1434                         mstate->dtms_access &=
1435                             ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1436                 }
1437         }
1438 
1439         /*
1440          * By merits of being in this code path at all, we have limited
1441          * privileges.  If the provider has indicated that limited privileges
1442          * are to denote restricted operation, strip off the ability to access
1443          * arguments.
1444          */
1445         if (mode & DTRACE_MODE_LIMITEDPRIV_RESTRICT)
1446                 mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1447 
1448         return (1);
1449 }
1450 
1451 /*
1452  * Note:  not called from probe context.  This function is called
1453  * asynchronously (and at a regular interval) from outside of probe context to
1454  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1455  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1456  */
1457 void
1458 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1459 {
1460         dtrace_dynvar_t *dirty;
1461         dtrace_dstate_percpu_t *dcpu;
1462         dtrace_dynvar_t **rinsep;
1463         int i, j, work = 0;
1464 
1465         for (i = 0; i < NCPU; i++) {
1466                 dcpu = &dstate->dtds_percpu[i];
1467                 rinsep = &dcpu->dtdsc_rinsing;
1468 
1469                 /*
1470                  * If the dirty list is NULL, there is no dirty work to do.
1471                  */
1472                 if (dcpu->dtdsc_dirty == NULL)
1473                         continue;
1474 
1475                 if (dcpu->dtdsc_rinsing != NULL) {
1476                         /*
1477                          * If the rinsing list is non-NULL, then it is because
1478                          * this CPU was selected to accept another CPU's
1479                          * dirty list -- and since that time, dirty buffers
1480                          * have accumulated.  This is a highly unlikely
1481                          * condition, but we choose to ignore the dirty
1482                          * buffers -- they'll be picked up a future cleanse.
1483                          */
1484                         continue;
1485                 }
1486 
1487                 if (dcpu->dtdsc_clean != NULL) {
1488                         /*
1489                          * If the clean list is non-NULL, then we're in a
1490                          * situation where a CPU has done deallocations (we
1491                          * have a non-NULL dirty list) but no allocations (we
1492                          * also have a non-NULL clean list).  We can't simply
1493                          * move the dirty list into the clean list on this
1494                          * CPU, yet we also don't want to allow this condition
1495                          * to persist, lest a short clean list prevent a
1496                          * massive dirty list from being cleaned (which in
1497                          * turn could lead to otherwise avoidable dynamic
1498                          * drops).  To deal with this, we look for some CPU
1499                          * with a NULL clean list, NULL dirty list, and NULL
1500                          * rinsing list -- and then we borrow this CPU to
1501                          * rinse our dirty list.
1502                          */
1503                         for (j = 0; j < NCPU; j++) {
1504                                 dtrace_dstate_percpu_t *rinser;
1505 
1506                                 rinser = &dstate->dtds_percpu[j];
1507 
1508                                 if (rinser->dtdsc_rinsing != NULL)
1509                                         continue;
1510 
1511                                 if (rinser->dtdsc_dirty != NULL)
1512                                         continue;
1513 
1514                                 if (rinser->dtdsc_clean != NULL)
1515                                         continue;
1516 
1517                                 rinsep = &rinser->dtdsc_rinsing;
1518                                 break;
1519                         }
1520 
1521                         if (j == NCPU) {
1522                                 /*
1523                                  * We were unable to find another CPU that
1524                                  * could accept this dirty list -- we are
1525                                  * therefore unable to clean it now.
1526                                  */
1527                                 dtrace_dynvar_failclean++;
1528                                 continue;
1529                         }
1530                 }
1531 
1532                 work = 1;
1533 
1534                 /*
1535                  * Atomically move the dirty list aside.
1536                  */
1537                 do {
1538                         dirty = dcpu->dtdsc_dirty;
1539 
1540                         /*
1541                          * Before we zap the dirty list, set the rinsing list.
1542                          * (This allows for a potential assertion in
1543                          * dtrace_dynvar():  if a free dynamic variable appears
1544                          * on a hash chain, either the dirty list or the
1545                          * rinsing list for some CPU must be non-NULL.)
1546                          */
1547                         *rinsep = dirty;
1548                         dtrace_membar_producer();
1549                 } while (dtrace_casptr(&dcpu->dtdsc_dirty,
1550                     dirty, NULL) != dirty);
1551         }
1552 
1553         if (!work) {
1554                 /*
1555                  * We have no work to do; we can simply return.
1556                  */
1557                 return;
1558         }
1559 
1560         dtrace_sync();
1561 
1562         for (i = 0; i < NCPU; i++) {
1563                 dcpu = &dstate->dtds_percpu[i];
1564 
1565                 if (dcpu->dtdsc_rinsing == NULL)
1566                         continue;
1567 
1568                 /*
1569                  * We are now guaranteed that no hash chain contains a pointer
1570                  * into this dirty list; we can make it clean.
1571                  */
1572                 ASSERT(dcpu->dtdsc_clean == NULL);
1573                 dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1574                 dcpu->dtdsc_rinsing = NULL;
1575         }
1576 
1577         /*
1578          * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1579          * sure that all CPUs have seen all of the dtdsc_clean pointers.
1580          * This prevents a race whereby a CPU incorrectly decides that
1581          * the state should be something other than DTRACE_DSTATE_CLEAN
1582          * after dtrace_dynvar_clean() has completed.
1583          */
1584         dtrace_sync();
1585 
1586         dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1587 }
1588 
1589 /*
1590  * Depending on the value of the op parameter, this function looks-up,
1591  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1592  * allocation is requested, this function will return a pointer to a
1593  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1594  * variable can be allocated.  If NULL is returned, the appropriate counter
1595  * will be incremented.
1596  */
1597 dtrace_dynvar_t *
1598 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1599     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1600     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1601 {
1602         uint64_t hashval = DTRACE_DYNHASH_VALID;
1603         dtrace_dynhash_t *hash = dstate->dtds_hash;
1604         dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1605         processorid_t me = CPU->cpu_id, cpu = me;
1606         dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1607         size_t bucket, ksize;
1608         size_t chunksize = dstate->dtds_chunksize;
1609         uintptr_t kdata, lock, nstate;
1610         uint_t i;
1611 
1612         ASSERT(nkeys != 0);
1613 
1614         /*
1615          * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1616          * algorithm.  For the by-value portions, we perform the algorithm in
1617          * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1618          * bit, and seems to have only a minute effect on distribution.  For
1619          * the by-reference data, we perform "One-at-a-time" iterating (safely)
1620          * over each referenced byte.  It's painful to do this, but it's much
1621          * better than pathological hash distribution.  The efficacy of the
1622          * hashing algorithm (and a comparison with other algorithms) may be
1623          * found by running the ::dtrace_dynstat MDB dcmd.
1624          */
1625         for (i = 0; i < nkeys; i++) {
1626                 if (key[i].dttk_size == 0) {
1627                         uint64_t val = key[i].dttk_value;
1628 
1629                         hashval += (val >> 48) & 0xffff;
1630                         hashval += (hashval << 10);
1631                         hashval ^= (hashval >> 6);
1632 
1633                         hashval += (val >> 32) & 0xffff;
1634                         hashval += (hashval << 10);
1635                         hashval ^= (hashval >> 6);
1636 
1637                         hashval += (val >> 16) & 0xffff;
1638                         hashval += (hashval << 10);
1639                         hashval ^= (hashval >> 6);
1640 
1641                         hashval += val & 0xffff;
1642                         hashval += (hashval << 10);
1643                         hashval ^= (hashval >> 6);
1644                 } else {
1645                         /*
1646                          * This is incredibly painful, but it beats the hell
1647                          * out of the alternative.
1648                          */
1649                         uint64_t j, size = key[i].dttk_size;
1650                         uintptr_t base = (uintptr_t)key[i].dttk_value;
1651 
1652                         if (!dtrace_canload(base, size, mstate, vstate))
1653                                 break;
1654 
1655                         for (j = 0; j < size; j++) {
1656                                 hashval += dtrace_load8(base + j);
1657                                 hashval += (hashval << 10);
1658                                 hashval ^= (hashval >> 6);
1659                         }
1660                 }
1661         }
1662 
1663         if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1664                 return (NULL);
1665 
1666         hashval += (hashval << 3);
1667         hashval ^= (hashval >> 11);
1668         hashval += (hashval << 15);
1669 
1670         /*
1671          * There is a remote chance (ideally, 1 in 2^31) that our hashval
1672          * comes out to be one of our two sentinel hash values.  If this
1673          * actually happens, we set the hashval to be a value known to be a
1674          * non-sentinel value.
1675          */
1676         if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1677                 hashval = DTRACE_DYNHASH_VALID;
1678 
1679         /*
1680          * Yes, it's painful to do a divide here.  If the cycle count becomes
1681          * important here, tricks can be pulled to reduce it.  (However, it's
1682          * critical that hash collisions be kept to an absolute minimum;
1683          * they're much more painful than a divide.)  It's better to have a
1684          * solution that generates few collisions and still keeps things
1685          * relatively simple.
1686          */
1687         bucket = hashval % dstate->dtds_hashsize;
1688 
1689         if (op == DTRACE_DYNVAR_DEALLOC) {
1690                 volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1691 
1692                 for (;;) {
1693                         while ((lock = *lockp) & 1)
1694                                 continue;
1695 
1696                         if (dtrace_casptr((void *)lockp,
1697                             (void *)lock, (void *)(lock + 1)) == (void *)lock)
1698                                 break;
1699                 }
1700 
1701                 dtrace_membar_producer();
1702         }
1703 
1704 top:
1705         prev = NULL;
1706         lock = hash[bucket].dtdh_lock;
1707 
1708         dtrace_membar_consumer();
1709 
1710         start = hash[bucket].dtdh_chain;
1711         ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1712             start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1713             op != DTRACE_DYNVAR_DEALLOC));
1714 
1715         for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1716                 dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1717                 dtrace_key_t *dkey = &dtuple->dtt_key[0];
1718 
1719                 if (dvar->dtdv_hashval != hashval) {
1720                         if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1721                                 /*
1722                                  * We've reached the sink, and therefore the
1723                                  * end of the hash chain; we can kick out of
1724                                  * the loop knowing that we have seen a valid
1725                                  * snapshot of state.
1726                                  */
1727                                 ASSERT(dvar->dtdv_next == NULL);
1728                                 ASSERT(dvar == &dtrace_dynhash_sink);
1729                                 break;
1730                         }
1731 
1732                         if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1733                                 /*
1734                                  * We've gone off the rails:  somewhere along
1735                                  * the line, one of the members of this hash
1736                                  * chain was deleted.  Note that we could also
1737                                  * detect this by simply letting this loop run
1738                                  * to completion, as we would eventually hit
1739                                  * the end of the dirty list.  However, we
1740                                  * want to avoid running the length of the
1741                                  * dirty list unnecessarily (it might be quite
1742                                  * long), so we catch this as early as
1743                                  * possible by detecting the hash marker.  In
1744                                  * this case, we simply set dvar to NULL and
1745                                  * break; the conditional after the loop will
1746                                  * send us back to top.
1747                                  */
1748                                 dvar = NULL;
1749                                 break;
1750                         }
1751 
1752                         goto next;
1753                 }
1754 
1755                 if (dtuple->dtt_nkeys != nkeys)
1756                         goto next;
1757 
1758                 for (i = 0; i < nkeys; i++, dkey++) {
1759                         if (dkey->dttk_size != key[i].dttk_size)
1760                                 goto next; /* size or type mismatch */
1761 
1762                         if (dkey->dttk_size != 0) {
1763                                 if (dtrace_bcmp(
1764                                     (void *)(uintptr_t)key[i].dttk_value,
1765                                     (void *)(uintptr_t)dkey->dttk_value,
1766                                     dkey->dttk_size))
1767                                         goto next;
1768                         } else {
1769                                 if (dkey->dttk_value != key[i].dttk_value)
1770                                         goto next;
1771                         }
1772                 }
1773 
1774                 if (op != DTRACE_DYNVAR_DEALLOC)
1775                         return (dvar);
1776 
1777                 ASSERT(dvar->dtdv_next == NULL ||
1778                     dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1779 
1780                 if (prev != NULL) {
1781                         ASSERT(hash[bucket].dtdh_chain != dvar);
1782                         ASSERT(start != dvar);
1783                         ASSERT(prev->dtdv_next == dvar);
1784                         prev->dtdv_next = dvar->dtdv_next;
1785                 } else {
1786                         if (dtrace_casptr(&hash[bucket].dtdh_chain,
1787                             start, dvar->dtdv_next) != start) {
1788                                 /*
1789                                  * We have failed to atomically swing the
1790                                  * hash table head pointer, presumably because
1791                                  * of a conflicting allocation on another CPU.
1792                                  * We need to reread the hash chain and try
1793                                  * again.
1794                                  */
1795                                 goto top;
1796                         }
1797                 }
1798 
1799                 dtrace_membar_producer();
1800 
1801                 /*
1802                  * Now set the hash value to indicate that it's free.
1803                  */
1804                 ASSERT(hash[bucket].dtdh_chain != dvar);
1805                 dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1806 
1807                 dtrace_membar_producer();
1808 
1809                 /*
1810                  * Set the next pointer to point at the dirty list, and
1811                  * atomically swing the dirty pointer to the newly freed dvar.
1812                  */
1813                 do {
1814                         next = dcpu->dtdsc_dirty;
1815                         dvar->dtdv_next = next;
1816                 } while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1817 
1818                 /*
1819                  * Finally, unlock this hash bucket.
1820                  */
1821                 ASSERT(hash[bucket].dtdh_lock == lock);
1822                 ASSERT(lock & 1);
1823                 hash[bucket].dtdh_lock++;
1824 
1825                 return (NULL);
1826 next:
1827                 prev = dvar;
1828                 continue;
1829         }
1830 
1831         if (dvar == NULL) {
1832                 /*
1833                  * If dvar is NULL, it is because we went off the rails:
1834                  * one of the elements that we traversed in the hash chain
1835                  * was deleted while we were traversing it.  In this case,
1836                  * we assert that we aren't doing a dealloc (deallocs lock
1837                  * the hash bucket to prevent themselves from racing with
1838                  * one another), and retry the hash chain traversal.
1839                  */
1840                 ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1841                 goto top;
1842         }
1843 
1844         if (op != DTRACE_DYNVAR_ALLOC) {
1845                 /*
1846                  * If we are not to allocate a new variable, we want to
1847                  * return NULL now.  Before we return, check that the value
1848                  * of the lock word hasn't changed.  If it has, we may have
1849                  * seen an inconsistent snapshot.
1850                  */
1851                 if (op == DTRACE_DYNVAR_NOALLOC) {
1852                         if (hash[bucket].dtdh_lock != lock)
1853                                 goto top;
1854                 } else {
1855                         ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1856                         ASSERT(hash[bucket].dtdh_lock == lock);
1857                         ASSERT(lock & 1);
1858                         hash[bucket].dtdh_lock++;
1859                 }
1860 
1861                 return (NULL);
1862         }
1863 
1864         /*
1865          * We need to allocate a new dynamic variable.  The size we need is the
1866          * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1867          * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1868          * the size of any referred-to data (dsize).  We then round the final
1869          * size up to the chunksize for allocation.
1870          */
1871         for (ksize = 0, i = 0; i < nkeys; i++)
1872                 ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1873 
1874         /*
1875          * This should be pretty much impossible, but could happen if, say,
1876          * strange DIF specified the tuple.  Ideally, this should be an
1877          * assertion and not an error condition -- but that requires that the
1878          * chunksize calculation in dtrace_difo_chunksize() be absolutely
1879          * bullet-proof.  (That is, it must not be able to be fooled by
1880          * malicious DIF.)  Given the lack of backwards branches in DIF,
1881          * solving this would presumably not amount to solving the Halting
1882          * Problem -- but it still seems awfully hard.
1883          */
1884         if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1885             ksize + dsize > chunksize) {
1886                 dcpu->dtdsc_drops++;
1887                 return (NULL);
1888         }
1889 
1890         nstate = DTRACE_DSTATE_EMPTY;
1891 
1892         do {
1893 retry:
1894                 free = dcpu->dtdsc_free;
1895 
1896                 if (free == NULL) {
1897                         dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1898                         void *rval;
1899 
1900                         if (clean == NULL) {
1901                                 /*
1902                                  * We're out of dynamic variable space on
1903                                  * this CPU.  Unless we have tried all CPUs,
1904                                  * we'll try to allocate from a different
1905                                  * CPU.
1906                                  */
1907                                 switch (dstate->dtds_state) {
1908                                 case DTRACE_DSTATE_CLEAN: {
1909                                         void *sp = &dstate->dtds_state;
1910 
1911                                         if (++cpu >= NCPU)
1912                                                 cpu = 0;
1913 
1914                                         if (dcpu->dtdsc_dirty != NULL &&
1915                                             nstate == DTRACE_DSTATE_EMPTY)
1916                                                 nstate = DTRACE_DSTATE_DIRTY;
1917 
1918                                         if (dcpu->dtdsc_rinsing != NULL)
1919                                                 nstate = DTRACE_DSTATE_RINSING;
1920 
1921                                         dcpu = &dstate->dtds_percpu[cpu];
1922 
1923                                         if (cpu != me)
1924                                                 goto retry;
1925 
1926                                         (void) dtrace_cas32(sp,
1927                                             DTRACE_DSTATE_CLEAN, nstate);
1928 
1929                                         /*
1930                                          * To increment the correct bean
1931                                          * counter, take another lap.
1932                                          */
1933                                         goto retry;
1934                                 }
1935 
1936                                 case DTRACE_DSTATE_DIRTY:
1937                                         dcpu->dtdsc_dirty_drops++;
1938                                         break;
1939 
1940                                 case DTRACE_DSTATE_RINSING:
1941                                         dcpu->dtdsc_rinsing_drops++;
1942                                         break;
1943 
1944                                 case DTRACE_DSTATE_EMPTY:
1945                                         dcpu->dtdsc_drops++;
1946                                         break;
1947                                 }
1948 
1949                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1950                                 return (NULL);
1951                         }
1952 
1953                         /*
1954                          * The clean list appears to be non-empty.  We want to
1955                          * move the clean list to the free list; we start by
1956                          * moving the clean pointer aside.
1957                          */
1958                         if (dtrace_casptr(&dcpu->dtdsc_clean,
1959                             clean, NULL) != clean) {
1960                                 /*
1961                                  * We are in one of two situations:
1962                                  *
1963                                  *  (a) The clean list was switched to the
1964                                  *      free list by another CPU.
1965                                  *
1966                                  *  (b) The clean list was added to by the
1967                                  *      cleansing cyclic.
1968                                  *
1969                                  * In either of these situations, we can
1970                                  * just reattempt the free list allocation.
1971                                  */
1972                                 goto retry;
1973                         }
1974 
1975                         ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1976 
1977                         /*
1978                          * Now we'll move the clean list to our free list.
1979                          * It's impossible for this to fail:  the only way
1980                          * the free list can be updated is through this
1981                          * code path, and only one CPU can own the clean list.
1982                          * Thus, it would only be possible for this to fail if
1983                          * this code were racing with dtrace_dynvar_clean().
1984                          * (That is, if dtrace_dynvar_clean() updated the clean
1985                          * list, and we ended up racing to update the free
1986                          * list.)  This race is prevented by the dtrace_sync()
1987                          * in dtrace_dynvar_clean() -- which flushes the
1988                          * owners of the clean lists out before resetting
1989                          * the clean lists.
1990                          */
1991                         dcpu = &dstate->dtds_percpu[me];
1992                         rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1993                         ASSERT(rval == NULL);
1994                         goto retry;
1995                 }
1996 
1997                 dvar = free;
1998                 new_free = dvar->dtdv_next;
1999         } while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2000 
2001         /*
2002          * We have now allocated a new chunk.  We copy the tuple keys into the
2003          * tuple array and copy any referenced key data into the data space
2004          * following the tuple array.  As we do this, we relocate dttk_value
2005          * in the final tuple to point to the key data address in the chunk.
2006          */
2007         kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2008         dvar->dtdv_data = (void *)(kdata + ksize);
2009         dvar->dtdv_tuple.dtt_nkeys = nkeys;
2010 
2011         for (i = 0; i < nkeys; i++) {
2012                 dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2013                 size_t kesize = key[i].dttk_size;
2014 
2015                 if (kesize != 0) {
2016                         dtrace_bcopy(
2017                             (const void *)(uintptr_t)key[i].dttk_value,
2018                             (void *)kdata, kesize);
2019                         dkey->dttk_value = kdata;
2020                         kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2021                 } else {
2022                         dkey->dttk_value = key[i].dttk_value;
2023                 }
2024 
2025                 dkey->dttk_size = kesize;
2026         }
2027 
2028         ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2029         dvar->dtdv_hashval = hashval;
2030         dvar->dtdv_next = start;
2031 
2032         if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2033                 return (dvar);
2034 
2035         /*
2036          * The cas has failed.  Either another CPU is adding an element to
2037          * this hash chain, or another CPU is deleting an element from this
2038          * hash chain.  The simplest way to deal with both of these cases
2039          * (though not necessarily the most efficient) is to free our
2040          * allocated block and tail-call ourselves.  Note that the free is
2041          * to the dirty list and _not_ to the free list.  This is to prevent
2042          * races with allocators, above.
2043          */
2044         dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2045 
2046         dtrace_membar_producer();
2047 
2048         do {
2049                 free = dcpu->dtdsc_dirty;
2050                 dvar->dtdv_next = free;
2051         } while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2052 
2053         return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
2054 }
2055 
2056 /*ARGSUSED*/
2057 static void
2058 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2059 {
2060         if ((int64_t)nval < (int64_t)*oval)
2061                 *oval = nval;
2062 }
2063 
2064 /*ARGSUSED*/
2065 static void
2066 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2067 {
2068         if ((int64_t)nval > (int64_t)*oval)
2069                 *oval = nval;
2070 }
2071 
2072 static void
2073 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2074 {
2075         int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2076         int64_t val = (int64_t)nval;
2077 
2078         if (val < 0) {
2079                 for (i = 0; i < zero; i++) {
2080                         if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2081                                 quanta[i] += incr;
2082                                 return;
2083                         }
2084                 }
2085         } else {
2086                 for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2087                         if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2088                                 quanta[i - 1] += incr;
2089                                 return;
2090                         }
2091                 }
2092 
2093                 quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2094                 return;
2095         }
2096 
2097         ASSERT(0);
2098 }
2099 
2100 static void
2101 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2102 {
2103         uint64_t arg = *lquanta++;
2104         int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2105         uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2106         uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2107         int32_t val = (int32_t)nval, level;
2108 
2109         ASSERT(step != 0);
2110         ASSERT(levels != 0);
2111 
2112         if (val < base) {
2113                 /*
2114                  * This is an underflow.
2115                  */
2116                 lquanta[0] += incr;
2117                 return;
2118         }
2119 
2120         level = (val - base) / step;
2121 
2122         if (level < levels) {
2123                 lquanta[level + 1] += incr;
2124                 return;
2125         }
2126 
2127         /*
2128          * This is an overflow.
2129          */
2130         lquanta[levels + 1] += incr;
2131 }
2132 
2133 static int
2134 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2135     uint16_t high, uint16_t nsteps, int64_t value)
2136 {
2137         int64_t this = 1, last, next;
2138         int base = 1, order;
2139 
2140         ASSERT(factor <= nsteps);
2141         ASSERT(nsteps % factor == 0);
2142 
2143         for (order = 0; order < low; order++)
2144                 this *= factor;
2145 
2146         /*
2147          * If our value is less than our factor taken to the power of the
2148          * low order of magnitude, it goes into the zeroth bucket.
2149          */
2150         if (value < (last = this))
2151                 return (0);
2152 
2153         for (this *= factor; order <= high; order++) {
2154                 int nbuckets = this > nsteps ? nsteps : this;
2155 
2156                 if ((next = this * factor) < this) {
2157                         /*
2158                          * We should not generally get log/linear quantizations
2159                          * with a high magnitude that allows 64-bits to
2160                          * overflow, but we nonetheless protect against this
2161                          * by explicitly checking for overflow, and clamping
2162                          * our value accordingly.
2163                          */
2164                         value = this - 1;
2165                 }
2166 
2167                 if (value < this) {
2168                         /*
2169                          * If our value lies within this order of magnitude,
2170                          * determine its position by taking the offset within
2171                          * the order of magnitude, dividing by the bucket
2172                          * width, and adding to our (accumulated) base.
2173                          */
2174                         return (base + (value - last) / (this / nbuckets));
2175                 }
2176 
2177                 base += nbuckets - (nbuckets / factor);
2178                 last = this;
2179                 this = next;
2180         }
2181 
2182         /*
2183          * Our value is greater than or equal to our factor taken to the
2184          * power of one plus the high magnitude -- return the top bucket.
2185          */
2186         return (base);
2187 }
2188 
2189 static void
2190 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2191 {
2192         uint64_t arg = *llquanta++;
2193         uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2194         uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2195         uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2196         uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2197 
2198         llquanta[dtrace_aggregate_llquantize_bucket(factor,
2199             low, high, nsteps, nval)] += incr;
2200 }
2201 
2202 /*ARGSUSED*/
2203 static void
2204 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2205 {
2206         data[0]++;
2207         data[1] += nval;
2208 }
2209 
2210 /*ARGSUSED*/
2211 static void
2212 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2213 {
2214         int64_t snval = (int64_t)nval;
2215         uint64_t tmp[2];
2216 
2217         data[0]++;
2218         data[1] += nval;
2219 
2220         /*
2221          * What we want to say here is:
2222          *
2223          * data[2] += nval * nval;
2224          *
2225          * But given that nval is 64-bit, we could easily overflow, so
2226          * we do this as 128-bit arithmetic.
2227          */
2228         if (snval < 0)
2229                 snval = -snval;
2230 
2231         dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2232         dtrace_add_128(data + 2, tmp, data + 2);
2233 }
2234 
2235 /*ARGSUSED*/
2236 static void
2237 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2238 {
2239         *oval = *oval + 1;
2240 }
2241 
2242 /*ARGSUSED*/
2243 static void
2244 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2245 {
2246         *oval += nval;
2247 }
2248 
2249 /*
2250  * Aggregate given the tuple in the principal data buffer, and the aggregating
2251  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2252  * buffer is specified as the buf parameter.  This routine does not return
2253  * failure; if there is no space in the aggregation buffer, the data will be
2254  * dropped, and a corresponding counter incremented.
2255  */
2256 static void
2257 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2258     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2259 {
2260         dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2261         uint32_t i, ndx, size, fsize;
2262         uint32_t align = sizeof (uint64_t) - 1;
2263         dtrace_aggbuffer_t *agb;
2264         dtrace_aggkey_t *key;
2265         uint32_t hashval = 0, limit, isstr;
2266         caddr_t tomax, data, kdata;
2267         dtrace_actkind_t action;
2268         dtrace_action_t *act;
2269         uintptr_t offs;
2270 
2271         if (buf == NULL)
2272                 return;
2273 
2274         if (!agg->dtag_hasarg) {
2275                 /*
2276                  * Currently, only quantize() and lquantize() take additional
2277                  * arguments, and they have the same semantics:  an increment
2278                  * value that defaults to 1 when not present.  If additional
2279                  * aggregating actions take arguments, the setting of the
2280                  * default argument value will presumably have to become more
2281                  * sophisticated...
2282                  */
2283                 arg = 1;
2284         }
2285 
2286         action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2287         size = rec->dtrd_offset - agg->dtag_base;
2288         fsize = size + rec->dtrd_size;
2289 
2290         ASSERT(dbuf->dtb_tomax != NULL);
2291         data = dbuf->dtb_tomax + offset + agg->dtag_base;
2292 
2293         if ((tomax = buf->dtb_tomax) == NULL) {
2294                 dtrace_buffer_drop(buf);
2295                 return;
2296         }
2297 
2298         /*
2299          * The metastructure is always at the bottom of the buffer.
2300          */
2301         agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2302             sizeof (dtrace_aggbuffer_t));
2303 
2304         if (buf->dtb_offset == 0) {
2305                 /*
2306                  * We just kludge up approximately 1/8th of the size to be
2307                  * buckets.  If this guess ends up being routinely
2308                  * off-the-mark, we may need to dynamically readjust this
2309                  * based on past performance.
2310                  */
2311                 uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2312 
2313                 if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2314                     (uintptr_t)tomax || hashsize == 0) {
2315                         /*
2316                          * We've been given a ludicrously small buffer;
2317                          * increment our drop count and leave.
2318                          */
2319                         dtrace_buffer_drop(buf);
2320                         return;
2321                 }
2322 
2323                 /*
2324                  * And now, a pathetic attempt to try to get a an odd (or
2325                  * perchance, a prime) hash size for better hash distribution.
2326                  */
2327                 if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2328                         hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2329 
2330                 agb->dtagb_hashsize = hashsize;
2331                 agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2332                     agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2333                 agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2334 
2335                 for (i = 0; i < agb->dtagb_hashsize; i++)
2336                         agb->dtagb_hash[i] = NULL;
2337         }
2338 
2339         ASSERT(agg->dtag_first != NULL);
2340         ASSERT(agg->dtag_first->dta_intuple);
2341 
2342         /*
2343          * Calculate the hash value based on the key.  Note that we _don't_
2344          * include the aggid in the hashing (but we will store it as part of
2345          * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2346          * algorithm: a simple, quick algorithm that has no known funnels, and
2347          * gets good distribution in practice.  The efficacy of the hashing
2348          * algorithm (and a comparison with other algorithms) may be found by
2349          * running the ::dtrace_aggstat MDB dcmd.
2350          */
2351         for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2352                 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2353                 limit = i + act->dta_rec.dtrd_size;
2354                 ASSERT(limit <= size);
2355                 isstr = DTRACEACT_ISSTRING(act);
2356 
2357                 for (; i < limit; i++) {
2358                         hashval += data[i];
2359                         hashval += (hashval << 10);
2360                         hashval ^= (hashval >> 6);
2361 
2362                         if (isstr && data[i] == '\0')
2363                                 break;
2364                 }
2365         }
2366 
2367         hashval += (hashval << 3);
2368         hashval ^= (hashval >> 11);
2369         hashval += (hashval << 15);
2370 
2371         /*
2372          * Yes, the divide here is expensive -- but it's generally the least
2373          * of the performance issues given the amount of data that we iterate
2374          * over to compute hash values, compare data, etc.
2375          */
2376         ndx = hashval % agb->dtagb_hashsize;
2377 
2378         for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2379                 ASSERT((caddr_t)key >= tomax);
2380                 ASSERT((caddr_t)key < tomax + buf->dtb_size);
2381 
2382                 if (hashval != key->dtak_hashval || key->dtak_size != size)
2383                         continue;
2384 
2385                 kdata = key->dtak_data;
2386                 ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2387 
2388                 for (act = agg->dtag_first; act->dta_intuple;
2389                     act = act->dta_next) {
2390                         i = act->dta_rec.dtrd_offset - agg->dtag_base;
2391                         limit = i + act->dta_rec.dtrd_size;
2392                         ASSERT(limit <= size);
2393                         isstr = DTRACEACT_ISSTRING(act);
2394 
2395                         for (; i < limit; i++) {
2396                                 if (kdata[i] != data[i])
2397                                         goto next;
2398 
2399                                 if (isstr && data[i] == '\0')
2400                                         break;
2401                         }
2402                 }
2403 
2404                 if (action != key->dtak_action) {
2405                         /*
2406                          * We are aggregating on the same value in the same
2407                          * aggregation with two different aggregating actions.
2408                          * (This should have been picked up in the compiler,
2409                          * so we may be dealing with errant or devious DIF.)
2410                          * This is an error condition; we indicate as much,
2411                          * and return.
2412                          */
2413                         DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2414                         return;
2415                 }
2416 
2417                 /*
2418                  * This is a hit:  we need to apply the aggregator to
2419                  * the value at this key.
2420                  */
2421                 agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2422                 return;
2423 next:
2424                 continue;
2425         }
2426 
2427         /*
2428          * We didn't find it.  We need to allocate some zero-filled space,
2429          * link it into the hash table appropriately, and apply the aggregator
2430          * to the (zero-filled) value.
2431          */
2432         offs = buf->dtb_offset;
2433         while (offs & (align - 1))
2434                 offs += sizeof (uint32_t);
2435 
2436         /*
2437          * If we don't have enough room to both allocate a new key _and_
2438          * its associated data, increment the drop count and return.
2439          */
2440         if ((uintptr_t)tomax + offs + fsize >
2441             agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2442                 dtrace_buffer_drop(buf);
2443                 return;
2444         }
2445 
2446         /*CONSTCOND*/
2447         ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2448         key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2449         agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2450 
2451         key->dtak_data = kdata = tomax + offs;
2452         buf->dtb_offset = offs + fsize;
2453 
2454         /*
2455          * Now copy the data across.
2456          */
2457         *((dtrace_aggid_t *)kdata) = agg->dtag_id;
2458 
2459         for (i = sizeof (dtrace_aggid_t); i < size; i++)
2460                 kdata[i] = data[i];
2461 
2462         /*
2463          * Because strings are not zeroed out by default, we need to iterate
2464          * looking for actions that store strings, and we need to explicitly
2465          * pad these strings out with zeroes.
2466          */
2467         for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2468                 int nul;
2469 
2470                 if (!DTRACEACT_ISSTRING(act))
2471                         continue;
2472 
2473                 i = act->dta_rec.dtrd_offset - agg->dtag_base;
2474                 limit = i + act->dta_rec.dtrd_size;
2475                 ASSERT(limit <= size);
2476 
2477                 for (nul = 0; i < limit; i++) {
2478                         if (nul) {
2479                                 kdata[i] = '\0';
2480                                 continue;
2481                         }
2482 
2483                         if (data[i] != '\0')
2484                                 continue;
2485 
2486                         nul = 1;
2487                 }
2488         }
2489 
2490         for (i = size; i < fsize; i++)
2491                 kdata[i] = 0;
2492 
2493         key->dtak_hashval = hashval;
2494         key->dtak_size = size;
2495         key->dtak_action = action;
2496         key->dtak_next = agb->dtagb_hash[ndx];
2497         agb->dtagb_hash[ndx] = key;
2498 
2499         /*
2500          * Finally, apply the aggregator.
2501          */
2502         *((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2503         agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2504 }
2505 
2506 /*
2507  * Given consumer state, this routine finds a speculation in the INACTIVE
2508  * state and transitions it into the ACTIVE state.  If there is no speculation
2509  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2510  * incremented -- it is up to the caller to take appropriate action.
2511  */
2512 static int
2513 dtrace_speculation(dtrace_state_t *state)
2514 {
2515         int i = 0;
2516         dtrace_speculation_state_t current;
2517         uint32_t *stat = &state->dts_speculations_unavail, count;
2518 
2519         while (i < state->dts_nspeculations) {
2520                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2521 
2522                 current = spec->dtsp_state;
2523 
2524                 if (current != DTRACESPEC_INACTIVE) {
2525                         if (current == DTRACESPEC_COMMITTINGMANY ||
2526                             current == DTRACESPEC_COMMITTING ||
2527                             current == DTRACESPEC_DISCARDING)
2528                                 stat = &state->dts_speculations_busy;
2529                         i++;
2530                         continue;
2531                 }
2532 
2533                 if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2534                     current, DTRACESPEC_ACTIVE) == current)
2535                         return (i + 1);
2536         }
2537 
2538         /*
2539          * We couldn't find a speculation.  If we found as much as a single
2540          * busy speculation buffer, we'll attribute this failure as "busy"
2541          * instead of "unavail".
2542          */
2543         do {
2544                 count = *stat;
2545         } while (dtrace_cas32(stat, count, count + 1) != count);
2546 
2547         return (0);
2548 }
2549 
2550 /*
2551  * This routine commits an active speculation.  If the specified speculation
2552  * is not in a valid state to perform a commit(), this routine will silently do
2553  * nothing.  The state of the specified speculation is transitioned according
2554  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2555  */
2556 static void
2557 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2558     dtrace_specid_t which)
2559 {
2560         dtrace_speculation_t *spec;
2561         dtrace_buffer_t *src, *dest;
2562         uintptr_t daddr, saddr, dlimit, slimit;
2563         dtrace_speculation_state_t current, new;
2564         intptr_t offs;
2565         uint64_t timestamp;
2566 
2567         if (which == 0)
2568                 return;
2569 
2570         if (which > state->dts_nspeculations) {
2571                 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2572                 return;
2573         }
2574 
2575         spec = &state->dts_speculations[which - 1];
2576         src = &spec->dtsp_buffer[cpu];
2577         dest = &state->dts_buffer[cpu];
2578 
2579         do {
2580                 current = spec->dtsp_state;
2581 
2582                 if (current == DTRACESPEC_COMMITTINGMANY)
2583                         break;
2584 
2585                 switch (current) {
2586                 case DTRACESPEC_INACTIVE:
2587                 case DTRACESPEC_DISCARDING:
2588                         return;
2589 
2590                 case DTRACESPEC_COMMITTING:
2591                         /*
2592                          * This is only possible if we are (a) commit()'ing
2593                          * without having done a prior speculate() on this CPU
2594                          * and (b) racing with another commit() on a different
2595                          * CPU.  There's nothing to do -- we just assert that
2596                          * our offset is 0.
2597                          */
2598                         ASSERT(src->dtb_offset == 0);
2599                         return;
2600 
2601                 case DTRACESPEC_ACTIVE:
2602                         new = DTRACESPEC_COMMITTING;
2603                         break;
2604 
2605                 case DTRACESPEC_ACTIVEONE:
2606                         /*
2607                          * This speculation is active on one CPU.  If our
2608                          * buffer offset is non-zero, we know that the one CPU
2609                          * must be us.  Otherwise, we are committing on a
2610                          * different CPU from the speculate(), and we must
2611                          * rely on being asynchronously cleaned.
2612                          */
2613                         if (src->dtb_offset != 0) {
2614                                 new = DTRACESPEC_COMMITTING;
2615                                 break;
2616                         }
2617                         /*FALLTHROUGH*/
2618 
2619                 case DTRACESPEC_ACTIVEMANY:
2620                         new = DTRACESPEC_COMMITTINGMANY;
2621                         break;
2622 
2623                 default:
2624                         ASSERT(0);
2625                 }
2626         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2627             current, new) != current);
2628 
2629         /*
2630          * We have set the state to indicate that we are committing this
2631          * speculation.  Now reserve the necessary space in the destination
2632          * buffer.
2633          */
2634         if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2635             sizeof (uint64_t), state, NULL)) < 0) {
2636                 dtrace_buffer_drop(dest);
2637                 goto out;
2638         }
2639 
2640         /*
2641          * We have sufficient space to copy the speculative buffer into the
2642          * primary buffer.  First, modify the speculative buffer, filling
2643          * in the timestamp of all entries with the current time.  The data
2644          * must have the commit() time rather than the time it was traced,
2645          * so that all entries in the primary buffer are in timestamp order.
2646          */
2647         timestamp = dtrace_gethrtime();
2648         saddr = (uintptr_t)src->dtb_tomax;
2649         slimit = saddr + src->dtb_offset;
2650         while (saddr < slimit) {
2651                 size_t size;
2652                 dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2653 
2654                 if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2655                         saddr += sizeof (dtrace_epid_t);
2656                         continue;
2657                 }
2658                 ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2659                 size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2660 
2661                 ASSERT3U(saddr + size, <=, slimit);
2662                 ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2663                 ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2664 
2665                 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2666 
2667                 saddr += size;
2668         }
2669 
2670         /*
2671          * Copy the buffer across.  (Note that this is a
2672          * highly subobtimal bcopy(); in the unlikely event that this becomes
2673          * a serious performance issue, a high-performance DTrace-specific
2674          * bcopy() should obviously be invented.)
2675          */
2676         daddr = (uintptr_t)dest->dtb_tomax + offs;
2677         dlimit = daddr + src->dtb_offset;
2678         saddr = (uintptr_t)src->dtb_tomax;
2679 
2680         /*
2681          * First, the aligned portion.
2682          */
2683         while (dlimit - daddr >= sizeof (uint64_t)) {
2684                 *((uint64_t *)daddr) = *((uint64_t *)saddr);
2685 
2686                 daddr += sizeof (uint64_t);
2687                 saddr += sizeof (uint64_t);
2688         }
2689 
2690         /*
2691          * Now any left-over bit...
2692          */
2693         while (dlimit - daddr)
2694                 *((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2695 
2696         /*
2697          * Finally, commit the reserved space in the destination buffer.
2698          */
2699         dest->dtb_offset = offs + src->dtb_offset;
2700 
2701 out:
2702         /*
2703          * If we're lucky enough to be the only active CPU on this speculation
2704          * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2705          */
2706         if (current == DTRACESPEC_ACTIVE ||
2707             (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2708                 uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2709                     DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2710 
2711                 ASSERT(rval == DTRACESPEC_COMMITTING);
2712         }
2713 
2714         src->dtb_offset = 0;
2715         src->dtb_xamot_drops += src->dtb_drops;
2716         src->dtb_drops = 0;
2717 }
2718 
2719 /*
2720  * This routine discards an active speculation.  If the specified speculation
2721  * is not in a valid state to perform a discard(), this routine will silently
2722  * do nothing.  The state of the specified speculation is transitioned
2723  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2724  */
2725 static void
2726 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2727     dtrace_specid_t which)
2728 {
2729         dtrace_speculation_t *spec;
2730         dtrace_speculation_state_t current, new;
2731         dtrace_buffer_t *buf;
2732 
2733         if (which == 0)
2734                 return;
2735 
2736         if (which > state->dts_nspeculations) {
2737                 cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2738                 return;
2739         }
2740 
2741         spec = &state->dts_speculations[which - 1];
2742         buf = &spec->dtsp_buffer[cpu];
2743 
2744         do {
2745                 current = spec->dtsp_state;
2746 
2747                 switch (current) {
2748                 case DTRACESPEC_INACTIVE:
2749                 case DTRACESPEC_COMMITTINGMANY:
2750                 case DTRACESPEC_COMMITTING:
2751                 case DTRACESPEC_DISCARDING:
2752                         return;
2753 
2754                 case DTRACESPEC_ACTIVE:
2755                 case DTRACESPEC_ACTIVEMANY:
2756                         new = DTRACESPEC_DISCARDING;
2757                         break;
2758 
2759                 case DTRACESPEC_ACTIVEONE:
2760                         if (buf->dtb_offset != 0) {
2761                                 new = DTRACESPEC_INACTIVE;
2762                         } else {
2763                                 new = DTRACESPEC_DISCARDING;
2764                         }
2765                         break;
2766 
2767                 default:
2768                         ASSERT(0);
2769                 }
2770         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2771             current, new) != current);
2772 
2773         buf->dtb_offset = 0;
2774         buf->dtb_drops = 0;
2775 }
2776 
2777 /*
2778  * Note:  not called from probe context.  This function is called
2779  * asynchronously from cross call context to clean any speculations that are
2780  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2781  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2782  * speculation.
2783  */
2784 static void
2785 dtrace_speculation_clean_here(dtrace_state_t *state)
2786 {
2787         dtrace_icookie_t cookie;
2788         processorid_t cpu = CPU->cpu_id;
2789         dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2790         dtrace_specid_t i;
2791 
2792         cookie = dtrace_interrupt_disable();
2793 
2794         if (dest->dtb_tomax == NULL) {
2795                 dtrace_interrupt_enable(cookie);
2796                 return;
2797         }
2798 
2799         for (i = 0; i < state->dts_nspeculations; i++) {
2800                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2801                 dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2802 
2803                 if (src->dtb_tomax == NULL)
2804                         continue;
2805 
2806                 if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2807                         src->dtb_offset = 0;
2808                         continue;
2809                 }
2810 
2811                 if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2812                         continue;
2813 
2814                 if (src->dtb_offset == 0)
2815                         continue;
2816 
2817                 dtrace_speculation_commit(state, cpu, i + 1);
2818         }
2819 
2820         dtrace_interrupt_enable(cookie);
2821 }
2822 
2823 /*
2824  * Note:  not called from probe context.  This function is called
2825  * asynchronously (and at a regular interval) to clean any speculations that
2826  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2827  * is work to be done, it cross calls all CPUs to perform that work;
2828  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2829  * INACTIVE state until they have been cleaned by all CPUs.
2830  */
2831 static void
2832 dtrace_speculation_clean(dtrace_state_t *state)
2833 {
2834         int work = 0, rv;
2835         dtrace_specid_t i;
2836 
2837         for (i = 0; i < state->dts_nspeculations; i++) {
2838                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2839 
2840                 ASSERT(!spec->dtsp_cleaning);
2841 
2842                 if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2843                     spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2844                         continue;
2845 
2846                 work++;
2847                 spec->dtsp_cleaning = 1;
2848         }
2849 
2850         if (!work)
2851                 return;
2852 
2853         dtrace_xcall(DTRACE_CPUALL,
2854             (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2855 
2856         /*
2857          * We now know that all CPUs have committed or discarded their
2858          * speculation buffers, as appropriate.  We can now set the state
2859          * to inactive.
2860          */
2861         for (i = 0; i < state->dts_nspeculations; i++) {
2862                 dtrace_speculation_t *spec = &state->dts_speculations[i];
2863                 dtrace_speculation_state_t current, new;
2864 
2865                 if (!spec->dtsp_cleaning)
2866                         continue;
2867 
2868                 current = spec->dtsp_state;
2869                 ASSERT(current == DTRACESPEC_DISCARDING ||
2870                     current == DTRACESPEC_COMMITTINGMANY);
2871 
2872                 new = DTRACESPEC_INACTIVE;
2873 
2874                 rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2875                 ASSERT(rv == current);
2876                 spec->dtsp_cleaning = 0;
2877         }
2878 }
2879 
2880 /*
2881  * Called as part of a speculate() to get the speculative buffer associated
2882  * with a given speculation.  Returns NULL if the specified speculation is not
2883  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2884  * the active CPU is not the specified CPU -- the speculation will be
2885  * atomically transitioned into the ACTIVEMANY state.
2886  */
2887 static dtrace_buffer_t *
2888 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2889     dtrace_specid_t which)
2890 {
2891         dtrace_speculation_t *spec;
2892         dtrace_speculation_state_t current, new;
2893         dtrace_buffer_t *buf;
2894 
2895         if (which == 0)
2896                 return (NULL);
2897 
2898         if (which > state->dts_nspeculations) {
2899                 cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2900                 return (NULL);
2901         }
2902 
2903         spec = &state->dts_speculations[which - 1];
2904         buf = &spec->dtsp_buffer[cpuid];
2905 
2906         do {
2907                 current = spec->dtsp_state;
2908 
2909                 switch (current) {
2910                 case DTRACESPEC_INACTIVE:
2911                 case DTRACESPEC_COMMITTINGMANY:
2912                 case DTRACESPEC_DISCARDING:
2913                         return (NULL);
2914 
2915                 case DTRACESPEC_COMMITTING:
2916                         ASSERT(buf->dtb_offset == 0);
2917                         return (NULL);
2918 
2919                 case DTRACESPEC_ACTIVEONE:
2920                         /*
2921                          * This speculation is currently active on one CPU.
2922                          * Check the offset in the buffer; if it's non-zero,
2923                          * that CPU must be us (and we leave the state alone).
2924                          * If it's zero, assume that we're starting on a new
2925                          * CPU -- and change the state to indicate that the
2926                          * speculation is active on more than one CPU.
2927                          */
2928                         if (buf->dtb_offset != 0)
2929                                 return (buf);
2930 
2931                         new = DTRACESPEC_ACTIVEMANY;
2932                         break;
2933 
2934                 case DTRACESPEC_ACTIVEMANY:
2935                         return (buf);
2936 
2937                 case DTRACESPEC_ACTIVE:
2938                         new = DTRACESPEC_ACTIVEONE;
2939                         break;
2940 
2941                 default:
2942                         ASSERT(0);
2943                 }
2944         } while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2945             current, new) != current);
2946 
2947         ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2948         return (buf);
2949 }
2950 
2951 /*
2952  * Return a string.  In the event that the user lacks the privilege to access
2953  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2954  * don't fail access checking.
2955  *
2956  * dtrace_dif_variable() uses this routine as a helper for various
2957  * builtin values such as 'execname' and 'probefunc.'
2958  */
2959 uintptr_t
2960 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2961     dtrace_mstate_t *mstate)
2962 {
2963         uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2964         uintptr_t ret;
2965         size_t strsz;
2966 
2967         /*
2968          * The easy case: this probe is allowed to read all of memory, so
2969          * we can just return this as a vanilla pointer.
2970          */
2971         if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2972                 return (addr);
2973 
2974         /*
2975          * This is the tougher case: we copy the string in question from
2976          * kernel memory into scratch memory and return it that way: this
2977          * ensures that we won't trip up when access checking tests the
2978          * BYREF return value.
2979          */
2980         strsz = dtrace_strlen((char *)addr, size) + 1;
2981 
2982         if (mstate->dtms_scratch_ptr + strsz >
2983             mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2984                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2985                 return (NULL);
2986         }
2987 
2988         dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2989             strsz);
2990         ret = mstate->dtms_scratch_ptr;
2991         mstate->dtms_scratch_ptr += strsz;
2992         return (ret);
2993 }
2994 
2995 /*
2996  * This function implements the DIF emulator's variable lookups.  The emulator
2997  * passes a reserved variable identifier and optional built-in array index.
2998  */
2999 static uint64_t
3000 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3001     uint64_t ndx)
3002 {
3003         /*
3004          * If we're accessing one of the uncached arguments, we'll turn this
3005          * into a reference in the args array.
3006          */
3007         if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3008                 ndx = v - DIF_VAR_ARG0;
3009                 v = DIF_VAR_ARGS;
3010         }
3011 
3012         switch (v) {
3013         case DIF_VAR_ARGS:
3014                 if (!(mstate->dtms_access & DTRACE_ACCESS_ARGS)) {
3015                         cpu_core[CPU->cpu_id].cpuc_dtrace_flags |=
3016                             CPU_DTRACE_KPRIV;
3017                         return (0);
3018                 }
3019 
3020                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3021                 if (ndx >= sizeof (mstate->dtms_arg) /
3022                     sizeof (mstate->dtms_arg[0])) {
3023                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3024                         dtrace_provider_t *pv;
3025                         uint64_t val;
3026 
3027                         pv = mstate->dtms_probe->dtpr_provider;
3028                         if (pv->dtpv_pops.dtps_getargval != NULL)
3029                                 val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3030                                     mstate->dtms_probe->dtpr_id,
3031                                     mstate->dtms_probe->dtpr_arg, ndx, aframes);
3032                         else
3033                                 val = dtrace_getarg(ndx, aframes);
3034 
3035                         /*
3036                          * This is regrettably required to keep the compiler
3037                          * from tail-optimizing the call to dtrace_getarg().
3038                          * The condition always evaluates to true, but the
3039                          * compiler has no way of figuring that out a priori.
3040                          * (None of this would be necessary if the compiler
3041                          * could be relied upon to _always_ tail-optimize
3042                          * the call to dtrace_getarg() -- but it can't.)
3043                          */
3044                         if (mstate->dtms_probe != NULL)
3045                                 return (val);
3046 
3047                         ASSERT(0);
3048                 }
3049 
3050                 return (mstate->dtms_arg[ndx]);
3051 
3052         case DIF_VAR_UREGS: {
3053                 klwp_t *lwp;
3054 
3055                 if (!dtrace_priv_proc(state, mstate))
3056                         return (0);
3057 
3058                 if ((lwp = curthread->t_lwp) == NULL) {
3059                         DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3060                         cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
3061                         return (0);
3062                 }
3063 
3064                 return (dtrace_getreg(lwp->lwp_regs, ndx));
3065         }
3066 
3067         case DIF_VAR_VMREGS: {
3068                 uint64_t rval;
3069 
3070                 if (!dtrace_priv_kernel(state))
3071                         return (0);
3072 
3073                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3074 
3075                 rval = dtrace_getvmreg(ndx,
3076                     &cpu_core[CPU->cpu_id].cpuc_dtrace_flags);
3077 
3078                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3079 
3080                 return (rval);
3081         }
3082 
3083         case DIF_VAR_CURTHREAD:
3084                 if (!dtrace_priv_proc(state, mstate))
3085                         return (0);
3086                 return ((uint64_t)(uintptr_t)curthread);
3087 
3088         case DIF_VAR_TIMESTAMP:
3089                 if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3090                         mstate->dtms_timestamp = dtrace_gethrtime();
3091                         mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3092                 }
3093                 return (mstate->dtms_timestamp);
3094 
3095         case DIF_VAR_VTIMESTAMP:
3096                 ASSERT(dtrace_vtime_references != 0);
3097                 return (curthread->t_dtrace_vtime);
3098 
3099         case DIF_VAR_WALLTIMESTAMP:
3100                 if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3101                         mstate->dtms_walltimestamp = dtrace_gethrestime();
3102                         mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3103                 }
3104                 return (mstate->dtms_walltimestamp);
3105 
3106         case DIF_VAR_IPL:
3107                 if (!dtrace_priv_kernel(state))
3108                         return (0);
3109                 if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3110                         mstate->dtms_ipl = dtrace_getipl();
3111                         mstate->dtms_present |= DTRACE_MSTATE_IPL;
3112                 }
3113                 return (mstate->dtms_ipl);
3114 
3115         case DIF_VAR_EPID:
3116                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3117                 return (mstate->dtms_epid);
3118 
3119         case DIF_VAR_ID:
3120                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3121                 return (mstate->dtms_probe->dtpr_id);
3122 
3123         case DIF_VAR_STACKDEPTH:
3124                 if (!dtrace_priv_kernel(state))
3125                         return (0);
3126                 if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3127                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3128 
3129                         mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3130                         mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3131                 }
3132                 return (mstate->dtms_stackdepth);
3133 
3134         case DIF_VAR_USTACKDEPTH:
3135                 if (!dtrace_priv_proc(state, mstate))
3136                         return (0);
3137                 if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3138                         /*
3139                          * See comment in DIF_VAR_PID.
3140                          */
3141                         if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3142                             CPU_ON_INTR(CPU)) {
3143                                 mstate->dtms_ustackdepth = 0;
3144                         } else {
3145                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3146                                 mstate->dtms_ustackdepth =
3147                                     dtrace_getustackdepth();
3148                                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3149                         }
3150                         mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3151                 }
3152                 return (mstate->dtms_ustackdepth);
3153 
3154         case DIF_VAR_CALLER:
3155                 if (!dtrace_priv_kernel(state))
3156                         return (0);
3157                 if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3158                         int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3159 
3160                         if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3161                                 /*
3162                                  * If this is an unanchored probe, we are
3163                                  * required to go through the slow path:
3164                                  * dtrace_caller() only guarantees correct
3165                                  * results for anchored probes.
3166                                  */
3167                                 pc_t caller[2];
3168 
3169                                 dtrace_getpcstack(caller, 2, aframes,
3170                                     (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3171                                 mstate->dtms_caller = caller[1];
3172                         } else if ((mstate->dtms_caller =
3173                             dtrace_caller(aframes)) == -1) {
3174                                 /*
3175                                  * We have failed to do this the quick way;
3176                                  * we must resort to the slower approach of
3177                                  * calling dtrace_getpcstack().
3178                                  */
3179                                 pc_t caller;
3180 
3181                                 dtrace_getpcstack(&caller, 1, aframes, NULL);
3182                                 mstate->dtms_caller = caller;
3183                         }
3184 
3185                         mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3186                 }
3187                 return (mstate->dtms_caller);
3188 
3189         case DIF_VAR_UCALLER:
3190                 if (!dtrace_priv_proc(state, mstate))
3191                         return (0);
3192 
3193                 if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3194                         uint64_t ustack[3];
3195 
3196                         /*
3197                          * dtrace_getupcstack() fills in the first uint64_t
3198                          * with the current PID.  The second uint64_t will
3199                          * be the program counter at user-level.  The third
3200                          * uint64_t will contain the caller, which is what
3201                          * we're after.
3202                          */
3203                         ustack[2] = NULL;
3204                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3205                         dtrace_getupcstack(ustack, 3);
3206                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3207                         mstate->dtms_ucaller = ustack[2];
3208                         mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3209                 }
3210 
3211                 return (mstate->dtms_ucaller);
3212 
3213         case DIF_VAR_PROBEPROV:
3214                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3215                 return (dtrace_dif_varstr(
3216                     (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3217                     state, mstate));
3218 
3219         case DIF_VAR_PROBEMOD:
3220                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3221                 return (dtrace_dif_varstr(
3222                     (uintptr_t)mstate->dtms_probe->dtpr_mod,
3223                     state, mstate));
3224 
3225         case DIF_VAR_PROBEFUNC:
3226                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3227                 return (dtrace_dif_varstr(
3228                     (uintptr_t)mstate->dtms_probe->dtpr_func,
3229                     state, mstate));
3230 
3231         case DIF_VAR_PROBENAME:
3232                 ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3233                 return (dtrace_dif_varstr(
3234                     (uintptr_t)mstate->dtms_probe->dtpr_name,
3235                     state, mstate));
3236 
3237         case DIF_VAR_PID:
3238                 if (!dtrace_priv_proc(state, mstate))
3239                         return (0);
3240 
3241                 /*
3242                  * Note that we are assuming that an unanchored probe is
3243                  * always due to a high-level interrupt.  (And we're assuming
3244                  * that there is only a single high level interrupt.)
3245                  */
3246                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3247                         return (pid0.pid_id);
3248 
3249                 /*
3250                  * It is always safe to dereference one's own t_procp pointer:
3251                  * it always points to a valid, allocated proc structure.
3252                  * Further, it is always safe to dereference the p_pidp member
3253                  * of one's own proc structure.  (These are truisms becuase
3254                  * threads and processes don't clean up their own state --
3255                  * they leave that task to whomever reaps them.)
3256                  */
3257                 return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3258 
3259         case DIF_VAR_PPID:
3260                 if (!dtrace_priv_proc(state, mstate))
3261                         return (0);
3262 
3263                 /*
3264                  * See comment in DIF_VAR_PID.
3265                  */
3266                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3267                         return (pid0.pid_id);
3268 
3269                 /*
3270                  * It is always safe to dereference one's own t_procp pointer:
3271                  * it always points to a valid, allocated proc structure.
3272                  * (This is true because threads don't clean up their own
3273                  * state -- they leave that task to whomever reaps them.)
3274                  */
3275                 return ((uint64_t)curthread->t_procp->p_ppid);
3276 
3277         case DIF_VAR_TID:
3278                 /*
3279                  * See comment in DIF_VAR_PID.
3280                  */
3281                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3282                         return (0);
3283 
3284                 return ((uint64_t)curthread->t_tid);
3285 
3286         case DIF_VAR_EXECNAME:
3287                 if (!dtrace_priv_proc(state, mstate))
3288                         return (0);
3289 
3290                 /*
3291                  * See comment in DIF_VAR_PID.
3292                  */
3293                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3294                         return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3295 
3296                 /*
3297                  * It is always safe to dereference one's own t_procp pointer:
3298                  * it always points to a valid, allocated proc structure.
3299                  * (This is true because threads don't clean up their own
3300                  * state -- they leave that task to whomever reaps them.)
3301                  */
3302                 return (dtrace_dif_varstr(
3303                     (uintptr_t)curthread->t_procp->p_user.u_comm,
3304                     state, mstate));
3305 
3306         case DIF_VAR_ZONENAME:
3307                 if (!dtrace_priv_proc(state, mstate))
3308                         return (0);
3309 
3310                 /*
3311                  * See comment in DIF_VAR_PID.
3312                  */
3313                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3314                         return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3315 
3316                 /*
3317                  * It is always safe to dereference one's own t_procp pointer:
3318                  * it always points to a valid, allocated proc structure.
3319                  * (This is true because threads don't clean up their own
3320                  * state -- they leave that task to whomever reaps them.)
3321                  */
3322                 return (dtrace_dif_varstr(
3323                     (uintptr_t)curthread->t_procp->p_zone->zone_name,
3324                     state, mstate));
3325 
3326         case DIF_VAR_UID:
3327                 if (!dtrace_priv_proc(state, mstate))
3328                         return (0);
3329 
3330                 /*
3331                  * See comment in DIF_VAR_PID.
3332                  */
3333                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3334                         return ((uint64_t)p0.p_cred->cr_uid);
3335 
3336                 /*
3337                  * It is always safe to dereference one's own t_procp pointer:
3338                  * it always points to a valid, allocated proc structure.
3339                  * (This is true because threads don't clean up their own
3340                  * state -- they leave that task to whomever reaps them.)
3341                  *
3342                  * Additionally, it is safe to dereference one's own process
3343                  * credential, since this is never NULL after process birth.
3344                  */
3345                 return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3346 
3347         case DIF_VAR_GID:
3348                 if (!dtrace_priv_proc(state, mstate))
3349                         return (0);
3350 
3351                 /*
3352                  * See comment in DIF_VAR_PID.
3353                  */
3354                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3355                         return ((uint64_t)p0.p_cred->cr_gid);
3356 
3357                 /*
3358                  * It is always safe to dereference one's own t_procp pointer:
3359                  * it always points to a valid, allocated proc structure.
3360                  * (This is true because threads don't clean up their own
3361                  * state -- they leave that task to whomever reaps them.)
3362                  *
3363                  * Additionally, it is safe to dereference one's own process
3364                  * credential, since this is never NULL after process birth.
3365                  */
3366                 return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3367 
3368         case DIF_VAR_ERRNO: {
3369                 klwp_t *lwp;
3370                 if (!dtrace_priv_proc(state, mstate))
3371                         return (0);
3372 
3373                 /*
3374                  * See comment in DIF_VAR_PID.
3375                  */
3376                 if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3377                         return (0);
3378 
3379                 /*
3380                  * It is always safe to dereference one's own t_lwp pointer in
3381                  * the event that this pointer is non-NULL.  (This is true
3382                  * because threads and lwps don't clean up their own state --
3383                  * they leave that task to whomever reaps them.)
3384                  */
3385                 if ((lwp = curthread->t_lwp) == NULL)
3386                         return (0);
3387 
3388                 return ((uint64_t)lwp->lwp_errno);
3389         }
3390         default:
3391                 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3392                 return (0);
3393         }
3394 }
3395 
3396 
3397 typedef enum json_state {
3398         JSON_REST = 1,
3399         JSON_OBJECT,
3400         JSON_STRING,
3401         JSON_STRING_ESCAPE,
3402         JSON_STRING_ESCAPE_UNICODE,
3403         JSON_COLON,
3404         JSON_COMMA,
3405         JSON_VALUE,
3406         JSON_IDENTIFIER,
3407         JSON_NUMBER,
3408         JSON_NUMBER_FRAC,
3409         JSON_NUMBER_EXP,
3410         JSON_COLLECT_OBJECT
3411 } json_state_t;
3412 
3413 /*
3414  * This function possesses just enough knowledge about JSON to extract a single
3415  * value from a JSON string and store it in the scratch buffer.  It is able
3416  * to extract nested object values, and members of arrays by index.
3417  *
3418  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3419  * be looked up as we descend into the object tree.  e.g.
3420  *
3421  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3422  *       with nelems = 5.
3423  */
3424 static char *
3425 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3426     char *dest)
3427 {
3428         json_state_t state = JSON_REST;
3429         uint64_t i;
3430         int64_t array_elem = INT64_MIN;
3431         int64_t array_pos = 0;
3432         uint8_t escape_unicount = 0;
3433         boolean_t string_is_key = B_FALSE;
3434         boolean_t collect_object = B_FALSE;
3435         boolean_t found_key = B_FALSE;
3436         boolean_t in_array = B_FALSE;
3437         uint8_t braces = 0, brackets = 0;
3438         char *elem = elemlist;
3439         char *dd = dest;
3440         uintptr_t cur;
3441 
3442         for (cur = json; cur < json + size; cur++) {
3443                 char cc = dtrace_load8(cur);
3444                 if (cc == '\0' || braces > 250)
3445                         return (NULL);
3446 
3447                 switch (state) {
3448                 case JSON_REST:
3449                         if (cc == ' ' || cc == '\t' || cc == '\n' || cc == '\r')
3450                                 break; /* eat whitespace */
3451 
3452                         if (cc == '{') {
3453                                 state = JSON_OBJECT;
3454                                 break;
3455                         }
3456 
3457                         if (cc == '[') {
3458                                 in_array = B_TRUE;
3459                                 array_pos = 0;
3460                                 array_elem = dtrace_strtoll(elem, 10, size);
3461                                 found_key = !!(array_elem == 0);
3462                                 state = JSON_VALUE;
3463                                 break;
3464                         }
3465 
3466                         /* ERROR: expected object or array */
3467                         return (NULL);
3468                 case JSON_OBJECT:
3469                         if (cc == ' ' || cc == '\t' || cc == '\n' || cc == '\r')
3470                                 break; /* eat whitespace */
3471 
3472                         if (cc == '"') {
3473                                 state = JSON_STRING;
3474                                 string_is_key = B_TRUE;
3475                                 break;
3476                         }
3477 
3478                         /* ERROR: key not found! */
3479                         return (NULL);
3480                 case JSON_STRING:
3481                         if (cc == '\\') {
3482                                 *dd++ = '\\';
3483                                 state = JSON_STRING_ESCAPE;
3484                                 break;
3485                         }
3486 
3487                         if (cc == '"') {
3488                                 if (collect_object) {
3489                                         /*
3490                                          * We don't reset the dest here, as
3491                                          * the string is part of a larger
3492                                          * object being collected.
3493                                          */
3494                                         *dd++ = cc;
3495                                         collect_object = B_FALSE;
3496                                         state = JSON_COLLECT_OBJECT;
3497                                         break;
3498                                 }
3499                                 *dd = '\0';
3500                                 dd = dest; /* reset string buffer */
3501                                 if (string_is_key) {
3502                                         if (dtrace_strncmp(dest, elem,
3503                                             size) == 0)
3504                                                 found_key = B_TRUE;
3505                                 } else if (found_key) {
3506                                         if (nelems > 1) {
3507                                                 /*
3508                                                  * We expected an object, not
3509                                                  * this string.
3510                                                  */
3511                                                 return (NULL);
3512                                         }
3513                                         return (dest);
3514                                 }
3515                                 state = string_is_key ? JSON_COLON :
3516                                     JSON_COMMA;
3517                                 string_is_key = B_FALSE;
3518                                 break;
3519                         }
3520 
3521                         *dd++ = cc;
3522                         break;
3523                 case JSON_STRING_ESCAPE:
3524                         *dd++ = cc;
3525                         if (cc == 'u') {
3526                                 escape_unicount = 0;
3527                                 state = JSON_STRING_ESCAPE_UNICODE;
3528                         } else {
3529                                 state = JSON_STRING;
3530                         }
3531                         break;
3532                 case JSON_STRING_ESCAPE_UNICODE:
3533                         if (!isxdigit(cc))
3534                                 /* ERROR: unvalid unicode escape */
3535                                 return (NULL);
3536 
3537                         *dd++ = cc;
3538                         if (++escape_unicount == 4)
3539                                 state = JSON_STRING;
3540                         break;
3541                 case JSON_COLON:
3542                         if (cc == ' ' || cc == '\t' || cc == '\n' || cc == '\r')
3543                                 break; /* eat whitespace */
3544 
3545                         if (cc == ':') {
3546                                 state = JSON_VALUE;
3547                                 break;
3548                         }
3549 
3550                         /* ERROR: expected colon */
3551                         return (NULL);
3552                 case JSON_COMMA:
3553                         if (cc == ' ' || cc == '\t' || cc == '\n' || cc == '\r')
3554                                 break; /* eat whitespace */
3555 
3556                         if (cc == ',') {
3557                                 if (in_array) {
3558                                         state = JSON_VALUE;
3559                                         if (++array_pos == array_elem)
3560                                                 found_key = B_TRUE;
3561                                 } else {
3562                                         state = JSON_OBJECT;
3563                                 }
3564                                 break;
3565                         }
3566 
3567                         /* ERROR: key not found or expected comma */
3568                         return (NULL);
3569                 case JSON_IDENTIFIER:
3570                         if (cc >= 'a' && cc <= 'z') {
3571                                 *dd++ = cc;
3572                                 break;
3573                         }
3574 
3575                         *dd = '\0';
3576                         dd = dest; /* reset string buffer */
3577 
3578                         if (dtrace_strncmp(dest, "true", 5) == 0 ||
3579                             dtrace_strncmp(dest, "false", 6) == 0 ||
3580                             dtrace_strncmp(dest, "null", 5) == 0) {
3581                                 if (found_key) {
3582                                         if (nelems > 1) {
3583                                                 /*
3584                                                  * We expected an object, not
3585                                                  * this identifier.
3586                                                  */
3587                                                 return (NULL);
3588                                         }
3589                                         return (dest);
3590                                 } else {
3591                                         cur--;
3592                                         state = JSON_COMMA;
3593                                         break;
3594                                 }
3595                         }
3596 
3597                         /* ERROR: unexpected identifier */
3598                         return (NULL);
3599                 case JSON_NUMBER:
3600                         if (cc == '.') {
3601                                 *dd++ = cc;
3602                                 state = JSON_NUMBER_FRAC;
3603                                 break;
3604                         }
3605 
3606                         if (cc == 'x' || cc == 'X')
3607                                 /* ERROR: spec explicitly excludes hex */
3608                                 return (NULL);
3609 
3610                         /* FALLTHRU */
3611                 case JSON_NUMBER_FRAC:
3612                         if (cc == 'e' || cc == 'E') {
3613                                 *dd++ = cc;
3614                                 state = JSON_NUMBER_EXP;
3615                                 break;
3616                         }
3617 
3618                         if (cc == '+' || cc == '-') {
3619                                 /*
3620                                  * ERROR: expect sign as part of exponent only
3621                                  */
3622                                 return (NULL);
3623                         }
3624                         /* FALLTHRU */
3625                 case JSON_NUMBER_EXP:
3626                         if ((cc >= '0' && cc <= '9') || cc == '+' ||
3627                             cc == '-') {
3628                                 *dd++ = cc;
3629                                 break;
3630                         }
3631 
3632                         *dd = '\0';
3633                         dd = dest; /* reset string buffer */
3634                         if (found_key) {
3635                                 if (nelems > 1) {
3636                                         /*
3637                                          * We expected an object, not this
3638                                          * number.
3639                                          */
3640                                         return (NULL);
3641                                 }
3642                                 return (dest);
3643                         }
3644 
3645                         cur--;
3646                         state = JSON_COMMA;
3647                         break;
3648                 case JSON_VALUE:
3649                         if (cc == ' ' || cc == '\t' || cc == '\n' || cc == '\r')
3650                                 break; /* eat whitespace */
3651 
3652                         if (cc == '{' || cc == '[') {
3653                                 if (nelems > 1 && found_key) {
3654                                         in_array = !!(cc == '[');
3655                                         /*
3656                                          * If our element selector directs us
3657                                          * to descend into this nested object,
3658                                          * then move to the next selector
3659                                          * element in the list and restart the
3660                                          * state machine.
3661                                          */
3662                                         while (*elem != '\0')
3663                                                 elem++;
3664                                         elem++; /* skip the inter-element NUL */
3665                                         nelems--;
3666                                         dd = dest;
3667                                         if (in_array) {
3668                                                 state = JSON_VALUE;
3669                                                 array_pos = 0;
3670                                                 array_elem = dtrace_strtoll(
3671                                                     elem, 10, size);
3672                                                 found_key = !!(array_elem == 0);
3673                                         } else {
3674                                                 found_key = B_FALSE;
3675                                                 state = JSON_OBJECT;
3676                                         }
3677                                         break;
3678                                 }
3679 
3680                                 /*
3681                                  * Otherwise, we wish to either skip this
3682                                  * nested object or return it in full.
3683                                  */
3684                                 if (cc == '[')
3685                                         brackets = 1;
3686                                 else
3687                                         braces = 1;
3688                                 *dd++ = cc;
3689                                 state = JSON_COLLECT_OBJECT;
3690                                 break;
3691                         }
3692 
3693                         if (cc == '"') {
3694                                 state = JSON_STRING;
3695                                 break;
3696                         }
3697 
3698                         if (cc >= 'a' && cc <= 'z') {
3699                                 /* Here we deal with true, false and null */
3700                                 *dd++ = cc;
3701                                 state = JSON_IDENTIFIER;
3702                                 break;
3703                         }
3704 
3705                         if (cc == '-' || (cc >= '0' && cc <= '9')) {
3706                                 *dd++ = cc;
3707                                 state = JSON_NUMBER;
3708                                 break;
3709                         }
3710 
3711                         /* ERROR: unexpected character */
3712                         return (NULL);
3713                 case JSON_COLLECT_OBJECT:
3714                         if (cc == '\0')
3715                                 /* ERROR: unexpected end of input */
3716                                 return (NULL);
3717 
3718                         *dd++ = cc;
3719                         if (cc == '"') {
3720                                 collect_object = B_TRUE;
3721                                 state = JSON_STRING;
3722                                 break;
3723                         }
3724 
3725                         if (cc == ']') {
3726                                 if (brackets-- == 0) {
3727                                         /* ERROR: unbalanced brackets */
3728                                         return (NULL);
3729                                 }
3730                         } else if (cc == '}') {
3731                                 if (braces-- == 0) {
3732                                         /* ERROR: unbalanced braces */
3733                                         return (NULL);
3734                                 }
3735                         } else if (cc == '{') {
3736                                 braces++;
3737                         } else if (cc == '[') {
3738                                 brackets++;
3739                         }
3740 
3741                         if (brackets == 0 && braces == 0) {
3742                                 if (found_key) {
3743                                         *dd = '\0';
3744                                         return (dest);
3745                                 }
3746                                 dd = dest; /* reset string buffer */
3747                                 state = JSON_COMMA;
3748                         }
3749                         break;
3750                 }
3751         }
3752         return (NULL);
3753 }
3754 
3755 /*
3756  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3757  * Notice that we don't bother validating the proper number of arguments or
3758  * their types in the tuple stack.  This isn't needed because all argument
3759  * interpretation is safe because of our load safety -- the worst that can
3760  * happen is that a bogus program can obtain bogus results.
3761  */
3762 static void
3763 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3764     dtrace_key_t *tupregs, int nargs,
3765     dtrace_mstate_t *mstate, dtrace_state_t *state)
3766 {
3767         volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3768         volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3769         dtrace_vstate_t *vstate = &state->dts_vstate;
3770 
3771         union {
3772                 mutex_impl_t mi;
3773                 uint64_t mx;
3774         } m;
3775 
3776         union {
3777                 krwlock_t ri;
3778                 uintptr_t rw;
3779         } r;
3780 
3781         switch (subr) {
3782         case DIF_SUBR_RAND:
3783                 regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3784                 break;
3785 
3786         case DIF_SUBR_MUTEX_OWNED:
3787                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3788                     mstate, vstate)) {
3789                         regs[rd] = NULL;
3790                         break;
3791                 }
3792 
3793                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3794                 if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3795                         regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3796                 else
3797                         regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3798                 break;
3799 
3800         case DIF_SUBR_MUTEX_OWNER:
3801                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3802                     mstate, vstate)) {
3803                         regs[rd] = NULL;
3804                         break;
3805                 }
3806 
3807                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3808                 if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3809                     MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3810                         regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3811                 else
3812                         regs[rd] = 0;
3813                 break;
3814 
3815         case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3816                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3817                     mstate, vstate)) {
3818                         regs[rd] = NULL;
3819                         break;
3820                 }
3821 
3822                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3823                 regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3824                 break;
3825 
3826         case DIF_SUBR_MUTEX_TYPE_SPIN:
3827                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3828                     mstate, vstate)) {
3829                         regs[rd] = NULL;
3830                         break;
3831                 }
3832 
3833                 m.mx = dtrace_load64(tupregs[0].dttk_value);
3834                 regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3835                 break;
3836 
3837         case DIF_SUBR_RW_READ_HELD: {
3838                 uintptr_t tmp;
3839 
3840                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3841                     mstate, vstate)) {
3842                         regs[rd] = NULL;
3843                         break;
3844                 }
3845 
3846                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3847                 regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3848                 break;
3849         }
3850 
3851         case DIF_SUBR_RW_WRITE_HELD:
3852                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3853                     mstate, vstate)) {
3854                         regs[rd] = NULL;
3855                         break;
3856                 }
3857 
3858                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3859                 regs[rd] = _RW_WRITE_HELD(&r.ri);
3860                 break;
3861 
3862         case DIF_SUBR_RW_ISWRITER:
3863                 if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3864                     mstate, vstate)) {
3865                         regs[rd] = NULL;
3866                         break;
3867                 }
3868 
3869                 r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3870                 regs[rd] = _RW_ISWRITER(&r.ri);
3871                 break;
3872 
3873         case DIF_SUBR_BCOPY: {
3874                 /*
3875                  * We need to be sure that the destination is in the scratch
3876                  * region -- no other region is allowed.
3877                  */
3878                 uintptr_t src = tupregs[0].dttk_value;
3879                 uintptr_t dest = tupregs[1].dttk_value;
3880                 size_t size = tupregs[2].dttk_value;
3881 
3882                 if (!dtrace_inscratch(dest, size, mstate)) {
3883                         *flags |= CPU_DTRACE_BADADDR;
3884                         *illval = regs[rd];
3885                         break;
3886                 }
3887 
3888                 if (!dtrace_canload(src, size, mstate, vstate)) {
3889                         regs[rd] = NULL;
3890                         break;
3891                 }
3892 
3893                 dtrace_bcopy((void *)src, (void *)dest, size);
3894                 break;
3895         }
3896 
3897         case DIF_SUBR_ALLOCA:
3898         case DIF_SUBR_COPYIN: {
3899                 uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3900                 uint64_t size =
3901                     tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3902                 size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3903 
3904                 /*
3905                  * This action doesn't require any credential checks since
3906                  * probes will not activate in user contexts to which the
3907                  * enabling user does not have permissions.
3908                  */
3909 
3910                 /*
3911                  * Rounding up the user allocation size could have overflowed
3912                  * a large, bogus allocation (like -1ULL) to 0.
3913                  */
3914                 if (scratch_size < size ||
3915                     !DTRACE_INSCRATCH(mstate, scratch_size)) {
3916                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3917                         regs[rd] = NULL;
3918                         break;
3919                 }
3920 
3921                 if (subr == DIF_SUBR_COPYIN) {
3922                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3923                         dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3924                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3925                 }
3926 
3927                 mstate->dtms_scratch_ptr += scratch_size;
3928                 regs[rd] = dest;
3929                 break;
3930         }
3931 
3932         case DIF_SUBR_COPYINTO: {
3933                 uint64_t size = tupregs[1].dttk_value;
3934                 uintptr_t dest = tupregs[2].dttk_value;
3935 
3936                 /*
3937                  * This action doesn't require any credential checks since
3938                  * probes will not activate in user contexts to which the
3939                  * enabling user does not have permissions.
3940                  */
3941                 if (!dtrace_inscratch(dest, size, mstate)) {
3942                         *flags |= CPU_DTRACE_BADADDR;
3943                         *illval = regs[rd];
3944                         break;
3945                 }
3946 
3947                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3948                 dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3949                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3950                 break;
3951         }
3952 
3953         case DIF_SUBR_COPYINSTR: {
3954                 uintptr_t dest = mstate->dtms_scratch_ptr;
3955                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3956 
3957                 if (nargs > 1 && tupregs[1].dttk_value < size)
3958                         size = tupregs[1].dttk_value + 1;
3959 
3960                 /*
3961                  * This action doesn't require any credential checks since
3962                  * probes will not activate in user contexts to which the
3963                  * enabling user does not have permissions.
3964                  */
3965                 if (!DTRACE_INSCRATCH(mstate, size)) {
3966                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3967                         regs[rd] = NULL;
3968                         break;
3969                 }
3970 
3971                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3972                 dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3973                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3974 
3975                 ((char *)dest)[size - 1] = '\0';
3976                 mstate->dtms_scratch_ptr += size;
3977                 regs[rd] = dest;
3978                 break;
3979         }
3980 
3981         case DIF_SUBR_MSGSIZE:
3982         case DIF_SUBR_MSGDSIZE: {
3983                 uintptr_t baddr = tupregs[0].dttk_value, daddr;
3984                 uintptr_t wptr, rptr;
3985                 size_t count = 0;
3986                 int cont = 0;
3987 
3988                 while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3989 
3990                         if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3991                             vstate)) {
3992                                 regs[rd] = NULL;
3993                                 break;
3994                         }
3995 
3996                         wptr = dtrace_loadptr(baddr +
3997                             offsetof(mblk_t, b_wptr));
3998 
3999                         rptr = dtrace_loadptr(baddr +
4000                             offsetof(mblk_t, b_rptr));
4001 
4002                         if (wptr < rptr) {
4003                                 *flags |= CPU_DTRACE_BADADDR;
4004                                 *illval = tupregs[0].dttk_value;
4005                                 break;
4006                         }
4007 
4008                         daddr = dtrace_loadptr(baddr +
4009                             offsetof(mblk_t, b_datap));
4010 
4011                         baddr = dtrace_loadptr(baddr +
4012                             offsetof(mblk_t, b_cont));
4013 
4014                         /*
4015                          * We want to prevent against denial-of-service here,
4016                          * so we're only going to search the list for
4017                          * dtrace_msgdsize_max mblks.
4018                          */
4019                         if (cont++ > dtrace_msgdsize_max) {
4020                                 *flags |= CPU_DTRACE_ILLOP;
4021                                 break;
4022                         }
4023 
4024                         if (subr == DIF_SUBR_MSGDSIZE) {
4025                                 if (dtrace_load8(daddr +
4026                                     offsetof(dblk_t, db_type)) != M_DATA)
4027                                         continue;
4028                         }
4029 
4030                         count += wptr - rptr;
4031                 }
4032 
4033                 if (!(*flags & CPU_DTRACE_FAULT))
4034                         regs[rd] = count;
4035 
4036                 break;
4037         }
4038 
4039         case DIF_SUBR_PROGENYOF: {
4040                 pid_t pid = tupregs[0].dttk_value;
4041                 proc_t *p;
4042                 int rval = 0;
4043 
4044                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4045 
4046                 for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4047                         if (p->p_pidp->pid_id == pid) {
4048                                 rval = 1;
4049                                 break;
4050                         }
4051                 }
4052 
4053                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4054 
4055                 regs[rd] = rval;
4056                 break;
4057         }
4058 
4059         case DIF_SUBR_SPECULATION:
4060                 regs[rd] = dtrace_speculation(state);
4061                 break;
4062 
4063         case DIF_SUBR_COPYOUT: {
4064                 uintptr_t kaddr = tupregs[0].dttk_value;
4065                 uintptr_t uaddr = tupregs[1].dttk_value;
4066                 uint64_t size = tupregs[2].dttk_value;
4067 
4068                 if (!dtrace_destructive_disallow &&
4069                     dtrace_priv_proc_control(state, mstate) &&
4070                     !dtrace_istoxic(kaddr, size)) {
4071                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4072                         dtrace_copyout(kaddr, uaddr, size, flags);
4073                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4074                 }
4075                 break;
4076         }
4077 
4078         case DIF_SUBR_COPYOUTSTR: {
4079                 uintptr_t kaddr = tupregs[0].dttk_value;
4080                 uintptr_t uaddr = tupregs[1].dttk_value;
4081                 uint64_t size = tupregs[2].dttk_value;
4082 
4083                 if (!dtrace_destructive_disallow &&
4084                     dtrace_priv_proc_control(state, mstate) &&
4085                     !dtrace_istoxic(kaddr, size)) {
4086                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4087                         dtrace_copyoutstr(kaddr, uaddr, size, flags);
4088                         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4089                 }
4090                 break;
4091         }
4092 
4093         case DIF_SUBR_STRLEN: {
4094                 size_t sz;
4095                 uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4096                 sz = dtrace_strlen((char *)addr,
4097                     state->dts_options[DTRACEOPT_STRSIZE]);
4098 
4099                 if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
4100                         regs[rd] = NULL;
4101                         break;
4102                 }
4103 
4104                 regs[rd] = sz;
4105 
4106                 break;
4107         }
4108 
4109         case DIF_SUBR_STRCHR:
4110         case DIF_SUBR_STRRCHR: {
4111                 /*
4112                  * We're going to iterate over the string looking for the
4113                  * specified character.  We will iterate until we have reached
4114                  * the string length or we have found the character.  If this
4115                  * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4116                  * of the specified character instead of the first.
4117                  */
4118                 uintptr_t saddr = tupregs[0].dttk_value;
4119                 uintptr_t addr = tupregs[0].dttk_value;
4120                 uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
4121                 char c, target = (char)tupregs[1].dttk_value;
4122 
4123                 for (regs[rd] = NULL; addr < limit; addr++) {
4124                         if ((c = dtrace_load8(addr)) == target) {
4125                                 regs[rd] = addr;
4126 
4127                                 if (subr == DIF_SUBR_STRCHR)
4128                                         break;
4129                         }
4130 
4131                         if (c == '\0')
4132                                 break;
4133                 }
4134 
4135                 if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
4136                         regs[rd] = NULL;
4137                         break;
4138                 }
4139 
4140                 break;
4141         }
4142 
4143         case DIF_SUBR_STRSTR:
4144         case DIF_SUBR_INDEX:
4145         case DIF_SUBR_RINDEX: {
4146                 /*
4147                  * We're going to iterate over the string looking for the
4148                  * specified string.  We will iterate until we have reached
4149                  * the string length or we have found the string.  (Yes, this
4150                  * is done in the most naive way possible -- but considering
4151                  * that the string we're searching for is likely to be
4152                  * relatively short, the complexity of Rabin-Karp or similar
4153                  * hardly seems merited.)
4154                  */
4155                 char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4156                 char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4157                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4158                 size_t len = dtrace_strlen(addr, size);
4159                 size_t sublen = dtrace_strlen(substr, size);
4160                 char *limit = addr + len, *orig = addr;
4161                 int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4162                 int inc = 1;
4163 
4164                 regs[rd] = notfound;
4165 
4166                 if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4167                         regs[rd] = NULL;
4168                         break;
4169                 }
4170 
4171                 if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4172                     vstate)) {
4173                         regs[rd] = NULL;
4174                         break;
4175                 }
4176 
4177                 /*
4178                  * strstr() and index()/rindex() have similar semantics if
4179                  * both strings are the empty string: strstr() returns a
4180                  * pointer to the (empty) string, and index() and rindex()
4181                  * both return index 0 (regardless of any position argument).
4182                  */
4183                 if (sublen == 0 && len == 0) {
4184                         if (subr == DIF_SUBR_STRSTR)
4185                                 regs[rd] = (uintptr_t)addr;
4186                         else
4187                                 regs[rd] = 0;
4188                         break;
4189                 }
4190 
4191                 if (subr != DIF_SUBR_STRSTR) {
4192                         if (subr == DIF_SUBR_RINDEX) {
4193                                 limit = orig - 1;
4194                                 addr += len;
4195                                 inc = -1;
4196                         }
4197 
4198                         /*
4199                          * Both index() and rindex() take an optional position
4200                          * argument that denotes the starting position.
4201                          */
4202                         if (nargs == 3) {
4203                                 int64_t pos = (int64_t)tupregs[2].dttk_value;
4204 
4205                                 /*
4206                                  * If the position argument to index() is
4207                                  * negative, Perl implicitly clamps it at
4208                                  * zero.  This semantic is a little surprising
4209                                  * given the special meaning of negative
4210                                  * positions to similar Perl functions like
4211                                  * substr(), but it appears to reflect a
4212                                  * notion that index() can start from a
4213                                  * negative index and increment its way up to
4214                                  * the string.  Given this notion, Perl's
4215                                  * rindex() is at least self-consistent in
4216                                  * that it implicitly clamps positions greater
4217                                  * than the string length to be the string
4218                                  * length.  Where Perl completely loses
4219                                  * coherence, however, is when the specified
4220                                  * substring is the empty string ("").  In
4221                                  * this case, even if the position is
4222                                  * negative, rindex() returns 0 -- and even if
4223                                  * the position is greater than the length,
4224                                  * index() returns the string length.  These
4225                                  * semantics violate the notion that index()
4226                                  * should never return a value less than the
4227                                  * specified position and that rindex() should
4228                                  * never return a value greater than the
4229                                  * specified position.  (One assumes that
4230                                  * these semantics are artifacts of Perl's
4231                                  * implementation and not the results of
4232                                  * deliberate design -- it beggars belief that
4233                                  * even Larry Wall could desire such oddness.)
4234                                  * While in the abstract one would wish for
4235                                  * consistent position semantics across
4236                                  * substr(), index() and rindex() -- or at the
4237                                  * very least self-consistent position
4238                                  * semantics for index() and rindex() -- we
4239                                  * instead opt to keep with the extant Perl
4240                                  * semantics, in all their broken glory.  (Do
4241                                  * we have more desire to maintain Perl's
4242                                  * semantics than Perl does?  Probably.)
4243                                  */
4244                                 if (subr == DIF_SUBR_RINDEX) {
4245                                         if (pos < 0) {
4246                                                 if (sublen == 0)
4247                                                         regs[rd] = 0;
4248                                                 break;
4249                                         }
4250 
4251                                         if (pos > len)
4252                                                 pos = len;
4253                                 } else {
4254                                         if (pos < 0)
4255                                                 pos = 0;
4256 
4257                                         if (pos >= len) {
4258                                                 if (sublen == 0)
4259                                                         regs[rd] = len;
4260                                                 break;
4261                                         }
4262                                 }
4263 
4264                                 addr = orig + pos;
4265                         }
4266                 }
4267 
4268                 for (regs[rd] = notfound; addr != limit; addr += inc) {
4269                         if (dtrace_strncmp(addr, substr, sublen) == 0) {
4270                                 if (subr != DIF_SUBR_STRSTR) {
4271                                         /*
4272                                          * As D index() and rindex() are
4273                                          * modeled on Perl (and not on awk),
4274                                          * we return a zero-based (and not a
4275                                          * one-based) index.  (For you Perl
4276                                          * weenies: no, we're not going to add
4277                                          * $[ -- and shouldn't you be at a con
4278                                          * or something?)
4279                                          */
4280                                         regs[rd] = (uintptr_t)(addr - orig);
4281                                         break;
4282                                 }
4283 
4284                                 ASSERT(subr == DIF_SUBR_STRSTR);
4285                                 regs[rd] = (uintptr_t)addr;
4286                                 break;
4287                         }
4288                 }
4289 
4290                 break;
4291         }
4292 
4293         case DIF_SUBR_STRTOK: {
4294                 uintptr_t addr = tupregs[0].dttk_value;
4295                 uintptr_t tokaddr = tupregs[1].dttk_value;
4296                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4297                 uintptr_t limit, toklimit = tokaddr + size;
4298                 uint8_t c, tokmap[32];   /* 256 / 8 */
4299                 char *dest = (char *)mstate->dtms_scratch_ptr;
4300                 int i;
4301 
4302                 /*
4303                  * Check both the token buffer and (later) the input buffer,
4304                  * since both could be non-scratch addresses.
4305                  */
4306                 if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
4307                         regs[rd] = NULL;
4308                         break;
4309                 }
4310 
4311                 if (!DTRACE_INSCRATCH(mstate, size)) {
4312                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4313                         regs[rd] = NULL;
4314                         break;
4315                 }
4316 
4317                 if (addr == NULL) {
4318                         /*
4319                          * If the address specified is NULL, we use our saved
4320                          * strtok pointer from the mstate.  Note that this
4321                          * means that the saved strtok pointer is _only_
4322                          * valid within multiple enablings of the same probe --
4323                          * it behaves like an implicit clause-local variable.
4324                          */
4325                         addr = mstate->dtms_strtok;
4326                 } else {
4327                         /*
4328                          * If the user-specified address is non-NULL we must
4329                          * access check it.  This is the only time we have
4330                          * a chance to do so, since this address may reside
4331                          * in the string table of this clause-- future calls
4332                          * (when we fetch addr from mstate->dtms_strtok)
4333                          * would fail this access check.
4334                          */
4335                         if (!dtrace_strcanload(addr, size, mstate, vstate)) {
4336                                 regs[rd] = NULL;
4337                                 break;
4338                         }
4339                 }
4340 
4341                 /*
4342                  * First, zero the token map, and then process the token
4343                  * string -- setting a bit in the map for every character
4344                  * found in the token string.
4345                  */
4346                 for (i = 0; i < sizeof (tokmap); i++)
4347                         tokmap[i] = 0;
4348 
4349                 for (; tokaddr < toklimit; tokaddr++) {
4350                         if ((c = dtrace_load8(tokaddr)) == '\0')
4351                                 break;
4352 
4353                         ASSERT((c >> 3) < sizeof (tokmap));
4354                         tokmap[c >> 3] |= (1 << (c & 0x7));
4355                 }
4356 
4357                 for (limit = addr + size; addr < limit; addr++) {
4358                         /*
4359                          * We're looking for a character that is _not_ contained
4360                          * in the token string.
4361                          */
4362                         if ((c = dtrace_load8(addr)) == '\0')
4363                                 break;
4364 
4365                         if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4366                                 break;
4367                 }
4368 
4369                 if (c == '\0') {
4370                         /*
4371                          * We reached the end of the string without finding
4372                          * any character that was not in the token string.
4373                          * We return NULL in this case, and we set the saved
4374                          * address to NULL as well.
4375                          */
4376                         regs[rd] = NULL;
4377                         mstate->dtms_strtok = NULL;
4378                         break;
4379                 }
4380 
4381                 /*
4382                  * From here on, we're copying into the destination string.
4383                  */
4384                 for (i = 0; addr < limit && i < size - 1; addr++) {
4385                         if ((c = dtrace_load8(addr)) == '\0')
4386                                 break;
4387 
4388                         if (tokmap[c >> 3] & (1 << (c & 0x7)))
4389                                 break;
4390 
4391                         ASSERT(i < size);
4392                         dest[i++] = c;
4393                 }
4394 
4395                 ASSERT(i < size);
4396                 dest[i] = '\0';
4397                 regs[rd] = (uintptr_t)dest;
4398                 mstate->dtms_scratch_ptr += size;
4399                 mstate->dtms_strtok = addr;
4400                 break;
4401         }
4402 
4403         case DIF_SUBR_SUBSTR: {
4404                 uintptr_t s = tupregs[0].dttk_value;
4405                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4406                 char *d = (char *)mstate->dtms_scratch_ptr;
4407                 int64_t index = (int64_t)tupregs[1].dttk_value;
4408                 int64_t remaining = (int64_t)tupregs[2].dttk_value;
4409                 size_t len = dtrace_strlen((char *)s, size);
4410                 int64_t i;
4411 
4412                 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4413                         regs[rd] = NULL;
4414                         break;
4415                 }
4416 
4417                 if (!DTRACE_INSCRATCH(mstate, size)) {
4418                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4419                         regs[rd] = NULL;
4420                         break;
4421                 }
4422 
4423                 if (nargs <= 2)
4424                         remaining = (int64_t)size;
4425 
4426                 if (index < 0) {
4427                         index += len;
4428 
4429                         if (index < 0 && index + remaining > 0) {
4430                                 remaining += index;
4431                                 index = 0;
4432                         }
4433                 }
4434 
4435                 if (index >= len || index < 0) {
4436                         remaining = 0;
4437                 } else if (remaining < 0) {
4438                         remaining += len - index;
4439                 } else if (index + remaining > size) {
4440                         remaining = size - index;
4441                 }
4442 
4443                 for (i = 0; i < remaining; i++) {
4444                         if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4445                                 break;
4446                 }
4447 
4448                 d[i] = '\0';
4449 
4450                 mstate->dtms_scratch_ptr += size;
4451                 regs[rd] = (uintptr_t)d;
4452                 break;
4453         }
4454 
4455         case DIF_SUBR_JSON: {
4456                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4457                 uintptr_t json = tupregs[0].dttk_value;
4458                 size_t jsonlen = dtrace_strlen((char *)json, size);
4459                 uintptr_t elem = tupregs[1].dttk_value;
4460                 size_t elemlen = dtrace_strlen((char *)elem, size);
4461 
4462                 char *dest = (char *)mstate->dtms_scratch_ptr;
4463                 char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
4464                 char *ee = elemlist;
4465                 int nelems = 1;
4466                 uintptr_t cur;
4467 
4468                 if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
4469                     !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
4470                         regs[rd] = NULL;
4471                         break;
4472                 }
4473 
4474                 if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
4475                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4476                         regs[rd] = NULL;
4477                         break;
4478                 }
4479 
4480                 /*
4481                  * Read the element selector and split it up into a packed list
4482                  * of strings.
4483                  */
4484                 for (cur = elem; cur < elem + elemlen; cur++) {
4485                         char cc = dtrace_load8(cur);
4486 
4487                         if (cur == elem && cc == '[')
4488                                 /* first element selector may be an array */
4489                                 continue;
4490 
4491                         if (cc == ']')
4492                                 continue;
4493 
4494                         if (cc == '.' || cc == '[') {
4495                                 nelems++;
4496                                 cc = '\0';
4497                         }
4498 
4499                         *ee++ = cc;
4500                 }
4501                 *ee++ = '\0';
4502 
4503                 if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
4504                     nelems, dest)) != NULL)
4505                         mstate->dtms_scratch_ptr += jsonlen + 1;
4506                 break;
4507         }
4508 
4509         case DIF_SUBR_TOUPPER:
4510         case DIF_SUBR_TOLOWER: {
4511                 uintptr_t s = tupregs[0].dttk_value;
4512                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4513                 char *dest = (char *)mstate->dtms_scratch_ptr, c;
4514                 size_t len = dtrace_strlen((char *)s, size);
4515                 char lower, upper, convert;
4516                 int64_t i;
4517 
4518                 if (subr == DIF_SUBR_TOUPPER) {
4519                         lower = 'a';
4520                         upper = 'z';
4521                         convert = 'A';
4522                 } else {
4523                         lower = 'A';
4524                         upper = 'Z';
4525                         convert = 'a';
4526                 }
4527 
4528                 if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4529                         regs[rd] = NULL;
4530                         break;
4531                 }
4532 
4533                 if (!DTRACE_INSCRATCH(mstate, size)) {
4534                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4535                         regs[rd] = NULL;
4536                         break;
4537                 }
4538 
4539                 for (i = 0; i < size - 1; i++) {
4540                         if ((c = dtrace_load8(s + i)) == '\0')
4541                                 break;
4542 
4543                         if (c >= lower && c <= upper)
4544                                 c = convert + (c - lower);
4545 
4546                         dest[i] = c;
4547                 }
4548 
4549                 ASSERT(i < size);
4550                 dest[i] = '\0';
4551                 regs[rd] = (uintptr_t)dest;
4552                 mstate->dtms_scratch_ptr += size;
4553                 break;
4554         }
4555 
4556 case DIF_SUBR_GETMAJOR:
4557 #ifdef _LP64
4558                 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4559 #else
4560                 regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4561 #endif
4562                 break;
4563 
4564         case DIF_SUBR_GETMINOR:
4565 #ifdef _LP64
4566                 regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4567 #else
4568                 regs[rd] = tupregs[0].dttk_value & MAXMIN;
4569 #endif
4570                 break;
4571 
4572         case DIF_SUBR_DDI_PATHNAME: {
4573                 /*
4574                  * This one is a galactic mess.  We are going to roughly
4575                  * emulate ddi_pathname(), but it's made more complicated
4576                  * by the fact that we (a) want to include the minor name and
4577                  * (b) must proceed iteratively instead of recursively.
4578                  */
4579                 uintptr_t dest = mstate->dtms_scratch_ptr;
4580                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4581                 char *start = (char *)dest, *end = start + size - 1;
4582                 uintptr_t daddr = tupregs[0].dttk_value;
4583                 int64_t minor = (int64_t)tupregs[1].dttk_value;
4584                 char *s;
4585                 int i, len, depth = 0;
4586 
4587                 /*
4588                  * Due to all the pointer jumping we do and context we must
4589                  * rely upon, we just mandate that the user must have kernel
4590                  * read privileges to use this routine.
4591                  */
4592                 if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4593                         *flags |= CPU_DTRACE_KPRIV;
4594                         *illval = daddr;
4595                         regs[rd] = NULL;
4596                 }
4597 
4598                 if (!DTRACE_INSCRATCH(mstate, size)) {
4599                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4600                         regs[rd] = NULL;
4601                         break;
4602                 }
4603 
4604                 *end = '\0';
4605 
4606                 /*
4607                  * We want to have a name for the minor.  In order to do this,
4608                  * we need to walk the minor list from the devinfo.  We want
4609                  * to be sure that we don't infinitely walk a circular list,
4610                  * so we check for circularity by sending a scout pointer
4611                  * ahead two elements for every element that we iterate over;
4612                  * if the list is circular, these will ultimately point to the
4613                  * same element.  You may recognize this little trick as the
4614                  * answer to a stupid interview question -- one that always
4615                  * seems to be asked by those who had to have it laboriously
4616                  * explained to them, and who can't even concisely describe
4617                  * the conditions under which one would be forced to resort to
4618                  * this technique.  Needless to say, those conditions are
4619                  * found here -- and probably only here.  Is this the only use
4620                  * of this infamous trick in shipping, production code?  If it
4621                  * isn't, it probably should be...
4622                  */
4623                 if (minor != -1) {
4624                         uintptr_t maddr = dtrace_loadptr(daddr +
4625                             offsetof(struct dev_info, devi_minor));
4626 
4627                         uintptr_t next = offsetof(struct ddi_minor_data, next);
4628                         uintptr_t name = offsetof(struct ddi_minor_data,
4629                             d_minor) + offsetof(struct ddi_minor, name);
4630                         uintptr_t dev = offsetof(struct ddi_minor_data,
4631                             d_minor) + offsetof(struct ddi_minor, dev);
4632                         uintptr_t scout;
4633 
4634                         if (maddr != NULL)
4635                                 scout = dtrace_loadptr(maddr + next);
4636 
4637                         while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4638                                 uint64_t m;
4639 #ifdef _LP64
4640                                 m = dtrace_load64(maddr + dev) & MAXMIN64;
4641 #else
4642                                 m = dtrace_load32(maddr + dev) & MAXMIN;
4643 #endif
4644                                 if (m != minor) {
4645                                         maddr = dtrace_loadptr(maddr + next);
4646 
4647                                         if (scout == NULL)
4648                                                 continue;
4649 
4650                                         scout = dtrace_loadptr(scout + next);
4651 
4652                                         if (scout == NULL)
4653                                                 continue;
4654 
4655                                         scout = dtrace_loadptr(scout + next);
4656 
4657                                         if (scout == NULL)
4658                                                 continue;
4659 
4660                                         if (scout == maddr) {
4661                                                 *flags |= CPU_DTRACE_ILLOP;
4662                                                 break;
4663                                         }
4664 
4665                                         continue;
4666                                 }
4667 
4668                                 /*
4669                                  * We have the minor data.  Now we need to
4670                                  * copy the minor's name into the end of the
4671                                  * pathname.
4672                                  */
4673                                 s = (char *)dtrace_loadptr(maddr + name);
4674                                 len = dtrace_strlen(s, size);
4675 
4676                                 if (*flags & CPU_DTRACE_FAULT)
4677                                         break;
4678 
4679                                 if (len != 0) {
4680                                         if ((end -= (len + 1)) < start)
4681                                                 break;
4682 
4683                                         *end = ':';
4684                                 }
4685 
4686                                 for (i = 1; i <= len; i++)
4687                                         end[i] = dtrace_load8((uintptr_t)s++);
4688                                 break;
4689                         }
4690                 }
4691 
4692                 while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4693                         ddi_node_state_t devi_state;
4694 
4695                         devi_state = dtrace_load32(daddr +
4696                             offsetof(struct dev_info, devi_node_state));
4697 
4698                         if (*flags & CPU_DTRACE_FAULT)
4699                                 break;
4700 
4701                         if (devi_state >= DS_INITIALIZED) {
4702                                 s = (char *)dtrace_loadptr(daddr +
4703                                     offsetof(struct dev_info, devi_addr));
4704                                 len = dtrace_strlen(s, size);
4705 
4706                                 if (*flags & CPU_DTRACE_FAULT)
4707                                         break;
4708 
4709                                 if (len != 0) {
4710                                         if ((end -= (len + 1)) < start)
4711                                                 break;
4712 
4713                                         *end = '@';
4714                                 }
4715 
4716                                 for (i = 1; i <= len; i++)
4717                                         end[i] = dtrace_load8((uintptr_t)s++);
4718                         }
4719 
4720                         /*
4721                          * Now for the node name...
4722                          */
4723                         s = (char *)dtrace_loadptr(daddr +
4724                             offsetof(struct dev_info, devi_node_name));
4725 
4726                         daddr = dtrace_loadptr(daddr +
4727                             offsetof(struct dev_info, devi_parent));
4728 
4729                         /*
4730                          * If our parent is NULL (that is, if we're the root
4731                          * node), we're going to use the special path
4732                          * "devices".
4733                          */
4734                         if (daddr == NULL)
4735                                 s = "devices";
4736 
4737                         len = dtrace_strlen(s, size);
4738                         if (*flags & CPU_DTRACE_FAULT)
4739                                 break;
4740 
4741                         if ((end -= (len + 1)) < start)
4742                                 break;
4743 
4744                         for (i = 1; i <= len; i++)
4745                                 end[i] = dtrace_load8((uintptr_t)s++);
4746                         *end = '/';
4747 
4748                         if (depth++ > dtrace_devdepth_max) {
4749                                 *flags |= CPU_DTRACE_ILLOP;
4750                                 break;
4751                         }
4752                 }
4753 
4754                 if (end < start)
4755                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4756 
4757                 if (daddr == NULL) {
4758                         regs[rd] = (uintptr_t)end;
4759                         mstate->dtms_scratch_ptr += size;
4760                 }
4761 
4762                 break;
4763         }
4764 
4765         case DIF_SUBR_STRJOIN: {
4766                 char *d = (char *)mstate->dtms_scratch_ptr;
4767                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4768                 uintptr_t s1 = tupregs[0].dttk_value;
4769                 uintptr_t s2 = tupregs[1].dttk_value;
4770                 int i = 0;
4771 
4772                 if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4773                     !dtrace_strcanload(s2, size, mstate, vstate)) {
4774                         regs[rd] = NULL;
4775                         break;
4776                 }
4777 
4778                 if (!DTRACE_INSCRATCH(mstate, size)) {
4779                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4780                         regs[rd] = NULL;
4781                         break;
4782                 }
4783 
4784                 for (;;) {
4785                         if (i >= size) {
4786                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4787                                 regs[rd] = NULL;
4788                                 break;
4789                         }
4790 
4791                         if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4792                                 i--;
4793                                 break;
4794                         }
4795                 }
4796 
4797                 for (;;) {
4798                         if (i >= size) {
4799                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4800                                 regs[rd] = NULL;
4801                                 break;
4802                         }
4803 
4804                         if ((d[i++] = dtrace_load8(s2++)) == '\0')
4805                                 break;
4806                 }
4807 
4808                 if (i < size) {
4809                         mstate->dtms_scratch_ptr += i;
4810                         regs[rd] = (uintptr_t)d;
4811                 }
4812 
4813                 break;
4814         }
4815 
4816         case DIF_SUBR_STRTOLL: {
4817                 uintptr_t s = tupregs[0].dttk_value;
4818                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4819                 int base = 10;
4820 
4821                 if (nargs > 1) {
4822                         if ((base = tupregs[1].dttk_value) <= 1 ||
4823                             base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4824                                 *flags |= CPU_DTRACE_ILLOP;
4825                                 break;
4826                         }
4827                 }
4828 
4829                 if (!dtrace_strcanload(s, size, mstate, vstate)) {
4830                         regs[rd] = INT64_MIN;
4831                         break;
4832                 }
4833 
4834                 regs[rd] = dtrace_strtoll((char *)s, base, size);
4835                 break;
4836         }
4837 
4838         case DIF_SUBR_LLTOSTR: {
4839                 int64_t i = (int64_t)tupregs[0].dttk_value;
4840                 uint64_t val, digit;
4841                 uint64_t size = 65;     /* enough room for 2^64 in binary */
4842                 char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4843                 int base = 10;
4844 
4845                 if (nargs > 1) {
4846                         if ((base = tupregs[1].dttk_value) <= 1 ||
4847                             base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4848                                 *flags |= CPU_DTRACE_ILLOP;
4849                                 break;
4850                         }
4851                 }
4852 
4853                 val = (base == 10 && i < 0) ? i * -1 : i;
4854 
4855                 if (!DTRACE_INSCRATCH(mstate, size)) {
4856                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4857                         regs[rd] = NULL;
4858                         break;
4859                 }
4860 
4861                 for (*end-- = '\0'; val; val /= base) {
4862                         if ((digit = val % base) <= '9' - '0') {
4863                                 *end-- = '0' + digit;
4864                         } else {
4865                                 *end-- = 'a' + (digit - ('9' - '0') - 1);
4866                         }
4867                 }
4868 
4869                 if (i == 0 && base == 16)
4870                         *end-- = '0';
4871 
4872                 if (base == 16)
4873                         *end-- = 'x';
4874 
4875                 if (i == 0 || base == 8 || base == 16)
4876                         *end-- = '0';
4877 
4878                 if (i < 0 && base == 10)
4879                         *end-- = '-';
4880 
4881                 regs[rd] = (uintptr_t)end + 1;
4882                 mstate->dtms_scratch_ptr += size;
4883                 break;
4884         }
4885 
4886         case DIF_SUBR_HTONS:
4887         case DIF_SUBR_NTOHS:
4888 #ifdef _BIG_ENDIAN
4889                 regs[rd] = (uint16_t)tupregs[0].dttk_value;
4890 #else
4891                 regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4892 #endif
4893                 break;
4894 
4895 
4896         case DIF_SUBR_HTONL:
4897         case DIF_SUBR_NTOHL:
4898 #ifdef _BIG_ENDIAN
4899                 regs[rd] = (uint32_t)tupregs[0].dttk_value;
4900 #else
4901                 regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4902 #endif
4903                 break;
4904 
4905 
4906         case DIF_SUBR_HTONLL:
4907         case DIF_SUBR_NTOHLL:
4908 #ifdef _BIG_ENDIAN
4909                 regs[rd] = (uint64_t)tupregs[0].dttk_value;
4910 #else
4911                 regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4912 #endif
4913                 break;
4914 
4915 
4916         case DIF_SUBR_DIRNAME:
4917         case DIF_SUBR_BASENAME: {
4918                 char *dest = (char *)mstate->dtms_scratch_ptr;
4919                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4920                 uintptr_t src = tupregs[0].dttk_value;
4921                 int i, j, len = dtrace_strlen((char *)src, size);
4922                 int lastbase = -1, firstbase = -1, lastdir = -1;
4923                 int start, end;
4924 
4925                 if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4926                         regs[rd] = NULL;
4927                         break;
4928                 }
4929 
4930                 if (!DTRACE_INSCRATCH(mstate, size)) {
4931                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4932                         regs[rd] = NULL;
4933                         break;
4934                 }
4935 
4936                 /*
4937                  * The basename and dirname for a zero-length string is
4938                  * defined to be "."
4939                  */
4940                 if (len == 0) {
4941                         len = 1;
4942                         src = (uintptr_t)".";
4943                 }
4944 
4945                 /*
4946                  * Start from the back of the string, moving back toward the
4947                  * front until we see a character that isn't a slash.  That
4948                  * character is the last character in the basename.
4949                  */
4950                 for (i = len - 1; i >= 0; i--) {
4951                         if (dtrace_load8(src + i) != '/')
4952                                 break;
4953                 }
4954 
4955                 if (i >= 0)
4956                         lastbase = i;
4957 
4958                 /*
4959                  * Starting from the last character in the basename, move
4960                  * towards the front until we find a slash.  The character
4961                  * that we processed immediately before that is the first
4962                  * character in the basename.
4963                  */
4964                 for (; i >= 0; i--) {
4965                         if (dtrace_load8(src + i) == '/')
4966                                 break;
4967                 }
4968 
4969                 if (i >= 0)
4970                         firstbase = i + 1;
4971 
4972                 /*
4973                  * Now keep going until we find a non-slash character.  That
4974                  * character is the last character in the dirname.
4975                  */
4976                 for (; i >= 0; i--) {
4977                         if (dtrace_load8(src + i) != '/')
4978                                 break;
4979                 }
4980 
4981                 if (i >= 0)
4982                         lastdir = i;
4983 
4984                 ASSERT(!(lastbase == -1 && firstbase != -1));
4985                 ASSERT(!(firstbase == -1 && lastdir != -1));
4986 
4987                 if (lastbase == -1) {
4988                         /*
4989                          * We didn't find a non-slash character.  We know that
4990                          * the length is non-zero, so the whole string must be
4991                          * slashes.  In either the dirname or the basename
4992                          * case, we return '/'.
4993                          */
4994                         ASSERT(firstbase == -1);
4995                         firstbase = lastbase = lastdir = 0;
4996                 }
4997 
4998                 if (firstbase == -1) {
4999                         /*
5000                          * The entire string consists only of a basename
5001                          * component.  If we're looking for dirname, we need
5002                          * to change our string to be just "."; if we're
5003                          * looking for a basename, we'll just set the first
5004                          * character of the basename to be 0.
5005                          */
5006                         if (subr == DIF_SUBR_DIRNAME) {
5007                                 ASSERT(lastdir == -1);
5008                                 src = (uintptr_t)".";
5009                                 lastdir = 0;
5010                         } else {
5011                                 firstbase = 0;
5012                         }
5013                 }
5014 
5015                 if (subr == DIF_SUBR_DIRNAME) {
5016                         if (lastdir == -1) {
5017                                 /*
5018                                  * We know that we have a slash in the name --
5019                                  * or lastdir would be set to 0, above.  And
5020                                  * because lastdir is -1, we know that this
5021                                  * slash must be the first character.  (That
5022                                  * is, the full string must be of the form
5023                                  * "/basename".)  In this case, the last
5024                                  * character of the directory name is 0.
5025                                  */
5026                                 lastdir = 0;
5027                         }
5028 
5029                         start = 0;
5030                         end = lastdir;
5031                 } else {
5032                         ASSERT(subr == DIF_SUBR_BASENAME);
5033                         ASSERT(firstbase != -1 && lastbase != -1);
5034                         start = firstbase;
5035                         end = lastbase;
5036                 }
5037 
5038                 for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5039                         dest[j] = dtrace_load8(src + i);
5040 
5041                 dest[j] = '\0';
5042                 regs[rd] = (uintptr_t)dest;
5043                 mstate->dtms_scratch_ptr += size;
5044                 break;
5045         }
5046 
5047         case DIF_SUBR_GETF: {
5048                 uintptr_t fd = tupregs[0].dttk_value;
5049                 uf_info_t *finfo = &curthread->t_procp->p_user.u_finfo;
5050                 file_t *fp;
5051 
5052                 if (!dtrace_priv_proc(state, mstate)) {
5053                         regs[rd] = NULL;
5054                         break;
5055                 }
5056 
5057                 /*
5058                  * This is safe because fi_nfiles only increases, and the
5059                  * fi_list array is not freed when the array size doubles.
5060                  * (See the comment in flist_grow() for details on the
5061                  * management of the u_finfo structure.)
5062                  */
5063                 fp = fd < finfo->fi_nfiles ? finfo->fi_list[fd].uf_file : NULL;
5064 
5065                 mstate->dtms_getf = fp;
5066                 regs[rd] = (uintptr_t)fp;
5067                 break;
5068         }
5069 
5070         case DIF_SUBR_CLEANPATH: {
5071                 char *dest = (char *)mstate->dtms_scratch_ptr, c;
5072                 uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5073                 uintptr_t src = tupregs[0].dttk_value;
5074                 int i = 0, j = 0;
5075                 zone_t *z;
5076 
5077                 if (!dtrace_strcanload(src, size, mstate, vstate)) {
5078                         regs[rd] = NULL;
5079                         break;
5080                 }
5081 
5082                 if (!DTRACE_INSCRATCH(mstate, size)) {
5083                         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5084                         regs[rd] = NULL;
5085                         break;
5086                 }
5087 
5088                 /*
5089                  * Move forward, loading each character.
5090                  */
5091                 do {
5092                         c = dtrace_load8(src + i++);
5093 next:
5094                         if (j + 5 >= size)   /* 5 = strlen("/..c\0") */
5095                                 break;
5096 
5097                         if (c != '/') {
5098                                 dest[j++] = c;
5099                                 continue;
5100                         }
5101 
5102                         c = dtrace_load8(src + i++);
5103 
5104                         if (c == '/') {
5105                                 /*
5106                                  * We have two slashes -- we can just advance
5107                                  * to the next character.
5108                                  */
5109                                 goto next;
5110                         }
5111 
5112                         if (c != '.') {
5113                                 /*
5114                                  * This is not "." and it's not ".." -- we can
5115                                  * just store the "/" and this character and
5116                                  * drive on.
5117                                  */
5118                                 dest[j++] = '/';
5119                                 dest[j++] = c;
5120                                 continue;
5121                         }
5122 
5123                         c = dtrace_load8(src + i++);
5124 
5125                         if (c == '/') {
5126                                 /*
5127                                  * This is a "/./" component.  We're not going
5128                                  * to store anything in the destination buffer;
5129                                  * we're just going to go to the next component.
5130                                  */
5131                                 goto next;
5132                         }
5133 
5134                         if (c != '.') {
5135                                 /*
5136                                  * This is not ".." -- we can just store the
5137                                  * "/." and this character and continue
5138                                  * processing.
5139                                  */
5140                                 dest[j++] = '/';
5141                                 dest[j++] = '.';
5142                                 dest[j++] = c;
5143                                 continue;
5144                         }
5145 
5146                         c = dtrace_load8(src + i++);
5147 
5148                         if (c != '/' && c != '\0') {
5149                                 /*
5150                                  * This is not ".." -- it's "..[mumble]".
5151                                  * We'll store the "/.." and this character
5152                                  * and continue processing.
5153                                  */
5154                                 dest[j++] = '/';
5155                                 dest[j++] = '.';
5156                                 dest[j++] = '.';
5157                                 dest[j++] = c;
5158                                 continue;
5159                         }
5160 
5161                         /*
5162                          * This is "/../" or "/..\0".  We need to back up
5163                          * our destination pointer until we find a "/".
5164                          */
5165                         i--;
5166                         while (j != 0 && dest[--j] != '/')
5167                                 continue;
5168 
5169                         if (c == '\0')
5170                                 dest[++j] = '/';
5171                 } while (c != '\0');
5172 
5173                 dest[j] = '\0';
5174 
5175                 if (mstate->dtms_getf != NULL &&
5176                     !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5177                     (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5178                         /*
5179                          * If we've done a getf() as a part of this ECB and we
5180                          * don't have kernel access (and we're not in the global
5181                          * zone), check if the path we cleaned up begins with
5182                          * the zone's root path, and trim it off if so.  Note
5183                          * that this is an output cleanliness issue, not a
5184                          * security issue: knowing one's zone root path does
5185                          * not enable privilege escalation.
5186                          */
5187                         if (strstr(dest, z->zone_rootpath) == dest)
5188                                 dest += strlen(z->zone_rootpath) - 1;
5189                 }
5190 
5191                 regs[rd] = (uintptr_t)dest;
5192                 mstate->dtms_scratch_ptr += size;
5193                 break;
5194         }
5195 
5196         case DIF_SUBR_INET_NTOA:
5197         case DIF_SUBR_INET_NTOA6:
5198         case DIF_SUBR_INET_NTOP: {
5199                 size_t size;
5200                 int af, argi, i;
5201                 char *base, *end;
5202 
5203                 if (subr == DIF_SUBR_INET_NTOP) {
5204                         af = (int)tupregs[0].dttk_value;
5205                         argi = 1;
5206                 } else {
5207                         af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5208                         argi = 0;
5209                 }
5210 
5211                 if (af == AF_INET) {
5212                         ipaddr_t ip4;
5213                         uint8_t *ptr8, val;
5214 
5215                         /*
5216                          * Safely load the IPv4 address.
5217                          */
5218                         ip4 = dtrace_load32(tupregs[argi].dttk_value);
5219 
5220                         /*
5221                          * Check an IPv4 string will fit in scratch.
5222                          */
5223                         size = INET_ADDRSTRLEN;
5224                         if (!DTRACE_INSCRATCH(mstate, size)) {
5225                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5226                                 regs[rd] = NULL;
5227                                 break;
5228                         }
5229                         base = (char *)mstate->dtms_scratch_ptr;
5230                         end = (char *)mstate->dtms_scratch_ptr + size - 1;
5231 
5232                         /*
5233                          * Stringify as a dotted decimal quad.
5234                          */
5235                         *end-- = '\0';
5236                         ptr8 = (uint8_t *)&ip4;
5237                         for (i = 3; i >= 0; i--) {
5238                                 val = ptr8[i];
5239 
5240                                 if (val == 0) {
5241                                         *end-- = '0';
5242                                 } else {
5243                                         for (; val; val /= 10) {
5244                                                 *end-- = '0' + (val % 10);
5245                                         }
5246                                 }
5247 
5248                                 if (i > 0)
5249                                         *end-- = '.';
5250                         }
5251                         ASSERT(end + 1 >= base);
5252 
5253                 } else if (af == AF_INET6) {
5254                         struct in6_addr ip6;
5255                         int firstzero, tryzero, numzero, v6end;
5256                         uint16_t val;
5257                         const char digits[] = "0123456789abcdef";
5258 
5259                         /*
5260                          * Stringify using RFC 1884 convention 2 - 16 bit
5261                          * hexadecimal values with a zero-run compression.
5262                          * Lower case hexadecimal digits are used.
5263                          *      eg, fe80::214:4fff:fe0b:76c8.
5264                          * The IPv4 embedded form is returned for inet_ntop,
5265                          * just the IPv4 string is returned for inet_ntoa6.
5266                          */
5267 
5268                         /*
5269                          * Safely load the IPv6 address.
5270                          */
5271                         dtrace_bcopy(
5272                             (void *)(uintptr_t)tupregs[argi].dttk_value,
5273                             (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5274 
5275                         /*
5276                          * Check an IPv6 string will fit in scratch.
5277                          */
5278                         size = INET6_ADDRSTRLEN;
5279                         if (!DTRACE_INSCRATCH(mstate, size)) {
5280                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5281                                 regs[rd] = NULL;
5282                                 break;
5283                         }
5284                         base = (char *)mstate->dtms_scratch_ptr;
5285                         end = (char *)mstate->dtms_scratch_ptr + size - 1;
5286                         *end-- = '\0';
5287 
5288                         /*
5289                          * Find the longest run of 16 bit zero values
5290                          * for the single allowed zero compression - "::".
5291                          */
5292                         firstzero = -1;
5293                         tryzero = -1;
5294                         numzero = 1;
5295                         for (i = 0; i < sizeof (struct in6_addr); i++) {
5296                                 if (ip6._S6_un._S6_u8[i] == 0 &&
5297                                     tryzero == -1 && i % 2 == 0) {
5298                                         tryzero = i;
5299                                         continue;
5300                                 }
5301 
5302                                 if (tryzero != -1 &&
5303                                     (ip6._S6_un._S6_u8[i] != 0 ||
5304                                     i == sizeof (struct in6_addr) - 1)) {
5305 
5306                                         if (i - tryzero <= numzero) {
5307                                                 tryzero = -1;
5308                                                 continue;
5309                                         }
5310 
5311                                         firstzero = tryzero;
5312                                         numzero = i - i % 2 - tryzero;
5313                                         tryzero = -1;
5314 
5315                                         if (ip6._S6_un._S6_u8[i] == 0 &&
5316                                             i == sizeof (struct in6_addr) - 1)
5317                                                 numzero += 2;
5318                                 }
5319                         }
5320                         ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5321 
5322                         /*
5323                          * Check for an IPv4 embedded address.
5324                          */
5325                         v6end = sizeof (struct in6_addr) - 2;
5326                         if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5327                             IN6_IS_ADDR_V4COMPAT(&ip6)) {
5328                                 for (i = sizeof (struct in6_addr) - 1;
5329                                     i >= DTRACE_V4MAPPED_OFFSET; i--) {
5330                                         ASSERT(end >= base);
5331 
5332                                         val = ip6._S6_un._S6_u8[i];
5333 
5334                                         if (val == 0) {
5335                                                 *end-- = '0';
5336                                         } else {
5337                                                 for (; val; val /= 10) {
5338                                                         *end-- = '0' + val % 10;
5339                                                 }
5340                                         }
5341 
5342                                         if (i > DTRACE_V4MAPPED_OFFSET)
5343                                                 *end-- = '.';
5344                                 }
5345 
5346                                 if (subr == DIF_SUBR_INET_NTOA6)
5347                                         goto inetout;
5348 
5349                                 /*
5350                                  * Set v6end to skip the IPv4 address that
5351                                  * we have already stringified.
5352                                  */
5353                                 v6end = 10;
5354                         }
5355 
5356                         /*
5357                          * Build the IPv6 string by working through the
5358                          * address in reverse.
5359                          */
5360                         for (i = v6end; i >= 0; i -= 2) {
5361                                 ASSERT(end >= base);
5362 
5363                                 if (i == firstzero + numzero - 2) {
5364                                         *end-- = ':';
5365                                         *end-- = ':';
5366                                         i -= numzero - 2;
5367                                         continue;
5368                                 }
5369 
5370                                 if (i < 14 && i != firstzero - 2)
5371                                         *end-- = ':';
5372 
5373                                 val = (ip6._S6_un._S6_u8[i] << 8) +
5374                                     ip6._S6_un._S6_u8[i + 1];
5375 
5376                                 if (val == 0) {
5377                                         *end-- = '0';
5378                                 } else {
5379                                         for (; val; val /= 16) {
5380                                                 *end-- = digits[val % 16];
5381                                         }
5382                                 }
5383                         }
5384                         ASSERT(end + 1 >= base);
5385 
5386                 } else {
5387                         /*
5388                          * The user didn't use AH_INET or AH_INET6.
5389                          */
5390                         DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5391                         regs[rd] = NULL;
5392                         break;
5393                 }
5394 
5395 inetout:        regs[rd] = (uintptr_t)end + 1;
5396                 mstate->dtms_scratch_ptr += size;
5397                 break;
5398         }
5399 
5400         }
5401 }
5402 
5403 /*
5404  * Emulate the execution of DTrace IR instructions specified by the given
5405  * DIF object.  This function is deliberately void of assertions as all of
5406  * the necessary checks are handled by a call to dtrace_difo_validate().
5407  */
5408 static uint64_t
5409 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5410     dtrace_vstate_t *vstate, dtrace_state_t *state)
5411 {
5412         const dif_instr_t *text = difo->dtdo_buf;
5413         const uint_t textlen = difo->dtdo_len;
5414         const char *strtab = difo->dtdo_strtab;
5415         const uint64_t *inttab = difo->dtdo_inttab;
5416 
5417         uint64_t rval = 0;
5418         dtrace_statvar_t *svar;
5419         dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5420         dtrace_difv_t *v;
5421         volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5422         volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
5423 
5424         dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5425         uint64_t regs[DIF_DIR_NREGS];
5426         uint64_t *tmp;
5427 
5428         uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5429         int64_t cc_r;
5430         uint_t pc = 0, id, opc;
5431         uint8_t ttop = 0;
5432         dif_instr_t instr;
5433         uint_t r1, r2, rd;
5434 
5435         /*
5436          * We stash the current DIF object into the machine state: we need it
5437          * for subsequent access checking.
5438          */
5439         mstate->dtms_difo = difo;
5440 
5441         regs[DIF_REG_R0] = 0;           /* %r0 is fixed at zero */
5442 
5443         while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5444                 opc = pc;
5445 
5446                 instr = text[pc++];
5447                 r1 = DIF_INSTR_R1(instr);
5448                 r2 = DIF_INSTR_R2(instr);
5449                 rd = DIF_INSTR_RD(instr);
5450 
5451                 switch (DIF_INSTR_OP(instr)) {
5452                 case DIF_OP_OR:
5453                         regs[rd] = regs[r1] | regs[r2];
5454                         break;
5455                 case DIF_OP_XOR:
5456                         regs[rd] = regs[r1] ^ regs[r2];
5457                         break;
5458                 case DIF_OP_AND:
5459                         regs[rd] = regs[r1] & regs[r2];
5460                         break;
5461                 case DIF_OP_SLL:
5462                         regs[rd] = regs[r1] << regs[r2];
5463                         break;
5464                 case DIF_OP_SRL:
5465                         regs[rd] = regs[r1] >> regs[r2];
5466                         break;
5467                 case DIF_OP_SUB:
5468                         regs[rd] = regs[r1] - regs[r2];
5469                         break;
5470                 case DIF_OP_ADD:
5471                         regs[rd] = regs[r1] + regs[r2];
5472                         break;
5473                 case DIF_OP_MUL:
5474                         regs[rd] = regs[r1] * regs[r2];
5475                         break;
5476                 case DIF_OP_SDIV:
5477                         if (regs[r2] == 0) {
5478                                 regs[rd] = 0;
5479                                 *flags |= CPU_DTRACE_DIVZERO;
5480                         } else {
5481                                 regs[rd] = (int64_t)regs[r1] /
5482                                     (int64_t)regs[r2];
5483                         }
5484                         break;
5485 
5486                 case DIF_OP_UDIV:
5487                         if (regs[r2] == 0) {
5488                                 regs[rd] = 0;
5489                                 *flags |= CPU_DTRACE_DIVZERO;
5490                         } else {
5491                                 regs[rd] = regs[r1] / regs[r2];
5492                         }
5493                         break;
5494 
5495                 case DIF_OP_SREM:
5496                         if (regs[r2] == 0) {
5497                                 regs[rd] = 0;
5498                                 *flags |= CPU_DTRACE_DIVZERO;
5499                         } else {
5500                                 regs[rd] = (int64_t)regs[r1] %
5501                                     (int64_t)regs[r2];
5502                         }
5503                         break;
5504 
5505                 case DIF_OP_UREM:
5506                         if (regs[r2] == 0) {
5507                                 regs[rd] = 0;
5508                                 *flags |= CPU_DTRACE_DIVZERO;
5509                         } else {
5510                                 regs[rd] = regs[r1] % regs[r2];
5511                         }
5512                         break;
5513 
5514                 case DIF_OP_NOT:
5515                         regs[rd] = ~regs[r1];
5516                         break;
5517                 case DIF_OP_MOV:
5518                         regs[rd] = regs[r1];
5519                         break;
5520                 case DIF_OP_CMP:
5521                         cc_r = regs[r1] - regs[r2];
5522                         cc_n = cc_r < 0;
5523                         cc_z = cc_r == 0;
5524                         cc_v = 0;
5525                         cc_c = regs[r1] < regs[r2];
5526                         break;
5527                 case DIF_OP_TST:
5528                         cc_n = cc_v = cc_c = 0;
5529                         cc_z = regs[r1] == 0;
5530                         break;
5531                 case DIF_OP_BA:
5532                         pc = DIF_INSTR_LABEL(instr);
5533                         break;
5534                 case DIF_OP_BE:
5535                         if (cc_z)
5536                                 pc = DIF_INSTR_LABEL(instr);
5537                         break;
5538                 case DIF_OP_BNE:
5539                         if (cc_z == 0)
5540                                 pc = DIF_INSTR_LABEL(instr);
5541                         break;
5542                 case DIF_OP_BG:
5543                         if ((cc_z | (cc_n ^ cc_v)) == 0)
5544                                 pc = DIF_INSTR_LABEL(instr);
5545                         break;
5546                 case DIF_OP_BGU:
5547                         if ((cc_c | cc_z) == 0)
5548                                 pc = DIF_INSTR_LABEL(instr);
5549                         break;
5550                 case DIF_OP_BGE:
5551                         if ((cc_n ^ cc_v) == 0)
5552                                 pc = DIF_INSTR_LABEL(instr);
5553                         break;
5554                 case DIF_OP_BGEU:
5555                         if (cc_c == 0)
5556                                 pc = DIF_INSTR_LABEL(instr);
5557                         break;
5558                 case DIF_OP_BL:
5559                         if (cc_n ^ cc_v)
5560                                 pc = DIF_INSTR_LABEL(instr);
5561                         break;
5562                 case DIF_OP_BLU:
5563                         if (cc_c)
5564                                 pc = DIF_INSTR_LABEL(instr);
5565                         break;
5566                 case DIF_OP_BLE:
5567                         if (cc_z | (cc_n ^ cc_v))
5568                                 pc = DIF_INSTR_LABEL(instr);
5569                         break;
5570                 case DIF_OP_BLEU:
5571                         if (cc_c | cc_z)
5572                                 pc = DIF_INSTR_LABEL(instr);
5573                         break;
5574                 case DIF_OP_RLDSB:
5575                         if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5576                                 break;
5577                         /*FALLTHROUGH*/
5578                 case DIF_OP_LDSB:
5579                         regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5580                         break;
5581                 case DIF_OP_RLDSH:
5582                         if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5583                                 break;
5584                         /*FALLTHROUGH*/
5585                 case DIF_OP_LDSH:
5586                         regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5587                         break;
5588                 case DIF_OP_RLDSW:
5589                         if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5590                                 break;
5591                         /*FALLTHROUGH*/
5592                 case DIF_OP_LDSW:
5593                         regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5594                         break;
5595                 case DIF_OP_RLDUB:
5596                         if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5597                                 break;
5598                         /*FALLTHROUGH*/
5599                 case DIF_OP_LDUB:
5600                         regs[rd] = dtrace_load8(regs[r1]);
5601                         break;
5602                 case DIF_OP_RLDUH:
5603                         if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5604                                 break;
5605                         /*FALLTHROUGH*/
5606                 case DIF_OP_LDUH:
5607                         regs[rd] = dtrace_load16(regs[r1]);
5608                         break;
5609                 case DIF_OP_RLDUW:
5610                         if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5611                                 break;
5612                         /*FALLTHROUGH*/
5613                 case DIF_OP_LDUW:
5614                         regs[rd] = dtrace_load32(regs[r1]);
5615                         break;
5616                 case DIF_OP_RLDX:
5617                         if (!dtrace_canload(regs[r1], 8, mstate, vstate))
5618                                 break;
5619                         /*FALLTHROUGH*/
5620                 case DIF_OP_LDX:
5621                         regs[rd] = dtrace_load64(regs[r1]);
5622                         break;
5623                 case DIF_OP_ULDSB:
5624                         regs[rd] = (int8_t)
5625                             dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5626                         break;
5627                 case DIF_OP_ULDSH:
5628                         regs[rd] = (int16_t)
5629                             dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5630                         break;
5631                 case DIF_OP_ULDSW:
5632                         regs[rd] = (int32_t)
5633                             dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5634                         break;
5635                 case DIF_OP_ULDUB:
5636                         regs[rd] =
5637                             dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5638                         break;
5639                 case DIF_OP_ULDUH:
5640                         regs[rd] =
5641                             dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5642                         break;
5643                 case DIF_OP_ULDUW:
5644                         regs[rd] =
5645                             dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5646                         break;
5647                 case DIF_OP_ULDX:
5648                         regs[rd] =
5649                             dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5650                         break;
5651                 case DIF_OP_RET:
5652                         rval = regs[rd];
5653                         pc = textlen;
5654                         break;
5655                 case DIF_OP_NOP:
5656                         break;
5657                 case DIF_OP_SETX:
5658                         regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5659                         break;
5660                 case DIF_OP_SETS:
5661                         regs[rd] = (uint64_t)(uintptr_t)
5662                             (strtab + DIF_INSTR_STRING(instr));
5663                         break;
5664                 case DIF_OP_SCMP: {
5665                         size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5666                         uintptr_t s1 = regs[r1];
5667                         uintptr_t s2 = regs[r2];
5668 
5669                         if (s1 != NULL &&
5670                             !dtrace_strcanload(s1, sz, mstate, vstate))
5671                                 break;
5672                         if (s2 != NULL &&
5673                             !dtrace_strcanload(s2, sz, mstate, vstate))
5674                                 break;
5675 
5676                         cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5677 
5678                         cc_n = cc_r < 0;
5679                         cc_z = cc_r == 0;
5680                         cc_v = cc_c = 0;
5681                         break;
5682                 }
5683                 case DIF_OP_LDGA:
5684                         regs[rd] = dtrace_dif_variable(mstate, state,
5685                             r1, regs[r2]);
5686                         break;
5687                 case DIF_OP_LDGS:
5688                         id = DIF_INSTR_VAR(instr);
5689 
5690                         if (id >= DIF_VAR_OTHER_UBASE) {
5691                                 uintptr_t a;
5692 
5693                                 id -= DIF_VAR_OTHER_UBASE;
5694                                 svar = vstate->dtvs_globals[id];
5695                                 ASSERT(svar != NULL);
5696                                 v = &svar->dtsv_var;
5697 
5698                                 if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5699                                         regs[rd] = svar->dtsv_data;
5700                                         break;
5701                                 }
5702 
5703                                 a = (uintptr_t)svar->dtsv_data;
5704 
5705                                 if (*(uint8_t *)a == UINT8_MAX) {
5706                                         /*
5707                                          * If the 0th byte is set to UINT8_MAX
5708                                          * then this is to be treated as a
5709                                          * reference to a NULL variable.
5710                                          */
5711                                         regs[rd] = NULL;
5712                                 } else {
5713                                         regs[rd] = a + sizeof (uint64_t);
5714                                 }
5715 
5716                                 break;
5717                         }
5718 
5719                         regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5720                         break;
5721 
5722                 case DIF_OP_STGS:
5723                         id = DIF_INSTR_VAR(instr);
5724 
5725                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5726                         id -= DIF_VAR_OTHER_UBASE;
5727 
5728                         svar = vstate->dtvs_globals[id];
5729                         ASSERT(svar != NULL);
5730                         v = &svar->dtsv_var;
5731 
5732                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5733                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5734 
5735                                 ASSERT(a != NULL);
5736                                 ASSERT(svar->dtsv_size != 0);
5737 
5738                                 if (regs[rd] == NULL) {
5739                                         *(uint8_t *)a = UINT8_MAX;
5740                                         break;
5741                                 } else {
5742                                         *(uint8_t *)a = 0;
5743                                         a += sizeof (uint64_t);
5744                                 }
5745                                 if (!dtrace_vcanload(
5746                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5747                                     mstate, vstate))
5748                                         break;
5749 
5750                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5751                                     (void *)a, &v->dtdv_type);
5752                                 break;
5753                         }
5754 
5755                         svar->dtsv_data = regs[rd];
5756                         break;
5757 
5758                 case DIF_OP_LDTA:
5759                         /*
5760                          * There are no DTrace built-in thread-local arrays at
5761                          * present.  This opcode is saved for future work.
5762                          */
5763                         *flags |= CPU_DTRACE_ILLOP;
5764                         regs[rd] = 0;
5765                         break;
5766 
5767                 case DIF_OP_LDLS:
5768                         id = DIF_INSTR_VAR(instr);
5769 
5770                         if (id < DIF_VAR_OTHER_UBASE) {
5771                                 /*
5772                                  * For now, this has no meaning.
5773                                  */
5774                                 regs[rd] = 0;
5775                                 break;
5776                         }
5777 
5778                         id -= DIF_VAR_OTHER_UBASE;
5779 
5780                         ASSERT(id < vstate->dtvs_nlocals);
5781                         ASSERT(vstate->dtvs_locals != NULL);
5782 
5783                         svar = vstate->dtvs_locals[id];
5784                         ASSERT(svar != NULL);
5785                         v = &svar->dtsv_var;
5786 
5787                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5788                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5789                                 size_t sz = v->dtdv_type.dtdt_size;
5790 
5791                                 sz += sizeof (uint64_t);
5792                                 ASSERT(svar->dtsv_size == NCPU * sz);
5793                                 a += CPU->cpu_id * sz;
5794 
5795                                 if (*(uint8_t *)a == UINT8_MAX) {
5796                                         /*
5797                                          * If the 0th byte is set to UINT8_MAX
5798                                          * then this is to be treated as a
5799                                          * reference to a NULL variable.
5800                                          */
5801                                         regs[rd] = NULL;
5802                                 } else {
5803                                         regs[rd] = a + sizeof (uint64_t);
5804                                 }
5805 
5806                                 break;
5807                         }
5808 
5809                         ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5810                         tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5811                         regs[rd] = tmp[CPU->cpu_id];
5812                         break;
5813 
5814                 case DIF_OP_STLS:
5815                         id = DIF_INSTR_VAR(instr);
5816 
5817                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5818                         id -= DIF_VAR_OTHER_UBASE;
5819                         ASSERT(id < vstate->dtvs_nlocals);
5820 
5821                         ASSERT(vstate->dtvs_locals != NULL);
5822                         svar = vstate->dtvs_locals[id];
5823                         ASSERT(svar != NULL);
5824                         v = &svar->dtsv_var;
5825 
5826                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5827                                 uintptr_t a = (uintptr_t)svar->dtsv_data;
5828                                 size_t sz = v->dtdv_type.dtdt_size;
5829 
5830                                 sz += sizeof (uint64_t);
5831                                 ASSERT(svar->dtsv_size == NCPU * sz);
5832                                 a += CPU->cpu_id * sz;
5833 
5834                                 if (regs[rd] == NULL) {
5835                                         *(uint8_t *)a = UINT8_MAX;
5836                                         break;
5837                                 } else {
5838                                         *(uint8_t *)a = 0;
5839                                         a += sizeof (uint64_t);
5840                                 }
5841 
5842                                 if (!dtrace_vcanload(
5843                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5844                                     mstate, vstate))
5845                                         break;
5846 
5847                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5848                                     (void *)a, &v->dtdv_type);
5849                                 break;
5850                         }
5851 
5852                         ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5853                         tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5854                         tmp[CPU->cpu_id] = regs[rd];
5855                         break;
5856 
5857                 case DIF_OP_LDTS: {
5858                         dtrace_dynvar_t *dvar;
5859                         dtrace_key_t *key;
5860 
5861                         id = DIF_INSTR_VAR(instr);
5862                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5863                         id -= DIF_VAR_OTHER_UBASE;
5864                         v = &vstate->dtvs_tlocals[id];
5865 
5866                         key = &tupregs[DIF_DTR_NREGS];
5867                         key[0].dttk_value = (uint64_t)id;
5868                         key[0].dttk_size = 0;
5869                         DTRACE_TLS_THRKEY(key[1].dttk_value);
5870                         key[1].dttk_size = 0;
5871 
5872                         dvar = dtrace_dynvar(dstate, 2, key,
5873                             sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5874                             mstate, vstate);
5875 
5876                         if (dvar == NULL) {
5877                                 regs[rd] = 0;
5878                                 break;
5879                         }
5880 
5881                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5882                                 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5883                         } else {
5884                                 regs[rd] = *((uint64_t *)dvar->dtdv_data);
5885                         }
5886 
5887                         break;
5888                 }
5889 
5890                 case DIF_OP_STTS: {
5891                         dtrace_dynvar_t *dvar;
5892                         dtrace_key_t *key;
5893 
5894                         id = DIF_INSTR_VAR(instr);
5895                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5896                         id -= DIF_VAR_OTHER_UBASE;
5897 
5898                         key = &tupregs[DIF_DTR_NREGS];
5899                         key[0].dttk_value = (uint64_t)id;
5900                         key[0].dttk_size = 0;
5901                         DTRACE_TLS_THRKEY(key[1].dttk_value);
5902                         key[1].dttk_size = 0;
5903                         v = &vstate->dtvs_tlocals[id];
5904 
5905                         dvar = dtrace_dynvar(dstate, 2, key,
5906                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5907                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
5908                             regs[rd] ? DTRACE_DYNVAR_ALLOC :
5909                             DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5910 
5911                         /*
5912                          * Given that we're storing to thread-local data,
5913                          * we need to flush our predicate cache.
5914                          */
5915                         curthread->t_predcache = NULL;
5916 
5917                         if (dvar == NULL)
5918                                 break;
5919 
5920                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5921                                 if (!dtrace_vcanload(
5922                                     (void *)(uintptr_t)regs[rd],
5923                                     &v->dtdv_type, mstate, vstate))
5924                                         break;
5925 
5926                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
5927                                     dvar->dtdv_data, &v->dtdv_type);
5928                         } else {
5929                                 *((uint64_t *)dvar->dtdv_data) = regs[rd];
5930                         }
5931 
5932                         break;
5933                 }
5934 
5935                 case DIF_OP_SRA:
5936                         regs[rd] = (int64_t)regs[r1] >> regs[r2];
5937                         break;
5938 
5939                 case DIF_OP_CALL:
5940                         dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5941                             regs, tupregs, ttop, mstate, state);
5942                         break;
5943 
5944                 case DIF_OP_PUSHTR:
5945                         if (ttop == DIF_DTR_NREGS) {
5946                                 *flags |= CPU_DTRACE_TUPOFLOW;
5947                                 break;
5948                         }
5949 
5950                         if (r1 == DIF_TYPE_STRING) {
5951                                 /*
5952                                  * If this is a string type and the size is 0,
5953                                  * we'll use the system-wide default string
5954                                  * size.  Note that we are _not_ looking at
5955                                  * the value of the DTRACEOPT_STRSIZE option;
5956                                  * had this been set, we would expect to have
5957                                  * a non-zero size value in the "pushtr".
5958                                  */
5959                                 tupregs[ttop].dttk_size =
5960                                     dtrace_strlen((char *)(uintptr_t)regs[rd],
5961                                     regs[r2] ? regs[r2] :
5962                                     dtrace_strsize_default) + 1;
5963                         } else {
5964                                 tupregs[ttop].dttk_size = regs[r2];
5965                         }
5966 
5967                         tupregs[ttop++].dttk_value = regs[rd];
5968                         break;
5969 
5970                 case DIF_OP_PUSHTV:
5971                         if (ttop == DIF_DTR_NREGS) {
5972                                 *flags |= CPU_DTRACE_TUPOFLOW;
5973                                 break;
5974                         }
5975 
5976                         tupregs[ttop].dttk_value = regs[rd];
5977                         tupregs[ttop++].dttk_size = 0;
5978                         break;
5979 
5980                 case DIF_OP_POPTS:
5981                         if (ttop != 0)
5982                                 ttop--;
5983                         break;
5984 
5985                 case DIF_OP_FLUSHTS:
5986                         ttop = 0;
5987                         break;
5988 
5989                 case DIF_OP_LDGAA:
5990                 case DIF_OP_LDTAA: {
5991                         dtrace_dynvar_t *dvar;
5992                         dtrace_key_t *key = tupregs;
5993                         uint_t nkeys = ttop;
5994 
5995                         id = DIF_INSTR_VAR(instr);
5996                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
5997                         id -= DIF_VAR_OTHER_UBASE;
5998 
5999                         key[nkeys].dttk_value = (uint64_t)id;
6000                         key[nkeys++].dttk_size = 0;
6001 
6002                         if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6003                                 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6004                                 key[nkeys++].dttk_size = 0;
6005                                 v = &vstate->dtvs_tlocals[id];
6006                         } else {
6007                                 v = &vstate->dtvs_globals[id]->dtsv_var;
6008                         }
6009 
6010                         dvar = dtrace_dynvar(dstate, nkeys, key,
6011                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6012                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
6013                             DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6014 
6015                         if (dvar == NULL) {
6016                                 regs[rd] = 0;
6017                                 break;
6018                         }
6019 
6020                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6021                                 regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6022                         } else {
6023                                 regs[rd] = *((uint64_t *)dvar->dtdv_data);
6024                         }
6025 
6026                         break;
6027                 }
6028 
6029                 case DIF_OP_STGAA:
6030                 case DIF_OP_STTAA: {
6031                         dtrace_dynvar_t *dvar;
6032                         dtrace_key_t *key = tupregs;
6033                         uint_t nkeys = ttop;
6034 
6035                         id = DIF_INSTR_VAR(instr);
6036                         ASSERT(id >= DIF_VAR_OTHER_UBASE);
6037                         id -= DIF_VAR_OTHER_UBASE;
6038 
6039                         key[nkeys].dttk_value = (uint64_t)id;
6040                         key[nkeys++].dttk_size = 0;
6041 
6042                         if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6043                                 DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6044                                 key[nkeys++].dttk_size = 0;
6045                                 v = &vstate->dtvs_tlocals[id];
6046                         } else {
6047                                 v = &vstate->dtvs_globals[id]->dtsv_var;
6048                         }
6049 
6050                         dvar = dtrace_dynvar(dstate, nkeys, key,
6051                             v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6052                             v->dtdv_type.dtdt_size : sizeof (uint64_t),
6053                             regs[rd] ? DTRACE_DYNVAR_ALLOC :
6054                             DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6055 
6056                         if (dvar == NULL)
6057                                 break;
6058 
6059                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6060                                 if (!dtrace_vcanload(
6061                                     (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6062                                     mstate, vstate))
6063                                         break;
6064 
6065                                 dtrace_vcopy((void *)(uintptr_t)regs[rd],
6066                                     dvar->dtdv_data, &v->dtdv_type);
6067                         } else {
6068                                 *((uint64_t *)dvar->dtdv_data) = regs[rd];
6069                         }
6070 
6071                         break;
6072                 }
6073 
6074                 case DIF_OP_ALLOCS: {
6075                         uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6076                         size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6077 
6078                         /*
6079                          * Rounding up the user allocation size could have
6080                          * overflowed large, bogus allocations (like -1ULL) to
6081                          * 0.
6082                          */
6083                         if (size < regs[r1] ||
6084                             !DTRACE_INSCRATCH(mstate, size)) {
6085                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6086                                 regs[rd] = NULL;
6087                                 break;
6088                         }
6089 
6090                         dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6091                         mstate->dtms_scratch_ptr += size;
6092                         regs[rd] = ptr;
6093                         break;
6094                 }
6095 
6096                 case DIF_OP_COPYS:
6097                         if (!dtrace_canstore(regs[rd], regs[r2],
6098                             mstate, vstate)) {
6099                                 *flags |= CPU_DTRACE_BADADDR;
6100                                 *illval = regs[rd];
6101                                 break;
6102                         }
6103 
6104                         if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6105                                 break;
6106 
6107                         dtrace_bcopy((void *)(uintptr_t)regs[r1],
6108                             (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6109                         break;
6110 
6111                 case DIF_OP_STB:
6112                         if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6113                                 *flags |= CPU_DTRACE_BADADDR;
6114                                 *illval = regs[rd];
6115                                 break;
6116                         }
6117                         *((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6118                         break;
6119 
6120                 case DIF_OP_STH:
6121                         if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6122                                 *flags |= CPU_DTRACE_BADADDR;
6123                                 *illval = regs[rd];
6124                                 break;
6125                         }
6126                         if (regs[rd] & 1) {
6127                                 *flags |= CPU_DTRACE_BADALIGN;
6128                                 *illval = regs[rd];
6129                                 break;
6130                         }
6131                         *((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6132                         break;
6133 
6134                 case DIF_OP_STW:
6135                         if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6136                                 *flags |= CPU_DTRACE_BADADDR;
6137                                 *illval = regs[rd];
6138                                 break;
6139                         }
6140                         if (regs[rd] & 3) {
6141                                 *flags |= CPU_DTRACE_BADALIGN;
6142                                 *illval = regs[rd];
6143                                 break;
6144                         }
6145                         *((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6146                         break;
6147 
6148                 case DIF_OP_STX:
6149                         if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6150                                 *flags |= CPU_DTRACE_BADADDR;
6151                                 *illval = regs[rd];
6152                                 break;
6153                         }
6154                         if (regs[rd] & 7) {
6155                                 *flags |= CPU_DTRACE_BADALIGN;
6156                                 *illval = regs[rd];
6157                                 break;
6158                         }
6159                         *((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6160                         break;
6161                 }
6162         }
6163 
6164         if (!(*flags & CPU_DTRACE_FAULT))
6165                 return (rval);
6166 
6167         mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6168         mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6169 
6170         return (0);
6171 }
6172 
6173 static void
6174 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6175 {
6176         dtrace_probe_t *probe = ecb->dte_probe;
6177         dtrace_provider_t *prov = probe->dtpr_provider;
6178         char c[DTRACE_FULLNAMELEN + 80], *str;
6179         char *msg = "dtrace: breakpoint action at probe ";
6180         char *ecbmsg = " (ecb ";
6181         uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6182         uintptr_t val = (uintptr_t)ecb;
6183         int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6184 
6185         if (dtrace_destructive_disallow)
6186                 return;
6187 
6188         /*
6189          * It's impossible to be taking action on the NULL probe.
6190          */
6191         ASSERT(probe != NULL);
6192 
6193         /*
6194          * This is a poor man's (destitute man's?) sprintf():  we want to
6195          * print the provider name, module name, function name and name of
6196          * the probe, along with the hex address of the ECB with the breakpoint
6197          * action -- all of which we must place in the character buffer by
6198          * hand.
6199          */
6200         while (*msg != '\0')
6201                 c[i++] = *msg++;
6202 
6203         for (str = prov->dtpv_name; *str != '\0'; str++)
6204                 c[i++] = *str;
6205         c[i++] = ':';
6206 
6207         for (str = probe->dtpr_mod; *str != '\0'; str++)
6208                 c[i++] = *str;
6209         c[i++] = ':';
6210 
6211         for (str = probe->dtpr_func; *str != '\0'; str++)
6212                 c[i++] = *str;
6213         c[i++] = ':';
6214 
6215         for (str = probe->dtpr_name; *str != '\0'; str++)
6216                 c[i++] = *str;
6217 
6218         while (*ecbmsg != '\0')
6219                 c[i++] = *ecbmsg++;
6220 
6221         while (shift >= 0) {
6222                 mask = (uintptr_t)0xf << shift;
6223 
6224                 if (val >= ((uintptr_t)1 << shift))
6225                         c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6226                 shift -= 4;
6227         }
6228 
6229         c[i++] = ')';
6230         c[i] = '\0';
6231 
6232         debug_enter(c);
6233 }
6234 
6235 static void
6236 dtrace_action_panic(dtrace_ecb_t *ecb)
6237 {
6238         dtrace_probe_t *probe = ecb->dte_probe;
6239 
6240         /*
6241          * It's impossible to be taking action on the NULL probe.
6242          */
6243         ASSERT(probe != NULL);
6244 
6245         if (dtrace_destructive_disallow)
6246                 return;
6247 
6248         if (dtrace_panicked != NULL)
6249                 return;
6250 
6251         if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6252                 return;
6253 
6254         /*
6255          * We won the right to panic.  (We want to be sure that only one
6256          * thread calls panic() from dtrace_probe(), and that panic() is
6257          * called exactly once.)
6258          */
6259         dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6260             probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6261             probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6262 }
6263 
6264 static void
6265 dtrace_action_raise(uint64_t sig)
6266 {
6267         if (dtrace_destructive_disallow)
6268                 return;
6269 
6270         if (sig >= NSIG) {
6271                 DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6272                 return;
6273         }
6274 
6275         /*
6276          * raise() has a queue depth of 1 -- we ignore all subsequent
6277          * invocations of the raise() action.
6278          */
6279         if (curthread->t_dtrace_sig == 0)
6280                 curthread->t_dtrace_sig = (uint8_t)sig;
6281 
6282         curthread->t_sig_check = 1;
6283         aston(curthread);
6284 }
6285 
6286 static void
6287 dtrace_action_stop(void)
6288 {
6289         if (dtrace_destructive_disallow)
6290                 return;
6291 
6292         if (!curthread->t_dtrace_stop) {
6293                 curthread->t_dtrace_stop = 1;
6294                 curthread->t_sig_check = 1;
6295                 aston(curthread);
6296         }
6297 }
6298 
6299 static void
6300 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6301 {
6302         hrtime_t now;
6303         volatile uint16_t *flags;
6304         cpu_t *cpu = CPU;
6305 
6306         if (dtrace_destructive_disallow)
6307                 return;
6308 
6309         flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6310 
6311         now = dtrace_gethrtime();
6312 
6313         if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6314                 /*
6315                  * We need to advance the mark to the current time.
6316                  */
6317                 cpu->cpu_dtrace_chillmark = now;
6318                 cpu->cpu_dtrace_chilled = 0;
6319         }
6320 
6321         /*
6322          * Now check to see if the requested chill time would take us over
6323          * the maximum amount of time allowed in the chill interval.  (Or
6324          * worse, if the calculation itself induces overflow.)
6325          */
6326         if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6327             cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6328                 *flags |= CPU_DTRACE_ILLOP;
6329                 return;
6330         }
6331 
6332         while (dtrace_gethrtime() - now < val)
6333                 continue;
6334 
6335         /*
6336          * Normally, we assure that the value of the variable "timestamp" does
6337          * not change within an ECB.  The presence of chill() represents an
6338          * exception to this rule, however.
6339          */
6340         mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6341         cpu->cpu_dtrace_chilled += val;
6342 }
6343 
6344 static void
6345 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6346     uint64_t *buf, uint64_t arg)
6347 {
6348         int nframes = DTRACE_USTACK_NFRAMES(arg);
6349         int strsize = DTRACE_USTACK_STRSIZE(arg);
6350         uint64_t *pcs = &buf[1], *fps;
6351         char *str = (char *)&pcs[nframes];
6352         int size, offs = 0, i, j;
6353         uintptr_t old = mstate->dtms_scratch_ptr, saved;
6354         uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6355         char *sym;
6356 
6357         /*
6358          * Should be taking a faster path if string space has not been
6359          * allocated.
6360          */
6361         ASSERT(strsize != 0);
6362 
6363         /*
6364          * We will first allocate some temporary space for the frame pointers.
6365          */
6366         fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6367         size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6368             (nframes * sizeof (uint64_t));
6369 
6370         if (!DTRACE_INSCRATCH(mstate, size)) {
6371                 /*
6372                  * Not enough room for our frame pointers -- need to indicate
6373                  * that we ran out of scratch space.
6374                  */
6375                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6376                 return;
6377         }
6378 
6379         mstate->dtms_scratch_ptr += size;
6380         saved = mstate->dtms_scratch_ptr;
6381 
6382         /*
6383          * Now get a stack with both program counters and frame pointers.
6384          */
6385         DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6386         dtrace_getufpstack(buf, fps, nframes + 1);
6387         DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6388 
6389         /*
6390          * If that faulted, we're cooked.
6391          */
6392         if (*flags & CPU_DTRACE_FAULT)
6393                 goto out;
6394 
6395         /*
6396          * Now we want to walk up the stack, calling the USTACK helper.  For
6397          * each iteration, we restore the scratch pointer.
6398          */
6399         for (i = 0; i < nframes; i++) {
6400                 mstate->dtms_scratch_ptr = saved;
6401 
6402                 if (offs >= strsize)
6403                         break;
6404 
6405                 sym = (char *)(uintptr_t)dtrace_helper(
6406                     DTRACE_HELPER_ACTION_USTACK,
6407                     mstate, state, pcs[i], fps[i]);
6408 
6409                 /*
6410                  * If we faulted while running the helper, we're going to
6411                  * clear the fault and null out the corresponding string.
6412                  */
6413                 if (*flags & CPU_DTRACE_FAULT) {
6414                         *flags &= ~CPU_DTRACE_FAULT;
6415                         str[offs++] = '\0';
6416                         continue;
6417                 }
6418 
6419                 if (sym == NULL) {
6420                         str[offs++] = '\0';
6421                         continue;
6422                 }
6423 
6424                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6425 
6426                 /*
6427                  * Now copy in the string that the helper returned to us.
6428                  */
6429                 for (j = 0; offs + j < strsize; j++) {
6430                         if ((str[offs + j] = sym[j]) == '\0')
6431                                 break;
6432                 }
6433 
6434                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6435 
6436                 offs += j + 1;
6437         }
6438 
6439         if (offs >= strsize) {
6440                 /*
6441                  * If we didn't have room for all of the strings, we don't
6442                  * abort processing -- this needn't be a fatal error -- but we
6443                  * still want to increment a counter (dts_stkstroverflows) to
6444                  * allow this condition to be warned about.  (If this is from
6445                  * a jstack() action, it is easily tuned via jstackstrsize.)
6446                  */
6447                 dtrace_error(&state->dts_stkstroverflows);
6448         }
6449 
6450         while (offs < strsize)
6451                 str[offs++] = '\0';
6452 
6453 out:
6454         mstate->dtms_scratch_ptr = old;
6455 }
6456 
6457 /*
6458  * If you're looking for the epicenter of DTrace, you just found it.  This
6459  * is the function called by the provider to fire a probe -- from which all
6460  * subsequent probe-context DTrace activity emanates.
6461  */
6462 void
6463 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6464     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6465 {
6466         processorid_t cpuid;
6467         dtrace_icookie_t cookie;
6468         dtrace_probe_t *probe;
6469         dtrace_mstate_t mstate;
6470         dtrace_ecb_t *ecb;
6471         dtrace_action_t *act;
6472         intptr_t offs;
6473         size_t size;
6474         int vtime, onintr;
6475         volatile uint16_t *flags;
6476         hrtime_t now;
6477 
6478         /*
6479          * Kick out immediately if this CPU is still being born (in which case
6480          * curthread will be set to -1) or the current thread can't allow
6481          * probes in its current context.
6482          */
6483         if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6484                 return;
6485 
6486         cookie = dtrace_interrupt_disable();
6487         probe = dtrace_probes[id - 1];
6488         cpuid = CPU->cpu_id;
6489         onintr = CPU_ON_INTR(CPU);
6490 
6491         if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6492             probe->dtpr_predcache == curthread->t_predcache) {
6493                 /*
6494                  * We have hit in the predicate cache; we know that
6495                  * this predicate would evaluate to be false.
6496                  */
6497                 dtrace_interrupt_enable(cookie);
6498                 return;
6499         }
6500 
6501         if (panic_quiesce) {
6502                 /*
6503                  * We don't trace anything if we're panicking.
6504                  */
6505                 dtrace_interrupt_enable(cookie);
6506                 return;
6507         }
6508 
6509         now = dtrace_gethrtime();
6510         vtime = dtrace_vtime_references != 0;
6511 
6512         if (vtime && curthread->t_dtrace_start)
6513                 curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6514 
6515         mstate.dtms_difo = NULL;
6516         mstate.dtms_probe = probe;
6517         mstate.dtms_strtok = NULL;
6518         mstate.dtms_arg[0] = arg0;
6519         mstate.dtms_arg[1] = arg1;
6520         mstate.dtms_arg[2] = arg2;
6521         mstate.dtms_arg[3] = arg3;
6522         mstate.dtms_arg[4] = arg4;
6523 
6524         flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6525 
6526         for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6527                 dtrace_predicate_t *pred = ecb->dte_predicate;
6528                 dtrace_state_t *state = ecb->dte_state;
6529                 dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6530                 dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6531                 dtrace_vstate_t *vstate = &state->dts_vstate;
6532                 dtrace_provider_t *prov = probe->dtpr_provider;
6533                 uint64_t tracememsize = 0;
6534                 int committed = 0;
6535                 caddr_t tomax;
6536 
6537                 /*
6538                  * A little subtlety with the following (seemingly innocuous)
6539                  * declaration of the automatic 'val':  by looking at the
6540                  * code, you might think that it could be declared in the
6541                  * action processing loop, below.  (That is, it's only used in
6542                  * the action processing loop.)  However, it must be declared
6543                  * out of that scope because in the case of DIF expression
6544                  * arguments to aggregating actions, one iteration of the
6545                  * action loop will use the last iteration's value.
6546                  */
6547 #ifdef lint
6548                 uint64_t val = 0;
6549 #else
6550                 uint64_t val;
6551 #endif
6552 
6553                 mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6554                 mstate.dtms_access = DTRACE_ACCESS_ARGS | DTRACE_ACCESS_PROC;
6555                 mstate.dtms_getf = NULL;
6556 
6557                 *flags &= ~CPU_DTRACE_ERROR;
6558 
6559                 if (prov == dtrace_provider) {
6560                         /*
6561                          * If dtrace itself is the provider of this probe,
6562                          * we're only going to continue processing the ECB if
6563                          * arg0 (the dtrace_state_t) is equal to the ECB's
6564                          * creating state.  (This prevents disjoint consumers
6565                          * from seeing one another's metaprobes.)
6566                          */
6567                         if (arg0 != (uint64_t)(uintptr_t)state)
6568                                 continue;
6569                 }
6570 
6571                 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6572                         /*
6573                          * We're not currently active.  If our provider isn't
6574                          * the dtrace pseudo provider, we're not interested.
6575                          */
6576                         if (prov != dtrace_provider)
6577                                 continue;
6578 
6579                         /*
6580                          * Now we must further check if we are in the BEGIN
6581                          * probe.  If we are, we will only continue processing
6582                          * if we're still in WARMUP -- if one BEGIN enabling
6583                          * has invoked the exit() action, we don't want to
6584                          * evaluate subsequent BEGIN enablings.
6585                          */
6586                         if (probe->dtpr_id == dtrace_probeid_begin &&
6587                             state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6588                                 ASSERT(state->dts_activity ==
6589                                     DTRACE_ACTIVITY_DRAINING);
6590                                 continue;
6591                         }
6592                 }
6593 
6594                 if (ecb->dte_cond && !dtrace_priv_probe(state, &mstate, ecb))
6595                         continue;
6596 
6597                 if (now - state->dts_alive > dtrace_deadman_timeout) {
6598                         /*
6599                          * We seem to be dead.  Unless we (a) have kernel
6600                          * destructive permissions (b) have explicitly enabled
6601                          * destructive actions and (c) destructive actions have
6602                          * not been disabled, we're going to transition into
6603                          * the KILLED state, from which no further processing
6604                          * on this state will be performed.
6605                          */
6606                         if (!dtrace_priv_kernel_destructive(state) ||
6607                             !state->dts_cred.dcr_destructive ||
6608                             dtrace_destructive_disallow) {
6609                                 void *activity = &state->dts_activity;
6610                                 dtrace_activity_t current;
6611 
6612                                 do {
6613                                         current = state->dts_activity;
6614                                 } while (dtrace_cas32(activity, current,
6615                                     DTRACE_ACTIVITY_KILLED) != current);
6616 
6617                                 continue;
6618                         }
6619                 }
6620 
6621                 if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6622                     ecb->dte_alignment, state, &mstate)) < 0)
6623                         continue;
6624 
6625                 tomax = buf->dtb_tomax;
6626                 ASSERT(tomax != NULL);
6627 
6628                 if (ecb->dte_size != 0) {
6629                         dtrace_rechdr_t dtrh;
6630                         if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6631                                 mstate.dtms_timestamp = dtrace_gethrtime();
6632                                 mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6633                         }
6634                         ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
6635                         dtrh.dtrh_epid = ecb->dte_epid;
6636                         DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
6637                             mstate.dtms_timestamp);
6638                         *((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
6639                 }
6640 
6641                 mstate.dtms_epid = ecb->dte_epid;
6642                 mstate.dtms_present |= DTRACE_MSTATE_EPID;
6643 
6644                 if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6645                         mstate.dtms_access |= DTRACE_ACCESS_KERNEL;
6646 
6647                 if (pred != NULL) {
6648                         dtrace_difo_t *dp = pred->dtp_difo;
6649                         int rval;
6650 
6651                         rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6652 
6653                         if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6654                                 dtrace_cacheid_t cid = probe->dtpr_predcache;
6655 
6656                                 if (cid != DTRACE_CACHEIDNONE && !onintr) {
6657                                         /*
6658                                          * Update the predicate cache...
6659                                          */
6660                                         ASSERT(cid == pred->dtp_cacheid);
6661                                         curthread->t_predcache = cid;
6662                                 }
6663 
6664                                 continue;
6665                         }
6666                 }
6667 
6668                 for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6669                     act != NULL; act = act->dta_next) {
6670                         size_t valoffs;
6671                         dtrace_difo_t *dp;
6672                         dtrace_recdesc_t *rec = &act->dta_rec;
6673 
6674                         size = rec->dtrd_size;
6675                         valoffs = offs + rec->dtrd_offset;
6676 
6677                         if (DTRACEACT_ISAGG(act->dta_kind)) {
6678                                 uint64_t v = 0xbad;
6679                                 dtrace_aggregation_t *agg;
6680 
6681                                 agg = (dtrace_aggregation_t *)act;
6682 
6683                                 if ((dp = act->dta_difo) != NULL)
6684                                         v = dtrace_dif_emulate(dp,
6685                                             &mstate, vstate, state);
6686 
6687                                 if (*flags & CPU_DTRACE_ERROR)
6688                                         continue;
6689 
6690                                 /*
6691                                  * Note that we always pass the expression
6692                                  * value from the previous iteration of the
6693                                  * action loop.  This value will only be used
6694                                  * if there is an expression argument to the
6695                                  * aggregating action, denoted by the
6696                                  * dtag_hasarg field.
6697                                  */
6698                                 dtrace_aggregate(agg, buf,
6699                                     offs, aggbuf, v, val);
6700                                 continue;
6701                         }
6702 
6703                         switch (act->dta_kind) {
6704                         case DTRACEACT_STOP:
6705                                 if (dtrace_priv_proc_destructive(state,
6706                                     &mstate))
6707                                         dtrace_action_stop();
6708                                 continue;
6709 
6710                         case DTRACEACT_BREAKPOINT:
6711                                 if (dtrace_priv_kernel_destructive(state))
6712                                         dtrace_action_breakpoint(ecb);
6713                                 continue;
6714 
6715                         case DTRACEACT_PANIC:
6716                                 if (dtrace_priv_kernel_destructive(state))
6717                                         dtrace_action_panic(ecb);
6718                                 continue;
6719 
6720                         case DTRACEACT_STACK:
6721                                 if (!dtrace_priv_kernel(state))
6722                                         continue;
6723 
6724                                 dtrace_getpcstack((pc_t *)(tomax + valoffs),
6725                                     size / sizeof (pc_t), probe->dtpr_aframes,
6726                                     DTRACE_ANCHORED(probe) ? NULL :
6727                                     (uint32_t *)arg0);
6728 
6729                                 continue;
6730 
6731                         case DTRACEACT_JSTACK:
6732                         case DTRACEACT_USTACK:
6733                                 if (!dtrace_priv_proc(state, &mstate))
6734                                         continue;
6735 
6736                                 /*
6737                                  * See comment in DIF_VAR_PID.
6738                                  */
6739                                 if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6740                                     CPU_ON_INTR(CPU)) {
6741                                         int depth = DTRACE_USTACK_NFRAMES(
6742                                             rec->dtrd_arg) + 1;
6743 
6744                                         dtrace_bzero((void *)(tomax + valoffs),
6745                                             DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6746                                             + depth * sizeof (uint64_t));
6747 
6748                                         continue;
6749                                 }
6750 
6751                                 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6752                                     curproc->p_dtrace_helpers != NULL) {
6753                                         /*
6754                                          * This is the slow path -- we have
6755                                          * allocated string space, and we're
6756                                          * getting the stack of a process that
6757                                          * has helpers.  Call into a separate
6758                                          * routine to perform this processing.
6759                                          */
6760                                         dtrace_action_ustack(&mstate, state,
6761                                             (uint64_t *)(tomax + valoffs),
6762                                             rec->dtrd_arg);
6763                                         continue;
6764                                 }
6765 
6766                                 /*
6767                                  * Clear the string space, since there's no
6768                                  * helper to do it for us.
6769                                  */
6770                                 if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0) {
6771                                         int depth = DTRACE_USTACK_NFRAMES(
6772                                             rec->dtrd_arg);
6773                                         size_t strsize = DTRACE_USTACK_STRSIZE(
6774                                             rec->dtrd_arg);
6775                                         uint64_t *buf = (uint64_t *)(tomax +
6776                                             valoffs);
6777                                         void *strspace = &buf[depth + 1];
6778 
6779                                         dtrace_bzero(strspace,
6780                                             MIN(depth, strsize));
6781                                 }
6782 
6783                                 DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6784                                 dtrace_getupcstack((uint64_t *)
6785                                     (tomax + valoffs),
6786                                     DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6787                                 DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6788                                 continue;
6789 
6790                         default:
6791                                 break;
6792                         }
6793 
6794                         dp = act->dta_difo;
6795                         ASSERT(dp != NULL);
6796 
6797                         val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6798 
6799                         if (*flags & CPU_DTRACE_ERROR)
6800                                 continue;
6801 
6802                         switch (act->dta_kind) {
6803                         case DTRACEACT_SPECULATE: {
6804                                 dtrace_rechdr_t *dtrh;
6805 
6806                                 ASSERT(buf == &state->dts_buffer[cpuid]);
6807                                 buf = dtrace_speculation_buffer(state,
6808                                     cpuid, val);
6809 
6810                                 if (buf == NULL) {
6811                                         *flags |= CPU_DTRACE_DROP;
6812                                         continue;
6813                                 }
6814 
6815                                 offs = dtrace_buffer_reserve(buf,
6816                                     ecb->dte_needed, ecb->dte_alignment,
6817                                     state, NULL);
6818 
6819                                 if (offs < 0) {
6820                                         *flags |= CPU_DTRACE_DROP;
6821                                         continue;
6822                                 }
6823 
6824                                 tomax = buf->dtb_tomax;
6825                                 ASSERT(tomax != NULL);
6826 
6827                                 if (ecb->dte_size == 0)
6828                                         continue;
6829 
6830                                 ASSERT3U(ecb->dte_size, >=,
6831                                     sizeof (dtrace_rechdr_t));
6832                                 dtrh = ((void *)(tomax + offs));
6833                                 dtrh->dtrh_epid = ecb->dte_epid;
6834                                 /*
6835                                  * When the speculation is committed, all of
6836                                  * the records in the speculative buffer will
6837                                  * have their timestamps set to the commit
6838                                  * time.  Until then, it is set to a sentinel
6839                                  * value, for debugability.
6840                                  */
6841                                 DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
6842                                 continue;
6843                         }
6844 
6845                         case DTRACEACT_CHILL:
6846                                 if (dtrace_priv_kernel_destructive(state))
6847                                         dtrace_action_chill(&mstate, val);
6848                                 continue;
6849 
6850                         case DTRACEACT_RAISE:
6851                                 if (dtrace_priv_proc_destructive(state,
6852                                     &mstate))
6853                                         dtrace_action_raise(val);
6854                                 continue;
6855 
6856                         case DTRACEACT_COMMIT:
6857                                 ASSERT(!committed);
6858 
6859                                 /*
6860                                  * We need to commit our buffer state.
6861                                  */
6862                                 if (ecb->dte_size)
6863                                         buf->dtb_offset = offs + ecb->dte_size;
6864                                 buf = &state->dts_buffer[cpuid];
6865                                 dtrace_speculation_commit(state, cpuid, val);
6866                                 committed = 1;
6867                                 continue;
6868 
6869                         case DTRACEACT_DISCARD:
6870                                 dtrace_speculation_discard(state, cpuid, val);
6871                                 continue;
6872 
6873                         case DTRACEACT_DIFEXPR:
6874                         case DTRACEACT_LIBACT:
6875                         case DTRACEACT_PRINTF:
6876                         case DTRACEACT_PRINTA:
6877                         case DTRACEACT_SYSTEM:
6878                         case DTRACEACT_FREOPEN:
6879                         case DTRACEACT_TRACEMEM:
6880                                 break;
6881 
6882                         case DTRACEACT_TRACEMEM_DYNSIZE:
6883                                 tracememsize = val;
6884                                 break;
6885 
6886                         case DTRACEACT_SYM:
6887                         case DTRACEACT_MOD:
6888                                 if (!dtrace_priv_kernel(state))
6889                                         continue;
6890                                 break;
6891 
6892                         case DTRACEACT_USYM:
6893                         case DTRACEACT_UMOD:
6894                         case DTRACEACT_UADDR: {
6895                                 struct pid *pid = curthread->t_procp->p_pidp;
6896 
6897                                 if (!dtrace_priv_proc(state, &mstate))
6898                                         continue;
6899 
6900                                 DTRACE_STORE(uint64_t, tomax,
6901                                     valoffs, (uint64_t)pid->pid_id);
6902                                 DTRACE_STORE(uint64_t, tomax,
6903                                     valoffs + sizeof (uint64_t), val);
6904 
6905                                 continue;
6906                         }
6907 
6908                         case DTRACEACT_EXIT: {
6909                                 /*
6910                                  * For the exit action, we are going to attempt
6911                                  * to atomically set our activity to be
6912                                  * draining.  If this fails (either because
6913                                  * another CPU has beat us to the exit action,
6914                                  * or because our current activity is something
6915                                  * other than ACTIVE or WARMUP), we will
6916                                  * continue.  This assures that the exit action
6917                                  * can be successfully recorded at most once
6918                                  * when we're in the ACTIVE state.  If we're
6919                                  * encountering the exit() action while in
6920                                  * COOLDOWN, however, we want to honor the new
6921                                  * status code.  (We know that we're the only
6922                                  * thread in COOLDOWN, so there is no race.)
6923                                  */
6924                                 void *activity = &state->dts_activity;
6925                                 dtrace_activity_t current = state->dts_activity;
6926 
6927                                 if (current == DTRACE_ACTIVITY_COOLDOWN)
6928                                         break;
6929 
6930                                 if (current != DTRACE_ACTIVITY_WARMUP)
6931                                         current = DTRACE_ACTIVITY_ACTIVE;
6932 
6933                                 if (dtrace_cas32(activity, current,
6934                                     DTRACE_ACTIVITY_DRAINING) != current) {
6935                                         *flags |= CPU_DTRACE_DROP;
6936                                         continue;
6937                                 }
6938 
6939                                 break;
6940                         }
6941 
6942                         default:
6943                                 ASSERT(0);
6944                         }
6945 
6946                         if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6947                                 uintptr_t end = valoffs + size;
6948 
6949                                 if (tracememsize != 0 &&
6950                                     valoffs + tracememsize < end) {
6951                                         end = valoffs + tracememsize;
6952                                         tracememsize = 0;
6953                                 }
6954 
6955                                 if (!dtrace_vcanload((void *)(uintptr_t)val,
6956                                     &dp->dtdo_rtype, &mstate, vstate))
6957                                         continue;
6958 
6959                                 /*
6960                                  * If this is a string, we're going to only
6961                                  * load until we find the zero byte -- after
6962                                  * which we'll store zero bytes.
6963                                  */
6964                                 if (dp->dtdo_rtype.dtdt_kind ==
6965                                     DIF_TYPE_STRING) {
6966                                         char c = '\0' + 1;
6967                                         int intuple = act->dta_intuple;
6968                                         size_t s;
6969 
6970                                         for (s = 0; s < size; s++) {
6971                                                 if (c != '\0')
6972                                                         c = dtrace_load8(val++);
6973 
6974                                                 DTRACE_STORE(uint8_t, tomax,
6975                                                     valoffs++, c);
6976 
6977                                                 if (c == '\0' && intuple)
6978                                                         break;
6979                                         }
6980 
6981                                         continue;
6982                                 }
6983 
6984                                 while (valoffs < end) {
6985                                         DTRACE_STORE(uint8_t, tomax, valoffs++,
6986                                             dtrace_load8(val++));
6987                                 }
6988 
6989                                 continue;
6990                         }
6991 
6992                         switch (size) {
6993                         case 0:
6994                                 break;
6995 
6996                         case sizeof (uint8_t):
6997                                 DTRACE_STORE(uint8_t, tomax, valoffs, val);
6998                                 break;
6999                         case sizeof (uint16_t):
7000                                 DTRACE_STORE(uint16_t, tomax, valoffs, val);
7001                                 break;
7002                         case sizeof (uint32_t):
7003                                 DTRACE_STORE(uint32_t, tomax, valoffs, val);
7004                                 break;
7005                         case sizeof (uint64_t):
7006                                 DTRACE_STORE(uint64_t, tomax, valoffs, val);
7007                                 break;
7008                         default:
7009                                 /*
7010                                  * Any other size should have been returned by
7011                                  * reference, not by value.
7012                                  */
7013                                 ASSERT(0);
7014                                 break;
7015                         }
7016                 }
7017 
7018                 if (*flags & CPU_DTRACE_DROP)
7019                         continue;
7020 
7021                 if (*flags & CPU_DTRACE_FAULT) {
7022                         int ndx;
7023                         dtrace_action_t *err;
7024 
7025                         buf->dtb_errors++;
7026 
7027                         if (probe->dtpr_id == dtrace_probeid_error) {
7028                                 /*
7029                                  * There's nothing we can do -- we had an
7030                                  * error on the error probe.  We bump an
7031                                  * error counter to at least indicate that
7032                                  * this condition happened.
7033                                  */
7034                                 dtrace_error(&state->dts_dblerrors);
7035                                 continue;
7036                         }
7037 
7038                         if (vtime) {
7039                                 /*
7040                                  * Before recursing on dtrace_probe(), we
7041                                  * need to explicitly clear out our start
7042                                  * time to prevent it from being accumulated
7043                                  * into t_dtrace_vtime.
7044                                  */
7045                                 curthread->t_dtrace_start = 0;
7046                         }
7047 
7048                         /*
7049                          * Iterate over the actions to figure out which action
7050                          * we were processing when we experienced the error.
7051                          * Note that act points _past_ the faulting action; if
7052                          * act is ecb->dte_action, the fault was in the
7053                          * predicate, if it's ecb->dte_action->dta_next it's
7054                          * in action #1, and so on.
7055                          */
7056                         for (err = ecb->dte_action, ndx = 0;
7057                             err != act; err = err->dta_next, ndx++)
7058                                 continue;
7059 
7060                         dtrace_probe_error(state, ecb->dte_epid, ndx,
7061                             (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7062                             mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7063                             cpu_core[cpuid].cpuc_dtrace_illval);
7064 
7065                         continue;
7066                 }
7067 
7068                 if (!committed)
7069                         buf->dtb_offset = offs + ecb->dte_size;
7070         }
7071 
7072         if (vtime)
7073                 curthread->t_dtrace_start = dtrace_gethrtime();
7074 
7075         dtrace_interrupt_enable(cookie);
7076 }
7077 
7078 /*
7079  * DTrace Probe Hashing Functions
7080  *
7081  * The functions in this section (and indeed, the functions in remaining
7082  * sections) are not _called_ from probe context.  (Any exceptions to this are
7083  * marked with a "Note:".)  Rather, they are called from elsewhere in the
7084  * DTrace framework to look-up probes in, add probes to and remove probes from
7085  * the DTrace probe hashes.  (Each probe is hashed by each element of the
7086  * probe tuple -- allowing for fast lookups, regardless of what was
7087  * specified.)
7088  */
7089 static uint_t
7090 dtrace_hash_str(char *p)
7091 {
7092         unsigned int g;
7093         uint_t hval = 0;
7094 
7095         while (*p) {
7096                 hval = (hval << 4) + *p++;
7097                 if ((g = (hval & 0xf0000000)) != 0)
7098                         hval ^= g >> 24;
7099                 hval &= ~g;
7100         }
7101         return (hval);
7102 }
7103 
7104 static dtrace_hash_t *
7105 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7106 {
7107         dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7108 
7109         hash->dth_stroffs = stroffs;
7110         hash->dth_nextoffs = nextoffs;
7111         hash->dth_prevoffs = prevoffs;
7112 
7113         hash->dth_size = 1;
7114         hash->dth_mask = hash->dth_size - 1;
7115 
7116         hash->dth_tab = kmem_zalloc(hash->dth_size *
7117             sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7118 
7119         return (hash);
7120 }
7121 
7122 static void
7123 dtrace_hash_destroy(dtrace_hash_t *hash)
7124 {
7125 #ifdef DEBUG
7126         int i;
7127 
7128         for (i = 0; i < hash->dth_size; i++)
7129                 ASSERT(hash->dth_tab[i] == NULL);
7130 #endif
7131 
7132         kmem_free(hash->dth_tab,
7133             hash->dth_size * sizeof (dtrace_hashbucket_t *));
7134         kmem_free(hash, sizeof (dtrace_hash_t));
7135 }
7136 
7137 static void
7138 dtrace_hash_resize(dtrace_hash_t *hash)
7139 {
7140         int size = hash->dth_size, i, ndx;
7141         int new_size = hash->dth_size << 1;
7142         int new_mask = new_size - 1;
7143         dtrace_hashbucket_t **new_tab, *bucket, *next;
7144 
7145         ASSERT((new_size & new_mask) == 0);
7146 
7147         new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7148 
7149         for (i = 0; i < size; i++) {
7150                 for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7151                         dtrace_probe_t *probe = bucket->dthb_chain;
7152 
7153                         ASSERT(probe != NULL);
7154                         ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7155 
7156                         next = bucket->dthb_next;
7157                         bucket->dthb_next = new_tab[ndx];
7158                         new_tab[ndx] = bucket;
7159                 }
7160         }
7161 
7162         kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7163         hash->dth_tab = new_tab;
7164         hash->dth_size = new_size;
7165         hash->dth_mask = new_mask;
7166 }
7167 
7168 static void
7169 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7170 {
7171         int hashval = DTRACE_HASHSTR(hash, new);
7172         int ndx = hashval & hash->dth_mask;
7173         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7174         dtrace_probe_t **nextp, **prevp;
7175 
7176         for (; bucket != NULL; bucket = bucket->dthb_next) {
7177                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7178                         goto add;
7179         }
7180 
7181         if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7182                 dtrace_hash_resize(hash);
7183                 dtrace_hash_add(hash, new);
7184                 return;
7185         }
7186 
7187         bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7188         bucket->dthb_next = hash->dth_tab[ndx];
7189         hash->dth_tab[ndx] = bucket;
7190         hash->dth_nbuckets++;
7191 
7192 add:
7193         nextp = DTRACE_HASHNEXT(hash, new);
7194         ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7195         *nextp = bucket->dthb_chain;
7196 
7197         if (bucket->dthb_chain != NULL) {
7198                 prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7199                 ASSERT(*prevp == NULL);
7200                 *prevp = new;
7201         }
7202 
7203         bucket->dthb_chain = new;
7204         bucket->dthb_len++;
7205 }
7206 
7207 static dtrace_probe_t *
7208 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7209 {
7210         int hashval = DTRACE_HASHSTR(hash, template);
7211         int ndx = hashval & hash->dth_mask;
7212         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7213 
7214         for (; bucket != NULL; bucket = bucket->dthb_next) {
7215                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7216                         return (bucket->dthb_chain);
7217         }
7218 
7219         return (NULL);
7220 }
7221 
7222 static int
7223 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7224 {
7225         int hashval = DTRACE_HASHSTR(hash, template);
7226         int ndx = hashval & hash->dth_mask;
7227         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7228 
7229         for (; bucket != NULL; bucket = bucket->dthb_next) {
7230                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7231                         return (bucket->dthb_len);
7232         }
7233 
7234         return (NULL);
7235 }
7236 
7237 static void
7238 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7239 {
7240         int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7241         dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7242 
7243         dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7244         dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7245 
7246         /*
7247          * Find the bucket that we're removing this probe from.
7248          */
7249         for (; bucket != NULL; bucket = bucket->dthb_next) {
7250                 if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7251                         break;
7252         }
7253 
7254         ASSERT(bucket != NULL);
7255 
7256         if (*prevp == NULL) {
7257                 if (*nextp == NULL) {
7258                         /*
7259                          * The removed probe was the only probe on this
7260                          * bucket; we need to remove the bucket.
7261                          */
7262                         dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7263 
7264                         ASSERT(bucket->dthb_chain == probe);
7265                         ASSERT(b != NULL);
7266 
7267                         if (b == bucket) {
7268                                 hash->dth_tab[ndx] = bucket->dthb_next;
7269                         } else {
7270                                 while (b->dthb_next != bucket)
7271                                         b = b->dthb_next;
7272                                 b->dthb_next = bucket->dthb_next;
7273                         }
7274 
7275                         ASSERT(hash->dth_nbuckets > 0);
7276                         hash->dth_nbuckets--;
7277                         kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7278                         return;
7279                 }
7280 
7281                 bucket->dthb_chain = *nextp;
7282         } else {
7283                 *(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7284         }
7285 
7286         if (*nextp != NULL)
7287                 *(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7288 }
7289 
7290 /*
7291  * DTrace Utility Functions
7292  *
7293  * These are random utility functions that are _not_ called from probe context.
7294  */
7295 static int
7296 dtrace_badattr(const dtrace_attribute_t *a)
7297 {
7298         return (a->dtat_name > DTRACE_STABILITY_MAX ||
7299             a->dtat_data > DTRACE_STABILITY_MAX ||
7300             a->dtat_class > DTRACE_CLASS_MAX);
7301 }
7302 
7303 /*
7304  * Return a duplicate copy of a string.  If the specified string is NULL,
7305  * this function returns a zero-length string.
7306  */
7307 static char *
7308 dtrace_strdup(const char *str)
7309 {
7310         char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7311 
7312         if (str != NULL)
7313                 (void) strcpy(new, str);
7314 
7315         return (new);
7316 }
7317 
7318 #define DTRACE_ISALPHA(c)       \
7319         (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7320 
7321 static int
7322 dtrace_badname(const char *s)
7323 {
7324         char c;
7325 
7326         if (s == NULL || (c = *s++) == '\0')
7327                 return (0);
7328 
7329         if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7330                 return (1);
7331 
7332         while ((c = *s++) != '\0') {
7333                 if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7334                     c != '-' && c != '_' && c != '.' && c != '`')
7335                         return (1);
7336         }
7337 
7338         return (0);
7339 }
7340 
7341 static void
7342 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7343 {
7344         uint32_t priv;
7345 
7346         if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7347                 /*
7348                  * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7349                  */
7350                 priv = DTRACE_PRIV_ALL;
7351         } else {
7352                 *uidp = crgetuid(cr);
7353                 *zoneidp = crgetzonedid(cr);
7354 
7355                 priv = 0;
7356                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7357                         priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7358                 else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7359                         priv |= DTRACE_PRIV_USER;
7360                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7361                         priv |= DTRACE_PRIV_PROC;
7362                 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7363                         priv |= DTRACE_PRIV_OWNER;
7364                 if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7365                         priv |= DTRACE_PRIV_ZONEOWNER;
7366         }
7367 
7368         *privp = priv;
7369 }
7370 
7371 #ifdef DTRACE_ERRDEBUG
7372 static void
7373 dtrace_errdebug(const char *str)
7374 {
7375         int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
7376         int occupied = 0;
7377 
7378         mutex_enter(&dtrace_errlock);
7379         dtrace_errlast = str;
7380         dtrace_errthread = curthread;
7381 
7382         while (occupied++ < DTRACE_ERRHASHSZ) {
7383                 if (dtrace_errhash[hval].dter_msg == str) {
7384                         dtrace_errhash[hval].dter_count++;
7385                         goto out;
7386                 }
7387 
7388                 if (dtrace_errhash[hval].dter_msg != NULL) {
7389                         hval = (hval + 1) % DTRACE_ERRHASHSZ;
7390                         continue;
7391                 }
7392 
7393                 dtrace_errhash[hval].dter_msg = str;
7394                 dtrace_errhash[hval].dter_count = 1;
7395                 goto out;
7396         }
7397 
7398         panic("dtrace: undersized error hash");
7399 out:
7400         mutex_exit(&dtrace_errlock);
7401 }
7402 #endif
7403 
7404 /*
7405  * DTrace Matching Functions
7406  *
7407  * These functions are used to match groups of probes, given some elements of
7408  * a probe tuple, or some globbed expressions for elements of a probe tuple.
7409  */
7410 static int
7411 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7412     zoneid_t zoneid)
7413 {
7414         if (priv != DTRACE_PRIV_ALL) {
7415                 uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7416                 uint32_t match = priv & ppriv;
7417 
7418                 /*
7419                  * No PRIV_DTRACE_* privileges...
7420                  */
7421                 if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7422                     DTRACE_PRIV_KERNEL)) == 0)
7423                         return (0);
7424 
7425                 /*
7426                  * No matching bits, but there were bits to match...
7427                  */
7428                 if (match == 0 && ppriv != 0)
7429                         return (0);
7430 
7431                 /*
7432                  * Need to have permissions to the process, but don't...
7433                  */
7434                 if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7435                     uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7436                         return (0);
7437                 }
7438 
7439                 /*
7440                  * Need to be in the same zone unless we possess the
7441                  * privilege to examine all zones.
7442                  */
7443                 if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7444                     zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7445                         return (0);
7446                 }
7447         }
7448 
7449         return (1);
7450 }
7451 
7452 /*
7453  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7454  * consists of input pattern strings and an ops-vector to evaluate them.
7455  * This function returns >0 for match, 0 for no match, and <0 for error.
7456  */
7457 static int
7458 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7459     uint32_t priv, uid_t uid, zoneid_t zoneid)
7460 {
7461         dtrace_provider_t *pvp = prp->dtpr_provider;
7462         int rv;
7463 
7464         if (pvp->dtpv_defunct)
7465                 return (0);
7466 
7467         if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7468                 return (rv);
7469 
7470         if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7471                 return (rv);
7472 
7473         if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7474                 return (rv);
7475 
7476         if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7477                 return (rv);
7478 
7479         if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7480                 return (0);
7481 
7482         return (rv);
7483 }
7484 
7485 /*
7486  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7487  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
7488  * libc's version, the kernel version only applies to 8-bit ASCII strings.
7489  * In addition, all of the recursion cases except for '*' matching have been
7490  * unwound.  For '*', we still implement recursive evaluation, but a depth
7491  * counter is maintained and matching is aborted if we recurse too deep.
7492  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7493  */
7494 static int
7495 dtrace_match_glob(const char *s, const char *p, int depth)
7496 {
7497         const char *olds;
7498         char s1, c;
7499         int gs;
7500 
7501         if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7502                 return (-1);
7503 
7504         if (s == NULL)
7505                 s = ""; /* treat NULL as empty string */
7506 
7507 top:
7508         olds = s;
7509         s1 = *s++;
7510 
7511         if (p == NULL)
7512                 return (0);
7513 
7514         if ((c = *p++) == '\0')
7515                 return (s1 == '\0');
7516 
7517         switch (c) {
7518         case '[': {
7519                 int ok = 0, notflag = 0;
7520                 char lc = '\0';
7521 
7522                 if (s1 == '\0')
7523                         return (0);
7524 
7525                 if (*p == '!') {
7526                         notflag = 1;
7527                         p++;
7528                 }
7529 
7530                 if ((c = *p++) == '\0')
7531                         return (0);
7532 
7533                 do {
7534                         if (c == '-' && lc != '\0' && *p != ']') {
7535                                 if ((c = *p++) == '\0')
7536                                         return (0);
7537                                 if (c == '\\' && (c = *p++) == '\0')
7538                                         return (0);
7539 
7540                                 if (notflag) {
7541                                         if (s1 < lc || s1 > c)
7542                                                 ok++;
7543                                         else
7544                                                 return (0);
7545                                 } else if (lc <= s1 && s1 <= c)
7546                                         ok++;
7547 
7548                         } else if (c == '\\' && (c = *p++) == '\0')
7549                                 return (0);
7550 
7551                         lc = c; /* save left-hand 'c' for next iteration */
7552 
7553                         if (notflag) {
7554                                 if (s1 != c)
7555                                         ok++;
7556                                 else
7557                                         return (0);
7558                         } else if (s1 == c)
7559                                 ok++;
7560 
7561                         if ((c = *p++) == '\0')
7562                                 return (0);
7563 
7564                 } while (c != ']');
7565 
7566                 if (ok)
7567                         goto top;
7568 
7569                 return (0);
7570         }
7571 
7572         case '\\':
7573                 if ((c = *p++) == '\0')
7574                         return (0);
7575                 /*FALLTHRU*/
7576 
7577         default:
7578                 if (c != s1)
7579                         return (0);
7580                 /*FALLTHRU*/
7581 
7582         case '?':
7583                 if (s1 != '\0')
7584                         goto top;
7585                 return (0);
7586 
7587         case '*':
7588                 while (*p == '*')
7589                         p++; /* consecutive *'s are identical to a single one */
7590 
7591                 if (*p == '\0')
7592                         return (1);
7593 
7594                 for (s = olds; *s != '\0'; s++) {
7595                         if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7596                                 return (gs);
7597                 }
7598 
7599                 return (0);
7600         }
7601 }
7602 
7603 /*ARGSUSED*/
7604 static int
7605 dtrace_match_string(const char *s, const char *p, int depth)
7606 {
7607         return (s != NULL && strcmp(s, p) == 0);
7608 }
7609 
7610 /*ARGSUSED*/
7611 static int
7612 dtrace_match_nul(const char *s, const char *p, int depth)
7613 {
7614         return (1); /* always match the empty pattern */
7615 }
7616 
7617 /*ARGSUSED*/
7618 static int
7619 dtrace_match_nonzero(const char *s, const char *p, int depth)
7620 {
7621         return (s != NULL && s[0] != '\0');
7622 }
7623 
7624 static int
7625 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7626     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7627 {
7628         dtrace_probe_t template, *probe;
7629         dtrace_hash_t *hash = NULL;
7630         int len, rc, best = INT_MAX, nmatched = 0;
7631         dtrace_id_t i;
7632 
7633         ASSERT(MUTEX_HELD(&dtrace_lock));
7634 
7635         /*
7636          * If the probe ID is specified in the key, just lookup by ID and
7637          * invoke the match callback once if a matching probe is found.
7638          */
7639         if (pkp->dtpk_id != DTRACE_IDNONE) {
7640                 if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7641                     dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7642                         if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
7643                                 return (DTRACE_MATCH_FAIL);
7644                         nmatched++;
7645                 }
7646                 return (nmatched);
7647         }
7648 
7649         template.dtpr_mod = (char *)pkp->dtpk_mod;
7650         template.dtpr_func = (char *)pkp->dtpk_func;
7651         template.dtpr_name = (char *)pkp->dtpk_name;
7652 
7653         /*
7654          * We want to find the most distinct of the module name, function
7655          * name, and name.  So for each one that is not a glob pattern or
7656          * empty string, we perform a lookup in the corresponding hash and
7657          * use the hash table with the fewest collisions to do our search.
7658          */
7659         if (pkp->dtpk_mmatch == &dtrace_match_string &&
7660             (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7661                 best = len;
7662                 hash = dtrace_bymod;
7663         }
7664 
7665         if (pkp->dtpk_fmatch == &dtrace_match_string &&
7666             (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7667                 best = len;
7668                 hash = dtrace_byfunc;
7669         }
7670 
7671         if (pkp->dtpk_nmatch == &dtrace_match_string &&
7672             (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7673                 best = len;
7674                 hash = dtrace_byname;
7675         }
7676 
7677         /*
7678          * If we did not select a hash table, iterate over every probe and
7679          * invoke our callback for each one that matches our input probe key.
7680          */
7681         if (hash == NULL) {
7682                 for (i = 0; i < dtrace_nprobes; i++) {
7683                         if ((probe = dtrace_probes[i]) == NULL ||
7684                             dtrace_match_probe(probe, pkp, priv, uid,
7685                             zoneid) <= 0)
7686                                 continue;
7687 
7688                         nmatched++;
7689 
7690                         if ((rc = (*matched)(probe, arg)) !=
7691                             DTRACE_MATCH_NEXT) {
7692                                 if (rc == DTRACE_MATCH_FAIL)
7693                                         return (DTRACE_MATCH_FAIL);
7694                                 break;
7695                         }
7696                 }
7697 
7698                 return (nmatched);
7699         }
7700 
7701         /*
7702          * If we selected a hash table, iterate over each probe of the same key
7703          * name and invoke the callback for every probe that matches the other
7704          * attributes of our input probe key.
7705          */
7706         for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7707             probe = *(DTRACE_HASHNEXT(hash, probe))) {
7708 
7709                 if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7710                         continue;
7711 
7712                 nmatched++;
7713 
7714                 if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7715                         if (rc == DTRACE_MATCH_FAIL)
7716                                 return (DTRACE_MATCH_FAIL);
7717                         break;
7718                 }
7719         }
7720 
7721         return (nmatched);
7722 }
7723 
7724 /*
7725  * Return the function pointer dtrace_probecmp() should use to compare the
7726  * specified pattern with a string.  For NULL or empty patterns, we select
7727  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
7728  * For non-empty non-glob strings, we use dtrace_match_string().
7729  */
7730 static dtrace_probekey_f *
7731 dtrace_probekey_func(const char *p)
7732 {
7733         char c;
7734 
7735         if (p == NULL || *p == '\0')
7736                 return (&dtrace_match_nul);
7737 
7738         while ((c = *p++) != '\0') {
7739                 if (c == '[' || c == '?' || c == '*' || c == '\\')
7740                         return (&dtrace_match_glob);
7741         }
7742 
7743         return (&dtrace_match_string);
7744 }
7745 
7746 /*
7747  * Build a probe comparison key for use with dtrace_match_probe() from the
7748  * given probe description.  By convention, a null key only matches anchored
7749  * probes: if each field is the empty string, reset dtpk_fmatch to
7750  * dtrace_match_nonzero().
7751  */
7752 static void
7753 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7754 {
7755         pkp->dtpk_prov = pdp->dtpd_provider;
7756         pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7757 
7758         pkp->dtpk_mod = pdp->dtpd_mod;
7759         pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7760 
7761         pkp->dtpk_func = pdp->dtpd_func;
7762         pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7763 
7764         pkp->dtpk_name = pdp->dtpd_name;
7765         pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7766 
7767         pkp->dtpk_id = pdp->dtpd_id;
7768 
7769         if (pkp->dtpk_id == DTRACE_IDNONE &&
7770             pkp->dtpk_pmatch == &dtrace_match_nul &&
7771             pkp->dtpk_mmatch == &dtrace_match_nul &&
7772             pkp->dtpk_fmatch == &dtrace_match_nul &&
7773             pkp->dtpk_nmatch == &dtrace_match_nul)
7774                 pkp->dtpk_fmatch = &dtrace_match_nonzero;
7775 }
7776 
7777 /*
7778  * DTrace Provider-to-Framework API Functions
7779  *
7780  * These functions implement much of the Provider-to-Framework API, as
7781  * described in <sys/dtrace.h>.  The parts of the API not in this section are
7782  * the functions in the API for probe management (found below), and
7783  * dtrace_probe() itself (found above).
7784  */
7785 
7786 /*
7787  * Register the calling provider with the DTrace framework.  This should
7788  * generally be called by DTrace providers in their attach(9E) entry point.
7789  */
7790 int
7791 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7792     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7793 {
7794         dtrace_provider_t *provider;
7795 
7796         if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7797                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7798                     "arguments", name ? name : "<NULL>");
7799                 return (EINVAL);
7800         }
7801 
7802         if (name[0] == '\0' || dtrace_badname(name)) {
7803                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7804                     "provider name", name);
7805                 return (EINVAL);
7806         }
7807 
7808         if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7809             pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7810             pops->dtps_destroy == NULL ||
7811             ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7812                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7813                     "provider ops", name);
7814                 return (EINVAL);
7815         }
7816 
7817         if (dtrace_badattr(&pap->dtpa_provider) ||
7818             dtrace_badattr(&pap->dtpa_mod) ||
7819             dtrace_badattr(&pap->dtpa_func) ||
7820             dtrace_badattr(&pap->dtpa_name) ||
7821             dtrace_badattr(&pap->dtpa_args)) {
7822                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7823                     "provider attributes", name);
7824                 return (EINVAL);
7825         }
7826 
7827         if (priv & ~DTRACE_PRIV_ALL) {
7828                 cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7829                     "privilege attributes", name);
7830                 return (EINVAL);
7831         }
7832 
7833         if ((priv & DTRACE_PRIV_KERNEL) &&
7834             (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7835             pops->dtps_mode == NULL) {
7836                 cmn_err(CE_WARN, "failed to register provider '%s': need "
7837                     "dtps_mode() op for given privilege attributes", name);
7838                 return (EINVAL);
7839         }
7840 
7841         provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7842         provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7843         (void) strcpy(provider->dtpv_name, name);
7844 
7845         provider->dtpv_attr = *pap;
7846         provider->dtpv_priv.dtpp_flags = priv;
7847         if (cr != NULL) {
7848                 provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7849                 provider->dtpv_priv.dtpp_zoneid = crgetzonedid(cr);
7850         }
7851         provider->dtpv_pops = *pops;
7852 
7853         if (pops->dtps_provide == NULL) {
7854                 ASSERT(pops->dtps_provide_module != NULL);
7855                 provider->dtpv_pops.dtps_provide =
7856                     (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
7857         }
7858 
7859         if (pops->dtps_provide_module == NULL) {
7860                 ASSERT(pops->dtps_provide != NULL);
7861                 provider->dtpv_pops.dtps_provide_module =
7862                     (void (*)(void *, struct modctl *))dtrace_nullop;
7863         }
7864 
7865         if (pops->dtps_suspend == NULL) {
7866                 ASSERT(pops->dtps_resume == NULL);
7867                 provider->dtpv_pops.dtps_suspend =
7868                     (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7869                 provider->dtpv_pops.dtps_resume =
7870                     (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7871         }
7872 
7873         provider->dtpv_arg = arg;
7874         *idp = (dtrace_provider_id_t)provider;
7875 
7876         if (pops == &dtrace_provider_ops) {
7877                 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7878                 ASSERT(MUTEX_HELD(&dtrace_lock));
7879                 ASSERT(dtrace_anon.dta_enabling == NULL);
7880 
7881                 /*
7882                  * We make sure that the DTrace provider is at the head of
7883                  * the provider chain.
7884                  */
7885                 provider->dtpv_next = dtrace_provider;
7886                 dtrace_provider = provider;
7887                 return (0);
7888         }
7889 
7890         mutex_enter(&dtrace_provider_lock);
7891         mutex_enter(&dtrace_lock);
7892 
7893         /*
7894          * If there is at least one provider registered, we'll add this
7895          * provider after the first provider.
7896          */
7897         if (dtrace_provider != NULL) {
7898                 provider->dtpv_next = dtrace_provider->dtpv_next;
7899                 dtrace_provider->dtpv_next = provider;
7900         } else {
7901                 dtrace_provider = provider;
7902         }
7903 
7904         if (dtrace_retained != NULL) {
7905                 dtrace_enabling_provide(provider);
7906 
7907                 /*
7908                  * Now we need to call dtrace_enabling_matchall() -- which
7909                  * will acquire cpu_lock and dtrace_lock.  We therefore need
7910                  * to drop all of our locks before calling into it...
7911                  */
7912                 mutex_exit(&dtrace_lock);
7913                 mutex_exit(&dtrace_provider_lock);
7914                 dtrace_enabling_matchall();
7915 
7916                 return (0);
7917         }
7918 
7919         mutex_exit(&dtrace_lock);
7920         mutex_exit(&dtrace_provider_lock);
7921 
7922         return (0);
7923 }
7924 
7925 /*
7926  * Unregister the specified provider from the DTrace framework.  This should
7927  * generally be called by DTrace providers in their detach(9E) entry point.
7928  */
7929 int
7930 dtrace_unregister(dtrace_provider_id_t id)
7931 {
7932         dtrace_provider_t *old = (dtrace_provider_t *)id;
7933         dtrace_provider_t *prev = NULL;
7934         int i, self = 0, noreap = 0;
7935         dtrace_probe_t *probe, *first = NULL;
7936 
7937         if (old->dtpv_pops.dtps_enable ==
7938             (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
7939                 /*
7940                  * If DTrace itself is the provider, we're called with locks
7941                  * already held.
7942                  */
7943                 ASSERT(old == dtrace_provider);
7944                 ASSERT(dtrace_devi != NULL);
7945                 ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7946                 ASSERT(MUTEX_HELD(&dtrace_lock));
7947                 self = 1;
7948 
7949                 if (dtrace_provider->dtpv_next != NULL) {
7950                         /*
7951                          * There's another provider here; return failure.
7952                          */
7953                         return (EBUSY);
7954                 }
7955         } else {
7956                 mutex_enter(&dtrace_provider_lock);
7957                 mutex_enter(&mod_lock);
7958                 mutex_enter(&dtrace_lock);
7959         }
7960 
7961         /*
7962          * If anyone has /dev/dtrace open, or if there are anonymous enabled
7963          * probes, we refuse to let providers slither away, unless this
7964          * provider has already been explicitly invalidated.
7965          */
7966         if (!old->dtpv_defunct &&
7967             (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7968             dtrace_anon.dta_state->dts_necbs > 0))) {
7969                 if (!self) {
7970                         mutex_exit(&dtrace_lock);
7971                         mutex_exit(&mod_lock);
7972                         mutex_exit(&dtrace_provider_lock);
7973                 }
7974                 return (EBUSY);
7975         }
7976 
7977         /*
7978          * Attempt to destroy the probes associated with this provider.
7979          */
7980         for (i = 0; i < dtrace_nprobes; i++) {
7981                 if ((probe = dtrace_probes[i]) == NULL)
7982                         continue;
7983 
7984                 if (probe->dtpr_provider != old)
7985                         continue;
7986 
7987                 if (probe->dtpr_ecb == NULL)
7988                         continue;
7989 
7990                 /*
7991                  * If we are trying to unregister a defunct provider, and the
7992                  * provider was made defunct within the interval dictated by
7993                  * dtrace_unregister_defunct_reap, we'll (asynchronously)
7994                  * attempt to reap our enablings.  To denote that the provider
7995                  * should reattempt to unregister itself at some point in the
7996                  * future, we will return a differentiable error code (EAGAIN
7997                  * instead of EBUSY) in this case.
7998                  */
7999                 if (dtrace_gethrtime() - old->dtpv_defunct >
8000                     dtrace_unregister_defunct_reap)
8001                         noreap = 1;
8002 
8003                 if (!self) {
8004                         mutex_exit(&dtrace_lock);
8005                         mutex_exit(&mod_lock);
8006                         mutex_exit(&dtrace_provider_lock);
8007                 }
8008 
8009                 if (noreap)
8010                         return (EBUSY);
8011 
8012                 (void) taskq_dispatch(dtrace_taskq,
8013                     (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8014 
8015                 return (EAGAIN);
8016         }
8017 
8018         /*
8019          * All of the probes for this provider are disabled; we can safely
8020          * remove all of them from their hash chains and from the probe array.
8021          */
8022         for (i = 0; i < dtrace_nprobes; i++) {
8023                 if ((probe = dtrace_probes[i]) == NULL)
8024                         continue;
8025 
8026                 if (probe->dtpr_provider != old)
8027                         continue;
8028 
8029                 dtrace_probes[i] = NULL;
8030 
8031                 dtrace_hash_remove(dtrace_bymod, probe);
8032                 dtrace_hash_remove(dtrace_byfunc, probe);
8033                 dtrace_hash_remove(dtrace_byname, probe);
8034 
8035                 if (first == NULL) {
8036                         first = probe;
8037                         probe->dtpr_nextmod = NULL;
8038                 } else {
8039                         probe->dtpr_nextmod = first;
8040                         first = probe;
8041                 }
8042         }
8043 
8044         /*
8045          * The provider's probes have been removed from the hash chains and
8046          * from the probe array.  Now issue a dtrace_sync() to be sure that
8047          * everyone has cleared out from any probe array processing.
8048          */
8049         dtrace_sync();
8050 
8051         for (probe = first; probe != NULL; probe = first) {
8052                 first = probe->dtpr_nextmod;
8053 
8054                 old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8055                     probe->dtpr_arg);
8056                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8057                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8058                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8059                 vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8060                 kmem_free(probe, sizeof (dtrace_probe_t));
8061         }
8062 
8063         if ((prev = dtrace_provider) == old) {
8064                 ASSERT(self || dtrace_devi == NULL);
8065                 ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8066                 dtrace_provider = old->dtpv_next;
8067         } else {
8068                 while (prev != NULL && prev->dtpv_next != old)
8069                         prev = prev->dtpv_next;
8070 
8071                 if (prev == NULL) {
8072                         panic("attempt to unregister non-existent "
8073                             "dtrace provider %p\n", (void *)id);
8074                 }
8075 
8076                 prev->dtpv_next = old->dtpv_next;
8077         }
8078 
8079         if (!self) {
8080                 mutex_exit(&dtrace_lock);
8081                 mutex_exit(&mod_lock);
8082                 mutex_exit(&dtrace_provider_lock);
8083         }
8084 
8085         kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8086         kmem_free(old, sizeof (dtrace_provider_t));
8087 
8088         return (0);
8089 }
8090 
8091 /*
8092  * Invalidate the specified provider.  All subsequent probe lookups for the
8093  * specified provider will fail, but its probes will not be removed.
8094  */
8095 void
8096 dtrace_invalidate(dtrace_provider_id_t id)
8097 {
8098         dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8099 
8100         ASSERT(pvp->dtpv_pops.dtps_enable !=
8101             (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8102 
8103         mutex_enter(&dtrace_provider_lock);
8104         mutex_enter(&dtrace_lock);
8105 
8106         pvp->dtpv_defunct = dtrace_gethrtime();
8107 
8108         mutex_exit(&dtrace_lock);
8109         mutex_exit(&dtrace_provider_lock);
8110 }
8111 
8112 /*
8113  * Indicate whether or not DTrace has attached.
8114  */
8115 int
8116 dtrace_attached(void)
8117 {
8118         /*
8119          * dtrace_provider will be non-NULL iff the DTrace driver has
8120          * attached.  (It's non-NULL because DTrace is always itself a
8121          * provider.)
8122          */
8123         return (dtrace_provider != NULL);
8124 }
8125 
8126 /*
8127  * Remove all the unenabled probes for the given provider.  This function is
8128  * not unlike dtrace_unregister(), except that it doesn't remove the provider
8129  * -- just as many of its associated probes as it can.
8130  */
8131 int
8132 dtrace_condense(dtrace_provider_id_t id)
8133 {
8134         dtrace_provider_t *prov = (dtrace_provider_t *)id;
8135         int i;
8136         dtrace_probe_t *probe;
8137 
8138         /*
8139          * Make sure this isn't the dtrace provider itself.
8140          */
8141         ASSERT(prov->dtpv_pops.dtps_enable !=
8142             (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8143 
8144         mutex_enter(&dtrace_provider_lock);
8145         mutex_enter(&dtrace_lock);
8146 
8147         /*
8148          * Attempt to destroy the probes associated with this provider.
8149          */
8150         for (i = 0; i < dtrace_nprobes; i++) {
8151                 if ((probe = dtrace_probes[i]) == NULL)
8152                         continue;
8153 
8154                 if (probe->dtpr_provider != prov)
8155                         continue;
8156 
8157                 if (probe->dtpr_ecb != NULL)
8158                         continue;
8159 
8160                 dtrace_probes[i] = NULL;
8161 
8162                 dtrace_hash_remove(dtrace_bymod, probe);
8163                 dtrace_hash_remove(dtrace_byfunc, probe);
8164                 dtrace_hash_remove(dtrace_byname, probe);
8165 
8166                 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8167                     probe->dtpr_arg);
8168                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8169                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8170                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8171                 kmem_free(probe, sizeof (dtrace_probe_t));
8172                 vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8173         }
8174 
8175         mutex_exit(&dtrace_lock);
8176         mutex_exit(&dtrace_provider_lock);
8177 
8178         return (0);
8179 }
8180 
8181 /*
8182  * DTrace Probe Management Functions
8183  *
8184  * The functions in this section perform the DTrace probe management,
8185  * including functions to create probes, look-up probes, and call into the
8186  * providers to request that probes be provided.  Some of these functions are
8187  * in the Provider-to-Framework API; these functions can be identified by the
8188  * fact that they are not declared "static".
8189  */
8190 
8191 /*
8192  * Create a probe with the specified module name, function name, and name.
8193  */
8194 dtrace_id_t
8195 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8196     const char *func, const char *name, int aframes, void *arg)
8197 {
8198         dtrace_probe_t *probe, **probes;
8199         dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8200         dtrace_id_t id;
8201 
8202         if (provider == dtrace_provider) {
8203                 ASSERT(MUTEX_HELD(&dtrace_lock));
8204         } else {
8205                 mutex_enter(&dtrace_lock);
8206         }
8207 
8208         id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8209             VM_BESTFIT | VM_SLEEP);
8210         probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8211 
8212         probe->dtpr_id = id;
8213         probe->dtpr_gen = dtrace_probegen++;
8214         probe->dtpr_mod = dtrace_strdup(mod);
8215         probe->dtpr_func = dtrace_strdup(func);
8216         probe->dtpr_name = dtrace_strdup(name);
8217         probe->dtpr_arg = arg;
8218         probe->dtpr_aframes = aframes;
8219         probe->dtpr_provider = provider;
8220 
8221         dtrace_hash_add(dtrace_bymod, probe);
8222         dtrace_hash_add(dtrace_byfunc, probe);
8223         dtrace_hash_add(dtrace_byname, probe);
8224 
8225         if (id - 1 >= dtrace_nprobes) {
8226                 size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8227                 size_t nsize = osize << 1;
8228 
8229                 if (nsize == 0) {
8230                         ASSERT(osize == 0);
8231                         ASSERT(dtrace_probes == NULL);
8232                         nsize = sizeof (dtrace_probe_t *);
8233                 }
8234 
8235                 probes = kmem_zalloc(nsize, KM_SLEEP);
8236 
8237                 if (dtrace_probes == NULL) {
8238                         ASSERT(osize == 0);
8239                         dtrace_probes = probes;
8240                         dtrace_nprobes = 1;
8241                 } else {
8242                         dtrace_probe_t **oprobes = dtrace_probes;
8243 
8244                         bcopy(oprobes, probes, osize);
8245                         dtrace_membar_producer();
8246                         dtrace_probes = probes;
8247 
8248                         dtrace_sync();
8249 
8250                         /*
8251                          * All CPUs are now seeing the new probes array; we can
8252                          * safely free the old array.
8253                          */
8254                         kmem_free(oprobes, osize);
8255                         dtrace_nprobes <<= 1;
8256                 }
8257 
8258                 ASSERT(id - 1 < dtrace_nprobes);
8259         }
8260 
8261         ASSERT(dtrace_probes[id - 1] == NULL);
8262         dtrace_probes[id - 1] = probe;
8263 
8264         if (provider != dtrace_provider)
8265                 mutex_exit(&dtrace_lock);
8266 
8267         return (id);
8268 }
8269 
8270 static dtrace_probe_t *
8271 dtrace_probe_lookup_id(dtrace_id_t id)
8272 {
8273         ASSERT(MUTEX_HELD(&dtrace_lock));
8274 
8275         if (id == 0 || id > dtrace_nprobes)
8276                 return (NULL);
8277 
8278         return (dtrace_probes[id - 1]);
8279 }
8280 
8281 static int
8282 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8283 {
8284         *((dtrace_id_t *)arg) = probe->dtpr_id;
8285 
8286         return (DTRACE_MATCH_DONE);
8287 }
8288 
8289 /*
8290  * Look up a probe based on provider and one or more of module name, function
8291  * name and probe name.
8292  */
8293 dtrace_id_t
8294 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
8295     const char *func, const char *name)
8296 {
8297         dtrace_probekey_t pkey;
8298         dtrace_id_t id;
8299         int match;
8300 
8301         pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8302         pkey.dtpk_pmatch = &dtrace_match_string;
8303         pkey.dtpk_mod = mod;
8304         pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8305         pkey.dtpk_func = func;
8306         pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8307         pkey.dtpk_name = name;
8308         pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8309         pkey.dtpk_id = DTRACE_IDNONE;
8310 
8311         mutex_enter(&dtrace_lock);
8312         match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8313             dtrace_probe_lookup_match, &id);
8314         mutex_exit(&dtrace_lock);
8315 
8316         ASSERT(match == 1 || match == 0);
8317         return (match ? id : 0);
8318 }
8319 
8320 /*
8321  * Returns the probe argument associated with the specified probe.
8322  */
8323 void *
8324 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8325 {
8326         dtrace_probe_t *probe;
8327         void *rval = NULL;
8328 
8329         mutex_enter(&dtrace_lock);
8330 
8331         if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8332             probe->dtpr_provider == (dtrace_provider_t *)id)
8333                 rval = probe->dtpr_arg;
8334 
8335         mutex_exit(&dtrace_lock);
8336 
8337         return (rval);
8338 }
8339 
8340 /*
8341  * Copy a probe into a probe description.
8342  */
8343 static void
8344 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8345 {
8346         bzero(pdp, sizeof (dtrace_probedesc_t));
8347         pdp->dtpd_id = prp->dtpr_id;
8348 
8349         (void) strncpy(pdp->dtpd_provider,
8350             prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8351 
8352         (void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8353         (void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8354         (void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8355 }
8356 
8357 /*
8358  * Called to indicate that a probe -- or probes -- should be provided by a
8359  * specfied provider.  If the specified description is NULL, the provider will
8360  * be told to provide all of its probes.  (This is done whenever a new
8361  * consumer comes along, or whenever a retained enabling is to be matched.) If
8362  * the specified description is non-NULL, the provider is given the
8363  * opportunity to dynamically provide the specified probe, allowing providers
8364  * to support the creation of probes on-the-fly.  (So-called _autocreated_
8365  * probes.)  If the provider is NULL, the operations will be applied to all
8366  * providers; if the provider is non-NULL the operations will only be applied
8367  * to the specified provider.  The dtrace_provider_lock must be held, and the
8368  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8369  * will need to grab the dtrace_lock when it reenters the framework through
8370  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8371  */
8372 static void
8373 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8374 {
8375         struct modctl *ctl;
8376         int all = 0;
8377 
8378         ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8379 
8380         if (prv == NULL) {
8381                 all = 1;
8382                 prv = dtrace_provider;
8383         }
8384 
8385         do {
8386                 /*
8387                  * First, call the blanket provide operation.
8388                  */
8389                 prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8390 
8391                 /*
8392                  * Now call the per-module provide operation.  We will grab
8393                  * mod_lock to prevent the list from being modified.  Note
8394                  * that this also prevents the mod_busy bits from changing.
8395                  * (mod_busy can only be changed with mod_lock held.)
8396                  */
8397                 mutex_enter(&mod_lock);
8398 
8399                 ctl = &modules;
8400                 do {
8401                         if (ctl->mod_busy || ctl->mod_mp == NULL)
8402                                 continue;
8403 
8404                         prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8405 
8406                 } while ((ctl = ctl->mod_next) != &modules);
8407 
8408                 mutex_exit(&mod_lock);
8409         } while (all && (prv = prv->dtpv_next) != NULL);
8410 }
8411 
8412 /*
8413  * Iterate over each probe, and call the Framework-to-Provider API function
8414  * denoted by offs.
8415  */
8416 static void
8417 dtrace_probe_foreach(uintptr_t offs)
8418 {
8419         dtrace_provider_t *prov;
8420         void (*func)(void *, dtrace_id_t, void *);
8421         dtrace_probe_t *probe;
8422         dtrace_icookie_t cookie;
8423         int i;
8424 
8425         /*
8426          * We disable interrupts to walk through the probe array.  This is
8427          * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8428          * won't see stale data.
8429          */
8430         cookie = dtrace_interrupt_disable();
8431 
8432         for (i = 0; i < dtrace_nprobes; i++) {
8433                 if ((probe = dtrace_probes[i]) == NULL)
8434                         continue;
8435 
8436                 if (probe->dtpr_ecb == NULL) {
8437                         /*
8438                          * This probe isn't enabled -- don't call the function.
8439                          */
8440                         continue;
8441                 }
8442 
8443                 prov = probe->dtpr_provider;
8444                 func = *((void(**)(void *, dtrace_id_t, void *))
8445                     ((uintptr_t)&prov->dtpv_pops + offs));
8446 
8447                 func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8448         }
8449 
8450         dtrace_interrupt_enable(cookie);
8451 }
8452 
8453 static int
8454 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8455 {
8456         dtrace_probekey_t pkey;
8457         uint32_t priv;
8458         uid_t uid;
8459         zoneid_t zoneid;
8460         dtrace_state_t *state = enab->dten_vstate->dtvs_state;
8461 
8462         ASSERT(MUTEX_HELD(&dtrace_lock));
8463         dtrace_ecb_create_cache = NULL;
8464 
8465         if (desc == NULL) {
8466                 /*
8467                  * If we're passed a NULL description, we're being asked to
8468                  * create an ECB with a NULL probe.
8469                  */
8470                 (void) dtrace_ecb_create_enable(NULL, enab);
8471                 return (0);
8472         }
8473 
8474         dtrace_probekey(desc, &pkey);
8475         dtrace_cred2priv(state->dts_cred.dcr_cred, &priv, &uid, &zoneid);
8476 
8477         if ((priv & DTRACE_PRIV_ZONEOWNER) &&
8478             state->dts_options[DTRACEOPT_ZONE] != DTRACEOPT_UNSET) {
8479                 /*
8480                  * If we have the privilege of instrumenting all zones but we
8481                  * have been told to instrument but one, we will spoof this up
8482                  * depriving ourselves of DTRACE_PRIV_ZONEOWNER for purposes
8483                  * of dtrace_match().  (Note that DTRACEOPT_ZONE is not for
8484                  * security but rather for performance: it allows the global
8485                  * zone to instrument USDT probes in a local zone without
8486                  * requiring all zones to be instrumented.)
8487                  */
8488                 priv &= ~DTRACE_PRIV_ZONEOWNER;
8489                 zoneid = state->dts_options[DTRACEOPT_ZONE];
8490         }
8491 
8492         return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8493             enab));
8494 }
8495 
8496 /*
8497  * DTrace Helper Provider Functions
8498  */
8499 static void
8500 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8501 {
8502         attr->dtat_name = DOF_ATTR_NAME(dofattr);
8503         attr->dtat_data = DOF_ATTR_DATA(dofattr);
8504         attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8505 }
8506 
8507 static void
8508 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8509     const dof_provider_t *dofprov, char *strtab)
8510 {
8511         hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8512         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8513             dofprov->dofpv_provattr);
8514         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8515             dofprov->dofpv_modattr);
8516         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8517             dofprov->dofpv_funcattr);
8518         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8519             dofprov->dofpv_nameattr);
8520         dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8521             dofprov->dofpv_argsattr);
8522 }
8523 
8524 static void
8525 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8526 {
8527         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8528         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8529         dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8530         dof_provider_t *provider;
8531         dof_probe_t *probe;
8532         uint32_t *off, *enoff;
8533         uint8_t *arg;
8534         char *strtab;
8535         uint_t i, nprobes;
8536         dtrace_helper_provdesc_t dhpv;
8537         dtrace_helper_probedesc_t dhpb;
8538         dtrace_meta_t *meta = dtrace_meta_pid;
8539         dtrace_mops_t *mops = &meta->dtm_mops;
8540         void *parg;
8541 
8542         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8543         str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8544             provider->dofpv_strtab * dof->dofh_secsize);
8545         prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8546             provider->dofpv_probes * dof->dofh_secsize);
8547         arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8548             provider->dofpv_prargs * dof->dofh_secsize);
8549         off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8550             provider->dofpv_proffs * dof->dofh_secsize);
8551 
8552         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8553         off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8554         arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8555         enoff = NULL;
8556 
8557         /*
8558          * See dtrace_helper_provider_validate().
8559          */
8560         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8561             provider->dofpv_prenoffs != DOF_SECT_NONE) {
8562                 enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8563                     provider->dofpv_prenoffs * dof->dofh_secsize);
8564                 enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8565         }
8566 
8567         nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8568 
8569         /*
8570          * Create the provider.
8571          */
8572         dtrace_dofprov2hprov(&dhpv, provider, strtab);
8573 
8574         if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8575                 return;
8576 
8577         meta->dtm_count++;
8578 
8579         /*
8580          * Create the probes.
8581          */
8582         for (i = 0; i < nprobes; i++) {
8583                 probe = (dof_probe_t *)(uintptr_t)(daddr +
8584                     prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8585 
8586                 dhpb.dthpb_mod = dhp->dofhp_mod;
8587                 dhpb.dthpb_func = strtab + probe->dofpr_func;
8588                 dhpb.dthpb_name = strtab + probe->dofpr_name;
8589                 dhpb.dthpb_base = probe->dofpr_addr;
8590                 dhpb.dthpb_offs = off + probe->dofpr_offidx;
8591                 dhpb.dthpb_noffs = probe->dofpr_noffs;
8592                 if (enoff != NULL) {
8593                         dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8594                         dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8595                 } else {
8596                         dhpb.dthpb_enoffs = NULL;
8597                         dhpb.dthpb_nenoffs = 0;
8598                 }
8599                 dhpb.dthpb_args = arg + probe->dofpr_argidx;
8600                 dhpb.dthpb_nargc = probe->dofpr_nargc;
8601                 dhpb.dthpb_xargc = probe->dofpr_xargc;
8602                 dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8603                 dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8604 
8605                 mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8606         }
8607 }
8608 
8609 static void
8610 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8611 {
8612         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8613         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8614         int i;
8615 
8616         ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8617 
8618         for (i = 0; i < dof->dofh_secnum; i++) {
8619                 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8620                     dof->dofh_secoff + i * dof->dofh_secsize);
8621 
8622                 if (sec->dofs_type != DOF_SECT_PROVIDER)
8623                         continue;
8624 
8625                 dtrace_helper_provide_one(dhp, sec, pid);
8626         }
8627 
8628         /*
8629          * We may have just created probes, so we must now rematch against
8630          * any retained enablings.  Note that this call will acquire both
8631          * cpu_lock and dtrace_lock; the fact that we are holding
8632          * dtrace_meta_lock now is what defines the ordering with respect to
8633          * these three locks.
8634          */
8635         dtrace_enabling_matchall();
8636 }
8637 
8638 static void
8639 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8640 {
8641         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8642         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8643         dof_sec_t *str_sec;
8644         dof_provider_t *provider;
8645         char *strtab;
8646         dtrace_helper_provdesc_t dhpv;
8647         dtrace_meta_t *meta = dtrace_meta_pid;
8648         dtrace_mops_t *mops = &meta->dtm_mops;
8649 
8650         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8651         str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8652             provider->dofpv_strtab * dof->dofh_secsize);
8653 
8654         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8655 
8656         /*
8657          * Create the provider.
8658          */
8659         dtrace_dofprov2hprov(&dhpv, provider, strtab);
8660 
8661         mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8662 
8663         meta->dtm_count--;
8664 }
8665 
8666 static void
8667 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8668 {
8669         uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8670         dof_hdr_t *dof = (dof_hdr_t *)daddr;
8671         int i;
8672 
8673         ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8674 
8675         for (i = 0; i < dof->dofh_secnum; i++) {
8676                 dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8677                     dof->dofh_secoff + i * dof->dofh_secsize);
8678 
8679                 if (sec->dofs_type != DOF_SECT_PROVIDER)
8680                         continue;
8681 
8682                 dtrace_helper_provider_remove_one(dhp, sec, pid);
8683         }
8684 }
8685 
8686 /*
8687  * DTrace Meta Provider-to-Framework API Functions
8688  *
8689  * These functions implement the Meta Provider-to-Framework API, as described
8690  * in <sys/dtrace.h>.
8691  */
8692 int
8693 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8694     dtrace_meta_provider_id_t *idp)
8695 {
8696         dtrace_meta_t *meta;
8697         dtrace_helpers_t *help, *next;
8698         int i;
8699 
8700         *idp = DTRACE_METAPROVNONE;
8701 
8702         /*
8703          * We strictly don't need the name, but we hold onto it for
8704          * debuggability. All hail error queues!
8705          */
8706         if (name == NULL) {
8707                 cmn_err(CE_WARN, "failed to register meta-provider: "
8708                     "invalid name");
8709                 return (EINVAL);
8710         }
8711 
8712         if (mops == NULL ||
8713             mops->dtms_create_probe == NULL ||
8714             mops->dtms_provide_pid == NULL ||
8715             mops->dtms_remove_pid == NULL) {
8716                 cmn_err(CE_WARN, "failed to register meta-register %s: "
8717                     "invalid ops", name);
8718                 return (EINVAL);
8719         }
8720 
8721         meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8722         meta->dtm_mops = *mops;
8723         meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8724         (void) strcpy(meta->dtm_name, name);
8725         meta->dtm_arg = arg;
8726 
8727         mutex_enter(&dtrace_meta_lock);
8728         mutex_enter(&dtrace_lock);
8729 
8730         if (dtrace_meta_pid != NULL) {
8731                 mutex_exit(&dtrace_lock);
8732                 mutex_exit(&dtrace_meta_lock);
8733                 cmn_err(CE_WARN, "failed to register meta-register %s: "
8734                     "user-land meta-provider exists", name);
8735                 kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8736                 kmem_free(meta, sizeof (dtrace_meta_t));
8737                 return (EINVAL);
8738         }
8739 
8740         dtrace_meta_pid = meta;
8741         *idp = (dtrace_meta_provider_id_t)meta;
8742 
8743         /*
8744          * If there are providers and probes ready to go, pass them
8745          * off to the new meta provider now.
8746          */
8747 
8748         help = dtrace_deferred_pid;
8749         dtrace_deferred_pid = NULL;
8750 
8751         mutex_exit(&dtrace_lock);
8752 
8753         while (help != NULL) {
8754                 for (i = 0; i < help->dthps_nprovs; i++) {
8755                         dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8756                             help->dthps_pid);
8757                 }
8758 
8759                 next = help->dthps_next;
8760                 help->dthps_next = NULL;
8761                 help->dthps_prev = NULL;
8762                 help->dthps_deferred = 0;
8763                 help = next;
8764         }
8765 
8766         mutex_exit(&dtrace_meta_lock);
8767 
8768         return (0);
8769 }
8770 
8771 int
8772 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8773 {
8774         dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8775 
8776         mutex_enter(&dtrace_meta_lock);
8777         mutex_enter(&dtrace_lock);
8778 
8779         if (old == dtrace_meta_pid) {
8780                 pp = &dtrace_meta_pid;
8781         } else {
8782                 panic("attempt to unregister non-existent "
8783                     "dtrace meta-provider %p\n", (void *)old);
8784         }
8785 
8786         if (old->dtm_count != 0) {
8787                 mutex_exit(&dtrace_lock);
8788                 mutex_exit(&dtrace_meta_lock);
8789                 return (EBUSY);
8790         }
8791 
8792         *pp = NULL;
8793 
8794         mutex_exit(&dtrace_lock);
8795         mutex_exit(&dtrace_meta_lock);
8796 
8797         kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8798         kmem_free(old, sizeof (dtrace_meta_t));
8799 
8800         return (0);
8801 }
8802 
8803 
8804 /*
8805  * DTrace DIF Object Functions
8806  */
8807 static int
8808 dtrace_difo_err(uint_t pc, const char *format, ...)
8809 {
8810         if (dtrace_err_verbose) {
8811                 va_list alist;
8812 
8813                 (void) uprintf("dtrace DIF object error: [%u]: ", pc);
8814                 va_start(alist, format);
8815                 (void) vuprintf(format, alist);
8816                 va_end(alist);
8817         }
8818 
8819 #ifdef DTRACE_ERRDEBUG
8820         dtrace_errdebug(format);
8821 #endif
8822         return (1);
8823 }
8824 
8825 /*
8826  * Validate a DTrace DIF object by checking the IR instructions.  The following
8827  * rules are currently enforced by dtrace_difo_validate():
8828  *
8829  * 1. Each instruction must have a valid opcode
8830  * 2. Each register, string, variable, or subroutine reference must be valid
8831  * 3. No instruction can modify register %r0 (must be zero)
8832  * 4. All instruction reserved bits must be set to zero
8833  * 5. The last instruction must be a "ret" instruction
8834  * 6. All branch targets must reference a valid instruction _after_ the branch
8835  */
8836 static int
8837 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8838     cred_t *cr)
8839 {
8840         int err = 0, i;
8841         int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8842         int kcheckload;
8843         uint_t pc;
8844 
8845         kcheckload = cr == NULL ||
8846             (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8847 
8848         dp->dtdo_destructive = 0;
8849 
8850         for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8851                 dif_instr_t instr = dp->dtdo_buf[pc];
8852 
8853                 uint_t r1 = DIF_INSTR_R1(instr);
8854                 uint_t r2 = DIF_INSTR_R2(instr);
8855                 uint_t rd = DIF_INSTR_RD(instr);
8856                 uint_t rs = DIF_INSTR_RS(instr);
8857                 uint_t label = DIF_INSTR_LABEL(instr);
8858                 uint_t v = DIF_INSTR_VAR(instr);
8859                 uint_t subr = DIF_INSTR_SUBR(instr);
8860                 uint_t type = DIF_INSTR_TYPE(instr);
8861                 uint_t op = DIF_INSTR_OP(instr);
8862 
8863                 switch (op) {
8864                 case DIF_OP_OR:
8865                 case DIF_OP_XOR:
8866                 case DIF_OP_AND:
8867                 case DIF_OP_SLL:
8868                 case DIF_OP_SRL:
8869                 case DIF_OP_SRA:
8870                 case DIF_OP_SUB:
8871                 case DIF_OP_ADD:
8872                 case DIF_OP_MUL:
8873                 case DIF_OP_SDIV:
8874                 case DIF_OP_UDIV:
8875                 case DIF_OP_SREM:
8876                 case DIF_OP_UREM:
8877                 case DIF_OP_COPYS:
8878                         if (r1 >= nregs)
8879                                 err += efunc(pc, "invalid register %u\n", r1);
8880                         if (r2 >= nregs)
8881                                 err += efunc(pc, "invalid register %u\n", r2);
8882                         if (rd >= nregs)
8883                                 err += efunc(pc, "invalid register %u\n", rd);
8884                         if (rd == 0)
8885                                 err += efunc(pc, "cannot write to %r0\n");
8886                         break;
8887                 case DIF_OP_NOT:
8888                 case DIF_OP_MOV:
8889                 case DIF_OP_ALLOCS:
8890                         if (r1 >= nregs)
8891                                 err += efunc(pc, "invalid register %u\n", r1);
8892                         if (r2 != 0)
8893                                 err += efunc(pc, "non-zero reserved bits\n");
8894                         if (rd >= nregs)
8895                                 err += efunc(pc, "invalid register %u\n", rd);
8896                         if (rd == 0)
8897                                 err += efunc(pc, "cannot write to %r0\n");
8898                         break;
8899                 case DIF_OP_LDSB:
8900                 case DIF_OP_LDSH:
8901                 case DIF_OP_LDSW:
8902                 case DIF_OP_LDUB:
8903                 case DIF_OP_LDUH:
8904                 case DIF_OP_LDUW:
8905                 case DIF_OP_LDX:
8906                         if (r1 >= nregs)
8907                                 err += efunc(pc, "invalid register %u\n", r1);
8908                         if (r2 != 0)
8909                                 err += efunc(pc, "non-zero reserved bits\n");
8910                         if (rd >= nregs)
8911                                 err += efunc(pc, "invalid register %u\n", rd);
8912                         if (rd == 0)
8913                                 err += efunc(pc, "cannot write to %r0\n");
8914                         if (kcheckload)
8915                                 dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8916                                     DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8917                         break;
8918                 case DIF_OP_RLDSB:
8919                 case DIF_OP_RLDSH:
8920                 case DIF_OP_RLDSW:
8921                 case DIF_OP_RLDUB:
8922                 case DIF_OP_RLDUH:
8923                 case DIF_OP_RLDUW:
8924                 case DIF_OP_RLDX:
8925                         if (r1 >= nregs)
8926                                 err += efunc(pc, "invalid register %u\n", r1);
8927                         if (r2 != 0)
8928                                 err += efunc(pc, "non-zero reserved bits\n");
8929                         if (rd >= nregs)
8930                                 err += efunc(pc, "invalid register %u\n", rd);
8931                         if (rd == 0)
8932                                 err += efunc(pc, "cannot write to %r0\n");
8933                         break;
8934                 case DIF_OP_ULDSB:
8935                 case DIF_OP_ULDSH:
8936                 case DIF_OP_ULDSW:
8937                 case DIF_OP_ULDUB:
8938                 case DIF_OP_ULDUH:
8939                 case DIF_OP_ULDUW:
8940                 case DIF_OP_ULDX:
8941                         if (r1 >= nregs)
8942                                 err += efunc(pc, "invalid register %u\n", r1);
8943                         if (r2 != 0)
8944                                 err += efunc(pc, "non-zero reserved bits\n");
8945                         if (rd >= nregs)
8946                                 err += efunc(pc, "invalid register %u\n", rd);
8947                         if (rd == 0)
8948                                 err += efunc(pc, "cannot write to %r0\n");
8949                         break;
8950                 case DIF_OP_STB:
8951                 case DIF_OP_STH:
8952                 case DIF_OP_STW:
8953                 case DIF_OP_STX:
8954                         if (r1 >= nregs)
8955                                 err += efunc(pc, "invalid register %u\n", r1);
8956                         if (r2 != 0)
8957                                 err += efunc(pc, "non-zero reserved bits\n");
8958                         if (rd >= nregs)
8959                                 err += efunc(pc, "invalid register %u\n", rd);
8960                         if (rd == 0)
8961                                 err += efunc(pc, "cannot write to 0 address\n");
8962                         break;
8963                 case DIF_OP_CMP:
8964                 case DIF_OP_SCMP:
8965                         if (r1 >= nregs)
8966                                 err += efunc(pc, "invalid register %u\n", r1);
8967                         if (r2 >= nregs)
8968                                 err += efunc(pc, "invalid register %u\n", r2);
8969                         if (rd != 0)
8970                                 err += efunc(pc, "non-zero reserved bits\n");
8971                         break;
8972                 case DIF_OP_TST:
8973                         if (r1 >= nregs)
8974                                 err += efunc(pc, "invalid register %u\n", r1);
8975                         if (r2 != 0 || rd != 0)
8976                                 err += efunc(pc, "non-zero reserved bits\n");
8977                         break;
8978                 case DIF_OP_BA:
8979                 case DIF_OP_BE:
8980                 case DIF_OP_BNE:
8981                 case DIF_OP_BG:
8982                 case DIF_OP_BGU:
8983                 case DIF_OP_BGE:
8984                 case DIF_OP_BGEU:
8985                 case DIF_OP_BL:
8986                 case DIF_OP_BLU:
8987                 case DIF_OP_BLE:
8988                 case DIF_OP_BLEU:
8989                         if (label >= dp->dtdo_len) {
8990                                 err += efunc(pc, "invalid branch target %u\n",
8991                                     label);
8992                         }
8993                         if (label <= pc) {
8994                                 err += efunc(pc, "backward branch to %u\n",
8995                                     label);
8996                         }
8997                         break;
8998                 case DIF_OP_RET:
8999                         if (r1 != 0 || r2 != 0)
9000                                 err += efunc(pc, "non-zero reserved bits\n");
9001                         if (rd >= nregs)
9002                                 err += efunc(pc, "invalid register %u\n", rd);
9003                         break;
9004                 case DIF_OP_NOP:
9005                 case DIF_OP_POPTS:
9006                 case DIF_OP_FLUSHTS:
9007                         if (r1 != 0 || r2 != 0 || rd != 0)
9008                                 err += efunc(pc, "non-zero reserved bits\n");
9009                         break;
9010                 case DIF_OP_SETX:
9011                         if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9012                                 err += efunc(pc, "invalid integer ref %u\n",
9013                                     DIF_INSTR_INTEGER(instr));
9014                         }
9015                         if (rd >= nregs)
9016                                 err += efunc(pc, "invalid register %u\n", rd);
9017                         if (rd == 0)
9018                                 err += efunc(pc, "cannot write to %r0\n");
9019                         break;
9020                 case DIF_OP_SETS:
9021                         if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9022                                 err += efunc(pc, "invalid string ref %u\n",
9023                                     DIF_INSTR_STRING(instr));
9024                         }
9025                         if (rd >= nregs)
9026                                 err += efunc(pc, "invalid register %u\n", rd);
9027                         if (rd == 0)
9028                                 err += efunc(pc, "cannot write to %r0\n");
9029                         break;
9030                 case DIF_OP_LDGA:
9031                 case DIF_OP_LDTA:
9032                         if (r1 > DIF_VAR_ARRAY_MAX)
9033                                 err += efunc(pc, "invalid array %u\n", r1);
9034                         if (r2 >= nregs)
9035                                 err += efunc(pc, "invalid register %u\n", r2);
9036                         if (rd >= nregs)
9037                                 err += efunc(pc, "invalid register %u\n", rd);
9038                         if (rd == 0)
9039                                 err += efunc(pc, "cannot write to %r0\n");
9040                         break;
9041                 case DIF_OP_LDGS:
9042                 case DIF_OP_LDTS:
9043                 case DIF_OP_LDLS:
9044                 case DIF_OP_LDGAA:
9045                 case DIF_OP_LDTAA:
9046                         if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9047                                 err += efunc(pc, "invalid variable %u\n", v);
9048                         if (rd >= nregs)
9049                                 err += efunc(pc, "invalid register %u\n", rd);
9050                         if (rd == 0)
9051                                 err += efunc(pc, "cannot write to %r0\n");
9052                         break;
9053                 case DIF_OP_STGS:
9054                 case DIF_OP_STTS:
9055                 case DIF_OP_STLS:
9056                 case DIF_OP_STGAA:
9057                 case DIF_OP_STTAA:
9058                         if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9059                                 err += efunc(pc, "invalid variable %u\n", v);
9060                         if (rs >= nregs)
9061                                 err += efunc(pc, "invalid register %u\n", rd);
9062                         break;
9063                 case DIF_OP_CALL:
9064                         if (subr > DIF_SUBR_MAX)
9065                                 err += efunc(pc, "invalid subr %u\n", subr);
9066                         if (rd >= nregs)
9067                                 err += efunc(pc, "invalid register %u\n", rd);
9068                         if (rd == 0)
9069                                 err += efunc(pc, "cannot write to %r0\n");
9070 
9071                         if (subr == DIF_SUBR_COPYOUT ||
9072                             subr == DIF_SUBR_COPYOUTSTR) {
9073                                 dp->dtdo_destructive = 1;
9074                         }
9075 
9076                         if (subr == DIF_SUBR_GETF) {
9077                                 /*
9078                                  * If we have a getf() we need to record that
9079                                  * in our state.  Note that our state can be
9080                                  * NULL if this is a helper -- but in that
9081                                  * case, the call to getf() is itself illegal,
9082                                  * and will be caught (slightly later) when
9083                                  * the helper is validated.
9084                                  */
9085                                 if (vstate->dtvs_state != NULL)
9086                                         vstate->dtvs_state->dts_getf++;
9087                         }
9088 
9089                         break;
9090                 case DIF_OP_PUSHTR:
9091                         if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9092                                 err += efunc(pc, "invalid ref type %u\n", type);
9093                         if (r2 >= nregs)
9094                                 err += efunc(pc, "invalid register %u\n", r2);
9095                         if (rs >= nregs)
9096                                 err += efunc(pc, "invalid register %u\n", rs);
9097                         break;
9098                 case DIF_OP_PUSHTV:
9099                         if (type != DIF_TYPE_CTF)
9100                                 err += efunc(pc, "invalid val type %u\n", type);
9101                         if (r2 >= nregs)
9102                                 err += efunc(pc, "invalid register %u\n", r2);
9103                         if (rs >= nregs)
9104                                 err += efunc(pc, "invalid register %u\n", rs);
9105                         break;
9106                 default:
9107                         err += efunc(pc, "invalid opcode %u\n",
9108                             DIF_INSTR_OP(instr));
9109                 }
9110         }
9111 
9112         if (dp->dtdo_len != 0 &&
9113             DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9114                 err += efunc(dp->dtdo_len - 1,
9115                     "expected 'ret' as last DIF instruction\n");
9116         }
9117 
9118         if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
9119                 /*
9120                  * If we're not returning by reference, the size must be either
9121                  * 0 or the size of one of the base types.
9122                  */
9123                 switch (dp->dtdo_rtype.dtdt_size) {
9124                 case 0:
9125                 case sizeof (uint8_t):
9126                 case sizeof (uint16_t):
9127                 case sizeof (uint32_t):
9128                 case sizeof (uint64_t):
9129                         break;
9130 
9131                 default:
9132                         err += efunc(dp->dtdo_len - 1, "bad return size\n");
9133                 }
9134         }
9135 
9136         for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9137                 dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9138                 dtrace_diftype_t *vt, *et;
9139                 uint_t id, ndx;
9140 
9141                 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9142                     v->dtdv_scope != DIFV_SCOPE_THREAD &&
9143                     v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9144                         err += efunc(i, "unrecognized variable scope %d\n",
9145                             v->dtdv_scope);
9146                         break;
9147                 }
9148 
9149                 if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9150                     v->dtdv_kind != DIFV_KIND_SCALAR) {
9151                         err += efunc(i, "unrecognized variable type %d\n",
9152                             v->dtdv_kind);
9153                         break;
9154                 }
9155 
9156                 if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9157                         err += efunc(i, "%d exceeds variable id limit\n", id);
9158                         break;
9159                 }
9160 
9161                 if (id < DIF_VAR_OTHER_UBASE)
9162                         continue;
9163 
9164                 /*
9165                  * For user-defined variables, we need to check that this
9166                  * definition is identical to any previous definition that we
9167                  * encountered.
9168                  */
9169                 ndx = id - DIF_VAR_OTHER_UBASE;
9170 
9171                 switch (v->dtdv_scope) {
9172                 case DIFV_SCOPE_GLOBAL:
9173                         if (ndx < vstate->dtvs_nglobals) {
9174                                 dtrace_statvar_t *svar;
9175 
9176                                 if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9177                                         existing = &svar->dtsv_var;
9178                         }
9179 
9180                         break;
9181 
9182                 case DIFV_SCOPE_THREAD:
9183                         if (ndx < vstate->dtvs_ntlocals)
9184                                 existing = &vstate->dtvs_tlocals[ndx];
9185                         break;
9186 
9187                 case DIFV_SCOPE_LOCAL:
9188                         if (ndx < vstate->dtvs_nlocals) {
9189                                 dtrace_statvar_t *svar;
9190 
9191                                 if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9192                                         existing = &svar->dtsv_var;
9193                         }
9194 
9195                         break;
9196                 }
9197 
9198                 vt = &v->dtdv_type;
9199 
9200                 if (vt->dtdt_flags & DIF_TF_BYREF) {
9201                         if (vt->dtdt_size == 0) {
9202                                 err += efunc(i, "zero-sized variable\n");
9203                                 break;
9204                         }
9205 
9206                         if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
9207                             vt->dtdt_size > dtrace_global_maxsize) {
9208                                 err += efunc(i, "oversized by-ref global\n");
9209                                 break;
9210                         }
9211                 }
9212 
9213                 if (existing == NULL || existing->dtdv_id == 0)
9214                         continue;
9215 
9216                 ASSERT(existing->dtdv_id == v->dtdv_id);
9217                 ASSERT(existing->dtdv_scope == v->dtdv_scope);
9218 
9219                 if (existing->dtdv_kind != v->dtdv_kind)
9220                         err += efunc(i, "%d changed variable kind\n", id);
9221 
9222                 et = &existing->dtdv_type;
9223 
9224                 if (vt->dtdt_flags != et->dtdt_flags) {
9225                         err += efunc(i, "%d changed variable type flags\n", id);
9226                         break;
9227                 }
9228 
9229                 if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9230                         err += efunc(i, "%d changed variable type size\n", id);
9231                         break;
9232                 }
9233         }
9234 
9235         return (err);
9236 }
9237 
9238 /*
9239  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
9240  * are much more constrained than normal DIFOs.  Specifically, they may
9241  * not:
9242  *
9243  * 1. Make calls to subroutines other than copyin(), copyinstr() or
9244  *    miscellaneous string routines
9245  * 2. Access DTrace variables other than the args[] array, and the
9246  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9247  * 3. Have thread-local variables.
9248  * 4. Have dynamic variables.
9249  */
9250 static int
9251 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9252 {
9253         int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9254         int err = 0;
9255         uint_t pc;
9256 
9257         for (pc = 0; pc < dp->dtdo_len; pc++) {
9258                 dif_instr_t instr = dp->dtdo_buf[pc];
9259 
9260                 uint_t v = DIF_INSTR_VAR(instr);
9261                 uint_t subr = DIF_INSTR_SUBR(instr);
9262                 uint_t op = DIF_INSTR_OP(instr);
9263 
9264                 switch (op) {
9265                 case DIF_OP_OR:
9266                 case DIF_OP_XOR:
9267                 case DIF_OP_AND:
9268                 case DIF_OP_SLL:
9269                 case DIF_OP_SRL:
9270                 case DIF_OP_SRA:
9271                 case DIF_OP_SUB:
9272                 case DIF_OP_ADD:
9273                 case DIF_OP_MUL:
9274                 case DIF_OP_SDIV:
9275                 case DIF_OP_UDIV:
9276                 case DIF_OP_SREM:
9277                 case DIF_OP_UREM:
9278                 case DIF_OP_COPYS:
9279                 case DIF_OP_NOT:
9280                 case DIF_OP_MOV:
9281                 case DIF_OP_RLDSB:
9282                 case DIF_OP_RLDSH:
9283                 case DIF_OP_RLDSW:
9284                 case DIF_OP_RLDUB:
9285                 case DIF_OP_RLDUH:
9286                 case DIF_OP_RLDUW:
9287                 case DIF_OP_RLDX:
9288                 case DIF_OP_ULDSB:
9289                 case DIF_OP_ULDSH:
9290                 case DIF_OP_ULDSW:
9291                 case DIF_OP_ULDUB:
9292                 case DIF_OP_ULDUH:
9293                 case DIF_OP_ULDUW:
9294                 case DIF_OP_ULDX:
9295                 case DIF_OP_STB:
9296                 case DIF_OP_STH:
9297                 case DIF_OP_STW:
9298                 case DIF_OP_STX:
9299                 case DIF_OP_ALLOCS:
9300                 case DIF_OP_CMP:
9301                 case DIF_OP_SCMP:
9302                 case DIF_OP_TST:
9303                 case DIF_OP_BA:
9304                 case DIF_OP_BE:
9305                 case DIF_OP_BNE:
9306                 case DIF_OP_BG:
9307                 case DIF_OP_BGU:
9308                 case DIF_OP_BGE:
9309                 case DIF_OP_BGEU:
9310                 case DIF_OP_BL:
9311                 case DIF_OP_BLU:
9312                 case DIF_OP_BLE:
9313                 case DIF_OP_BLEU:
9314                 case DIF_OP_RET:
9315                 case DIF_OP_NOP:
9316                 case DIF_OP_POPTS:
9317                 case DIF_OP_FLUSHTS:
9318                 case DIF_OP_SETX:
9319                 case DIF_OP_SETS:
9320                 case DIF_OP_LDGA:
9321                 case DIF_OP_LDLS:
9322                 case DIF_OP_STGS:
9323                 case DIF_OP_STLS:
9324                 case DIF_OP_PUSHTR:
9325                 case DIF_OP_PUSHTV:
9326                         break;
9327 
9328                 case DIF_OP_LDGS:
9329                         if (v >= DIF_VAR_OTHER_UBASE)
9330                                 break;
9331 
9332                         if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9333                                 break;
9334 
9335                         if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9336                             v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9337                             v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9338                             v == DIF_VAR_UID || v == DIF_VAR_GID)
9339                                 break;
9340 
9341                         err += efunc(pc, "illegal variable %u\n", v);
9342                         break;
9343 
9344                 case DIF_OP_LDTA:
9345                 case DIF_OP_LDTS:
9346                 case DIF_OP_LDGAA:
9347                 case DIF_OP_LDTAA:
9348                         err += efunc(pc, "illegal dynamic variable load\n");
9349                         break;
9350 
9351                 case DIF_OP_STTS:
9352                 case DIF_OP_STGAA:
9353                 case DIF_OP_STTAA:
9354                         err += efunc(pc, "illegal dynamic variable store\n");
9355                         break;
9356 
9357                 case DIF_OP_CALL:
9358                         if (subr == DIF_SUBR_ALLOCA ||
9359                             subr == DIF_SUBR_BCOPY ||
9360                             subr == DIF_SUBR_COPYIN ||
9361                             subr == DIF_SUBR_COPYINTO ||
9362                             subr == DIF_SUBR_COPYINSTR ||
9363                             subr == DIF_SUBR_INDEX ||
9364                             subr == DIF_SUBR_INET_NTOA ||
9365                             subr == DIF_SUBR_INET_NTOA6 ||
9366                             subr == DIF_SUBR_INET_NTOP ||
9367                             subr == DIF_SUBR_LLTOSTR ||
9368                             subr == DIF_SUBR_STRTOLL ||
9369                             subr == DIF_SUBR_RINDEX ||
9370                             subr == DIF_SUBR_STRCHR ||
9371                             subr == DIF_SUBR_STRJOIN ||
9372                             subr == DIF_SUBR_STRRCHR ||
9373                             subr == DIF_SUBR_STRSTR ||
9374                             subr == DIF_SUBR_HTONS ||
9375                             subr == DIF_SUBR_HTONL ||
9376                             subr == DIF_SUBR_HTONLL ||
9377                             subr == DIF_SUBR_NTOHS ||
9378                             subr == DIF_SUBR_NTOHL ||
9379                             subr == DIF_SUBR_NTOHLL)
9380                                 break;
9381 
9382                         err += efunc(pc, "invalid subr %u\n", subr);
9383                         break;
9384 
9385                 default:
9386                         err += efunc(pc, "invalid opcode %u\n",
9387                             DIF_INSTR_OP(instr));
9388                 }
9389         }
9390 
9391         return (err);
9392 }
9393 
9394 /*
9395  * Returns 1 if the expression in the DIF object can be cached on a per-thread
9396  * basis; 0 if not.
9397  */
9398 static int
9399 dtrace_difo_cacheable(dtrace_difo_t *dp)
9400 {
9401         int i;
9402 
9403         if (dp == NULL)
9404                 return (0);
9405 
9406         for (i = 0; i < dp->dtdo_varlen; i++) {
9407                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9408 
9409                 if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9410                         continue;
9411 
9412                 switch (v->dtdv_id) {
9413                 case DIF_VAR_CURTHREAD:
9414                 case DIF_VAR_PID:
9415                 case DIF_VAR_TID:
9416                 case DIF_VAR_EXECNAME:
9417                 case DIF_VAR_ZONENAME:
9418                         break;
9419 
9420                 default:
9421                         return (0);
9422                 }
9423         }
9424 
9425         /*
9426          * This DIF object may be cacheable.  Now we need to look for any
9427          * array loading instructions, any memory loading instructions, or
9428          * any stores to thread-local variables.
9429          */
9430         for (i = 0; i < dp->dtdo_len; i++) {
9431                 uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9432 
9433                 if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9434                     (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9435                     (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9436                     op == DIF_OP_LDGA || op == DIF_OP_STTS)
9437                         return (0);
9438         }
9439 
9440         return (1);
9441 }
9442 
9443 static void
9444 dtrace_difo_hold(dtrace_difo_t *dp)
9445 {
9446         int i;
9447 
9448         ASSERT(MUTEX_HELD(&dtrace_lock));
9449 
9450         dp->dtdo_refcnt++;
9451         ASSERT(dp->dtdo_refcnt != 0);
9452 
9453         /*
9454          * We need to check this DIF object for references to the variable
9455          * DIF_VAR_VTIMESTAMP.
9456          */
9457         for (i = 0; i < dp->dtdo_varlen; i++) {
9458                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9459 
9460                 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9461                         continue;
9462 
9463                 if (dtrace_vtime_references++ == 0)
9464                         dtrace_vtime_enable();
9465         }
9466 }
9467 
9468 /*
9469  * This routine calculates the dynamic variable chunksize for a given DIF
9470  * object.  The calculation is not fool-proof, and can probably be tricked by
9471  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
9472  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9473  * if a dynamic variable size exceeds the chunksize.
9474  */
9475 static void
9476 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9477 {
9478         uint64_t sval;
9479         dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9480         const dif_instr_t *text = dp->dtdo_buf;
9481         uint_t pc, srd = 0;
9482         uint_t ttop = 0;
9483         size_t size, ksize;
9484         uint_t id, i;
9485 
9486         for (pc = 0; pc < dp->dtdo_len; pc++) {
9487                 dif_instr_t instr = text[pc];
9488                 uint_t op = DIF_INSTR_OP(instr);
9489                 uint_t rd = DIF_INSTR_RD(instr);
9490                 uint_t r1 = DIF_INSTR_R1(instr);
9491                 uint_t nkeys = 0;
9492                 uchar_t scope;
9493 
9494                 dtrace_key_t *key = tupregs;
9495 
9496                 switch (op) {
9497                 case DIF_OP_SETX:
9498                         sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9499                         srd = rd;
9500                         continue;
9501 
9502                 case DIF_OP_STTS:
9503                         key = &tupregs[DIF_DTR_NREGS];
9504                         key[0].dttk_size = 0;
9505                         key[1].dttk_size = 0;
9506                         nkeys = 2;
9507                         scope = DIFV_SCOPE_THREAD;
9508                         break;
9509 
9510                 case DIF_OP_STGAA:
9511                 case DIF_OP_STTAA:
9512                         nkeys = ttop;
9513 
9514                         if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9515                                 key[nkeys++].dttk_size = 0;
9516 
9517                         key[nkeys++].dttk_size = 0;
9518 
9519                         if (op == DIF_OP_STTAA) {
9520                                 scope = DIFV_SCOPE_THREAD;
9521                         } else {
9522                                 scope = DIFV_SCOPE_GLOBAL;
9523                         }
9524 
9525                         break;
9526 
9527                 case DIF_OP_PUSHTR:
9528                         if (ttop == DIF_DTR_NREGS)
9529                                 return;
9530 
9531                         if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9532                                 /*
9533                                  * If the register for the size of the "pushtr"
9534                                  * is %r0 (or the value is 0) and the type is
9535                                  * a string, we'll use the system-wide default
9536                                  * string size.
9537                                  */
9538                                 tupregs[ttop++].dttk_size =
9539                                     dtrace_strsize_default;
9540                         } else {
9541                                 if (srd == 0)
9542                                         return;
9543 
9544                                 tupregs[ttop++].dttk_size = sval;
9545                         }
9546 
9547                         break;
9548 
9549                 case DIF_OP_PUSHTV:
9550                         if (ttop == DIF_DTR_NREGS)
9551                                 return;
9552 
9553                         tupregs[ttop++].dttk_size = 0;
9554                         break;
9555 
9556                 case DIF_OP_FLUSHTS:
9557                         ttop = 0;
9558                         break;
9559 
9560                 case DIF_OP_POPTS:
9561                         if (ttop != 0)
9562                                 ttop--;
9563                         break;
9564                 }
9565 
9566                 sval = 0;
9567                 srd = 0;
9568 
9569                 if (nkeys == 0)
9570                         continue;
9571 
9572                 /*
9573                  * We have a dynamic variable allocation; calculate its size.
9574                  */
9575                 for (ksize = 0, i = 0; i < nkeys; i++)
9576                         ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9577 
9578                 size = sizeof (dtrace_dynvar_t);
9579                 size += sizeof (dtrace_key_t) * (nkeys - 1);
9580                 size += ksize;
9581 
9582                 /*
9583                  * Now we need to determine the size of the stored data.
9584                  */
9585                 id = DIF_INSTR_VAR(instr);
9586 
9587                 for (i = 0; i < dp->dtdo_varlen; i++) {
9588                         dtrace_difv_t *v = &dp->dtdo_vartab[i];
9589 
9590                         if (v->dtdv_id == id && v->dtdv_scope == scope) {
9591                                 size += v->dtdv_type.dtdt_size;
9592                                 break;
9593                         }
9594                 }
9595 
9596                 if (i == dp->dtdo_varlen)
9597                         return;
9598 
9599                 /*
9600                  * We have the size.  If this is larger than the chunk size
9601                  * for our dynamic variable state, reset the chunk size.
9602                  */
9603                 size = P2ROUNDUP(size, sizeof (uint64_t));
9604 
9605                 if (size > vstate->dtvs_dynvars.dtds_chunksize)
9606                         vstate->dtvs_dynvars.dtds_chunksize = size;
9607         }
9608 }
9609 
9610 static void
9611 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9612 {
9613         int i, oldsvars, osz, nsz, otlocals, ntlocals;
9614         uint_t id;
9615 
9616         ASSERT(MUTEX_HELD(&dtrace_lock));
9617         ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9618 
9619         for (i = 0; i < dp->dtdo_varlen; i++) {
9620                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9621                 dtrace_statvar_t *svar, ***svarp;
9622                 size_t dsize = 0;
9623                 uint8_t scope = v->dtdv_scope;
9624                 int *np;
9625 
9626                 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9627                         continue;
9628 
9629                 id -= DIF_VAR_OTHER_UBASE;
9630 
9631                 switch (scope) {
9632                 case DIFV_SCOPE_THREAD:
9633                         while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9634                                 dtrace_difv_t *tlocals;
9635 
9636                                 if ((ntlocals = (otlocals << 1)) == 0)
9637                                         ntlocals = 1;
9638 
9639                                 osz = otlocals * sizeof (dtrace_difv_t);
9640                                 nsz = ntlocals * sizeof (dtrace_difv_t);
9641 
9642                                 tlocals = kmem_zalloc(nsz, KM_SLEEP);
9643 
9644                                 if (osz != 0) {
9645                                         bcopy(vstate->dtvs_tlocals,
9646                                             tlocals, osz);
9647                                         kmem_free(vstate->dtvs_tlocals, osz);
9648                                 }
9649 
9650                                 vstate->dtvs_tlocals = tlocals;
9651                                 vstate->dtvs_ntlocals = ntlocals;
9652                         }
9653 
9654                         vstate->dtvs_tlocals[id] = *v;
9655                         continue;
9656 
9657                 case DIFV_SCOPE_LOCAL:
9658                         np = &vstate->dtvs_nlocals;
9659                         svarp = &vstate->dtvs_locals;
9660 
9661                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9662                                 dsize = NCPU * (v->dtdv_type.dtdt_size +
9663                                     sizeof (uint64_t));
9664                         else
9665                                 dsize = NCPU * sizeof (uint64_t);
9666 
9667                         break;
9668 
9669                 case DIFV_SCOPE_GLOBAL:
9670                         np = &vstate->dtvs_nglobals;
9671                         svarp = &vstate->dtvs_globals;
9672 
9673                         if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9674                                 dsize = v->dtdv_type.dtdt_size +
9675                                     sizeof (uint64_t);
9676 
9677                         break;
9678 
9679                 default:
9680                         ASSERT(0);
9681                 }
9682 
9683                 while (id >= (oldsvars = *np)) {
9684                         dtrace_statvar_t **statics;
9685                         int newsvars, oldsize, newsize;
9686 
9687                         if ((newsvars = (oldsvars << 1)) == 0)
9688                                 newsvars = 1;
9689 
9690                         oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9691                         newsize = newsvars * sizeof (dtrace_statvar_t *);
9692 
9693                         statics = kmem_zalloc(newsize, KM_SLEEP);
9694 
9695                         if (oldsize != 0) {
9696                                 bcopy(*svarp, statics, oldsize);
9697                                 kmem_free(*svarp, oldsize);
9698                         }
9699 
9700                         *svarp = statics;
9701                         *np = newsvars;
9702                 }
9703 
9704                 if ((svar = (*svarp)[id]) == NULL) {
9705                         svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9706                         svar->dtsv_var = *v;
9707 
9708                         if ((svar->dtsv_size = dsize) != 0) {
9709                                 svar->dtsv_data = (uint64_t)(uintptr_t)
9710                                     kmem_zalloc(dsize, KM_SLEEP);
9711                         }
9712 
9713                         (*svarp)[id] = svar;
9714                 }
9715 
9716                 svar->dtsv_refcnt++;
9717         }
9718 
9719         dtrace_difo_chunksize(dp, vstate);
9720         dtrace_difo_hold(dp);
9721 }
9722 
9723 static dtrace_difo_t *
9724 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9725 {
9726         dtrace_difo_t *new;
9727         size_t sz;
9728 
9729         ASSERT(dp->dtdo_buf != NULL);
9730         ASSERT(dp->dtdo_refcnt != 0);
9731 
9732         new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9733 
9734         ASSERT(dp->dtdo_buf != NULL);
9735         sz = dp->dtdo_len * sizeof (dif_instr_t);
9736         new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9737         bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9738         new->dtdo_len = dp->dtdo_len;
9739 
9740         if (dp->dtdo_strtab != NULL) {
9741                 ASSERT(dp->dtdo_strlen != 0);
9742                 new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9743                 bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9744                 new->dtdo_strlen = dp->dtdo_strlen;
9745         }
9746 
9747         if (dp->dtdo_inttab != NULL) {
9748                 ASSERT(dp->dtdo_intlen != 0);
9749                 sz = dp->dtdo_intlen * sizeof (uint64_t);
9750                 new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9751                 bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9752                 new->dtdo_intlen = dp->dtdo_intlen;
9753         }
9754 
9755         if (dp->dtdo_vartab != NULL) {
9756                 ASSERT(dp->dtdo_varlen != 0);
9757                 sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9758                 new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9759                 bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9760                 new->dtdo_varlen = dp->dtdo_varlen;
9761         }
9762 
9763         dtrace_difo_init(new, vstate);
9764         return (new);
9765 }
9766 
9767 static void
9768 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9769 {
9770         int i;
9771 
9772         ASSERT(dp->dtdo_refcnt == 0);
9773 
9774         for (i = 0; i < dp->dtdo_varlen; i++) {
9775                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9776                 dtrace_statvar_t *svar, **svarp;
9777                 uint_t id;
9778                 uint8_t scope = v->dtdv_scope;
9779                 int *np;
9780 
9781                 switch (scope) {
9782                 case DIFV_SCOPE_THREAD:
9783                         continue;
9784 
9785                 case DIFV_SCOPE_LOCAL:
9786                         np = &vstate->dtvs_nlocals;
9787                         svarp = vstate->dtvs_locals;
9788                         break;
9789 
9790                 case DIFV_SCOPE_GLOBAL:
9791                         np = &vstate->dtvs_nglobals;
9792                         svarp = vstate->dtvs_globals;
9793                         break;
9794 
9795                 default:
9796                         ASSERT(0);
9797                 }
9798 
9799                 if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9800                         continue;
9801 
9802                 id -= DIF_VAR_OTHER_UBASE;
9803                 ASSERT(id < *np);
9804 
9805                 svar = svarp[id];
9806                 ASSERT(svar != NULL);
9807                 ASSERT(svar->dtsv_refcnt > 0);
9808 
9809                 if (--svar->dtsv_refcnt > 0)
9810                         continue;
9811 
9812                 if (svar->dtsv_size != 0) {
9813                         ASSERT(svar->dtsv_data != NULL);
9814                         kmem_free((void *)(uintptr_t)svar->dtsv_data,
9815                             svar->dtsv_size);
9816                 }
9817 
9818                 kmem_free(svar, sizeof (dtrace_statvar_t));
9819                 svarp[id] = NULL;
9820         }
9821 
9822         kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9823         kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9824         kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9825         kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9826 
9827         kmem_free(dp, sizeof (dtrace_difo_t));
9828 }
9829 
9830 static void
9831 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9832 {
9833         int i;
9834 
9835         ASSERT(MUTEX_HELD(&dtrace_lock));
9836         ASSERT(dp->dtdo_refcnt != 0);
9837 
9838         for (i = 0; i < dp->dtdo_varlen; i++) {
9839                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
9840 
9841                 if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9842                         continue;
9843 
9844                 ASSERT(dtrace_vtime_references > 0);
9845                 if (--dtrace_vtime_references == 0)
9846                         dtrace_vtime_disable();
9847         }
9848 
9849         if (--dp->dtdo_refcnt == 0)
9850                 dtrace_difo_destroy(dp, vstate);
9851 }
9852 
9853 /*
9854  * DTrace Format Functions
9855  */
9856 static uint16_t
9857 dtrace_format_add(dtrace_state_t *state, char *str)
9858 {
9859         char *fmt, **new;
9860         uint16_t ndx, len = strlen(str) + 1;
9861 
9862         fmt = kmem_zalloc(len, KM_SLEEP);
9863         bcopy(str, fmt, len);
9864 
9865         for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9866                 if (state->dts_formats[ndx] == NULL) {
9867                         state->dts_formats[ndx] = fmt;
9868                         return (ndx + 1);
9869                 }
9870         }
9871 
9872         if (state->dts_nformats == USHRT_MAX) {
9873                 /*
9874                  * This is only likely if a denial-of-service attack is being
9875                  * attempted.  As such, it's okay to fail silently here.
9876                  */
9877                 kmem_free(fmt, len);
9878                 return (0);
9879         }
9880 
9881         /*
9882          * For simplicity, we always resize the formats array to be exactly the
9883          * number of formats.
9884          */
9885         ndx = state->dts_nformats++;
9886         new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9887 
9888         if (state->dts_formats != NULL) {
9889                 ASSERT(ndx != 0);
9890                 bcopy(state->dts_formats, new, ndx * sizeof (char *));
9891                 kmem_free(state->dts_formats, ndx * sizeof (char *));
9892         }
9893 
9894         state->dts_formats = new;
9895         state->dts_formats[ndx] = fmt;
9896 
9897         return (ndx + 1);
9898 }
9899 
9900 static void
9901 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9902 {
9903         char *fmt;
9904 
9905         ASSERT(state->dts_formats != NULL);
9906         ASSERT(format <= state->dts_nformats);
9907         ASSERT(state->dts_formats[format - 1] != NULL);
9908 
9909         fmt = state->dts_formats[format - 1];
9910         kmem_free(fmt, strlen(fmt) + 1);
9911         state->dts_formats[format - 1] = NULL;
9912 }
9913 
9914 static void
9915 dtrace_format_destroy(dtrace_state_t *state)
9916 {
9917         int i;
9918 
9919         if (state->dts_nformats == 0) {
9920                 ASSERT(state->dts_formats == NULL);
9921                 return;
9922         }
9923 
9924         ASSERT(state->dts_formats != NULL);
9925 
9926         for (i = 0; i < state->dts_nformats; i++) {
9927                 char *fmt = state->dts_formats[i];
9928 
9929                 if (fmt == NULL)
9930                         continue;
9931 
9932                 kmem_free(fmt, strlen(fmt) + 1);
9933         }
9934 
9935         kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9936         state->dts_nformats = 0;
9937         state->dts_formats = NULL;
9938 }
9939 
9940 /*
9941  * DTrace Predicate Functions
9942  */
9943 static dtrace_predicate_t *
9944 dtrace_predicate_create(dtrace_difo_t *dp)
9945 {
9946         dtrace_predicate_t *pred;
9947 
9948         ASSERT(MUTEX_HELD(&dtrace_lock));
9949         ASSERT(dp->dtdo_refcnt != 0);
9950 
9951         pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9952         pred->dtp_difo = dp;
9953         pred->dtp_refcnt = 1;
9954 
9955         if (!dtrace_difo_cacheable(dp))
9956                 return (pred);
9957 
9958         if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9959                 /*
9960                  * This is only theoretically possible -- we have had 2^32
9961                  * cacheable predicates on this machine.  We cannot allow any
9962                  * more predicates to become cacheable:  as unlikely as it is,
9963                  * there may be a thread caching a (now stale) predicate cache
9964                  * ID. (N.B.: the temptation is being successfully resisted to
9965                  * have this cmn_err() "Holy shit -- we executed this code!")
9966                  */
9967                 return (pred);
9968         }
9969 
9970         pred->dtp_cacheid = dtrace_predcache_id++;
9971 
9972         return (pred);
9973 }
9974 
9975 static void
9976 dtrace_predicate_hold(dtrace_predicate_t *pred)
9977 {
9978         ASSERT(MUTEX_HELD(&dtrace_lock));
9979         ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9980         ASSERT(pred->dtp_refcnt > 0);
9981 
9982         pred->dtp_refcnt++;
9983 }
9984 
9985 static void
9986 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9987 {
9988         dtrace_difo_t *dp = pred->dtp_difo;
9989 
9990         ASSERT(MUTEX_HELD(&dtrace_lock));
9991         ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9992         ASSERT(pred->dtp_refcnt > 0);
9993 
9994         if (--pred->dtp_refcnt == 0) {
9995                 dtrace_difo_release(pred->dtp_difo, vstate);
9996                 kmem_free(pred, sizeof (dtrace_predicate_t));
9997         }
9998 }
9999 
10000 /*
10001  * DTrace Action Description Functions
10002  */
10003 static dtrace_actdesc_t *
10004 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10005     uint64_t uarg, uint64_t arg)
10006 {
10007         dtrace_actdesc_t *act;
10008 
10009         ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
10010             arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
10011 
10012         act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10013         act->dtad_kind = kind;
10014         act->dtad_ntuple = ntuple;
10015         act->dtad_uarg = uarg;
10016         act->dtad_arg = arg;
10017         act->dtad_refcnt = 1;
10018 
10019         return (act);
10020 }
10021 
10022 static void
10023 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10024 {
10025         ASSERT(act->dtad_refcnt >= 1);
10026         act->dtad_refcnt++;
10027 }
10028 
10029 static void
10030 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10031 {
10032         dtrace_actkind_t kind = act->dtad_kind;
10033         dtrace_difo_t *dp;
10034 
10035         ASSERT(act->dtad_refcnt >= 1);
10036 
10037         if (--act->dtad_refcnt != 0)
10038                 return;
10039 
10040         if ((dp = act->dtad_difo) != NULL)
10041                 dtrace_difo_release(dp, vstate);
10042 
10043         if (DTRACEACT_ISPRINTFLIKE(kind)) {
10044                 char *str = (char *)(uintptr_t)act->dtad_arg;
10045 
10046                 ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10047                     (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10048 
10049                 if (str != NULL)
10050                         kmem_free(str, strlen(str) + 1);
10051         }
10052 
10053         kmem_free(act, sizeof (dtrace_actdesc_t));
10054 }
10055 
10056 /*
10057  * DTrace ECB Functions
10058  */
10059 static dtrace_ecb_t *
10060 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10061 {
10062         dtrace_ecb_t *ecb;
10063         dtrace_epid_t epid;
10064 
10065         ASSERT(MUTEX_HELD(&dtrace_lock));
10066 
10067         ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10068         ecb->dte_predicate = NULL;
10069         ecb->dte_probe = probe;
10070 
10071         /*
10072          * The default size is the size of the default action: recording
10073          * the header.
10074          */
10075         ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10076         ecb->dte_alignment = sizeof (dtrace_epid_t);
10077 
10078         epid = state->dts_epid++;
10079 
10080         if (epid - 1 >= state->dts_necbs) {
10081                 dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10082                 int necbs = state->dts_necbs << 1;
10083 
10084                 ASSERT(epid == state->dts_necbs + 1);
10085 
10086                 if (necbs == 0) {
10087                         ASSERT(oecbs == NULL);
10088                         necbs = 1;
10089                 }
10090 
10091                 ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10092 
10093                 if (oecbs != NULL)
10094                         bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10095 
10096                 dtrace_membar_producer();
10097                 state->dts_ecbs = ecbs;
10098 
10099                 if (oecbs != NULL) {
10100                         /*
10101                          * If this state is active, we must dtrace_sync()
10102                          * before we can free the old dts_ecbs array:  we're
10103                          * coming in hot, and there may be active ring
10104                          * buffer processing (which indexes into the dts_ecbs
10105                          * array) on another CPU.
10106                          */
10107                         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10108                                 dtrace_sync();
10109 
10110                         kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10111                 }
10112 
10113                 dtrace_membar_producer();
10114                 state->dts_necbs = necbs;
10115         }
10116 
10117         ecb->dte_state = state;
10118 
10119         ASSERT(state->dts_ecbs[epid - 1] == NULL);
10120         dtrace_membar_producer();
10121         state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10122 
10123         return (ecb);
10124 }
10125 
10126 static int
10127 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10128 {
10129         dtrace_probe_t *probe = ecb->dte_probe;
10130 
10131         ASSERT(MUTEX_HELD(&cpu_lock));
10132         ASSERT(MUTEX_HELD(&dtrace_lock));
10133         ASSERT(ecb->dte_next == NULL);
10134 
10135         if (probe == NULL) {
10136                 /*
10137                  * This is the NULL probe -- there's nothing to do.
10138                  */
10139                 return (0);
10140         }
10141 
10142         if (probe->dtpr_ecb == NULL) {
10143                 dtrace_provider_t *prov = probe->dtpr_provider;
10144 
10145                 /*
10146                  * We're the first ECB on this probe.
10147                  */
10148                 probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10149 
10150                 if (ecb->dte_predicate != NULL)
10151                         probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10152 
10153                 return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10154                     probe->dtpr_id, probe->dtpr_arg));
10155         } else {
10156                 /*
10157                  * This probe is already active.  Swing the last pointer to
10158                  * point to the new ECB, and issue a dtrace_sync() to assure
10159                  * that all CPUs have seen the change.
10160                  */
10161                 ASSERT(probe->dtpr_ecb_last != NULL);
10162                 probe->dtpr_ecb_last->dte_next = ecb;
10163                 probe->dtpr_ecb_last = ecb;
10164                 probe->dtpr_predcache = 0;
10165 
10166                 dtrace_sync();
10167                 return (0);
10168         }
10169 }
10170 
10171 static void
10172 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10173 {
10174         dtrace_action_t *act;
10175         uint32_t curneeded = UINT32_MAX;
10176         uint32_t aggbase = UINT32_MAX;
10177 
10178         /*
10179          * If we record anything, we always record the dtrace_rechdr_t.  (And
10180          * we always record it first.)
10181          */
10182         ecb->dte_size = sizeof (dtrace_rechdr_t);
10183         ecb->dte_alignment = sizeof (dtrace_epid_t);
10184 
10185         for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10186                 dtrace_recdesc_t *rec = &act->dta_rec;
10187                 ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10188 
10189                 ecb->dte_alignment = MAX(ecb->dte_alignment,
10190                     rec->dtrd_alignment);
10191 
10192                 if (DTRACEACT_ISAGG(act->dta_kind)) {
10193                         dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10194 
10195                         ASSERT(rec->dtrd_size != 0);
10196                         ASSERT(agg->dtag_first != NULL);
10197                         ASSERT(act->dta_prev->dta_intuple);
10198                         ASSERT(aggbase != UINT32_MAX);
10199                         ASSERT(curneeded != UINT32_MAX);
10200 
10201                         agg->dtag_base = aggbase;
10202 
10203                         curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10204                         rec->dtrd_offset = curneeded;
10205                         curneeded += rec->dtrd_size;
10206                         ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10207 
10208                         aggbase = UINT32_MAX;
10209                         curneeded = UINT32_MAX;
10210                 } else if (act->dta_intuple) {
10211                         if (curneeded == UINT32_MAX) {
10212                                 /*
10213                                  * This is the first record in a tuple.  Align
10214                                  * curneeded to be at offset 4 in an 8-byte
10215                                  * aligned block.
10216                                  */
10217                                 ASSERT(act->dta_prev == NULL ||
10218                                     !act->dta_prev->dta_intuple);
10219                                 ASSERT3U(aggbase, ==, UINT32_MAX);
10220                                 curneeded = P2PHASEUP(ecb->dte_size,
10221                                     sizeof (uint64_t), sizeof (dtrace_aggid_t));
10222 
10223                                 aggbase = curneeded - sizeof (dtrace_aggid_t);
10224                                 ASSERT(IS_P2ALIGNED(aggbase,
10225                                     sizeof (uint64_t)));
10226                         }
10227                         curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10228                         rec->dtrd_offset = curneeded;
10229                         curneeded += rec->dtrd_size;
10230                 } else {
10231                         /* tuples must be followed by an aggregation */
10232                         ASSERT(act->dta_prev == NULL ||
10233                             !act->dta_prev->dta_intuple);
10234 
10235                         ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10236                             rec->dtrd_alignment);
10237                         rec->dtrd_offset = ecb->dte_size;
10238                         ecb->dte_size += rec->dtrd_size;
10239                         ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10240                 }
10241         }
10242 
10243         if ((act = ecb->dte_action) != NULL &&
10244             !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10245             ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10246                 /*
10247                  * If the size is still sizeof (dtrace_rechdr_t), then all
10248                  * actions store no data; set the size to 0.
10249                  */
10250                 ecb->dte_size = 0;
10251         }
10252 
10253         ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10254         ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10255         ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10256             ecb->dte_needed);
10257 }
10258 
10259 static dtrace_action_t *
10260 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10261 {
10262         dtrace_aggregation_t *agg;
10263         size_t size = sizeof (uint64_t);
10264         int ntuple = desc->dtad_ntuple;
10265         dtrace_action_t *act;
10266         dtrace_recdesc_t *frec;
10267         dtrace_aggid_t aggid;
10268         dtrace_state_t *state = ecb->dte_state;
10269 
10270         agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10271         agg->dtag_ecb = ecb;
10272 
10273         ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10274 
10275         switch (desc->dtad_kind) {
10276         case DTRACEAGG_MIN:
10277                 agg->dtag_initial = INT64_MAX;
10278                 agg->dtag_aggregate = dtrace_aggregate_min;
10279                 break;
10280 
10281         case DTRACEAGG_MAX:
10282                 agg->dtag_initial = INT64_MIN;
10283                 agg->dtag_aggregate = dtrace_aggregate_max;
10284                 break;
10285 
10286         case DTRACEAGG_COUNT:
10287                 agg->dtag_aggregate = dtrace_aggregate_count;
10288                 break;
10289 
10290         case DTRACEAGG_QUANTIZE:
10291                 agg->dtag_aggregate = dtrace_aggregate_quantize;
10292                 size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10293                     sizeof (uint64_t);
10294                 break;
10295 
10296         case DTRACEAGG_LQUANTIZE: {
10297                 uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10298                 uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10299 
10300                 agg->dtag_initial = desc->dtad_arg;
10301                 agg->dtag_aggregate = dtrace_aggregate_lquantize;
10302 
10303                 if (step == 0 || levels == 0)
10304                         goto err;
10305 
10306                 size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10307                 break;
10308         }
10309 
10310         case DTRACEAGG_LLQUANTIZE: {
10311                 uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10312                 uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10313                 uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10314                 uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10315                 int64_t v;
10316 
10317                 agg->dtag_initial = desc->dtad_arg;
10318                 agg->dtag_aggregate = dtrace_aggregate_llquantize;
10319 
10320                 if (factor < 2 || low >= high || nsteps < factor)
10321                         goto err;
10322 
10323                 /*
10324                  * Now check that the number of steps evenly divides a power
10325                  * of the factor.  (This assures both integer bucket size and
10326                  * linearity within each magnitude.)
10327                  */
10328                 for (v = factor; v < nsteps; v *= factor)
10329                         continue;
10330 
10331                 if ((v % nsteps) || (nsteps % factor))
10332                         goto err;
10333 
10334                 size = (dtrace_aggregate_llquantize_bucket(factor,
10335                     low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10336                 break;
10337         }
10338 
10339         case DTRACEAGG_AVG:
10340                 agg->dtag_aggregate = dtrace_aggregate_avg;
10341                 size = sizeof (uint64_t) * 2;
10342                 break;
10343 
10344         case DTRACEAGG_STDDEV:
10345                 agg->dtag_aggregate = dtrace_aggregate_stddev;
10346                 size = sizeof (uint64_t) * 4;
10347                 break;
10348 
10349         case DTRACEAGG_SUM:
10350                 agg->dtag_aggregate = dtrace_aggregate_sum;
10351                 break;
10352 
10353         default:
10354                 goto err;
10355         }
10356 
10357         agg->dtag_action.dta_rec.dtrd_size = size;
10358 
10359         if (ntuple == 0)
10360                 goto err;
10361 
10362         /*
10363          * We must make sure that we have enough actions for the n-tuple.
10364          */
10365         for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10366                 if (DTRACEACT_ISAGG(act->dta_kind))
10367                         break;
10368 
10369                 if (--ntuple == 0) {
10370                         /*
10371                          * This is the action with which our n-tuple begins.
10372                          */
10373                         agg->dtag_first = act;
10374                         goto success;
10375                 }
10376         }
10377 
10378         /*
10379          * This n-tuple is short by ntuple elements.  Return failure.
10380          */
10381         ASSERT(ntuple != 0);
10382 err:
10383         kmem_free(agg, sizeof (dtrace_aggregation_t));
10384         return (NULL);
10385 
10386 success:
10387         /*
10388          * If the last action in the tuple has a size of zero, it's actually
10389          * an expression argument for the aggregating action.
10390          */
10391         ASSERT(ecb->dte_action_last != NULL);
10392         act = ecb->dte_action_last;
10393 
10394         if (act->dta_kind == DTRACEACT_DIFEXPR) {
10395                 ASSERT(act->dta_difo != NULL);
10396 
10397                 if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10398                         agg->dtag_hasarg = 1;
10399         }
10400 
10401         /*
10402          * We need to allocate an id for this aggregation.
10403          */
10404         aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10405             VM_BESTFIT | VM_SLEEP);
10406 
10407         if (aggid - 1 >= state->dts_naggregations) {
10408                 dtrace_aggregation_t **oaggs = state->dts_aggregations;
10409                 dtrace_aggregation_t **aggs;
10410                 int naggs = state->dts_naggregations << 1;
10411                 int onaggs = state->dts_naggregations;
10412 
10413                 ASSERT(aggid == state->dts_naggregations + 1);
10414 
10415                 if (naggs == 0) {
10416                         ASSERT(oaggs == NULL);
10417                         naggs = 1;
10418                 }
10419 
10420                 aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10421 
10422                 if (oaggs != NULL) {
10423                         bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10424                         kmem_free(oaggs, onaggs * sizeof (*aggs));
10425                 }
10426 
10427                 state->dts_aggregations = aggs;
10428                 state->dts_naggregations = naggs;
10429         }
10430 
10431         ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10432         state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10433 
10434         frec = &agg->dtag_first->dta_rec;
10435         if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10436                 frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10437 
10438         for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10439                 ASSERT(!act->dta_intuple);
10440                 act->dta_intuple = 1;
10441         }
10442 
10443         return (&agg->dtag_action);
10444 }
10445 
10446 static void
10447 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10448 {
10449         dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10450         dtrace_state_t *state = ecb->dte_state;
10451         dtrace_aggid_t aggid = agg->dtag_id;
10452 
10453         ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10454         vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10455 
10456         ASSERT(state->dts_aggregations[aggid - 1] == agg);
10457         state->dts_aggregations[aggid - 1] = NULL;
10458 
10459         kmem_free(agg, sizeof (dtrace_aggregation_t));
10460 }
10461 
10462 static int
10463 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10464 {
10465         dtrace_action_t *action, *last;
10466         dtrace_difo_t *dp = desc->dtad_difo;
10467         uint32_t size = 0, align = sizeof (uint8_t), mask;
10468         uint16_t format = 0;
10469         dtrace_recdesc_t *rec;
10470         dtrace_state_t *state = ecb->dte_state;
10471         dtrace_optval_t *opt = state->dts_options, nframes, strsize;
10472         uint64_t arg = desc->dtad_arg;
10473 
10474         ASSERT(MUTEX_HELD(&dtrace_lock));
10475         ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10476 
10477         if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10478                 /*
10479                  * If this is an aggregating action, there must be neither
10480                  * a speculate nor a commit on the action chain.
10481                  */
10482                 dtrace_action_t *act;
10483 
10484                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10485                         if (act->dta_kind == DTRACEACT_COMMIT)
10486                                 return (EINVAL);
10487 
10488                         if (act->dta_kind == DTRACEACT_SPECULATE)
10489                                 return (EINVAL);
10490                 }
10491 
10492                 action = dtrace_ecb_aggregation_create(ecb, desc);
10493 
10494                 if (action == NULL)
10495                         return (EINVAL);
10496         } else {
10497                 if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10498                     (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10499                     dp != NULL && dp->dtdo_destructive)) {
10500                         state->dts_destructive = 1;
10501                 }
10502 
10503                 switch (desc->dtad_kind) {
10504                 case DTRACEACT_PRINTF:
10505                 case DTRACEACT_PRINTA:
10506                 case DTRACEACT_SYSTEM:
10507                 case DTRACEACT_FREOPEN:
10508                 case DTRACEACT_DIFEXPR:
10509                         /*
10510                          * We know that our arg is a string -- turn it into a
10511                          * format.
10512                          */
10513                         if (arg == NULL) {
10514                                 ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10515                                     desc->dtad_kind == DTRACEACT_DIFEXPR);
10516                                 format = 0;
10517                         } else {
10518                                 ASSERT(arg != NULL);
10519                                 ASSERT(arg > KERNELBASE);
10520                                 format = dtrace_format_add(state,
10521                                     (char *)(uintptr_t)arg);
10522                         }
10523 
10524                         /*FALLTHROUGH*/
10525                 case DTRACEACT_LIBACT:
10526                 case DTRACEACT_TRACEMEM:
10527                 case DTRACEACT_TRACEMEM_DYNSIZE:
10528                         if (dp == NULL)
10529                                 return (EINVAL);
10530 
10531                         if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10532                                 break;
10533 
10534                         if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10535                                 if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10536                                         return (EINVAL);
10537 
10538                                 size = opt[DTRACEOPT_STRSIZE];
10539                         }
10540 
10541                         break;
10542 
10543                 case DTRACEACT_STACK:
10544                         if ((nframes = arg) == 0) {
10545                                 nframes = opt[DTRACEOPT_STACKFRAMES];
10546                                 ASSERT(nframes > 0);
10547                                 arg = nframes;
10548                         }
10549 
10550                         size = nframes * sizeof (pc_t);
10551                         break;
10552 
10553                 case DTRACEACT_JSTACK:
10554                         if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10555                                 strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10556 
10557                         if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10558                                 nframes = opt[DTRACEOPT_JSTACKFRAMES];
10559 
10560                         arg = DTRACE_USTACK_ARG(nframes, strsize);
10561 
10562                         /*FALLTHROUGH*/
10563                 case DTRACEACT_USTACK:
10564                         if (desc->dtad_kind != DTRACEACT_JSTACK &&
10565                             (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10566                                 strsize = DTRACE_USTACK_STRSIZE(arg);
10567                                 nframes = opt[DTRACEOPT_USTACKFRAMES];
10568                                 ASSERT(nframes > 0);
10569                                 arg = DTRACE_USTACK_ARG(nframes, strsize);
10570                         }
10571 
10572                         /*
10573                          * Save a slot for the pid.
10574                          */
10575                         size = (nframes + 1) * sizeof (uint64_t);
10576                         size += DTRACE_USTACK_STRSIZE(arg);
10577                         size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10578 
10579                         break;
10580 
10581                 case DTRACEACT_SYM:
10582                 case DTRACEACT_MOD:
10583                         if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10584                             sizeof (uint64_t)) ||
10585                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10586                                 return (EINVAL);
10587                         break;
10588 
10589                 case DTRACEACT_USYM:
10590                 case DTRACEACT_UMOD:
10591                 case DTRACEACT_UADDR:
10592                         if (dp == NULL ||
10593                             (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10594                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10595                                 return (EINVAL);
10596 
10597                         /*
10598                          * We have a slot for the pid, plus a slot for the
10599                          * argument.  To keep things simple (aligned with
10600                          * bitness-neutral sizing), we store each as a 64-bit
10601                          * quantity.
10602                          */
10603                         size = 2 * sizeof (uint64_t);
10604                         break;
10605 
10606                 case DTRACEACT_STOP:
10607                 case DTRACEACT_BREAKPOINT:
10608                 case DTRACEACT_PANIC:
10609                         break;
10610 
10611                 case DTRACEACT_CHILL:
10612                 case DTRACEACT_DISCARD:
10613                 case DTRACEACT_RAISE:
10614                         if (dp == NULL)
10615                                 return (EINVAL);
10616                         break;
10617 
10618                 case DTRACEACT_EXIT:
10619                         if (dp == NULL ||
10620                             (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10621                             (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10622                                 return (EINVAL);
10623                         break;
10624 
10625                 case DTRACEACT_SPECULATE:
10626                         if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10627                                 return (EINVAL);
10628 
10629                         if (dp == NULL)
10630                                 return (EINVAL);
10631 
10632                         state->dts_speculates = 1;
10633                         break;
10634 
10635                 case DTRACEACT_COMMIT: {
10636                         dtrace_action_t *act = ecb->dte_action;
10637 
10638                         for (; act != NULL; act = act->dta_next) {
10639                                 if (act->dta_kind == DTRACEACT_COMMIT)
10640                                         return (EINVAL);
10641                         }
10642 
10643                         if (dp == NULL)
10644                                 return (EINVAL);
10645                         break;
10646                 }
10647 
10648                 default:
10649                         return (EINVAL);
10650                 }
10651 
10652                 if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10653                         /*
10654                          * If this is a data-storing action or a speculate,
10655                          * we must be sure that there isn't a commit on the
10656                          * action chain.
10657                          */
10658                         dtrace_action_t *act = ecb->dte_action;
10659 
10660                         for (; act != NULL; act = act->dta_next) {
10661                                 if (act->dta_kind == DTRACEACT_COMMIT)
10662                                         return (EINVAL);
10663                         }
10664                 }
10665 
10666                 action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10667                 action->dta_rec.dtrd_size = size;
10668         }
10669 
10670         action->dta_refcnt = 1;
10671         rec = &action->dta_rec;
10672         size = rec->dtrd_size;
10673 
10674         for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10675                 if (!(size & mask)) {
10676                         align = mask + 1;
10677                         break;
10678                 }
10679         }
10680 
10681         action->dta_kind = desc->dtad_kind;
10682 
10683         if ((action->dta_difo = dp) != NULL)
10684                 dtrace_difo_hold(dp);
10685 
10686         rec->dtrd_action = action->dta_kind;
10687         rec->dtrd_arg = arg;
10688         rec->dtrd_uarg = desc->dtad_uarg;
10689         rec->dtrd_alignment = (uint16_t)align;
10690         rec->dtrd_format = format;
10691 
10692         if ((last = ecb->dte_action_last) != NULL) {
10693                 ASSERT(ecb->dte_action != NULL);
10694                 action->dta_prev = last;
10695                 last->dta_next = action;
10696         } else {
10697                 ASSERT(ecb->dte_action == NULL);
10698                 ecb->dte_action = action;
10699         }
10700 
10701         ecb->dte_action_last = action;
10702 
10703         return (0);
10704 }
10705 
10706 static void
10707 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10708 {
10709         dtrace_action_t *act = ecb->dte_action, *next;
10710         dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10711         dtrace_difo_t *dp;
10712         uint16_t format;
10713 
10714         if (act != NULL && act->dta_refcnt > 1) {
10715                 ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10716                 act->dta_refcnt--;
10717         } else {
10718                 for (; act != NULL; act = next) {
10719                         next = act->dta_next;
10720                         ASSERT(next != NULL || act == ecb->dte_action_last);
10721                         ASSERT(act->dta_refcnt == 1);
10722 
10723                         if ((format = act->dta_rec.dtrd_format) != 0)
10724                                 dtrace_format_remove(ecb->dte_state, format);
10725 
10726                         if ((dp = act->dta_difo) != NULL)
10727                                 dtrace_difo_release(dp, vstate);
10728 
10729                         if (DTRACEACT_ISAGG(act->dta_kind)) {
10730                                 dtrace_ecb_aggregation_destroy(ecb, act);
10731                         } else {
10732                                 kmem_free(act, sizeof (dtrace_action_t));
10733                         }
10734                 }
10735         }
10736 
10737         ecb->dte_action = NULL;
10738         ecb->dte_action_last = NULL;
10739         ecb->dte_size = 0;
10740 }
10741 
10742 static void
10743 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10744 {
10745         /*
10746          * We disable the ECB by removing it from its probe.
10747          */
10748         dtrace_ecb_t *pecb, *prev = NULL;
10749         dtrace_probe_t *probe = ecb->dte_probe;
10750 
10751         ASSERT(MUTEX_HELD(&dtrace_lock));
10752 
10753         if (probe == NULL) {
10754                 /*
10755                  * This is the NULL probe; there is nothing to disable.
10756                  */
10757                 return;
10758         }
10759 
10760         for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10761                 if (pecb == ecb)
10762                         break;
10763                 prev = pecb;
10764         }
10765 
10766         ASSERT(pecb != NULL);
10767 
10768         if (prev == NULL) {
10769                 probe->dtpr_ecb = ecb->dte_next;
10770         } else {
10771                 prev->dte_next = ecb->dte_next;
10772         }
10773 
10774         if (ecb == probe->dtpr_ecb_last) {
10775                 ASSERT(ecb->dte_next == NULL);
10776                 probe->dtpr_ecb_last = prev;
10777         }
10778 
10779         /*
10780          * The ECB has been disconnected from the probe; now sync to assure
10781          * that all CPUs have seen the change before returning.
10782          */
10783         dtrace_sync();
10784 
10785         if (probe->dtpr_ecb == NULL) {
10786                 /*
10787                  * That was the last ECB on the probe; clear the predicate
10788                  * cache ID for the probe, disable it and sync one more time
10789                  * to assure that we'll never hit it again.
10790                  */
10791                 dtrace_provider_t *prov = probe->dtpr_provider;
10792 
10793                 ASSERT(ecb->dte_next == NULL);
10794                 ASSERT(probe->dtpr_ecb_last == NULL);
10795                 probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10796                 prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10797                     probe->dtpr_id, probe->dtpr_arg);
10798                 dtrace_sync();
10799         } else {
10800                 /*
10801                  * There is at least one ECB remaining on the probe.  If there
10802                  * is _exactly_ one, set the probe's predicate cache ID to be
10803                  * the predicate cache ID of the remaining ECB.
10804                  */
10805                 ASSERT(probe->dtpr_ecb_last != NULL);
10806                 ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10807 
10808                 if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10809                         dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10810 
10811                         ASSERT(probe->dtpr_ecb->dte_next == NULL);
10812 
10813                         if (p != NULL)
10814                                 probe->dtpr_predcache = p->dtp_cacheid;
10815                 }
10816 
10817                 ecb->dte_next = NULL;
10818         }
10819 }
10820 
10821 static void
10822 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10823 {
10824         dtrace_state_t *state = ecb->dte_state;
10825         dtrace_vstate_t *vstate = &state->dts_vstate;
10826         dtrace_predicate_t *pred;
10827         dtrace_epid_t epid = ecb->dte_epid;
10828 
10829         ASSERT(MUTEX_HELD(&dtrace_lock));
10830         ASSERT(ecb->dte_next == NULL);
10831         ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10832 
10833         if ((pred = ecb->dte_predicate) != NULL)
10834                 dtrace_predicate_release(pred, vstate);
10835 
10836         dtrace_ecb_action_remove(ecb);
10837 
10838         ASSERT(state->dts_ecbs[epid - 1] == ecb);
10839         state->dts_ecbs[epid - 1] = NULL;
10840 
10841         kmem_free(ecb, sizeof (dtrace_ecb_t));
10842 }
10843 
10844 static dtrace_ecb_t *
10845 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10846     dtrace_enabling_t *enab)
10847 {
10848         dtrace_ecb_t *ecb;
10849         dtrace_predicate_t *pred;
10850         dtrace_actdesc_t *act;
10851         dtrace_provider_t *prov;
10852         dtrace_ecbdesc_t *desc = enab->dten_current;
10853 
10854         ASSERT(MUTEX_HELD(&dtrace_lock));
10855         ASSERT(state != NULL);
10856 
10857         ecb = dtrace_ecb_add(state, probe);
10858         ecb->dte_uarg = desc->dted_uarg;
10859 
10860         if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10861                 dtrace_predicate_hold(pred);
10862                 ecb->dte_predicate = pred;
10863         }
10864 
10865         if (probe != NULL) {
10866                 /*
10867                  * If the provider shows more leg than the consumer is old
10868                  * enough to see, we need to enable the appropriate implicit
10869                  * predicate bits to prevent the ecb from activating at
10870                  * revealing times.
10871                  *
10872                  * Providers specifying DTRACE_PRIV_USER at register time
10873                  * are stating that they need the /proc-style privilege
10874                  * model to be enforced, and this is what DTRACE_COND_OWNER
10875                  * and DTRACE_COND_ZONEOWNER will then do at probe time.
10876                  */
10877                 prov = probe->dtpr_provider;
10878                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10879                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10880                         ecb->dte_cond |= DTRACE_COND_OWNER;
10881 
10882                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10883                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10884                         ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10885 
10886                 /*
10887                  * If the provider shows us kernel innards and the user
10888                  * is lacking sufficient privilege, enable the
10889                  * DTRACE_COND_USERMODE implicit predicate.
10890                  */
10891                 if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10892                     (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10893                         ecb->dte_cond |= DTRACE_COND_USERMODE;
10894         }
10895 
10896         if (dtrace_ecb_create_cache != NULL) {
10897                 /*
10898                  * If we have a cached ecb, we'll use its action list instead
10899                  * of creating our own (saving both time and space).
10900                  */
10901                 dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10902                 dtrace_action_t *act = cached->dte_action;
10903 
10904                 if (act != NULL) {
10905                         ASSERT(act->dta_refcnt > 0);
10906                         act->dta_refcnt++;
10907                         ecb->dte_action = act;
10908                         ecb->dte_action_last = cached->dte_action_last;
10909                         ecb->dte_needed = cached->dte_needed;
10910                         ecb->dte_size = cached->dte_size;
10911                         ecb->dte_alignment = cached->dte_alignment;
10912                 }
10913 
10914                 return (ecb);
10915         }
10916 
10917         for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10918                 if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10919                         dtrace_ecb_destroy(ecb);
10920                         return (NULL);
10921                 }
10922         }
10923 
10924         dtrace_ecb_resize(ecb);
10925 
10926         return (dtrace_ecb_create_cache = ecb);
10927 }
10928 
10929 static int
10930 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10931 {
10932         dtrace_ecb_t *ecb;
10933         dtrace_enabling_t *enab = arg;
10934         dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10935 
10936         ASSERT(state != NULL);
10937 
10938         if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10939                 /*
10940                  * This probe was created in a generation for which this
10941                  * enabling has previously created ECBs; we don't want to
10942                  * enable it again, so just kick out.
10943                  */
10944                 return (DTRACE_MATCH_NEXT);
10945         }
10946 
10947         if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10948                 return (DTRACE_MATCH_DONE);
10949 
10950         if (dtrace_ecb_enable(ecb) < 0)
10951                 return (DTRACE_MATCH_FAIL);
10952 
10953         return (DTRACE_MATCH_NEXT);
10954 }
10955 
10956 static dtrace_ecb_t *
10957 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10958 {
10959         dtrace_ecb_t *ecb;
10960 
10961         ASSERT(MUTEX_HELD(&dtrace_lock));
10962 
10963         if (id == 0 || id > state->dts_necbs)
10964                 return (NULL);
10965 
10966         ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10967         ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10968 
10969         return (state->dts_ecbs[id - 1]);
10970 }
10971 
10972 static dtrace_aggregation_t *
10973 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10974 {
10975         dtrace_aggregation_t *agg;
10976 
10977         ASSERT(MUTEX_HELD(&dtrace_lock));
10978 
10979         if (id == 0 || id > state->dts_naggregations)
10980                 return (NULL);
10981 
10982         ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10983         ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10984             agg->dtag_id == id);
10985 
10986         return (state->dts_aggregations[id - 1]);
10987 }
10988 
10989 /*
10990  * DTrace Buffer Functions
10991  *
10992  * The following functions manipulate DTrace buffers.  Most of these functions
10993  * are called in the context of establishing or processing consumer state;
10994  * exceptions are explicitly noted.
10995  */
10996 
10997 /*
10998  * Note:  called from cross call context.  This function switches the two
10999  * buffers on a given CPU.  The atomicity of this operation is assured by
11000  * disabling interrupts while the actual switch takes place; the disabling of
11001  * interrupts serializes the execution with any execution of dtrace_probe() on
11002  * the same CPU.
11003  */
11004 static void
11005 dtrace_buffer_switch(dtrace_buffer_t *buf)
11006 {
11007         caddr_t tomax = buf->dtb_tomax;
11008         caddr_t xamot = buf->dtb_xamot;
11009         dtrace_icookie_t cookie;
11010         hrtime_t now;
11011 
11012         ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11013         ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11014 
11015         cookie = dtrace_interrupt_disable();
11016         now = dtrace_gethrtime();
11017         buf->dtb_tomax = xamot;
11018         buf->dtb_xamot = tomax;
11019         buf->dtb_xamot_drops = buf->dtb_drops;
11020         buf->dtb_xamot_offset = buf->dtb_offset;
11021         buf->dtb_xamot_errors = buf->dtb_errors;
11022         buf->dtb_xamot_flags = buf->dtb_flags;
11023         buf->dtb_offset = 0;
11024         buf->dtb_drops = 0;
11025         buf->dtb_errors = 0;
11026         buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11027         buf->dtb_interval = now - buf->dtb_switched;
11028         buf->dtb_switched = now;
11029         dtrace_interrupt_enable(cookie);
11030 }
11031 
11032 /*
11033  * Note:  called from cross call context.  This function activates a buffer
11034  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
11035  * is guaranteed by the disabling of interrupts.
11036  */
11037 static void
11038 dtrace_buffer_activate(dtrace_state_t *state)
11039 {
11040         dtrace_buffer_t *buf;
11041         dtrace_icookie_t cookie = dtrace_interrupt_disable();
11042 
11043         buf = &state->dts_buffer[CPU->cpu_id];
11044 
11045         if (buf->dtb_tomax != NULL) {
11046                 /*
11047                  * We might like to assert that the buffer is marked inactive,
11048                  * but this isn't necessarily true:  the buffer for the CPU
11049                  * that processes the BEGIN probe has its buffer activated
11050                  * manually.  In this case, we take the (harmless) action
11051                  * re-clearing the bit INACTIVE bit.
11052                  */
11053                 buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11054         }
11055 
11056         dtrace_interrupt_enable(cookie);
11057 }
11058 
11059 static int
11060 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11061     processorid_t cpu, int *factor)
11062 {
11063         cpu_t *cp;
11064         dtrace_buffer_t *buf;
11065         int allocated = 0, desired = 0;
11066 
11067         ASSERT(MUTEX_HELD(&cpu_lock));
11068         ASSERT(MUTEX_HELD(&dtrace_lock));
11069 
11070         *factor = 1;
11071 
11072         if (size > dtrace_nonroot_maxsize &&
11073             !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11074                 return (EFBIG);
11075 
11076         cp = cpu_list;
11077 
11078         do {
11079                 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11080                         continue;
11081 
11082                 buf = &bufs[cp->cpu_id];
11083 
11084                 /*
11085                  * If there is already a buffer allocated for this CPU, it
11086                  * is only possible that this is a DR event.  In this case,
11087                  * the buffer size must match our specified size.
11088                  */
11089                 if (buf->dtb_tomax != NULL) {
11090                         ASSERT(buf->dtb_size == size);
11091                         continue;
11092                 }
11093 
11094                 ASSERT(buf->dtb_xamot == NULL);
11095 
11096                 if ((buf->dtb_tomax = kmem_zalloc(size,
11097                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11098                         goto err;
11099 
11100                 buf->dtb_size = size;
11101                 buf->dtb_flags = flags;
11102                 buf->dtb_offset = 0;
11103                 buf->dtb_drops = 0;
11104 
11105                 if (flags & DTRACEBUF_NOSWITCH)
11106                         continue;
11107 
11108                 if ((buf->dtb_xamot = kmem_zalloc(size,
11109                     KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11110                         goto err;
11111         } while ((cp = cp->cpu_next) != cpu_list);
11112 
11113         return (0);
11114 
11115 err:
11116         cp = cpu_list;
11117 
11118         do {
11119                 if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11120                         continue;
11121 
11122                 buf = &bufs[cp->cpu_id];
11123                 desired += 2;
11124 
11125                 if (buf->dtb_xamot != NULL) {
11126                         ASSERT(buf->dtb_tomax != NULL);
11127                         ASSERT(buf->dtb_size == size);
11128                         kmem_free(buf->dtb_xamot, size);
11129                         allocated++;
11130                 }
11131 
11132                 if (buf->dtb_tomax != NULL) {
11133                         ASSERT(buf->dtb_size == size);
11134                         kmem_free(buf->dtb_tomax, size);
11135                         allocated++;
11136                 }
11137 
11138                 buf->dtb_tomax = NULL;
11139                 buf->dtb_xamot = NULL;
11140                 buf->dtb_size = 0;
11141         } while ((cp = cp->cpu_next) != cpu_list);
11142 
11143         *factor = desired / (allocated > 0 ? allocated : 1);
11144 
11145         return (ENOMEM);
11146 }
11147 
11148 /*
11149  * Note:  called from probe context.  This function just increments the drop
11150  * count on a buffer.  It has been made a function to allow for the
11151  * possibility of understanding the source of mysterious drop counts.  (A
11152  * problem for which one may be particularly disappointed that DTrace cannot
11153  * be used to understand DTrace.)
11154  */
11155 static void
11156 dtrace_buffer_drop(dtrace_buffer_t *buf)
11157 {
11158         buf->dtb_drops++;
11159 }
11160 
11161 /*
11162  * Note:  called from probe context.  This function is called to reserve space
11163  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
11164  * mstate.  Returns the new offset in the buffer, or a negative value if an
11165  * error has occurred.
11166  */
11167 static intptr_t
11168 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11169     dtrace_state_t *state, dtrace_mstate_t *mstate)
11170 {
11171         intptr_t offs = buf->dtb_offset, soffs;
11172         intptr_t woffs;
11173         caddr_t tomax;
11174         size_t total;
11175 
11176         if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11177                 return (-1);
11178 
11179         if ((tomax = buf->dtb_tomax) == NULL) {
11180                 dtrace_buffer_drop(buf);
11181                 return (-1);
11182         }
11183 
11184         if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11185                 while (offs & (align - 1)) {
11186                         /*
11187                          * Assert that our alignment is off by a number which
11188                          * is itself sizeof (uint32_t) aligned.
11189                          */
11190                         ASSERT(!((align - (offs & (align - 1))) &
11191                             (sizeof (uint32_t) - 1)));
11192                         DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11193                         offs += sizeof (uint32_t);
11194                 }
11195 
11196                 if ((soffs = offs + needed) > buf->dtb_size) {
11197                         dtrace_buffer_drop(buf);
11198                         return (-1);
11199                 }
11200 
11201                 if (mstate == NULL)
11202                         return (offs);
11203 
11204                 mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11205                 mstate->dtms_scratch_size = buf->dtb_size - soffs;
11206                 mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11207 
11208                 return (offs);
11209         }
11210 
11211         if (buf->dtb_flags & DTRACEBUF_FILL) {
11212                 if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11213                     (buf->dtb_flags & DTRACEBUF_FULL))
11214                         return (-1);
11215                 goto out;
11216         }
11217 
11218         total = needed + (offs & (align - 1));
11219 
11220         /*
11221          * For a ring buffer, life is quite a bit more complicated.  Before
11222          * we can store any padding, we need to adjust our wrapping offset.
11223          * (If we've never before wrapped or we're not about to, no adjustment
11224          * is required.)
11225          */
11226         if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11227             offs + total > buf->dtb_size) {
11228                 woffs = buf->dtb_xamot_offset;
11229 
11230                 if (offs + total > buf->dtb_size) {
11231                         /*
11232                          * We can't fit in the end of the buffer.  First, a
11233                          * sanity check that we can fit in the buffer at all.
11234                          */
11235                         if (total > buf->dtb_size) {
11236                                 dtrace_buffer_drop(buf);
11237                                 return (-1);
11238                         }
11239 
11240                         /*
11241                          * We're going to be storing at the top of the buffer,
11242                          * so now we need to deal with the wrapped offset.  We
11243                          * only reset our wrapped offset to 0 if it is
11244                          * currently greater than the current offset.  If it
11245                          * is less than the current offset, it is because a
11246                          * previous allocation induced a wrap -- but the
11247                          * allocation didn't subsequently take the space due
11248                          * to an error or false predicate evaluation.  In this
11249                          * case, we'll just leave the wrapped offset alone: if
11250                          * the wrapped offset hasn't been advanced far enough
11251                          * for this allocation, it will be adjusted in the
11252                          * lower loop.
11253                          */
11254                         if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11255                                 if (woffs >= offs)
11256                                         woffs = 0;
11257                         } else {
11258                                 woffs = 0;
11259                         }
11260 
11261                         /*
11262                          * Now we know that we're going to be storing to the
11263                          * top of the buffer and that there is room for us
11264                          * there.  We need to clear the buffer from the current
11265                          * offset to the end (there may be old gunk there).
11266                          */
11267                         while (offs < buf->dtb_size)
11268                                 tomax[offs++] = 0;
11269 
11270                         /*
11271                          * We need to set our offset to zero.  And because we
11272                          * are wrapping, we need to set the bit indicating as
11273                          * much.  We can also adjust our needed space back
11274                          * down to the space required by the ECB -- we know
11275                          * that the top of the buffer is aligned.
11276                          */
11277                         offs = 0;
11278                         total = needed;
11279                         buf->dtb_flags |= DTRACEBUF_WRAPPED;
11280                 } else {
11281                         /*
11282                          * There is room for us in the buffer, so we simply
11283                          * need to check the wrapped offset.
11284                          */
11285                         if (woffs < offs) {
11286                                 /*
11287                                  * The wrapped offset is less than the offset.
11288                                  * This can happen if we allocated buffer space
11289                                  * that induced a wrap, but then we didn't
11290                                  * subsequently take the space due to an error
11291                                  * or false predicate evaluation.  This is
11292                                  * okay; we know that _this_ allocation isn't
11293                                  * going to induce a wrap.  We still can't
11294                                  * reset the wrapped offset to be zero,
11295                                  * however: the space may have been trashed in
11296                                  * the previous failed probe attempt.  But at
11297                                  * least the wrapped offset doesn't need to
11298                                  * be adjusted at all...
11299                                  */
11300                                 goto out;
11301                         }
11302                 }
11303 
11304                 while (offs + total > woffs) {
11305                         dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11306                         size_t size;
11307 
11308                         if (epid == DTRACE_EPIDNONE) {
11309                                 size = sizeof (uint32_t);
11310                         } else {
11311                                 ASSERT3U(epid, <=, state->dts_necbs);
11312                                 ASSERT(state->dts_ecbs[epid - 1] != NULL);
11313 
11314                                 size = state->dts_ecbs[epid - 1]->dte_size;
11315                         }
11316 
11317                         ASSERT(woffs + size <= buf->dtb_size);
11318                         ASSERT(size != 0);
11319 
11320                         if (woffs + size == buf->dtb_size) {
11321                                 /*
11322                                  * We've reached the end of the buffer; we want
11323                                  * to set the wrapped offset to 0 and break
11324                                  * out.  However, if the offs is 0, then we're
11325                                  * in a strange edge-condition:  the amount of
11326                                  * space that we want to reserve plus the size
11327                                  * of the record that we're overwriting is
11328                                  * greater than the size of the buffer.  This
11329                                  * is problematic because if we reserve the
11330                                  * space but subsequently don't consume it (due
11331                                  * to a failed predicate or error) the wrapped
11332                                  * offset will be 0 -- yet the EPID at offset 0
11333                                  * will not be committed.  This situation is
11334                                  * relatively easy to deal with:  if we're in
11335                                  * this case, the buffer is indistinguishable
11336                                  * from one that hasn't wrapped; we need only
11337                                  * finish the job by clearing the wrapped bit,
11338                                  * explicitly setting the offset to be 0, and
11339                                  * zero'ing out the old data in the buffer.
11340                                  */
11341                                 if (offs == 0) {
11342                                         buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11343                                         buf->dtb_offset = 0;
11344                                         woffs = total;
11345 
11346                                         while (woffs < buf->dtb_size)
11347                                                 tomax[woffs++] = 0;
11348                                 }
11349 
11350                                 woffs = 0;
11351                                 break;
11352                         }
11353 
11354                         woffs += size;
11355                 }
11356 
11357                 /*
11358                  * We have a wrapped offset.  It may be that the wrapped offset
11359                  * has become zero -- that's okay.
11360                  */
11361                 buf->dtb_xamot_offset = woffs;
11362         }
11363 
11364 out:
11365         /*
11366          * Now we can plow the buffer with any necessary padding.
11367          */
11368         while (offs & (align - 1)) {
11369                 /*
11370                  * Assert that our alignment is off by a number which
11371                  * is itself sizeof (uint32_t) aligned.
11372                  */
11373                 ASSERT(!((align - (offs & (align - 1))) &
11374                     (sizeof (uint32_t) - 1)));
11375                 DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11376                 offs += sizeof (uint32_t);
11377         }
11378 
11379         if (buf->dtb_flags & DTRACEBUF_FILL) {
11380                 if (offs + needed > buf->dtb_size - state->dts_reserve) {
11381                         buf->dtb_flags |= DTRACEBUF_FULL;
11382                         return (-1);
11383                 }
11384         }
11385 
11386         if (mstate == NULL)
11387                 return (offs);
11388 
11389         /*
11390          * For ring buffers and fill buffers, the scratch space is always
11391          * the inactive buffer.
11392          */
11393         mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11394         mstate->dtms_scratch_size = buf->dtb_size;
11395         mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11396 
11397         return (offs);
11398 }
11399 
11400 static void
11401 dtrace_buffer_polish(dtrace_buffer_t *buf)
11402 {
11403         ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11404         ASSERT(MUTEX_HELD(&dtrace_lock));
11405 
11406         if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11407                 return;
11408 
11409         /*
11410          * We need to polish the ring buffer.  There are three cases:
11411          *
11412          * - The first (and presumably most common) is that there is no gap
11413          *   between the buffer offset and the wrapped offset.  In this case,
11414          *   there is nothing in the buffer that isn't valid data; we can
11415          *   mark the buffer as polished and return.
11416          *
11417          * - The second (less common than the first but still more common
11418          *   than the third) is that there is a gap between the buffer offset
11419          *   and the wrapped offset, and the wrapped offset is larger than the
11420          *   buffer offset.  This can happen because of an alignment issue, or
11421          *   can happen because of a call to dtrace_buffer_reserve() that
11422          *   didn't subsequently consume the buffer space.  In this case,
11423          *   we need to zero the data from the buffer offset to the wrapped
11424          *   offset.
11425          *
11426          * - The third (and least common) is that there is a gap between the
11427          *   buffer offset and the wrapped offset, but the wrapped offset is
11428          *   _less_ than the buffer offset.  This can only happen because a
11429          *   call to dtrace_buffer_reserve() induced a wrap, but the space
11430          *   was not subsequently consumed.  In this case, we need to zero the
11431          *   space from the offset to the end of the buffer _and_ from the
11432          *   top of the buffer to the wrapped offset.
11433          */
11434         if (buf->dtb_offset < buf->dtb_xamot_offset) {
11435                 bzero(buf->dtb_tomax + buf->dtb_offset,
11436                     buf->dtb_xamot_offset - buf->dtb_offset);
11437         }
11438 
11439         if (buf->dtb_offset > buf->dtb_xamot_offset) {
11440                 bzero(buf->dtb_tomax + buf->dtb_offset,
11441                     buf->dtb_size - buf->dtb_offset);
11442                 bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11443         }
11444 }
11445 
11446 /*
11447  * This routine determines if data generated at the specified time has likely
11448  * been entirely consumed at user-level.  This routine is called to determine
11449  * if an ECB on a defunct probe (but for an active enabling) can be safely
11450  * disabled and destroyed.
11451  */
11452 static int
11453 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
11454 {
11455         int i;
11456 
11457         for (i = 0; i < NCPU; i++) {
11458                 dtrace_buffer_t *buf = &bufs[i];
11459 
11460                 if (buf->dtb_size == 0)
11461                         continue;
11462 
11463                 if (buf->dtb_flags & DTRACEBUF_RING)
11464                         return (0);
11465 
11466                 if (!buf->dtb_switched && buf->dtb_offset != 0)
11467                         return (0);
11468 
11469                 if (buf->dtb_switched - buf->dtb_interval < when)
11470                         return (0);
11471         }
11472 
11473         return (1);
11474 }
11475 
11476 static void
11477 dtrace_buffer_free(dtrace_buffer_t *bufs)
11478 {
11479         int i;
11480 
11481         for (i = 0; i < NCPU; i++) {
11482                 dtrace_buffer_t *buf = &bufs[i];
11483 
11484                 if (buf->dtb_tomax == NULL) {
11485                         ASSERT(buf->dtb_xamot == NULL);
11486                         ASSERT(buf->dtb_size == 0);
11487                         continue;
11488                 }
11489 
11490                 if (buf->dtb_xamot != NULL) {
11491                         ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11492                         kmem_free(buf->dtb_xamot, buf->dtb_size);
11493                 }
11494 
11495                 kmem_free(buf->dtb_tomax, buf->dtb_size);
11496                 buf->dtb_size = 0;
11497                 buf->dtb_tomax = NULL;
11498                 buf->dtb_xamot = NULL;
11499         }
11500 }
11501 
11502 /*
11503  * DTrace Enabling Functions
11504  */
11505 static dtrace_enabling_t *
11506 dtrace_enabling_create(dtrace_vstate_t *vstate)
11507 {
11508         dtrace_enabling_t *enab;
11509 
11510         enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11511         enab->dten_vstate = vstate;
11512 
11513         return (enab);
11514 }
11515 
11516 static void
11517 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11518 {
11519         dtrace_ecbdesc_t **ndesc;
11520         size_t osize, nsize;
11521 
11522         /*
11523          * We can't add to enablings after we've enabled them, or after we've
11524          * retained them.
11525          */
11526         ASSERT(enab->dten_probegen == 0);
11527         ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11528 
11529         if (enab->dten_ndesc < enab->dten_maxdesc) {
11530                 enab->dten_desc[enab->dten_ndesc++] = ecb;
11531                 return;
11532         }
11533 
11534         osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11535 
11536         if (enab->dten_maxdesc == 0) {
11537                 enab->dten_maxdesc = 1;
11538         } else {
11539                 enab->dten_maxdesc <<= 1;
11540         }
11541 
11542         ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11543 
11544         nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11545         ndesc = kmem_zalloc(nsize, KM_SLEEP);
11546         bcopy(enab->dten_desc, ndesc, osize);
11547         kmem_free(enab->dten_desc, osize);
11548 
11549         enab->dten_desc = ndesc;
11550         enab->dten_desc[enab->dten_ndesc++] = ecb;
11551 }
11552 
11553 static void
11554 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11555     dtrace_probedesc_t *pd)
11556 {
11557         dtrace_ecbdesc_t *new;
11558         dtrace_predicate_t *pred;
11559         dtrace_actdesc_t *act;
11560 
11561         /*
11562          * We're going to create a new ECB description that matches the
11563          * specified ECB in every way, but has the specified probe description.
11564          */
11565         new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11566 
11567         if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11568                 dtrace_predicate_hold(pred);
11569 
11570         for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11571                 dtrace_actdesc_hold(act);
11572 
11573         new->dted_action = ecb->dted_action;
11574         new->dted_pred = ecb->dted_pred;
11575         new->dted_probe = *pd;
11576         new->dted_uarg = ecb->dted_uarg;
11577 
11578         dtrace_enabling_add(enab, new);
11579 }
11580 
11581 static void
11582 dtrace_enabling_dump(dtrace_enabling_t *enab)
11583 {
11584         int i;
11585 
11586         for (i = 0; i < enab->dten_ndesc; i++) {
11587                 dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11588 
11589                 cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11590                     desc->dtpd_provider, desc->dtpd_mod,
11591                     desc->dtpd_func, desc->dtpd_name);
11592         }
11593 }
11594 
11595 static void
11596 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11597 {
11598         int i;
11599         dtrace_ecbdesc_t *ep;
11600         dtrace_vstate_t *vstate = enab->dten_vstate;
11601 
11602         ASSERT(MUTEX_HELD(&dtrace_lock));
11603 
11604         for (i = 0; i < enab->dten_ndesc; i++) {
11605                 dtrace_actdesc_t *act, *next;
11606                 dtrace_predicate_t *pred;
11607 
11608                 ep = enab->dten_desc[i];
11609 
11610                 if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11611                         dtrace_predicate_release(pred, vstate);
11612 
11613                 for (act = ep->dted_action; act != NULL; act = next) {
11614                         next = act->dtad_next;
11615                         dtrace_actdesc_release(act, vstate);
11616                 }
11617 
11618                 kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11619         }
11620 
11621         kmem_free(enab->dten_desc,
11622             enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11623 
11624         /*
11625          * If this was a retained enabling, decrement the dts_nretained count
11626          * and take it off of the dtrace_retained list.
11627          */
11628         if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11629             dtrace_retained == enab) {
11630                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11631                 ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11632                 enab->dten_vstate->dtvs_state->dts_nretained--;
11633                 dtrace_retained_gen++;
11634         }
11635 
11636         if (enab->dten_prev == NULL) {
11637                 if (dtrace_retained == enab) {
11638                         dtrace_retained = enab->dten_next;
11639 
11640                         if (dtrace_retained != NULL)
11641                                 dtrace_retained->dten_prev = NULL;
11642                 }
11643         } else {
11644                 ASSERT(enab != dtrace_retained);
11645                 ASSERT(dtrace_retained != NULL);
11646                 enab->dten_prev->dten_next = enab->dten_next;
11647         }
11648 
11649         if (enab->dten_next != NULL) {
11650                 ASSERT(dtrace_retained != NULL);
11651                 enab->dten_next->dten_prev = enab->dten_prev;
11652         }
11653 
11654         kmem_free(enab, sizeof (dtrace_enabling_t));
11655 }
11656 
11657 static int
11658 dtrace_enabling_retain(dtrace_enabling_t *enab)
11659 {
11660         dtrace_state_t *state;
11661 
11662         ASSERT(MUTEX_HELD(&dtrace_lock));
11663         ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11664         ASSERT(enab->dten_vstate != NULL);
11665 
11666         state = enab->dten_vstate->dtvs_state;
11667         ASSERT(state != NULL);
11668 
11669         /*
11670          * We only allow each state to retain dtrace_retain_max enablings.
11671          */
11672         if (state->dts_nretained >= dtrace_retain_max)
11673                 return (ENOSPC);
11674 
11675         state->dts_nretained++;
11676         dtrace_retained_gen++;
11677 
11678         if (dtrace_retained == NULL) {
11679                 dtrace_retained = enab;
11680                 return (0);
11681         }
11682 
11683         enab->dten_next = dtrace_retained;
11684         dtrace_retained->dten_prev = enab;
11685         dtrace_retained = enab;
11686 
11687         return (0);
11688 }
11689 
11690 static int
11691 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11692     dtrace_probedesc_t *create)
11693 {
11694         dtrace_enabling_t *new, *enab;
11695         int found = 0, err = ENOENT;
11696 
11697         ASSERT(MUTEX_HELD(&dtrace_lock));
11698         ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11699         ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11700         ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11701         ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11702 
11703         new = dtrace_enabling_create(&state->dts_vstate);
11704 
11705         /*
11706          * Iterate over all retained enablings, looking for enablings that
11707          * match the specified state.
11708          */
11709         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11710                 int i;
11711 
11712                 /*
11713                  * dtvs_state can only be NULL for helper enablings -- and
11714                  * helper enablings can't be retained.
11715                  */
11716                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11717 
11718                 if (enab->dten_vstate->dtvs_state != state)
11719                         continue;
11720 
11721                 /*
11722                  * Now iterate over each probe description; we're looking for
11723                  * an exact match to the specified probe description.
11724                  */
11725                 for (i = 0; i < enab->dten_ndesc; i++) {
11726                         dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11727                         dtrace_probedesc_t *pd = &ep->dted_probe;
11728 
11729                         if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11730                                 continue;
11731 
11732                         if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11733                                 continue;
11734 
11735                         if (strcmp(pd->dtpd_func, match->dtpd_func))
11736                                 continue;
11737 
11738                         if (strcmp(pd->dtpd_name, match->dtpd_name))
11739                                 continue;
11740 
11741                         /*
11742                          * We have a winning probe!  Add it to our growing
11743                          * enabling.
11744                          */
11745                         found = 1;
11746                         dtrace_enabling_addlike(new, ep, create);
11747                 }
11748         }
11749 
11750         if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11751                 dtrace_enabling_destroy(new);
11752                 return (err);
11753         }
11754 
11755         return (0);
11756 }
11757 
11758 static void
11759 dtrace_enabling_retract(dtrace_state_t *state)
11760 {
11761         dtrace_enabling_t *enab, *next;
11762 
11763         ASSERT(MUTEX_HELD(&dtrace_lock));
11764 
11765         /*
11766          * Iterate over all retained enablings, destroy the enablings retained
11767          * for the specified state.
11768          */
11769         for (enab = dtrace_retained; enab != NULL; enab = next) {
11770                 next = enab->dten_next;
11771 
11772                 /*
11773                  * dtvs_state can only be NULL for helper enablings -- and
11774                  * helper enablings can't be retained.
11775                  */
11776                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11777 
11778                 if (enab->dten_vstate->dtvs_state == state) {
11779                         ASSERT(state->dts_nretained > 0);
11780                         dtrace_enabling_destroy(enab);
11781                 }
11782         }
11783 
11784         ASSERT(state->dts_nretained == 0);
11785 }
11786 
11787 static int
11788 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11789 {
11790         int i = 0;
11791         int total_matched = 0, matched = 0;
11792 
11793         ASSERT(MUTEX_HELD(&cpu_lock));
11794         ASSERT(MUTEX_HELD(&dtrace_lock));
11795 
11796         for (i = 0; i < enab->dten_ndesc; i++) {
11797                 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11798 
11799                 enab->dten_current = ep;
11800                 enab->dten_error = 0;
11801 
11802                 /*
11803                  * If a provider failed to enable a probe then get out and
11804                  * let the consumer know we failed.
11805                  */
11806                 if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
11807                         return (EBUSY);
11808 
11809                 total_matched += matched;
11810 
11811                 if (enab->dten_error != 0) {
11812                         /*
11813                          * If we get an error half-way through enabling the
11814                          * probes, we kick out -- perhaps with some number of
11815                          * them enabled.  Leaving enabled probes enabled may
11816                          * be slightly confusing for user-level, but we expect
11817                          * that no one will attempt to actually drive on in
11818                          * the face of such errors.  If this is an anonymous
11819                          * enabling (indicated with a NULL nmatched pointer),
11820                          * we cmn_err() a message.  We aren't expecting to
11821                          * get such an error -- such as it can exist at all,
11822                          * it would be a result of corrupted DOF in the driver
11823                          * properties.
11824                          */
11825                         if (nmatched == NULL) {
11826                                 cmn_err(CE_WARN, "dtrace_enabling_match() "
11827                                     "error on %p: %d", (void *)ep,
11828                                     enab->dten_error);
11829                         }
11830 
11831                         return (enab->dten_error);
11832                 }
11833         }
11834 
11835         enab->dten_probegen = dtrace_probegen;
11836         if (nmatched != NULL)
11837                 *nmatched = total_matched;
11838 
11839         return (0);
11840 }
11841 
11842 static void
11843 dtrace_enabling_matchall(void)
11844 {
11845         dtrace_enabling_t *enab;
11846 
11847         mutex_enter(&cpu_lock);
11848         mutex_enter(&dtrace_lock);
11849 
11850         /*
11851          * Iterate over all retained enablings to see if any probes match
11852          * against them.  We only perform this operation on enablings for which
11853          * we have sufficient permissions by virtue of being in the global zone
11854          * or in the same zone as the DTrace client.  Because we can be called
11855          * after dtrace_detach() has been called, we cannot assert that there
11856          * are retained enablings.  We can safely load from dtrace_retained,
11857          * however:  the taskq_destroy() at the end of dtrace_detach() will
11858          * block pending our completion.
11859          */
11860         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11861                 dtrace_cred_t *dcr = &enab->dten_vstate->dtvs_state->dts_cred;
11862                 cred_t *cr = dcr->dcr_cred;
11863                 zoneid_t zone = cr != NULL ? crgetzoneid(cr) : 0;
11864 
11865                 if ((dcr->dcr_visible & DTRACE_CRV_ALLZONE) || (cr != NULL &&
11866                     (zone == GLOBAL_ZONEID || getzoneid() == zone)))
11867                         (void) dtrace_enabling_match(enab, NULL);
11868         }
11869 
11870         mutex_exit(&dtrace_lock);
11871         mutex_exit(&cpu_lock);
11872 }
11873 
11874 /*
11875  * If an enabling is to be enabled without having matched probes (that is, if
11876  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11877  * enabling must be _primed_ by creating an ECB for every ECB description.
11878  * This must be done to assure that we know the number of speculations, the
11879  * number of aggregations, the minimum buffer size needed, etc. before we
11880  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
11881  * enabling any probes, we create ECBs for every ECB decription, but with a
11882  * NULL probe -- which is exactly what this function does.
11883  */
11884 static void
11885 dtrace_enabling_prime(dtrace_state_t *state)
11886 {
11887         dtrace_enabling_t *enab;
11888         int i;
11889 
11890         for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11891                 ASSERT(enab->dten_vstate->dtvs_state != NULL);
11892 
11893                 if (enab->dten_vstate->dtvs_state != state)
11894                         continue;
11895 
11896                 /*
11897                  * We don't want to prime an enabling more than once, lest
11898                  * we allow a malicious user to induce resource exhaustion.
11899                  * (The ECBs that result from priming an enabling aren't
11900                  * leaked -- but they also aren't deallocated until the
11901                  * consumer state is destroyed.)
11902                  */
11903                 if (enab->dten_primed)
11904                         continue;
11905 
11906                 for (i = 0; i < enab->dten_ndesc; i++) {
11907                         enab->dten_current = enab->dten_desc[i];
11908                         (void) dtrace_probe_enable(NULL, enab);
11909                 }
11910 
11911                 enab->dten_primed = 1;
11912         }
11913 }
11914 
11915 /*
11916  * Called to indicate that probes should be provided due to retained
11917  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
11918  * must take an initial lap through the enabling calling the dtps_provide()
11919  * entry point explicitly to allow for autocreated probes.
11920  */
11921 static void
11922 dtrace_enabling_provide(dtrace_provider_t *prv)
11923 {
11924         int i, all = 0;
11925         dtrace_probedesc_t desc;
11926         dtrace_genid_t gen;
11927 
11928         ASSERT(MUTEX_HELD(&dtrace_lock));
11929         ASSERT(MUTEX_HELD(&dtrace_provider_lock));
11930 
11931         if (prv == NULL) {
11932                 all = 1;
11933                 prv = dtrace_provider;
11934         }
11935 
11936         do {
11937                 dtrace_enabling_t *enab;
11938                 void *parg = prv->dtpv_arg;
11939 
11940 retry:
11941                 gen = dtrace_retained_gen;
11942                 for (enab = dtrace_retained; enab != NULL;
11943                     enab = enab->dten_next) {
11944                         for (i = 0; i < enab->dten_ndesc; i++) {
11945                                 desc = enab->dten_desc[i]->dted_probe;
11946                                 mutex_exit(&dtrace_lock);
11947                                 prv->dtpv_pops.dtps_provide(parg, &desc);
11948                                 mutex_enter(&dtrace_lock);
11949                                 /*
11950                                  * Process the retained enablings again if
11951                                  * they have changed while we weren't holding
11952                                  * dtrace_lock.
11953                                  */
11954                                 if (gen != dtrace_retained_gen)
11955                                         goto retry;
11956                         }
11957                 }
11958         } while (all && (prv = prv->dtpv_next) != NULL);
11959 
11960         mutex_exit(&dtrace_lock);
11961         dtrace_probe_provide(NULL, all ? NULL : prv);
11962         mutex_enter(&dtrace_lock);
11963 }
11964 
11965 /*
11966  * Called to reap ECBs that are attached to probes from defunct providers.
11967  */
11968 static void
11969 dtrace_enabling_reap(void)
11970 {
11971         dtrace_provider_t *prov;
11972         dtrace_probe_t *probe;
11973         dtrace_ecb_t *ecb;
11974         hrtime_t when;
11975         int i;
11976 
11977         mutex_enter(&cpu_lock);
11978         mutex_enter(&dtrace_lock);
11979 
11980         for (i = 0; i < dtrace_nprobes; i++) {
11981                 if ((probe = dtrace_probes[i]) == NULL)
11982                         continue;
11983 
11984                 if (probe->dtpr_ecb == NULL)
11985                         continue;
11986 
11987                 prov = probe->dtpr_provider;
11988 
11989                 if ((when = prov->dtpv_defunct) == 0)
11990                         continue;
11991 
11992                 /*
11993                  * We have ECBs on a defunct provider:  we want to reap these
11994                  * ECBs to allow the provider to unregister.  The destruction
11995                  * of these ECBs must be done carefully:  if we destroy the ECB
11996                  * and the consumer later wishes to consume an EPID that
11997                  * corresponds to the destroyed ECB (and if the EPID metadata
11998                  * has not been previously consumed), the consumer will abort
11999                  * processing on the unknown EPID.  To reduce (but not, sadly,
12000                  * eliminate) the possibility of this, we will only destroy an
12001                  * ECB for a defunct provider if, for the state that
12002                  * corresponds to the ECB:
12003                  *
12004                  *  (a) There is no speculative tracing (which can effectively
12005                  *      cache an EPID for an arbitrary amount of time).
12006                  *
12007                  *  (b) The principal buffers have been switched twice since the
12008                  *      provider became defunct.
12009                  *
12010                  *  (c) The aggregation buffers are of zero size or have been
12011                  *      switched twice since the provider became defunct.
12012                  *
12013                  * We use dts_speculates to determine (a) and call a function
12014                  * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
12015                  * that as soon as we've been unable to destroy one of the ECBs
12016                  * associated with the probe, we quit trying -- reaping is only
12017                  * fruitful in as much as we can destroy all ECBs associated
12018                  * with the defunct provider's probes.
12019                  */
12020                 while ((ecb = probe->dtpr_ecb) != NULL) {
12021                         dtrace_state_t *state = ecb->dte_state;
12022                         dtrace_buffer_t *buf = state->dts_buffer;
12023                         dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12024 
12025                         if (state->dts_speculates)
12026                                 break;
12027 
12028                         if (!dtrace_buffer_consumed(buf, when))
12029                                 break;
12030 
12031                         if (!dtrace_buffer_consumed(aggbuf, when))
12032                                 break;
12033 
12034                         dtrace_ecb_disable(ecb);
12035                         ASSERT(probe->dtpr_ecb != ecb);
12036                         dtrace_ecb_destroy(ecb);
12037                 }
12038         }
12039 
12040         mutex_exit(&dtrace_lock);
12041         mutex_exit(&cpu_lock);
12042 }
12043 
12044 /*
12045  * DTrace DOF Functions
12046  */
12047 /*ARGSUSED*/
12048 static void
12049 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12050 {
12051         if (dtrace_err_verbose)
12052                 cmn_err(CE_WARN, "failed to process DOF: %s", str);
12053 
12054 #ifdef DTRACE_ERRDEBUG
12055         dtrace_errdebug(str);
12056 #endif
12057 }
12058 
12059 /*
12060  * Create DOF out of a currently enabled state.  Right now, we only create
12061  * DOF containing the run-time options -- but this could be expanded to create
12062  * complete DOF representing the enabled state.
12063  */
12064 static dof_hdr_t *
12065 dtrace_dof_create(dtrace_state_t *state)
12066 {
12067         dof_hdr_t *dof;
12068         dof_sec_t *sec;
12069         dof_optdesc_t *opt;
12070         int i, len = sizeof (dof_hdr_t) +
12071             roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12072             sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12073 
12074         ASSERT(MUTEX_HELD(&dtrace_lock));
12075 
12076         dof = kmem_zalloc(len, KM_SLEEP);
12077         dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12078         dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12079         dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12080         dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12081 
12082         dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12083         dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12084         dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12085         dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12086         dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12087         dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12088 
12089         dof->dofh_flags = 0;
12090         dof->dofh_hdrsize = sizeof (dof_hdr_t);
12091         dof->dofh_secsize = sizeof (dof_sec_t);
12092         dof->dofh_secnum = 1;        /* only DOF_SECT_OPTDESC */
12093         dof->dofh_secoff = sizeof (dof_hdr_t);
12094         dof->dofh_loadsz = len;
12095         dof->dofh_filesz = len;
12096         dof->dofh_pad = 0;
12097 
12098         /*
12099          * Fill in the option section header...
12100          */
12101         sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12102         sec->dofs_type = DOF_SECT_OPTDESC;
12103         sec->dofs_align = sizeof (uint64_t);
12104         sec->dofs_flags = DOF_SECF_LOAD;
12105         sec->dofs_entsize = sizeof (dof_optdesc_t);
12106 
12107         opt = (dof_optdesc_t *)((uintptr_t)sec +
12108             roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12109 
12110         sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12111         sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12112 
12113         for (i = 0; i < DTRACEOPT_MAX; i++) {
12114                 opt[i].dofo_option = i;
12115                 opt[i].dofo_strtab = DOF_SECIDX_NONE;
12116                 opt[i].dofo_value = state->dts_options[i];
12117         }
12118 
12119         return (dof);
12120 }
12121 
12122 static dof_hdr_t *
12123 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12124 {
12125         dof_hdr_t hdr, *dof;
12126 
12127         ASSERT(!MUTEX_HELD(&dtrace_lock));
12128 
12129         /*
12130          * First, we're going to copyin() the sizeof (dof_hdr_t).
12131          */
12132         if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
12133                 dtrace_dof_error(NULL, "failed to copyin DOF header");
12134                 *errp = EFAULT;
12135                 return (NULL);
12136         }
12137 
12138         /*
12139          * Now we'll allocate the entire DOF and copy it in -- provided
12140          * that the length isn't outrageous.
12141          */
12142         if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12143                 dtrace_dof_error(&hdr, "load size exceeds maximum");
12144                 *errp = E2BIG;
12145                 return (NULL);
12146         }
12147 
12148         if (hdr.dofh_loadsz < sizeof (hdr)) {
12149                 dtrace_dof_error(&hdr, "invalid load size");
12150                 *errp = EINVAL;
12151                 return (NULL);
12152         }
12153 
12154         dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12155 
12156         if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
12157             dof->dofh_loadsz != hdr.dofh_loadsz) {
12158                 kmem_free(dof, hdr.dofh_loadsz);
12159                 *errp = EFAULT;
12160                 return (NULL);
12161         }
12162 
12163         return (dof);
12164 }
12165 
12166 static dof_hdr_t *
12167 dtrace_dof_property(const char *name)
12168 {
12169         uchar_t *buf;
12170         uint64_t loadsz;
12171         unsigned int len, i;
12172         dof_hdr_t *dof;
12173 
12174         /*
12175          * Unfortunately, array of values in .conf files are always (and
12176          * only) interpreted to be integer arrays.  We must read our DOF
12177          * as an integer array, and then squeeze it into a byte array.
12178          */
12179         if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12180             (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12181                 return (NULL);
12182 
12183         for (i = 0; i < len; i++)
12184                 buf[i] = (uchar_t)(((int *)buf)[i]);
12185 
12186         if (len < sizeof (dof_hdr_t)) {
12187                 ddi_prop_free(buf);
12188                 dtrace_dof_error(NULL, "truncated header");
12189                 return (NULL);
12190         }
12191 
12192         if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12193                 ddi_prop_free(buf);
12194                 dtrace_dof_error(NULL, "truncated DOF");
12195                 return (NULL);
12196         }
12197 
12198         if (loadsz >= dtrace_dof_maxsize) {
12199                 ddi_prop_free(buf);
12200                 dtrace_dof_error(NULL, "oversized DOF");
12201                 return (NULL);
12202         }
12203 
12204         dof = kmem_alloc(loadsz, KM_SLEEP);
12205         bcopy(buf, dof, loadsz);
12206         ddi_prop_free(buf);
12207 
12208         return (dof);
12209 }
12210 
12211 static void
12212 dtrace_dof_destroy(dof_hdr_t *dof)
12213 {
12214         kmem_free(dof, dof->dofh_loadsz);
12215 }
12216 
12217 /*
12218  * Return the dof_sec_t pointer corresponding to a given section index.  If the
12219  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
12220  * a type other than DOF_SECT_NONE is specified, the header is checked against
12221  * this type and NULL is returned if the types do not match.
12222  */
12223 static dof_sec_t *
12224 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12225 {
12226         dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12227             ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12228 
12229         if (i >= dof->dofh_secnum) {
12230                 dtrace_dof_error(dof, "referenced section index is invalid");
12231                 return (NULL);
12232         }
12233 
12234         if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12235                 dtrace_dof_error(dof, "referenced section is not loadable");
12236                 return (NULL);
12237         }
12238 
12239         if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12240                 dtrace_dof_error(dof, "referenced section is the wrong type");
12241                 return (NULL);
12242         }
12243 
12244         return (sec);
12245 }
12246 
12247 static dtrace_probedesc_t *
12248 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12249 {
12250         dof_probedesc_t *probe;
12251         dof_sec_t *strtab;
12252         uintptr_t daddr = (uintptr_t)dof;
12253         uintptr_t str;
12254         size_t size;
12255 
12256         if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12257                 dtrace_dof_error(dof, "invalid probe section");
12258                 return (NULL);
12259         }
12260 
12261         if (sec->dofs_align != sizeof (dof_secidx_t)) {
12262                 dtrace_dof_error(dof, "bad alignment in probe description");
12263                 return (NULL);
12264         }
12265 
12266         if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12267                 dtrace_dof_error(dof, "truncated probe description");
12268                 return (NULL);
12269         }
12270 
12271         probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12272         strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12273 
12274         if (strtab == NULL)
12275                 return (NULL);
12276 
12277         str = daddr + strtab->dofs_offset;
12278         size = strtab->dofs_size;
12279 
12280         if (probe->dofp_provider >= strtab->dofs_size) {
12281                 dtrace_dof_error(dof, "corrupt probe provider");
12282                 return (NULL);
12283         }
12284 
12285         (void) strncpy(desc->dtpd_provider,
12286             (char *)(str + probe->dofp_provider),
12287             MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12288 
12289         if (probe->dofp_mod >= strtab->dofs_size) {
12290                 dtrace_dof_error(dof, "corrupt probe module");
12291                 return (NULL);
12292         }
12293 
12294         (void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12295             MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12296 
12297         if (probe->dofp_func >= strtab->dofs_size) {
12298                 dtrace_dof_error(dof, "corrupt probe function");
12299                 return (NULL);
12300         }
12301 
12302         (void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12303             MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12304 
12305         if (probe->dofp_name >= strtab->dofs_size) {
12306                 dtrace_dof_error(dof, "corrupt probe name");
12307                 return (NULL);
12308         }
12309 
12310         (void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12311             MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12312 
12313         return (desc);
12314 }
12315 
12316 static dtrace_difo_t *
12317 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12318     cred_t *cr)
12319 {
12320         dtrace_difo_t *dp;
12321         size_t ttl = 0;
12322         dof_difohdr_t *dofd;
12323         uintptr_t daddr = (uintptr_t)dof;
12324         size_t max = dtrace_difo_maxsize;
12325         int i, l, n;
12326 
12327         static const struct {
12328                 int section;
12329                 int bufoffs;
12330                 int lenoffs;
12331                 int entsize;
12332                 int align;
12333                 const char *msg;
12334         } difo[] = {
12335                 { DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12336                 offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12337                 sizeof (dif_instr_t), "multiple DIF sections" },
12338 
12339                 { DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12340                 offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12341                 sizeof (uint64_t), "multiple integer tables" },
12342 
12343                 { DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12344                 offsetof(dtrace_difo_t, dtdo_strlen), 0,
12345                 sizeof (char), "multiple string tables" },
12346 
12347                 { DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12348                 offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12349                 sizeof (uint_t), "multiple variable tables" },
12350 
12351                 { DOF_SECT_NONE, 0, 0, 0, NULL }
12352         };
12353 
12354         if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12355                 dtrace_dof_error(dof, "invalid DIFO header section");
12356                 return (NULL);
12357         }
12358 
12359         if (sec->dofs_align != sizeof (dof_secidx_t)) {
12360                 dtrace_dof_error(dof, "bad alignment in DIFO header");
12361                 return (NULL);
12362         }
12363 
12364         if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12365             sec->dofs_size % sizeof (dof_secidx_t)) {
12366                 dtrace_dof_error(dof, "bad size in DIFO header");
12367                 return (NULL);
12368         }
12369 
12370         dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12371         n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12372 
12373         dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12374         dp->dtdo_rtype = dofd->dofd_rtype;
12375 
12376         for (l = 0; l < n; l++) {
12377                 dof_sec_t *subsec;
12378                 void **bufp;
12379                 uint32_t *lenp;
12380 
12381                 if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12382                     dofd->dofd_links[l])) == NULL)
12383                         goto err; /* invalid section link */
12384 
12385                 if (ttl + subsec->dofs_size > max) {
12386                         dtrace_dof_error(dof, "exceeds maximum size");
12387                         goto err;
12388                 }
12389 
12390                 ttl += subsec->dofs_size;
12391 
12392                 for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12393                         if (subsec->dofs_type != difo[i].section)
12394                                 continue;
12395 
12396                         if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12397                                 dtrace_dof_error(dof, "section not loaded");
12398                                 goto err;
12399                         }
12400 
12401                         if (subsec->dofs_align != difo[i].align) {
12402                                 dtrace_dof_error(dof, "bad alignment");
12403                                 goto err;
12404                         }
12405 
12406                         bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12407                         lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12408 
12409                         if (*bufp != NULL) {
12410                                 dtrace_dof_error(dof, difo[i].msg);
12411                                 goto err;
12412                         }
12413 
12414                         if (difo[i].entsize != subsec->dofs_entsize) {
12415                                 dtrace_dof_error(dof, "entry size mismatch");
12416                                 goto err;
12417                         }
12418 
12419                         if (subsec->dofs_entsize != 0 &&
12420                             (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12421                                 dtrace_dof_error(dof, "corrupt entry size");
12422                                 goto err;
12423                         }
12424 
12425                         *lenp = subsec->dofs_size;
12426                         *bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12427                         bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12428                             *bufp, subsec->dofs_size);
12429 
12430                         if (subsec->dofs_entsize != 0)
12431                                 *lenp /= subsec->dofs_entsize;
12432 
12433                         break;
12434                 }
12435 
12436                 /*
12437                  * If we encounter a loadable DIFO sub-section that is not
12438                  * known to us, assume this is a broken program and fail.
12439                  */
12440                 if (difo[i].section == DOF_SECT_NONE &&
12441                     (subsec->dofs_flags & DOF_SECF_LOAD)) {
12442                         dtrace_dof_error(dof, "unrecognized DIFO subsection");
12443                         goto err;
12444                 }
12445         }
12446 
12447         if (dp->dtdo_buf == NULL) {
12448                 /*
12449                  * We can't have a DIF object without DIF text.
12450                  */
12451                 dtrace_dof_error(dof, "missing DIF text");
12452                 goto err;
12453         }
12454 
12455         /*
12456          * Before we validate the DIF object, run through the variable table
12457          * looking for the strings -- if any of their size are under, we'll set
12458          * their size to be the system-wide default string size.  Note that
12459          * this should _not_ happen if the "strsize" option has been set --
12460          * in this case, the compiler should have set the size to reflect the
12461          * setting of the option.
12462          */
12463         for (i = 0; i < dp->dtdo_varlen; i++) {
12464                 dtrace_difv_t *v = &dp->dtdo_vartab[i];
12465                 dtrace_diftype_t *t = &v->dtdv_type;
12466 
12467                 if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12468                         continue;
12469 
12470                 if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12471                         t->dtdt_size = dtrace_strsize_default;
12472         }
12473 
12474         if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12475                 goto err;
12476 
12477         dtrace_difo_init(dp, vstate);
12478         return (dp);
12479 
12480 err:
12481         kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12482         kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12483         kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12484         kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12485 
12486         kmem_free(dp, sizeof (dtrace_difo_t));
12487         return (NULL);
12488 }
12489 
12490 static dtrace_predicate_t *
12491 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12492     cred_t *cr)
12493 {
12494         dtrace_difo_t *dp;
12495 
12496         if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12497                 return (NULL);
12498 
12499         return (dtrace_predicate_create(dp));
12500 }
12501 
12502 static dtrace_actdesc_t *
12503 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12504     cred_t *cr)
12505 {
12506         dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12507         dof_actdesc_t *desc;
12508         dof_sec_t *difosec;
12509         size_t offs;
12510         uintptr_t daddr = (uintptr_t)dof;
12511         uint64_t arg;
12512         dtrace_actkind_t kind;
12513 
12514         if (sec->dofs_type != DOF_SECT_ACTDESC) {
12515                 dtrace_dof_error(dof, "invalid action section");
12516                 return (NULL);
12517         }
12518 
12519         if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12520                 dtrace_dof_error(dof, "truncated action description");
12521                 return (NULL);
12522         }
12523 
12524         if (sec->dofs_align != sizeof (uint64_t)) {
12525                 dtrace_dof_error(dof, "bad alignment in action description");
12526                 return (NULL);
12527         }
12528 
12529         if (sec->dofs_size < sec->dofs_entsize) {
12530                 dtrace_dof_error(dof, "section entry size exceeds total size");
12531                 return (NULL);
12532         }
12533 
12534         if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12535                 dtrace_dof_error(dof, "bad entry size in action description");
12536                 return (NULL);
12537         }
12538 
12539         if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12540                 dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12541                 return (NULL);
12542         }
12543 
12544         for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12545                 desc = (dof_actdesc_t *)(daddr +
12546                     (uintptr_t)sec->dofs_offset + offs);
12547                 kind = (dtrace_actkind_t)desc->dofa_kind;
12548 
12549                 if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12550                     (kind != DTRACEACT_PRINTA ||
12551                     desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12552                     (kind == DTRACEACT_DIFEXPR &&
12553                     desc->dofa_strtab != DOF_SECIDX_NONE)) {
12554                         dof_sec_t *strtab;
12555                         char *str, *fmt;
12556                         uint64_t i;
12557 
12558                         /*
12559                          * The argument to these actions is an index into the
12560                          * DOF string table.  For printf()-like actions, this
12561                          * is the format string.  For print(), this is the
12562                          * CTF type of the expression result.
12563                          */
12564                         if ((strtab = dtrace_dof_sect(dof,
12565                             DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12566                                 goto err;
12567 
12568                         str = (char *)((uintptr_t)dof +
12569                             (uintptr_t)strtab->dofs_offset);
12570 
12571                         for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12572                                 if (str[i] == '\0')
12573                                         break;
12574                         }
12575 
12576                         if (i >= strtab->dofs_size) {
12577                                 dtrace_dof_error(dof, "bogus format string");
12578                                 goto err;
12579                         }
12580 
12581                         if (i == desc->dofa_arg) {
12582                                 dtrace_dof_error(dof, "empty format string");
12583                                 goto err;
12584                         }
12585 
12586                         i -= desc->dofa_arg;
12587                         fmt = kmem_alloc(i + 1, KM_SLEEP);
12588                         bcopy(&str[desc->dofa_arg], fmt, i + 1);
12589                         arg = (uint64_t)(uintptr_t)fmt;
12590                 } else {
12591                         if (kind == DTRACEACT_PRINTA) {
12592                                 ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12593                                 arg = 0;
12594                         } else {
12595                                 arg = desc->dofa_arg;
12596                         }
12597                 }
12598 
12599                 act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12600                     desc->dofa_uarg, arg);
12601 
12602                 if (last != NULL) {
12603                         last->dtad_next = act;
12604                 } else {
12605                         first = act;
12606                 }
12607 
12608                 last = act;
12609 
12610                 if (desc->dofa_difo == DOF_SECIDX_NONE)
12611                         continue;
12612 
12613                 if ((difosec = dtrace_dof_sect(dof,
12614                     DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12615                         goto err;
12616 
12617                 act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12618 
12619                 if (act->dtad_difo == NULL)
12620                         goto err;
12621         }
12622 
12623         ASSERT(first != NULL);
12624         return (first);
12625 
12626 err:
12627         for (act = first; act != NULL; act = next) {
12628                 next = act->dtad_next;
12629                 dtrace_actdesc_release(act, vstate);
12630         }
12631 
12632         return (NULL);
12633 }
12634 
12635 static dtrace_ecbdesc_t *
12636 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12637     cred_t *cr)
12638 {
12639         dtrace_ecbdesc_t *ep;
12640         dof_ecbdesc_t *ecb;
12641         dtrace_probedesc_t *desc;
12642         dtrace_predicate_t *pred = NULL;
12643 
12644         if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12645                 dtrace_dof_error(dof, "truncated ECB description");
12646                 return (NULL);
12647         }
12648 
12649         if (sec->dofs_align != sizeof (uint64_t)) {
12650                 dtrace_dof_error(dof, "bad alignment in ECB description");
12651                 return (NULL);
12652         }
12653 
12654         ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12655         sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12656 
12657         if (sec == NULL)
12658                 return (NULL);
12659 
12660         ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12661         ep->dted_uarg = ecb->dofe_uarg;
12662         desc = &ep->dted_probe;
12663 
12664         if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12665                 goto err;
12666 
12667         if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12668                 if ((sec = dtrace_dof_sect(dof,
12669                     DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12670                         goto err;
12671 
12672                 if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12673                         goto err;
12674 
12675                 ep->dted_pred.dtpdd_predicate = pred;
12676         }
12677 
12678         if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12679                 if ((sec = dtrace_dof_sect(dof,
12680                     DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12681                         goto err;
12682 
12683                 ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12684 
12685                 if (ep->dted_action == NULL)
12686                         goto err;
12687         }
12688 
12689         return (ep);
12690 
12691 err:
12692         if (pred != NULL)
12693                 dtrace_predicate_release(pred, vstate);
12694         kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12695         return (NULL);
12696 }
12697 
12698 /*
12699  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12700  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
12701  * site of any user SETX relocations to account for load object base address.
12702  * In the future, if we need other relocations, this function can be extended.
12703  */
12704 static int
12705 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12706 {
12707         uintptr_t daddr = (uintptr_t)dof;
12708         dof_relohdr_t *dofr =
12709             (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12710         dof_sec_t *ss, *rs, *ts;
12711         dof_relodesc_t *r;
12712         uint_t i, n;
12713 
12714         if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12715             sec->dofs_align != sizeof (dof_secidx_t)) {
12716                 dtrace_dof_error(dof, "invalid relocation header");
12717                 return (-1);
12718         }
12719 
12720         ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12721         rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12722         ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12723 
12724         if (ss == NULL || rs == NULL || ts == NULL)
12725                 return (-1); /* dtrace_dof_error() has been called already */
12726 
12727         if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12728             rs->dofs_align != sizeof (uint64_t)) {
12729                 dtrace_dof_error(dof, "invalid relocation section");
12730                 return (-1);
12731         }
12732 
12733         r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12734         n = rs->dofs_size / rs->dofs_entsize;
12735 
12736         for (i = 0; i < n; i++) {
12737                 uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12738 
12739                 switch (r->dofr_type) {
12740                 case DOF_RELO_NONE:
12741                         break;
12742                 case DOF_RELO_SETX:
12743                         if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12744                             sizeof (uint64_t) > ts->dofs_size) {
12745                                 dtrace_dof_error(dof, "bad relocation offset");
12746                                 return (-1);
12747                         }
12748 
12749                         if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12750                                 dtrace_dof_error(dof, "misaligned setx relo");
12751                                 return (-1);
12752                         }
12753 
12754                         *(uint64_t *)taddr += ubase;
12755                         break;
12756                 default:
12757                         dtrace_dof_error(dof, "invalid relocation type");
12758                         return (-1);
12759                 }
12760 
12761                 r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12762         }
12763 
12764         return (0);
12765 }
12766 
12767 /*
12768  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12769  * header:  it should be at the front of a memory region that is at least
12770  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12771  * size.  It need not be validated in any other way.
12772  */
12773 static int
12774 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12775     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12776 {
12777         uint64_t len = dof->dofh_loadsz, seclen;
12778         uintptr_t daddr = (uintptr_t)dof;
12779         dtrace_ecbdesc_t *ep;
12780         dtrace_enabling_t *enab;
12781         uint_t i;
12782 
12783         ASSERT(MUTEX_HELD(&dtrace_lock));
12784         ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12785 
12786         /*
12787          * Check the DOF header identification bytes.  In addition to checking
12788          * valid settings, we also verify that unused bits/bytes are zeroed so
12789          * we can use them later without fear of regressing existing binaries.
12790          */
12791         if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12792             DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12793                 dtrace_dof_error(dof, "DOF magic string mismatch");
12794                 return (-1);
12795         }
12796 
12797         if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12798             dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12799                 dtrace_dof_error(dof, "DOF has invalid data model");
12800                 return (-1);
12801         }
12802 
12803         if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12804                 dtrace_dof_error(dof, "DOF encoding mismatch");
12805                 return (-1);
12806         }
12807 
12808         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12809             dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12810                 dtrace_dof_error(dof, "DOF version mismatch");
12811                 return (-1);
12812         }
12813 
12814         if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12815                 dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12816                 return (-1);
12817         }
12818 
12819         if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12820                 dtrace_dof_error(dof, "DOF uses too many integer registers");
12821                 return (-1);
12822         }
12823 
12824         if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12825                 dtrace_dof_error(dof, "DOF uses too many tuple registers");
12826                 return (-1);
12827         }
12828 
12829         for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12830                 if (dof->dofh_ident[i] != 0) {
12831                         dtrace_dof_error(dof, "DOF has invalid ident byte set");
12832                         return (-1);
12833                 }
12834         }
12835 
12836         if (dof->dofh_flags & ~DOF_FL_VALID) {
12837                 dtrace_dof_error(dof, "DOF has invalid flag bits set");
12838                 return (-1);
12839         }
12840 
12841         if (dof->dofh_secsize == 0) {
12842                 dtrace_dof_error(dof, "zero section header size");
12843                 return (-1);
12844         }
12845 
12846         /*
12847          * Check that the section headers don't exceed the amount of DOF
12848          * data.  Note that we cast the section size and number of sections
12849          * to uint64_t's to prevent possible overflow in the multiplication.
12850          */
12851         seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12852 
12853         if (dof->dofh_secoff > len || seclen > len ||
12854             dof->dofh_secoff + seclen > len) {
12855                 dtrace_dof_error(dof, "truncated section headers");
12856                 return (-1);
12857         }
12858 
12859         if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12860                 dtrace_dof_error(dof, "misaligned section headers");
12861                 return (-1);
12862         }
12863 
12864         if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12865                 dtrace_dof_error(dof, "misaligned section size");
12866                 return (-1);
12867         }
12868 
12869         /*
12870          * Take an initial pass through the section headers to be sure that
12871          * the headers don't have stray offsets.  If the 'noprobes' flag is
12872          * set, do not permit sections relating to providers, probes, or args.
12873          */
12874         for (i = 0; i < dof->dofh_secnum; i++) {
12875                 dof_sec_t *sec = (dof_sec_t *)(daddr +
12876                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12877 
12878                 if (noprobes) {
12879                         switch (sec->dofs_type) {
12880                         case DOF_SECT_PROVIDER:
12881                         case DOF_SECT_PROBES:
12882                         case DOF_SECT_PRARGS:
12883                         case DOF_SECT_PROFFS:
12884                                 dtrace_dof_error(dof, "illegal sections "
12885                                     "for enabling");
12886                                 return (-1);
12887                         }
12888                 }
12889 
12890                 if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
12891                     !(sec->dofs_flags & DOF_SECF_LOAD)) {
12892                         dtrace_dof_error(dof, "loadable section with load "
12893                             "flag unset");
12894                         return (-1);
12895                 }
12896 
12897                 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12898                         continue; /* just ignore non-loadable sections */
12899 
12900                 if (sec->dofs_align & (sec->dofs_align - 1)) {
12901                         dtrace_dof_error(dof, "bad section alignment");
12902                         return (-1);
12903                 }
12904 
12905                 if (sec->dofs_offset & (sec->dofs_align - 1)) {
12906                         dtrace_dof_error(dof, "misaligned section");
12907                         return (-1);
12908                 }
12909 
12910                 if (sec->dofs_offset > len || sec->dofs_size > len ||
12911                     sec->dofs_offset + sec->dofs_size > len) {
12912                         dtrace_dof_error(dof, "corrupt section header");
12913                         return (-1);
12914                 }
12915 
12916                 if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12917                     sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12918                         dtrace_dof_error(dof, "non-terminating string table");
12919                         return (-1);
12920                 }
12921         }
12922 
12923         /*
12924          * Take a second pass through the sections and locate and perform any
12925          * relocations that are present.  We do this after the first pass to
12926          * be sure that all sections have had their headers validated.
12927          */
12928         for (i = 0; i < dof->dofh_secnum; i++) {
12929                 dof_sec_t *sec = (dof_sec_t *)(daddr +
12930                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12931 
12932                 if (!(sec->dofs_flags & DOF_SECF_LOAD))
12933                         continue; /* skip sections that are not loadable */
12934 
12935                 switch (sec->dofs_type) {
12936                 case DOF_SECT_URELHDR:
12937                         if (dtrace_dof_relocate(dof, sec, ubase) != 0)
12938                                 return (-1);
12939                         break;
12940                 }
12941         }
12942 
12943         if ((enab = *enabp) == NULL)
12944                 enab = *enabp = dtrace_enabling_create(vstate);
12945 
12946         for (i = 0; i < dof->dofh_secnum; i++) {
12947                 dof_sec_t *sec = (dof_sec_t *)(daddr +
12948                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12949 
12950                 if (sec->dofs_type != DOF_SECT_ECBDESC)
12951                         continue;
12952 
12953                 if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
12954                         dtrace_enabling_destroy(enab);
12955                         *enabp = NULL;
12956                         return (-1);
12957                 }
12958 
12959                 dtrace_enabling_add(enab, ep);
12960         }
12961 
12962         return (0);
12963 }
12964 
12965 /*
12966  * Process DOF for any options.  This routine assumes that the DOF has been
12967  * at least processed by dtrace_dof_slurp().
12968  */
12969 static int
12970 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12971 {
12972         int i, rval;
12973         uint32_t entsize;
12974         size_t offs;
12975         dof_optdesc_t *desc;
12976 
12977         for (i = 0; i < dof->dofh_secnum; i++) {
12978                 dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12979                     (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12980 
12981                 if (sec->dofs_type != DOF_SECT_OPTDESC)
12982                         continue;
12983 
12984                 if (sec->dofs_align != sizeof (uint64_t)) {
12985                         dtrace_dof_error(dof, "bad alignment in "
12986                             "option description");
12987                         return (EINVAL);
12988                 }
12989 
12990                 if ((entsize = sec->dofs_entsize) == 0) {
12991                         dtrace_dof_error(dof, "zeroed option entry size");
12992                         return (EINVAL);
12993                 }
12994 
12995                 if (entsize < sizeof (dof_optdesc_t)) {
12996                         dtrace_dof_error(dof, "bad option entry size");
12997                         return (EINVAL);
12998                 }
12999 
13000                 for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13001                         desc = (dof_optdesc_t *)((uintptr_t)dof +
13002                             (uintptr_t)sec->dofs_offset + offs);
13003 
13004                         if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13005                                 dtrace_dof_error(dof, "non-zero option string");
13006                                 return (EINVAL);
13007                         }
13008 
13009                         if (desc->dofo_value == DTRACEOPT_UNSET) {
13010                                 dtrace_dof_error(dof, "unset option");
13011                                 return (EINVAL);
13012                         }
13013 
13014                         if ((rval = dtrace_state_option(state,
13015                             desc->dofo_option, desc->dofo_value)) != 0) {
13016                                 dtrace_dof_error(dof, "rejected option");
13017                                 return (rval);
13018                         }
13019                 }
13020         }
13021 
13022         return (0);
13023 }
13024 
13025 /*
13026  * DTrace Consumer State Functions
13027  */
13028 int
13029 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13030 {
13031         size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
13032         void *base;
13033         uintptr_t limit;
13034         dtrace_dynvar_t *dvar, *next, *start;
13035         int i;
13036 
13037         ASSERT(MUTEX_HELD(&dtrace_lock));
13038         ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13039 
13040         bzero(dstate, sizeof (dtrace_dstate_t));
13041 
13042         if ((dstate->dtds_chunksize = chunksize) == 0)
13043                 dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13044 
13045         if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13046                 size = min;
13047 
13048         if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
13049                 return (ENOMEM);
13050 
13051         dstate->dtds_size = size;
13052         dstate->dtds_base = base;
13053         dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
13054         bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
13055 
13056         hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13057 
13058         if (hashsize != 1 && (hashsize & 1))
13059                 hashsize--;
13060 
13061         dstate->dtds_hashsize = hashsize;
13062         dstate->dtds_hash = dstate->dtds_base;
13063 
13064         /*
13065          * Set all of our hash buckets to point to the single sink, and (if
13066          * it hasn't already been set), set the sink's hash value to be the
13067          * sink sentinel value.  The sink is needed for dynamic variable
13068          * lookups to know that they have iterated over an entire, valid hash
13069          * chain.
13070          */
13071         for (i = 0; i < hashsize; i++)
13072                 dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13073 
13074         if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13075                 dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13076 
13077         /*
13078          * Determine number of active CPUs.  Divide free list evenly among
13079          * active CPUs.
13080          */
13081         start = (dtrace_dynvar_t *)
13082             ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13083         limit = (uintptr_t)base + size;
13084 
13085         maxper = (limit - (uintptr_t)start) / NCPU;
13086         maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13087 
13088         for (i = 0; i < NCPU; i++) {
13089                 dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13090 
13091                 /*
13092                  * If we don't even have enough chunks to make it once through
13093                  * NCPUs, we're just going to allocate everything to the first
13094                  * CPU.  And if we're on the last CPU, we're going to allocate
13095                  * whatever is left over.  In either case, we set the limit to
13096                  * be the limit of the dynamic variable space.
13097                  */
13098                 if (maxper == 0 || i == NCPU - 1) {
13099                         limit = (uintptr_t)base + size;
13100                         start = NULL;
13101                 } else {
13102                         limit = (uintptr_t)start + maxper;
13103                         start = (dtrace_dynvar_t *)limit;
13104                 }
13105 
13106                 ASSERT(limit <= (uintptr_t)base + size);
13107 
13108                 for (;;) {
13109                         next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13110                             dstate->dtds_chunksize);
13111 
13112                         if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13113                                 break;
13114 
13115                         dvar->dtdv_next = next;
13116                         dvar = next;
13117                 }
13118 
13119                 if (maxper == 0)
13120                         break;
13121         }
13122 
13123         return (0);
13124 }
13125 
13126 void
13127 dtrace_dstate_fini(dtrace_dstate_t *dstate)
13128 {
13129         ASSERT(MUTEX_HELD(&cpu_lock));
13130 
13131         if (dstate->dtds_base == NULL)
13132                 return;
13133 
13134         kmem_free(dstate->dtds_base, dstate->dtds_size);
13135         kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13136 }
13137 
13138 static void
13139 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13140 {
13141         /*
13142          * Logical XOR, where are you?
13143          */
13144         ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13145 
13146         if (vstate->dtvs_nglobals > 0) {
13147                 kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13148                     sizeof (dtrace_statvar_t *));
13149         }
13150 
13151         if (vstate->dtvs_ntlocals > 0) {
13152                 kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13153                     sizeof (dtrace_difv_t));
13154         }
13155 
13156         ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13157 
13158         if (vstate->dtvs_nlocals > 0) {
13159                 kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13160                     sizeof (dtrace_statvar_t *));
13161         }
13162 }
13163 
13164 static void
13165 dtrace_state_clean(dtrace_state_t *state)
13166 {
13167         if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13168                 return;
13169 
13170         dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13171         dtrace_speculation_clean(state);
13172 }
13173 
13174 static void
13175 dtrace_state_deadman(dtrace_state_t *state)
13176 {
13177         hrtime_t now;
13178 
13179         dtrace_sync();
13180 
13181         now = dtrace_gethrtime();
13182 
13183         if (state != dtrace_anon.dta_state &&
13184             now - state->dts_laststatus >= dtrace_deadman_user)
13185                 return;
13186 
13187         /*
13188          * We must be sure that dts_alive never appears to be less than the
13189          * value upon entry to dtrace_state_deadman(), and because we lack a
13190          * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13191          * store INT64_MAX to it, followed by a memory barrier, followed by
13192          * the new value.  This assures that dts_alive never appears to be
13193          * less than its true value, regardless of the order in which the
13194          * stores to the underlying storage are issued.
13195          */
13196         state->dts_alive = INT64_MAX;
13197         dtrace_membar_producer();
13198         state->dts_alive = now;
13199 }
13200 
13201 dtrace_state_t *
13202 dtrace_state_create(dev_t *devp, cred_t *cr)
13203 {
13204         minor_t minor;
13205         major_t major;
13206         char c[30];
13207         dtrace_state_t *state;
13208         dtrace_optval_t *opt;
13209         int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13210 
13211         ASSERT(MUTEX_HELD(&dtrace_lock));
13212         ASSERT(MUTEX_HELD(&cpu_lock));
13213 
13214         minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13215             VM_BESTFIT | VM_SLEEP);
13216 
13217         if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13218                 vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13219                 return (NULL);
13220         }
13221 
13222         state = ddi_get_soft_state(dtrace_softstate, minor);
13223         state->dts_epid = DTRACE_EPIDNONE + 1;
13224 
13225         (void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
13226         state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13227             NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13228 
13229         if (devp != NULL) {
13230                 major = getemajor(*devp);
13231         } else {
13232                 major = ddi_driver_major(dtrace_devi);
13233         }
13234 
13235         state->dts_dev = makedevice(major, minor);
13236 
13237         if (devp != NULL)
13238                 *devp = state->dts_dev;
13239 
13240         /*
13241          * We allocate NCPU buffers.  On the one hand, this can be quite
13242          * a bit of memory per instance (nearly 36K on a Starcat).  On the
13243          * other hand, it saves an additional memory reference in the probe
13244          * path.
13245          */
13246         state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13247         state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13248         state->dts_cleaner = CYCLIC_NONE;
13249         state->dts_deadman = CYCLIC_NONE;
13250         state->dts_vstate.dtvs_state = state;
13251 
13252         for (i = 0; i < DTRACEOPT_MAX; i++)
13253                 state->dts_options[i] = DTRACEOPT_UNSET;
13254 
13255         /*
13256          * Set the default options.
13257          */
13258         opt = state->dts_options;
13259         opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13260         opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13261         opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13262         opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13263         opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13264         opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13265         opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13266         opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13267         opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13268         opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13269         opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13270         opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13271         opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13272         opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13273 
13274         state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13275 
13276         /*
13277          * Depending on the user credentials, we set flag bits which alter probe
13278          * visibility or the amount of destructiveness allowed.  In the case of
13279          * actual anonymous tracing, or the possession of all privileges, all of
13280          * the normal checks are bypassed.
13281          */
13282         if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13283                 state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13284                 state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13285         } else {
13286                 /*
13287                  * Set up the credentials for this instantiation.  We take a
13288                  * hold on the credential to prevent it from disappearing on
13289                  * us; this in turn prevents the zone_t referenced by this
13290                  * credential from disappearing.  This means that we can
13291                  * examine the credential and the zone from probe context.
13292                  */
13293                 crhold(cr);
13294                 state->dts_cred.dcr_cred = cr;
13295 
13296                 /*
13297                  * CRA_PROC means "we have *some* privilege for dtrace" and
13298                  * unlocks the use of variables like pid, zonename, etc.
13299                  */
13300                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13301                     PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13302                         state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13303                 }
13304 
13305                 /*
13306                  * dtrace_user allows use of syscall and profile providers.
13307                  * If the user also has proc_owner and/or proc_zone, we
13308                  * extend the scope to include additional visibility and
13309                  * destructive power.
13310                  */
13311                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13312                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13313                                 state->dts_cred.dcr_visible |=
13314                                     DTRACE_CRV_ALLPROC;
13315 
13316                                 state->dts_cred.dcr_action |=
13317                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13318                         }
13319 
13320                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13321                                 state->dts_cred.dcr_visible |=
13322                                     DTRACE_CRV_ALLZONE;
13323 
13324                                 state->dts_cred.dcr_action |=
13325                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13326                         }
13327 
13328                         /*
13329                          * If we have all privs in whatever zone this is,
13330                          * we can do destructive things to processes which
13331                          * have altered credentials.
13332                          */
13333                         if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13334                             cr->cr_zone->zone_privset)) {
13335                                 state->dts_cred.dcr_action |=
13336                                     DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13337                         }
13338                 }
13339 
13340                 /*
13341                  * Holding the dtrace_kernel privilege also implies that
13342                  * the user has the dtrace_user privilege from a visibility
13343                  * perspective.  But without further privileges, some
13344                  * destructive actions are not available.
13345                  */
13346                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13347                         /*
13348                          * Make all probes in all zones visible.  However,
13349                          * this doesn't mean that all actions become available
13350                          * to all zones.
13351                          */
13352                         state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13353                             DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13354 
13355                         state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13356                             DTRACE_CRA_PROC;
13357                         /*
13358                          * Holding proc_owner means that destructive actions
13359                          * for *this* zone are allowed.
13360                          */
13361                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13362                                 state->dts_cred.dcr_action |=
13363                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13364 
13365                         /*
13366                          * Holding proc_zone means that destructive actions
13367                          * for this user/group ID in all zones is allowed.
13368                          */
13369                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13370                                 state->dts_cred.dcr_action |=
13371                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13372 
13373                         /*
13374                          * If we have all privs in whatever zone this is,
13375                          * we can do destructive things to processes which
13376                          * have altered credentials.
13377                          */
13378                         if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13379                             cr->cr_zone->zone_privset)) {
13380                                 state->dts_cred.dcr_action |=
13381                                     DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13382                         }
13383                 }
13384 
13385                 /*
13386                  * Holding the dtrace_proc privilege gives control over fasttrap
13387                  * and pid providers.  We need to grant wider destructive
13388                  * privileges in the event that the user has proc_owner and/or
13389                  * proc_zone.
13390                  */
13391                 if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13392                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13393                                 state->dts_cred.dcr_action |=
13394                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13395 
13396                         if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13397                                 state->dts_cred.dcr_action |=
13398                                     DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13399                 }
13400         }
13401 
13402         return (state);
13403 }
13404 
13405 static int
13406 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13407 {
13408         dtrace_optval_t *opt = state->dts_options, size;
13409         processorid_t cpu;
13410         int flags = 0, rval, factor, divisor = 1;
13411 
13412         ASSERT(MUTEX_HELD(&dtrace_lock));
13413         ASSERT(MUTEX_HELD(&cpu_lock));
13414         ASSERT(which < DTRACEOPT_MAX);
13415         ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13416             (state == dtrace_anon.dta_state &&
13417             state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13418 
13419         if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13420                 return (0);
13421 
13422         if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13423                 cpu = opt[DTRACEOPT_CPU];
13424 
13425         if (which == DTRACEOPT_SPECSIZE)
13426                 flags |= DTRACEBUF_NOSWITCH;
13427 
13428         if (which == DTRACEOPT_BUFSIZE) {
13429                 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13430                         flags |= DTRACEBUF_RING;
13431 
13432                 if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13433                         flags |= DTRACEBUF_FILL;
13434 
13435                 if (state != dtrace_anon.dta_state ||
13436                     state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13437                         flags |= DTRACEBUF_INACTIVE;
13438         }
13439 
13440         for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
13441                 /*
13442                  * The size must be 8-byte aligned.  If the size is not 8-byte
13443                  * aligned, drop it down by the difference.
13444                  */
13445                 if (size & (sizeof (uint64_t) - 1))
13446                         size -= size & (sizeof (uint64_t) - 1);
13447 
13448                 if (size < state->dts_reserve) {
13449                         /*
13450                          * Buffers always must be large enough to accommodate
13451                          * their prereserved space.  We return E2BIG instead
13452                          * of ENOMEM in this case to allow for user-level
13453                          * software to differentiate the cases.
13454                          */
13455                         return (E2BIG);
13456                 }
13457 
13458                 rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
13459 
13460                 if (rval != ENOMEM) {
13461                         opt[which] = size;
13462                         return (rval);
13463                 }
13464 
13465                 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13466                         return (rval);
13467 
13468                 for (divisor = 2; divisor < factor; divisor <<= 1)
13469                         continue;
13470         }
13471 
13472         return (ENOMEM);
13473 }
13474 
13475 static int
13476 dtrace_state_buffers(dtrace_state_t *state)
13477 {
13478         dtrace_speculation_t *spec = state->dts_speculations;
13479         int rval, i;
13480 
13481         if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13482             DTRACEOPT_BUFSIZE)) != 0)
13483                 return (rval);
13484 
13485         if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13486             DTRACEOPT_AGGSIZE)) != 0)
13487                 return (rval);
13488 
13489         for (i = 0; i < state->dts_nspeculations; i++) {
13490                 if ((rval = dtrace_state_buffer(state,
13491                     spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13492                         return (rval);
13493         }
13494 
13495         return (0);
13496 }
13497 
13498 static void
13499 dtrace_state_prereserve(dtrace_state_t *state)
13500 {
13501         dtrace_ecb_t *ecb;
13502         dtrace_probe_t *probe;
13503 
13504         state->dts_reserve = 0;
13505 
13506         if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13507                 return;
13508 
13509         /*
13510          * If our buffer policy is a "fill" buffer policy, we need to set the
13511          * prereserved space to be the space required by the END probes.
13512          */
13513         probe = dtrace_probes[dtrace_probeid_end - 1];
13514         ASSERT(probe != NULL);
13515 
13516         for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13517                 if (ecb->dte_state != state)
13518                         continue;
13519 
13520                 state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13521         }
13522 }
13523 
13524 static int
13525 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13526 {
13527         dtrace_optval_t *opt = state->dts_options, sz, nspec;
13528         dtrace_speculation_t *spec;
13529         dtrace_buffer_t *buf;
13530         cyc_handler_t hdlr;
13531         cyc_time_t when;
13532         int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13533         dtrace_icookie_t cookie;
13534 
13535         mutex_enter(&cpu_lock);
13536         mutex_enter(&dtrace_lock);
13537 
13538         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13539                 rval = EBUSY;
13540                 goto out;
13541         }
13542 
13543         /*
13544          * Before we can perform any checks, we must prime all of the
13545          * retained enablings that correspond to this state.
13546          */
13547         dtrace_enabling_prime(state);
13548 
13549         if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13550                 rval = EACCES;
13551                 goto out;
13552         }
13553 
13554         dtrace_state_prereserve(state);
13555 
13556         /*
13557          * Now we want to do is try to allocate our speculations.
13558          * We do not automatically resize the number of speculations; if
13559          * this fails, we will fail the operation.
13560          */
13561         nspec = opt[DTRACEOPT_NSPEC];
13562         ASSERT(nspec != DTRACEOPT_UNSET);
13563 
13564         if (nspec > INT_MAX) {
13565                 rval = ENOMEM;
13566                 goto out;
13567         }
13568 
13569         spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
13570             KM_NOSLEEP | KM_NORMALPRI);
13571 
13572         if (spec == NULL) {
13573                 rval = ENOMEM;
13574                 goto out;
13575         }
13576 
13577         state->dts_speculations = spec;
13578         state->dts_nspeculations = (int)nspec;
13579 
13580         for (i = 0; i < nspec; i++) {
13581                 if ((buf = kmem_zalloc(bufsize,
13582                     KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
13583                         rval = ENOMEM;
13584                         goto err;
13585                 }
13586 
13587                 spec[i].dtsp_buffer = buf;
13588         }
13589 
13590         if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13591                 if (dtrace_anon.dta_state == NULL) {
13592                         rval = ENOENT;
13593                         goto out;
13594                 }
13595 
13596                 if (state->dts_necbs != 0) {
13597                         rval = EALREADY;
13598                         goto out;
13599                 }
13600 
13601                 state->dts_anon = dtrace_anon_grab();
13602                 ASSERT(state->dts_anon != NULL);
13603                 state = state->dts_anon;
13604 
13605                 /*
13606                  * We want "grabanon" to be set in the grabbed state, so we'll
13607                  * copy that option value from the grabbing state into the
13608                  * grabbed state.
13609                  */
13610                 state->dts_options[DTRACEOPT_GRABANON] =
13611                     opt[DTRACEOPT_GRABANON];
13612 
13613                 *cpu = dtrace_anon.dta_beganon;
13614 
13615                 /*
13616                  * If the anonymous state is active (as it almost certainly
13617                  * is if the anonymous enabling ultimately matched anything),
13618                  * we don't allow any further option processing -- but we
13619                  * don't return failure.
13620                  */
13621                 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13622                         goto out;
13623         }
13624 
13625         if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13626             opt[DTRACEOPT_AGGSIZE] != 0) {
13627                 if (state->dts_aggregations == NULL) {
13628                         /*
13629                          * We're not going to create an aggregation buffer
13630                          * because we don't have any ECBs that contain
13631                          * aggregations -- set this option to 0.
13632                          */
13633                         opt[DTRACEOPT_AGGSIZE] = 0;
13634                 } else {
13635                         /*
13636                          * If we have an aggregation buffer, we must also have
13637                          * a buffer to use as scratch.
13638                          */
13639                         if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13640                             opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13641                                 opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13642                         }
13643                 }
13644         }
13645 
13646         if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13647             opt[DTRACEOPT_SPECSIZE] != 0) {
13648                 if (!state->dts_speculates) {
13649                         /*
13650                          * We're not going to create speculation buffers
13651                          * because we don't have any ECBs that actually
13652                          * speculate -- set the speculation size to 0.
13653                          */
13654                         opt[DTRACEOPT_SPECSIZE] = 0;
13655                 }
13656         }
13657 
13658         /*
13659          * The bare minimum size for any buffer that we're actually going to
13660          * do anything to is sizeof (uint64_t).
13661          */
13662         sz = sizeof (uint64_t);
13663 
13664         if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13665             (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13666             (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13667                 /*
13668                  * A buffer size has been explicitly set to 0 (or to a size
13669                  * that will be adjusted to 0) and we need the space -- we
13670                  * need to return failure.  We return ENOSPC to differentiate
13671                  * it from failing to allocate a buffer due to failure to meet
13672                  * the reserve (for which we return E2BIG).
13673                  */
13674                 rval = ENOSPC;
13675                 goto out;
13676         }
13677 
13678         if ((rval = dtrace_state_buffers(state)) != 0)
13679                 goto err;
13680 
13681         if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13682                 sz = dtrace_dstate_defsize;
13683 
13684         do {
13685                 rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13686 
13687                 if (rval == 0)
13688                         break;
13689 
13690                 if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13691                         goto err;
13692         } while (sz >>= 1);
13693 
13694         opt[DTRACEOPT_DYNVARSIZE] = sz;
13695 
13696         if (rval != 0)
13697                 goto err;
13698 
13699         if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13700                 opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13701 
13702         if (opt[DTRACEOPT_CLEANRATE] == 0)
13703                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13704 
13705         if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13706                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13707 
13708         if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13709                 opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13710 
13711         hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13712         hdlr.cyh_arg = state;
13713         hdlr.cyh_level = CY_LOW_LEVEL;
13714 
13715         when.cyt_when = 0;
13716         when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13717 
13718         state->dts_cleaner = cyclic_add(&hdlr, &when);
13719 
13720         hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13721         hdlr.cyh_arg = state;
13722         hdlr.cyh_level = CY_LOW_LEVEL;
13723 
13724         when.cyt_when = 0;
13725         when.cyt_interval = dtrace_deadman_interval;
13726 
13727         state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13728         state->dts_deadman = cyclic_add(&hdlr, &when);
13729 
13730         state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13731 
13732         if (state->dts_getf != 0 &&
13733             !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
13734                 /*
13735                  * We don't have kernel privs but we have at least one call
13736                  * to getf(); we need to bump our zone's count, and (if
13737                  * this is the first enabling to have an unprivileged call
13738                  * to getf()) we need to hook into closef().
13739                  */
13740                 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
13741 
13742                 if (dtrace_getf++ == 0) {
13743                         ASSERT(dtrace_closef == NULL);
13744                         dtrace_closef = dtrace_getf_barrier;
13745                 }
13746         }
13747 
13748         /*
13749          * Now it's time to actually fire the BEGIN probe.  We need to disable
13750          * interrupts here both to record the CPU on which we fired the BEGIN
13751          * probe (the data from this CPU will be processed first at user
13752          * level) and to manually activate the buffer for this CPU.
13753          */
13754         cookie = dtrace_interrupt_disable();
13755         *cpu = CPU->cpu_id;
13756         ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13757         state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13758 
13759         dtrace_probe(dtrace_probeid_begin,
13760             (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13761         dtrace_interrupt_enable(cookie);
13762         /*
13763          * We may have had an exit action from a BEGIN probe; only change our
13764          * state to ACTIVE if we're still in WARMUP.
13765          */
13766         ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13767             state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13768 
13769         if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13770                 state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13771 
13772         /*
13773          * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13774          * want each CPU to transition its principal buffer out of the
13775          * INACTIVE state.  Doing this assures that no CPU will suddenly begin
13776          * processing an ECB halfway down a probe's ECB chain; all CPUs will
13777          * atomically transition from processing none of a state's ECBs to
13778          * processing all of them.
13779          */
13780         dtrace_xcall(DTRACE_CPUALL,
13781             (dtrace_xcall_t)dtrace_buffer_activate, state);
13782         goto out;
13783 
13784 err:
13785         dtrace_buffer_free(state->dts_buffer);
13786         dtrace_buffer_free(state->dts_aggbuffer);
13787 
13788         if ((nspec = state->dts_nspeculations) == 0) {
13789                 ASSERT(state->dts_speculations == NULL);
13790                 goto out;
13791         }
13792 
13793         spec = state->dts_speculations;
13794         ASSERT(spec != NULL);
13795 
13796         for (i = 0; i < state->dts_nspeculations; i++) {
13797                 if ((buf = spec[i].dtsp_buffer) == NULL)
13798                         break;
13799 
13800                 dtrace_buffer_free(buf);
13801                 kmem_free(buf, bufsize);
13802         }
13803 
13804         kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13805         state->dts_nspeculations = 0;
13806         state->dts_speculations = NULL;
13807 
13808 out:
13809         mutex_exit(&dtrace_lock);
13810         mutex_exit(&cpu_lock);
13811 
13812         return (rval);
13813 }
13814 
13815 static int
13816 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13817 {
13818         dtrace_icookie_t cookie;
13819 
13820         ASSERT(MUTEX_HELD(&dtrace_lock));
13821 
13822         if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13823             state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13824                 return (EINVAL);
13825 
13826         /*
13827          * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13828          * to be sure that every CPU has seen it.  See below for the details
13829          * on why this is done.
13830          */
13831         state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13832         dtrace_sync();
13833 
13834         /*
13835          * By this point, it is impossible for any CPU to be still processing
13836          * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
13837          * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13838          * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
13839          * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13840          * iff we're in the END probe.
13841          */
13842         state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13843         dtrace_sync();
13844         ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13845 
13846         /*
13847          * Finally, we can release the reserve and call the END probe.  We
13848          * disable interrupts across calling the END probe to allow us to
13849          * return the CPU on which we actually called the END probe.  This
13850          * allows user-land to be sure that this CPU's principal buffer is
13851          * processed last.
13852          */
13853         state->dts_reserve = 0;
13854 
13855         cookie = dtrace_interrupt_disable();
13856         *cpu = CPU->cpu_id;
13857         dtrace_probe(dtrace_probeid_end,
13858             (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13859         dtrace_interrupt_enable(cookie);
13860 
13861         state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13862         dtrace_sync();
13863 
13864         if (state->dts_getf != 0 &&
13865             !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
13866                 /*
13867                  * We don't have kernel privs but we have at least one call
13868                  * to getf(); we need to lower our zone's count, and (if
13869                  * this is the last enabling to have an unprivileged call
13870                  * to getf()) we need to clear the closef() hook.
13871                  */
13872                 ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
13873                 ASSERT(dtrace_closef == dtrace_getf_barrier);
13874                 ASSERT(dtrace_getf > 0);
13875 
13876                 state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
13877 
13878                 if (--dtrace_getf == 0)
13879                         dtrace_closef = NULL;
13880         }
13881 
13882         return (0);
13883 }
13884 
13885 static int
13886 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13887     dtrace_optval_t val)
13888 {
13889         ASSERT(MUTEX_HELD(&dtrace_lock));
13890 
13891         if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13892                 return (EBUSY);
13893 
13894         if (option >= DTRACEOPT_MAX)
13895                 return (EINVAL);
13896 
13897         if (option != DTRACEOPT_CPU && val < 0)
13898                 return (EINVAL);
13899 
13900         switch (option) {
13901         case DTRACEOPT_DESTRUCTIVE:
13902                 if (dtrace_destructive_disallow)
13903                         return (EACCES);
13904 
13905                 state->dts_cred.dcr_destructive = 1;
13906                 break;
13907 
13908         case DTRACEOPT_BUFSIZE:
13909         case DTRACEOPT_DYNVARSIZE:
13910         case DTRACEOPT_AGGSIZE:
13911         case DTRACEOPT_SPECSIZE:
13912         case DTRACEOPT_STRSIZE:
13913                 if (val < 0)
13914                         return (EINVAL);
13915 
13916                 if (val >= LONG_MAX) {
13917                         /*
13918                          * If this is an otherwise negative value, set it to
13919                          * the highest multiple of 128m less than LONG_MAX.
13920                          * Technically, we're adjusting the size without
13921                          * regard to the buffer resizing policy, but in fact,
13922                          * this has no effect -- if we set the buffer size to
13923                          * ~LONG_MAX and the buffer policy is ultimately set to
13924                          * be "manual", the buffer allocation is guaranteed to
13925                          * fail, if only because the allocation requires two
13926                          * buffers.  (We set the the size to the highest
13927                          * multiple of 128m because it ensures that the size
13928                          * will remain a multiple of a megabyte when
13929                          * repeatedly halved -- all the way down to 15m.)
13930                          */
13931                         val = LONG_MAX - (1 << 27) + 1;
13932                 }
13933         }
13934 
13935         state->dts_options[option] = val;
13936 
13937         return (0);
13938 }
13939 
13940 static void
13941 dtrace_state_destroy(dtrace_state_t *state)
13942 {
13943         dtrace_ecb_t *ecb;
13944         dtrace_vstate_t *vstate = &state->dts_vstate;
13945         minor_t minor = getminor(state->dts_dev);
13946         int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13947         dtrace_speculation_t *spec = state->dts_speculations;
13948         int nspec = state->dts_nspeculations;
13949         uint32_t match;
13950 
13951         ASSERT(MUTEX_HELD(&dtrace_lock));
13952         ASSERT(MUTEX_HELD(&cpu_lock));
13953 
13954         /*
13955          * First, retract any retained enablings for this state.
13956          */
13957         dtrace_enabling_retract(state);
13958         ASSERT(state->dts_nretained == 0);
13959 
13960         if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13961             state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13962                 /*
13963                  * We have managed to come into dtrace_state_destroy() on a
13964                  * hot enabling -- almost certainly because of a disorderly
13965                  * shutdown of a consumer.  (That is, a consumer that is
13966                  * exiting without having called dtrace_stop().) In this case,
13967                  * we're going to set our activity to be KILLED, and then
13968                  * issue a sync to be sure that everyone is out of probe
13969                  * context before we start blowing away ECBs.
13970                  */
13971                 state->dts_activity = DTRACE_ACTIVITY_KILLED;
13972                 dtrace_sync();
13973         }
13974 
13975         /*
13976          * Release the credential hold we took in dtrace_state_create().
13977          */
13978         if (state->dts_cred.dcr_cred != NULL)
13979                 crfree(state->dts_cred.dcr_cred);
13980 
13981         /*
13982          * Now we can safely disable and destroy any enabled probes.  Because
13983          * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13984          * (especially if they're all enabled), we take two passes through the
13985          * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13986          * in the second we disable whatever is left over.
13987          */
13988         for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13989                 for (i = 0; i < state->dts_necbs; i++) {
13990                         if ((ecb = state->dts_ecbs[i]) == NULL)
13991                                 continue;
13992 
13993                         if (match && ecb->dte_probe != NULL) {
13994                                 dtrace_probe_t *probe = ecb->dte_probe;
13995                                 dtrace_provider_t *prov = probe->dtpr_provider;
13996 
13997                                 if (!(prov->dtpv_priv.dtpp_flags & match))
13998                                         continue;
13999                         }
14000 
14001                         dtrace_ecb_disable(ecb);
14002                         dtrace_ecb_destroy(ecb);
14003                 }
14004 
14005                 if (!match)
14006                         break;
14007         }
14008 
14009         /*
14010          * Before we free the buffers, perform one more sync to assure that
14011          * every CPU is out of probe context.
14012          */
14013         dtrace_sync();
14014 
14015         dtrace_buffer_free(state->dts_buffer);
14016         dtrace_buffer_free(state->dts_aggbuffer);
14017 
14018         for (i = 0; i < nspec; i++)
14019                 dtrace_buffer_free(spec[i].dtsp_buffer);
14020 
14021         if (state->dts_cleaner != CYCLIC_NONE)
14022                 cyclic_remove(state->dts_cleaner);
14023 
14024         if (state->dts_deadman != CYCLIC_NONE)
14025                 cyclic_remove(state->dts_deadman);
14026 
14027         dtrace_dstate_fini(&vstate->dtvs_dynvars);
14028         dtrace_vstate_fini(vstate);
14029         kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14030 
14031         if (state->dts_aggregations != NULL) {
14032 #ifdef DEBUG
14033                 for (i = 0; i < state->dts_naggregations; i++)
14034                         ASSERT(state->dts_aggregations[i] == NULL);
14035 #endif
14036                 ASSERT(state->dts_naggregations > 0);
14037                 kmem_free(state->dts_aggregations,
14038                     state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14039         }
14040 
14041         kmem_free(state->dts_buffer, bufsize);
14042         kmem_free(state->dts_aggbuffer, bufsize);
14043 
14044         for (i = 0; i < nspec; i++)
14045                 kmem_free(spec[i].dtsp_buffer, bufsize);
14046 
14047         kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14048 
14049         dtrace_format_destroy(state);
14050 
14051         vmem_destroy(state->dts_aggid_arena);
14052         ddi_soft_state_free(dtrace_softstate, minor);
14053         vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14054 }
14055 
14056 /*
14057  * DTrace Anonymous Enabling Functions
14058  */
14059 static dtrace_state_t *
14060 dtrace_anon_grab(void)
14061 {
14062         dtrace_state_t *state;
14063 
14064         ASSERT(MUTEX_HELD(&dtrace_lock));
14065 
14066         if ((state = dtrace_anon.dta_state) == NULL) {
14067                 ASSERT(dtrace_anon.dta_enabling == NULL);
14068                 return (NULL);
14069         }
14070 
14071         ASSERT(dtrace_anon.dta_enabling != NULL);
14072         ASSERT(dtrace_retained != NULL);
14073 
14074         dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14075         dtrace_anon.dta_enabling = NULL;
14076         dtrace_anon.dta_state = NULL;
14077 
14078         return (state);
14079 }
14080 
14081 static void
14082 dtrace_anon_property(void)
14083 {
14084         int i, rv;
14085         dtrace_state_t *state;
14086         dof_hdr_t *dof;
14087         char c[32];             /* enough for "dof-data-" + digits */
14088 
14089         ASSERT(MUTEX_HELD(&dtrace_lock));
14090         ASSERT(MUTEX_HELD(&cpu_lock));
14091 
14092         for (i = 0; ; i++) {
14093                 (void) snprintf(c, sizeof (c), "dof-data-%d", i);
14094 
14095                 dtrace_err_verbose = 1;
14096 
14097                 if ((dof = dtrace_dof_property(c)) == NULL) {
14098                         dtrace_err_verbose = 0;
14099                         break;
14100                 }
14101 
14102                 /*
14103                  * We want to create anonymous state, so we need to transition
14104                  * the kernel debugger to indicate that DTrace is active.  If
14105                  * this fails (e.g. because the debugger has modified text in
14106                  * some way), we won't continue with the processing.
14107                  */
14108                 if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14109                         cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14110                             "enabling ignored.");
14111                         dtrace_dof_destroy(dof);
14112                         break;
14113                 }
14114 
14115                 /*
14116                  * If we haven't allocated an anonymous state, we'll do so now.
14117                  */
14118                 if ((state = dtrace_anon.dta_state) == NULL) {
14119                         state = dtrace_state_create(NULL, NULL);
14120                         dtrace_anon.dta_state = state;
14121 
14122                         if (state == NULL) {
14123                                 /*
14124                                  * This basically shouldn't happen:  the only
14125                                  * failure mode from dtrace_state_create() is a
14126                                  * failure of ddi_soft_state_zalloc() that
14127                                  * itself should never happen.  Still, the
14128                                  * interface allows for a failure mode, and
14129                                  * we want to fail as gracefully as possible:
14130                                  * we'll emit an error message and cease
14131                                  * processing anonymous state in this case.
14132                                  */
14133                                 cmn_err(CE_WARN, "failed to create "
14134                                     "anonymous state");
14135                                 dtrace_dof_destroy(dof);
14136                                 break;
14137                         }
14138                 }
14139 
14140                 rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14141                     &dtrace_anon.dta_enabling, 0, B_TRUE);
14142 
14143                 if (rv == 0)
14144                         rv = dtrace_dof_options(dof, state);
14145 
14146                 dtrace_err_verbose = 0;
14147                 dtrace_dof_destroy(dof);
14148 
14149                 if (rv != 0) {
14150                         /*
14151                          * This is malformed DOF; chuck any anonymous state
14152                          * that we created.
14153                          */
14154                         ASSERT(dtrace_anon.dta_enabling == NULL);
14155                         dtrace_state_destroy(state);
14156                         dtrace_anon.dta_state = NULL;
14157                         break;
14158                 }
14159 
14160                 ASSERT(dtrace_anon.dta_enabling != NULL);
14161         }
14162 
14163         if (dtrace_anon.dta_enabling != NULL) {
14164                 int rval;
14165 
14166                 /*
14167                  * dtrace_enabling_retain() can only fail because we are
14168                  * trying to retain more enablings than are allowed -- but
14169                  * we only have one anonymous enabling, and we are guaranteed
14170                  * to be allowed at least one retained enabling; we assert
14171                  * that dtrace_enabling_retain() returns success.
14172                  */
14173                 rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14174                 ASSERT(rval == 0);
14175 
14176                 dtrace_enabling_dump(dtrace_anon.dta_enabling);
14177         }
14178 }
14179 
14180 /*
14181  * DTrace Helper Functions
14182  */
14183 static void
14184 dtrace_helper_trace(dtrace_helper_action_t *helper,
14185     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14186 {
14187         uint32_t size, next, nnext, i;
14188         dtrace_helptrace_t *ent, *buffer;
14189         uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14190 
14191         if ((buffer = dtrace_helptrace_buffer) == NULL)
14192                 return;
14193 
14194         ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14195 
14196         /*
14197          * What would a tracing framework be without its own tracing
14198          * framework?  (Well, a hell of a lot simpler, for starters...)
14199          */
14200         size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14201             sizeof (uint64_t) - sizeof (uint64_t);
14202 
14203         /*
14204          * Iterate until we can allocate a slot in the trace buffer.
14205          */
14206         do {
14207                 next = dtrace_helptrace_next;
14208 
14209                 if (next + size < dtrace_helptrace_bufsize) {
14210                         nnext = next + size;
14211                 } else {
14212                         nnext = size;
14213                 }
14214         } while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14215 
14216         /*
14217          * We have our slot; fill it in.
14218          */
14219         if (nnext == size) {
14220                 dtrace_helptrace_wrapped++;
14221                 next = 0;
14222         }
14223 
14224         ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
14225         ent->dtht_helper = helper;
14226         ent->dtht_where = where;
14227         ent->dtht_nlocals = vstate->dtvs_nlocals;
14228 
14229         ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14230             mstate->dtms_fltoffs : -1;
14231         ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14232         ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
14233 
14234         for (i = 0; i < vstate->dtvs_nlocals; i++) {
14235                 dtrace_statvar_t *svar;
14236 
14237                 if ((svar = vstate->dtvs_locals[i]) == NULL)
14238                         continue;
14239 
14240                 ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14241                 ent->dtht_locals[i] =
14242                     ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
14243         }
14244 }
14245 
14246 static uint64_t
14247 dtrace_helper(int which, dtrace_mstate_t *mstate,
14248     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14249 {
14250         uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14251         uint64_t sarg0 = mstate->dtms_arg[0];
14252         uint64_t sarg1 = mstate->dtms_arg[1];
14253         uint64_t rval;
14254         dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14255         dtrace_helper_action_t *helper;
14256         dtrace_vstate_t *vstate;
14257         dtrace_difo_t *pred;
14258         int i, trace = dtrace_helptrace_buffer != NULL;
14259 
14260         ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14261 
14262         if (helpers == NULL)
14263                 return (0);
14264 
14265         if ((helper = helpers->dthps_actions[which]) == NULL)
14266                 return (0);
14267 
14268         vstate = &helpers->dthps_vstate;
14269         mstate->dtms_arg[0] = arg0;
14270         mstate->dtms_arg[1] = arg1;
14271 
14272         /*
14273          * Now iterate over each helper.  If its predicate evaluates to 'true',
14274          * we'll call the corresponding actions.  Note that the below calls
14275          * to dtrace_dif_emulate() may set faults in machine state.  This is
14276          * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
14277          * the stored DIF offset with its own (which is the desired behavior).
14278          * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14279          * from machine state; this is okay, too.
14280          */
14281         for (; helper != NULL; helper = helper->dtha_next) {
14282                 if ((pred = helper->dtha_predicate) != NULL) {
14283                         if (trace)
14284                                 dtrace_helper_trace(helper, mstate, vstate, 0);
14285 
14286                         if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14287                                 goto next;
14288 
14289                         if (*flags & CPU_DTRACE_FAULT)
14290                                 goto err;
14291                 }
14292 
14293                 for (i = 0; i < helper->dtha_nactions; i++) {
14294                         if (trace)
14295                                 dtrace_helper_trace(helper,
14296                                     mstate, vstate, i + 1);
14297 
14298                         rval = dtrace_dif_emulate(helper->dtha_actions[i],
14299                             mstate, vstate, state);
14300 
14301                         if (*flags & CPU_DTRACE_FAULT)
14302                                 goto err;
14303                 }
14304 
14305 next:
14306                 if (trace)
14307                         dtrace_helper_trace(helper, mstate, vstate,
14308                             DTRACE_HELPTRACE_NEXT);
14309         }
14310 
14311         if (trace)
14312                 dtrace_helper_trace(helper, mstate, vstate,
14313                     DTRACE_HELPTRACE_DONE);
14314 
14315         /*
14316          * Restore the arg0 that we saved upon entry.
14317          */
14318         mstate->dtms_arg[0] = sarg0;
14319         mstate->dtms_arg[1] = sarg1;
14320 
14321         return (rval);
14322 
14323 err:
14324         if (trace)
14325                 dtrace_helper_trace(helper, mstate, vstate,
14326                     DTRACE_HELPTRACE_ERR);
14327 
14328         /*
14329          * Restore the arg0 that we saved upon entry.
14330          */
14331         mstate->dtms_arg[0] = sarg0;
14332         mstate->dtms_arg[1] = sarg1;
14333 
14334         return (NULL);
14335 }
14336 
14337 static void
14338 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14339     dtrace_vstate_t *vstate)
14340 {
14341         int i;
14342 
14343         if (helper->dtha_predicate != NULL)
14344                 dtrace_difo_release(helper->dtha_predicate, vstate);
14345 
14346         for (i = 0; i < helper->dtha_nactions; i++) {
14347                 ASSERT(helper->dtha_actions[i] != NULL);
14348                 dtrace_difo_release(helper->dtha_actions[i], vstate);
14349         }
14350 
14351         kmem_free(helper->dtha_actions,
14352             helper->dtha_nactions * sizeof (dtrace_difo_t *));
14353         kmem_free(helper, sizeof (dtrace_helper_action_t));
14354 }
14355 
14356 static int
14357 dtrace_helper_destroygen(int gen)
14358 {
14359         proc_t *p = curproc;
14360         dtrace_helpers_t *help = p->p_dtrace_helpers;
14361         dtrace_vstate_t *vstate;
14362         int i;
14363 
14364         ASSERT(MUTEX_HELD(&dtrace_lock));
14365 
14366         if (help == NULL || gen > help->dthps_generation)
14367                 return (EINVAL);
14368 
14369         vstate = &help->dthps_vstate;
14370 
14371         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14372                 dtrace_helper_action_t *last = NULL, *h, *next;
14373 
14374                 for (h = help->dthps_actions[i]; h != NULL; h = next) {
14375                         next = h->dtha_next;
14376 
14377                         if (h->dtha_generation == gen) {
14378                                 if (last != NULL) {
14379                                         last->dtha_next = next;
14380                                 } else {
14381                                         help->dthps_actions[i] = next;
14382                                 }
14383 
14384                                 dtrace_helper_action_destroy(h, vstate);
14385                         } else {
14386                                 last = h;
14387                         }
14388                 }
14389         }
14390 
14391         /*
14392          * Interate until we've cleared out all helper providers with the
14393          * given generation number.
14394          */
14395         for (;;) {
14396                 dtrace_helper_provider_t *prov;
14397 
14398                 /*
14399                  * Look for a helper provider with the right generation. We
14400                  * have to start back at the beginning of the list each time
14401                  * because we drop dtrace_lock. It's unlikely that we'll make
14402                  * more than two passes.
14403                  */
14404                 for (i = 0; i < help->dthps_nprovs; i++) {
14405                         prov = help->dthps_provs[i];
14406 
14407                         if (prov->dthp_generation == gen)
14408                                 break;
14409                 }
14410 
14411                 /*
14412                  * If there were no matches, we're done.
14413                  */
14414                 if (i == help->dthps_nprovs)
14415                         break;
14416 
14417                 /*
14418                  * Move the last helper provider into this slot.
14419                  */
14420                 help->dthps_nprovs--;
14421                 help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14422                 help->dthps_provs[help->dthps_nprovs] = NULL;
14423 
14424                 mutex_exit(&dtrace_lock);
14425 
14426                 /*
14427                  * If we have a meta provider, remove this helper provider.
14428                  */
14429                 mutex_enter(&dtrace_meta_lock);
14430                 if (dtrace_meta_pid != NULL) {
14431                         ASSERT(dtrace_deferred_pid == NULL);
14432                         dtrace_helper_provider_remove(&prov->dthp_prov,
14433                             p->p_pid);
14434                 }
14435                 mutex_exit(&dtrace_meta_lock);
14436 
14437                 dtrace_helper_provider_destroy(prov);
14438 
14439                 mutex_enter(&dtrace_lock);
14440         }
14441 
14442         return (0);
14443 }
14444 
14445 static int
14446 dtrace_helper_validate(dtrace_helper_action_t *helper)
14447 {
14448         int err = 0, i;
14449         dtrace_difo_t *dp;
14450 
14451         if ((dp = helper->dtha_predicate) != NULL)
14452                 err += dtrace_difo_validate_helper(dp);
14453 
14454         for (i = 0; i < helper->dtha_nactions; i++)
14455                 err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14456 
14457         return (err == 0);
14458 }
14459 
14460 static int
14461 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14462 {
14463         dtrace_helpers_t *help;
14464         dtrace_helper_action_t *helper, *last;
14465         dtrace_actdesc_t *act;
14466         dtrace_vstate_t *vstate;
14467         dtrace_predicate_t *pred;
14468         int count = 0, nactions = 0, i;
14469 
14470         if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14471                 return (EINVAL);
14472 
14473         help = curproc->p_dtrace_helpers;
14474         last = help->dthps_actions[which];
14475         vstate = &help->dthps_vstate;
14476 
14477         for (count = 0; last != NULL; last = last->dtha_next) {
14478                 count++;
14479                 if (last->dtha_next == NULL)
14480                         break;
14481         }
14482 
14483         /*
14484          * If we already have dtrace_helper_actions_max helper actions for this
14485          * helper action type, we'll refuse to add a new one.
14486          */
14487         if (count >= dtrace_helper_actions_max)
14488                 return (ENOSPC);
14489 
14490         helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14491         helper->dtha_generation = help->dthps_generation;
14492 
14493         if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14494                 ASSERT(pred->dtp_difo != NULL);
14495                 dtrace_difo_hold(pred->dtp_difo);
14496                 helper->dtha_predicate = pred->dtp_difo;
14497         }
14498 
14499         for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14500                 if (act->dtad_kind != DTRACEACT_DIFEXPR)
14501                         goto err;
14502 
14503                 if (act->dtad_difo == NULL)
14504                         goto err;
14505 
14506                 nactions++;
14507         }
14508 
14509         helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14510             (helper->dtha_nactions = nactions), KM_SLEEP);
14511 
14512         for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14513                 dtrace_difo_hold(act->dtad_difo);
14514                 helper->dtha_actions[i++] = act->dtad_difo;
14515         }
14516 
14517         if (!dtrace_helper_validate(helper))
14518                 goto err;
14519 
14520         if (last == NULL) {
14521                 help->dthps_actions[which] = helper;
14522         } else {
14523                 last->dtha_next = helper;
14524         }
14525 
14526         if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14527                 dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14528                 dtrace_helptrace_next = 0;
14529         }
14530 
14531         return (0);
14532 err:
14533         dtrace_helper_action_destroy(helper, vstate);
14534         return (EINVAL);
14535 }
14536 
14537 static void
14538 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14539     dof_helper_t *dofhp)
14540 {
14541         ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
14542 
14543         mutex_enter(&dtrace_meta_lock);
14544         mutex_enter(&dtrace_lock);
14545 
14546         if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14547                 /*
14548                  * If the dtrace module is loaded but not attached, or if
14549                  * there aren't isn't a meta provider registered to deal with
14550                  * these provider descriptions, we need to postpone creating
14551                  * the actual providers until later.
14552                  */
14553 
14554                 if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14555                     dtrace_deferred_pid != help) {
14556                         help->dthps_deferred = 1;
14557                         help->dthps_pid = p->p_pid;
14558                         help->dthps_next = dtrace_deferred_pid;
14559                         help->dthps_prev = NULL;
14560                         if (dtrace_deferred_pid != NULL)
14561                                 dtrace_deferred_pid->dthps_prev = help;
14562                         dtrace_deferred_pid = help;
14563                 }
14564 
14565                 mutex_exit(&dtrace_lock);
14566 
14567         } else if (dofhp != NULL) {
14568                 /*
14569                  * If the dtrace module is loaded and we have a particular
14570                  * helper provider description, pass that off to the
14571                  * meta provider.
14572                  */
14573 
14574                 mutex_exit(&dtrace_lock);
14575 
14576                 dtrace_helper_provide(dofhp, p->p_pid);
14577 
14578         } else {
14579                 /*
14580                  * Otherwise, just pass all the helper provider descriptions
14581                  * off to the meta provider.
14582                  */
14583 
14584                 int i;
14585                 mutex_exit(&dtrace_lock);
14586 
14587                 for (i = 0; i < help->dthps_nprovs; i++) {
14588                         dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14589                             p->p_pid);
14590                 }
14591         }
14592 
14593         mutex_exit(&dtrace_meta_lock);
14594 }
14595 
14596 static int
14597 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14598 {
14599         dtrace_helpers_t *help;
14600         dtrace_helper_provider_t *hprov, **tmp_provs;
14601         uint_t tmp_maxprovs, i;
14602 
14603         ASSERT(MUTEX_HELD(&dtrace_lock));
14604 
14605         help = curproc->p_dtrace_helpers;
14606         ASSERT(help != NULL);
14607 
14608         /*
14609          * If we already have dtrace_helper_providers_max helper providers,
14610          * we're refuse to add a new one.
14611          */
14612         if (help->dthps_nprovs >= dtrace_helper_providers_max)
14613                 return (ENOSPC);
14614 
14615         /*
14616          * Check to make sure this isn't a duplicate.
14617          */
14618         for (i = 0; i < help->dthps_nprovs; i++) {
14619                 if (dofhp->dofhp_addr ==
14620                     help->dthps_provs[i]->dthp_prov.dofhp_addr)
14621                         return (EALREADY);
14622         }
14623 
14624         hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14625         hprov->dthp_prov = *dofhp;
14626         hprov->dthp_ref = 1;
14627         hprov->dthp_generation = gen;
14628 
14629         /*
14630          * Allocate a bigger table for helper providers if it's already full.
14631          */
14632         if (help->dthps_maxprovs == help->dthps_nprovs) {
14633                 tmp_maxprovs = help->dthps_maxprovs;
14634                 tmp_provs = help->dthps_provs;
14635 
14636                 if (help->dthps_maxprovs == 0)
14637                         help->dthps_maxprovs = 2;
14638                 else
14639                         help->dthps_maxprovs *= 2;
14640                 if (help->dthps_maxprovs > dtrace_helper_providers_max)
14641                         help->dthps_maxprovs = dtrace_helper_providers_max;
14642 
14643                 ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14644 
14645                 help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14646                     sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14647 
14648                 if (tmp_provs != NULL) {
14649                         bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14650                             sizeof (dtrace_helper_provider_t *));
14651                         kmem_free(tmp_provs, tmp_maxprovs *
14652                             sizeof (dtrace_helper_provider_t *));
14653                 }
14654         }
14655 
14656         help->dthps_provs[help->dthps_nprovs] = hprov;
14657         help->dthps_nprovs++;
14658 
14659         return (0);
14660 }
14661 
14662 static void
14663 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14664 {
14665         mutex_enter(&dtrace_lock);
14666 
14667         if (--hprov->dthp_ref == 0) {
14668                 dof_hdr_t *dof;
14669                 mutex_exit(&dtrace_lock);
14670                 dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14671                 dtrace_dof_destroy(dof);
14672                 kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14673         } else {
14674                 mutex_exit(&dtrace_lock);
14675         }
14676 }
14677 
14678 static int
14679 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14680 {
14681         uintptr_t daddr = (uintptr_t)dof;
14682         dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14683         dof_provider_t *provider;
14684         dof_probe_t *probe;
14685         uint8_t *arg;
14686         char *strtab, *typestr;
14687         dof_stridx_t typeidx;
14688         size_t typesz;
14689         uint_t nprobes, j, k;
14690 
14691         ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14692 
14693         if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14694                 dtrace_dof_error(dof, "misaligned section offset");
14695                 return (-1);
14696         }
14697 
14698         /*
14699          * The section needs to be large enough to contain the DOF provider
14700          * structure appropriate for the given version.
14701          */
14702         if (sec->dofs_size <
14703             ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14704             offsetof(dof_provider_t, dofpv_prenoffs) :
14705             sizeof (dof_provider_t))) {
14706                 dtrace_dof_error(dof, "provider section too small");
14707                 return (-1);
14708         }
14709 
14710         provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14711         str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14712         prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14713         arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14714         off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14715 
14716         if (str_sec == NULL || prb_sec == NULL ||
14717             arg_sec == NULL || off_sec == NULL)
14718                 return (-1);
14719 
14720         enoff_sec = NULL;
14721 
14722         if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14723             provider->dofpv_prenoffs != DOF_SECT_NONE &&
14724             (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14725             provider->dofpv_prenoffs)) == NULL)
14726                 return (-1);
14727 
14728         strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14729 
14730         if (provider->dofpv_name >= str_sec->dofs_size ||
14731             strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14732                 dtrace_dof_error(dof, "invalid provider name");
14733                 return (-1);
14734         }
14735 
14736         if (prb_sec->dofs_entsize == 0 ||
14737             prb_sec->dofs_entsize > prb_sec->dofs_size) {
14738                 dtrace_dof_error(dof, "invalid entry size");
14739                 return (-1);
14740         }
14741 
14742         if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14743                 dtrace_dof_error(dof, "misaligned entry size");
14744                 return (-1);
14745         }
14746 
14747         if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14748                 dtrace_dof_error(dof, "invalid entry size");
14749                 return (-1);
14750         }
14751 
14752         if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14753                 dtrace_dof_error(dof, "misaligned section offset");
14754                 return (-1);
14755         }
14756 
14757         if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14758                 dtrace_dof_error(dof, "invalid entry size");
14759                 return (-1);
14760         }
14761 
14762         arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14763 
14764         nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14765 
14766         /*
14767          * Take a pass through the probes to check for errors.
14768          */
14769         for (j = 0; j < nprobes; j++) {
14770                 probe = (dof_probe_t *)(uintptr_t)(daddr +
14771                     prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14772 
14773                 if (probe->dofpr_func >= str_sec->dofs_size) {
14774                         dtrace_dof_error(dof, "invalid function name");
14775                         return (-1);
14776                 }
14777 
14778                 if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14779                         dtrace_dof_error(dof, "function name too long");
14780                         return (-1);
14781                 }
14782 
14783                 if (probe->dofpr_name >= str_sec->dofs_size ||
14784                     strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14785                         dtrace_dof_error(dof, "invalid probe name");
14786                         return (-1);
14787                 }
14788 
14789                 /*
14790                  * The offset count must not wrap the index, and the offsets
14791                  * must also not overflow the section's data.
14792                  */
14793                 if (probe->dofpr_offidx + probe->dofpr_noffs <
14794                     probe->dofpr_offidx ||
14795                     (probe->dofpr_offidx + probe->dofpr_noffs) *
14796                     off_sec->dofs_entsize > off_sec->dofs_size) {
14797                         dtrace_dof_error(dof, "invalid probe offset");
14798                         return (-1);
14799                 }
14800 
14801                 if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14802                         /*
14803                          * If there's no is-enabled offset section, make sure
14804                          * there aren't any is-enabled offsets. Otherwise
14805                          * perform the same checks as for probe offsets
14806                          * (immediately above).
14807                          */
14808                         if (enoff_sec == NULL) {
14809                                 if (probe->dofpr_enoffidx != 0 ||
14810                                     probe->dofpr_nenoffs != 0) {
14811                                         dtrace_dof_error(dof, "is-enabled "
14812                                             "offsets with null section");
14813                                         return (-1);
14814                                 }
14815                         } else if (probe->dofpr_enoffidx +
14816                             probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14817                             (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14818                             enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14819                                 dtrace_dof_error(dof, "invalid is-enabled "
14820                                     "offset");
14821                                 return (-1);
14822                         }
14823 
14824                         if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14825                                 dtrace_dof_error(dof, "zero probe and "
14826                                     "is-enabled offsets");
14827                                 return (-1);
14828                         }
14829                 } else if (probe->dofpr_noffs == 0) {
14830                         dtrace_dof_error(dof, "zero probe offsets");
14831                         return (-1);
14832                 }
14833 
14834                 if (probe->dofpr_argidx + probe->dofpr_xargc <
14835                     probe->dofpr_argidx ||
14836                     (probe->dofpr_argidx + probe->dofpr_xargc) *
14837                     arg_sec->dofs_entsize > arg_sec->dofs_size) {
14838                         dtrace_dof_error(dof, "invalid args");
14839                         return (-1);
14840                 }
14841 
14842                 typeidx = probe->dofpr_nargv;
14843                 typestr = strtab + probe->dofpr_nargv;
14844                 for (k = 0; k < probe->dofpr_nargc; k++) {
14845                         if (typeidx >= str_sec->dofs_size) {
14846                                 dtrace_dof_error(dof, "bad "
14847                                     "native argument type");
14848                                 return (-1);
14849                         }
14850 
14851                         typesz = strlen(typestr) + 1;
14852                         if (typesz > DTRACE_ARGTYPELEN) {
14853                                 dtrace_dof_error(dof, "native "
14854                                     "argument type too long");
14855                                 return (-1);
14856                         }
14857                         typeidx += typesz;
14858                         typestr += typesz;
14859                 }
14860 
14861                 typeidx = probe->dofpr_xargv;
14862                 typestr = strtab + probe->dofpr_xargv;
14863                 for (k = 0; k < probe->dofpr_xargc; k++) {
14864                         if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14865                                 dtrace_dof_error(dof, "bad "
14866                                     "native argument index");
14867                                 return (-1);
14868                         }
14869 
14870                         if (typeidx >= str_sec->dofs_size) {
14871                                 dtrace_dof_error(dof, "bad "
14872                                     "translated argument type");
14873                                 return (-1);
14874                         }
14875 
14876                         typesz = strlen(typestr) + 1;
14877                         if (typesz > DTRACE_ARGTYPELEN) {
14878                                 dtrace_dof_error(dof, "translated argument "
14879                                     "type too long");
14880                                 return (-1);
14881                         }
14882 
14883                         typeidx += typesz;
14884                         typestr += typesz;
14885                 }
14886         }
14887 
14888         return (0);
14889 }
14890 
14891 static int
14892 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
14893 {
14894         dtrace_helpers_t *help;
14895         dtrace_vstate_t *vstate;
14896         dtrace_enabling_t *enab = NULL;
14897         int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14898         uintptr_t daddr = (uintptr_t)dof;
14899 
14900         ASSERT(MUTEX_HELD(&dtrace_lock));
14901 
14902         if ((help = curproc->p_dtrace_helpers) == NULL)
14903                 help = dtrace_helpers_create(curproc);
14904 
14905         vstate = &help->dthps_vstate;
14906 
14907         if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14908             dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14909                 dtrace_dof_destroy(dof);
14910                 return (rv);
14911         }
14912 
14913         /*
14914          * Look for helper providers and validate their descriptions.
14915          */
14916         if (dhp != NULL) {
14917                 for (i = 0; i < dof->dofh_secnum; i++) {
14918                         dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14919                             dof->dofh_secoff + i * dof->dofh_secsize);
14920 
14921                         if (sec->dofs_type != DOF_SECT_PROVIDER)
14922                                 continue;
14923 
14924                         if (dtrace_helper_provider_validate(dof, sec) != 0) {
14925                                 dtrace_enabling_destroy(enab);
14926                                 dtrace_dof_destroy(dof);
14927                                 return (-1);
14928                         }
14929 
14930                         nprovs++;
14931                 }
14932         }
14933 
14934         /*
14935          * Now we need to walk through the ECB descriptions in the enabling.
14936          */
14937         for (i = 0; i < enab->dten_ndesc; i++) {
14938                 dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14939                 dtrace_probedesc_t *desc = &ep->dted_probe;
14940 
14941                 if (strcmp(desc->dtpd_provider, "dtrace") != 0)
14942                         continue;
14943 
14944                 if (strcmp(desc->dtpd_mod, "helper") != 0)
14945                         continue;
14946 
14947                 if (strcmp(desc->dtpd_func, "ustack") != 0)
14948                         continue;
14949 
14950                 if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
14951                     ep)) != 0) {
14952                         /*
14953                          * Adding this helper action failed -- we are now going
14954                          * to rip out the entire generation and return failure.
14955                          */
14956                         (void) dtrace_helper_destroygen(help->dthps_generation);
14957                         dtrace_enabling_destroy(enab);
14958                         dtrace_dof_destroy(dof);
14959                         return (-1);
14960                 }
14961 
14962                 nhelpers++;
14963         }
14964 
14965         if (nhelpers < enab->dten_ndesc)
14966                 dtrace_dof_error(dof, "unmatched helpers");
14967 
14968         gen = help->dthps_generation++;
14969         dtrace_enabling_destroy(enab);
14970 
14971         if (dhp != NULL && nprovs > 0) {
14972                 dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14973                 if (dtrace_helper_provider_add(dhp, gen) == 0) {
14974                         mutex_exit(&dtrace_lock);
14975                         dtrace_helper_provider_register(curproc, help, dhp);
14976                         mutex_enter(&dtrace_lock);
14977 
14978                         destroy = 0;
14979                 }
14980         }
14981 
14982         if (destroy)
14983                 dtrace_dof_destroy(dof);
14984 
14985         return (gen);
14986 }
14987 
14988 static dtrace_helpers_t *
14989 dtrace_helpers_create(proc_t *p)
14990 {
14991         dtrace_helpers_t *help;
14992 
14993         ASSERT(MUTEX_HELD(&dtrace_lock));
14994         ASSERT(p->p_dtrace_helpers == NULL);
14995 
14996         help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
14997         help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
14998             DTRACE_NHELPER_ACTIONS, KM_SLEEP);
14999 
15000         p->p_dtrace_helpers = help;
15001         dtrace_helpers++;
15002 
15003         return (help);
15004 }
15005 
15006 static void
15007 dtrace_helpers_destroy(void)
15008 {
15009         dtrace_helpers_t *help;
15010         dtrace_vstate_t *vstate;
15011         proc_t *p = curproc;
15012         int i;
15013 
15014         mutex_enter(&dtrace_lock);
15015 
15016         ASSERT(p->p_dtrace_helpers != NULL);
15017         ASSERT(dtrace_helpers > 0);
15018 
15019         help = p->p_dtrace_helpers;
15020         vstate = &help->dthps_vstate;
15021 
15022         /*
15023          * We're now going to lose the help from this process.
15024          */
15025         p->p_dtrace_helpers = NULL;
15026         dtrace_sync();
15027 
15028         /*
15029          * Destory the helper actions.
15030          */
15031         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15032                 dtrace_helper_action_t *h, *next;
15033 
15034                 for (h = help->dthps_actions[i]; h != NULL; h = next) {
15035                         next = h->dtha_next;
15036                         dtrace_helper_action_destroy(h, vstate);
15037                         h = next;
15038                 }
15039         }
15040 
15041         mutex_exit(&dtrace_lock);
15042 
15043         /*
15044          * Destroy the helper providers.
15045          */
15046         if (help->dthps_maxprovs > 0) {
15047                 mutex_enter(&dtrace_meta_lock);
15048                 if (dtrace_meta_pid != NULL) {
15049                         ASSERT(dtrace_deferred_pid == NULL);
15050 
15051                         for (i = 0; i < help->dthps_nprovs; i++) {
15052                                 dtrace_helper_provider_remove(
15053                                     &help->dthps_provs[i]->dthp_prov, p->p_pid);
15054                         }
15055                 } else {
15056                         mutex_enter(&dtrace_lock);
15057                         ASSERT(help->dthps_deferred == 0 ||
15058                             help->dthps_next != NULL ||
15059                             help->dthps_prev != NULL ||
15060                             help == dtrace_deferred_pid);
15061 
15062                         /*
15063                          * Remove the helper from the deferred list.
15064                          */
15065                         if (help->dthps_next != NULL)
15066                                 help->dthps_next->dthps_prev = help->dthps_prev;
15067                         if (help->dthps_prev != NULL)
15068                                 help->dthps_prev->dthps_next = help->dthps_next;
15069                         if (dtrace_deferred_pid == help) {
15070                                 dtrace_deferred_pid = help->dthps_next;
15071                                 ASSERT(help->dthps_prev == NULL);
15072                         }
15073 
15074                         mutex_exit(&dtrace_lock);
15075                 }
15076 
15077                 mutex_exit(&dtrace_meta_lock);
15078 
15079                 for (i = 0; i < help->dthps_nprovs; i++) {
15080                         dtrace_helper_provider_destroy(help->dthps_provs[i]);
15081                 }
15082 
15083                 kmem_free(help->dthps_provs, help->dthps_maxprovs *
15084                     sizeof (dtrace_helper_provider_t *));
15085         }
15086 
15087         mutex_enter(&dtrace_lock);
15088 
15089         dtrace_vstate_fini(&help->dthps_vstate);
15090         kmem_free(help->dthps_actions,
15091             sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15092         kmem_free(help, sizeof (dtrace_helpers_t));
15093 
15094         --dtrace_helpers;
15095         mutex_exit(&dtrace_lock);
15096 }
15097 
15098 static void
15099 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15100 {
15101         dtrace_helpers_t *help, *newhelp;
15102         dtrace_helper_action_t *helper, *new, *last;
15103         dtrace_difo_t *dp;
15104         dtrace_vstate_t *vstate;
15105         int i, j, sz, hasprovs = 0;
15106 
15107         mutex_enter(&dtrace_lock);
15108         ASSERT(from->p_dtrace_helpers != NULL);
15109         ASSERT(dtrace_helpers > 0);
15110 
15111         help = from->p_dtrace_helpers;
15112         newhelp = dtrace_helpers_create(to);
15113         ASSERT(to->p_dtrace_helpers != NULL);
15114 
15115         newhelp->dthps_generation = help->dthps_generation;
15116         vstate = &newhelp->dthps_vstate;
15117 
15118         /*
15119          * Duplicate the helper actions.
15120          */
15121         for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15122                 if ((helper = help->dthps_actions[i]) == NULL)
15123                         continue;
15124 
15125                 for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15126                         new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15127                             KM_SLEEP);
15128                         new->dtha_generation = helper->dtha_generation;
15129 
15130                         if ((dp = helper->dtha_predicate) != NULL) {
15131                                 dp = dtrace_difo_duplicate(dp, vstate);
15132                                 new->dtha_predicate = dp;
15133                         }
15134 
15135                         new->dtha_nactions = helper->dtha_nactions;
15136                         sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15137                         new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15138 
15139                         for (j = 0; j < new->dtha_nactions; j++) {
15140                                 dtrace_difo_t *dp = helper->dtha_actions[j];
15141 
15142                                 ASSERT(dp != NULL);
15143                                 dp = dtrace_difo_duplicate(dp, vstate);
15144                                 new->dtha_actions[j] = dp;
15145                         }
15146 
15147                         if (last != NULL) {
15148                                 last->dtha_next = new;
15149                         } else {
15150                                 newhelp->dthps_actions[i] = new;
15151                         }
15152 
15153                         last = new;
15154                 }
15155         }
15156 
15157         /*
15158          * Duplicate the helper providers and register them with the
15159          * DTrace framework.
15160          */
15161         if (help->dthps_nprovs > 0) {
15162                 newhelp->dthps_nprovs = help->dthps_nprovs;
15163                 newhelp->dthps_maxprovs = help->dthps_nprovs;
15164                 newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15165                     sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15166                 for (i = 0; i < newhelp->dthps_nprovs; i++) {
15167                         newhelp->dthps_provs[i] = help->dthps_provs[i];
15168                         newhelp->dthps_provs[i]->dthp_ref++;
15169                 }
15170 
15171                 hasprovs = 1;
15172         }
15173 
15174         mutex_exit(&dtrace_lock);
15175 
15176         if (hasprovs)
15177                 dtrace_helper_provider_register(to, newhelp, NULL);
15178 }
15179 
15180 /*
15181  * DTrace Hook Functions
15182  */
15183 static void
15184 dtrace_module_loaded(struct modctl *ctl)
15185 {
15186         dtrace_provider_t *prv;
15187 
15188         mutex_enter(&dtrace_provider_lock);
15189         mutex_enter(&mod_lock);
15190 
15191         ASSERT(ctl->mod_busy);
15192 
15193         /*
15194          * We're going to call each providers per-module provide operation
15195          * specifying only this module.
15196          */
15197         for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15198                 prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15199 
15200         mutex_exit(&mod_lock);
15201         mutex_exit(&dtrace_provider_lock);
15202 
15203         /*
15204          * If we have any retained enablings, we need to match against them.
15205          * Enabling probes requires that cpu_lock be held, and we cannot hold
15206          * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15207          * module.  (In particular, this happens when loading scheduling
15208          * classes.)  So if we have any retained enablings, we need to dispatch
15209          * our task queue to do the match for us.
15210          */
15211         mutex_enter(&dtrace_lock);
15212 
15213         if (dtrace_retained == NULL) {
15214                 mutex_exit(&dtrace_lock);
15215                 return;
15216         }
15217 
15218         (void) taskq_dispatch(dtrace_taskq,
15219             (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15220 
15221         mutex_exit(&dtrace_lock);
15222 
15223         /*
15224          * And now, for a little heuristic sleaze:  in general, we want to
15225          * match modules as soon as they load.  However, we cannot guarantee
15226          * this, because it would lead us to the lock ordering violation
15227          * outlined above.  The common case, of course, is that cpu_lock is
15228          * _not_ held -- so we delay here for a clock tick, hoping that that's
15229          * long enough for the task queue to do its work.  If it's not, it's
15230          * not a serious problem -- it just means that the module that we
15231          * just loaded may not be immediately instrumentable.
15232          */
15233         delay(1);
15234 }
15235 
15236 static void
15237 dtrace_module_unloaded(struct modctl *ctl)
15238 {
15239         dtrace_probe_t template, *probe, *first, *next;
15240         dtrace_provider_t *prov;
15241 
15242         template.dtpr_mod = ctl->mod_modname;
15243 
15244         mutex_enter(&dtrace_provider_lock);
15245         mutex_enter(&mod_lock);
15246         mutex_enter(&dtrace_lock);
15247 
15248         if (dtrace_bymod == NULL) {
15249                 /*
15250                  * The DTrace module is loaded (obviously) but not attached;
15251                  * we don't have any work to do.
15252                  */
15253                 mutex_exit(&dtrace_provider_lock);
15254                 mutex_exit(&mod_lock);
15255                 mutex_exit(&dtrace_lock);
15256                 return;
15257         }
15258 
15259         for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15260             probe != NULL; probe = probe->dtpr_nextmod) {
15261                 if (probe->dtpr_ecb != NULL) {
15262                         mutex_exit(&dtrace_provider_lock);
15263                         mutex_exit(&mod_lock);
15264                         mutex_exit(&dtrace_lock);
15265 
15266                         /*
15267                          * This shouldn't _actually_ be possible -- we're
15268                          * unloading a module that has an enabled probe in it.
15269                          * (It's normally up to the provider to make sure that
15270                          * this can't happen.)  However, because dtps_enable()
15271                          * doesn't have a failure mode, there can be an
15272                          * enable/unload race.  Upshot:  we don't want to
15273                          * assert, but we're not going to disable the
15274                          * probe, either.
15275                          */
15276                         if (dtrace_err_verbose) {
15277                                 cmn_err(CE_WARN, "unloaded module '%s' had "
15278                                     "enabled probes", ctl->mod_modname);
15279                         }
15280 
15281                         return;
15282                 }
15283         }
15284 
15285         probe = first;
15286 
15287         for (first = NULL; probe != NULL; probe = next) {
15288                 ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15289 
15290                 dtrace_probes[probe->dtpr_id - 1] = NULL;
15291 
15292                 next = probe->dtpr_nextmod;
15293                 dtrace_hash_remove(dtrace_bymod, probe);
15294                 dtrace_hash_remove(dtrace_byfunc, probe);
15295                 dtrace_hash_remove(dtrace_byname, probe);
15296 
15297                 if (first == NULL) {
15298                         first = probe;
15299                         probe->dtpr_nextmod = NULL;
15300                 } else {
15301                         probe->dtpr_nextmod = first;
15302                         first = probe;
15303                 }
15304         }
15305 
15306         /*
15307          * We've removed all of the module's probes from the hash chains and
15308          * from the probe array.  Now issue a dtrace_sync() to be sure that
15309          * everyone has cleared out from any probe array processing.
15310          */
15311         dtrace_sync();
15312 
15313         for (probe = first; probe != NULL; probe = first) {
15314                 first = probe->dtpr_nextmod;
15315                 prov = probe->dtpr_provider;
15316                 prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15317                     probe->dtpr_arg);
15318                 kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15319                 kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15320                 kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15321                 vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15322                 kmem_free(probe, sizeof (dtrace_probe_t));
15323         }
15324 
15325         mutex_exit(&dtrace_lock);
15326         mutex_exit(&mod_lock);
15327         mutex_exit(&dtrace_provider_lock);
15328 }
15329 
15330 void
15331 dtrace_suspend(void)
15332 {
15333         dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15334 }
15335 
15336 void
15337 dtrace_resume(void)
15338 {
15339         dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15340 }
15341 
15342 static int
15343 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15344 {
15345         ASSERT(MUTEX_HELD(&cpu_lock));
15346         mutex_enter(&dtrace_lock);
15347 
15348         switch (what) {
15349         case CPU_CONFIG: {
15350                 dtrace_state_t *state;
15351                 dtrace_optval_t *opt, rs, c;
15352 
15353                 /*
15354                  * For now, we only allocate a new buffer for anonymous state.
15355                  */
15356                 if ((state = dtrace_anon.dta_state) == NULL)
15357                         break;
15358 
15359                 if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15360                         break;
15361 
15362                 opt = state->dts_options;
15363                 c = opt[DTRACEOPT_CPU];
15364 
15365                 if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15366                         break;
15367 
15368                 /*
15369                  * Regardless of what the actual policy is, we're going to
15370                  * temporarily set our resize policy to be manual.  We're
15371                  * also going to temporarily set our CPU option to denote
15372                  * the newly configured CPU.
15373                  */
15374                 rs = opt[DTRACEOPT_BUFRESIZE];
15375                 opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15376                 opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15377 
15378                 (void) dtrace_state_buffers(state);
15379 
15380                 opt[DTRACEOPT_BUFRESIZE] = rs;
15381                 opt[DTRACEOPT_CPU] = c;
15382 
15383                 break;
15384         }
15385 
15386         case CPU_UNCONFIG:
15387                 /*
15388                  * We don't free the buffer in the CPU_UNCONFIG case.  (The
15389                  * buffer will be freed when the consumer exits.)
15390                  */
15391                 break;
15392 
15393         default:
15394                 break;
15395         }
15396 
15397         mutex_exit(&dtrace_lock);
15398         return (0);
15399 }
15400 
15401 static void
15402 dtrace_cpu_setup_initial(processorid_t cpu)
15403 {
15404         (void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15405 }
15406 
15407 static void
15408 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15409 {
15410         if (dtrace_toxranges >= dtrace_toxranges_max) {
15411                 int osize, nsize;
15412                 dtrace_toxrange_t *range;
15413 
15414                 osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15415 
15416                 if (osize == 0) {
15417                         ASSERT(dtrace_toxrange == NULL);
15418                         ASSERT(dtrace_toxranges_max == 0);
15419                         dtrace_toxranges_max = 1;
15420                 } else {
15421                         dtrace_toxranges_max <<= 1;
15422                 }
15423 
15424                 nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15425                 range = kmem_zalloc(nsize, KM_SLEEP);
15426 
15427                 if (dtrace_toxrange != NULL) {
15428                         ASSERT(osize != 0);
15429                         bcopy(dtrace_toxrange, range, osize);
15430                         kmem_free(dtrace_toxrange, osize);
15431                 }
15432 
15433                 dtrace_toxrange = range;
15434         }
15435 
15436         ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
15437         ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
15438 
15439         dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15440         dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15441         dtrace_toxranges++;
15442 }
15443 
15444 static void
15445 dtrace_getf_barrier()
15446 {
15447         /*
15448          * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
15449          * that contain calls to getf(), this routine will be called on every
15450          * closef() before either the underlying vnode is released or the
15451          * file_t itself is freed.  By the time we are here, it is essential
15452          * that the file_t can no longer be accessed from a call to getf()
15453          * in probe context -- that assures that a dtrace_sync() can be used
15454          * to clear out any enablings referring to the old structures.
15455          */
15456         if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
15457             kcred->cr_zone->zone_dtrace_getf != 0)
15458                 dtrace_sync();
15459 }
15460 
15461 /*
15462  * DTrace Driver Cookbook Functions
15463  */
15464 /*ARGSUSED*/
15465 static int
15466 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15467 {
15468         dtrace_provider_id_t id;
15469         dtrace_state_t *state = NULL;
15470         dtrace_enabling_t *enab;
15471 
15472         mutex_enter(&cpu_lock);
15473         mutex_enter(&dtrace_provider_lock);
15474         mutex_enter(&dtrace_lock);
15475 
15476         if (ddi_soft_state_init(&dtrace_softstate,
15477             sizeof (dtrace_state_t), 0) != 0) {
15478                 cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15479                 mutex_exit(&cpu_lock);
15480                 mutex_exit(&dtrace_provider_lock);
15481                 mutex_exit(&dtrace_lock);
15482                 return (DDI_FAILURE);
15483         }
15484 
15485         if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
15486             DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
15487             ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
15488             DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
15489                 cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
15490                 ddi_remove_minor_node(devi, NULL);
15491                 ddi_soft_state_fini(&dtrace_softstate);
15492                 mutex_exit(&cpu_lock);
15493                 mutex_exit(&dtrace_provider_lock);
15494                 mutex_exit(&dtrace_lock);
15495                 return (DDI_FAILURE);
15496         }
15497 
15498         ddi_report_dev(devi);
15499         dtrace_devi = devi;
15500 
15501         dtrace_modload = dtrace_module_loaded;
15502         dtrace_modunload = dtrace_module_unloaded;
15503         dtrace_cpu_init = dtrace_cpu_setup_initial;
15504         dtrace_helpers_cleanup = dtrace_helpers_destroy;
15505         dtrace_helpers_fork = dtrace_helpers_duplicate;
15506         dtrace_cpustart_init = dtrace_suspend;
15507         dtrace_cpustart_fini = dtrace_resume;
15508         dtrace_debugger_init = dtrace_suspend;
15509         dtrace_debugger_fini = dtrace_resume;
15510 
15511         register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15512 
15513         ASSERT(MUTEX_HELD(&cpu_lock));
15514 
15515         dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15516             NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15517         dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15518             UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15519             VM_SLEEP | VMC_IDENTIFIER);
15520         dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15521             1, INT_MAX, 0);
15522 
15523         dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15524             sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
15525             NULL, NULL, NULL, NULL, NULL, 0);
15526 
15527         ASSERT(MUTEX_HELD(&cpu_lock));
15528         dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15529             offsetof(dtrace_probe_t, dtpr_nextmod),
15530             offsetof(dtrace_probe_t, dtpr_prevmod));
15531 
15532         dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15533             offsetof(dtrace_probe_t, dtpr_nextfunc),
15534             offsetof(dtrace_probe_t, dtpr_prevfunc));
15535 
15536         dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15537             offsetof(dtrace_probe_t, dtpr_nextname),
15538             offsetof(dtrace_probe_t, dtpr_prevname));
15539 
15540         if (dtrace_retain_max < 1) {
15541                 cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15542                     "setting to 1", dtrace_retain_max);
15543                 dtrace_retain_max = 1;
15544         }
15545 
15546         /*
15547          * Now discover our toxic ranges.
15548          */
15549         dtrace_toxic_ranges(dtrace_toxrange_add);
15550 
15551         /*
15552          * Before we register ourselves as a provider to our own framework,
15553          * we would like to assert that dtrace_provider is NULL -- but that's
15554          * not true if we were loaded as a dependency of a DTrace provider.
15555          * Once we've registered, we can assert that dtrace_provider is our
15556          * pseudo provider.
15557          */
15558         (void) dtrace_register("dtrace", &dtrace_provider_attr,
15559             DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15560 
15561         ASSERT(dtrace_provider != NULL);
15562         ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15563 
15564         dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15565             dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
15566         dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15567             dtrace_provider, NULL, NULL, "END", 0, NULL);
15568         dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15569             dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15570 
15571         dtrace_anon_property();
15572         mutex_exit(&cpu_lock);
15573 
15574         /*
15575          * If there are already providers, we must ask them to provide their
15576          * probes, and then match any anonymous enabling against them.  Note
15577          * that there should be no other retained enablings at this time:
15578          * the only retained enablings at this time should be the anonymous
15579          * enabling.
15580          */
15581         if (dtrace_anon.dta_enabling != NULL) {
15582                 ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15583 
15584                 dtrace_enabling_provide(NULL);
15585                 state = dtrace_anon.dta_state;
15586 
15587                 /*
15588                  * We couldn't hold cpu_lock across the above call to
15589                  * dtrace_enabling_provide(), but we must hold it to actually
15590                  * enable the probes.  We have to drop all of our locks, pick
15591                  * up cpu_lock, and regain our locks before matching the
15592                  * retained anonymous enabling.
15593                  */
15594                 mutex_exit(&dtrace_lock);
15595                 mutex_exit(&dtrace_provider_lock);
15596 
15597                 mutex_enter(&cpu_lock);
15598                 mutex_enter(&dtrace_provider_lock);
15599                 mutex_enter(&dtrace_lock);
15600 
15601                 if ((enab = dtrace_anon.dta_enabling) != NULL)
15602                         (void) dtrace_enabling_match(enab, NULL);
15603 
15604                 mutex_exit(&cpu_lock);
15605         }
15606 
15607         mutex_exit(&dtrace_lock);
15608         mutex_exit(&dtrace_provider_lock);
15609 
15610         if (state != NULL) {
15611                 /*
15612                  * If we created any anonymous state, set it going now.
15613                  */
15614                 (void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15615         }
15616 
15617         return (DDI_SUCCESS);
15618 }
15619 
15620 /*ARGSUSED*/
15621 static int
15622 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15623 {
15624         dtrace_state_t *state;
15625         uint32_t priv;
15626         uid_t uid;
15627         zoneid_t zoneid;
15628 
15629         if (getminor(*devp) == DTRACEMNRN_HELPER)
15630                 return (0);
15631 
15632         /*
15633          * If this wasn't an open with the "helper" minor, then it must be
15634          * the "dtrace" minor.
15635          */
15636         if (getminor(*devp) != DTRACEMNRN_DTRACE)
15637                 return (ENXIO);
15638 
15639         /*
15640          * If no DTRACE_PRIV_* bits are set in the credential, then the
15641          * caller lacks sufficient permission to do anything with DTrace.
15642          */
15643         dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15644         if (priv == DTRACE_PRIV_NONE)
15645                 return (EACCES);
15646 
15647         /*
15648          * Ask all providers to provide all their probes.
15649          */
15650         mutex_enter(&dtrace_provider_lock);
15651         dtrace_probe_provide(NULL, NULL);
15652         mutex_exit(&dtrace_provider_lock);
15653 
15654         mutex_enter(&cpu_lock);
15655         mutex_enter(&dtrace_lock);
15656         dtrace_opens++;
15657         dtrace_membar_producer();
15658 
15659         /*
15660          * If the kernel debugger is active (that is, if the kernel debugger
15661          * modified text in some way), we won't allow the open.
15662          */
15663         if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15664                 dtrace_opens--;
15665                 mutex_exit(&cpu_lock);
15666                 mutex_exit(&dtrace_lock);
15667                 return (EBUSY);
15668         }
15669 
15670         if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
15671                 /*
15672                  * If DTrace helper tracing is enabled, we need to allocate the
15673                  * trace buffer and initialize the values.
15674                  */
15675                 dtrace_helptrace_buffer =
15676                     kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15677                 dtrace_helptrace_next = 0;
15678                 dtrace_helptrace_wrapped = 0;
15679                 dtrace_helptrace_enable = 0;
15680         }
15681 
15682         state = dtrace_state_create(devp, cred_p);
15683         mutex_exit(&cpu_lock);
15684 
15685         if (state == NULL) {
15686                 if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15687                         (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15688                 mutex_exit(&dtrace_lock);
15689                 return (EAGAIN);
15690         }
15691 
15692         mutex_exit(&dtrace_lock);
15693 
15694         return (0);
15695 }
15696 
15697 /*ARGSUSED*/
15698 static int
15699 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15700 {
15701         minor_t minor = getminor(dev);
15702         dtrace_state_t *state;
15703         dtrace_helptrace_t *buf = NULL;
15704 
15705         if (minor == DTRACEMNRN_HELPER)
15706                 return (0);
15707 
15708         state = ddi_get_soft_state(dtrace_softstate, minor);
15709 
15710         mutex_enter(&cpu_lock);
15711         mutex_enter(&dtrace_lock);
15712 
15713         if (state->dts_anon) {
15714                 /*
15715                  * There is anonymous state. Destroy that first.
15716                  */
15717                 ASSERT(dtrace_anon.dta_state == NULL);
15718                 dtrace_state_destroy(state->dts_anon);
15719         }
15720 
15721         if (dtrace_helptrace_disable) {
15722                 /*
15723                  * If we have been told to disable helper tracing, set the
15724                  * buffer to NULL before calling into dtrace_state_destroy();
15725                  * we take advantage of its dtrace_sync() to know that no
15726                  * CPU is in probe context with enabled helper tracing
15727                  * after it returns.
15728                  */
15729                 buf = dtrace_helptrace_buffer;
15730                 dtrace_helptrace_buffer = NULL;
15731         }
15732 
15733         dtrace_state_destroy(state);
15734         ASSERT(dtrace_opens > 0);
15735 
15736         /*
15737          * Only relinquish control of the kernel debugger interface when there
15738          * are no consumers and no anonymous enablings.
15739          */
15740         if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15741                 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15742 
15743         if (buf != NULL) {
15744                 kmem_free(buf, dtrace_helptrace_bufsize);
15745                 dtrace_helptrace_disable = 0;
15746         }
15747 
15748         mutex_exit(&dtrace_lock);
15749         mutex_exit(&cpu_lock);
15750 
15751         return (0);
15752 }
15753 
15754 /*ARGSUSED*/
15755 static int
15756 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
15757 {
15758         int rval;
15759         dof_helper_t help, *dhp = NULL;
15760 
15761         switch (cmd) {
15762         case DTRACEHIOC_ADDDOF:
15763                 if (copyin((void *)arg, &help, sizeof (help)) != 0) {
15764                         dtrace_dof_error(NULL, "failed to copyin DOF helper");
15765                         return (EFAULT);
15766                 }
15767 
15768                 dhp = &help;
15769                 arg = (intptr_t)help.dofhp_dof;
15770                 /*FALLTHROUGH*/
15771 
15772         case DTRACEHIOC_ADD: {
15773                 dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
15774 
15775                 if (dof == NULL)
15776                         return (rval);
15777 
15778                 mutex_enter(&dtrace_lock);
15779 
15780                 /*
15781                  * dtrace_helper_slurp() takes responsibility for the dof --
15782                  * it may free it now or it may save it and free it later.
15783                  */
15784                 if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
15785                         *rv = rval;
15786                         rval = 0;
15787                 } else {
15788                         rval = EINVAL;
15789                 }
15790 
15791                 mutex_exit(&dtrace_lock);
15792                 return (rval);
15793         }
15794 
15795         case DTRACEHIOC_REMOVE: {
15796                 mutex_enter(&dtrace_lock);
15797                 rval = dtrace_helper_destroygen(arg);
15798                 mutex_exit(&dtrace_lock);
15799 
15800                 return (rval);
15801         }
15802 
15803         default:
15804                 break;
15805         }
15806 
15807         return (ENOTTY);
15808 }
15809 
15810 /*ARGSUSED*/
15811 static int
15812 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
15813 {
15814         minor_t minor = getminor(dev);
15815         dtrace_state_t *state;
15816         int rval;
15817 
15818         if (minor == DTRACEMNRN_HELPER)
15819                 return (dtrace_ioctl_helper(cmd, arg, rv));
15820 
15821         state = ddi_get_soft_state(dtrace_softstate, minor);
15822 
15823         if (state->dts_anon) {
15824                 ASSERT(dtrace_anon.dta_state == NULL);
15825                 state = state->dts_anon;
15826         }
15827 
15828         switch (cmd) {
15829         case DTRACEIOC_PROVIDER: {
15830                 dtrace_providerdesc_t pvd;
15831                 dtrace_provider_t *pvp;
15832 
15833                 if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
15834                         return (EFAULT);
15835 
15836                 pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
15837                 mutex_enter(&dtrace_provider_lock);
15838 
15839                 for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
15840                         if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
15841                                 break;
15842                 }
15843 
15844                 mutex_exit(&dtrace_provider_lock);
15845 
15846                 if (pvp == NULL)
15847                         return (ESRCH);
15848 
15849                 bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
15850                 bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
15851                 if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
15852                         return (EFAULT);
15853 
15854                 return (0);
15855         }
15856 
15857         case DTRACEIOC_EPROBE: {
15858                 dtrace_eprobedesc_t epdesc;
15859                 dtrace_ecb_t *ecb;
15860                 dtrace_action_t *act;
15861                 void *buf;
15862                 size_t size;
15863                 uintptr_t dest;
15864                 int nrecs;
15865 
15866                 if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
15867                         return (EFAULT);
15868 
15869                 mutex_enter(&dtrace_lock);
15870 
15871                 if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
15872                         mutex_exit(&dtrace_lock);
15873                         return (EINVAL);
15874                 }
15875 
15876                 if (ecb->dte_probe == NULL) {
15877                         mutex_exit(&dtrace_lock);
15878                         return (EINVAL);
15879                 }
15880 
15881                 epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
15882                 epdesc.dtepd_uarg = ecb->dte_uarg;
15883                 epdesc.dtepd_size = ecb->dte_size;
15884 
15885                 nrecs = epdesc.dtepd_nrecs;
15886                 epdesc.dtepd_nrecs = 0;
15887                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15888                         if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15889                                 continue;
15890 
15891                         epdesc.dtepd_nrecs++;
15892                 }
15893 
15894                 /*
15895                  * Now that we have the size, we need to allocate a temporary
15896                  * buffer in which to store the complete description.  We need
15897                  * the temporary buffer to be able to drop dtrace_lock()
15898                  * across the copyout(), below.
15899                  */
15900                 size = sizeof (dtrace_eprobedesc_t) +
15901                     (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
15902 
15903                 buf = kmem_alloc(size, KM_SLEEP);
15904                 dest = (uintptr_t)buf;
15905 
15906                 bcopy(&epdesc, (void *)dest, sizeof (epdesc));
15907                 dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
15908 
15909                 for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15910                         if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15911                                 continue;
15912 
15913                         if (nrecs-- == 0)
15914                                 break;
15915 
15916                         bcopy(&act->dta_rec, (void *)dest,
15917                             sizeof (dtrace_recdesc_t));
15918                         dest += sizeof (dtrace_recdesc_t);
15919                 }
15920 
15921                 mutex_exit(&dtrace_lock);
15922 
15923                 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
15924                         kmem_free(buf, size);
15925                         return (EFAULT);
15926                 }
15927 
15928                 kmem_free(buf, size);
15929                 return (0);
15930         }
15931 
15932         case DTRACEIOC_AGGDESC: {
15933                 dtrace_aggdesc_t aggdesc;
15934                 dtrace_action_t *act;
15935                 dtrace_aggregation_t *agg;
15936                 int nrecs;
15937                 uint32_t offs;
15938                 dtrace_recdesc_t *lrec;
15939                 void *buf;
15940                 size_t size;
15941                 uintptr_t dest;
15942 
15943                 if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
15944                         return (EFAULT);
15945 
15946                 mutex_enter(&dtrace_lock);
15947 
15948                 if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
15949                         mutex_exit(&dtrace_lock);
15950                         return (EINVAL);
15951                 }
15952 
15953                 aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
15954 
15955                 nrecs = aggdesc.dtagd_nrecs;
15956                 aggdesc.dtagd_nrecs = 0;
15957 
15958                 offs = agg->dtag_base;
15959                 lrec = &agg->dtag_action.dta_rec;
15960                 aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
15961 
15962                 for (act = agg->dtag_first; ; act = act->dta_next) {
15963                         ASSERT(act->dta_intuple ||
15964                             DTRACEACT_ISAGG(act->dta_kind));
15965 
15966                         /*
15967                          * If this action has a record size of zero, it
15968                          * denotes an argument to the aggregating action.
15969                          * Because the presence of this record doesn't (or
15970                          * shouldn't) affect the way the data is interpreted,
15971                          * we don't copy it out to save user-level the
15972                          * confusion of dealing with a zero-length record.
15973                          */
15974                         if (act->dta_rec.dtrd_size == 0) {
15975                                 ASSERT(agg->dtag_hasarg);
15976                                 continue;
15977                         }
15978 
15979                         aggdesc.dtagd_nrecs++;
15980 
15981                         if (act == &agg->dtag_action)
15982                                 break;
15983                 }
15984 
15985                 /*
15986                  * Now that we have the size, we need to allocate a temporary
15987                  * buffer in which to store the complete description.  We need
15988                  * the temporary buffer to be able to drop dtrace_lock()
15989                  * across the copyout(), below.
15990                  */
15991                 size = sizeof (dtrace_aggdesc_t) +
15992                     (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
15993 
15994                 buf = kmem_alloc(size, KM_SLEEP);
15995                 dest = (uintptr_t)buf;
15996 
15997                 bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
15998                 dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
15999 
16000                 for (act = agg->dtag_first; ; act = act->dta_next) {
16001                         dtrace_recdesc_t rec = act->dta_rec;
16002 
16003                         /*
16004                          * See the comment in the above loop for why we pass
16005                          * over zero-length records.
16006                          */
16007                         if (rec.dtrd_size == 0) {
16008                                 ASSERT(agg->dtag_hasarg);
16009                                 continue;
16010                         }
16011 
16012                         if (nrecs-- == 0)
16013                                 break;
16014 
16015                         rec.dtrd_offset -= offs;
16016                         bcopy(&rec, (void *)dest, sizeof (rec));
16017                         dest += sizeof (dtrace_recdesc_t);
16018 
16019                         if (act == &agg->dtag_action)
16020                                 break;
16021                 }
16022 
16023                 mutex_exit(&dtrace_lock);
16024 
16025                 if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16026                         kmem_free(buf, size);
16027                         return (EFAULT);
16028                 }
16029 
16030                 kmem_free(buf, size);
16031                 return (0);
16032         }
16033 
16034         case DTRACEIOC_ENABLE: {
16035                 dof_hdr_t *dof;
16036                 dtrace_enabling_t *enab = NULL;
16037                 dtrace_vstate_t *vstate;
16038                 int err = 0;
16039 
16040                 *rv = 0;
16041 
16042                 /*
16043                  * If a NULL argument has been passed, we take this as our
16044                  * cue to reevaluate our enablings.
16045                  */
16046                 if (arg == NULL) {
16047                         dtrace_enabling_matchall();
16048 
16049                         return (0);
16050                 }
16051 
16052                 if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16053                         return (rval);
16054 
16055                 mutex_enter(&cpu_lock);
16056                 mutex_enter(&dtrace_lock);
16057                 vstate = &state->dts_vstate;
16058 
16059                 if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16060                         mutex_exit(&dtrace_lock);
16061                         mutex_exit(&cpu_lock);
16062                         dtrace_dof_destroy(dof);
16063                         return (EBUSY);
16064                 }
16065 
16066                 if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16067                         mutex_exit(&dtrace_lock);
16068                         mutex_exit(&cpu_lock);
16069                         dtrace_dof_destroy(dof);
16070                         return (EINVAL);
16071                 }
16072 
16073                 if ((rval = dtrace_dof_options(dof, state)) != 0) {
16074                         dtrace_enabling_destroy(enab);
16075                         mutex_exit(&dtrace_lock);
16076                         mutex_exit(&cpu_lock);
16077                         dtrace_dof_destroy(dof);
16078                         return (rval);
16079                 }
16080 
16081                 if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16082                         err = dtrace_enabling_retain(enab);
16083                 } else {
16084                         dtrace_enabling_destroy(enab);
16085                 }
16086 
16087                 mutex_exit(&cpu_lock);
16088                 mutex_exit(&dtrace_lock);
16089                 dtrace_dof_destroy(dof);
16090 
16091                 return (err);
16092         }
16093 
16094         case DTRACEIOC_REPLICATE: {
16095                 dtrace_repldesc_t desc;
16096                 dtrace_probedesc_t *match = &desc.dtrpd_match;
16097                 dtrace_probedesc_t *create = &desc.dtrpd_create;
16098                 int err;
16099 
16100                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16101                         return (EFAULT);
16102 
16103                 match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16104                 match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16105                 match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16106                 match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16107 
16108                 create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16109                 create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16110                 create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16111                 create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16112 
16113                 mutex_enter(&dtrace_lock);
16114                 err = dtrace_enabling_replicate(state, match, create);
16115                 mutex_exit(&dtrace_lock);
16116 
16117                 return (err);
16118         }
16119 
16120         case DTRACEIOC_PROBEMATCH:
16121         case DTRACEIOC_PROBES: {
16122                 dtrace_probe_t *probe = NULL;
16123                 dtrace_probedesc_t desc;
16124                 dtrace_probekey_t pkey;
16125                 dtrace_id_t i;
16126                 int m = 0;
16127                 uint32_t priv;
16128                 uid_t uid;
16129                 zoneid_t zoneid;
16130 
16131                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16132                         return (EFAULT);
16133 
16134                 desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16135                 desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16136                 desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16137                 desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16138 
16139                 /*
16140                  * Before we attempt to match this probe, we want to give
16141                  * all providers the opportunity to provide it.
16142                  */
16143                 if (desc.dtpd_id == DTRACE_IDNONE) {
16144                         mutex_enter(&dtrace_provider_lock);
16145                         dtrace_probe_provide(&desc, NULL);
16146                         mutex_exit(&dtrace_provider_lock);
16147                         desc.dtpd_id++;
16148                 }
16149 
16150                 if (cmd == DTRACEIOC_PROBEMATCH)  {
16151                         dtrace_probekey(&desc, &pkey);
16152                         pkey.dtpk_id = DTRACE_IDNONE;
16153                 }
16154 
16155                 dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16156 
16157                 mutex_enter(&dtrace_lock);
16158 
16159                 if (cmd == DTRACEIOC_PROBEMATCH) {
16160                         for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16161                                 if ((probe = dtrace_probes[i - 1]) != NULL &&
16162                                     (m = dtrace_match_probe(probe, &pkey,
16163                                     priv, uid, zoneid)) != 0)
16164                                         break;
16165                         }
16166 
16167                         if (m < 0) {
16168                                 mutex_exit(&dtrace_lock);
16169                                 return (EINVAL);
16170                         }
16171 
16172                 } else {
16173                         for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16174                                 if ((probe = dtrace_probes[i - 1]) != NULL &&
16175                                     dtrace_match_priv(probe, priv, uid, zoneid))
16176                                         break;
16177                         }
16178                 }
16179 
16180                 if (probe == NULL) {
16181                         mutex_exit(&dtrace_lock);
16182                         return (ESRCH);
16183                 }
16184 
16185                 dtrace_probe_description(probe, &desc);
16186                 mutex_exit(&dtrace_lock);
16187 
16188                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16189                         return (EFAULT);
16190 
16191                 return (0);
16192         }
16193 
16194         case DTRACEIOC_PROBEARG: {
16195                 dtrace_argdesc_t desc;
16196                 dtrace_probe_t *probe;
16197                 dtrace_provider_t *prov;
16198 
16199                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16200                         return (EFAULT);
16201 
16202                 if (desc.dtargd_id == DTRACE_IDNONE)
16203                         return (EINVAL);
16204 
16205                 if (desc.dtargd_ndx == DTRACE_ARGNONE)
16206                         return (EINVAL);
16207 
16208                 mutex_enter(&dtrace_provider_lock);
16209                 mutex_enter(&mod_lock);
16210                 mutex_enter(&dtrace_lock);
16211 
16212                 if (desc.dtargd_id > dtrace_nprobes) {
16213                         mutex_exit(&dtrace_lock);
16214                         mutex_exit(&mod_lock);
16215                         mutex_exit(&dtrace_provider_lock);
16216                         return (EINVAL);
16217                 }
16218 
16219                 if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16220                         mutex_exit(&dtrace_lock);
16221                         mutex_exit(&mod_lock);
16222                         mutex_exit(&dtrace_provider_lock);
16223                         return (EINVAL);
16224                 }
16225 
16226                 mutex_exit(&dtrace_lock);
16227 
16228                 prov = probe->dtpr_provider;
16229 
16230                 if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16231                         /*
16232                          * There isn't any typed information for this probe.
16233                          * Set the argument number to DTRACE_ARGNONE.
16234                          */
16235                         desc.dtargd_ndx = DTRACE_ARGNONE;
16236                 } else {
16237                         desc.dtargd_native[0] = '\0';
16238                         desc.dtargd_xlate[0] = '\0';
16239                         desc.dtargd_mapping = desc.dtargd_ndx;
16240 
16241                         prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16242                             probe->dtpr_id, probe->dtpr_arg, &desc);
16243                 }
16244 
16245                 mutex_exit(&mod_lock);
16246                 mutex_exit(&dtrace_provider_lock);
16247 
16248                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16249                         return (EFAULT);
16250 
16251                 return (0);
16252         }
16253 
16254         case DTRACEIOC_GO: {
16255                 processorid_t cpuid;
16256                 rval = dtrace_state_go(state, &cpuid);
16257 
16258                 if (rval != 0)
16259                         return (rval);
16260 
16261                 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16262                         return (EFAULT);
16263 
16264                 return (0);
16265         }
16266 
16267         case DTRACEIOC_STOP: {
16268                 processorid_t cpuid;
16269 
16270                 mutex_enter(&dtrace_lock);
16271                 rval = dtrace_state_stop(state, &cpuid);
16272                 mutex_exit(&dtrace_lock);
16273 
16274                 if (rval != 0)
16275                         return (rval);
16276 
16277                 if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16278                         return (EFAULT);
16279 
16280                 return (0);
16281         }
16282 
16283         case DTRACEIOC_DOFGET: {
16284                 dof_hdr_t hdr, *dof;
16285                 uint64_t len;
16286 
16287                 if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16288                         return (EFAULT);
16289 
16290                 mutex_enter(&dtrace_lock);
16291                 dof = dtrace_dof_create(state);
16292                 mutex_exit(&dtrace_lock);
16293 
16294                 len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16295                 rval = copyout(dof, (void *)arg, len);
16296                 dtrace_dof_destroy(dof);
16297 
16298                 return (rval == 0 ? 0 : EFAULT);
16299         }
16300 
16301         case DTRACEIOC_AGGSNAP:
16302         case DTRACEIOC_BUFSNAP: {
16303                 dtrace_bufdesc_t desc;
16304                 caddr_t cached;
16305                 dtrace_buffer_t *buf;
16306 
16307                 if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16308                         return (EFAULT);
16309 
16310                 if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16311                         return (EINVAL);
16312 
16313                 mutex_enter(&dtrace_lock);
16314 
16315                 if (cmd == DTRACEIOC_BUFSNAP) {
16316                         buf = &state->dts_buffer[desc.dtbd_cpu];
16317                 } else {
16318                         buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16319                 }
16320 
16321                 if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16322                         size_t sz = buf->dtb_offset;
16323 
16324                         if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16325                                 mutex_exit(&dtrace_lock);
16326                                 return (EBUSY);
16327                         }
16328 
16329                         /*
16330                          * If this buffer has already been consumed, we're
16331                          * going to indicate that there's nothing left here
16332                          * to consume.
16333                          */
16334                         if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16335                                 mutex_exit(&dtrace_lock);
16336 
16337                                 desc.dtbd_size = 0;
16338                                 desc.dtbd_drops = 0;
16339                                 desc.dtbd_errors = 0;
16340                                 desc.dtbd_oldest = 0;
16341                                 sz = sizeof (desc);
16342 
16343                                 if (copyout(&desc, (void *)arg, sz) != 0)
16344                                         return (EFAULT);
16345 
16346                                 return (0);
16347                         }
16348 
16349                         /*
16350                          * If this is a ring buffer that has wrapped, we want
16351                          * to copy the whole thing out.
16352                          */
16353                         if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16354                                 dtrace_buffer_polish(buf);
16355                                 sz = buf->dtb_size;
16356                         }
16357 
16358                         if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
16359                                 mutex_exit(&dtrace_lock);
16360                                 return (EFAULT);
16361                         }
16362 
16363                         desc.dtbd_size = sz;
16364                         desc.dtbd_drops = buf->dtb_drops;
16365                         desc.dtbd_errors = buf->dtb_errors;
16366                         desc.dtbd_oldest = buf->dtb_xamot_offset;
16367                         desc.dtbd_timestamp = dtrace_gethrtime();
16368 
16369                         mutex_exit(&dtrace_lock);
16370 
16371                         if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16372                                 return (EFAULT);
16373 
16374                         buf->dtb_flags |= DTRACEBUF_CONSUMED;
16375 
16376                         return (0);
16377                 }
16378 
16379                 if (buf->dtb_tomax == NULL) {
16380                         ASSERT(buf->dtb_xamot == NULL);
16381                         mutex_exit(&dtrace_lock);
16382                         return (ENOENT);
16383                 }
16384 
16385                 cached = buf->dtb_tomax;
16386                 ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16387 
16388                 dtrace_xcall(desc.dtbd_cpu,
16389                     (dtrace_xcall_t)dtrace_buffer_switch, buf);
16390 
16391                 state->dts_errors += buf->dtb_xamot_errors;
16392 
16393                 /*
16394                  * If the buffers did not actually switch, then the cross call
16395                  * did not take place -- presumably because the given CPU is
16396                  * not in the ready set.  If this is the case, we'll return
16397                  * ENOENT.
16398                  */
16399                 if (buf->dtb_tomax == cached) {
16400                         ASSERT(buf->dtb_xamot != cached);
16401                         mutex_exit(&dtrace_lock);
16402                         return (ENOENT);
16403                 }
16404 
16405                 ASSERT(cached == buf->dtb_xamot);
16406 
16407                 /*
16408                  * We have our snapshot; now copy it out.
16409                  */
16410                 if (copyout(buf->dtb_xamot, desc.dtbd_data,
16411                     buf->dtb_xamot_offset) != 0) {
16412                         mutex_exit(&dtrace_lock);
16413                         return (EFAULT);
16414                 }
16415 
16416                 desc.dtbd_size = buf->dtb_xamot_offset;
16417                 desc.dtbd_drops = buf->dtb_xamot_drops;
16418                 desc.dtbd_errors = buf->dtb_xamot_errors;
16419                 desc.dtbd_oldest = 0;
16420                 desc.dtbd_timestamp = buf->dtb_switched;
16421 
16422                 mutex_exit(&dtrace_lock);
16423 
16424                 /*
16425                  * Finally, copy out the buffer description.
16426                  */
16427                 if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16428                         return (EFAULT);
16429 
16430                 return (0);
16431         }
16432 
16433         case DTRACEIOC_CONF: {
16434                 dtrace_conf_t conf;
16435 
16436                 bzero(&conf, sizeof (conf));
16437                 conf.dtc_difversion = DIF_VERSION;
16438                 conf.dtc_difintregs = DIF_DIR_NREGS;
16439                 conf.dtc_diftupregs = DIF_DTR_NREGS;
16440                 conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16441 
16442                 if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
16443                         return (EFAULT);
16444 
16445                 return (0);
16446         }
16447 
16448         case DTRACEIOC_STATUS: {
16449                 dtrace_status_t stat;
16450                 dtrace_dstate_t *dstate;
16451                 int i, j;
16452                 uint64_t nerrs;
16453 
16454                 /*
16455                  * See the comment in dtrace_state_deadman() for the reason
16456                  * for setting dts_laststatus to INT64_MAX before setting
16457                  * it to the correct value.
16458                  */
16459                 state->dts_laststatus = INT64_MAX;
16460                 dtrace_membar_producer();
16461                 state->dts_laststatus = dtrace_gethrtime();
16462 
16463                 bzero(&stat, sizeof (stat));
16464 
16465                 mutex_enter(&dtrace_lock);
16466 
16467                 if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16468                         mutex_exit(&dtrace_lock);
16469                         return (ENOENT);
16470                 }
16471 
16472                 if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16473                         stat.dtst_exiting = 1;
16474 
16475                 nerrs = state->dts_errors;
16476                 dstate = &state->dts_vstate.dtvs_dynvars;
16477 
16478                 for (i = 0; i < NCPU; i++) {
16479                         dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16480 
16481                         stat.dtst_dyndrops += dcpu->dtdsc_drops;
16482                         stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16483                         stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16484 
16485                         if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16486                                 stat.dtst_filled++;
16487 
16488                         nerrs += state->dts_buffer[i].dtb_errors;
16489 
16490                         for (j = 0; j < state->dts_nspeculations; j++) {
16491                                 dtrace_speculation_t *spec;
16492                                 dtrace_buffer_t *buf;
16493 
16494                                 spec = &state->dts_speculations[j];
16495                                 buf = &spec->dtsp_buffer[i];
16496                                 stat.dtst_specdrops += buf->dtb_xamot_drops;
16497                         }
16498                 }
16499 
16500                 stat.dtst_specdrops_busy = state->dts_speculations_busy;
16501                 stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16502                 stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16503                 stat.dtst_dblerrors = state->dts_dblerrors;
16504                 stat.dtst_killed =
16505                     (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16506                 stat.dtst_errors = nerrs;
16507 
16508                 mutex_exit(&dtrace_lock);
16509 
16510                 if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
16511                         return (EFAULT);
16512 
16513                 return (0);
16514         }
16515 
16516         case DTRACEIOC_FORMAT: {
16517                 dtrace_fmtdesc_t fmt;
16518                 char *str;
16519                 int len;
16520 
16521                 if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
16522                         return (EFAULT);
16523 
16524                 mutex_enter(&dtrace_lock);
16525 
16526                 if (fmt.dtfd_format == 0 ||
16527                     fmt.dtfd_format > state->dts_nformats) {
16528                         mutex_exit(&dtrace_lock);
16529                         return (EINVAL);
16530                 }
16531 
16532                 /*
16533                  * Format strings are allocated contiguously and they are
16534                  * never freed; if a format index is less than the number
16535                  * of formats, we can assert that the format map is non-NULL
16536                  * and that the format for the specified index is non-NULL.
16537                  */
16538                 ASSERT(state->dts_formats != NULL);
16539                 str = state->dts_formats[fmt.dtfd_format - 1];
16540                 ASSERT(str != NULL);
16541 
16542                 len = strlen(str) + 1;
16543 
16544                 if (len > fmt.dtfd_length) {
16545                         fmt.dtfd_length = len;
16546 
16547                         if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16548                                 mutex_exit(&dtrace_lock);
16549                                 return (EINVAL);
16550                         }
16551                 } else {
16552                         if (copyout(str, fmt.dtfd_string, len) != 0) {
16553                                 mutex_exit(&dtrace_lock);
16554                                 return (EINVAL);
16555                         }
16556                 }
16557 
16558                 mutex_exit(&dtrace_lock);
16559                 return (0);
16560         }
16561 
16562         default:
16563                 break;
16564         }
16565 
16566         return (ENOTTY);
16567 }
16568 
16569 /*ARGSUSED*/
16570 static int
16571 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16572 {
16573         dtrace_state_t *state;
16574 
16575         switch (cmd) {
16576         case DDI_DETACH:
16577                 break;
16578 
16579         case DDI_SUSPEND:
16580                 return (DDI_SUCCESS);
16581 
16582         default:
16583                 return (DDI_FAILURE);
16584         }
16585 
16586         mutex_enter(&cpu_lock);
16587         mutex_enter(&dtrace_provider_lock);
16588         mutex_enter(&dtrace_lock);
16589 
16590         ASSERT(dtrace_opens == 0);
16591 
16592         if (dtrace_helpers > 0) {
16593                 mutex_exit(&dtrace_provider_lock);
16594                 mutex_exit(&dtrace_lock);
16595                 mutex_exit(&cpu_lock);
16596                 return (DDI_FAILURE);
16597         }
16598 
16599         if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
16600                 mutex_exit(&dtrace_provider_lock);
16601                 mutex_exit(&dtrace_lock);
16602                 mutex_exit(&cpu_lock);
16603                 return (DDI_FAILURE);
16604         }
16605 
16606         dtrace_provider = NULL;
16607 
16608         if ((state = dtrace_anon_grab()) != NULL) {
16609                 /*
16610                  * If there were ECBs on this state, the provider should
16611                  * have not been allowed to detach; assert that there is
16612                  * none.
16613                  */
16614                 ASSERT(state->dts_necbs == 0);
16615                 dtrace_state_destroy(state);
16616 
16617                 /*
16618                  * If we're being detached with anonymous state, we need to
16619                  * indicate to the kernel debugger that DTrace is now inactive.
16620                  */
16621                 (void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16622         }
16623 
16624         bzero(&dtrace_anon, sizeof (dtrace_anon_t));
16625         unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16626         dtrace_cpu_init = NULL;
16627         dtrace_helpers_cleanup = NULL;
16628         dtrace_helpers_fork = NULL;
16629         dtrace_cpustart_init = NULL;
16630         dtrace_cpustart_fini = NULL;
16631         dtrace_debugger_init = NULL;
16632         dtrace_debugger_fini = NULL;
16633         dtrace_modload = NULL;
16634         dtrace_modunload = NULL;
16635 
16636         ASSERT(dtrace_getf == 0);
16637         ASSERT(dtrace_closef == NULL);
16638 
16639         mutex_exit(&cpu_lock);
16640 
16641         kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
16642         dtrace_probes = NULL;
16643         dtrace_nprobes = 0;
16644 
16645         dtrace_hash_destroy(dtrace_bymod);
16646         dtrace_hash_destroy(dtrace_byfunc);
16647         dtrace_hash_destroy(dtrace_byname);
16648         dtrace_bymod = NULL;
16649         dtrace_byfunc = NULL;
16650         dtrace_byname = NULL;
16651 
16652         kmem_cache_destroy(dtrace_state_cache);
16653         vmem_destroy(dtrace_minor);
16654         vmem_destroy(dtrace_arena);
16655 
16656         if (dtrace_toxrange != NULL) {
16657                 kmem_free(dtrace_toxrange,
16658                     dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
16659                 dtrace_toxrange = NULL;
16660                 dtrace_toxranges = 0;
16661                 dtrace_toxranges_max = 0;
16662         }
16663 
16664         ddi_remove_minor_node(dtrace_devi, NULL);
16665         dtrace_devi = NULL;
16666 
16667         ddi_soft_state_fini(&dtrace_softstate);
16668 
16669         ASSERT(dtrace_vtime_references == 0);
16670         ASSERT(dtrace_opens == 0);
16671         ASSERT(dtrace_retained == NULL);
16672 
16673         mutex_exit(&dtrace_lock);
16674         mutex_exit(&dtrace_provider_lock);
16675 
16676         /*
16677          * We don't destroy the task queue until after we have dropped our
16678          * locks (taskq_destroy() may block on running tasks).  To prevent
16679          * attempting to do work after we have effectively detached but before
16680          * the task queue has been destroyed, all tasks dispatched via the
16681          * task queue must check that DTrace is still attached before
16682          * performing any operation.
16683          */
16684         taskq_destroy(dtrace_taskq);
16685         dtrace_taskq = NULL;
16686 
16687         return (DDI_SUCCESS);
16688 }
16689 
16690 /*ARGSUSED*/
16691 static int
16692 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
16693 {
16694         int error;
16695 
16696         switch (infocmd) {
16697         case DDI_INFO_DEVT2DEVINFO:
16698                 *result = (void *)dtrace_devi;
16699                 error = DDI_SUCCESS;
16700                 break;
16701         case DDI_INFO_DEVT2INSTANCE:
16702                 *result = (void *)0;
16703                 error = DDI_SUCCESS;
16704                 break;
16705         default:
16706                 error = DDI_FAILURE;
16707         }
16708         return (error);
16709 }
16710 
16711 static struct cb_ops dtrace_cb_ops = {
16712         dtrace_open,            /* open */
16713         dtrace_close,           /* close */
16714         nulldev,                /* strategy */
16715         nulldev,                /* print */
16716         nodev,                  /* dump */
16717         nodev,                  /* read */
16718         nodev,                  /* write */
16719         dtrace_ioctl,           /* ioctl */
16720         nodev,                  /* devmap */
16721         nodev,                  /* mmap */
16722         nodev,                  /* segmap */
16723         nochpoll,               /* poll */
16724         ddi_prop_op,            /* cb_prop_op */
16725         0,                      /* streamtab  */
16726         D_NEW | D_MP            /* Driver compatibility flag */
16727 };
16728 
16729 static struct dev_ops dtrace_ops = {
16730         DEVO_REV,               /* devo_rev */
16731         0,                      /* refcnt */
16732         dtrace_info,            /* get_dev_info */
16733         nulldev,                /* identify */
16734         nulldev,                /* probe */
16735         dtrace_attach,          /* attach */
16736         dtrace_detach,          /* detach */
16737         nodev,                  /* reset */
16738         &dtrace_cb_ops,             /* driver operations */
16739         NULL,                   /* bus operations */
16740         nodev,                  /* dev power */
16741         ddi_quiesce_not_needed,         /* quiesce */
16742 };
16743 
16744 static struct modldrv modldrv = {
16745         &mod_driverops,             /* module type (this is a pseudo driver) */
16746         "Dynamic Tracing",      /* name of module */
16747         &dtrace_ops,                /* driver ops */
16748 };
16749 
16750 static struct modlinkage modlinkage = {
16751         MODREV_1,
16752         (void *)&modldrv,
16753         NULL
16754 };
16755 
16756 int
16757 _init(void)
16758 {
16759         return (mod_install(&modlinkage));
16760 }
16761 
16762 int
16763 _info(struct modinfo *modinfop)
16764 {
16765         return (mod_info(&modlinkage, modinfop));
16766 }
16767 
16768 int
16769 _fini(void)
16770 {
16771         return (mod_remove(&modlinkage));
16772 }