Home | History | Annotate | Download | only in dtrace
      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 2009 Sun Microsystems, Inc.  All rights reserved.
     24  * Use is subject to license terms.
     25  */
     26 
     27 /*
     28  * DTrace - Dynamic Tracing for Solaris
     29  *
     30  * This is the implementation of the Solaris Dynamic Tracing framework
     31  * (DTrace).  The user-visible interface to DTrace is described at length in
     32  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
     33  * library, the in-kernel DTrace framework, and the DTrace providers are
     34  * described in the block comments in the <sys/dtrace.h> header file.  The
     35  * internal architecture of DTrace is described in the block comments in the
     36  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
     37  * implementation very much assume mastery of all of these sources; if one has
     38  * an unanswered question about the implementation, one should consult them
     39  * first.
     40  *
     41  * The functions here are ordered roughly as follows:
     42  *
     43  *   - Probe context functions
     44  *   - Probe hashing functions
     45  *   - Non-probe context utility functions
     46  *   - Matching functions
     47  *   - Provider-to-Framework API functions
     48  *   - Probe management functions
     49  *   - DIF object functions
     50  *   - Format functions
     51  *   - Predicate functions
     52  *   - ECB functions
     53  *   - Buffer functions
     54  *   - Enabling functions
     55  *   - DOF functions
     56  *   - Anonymous enabling functions
     57  *   - Consumer state functions
     58  *   - Helper functions
     59  *   - Hook functions
     60  *   - Driver cookbook functions
     61  *
     62  * Each group of functions begins with a block comment labelled the "DTrace
     63  * [Group] Functions", allowing one to find each block by searching forward
     64  * on capital-f functions.
     65  */
     66 #include <sys/errno.h>
     67 #include <sys/stat.h>
     68 #include <sys/modctl.h>
     69 #include <sys/conf.h>
     70 #include <sys/systm.h>
     71 #include <sys/ddi.h>
     72 #include <sys/sunddi.h>
     73 #include <sys/cpuvar.h>
     74 #include <sys/kmem.h>
     75 #include <sys/strsubr.h>
     76 #include <sys/sysmacros.h>
     77 #include <sys/dtrace_impl.h>
     78 #include <sys/atomic.h>
     79 #include <sys/cmn_err.h>
     80 #include <sys/mutex_impl.h>
     81 #include <sys/rwlock_impl.h>
     82 #include <sys/ctf_api.h>
     83 #include <sys/panic.h>
     84 #include <sys/priv_impl.h>
     85 #include <sys/policy.h>
     86 #include <sys/cred_impl.h>
     87 #include <sys/procfs_isa.h>
     88 #include <sys/taskq.h>
     89 #include <sys/mkdev.h>
     90 #include <sys/kdi.h>
     91 #include <sys/zone.h>
     92 #include <sys/socket.h>
     93 #include <netinet/in.h>
     94 
     95 /*
     96  * DTrace Tunable Variables
     97  *
     98  * The following variables may be tuned by adding a line to /etc/system that
     99  * includes both the name of the DTrace module ("dtrace") and the name of the
    100  * variable.  For example:
    101  *
    102  *   set dtrace:dtrace_destructive_disallow = 1
    103  *
    104  * In general, the only variables that one should be tuning this way are those
    105  * that affect system-wide DTrace behavior, and for which the default behavior
    106  * is undesirable.  Most of these variables are tunable on a per-consumer
    107  * basis using DTrace options, and need not be tuned on a system-wide basis.
    108  * When tuning these variables, avoid pathological values; while some attempt
    109  * is made to verify the integrity of these variables, they are not considered
    110  * part of the supported interface to DTrace, and they are therefore not
    111  * checked comprehensively.  Further, these variables should not be tuned
    112  * dynamically via "mdb -kw" or other means; they should only be tuned via
    113  * /etc/system.
    114  */
    115 int		dtrace_destructive_disallow = 0;
    116 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
    117 size_t		dtrace_difo_maxsize = (256 * 1024);
    118 dtrace_optval_t	dtrace_dof_maxsize = (256 * 1024);
    119 size_t		dtrace_global_maxsize = (16 * 1024);
    120 size_t		dtrace_actions_max = (16 * 1024);
    121 size_t		dtrace_retain_max = 1024;
    122 dtrace_optval_t	dtrace_helper_actions_max = 32;
    123 dtrace_optval_t	dtrace_helper_providers_max = 32;
    124 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
    125 size_t		dtrace_strsize_default = 256;
    126 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
    127 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
    128 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
    129 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
    130 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
    131 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
    132 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
    133 dtrace_optval_t	dtrace_nspec_default = 1;
    134 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
    135 dtrace_optval_t dtrace_stackframes_default = 20;
    136 dtrace_optval_t dtrace_ustackframes_default = 20;
    137 dtrace_optval_t dtrace_jstackframes_default = 50;
    138 dtrace_optval_t dtrace_jstackstrsize_default = 512;
    139 int		dtrace_msgdsize_max = 128;
    140 hrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
    141 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
    142 int		dtrace_devdepth_max = 32;
    143 int		dtrace_err_verbose;
    144 hrtime_t	dtrace_deadman_interval = NANOSEC;
    145 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
    146 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
    147 
    148 /*
    149  * DTrace External Variables
    150  *
    151  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
    152  * available to DTrace consumers via the backtick (`) syntax.  One of these,
    153  * dtrace_zero, is made deliberately so:  it is provided as a source of
    154  * well-known, zero-filled memory.  While this variable is not documented,
    155  * it is used by some translators as an implementation detail.
    156  */
    157 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
    158 
    159 /*
    160  * DTrace Internal Variables
    161  */
    162 static dev_info_t	*dtrace_devi;		/* device info */
    163 static vmem_t		*dtrace_arena;		/* probe ID arena */
    164 static vmem_t		*dtrace_minor;		/* minor number arena */
    165 static taskq_t		*dtrace_taskq;		/* task queue */
    166 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
    167 static int		dtrace_nprobes;		/* number of probes */
    168 static dtrace_provider_t *dtrace_provider;	/* provider list */
    169 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
    170 static int		dtrace_opens;		/* number of opens */
    171 static int		dtrace_helpers;		/* number of helpers */
    172 static void		*dtrace_softstate;	/* softstate pointer */
    173 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
    174 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
    175 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
    176 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
    177 static int		dtrace_toxranges;	/* number of toxic ranges */
    178 static int		dtrace_toxranges_max;	/* size of toxic range array */
    179 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
    180 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
    181 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
    182 static kthread_t	*dtrace_panicked;	/* panicking thread */
    183 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
    184 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
    185 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
    186 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
    187 static dtrace_genid_t	dtrace_retained_gen;	/* current retained enab gen */
    188 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
    189 
    190 /*
    191  * DTrace Locking
    192  * DTrace is protected by three (relatively coarse-grained) locks:
    193  *
    194  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
    195  *     including enabling state, probes, ECBs, consumer state, helper state,
    196  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
    197  *     probe context is lock-free -- synchronization is handled via the
    198  *     dtrace_sync() cross call mechanism.
    199  *
    200  * (2) dtrace_provider_lock is required when manipulating provider state, or
    201  *     when provider state must be held constant.
    202  *
    203  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
    204  *     when meta provider state must be held constant.
    205  *
    206  * The lock ordering between these three locks is dtrace_meta_lock before
    207  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
    208  * several places where dtrace_provider_lock is held by the framework as it
    209  * calls into the providers -- which then call back into the framework,
    210  * grabbing dtrace_lock.)
    211  *
    212  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
    213  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
    214  * role as a coarse-grained lock; it is acquired before both of these locks.
    215  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
    216  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
    217  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
    218  * acquired _between_ dtrace_provider_lock and dtrace_lock.
    219  */
    220 static kmutex_t		dtrace_lock;		/* probe state lock */
    221 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
    222 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
    223 
    224 /*
    225  * DTrace Provider Variables
    226  *
    227  * These are the variables relating to DTrace as a provider (that is, the
    228  * provider of the BEGIN, END, and ERROR probes).
    229  */
    230 static dtrace_pattr_t	dtrace_provider_attr = {
    231 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
    232 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
    233 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
    234 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
    235 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
    236 };
    237 
    238 static void
    239 dtrace_nullop(void)
    240 {}
    241 
    242 static int
    243 dtrace_enable_nullop(void)
    244 {
    245 	return (0);
    246 }
    247 
    248 static dtrace_pops_t	dtrace_provider_ops = {
    249 	(void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
    250 	(void (*)(void *, struct modctl *))dtrace_nullop,
    251 	(int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
    252 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
    253 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
    254 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
    255 	NULL,
    256 	NULL,
    257 	NULL,
    258 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
    259 };
    260 
    261 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
    262 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
    263 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
    264 
    265 /*
    266  * DTrace Helper Tracing Variables
    267  */
    268 uint32_t dtrace_helptrace_next = 0;
    269 uint32_t dtrace_helptrace_nlocals;
    270 char	*dtrace_helptrace_buffer;
    271 int	dtrace_helptrace_bufsize = 512 * 1024;
    272 
    273 #ifdef DEBUG
    274 int	dtrace_helptrace_enabled = 1;
    275 #else
    276 int	dtrace_helptrace_enabled = 0;
    277 #endif
    278 
    279 /*
    280  * DTrace Error Hashing
    281  *
    282  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
    283  * table.  This is very useful for checking coverage of tests that are
    284  * expected to induce DIF or DOF processing errors, and may be useful for
    285  * debugging problems in the DIF code generator or in DOF generation .  The
    286  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
    287  */
    288 #ifdef DEBUG
    289 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
    290 static const char *dtrace_errlast;
    291 static kthread_t *dtrace_errthread;
    292 static kmutex_t dtrace_errlock;
    293 #endif
    294 
    295 /*
    296  * DTrace Macros and Constants
    297  *
    298  * These are various macros that are useful in various spots in the
    299  * implementation, along with a few random constants that have no meaning
    300  * outside of the implementation.  There is no real structure to this cpp
    301  * mishmash -- but is there ever?
    302  */
    303 #define	DTRACE_HASHSTR(hash, probe)	\
    304 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
    305 
    306 #define	DTRACE_HASHNEXT(hash, probe)	\
    307 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
    308 
    309 #define	DTRACE_HASHPREV(hash, probe)	\
    310 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
    311 
    312 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
    313 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
    314 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
    315 
    316 #define	DTRACE_AGGHASHSIZE_SLEW		17
    317 
    318 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
    319 
    320 /*
    321  * The key for a thread-local variable consists of the lower 61 bits of the
    322  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
    323  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
    324  * equal to a variable identifier.  This is necessary (but not sufficient) to
    325  * assure that global associative arrays never collide with thread-local
    326  * variables.  To guarantee that they cannot collide, we must also define the
    327  * order for keying dynamic variables.  That order is:
    328  *
    329  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
    330  *
    331  * Because the variable-key and the tls-key are in orthogonal spaces, there is
    332  * no way for a global variable key signature to match a thread-local key
    333  * signature.
    334  */
    335 #define	DTRACE_TLS_THRKEY(where) { \
    336 	uint_t intr = 0; \
    337 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
    338 	for (; actv; actv >>= 1) \
    339 		intr++; \
    340 	ASSERT(intr < (1 << 3)); \
    341 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
    342 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
    343 }
    344 
    345 #define	DT_BSWAP_8(x)	((x) & 0xff)
    346 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
    347 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
    348 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
    349 
    350 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
    351 
    352 #define	DTRACE_STORE(type, tomax, offset, what) \
    353 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
    354 
    355 #ifndef __i386
    356 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
    357 	if (addr & (size - 1)) {					\
    358 		*flags |= CPU_DTRACE_BADALIGN;				\
    359 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
    360 		return (0);						\
    361 	}
    362 #else
    363 #define	DTRACE_ALIGNCHECK(addr, size, flags)
    364 #endif
    365 
    366 /*
    367  * Test whether a range of memory starting at testaddr of size testsz falls
    368  * within the range of memory described by addr, sz.  We take care to avoid
    369  * problems with overflow and underflow of the unsigned quantities, and
    370  * disallow all negative sizes.  Ranges of size 0 are allowed.
    371  */
    372 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
    373 	((testaddr) - (baseaddr) < (basesz) && \
    374 	(testaddr) + (testsz) - (baseaddr) <= (basesz) && \
    375 	(testaddr) + (testsz) >= (testaddr))
    376 
    377 /*
    378  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
    379  * alloc_sz on the righthand side of the comparison in order to avoid overflow
    380  * or underflow in the comparison with it.  This is simpler than the INRANGE
    381  * check above, because we know that the dtms_scratch_ptr is valid in the
    382  * range.  Allocations of size zero are allowed.
    383  */
    384 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
    385 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
    386 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
    387 
    388 #define	DTRACE_LOADFUNC(bits)						\
    389 /*CSTYLED*/								\
    390 uint##bits##_t								\
    391 dtrace_load##bits(uintptr_t addr)					\
    392 {									\
    393 	size_t size = bits / NBBY;					\
    394 	/*CSTYLED*/							\
    395 	uint##bits##_t rval;						\
    396 	int i;								\
    397 	volatile uint16_t *flags = (volatile uint16_t *)		\
    398 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
    399 									\
    400 	DTRACE_ALIGNCHECK(addr, size, flags);				\
    401 									\
    402 	for (i = 0; i < dtrace_toxranges; i++) {			\
    403 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
    404 			continue;					\
    405 									\
    406 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
    407 			continue;					\
    408 									\
    409 		/*							\
    410 		 * This address falls within a toxic region; return 0.	\
    411 		 */							\
    412 		*flags |= CPU_DTRACE_BADADDR;				\
    413 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
    414 		return (0);						\
    415 	}								\
    416 									\
    417 	*flags |= CPU_DTRACE_NOFAULT;					\
    418 	/*CSTYLED*/							\
    419 	rval = *((volatile uint##bits##_t *)addr);			\
    420 	*flags &= ~CPU_DTRACE_NOFAULT;					\
    421 									\
    422 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
    423 }
    424 
    425 #ifdef _LP64
    426 #define	dtrace_loadptr	dtrace_load64
    427 #else
    428 #define	dtrace_loadptr	dtrace_load32
    429 #endif
    430 
    431 #define	DTRACE_DYNHASH_FREE	0
    432 #define	DTRACE_DYNHASH_SINK	1
    433 #define	DTRACE_DYNHASH_VALID	2
    434 
    435 #define	DTRACE_MATCH_FAIL	-1
    436 #define	DTRACE_MATCH_NEXT	0
    437 #define	DTRACE_MATCH_DONE	1
    438 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
    439 #define	DTRACE_STATE_ALIGN	64
    440 
    441 #define	DTRACE_FLAGS2FLT(flags)						\
    442 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
    443 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
    444 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
    445 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
    446 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
    447 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
    448 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
    449 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
    450 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
    451 	DTRACEFLT_UNKNOWN)
    452 
    453 #define	DTRACEACT_ISSTRING(act)						\
    454 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
    455 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
    456 
    457 static size_t dtrace_strlen(const char *, size_t);
    458 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
    459 static void dtrace_enabling_provide(dtrace_provider_t *);
    460 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
    461 static void dtrace_enabling_matchall(void);
    462 static dtrace_state_t *dtrace_anon_grab(void);
    463 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
    464     dtrace_state_t *, uint64_t, uint64_t);
    465 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
    466 static void dtrace_buffer_drop(dtrace_buffer_t *);
    467 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
    468     dtrace_state_t *, dtrace_mstate_t *);
    469 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
    470     dtrace_optval_t);
    471 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
    472 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
    473 
    474 /*
    475  * DTrace Probe Context Functions
    476  *
    477  * These functions are called from probe context.  Because probe context is
    478  * any context in which C may be called, arbitrarily locks may be held,
    479  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
    480  * As a result, functions called from probe context may only call other DTrace
    481  * support functions -- they may not interact at all with the system at large.
    482  * (Note that the ASSERT macro is made probe-context safe by redefining it in
    483  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
    484  * loads are to be performed from probe context, they _must_ be in terms of
    485  * the safe dtrace_load*() variants.
    486  *
    487  * Some functions in this block are not actually called from probe context;
    488  * for these functions, there will be a comment above the function reading
    489  * "Note:  not called from probe context."
    490  */
    491 void
    492 dtrace_panic(const char *format, ...)
    493 {
    494 	va_list alist;
    495 
    496 	va_start(alist, format);
    497 	dtrace_vpanic(format, alist);
    498 	va_end(alist);
    499 }
    500 
    501 int
    502 dtrace_assfail(const char *a, const char *f, int l)
    503 {
    504 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
    505 
    506 	/*
    507 	 * We just need something here that even the most clever compiler
    508 	 * cannot optimize away.
    509 	 */
    510 	return (a[(uintptr_t)f]);
    511 }
    512 
    513 /*
    514  * Atomically increment a specified error counter from probe context.
    515  */
    516 static void
    517 dtrace_error(uint32_t *counter)
    518 {
    519 	/*
    520 	 * Most counters stored to in probe context are per-CPU counters.
    521 	 * However, there are some error conditions that are sufficiently
    522 	 * arcane that they don't merit per-CPU storage.  If these counters
    523 	 * are incremented concurrently on different CPUs, scalability will be
    524 	 * adversely affected -- but we don't expect them to be white-hot in a
    525 	 * correctly constructed enabling...
    526 	 */
    527 	uint32_t oval, nval;
    528 
    529 	do {
    530 		oval = *counter;
    531 
    532 		if ((nval = oval + 1) == 0) {
    533 			/*
    534 			 * If the counter would wrap, set it to 1 -- assuring
    535 			 * that the counter is never zero when we have seen
    536 			 * errors.  (The counter must be 32-bits because we
    537 			 * aren't guaranteed a 64-bit compare&swap operation.)
    538 			 * To save this code both the infamy of being fingered
    539 			 * by a priggish news story and the indignity of being
    540 			 * the target of a neo-puritan witch trial, we're
    541 			 * carefully avoiding any colorful description of the
    542 			 * likelihood of this condition -- but suffice it to
    543 			 * say that it is only slightly more likely than the
    544 			 * overflow of predicate cache IDs, as discussed in
    545 			 * dtrace_predicate_create().
    546 			 */
    547 			nval = 1;
    548 		}
    549 	} while (dtrace_cas32(counter, oval, nval) != oval);
    550 }
    551 
    552 /*
    553  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
    554  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
    555  */
    556 DTRACE_LOADFUNC(8)
    557 DTRACE_LOADFUNC(16)
    558 DTRACE_LOADFUNC(32)
    559 DTRACE_LOADFUNC(64)
    560 
    561 static int
    562 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
    563 {
    564 	if (dest < mstate->dtms_scratch_base)
    565 		return (0);
    566 
    567 	if (dest + size < dest)
    568 		return (0);
    569 
    570 	if (dest + size > mstate->dtms_scratch_ptr)
    571 		return (0);
    572 
    573 	return (1);
    574 }
    575 
    576 static int
    577 dtrace_canstore_statvar(uint64_t addr, size_t sz,
    578     dtrace_statvar_t **svars, int nsvars)
    579 {
    580 	int i;
    581 
    582 	for (i = 0; i < nsvars; i++) {
    583 		dtrace_statvar_t *svar = svars[i];
    584 
    585 		if (svar == NULL || svar->dtsv_size == 0)
    586 			continue;
    587 
    588 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
    589 			return (1);
    590 	}
    591 
    592 	return (0);
    593 }
    594 
    595 /*
    596  * Check to see if the address is within a memory region to which a store may
    597  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
    598  * region.  The caller of dtrace_canstore() is responsible for performing any
    599  * alignment checks that are needed before stores are actually executed.
    600  */
    601 static int
    602 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
    603     dtrace_vstate_t *vstate)
    604 {
    605 	/*
    606 	 * First, check to see if the address is in scratch space...
    607 	 */
    608 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
    609 	    mstate->dtms_scratch_size))
    610 		return (1);
    611 
    612 	/*
    613 	 * Now check to see if it's a dynamic variable.  This check will pick
    614 	 * up both thread-local variables and any global dynamically-allocated
    615 	 * variables.
    616 	 */
    617 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
    618 	    vstate->dtvs_dynvars.dtds_size)) {
    619 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
    620 		uintptr_t base = (uintptr_t)dstate->dtds_base +
    621 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
    622 		uintptr_t chunkoffs;
    623 
    624 		/*
    625 		 * Before we assume that we can store here, we need to make
    626 		 * sure that it isn't in our metadata -- storing to our
    627 		 * dynamic variable metadata would corrupt our state.  For
    628 		 * the range to not include any dynamic variable metadata,
    629 		 * it must:
    630 		 *
    631 		 *	(1) Start above the hash table that is at the base of
    632 		 *	the dynamic variable space
    633 		 *
    634 		 *	(2) Have a starting chunk offset that is beyond the
    635 		 *	dtrace_dynvar_t that is at the base of every chunk
    636 		 *
    637 		 *	(3) Not span a chunk boundary
    638 		 *
    639 		 */
    640 		if (addr < base)
    641 			return (0);
    642 
    643 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
    644 
    645 		if (chunkoffs < sizeof (dtrace_dynvar_t))
    646 			return (0);
    647 
    648 		if (chunkoffs + sz > dstate->dtds_chunksize)
    649 			return (0);
    650 
    651 		return (1);
    652 	}
    653 
    654 	/*
    655 	 * Finally, check the static local and global variables.  These checks
    656 	 * take the longest, so we perform them last.
    657 	 */
    658 	if (dtrace_canstore_statvar(addr, sz,
    659 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
    660 		return (1);
    661 
    662 	if (dtrace_canstore_statvar(addr, sz,
    663 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
    664 		return (1);
    665 
    666 	return (0);
    667 }
    668 
    669 
    670 /*
    671  * Convenience routine to check to see if the address is within a memory
    672  * region in which a load may be issued given the user's privilege level;
    673  * if not, it sets the appropriate error flags and loads 'addr' into the
    674  * illegal value slot.
    675  *
    676  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
    677  * appropriate memory access protection.
    678  */
    679 static int
    680 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
    681     dtrace_vstate_t *vstate)
    682 {
    683 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
    684 
    685 	/*
    686 	 * If we hold the privilege to read from kernel memory, then
    687 	 * everything is readable.
    688 	 */
    689 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
    690 		return (1);
    691 
    692 	/*
    693 	 * You can obviously read that which you can store.
    694 	 */
    695 	if (dtrace_canstore(addr, sz, mstate, vstate))
    696 		return (1);
    697 
    698 	/*
    699 	 * We're allowed to read from our own string table.
    700 	 */
    701 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
    702 	    mstate->dtms_difo->dtdo_strlen))
    703 		return (1);
    704 
    705 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
    706 	*illval = addr;
    707 	return (0);
    708 }
    709 
    710 /*
    711  * Convenience routine to check to see if a given string is within a memory
    712  * region in which a load may be issued given the user's privilege level;
    713  * this exists so that we don't need to issue unnecessary dtrace_strlen()
    714  * calls in the event that the user has all privileges.
    715  */
    716 static int
    717 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
    718     dtrace_vstate_t *vstate)
    719 {
    720 	size_t strsz;
    721 
    722 	/*
    723 	 * If we hold the privilege to read from kernel memory, then
    724 	 * everything is readable.
    725 	 */
    726 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
    727 		return (1);
    728 
    729 	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
    730 	if (dtrace_canload(addr, strsz, mstate, vstate))
    731 		return (1);
    732 
    733 	return (0);
    734 }
    735 
    736 /*
    737  * Convenience routine to check to see if a given variable is within a memory
    738  * region in which a load may be issued given the user's privilege level.
    739  */
    740 static int
    741 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
    742     dtrace_vstate_t *vstate)
    743 {
    744 	size_t sz;
    745 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
    746 
    747 	/*
    748 	 * If we hold the privilege to read from kernel memory, then
    749 	 * everything is readable.
    750 	 */
    751 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
    752 		return (1);
    753 
    754 	if (type->dtdt_kind == DIF_TYPE_STRING)
    755 		sz = dtrace_strlen(src,
    756 		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
    757 	else
    758 		sz = type->dtdt_size;
    759 
    760 	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
    761 }
    762 
    763 /*
    764  * Compare two strings using safe loads.
    765  */
    766 static int
    767 dtrace_strncmp(char *s1, char *s2, size_t limit)
    768 {
    769 	uint8_t c1, c2;
    770 	volatile uint16_t *flags;
    771 
    772 	if (s1 == s2 || limit == 0)
    773 		return (0);
    774 
    775 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
    776 
    777 	do {
    778 		if (s1 == NULL) {
    779 			c1 = '\0';
    780 		} else {
    781 			c1 = dtrace_load8((uintptr_t)s1++);
    782 		}
    783 
    784 		if (s2 == NULL) {
    785 			c2 = '\0';
    786 		} else {
    787 			c2 = dtrace_load8((uintptr_t)s2++);
    788 		}
    789 
    790 		if (c1 != c2)
    791 			return (c1 - c2);
    792 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
    793 
    794 	return (0);
    795 }
    796 
    797 /*
    798  * Compute strlen(s) for a string using safe memory accesses.  The additional
    799  * len parameter is used to specify a maximum length to ensure completion.
    800  */
    801 static size_t
    802 dtrace_strlen(const char *s, size_t lim)
    803 {
    804 	uint_t len;
    805 
    806 	for (len = 0; len != lim; len++) {
    807 		if (dtrace_load8((uintptr_t)s++) == '\0')
    808 			break;
    809 	}
    810 
    811 	return (len);
    812 }
    813 
    814 /*
    815  * Check if an address falls within a toxic region.
    816  */
    817 static int
    818 dtrace_istoxic(uintptr_t kaddr, size_t size)
    819 {
    820 	uintptr_t taddr, tsize;
    821 	int i;
    822 
    823 	for (i = 0; i < dtrace_toxranges; i++) {
    824 		taddr = dtrace_toxrange[i].dtt_base;
    825 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
    826 
    827 		if (kaddr - taddr < tsize) {
    828 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
    829 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
    830 			return (1);
    831 		}
    832 
    833 		if (taddr - kaddr < size) {
    834 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
    835 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
    836 			return (1);
    837 		}
    838 	}
    839 
    840 	return (0);
    841 }
    842 
    843 /*
    844  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
    845  * memory specified by the DIF program.  The dst is assumed to be safe memory
    846  * that we can store to directly because it is managed by DTrace.  As with
    847  * standard bcopy, overlapping copies are handled properly.
    848  */
    849 static void
    850 dtrace_bcopy(const void *src, void *dst, size_t len)
    851 {
    852 	if (len != 0) {
    853 		uint8_t *s1 = dst;
    854 		const uint8_t *s2 = src;
    855 
    856 		if (s1 <= s2) {
    857 			do {
    858 				*s1++ = dtrace_load8((uintptr_t)s2++);
    859 			} while (--len != 0);
    860 		} else {
    861 			s2 += len;
    862 			s1 += len;
    863 
    864 			do {
    865 				*--s1 = dtrace_load8((uintptr_t)--s2);
    866 			} while (--len != 0);
    867 		}
    868 	}
    869 }
    870 
    871 /*
    872  * Copy src to dst using safe memory accesses, up to either the specified
    873  * length, or the point that a nul byte is encountered.  The src is assumed to
    874  * be unsafe memory specified by the DIF program.  The dst is assumed to be
    875  * safe memory that we can store to directly because it is managed by DTrace.
    876  * Unlike dtrace_bcopy(), overlapping regions are not handled.
    877  */
    878 static void
    879 dtrace_strcpy(const void *src, void *dst, size_t len)
    880 {
    881 	if (len != 0) {
    882 		uint8_t *s1 = dst, c;
    883 		const uint8_t *s2 = src;
    884 
    885 		do {
    886 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
    887 		} while (--len != 0 && c != '\0');
    888 	}
    889 }
    890 
    891 /*
    892  * Copy src to dst, deriving the size and type from the specified (BYREF)
    893  * variable type.  The src is assumed to be unsafe memory specified by the DIF
    894  * program.  The dst is assumed to be DTrace variable memory that is of the
    895  * specified type; we assume that we can store to directly.
    896  */
    897 static void
    898 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
    899 {
    900 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
    901 
    902 	if (type->dtdt_kind == DIF_TYPE_STRING) {
    903 		dtrace_strcpy(src, dst, type->dtdt_size);
    904 	} else {
    905 		dtrace_bcopy(src, dst, type->dtdt_size);
    906 	}
    907 }
    908 
    909 /*
    910  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
    911  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
    912  * safe memory that we can access directly because it is managed by DTrace.
    913  */
    914 static int
    915 dtrace_bcmp(const void *s1, const void *s2, size_t len)
    916 {
    917 	volatile uint16_t *flags;
    918 
    919 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
    920 
    921 	if (s1 == s2)
    922 		return (0);
    923 
    924 	if (s1 == NULL || s2 == NULL)
    925 		return (1);
    926 
    927 	if (s1 != s2 && len != 0) {
    928 		const uint8_t *ps1 = s1;
    929 		const uint8_t *ps2 = s2;
    930 
    931 		do {
    932 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
    933 				return (1);
    934 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
    935 	}
    936 	return (0);
    937 }
    938 
    939 /*
    940  * Zero the specified region using a simple byte-by-byte loop.  Note that this
    941  * is for safe DTrace-managed memory only.
    942  */
    943 static void
    944 dtrace_bzero(void *dst, size_t len)
    945 {
    946 	uchar_t *cp;
    947 
    948 	for (cp = dst; len != 0; len--)
    949 		*cp++ = 0;
    950 }
    951 
    952 static void
    953 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
    954 {
    955 	uint64_t result[2];
    956 
    957 	result[0] = addend1[0] + addend2[0];
    958 	result[1] = addend1[1] + addend2[1] +
    959 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
    960 
    961 	sum[0] = result[0];
    962 	sum[1] = result[1];
    963 }
    964 
    965 /*
    966  * Shift the 128-bit value in a by b. If b is positive, shift left.
    967  * If b is negative, shift right.
    968  */
    969 static void
    970 dtrace_shift_128(uint64_t *a, int b)
    971 {
    972 	uint64_t mask;
    973 
    974 	if (b == 0)
    975 		return;
    976 
    977 	if (b < 0) {
    978 		b = -b;
    979 		if (b >= 64) {
    980 			a[0] = a[1] >> (b - 64);
    981 			a[1] = 0;
    982 		} else {
    983 			a[0] >>= b;
    984 			mask = 1LL << (64 - b);
    985 			mask -= 1;
    986 			a[0] |= ((a[1] & mask) << (64 - b));
    987 			a[1] >>= b;
    988 		}
    989 	} else {
    990 		if (b >= 64) {
    991 			a[1] = a[0] << (b - 64);
    992 			a[0] = 0;
    993 		} else {
    994 			a[1] <<= b;
    995 			mask = a[0] >> (64 - b);
    996 			a[1] |= mask;
    997 			a[0] <<= b;
    998 		}
    999 	}
   1000 }
   1001 
   1002 /*
   1003  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
   1004  * use native multiplication on those, and then re-combine into the
   1005  * resulting 128-bit value.
   1006  *
   1007  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
   1008  *     hi1 * hi2 << 64 +
   1009  *     hi1 * lo2 << 32 +
   1010  *     hi2 * lo1 << 32 +
   1011  *     lo1 * lo2
   1012  */
   1013 static void
   1014 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
   1015 {
   1016 	uint64_t hi1, hi2, lo1, lo2;
   1017 	uint64_t tmp[2];
   1018 
   1019 	hi1 = factor1 >> 32;
   1020 	hi2 = factor2 >> 32;
   1021 
   1022 	lo1 = factor1 & DT_MASK_LO;
   1023 	lo2 = factor2 & DT_MASK_LO;
   1024 
   1025 	product[0] = lo1 * lo2;
   1026 	product[1] = hi1 * hi2;
   1027 
   1028 	tmp[0] = hi1 * lo2;
   1029 	tmp[1] = 0;
   1030 	dtrace_shift_128(tmp, 32);
   1031 	dtrace_add_128(product, tmp, product);
   1032 
   1033 	tmp[0] = hi2 * lo1;
   1034 	tmp[1] = 0;
   1035 	dtrace_shift_128(tmp, 32);
   1036 	dtrace_add_128(product, tmp, product);
   1037 }
   1038 
   1039 /*
   1040  * This privilege check should be used by actions and subroutines to
   1041  * verify that the user credentials of the process that enabled the
   1042  * invoking ECB match the target credentials
   1043  */
   1044 static int
   1045 dtrace_priv_proc_common_user(dtrace_state_t *state)
   1046 {
   1047 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
   1048 
   1049 	/*
   1050 	 * We should always have a non-NULL state cred here, since if cred
   1051 	 * is null (anonymous tracing), we fast-path bypass this routine.
   1052 	 */
   1053 	ASSERT(s_cr != NULL);
   1054 
   1055 	if ((cr = CRED()) != NULL &&
   1056 	    s_cr->cr_uid == cr->cr_uid &&
   1057 	    s_cr->cr_uid == cr->cr_ruid &&
   1058 	    s_cr->cr_uid == cr->cr_suid &&
   1059 	    s_cr->cr_gid == cr->cr_gid &&
   1060 	    s_cr->cr_gid == cr->cr_rgid &&
   1061 	    s_cr->cr_gid == cr->cr_sgid)
   1062 		return (1);
   1063 
   1064 	return (0);
   1065 }
   1066 
   1067 /*
   1068  * This privilege check should be used by actions and subroutines to
   1069  * verify that the zone of the process that enabled the invoking ECB
   1070  * matches the target credentials
   1071  */
   1072 static int
   1073 dtrace_priv_proc_common_zone(dtrace_state_t *state)
   1074 {
   1075 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
   1076 
   1077 	/*
   1078 	 * We should always have a non-NULL state cred here, since if cred
   1079 	 * is null (anonymous tracing), we fast-path bypass this routine.
   1080 	 */
   1081 	ASSERT(s_cr != NULL);
   1082 
   1083 	if ((cr = CRED()) != NULL &&
   1084 	    s_cr->cr_zone == cr->cr_zone)
   1085 		return (1);
   1086 
   1087 	return (0);
   1088 }
   1089 
   1090 /*
   1091  * This privilege check should be used by actions and subroutines to
   1092  * verify that the process has not setuid or changed credentials.
   1093  */
   1094 static int
   1095 dtrace_priv_proc_common_nocd()
   1096 {
   1097 	proc_t *proc;
   1098 
   1099 	if ((proc = ttoproc(curthread)) != NULL &&
   1100 	    !(proc->p_flag & SNOCD))
   1101 		return (1);
   1102 
   1103 	return (0);
   1104 }
   1105 
   1106 static int
   1107 dtrace_priv_proc_destructive(dtrace_state_t *state)
   1108 {
   1109 	int action = state->dts_cred.dcr_action;
   1110 
   1111 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
   1112 	    dtrace_priv_proc_common_zone(state) == 0)
   1113 		goto bad;
   1114 
   1115 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
   1116 	    dtrace_priv_proc_common_user(state) == 0)
   1117 		goto bad;
   1118 
   1119 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
   1120 	    dtrace_priv_proc_common_nocd() == 0)
   1121 		goto bad;
   1122 
   1123 	return (1);
   1124 
   1125 bad:
   1126 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
   1127 
   1128 	return (0);
   1129 }
   1130 
   1131 static int
   1132 dtrace_priv_proc_control(dtrace_state_t *state)
   1133 {
   1134 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
   1135 		return (1);
   1136 
   1137 	if (dtrace_priv_proc_common_zone(state) &&
   1138 	    dtrace_priv_proc_common_user(state) &&
   1139 	    dtrace_priv_proc_common_nocd())
   1140 		return (1);
   1141 
   1142 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
   1143 
   1144 	return (0);
   1145 }
   1146 
   1147 static int
   1148 dtrace_priv_proc(dtrace_state_t *state)
   1149 {
   1150 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
   1151 		return (1);
   1152 
   1153 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
   1154 
   1155 	return (0);
   1156 }
   1157 
   1158 static int
   1159 dtrace_priv_kernel(dtrace_state_t *state)
   1160 {
   1161 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
   1162 		return (1);
   1163 
   1164 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
   1165 
   1166 	return (0);
   1167 }
   1168 
   1169 static int
   1170 dtrace_priv_kernel_destructive(dtrace_state_t *state)
   1171 {
   1172 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
   1173 		return (1);
   1174 
   1175 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
   1176 
   1177 	return (0);
   1178 }
   1179 
   1180 /*
   1181  * Note:  not called from probe context.  This function is called
   1182  * asynchronously (and at a regular interval) from outside of probe context to
   1183  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
   1184  * cleaning is explained in detail in <sys/dtrace_impl.h>.
   1185  */
   1186 void
   1187 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
   1188 {
   1189 	dtrace_dynvar_t *dirty;
   1190 	dtrace_dstate_percpu_t *dcpu;
   1191 	int i, work = 0;
   1192 
   1193 	for (i = 0; i < NCPU; i++) {
   1194 		dcpu = &dstate->dtds_percpu[i];
   1195 
   1196 		ASSERT(dcpu->dtdsc_rinsing == NULL);
   1197 
   1198 		/*
   1199 		 * If the dirty list is NULL, there is no dirty work to do.
   1200 		 */
   1201 		if (dcpu->dtdsc_dirty == NULL)
   1202 			continue;
   1203 
   1204 		/*
   1205 		 * If the clean list is non-NULL, then we're not going to do
   1206 		 * any work for this CPU -- it means that there has not been
   1207 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
   1208 		 * since the last time we cleaned house.
   1209 		 */
   1210 		if (dcpu->dtdsc_clean != NULL)
   1211 			continue;
   1212 
   1213 		work = 1;
   1214 
   1215 		/*
   1216 		 * Atomically move the dirty list aside.
   1217 		 */
   1218 		do {
   1219 			dirty = dcpu->dtdsc_dirty;
   1220 
   1221 			/*
   1222 			 * Before we zap the dirty list, set the rinsing list.
   1223 			 * (This allows for a potential assertion in
   1224 			 * dtrace_dynvar():  if a free dynamic variable appears
   1225 			 * on a hash chain, either the dirty list or the
   1226 			 * rinsing list for some CPU must be non-NULL.)
   1227 			 */
   1228 			dcpu->dtdsc_rinsing = dirty;
   1229 			dtrace_membar_producer();
   1230 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
   1231 		    dirty, NULL) != dirty);
   1232 	}
   1233 
   1234 	if (!work) {
   1235 		/*
   1236 		 * We have no work to do; we can simply return.
   1237 		 */
   1238 		return;
   1239 	}
   1240 
   1241 	dtrace_sync();
   1242 
   1243 	for (i = 0; i < NCPU; i++) {
   1244 		dcpu = &dstate->dtds_percpu[i];
   1245 
   1246 		if (dcpu->dtdsc_rinsing == NULL)
   1247 			continue;
   1248 
   1249 		/*
   1250 		 * We are now guaranteed that no hash chain contains a pointer
   1251 		 * into this dirty list; we can make it clean.
   1252 		 */
   1253 		ASSERT(dcpu->dtdsc_clean == NULL);
   1254 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
   1255 		dcpu->dtdsc_rinsing = NULL;
   1256 	}
   1257 
   1258 	/*
   1259 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
   1260 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
   1261 	 * This prevents a race whereby a CPU incorrectly decides that
   1262 	 * the state should be something other than DTRACE_DSTATE_CLEAN
   1263 	 * after dtrace_dynvar_clean() has completed.
   1264 	 */
   1265 	dtrace_sync();
   1266 
   1267 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
   1268 }
   1269 
   1270 /*
   1271  * Depending on the value of the op parameter, this function looks-up,
   1272  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
   1273  * allocation is requested, this function will return a pointer to a
   1274  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
   1275  * variable can be allocated.  If NULL is returned, the appropriate counter
   1276  * will be incremented.
   1277  */
   1278 dtrace_dynvar_t *
   1279 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
   1280     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
   1281     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
   1282 {
   1283 	uint64_t hashval = DTRACE_DYNHASH_VALID;
   1284 	dtrace_dynhash_t *hash = dstate->dtds_hash;
   1285 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
   1286 	processorid_t me = CPU->cpu_id, cpu = me;
   1287 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
   1288 	size_t bucket, ksize;
   1289 	size_t chunksize = dstate->dtds_chunksize;
   1290 	uintptr_t kdata, lock, nstate;
   1291 	uint_t i;
   1292 
   1293 	ASSERT(nkeys != 0);
   1294 
   1295 	/*
   1296 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
   1297 	 * algorithm.  For the by-value portions, we perform the algorithm in
   1298 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
   1299 	 * bit, and seems to have only a minute effect on distribution.  For
   1300 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
   1301 	 * over each referenced byte.  It's painful to do this, but it's much
   1302 	 * better than pathological hash distribution.  The efficacy of the
   1303 	 * hashing algorithm (and a comparison with other algorithms) may be
   1304 	 * found by running the ::dtrace_dynstat MDB dcmd.
   1305 	 */
   1306 	for (i = 0; i < nkeys; i++) {
   1307 		if (key[i].dttk_size == 0) {
   1308 			uint64_t val = key[i].dttk_value;
   1309 
   1310 			hashval += (val >> 48) & 0xffff;
   1311 			hashval += (hashval << 10);
   1312 			hashval ^= (hashval >> 6);
   1313 
   1314 			hashval += (val >> 32) & 0xffff;
   1315 			hashval += (hashval << 10);
   1316 			hashval ^= (hashval >> 6);
   1317 
   1318 			hashval += (val >> 16) & 0xffff;
   1319 			hashval += (hashval << 10);
   1320 			hashval ^= (hashval >> 6);
   1321 
   1322 			hashval += val & 0xffff;
   1323 			hashval += (hashval << 10);
   1324 			hashval ^= (hashval >> 6);
   1325 		} else {
   1326 			/*
   1327 			 * This is incredibly painful, but it beats the hell
   1328 			 * out of the alternative.
   1329 			 */
   1330 			uint64_t j, size = key[i].dttk_size;
   1331 			uintptr_t base = (uintptr_t)key[i].dttk_value;
   1332 
   1333 			if (!dtrace_canload(base, size, mstate, vstate))
   1334 				break;
   1335 
   1336 			for (j = 0; j < size; j++) {
   1337 				hashval += dtrace_load8(base + j);
   1338 				hashval += (hashval << 10);
   1339 				hashval ^= (hashval >> 6);
   1340 			}
   1341 		}
   1342 	}
   1343 
   1344 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
   1345 		return (NULL);
   1346 
   1347 	hashval += (hashval << 3);
   1348 	hashval ^= (hashval >> 11);
   1349 	hashval += (hashval << 15);
   1350 
   1351 	/*
   1352 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
   1353 	 * comes out to be one of our two sentinel hash values.  If this
   1354 	 * actually happens, we set the hashval to be a value known to be a
   1355 	 * non-sentinel value.
   1356 	 */
   1357 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
   1358 		hashval = DTRACE_DYNHASH_VALID;
   1359 
   1360 	/*
   1361 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
   1362 	 * important here, tricks can be pulled to reduce it.  (However, it's
   1363 	 * critical that hash collisions be kept to an absolute minimum;
   1364 	 * they're much more painful than a divide.)  It's better to have a
   1365 	 * solution that generates few collisions and still keeps things
   1366 	 * relatively simple.
   1367 	 */
   1368 	bucket = hashval % dstate->dtds_hashsize;
   1369 
   1370 	if (op == DTRACE_DYNVAR_DEALLOC) {
   1371 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
   1372 
   1373 		for (;;) {
   1374 			while ((lock = *lockp) & 1)
   1375 				continue;
   1376 
   1377 			if (dtrace_casptr((void *)lockp,
   1378 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
   1379 				break;
   1380 		}
   1381 
   1382 		dtrace_membar_producer();
   1383 	}
   1384 
   1385 top:
   1386 	prev = NULL;
   1387 	lock = hash[bucket].dtdh_lock;
   1388 
   1389 	dtrace_membar_consumer();
   1390 
   1391 	start = hash[bucket].dtdh_chain;
   1392 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
   1393 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
   1394 	    op != DTRACE_DYNVAR_DEALLOC));
   1395 
   1396 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
   1397 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
   1398 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
   1399 
   1400 		if (dvar->dtdv_hashval != hashval) {
   1401 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
   1402 				/*
   1403 				 * We've reached the sink, and therefore the
   1404 				 * end of the hash chain; we can kick out of
   1405 				 * the loop knowing that we have seen a valid
   1406 				 * snapshot of state.
   1407 				 */
   1408 				ASSERT(dvar->dtdv_next == NULL);
   1409 				ASSERT(dvar == &dtrace_dynhash_sink);
   1410 				break;
   1411 			}
   1412 
   1413 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
   1414 				/*
   1415 				 * We've gone off the rails:  somewhere along
   1416 				 * the line, one of the members of this hash
   1417 				 * chain was deleted.  Note that we could also
   1418 				 * detect this by simply letting this loop run
   1419 				 * to completion, as we would eventually hit
   1420 				 * the end of the dirty list.  However, we
   1421 				 * want to avoid running the length of the
   1422 				 * dirty list unnecessarily (it might be quite
   1423 				 * long), so we catch this as early as
   1424 				 * possible by detecting the hash marker.  In
   1425 				 * this case, we simply set dvar to NULL and
   1426 				 * break; the conditional after the loop will
   1427 				 * send us back to top.
   1428 				 */
   1429 				dvar = NULL;
   1430 				break;
   1431 			}
   1432 
   1433 			goto next;
   1434 		}
   1435 
   1436 		if (dtuple->dtt_nkeys != nkeys)
   1437 			goto next;
   1438 
   1439 		for (i = 0; i < nkeys; i++, dkey++) {
   1440 			if (dkey->dttk_size != key[i].dttk_size)
   1441 				goto next; /* size or type mismatch */
   1442 
   1443 			if (dkey->dttk_size != 0) {
   1444 				if (dtrace_bcmp(
   1445 				    (void *)(uintptr_t)key[i].dttk_value,
   1446 				    (void *)(uintptr_t)dkey->dttk_value,
   1447 				    dkey->dttk_size))
   1448 					goto next;
   1449 			} else {
   1450 				if (dkey->dttk_value != key[i].dttk_value)
   1451 					goto next;
   1452 			}
   1453 		}
   1454 
   1455 		if (op != DTRACE_DYNVAR_DEALLOC)
   1456 			return (dvar);
   1457 
   1458 		ASSERT(dvar->dtdv_next == NULL ||
   1459 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
   1460 
   1461 		if (prev != NULL) {
   1462 			ASSERT(hash[bucket].dtdh_chain != dvar);
   1463 			ASSERT(start != dvar);
   1464 			ASSERT(prev->dtdv_next == dvar);
   1465 			prev->dtdv_next = dvar->dtdv_next;
   1466 		} else {
   1467 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
   1468 			    start, dvar->dtdv_next) != start) {
   1469 				/*
   1470 				 * We have failed to atomically swing the
   1471 				 * hash table head pointer, presumably because
   1472 				 * of a conflicting allocation on another CPU.
   1473 				 * We need to reread the hash chain and try
   1474 				 * again.
   1475 				 */
   1476 				goto top;
   1477 			}
   1478 		}
   1479 
   1480 		dtrace_membar_producer();
   1481 
   1482 		/*
   1483 		 * Now set the hash value to indicate that it's free.
   1484 		 */
   1485 		ASSERT(hash[bucket].dtdh_chain != dvar);
   1486 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
   1487 
   1488 		dtrace_membar_producer();
   1489 
   1490 		/*
   1491 		 * Set the next pointer to point at the dirty list, and
   1492 		 * atomically swing the dirty pointer to the newly freed dvar.
   1493 		 */
   1494 		do {
   1495 			next = dcpu->dtdsc_dirty;
   1496 			dvar->dtdv_next = next;
   1497 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
   1498 
   1499 		/*
   1500 		 * Finally, unlock this hash bucket.
   1501 		 */
   1502 		ASSERT(hash[bucket].dtdh_lock == lock);
   1503 		ASSERT(lock & 1);
   1504 		hash[bucket].dtdh_lock++;
   1505 
   1506 		return (NULL);
   1507 next:
   1508 		prev = dvar;
   1509 		continue;
   1510 	}
   1511 
   1512 	if (dvar == NULL) {
   1513 		/*
   1514 		 * If dvar is NULL, it is because we went off the rails:
   1515 		 * one of the elements that we traversed in the hash chain
   1516 		 * was deleted while we were traversing it.  In this case,
   1517 		 * we assert that we aren't doing a dealloc (deallocs lock
   1518 		 * the hash bucket to prevent themselves from racing with
   1519 		 * one another), and retry the hash chain traversal.
   1520 		 */
   1521 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
   1522 		goto top;
   1523 	}
   1524 
   1525 	if (op != DTRACE_DYNVAR_ALLOC) {
   1526 		/*
   1527 		 * If we are not to allocate a new variable, we want to
   1528 		 * return NULL now.  Before we return, check that the value
   1529 		 * of the lock word hasn't changed.  If it has, we may have
   1530 		 * seen an inconsistent snapshot.
   1531 		 */
   1532 		if (op == DTRACE_DYNVAR_NOALLOC) {
   1533 			if (hash[bucket].dtdh_lock != lock)
   1534 				goto top;
   1535 		} else {
   1536 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
   1537 			ASSERT(hash[bucket].dtdh_lock == lock);
   1538 			ASSERT(lock & 1);
   1539 			hash[bucket].dtdh_lock++;
   1540 		}
   1541 
   1542 		return (NULL);
   1543 	}
   1544 
   1545 	/*
   1546 	 * We need to allocate a new dynamic variable.  The size we need is the
   1547 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
   1548 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
   1549 	 * the size of any referred-to data (dsize).  We then round the final
   1550 	 * size up to the chunksize for allocation.
   1551 	 */
   1552 	for (ksize = 0, i = 0; i < nkeys; i++)
   1553 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
   1554 
   1555 	/*
   1556 	 * This should be pretty much impossible, but could happen if, say,
   1557 	 * strange DIF specified the tuple.  Ideally, this should be an
   1558 	 * assertion and not an error condition -- but that requires that the
   1559 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
   1560 	 * bullet-proof.  (That is, it must not be able to be fooled by
   1561 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
   1562 	 * solving this would presumably not amount to solving the Halting
   1563 	 * Problem -- but it still seems awfully hard.
   1564 	 */
   1565 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
   1566 	    ksize + dsize > chunksize) {
   1567 		dcpu->dtdsc_drops++;
   1568 		return (NULL);
   1569 	}
   1570 
   1571 	nstate = DTRACE_DSTATE_EMPTY;
   1572 
   1573 	do {
   1574 retry:
   1575 		free = dcpu->dtdsc_free;
   1576 
   1577 		if (free == NULL) {
   1578 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
   1579 			void *rval;
   1580 
   1581 			if (clean == NULL) {
   1582 				/*
   1583 				 * We're out of dynamic variable space on
   1584 				 * this CPU.  Unless we have tried all CPUs,
   1585 				 * we'll try to allocate from a different
   1586 				 * CPU.
   1587 				 */
   1588 				switch (dstate->dtds_state) {
   1589 				case DTRACE_DSTATE_CLEAN: {
   1590 					void *sp = &dstate->dtds_state;
   1591 
   1592 					if (++cpu >= NCPU)
   1593 						cpu = 0;
   1594 
   1595 					if (dcpu->dtdsc_dirty != NULL &&
   1596 					    nstate == DTRACE_DSTATE_EMPTY)
   1597 						nstate = DTRACE_DSTATE_DIRTY;
   1598 
   1599 					if (dcpu->dtdsc_rinsing != NULL)
   1600 						nstate = DTRACE_DSTATE_RINSING;
   1601 
   1602 					dcpu = &dstate->dtds_percpu[cpu];
   1603 
   1604 					if (cpu != me)
   1605 						goto retry;
   1606 
   1607 					(void) dtrace_cas32(sp,
   1608 					    DTRACE_DSTATE_CLEAN, nstate);
   1609 
   1610 					/*
   1611 					 * To increment the correct bean
   1612 					 * counter, take another lap.
   1613 					 */
   1614 					goto retry;
   1615 				}
   1616 
   1617 				case DTRACE_DSTATE_DIRTY:
   1618 					dcpu->dtdsc_dirty_drops++;
   1619 					break;
   1620 
   1621 				case DTRACE_DSTATE_RINSING:
   1622 					dcpu->dtdsc_rinsing_drops++;
   1623 					break;
   1624 
   1625 				case DTRACE_DSTATE_EMPTY:
   1626 					dcpu->dtdsc_drops++;
   1627 					break;
   1628 				}
   1629 
   1630 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
   1631 				return (NULL);
   1632 			}
   1633 
   1634 			/*
   1635 			 * The clean list appears to be non-empty.  We want to
   1636 			 * move the clean list to the free list; we start by
   1637 			 * moving the clean pointer aside.
   1638 			 */
   1639 			if (dtrace_casptr(&dcpu->dtdsc_clean,
   1640 			    clean, NULL) != clean) {
   1641 				/*
   1642 				 * We are in one of two situations:
   1643 				 *
   1644 				 *  (a)	The clean list was switched to the
   1645 				 *	free list by another CPU.
   1646 				 *
   1647 				 *  (b)	The clean list was added to by the
   1648 				 *	cleansing cyclic.
   1649 				 *
   1650 				 * In either of these situations, we can
   1651 				 * just reattempt the free list allocation.
   1652 				 */
   1653 				goto retry;
   1654 			}
   1655 
   1656 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
   1657 
   1658 			/*
   1659 			 * Now we'll move the clean list to the free list.
   1660 			 * It's impossible for this to fail:  the only way
   1661 			 * the free list can be updated is through this
   1662 			 * code path, and only one CPU can own the clean list.
   1663 			 * Thus, it would only be possible for this to fail if
   1664 			 * this code were racing with dtrace_dynvar_clean().
   1665 			 * (That is, if dtrace_dynvar_clean() updated the clean
   1666 			 * list, and we ended up racing to update the free
   1667 			 * list.)  This race is prevented by the dtrace_sync()
   1668 			 * in dtrace_dynvar_clean() -- which flushes the
   1669 			 * owners of the clean lists out before resetting
   1670 			 * the clean lists.
   1671 			 */
   1672 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
   1673 			ASSERT(rval == NULL);
   1674 			goto retry;
   1675 		}
   1676 
   1677 		dvar = free;
   1678 		new_free = dvar->dtdv_next;
   1679 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
   1680 
   1681 	/*
   1682 	 * We have now allocated a new chunk.  We copy the tuple keys into the
   1683 	 * tuple array and copy any referenced key data into the data space
   1684 	 * following the tuple array.  As we do this, we relocate dttk_value
   1685 	 * in the final tuple to point to the key data address in the chunk.
   1686 	 */
   1687 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
   1688 	dvar->dtdv_data = (void *)(kdata + ksize);
   1689 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
   1690 
   1691 	for (i = 0; i < nkeys; i++) {
   1692 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
   1693 		size_t kesize = key[i].dttk_size;
   1694 
   1695 		if (kesize != 0) {
   1696 			dtrace_bcopy(
   1697 			    (const void *)(uintptr_t)key[i].dttk_value,
   1698 			    (void *)kdata, kesize);
   1699 			dkey->dttk_value = kdata;
   1700 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
   1701 		} else {
   1702 			dkey->dttk_value = key[i].dttk_value;
   1703 		}
   1704 
   1705 		dkey->dttk_size = kesize;
   1706 	}
   1707 
   1708 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
   1709 	dvar->dtdv_hashval = hashval;
   1710 	dvar->dtdv_next = start;
   1711 
   1712 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
   1713 		return (dvar);
   1714 
   1715 	/*
   1716 	 * The cas has failed.  Either another CPU is adding an element to
   1717 	 * this hash chain, or another CPU is deleting an element from this
   1718 	 * hash chain.  The simplest way to deal with both of these cases
   1719 	 * (though not necessarily the most efficient) is to free our
   1720 	 * allocated block and tail-call ourselves.  Note that the free is
   1721 	 * to the dirty list and _not_ to the free list.  This is to prevent
   1722 	 * races with allocators, above.
   1723 	 */
   1724 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
   1725 
   1726 	dtrace_membar_producer();
   1727 
   1728 	do {
   1729 		free = dcpu->dtdsc_dirty;
   1730 		dvar->dtdv_next = free;
   1731 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
   1732 
   1733 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
   1734 }
   1735 
   1736 /*ARGSUSED*/
   1737 static void
   1738 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
   1739 {
   1740 	if ((int64_t)nval < (int64_t)*oval)
   1741 		*oval = nval;
   1742 }
   1743 
   1744 /*ARGSUSED*/
   1745 static void
   1746 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
   1747 {
   1748 	if ((int64_t)nval > (int64_t)*oval)
   1749 		*oval = nval;
   1750 }
   1751 
   1752 static void
   1753 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
   1754 {
   1755 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
   1756 	int64_t val = (int64_t)nval;
   1757 
   1758 	if (val < 0) {
   1759 		for (i = 0; i < zero; i++) {
   1760 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
   1761 				quanta[i] += incr;
   1762 				return;
   1763 			}
   1764 		}
   1765 	} else {
   1766 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
   1767 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
   1768 				quanta[i - 1] += incr;
   1769 				return;
   1770 			}
   1771 		}
   1772 
   1773 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
   1774 		return;
   1775 	}
   1776 
   1777 	ASSERT(0);
   1778 }
   1779 
   1780 static void
   1781 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
   1782 {
   1783 	uint64_t arg = *lquanta++;
   1784 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
   1785 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
   1786 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
   1787 	int32_t val = (int32_t)nval, level;
   1788 
   1789 	ASSERT(step != 0);
   1790 	ASSERT(levels != 0);
   1791 
   1792 	if (val < base) {
   1793 		/*
   1794 		 * This is an underflow.
   1795 		 */
   1796 		lquanta[0] += incr;
   1797 		return;
   1798 	}
   1799 
   1800 	level = (val - base) / step;
   1801 
   1802 	if (level < levels) {
   1803 		lquanta[level + 1] += incr;
   1804 		return;
   1805 	}
   1806 
   1807 	/*
   1808 	 * This is an overflow.
   1809 	 */
   1810 	lquanta[levels + 1] += incr;
   1811 }
   1812 
   1813 /*ARGSUSED*/
   1814 static void
   1815 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
   1816 {
   1817 	data[0]++;
   1818 	data[1] += nval;
   1819 }
   1820 
   1821 /*ARGSUSED*/
   1822 static void
   1823 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
   1824 {
   1825 	int64_t snval = (int64_t)nval;
   1826 	uint64_t tmp[2];
   1827 
   1828 	data[0]++;
   1829 	data[1] += nval;
   1830 
   1831 	/*
   1832 	 * What we want to say here is:
   1833 	 *
   1834 	 * data[2] += nval * nval;
   1835 	 *
   1836 	 * But given that nval is 64-bit, we could easily overflow, so
   1837 	 * we do this as 128-bit arithmetic.
   1838 	 */
   1839 	if (snval < 0)
   1840 		snval = -snval;
   1841 
   1842 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
   1843 	dtrace_add_128(data + 2, tmp, data + 2);
   1844 }
   1845 
   1846 /*ARGSUSED*/
   1847 static void
   1848 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
   1849 {
   1850 	*oval = *oval + 1;
   1851 }
   1852 
   1853 /*ARGSUSED*/
   1854 static void
   1855 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
   1856 {
   1857 	*oval += nval;
   1858 }
   1859 
   1860 /*
   1861  * Aggregate given the tuple in the principal data buffer, and the aggregating
   1862  * action denoted by the specified dtrace_aggregation_t.  The aggregation
   1863  * buffer is specified as the buf parameter.  This routine does not return
   1864  * failure; if there is no space in the aggregation buffer, the data will be
   1865  * dropped, and a corresponding counter incremented.
   1866  */
   1867 static void
   1868 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
   1869     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
   1870 {
   1871 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
   1872 	uint32_t i, ndx, size, fsize;
   1873 	uint32_t align = sizeof (uint64_t) - 1;
   1874 	dtrace_aggbuffer_t *agb;
   1875 	dtrace_aggkey_t *key;
   1876 	uint32_t hashval = 0, limit, isstr;
   1877 	caddr_t tomax, data, kdata;
   1878 	dtrace_actkind_t action;
   1879 	dtrace_action_t *act;
   1880 	uintptr_t offs;
   1881 
   1882 	if (buf == NULL)
   1883 		return;
   1884 
   1885 	if (!agg->dtag_hasarg) {
   1886 		/*
   1887 		 * Currently, only quantize() and lquantize() take additional
   1888 		 * arguments, and they have the same semantics:  an increment
   1889 		 * value that defaults to 1 when not present.  If additional
   1890 		 * aggregating actions take arguments, the setting of the
   1891 		 * default argument value will presumably have to become more
   1892 		 * sophisticated...
   1893 		 */
   1894 		arg = 1;
   1895 	}
   1896 
   1897 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
   1898 	size = rec->dtrd_offset - agg->dtag_base;
   1899 	fsize = size + rec->dtrd_size;
   1900 
   1901 	ASSERT(dbuf->dtb_tomax != NULL);
   1902 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
   1903 
   1904 	if ((tomax = buf->dtb_tomax) == NULL) {
   1905 		dtrace_buffer_drop(buf);
   1906 		return;
   1907 	}
   1908 
   1909 	/*
   1910 	 * The metastructure is always at the bottom of the buffer.
   1911 	 */
   1912 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
   1913 	    sizeof (dtrace_aggbuffer_t));
   1914 
   1915 	if (buf->dtb_offset == 0) {
   1916 		/*
   1917 		 * We just kludge up approximately 1/8th of the size to be
   1918 		 * buckets.  If this guess ends up being routinely
   1919 		 * off-the-mark, we may need to dynamically readjust this
   1920 		 * based on past performance.
   1921 		 */
   1922 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
   1923 
   1924 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
   1925 		    (uintptr_t)tomax || hashsize == 0) {
   1926 			/*
   1927 			 * We've been given a ludicrously small buffer;
   1928 			 * increment our drop count and leave.
   1929 			 */
   1930 			dtrace_buffer_drop(buf);
   1931 			return;
   1932 		}
   1933 
   1934 		/*
   1935 		 * And now, a pathetic attempt to try to get a an odd (or
   1936 		 * perchance, a prime) hash size for better hash distribution.
   1937 		 */
   1938 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
   1939 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
   1940 
   1941 		agb->dtagb_hashsize = hashsize;
   1942 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
   1943 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
   1944 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
   1945 
   1946 		for (i = 0; i < agb->dtagb_hashsize; i++)
   1947 			agb->dtagb_hash[i] = NULL;
   1948 	}
   1949 
   1950 	ASSERT(agg->dtag_first != NULL);
   1951 	ASSERT(agg->dtag_first->dta_intuple);
   1952 
   1953 	/*
   1954 	 * Calculate the hash value based on the key.  Note that we _don't_
   1955 	 * include the aggid in the hashing (but we will store it as part of
   1956 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
   1957 	 * algorithm: a simple, quick algorithm that has no known funnels, and
   1958 	 * gets good distribution in practice.  The efficacy of the hashing
   1959 	 * algorithm (and a comparison with other algorithms) may be found by
   1960 	 * running the ::dtrace_aggstat MDB dcmd.
   1961 	 */
   1962 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
   1963 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
   1964 		limit = i + act->dta_rec.dtrd_size;
   1965 		ASSERT(limit <= size);
   1966 		isstr = DTRACEACT_ISSTRING(act);
   1967 
   1968 		for (; i < limit; i++) {
   1969 			hashval += data[i];
   1970 			hashval += (hashval << 10);
   1971 			hashval ^= (hashval >> 6);
   1972 
   1973 			if (isstr && data[i] == '\0')
   1974 				break;
   1975 		}
   1976 	}
   1977 
   1978 	hashval += (hashval << 3);
   1979 	hashval ^= (hashval >> 11);
   1980 	hashval += (hashval << 15);
   1981 
   1982 	/*
   1983 	 * Yes, the divide here is expensive -- but it's generally the least
   1984 	 * of the performance issues given the amount of data that we iterate
   1985 	 * over to compute hash values, compare data, etc.
   1986 	 */
   1987 	ndx = hashval % agb->dtagb_hashsize;
   1988 
   1989 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
   1990 		ASSERT((caddr_t)key >= tomax);
   1991 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
   1992 
   1993 		if (hashval != key->dtak_hashval || key->dtak_size != size)
   1994 			continue;
   1995 
   1996 		kdata = key->dtak_data;
   1997 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
   1998 
   1999 		for (act = agg->dtag_first; act->dta_intuple;
   2000 		    act = act->dta_next) {
   2001 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
   2002 			limit = i + act->dta_rec.dtrd_size;
   2003 			ASSERT(limit <= size);
   2004 			isstr = DTRACEACT_ISSTRING(act);
   2005 
   2006 			for (; i < limit; i++) {
   2007 				if (kdata[i] != data[i])
   2008 					goto next;
   2009 
   2010 				if (isstr && data[i] == '\0')
   2011 					break;
   2012 			}
   2013 		}
   2014 
   2015 		if (action != key->dtak_action) {
   2016 			/*
   2017 			 * We are aggregating on the same value in the same
   2018 			 * aggregation with two different aggregating actions.
   2019 			 * (This should have been picked up in the compiler,
   2020 			 * so we may be dealing with errant or devious DIF.)
   2021 			 * This is an error condition; we indicate as much,
   2022 			 * and return.
   2023 			 */
   2024 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
   2025 			return;
   2026 		}
   2027 
   2028 		/*
   2029 		 * This is a hit:  we need to apply the aggregator to
   2030 		 * the value at this key.
   2031 		 */
   2032 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
   2033 		return;
   2034 next:
   2035 		continue;
   2036 	}
   2037 
   2038 	/*
   2039 	 * We didn't find it.  We need to allocate some zero-filled space,
   2040 	 * link it into the hash table appropriately, and apply the aggregator
   2041 	 * to the (zero-filled) value.
   2042 	 */
   2043 	offs = buf->dtb_offset;
   2044 	while (offs & (align - 1))
   2045 		offs += sizeof (uint32_t);
   2046 
   2047 	/*
   2048 	 * If we don't have enough room to both allocate a new key _and_
   2049 	 * its associated data, increment the drop count and return.
   2050 	 */
   2051 	if ((uintptr_t)tomax + offs + fsize >
   2052 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
   2053 		dtrace_buffer_drop(buf);
   2054 		return;
   2055 	}
   2056 
   2057 	/*CONSTCOND*/
   2058 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
   2059 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
   2060 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
   2061 
   2062 	key->dtak_data = kdata = tomax + offs;
   2063 	buf->dtb_offset = offs + fsize;
   2064 
   2065 	/*
   2066 	 * Now copy the data across.
   2067 	 */
   2068 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
   2069 
   2070 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
   2071 		kdata[i] = data[i];
   2072 
   2073 	/*
   2074 	 * Because strings are not zeroed out by default, we need to iterate
   2075 	 * looking for actions that store strings, and we need to explicitly
   2076 	 * pad these strings out with zeroes.
   2077 	 */
   2078 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
   2079 		int nul;
   2080 
   2081 		if (!DTRACEACT_ISSTRING(act))
   2082 			continue;
   2083 
   2084 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
   2085 		limit = i + act->dta_rec.dtrd_size;
   2086 		ASSERT(limit <= size);
   2087 
   2088 		for (nul = 0; i < limit; i++) {
   2089 			if (nul) {
   2090 				kdata[i] = '\0';
   2091 				continue;
   2092 			}
   2093 
   2094 			if (data[i] != '\0')
   2095 				continue;
   2096 
   2097 			nul = 1;
   2098 		}
   2099 	}
   2100 
   2101 	for (i = size; i < fsize; i++)
   2102 		kdata[i] = 0;
   2103 
   2104 	key->dtak_hashval = hashval;
   2105 	key->dtak_size = size;
   2106 	key->dtak_action = action;
   2107 	key->dtak_next = agb->dtagb_hash[ndx];
   2108 	agb->dtagb_hash[ndx] = key;
   2109 
   2110 	/*
   2111 	 * Finally, apply the aggregator.
   2112 	 */
   2113 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
   2114 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
   2115 }
   2116 
   2117 /*
   2118  * Given consumer state, this routine finds a speculation in the INACTIVE
   2119  * state and transitions it into the ACTIVE state.  If there is no speculation
   2120  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
   2121  * incremented -- it is up to the caller to take appropriate action.
   2122  */
   2123 static int
   2124 dtrace_speculation(dtrace_state_t *state)
   2125 {
   2126 	int i = 0;
   2127 	dtrace_speculation_state_t current;
   2128 	uint32_t *stat = &state->dts_speculations_unavail, count;
   2129 
   2130 	while (i < state->dts_nspeculations) {
   2131 		dtrace_speculation_t *spec = &state->dts_speculations[i];
   2132 
   2133 		current = spec->dtsp_state;
   2134 
   2135 		if (current != DTRACESPEC_INACTIVE) {
   2136 			if (current == DTRACESPEC_COMMITTINGMANY ||
   2137 			    current == DTRACESPEC_COMMITTING ||
   2138 			    current == DTRACESPEC_DISCARDING)
   2139 				stat = &state->dts_speculations_busy;
   2140 			i++;
   2141 			continue;
   2142 		}
   2143 
   2144 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
   2145 		    current, DTRACESPEC_ACTIVE) == current)
   2146 			return (i + 1);
   2147 	}
   2148 
   2149 	/*
   2150 	 * We couldn't find a speculation.  If we found as much as a single
   2151 	 * busy speculation buffer, we'll attribute this failure as "busy"
   2152 	 * instead of "unavail".
   2153 	 */
   2154 	do {
   2155 		count = *stat;
   2156 	} while (dtrace_cas32(stat, count, count + 1) != count);
   2157 
   2158 	return (0);
   2159 }
   2160 
   2161 /*
   2162  * This routine commits an active speculation.  If the specified speculation
   2163  * is not in a valid state to perform a commit(), this routine will silently do
   2164  * nothing.  The state of the specified speculation is transitioned according
   2165  * to the state transition diagram outlined in <sys/dtrace_impl.h>
   2166  */
   2167 static void
   2168 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
   2169     dtrace_specid_t which)
   2170 {
   2171 	dtrace_speculation_t *spec;
   2172 	dtrace_buffer_t *src, *dest;
   2173 	uintptr_t daddr, saddr, dlimit;
   2174 	dtrace_speculation_state_t current, new;
   2175 	intptr_t offs;
   2176 
   2177 	if (which == 0)
   2178 		return;
   2179 
   2180 	if (which > state->dts_nspeculations) {
   2181 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
   2182 		return;
   2183 	}
   2184 
   2185 	spec = &state->dts_speculations[which - 1];
   2186 	src = &spec->dtsp_buffer[cpu];
   2187 	dest = &state->dts_buffer[cpu];
   2188 
   2189 	do {
   2190 		current = spec->dtsp_state;
   2191 
   2192 		if (current == DTRACESPEC_COMMITTINGMANY)
   2193 			break;
   2194 
   2195 		switch (current) {
   2196 		case DTRACESPEC_INACTIVE:
   2197 		case DTRACESPEC_DISCARDING:
   2198 			return;
   2199 
   2200 		case DTRACESPEC_COMMITTING:
   2201 			/*
   2202 			 * This is only possible if we are (a) commit()'ing
   2203 			 * without having done a prior speculate() on this CPU
   2204 			 * and (b) racing with another commit() on a different
   2205 			 * CPU.  There's nothing to do -- we just assert that
   2206 			 * our offset is 0.
   2207 			 */
   2208 			ASSERT(src->dtb_offset == 0);
   2209 			return;
   2210 
   2211 		case DTRACESPEC_ACTIVE:
   2212 			new = DTRACESPEC_COMMITTING;
   2213 			break;
   2214 
   2215 		case DTRACESPEC_ACTIVEONE:
   2216 			/*
   2217 			 * This speculation is active on one CPU.  If our
   2218 			 * buffer offset is non-zero, we know that the one CPU
   2219 			 * must be us.  Otherwise, we are committing on a
   2220 			 * different CPU from the speculate(), and we must
   2221 			 * rely on being asynchronously cleaned.
   2222 			 */
   2223 			if (src->dtb_offset != 0) {
   2224 				new = DTRACESPEC_COMMITTING;
   2225 				break;
   2226 			}
   2227 			/*FALLTHROUGH*/
   2228 
   2229 		case DTRACESPEC_ACTIVEMANY:
   2230 			new = DTRACESPEC_COMMITTINGMANY;
   2231 			break;
   2232 
   2233 		default:
   2234 			ASSERT(0);
   2235 		}
   2236 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
   2237 	    current, new) != current);
   2238 
   2239 	/*
   2240 	 * We have set the state to indicate that we are committing this
   2241 	 * speculation.  Now reserve the necessary space in the destination
   2242 	 * buffer.
   2243 	 */
   2244 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
   2245 	    sizeof (uint64_t), state, NULL)) < 0) {
   2246 		dtrace_buffer_drop(dest);
   2247 		goto out;
   2248 	}
   2249 
   2250 	/*
   2251 	 * We have the space; copy the buffer across.  (Note that this is a
   2252 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
   2253 	 * a serious performance issue, a high-performance DTrace-specific
   2254 	 * bcopy() should obviously be invented.)
   2255 	 */
   2256 	daddr = (uintptr_t)dest->dtb_tomax + offs;
   2257 	dlimit = daddr + src->dtb_offset;
   2258 	saddr = (uintptr_t)src->dtb_tomax;
   2259 
   2260 	/*
   2261 	 * First, the aligned portion.
   2262 	 */
   2263 	while (dlimit - daddr >= sizeof (uint64_t)) {
   2264 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
   2265 
   2266 		daddr += sizeof (uint64_t);
   2267 		saddr += sizeof (uint64_t);
   2268 	}
   2269 
   2270 	/*
   2271 	 * Now any left-over bit...
   2272 	 */
   2273 	while (dlimit - daddr)
   2274 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
   2275 
   2276 	/*
   2277 	 * Finally, commit the reserved space in the destination buffer.
   2278 	 */
   2279 	dest->dtb_offset = offs + src->dtb_offset;
   2280 
   2281 out:
   2282 	/*
   2283 	 * If we're lucky enough to be the only active CPU on this speculation
   2284 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
   2285 	 */
   2286 	if (current == DTRACESPEC_ACTIVE ||
   2287 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
   2288 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
   2289 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
   2290 
   2291 		ASSERT(rval == DTRACESPEC_COMMITTING);
   2292 	}
   2293 
   2294 	src->dtb_offset = 0;
   2295 	src->dtb_xamot_drops += src->dtb_drops;
   2296 	src->dtb_drops = 0;
   2297 }
   2298 
   2299 /*
   2300  * This routine discards an active speculation.  If the specified speculation
   2301  * is not in a valid state to perform a discard(), this routine will silently
   2302  * do nothing.  The state of the specified speculation is transitioned
   2303  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
   2304  */
   2305 static void
   2306 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
   2307     dtrace_specid_t which)
   2308 {
   2309 	dtrace_speculation_t *spec;
   2310 	dtrace_speculation_state_t current, new;
   2311 	dtrace_buffer_t *buf;
   2312 
   2313 	if (which == 0)
   2314 		return;
   2315 
   2316 	if (which > state->dts_nspeculations) {
   2317 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
   2318 		return;
   2319 	}
   2320 
   2321 	spec = &state->dts_speculations[which - 1];
   2322 	buf = &spec->dtsp_buffer[cpu];
   2323 
   2324 	do {
   2325 		current = spec->dtsp_state;
   2326 
   2327 		switch (current) {
   2328 		case DTRACESPEC_INACTIVE:
   2329 		case DTRACESPEC_COMMITTINGMANY:
   2330 		case DTRACESPEC_COMMITTING:
   2331 		case DTRACESPEC_DISCARDING:
   2332 			return;
   2333 
   2334 		case DTRACESPEC_ACTIVE:
   2335 		case DTRACESPEC_ACTIVEMANY:
   2336 			new = DTRACESPEC_DISCARDING;
   2337 			break;
   2338 
   2339 		case DTRACESPEC_ACTIVEONE:
   2340 			if (buf->dtb_offset != 0) {
   2341 				new = DTRACESPEC_INACTIVE;
   2342 			} else {
   2343 				new = DTRACESPEC_DISCARDING;
   2344 			}
   2345 			break;
   2346 
   2347 		default:
   2348 			ASSERT(0);
   2349 		}
   2350 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
   2351 	    current, new) != current);
   2352 
   2353 	buf->dtb_offset = 0;
   2354 	buf->dtb_drops = 0;
   2355 }
   2356 
   2357 /*
   2358  * Note:  not called from probe context.  This function is called
   2359  * asynchronously from cross call context to clean any speculations that are
   2360  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
   2361  * transitioned back to the INACTIVE state until all CPUs have cleaned the
   2362  * speculation.
   2363  */
   2364 static void
   2365 dtrace_speculation_clean_here(dtrace_state_t *state)
   2366 {
   2367 	dtrace_icookie_t cookie;
   2368 	processorid_t cpu = CPU->cpu_id;
   2369 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
   2370 	dtrace_specid_t i;
   2371 
   2372 	cookie = dtrace_interrupt_disable();
   2373 
   2374 	if (dest->dtb_tomax == NULL) {
   2375 		dtrace_interrupt_enable(cookie);
   2376 		return;
   2377 	}
   2378 
   2379 	for (i = 0; i < state->dts_nspeculations; i++) {
   2380 		dtrace_speculation_t *spec = &state->dts_speculations[i];
   2381 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
   2382 
   2383 		if (src->dtb_tomax == NULL)
   2384 			continue;
   2385 
   2386 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
   2387 			src->dtb_offset = 0;
   2388 			continue;
   2389 		}
   2390 
   2391 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
   2392 			continue;
   2393 
   2394 		if (src->dtb_offset == 0)
   2395 			continue;
   2396 
   2397 		dtrace_speculation_commit(state, cpu, i + 1);
   2398 	}
   2399 
   2400 	dtrace_interrupt_enable(cookie);
   2401 }
   2402 
   2403 /*
   2404  * Note:  not called from probe context.  This function is called
   2405  * asynchronously (and at a regular interval) to clean any speculations that
   2406  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
   2407  * is work to be done, it cross calls all CPUs to perform that work;
   2408  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
   2409  * INACTIVE state until they have been cleaned by all CPUs.
   2410  */
   2411 static void
   2412 dtrace_speculation_clean(dtrace_state_t *state)
   2413 {
   2414 	int work = 0, rv;
   2415 	dtrace_specid_t i;
   2416 
   2417 	for (i = 0; i < state->dts_nspeculations; i++) {
   2418 		dtrace_speculation_t *spec = &state->dts_speculations[i];
   2419 
   2420 		ASSERT(!spec->dtsp_cleaning);
   2421 
   2422 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
   2423 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
   2424 			continue;
   2425 
   2426 		work++;
   2427 		spec->dtsp_cleaning = 1;
   2428 	}
   2429 
   2430 	if (!work)
   2431 		return;
   2432 
   2433 	dtrace_xcall(DTRACE_CPUALL,
   2434 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
   2435 
   2436 	/*
   2437 	 * We now know that all CPUs have committed or discarded their
   2438 	 * speculation buffers, as appropriate.  We can now set the state
   2439 	 * to inactive.
   2440 	 */
   2441 	for (i = 0; i < state->dts_nspeculations; i++) {
   2442 		dtrace_speculation_t *spec = &state->dts_speculations[i];
   2443 		dtrace_speculation_state_t current, new;
   2444 
   2445 		if (!spec->dtsp_cleaning)
   2446 			continue;
   2447 
   2448 		current = spec->dtsp_state;
   2449 		ASSERT(current == DTRACESPEC_DISCARDING ||
   2450 		    current == DTRACESPEC_COMMITTINGMANY);
   2451 
   2452 		new = DTRACESPEC_INACTIVE;
   2453 
   2454 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
   2455 		ASSERT(rv == current);
   2456 		spec->dtsp_cleaning = 0;
   2457 	}
   2458 }
   2459 
   2460 /*
   2461  * Called as part of a speculate() to get the speculative buffer associated
   2462  * with a given speculation.  Returns NULL if the specified speculation is not
   2463  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
   2464  * the active CPU is not the specified CPU -- the speculation will be
   2465  * atomically transitioned into the ACTIVEMANY state.
   2466  */
   2467 static dtrace_buffer_t *
   2468 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
   2469     dtrace_specid_t which)
   2470 {
   2471 	dtrace_speculation_t *spec;
   2472 	dtrace_speculation_state_t current, new;
   2473 	dtrace_buffer_t *buf;
   2474 
   2475 	if (which == 0)
   2476 		return (NULL);
   2477 
   2478 	if (which > state->dts_nspeculations) {
   2479 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
   2480 		return (NULL);
   2481 	}
   2482 
   2483 	spec = &state->dts_speculations[which - 1];
   2484 	buf = &spec->dtsp_buffer[cpuid];
   2485 
   2486 	do {
   2487 		current = spec->dtsp_state;
   2488 
   2489 		switch (current) {
   2490 		case DTRACESPEC_INACTIVE:
   2491 		case DTRACESPEC_COMMITTINGMANY:
   2492 		case DTRACESPEC_DISCARDING:
   2493 			return (NULL);
   2494 
   2495 		case DTRACESPEC_COMMITTING:
   2496 			ASSERT(buf->dtb_offset == 0);
   2497 			return (NULL);
   2498 
   2499 		case DTRACESPEC_ACTIVEONE:
   2500 			/*
   2501 			 * This speculation is currently active on one CPU.
   2502 			 * Check the offset in the buffer; if it's non-zero,
   2503 			 * that CPU must be us (and we leave the state alone).
   2504 			 * If it's zero, assume that we're starting on a new
   2505 			 * CPU -- and change the state to indicate that the
   2506 			 * speculation is active on more than one CPU.
   2507 			 */
   2508 			if (buf->dtb_offset != 0)
   2509 				return (buf);
   2510 
   2511 			new = DTRACESPEC_ACTIVEMANY;
   2512 			break;
   2513 
   2514 		case DTRACESPEC_ACTIVEMANY:
   2515 			return (buf);
   2516 
   2517 		case DTRACESPEC_ACTIVE:
   2518 			new = DTRACESPEC_ACTIVEONE;
   2519 			break;
   2520 
   2521 		default:
   2522 			ASSERT(0);
   2523 		}
   2524 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
   2525 	    current, new) != current);
   2526 
   2527 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
   2528 	return (buf);
   2529 }
   2530 
   2531 /*
   2532  * Return a string.  In the event that the user lacks the privilege to access
   2533  * arbitrary kernel memory, we copy the string out to scratch memory so that we
   2534  * don't fail access checking.
   2535  *
   2536  * dtrace_dif_variable() uses this routine as a helper for various
   2537  * builtin values such as 'execname' and 'probefunc.'
   2538  */
   2539 uintptr_t
   2540 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
   2541     dtrace_mstate_t *mstate)
   2542 {
   2543 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
   2544 	uintptr_t ret;
   2545 	size_t strsz;
   2546 
   2547 	/*
   2548 	 * The easy case: this probe is allowed to read all of memory, so
   2549 	 * we can just return this as a vanilla pointer.
   2550 	 */
   2551 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
   2552 		return (addr);
   2553 
   2554 	/*
   2555 	 * This is the tougher case: we copy the string in question from
   2556 	 * kernel memory into scratch memory and return it that way: this
   2557 	 * ensures that we won't trip up when access checking tests the
   2558 	 * BYREF return value.
   2559 	 */
   2560 	strsz = dtrace_strlen((char *)addr, size) + 1;
   2561 
   2562 	if (mstate->dtms_scratch_ptr + strsz >
   2563 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
   2564 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   2565 		return (NULL);
   2566 	}
   2567 
   2568 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
   2569 	    strsz);
   2570 	ret = mstate->dtms_scratch_ptr;
   2571 	mstate->dtms_scratch_ptr += strsz;
   2572 	return (ret);
   2573 }
   2574 
   2575 /*
   2576  * This function implements the DIF emulator's variable lookups.  The emulator
   2577  * passes a reserved variable identifier and optional built-in array index.
   2578  */
   2579 static uint64_t
   2580 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
   2581     uint64_t ndx)
   2582 {
   2583 	/*
   2584 	 * If we're accessing one of the uncached arguments, we'll turn this
   2585 	 * into a reference in the args array.
   2586 	 */
   2587 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
   2588 		ndx = v - DIF_VAR_ARG0;
   2589 		v = DIF_VAR_ARGS;
   2590 	}
   2591 
   2592 	switch (v) {
   2593 	case DIF_VAR_ARGS:
   2594 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
   2595 		if (ndx >= sizeof (mstate->dtms_arg) /
   2596 		    sizeof (mstate->dtms_arg[0])) {
   2597 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
   2598 			dtrace_provider_t *pv;
   2599 			uint64_t val;
   2600 
   2601 			pv = mstate->dtms_probe->dtpr_provider;
   2602 			if (pv->dtpv_pops.dtps_getargval != NULL)
   2603 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
   2604 				    mstate->dtms_probe->dtpr_id,
   2605 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
   2606 			else
   2607 				val = dtrace_getarg(ndx, aframes);
   2608 
   2609 			/*
   2610 			 * This is regrettably required to keep the compiler
   2611 			 * from tail-optimizing the call to dtrace_getarg().
   2612 			 * The condition always evaluates to true, but the
   2613 			 * compiler has no way of figuring that out a priori.
   2614 			 * (None of this would be necessary if the compiler
   2615 			 * could be relied upon to _always_ tail-optimize
   2616 			 * the call to dtrace_getarg() -- but it can't.)
   2617 			 */
   2618 			if (mstate->dtms_probe != NULL)
   2619 				return (val);
   2620 
   2621 			ASSERT(0);
   2622 		}
   2623 
   2624 		return (mstate->dtms_arg[ndx]);
   2625 
   2626 	case DIF_VAR_UREGS: {
   2627 		klwp_t *lwp;
   2628 
   2629 		if (!dtrace_priv_proc(state))
   2630 			return (0);
   2631 
   2632 		if ((lwp = curthread->t_lwp) == NULL) {
   2633 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
   2634 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
   2635 			return (0);
   2636 		}
   2637 
   2638 		return (dtrace_getreg(lwp->lwp_regs, ndx));
   2639 	}
   2640 
   2641 	case DIF_VAR_CURTHREAD:
   2642 		if (!dtrace_priv_kernel(state))
   2643 			return (0);
   2644 		return ((uint64_t)(uintptr_t)curthread);
   2645 
   2646 	case DIF_VAR_TIMESTAMP:
   2647 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
   2648 			mstate->dtms_timestamp = dtrace_gethrtime();
   2649 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
   2650 		}
   2651 		return (mstate->dtms_timestamp);
   2652 
   2653 	case DIF_VAR_VTIMESTAMP:
   2654 		ASSERT(dtrace_vtime_references != 0);
   2655 		return (curthread->t_dtrace_vtime);
   2656 
   2657 	case DIF_VAR_WALLTIMESTAMP:
   2658 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
   2659 			mstate->dtms_walltimestamp = dtrace_gethrestime();
   2660 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
   2661 		}
   2662 		return (mstate->dtms_walltimestamp);
   2663 
   2664 	case DIF_VAR_IPL:
   2665 		if (!dtrace_priv_kernel(state))
   2666 			return (0);
   2667 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
   2668 			mstate->dtms_ipl = dtrace_getipl();
   2669 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
   2670 		}
   2671 		return (mstate->dtms_ipl);
   2672 
   2673 	case DIF_VAR_EPID:
   2674 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
   2675 		return (mstate->dtms_epid);
   2676 
   2677 	case DIF_VAR_ID:
   2678 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
   2679 		return (mstate->dtms_probe->dtpr_id);
   2680 
   2681 	case DIF_VAR_STACKDEPTH:
   2682 		if (!dtrace_priv_kernel(state))
   2683 			return (0);
   2684 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
   2685 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
   2686 
   2687 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
   2688 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
   2689 		}
   2690 		return (mstate->dtms_stackdepth);
   2691 
   2692 	case DIF_VAR_USTACKDEPTH:
   2693 		if (!dtrace_priv_proc(state))
   2694 			return (0);
   2695 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
   2696 			/*
   2697 			 * See comment in DIF_VAR_PID.
   2698 			 */
   2699 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
   2700 			    CPU_ON_INTR(CPU)) {
   2701 				mstate->dtms_ustackdepth = 0;
   2702 			} else {
   2703 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
   2704 				mstate->dtms_ustackdepth =
   2705 				    dtrace_getustackdepth();
   2706 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
   2707 			}
   2708 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
   2709 		}
   2710 		return (mstate->dtms_ustackdepth);
   2711 
   2712 	case DIF_VAR_CALLER:
   2713 		if (!dtrace_priv_kernel(state))
   2714 			return (0);
   2715 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
   2716 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
   2717 
   2718 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
   2719 				/*
   2720 				 * If this is an unanchored probe, we are
   2721 				 * required to go through the slow path:
   2722 				 * dtrace_caller() only guarantees correct
   2723 				 * results for anchored probes.
   2724 				 */
   2725 				pc_t caller[2];
   2726 
   2727 				dtrace_getpcstack(caller, 2, aframes,
   2728 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
   2729 				mstate->dtms_caller = caller[1];
   2730 			} else if ((mstate->dtms_caller =
   2731 			    dtrace_caller(aframes)) == -1) {
   2732 				/*
   2733 				 * We have failed to do this the quick way;
   2734 				 * we must resort to the slower approach of
   2735 				 * calling dtrace_getpcstack().
   2736 				 */
   2737 				pc_t caller;
   2738 
   2739 				dtrace_getpcstack(&caller, 1, aframes, NULL);
   2740 				mstate->dtms_caller = caller;
   2741 			}
   2742 
   2743 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
   2744 		}
   2745 		return (mstate->dtms_caller);
   2746 
   2747 	case DIF_VAR_UCALLER:
   2748 		if (!dtrace_priv_proc(state))
   2749 			return (0);
   2750 
   2751 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
   2752 			uint64_t ustack[3];
   2753 
   2754 			/*
   2755 			 * dtrace_getupcstack() fills in the first uint64_t
   2756 			 * with the current PID.  The second uint64_t will
   2757 			 * be the program counter at user-level.  The third
   2758 			 * uint64_t will contain the caller, which is what
   2759 			 * we're after.
   2760 			 */
   2761 			ustack[2] = NULL;
   2762 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
   2763 			dtrace_getupcstack(ustack, 3);
   2764 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
   2765 			mstate->dtms_ucaller = ustack[2];
   2766 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
   2767 		}
   2768 
   2769 		return (mstate->dtms_ucaller);
   2770 
   2771 	case DIF_VAR_PROBEPROV:
   2772 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
   2773 		return (dtrace_dif_varstr(
   2774 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
   2775 		    state, mstate));
   2776 
   2777 	case DIF_VAR_PROBEMOD:
   2778 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
   2779 		return (dtrace_dif_varstr(
   2780 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
   2781 		    state, mstate));
   2782 
   2783 	case DIF_VAR_PROBEFUNC:
   2784 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
   2785 		return (dtrace_dif_varstr(
   2786 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
   2787 		    state, mstate));
   2788 
   2789 	case DIF_VAR_PROBENAME:
   2790 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
   2791 		return (dtrace_dif_varstr(
   2792 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
   2793 		    state, mstate));
   2794 
   2795 	case DIF_VAR_PID:
   2796 		if (!dtrace_priv_proc(state))
   2797 			return (0);
   2798 
   2799 		/*
   2800 		 * Note that we are assuming that an unanchored probe is
   2801 		 * always due to a high-level interrupt.  (And we're assuming
   2802 		 * that there is only a single high level interrupt.)
   2803 		 */
   2804 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
   2805 			return (pid0.pid_id);
   2806 
   2807 		/*
   2808 		 * It is always safe to dereference one's own t_procp pointer:
   2809 		 * it always points to a valid, allocated proc structure.
   2810 		 * Further, it is always safe to dereference the p_pidp member
   2811 		 * of one's own proc structure.  (These are truisms becuase
   2812 		 * threads and processes don't clean up their own state --
   2813 		 * they leave that task to whomever reaps them.)
   2814 		 */
   2815 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
   2816 
   2817 	case DIF_VAR_PPID:
   2818 		if (!dtrace_priv_proc(state))
   2819 			return (0);
   2820 
   2821 		/*
   2822 		 * See comment in DIF_VAR_PID.
   2823 		 */
   2824 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
   2825 			return (pid0.pid_id);
   2826 
   2827 		/*
   2828 		 * It is always safe to dereference one's own t_procp pointer:
   2829 		 * it always points to a valid, allocated proc structure.
   2830 		 * (This is true because threads don't clean up their own
   2831 		 * state -- they leave that task to whomever reaps them.)
   2832 		 */
   2833 		return ((uint64_t)curthread->t_procp->p_ppid);
   2834 
   2835 	case DIF_VAR_TID:
   2836 		/*
   2837 		 * See comment in DIF_VAR_PID.
   2838 		 */
   2839 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
   2840 			return (0);
   2841 
   2842 		return ((uint64_t)curthread->t_tid);
   2843 
   2844 	case DIF_VAR_EXECNAME:
   2845 		if (!dtrace_priv_proc(state))
   2846 			return (0);
   2847 
   2848 		/*
   2849 		 * See comment in DIF_VAR_PID.
   2850 		 */
   2851 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
   2852 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
   2853 
   2854 		/*
   2855 		 * It is always safe to dereference one's own t_procp pointer:
   2856 		 * it always points to a valid, allocated proc structure.
   2857 		 * (This is true because threads don't clean up their own
   2858 		 * state -- they leave that task to whomever reaps them.)
   2859 		 */
   2860 		return (dtrace_dif_varstr(
   2861 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
   2862 		    state, mstate));
   2863 
   2864 	case DIF_VAR_ZONENAME:
   2865 		if (!dtrace_priv_proc(state))
   2866 			return (0);
   2867 
   2868 		/*
   2869 		 * See comment in DIF_VAR_PID.
   2870 		 */
   2871 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
   2872 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
   2873 
   2874 		/*
   2875 		 * It is always safe to dereference one's own t_procp pointer:
   2876 		 * it always points to a valid, allocated proc structure.
   2877 		 * (This is true because threads don't clean up their own
   2878 		 * state -- they leave that task to whomever reaps them.)
   2879 		 */
   2880 		return (dtrace_dif_varstr(
   2881 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
   2882 		    state, mstate));
   2883 
   2884 	case DIF_VAR_UID:
   2885 		if (!dtrace_priv_proc(state))
   2886 			return (0);
   2887 
   2888 		/*
   2889 		 * See comment in DIF_VAR_PID.
   2890 		 */
   2891 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
   2892 			return ((uint64_t)p0.p_cred->cr_uid);
   2893 
   2894 		/*
   2895 		 * It is always safe to dereference one's own t_procp pointer:
   2896 		 * it always points to a valid, allocated proc structure.
   2897 		 * (This is true because threads don't clean up their own
   2898 		 * state -- they leave that task to whomever reaps them.)
   2899 		 *
   2900 		 * Additionally, it is safe to dereference one's own process
   2901 		 * credential, since this is never NULL after process birth.
   2902 		 */
   2903 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
   2904 
   2905 	case DIF_VAR_GID:
   2906 		if (!dtrace_priv_proc(state))
   2907 			return (0);
   2908 
   2909 		/*
   2910 		 * See comment in DIF_VAR_PID.
   2911 		 */
   2912 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
   2913 			return ((uint64_t)p0.p_cred->cr_gid);
   2914 
   2915 		/*
   2916 		 * It is always safe to dereference one's own t_procp pointer:
   2917 		 * it always points to a valid, allocated proc structure.
   2918 		 * (This is true because threads don't clean up their own
   2919 		 * state -- they leave that task to whomever reaps them.)
   2920 		 *
   2921 		 * Additionally, it is safe to dereference one's own process
   2922 		 * credential, since this is never NULL after process birth.
   2923 		 */
   2924 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
   2925 
   2926 	case DIF_VAR_ERRNO: {
   2927 		klwp_t *lwp;
   2928 		if (!dtrace_priv_proc(state))
   2929 			return (0);
   2930 
   2931 		/*
   2932 		 * See comment in DIF_VAR_PID.
   2933 		 */
   2934 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
   2935 			return (0);
   2936 
   2937 		/*
   2938 		 * It is always safe to dereference one's own t_lwp pointer in
   2939 		 * the event that this pointer is non-NULL.  (This is true
   2940 		 * because threads and lwps don't clean up their own state --
   2941 		 * they leave that task to whomever reaps them.)
   2942 		 */
   2943 		if ((lwp = curthread->t_lwp) == NULL)
   2944 			return (0);
   2945 
   2946 		return ((uint64_t)lwp->lwp_errno);
   2947 	}
   2948 	default:
   2949 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
   2950 		return (0);
   2951 	}
   2952 }
   2953 
   2954 /*
   2955  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
   2956  * Notice that we don't bother validating the proper number of arguments or
   2957  * their types in the tuple stack.  This isn't needed because all argument
   2958  * interpretation is safe because of our load safety -- the worst that can
   2959  * happen is that a bogus program can obtain bogus results.
   2960  */
   2961 static void
   2962 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
   2963     dtrace_key_t *tupregs, int nargs,
   2964     dtrace_mstate_t *mstate, dtrace_state_t *state)
   2965 {
   2966 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
   2967 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
   2968 	dtrace_vstate_t *vstate = &state->dts_vstate;
   2969 
   2970 	union {
   2971 		mutex_impl_t mi;
   2972 		uint64_t mx;
   2973 	} m;
   2974 
   2975 	union {
   2976 		krwlock_t ri;
   2977 		uintptr_t rw;
   2978 	} r;
   2979 
   2980 	switch (subr) {
   2981 	case DIF_SUBR_RAND:
   2982 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
   2983 		break;
   2984 
   2985 	case DIF_SUBR_MUTEX_OWNED:
   2986 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
   2987 		    mstate, vstate)) {
   2988 			regs[rd] = NULL;
   2989 			break;
   2990 		}
   2991 
   2992 		m.mx = dtrace_load64(tupregs[0].dttk_value);
   2993 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
   2994 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
   2995 		else
   2996 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
   2997 		break;
   2998 
   2999 	case DIF_SUBR_MUTEX_OWNER:
   3000 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
   3001 		    mstate, vstate)) {
   3002 			regs[rd] = NULL;
   3003 			break;
   3004 		}
   3005 
   3006 		m.mx = dtrace_load64(tupregs[0].dttk_value);
   3007 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
   3008 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
   3009 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
   3010 		else
   3011 			regs[rd] = 0;
   3012 		break;
   3013 
   3014 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
   3015 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
   3016 		    mstate, vstate)) {
   3017 			regs[rd] = NULL;
   3018 			break;
   3019 		}
   3020 
   3021 		m.mx = dtrace_load64(tupregs[0].dttk_value);
   3022 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
   3023 		break;
   3024 
   3025 	case DIF_SUBR_MUTEX_TYPE_SPIN:
   3026 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
   3027 		    mstate, vstate)) {
   3028 			regs[rd] = NULL;
   3029 			break;
   3030 		}
   3031 
   3032 		m.mx = dtrace_load64(tupregs[0].dttk_value);
   3033 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
   3034 		break;
   3035 
   3036 	case DIF_SUBR_RW_READ_HELD: {
   3037 		uintptr_t tmp;
   3038 
   3039 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
   3040 		    mstate, vstate)) {
   3041 			regs[rd] = NULL;
   3042 			break;
   3043 		}
   3044 
   3045 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
   3046 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
   3047 		break;
   3048 	}
   3049 
   3050 	case DIF_SUBR_RW_WRITE_HELD:
   3051 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
   3052 		    mstate, vstate)) {
   3053 			regs[rd] = NULL;
   3054 			break;
   3055 		}
   3056 
   3057 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
   3058 		regs[rd] = _RW_WRITE_HELD(&r.ri);
   3059 		break;
   3060 
   3061 	case DIF_SUBR_RW_ISWRITER:
   3062 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
   3063 		    mstate, vstate)) {
   3064 			regs[rd] = NULL;
   3065 			break;
   3066 		}
   3067 
   3068 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
   3069 		regs[rd] = _RW_ISWRITER(&r.ri);
   3070 		break;
   3071 
   3072 	case DIF_SUBR_BCOPY: {
   3073 		/*
   3074 		 * We need to be sure that the destination is in the scratch
   3075 		 * region -- no other region is allowed.
   3076 		 */
   3077 		uintptr_t src = tupregs[0].dttk_value;
   3078 		uintptr_t dest = tupregs[1].dttk_value;
   3079 		size_t size = tupregs[2].dttk_value;
   3080 
   3081 		if (!dtrace_inscratch(dest, size, mstate)) {
   3082 			*flags |= CPU_DTRACE_BADADDR;
   3083 			*illval = regs[rd];
   3084 			break;
   3085 		}
   3086 
   3087 		if (!dtrace_canload(src, size, mstate, vstate)) {
   3088 			regs[rd] = NULL;
   3089 			break;
   3090 		}
   3091 
   3092 		dtrace_bcopy((void *)src, (void *)dest, size);
   3093 		break;
   3094 	}
   3095 
   3096 	case DIF_SUBR_ALLOCA:
   3097 	case DIF_SUBR_COPYIN: {
   3098 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
   3099 		uint64_t size =
   3100 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
   3101 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
   3102 
   3103 		/*
   3104 		 * This action doesn't require any credential checks since
   3105 		 * probes will not activate in user contexts to which the
   3106 		 * enabling user does not have permissions.
   3107 		 */
   3108 
   3109 		/*
   3110 		 * Rounding up the user allocation size could have overflowed
   3111 		 * a large, bogus allocation (like -1ULL) to 0.
   3112 		 */
   3113 		if (scratch_size < size ||
   3114 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
   3115 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   3116 			regs[rd] = NULL;
   3117 			break;
   3118 		}
   3119 
   3120 		if (subr == DIF_SUBR_COPYIN) {
   3121 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
   3122 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
   3123 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
   3124 		}
   3125 
   3126 		mstate->dtms_scratch_ptr += scratch_size;
   3127 		regs[rd] = dest;
   3128 		break;
   3129 	}
   3130 
   3131 	case DIF_SUBR_COPYINTO: {
   3132 		uint64_t size = tupregs[1].dttk_value;
   3133 		uintptr_t dest = tupregs[2].dttk_value;
   3134 
   3135 		/*
   3136 		 * This action doesn't require any credential checks since
   3137 		 * probes will not activate in user contexts to which the
   3138 		 * enabling user does not have permissions.
   3139 		 */
   3140 		if (!dtrace_inscratch(dest, size, mstate)) {
   3141 			*flags |= CPU_DTRACE_BADADDR;
   3142 			*illval = regs[rd];
   3143 			break;
   3144 		}
   3145 
   3146 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
   3147 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
   3148 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
   3149 		break;
   3150 	}
   3151 
   3152 	case DIF_SUBR_COPYINSTR: {
   3153 		uintptr_t dest = mstate->dtms_scratch_ptr;
   3154 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
   3155 
   3156 		if (nargs > 1 && tupregs[1].dttk_value < size)
   3157 			size = tupregs[1].dttk_value + 1;
   3158 
   3159 		/*
   3160 		 * This action doesn't require any credential checks since
   3161 		 * probes will not activate in user contexts to which the
   3162 		 * enabling user does not have permissions.
   3163 		 */
   3164 		if (!DTRACE_INSCRATCH(mstate, size)) {
   3165 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   3166 			regs[rd] = NULL;
   3167 			break;
   3168 		}
   3169 
   3170 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
   3171 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
   3172 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
   3173 
   3174 		((char *)dest)[size - 1] = '\0';
   3175 		mstate->dtms_scratch_ptr += size;
   3176 		regs[rd] = dest;
   3177 		break;
   3178 	}
   3179 
   3180 	case DIF_SUBR_MSGSIZE:
   3181 	case DIF_SUBR_MSGDSIZE: {
   3182 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
   3183 		uintptr_t wptr, rptr;
   3184 		size_t count = 0;
   3185 		int cont = 0;
   3186 
   3187 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
   3188 
   3189 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
   3190 			    vstate)) {
   3191 				regs[rd] = NULL;
   3192 				break;
   3193 			}
   3194 
   3195 			wptr = dtrace_loadptr(baddr +
   3196 			    offsetof(mblk_t, b_wptr));
   3197 
   3198 			rptr = dtrace_loadptr(baddr +
   3199 			    offsetof(mblk_t, b_rptr));
   3200 
   3201 			if (wptr < rptr) {
   3202 				*flags |= CPU_DTRACE_BADADDR;
   3203 				*illval = tupregs[0].dttk_value;
   3204 				break;
   3205 			}
   3206 
   3207 			daddr = dtrace_loadptr(baddr +
   3208 			    offsetof(mblk_t, b_datap));
   3209 
   3210 			baddr = dtrace_loadptr(baddr +
   3211 			    offsetof(mblk_t, b_cont));
   3212 
   3213 			/*
   3214 			 * We want to prevent against denial-of-service here,
   3215 			 * so we're only going to search the list for
   3216 			 * dtrace_msgdsize_max mblks.
   3217 			 */
   3218 			if (cont++ > dtrace_msgdsize_max) {
   3219 				*flags |= CPU_DTRACE_ILLOP;
   3220 				break;
   3221 			}
   3222 
   3223 			if (subr == DIF_SUBR_MSGDSIZE) {
   3224 				if (dtrace_load8(daddr +
   3225 				    offsetof(dblk_t, db_type)) != M_DATA)
   3226 					continue;
   3227 			}
   3228 
   3229 			count += wptr - rptr;
   3230 		}
   3231 
   3232 		if (!(*flags & CPU_DTRACE_FAULT))
   3233 			regs[rd] = count;
   3234 
   3235 		break;
   3236 	}
   3237 
   3238 	case DIF_SUBR_PROGENYOF: {
   3239 		pid_t pid = tupregs[0].dttk_value;
   3240 		proc_t *p;
   3241 		int rval = 0;
   3242 
   3243 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
   3244 
   3245 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
   3246 			if (p->p_pidp->pid_id == pid) {
   3247 				rval = 1;
   3248 				break;
   3249 			}
   3250 		}
   3251 
   3252 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
   3253 
   3254 		regs[rd] = rval;
   3255 		break;
   3256 	}
   3257 
   3258 	case DIF_SUBR_SPECULATION:
   3259 		regs[rd] = dtrace_speculation(state);
   3260 		break;
   3261 
   3262 	case DIF_SUBR_COPYOUT: {
   3263 		uintptr_t kaddr = tupregs[0].dttk_value;
   3264 		uintptr_t uaddr = tupregs[1].dttk_value;
   3265 		uint64_t size = tupregs[2].dttk_value;
   3266 
   3267 		if (!dtrace_destructive_disallow &&
   3268 		    dtrace_priv_proc_control(state) &&
   3269 		    !dtrace_istoxic(kaddr, size)) {
   3270 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
   3271 			dtrace_copyout(kaddr, uaddr, size, flags);
   3272 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
   3273 		}
   3274 		break;
   3275 	}
   3276 
   3277 	case DIF_SUBR_COPYOUTSTR: {
   3278 		uintptr_t kaddr = tupregs[0].dttk_value;
   3279 		uintptr_t uaddr = tupregs[1].dttk_value;
   3280 		uint64_t size = tupregs[2].dttk_value;
   3281 
   3282 		if (!dtrace_destructive_disallow &&
   3283 		    dtrace_priv_proc_control(state) &&
   3284 		    !dtrace_istoxic(kaddr, size)) {
   3285 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
   3286 			dtrace_copyoutstr(kaddr, uaddr, size, flags);
   3287 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
   3288 		}
   3289 		break;
   3290 	}
   3291 
   3292 	case DIF_SUBR_STRLEN: {
   3293 		size_t sz;
   3294 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
   3295 		sz = dtrace_strlen((char *)addr,
   3296 		    state->dts_options[DTRACEOPT_STRSIZE]);
   3297 
   3298 		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
   3299 			regs[rd] = NULL;
   3300 			break;
   3301 		}
   3302 
   3303 		regs[rd] = sz;
   3304 
   3305 		break;
   3306 	}
   3307 
   3308 	case DIF_SUBR_STRCHR:
   3309 	case DIF_SUBR_STRRCHR: {
   3310 		/*
   3311 		 * We're going to iterate over the string looking for the
   3312 		 * specified character.  We will iterate until we have reached
   3313 		 * the string length or we have found the character.  If this
   3314 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
   3315 		 * of the specified character instead of the first.
   3316 		 */
   3317 		uintptr_t saddr = tupregs[0].dttk_value;
   3318 		uintptr_t addr = tupregs[0].dttk_value;
   3319 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
   3320 		char c, target = (char)tupregs[1].dttk_value;
   3321 
   3322 		for (regs[rd] = NULL; addr < limit; addr++) {
   3323 			if ((c = dtrace_load8(addr)) == target) {
   3324 				regs[rd] = addr;
   3325 
   3326 				if (subr == DIF_SUBR_STRCHR)
   3327 					break;
   3328 			}
   3329 
   3330 			if (c == '\0')
   3331 				break;
   3332 		}
   3333 
   3334 		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
   3335 			regs[rd] = NULL;
   3336 			break;
   3337 		}
   3338 
   3339 		break;
   3340 	}
   3341 
   3342 	case DIF_SUBR_STRSTR:
   3343 	case DIF_SUBR_INDEX:
   3344 	case DIF_SUBR_RINDEX: {
   3345 		/*
   3346 		 * We're going to iterate over the string looking for the
   3347 		 * specified string.  We will iterate until we have reached
   3348 		 * the string length or we have found the string.  (Yes, this
   3349 		 * is done in the most naive way possible -- but considering
   3350 		 * that the string we're searching for is likely to be
   3351 		 * relatively short, the complexity of Rabin-Karp or similar
   3352 		 * hardly seems merited.)
   3353 		 */
   3354 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
   3355 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
   3356 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
   3357 		size_t len = dtrace_strlen(addr, size);
   3358 		size_t sublen = dtrace_strlen(substr, size);
   3359 		char *limit = addr + len, *orig = addr;
   3360 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
   3361 		int inc = 1;
   3362 
   3363 		regs[rd] = notfound;
   3364 
   3365 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
   3366 			regs[rd] = NULL;
   3367 			break;
   3368 		}
   3369 
   3370 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
   3371 		    vstate)) {
   3372 			regs[rd] = NULL;
   3373 			break;
   3374 		}
   3375 
   3376 		/*
   3377 		 * strstr() and index()/rindex() have similar semantics if
   3378 		 * both strings are the empty string: strstr() returns a
   3379 		 * pointer to the (empty) string, and index() and rindex()
   3380 		 * both return index 0 (regardless of any position argument).
   3381 		 */
   3382 		if (sublen == 0 && len == 0) {
   3383 			if (subr == DIF_SUBR_STRSTR)
   3384 				regs[rd] = (uintptr_t)addr;
   3385 			else
   3386 				regs[rd] = 0;
   3387 			break;
   3388 		}
   3389 
   3390 		if (subr != DIF_SUBR_STRSTR) {
   3391 			if (subr == DIF_SUBR_RINDEX) {
   3392 				limit = orig - 1;
   3393 				addr += len;
   3394 				inc = -1;
   3395 			}
   3396 
   3397 			/*
   3398 			 * Both index() and rindex() take an optional position
   3399 			 * argument that denotes the starting position.
   3400 			 */
   3401 			if (nargs == 3) {
   3402 				int64_t pos = (int64_t)tupregs[2].dttk_value;
   3403 
   3404 				/*
   3405 				 * If the position argument to index() is
   3406 				 * negative, Perl implicitly clamps it at
   3407 				 * zero.  This semantic is a little surprising
   3408 				 * given the special meaning of negative
   3409 				 * positions to similar Perl functions like
   3410 				 * substr(), but it appears to reflect a
   3411 				 * notion that index() can start from a
   3412 				 * negative index and increment its way up to
   3413 				 * the string.  Given this notion, Perl's
   3414 				 * rindex() is at least self-consistent in
   3415 				 * that it implicitly clamps positions greater
   3416 				 * than the string length to be the string
   3417 				 * length.  Where Perl completely loses
   3418 				 * coherence, however, is when the specified
   3419 				 * substring is the empty string ("").  In
   3420 				 * this case, even if the position is
   3421 				 * negative, rindex() returns 0 -- and even if
   3422 				 * the position is greater than the length,
   3423 				 * index() returns the string length.  These
   3424 				 * semantics violate the notion that index()
   3425 				 * should never return a value less than the
   3426 				 * specified position and that rindex() should
   3427 				 * never return a value greater than the
   3428 				 * specified position.  (One assumes that
   3429 				 * these semantics are artifacts of Perl's
   3430 				 * implementation and not the results of
   3431 				 * deliberate design -- it beggars belief that
   3432 				 * even Larry Wall could desire such oddness.)
   3433 				 * While in the abstract one would wish for
   3434 				 * consistent position semantics across
   3435 				 * substr(), index() and rindex() -- or at the
   3436 				 * very least self-consistent position
   3437 				 * semantics for index() and rindex() -- we
   3438 				 * instead opt to keep with the extant Perl
   3439 				 * semantics, in all their broken glory.  (Do
   3440 				 * we have more desire to maintain Perl's
   3441 				 * semantics than Perl does?  Probably.)
   3442 				 */
   3443 				if (subr == DIF_SUBR_RINDEX) {
   3444 					if (pos < 0) {
   3445 						if (sublen == 0)
   3446 							regs[rd] = 0;
   3447 						break;
   3448 					}
   3449 
   3450 					if (pos > len)
   3451 						pos = len;
   3452 				} else {
   3453 					if (pos < 0)
   3454 						pos = 0;
   3455 
   3456 					if (pos >= len) {
   3457 						if (sublen == 0)
   3458 							regs[rd] = len;
   3459 						break;
   3460 					}
   3461 				}
   3462 
   3463 				addr = orig + pos;
   3464 			}
   3465 		}
   3466 
   3467 		for (regs[rd] = notfound; addr != limit; addr += inc) {
   3468 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
   3469 				if (subr != DIF_SUBR_STRSTR) {
   3470 					/*
   3471 					 * As D index() and rindex() are
   3472 					 * modeled on Perl (and not on awk),
   3473 					 * we return a zero-based (and not a
   3474 					 * one-based) index.  (For you Perl
   3475 					 * weenies: no, we're not going to add
   3476 					 * $[ -- and shouldn't you be at a con
   3477 					 * or something?)
   3478 					 */
   3479 					regs[rd] = (uintptr_t)(addr - orig);
   3480 					break;
   3481 				}
   3482 
   3483 				ASSERT(subr == DIF_SUBR_STRSTR);
   3484 				regs[rd] = (uintptr_t)addr;
   3485 				break;
   3486 			}
   3487 		}
   3488 
   3489 		break;
   3490 	}
   3491 
   3492 	case DIF_SUBR_STRTOK: {
   3493 		uintptr_t addr = tupregs[0].dttk_value;
   3494 		uintptr_t tokaddr = tupregs[1].dttk_value;
   3495 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
   3496 		uintptr_t limit, toklimit = tokaddr + size;
   3497 		uint8_t c, tokmap[32];	 /* 256 / 8 */
   3498 		char *dest = (char *)mstate->dtms_scratch_ptr;
   3499 		int i;
   3500 
   3501 		/*
   3502 		 * Check both the token buffer and (later) the input buffer,
   3503 		 * since both could be non-scratch addresses.
   3504 		 */
   3505 		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
   3506 			regs[rd] = NULL;
   3507 			break;
   3508 		}
   3509 
   3510 		if (!DTRACE_INSCRATCH(mstate, size)) {
   3511 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   3512 			regs[rd] = NULL;
   3513 			break;
   3514 		}
   3515 
   3516 		if (addr == NULL) {
   3517 			/*
   3518 			 * If the address specified is NULL, we use our saved
   3519 			 * strtok pointer from the mstate.  Note that this
   3520 			 * means that the saved strtok pointer is _only_
   3521 			 * valid within multiple enablings of the same probe --
   3522 			 * it behaves like an implicit clause-local variable.
   3523 			 */
   3524 			addr = mstate->dtms_strtok;
   3525 		} else {
   3526 			/*
   3527 			 * If the user-specified address is non-NULL we must
   3528 			 * access check it.  This is the only time we have
   3529 			 * a chance to do so, since this address may reside
   3530 			 * in the string table of this clause-- future calls
   3531 			 * (when we fetch addr from mstate->dtms_strtok)
   3532 			 * would fail this access check.
   3533 			 */
   3534 			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
   3535 				regs[rd] = NULL;
   3536 				break;
   3537 			}
   3538 		}
   3539 
   3540 		/*
   3541 		 * First, zero the token map, and then process the token
   3542 		 * string -- setting a bit in the map for every character
   3543 		 * found in the token string.
   3544 		 */
   3545 		for (i = 0; i < sizeof (tokmap); i++)
   3546 			tokmap[i] = 0;
   3547 
   3548 		for (; tokaddr < toklimit; tokaddr++) {
   3549 			if ((c = dtrace_load8(tokaddr)) == '\0')
   3550 				break;
   3551 
   3552 			ASSERT((c >> 3) < sizeof (tokmap));
   3553 			tokmap[c >> 3] |= (1 << (c & 0x7));
   3554 		}
   3555 
   3556 		for (limit = addr + size; addr < limit; addr++) {
   3557 			/*
   3558 			 * We're looking for a character that is _not_ contained
   3559 			 * in the token string.
   3560 			 */
   3561 			if ((c = dtrace_load8(addr)) == '\0')
   3562 				break;
   3563 
   3564 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
   3565 				break;
   3566 		}
   3567 
   3568 		if (c == '\0') {
   3569 			/*
   3570 			 * We reached the end of the string without finding
   3571 			 * any character that was not in the token string.
   3572 			 * We return NULL in this case, and we set the saved
   3573 			 * address to NULL as well.
   3574 			 */
   3575 			regs[rd] = NULL;
   3576 			mstate->dtms_strtok = NULL;
   3577 			break;
   3578 		}
   3579 
   3580 		/*
   3581 		 * From here on, we're copying into the destination string.
   3582 		 */
   3583 		for (i = 0; addr < limit && i < size - 1; addr++) {
   3584 			if ((c = dtrace_load8(addr)) == '\0')
   3585 				break;
   3586 
   3587 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
   3588 				break;
   3589 
   3590 			ASSERT(i < size);
   3591 			dest[i++] = c;
   3592 		}
   3593 
   3594 		ASSERT(i < size);
   3595 		dest[i] = '\0';
   3596 		regs[rd] = (uintptr_t)dest;
   3597 		mstate->dtms_scratch_ptr += size;
   3598 		mstate->dtms_strtok = addr;
   3599 		break;
   3600 	}
   3601 
   3602 	case DIF_SUBR_SUBSTR: {
   3603 		uintptr_t s = tupregs[0].dttk_value;
   3604 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
   3605 		char *d = (char *)mstate->dtms_scratch_ptr;
   3606 		int64_t index = (int64_t)tupregs[1].dttk_value;
   3607 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
   3608 		size_t len = dtrace_strlen((char *)s, size);
   3609 		int64_t i = 0;
   3610 
   3611 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
   3612 			regs[rd] = NULL;
   3613 			break;
   3614 		}
   3615 
   3616 		if (!DTRACE_INSCRATCH(mstate, size)) {
   3617 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   3618 			regs[rd] = NULL;
   3619 			break;
   3620 		}
   3621 
   3622 		if (nargs <= 2)
   3623 			remaining = (int64_t)size;
   3624 
   3625 		if (index < 0) {
   3626 			index += len;
   3627 
   3628 			if (index < 0 && index + remaining > 0) {
   3629 				remaining += index;
   3630 				index = 0;
   3631 			}
   3632 		}
   3633 
   3634 		if (index >= len || index < 0) {
   3635 			remaining = 0;
   3636 		} else if (remaining < 0) {
   3637 			remaining += len - index;
   3638 		} else if (index + remaining > size) {
   3639 			remaining = size - index;
   3640 		}
   3641 
   3642 		for (i = 0; i < remaining; i++) {
   3643 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
   3644 				break;
   3645 		}
   3646 
   3647 		d[i] = '\0';
   3648 
   3649 		mstate->dtms_scratch_ptr += size;
   3650 		regs[rd] = (uintptr_t)d;
   3651 		break;
   3652 	}
   3653 
   3654 	case DIF_SUBR_GETMAJOR:
   3655 #ifdef _LP64
   3656 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
   3657 #else
   3658 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
   3659 #endif
   3660 		break;
   3661 
   3662 	case DIF_SUBR_GETMINOR:
   3663 #ifdef _LP64
   3664 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
   3665 #else
   3666 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
   3667 #endif
   3668 		break;
   3669 
   3670 	case DIF_SUBR_DDI_PATHNAME: {
   3671 		/*
   3672 		 * This one is a galactic mess.  We are going to roughly
   3673 		 * emulate ddi_pathname(), but it's made more complicated
   3674 		 * by the fact that we (a) want to include the minor name and
   3675 		 * (b) must proceed iteratively instead of recursively.
   3676 		 */
   3677 		uintptr_t dest = mstate->dtms_scratch_ptr;
   3678 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
   3679 		char *start = (char *)dest, *end = start + size - 1;
   3680 		uintptr_t daddr = tupregs[0].dttk_value;
   3681 		int64_t minor = (int64_t)tupregs[1].dttk_value;
   3682 		char *s;
   3683 		int i, len, depth = 0;
   3684 
   3685 		/*
   3686 		 * Due to all the pointer jumping we do and context we must
   3687 		 * rely upon, we just mandate that the user must have kernel
   3688 		 * read privileges to use this routine.
   3689 		 */
   3690 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
   3691 			*flags |= CPU_DTRACE_KPRIV;
   3692 			*illval = daddr;
   3693 			regs[rd] = NULL;
   3694 		}
   3695 
   3696 		if (!DTRACE_INSCRATCH(mstate, size)) {
   3697 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   3698 			regs[rd] = NULL;
   3699 			break;
   3700 		}
   3701 
   3702 		*end = '\0';
   3703 
   3704 		/*
   3705 		 * We want to have a name for the minor.  In order to do this,
   3706 		 * we need to walk the minor list from the devinfo.  We want
   3707 		 * to be sure that we don't infinitely walk a circular list,
   3708 		 * so we check for circularity by sending a scout pointer
   3709 		 * ahead two elements for every element that we iterate over;
   3710 		 * if the list is circular, these will ultimately point to the
   3711 		 * same element.  You may recognize this little trick as the
   3712 		 * answer to a stupid interview question -- one that always
   3713 		 * seems to be asked by those who had to have it laboriously
   3714 		 * explained to them, and who can't even concisely describe
   3715 		 * the conditions under which one would be forced to resort to
   3716 		 * this technique.  Needless to say, those conditions are
   3717 		 * found here -- and probably only here.  Is this the only use
   3718 		 * of this infamous trick in shipping, production code?  If it
   3719 		 * isn't, it probably should be...
   3720 		 */
   3721 		if (minor != -1) {
   3722 			uintptr_t maddr = dtrace_loadptr(daddr +
   3723 			    offsetof(struct dev_info, devi_minor));
   3724 
   3725 			uintptr_t next = offsetof(struct ddi_minor_data, next);
   3726 			uintptr_t name = offsetof(struct ddi_minor_data,
   3727 			    d_minor) + offsetof(struct ddi_minor, name);
   3728 			uintptr_t dev = offsetof(struct ddi_minor_data,
   3729 			    d_minor) + offsetof(struct ddi_minor, dev);
   3730 			uintptr_t scout;
   3731 
   3732 			if (maddr != NULL)
   3733 				scout = dtrace_loadptr(maddr + next);
   3734 
   3735 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
   3736 				uint64_t m;
   3737 #ifdef _LP64
   3738 				m = dtrace_load64(maddr + dev) & MAXMIN64;
   3739 #else
   3740 				m = dtrace_load32(maddr + dev) & MAXMIN;
   3741 #endif
   3742 				if (m != minor) {
   3743 					maddr = dtrace_loadptr(maddr + next);
   3744 
   3745 					if (scout == NULL)
   3746 						continue;
   3747 
   3748 					scout = dtrace_loadptr(scout + next);
   3749 
   3750 					if (scout == NULL)
   3751 						continue;
   3752 
   3753 					scout = dtrace_loadptr(scout + next);
   3754 
   3755 					if (scout == NULL)
   3756 						continue;
   3757 
   3758 					if (scout == maddr) {
   3759 						*flags |= CPU_DTRACE_ILLOP;
   3760 						break;
   3761 					}
   3762 
   3763 					continue;
   3764 				}
   3765 
   3766 				/*
   3767 				 * We have the minor data.  Now we need to
   3768 				 * copy the minor's name into the end of the
   3769 				 * pathname.
   3770 				 */
   3771 				s = (char *)dtrace_loadptr(maddr + name);
   3772 				len = dtrace_strlen(s, size);
   3773 
   3774 				if (*flags & CPU_DTRACE_FAULT)
   3775 					break;
   3776 
   3777 				if (len != 0) {
   3778 					if ((end -= (len + 1)) < start)
   3779 						break;
   3780 
   3781 					*end = ':';
   3782 				}
   3783 
   3784 				for (i = 1; i <= len; i++)
   3785 					end[i] = dtrace_load8((uintptr_t)s++);
   3786 				break;
   3787 			}
   3788 		}
   3789 
   3790 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
   3791 			ddi_node_state_t devi_state;
   3792 
   3793 			devi_state = dtrace_load32(daddr +
   3794 			    offsetof(struct dev_info, devi_node_state));
   3795 
   3796 			if (*flags & CPU_DTRACE_FAULT)
   3797 				break;
   3798 
   3799 			if (devi_state >= DS_INITIALIZED) {
   3800 				s = (char *)dtrace_loadptr(daddr +
   3801 				    offsetof(struct dev_info, devi_addr));
   3802 				len = dtrace_strlen(s, size);
   3803 
   3804 				if (*flags & CPU_DTRACE_FAULT)
   3805 					break;
   3806 
   3807 				if (len != 0) {
   3808 					if ((end -= (len + 1)) < start)
   3809 						break;
   3810 
   3811 					*end = '@';
   3812 				}
   3813 
   3814 				for (i = 1; i <= len; i++)
   3815 					end[i] = dtrace_load8((uintptr_t)s++);
   3816 			}
   3817 
   3818 			/*
   3819 			 * Now for the node name...
   3820 			 */
   3821 			s = (char *)dtrace_loadptr(daddr +
   3822 			    offsetof(struct dev_info, devi_node_name));
   3823 
   3824 			daddr = dtrace_loadptr(daddr +
   3825 			    offsetof(struct dev_info, devi_parent));
   3826 
   3827 			/*
   3828 			 * If our parent is NULL (that is, if we're the root
   3829 			 * node), we're going to use the special path
   3830 			 * "devices".
   3831 			 */
   3832 			if (daddr == NULL)
   3833 				s = "devices";
   3834 
   3835 			len = dtrace_strlen(s, size);
   3836 			if (*flags & CPU_DTRACE_FAULT)
   3837 				break;
   3838 
   3839 			if ((end -= (len + 1)) < start)
   3840 				break;
   3841 
   3842 			for (i = 1; i <= len; i++)
   3843 				end[i] = dtrace_load8((uintptr_t)s++);
   3844 			*end = '/';
   3845 
   3846 			if (depth++ > dtrace_devdepth_max) {
   3847 				*flags |= CPU_DTRACE_ILLOP;
   3848 				break;
   3849 			}
   3850 		}
   3851 
   3852 		if (end < start)
   3853 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   3854 
   3855 		if (daddr == NULL) {
   3856 			regs[rd] = (uintptr_t)end;
   3857 			mstate->dtms_scratch_ptr += size;
   3858 		}
   3859 
   3860 		break;
   3861 	}
   3862 
   3863 	case DIF_SUBR_STRJOIN: {
   3864 		char *d = (char *)mstate->dtms_scratch_ptr;
   3865 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
   3866 		uintptr_t s1 = tupregs[0].dttk_value;
   3867 		uintptr_t s2 = tupregs[1].dttk_value;
   3868 		int i = 0;
   3869 
   3870 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
   3871 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
   3872 			regs[rd] = NULL;
   3873 			break;
   3874 		}
   3875 
   3876 		if (!DTRACE_INSCRATCH(mstate, size)) {
   3877 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   3878 			regs[rd] = NULL;
   3879 			break;
   3880 		}
   3881 
   3882 		for (;;) {
   3883 			if (i >= size) {
   3884 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   3885 				regs[rd] = NULL;
   3886 				break;
   3887 			}
   3888 
   3889 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
   3890 				i--;
   3891 				break;
   3892 			}
   3893 		}
   3894 
   3895 		for (;;) {
   3896 			if (i >= size) {
   3897 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   3898 				regs[rd] = NULL;
   3899 				break;
   3900 			}
   3901 
   3902 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
   3903 				break;
   3904 		}
   3905 
   3906 		if (i < size) {
   3907 			mstate->dtms_scratch_ptr += i;
   3908 			regs[rd] = (uintptr_t)d;
   3909 		}
   3910 
   3911 		break;
   3912 	}
   3913 
   3914 	case DIF_SUBR_LLTOSTR: {
   3915 		int64_t i = (int64_t)tupregs[0].dttk_value;
   3916 		int64_t val = i < 0 ? i * -1 : i;
   3917 		uint64_t size = 22;	/* enough room for 2^64 in decimal */
   3918 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
   3919 
   3920 		if (!DTRACE_INSCRATCH(mstate, size)) {
   3921 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   3922 			regs[rd] = NULL;
   3923 			break;
   3924 		}
   3925 
   3926 		for (*end-- = '\0'; val; val /= 10)
   3927 			*end-- = '0' + (val % 10);
   3928 
   3929 		if (i == 0)
   3930 			*end-- = '0';
   3931 
   3932 		if (i < 0)
   3933 			*end-- = '-';
   3934 
   3935 		regs[rd] = (uintptr_t)end + 1;
   3936 		mstate->dtms_scratch_ptr += size;
   3937 		break;
   3938 	}
   3939 
   3940 	case DIF_SUBR_HTONS:
   3941 	case DIF_SUBR_NTOHS:
   3942 #ifdef _BIG_ENDIAN
   3943 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
   3944 #else
   3945 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
   3946 #endif
   3947 		break;
   3948 
   3949 
   3950 	case DIF_SUBR_HTONL:
   3951 	case DIF_SUBR_NTOHL:
   3952 #ifdef _BIG_ENDIAN
   3953 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
   3954 #else
   3955 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
   3956 #endif
   3957 		break;
   3958 
   3959 
   3960 	case DIF_SUBR_HTONLL:
   3961 	case DIF_SUBR_NTOHLL:
   3962 #ifdef _BIG_ENDIAN
   3963 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
   3964 #else
   3965 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
   3966 #endif
   3967 		break;
   3968 
   3969 
   3970 	case DIF_SUBR_DIRNAME:
   3971 	case DIF_SUBR_BASENAME: {
   3972 		char *dest = (char *)mstate->dtms_scratch_ptr;
   3973 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
   3974 		uintptr_t src = tupregs[0].dttk_value;
   3975 		int i, j, len = dtrace_strlen((char *)src, size);
   3976 		int lastbase = -1, firstbase = -1, lastdir = -1;
   3977 		int start, end;
   3978 
   3979 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
   3980 			regs[rd] = NULL;
   3981 			break;
   3982 		}
   3983 
   3984 		if (!DTRACE_INSCRATCH(mstate, size)) {
   3985 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   3986 			regs[rd] = NULL;
   3987 			break;
   3988 		}
   3989 
   3990 		/*
   3991 		 * The basename and dirname for a zero-length string is
   3992 		 * defined to be "."
   3993 		 */
   3994 		if (len == 0) {
   3995 			len = 1;
   3996 			src = (uintptr_t)".";
   3997 		}
   3998 
   3999 		/*
   4000 		 * Start from the back of the string, moving back toward the
   4001 		 * front until we see a character that isn't a slash.  That
   4002 		 * character is the last character in the basename.
   4003 		 */
   4004 		for (i = len - 1; i >= 0; i--) {
   4005 			if (dtrace_load8(src + i) != '/')
   4006 				break;
   4007 		}
   4008 
   4009 		if (i >= 0)
   4010 			lastbase = i;
   4011 
   4012 		/*
   4013 		 * Starting from the last character in the basename, move
   4014 		 * towards the front until we find a slash.  The character
   4015 		 * that we processed immediately before that is the first
   4016 		 * character in the basename.
   4017 		 */
   4018 		for (; i >= 0; i--) {
   4019 			if (dtrace_load8(src + i) == '/')
   4020 				break;
   4021 		}
   4022 
   4023 		if (i >= 0)
   4024 			firstbase = i + 1;
   4025 
   4026 		/*
   4027 		 * Now keep going until we find a non-slash character.  That
   4028 		 * character is the last character in the dirname.
   4029 		 */
   4030 		for (; i >= 0; i--) {
   4031 			if (dtrace_load8(src + i) != '/')
   4032 				break;
   4033 		}
   4034 
   4035 		if (i >= 0)
   4036 			lastdir = i;
   4037 
   4038 		ASSERT(!(lastbase == -1 && firstbase != -1));
   4039 		ASSERT(!(firstbase == -1 && lastdir != -1));
   4040 
   4041 		if (lastbase == -1) {
   4042 			/*
   4043 			 * We didn't find a non-slash character.  We know that
   4044 			 * the length is non-zero, so the whole string must be
   4045 			 * slashes.  In either the dirname or the basename
   4046 			 * case, we return '/'.
   4047 			 */
   4048 			ASSERT(firstbase == -1);
   4049 			firstbase = lastbase = lastdir = 0;
   4050 		}
   4051 
   4052 		if (firstbase == -1) {
   4053 			/*
   4054 			 * The entire string consists only of a basename
   4055 			 * component.  If we're looking for dirname, we need
   4056 			 * to change our string to be just "."; if we're
   4057 			 * looking for a basename, we'll just set the first
   4058 			 * character of the basename to be 0.
   4059 			 */
   4060 			if (subr == DIF_SUBR_DIRNAME) {
   4061 				ASSERT(lastdir == -1);
   4062 				src = (uintptr_t)".";
   4063 				lastdir = 0;
   4064 			} else {
   4065 				firstbase = 0;
   4066 			}
   4067 		}
   4068 
   4069 		if (subr == DIF_SUBR_DIRNAME) {
   4070 			if (lastdir == -1) {
   4071 				/*
   4072 				 * We know that we have a slash in the name --
   4073 				 * or lastdir would be set to 0, above.  And
   4074 				 * because lastdir is -1, we know that this
   4075 				 * slash must be the first character.  (That
   4076 				 * is, the full string must be of the form
   4077 				 * "/basename".)  In this case, the last
   4078 				 * character of the directory name is 0.
   4079 				 */
   4080 				lastdir = 0;
   4081 			}
   4082 
   4083 			start = 0;
   4084 			end = lastdir;
   4085 		} else {
   4086 			ASSERT(subr == DIF_SUBR_BASENAME);
   4087 			ASSERT(firstbase != -1 && lastbase != -1);
   4088 			start = firstbase;
   4089 			end = lastbase;
   4090 		}
   4091 
   4092 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
   4093 			dest[j] = dtrace_load8(src + i);
   4094 
   4095 		dest[j] = '\0';
   4096 		regs[rd] = (uintptr_t)dest;
   4097 		mstate->dtms_scratch_ptr += size;
   4098 		break;
   4099 	}
   4100 
   4101 	case DIF_SUBR_CLEANPATH: {
   4102 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
   4103 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
   4104 		uintptr_t src = tupregs[0].dttk_value;
   4105 		int i = 0, j = 0;
   4106 
   4107 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
   4108 			regs[rd] = NULL;
   4109 			break;
   4110 		}
   4111 
   4112 		if (!DTRACE_INSCRATCH(mstate, size)) {
   4113 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   4114 			regs[rd] = NULL;
   4115 			break;
   4116 		}
   4117 
   4118 		/*
   4119 		 * Move forward, loading each character.
   4120 		 */
   4121 		do {
   4122 			c = dtrace_load8(src + i++);
   4123 next:
   4124 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
   4125 				break;
   4126 
   4127 			if (c != '/') {
   4128 				dest[j++] = c;
   4129 				continue;
   4130 			}
   4131 
   4132 			c = dtrace_load8(src + i++);
   4133 
   4134 			if (c == '/') {
   4135 				/*
   4136 				 * We have two slashes -- we can just advance
   4137 				 * to the next character.
   4138 				 */
   4139 				goto next;
   4140 			}
   4141 
   4142 			if (c != '.') {
   4143 				/*
   4144 				 * This is not "." and it's not ".." -- we can
   4145 				 * just store the "/" and this character and
   4146 				 * drive on.
   4147 				 */
   4148 				dest[j++] = '/';
   4149 				dest[j++] = c;
   4150 				continue;
   4151 			}
   4152 
   4153 			c = dtrace_load8(src + i++);
   4154 
   4155 			if (c == '/') {
   4156 				/*
   4157 				 * This is a "/./" component.  We're not going
   4158 				 * to store anything in the destination buffer;
   4159 				 * we're just going to go to the next component.
   4160 				 */
   4161 				goto next;
   4162 			}
   4163 
   4164 			if (c != '.') {
   4165 				/*
   4166 				 * This is not ".." -- we can just store the
   4167 				 * "/." and this character and continue
   4168 				 * processing.
   4169 				 */
   4170 				dest[j++] = '/';
   4171 				dest[j++] = '.';
   4172 				dest[j++] = c;
   4173 				continue;
   4174 			}
   4175 
   4176 			c = dtrace_load8(src + i++);
   4177 
   4178 			if (c != '/' && c != '\0') {
   4179 				/*
   4180 				 * This is not ".." -- it's "..[mumble]".
   4181 				 * We'll store the "/.." and this character
   4182 				 * and continue processing.
   4183 				 */
   4184 				dest[j++] = '/';
   4185 				dest[j++] = '.';
   4186 				dest[j++] = '.';
   4187 				dest[j++] = c;
   4188 				continue;
   4189 			}
   4190 
   4191 			/*
   4192 			 * This is "/../" or "/..\0".  We need to back up
   4193 			 * our destination pointer until we find a "/".
   4194 			 */
   4195 			i--;
   4196 			while (j != 0 && dest[--j] != '/')
   4197 				continue;
   4198 
   4199 			if (c == '\0')
   4200 				dest[++j] = '/';
   4201 		} while (c != '\0');
   4202 
   4203 		dest[j] = '\0';
   4204 		regs[rd] = (uintptr_t)dest;
   4205 		mstate->dtms_scratch_ptr += size;
   4206 		break;
   4207 	}
   4208 
   4209 	case DIF_SUBR_INET_NTOA:
   4210 	case DIF_SUBR_INET_NTOA6:
   4211 	case DIF_SUBR_INET_NTOP: {
   4212 		size_t size;
   4213 		int af, argi, i;
   4214 		char *base, *end;
   4215 
   4216 		if (subr == DIF_SUBR_INET_NTOP) {
   4217 			af = (int)tupregs[0].dttk_value;
   4218 			argi = 1;
   4219 		} else {
   4220 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
   4221 			argi = 0;
   4222 		}
   4223 
   4224 		if (af == AF_INET) {
   4225 			ipaddr_t ip4;
   4226 			uint8_t *ptr8, val;
   4227 
   4228 			/*
   4229 			 * Safely load the IPv4 address.
   4230 			 */
   4231 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
   4232 
   4233 			/*
   4234 			 * Check an IPv4 string will fit in scratch.
   4235 			 */
   4236 			size = INET_ADDRSTRLEN;
   4237 			if (!DTRACE_INSCRATCH(mstate, size)) {
   4238 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   4239 				regs[rd] = NULL;
   4240 				break;
   4241 			}
   4242 			base = (char *)mstate->dtms_scratch_ptr;
   4243 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
   4244 
   4245 			/*
   4246 			 * Stringify as a dotted decimal quad.
   4247 			 */
   4248 			*end-- = '\0';
   4249 			ptr8 = (uint8_t *)&ip4;
   4250 			for (i = 3; i >= 0; i--) {
   4251 				val = ptr8[i];
   4252 
   4253 				if (val == 0) {
   4254 					*end-- = '0';
   4255 				} else {
   4256 					for (; val; val /= 10) {
   4257 						*end-- = '0' + (val % 10);
   4258 					}
   4259 				}
   4260 
   4261 				if (i > 0)
   4262 					*end-- = '.';
   4263 			}
   4264 			ASSERT(end + 1 >= base);
   4265 
   4266 		} else if (af == AF_INET6) {
   4267 			struct in6_addr ip6;
   4268 			int firstzero, tryzero, numzero, v6end;
   4269 			uint16_t val;
   4270 			const char digits[] = "0123456789abcdef";
   4271 
   4272 			/*
   4273 			 * Stringify using RFC 1884 convention 2 - 16 bit
   4274 			 * hexadecimal values with a zero-run compression.
   4275 			 * Lower case hexadecimal digits are used.
   4276 			 * 	eg, fe80::214:4fff:fe0b:76c8.
   4277 			 * The IPv4 embedded form is returned for inet_ntop,
   4278 			 * just the IPv4 string is returned for inet_ntoa6.
   4279 			 */
   4280 
   4281 			/*
   4282 			 * Safely load the IPv6 address.
   4283 			 */
   4284 			dtrace_bcopy(
   4285 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
   4286 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
   4287 
   4288 			/*
   4289 			 * Check an IPv6 string will fit in scratch.
   4290 			 */
   4291 			size = INET6_ADDRSTRLEN;
   4292 			if (!DTRACE_INSCRATCH(mstate, size)) {
   4293 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   4294 				regs[rd] = NULL;
   4295 				break;
   4296 			}
   4297 			base = (char *)mstate->dtms_scratch_ptr;
   4298 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
   4299 			*end-- = '\0';
   4300 
   4301 			/*
   4302 			 * Find the longest run of 16 bit zero values
   4303 			 * for the single allowed zero compression - "::".
   4304 			 */
   4305 			firstzero = -1;
   4306 			tryzero = -1;
   4307 			numzero = 1;
   4308 			for (i = 0; i < sizeof (struct in6_addr); i++) {
   4309 				if (ip6._S6_un._S6_u8[i] == 0 &&
   4310 				    tryzero == -1 && i % 2 == 0) {
   4311 					tryzero = i;
   4312 					continue;
   4313 				}
   4314 
   4315 				if (tryzero != -1 &&
   4316 				    (ip6._S6_un._S6_u8[i] != 0 ||
   4317 				    i == sizeof (struct in6_addr) - 1)) {
   4318 
   4319 					if (i - tryzero <= numzero) {
   4320 						tryzero = -1;
   4321 						continue;
   4322 					}
   4323 
   4324 					firstzero = tryzero;
   4325 					numzero = i - i % 2 - tryzero;
   4326 					tryzero = -1;
   4327 
   4328 					if (ip6._S6_un._S6_u8[i] == 0 &&
   4329 					    i == sizeof (struct in6_addr) - 1)
   4330 						numzero += 2;
   4331 				}
   4332 			}
   4333 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
   4334 
   4335 			/*
   4336 			 * Check for an IPv4 embedded address.
   4337 			 */
   4338 			v6end = sizeof (struct in6_addr) - 2;
   4339 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
   4340 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
   4341 				for (i = sizeof (struct in6_addr) - 1;
   4342 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
   4343 					ASSERT(end >= base);
   4344 
   4345 					val = ip6._S6_un._S6_u8[i];
   4346 
   4347 					if (val == 0) {
   4348 						*end-- = '0';
   4349 					} else {
   4350 						for (; val; val /= 10) {
   4351 							*end-- = '0' + val % 10;
   4352 						}
   4353 					}
   4354 
   4355 					if (i > DTRACE_V4MAPPED_OFFSET)
   4356 						*end-- = '.';
   4357 				}
   4358 
   4359 				if (subr == DIF_SUBR_INET_NTOA6)
   4360 					goto inetout;
   4361 
   4362 				/*
   4363 				 * Set v6end to skip the IPv4 address that
   4364 				 * we have already stringified.
   4365 				 */
   4366 				v6end = 10;
   4367 			}
   4368 
   4369 			/*
   4370 			 * Build the IPv6 string by working through the
   4371 			 * address in reverse.
   4372 			 */
   4373 			for (i = v6end; i >= 0; i -= 2) {
   4374 				ASSERT(end >= base);
   4375 
   4376 				if (i == firstzero + numzero - 2) {
   4377 					*end-- = ':';
   4378 					*end-- = ':';
   4379 					i -= numzero - 2;
   4380 					continue;
   4381 				}
   4382 
   4383 				if (i < 14 && i != firstzero - 2)
   4384 					*end-- = ':';
   4385 
   4386 				val = (ip6._S6_un._S6_u8[i] << 8) +
   4387 				    ip6._S6_un._S6_u8[i + 1];
   4388 
   4389 				if (val == 0) {
   4390 					*end-- = '0';
   4391 				} else {
   4392 					for (; val; val /= 16) {
   4393 						*end-- = digits[val % 16];
   4394 					}
   4395 				}
   4396 			}
   4397 			ASSERT(end + 1 >= base);
   4398 
   4399 		} else {
   4400 			/*
   4401 			 * The user didn't use AH_INET or AH_INET6.
   4402 			 */
   4403 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
   4404 			regs[rd] = NULL;
   4405 			break;
   4406 		}
   4407 
   4408 inetout:	regs[rd] = (uintptr_t)end + 1;
   4409 		mstate->dtms_scratch_ptr += size;
   4410 		break;
   4411 	}
   4412 
   4413 	}
   4414 }
   4415 
   4416 /*
   4417  * Emulate the execution of DTrace IR instructions specified by the given
   4418  * DIF object.  This function is deliberately void of assertions as all of
   4419  * the necessary checks are handled by a call to dtrace_difo_validate().
   4420  */
   4421 static uint64_t
   4422 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
   4423     dtrace_vstate_t *vstate, dtrace_state_t *state)
   4424 {
   4425 	const dif_instr_t *text = difo->dtdo_buf;
   4426 	const uint_t textlen = difo->dtdo_len;
   4427 	const char *strtab = difo->dtdo_strtab;
   4428 	const uint64_t *inttab = difo->dtdo_inttab;
   4429 
   4430 	uint64_t rval = 0;
   4431 	dtrace_statvar_t *svar;
   4432 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
   4433 	dtrace_difv_t *v;
   4434 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
   4435 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
   4436 
   4437 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
   4438 	uint64_t regs[DIF_DIR_NREGS];
   4439 	uint64_t *tmp;
   4440 
   4441 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
   4442 	int64_t cc_r;
   4443 	uint_t pc = 0, id, opc;
   4444 	uint8_t ttop = 0;
   4445 	dif_instr_t instr;
   4446 	uint_t r1, r2, rd;
   4447 
   4448 	/*
   4449 	 * We stash the current DIF object into the machine state: we need it
   4450 	 * for subsequent access checking.
   4451 	 */
   4452 	mstate->dtms_difo = difo;
   4453 
   4454 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
   4455 
   4456 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
   4457 		opc = pc;
   4458 
   4459 		instr = text[pc++];
   4460 		r1 = DIF_INSTR_R1(instr);
   4461 		r2 = DIF_INSTR_R2(instr);
   4462 		rd = DIF_INSTR_RD(instr);
   4463 
   4464 		switch (DIF_INSTR_OP(instr)) {
   4465 		case DIF_OP_OR:
   4466 			regs[rd] = regs[r1] | regs[r2];
   4467 			break;
   4468 		case DIF_OP_XOR:
   4469 			regs[rd] = regs[r1] ^ regs[r2];
   4470 			break;
   4471 		case DIF_OP_AND:
   4472 			regs[rd] = regs[r1] & regs[r2];
   4473 			break;
   4474 		case DIF_OP_SLL:
   4475 			regs[rd] = regs[r1] << regs[r2];
   4476 			break;
   4477 		case DIF_OP_SRL:
   4478 			regs[rd] = regs[r1] >> regs[r2];
   4479 			break;
   4480 		case DIF_OP_SUB:
   4481 			regs[rd] = regs[r1] - regs[r2];
   4482 			break;
   4483 		case DIF_OP_ADD:
   4484 			regs[rd] = regs[r1] + regs[r2];
   4485 			break;
   4486 		case DIF_OP_MUL:
   4487 			regs[rd] = regs[r1] * regs[r2];
   4488 			break;
   4489 		case DIF_OP_SDIV:
   4490 			if (regs[r2] == 0) {
   4491 				regs[rd] = 0;
   4492 				*flags |= CPU_DTRACE_DIVZERO;
   4493 			} else {
   4494 				regs[rd] = (int64_t)regs[r1] /
   4495 				    (int64_t)regs[r2];
   4496 			}
   4497 			break;
   4498 
   4499 		case DIF_OP_UDIV:
   4500 			if (regs[r2] == 0) {
   4501 				regs[rd] = 0;
   4502 				*flags |= CPU_DTRACE_DIVZERO;
   4503 			} else {
   4504 				regs[rd] = regs[r1] / regs[r2];
   4505 			}
   4506 			break;
   4507 
   4508 		case DIF_OP_SREM:
   4509 			if (regs[r2] == 0) {
   4510 				regs[rd] = 0;
   4511 				*flags |= CPU_DTRACE_DIVZERO;
   4512 			} else {
   4513 				regs[rd] = (int64_t)regs[r1] %
   4514 				    (int64_t)regs[r2];
   4515 			}
   4516 			break;
   4517 
   4518 		case DIF_OP_UREM:
   4519 			if (regs[r2] == 0) {
   4520 				regs[rd] = 0;
   4521 				*flags |= CPU_DTRACE_DIVZERO;
   4522 			} else {
   4523 				regs[rd] = regs[r1] % regs[r2];
   4524 			}
   4525 			break;
   4526 
   4527 		case DIF_OP_NOT:
   4528 			regs[rd] = ~regs[r1];
   4529 			break;
   4530 		case DIF_OP_MOV:
   4531 			regs[rd] = regs[r1];
   4532 			break;
   4533 		case DIF_OP_CMP:
   4534 			cc_r = regs[r1] - regs[r2];
   4535 			cc_n = cc_r < 0;
   4536 			cc_z = cc_r == 0;
   4537 			cc_v = 0;
   4538 			cc_c = regs[r1] < regs[r2];
   4539 			break;
   4540 		case DIF_OP_TST:
   4541 			cc_n = cc_v = cc_c = 0;
   4542 			cc_z = regs[r1] == 0;
   4543 			break;
   4544 		case DIF_OP_BA:
   4545 			pc = DIF_INSTR_LABEL(instr);
   4546 			break;
   4547 		case DIF_OP_BE:
   4548 			if (cc_z)
   4549 				pc = DIF_INSTR_LABEL(instr);
   4550 			break;
   4551 		case DIF_OP_BNE:
   4552 			if (cc_z == 0)
   4553 				pc = DIF_INSTR_LABEL(instr);
   4554 			break;
   4555 		case DIF_OP_BG:
   4556 			if ((cc_z | (cc_n ^ cc_v)) == 0)
   4557 				pc = DIF_INSTR_LABEL(instr);
   4558 			break;
   4559 		case DIF_OP_BGU:
   4560 			if ((cc_c | cc_z) == 0)
   4561 				pc = DIF_INSTR_LABEL(instr);
   4562 			break;
   4563 		case DIF_OP_BGE:
   4564 			if ((cc_n ^ cc_v) == 0)
   4565 				pc = DIF_INSTR_LABEL(instr);
   4566 			break;
   4567 		case DIF_OP_BGEU:
   4568 			if (cc_c == 0)
   4569 				pc = DIF_INSTR_LABEL(instr);
   4570 			break;
   4571 		case DIF_OP_BL:
   4572 			if (cc_n ^ cc_v)
   4573 				pc = DIF_INSTR_LABEL(instr);
   4574 			break;
   4575 		case DIF_OP_BLU:
   4576 			if (cc_c)
   4577 				pc = DIF_INSTR_LABEL(instr);
   4578 			break;
   4579 		case DIF_OP_BLE:
   4580 			if (cc_z | (cc_n ^ cc_v))
   4581 				pc = DIF_INSTR_LABEL(instr);
   4582 			break;
   4583 		case DIF_OP_BLEU:
   4584 			if (cc_c | cc_z)
   4585 				pc = DIF_INSTR_LABEL(instr);
   4586 			break;
   4587 		case DIF_OP_RLDSB:
   4588 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
   4589 				*flags |= CPU_DTRACE_KPRIV;
   4590 				*illval = regs[r1];
   4591 				break;
   4592 			}
   4593 			/*FALLTHROUGH*/
   4594 		case DIF_OP_LDSB:
   4595 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
   4596 			break;
   4597 		case DIF_OP_RLDSH:
   4598 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
   4599 				*flags |= CPU_DTRACE_KPRIV;
   4600 				*illval = regs[r1];
   4601 				break;
   4602 			}
   4603 			/*FALLTHROUGH*/
   4604 		case DIF_OP_LDSH:
   4605 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
   4606 			break;
   4607 		case DIF_OP_RLDSW:
   4608 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
   4609 				*flags |= CPU_DTRACE_KPRIV;
   4610 				*illval = regs[r1];
   4611 				break;
   4612 			}
   4613 			/*FALLTHROUGH*/
   4614 		case DIF_OP_LDSW:
   4615 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
   4616 			break;
   4617 		case DIF_OP_RLDUB:
   4618 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
   4619 				*flags |= CPU_DTRACE_KPRIV;
   4620 				*illval = regs[r1];
   4621 				break;
   4622 			}
   4623 			/*FALLTHROUGH*/
   4624 		case DIF_OP_LDUB:
   4625 			regs[rd] = dtrace_load8(regs[r1]);
   4626 			break;
   4627 		case DIF_OP_RLDUH:
   4628 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
   4629 				*flags |= CPU_DTRACE_KPRIV;
   4630 				*illval = regs[r1];
   4631 				break;
   4632 			}
   4633 			/*FALLTHROUGH*/
   4634 		case DIF_OP_LDUH:
   4635 			regs[rd] = dtrace_load16(regs[r1]);
   4636 			break;
   4637 		case DIF_OP_RLDUW:
   4638 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
   4639 				*flags |= CPU_DTRACE_KPRIV;
   4640 				*illval = regs[r1];
   4641 				break;
   4642 			}
   4643 			/*FALLTHROUGH*/
   4644 		case DIF_OP_LDUW:
   4645 			regs[rd] = dtrace_load32(regs[r1]);
   4646 			break;
   4647 		case DIF_OP_RLDX:
   4648 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
   4649 				*flags |= CPU_DTRACE_KPRIV;
   4650 				*illval = regs[r1];
   4651 				break;
   4652 			}
   4653 			/*FALLTHROUGH*/
   4654 		case DIF_OP_LDX:
   4655 			regs[rd] = dtrace_load64(regs[r1]);
   4656 			break;
   4657 		case DIF_OP_ULDSB:
   4658 			regs[rd] = (int8_t)
   4659 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
   4660 			break;
   4661 		case DIF_OP_ULDSH:
   4662 			regs[rd] = (int16_t)
   4663 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
   4664 			break;
   4665 		case DIF_OP_ULDSW:
   4666 			regs[rd] = (int32_t)
   4667 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
   4668 			break;
   4669 		case DIF_OP_ULDUB:
   4670 			regs[rd] =
   4671 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
   4672 			break;
   4673 		case DIF_OP_ULDUH:
   4674 			regs[rd] =
   4675 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
   4676 			break;
   4677 		case DIF_OP_ULDUW:
   4678 			regs[rd] =
   4679 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
   4680 			break;
   4681 		case DIF_OP_ULDX:
   4682 			regs[rd] =
   4683 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
   4684 			break;
   4685 		case DIF_OP_RET:
   4686 			rval = regs[rd];
   4687 			pc = textlen;
   4688 			break;
   4689 		case DIF_OP_NOP:
   4690 			break;
   4691 		case DIF_OP_SETX:
   4692 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
   4693 			break;
   4694 		case DIF_OP_SETS:
   4695 			regs[rd] = (uint64_t)(uintptr_t)
   4696 			    (strtab + DIF_INSTR_STRING(instr));
   4697 			break;
   4698 		case DIF_OP_SCMP: {
   4699 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
   4700 			uintptr_t s1 = regs[r1];
   4701 			uintptr_t s2 = regs[r2];
   4702 
   4703 			if (s1 != NULL &&
   4704 			    !dtrace_strcanload(s1, sz, mstate, vstate))
   4705 				break;
   4706 			if (s2 != NULL &&
   4707 			    !dtrace_strcanload(s2, sz, mstate, vstate))
   4708 				break;
   4709 
   4710 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
   4711 
   4712 			cc_n = cc_r < 0;
   4713 			cc_z = cc_r == 0;
   4714 			cc_v = cc_c = 0;
   4715 			break;
   4716 		}
   4717 		case DIF_OP_LDGA:
   4718 			regs[rd] = dtrace_dif_variable(mstate, state,
   4719 			    r1, regs[r2]);
   4720 			break;
   4721 		case DIF_OP_LDGS:
   4722 			id = DIF_INSTR_VAR(instr);
   4723 
   4724 			if (id >= DIF_VAR_OTHER_UBASE) {
   4725 				uintptr_t a;
   4726 
   4727 				id -= DIF_VAR_OTHER_UBASE;
   4728 				svar = vstate->dtvs_globals[id];
   4729 				ASSERT(svar != NULL);
   4730 				v = &svar->dtsv_var;
   4731 
   4732 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
   4733 					regs[rd] = svar->dtsv_data;
   4734 					break;
   4735 				}
   4736 
   4737 				a = (uintptr_t)svar->dtsv_data;
   4738 
   4739 				if (*(uint8_t *)a == UINT8_MAX) {
   4740 					/*
   4741 					 * If the 0th byte is set to UINT8_MAX
   4742 					 * then this is to be treated as a
   4743 					 * reference to a NULL variable.
   4744 					 */
   4745 					regs[rd] = NULL;
   4746 				} else {
   4747 					regs[rd] = a + sizeof (uint64_t);
   4748 				}
   4749 
   4750 				break;
   4751 			}
   4752 
   4753 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
   4754 			break;
   4755 
   4756 		case DIF_OP_STGS:
   4757 			id = DIF_INSTR_VAR(instr);
   4758 
   4759 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
   4760 			id -= DIF_VAR_OTHER_UBASE;
   4761 
   4762 			svar = vstate->dtvs_globals[id];
   4763 			ASSERT(svar != NULL);
   4764 			v = &svar->dtsv_var;
   4765 
   4766 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
   4767 				uintptr_t a = (uintptr_t)svar->dtsv_data;
   4768 
   4769 				ASSERT(a != NULL);
   4770 				ASSERT(svar->dtsv_size != 0);
   4771 
   4772 				if (regs[rd] == NULL) {
   4773 					*(uint8_t *)a = UINT8_MAX;
   4774 					break;
   4775 				} else {
   4776 					*(uint8_t *)a = 0;
   4777 					a += sizeof (uint64_t);
   4778 				}
   4779 				if (!dtrace_vcanload(
   4780 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
   4781 				    mstate, vstate))
   4782 					break;
   4783 
   4784 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
   4785 				    (void *)a, &v->dtdv_type);
   4786 				break;
   4787 			}
   4788 
   4789 			svar->dtsv_data = regs[rd];
   4790 			break;
   4791 
   4792 		case DIF_OP_LDTA:
   4793 			/*
   4794 			 * There are no DTrace built-in thread-local arrays at
   4795 			 * present.  This opcode is saved for future work.
   4796 			 */
   4797 			*flags |= CPU_DTRACE_ILLOP;
   4798 			regs[rd] = 0;
   4799 			break;
   4800 
   4801 		case DIF_OP_LDLS:
   4802 			id = DIF_INSTR_VAR(instr);
   4803 
   4804 			if (id < DIF_VAR_OTHER_UBASE) {
   4805 				/*
   4806 				 * For now, this has no meaning.
   4807 				 */
   4808 				regs[rd] = 0;
   4809 				break;
   4810 			}
   4811 
   4812 			id -= DIF_VAR_OTHER_UBASE;
   4813 
   4814 			ASSERT(id < vstate->dtvs_nlocals);
   4815 			ASSERT(vstate->dtvs_locals != NULL);
   4816 
   4817 			svar = vstate->dtvs_locals[id];
   4818 			ASSERT(svar != NULL);
   4819 			v = &svar->dtsv_var;
   4820 
   4821 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
   4822 				uintptr_t a = (uintptr_t)svar->dtsv_data;
   4823 				size_t sz = v->dtdv_type.dtdt_size;
   4824 
   4825 				sz += sizeof (uint64_t);
   4826 				ASSERT(svar->dtsv_size == NCPU * sz);
   4827 				a += CPU->cpu_id * sz;
   4828 
   4829 				if (*(uint8_t *)a == UINT8_MAX) {
   4830 					/*
   4831 					 * If the 0th byte is set to UINT8_MAX
   4832 					 * then this is to be treated as a
   4833 					 * reference to a NULL variable.
   4834 					 */
   4835 					regs[rd] = NULL;
   4836 				} else {
   4837 					regs[rd] = a + sizeof (uint64_t);
   4838 				}
   4839 
   4840 				break;
   4841 			}
   4842 
   4843 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
   4844 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
   4845 			regs[rd] = tmp[CPU->cpu_id];
   4846 			break;
   4847 
   4848 		case DIF_OP_STLS:
   4849 			id = DIF_INSTR_VAR(instr);
   4850 
   4851 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
   4852 			id -= DIF_VAR_OTHER_UBASE;
   4853 			ASSERT(id < vstate->dtvs_nlocals);
   4854 
   4855 			ASSERT(vstate->dtvs_locals != NULL);
   4856 			svar = vstate->dtvs_locals[id];
   4857 			ASSERT(svar != NULL);
   4858 			v = &svar->dtsv_var;
   4859 
   4860 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
   4861 				uintptr_t a = (uintptr_t)svar->dtsv_data;
   4862 				size_t sz = v->dtdv_type.dtdt_size;
   4863 
   4864 				sz += sizeof (uint64_t);
   4865 				ASSERT(svar->dtsv_size == NCPU * sz);
   4866 				a += CPU->cpu_id * sz;
   4867 
   4868 				if (regs[rd] == NULL) {
   4869 					*(uint8_t *)a = UINT8_MAX;
   4870 					break;
   4871 				} else {
   4872 					*(uint8_t *)a = 0;
   4873 					a += sizeof (uint64_t);
   4874 				}
   4875 
   4876 				if (!dtrace_vcanload(
   4877 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
   4878 				    mstate, vstate))
   4879 					break;
   4880 
   4881 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
   4882 				    (void *)a, &v->dtdv_type);
   4883 				break;
   4884 			}
   4885 
   4886 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
   4887 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
   4888 			tmp[CPU->cpu_id] = regs[rd];
   4889 			break;
   4890 
   4891 		case DIF_OP_LDTS: {
   4892 			dtrace_dynvar_t *dvar;
   4893 			dtrace_key_t *key;
   4894 
   4895 			id = DIF_INSTR_VAR(instr);
   4896 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
   4897 			id -= DIF_VAR_OTHER_UBASE;
   4898 			v = &vstate->dtvs_tlocals[id];
   4899 
   4900 			key = &tupregs[DIF_DTR_NREGS];
   4901 			key[0].dttk_value = (uint64_t)id;
   4902 			key[0].dttk_size = 0;
   4903 			DTRACE_TLS_THRKEY(key[1].dttk_value);
   4904 			key[1].dttk_size = 0;
   4905 
   4906 			dvar = dtrace_dynvar(dstate, 2, key,
   4907 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
   4908 			    mstate, vstate);
   4909 
   4910 			if (dvar == NULL) {
   4911 				regs[rd] = 0;
   4912 				break;
   4913 			}
   4914 
   4915 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
   4916 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
   4917 			} else {
   4918 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
   4919 			}
   4920 
   4921 			break;
   4922 		}
   4923 
   4924 		case DIF_OP_STTS: {
   4925 			dtrace_dynvar_t *dvar;
   4926 			dtrace_key_t *key;
   4927 
   4928 			id = DIF_INSTR_VAR(instr);
   4929 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
   4930 			id -= DIF_VAR_OTHER_UBASE;
   4931 
   4932 			key = &tupregs[DIF_DTR_NREGS];
   4933 			key[0].dttk_value = (uint64_t)id;
   4934 			key[0].dttk_size = 0;
   4935 			DTRACE_TLS_THRKEY(key[1].dttk_value);
   4936 			key[1].dttk_size = 0;
   4937 			v = &vstate->dtvs_tlocals[id];
   4938 
   4939 			dvar = dtrace_dynvar(dstate, 2, key,
   4940 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
   4941 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
   4942 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
   4943 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
   4944 
   4945 			/*
   4946 			 * Given that we're storing to thread-local data,
   4947 			 * we need to flush our predicate cache.
   4948 			 */
   4949 			curthread->t_predcache = NULL;
   4950 
   4951 			if (dvar == NULL)
   4952 				break;
   4953 
   4954 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
   4955 				if (!dtrace_vcanload(
   4956 				    (void *)(uintptr_t)regs[rd],
   4957 				    &v->dtdv_type, mstate, vstate))
   4958 					break;
   4959 
   4960 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
   4961 				    dvar->dtdv_data, &v->dtdv_type);
   4962 			} else {
   4963 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
   4964 			}
   4965 
   4966 			break;
   4967 		}
   4968 
   4969 		case DIF_OP_SRA:
   4970 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
   4971 			break;
   4972 
   4973 		case DIF_OP_CALL:
   4974 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
   4975 			    regs, tupregs, ttop, mstate, state);
   4976 			break;
   4977 
   4978 		case DIF_OP_PUSHTR:
   4979 			if (ttop == DIF_DTR_NREGS) {
   4980 				*flags |= CPU_DTRACE_TUPOFLOW;
   4981 				break;
   4982 			}
   4983 
   4984 			if (r1 == DIF_TYPE_STRING) {
   4985 				/*
   4986 				 * If this is a string type and the size is 0,
   4987 				 * we'll use the system-wide default string
   4988 				 * size.  Note that we are _not_ looking at
   4989 				 * the value of the DTRACEOPT_STRSIZE option;
   4990 				 * had this been set, we would expect to have
   4991 				 * a non-zero size value in the "pushtr".
   4992 				 */
   4993 				tupregs[ttop].dttk_size =
   4994 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
   4995 				    regs[r2] ? regs[r2] :
   4996 				    dtrace_strsize_default) + 1;
   4997 			} else {
   4998 				tupregs[ttop].dttk_size = regs[r2];
   4999 			}
   5000 
   5001 			tupregs[ttop++].dttk_value = regs[rd];
   5002 			break;
   5003 
   5004 		case DIF_OP_PUSHTV:
   5005 			if (ttop == DIF_DTR_NREGS) {
   5006 				*flags |= CPU_DTRACE_TUPOFLOW;
   5007 				break;
   5008 			}
   5009 
   5010 			tupregs[ttop].dttk_value = regs[rd];
   5011 			tupregs[ttop++].dttk_size = 0;
   5012 			break;
   5013 
   5014 		case DIF_OP_POPTS:
   5015 			if (ttop != 0)
   5016 				ttop--;
   5017 			break;
   5018 
   5019 		case DIF_OP_FLUSHTS:
   5020 			ttop = 0;
   5021 			break;
   5022 
   5023 		case DIF_OP_LDGAA:
   5024 		case DIF_OP_LDTAA: {
   5025 			dtrace_dynvar_t *dvar;
   5026 			dtrace_key_t *key = tupregs;
   5027 			uint_t nkeys = ttop;
   5028 
   5029 			id = DIF_INSTR_VAR(instr);
   5030 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
   5031 			id -= DIF_VAR_OTHER_UBASE;
   5032 
   5033 			key[nkeys].dttk_value = (uint64_t)id;
   5034 			key[nkeys++].dttk_size = 0;
   5035 
   5036 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
   5037 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
   5038 				key[nkeys++].dttk_size = 0;
   5039 				v = &vstate->dtvs_tlocals[id];
   5040 			} else {
   5041 				v = &vstate->dtvs_globals[id]->dtsv_var;
   5042 			}
   5043 
   5044 			dvar = dtrace_dynvar(dstate, nkeys, key,
   5045 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
   5046 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
   5047 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
   5048 
   5049 			if (dvar == NULL) {
   5050 				regs[rd] = 0;
   5051 				break;
   5052 			}
   5053 
   5054 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
   5055 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
   5056 			} else {
   5057 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
   5058 			}
   5059 
   5060 			break;
   5061 		}
   5062 
   5063 		case DIF_OP_STGAA:
   5064 		case DIF_OP_STTAA: {
   5065 			dtrace_dynvar_t *dvar;
   5066 			dtrace_key_t *key = tupregs;
   5067 			uint_t nkeys = ttop;
   5068 
   5069 			id = DIF_INSTR_VAR(instr);
   5070 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
   5071 			id -= DIF_VAR_OTHER_UBASE;
   5072 
   5073 			key[nkeys].dttk_value = (uint64_t)id;
   5074 			key[nkeys++].dttk_size = 0;
   5075 
   5076 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
   5077 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
   5078 				key[nkeys++].dttk_size = 0;
   5079 				v = &vstate->dtvs_tlocals[id];
   5080 			} else {
   5081 				v = &vstate->dtvs_globals[id]->dtsv_var;
   5082 			}
   5083 
   5084 			dvar = dtrace_dynvar(dstate, nkeys, key,
   5085 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
   5086 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
   5087 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
   5088 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
   5089 
   5090 			if (dvar == NULL)
   5091 				break;
   5092 
   5093 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
   5094 				if (!dtrace_vcanload(
   5095 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
   5096 				    mstate, vstate))
   5097 					break;
   5098 
   5099 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
   5100 				    dvar->dtdv_data, &v->dtdv_type);
   5101 			} else {
   5102 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
   5103 			}
   5104 
   5105 			break;
   5106 		}
   5107 
   5108 		case DIF_OP_ALLOCS: {
   5109 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
   5110 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
   5111 
   5112 			/*
   5113 			 * Rounding up the user allocation size could have
   5114 			 * overflowed large, bogus allocations (like -1ULL) to
   5115 			 * 0.
   5116 			 */
   5117 			if (size < regs[r1] ||
   5118 			    !DTRACE_INSCRATCH(mstate, size)) {
   5119 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   5120 				regs[rd] = NULL;
   5121 				break;
   5122 			}
   5123 
   5124 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
   5125 			mstate->dtms_scratch_ptr += size;
   5126 			regs[rd] = ptr;
   5127 			break;
   5128 		}
   5129 
   5130 		case DIF_OP_COPYS:
   5131 			if (!dtrace_canstore(regs[rd], regs[r2],
   5132 			    mstate, vstate)) {
   5133 				*flags |= CPU_DTRACE_BADADDR;
   5134 				*illval = regs[rd];
   5135 				break;
   5136 			}
   5137 
   5138 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
   5139 				break;
   5140 
   5141 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
   5142 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
   5143 			break;
   5144 
   5145 		case DIF_OP_STB:
   5146 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
   5147 				*flags |= CPU_DTRACE_BADADDR;
   5148 				*illval = regs[rd];
   5149 				break;
   5150 			}
   5151 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
   5152 			break;
   5153 
   5154 		case DIF_OP_STH:
   5155 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
   5156 				*flags |= CPU_DTRACE_BADADDR;
   5157 				*illval = regs[rd];
   5158 				break;
   5159 			}
   5160 			if (regs[rd] & 1) {
   5161 				*flags |= CPU_DTRACE_BADALIGN;
   5162 				*illval = regs[rd];
   5163 				break;
   5164 			}
   5165 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
   5166 			break;
   5167 
   5168 		case DIF_OP_STW:
   5169 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
   5170 				*flags |= CPU_DTRACE_BADADDR;
   5171 				*illval = regs[rd];
   5172 				break;
   5173 			}
   5174 			if (regs[rd] & 3) {
   5175 				*flags |= CPU_DTRACE_BADALIGN;
   5176 				*illval = regs[rd];
   5177 				break;
   5178 			}
   5179 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
   5180 			break;
   5181 
   5182 		case DIF_OP_STX:
   5183 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
   5184 				*flags |= CPU_DTRACE_BADADDR;
   5185 				*illval = regs[rd];
   5186 				break;
   5187 			}
   5188 			if (regs[rd] & 7) {
   5189 				*flags |= CPU_DTRACE_BADALIGN;
   5190 				*illval = regs[rd];
   5191 				break;
   5192 			}
   5193 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
   5194 			break;
   5195 		}
   5196 	}
   5197 
   5198 	if (!(*flags & CPU_DTRACE_FAULT))
   5199 		return (rval);
   5200 
   5201 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
   5202 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
   5203 
   5204 	return (0);
   5205 }
   5206 
   5207 static void
   5208 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
   5209 {
   5210 	dtrace_probe_t *probe = ecb->dte_probe;
   5211 	dtrace_provider_t *prov = probe->dtpr_provider;
   5212 	char c[DTRACE_FULLNAMELEN + 80], *str;
   5213 	char *msg = "dtrace: breakpoint action at probe ";
   5214 	char *ecbmsg = " (ecb ";
   5215 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
   5216 	uintptr_t val = (uintptr_t)ecb;
   5217 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
   5218 
   5219 	if (dtrace_destructive_disallow)
   5220 		return;
   5221 
   5222 	/*
   5223 	 * It's impossible to be taking action on the NULL probe.
   5224 	 */
   5225 	ASSERT(probe != NULL);
   5226 
   5227 	/*
   5228 	 * This is a poor man's (destitute man's?) sprintf():  we want to
   5229 	 * print the provider name, module name, function name and name of
   5230 	 * the probe, along with the hex address of the ECB with the breakpoint
   5231 	 * action -- all of which we must place in the character buffer by
   5232 	 * hand.
   5233 	 */
   5234 	while (*msg != '\0')
   5235 		c[i++] = *msg++;
   5236 
   5237 	for (str = prov->dtpv_name; *str != '\0'; str++)
   5238 		c[i++] = *str;
   5239 	c[i++] = ':';
   5240 
   5241 	for (str = probe->dtpr_mod; *str != '\0'; str++)
   5242 		c[i++] = *str;
   5243 	c[i++] = ':';
   5244 
   5245 	for (str = probe->dtpr_func; *str != '\0'; str++)
   5246 		c[i++] = *str;
   5247 	c[i++] = ':';
   5248 
   5249 	for (str = probe->dtpr_name; *str != '\0'; str++)
   5250 		c[i++] = *str;
   5251 
   5252 	while (*ecbmsg != '\0')
   5253 		c[i++] = *ecbmsg++;
   5254 
   5255 	while (shift >= 0) {
   5256 		mask = (uintptr_t)0xf << shift;
   5257 
   5258 		if (val >= ((uintptr_t)1 << shift))
   5259 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
   5260 		shift -= 4;
   5261 	}
   5262 
   5263 	c[i++] = ')';
   5264 	c[i] = '\0';
   5265 
   5266 	debug_enter(c);
   5267 }
   5268 
   5269 static void
   5270 dtrace_action_panic(dtrace_ecb_t *ecb)
   5271 {
   5272 	dtrace_probe_t *probe = ecb->dte_probe;
   5273 
   5274 	/*
   5275 	 * It's impossible to be taking action on the NULL probe.
   5276 	 */
   5277 	ASSERT(probe != NULL);
   5278 
   5279 	if (dtrace_destructive_disallow)
   5280 		return;
   5281 
   5282 	if (dtrace_panicked != NULL)
   5283 		return;
   5284 
   5285 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
   5286 		return;
   5287 
   5288 	/*
   5289 	 * We won the right to panic.  (We want to be sure that only one
   5290 	 * thread calls panic() from dtrace_probe(), and that panic() is
   5291 	 * called exactly once.)
   5292 	 */
   5293 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
   5294 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
   5295 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
   5296 }
   5297 
   5298 static void
   5299 dtrace_action_raise(uint64_t sig)
   5300 {
   5301 	if (dtrace_destructive_disallow)
   5302 		return;
   5303 
   5304 	if (sig >= NSIG) {
   5305 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
   5306 		return;
   5307 	}
   5308 
   5309 	/*
   5310 	 * raise() has a queue depth of 1 -- we ignore all subsequent
   5311 	 * invocations of the raise() action.
   5312 	 */
   5313 	if (curthread->t_dtrace_sig == 0)
   5314 		curthread->t_dtrace_sig = (uint8_t)sig;
   5315 
   5316 	curthread->t_sig_check = 1;
   5317 	aston(curthread);
   5318 }
   5319 
   5320 static void
   5321 dtrace_action_stop(void)
   5322 {
   5323 	if (dtrace_destructive_disallow)
   5324 		return;
   5325 
   5326 	if (!curthread->t_dtrace_stop) {
   5327 		curthread->t_dtrace_stop = 1;
   5328 		curthread->t_sig_check = 1;
   5329 		aston(curthread);
   5330 	}
   5331 }
   5332 
   5333 static void
   5334 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
   5335 {
   5336 	hrtime_t now;
   5337 	volatile uint16_t *flags;
   5338 	cpu_t *cpu = CPU;
   5339 
   5340 	if (dtrace_destructive_disallow)
   5341 		return;
   5342 
   5343 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
   5344 
   5345 	now = dtrace_gethrtime();
   5346 
   5347 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
   5348 		/*
   5349 		 * We need to advance the mark to the current time.
   5350 		 */
   5351 		cpu->cpu_dtrace_chillmark = now;
   5352 		cpu->cpu_dtrace_chilled = 0;
   5353 	}
   5354 
   5355 	/*
   5356 	 * Now check to see if the requested chill time would take us over
   5357 	 * the maximum amount of time allowed in the chill interval.  (Or
   5358 	 * worse, if the calculation itself induces overflow.)
   5359 	 */
   5360 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
   5361 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
   5362 		*flags |= CPU_DTRACE_ILLOP;
   5363 		return;
   5364 	}
   5365 
   5366 	while (dtrace_gethrtime() - now < val)
   5367 		continue;
   5368 
   5369 	/*
   5370 	 * Normally, we assure that the value of the variable "timestamp" does
   5371 	 * not change within an ECB.  The presence of chill() represents an
   5372 	 * exception to this rule, however.
   5373 	 */
   5374 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
   5375 	cpu->cpu_dtrace_chilled += val;
   5376 }
   5377 
   5378 static void
   5379 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
   5380     uint64_t *buf, uint64_t arg)
   5381 {
   5382 	int nframes = DTRACE_USTACK_NFRAMES(arg);
   5383 	int strsize = DTRACE_USTACK_STRSIZE(arg);
   5384 	uint64_t *pcs = &buf[1], *fps;
   5385 	char *str = (char *)&pcs[nframes];
   5386 	int size, offs = 0, i, j;
   5387 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
   5388 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
   5389 	char *sym;
   5390 
   5391 	/*
   5392 	 * Should be taking a faster path if string space has not been
   5393 	 * allocated.
   5394 	 */
   5395 	ASSERT(strsize != 0);
   5396 
   5397 	/*
   5398 	 * We will first allocate some temporary space for the frame pointers.
   5399 	 */
   5400 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
   5401 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
   5402 	    (nframes * sizeof (uint64_t));
   5403 
   5404 	if (!DTRACE_INSCRATCH(mstate, size)) {
   5405 		/*
   5406 		 * Not enough room for our frame pointers -- need to indicate
   5407 		 * that we ran out of scratch space.
   5408 		 */
   5409 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
   5410 		return;
   5411 	}
   5412 
   5413 	mstate->dtms_scratch_ptr += size;
   5414 	saved = mstate->dtms_scratch_ptr;
   5415 
   5416 	/*
   5417 	 * Now get a stack with both program counters and frame pointers.
   5418 	 */
   5419 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
   5420 	dtrace_getufpstack(buf, fps, nframes + 1);
   5421 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
   5422 
   5423 	/*
   5424 	 * If that faulted, we're cooked.
   5425 	 */
   5426 	if (*flags & CPU_DTRACE_FAULT)
   5427 		goto out;
   5428 
   5429 	/*
   5430 	 * Now we want to walk up the stack, calling the USTACK helper.  For
   5431 	 * each iteration, we restore the scratch pointer.
   5432 	 */
   5433 	for (i = 0; i < nframes; i++) {
   5434 		mstate->dtms_scratch_ptr = saved;
   5435 
   5436 		if (offs >= strsize)
   5437 			break;
   5438 
   5439 		sym = (char *)(uintptr_t)dtrace_helper(
   5440 		    DTRACE_HELPER_ACTION_USTACK,
   5441 		    mstate, state, pcs[i], fps[i]);
   5442 
   5443 		/*
   5444 		 * If we faulted while running the helper, we're going to
   5445 		 * clear the fault and null out the corresponding string.
   5446 		 */
   5447 		if (*flags & CPU_DTRACE_FAULT) {
   5448 			*flags &= ~CPU_DTRACE_FAULT;
   5449 			str[offs++] = '\0';
   5450 			continue;
   5451 		}
   5452 
   5453 		if (sym == NULL) {
   5454 			str[offs++] = '\0';
   5455 			continue;
   5456 		}
   5457 
   5458 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
   5459 
   5460 		/*
   5461 		 * Now copy in the string that the helper returned to us.
   5462 		 */
   5463 		for (j = 0; offs + j < strsize; j++) {
   5464 			if ((str[offs + j] = sym[j]) == '\0')
   5465 				break;
   5466 		}
   5467 
   5468 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
   5469 
   5470 		offs += j + 1;
   5471 	}
   5472 
   5473 	if (offs >= strsize) {
   5474 		/*
   5475 		 * If we didn't have room for all of the strings, we don't
   5476 		 * abort processing -- this needn't be a fatal error -- but we
   5477 		 * still want to increment a counter (dts_stkstroverflows) to
   5478 		 * allow this condition to be warned about.  (If this is from
   5479 		 * a jstack() action, it is easily tuned via jstackstrsize.)
   5480 		 */
   5481 		dtrace_error(&state->dts_stkstroverflows);
   5482 	}
   5483 
   5484 	while (offs < strsize)
   5485 		str[offs++] = '\0';
   5486 
   5487 out:
   5488 	mstate->dtms_scratch_ptr = old;
   5489 }
   5490 
   5491 /*
   5492  * If you're looking for the epicenter of DTrace, you just found it.  This
   5493  * is the function called by the provider to fire a probe -- from which all
   5494  * subsequent probe-context DTrace activity emanates.
   5495  */
   5496 void
   5497 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
   5498     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
   5499 {
   5500 	processorid_t cpuid;
   5501 	dtrace_icookie_t cookie;
   5502 	dtrace_probe_t *probe;
   5503 	dtrace_mstate_t mstate;
   5504 	dtrace_ecb_t *ecb;
   5505 	dtrace_action_t *act;
   5506 	intptr_t offs;
   5507 	size_t size;
   5508 	int vtime, onintr;
   5509 	volatile uint16_t *flags;
   5510 	hrtime_t now;
   5511 
   5512 	/*
   5513 	 * Kick out immediately if this CPU is still being born (in which case
   5514 	 * curthread will be set to -1) or the current thread can't allow
   5515 	 * probes in its current context.
   5516 	 */
   5517 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
   5518 		return;
   5519 
   5520 	cookie = dtrace_interrupt_disable();
   5521 	probe = dtrace_probes[id - 1];
   5522 	cpuid = CPU->cpu_id;
   5523 	onintr = CPU_ON_INTR(CPU);
   5524 
   5525 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
   5526 	    probe->dtpr_predcache == curthread->t_predcache) {
   5527 		/*
   5528 		 * We have hit in the predicate cache; we know that
   5529 		 * this predicate would evaluate to be false.
   5530 		 */
   5531 		dtrace_interrupt_enable(cookie);
   5532 		return;
   5533 	}
   5534 
   5535 	if (panic_quiesce) {
   5536 		/*
   5537 		 * We don't trace anything if we're panicking.
   5538 		 */
   5539 		dtrace_interrupt_enable(cookie);
   5540 		return;
   5541 	}
   5542 
   5543 	now = dtrace_gethrtime();
   5544 	vtime = dtrace_vtime_references != 0;
   5545 
   5546 	if (vtime && curthread->t_dtrace_start)
   5547 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
   5548 
   5549 	mstate.dtms_difo = NULL;
   5550 	mstate.dtms_probe = probe;
   5551 	mstate.dtms_strtok = NULL;
   5552 	mstate.dtms_arg[0] = arg0;
   5553 	mstate.dtms_arg[1] = arg1;
   5554 	mstate.dtms_arg[2] = arg2;
   5555 	mstate.dtms_arg[3] = arg3;
   5556 	mstate.dtms_arg[4] = arg4;
   5557 
   5558 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
   5559 
   5560 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
   5561 		dtrace_predicate_t *pred = ecb->dte_predicate;
   5562 		dtrace_state_t *state = ecb->dte_state;
   5563 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
   5564 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
   5565 		dtrace_vstate_t *vstate = &state->dts_vstate;
   5566 		dtrace_provider_t *prov = probe->dtpr_provider;
   5567 		int committed = 0;
   5568 		caddr_t tomax;
   5569 
   5570 		/*
   5571 		 * A little subtlety with the following (seemingly innocuous)
   5572 		 * declaration of the automatic 'val':  by looking at the
   5573 		 * code, you might think that it could be declared in the
   5574 		 * action processing loop, below.  (That is, it's only used in
   5575 		 * the action processing loop.)  However, it must be declared
   5576 		 * out of that scope because in the case of DIF expression
   5577 		 * arguments to aggregating actions, one iteration of the
   5578 		 * action loop will use the last iteration's value.
   5579 		 */
   5580 #ifdef lint
   5581 		uint64_t val = 0;
   5582 #else
   5583 		uint64_t val;
   5584 #endif
   5585 
   5586 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
   5587 		*flags &= ~CPU_DTRACE_ERROR;
   5588 
   5589 		if (prov == dtrace_provider) {
   5590 			/*
   5591 			 * If dtrace itself is the provider of this probe,
   5592 			 * we're only going to continue processing the ECB if
   5593 			 * arg0 (the dtrace_state_t) is equal to the ECB's
   5594 			 * creating state.  (This prevents disjoint consumers
   5595 			 * from seeing one another's metaprobes.)
   5596 			 */
   5597 			if (arg0 != (uint64_t)(uintptr_t)state)
   5598 				continue;
   5599 		}
   5600 
   5601 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
   5602 			/*
   5603 			 * We're not currently active.  If our provider isn't
   5604 			 * the dtrace pseudo provider, we're not interested.
   5605 			 */
   5606 			if (prov != dtrace_provider)
   5607 				continue;
   5608 
   5609 			/*
   5610 			 * Now we must further check if we are in the BEGIN
   5611 			 * probe.  If we are, we will only continue processing
   5612 			 * if we're still in WARMUP -- if one BEGIN enabling
   5613 			 * has invoked the exit() action, we don't want to
   5614 			 * evaluate subsequent BEGIN enablings.
   5615 			 */
   5616 			if (probe->dtpr_id == dtrace_probeid_begin &&
   5617 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
   5618 				ASSERT(state->dts_activity ==
   5619 				    DTRACE_ACTIVITY_DRAINING);
   5620 				continue;
   5621 			}
   5622 		}
   5623 
   5624 		if (ecb->dte_cond) {
   5625 			/*
   5626 			 * If the dte_cond bits indicate that this
   5627 			 * consumer is only allowed to see user-mode firings
   5628 			 * of this probe, call the provider's dtps_usermode()
   5629 			 * entry point to check that the probe was fired
   5630 			 * while in a user context. Skip this ECB if that's
   5631 			 * not the case.
   5632 			 */
   5633 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
   5634 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
   5635 			    probe->dtpr_id, probe->dtpr_arg) == 0)
   5636 				continue;
   5637 
   5638 			/*
   5639 			 * This is more subtle than it looks. We have to be
   5640 			 * absolutely certain that CRED() isn't going to
   5641 			 * change out from under us so it's only legit to
   5642 			 * examine that structure if we're in constrained
   5643 			 * situations. Currently, the only times we'll this
   5644 			 * check is if a non-super-user has enabled the
   5645 			 * profile or syscall providers -- providers that
   5646 			 * allow visibility of all processes. For the
   5647 			 * profile case, the check above will ensure that
   5648 			 * we're examining a user context.
   5649 			 */
   5650 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
   5651 				cred_t *cr;
   5652 				cred_t *s_cr =
   5653 				    ecb->dte_state->dts_cred.dcr_cred;
   5654 				proc_t *proc;
   5655 
   5656 				ASSERT(s_cr != NULL);
   5657 
   5658 				if ((cr = CRED()) == NULL ||
   5659 				    s_cr->cr_uid != cr->cr_uid ||
   5660 				    s_cr->cr_uid != cr->cr_ruid ||
   5661 				    s_cr->cr_uid != cr->cr_suid ||
   5662 				    s_cr->cr_gid != cr->cr_gid ||
   5663 				    s_cr->cr_gid != cr->cr_rgid ||
   5664 				    s_cr->cr_gid != cr->cr_sgid ||
   5665 				    (proc = ttoproc(curthread)) == NULL ||
   5666 				    (proc->p_flag & SNOCD))
   5667 					continue;
   5668 			}
   5669 
   5670 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
   5671 				cred_t *cr;
   5672 				cred_t *s_cr =
   5673 				    ecb->dte_state->dts_cred.dcr_cred;
   5674 
   5675 				ASSERT(s_cr != NULL);
   5676 
   5677 				if ((cr = CRED()) == NULL ||
   5678 				    s_cr->cr_zone->zone_id !=
   5679 				    cr->cr_zone->zone_id)
   5680 					continue;
   5681 			}
   5682 		}
   5683 
   5684 		if (now - state->dts_alive > dtrace_deadman_timeout) {
   5685 			/*
   5686 			 * We seem to be dead.  Unless we (a) have kernel
   5687 			 * destructive permissions (b) have expicitly enabled
   5688 			 * destructive actions and (c) destructive actions have
   5689 			 * not been disabled, we're going to transition into
   5690 			 * the KILLED state, from which no further processing
   5691 			 * on this state will be performed.
   5692 			 */
   5693 			if (!dtrace_priv_kernel_destructive(state) ||
   5694 			    !state->dts_cred.dcr_destructive ||
   5695 			    dtrace_destructive_disallow) {
   5696 				void *activity = &state->dts_activity;
   5697 				dtrace_activity_t current;
   5698 
   5699 				do {
   5700 					current = state->dts_activity;
   5701 				} while (dtrace_cas32(activity, current,
   5702 				    DTRACE_ACTIVITY_KILLED) != current);
   5703 
   5704 				continue;
   5705 			}
   5706 		}
   5707 
   5708 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
   5709 		    ecb->dte_alignment, state, &mstate)) < 0)
   5710 			continue;
   5711 
   5712 		tomax = buf->dtb_tomax;
   5713 		ASSERT(tomax != NULL);
   5714 
   5715 		if (ecb->dte_size != 0)
   5716 			DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
   5717 
   5718 		mstate.dtms_epid = ecb->dte_epid;
   5719 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
   5720 
   5721 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
   5722 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
   5723 		else
   5724 			mstate.dtms_access = 0;
   5725 
   5726 		if (pred != NULL) {
   5727 			dtrace_difo_t *dp = pred->dtp_difo;
   5728 			int rval;
   5729 
   5730 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
   5731 
   5732 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
   5733 				dtrace_cacheid_t cid = probe->dtpr_predcache;
   5734 
   5735 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
   5736 					/*
   5737 					 * Update the predicate cache...
   5738 					 */
   5739 					ASSERT(cid == pred->dtp_cacheid);
   5740 					curthread->t_predcache = cid;
   5741 				}
   5742 
   5743 				continue;
   5744 			}
   5745 		}
   5746 
   5747 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
   5748 		    act != NULL; act = act->dta_next) {
   5749 			size_t valoffs;
   5750 			dtrace_difo_t *dp;
   5751 			dtrace_recdesc_t *rec = &act->dta_rec;
   5752 
   5753 			size = rec->dtrd_size;
   5754 			valoffs = offs + rec->dtrd_offset;
   5755 
   5756 			if (DTRACEACT_ISAGG(act->dta_kind)) {
   5757 				uint64_t v = 0xbad;
   5758 				dtrace_aggregation_t *agg;
   5759 
   5760 				agg = (dtrace_aggregation_t *)act;
   5761 
   5762 				if ((dp = act->dta_difo) != NULL)
   5763 					v = dtrace_dif_emulate(dp,
   5764 					    &mstate, vstate, state);
   5765 
   5766 				if (*flags & CPU_DTRACE_ERROR)
   5767 					continue;
   5768 
   5769 				/*
   5770 				 * Note that we always pass the expression
   5771 				 * value from the previous iteration of the
   5772 				 * action loop.  This value will only be used
   5773 				 * if there is an expression argument to the
   5774 				 * aggregating action, denoted by the
   5775 				 * dtag_hasarg field.
   5776 				 */
   5777 				dtrace_aggregate(agg, buf,
   5778 				    offs, aggbuf, v, val);
   5779 				continue;
   5780 			}
   5781 
   5782 			switch (act->dta_kind) {
   5783 			case DTRACEACT_STOP:
   5784 				if (dtrace_priv_proc_destructive(state))
   5785 					dtrace_action_stop();
   5786 				continue;
   5787 
   5788 			case DTRACEACT_BREAKPOINT:
   5789 				if (dtrace_priv_kernel_destructive(state))
   5790 					dtrace_action_breakpoint(ecb);
   5791 				continue;
   5792 
   5793 			case DTRACEACT_PANIC:
   5794 				if (dtrace_priv_kernel_destructive(state))
   5795 					dtrace_action_panic(ecb);
   5796 				continue;
   5797 
   5798 			case DTRACEACT_STACK:
   5799 				if (!dtrace_priv_kernel(state))
   5800 					continue;
   5801 
   5802 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
   5803 				    size / sizeof (pc_t), probe->dtpr_aframes,
   5804 				    DTRACE_ANCHORED(probe) ? NULL :
   5805 				    (uint32_t *)arg0);
   5806 
   5807 				continue;
   5808 
   5809 			case DTRACEACT_JSTACK:
   5810 			case DTRACEACT_USTACK:
   5811 				if (!dtrace_priv_proc(state))
   5812 					continue;
   5813 
   5814 				/*
   5815 				 * See comment in DIF_VAR_PID.
   5816 				 */
   5817 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
   5818 				    CPU_ON_INTR(CPU)) {
   5819 					int depth = DTRACE_USTACK_NFRAMES(
   5820 					    rec->dtrd_arg) + 1;
   5821 
   5822 					dtrace_bzero((void *)(tomax + valoffs),
   5823 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
   5824 					    + depth * sizeof (uint64_t));
   5825 
   5826 					continue;
   5827 				}
   5828 
   5829 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
   5830 				    curproc->p_dtrace_helpers != NULL) {
   5831 					/*
   5832 					 * This is the slow path -- we have
   5833 					 * allocated string space, and we're
   5834 					 * getting the stack of a process that
   5835 					 * has helpers.  Call into a separate
   5836 					 * routine to perform this processing.
   5837 					 */
   5838 					dtrace_action_ustack(&mstate, state,
   5839 					    (uint64_t *)(tomax + valoffs),
   5840 					    rec->dtrd_arg);
   5841 					continue;
   5842 				}
   5843 
   5844 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
   5845 				dtrace_getupcstack((uint64_t *)
   5846 				    (tomax + valoffs),
   5847 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
   5848 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
   5849 				continue;
   5850 
   5851 			default:
   5852 				break;
   5853 			}
   5854 
   5855 			dp = act->dta_difo;
   5856 			ASSERT(dp != NULL);
   5857 
   5858 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
   5859 
   5860 			if (*flags & CPU_DTRACE_ERROR)
   5861 				continue;
   5862 
   5863 			switch (act->dta_kind) {
   5864 			case DTRACEACT_SPECULATE:
   5865 				ASSERT(buf == &state->dts_buffer[cpuid]);
   5866 				buf = dtrace_speculation_buffer(state,
   5867 				    cpuid, val);
   5868 
   5869 				if (buf == NULL) {
   5870 					*flags |= CPU_DTRACE_DROP;
   5871 					continue;
   5872 				}
   5873 
   5874 				offs = dtrace_buffer_reserve(buf,
   5875 				    ecb->dte_needed, ecb->dte_alignment,
   5876 				    state, NULL);
   5877 
   5878 				if (offs < 0) {
   5879 					*flags |= CPU_DTRACE_DROP;
   5880 					continue;
   5881 				}
   5882 
   5883 				tomax = buf->dtb_tomax;
   5884 				ASSERT(tomax != NULL);
   5885 
   5886 				if (ecb->dte_size != 0)
   5887 					DTRACE_STORE(uint32_t, tomax, offs,
   5888 					    ecb->dte_epid);
   5889 				continue;
   5890 
   5891 			case DTRACEACT_CHILL:
   5892 				if (dtrace_priv_kernel_destructive(state))
   5893 					dtrace_action_chill(&mstate, val);
   5894 				continue;
   5895 
   5896 			case DTRACEACT_RAISE:
   5897 				if (dtrace_priv_proc_destructive(state))
   5898 					dtrace_action_raise(val);
   5899 				continue;
   5900 
   5901 			case DTRACEACT_COMMIT:
   5902 				ASSERT(!committed);
   5903 
   5904 				/*
   5905 				 * We need to commit our buffer state.
   5906 				 */
   5907 				if (ecb->dte_size)
   5908 					buf->dtb_offset = offs + ecb->dte_size;
   5909 				buf = &state->dts_buffer[cpuid];
   5910 				dtrace_speculation_commit(state, cpuid, val);
   5911 				committed = 1;
   5912 				continue;
   5913 
   5914 			case DTRACEACT_DISCARD:
   5915 				dtrace_speculation_discard(state, cpuid, val);
   5916 				continue;
   5917 
   5918 			case DTRACEACT_DIFEXPR:
   5919 			case DTRACEACT_LIBACT:
   5920 			case DTRACEACT_PRINTF:
   5921 			case DTRACEACT_PRINTA:
   5922 			case DTRACEACT_SYSTEM:
   5923 			case DTRACEACT_FREOPEN:
   5924 				break;
   5925 
   5926 			case DTRACEACT_SYM:
   5927 			case DTRACEACT_MOD:
   5928 				if (!dtrace_priv_kernel(state))
   5929 					continue;
   5930 				break;
   5931 
   5932 			case DTRACEACT_USYM:
   5933 			case DTRACEACT_UMOD:
   5934 			case DTRACEACT_UADDR: {
   5935 				struct pid *pid = curthread->t_procp->p_pidp;
   5936 
   5937 				if (!dtrace_priv_proc(state))
   5938 					continue;
   5939 
   5940 				DTRACE_STORE(uint64_t, tomax,
   5941 				    valoffs, (uint64_t)pid->pid_id);
   5942 				DTRACE_STORE(uint64_t, tomax,
   5943 				    valoffs + sizeof (uint64_t), val);
   5944 
   5945 				continue;
   5946 			}
   5947 
   5948 			case DTRACEACT_EXIT: {
   5949 				/*
   5950 				 * For the exit action, we are going to attempt
   5951 				 * to atomically set our activity to be
   5952 				 * draining.  If this fails (either because
   5953 				 * another CPU has beat us to the exit action,
   5954 				 * or because our current activity is something
   5955 				 * other than ACTIVE or WARMUP), we will
   5956 				 * continue.  This assures that the exit action
   5957 				 * can be successfully recorded at most once
   5958 				 * when we're in the ACTIVE state.  If we're
   5959 				 * encountering the exit() action while in
   5960 				 * COOLDOWN, however, we want to honor the new
   5961 				 * status code.  (We know that we're the only
   5962 				 * thread in COOLDOWN, so there is no race.)
   5963 				 */
   5964 				void *activity = &state->dts_activity;
   5965 				dtrace_activity_t current = state->dts_activity;
   5966 
   5967 				if (current == DTRACE_ACTIVITY_COOLDOWN)
   5968 					break;
   5969 
   5970 				if (current != DTRACE_ACTIVITY_WARMUP)
   5971 					current = DTRACE_ACTIVITY_ACTIVE;
   5972 
   5973 				if (dtrace_cas32(activity, current,
   5974 				    DTRACE_ACTIVITY_DRAINING) != current) {
   5975 					*flags |= CPU_DTRACE_DROP;
   5976 					continue;
   5977 				}
   5978 
   5979 				break;
   5980 			}
   5981 
   5982 			default:
   5983 				ASSERT(0);
   5984 			}
   5985 
   5986 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
   5987 				uintptr_t end = valoffs + size;
   5988 
   5989 				if (!dtrace_vcanload((void *)(uintptr_t)val,
   5990 				    &dp->dtdo_rtype, &mstate, vstate))
   5991 					continue;
   5992 
   5993 				/*
   5994 				 * If this is a string, we're going to only
   5995 				 * load until we find the zero byte -- after
   5996 				 * which we'll store zero bytes.
   5997 				 */
   5998 				if (dp->dtdo_rtype.dtdt_kind ==
   5999 				    DIF_TYPE_STRING) {
   6000 					char c = '\0' + 1;
   6001 					int intuple = act->dta_intuple;
   6002 					size_t s;
   6003 
   6004 					for (s = 0; s < size; s++) {
   6005 						if (c != '\0')
   6006 							c = dtrace_load8(val++);
   6007 
   6008 						DTRACE_STORE(uint8_t, tomax,
   6009 						    valoffs++, c);
   6010 
   6011 						if (c == '\0' && intuple)
   6012 							break;
   6013 					}
   6014 
   6015 					continue;
   6016 				}
   6017 
   6018 				while (valoffs < end) {
   6019 					DTRACE_STORE(uint8_t, tomax, valoffs++,
   6020 					    dtrace_load8(val++));
   6021 				}
   6022 
   6023 				continue;
   6024 			}
   6025 
   6026 			switch (size) {
   6027 			case 0:
   6028 				break;
   6029 
   6030 			case sizeof (uint8_t):
   6031 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
   6032 				break;
   6033 			case sizeof (uint16_t):
   6034 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
   6035 				break;
   6036 			case sizeof (uint32_t):
   6037 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
   6038 				break;
   6039 			case sizeof (uint64_t):
   6040 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
   6041 				break;
   6042 			default:
   6043 				/*
   6044 				 * Any other size should have been returned by
   6045 				 * reference, not by value.
   6046 				 */
   6047 				ASSERT(0);
   6048 				break;
   6049 			}
   6050 		}
   6051 
   6052 		if (*flags & CPU_DTRACE_DROP)
   6053 			continue;
   6054 
   6055 		if (*flags & CPU_DTRACE_FAULT) {
   6056 			int ndx;
   6057 			dtrace_action_t *err;
   6058 
   6059 			buf->dtb_errors++;
   6060 
   6061 			if (probe->dtpr_id == dtrace_probeid_error) {
   6062 				/*
   6063 				 * There's nothing we can do -- we had an
   6064 				 * error on the error probe.  We bump an
   6065 				 * error counter to at least indicate that
   6066 				 * this condition happened.
   6067 				 */
   6068 				dtrace_error(&state->dts_dblerrors);
   6069 				continue;
   6070 			}
   6071 
   6072 			if (vtime) {
   6073 				/*
   6074 				 * Before recursing on dtrace_probe(), we
   6075 				 * need to explicitly clear out our start
   6076 				 * time to prevent it from being accumulated
   6077 				 * into t_dtrace_vtime.
   6078 				 */
   6079 				curthread->t_dtrace_start = 0;
   6080 			}
   6081 
   6082 			/*
   6083 			 * Iterate over the actions to figure out which action
   6084 			 * we were processing when we experienced the error.
   6085 			 * Note that act points _past_ the faulting action; if
   6086 			 * act is ecb->dte_action, the fault was in the
   6087 			 * predicate, if it's ecb->dte_action->dta_next it's
   6088 			 * in action #1, and so on.
   6089 			 */
   6090 			for (err = ecb->dte_action, ndx = 0;
   6091 			    err != act; err = err->dta_next, ndx++)
   6092 				continue;
   6093 
   6094 			dtrace_probe_error(state, ecb->dte_epid, ndx,
   6095 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
   6096 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
   6097 			    cpu_core[cpuid].cpuc_dtrace_illval);
   6098 
   6099 			continue;
   6100 		}
   6101 
   6102 		if (!committed)
   6103 			buf->dtb_offset = offs + ecb->dte_size;
   6104 	}
   6105 
   6106 	if (vtime)
   6107 		curthread->t_dtrace_start = dtrace_gethrtime();
   6108 
   6109 	dtrace_interrupt_enable(cookie);
   6110 }
   6111 
   6112 /*
   6113  * DTrace Probe Hashing Functions
   6114  *
   6115  * The functions in this section (and indeed, the functions in remaining
   6116  * sections) are not _called_ from probe context.  (Any exceptions to this are
   6117  * marked with a "Note:".)  Rather, they are called from elsewhere in the
   6118  * DTrace framework to look-up probes in, add probes to and remove probes from
   6119  * the DTrace probe hashes.  (Each probe is hashed by each element of the
   6120  * probe tuple -- allowing for fast lookups, regardless of what was
   6121  * specified.)
   6122  */
   6123 static uint_t
   6124 dtrace_hash_str(char *p)
   6125 {
   6126 	unsigned int g;
   6127 	uint_t hval = 0;
   6128 
   6129 	while (*p) {
   6130 		hval = (hval << 4) + *p++;
   6131 		if ((g = (hval & 0xf0000000)) != 0)
   6132 			hval ^= g >> 24;
   6133 		hval &= ~g;
   6134 	}
   6135 	return (hval);
   6136 }
   6137 
   6138 static dtrace_hash_t *
   6139 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
   6140 {
   6141 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
   6142 
   6143 	hash->dth_stroffs = stroffs;
   6144 	hash->dth_nextoffs = nextoffs;
   6145 	hash->dth_prevoffs = prevoffs;
   6146 
   6147 	hash->dth_size = 1;
   6148 	hash->dth_mask = hash->dth_size - 1;
   6149 
   6150 	hash->dth_tab = kmem_zalloc(hash->dth_size *
   6151 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
   6152 
   6153 	return (hash);
   6154 }
   6155 
   6156 static void
   6157 dtrace_hash_destroy(dtrace_hash_t *hash)
   6158 {
   6159 #ifdef DEBUG
   6160 	int i;
   6161 
   6162 	for (i = 0; i < hash->dth_size; i++)
   6163 		ASSERT(hash->dth_tab[i] == NULL);
   6164 #endif
   6165 
   6166 	kmem_free(hash->dth_tab,
   6167 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
   6168 	kmem_free(hash, sizeof (dtrace_hash_t));
   6169 }
   6170 
   6171 static void
   6172 dtrace_hash_resize(dtrace_hash_t *hash)
   6173 {
   6174 	int size = hash->dth_size, i, ndx;
   6175 	int new_size = hash->dth_size << 1;
   6176 	int new_mask = new_size - 1;
   6177 	dtrace_hashbucket_t **new_tab, *bucket, *next;
   6178 
   6179 	ASSERT((new_size & new_mask) == 0);
   6180 
   6181 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
   6182 
   6183 	for (i = 0; i < size; i++) {
   6184 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
   6185 			dtrace_probe_t *probe = bucket->dthb_chain;
   6186 
   6187 			ASSERT(probe != NULL);
   6188 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
   6189 
   6190 			next = bucket->dthb_next;
   6191 			bucket->dthb_next = new_tab[ndx];
   6192 			new_tab[ndx] = bucket;
   6193 		}
   6194 	}
   6195 
   6196 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
   6197 	hash->dth_tab = new_tab;
   6198 	hash->dth_size = new_size;
   6199 	hash->dth_mask = new_mask;
   6200 }
   6201 
   6202 static void
   6203 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
   6204 {
   6205 	int hashval = DTRACE_HASHSTR(hash, new);
   6206 	int ndx = hashval & hash->dth_mask;
   6207 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
   6208 	dtrace_probe_t **nextp, **prevp;
   6209 
   6210 	for (; bucket != NULL; bucket = bucket->dthb_next) {
   6211 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
   6212 			goto add;
   6213 	}
   6214 
   6215 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
   6216 		dtrace_hash_resize(hash);
   6217 		dtrace_hash_add(hash, new);
   6218 		return;
   6219 	}
   6220 
   6221 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
   6222 	bucket->dthb_next = hash->dth_tab[ndx];
   6223 	hash->dth_tab[ndx] = bucket;
   6224 	hash->dth_nbuckets++;
   6225 
   6226 add:
   6227 	nextp = DTRACE_HASHNEXT(hash, new);
   6228 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
   6229 	*nextp = bucket->dthb_chain;
   6230 
   6231 	if (bucket->dthb_chain != NULL) {
   6232 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
   6233 		ASSERT(*prevp == NULL);
   6234 		*prevp = new;
   6235 	}
   6236 
   6237 	bucket->dthb_chain = new;
   6238 	bucket->dthb_len++;
   6239 }
   6240 
   6241 static dtrace_probe_t *
   6242 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
   6243 {
   6244 	int hashval = DTRACE_HASHSTR(hash, template);
   6245 	int ndx = hashval & hash->dth_mask;
   6246 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
   6247 
   6248 	for (; bucket != NULL; bucket = bucket->dthb_next) {
   6249 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
   6250 			return (bucket->dthb_chain);
   6251 	}
   6252 
   6253 	return (NULL);
   6254 }
   6255 
   6256 static int
   6257 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
   6258 {
   6259 	int hashval = DTRACE_HASHSTR(hash, template);
   6260 	int ndx = hashval & hash->dth_mask;
   6261 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
   6262 
   6263 	for (; bucket != NULL; bucket = bucket->dthb_next) {
   6264 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
   6265 			return (bucket->dthb_len);
   6266 	}
   6267 
   6268 	return (NULL);
   6269 }
   6270 
   6271 static void
   6272 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
   6273 {
   6274 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
   6275 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
   6276 
   6277 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
   6278 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
   6279 
   6280 	/*
   6281 	 * Find the bucket that we're removing this probe from.
   6282 	 */
   6283 	for (; bucket != NULL; bucket = bucket->dthb_next) {
   6284 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
   6285 			break;
   6286 	}
   6287 
   6288 	ASSERT(bucket != NULL);
   6289 
   6290 	if (*prevp == NULL) {
   6291 		if (*nextp == NULL) {
   6292 			/*
   6293 			 * The removed probe was the only probe on this
   6294 			 * bucket; we need to remove the bucket.
   6295 			 */
   6296 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
   6297 
   6298 			ASSERT(bucket->dthb_chain == probe);
   6299 			ASSERT(b != NULL);
   6300 
   6301 			if (b == bucket) {
   6302 				hash->dth_tab[ndx] = bucket->dthb_next;
   6303 			} else {
   6304 				while (b->dthb_next != bucket)
   6305 					b = b->dthb_next;
   6306 				b->dthb_next = bucket->dthb_next;
   6307 			}
   6308 
   6309 			ASSERT(hash->dth_nbuckets > 0);
   6310 			hash->dth_nbuckets--;
   6311 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
   6312 			return;
   6313 		}
   6314 
   6315 		bucket->dthb_chain = *nextp;
   6316 	} else {
   6317 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
   6318 	}
   6319 
   6320 	if (*nextp != NULL)
   6321 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
   6322 }
   6323 
   6324 /*
   6325  * DTrace Utility Functions
   6326  *
   6327  * These are random utility functions that are _not_ called from probe context.
   6328  */
   6329 static int
   6330 dtrace_badattr(const dtrace_attribute_t *a)
   6331 {
   6332 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
   6333 	    a->dtat_data > DTRACE_STABILITY_MAX ||
   6334 	    a->dtat_class > DTRACE_CLASS_MAX);
   6335 }
   6336 
   6337 /*
   6338  * Return a duplicate copy of a string.  If the specified string is NULL,
   6339  * this function returns a zero-length string.
   6340  */
   6341 static char *
   6342 dtrace_strdup(const char *str)
   6343 {
   6344 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
   6345 
   6346 	if (str != NULL)
   6347 		(void) strcpy(new, str);
   6348 
   6349 	return (new);
   6350 }
   6351 
   6352 #define	DTRACE_ISALPHA(c)	\
   6353 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
   6354 
   6355 static int
   6356 dtrace_badname(const char *s)
   6357 {
   6358 	char c;
   6359 
   6360 	if (s == NULL || (c = *s++) == '\0')
   6361 		return (0);
   6362 
   6363 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
   6364 		return (1);
   6365 
   6366 	while ((c = *s++) != '\0') {
   6367 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
   6368 		    c != '-' && c != '_' && c != '.' && c != '`')
   6369 			return (1);
   6370 	}
   6371 
   6372 	return (0);
   6373 }
   6374 
   6375 static void
   6376 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
   6377 {
   6378 	uint32_t priv;
   6379 
   6380 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
   6381 		/*
   6382 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
   6383 		 */
   6384 		priv = DTRACE_PRIV_ALL;
   6385 	} else {
   6386 		*uidp = crgetuid(cr);
   6387 		*zoneidp = crgetzoneid(cr);
   6388 
   6389 		priv = 0;
   6390 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
   6391 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
   6392 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
   6393 			priv |= DTRACE_PRIV_USER;
   6394 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
   6395 			priv |= DTRACE_PRIV_PROC;
   6396 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
   6397 			priv |= DTRACE_PRIV_OWNER;
   6398 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
   6399 			priv |= DTRACE_PRIV_ZONEOWNER;
   6400 	}
   6401 
   6402 	*privp = priv;
   6403 }
   6404 
   6405 #ifdef DTRACE_ERRDEBUG
   6406 static void
   6407 dtrace_errdebug(const char *str)
   6408 {
   6409 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
   6410 	int occupied = 0;
   6411 
   6412 	mutex_enter(&dtrace_errlock);
   6413 	dtrace_errlast = str;
   6414 	dtrace_errthread = curthread;
   6415 
   6416 	while (occupied++ < DTRACE_ERRHASHSZ) {
   6417 		if (dtrace_errhash[hval].dter_msg == str) {
   6418 			dtrace_errhash[hval].dter_count++;
   6419 			goto out;
   6420 		}
   6421 
   6422 		if (dtrace_errhash[hval].dter_msg != NULL) {
   6423 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
   6424 			continue;
   6425 		}
   6426 
   6427 		dtrace_errhash[hval].dter_msg = str;
   6428 		dtrace_errhash[hval].dter_count = 1;
   6429 		goto out;
   6430 	}
   6431 
   6432 	panic("dtrace: undersized error hash");
   6433 out:
   6434 	mutex_exit(&dtrace_errlock);
   6435 }
   6436 #endif
   6437 
   6438 /*
   6439  * DTrace Matching Functions
   6440  *
   6441  * These functions are used to match groups of probes, given some elements of
   6442  * a probe tuple, or some globbed expressions for elements of a probe tuple.
   6443  */
   6444 static int
   6445 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
   6446     zoneid_t zoneid)
   6447 {
   6448 	if (priv != DTRACE_PRIV_ALL) {
   6449 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
   6450 		uint32_t match = priv & ppriv;
   6451 
   6452 		/*
   6453 		 * No PRIV_DTRACE_* privileges...
   6454 		 */
   6455 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
   6456 		    DTRACE_PRIV_KERNEL)) == 0)
   6457 			return (0);
   6458 
   6459 		/*
   6460 		 * No matching bits, but there were bits to match...
   6461 		 */
   6462 		if (match == 0 && ppriv != 0)
   6463 			return (0);
   6464 
   6465 		/*
   6466 		 * Need to have permissions to the process, but don't...
   6467 		 */
   6468 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
   6469 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
   6470 			return (0);
   6471 		}
   6472 
   6473 		/*
   6474 		 * Need to be in the same zone unless we possess the
   6475 		 * privilege to examine all zones.
   6476 		 */
   6477 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
   6478 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
   6479 			return (0);
   6480 		}
   6481 	}
   6482 
   6483 	return (1);
   6484 }
   6485 
   6486 /*
   6487  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
   6488  * consists of input pattern strings and an ops-vector to evaluate them.
   6489  * This function returns >0 for match, 0 for no match, and <0 for error.
   6490  */
   6491 static int
   6492 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
   6493     uint32_t priv, uid_t uid, zoneid_t zoneid)
   6494 {
   6495 	dtrace_provider_t *pvp = prp->dtpr_provider;
   6496 	int rv;
   6497 
   6498 	if (pvp->dtpv_defunct)
   6499 		return (0);
   6500 
   6501 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
   6502 		return (rv);
   6503 
   6504 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
   6505 		return (rv);
   6506 
   6507 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
   6508 		return (rv);
   6509 
   6510 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
   6511 		return (rv);
   6512 
   6513 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
   6514 		return (0);
   6515 
   6516 	return (rv);
   6517 }
   6518 
   6519 /*
   6520  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
   6521  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
   6522  * libc's version, the kernel version only applies to 8-bit ASCII strings.
   6523  * In addition, all of the recursion cases except for '*' matching have been
   6524  * unwound.  For '*', we still implement recursive evaluation, but a depth
   6525  * counter is maintained and matching is aborted if we recurse too deep.
   6526  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
   6527  */
   6528 static int
   6529 dtrace_match_glob(const char *s, const char *p, int depth)
   6530 {
   6531 	const char *olds;
   6532 	char s1, c;
   6533 	int gs;
   6534 
   6535 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
   6536 		return (-1);
   6537 
   6538 	if (s == NULL)
   6539 		s = ""; /* treat NULL as empty string */
   6540 
   6541 top:
   6542 	olds = s;
   6543 	s1 = *s++;
   6544 
   6545 	if (p == NULL)
   6546 		return (0);
   6547 
   6548 	if ((c = *p++) == '\0')
   6549 		return (s1 == '\0');
   6550 
   6551 	switch (c) {
   6552 	case '[': {
   6553 		int ok = 0, notflag = 0;
   6554 		char lc = '\0';
   6555 
   6556 		if (s1 == '\0')
   6557 			return (0);
   6558 
   6559 		if (*p == '!') {
   6560 			notflag = 1;
   6561 			p++;
   6562 		}
   6563 
   6564 		if ((c = *p++) == '\0')
   6565 			return (0);
   6566 
   6567 		do {
   6568 			if (c == '-' && lc != '\0' && *p != ']') {
   6569 				if ((c = *p++) == '\0')
   6570 					return (0);
   6571 				if (c == '\\' && (c = *p++) == '\0')
   6572 					return (0);
   6573 
   6574 				if (notflag) {
   6575 					if (s1 < lc || s1 > c)
   6576 						ok++;
   6577 					else
   6578 						return (0);
   6579 				} else if (lc <= s1 && s1 <= c)
   6580 					ok++;
   6581 
   6582 			} else if (c == '\\' && (c = *p++) == '\0')
   6583 				return (0);
   6584 
   6585 			lc = c; /* save left-hand 'c' for next iteration */
   6586 
   6587 			if (notflag) {
   6588 				if (s1 != c)
   6589 					ok++;
   6590 				else
   6591 					return (0);
   6592 			} else if (s1 == c)
   6593 				ok++;
   6594 
   6595 			if ((c = *p++) == '\0')
   6596 				return (0);
   6597 
   6598 		} while (c != ']');
   6599 
   6600 		if (ok)
   6601 			goto top;
   6602 
   6603 		return (0);
   6604 	}
   6605 
   6606 	case '\\':
   6607 		if ((c = *p++) == '\0')
   6608 			return (0);
   6609 		/*FALLTHRU*/
   6610 
   6611 	default:
   6612 		if (c != s1)
   6613 			return (0);
   6614 		/*FALLTHRU*/
   6615 
   6616 	case '?':
   6617 		if (s1 != '\0')
   6618 			goto top;
   6619 		return (0);
   6620 
   6621 	case '*':
   6622 		while (*p == '*')
   6623 			p++; /* consecutive *'s are identical to a single one */
   6624 
   6625 		if (*p == '\0')
   6626 			return (1);
   6627 
   6628 		for (s = olds; *s != '\0'; s++) {
   6629 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
   6630 				return (gs);
   6631 		}
   6632 
   6633 		return (0);
   6634 	}
   6635 }
   6636 
   6637 /*ARGSUSED*/
   6638 static int
   6639 dtrace_match_string(const char *s, const char *p, int depth)
   6640 {
   6641 	return (s != NULL && strcmp(s, p) == 0);
   6642 }
   6643 
   6644 /*ARGSUSED*/
   6645 static int
   6646 dtrace_match_nul(const char *s, const char *p, int depth)
   6647 {
   6648 	return (1); /* always match the empty pattern */
   6649 }
   6650 
   6651 /*ARGSUSED*/
   6652 static int
   6653 dtrace_match_nonzero(const char *s, const char *p, int depth)
   6654 {
   6655 	return (s != NULL && s[0] != '\0');
   6656 }
   6657 
   6658 static int
   6659 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
   6660     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
   6661 {
   6662 	dtrace_probe_t template, *probe;
   6663 	dtrace_hash_t *hash = NULL;
   6664 	int len, rc, best = INT_MAX, nmatched = 0;
   6665 	dtrace_id_t i;
   6666 
   6667 	ASSERT(MUTEX_HELD(&dtrace_lock));
   6668 
   6669 	/*
   6670 	 * If the probe ID is specified in the key, just lookup by ID and
   6671 	 * invoke the match callback once if a matching probe is found.
   6672 	 */
   6673 	if (pkp->dtpk_id != DTRACE_IDNONE) {
   6674 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
   6675 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
   6676 			if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
   6677 				return (DTRACE_MATCH_FAIL);
   6678 			nmatched++;
   6679 		}
   6680 		return (nmatched);
   6681 	}
   6682 
   6683 	template.dtpr_mod = (char *)pkp->dtpk_mod;
   6684 	template.dtpr_func = (char *)pkp->dtpk_func;
   6685 	template.dtpr_name = (char *)pkp->dtpk_name;
   6686 
   6687 	/*
   6688 	 * We want to find the most distinct of the module name, function
   6689 	 * name, and name.  So for each one that is not a glob pattern or
   6690 	 * empty string, we perform a lookup in the corresponding hash and
   6691 	 * use the hash table with the fewest collisions to do our search.
   6692 	 */
   6693 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
   6694 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
   6695 		best = len;
   6696 		hash = dtrace_bymod;
   6697 	}
   6698 
   6699 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
   6700 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
   6701 		best = len;
   6702 		hash = dtrace_byfunc;
   6703 	}
   6704 
   6705 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
   6706 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
   6707 		best = len;
   6708 		hash = dtrace_byname;
   6709 	}
   6710 
   6711 	/*
   6712 	 * If we did not select a hash table, iterate over every probe and
   6713 	 * invoke our callback for each one that matches our input probe key.
   6714 	 */
   6715 	if (hash == NULL) {
   6716 		for (i = 0; i < dtrace_nprobes; i++) {
   6717 			if ((probe = dtrace_probes[i]) == NULL ||
   6718 			    dtrace_match_probe(probe, pkp, priv, uid,
   6719 			    zoneid) <= 0)
   6720 				continue;
   6721 
   6722 			nmatched++;
   6723 
   6724 			if ((rc = (*matched)(probe, arg)) !=
   6725 			    DTRACE_MATCH_NEXT) {
   6726 				if (rc == DTRACE_MATCH_FAIL)
   6727 					return (DTRACE_MATCH_FAIL);
   6728 				break;
   6729 			}
   6730 		}
   6731 
   6732 		return (nmatched);
   6733 	}
   6734 
   6735 	/*
   6736 	 * If we selected a hash table, iterate over each probe of the same key
   6737 	 * name and invoke the callback for every probe that matches the other
   6738 	 * attributes of our input probe key.
   6739 	 */
   6740 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
   6741 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
   6742 
   6743 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
   6744 			continue;
   6745 
   6746 		nmatched++;
   6747 
   6748 		if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
   6749 			if (rc == DTRACE_MATCH_FAIL)
   6750 				return (DTRACE_MATCH_FAIL);
   6751 			break;
   6752 		}
   6753 	}
   6754 
   6755 	return (nmatched);
   6756 }
   6757 
   6758 /*
   6759  * Return the function pointer dtrace_probecmp() should use to compare the
   6760  * specified pattern with a string.  For NULL or empty patterns, we select
   6761  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
   6762  * For non-empty non-glob strings, we use dtrace_match_string().
   6763  */
   6764 static dtrace_probekey_f *
   6765 dtrace_probekey_func(const char *p)
   6766 {
   6767 	char c;
   6768 
   6769 	if (p == NULL || *p == '\0')
   6770 		return (&dtrace_match_nul);
   6771 
   6772 	while ((c = *p++) != '\0') {
   6773 		if (c == '[' || c == '?' || c == '*' || c == '\\')
   6774 			return (&dtrace_match_glob);
   6775 	}
   6776 
   6777 	return (&dtrace_match_string);
   6778 }
   6779 
   6780 /*
   6781  * Build a probe comparison key for use with dtrace_match_probe() from the
   6782  * given probe description.  By convention, a null key only matches anchored
   6783  * probes: if each field is the empty string, reset dtpk_fmatch to
   6784  * dtrace_match_nonzero().
   6785  */
   6786 static void
   6787 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
   6788 {
   6789 	pkp->dtpk_prov = pdp->dtpd_provider;
   6790 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
   6791 
   6792 	pkp->dtpk_mod = pdp->dtpd_mod;
   6793 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
   6794 
   6795 	pkp->dtpk_func = pdp->dtpd_func;
   6796 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
   6797 
   6798 	pkp->dtpk_name = pdp->dtpd_name;
   6799 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
   6800 
   6801 	pkp->dtpk_id = pdp->dtpd_id;
   6802 
   6803 	if (pkp->dtpk_id == DTRACE_IDNONE &&
   6804 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
   6805 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
   6806 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
   6807 	    pkp->dtpk_nmatch == &dtrace_match_nul)
   6808 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
   6809 }
   6810 
   6811 /*
   6812  * DTrace Provider-to-Framework API Functions
   6813  *
   6814  * These functions implement much of the Provider-to-Framework API, as
   6815  * described in <sys/dtrace.h>.  The parts of the API not in this section are
   6816  * the functions in the API for probe management (found below), and
   6817  * dtrace_probe() itself (found above).
   6818  */
   6819 
   6820 /*
   6821  * Register the calling provider with the DTrace framework.  This should
   6822  * generally be called by DTrace providers in their attach(9E) entry point.
   6823  */
   6824 int
   6825 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
   6826     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
   6827 {
   6828 	dtrace_provider_t *provider;
   6829 
   6830 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
   6831 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
   6832 		    "arguments", name ? name : "<NULL>");
   6833 		return (EINVAL);
   6834 	}
   6835 
   6836 	if (name[0] == '\0' || dtrace_badname(name)) {
   6837 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
   6838 		    "provider name", name);
   6839 		return (EINVAL);
   6840 	}
   6841 
   6842 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
   6843 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
   6844 	    pops->dtps_destroy == NULL ||
   6845 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
   6846 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
   6847 		    "provider ops", name);
   6848 		return (EINVAL);
   6849 	}
   6850 
   6851 	if (dtrace_badattr(&pap->dtpa_provider) ||
   6852 	    dtrace_badattr(&pap->dtpa_mod) ||
   6853 	    dtrace_badattr(&pap->dtpa_func) ||
   6854 	    dtrace_badattr(&pap->dtpa_name) ||
   6855 	    dtrace_badattr(&pap->dtpa_args)) {
   6856 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
   6857 		    "provider attributes", name);
   6858 		return (EINVAL);
   6859 	}
   6860 
   6861 	if (priv & ~DTRACE_PRIV_ALL) {
   6862 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
   6863 		    "privilege attributes", name);
   6864 		return (EINVAL);
   6865 	}
   6866 
   6867 	if ((priv & DTRACE_PRIV_KERNEL) &&
   6868 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
   6869 	    pops->dtps_usermode == NULL) {
   6870 		cmn_err(CE_WARN, "failed to register provider '%s': need "
   6871 		    "dtps_usermode() op for given privilege attributes", name);
   6872 		return (EINVAL);
   6873 	}
   6874 
   6875 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
   6876 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
   6877 	(void) strcpy(provider->dtpv_name, name);
   6878 
   6879 	provider->dtpv_attr = *pap;
   6880 	provider->dtpv_priv.dtpp_flags = priv;
   6881 	if (cr != NULL) {
   6882 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
   6883 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
   6884 	}
   6885 	provider->dtpv_pops = *pops;
   6886 
   6887 	if (pops->dtps_provide == NULL) {
   6888 		ASSERT(pops->dtps_provide_module != NULL);
   6889 		provider->dtpv_pops.dtps_provide =
   6890 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
   6891 	}
   6892 
   6893 	if (pops->dtps_provide_module == NULL) {
   6894 		ASSERT(pops->dtps_provide != NULL);
   6895 		provider->dtpv_pops.dtps_provide_module =
   6896 		    (void (*)(void *, struct modctl *))dtrace_nullop;
   6897 	}
   6898 
   6899 	if (pops->dtps_suspend == NULL) {
   6900 		ASSERT(pops->dtps_resume == NULL);
   6901 		provider->dtpv_pops.dtps_suspend =
   6902 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
   6903 		provider->dtpv_pops.dtps_resume =
   6904 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
   6905 	}
   6906 
   6907 	provider->dtpv_arg = arg;
   6908 	*idp = (dtrace_provider_id_t)provider;
   6909 
   6910 	if (pops == &dtrace_provider_ops) {
   6911 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
   6912 		ASSERT(MUTEX_HELD(&dtrace_lock));
   6913 		ASSERT(dtrace_anon.dta_enabling == NULL);
   6914 
   6915 		/*
   6916 		 * We make sure that the DTrace provider is at the head of
   6917 		 * the provider chain.
   6918 		 */
   6919 		provider->dtpv_next = dtrace_provider;
   6920 		dtrace_provider = provider;
   6921 		return (0);
   6922 	}
   6923 
   6924 	mutex_enter(&dtrace_provider_lock);
   6925 	mutex_enter(&dtrace_lock);
   6926 
   6927 	/*
   6928 	 * If there is at least one provider registered, we'll add this
   6929 	 * provider after the first provider.
   6930 	 */
   6931 	if (dtrace_provider != NULL) {
   6932 		provider->dtpv_next = dtrace_provider->dtpv_next;
   6933 		dtrace_provider->dtpv_next = provider;
   6934 	} else {
   6935 		dtrace_provider = provider;
   6936 	}
   6937 
   6938 	if (dtrace_retained != NULL) {
   6939 		dtrace_enabling_provide(provider);
   6940 
   6941 		/*
   6942 		 * Now we need to call dtrace_enabling_matchall() -- which
   6943 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
   6944 		 * to drop all of our locks before calling into it...
   6945 		 */
   6946 		mutex_exit(&dtrace_lock);
   6947 		mutex_exit(&dtrace_provider_lock);
   6948 		dtrace_enabling_matchall();
   6949 
   6950 		return (0);
   6951 	}
   6952 
   6953 	mutex_exit(&dtrace_lock);
   6954 	mutex_exit(&dtrace_provider_lock);
   6955 
   6956 	return (0);
   6957 }
   6958 
   6959 /*
   6960  * Unregister the specified provider from the DTrace framework.  This should
   6961  * generally be called by DTrace providers in their detach(9E) entry point.
   6962  */
   6963 int
   6964 dtrace_unregister(dtrace_provider_id_t id)
   6965 {
   6966 	dtrace_provider_t *old = (dtrace_provider_t *)id;
   6967 	dtrace_provider_t *prev = NULL;
   6968 	int i, self = 0;
   6969 	dtrace_probe_t *probe, *first = NULL;
   6970 
   6971 	if (old->dtpv_pops.dtps_enable ==
   6972 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
   6973 		/*
   6974 		 * If DTrace itself is the provider, we're called with locks
   6975 		 * already held.
   6976 		 */
   6977 		ASSERT(old == dtrace_provider);
   6978 		ASSERT(dtrace_devi != NULL);
   6979 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
   6980 		ASSERT(MUTEX_HELD(&dtrace_lock));
   6981 		self = 1;
   6982 
   6983 		if (dtrace_provider->dtpv_next != NULL) {
   6984 			/*
   6985 			 * There's another provider here; return failure.
   6986 			 */
   6987 			return (EBUSY);
   6988 		}
   6989 	} else {
   6990 		mutex_enter(&dtrace_provider_lock);
   6991 		mutex_enter(&mod_lock);
   6992 		mutex_enter(&dtrace_lock);
   6993 	}
   6994 
   6995 	/*
   6996 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
   6997 	 * probes, we refuse to let providers slither away, unless this
   6998 	 * provider has already been explicitly invalidated.
   6999 	 */
   7000 	if (!old->dtpv_defunct &&
   7001 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
   7002 	    dtrace_anon.dta_state->dts_necbs > 0))) {
   7003 		if (!self) {
   7004 			mutex_exit(&dtrace_lock);
   7005 			mutex_exit(&mod_lock);
   7006 			mutex_exit(&dtrace_provider_lock);
   7007 		}
   7008 		return (EBUSY);
   7009 	}
   7010 
   7011 	/*
   7012 	 * Attempt to destroy the probes associated with this provider.
   7013 	 */
   7014 	for (i = 0; i < dtrace_nprobes; i++) {
   7015 		if ((probe = dtrace_probes[i]) == NULL)
   7016 			continue;
   7017 
   7018 		if (probe->dtpr_provider != old)
   7019 			continue;
   7020 
   7021 		if (probe->dtpr_ecb == NULL)
   7022 			continue;
   7023 
   7024 		/*
   7025 		 * We have at least one ECB; we can't remove this provider.
   7026 		 */
   7027 		if (!self) {
   7028 			mutex_exit(&dtrace_lock);
   7029 			mutex_exit(&mod_lock);
   7030 			mutex_exit(&dtrace_provider_lock);
   7031 		}
   7032 		return (EBUSY);
   7033 	}
   7034 
   7035 	/*
   7036 	 * All of the probes for this provider are disabled; we can safely
   7037 	 * remove all of them from their hash chains and from the probe array.
   7038 	 */
   7039 	for (i = 0; i < dtrace_nprobes; i++) {
   7040 		if ((probe = dtrace_probes[i]) == NULL)
   7041 			continue;
   7042 
   7043 		if (probe->dtpr_provider != old)
   7044 			continue;
   7045 
   7046 		dtrace_probes[i] = NULL;
   7047 
   7048 		dtrace_hash_remove(dtrace_bymod, probe);
   7049 		dtrace_hash_remove(dtrace_byfunc, probe);
   7050 		dtrace_hash_remove(dtrace_byname, probe);
   7051 
   7052 		if (first == NULL) {
   7053 			first = probe;
   7054 			probe->dtpr_nextmod = NULL;
   7055 		} else {
   7056 			probe->dtpr_nextmod = first;
   7057 			first = probe;
   7058 		}
   7059 	}
   7060 
   7061 	/*
   7062 	 * The provider's probes have been removed from the hash chains and
   7063 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
   7064 	 * everyone has cleared out from any probe array processing.
   7065 	 */
   7066 	dtrace_sync();
   7067 
   7068 	for (probe = first; probe != NULL; probe = first) {
   7069 		first = probe->dtpr_nextmod;
   7070 
   7071 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
   7072 		    probe->dtpr_arg);
   7073 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
   7074 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
   7075 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
   7076 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
   7077 		kmem_free(probe, sizeof (dtrace_probe_t));
   7078 	}
   7079 
   7080 	if ((prev = dtrace_provider) == old) {
   7081 		ASSERT(self || dtrace_devi == NULL);
   7082 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
   7083 		dtrace_provider = old->dtpv_next;
   7084 	} else {
   7085 		while (prev != NULL && prev->dtpv_next != old)
   7086 			prev = prev->dtpv_next;
   7087 
   7088 		if (prev == NULL) {
   7089 			panic("attempt to unregister non-existent "
   7090 			    "dtrace provider %p\n", (void *)id);
   7091 		}
   7092 
   7093 		prev->dtpv_next = old->dtpv_next;
   7094 	}
   7095 
   7096 	if (!self) {
   7097 		mutex_exit(&dtrace_lock);
   7098 		mutex_exit(&mod_lock);
   7099 		mutex_exit(&dtrace_provider_lock);
   7100 	}
   7101 
   7102 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
   7103 	kmem_free(old, sizeof (dtrace_provider_t));
   7104 
   7105 	return (0);
   7106 }
   7107 
   7108 /*
   7109  * Invalidate the specified provider.  All subsequent probe lookups for the
   7110  * specified provider will fail, but its probes will not be removed.
   7111  */
   7112 void
   7113 dtrace_invalidate(dtrace_provider_id_t id)
   7114 {
   7115 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
   7116 
   7117 	ASSERT(pvp->dtpv_pops.dtps_enable !=
   7118 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
   7119 
   7120 	mutex_enter(&dtrace_provider_lock);
   7121 	mutex_enter(&dtrace_lock);
   7122 
   7123 	pvp->dtpv_defunct = 1;
   7124 
   7125 	mutex_exit(&dtrace_lock);
   7126 	mutex_exit(&dtrace_provider_lock);
   7127 }
   7128 
   7129 /*
   7130  * Indicate whether or not DTrace has attached.
   7131  */
   7132 int
   7133 dtrace_attached(void)
   7134 {
   7135 	/*
   7136 	 * dtrace_provider will be non-NULL iff the DTrace driver has
   7137 	 * attached.  (It's non-NULL because DTrace is always itself a
   7138 	 * provider.)
   7139 	 */
   7140 	return (dtrace_provider != NULL);
   7141 }
   7142 
   7143 /*
   7144  * Remove all the unenabled probes for the given provider.  This function is
   7145  * not unlike dtrace_unregister(), except that it doesn't remove the provider
   7146  * -- just as many of its associated probes as it can.
   7147  */
   7148 int
   7149 dtrace_condense(dtrace_provider_id_t id)
   7150 {
   7151 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
   7152 	int i;
   7153 	dtrace_probe_t *probe;
   7154 
   7155 	/*
   7156 	 * Make sure this isn't the dtrace provider itself.
   7157 	 */
   7158 	ASSERT(prov->dtpv_pops.dtps_enable !=
   7159 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
   7160 
   7161 	mutex_enter(&dtrace_provider_lock);
   7162 	mutex_enter(&dtrace_lock);
   7163 
   7164 	/*
   7165 	 * Attempt to destroy the probes associated with this provider.
   7166 	 */
   7167 	for (i = 0; i < dtrace_nprobes; i++) {
   7168 		if ((probe = dtrace_probes[i]) == NULL)
   7169 			continue;
   7170 
   7171 		if (probe->dtpr_provider != prov)
   7172 			continue;
   7173 
   7174 		if (probe->dtpr_ecb != NULL)
   7175 			continue;
   7176 
   7177 		dtrace_probes[i] = NULL;
   7178 
   7179 		dtrace_hash_remove(dtrace_bymod, probe);
   7180 		dtrace_hash_remove(dtrace_byfunc, probe);
   7181 		dtrace_hash_remove(dtrace_byname, probe);
   7182 
   7183 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
   7184 		    probe->dtpr_arg);
   7185 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
   7186 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
   7187 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
   7188 		kmem_free(probe, sizeof (dtrace_probe_t));
   7189 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
   7190 	}
   7191 
   7192 	mutex_exit(&dtrace_lock);
   7193 	mutex_exit(&dtrace_provider_lock);
   7194 
   7195 	return (0);
   7196 }
   7197 
   7198 /*
   7199  * DTrace Probe Management Functions
   7200  *
   7201  * The functions in this section perform the DTrace probe management,
   7202  * including functions to create probes, look-up probes, and call into the
   7203  * providers to request that probes be provided.  Some of these functions are
   7204  * in the Provider-to-Framework API; these functions can be identified by the
   7205  * fact that they are not declared "static".
   7206  */
   7207 
   7208 /*
   7209  * Create a probe with the specified module name, function name, and name.
   7210  */
   7211 dtrace_id_t
   7212 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
   7213     const char *func, const char *name, int aframes, void *arg)
   7214 {
   7215 	dtrace_probe_t *probe, **probes;
   7216 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
   7217 	dtrace_id_t id;
   7218 
   7219 	if (provider == dtrace_provider) {
   7220 		ASSERT(MUTEX_HELD(&dtrace_lock));
   7221 	} else {
   7222 		mutex_enter(&dtrace_lock);
   7223 	}
   7224 
   7225 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
   7226 	    VM_BESTFIT | VM_SLEEP);
   7227 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
   7228 
   7229 	probe->dtpr_id = id;
   7230 	probe->dtpr_gen = dtrace_probegen++;
   7231 	probe->dtpr_mod = dtrace_strdup(mod);
   7232 	probe->dtpr_func = dtrace_strdup(func);
   7233 	probe->dtpr_name = dtrace_strdup(name);
   7234 	probe->dtpr_arg = arg;
   7235 	probe->dtpr_aframes = aframes;
   7236 	probe->dtpr_provider = provider;
   7237 
   7238 	dtrace_hash_add(dtrace_bymod, probe);
   7239 	dtrace_hash_add(dtrace_byfunc, probe);
   7240 	dtrace_hash_add(dtrace_byname, probe);
   7241 
   7242 	if (id - 1 >= dtrace_nprobes) {
   7243 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
   7244 		size_t nsize = osize << 1;
   7245 
   7246 		if (nsize == 0) {
   7247 			ASSERT(osize == 0);
   7248 			ASSERT(dtrace_probes == NULL);
   7249 			nsize = sizeof (dtrace_probe_t *);
   7250 		}
   7251 
   7252 		probes = kmem_zalloc(nsize, KM_SLEEP);
   7253 
   7254 		if (dtrace_probes == NULL) {
   7255 			ASSERT(osize == 0);
   7256 			dtrace_probes = probes;
   7257 			dtrace_nprobes = 1;
   7258 		} else {
   7259 			dtrace_probe_t **oprobes = dtrace_probes;
   7260 
   7261 			bcopy(oprobes, probes, osize);
   7262 			dtrace_membar_producer();
   7263 			dtrace_probes = probes;
   7264 
   7265 			dtrace_sync();
   7266 
   7267 			/*
   7268 			 * All CPUs are now seeing the new probes array; we can
   7269 			 * safely free the old array.
   7270 			 */
   7271 			kmem_free(oprobes, osize);
   7272 			dtrace_nprobes <<= 1;
   7273 		}
   7274 
   7275 		ASSERT(id - 1 < dtrace_nprobes);
   7276 	}
   7277 
   7278 	ASSERT(dtrace_probes[id - 1] == NULL);
   7279 	dtrace_probes[id - 1] = probe;
   7280 
   7281 	if (provider != dtrace_provider)
   7282 		mutex_exit(&dtrace_lock);
   7283 
   7284 	return (id);
   7285 }
   7286 
   7287 static dtrace_probe_t *
   7288 dtrace_probe_lookup_id(dtrace_id_t id)
   7289 {
   7290 	ASSERT(MUTEX_HELD(&dtrace_lock));
   7291 
   7292 	if (id == 0 || id > dtrace_nprobes)
   7293 		return (NULL);
   7294 
   7295 	return (dtrace_probes[id - 1]);
   7296 }
   7297 
   7298 static int
   7299 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
   7300 {
   7301 	*((dtrace_id_t *)arg) = probe->dtpr_id;
   7302 
   7303 	return (DTRACE_MATCH_DONE);
   7304 }
   7305 
   7306 /*
   7307  * Look up a probe based on provider and one or more of module name, function
   7308  * name and probe name.
   7309  */
   7310 dtrace_id_t
   7311 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
   7312     const char *func, const char *name)
   7313 {
   7314 	dtrace_probekey_t pkey;
   7315 	dtrace_id_t id;
   7316 	int match;
   7317 
   7318 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
   7319 	pkey.dtpk_pmatch = &dtrace_match_string;
   7320 	pkey.dtpk_mod = mod;
   7321 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
   7322 	pkey.dtpk_func = func;
   7323 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
   7324 	pkey.dtpk_name = name;
   7325 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
   7326 	pkey.dtpk_id = DTRACE_IDNONE;
   7327 
   7328 	mutex_enter(&dtrace_lock);
   7329 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
   7330 	    dtrace_probe_lookup_match, &id);
   7331 	mutex_exit(&dtrace_lock);
   7332 
   7333 	ASSERT(match == 1 || match == 0);
   7334 	return (match ? id : 0);
   7335 }
   7336 
   7337 /*
   7338  * Returns the probe argument associated with the specified probe.
   7339  */
   7340 void *
   7341 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
   7342 {
   7343 	dtrace_probe_t *probe;
   7344 	void *rval = NULL;
   7345 
   7346 	mutex_enter(&dtrace_lock);
   7347 
   7348 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
   7349 	    probe->dtpr_provider == (dtrace_provider_t *)id)
   7350 		rval = probe->dtpr_arg;
   7351 
   7352 	mutex_exit(&dtrace_lock);
   7353 
   7354 	return (rval);
   7355 }
   7356 
   7357 /*
   7358  * Copy a probe into a probe description.
   7359  */
   7360 static void
   7361 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
   7362 {
   7363 	bzero(pdp, sizeof (dtrace_probedesc_t));
   7364 	pdp->dtpd_id = prp->dtpr_id;
   7365 
   7366 	(void) strncpy(pdp->dtpd_provider,
   7367 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
   7368 
   7369 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
   7370 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
   7371 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
   7372 }
   7373 
   7374 /*
   7375  * Called to indicate that a probe -- or probes -- should be provided by a
   7376  * specfied provider.  If the specified description is NULL, the provider will
   7377  * be told to provide all of its probes.  (This is done whenever a new
   7378  * consumer comes along, or whenever a retained enabling is to be matched.) If
   7379  * the specified description is non-NULL, the provider is given the
   7380  * opportunity to dynamically provide the specified probe, allowing providers
   7381  * to support the creation of probes on-the-fly.  (So-called _autocreated_
   7382  * probes.)  If the provider is NULL, the operations will be applied to all
   7383  * providers; if the provider is non-NULL the operations will only be applied
   7384  * to the specified provider.  The dtrace_provider_lock must be held, and the
   7385  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
   7386  * will need to grab the dtrace_lock when it reenters the framework through
   7387  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
   7388  */
   7389 static void
   7390 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
   7391 {
   7392 	struct modctl *ctl;
   7393 	int all = 0;
   7394 
   7395 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
   7396 
   7397 	if (prv == NULL) {
   7398 		all = 1;
   7399 		prv = dtrace_provider;
   7400 	}
   7401 
   7402 	do {
   7403 		/*
   7404 		 * First, call the blanket provide operation.
   7405 		 */
   7406 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
   7407 
   7408 		/*
   7409 		 * Now call the per-module provide operation.  We will grab
   7410 		 * mod_lock to prevent the list from being modified.  Note
   7411 		 * that this also prevents the mod_busy bits from changing.
   7412 		 * (mod_busy can only be changed with mod_lock held.)
   7413 		 */
   7414 		mutex_enter(&mod_lock);
   7415 
   7416 		ctl = &modules;
   7417 		do {
   7418 			if (ctl->mod_busy || ctl->mod_mp == NULL)
   7419 				continue;
   7420 
   7421 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
   7422 
   7423 		} while ((ctl = ctl->mod_next) != &modules);
   7424 
   7425 		mutex_exit(&mod_lock);
   7426 	} while (all && (prv = prv->dtpv_next) != NULL);
   7427 }
   7428 
   7429 /*
   7430  * Iterate over each probe, and call the Framework-to-Provider API function
   7431  * denoted by offs.
   7432  */
   7433 static void
   7434 dtrace_probe_foreach(uintptr_t offs)
   7435 {
   7436 	dtrace_provider_t *prov;
   7437 	void (*func)(void *, dtrace_id_t, void *);
   7438 	dtrace_probe_t *probe;
   7439 	dtrace_icookie_t cookie;
   7440 	int i;
   7441 
   7442 	/*
   7443 	 * We disable interrupts to walk through the probe array.  This is
   7444 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
   7445 	 * won't see stale data.
   7446 	 */
   7447 	cookie = dtrace_interrupt_disable();
   7448 
   7449 	for (i = 0; i < dtrace_nprobes; i++) {
   7450 		if ((probe = dtrace_probes[i]) == NULL)
   7451 			continue;
   7452 
   7453 		if (probe->dtpr_ecb == NULL) {
   7454 			/*
   7455 			 * This probe isn't enabled -- don't call the function.
   7456 			 */
   7457 			continue;
   7458 		}
   7459 
   7460 		prov = probe->dtpr_provider;
   7461 		func = *((void(**)(void *, dtrace_id_t, void *))
   7462 		    ((uintptr_t)&prov->dtpv_pops + offs));
   7463 
   7464 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
   7465 	}
   7466 
   7467 	dtrace_interrupt_enable(cookie);
   7468 }
   7469 
   7470 static int
   7471 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
   7472 {
   7473 	dtrace_probekey_t pkey;
   7474 	uint32_t priv;
   7475 	uid_t uid;
   7476 	zoneid_t zoneid;
   7477 
   7478 	ASSERT(MUTEX_HELD(&dtrace_lock));
   7479 	dtrace_ecb_create_cache = NULL;
   7480 
   7481 	if (desc == NULL) {
   7482 		/*
   7483 		 * If we're passed a NULL description, we're being asked to
   7484 		 * create an ECB with a NULL probe.
   7485 		 */
   7486 		(void) dtrace_ecb_create_enable(NULL, enab);
   7487 		return (0);
   7488 	}
   7489 
   7490 	dtrace_probekey(desc, &pkey);
   7491 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
   7492 	    &priv, &uid, &zoneid);
   7493 
   7494 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
   7495 	    enab));
   7496 }
   7497 
   7498 /*
   7499  * DTrace Helper Provider Functions
   7500  */
   7501 static void
   7502 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
   7503 {
   7504 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
   7505 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
   7506 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
   7507 }
   7508 
   7509 static void
   7510 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
   7511     const dof_provider_t *dofprov, char *strtab)
   7512 {
   7513 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
   7514 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
   7515 	    dofprov->dofpv_provattr);
   7516 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
   7517 	    dofprov->dofpv_modattr);
   7518 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
   7519 	    dofprov->dofpv_funcattr);
   7520 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
   7521 	    dofprov->dofpv_nameattr);
   7522 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
   7523 	    dofprov->dofpv_argsattr);
   7524 }
   7525 
   7526 static void
   7527 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
   7528 {
   7529 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
   7530 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
   7531 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
   7532 	dof_provider_t *provider;
   7533 	dof_probe_t *probe;
   7534 	uint32_t *off, *enoff;
   7535 	uint8_t *arg;
   7536 	char *strtab;
   7537 	uint_t i, nprobes;
   7538 	dtrace_helper_provdesc_t dhpv;
   7539 	dtrace_helper_probedesc_t dhpb;
   7540 	dtrace_meta_t *meta = dtrace_meta_pid;
   7541 	dtrace_mops_t *mops = &meta->dtm_mops;
   7542 	void *parg;
   7543 
   7544 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
   7545 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
   7546 	    provider->dofpv_strtab * dof->dofh_secsize);
   7547 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
   7548 	    provider->dofpv_probes * dof->dofh_secsize);
   7549 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
   7550 	    provider->dofpv_prargs * dof->dofh_secsize);
   7551 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
   7552 	    provider->dofpv_proffs * dof->dofh_secsize);
   7553 
   7554 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
   7555 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
   7556 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
   7557 	enoff = NULL;
   7558 
   7559 	/*
   7560 	 * See dtrace_helper_provider_validate().
   7561 	 */
   7562 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
   7563 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
   7564 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
   7565 		    provider->dofpv_prenoffs * dof->dofh_secsize);
   7566 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
   7567 	}
   7568 
   7569 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
   7570 
   7571 	/*
   7572 	 * Create the provider.
   7573 	 */
   7574 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
   7575 
   7576 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
   7577 		return;
   7578 
   7579 	meta->dtm_count++;
   7580 
   7581 	/*
   7582 	 * Create the probes.
   7583 	 */
   7584 	for (i = 0; i < nprobes; i++) {
   7585 		probe = (dof_probe_t *)(uintptr_t)(daddr +
   7586 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
   7587 
   7588 		dhpb.dthpb_mod = dhp->dofhp_mod;
   7589 		dhpb.dthpb_func = strtab + probe->dofpr_func;
   7590 		dhpb.dthpb_name = strtab + probe->dofpr_name;
   7591 		dhpb.dthpb_base = probe->dofpr_addr;
   7592 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
   7593 		dhpb.dthpb_noffs = probe->dofpr_noffs;
   7594 		if (enoff != NULL) {
   7595 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
   7596 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
   7597 		} else {
   7598 			dhpb.dthpb_enoffs = NULL;
   7599 			dhpb.dthpb_nenoffs = 0;
   7600 		}
   7601 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
   7602 		dhpb.dthpb_nargc = probe->dofpr_nargc;
   7603 		dhpb.dthpb_xargc = probe->dofpr_xargc;
   7604 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
   7605 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
   7606 
   7607 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
   7608 	}
   7609 }
   7610 
   7611 static void
   7612 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
   7613 {
   7614 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
   7615 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
   7616 	int i;
   7617 
   7618 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
   7619 
   7620 	for (i = 0; i < dof->dofh_secnum; i++) {
   7621 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
   7622 		    dof->dofh_secoff + i * dof->dofh_secsize);
   7623 
   7624 		if (sec->dofs_type != DOF_SECT_PROVIDER)
   7625 			continue;
   7626 
   7627 		dtrace_helper_provide_one(dhp, sec, pid);
   7628 	}
   7629 
   7630 	/*
   7631 	 * We may have just created probes, so we must now rematch against
   7632 	 * any retained enablings.  Note that this call will acquire both
   7633 	 * cpu_lock and dtrace_lock; the fact that we are holding
   7634 	 * dtrace_meta_lock now is what defines the ordering with respect to
   7635 	 * these three locks.
   7636 	 */
   7637 	dtrace_enabling_matchall();
   7638 }
   7639 
   7640 static void
   7641 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
   7642 {
   7643 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
   7644 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
   7645 	dof_sec_t *str_sec;
   7646 	dof_provider_t *provider;
   7647 	char *strtab;
   7648 	dtrace_helper_provdesc_t dhpv;
   7649 	dtrace_meta_t *meta = dtrace_meta_pid;
   7650 	dtrace_mops_t *mops = &meta->dtm_mops;
   7651 
   7652 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
   7653 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
   7654 	    provider->dofpv_strtab * dof->dofh_secsize);
   7655 
   7656 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
   7657 
   7658 	/*
   7659 	 * Create the provider.
   7660 	 */
   7661 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
   7662 
   7663 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
   7664 
   7665 	meta->dtm_count--;
   7666 }
   7667 
   7668 static void
   7669 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
   7670 {
   7671 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
   7672 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
   7673 	int i;
   7674 
   7675 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
   7676 
   7677 	for (i = 0; i < dof->dofh_secnum; i++) {
   7678 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
   7679 		    dof->dofh_secoff + i * dof->dofh_secsize);
   7680 
   7681 		if (sec->dofs_type != DOF_SECT_PROVIDER)
   7682 			continue;
   7683 
   7684 		dtrace_helper_provider_remove_one(dhp, sec, pid);
   7685 	}
   7686 }
   7687 
   7688 /*
   7689  * DTrace Meta Provider-to-Framework API Functions
   7690  *
   7691  * These functions implement the Meta Provider-to-Framework API, as described
   7692  * in <sys/dtrace.h>.
   7693  */
   7694 int
   7695 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
   7696     dtrace_meta_provider_id_t *idp)
   7697 {
   7698 	dtrace_meta_t *meta;
   7699 	dtrace_helpers_t *help, *next;
   7700 	int i;
   7701 
   7702 	*idp = DTRACE_METAPROVNONE;
   7703 
   7704 	/*
   7705 	 * We strictly don't need the name, but we hold onto it for
   7706 	 * debuggability. All hail error queues!
   7707 	 */
   7708 	if (name == NULL) {
   7709 		cmn_err(CE_WARN, "failed to register meta-provider: "
   7710 		    "invalid name");
   7711 		return (EINVAL);
   7712 	}
   7713 
   7714 	if (mops == NULL ||
   7715 	    mops->dtms_create_probe == NULL ||
   7716 	    mops->dtms_provide_pid == NULL ||
   7717 	    mops->dtms_remove_pid == NULL) {
   7718 		cmn_err(CE_WARN, "failed to register meta-register %s: "
   7719 		    "invalid ops", name);
   7720 		return (EINVAL);
   7721 	}
   7722 
   7723 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
   7724 	meta->dtm_mops = *mops;
   7725 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
   7726 	(void) strcpy(meta->dtm_name, name);
   7727 	meta->dtm_arg = arg;
   7728 
   7729 	mutex_enter(&dtrace_meta_lock);
   7730 	mutex_enter(&dtrace_lock);
   7731 
   7732 	if (dtrace_meta_pid != NULL) {
   7733 		mutex_exit(&dtrace_lock);
   7734 		mutex_exit(&dtrace_meta_lock);
   7735 		cmn_err(CE_WARN, "failed to register meta-register %s: "
   7736 		    "user-land meta-provider exists", name);
   7737 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
   7738 		kmem_free(meta, sizeof (dtrace_meta_t));
   7739 		return (EINVAL);
   7740 	}
   7741 
   7742 	dtrace_meta_pid = meta;
   7743 	*idp = (dtrace_meta_provider_id_t)meta;
   7744 
   7745 	/*
   7746 	 * If there are providers and probes ready to go, pass them
   7747 	 * off to the new meta provider now.
   7748 	 */
   7749 
   7750 	help = dtrace_deferred_pid;
   7751 	dtrace_deferred_pid = NULL;
   7752 
   7753 	mutex_exit(&dtrace_lock);
   7754 
   7755 	while (help != NULL) {
   7756 		for (i = 0; i < help->dthps_nprovs; i++) {
   7757 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
   7758 			    help->dthps_pid);
   7759 		}
   7760 
   7761 		next = help->dthps_next;
   7762 		help->dthps_next = NULL;
   7763 		help->dthps_prev = NULL;
   7764 		help->dthps_deferred = 0;
   7765 		help = next;
   7766 	}
   7767 
   7768 	mutex_exit(&dtrace_meta_lock);
   7769 
   7770 	return (0);
   7771 }
   7772 
   7773 int
   7774 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
   7775 {
   7776 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
   7777 
   7778 	mutex_enter(&dtrace_meta_lock);
   7779 	mutex_enter(&dtrace_lock);
   7780 
   7781 	if (old == dtrace_meta_pid) {
   7782 		pp = &dtrace_meta_pid;
   7783 	} else {
   7784 		panic("attempt to unregister non-existent "
   7785 		    "dtrace meta-provider %p\n", (void *)old);
   7786 	}
   7787 
   7788 	if (old->dtm_count != 0) {
   7789 		mutex_exit(&dtrace_lock);
   7790 		mutex_exit(&dtrace_meta_lock);
   7791 		return (EBUSY);
   7792 	}
   7793 
   7794 	*pp = NULL;
   7795 
   7796 	mutex_exit(&dtrace_lock);
   7797 	mutex_exit(&dtrace_meta_lock);
   7798 
   7799 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
   7800 	kmem_free(old, sizeof (dtrace_meta_t));
   7801 
   7802 	return (0);
   7803 }
   7804 
   7805 
   7806 /*
   7807  * DTrace DIF Object Functions
   7808  */
   7809 static int
   7810 dtrace_difo_err(uint_t pc, const char *format, ...)
   7811 {
   7812 	if (dtrace_err_verbose) {
   7813 		va_list alist;
   7814 
   7815 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
   7816 		va_start(alist, format);
   7817 		(void) vuprintf(format, alist);
   7818 		va_end(alist);
   7819 	}
   7820 
   7821 #ifdef DTRACE_ERRDEBUG
   7822 	dtrace_errdebug(format);
   7823 #endif
   7824 	return (1);
   7825 }
   7826 
   7827 /*
   7828  * Validate a DTrace DIF object by checking the IR instructions.  The following
   7829  * rules are currently enforced by dtrace_difo_validate():
   7830  *
   7831  * 1. Each instruction must have a valid opcode
   7832  * 2. Each register, string, variable, or subroutine reference must be valid
   7833  * 3. No instruction can modify register %r0 (must be zero)
   7834  * 4. All instruction reserved bits must be set to zero
   7835  * 5. The last instruction must be a "ret" instruction
   7836  * 6. All branch targets must reference a valid instruction _after_ the branch
   7837  */
   7838 static int
   7839 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
   7840     cred_t *cr)
   7841 {
   7842 	int err = 0, i;
   7843 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
   7844 	int kcheckload;
   7845 	uint_t pc;
   7846 
   7847 	kcheckload = cr == NULL ||
   7848 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
   7849 
   7850 	dp->dtdo_destructive = 0;
   7851 
   7852 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
   7853 		dif_instr_t instr = dp->dtdo_buf[pc];
   7854 
   7855 		uint_t r1 = DIF_INSTR_R1(instr);
   7856 		uint_t r2 = DIF_INSTR_R2(instr);
   7857 		uint_t rd = DIF_INSTR_RD(instr);
   7858 		uint_t rs = DIF_INSTR_RS(instr);
   7859 		uint_t label = DIF_INSTR_LABEL(instr);
   7860 		uint_t v = DIF_INSTR_VAR(instr);
   7861 		uint_t subr = DIF_INSTR_SUBR(instr);
   7862 		uint_t type = DIF_INSTR_TYPE(instr);
   7863 		uint_t op = DIF_INSTR_OP(instr);
   7864 
   7865 		switch (op) {
   7866 		case DIF_OP_OR:
   7867 		case DIF_OP_XOR:
   7868 		case DIF_OP_AND:
   7869 		case DIF_OP_SLL:
   7870 		case DIF_OP_SRL:
   7871 		case DIF_OP_SRA:
   7872 		case DIF_OP_SUB:
   7873 		case DIF_OP_ADD:
   7874 		case DIF_OP_MUL:
   7875 		case DIF_OP_SDIV:
   7876 		case DIF_OP_UDIV:
   7877 		case DIF_OP_SREM:
   7878 		case DIF_OP_UREM:
   7879 		case DIF_OP_COPYS:
   7880 			if (r1 >= nregs)
   7881 				err += efunc(pc, "invalid register %u\n", r1);
   7882 			if (r2 >= nregs)
   7883 				err += efunc(pc, "invalid register %u\n", r2);
   7884 			if (rd >= nregs)
   7885 				err += efunc(pc, "invalid register %u\n", rd);
   7886 			if (rd == 0)
   7887 				err += efunc(pc, "cannot write to %r0\n");
   7888 			break;
   7889 		case DIF_OP_NOT:
   7890 		case DIF_OP_MOV:
   7891 		case DIF_OP_ALLOCS:
   7892 			if (r1 >= nregs)
   7893 				err += efunc(pc, "invalid register %u\n", r1);
   7894 			if (r2 != 0)
   7895 				err += efunc(pc, "non-zero reserved bits\n");
   7896 			if (rd >= nregs)
   7897 				err += efunc(pc, "invalid register %u\n", rd);
   7898 			if (rd == 0)
   7899 				err += efunc(pc, "cannot write to %r0\n");
   7900 			break;
   7901 		case DIF_OP_LDSB:
   7902 		case DIF_OP_LDSH:
   7903 		case DIF_OP_LDSW:
   7904 		case DIF_OP_LDUB:
   7905 		case DIF_OP_LDUH:
   7906 		case DIF_OP_LDUW:
   7907 		case DIF_OP_LDX:
   7908 			if (r1 >= nregs)
   7909 				err += efunc(pc, "invalid register %u\n", r1);
   7910 			if (r2 != 0)
   7911 				err += efunc(pc, "non-zero reserved bits\n");
   7912 			if (rd >= nregs)
   7913 				err += efunc(pc, "invalid register %u\n", rd);
   7914 			if (rd == 0)
   7915 				err += efunc(pc, "cannot write to %r0\n");
   7916 			if (kcheckload)
   7917 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
   7918 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
   7919 			break;
   7920 		case DIF_OP_RLDSB:
   7921 		case DIF_OP_RLDSH:
   7922 		case DIF_OP_RLDSW:
   7923 		case DIF_OP_RLDUB:
   7924 		case DIF_OP_RLDUH:
   7925 		case DIF_OP_RLDUW:
   7926 		case DIF_OP_RLDX:
   7927 			if (r1 >= nregs)
   7928 				err += efunc(pc, "invalid register %u\n", r1);
   7929 			if (r2 != 0)
   7930 				err += efunc(pc, "non-zero reserved bits\n");
   7931 			if (rd >= nregs)
   7932 				err += efunc(pc, "invalid register %u\n", rd);
   7933 			if (rd == 0)
   7934 				err += efunc(pc, "cannot write to %r0\n");
   7935 			break;
   7936 		case DIF_OP_ULDSB:
   7937 		case DIF_OP_ULDSH:
   7938 		case DIF_OP_ULDSW:
   7939 		case DIF_OP_ULDUB:
   7940 		case DIF_OP_ULDUH:
   7941 		case DIF_OP_ULDUW:
   7942 		case DIF_OP_ULDX:
   7943 			if (r1 >= nregs)
   7944 				err += efunc(pc, "invalid register %u\n", r1);
   7945 			if (r2 != 0)
   7946 				err += efunc(pc, "non-zero reserved bits\n");
   7947 			if (rd >= nregs)
   7948 				err += efunc(pc, "invalid register %u\n", rd);
   7949 			if (rd == 0)
   7950 				err += efunc(pc, "cannot write to %r0\n");
   7951 			break;
   7952 		case DIF_OP_STB:
   7953 		case DIF_OP_STH:
   7954 		case DIF_OP_STW:
   7955 		case DIF_OP_STX:
   7956 			if (r1 >= nregs)
   7957 				err += efunc(pc, "invalid register %u\n", r1);
   7958 			if (r2 != 0)
   7959 				err += efunc(pc, "non-zero reserved bits\n");
   7960 			if (rd >= nregs)
   7961 				err += efunc(pc, "invalid register %u\n", rd);
   7962 			if (rd == 0)
   7963 				err += efunc(pc, "cannot write to 0 address\n");
   7964 			break;
   7965 		case DIF_OP_CMP:
   7966 		case DIF_OP_SCMP:
   7967 			if (r1 >= nregs)
   7968 				err += efunc(pc, "invalid register %u\n", r1);
   7969 			if (r2 >= nregs)
   7970 				err += efunc(pc, "invalid register %u\n", r2);
   7971 			if (rd != 0)
   7972 				err += efunc(pc, "non-zero reserved bits\n");
   7973 			break;
   7974 		case DIF_OP_TST:
   7975 			if (r1 >= nregs)
   7976 				err += efunc(pc, "invalid register %u\n", r1);
   7977 			if (r2 != 0 || rd != 0)
   7978 				err += efunc(pc, "non-zero reserved bits\n");
   7979 			break;
   7980 		case DIF_OP_BA:
   7981 		case DIF_OP_BE:
   7982 		case DIF_OP_BNE:
   7983 		case DIF_OP_BG:
   7984 		case DIF_OP_BGU:
   7985 		case DIF_OP_BGE:
   7986 		case DIF_OP_BGEU:
   7987 		case DIF_OP_BL:
   7988 		case DIF_OP_BLU:
   7989 		case DIF_OP_BLE:
   7990 		case DIF_OP_BLEU:
   7991 			if (label >= dp->dtdo_len) {
   7992 				err += efunc(pc, "invalid branch target %u\n",
   7993 				    label);
   7994 			}
   7995 			if (label <= pc) {
   7996 				err += efunc(pc, "backward branch to %u\n",
   7997 				    label);
   7998 			}
   7999 			break;
   8000 		case DIF_OP_RET:
   8001 			if (r1 != 0 || r2 != 0)
   8002 				err += efunc(pc, "non-zero reserved bits\n");
   8003 			if (rd >= nregs)
   8004 				err += efunc(pc, "invalid register %u\n", rd);
   8005 			break;
   8006 		case DIF_OP_NOP:
   8007 		case DIF_OP_POPTS:
   8008 		case DIF_OP_FLUSHTS:
   8009 			if (r1 != 0 || r2 != 0 || rd != 0)
   8010 				err += efunc(pc, "non-zero reserved bits\n");
   8011 			break;
   8012 		case DIF_OP_SETX:
   8013 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
   8014 				err += efunc(pc, "invalid integer ref %u\n",
   8015 				    DIF_INSTR_INTEGER(instr));
   8016 			}
   8017 			if (rd >= nregs)
   8018 				err += efunc(pc, "invalid register %u\n", rd);
   8019 			if (rd == 0)
   8020 				err += efunc(pc, "cannot write to %r0\n");
   8021 			break;
   8022 		case DIF_OP_SETS:
   8023 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
   8024 				err += efunc(pc, "invalid string ref %u\n",
   8025 				    DIF_INSTR_STRING(instr));
   8026 			}
   8027 			if (rd >= nregs)
   8028 				err += efunc(pc, "invalid register %u\n", rd);
   8029 			if (rd == 0)
   8030 				err += efunc(pc, "cannot write to %r0\n");
   8031 			break;
   8032 		case DIF_OP_LDGA:
   8033 		case DIF_OP_LDTA:
   8034 			if (r1 > DIF_VAR_ARRAY_MAX)
   8035 				err += efunc(pc, "invalid array %u\n", r1);
   8036 			if (r2 >= nregs)
   8037 				err += efunc(pc, "invalid register %u\n", r2);
   8038 			if (rd >= nregs)
   8039 				err += efunc(pc, "invalid register %u\n", rd);
   8040 			if (rd == 0)
   8041 				err += efunc(pc, "cannot write to %r0\n");
   8042 			break;
   8043 		case DIF_OP_LDGS:
   8044 		case DIF_OP_LDTS:
   8045 		case DIF_OP_LDLS:
   8046 		case DIF_OP_LDGAA:
   8047 		case DIF_OP_LDTAA:
   8048 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
   8049 				err += efunc(pc, "invalid variable %u\n", v);
   8050 			if (rd >= nregs)
   8051 				err += efunc(pc, "invalid register %u\n", rd);
   8052 			if (rd == 0)
   8053 				err += efunc(pc, "cannot write to %r0\n");
   8054 			break;
   8055 		case DIF_OP_STGS:
   8056 		case DIF_OP_STTS:
   8057 		case DIF_OP_STLS:
   8058 		case DIF_OP_STGAA:
   8059 		case DIF_OP_STTAA:
   8060 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
   8061 				err += efunc(pc, "invalid variable %u\n", v);
   8062 			if (rs >= nregs)
   8063 				err += efunc(pc, "invalid register %u\n", rd);
   8064 			break;
   8065 		case DIF_OP_CALL:
   8066 			if (subr > DIF_SUBR_MAX)
   8067 				err += efunc(pc, "invalid subr %u\n", subr);
   8068 			if (rd >= nregs)
   8069 				err += efunc(pc, "invalid register %u\n", rd);
   8070 			if (rd == 0)
   8071 				err += efunc(pc, "cannot write to %r0\n");
   8072 
   8073 			if (subr == DIF_SUBR_COPYOUT ||
   8074 			    subr == DIF_SUBR_COPYOUTSTR) {
   8075 				dp->dtdo_destructive = 1;
   8076 			}
   8077 			break;
   8078 		case DIF_OP_PUSHTR:
   8079 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
   8080 				err += efunc(pc, "invalid ref type %u\n", type);
   8081 			if (r2 >= nregs)
   8082 				err += efunc(pc, "invalid register %u\n", r2);
   8083 			if (rs >= nregs)
   8084 				err += efunc(pc, "invalid register %u\n", rs);
   8085 			break;
   8086 		case DIF_OP_PUSHTV:
   8087 			if (type != DIF_TYPE_CTF)
   8088 				err += efunc(pc, "invalid val type %u\n", type);
   8089 			if (r2 >= nregs)
   8090 				err += efunc(pc, "invalid register %u\n", r2);
   8091 			if (rs >= nregs)
   8092 				err += efunc(pc, "invalid register %u\n", rs);
   8093 			break;
   8094 		default:
   8095 			err += efunc(pc, "invalid opcode %u\n",
   8096 			    DIF_INSTR_OP(instr));
   8097 		}
   8098 	}
   8099 
   8100 	if (dp->dtdo_len != 0 &&
   8101 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
   8102 		err += efunc(dp->dtdo_len - 1,
   8103 		    "expected 'ret' as last DIF instruction\n");
   8104 	}
   8105 
   8106 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
   8107 		/*
   8108 		 * If we're not returning by reference, the size must be either
   8109 		 * 0 or the size of one of the base types.
   8110 		 */
   8111 		switch (dp->dtdo_rtype.dtdt_size) {
   8112 		case 0:
   8113 		case sizeof (uint8_t):
   8114 		case sizeof (uint16_t):
   8115 		case sizeof (uint32_t):
   8116 		case sizeof (uint64_t):
   8117 			break;
   8118 
   8119 		default:
   8120 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
   8121 		}
   8122 	}
   8123 
   8124 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
   8125 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
   8126 		dtrace_diftype_t *vt, *et;
   8127 		uint_t id, ndx;
   8128 
   8129 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
   8130 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
   8131 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
   8132 			err += efunc(i, "unrecognized variable scope %d\n",
   8133 			    v->dtdv_scope);
   8134 			break;
   8135 		}
   8136 
   8137 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
   8138 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
   8139 			err += efunc(i, "unrecognized variable type %d\n",
   8140 			    v->dtdv_kind);
   8141 			break;
   8142 		}
   8143 
   8144 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
   8145 			err += efunc(i, "%d exceeds variable id limit\n", id);
   8146 			break;
   8147 		}
   8148 
   8149 		if (id < DIF_VAR_OTHER_UBASE)
   8150 			continue;
   8151 
   8152 		/*
   8153 		 * For user-defined variables, we need to check that this
   8154 		 * definition is identical to any previous definition that we
   8155 		 * encountered.
   8156 		 */
   8157 		ndx = id - DIF_VAR_OTHER_UBASE;
   8158 
   8159 		switch (v->dtdv_scope) {
   8160 		case DIFV_SCOPE_GLOBAL:
   8161 			if (ndx < vstate->dtvs_nglobals) {
   8162 				dtrace_statvar_t *svar;
   8163 
   8164 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
   8165 					existing = &svar->dtsv_var;
   8166 			}
   8167 
   8168 			break;
   8169 
   8170 		case DIFV_SCOPE_THREAD:
   8171 			if (ndx < vstate->dtvs_ntlocals)
   8172 				existing = &vstate->dtvs_tlocals[ndx];
   8173 			break;
   8174 
   8175 		case DIFV_SCOPE_LOCAL:
   8176 			if (ndx < vstate->dtvs_nlocals) {
   8177 				dtrace_statvar_t *svar;
   8178 
   8179 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
   8180 					existing = &svar->dtsv_var;
   8181 			}
   8182 
   8183 			break;
   8184 		}
   8185 
   8186 		vt = &v->dtdv_type;
   8187 
   8188 		if (vt->dtdt_flags & DIF_TF_BYREF) {
   8189 			if (vt->dtdt_size == 0) {
   8190 				err += efunc(i, "zero-sized variable\n");
   8191 				break;
   8192 			}
   8193 
   8194 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
   8195 			    vt->dtdt_size > dtrace_global_maxsize) {
   8196 				err += efunc(i, "oversized by-ref global\n");
   8197 				break;
   8198 			}
   8199 		}
   8200 
   8201 		if (existing == NULL || existing->dtdv_id == 0)
   8202 			continue;
   8203 
   8204 		ASSERT(existing->dtdv_id == v->dtdv_id);
   8205 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
   8206 
   8207 		if (existing->dtdv_kind != v->dtdv_kind)
   8208 			err += efunc(i, "%d changed variable kind\n", id);
   8209 
   8210 		et = &existing->dtdv_type;
   8211 
   8212 		if (vt->dtdt_flags != et->dtdt_flags) {
   8213 			err += efunc(i, "%d changed variable type flags\n", id);
   8214 			break;
   8215 		}
   8216 
   8217 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
   8218 			err += efunc(i, "%d changed variable type size\n", id);
   8219 			break;
   8220 		}
   8221 	}
   8222 
   8223 	return (err);
   8224 }
   8225 
   8226 /*
   8227  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
   8228  * are much more constrained than normal DIFOs.  Specifically, they may
   8229  * not:
   8230  *
   8231  * 1. Make calls to subroutines other than copyin(), copyinstr() or
   8232  *    miscellaneous string routines
   8233  * 2. Access DTrace variables other than the args[] array, and the
   8234  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
   8235  * 3. Have thread-local variables.
   8236  * 4. Have dynamic variables.
   8237  */
   8238 static int
   8239 dtrace_difo_validate_helper(dtrace_difo_t *dp)
   8240 {
   8241 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
   8242 	int err = 0;
   8243 	uint_t pc;
   8244 
   8245 	for (pc = 0; pc < dp->dtdo_len; pc++) {
   8246 		dif_instr_t instr = dp->dtdo_buf[pc];
   8247 
   8248 		uint_t v = DIF_INSTR_VAR(instr);
   8249 		uint_t subr = DIF_INSTR_SUBR(instr);
   8250 		uint_t op = DIF_INSTR_OP(instr);
   8251 
   8252 		switch (op) {
   8253 		case DIF_OP_OR:
   8254 		case DIF_OP_XOR:
   8255 		case DIF_OP_AND:
   8256 		case DIF_OP_SLL:
   8257 		case DIF_OP_SRL:
   8258 		case DIF_OP_SRA:
   8259 		case DIF_OP_SUB:
   8260 		case DIF_OP_ADD:
   8261 		case DIF_OP_MUL:
   8262 		case DIF_OP_SDIV:
   8263 		case DIF_OP_UDIV:
   8264 		case DIF_OP_SREM:
   8265 		case DIF_OP_UREM:
   8266 		case DIF_OP_COPYS:
   8267 		case DIF_OP_NOT:
   8268 		case DIF_OP_MOV:
   8269 		case DIF_OP_RLDSB:
   8270 		case DIF_OP_RLDSH:
   8271 		case DIF_OP_RLDSW:
   8272 		case DIF_OP_RLDUB:
   8273 		case DIF_OP_RLDUH:
   8274 		case DIF_OP_RLDUW:
   8275 		case DIF_OP_RLDX:
   8276 		case DIF_OP_ULDSB:
   8277 		case DIF_OP_ULDSH:
   8278 		case DIF_OP_ULDSW:
   8279 		case DIF_OP_ULDUB:
   8280 		case DIF_OP_ULDUH:
   8281 		case DIF_OP_ULDUW:
   8282 		case DIF_OP_ULDX:
   8283 		case DIF_OP_STB:
   8284 		case DIF_OP_STH:
   8285 		case DIF_OP_STW:
   8286 		case DIF_OP_STX:
   8287 		case DIF_OP_ALLOCS:
   8288 		case DIF_OP_CMP:
   8289 		case DIF_OP_SCMP:
   8290 		case DIF_OP_TST:
   8291 		case DIF_OP_BA:
   8292 		case DIF_OP_BE:
   8293 		case DIF_OP_BNE:
   8294 		case DIF_OP_BG:
   8295 		case DIF_OP_BGU:
   8296 		case DIF_OP_BGE:
   8297 		case DIF_OP_BGEU:
   8298 		case DIF_OP_BL:
   8299 		case DIF_OP_BLU:
   8300 		case DIF_OP_BLE:
   8301 		case DIF_OP_BLEU:
   8302 		case DIF_OP_RET:
   8303 		case DIF_OP_NOP:
   8304 		case DIF_OP_POPTS:
   8305 		case DIF_OP_FLUSHTS:
   8306 		case DIF_OP_SETX:
   8307 		case DIF_OP_SETS:
   8308 		case DIF_OP_LDGA:
   8309 		case DIF_OP_LDLS:
   8310 		case DIF_OP_STGS:
   8311 		case DIF_OP_STLS:
   8312 		case DIF_OP_PUSHTR:
   8313 		case DIF_OP_PUSHTV:
   8314 			break;
   8315 
   8316 		case DIF_OP_LDGS:
   8317 			if (v >= DIF_VAR_OTHER_UBASE)
   8318 				break;
   8319 
   8320 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
   8321 				break;
   8322 
   8323 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
   8324 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
   8325 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
   8326 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
   8327 				break;
   8328 
   8329 			err += efunc(pc, "illegal variable %u\n", v);
   8330 			break;
   8331 
   8332 		case DIF_OP_LDTA:
   8333 		case DIF_OP_LDTS:
   8334 		case DIF_OP_LDGAA:
   8335 		case DIF_OP_LDTAA:
   8336 			err += efunc(pc, "illegal dynamic variable load\n");
   8337 			break;
   8338 
   8339 		case DIF_OP_STTS:
   8340 		case DIF_OP_STGAA:
   8341 		case DIF_OP_STTAA:
   8342 			err += efunc(pc, "illegal dynamic variable store\n");
   8343 			break;
   8344 
   8345 		case DIF_OP_CALL:
   8346 			if (subr == DIF_SUBR_ALLOCA ||
   8347 			    subr == DIF_SUBR_BCOPY ||
   8348 			    subr == DIF_SUBR_COPYIN ||
   8349 			    subr == DIF_SUBR_COPYINTO ||
   8350 			    subr == DIF_SUBR_COPYINSTR ||
   8351 			    subr == DIF_SUBR_INDEX ||
   8352 			    subr == DIF_SUBR_INET_NTOA ||
   8353 			    subr == DIF_SUBR_INET_NTOA6 ||
   8354 			    subr == DIF_SUBR_INET_NTOP ||
   8355 			    subr == DIF_SUBR_LLTOSTR ||
   8356 			    subr == DIF_SUBR_RINDEX ||
   8357 			    subr == DIF_SUBR_STRCHR ||
   8358 			    subr == DIF_SUBR_STRJOIN ||
   8359 			    subr == DIF_SUBR_STRRCHR ||
   8360 			    subr == DIF_SUBR_STRSTR ||
   8361 			    subr == DIF_SUBR_HTONS ||
   8362 			    subr == DIF_SUBR_HTONL ||
   8363 			    subr == DIF_SUBR_HTONLL</