xref: /titanic_51/usr/src/uts/common/dtrace/dtrace.c (revision d65f2bb4e50559c6c375a2aa9f728cbc34379015)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2016, Joyent, Inc. All rights reserved.
25  * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
26  */
27 
28 /*
29  * DTrace - Dynamic Tracing for Solaris
30  *
31  * This is the implementation of the Solaris Dynamic Tracing framework
32  * (DTrace).  The user-visible interface to DTrace is described at length in
33  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
34  * library, the in-kernel DTrace framework, and the DTrace providers are
35  * described in the block comments in the <sys/dtrace.h> header file.  The
36  * internal architecture of DTrace is described in the block comments in the
37  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
38  * implementation very much assume mastery of all of these sources; if one has
39  * an unanswered question about the implementation, one should consult them
40  * first.
41  *
42  * The functions here are ordered roughly as follows:
43  *
44  *   - Probe context functions
45  *   - Probe hashing functions
46  *   - Non-probe context utility functions
47  *   - Matching functions
48  *   - Provider-to-Framework API functions
49  *   - Probe management functions
50  *   - DIF object functions
51  *   - Format functions
52  *   - Predicate functions
53  *   - ECB functions
54  *   - Buffer functions
55  *   - Enabling functions
56  *   - DOF functions
57  *   - Anonymous enabling functions
58  *   - Consumer state functions
59  *   - Helper functions
60  *   - Hook functions
61  *   - Driver cookbook functions
62  *
63  * Each group of functions begins with a block comment labelled the "DTrace
64  * [Group] Functions", allowing one to find each block by searching forward
65  * on capital-f functions.
66  */
67 #include <sys/errno.h>
68 #include <sys/stat.h>
69 #include <sys/modctl.h>
70 #include <sys/conf.h>
71 #include <sys/systm.h>
72 #include <sys/ddi.h>
73 #include <sys/sunddi.h>
74 #include <sys/cpuvar.h>
75 #include <sys/kmem.h>
76 #include <sys/strsubr.h>
77 #include <sys/sysmacros.h>
78 #include <sys/dtrace_impl.h>
79 #include <sys/atomic.h>
80 #include <sys/cmn_err.h>
81 #include <sys/mutex_impl.h>
82 #include <sys/rwlock_impl.h>
83 #include <sys/ctf_api.h>
84 #include <sys/panic.h>
85 #include <sys/priv_impl.h>
86 #include <sys/policy.h>
87 #include <sys/cred_impl.h>
88 #include <sys/procfs_isa.h>
89 #include <sys/taskq.h>
90 #include <sys/mkdev.h>
91 #include <sys/kdi.h>
92 #include <sys/zone.h>
93 #include <sys/socket.h>
94 #include <netinet/in.h>
95 #include "strtolctype.h"
96 
97 /*
98  * DTrace Tunable Variables
99  *
100  * The following variables may be tuned by adding a line to /etc/system that
101  * includes both the name of the DTrace module ("dtrace") and the name of the
102  * variable.  For example:
103  *
104  *   set dtrace:dtrace_destructive_disallow = 1
105  *
106  * In general, the only variables that one should be tuning this way are those
107  * that affect system-wide DTrace behavior, and for which the default behavior
108  * is undesirable.  Most of these variables are tunable on a per-consumer
109  * basis using DTrace options, and need not be tuned on a system-wide basis.
110  * When tuning these variables, avoid pathological values; while some attempt
111  * is made to verify the integrity of these variables, they are not considered
112  * part of the supported interface to DTrace, and they are therefore not
113  * checked comprehensively.  Further, these variables should not be tuned
114  * dynamically via "mdb -kw" or other means; they should only be tuned via
115  * /etc/system.
116  */
117 int		dtrace_destructive_disallow = 0;
118 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
119 size_t		dtrace_difo_maxsize = (256 * 1024);
120 dtrace_optval_t	dtrace_dof_maxsize = (8 * 1024 * 1024);
121 size_t		dtrace_statvar_maxsize = (16 * 1024);
122 size_t		dtrace_actions_max = (16 * 1024);
123 size_t		dtrace_retain_max = 1024;
124 dtrace_optval_t	dtrace_helper_actions_max = 1024;
125 dtrace_optval_t	dtrace_helper_providers_max = 32;
126 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
127 size_t		dtrace_strsize_default = 256;
128 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
129 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
130 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
131 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
132 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
133 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
134 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
135 dtrace_optval_t	dtrace_nspec_default = 1;
136 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
137 dtrace_optval_t dtrace_stackframes_default = 20;
138 dtrace_optval_t dtrace_ustackframes_default = 20;
139 dtrace_optval_t dtrace_jstackframes_default = 50;
140 dtrace_optval_t dtrace_jstackstrsize_default = 512;
141 int		dtrace_msgdsize_max = 128;
142 hrtime_t	dtrace_chill_max = MSEC2NSEC(500);		/* 500 ms */
143 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
144 int		dtrace_devdepth_max = 32;
145 int		dtrace_err_verbose;
146 hrtime_t	dtrace_deadman_interval = NANOSEC;
147 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
148 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
149 hrtime_t	dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
150 
151 /*
152  * DTrace External Variables
153  *
154  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
155  * available to DTrace consumers via the backtick (`) syntax.  One of these,
156  * dtrace_zero, is made deliberately so:  it is provided as a source of
157  * well-known, zero-filled memory.  While this variable is not documented,
158  * it is used by some translators as an implementation detail.
159  */
160 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
161 
162 /*
163  * DTrace Internal Variables
164  */
165 static dev_info_t	*dtrace_devi;		/* device info */
166 static vmem_t		*dtrace_arena;		/* probe ID arena */
167 static vmem_t		*dtrace_minor;		/* minor number arena */
168 static taskq_t		*dtrace_taskq;		/* task queue */
169 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
170 static int		dtrace_nprobes;		/* number of probes */
171 static dtrace_provider_t *dtrace_provider;	/* provider list */
172 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
173 static int		dtrace_opens;		/* number of opens */
174 static int		dtrace_helpers;		/* number of helpers */
175 static int		dtrace_getf;		/* number of unpriv getf()s */
176 static void		*dtrace_softstate;	/* softstate pointer */
177 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
178 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
179 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
180 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
181 static int		dtrace_toxranges;	/* number of toxic ranges */
182 static int		dtrace_toxranges_max;	/* size of toxic range array */
183 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
184 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
185 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
186 static kthread_t	*dtrace_panicked;	/* panicking thread */
187 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
188 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
189 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
190 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
191 static dtrace_genid_t	dtrace_retained_gen;	/* current retained enab gen */
192 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
193 static int		dtrace_dynvar_failclean; /* dynvars failed to clean */
194 
195 /*
196  * DTrace Locking
197  * DTrace is protected by three (relatively coarse-grained) locks:
198  *
199  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
200  *     including enabling state, probes, ECBs, consumer state, helper state,
201  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
202  *     probe context is lock-free -- synchronization is handled via the
203  *     dtrace_sync() cross call mechanism.
204  *
205  * (2) dtrace_provider_lock is required when manipulating provider state, or
206  *     when provider state must be held constant.
207  *
208  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
209  *     when meta provider state must be held constant.
210  *
211  * The lock ordering between these three locks is dtrace_meta_lock before
212  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
213  * several places where dtrace_provider_lock is held by the framework as it
214  * calls into the providers -- which then call back into the framework,
215  * grabbing dtrace_lock.)
216  *
217  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
218  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
219  * role as a coarse-grained lock; it is acquired before both of these locks.
220  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
221  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
222  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
223  * acquired _between_ dtrace_provider_lock and dtrace_lock.
224  */
225 static kmutex_t		dtrace_lock;		/* probe state lock */
226 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
227 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
228 
229 /*
230  * DTrace Provider Variables
231  *
232  * These are the variables relating to DTrace as a provider (that is, the
233  * provider of the BEGIN, END, and ERROR probes).
234  */
235 static dtrace_pattr_t	dtrace_provider_attr = {
236 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
237 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
238 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
239 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
240 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
241 };
242 
243 static void
244 dtrace_nullop(void)
245 {}
246 
247 static int
248 dtrace_enable_nullop(void)
249 {
250 	return (0);
251 }
252 
253 static dtrace_pops_t	dtrace_provider_ops = {
254 	(void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
255 	(void (*)(void *, struct modctl *))dtrace_nullop,
256 	(int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
257 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
258 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
259 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
260 	NULL,
261 	NULL,
262 	NULL,
263 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
264 };
265 
266 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
267 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
268 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
269 
270 /*
271  * DTrace Helper Tracing Variables
272  *
273  * These variables should be set dynamically to enable helper tracing.  The
274  * only variables that should be set are dtrace_helptrace_enable (which should
275  * be set to a non-zero value to allocate helper tracing buffers on the next
276  * open of /dev/dtrace) and dtrace_helptrace_disable (which should be set to a
277  * non-zero value to deallocate helper tracing buffers on the next close of
278  * /dev/dtrace).  When (and only when) helper tracing is disabled, the
279  * buffer size may also be set via dtrace_helptrace_bufsize.
280  */
281 int			dtrace_helptrace_enable = 0;
282 int			dtrace_helptrace_disable = 0;
283 int			dtrace_helptrace_bufsize = 16 * 1024 * 1024;
284 uint32_t		dtrace_helptrace_nlocals;
285 static dtrace_helptrace_t *dtrace_helptrace_buffer;
286 static uint32_t		dtrace_helptrace_next = 0;
287 static int		dtrace_helptrace_wrapped = 0;
288 
289 /*
290  * DTrace Error Hashing
291  *
292  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
293  * table.  This is very useful for checking coverage of tests that are
294  * expected to induce DIF or DOF processing errors, and may be useful for
295  * debugging problems in the DIF code generator or in DOF generation .  The
296  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
297  */
298 #ifdef DEBUG
299 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
300 static const char *dtrace_errlast;
301 static kthread_t *dtrace_errthread;
302 static kmutex_t dtrace_errlock;
303 #endif
304 
305 /*
306  * DTrace Macros and Constants
307  *
308  * These are various macros that are useful in various spots in the
309  * implementation, along with a few random constants that have no meaning
310  * outside of the implementation.  There is no real structure to this cpp
311  * mishmash -- but is there ever?
312  */
313 #define	DTRACE_HASHSTR(hash, probe)	\
314 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
315 
316 #define	DTRACE_HASHNEXT(hash, probe)	\
317 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
318 
319 #define	DTRACE_HASHPREV(hash, probe)	\
320 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
321 
322 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
323 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
324 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
325 
326 #define	DTRACE_AGGHASHSIZE_SLEW		17
327 
328 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
329 
330 /*
331  * The key for a thread-local variable consists of the lower 61 bits of the
332  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
333  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
334  * equal to a variable identifier.  This is necessary (but not sufficient) to
335  * assure that global associative arrays never collide with thread-local
336  * variables.  To guarantee that they cannot collide, we must also define the
337  * order for keying dynamic variables.  That order is:
338  *
339  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
340  *
341  * Because the variable-key and the tls-key are in orthogonal spaces, there is
342  * no way for a global variable key signature to match a thread-local key
343  * signature.
344  */
345 #define	DTRACE_TLS_THRKEY(where) { \
346 	uint_t intr = 0; \
347 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
348 	for (; actv; actv >>= 1) \
349 		intr++; \
350 	ASSERT(intr < (1 << 3)); \
351 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
352 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
353 }
354 
355 #define	DT_BSWAP_8(x)	((x) & 0xff)
356 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
357 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
358 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
359 
360 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
361 
362 #define	DTRACE_STORE(type, tomax, offset, what) \
363 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
364 
365 #ifndef __x86
366 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
367 	if (addr & (size - 1)) {					\
368 		*flags |= CPU_DTRACE_BADALIGN;				\
369 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
370 		return (0);						\
371 	}
372 #else
373 #define	DTRACE_ALIGNCHECK(addr, size, flags)
374 #endif
375 
376 /*
377  * Test whether a range of memory starting at testaddr of size testsz falls
378  * within the range of memory described by addr, sz.  We take care to avoid
379  * problems with overflow and underflow of the unsigned quantities, and
380  * disallow all negative sizes.  Ranges of size 0 are allowed.
381  */
382 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
383 	((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
384 	(testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
385 	(testaddr) + (testsz) >= (testaddr))
386 
387 /*
388  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
389  * alloc_sz on the righthand side of the comparison in order to avoid overflow
390  * or underflow in the comparison with it.  This is simpler than the INRANGE
391  * check above, because we know that the dtms_scratch_ptr is valid in the
392  * range.  Allocations of size zero are allowed.
393  */
394 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
395 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
396 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
397 
398 #define	DTRACE_LOADFUNC(bits)						\
399 /*CSTYLED*/								\
400 uint##bits##_t								\
401 dtrace_load##bits(uintptr_t addr)					\
402 {									\
403 	size_t size = bits / NBBY;					\
404 	/*CSTYLED*/							\
405 	uint##bits##_t rval;						\
406 	int i;								\
407 	volatile uint16_t *flags = (volatile uint16_t *)		\
408 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
409 									\
410 	DTRACE_ALIGNCHECK(addr, size, flags);				\
411 									\
412 	for (i = 0; i < dtrace_toxranges; i++) {			\
413 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
414 			continue;					\
415 									\
416 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
417 			continue;					\
418 									\
419 		/*							\
420 		 * This address falls within a toxic region; return 0.	\
421 		 */							\
422 		*flags |= CPU_DTRACE_BADADDR;				\
423 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
424 		return (0);						\
425 	}								\
426 									\
427 	*flags |= CPU_DTRACE_NOFAULT;					\
428 	/*CSTYLED*/							\
429 	rval = *((volatile uint##bits##_t *)addr);			\
430 	*flags &= ~CPU_DTRACE_NOFAULT;					\
431 									\
432 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
433 }
434 
435 #ifdef _LP64
436 #define	dtrace_loadptr	dtrace_load64
437 #else
438 #define	dtrace_loadptr	dtrace_load32
439 #endif
440 
441 #define	DTRACE_DYNHASH_FREE	0
442 #define	DTRACE_DYNHASH_SINK	1
443 #define	DTRACE_DYNHASH_VALID	2
444 
445 #define	DTRACE_MATCH_FAIL	-1
446 #define	DTRACE_MATCH_NEXT	0
447 #define	DTRACE_MATCH_DONE	1
448 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
449 #define	DTRACE_STATE_ALIGN	64
450 
451 #define	DTRACE_FLAGS2FLT(flags)						\
452 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
453 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
454 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
455 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
456 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
457 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
458 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
459 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
460 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
461 	DTRACEFLT_UNKNOWN)
462 
463 #define	DTRACEACT_ISSTRING(act)						\
464 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
465 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
466 
467 static size_t dtrace_strlen(const char *, size_t);
468 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
469 static void dtrace_enabling_provide(dtrace_provider_t *);
470 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
471 static void dtrace_enabling_matchall(void);
472 static void dtrace_enabling_reap(void);
473 static dtrace_state_t *dtrace_anon_grab(void);
474 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
475     dtrace_state_t *, uint64_t, uint64_t);
476 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
477 static void dtrace_buffer_drop(dtrace_buffer_t *);
478 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
479 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
480     dtrace_state_t *, dtrace_mstate_t *);
481 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
482     dtrace_optval_t);
483 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
484 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
485 static int dtrace_priv_proc(dtrace_state_t *, dtrace_mstate_t *);
486 static void dtrace_getf_barrier(void);
487 
488 /*
489  * DTrace Probe Context Functions
490  *
491  * These functions are called from probe context.  Because probe context is
492  * any context in which C may be called, arbitrarily locks may be held,
493  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
494  * As a result, functions called from probe context may only call other DTrace
495  * support functions -- they may not interact at all with the system at large.
496  * (Note that the ASSERT macro is made probe-context safe by redefining it in
497  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
498  * loads are to be performed from probe context, they _must_ be in terms of
499  * the safe dtrace_load*() variants.
500  *
501  * Some functions in this block are not actually called from probe context;
502  * for these functions, there will be a comment above the function reading
503  * "Note:  not called from probe context."
504  */
505 void
506 dtrace_panic(const char *format, ...)
507 {
508 	va_list alist;
509 
510 	va_start(alist, format);
511 	dtrace_vpanic(format, alist);
512 	va_end(alist);
513 }
514 
515 int
516 dtrace_assfail(const char *a, const char *f, int l)
517 {
518 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
519 
520 	/*
521 	 * We just need something here that even the most clever compiler
522 	 * cannot optimize away.
523 	 */
524 	return (a[(uintptr_t)f]);
525 }
526 
527 /*
528  * Atomically increment a specified error counter from probe context.
529  */
530 static void
531 dtrace_error(uint32_t *counter)
532 {
533 	/*
534 	 * Most counters stored to in probe context are per-CPU counters.
535 	 * However, there are some error conditions that are sufficiently
536 	 * arcane that they don't merit per-CPU storage.  If these counters
537 	 * are incremented concurrently on different CPUs, scalability will be
538 	 * adversely affected -- but we don't expect them to be white-hot in a
539 	 * correctly constructed enabling...
540 	 */
541 	uint32_t oval, nval;
542 
543 	do {
544 		oval = *counter;
545 
546 		if ((nval = oval + 1) == 0) {
547 			/*
548 			 * If the counter would wrap, set it to 1 -- assuring
549 			 * that the counter is never zero when we have seen
550 			 * errors.  (The counter must be 32-bits because we
551 			 * aren't guaranteed a 64-bit compare&swap operation.)
552 			 * To save this code both the infamy of being fingered
553 			 * by a priggish news story and the indignity of being
554 			 * the target of a neo-puritan witch trial, we're
555 			 * carefully avoiding any colorful description of the
556 			 * likelihood of this condition -- but suffice it to
557 			 * say that it is only slightly more likely than the
558 			 * overflow of predicate cache IDs, as discussed in
559 			 * dtrace_predicate_create().
560 			 */
561 			nval = 1;
562 		}
563 	} while (dtrace_cas32(counter, oval, nval) != oval);
564 }
565 
566 /*
567  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
568  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
569  */
570 /* BEGIN CSTYLED */
571 DTRACE_LOADFUNC(8)
572 DTRACE_LOADFUNC(16)
573 DTRACE_LOADFUNC(32)
574 DTRACE_LOADFUNC(64)
575 /* END CSTYLED */
576 
577 static int
578 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
579 {
580 	if (dest < mstate->dtms_scratch_base)
581 		return (0);
582 
583 	if (dest + size < dest)
584 		return (0);
585 
586 	if (dest + size > mstate->dtms_scratch_ptr)
587 		return (0);
588 
589 	return (1);
590 }
591 
592 static int
593 dtrace_canstore_statvar(uint64_t addr, size_t sz,
594     dtrace_statvar_t **svars, int nsvars)
595 {
596 	int i;
597 	size_t maxglobalsize, maxlocalsize;
598 
599 	if (nsvars == 0)
600 		return (0);
601 
602 	maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
603 	maxlocalsize = maxglobalsize * NCPU;
604 
605 	for (i = 0; i < nsvars; i++) {
606 		dtrace_statvar_t *svar = svars[i];
607 		uint8_t scope;
608 		size_t size;
609 
610 		if (svar == NULL || (size = svar->dtsv_size) == 0)
611 			continue;
612 
613 		scope = svar->dtsv_var.dtdv_scope;
614 
615 		/*
616 		 * We verify that our size is valid in the spirit of providing
617 		 * defense in depth:  we want to prevent attackers from using
618 		 * DTrace to escalate an orthogonal kernel heap corruption bug
619 		 * into the ability to store to arbitrary locations in memory.
620 		 */
621 		VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
622 		    (scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
623 
624 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
625 			return (1);
626 	}
627 
628 	return (0);
629 }
630 
631 /*
632  * Check to see if the address is within a memory region to which a store may
633  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
634  * region.  The caller of dtrace_canstore() is responsible for performing any
635  * alignment checks that are needed before stores are actually executed.
636  */
637 static int
638 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
639     dtrace_vstate_t *vstate)
640 {
641 	/*
642 	 * First, check to see if the address is in scratch space...
643 	 */
644 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
645 	    mstate->dtms_scratch_size))
646 		return (1);
647 
648 	/*
649 	 * Now check to see if it's a dynamic variable.  This check will pick
650 	 * up both thread-local variables and any global dynamically-allocated
651 	 * variables.
652 	 */
653 	if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
654 	    vstate->dtvs_dynvars.dtds_size)) {
655 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
656 		uintptr_t base = (uintptr_t)dstate->dtds_base +
657 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
658 		uintptr_t chunkoffs;
659 		dtrace_dynvar_t *dvar;
660 
661 		/*
662 		 * Before we assume that we can store here, we need to make
663 		 * sure that it isn't in our metadata -- storing to our
664 		 * dynamic variable metadata would corrupt our state.  For
665 		 * the range to not include any dynamic variable metadata,
666 		 * it must:
667 		 *
668 		 *	(1) Start above the hash table that is at the base of
669 		 *	the dynamic variable space
670 		 *
671 		 *	(2) Have a starting chunk offset that is beyond the
672 		 *	dtrace_dynvar_t that is at the base of every chunk
673 		 *
674 		 *	(3) Not span a chunk boundary
675 		 *
676 		 *	(4) Not be in the tuple space of a dynamic variable
677 		 *
678 		 */
679 		if (addr < base)
680 			return (0);
681 
682 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
683 
684 		if (chunkoffs < sizeof (dtrace_dynvar_t))
685 			return (0);
686 
687 		if (chunkoffs + sz > dstate->dtds_chunksize)
688 			return (0);
689 
690 		dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
691 
692 		if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
693 			return (0);
694 
695 		if (chunkoffs < sizeof (dtrace_dynvar_t) +
696 		    ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
697 			return (0);
698 
699 		return (1);
700 	}
701 
702 	/*
703 	 * Finally, check the static local and global variables.  These checks
704 	 * take the longest, so we perform them last.
705 	 */
706 	if (dtrace_canstore_statvar(addr, sz,
707 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
708 		return (1);
709 
710 	if (dtrace_canstore_statvar(addr, sz,
711 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
712 		return (1);
713 
714 	return (0);
715 }
716 
717 
718 /*
719  * Convenience routine to check to see if the address is within a memory
720  * region in which a load may be issued given the user's privilege level;
721  * if not, it sets the appropriate error flags and loads 'addr' into the
722  * illegal value slot.
723  *
724  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
725  * appropriate memory access protection.
726  */
727 static int
728 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
729     dtrace_vstate_t *vstate)
730 {
731 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
732 	file_t *fp;
733 
734 	/*
735 	 * If we hold the privilege to read from kernel memory, then
736 	 * everything is readable.
737 	 */
738 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
739 		return (1);
740 
741 	/*
742 	 * You can obviously read that which you can store.
743 	 */
744 	if (dtrace_canstore(addr, sz, mstate, vstate))
745 		return (1);
746 
747 	/*
748 	 * We're allowed to read from our own string table.
749 	 */
750 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
751 	    mstate->dtms_difo->dtdo_strlen))
752 		return (1);
753 
754 	if (vstate->dtvs_state != NULL &&
755 	    dtrace_priv_proc(vstate->dtvs_state, mstate)) {
756 		proc_t *p;
757 
758 		/*
759 		 * When we have privileges to the current process, there are
760 		 * several context-related kernel structures that are safe to
761 		 * read, even absent the privilege to read from kernel memory.
762 		 * These reads are safe because these structures contain only
763 		 * state that (1) we're permitted to read, (2) is harmless or
764 		 * (3) contains pointers to additional kernel state that we're
765 		 * not permitted to read (and as such, do not present an
766 		 * opportunity for privilege escalation).  Finally (and
767 		 * critically), because of the nature of their relation with
768 		 * the current thread context, the memory associated with these
769 		 * structures cannot change over the duration of probe context,
770 		 * and it is therefore impossible for this memory to be
771 		 * deallocated and reallocated as something else while it's
772 		 * being operated upon.
773 		 */
774 		if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t)))
775 			return (1);
776 
777 		if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
778 		    sz, curthread->t_procp, sizeof (proc_t))) {
779 			return (1);
780 		}
781 
782 		if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
783 		    curthread->t_cred, sizeof (cred_t))) {
784 			return (1);
785 		}
786 
787 		if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
788 		    &(p->p_pidp->pid_id), sizeof (pid_t))) {
789 			return (1);
790 		}
791 
792 		if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
793 		    curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
794 			return (1);
795 		}
796 	}
797 
798 	if ((fp = mstate->dtms_getf) != NULL) {
799 		uintptr_t psz = sizeof (void *);
800 		vnode_t *vp;
801 		vnodeops_t *op;
802 
803 		/*
804 		 * When getf() returns a file_t, the enabling is implicitly
805 		 * granted the (transient) right to read the returned file_t
806 		 * as well as the v_path and v_op->vnop_name of the underlying
807 		 * vnode.  These accesses are allowed after a successful
808 		 * getf() because the members that they refer to cannot change
809 		 * once set -- and the barrier logic in the kernel's closef()
810 		 * path assures that the file_t and its referenced vode_t
811 		 * cannot themselves be stale (that is, it impossible for
812 		 * either dtms_getf itself or its f_vnode member to reference
813 		 * freed memory).
814 		 */
815 		if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t)))
816 			return (1);
817 
818 		if ((vp = fp->f_vnode) != NULL) {
819 			if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz))
820 				return (1);
821 
822 			if (vp->v_path != NULL && DTRACE_INRANGE(addr, sz,
823 			    vp->v_path, strlen(vp->v_path) + 1)) {
824 				return (1);
825 			}
826 
827 			if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz))
828 				return (1);
829 
830 			if ((op = vp->v_op) != NULL &&
831 			    DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
832 				return (1);
833 			}
834 
835 			if (op != NULL && op->vnop_name != NULL &&
836 			    DTRACE_INRANGE(addr, sz, op->vnop_name,
837 			    strlen(op->vnop_name) + 1)) {
838 				return (1);
839 			}
840 		}
841 	}
842 
843 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
844 	*illval = addr;
845 	return (0);
846 }
847 
848 /*
849  * Convenience routine to check to see if a given string is within a memory
850  * region in which a load may be issued given the user's privilege level;
851  * this exists so that we don't need to issue unnecessary dtrace_strlen()
852  * calls in the event that the user has all privileges.
853  */
854 static int
855 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
856     dtrace_vstate_t *vstate)
857 {
858 	size_t strsz;
859 
860 	/*
861 	 * If we hold the privilege to read from kernel memory, then
862 	 * everything is readable.
863 	 */
864 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
865 		return (1);
866 
867 	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
868 	if (dtrace_canload(addr, strsz, mstate, vstate))
869 		return (1);
870 
871 	return (0);
872 }
873 
874 /*
875  * Convenience routine to check to see if a given variable is within a memory
876  * region in which a load may be issued given the user's privilege level.
877  */
878 static int
879 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
880     dtrace_vstate_t *vstate)
881 {
882 	size_t sz;
883 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
884 
885 	/*
886 	 * If we hold the privilege to read from kernel memory, then
887 	 * everything is readable.
888 	 */
889 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
890 		return (1);
891 
892 	if (type->dtdt_kind == DIF_TYPE_STRING)
893 		sz = dtrace_strlen(src,
894 		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
895 	else
896 		sz = type->dtdt_size;
897 
898 	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
899 }
900 
901 /*
902  * Convert a string to a signed integer using safe loads.
903  *
904  * NOTE: This function uses various macros from strtolctype.h to manipulate
905  * digit values, etc -- these have all been checked to ensure they make
906  * no additional function calls.
907  */
908 static int64_t
909 dtrace_strtoll(char *input, int base, size_t limit)
910 {
911 	uintptr_t pos = (uintptr_t)input;
912 	int64_t val = 0;
913 	int x;
914 	boolean_t neg = B_FALSE;
915 	char c, cc, ccc;
916 	uintptr_t end = pos + limit;
917 
918 	/*
919 	 * Consume any whitespace preceding digits.
920 	 */
921 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
922 		pos++;
923 
924 	/*
925 	 * Handle an explicit sign if one is present.
926 	 */
927 	if (c == '-' || c == '+') {
928 		if (c == '-')
929 			neg = B_TRUE;
930 		c = dtrace_load8(++pos);
931 	}
932 
933 	/*
934 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
935 	 * if present.
936 	 */
937 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
938 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
939 		pos += 2;
940 		c = ccc;
941 	}
942 
943 	/*
944 	 * Read in contiguous digits until the first non-digit character.
945 	 */
946 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
947 	    c = dtrace_load8(++pos))
948 		val = val * base + x;
949 
950 	return (neg ? -val : val);
951 }
952 
953 /*
954  * Compare two strings using safe loads.
955  */
956 static int
957 dtrace_strncmp(char *s1, char *s2, size_t limit)
958 {
959 	uint8_t c1, c2;
960 	volatile uint16_t *flags;
961 
962 	if (s1 == s2 || limit == 0)
963 		return (0);
964 
965 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
966 
967 	do {
968 		if (s1 == NULL) {
969 			c1 = '\0';
970 		} else {
971 			c1 = dtrace_load8((uintptr_t)s1++);
972 		}
973 
974 		if (s2 == NULL) {
975 			c2 = '\0';
976 		} else {
977 			c2 = dtrace_load8((uintptr_t)s2++);
978 		}
979 
980 		if (c1 != c2)
981 			return (c1 - c2);
982 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
983 
984 	return (0);
985 }
986 
987 /*
988  * Compute strlen(s) for a string using safe memory accesses.  The additional
989  * len parameter is used to specify a maximum length to ensure completion.
990  */
991 static size_t
992 dtrace_strlen(const char *s, size_t lim)
993 {
994 	uint_t len;
995 
996 	for (len = 0; len != lim; len++) {
997 		if (dtrace_load8((uintptr_t)s++) == '\0')
998 			break;
999 	}
1000 
1001 	return (len);
1002 }
1003 
1004 /*
1005  * Check if an address falls within a toxic region.
1006  */
1007 static int
1008 dtrace_istoxic(uintptr_t kaddr, size_t size)
1009 {
1010 	uintptr_t taddr, tsize;
1011 	int i;
1012 
1013 	for (i = 0; i < dtrace_toxranges; i++) {
1014 		taddr = dtrace_toxrange[i].dtt_base;
1015 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1016 
1017 		if (kaddr - taddr < tsize) {
1018 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1019 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
1020 			return (1);
1021 		}
1022 
1023 		if (taddr - kaddr < size) {
1024 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1025 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1026 			return (1);
1027 		}
1028 	}
1029 
1030 	return (0);
1031 }
1032 
1033 /*
1034  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1035  * memory specified by the DIF program.  The dst is assumed to be safe memory
1036  * that we can store to directly because it is managed by DTrace.  As with
1037  * standard bcopy, overlapping copies are handled properly.
1038  */
1039 static void
1040 dtrace_bcopy(const void *src, void *dst, size_t len)
1041 {
1042 	if (len != 0) {
1043 		uint8_t *s1 = dst;
1044 		const uint8_t *s2 = src;
1045 
1046 		if (s1 <= s2) {
1047 			do {
1048 				*s1++ = dtrace_load8((uintptr_t)s2++);
1049 			} while (--len != 0);
1050 		} else {
1051 			s2 += len;
1052 			s1 += len;
1053 
1054 			do {
1055 				*--s1 = dtrace_load8((uintptr_t)--s2);
1056 			} while (--len != 0);
1057 		}
1058 	}
1059 }
1060 
1061 /*
1062  * Copy src to dst using safe memory accesses, up to either the specified
1063  * length, or the point that a nul byte is encountered.  The src is assumed to
1064  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1065  * safe memory that we can store to directly because it is managed by DTrace.
1066  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1067  */
1068 static void
1069 dtrace_strcpy(const void *src, void *dst, size_t len)
1070 {
1071 	if (len != 0) {
1072 		uint8_t *s1 = dst, c;
1073 		const uint8_t *s2 = src;
1074 
1075 		do {
1076 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1077 		} while (--len != 0 && c != '\0');
1078 	}
1079 }
1080 
1081 /*
1082  * Copy src to dst, deriving the size and type from the specified (BYREF)
1083  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1084  * program.  The dst is assumed to be DTrace variable memory that is of the
1085  * specified type; we assume that we can store to directly.
1086  */
1087 static void
1088 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1089 {
1090 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1091 
1092 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1093 		dtrace_strcpy(src, dst, type->dtdt_size);
1094 	} else {
1095 		dtrace_bcopy(src, dst, type->dtdt_size);
1096 	}
1097 }
1098 
1099 /*
1100  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1101  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1102  * safe memory that we can access directly because it is managed by DTrace.
1103  */
1104 static int
1105 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1106 {
1107 	volatile uint16_t *flags;
1108 
1109 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1110 
1111 	if (s1 == s2)
1112 		return (0);
1113 
1114 	if (s1 == NULL || s2 == NULL)
1115 		return (1);
1116 
1117 	if (s1 != s2 && len != 0) {
1118 		const uint8_t *ps1 = s1;
1119 		const uint8_t *ps2 = s2;
1120 
1121 		do {
1122 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1123 				return (1);
1124 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1125 	}
1126 	return (0);
1127 }
1128 
1129 /*
1130  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1131  * is for safe DTrace-managed memory only.
1132  */
1133 static void
1134 dtrace_bzero(void *dst, size_t len)
1135 {
1136 	uchar_t *cp;
1137 
1138 	for (cp = dst; len != 0; len--)
1139 		*cp++ = 0;
1140 }
1141 
1142 static void
1143 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1144 {
1145 	uint64_t result[2];
1146 
1147 	result[0] = addend1[0] + addend2[0];
1148 	result[1] = addend1[1] + addend2[1] +
1149 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1150 
1151 	sum[0] = result[0];
1152 	sum[1] = result[1];
1153 }
1154 
1155 /*
1156  * Shift the 128-bit value in a by b. If b is positive, shift left.
1157  * If b is negative, shift right.
1158  */
1159 static void
1160 dtrace_shift_128(uint64_t *a, int b)
1161 {
1162 	uint64_t mask;
1163 
1164 	if (b == 0)
1165 		return;
1166 
1167 	if (b < 0) {
1168 		b = -b;
1169 		if (b >= 64) {
1170 			a[0] = a[1] >> (b - 64);
1171 			a[1] = 0;
1172 		} else {
1173 			a[0] >>= b;
1174 			mask = 1LL << (64 - b);
1175 			mask -= 1;
1176 			a[0] |= ((a[1] & mask) << (64 - b));
1177 			a[1] >>= b;
1178 		}
1179 	} else {
1180 		if (b >= 64) {
1181 			a[1] = a[0] << (b - 64);
1182 			a[0] = 0;
1183 		} else {
1184 			a[1] <<= b;
1185 			mask = a[0] >> (64 - b);
1186 			a[1] |= mask;
1187 			a[0] <<= b;
1188 		}
1189 	}
1190 }
1191 
1192 /*
1193  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1194  * use native multiplication on those, and then re-combine into the
1195  * resulting 128-bit value.
1196  *
1197  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1198  *     hi1 * hi2 << 64 +
1199  *     hi1 * lo2 << 32 +
1200  *     hi2 * lo1 << 32 +
1201  *     lo1 * lo2
1202  */
1203 static void
1204 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1205 {
1206 	uint64_t hi1, hi2, lo1, lo2;
1207 	uint64_t tmp[2];
1208 
1209 	hi1 = factor1 >> 32;
1210 	hi2 = factor2 >> 32;
1211 
1212 	lo1 = factor1 & DT_MASK_LO;
1213 	lo2 = factor2 & DT_MASK_LO;
1214 
1215 	product[0] = lo1 * lo2;
1216 	product[1] = hi1 * hi2;
1217 
1218 	tmp[0] = hi1 * lo2;
1219 	tmp[1] = 0;
1220 	dtrace_shift_128(tmp, 32);
1221 	dtrace_add_128(product, tmp, product);
1222 
1223 	tmp[0] = hi2 * lo1;
1224 	tmp[1] = 0;
1225 	dtrace_shift_128(tmp, 32);
1226 	dtrace_add_128(product, tmp, product);
1227 }
1228 
1229 /*
1230  * This privilege check should be used by actions and subroutines to
1231  * verify that the user credentials of the process that enabled the
1232  * invoking ECB match the target credentials
1233  */
1234 static int
1235 dtrace_priv_proc_common_user(dtrace_state_t *state)
1236 {
1237 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1238 
1239 	/*
1240 	 * We should always have a non-NULL state cred here, since if cred
1241 	 * is null (anonymous tracing), we fast-path bypass this routine.
1242 	 */
1243 	ASSERT(s_cr != NULL);
1244 
1245 	if ((cr = CRED()) != NULL &&
1246 	    s_cr->cr_uid == cr->cr_uid &&
1247 	    s_cr->cr_uid == cr->cr_ruid &&
1248 	    s_cr->cr_uid == cr->cr_suid &&
1249 	    s_cr->cr_gid == cr->cr_gid &&
1250 	    s_cr->cr_gid == cr->cr_rgid &&
1251 	    s_cr->cr_gid == cr->cr_sgid)
1252 		return (1);
1253 
1254 	return (0);
1255 }
1256 
1257 /*
1258  * This privilege check should be used by actions and subroutines to
1259  * verify that the zone of the process that enabled the invoking ECB
1260  * matches the target credentials
1261  */
1262 static int
1263 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1264 {
1265 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1266 
1267 	/*
1268 	 * We should always have a non-NULL state cred here, since if cred
1269 	 * is null (anonymous tracing), we fast-path bypass this routine.
1270 	 */
1271 	ASSERT(s_cr != NULL);
1272 
1273 	if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1274 		return (1);
1275 
1276 	return (0);
1277 }
1278 
1279 /*
1280  * This privilege check should be used by actions and subroutines to
1281  * verify that the process has not setuid or changed credentials.
1282  */
1283 static int
1284 dtrace_priv_proc_common_nocd()
1285 {
1286 	proc_t *proc;
1287 
1288 	if ((proc = ttoproc(curthread)) != NULL &&
1289 	    !(proc->p_flag & SNOCD))
1290 		return (1);
1291 
1292 	return (0);
1293 }
1294 
1295 static int
1296 dtrace_priv_proc_destructive(dtrace_state_t *state, dtrace_mstate_t *mstate)
1297 {
1298 	int action = state->dts_cred.dcr_action;
1299 
1300 	if (!(mstate->dtms_access & DTRACE_ACCESS_PROC))
1301 		goto bad;
1302 
1303 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1304 	    dtrace_priv_proc_common_zone(state) == 0)
1305 		goto bad;
1306 
1307 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1308 	    dtrace_priv_proc_common_user(state) == 0)
1309 		goto bad;
1310 
1311 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1312 	    dtrace_priv_proc_common_nocd() == 0)
1313 		goto bad;
1314 
1315 	return (1);
1316 
1317 bad:
1318 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1319 
1320 	return (0);
1321 }
1322 
1323 static int
1324 dtrace_priv_proc_control(dtrace_state_t *state, dtrace_mstate_t *mstate)
1325 {
1326 	if (mstate->dtms_access & DTRACE_ACCESS_PROC) {
1327 		if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1328 			return (1);
1329 
1330 		if (dtrace_priv_proc_common_zone(state) &&
1331 		    dtrace_priv_proc_common_user(state) &&
1332 		    dtrace_priv_proc_common_nocd())
1333 			return (1);
1334 	}
1335 
1336 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1337 
1338 	return (0);
1339 }
1340 
1341 static int
1342 dtrace_priv_proc(dtrace_state_t *state, dtrace_mstate_t *mstate)
1343 {
1344 	if ((mstate->dtms_access & DTRACE_ACCESS_PROC) &&
1345 	    (state->dts_cred.dcr_action & DTRACE_CRA_PROC))
1346 		return (1);
1347 
1348 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1349 
1350 	return (0);
1351 }
1352 
1353 static int
1354 dtrace_priv_kernel(dtrace_state_t *state)
1355 {
1356 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1357 		return (1);
1358 
1359 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1360 
1361 	return (0);
1362 }
1363 
1364 static int
1365 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1366 {
1367 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1368 		return (1);
1369 
1370 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1371 
1372 	return (0);
1373 }
1374 
1375 /*
1376  * Determine if the dte_cond of the specified ECB allows for processing of
1377  * the current probe to continue.  Note that this routine may allow continued
1378  * processing, but with access(es) stripped from the mstate's dtms_access
1379  * field.
1380  */
1381 static int
1382 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1383     dtrace_ecb_t *ecb)
1384 {
1385 	dtrace_probe_t *probe = ecb->dte_probe;
1386 	dtrace_provider_t *prov = probe->dtpr_provider;
1387 	dtrace_pops_t *pops = &prov->dtpv_pops;
1388 	int mode = DTRACE_MODE_NOPRIV_DROP;
1389 
1390 	ASSERT(ecb->dte_cond);
1391 
1392 	if (pops->dtps_mode != NULL) {
1393 		mode = pops->dtps_mode(prov->dtpv_arg,
1394 		    probe->dtpr_id, probe->dtpr_arg);
1395 
1396 		ASSERT(mode & (DTRACE_MODE_USER | DTRACE_MODE_KERNEL));
1397 		ASSERT(mode & (DTRACE_MODE_NOPRIV_RESTRICT |
1398 		    DTRACE_MODE_NOPRIV_DROP));
1399 	}
1400 
1401 	/*
1402 	 * If the dte_cond bits indicate that this consumer is only allowed to
1403 	 * see user-mode firings of this probe, check that the probe was fired
1404 	 * while in a user context.  If that's not the case, use the policy
1405 	 * specified by the provider to determine if we drop the probe or
1406 	 * merely restrict operation.
1407 	 */
1408 	if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1409 		ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1410 
1411 		if (!(mode & DTRACE_MODE_USER)) {
1412 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1413 				return (0);
1414 
1415 			mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1416 		}
1417 	}
1418 
1419 	/*
1420 	 * This is more subtle than it looks. We have to be absolutely certain
1421 	 * that CRED() isn't going to change out from under us so it's only
1422 	 * legit to examine that structure if we're in constrained situations.
1423 	 * Currently, the only times we'll this check is if a non-super-user
1424 	 * has enabled the profile or syscall providers -- providers that
1425 	 * allow visibility of all processes. For the profile case, the check
1426 	 * above will ensure that we're examining a user context.
1427 	 */
1428 	if (ecb->dte_cond & DTRACE_COND_OWNER) {
1429 		cred_t *cr;
1430 		cred_t *s_cr = state->dts_cred.dcr_cred;
1431 		proc_t *proc;
1432 
1433 		ASSERT(s_cr != NULL);
1434 
1435 		if ((cr = CRED()) == NULL ||
1436 		    s_cr->cr_uid != cr->cr_uid ||
1437 		    s_cr->cr_uid != cr->cr_ruid ||
1438 		    s_cr->cr_uid != cr->cr_suid ||
1439 		    s_cr->cr_gid != cr->cr_gid ||
1440 		    s_cr->cr_gid != cr->cr_rgid ||
1441 		    s_cr->cr_gid != cr->cr_sgid ||
1442 		    (proc = ttoproc(curthread)) == NULL ||
1443 		    (proc->p_flag & SNOCD)) {
1444 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1445 				return (0);
1446 
1447 			mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1448 		}
1449 	}
1450 
1451 	/*
1452 	 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1453 	 * in our zone, check to see if our mode policy is to restrict rather
1454 	 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1455 	 * and DTRACE_ACCESS_ARGS
1456 	 */
1457 	if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1458 		cred_t *cr;
1459 		cred_t *s_cr = state->dts_cred.dcr_cred;
1460 
1461 		ASSERT(s_cr != NULL);
1462 
1463 		if ((cr = CRED()) == NULL ||
1464 		    s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1465 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1466 				return (0);
1467 
1468 			mstate->dtms_access &=
1469 			    ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1470 		}
1471 	}
1472 
1473 	/*
1474 	 * By merits of being in this code path at all, we have limited
1475 	 * privileges.  If the provider has indicated that limited privileges
1476 	 * are to denote restricted operation, strip off the ability to access
1477 	 * arguments.
1478 	 */
1479 	if (mode & DTRACE_MODE_LIMITEDPRIV_RESTRICT)
1480 		mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1481 
1482 	return (1);
1483 }
1484 
1485 /*
1486  * Note:  not called from probe context.  This function is called
1487  * asynchronously (and at a regular interval) from outside of probe context to
1488  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1489  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1490  */
1491 void
1492 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1493 {
1494 	dtrace_dynvar_t *dirty;
1495 	dtrace_dstate_percpu_t *dcpu;
1496 	dtrace_dynvar_t **rinsep;
1497 	int i, j, work = 0;
1498 
1499 	for (i = 0; i < NCPU; i++) {
1500 		dcpu = &dstate->dtds_percpu[i];
1501 		rinsep = &dcpu->dtdsc_rinsing;
1502 
1503 		/*
1504 		 * If the dirty list is NULL, there is no dirty work to do.
1505 		 */
1506 		if (dcpu->dtdsc_dirty == NULL)
1507 			continue;
1508 
1509 		if (dcpu->dtdsc_rinsing != NULL) {
1510 			/*
1511 			 * If the rinsing list is non-NULL, then it is because
1512 			 * this CPU was selected to accept another CPU's
1513 			 * dirty list -- and since that time, dirty buffers
1514 			 * have accumulated.  This is a highly unlikely
1515 			 * condition, but we choose to ignore the dirty
1516 			 * buffers -- they'll be picked up a future cleanse.
1517 			 */
1518 			continue;
1519 		}
1520 
1521 		if (dcpu->dtdsc_clean != NULL) {
1522 			/*
1523 			 * If the clean list is non-NULL, then we're in a
1524 			 * situation where a CPU has done deallocations (we
1525 			 * have a non-NULL dirty list) but no allocations (we
1526 			 * also have a non-NULL clean list).  We can't simply
1527 			 * move the dirty list into the clean list on this
1528 			 * CPU, yet we also don't want to allow this condition
1529 			 * to persist, lest a short clean list prevent a
1530 			 * massive dirty list from being cleaned (which in
1531 			 * turn could lead to otherwise avoidable dynamic
1532 			 * drops).  To deal with this, we look for some CPU
1533 			 * with a NULL clean list, NULL dirty list, and NULL
1534 			 * rinsing list -- and then we borrow this CPU to
1535 			 * rinse our dirty list.
1536 			 */
1537 			for (j = 0; j < NCPU; j++) {
1538 				dtrace_dstate_percpu_t *rinser;
1539 
1540 				rinser = &dstate->dtds_percpu[j];
1541 
1542 				if (rinser->dtdsc_rinsing != NULL)
1543 					continue;
1544 
1545 				if (rinser->dtdsc_dirty != NULL)
1546 					continue;
1547 
1548 				if (rinser->dtdsc_clean != NULL)
1549 					continue;
1550 
1551 				rinsep = &rinser->dtdsc_rinsing;
1552 				break;
1553 			}
1554 
1555 			if (j == NCPU) {
1556 				/*
1557 				 * We were unable to find another CPU that
1558 				 * could accept this dirty list -- we are
1559 				 * therefore unable to clean it now.
1560 				 */
1561 				dtrace_dynvar_failclean++;
1562 				continue;
1563 			}
1564 		}
1565 
1566 		work = 1;
1567 
1568 		/*
1569 		 * Atomically move the dirty list aside.
1570 		 */
1571 		do {
1572 			dirty = dcpu->dtdsc_dirty;
1573 
1574 			/*
1575 			 * Before we zap the dirty list, set the rinsing list.
1576 			 * (This allows for a potential assertion in
1577 			 * dtrace_dynvar():  if a free dynamic variable appears
1578 			 * on a hash chain, either the dirty list or the
1579 			 * rinsing list for some CPU must be non-NULL.)
1580 			 */
1581 			*rinsep = dirty;
1582 			dtrace_membar_producer();
1583 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1584 		    dirty, NULL) != dirty);
1585 	}
1586 
1587 	if (!work) {
1588 		/*
1589 		 * We have no work to do; we can simply return.
1590 		 */
1591 		return;
1592 	}
1593 
1594 	dtrace_sync();
1595 
1596 	for (i = 0; i < NCPU; i++) {
1597 		dcpu = &dstate->dtds_percpu[i];
1598 
1599 		if (dcpu->dtdsc_rinsing == NULL)
1600 			continue;
1601 
1602 		/*
1603 		 * We are now guaranteed that no hash chain contains a pointer
1604 		 * into this dirty list; we can make it clean.
1605 		 */
1606 		ASSERT(dcpu->dtdsc_clean == NULL);
1607 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1608 		dcpu->dtdsc_rinsing = NULL;
1609 	}
1610 
1611 	/*
1612 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1613 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1614 	 * This prevents a race whereby a CPU incorrectly decides that
1615 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1616 	 * after dtrace_dynvar_clean() has completed.
1617 	 */
1618 	dtrace_sync();
1619 
1620 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1621 }
1622 
1623 /*
1624  * Depending on the value of the op parameter, this function looks-up,
1625  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1626  * allocation is requested, this function will return a pointer to a
1627  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1628  * variable can be allocated.  If NULL is returned, the appropriate counter
1629  * will be incremented.
1630  */
1631 dtrace_dynvar_t *
1632 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1633     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1634     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1635 {
1636 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1637 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1638 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1639 	processorid_t me = CPU->cpu_id, cpu = me;
1640 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1641 	size_t bucket, ksize;
1642 	size_t chunksize = dstate->dtds_chunksize;
1643 	uintptr_t kdata, lock, nstate;
1644 	uint_t i;
1645 
1646 	ASSERT(nkeys != 0);
1647 
1648 	/*
1649 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1650 	 * algorithm.  For the by-value portions, we perform the algorithm in
1651 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1652 	 * bit, and seems to have only a minute effect on distribution.  For
1653 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1654 	 * over each referenced byte.  It's painful to do this, but it's much
1655 	 * better than pathological hash distribution.  The efficacy of the
1656 	 * hashing algorithm (and a comparison with other algorithms) may be
1657 	 * found by running the ::dtrace_dynstat MDB dcmd.
1658 	 */
1659 	for (i = 0; i < nkeys; i++) {
1660 		if (key[i].dttk_size == 0) {
1661 			uint64_t val = key[i].dttk_value;
1662 
1663 			hashval += (val >> 48) & 0xffff;
1664 			hashval += (hashval << 10);
1665 			hashval ^= (hashval >> 6);
1666 
1667 			hashval += (val >> 32) & 0xffff;
1668 			hashval += (hashval << 10);
1669 			hashval ^= (hashval >> 6);
1670 
1671 			hashval += (val >> 16) & 0xffff;
1672 			hashval += (hashval << 10);
1673 			hashval ^= (hashval >> 6);
1674 
1675 			hashval += val & 0xffff;
1676 			hashval += (hashval << 10);
1677 			hashval ^= (hashval >> 6);
1678 		} else {
1679 			/*
1680 			 * This is incredibly painful, but it beats the hell
1681 			 * out of the alternative.
1682 			 */
1683 			uint64_t j, size = key[i].dttk_size;
1684 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1685 
1686 			if (!dtrace_canload(base, size, mstate, vstate))
1687 				break;
1688 
1689 			for (j = 0; j < size; j++) {
1690 				hashval += dtrace_load8(base + j);
1691 				hashval += (hashval << 10);
1692 				hashval ^= (hashval >> 6);
1693 			}
1694 		}
1695 	}
1696 
1697 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1698 		return (NULL);
1699 
1700 	hashval += (hashval << 3);
1701 	hashval ^= (hashval >> 11);
1702 	hashval += (hashval << 15);
1703 
1704 	/*
1705 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1706 	 * comes out to be one of our two sentinel hash values.  If this
1707 	 * actually happens, we set the hashval to be a value known to be a
1708 	 * non-sentinel value.
1709 	 */
1710 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1711 		hashval = DTRACE_DYNHASH_VALID;
1712 
1713 	/*
1714 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1715 	 * important here, tricks can be pulled to reduce it.  (However, it's
1716 	 * critical that hash collisions be kept to an absolute minimum;
1717 	 * they're much more painful than a divide.)  It's better to have a
1718 	 * solution that generates few collisions and still keeps things
1719 	 * relatively simple.
1720 	 */
1721 	bucket = hashval % dstate->dtds_hashsize;
1722 
1723 	if (op == DTRACE_DYNVAR_DEALLOC) {
1724 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1725 
1726 		for (;;) {
1727 			while ((lock = *lockp) & 1)
1728 				continue;
1729 
1730 			if (dtrace_casptr((void *)lockp,
1731 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1732 				break;
1733 		}
1734 
1735 		dtrace_membar_producer();
1736 	}
1737 
1738 top:
1739 	prev = NULL;
1740 	lock = hash[bucket].dtdh_lock;
1741 
1742 	dtrace_membar_consumer();
1743 
1744 	start = hash[bucket].dtdh_chain;
1745 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1746 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1747 	    op != DTRACE_DYNVAR_DEALLOC));
1748 
1749 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1750 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1751 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1752 
1753 		if (dvar->dtdv_hashval != hashval) {
1754 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1755 				/*
1756 				 * We've reached the sink, and therefore the
1757 				 * end of the hash chain; we can kick out of
1758 				 * the loop knowing that we have seen a valid
1759 				 * snapshot of state.
1760 				 */
1761 				ASSERT(dvar->dtdv_next == NULL);
1762 				ASSERT(dvar == &dtrace_dynhash_sink);
1763 				break;
1764 			}
1765 
1766 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1767 				/*
1768 				 * We've gone off the rails:  somewhere along
1769 				 * the line, one of the members of this hash
1770 				 * chain was deleted.  Note that we could also
1771 				 * detect this by simply letting this loop run
1772 				 * to completion, as we would eventually hit
1773 				 * the end of the dirty list.  However, we
1774 				 * want to avoid running the length of the
1775 				 * dirty list unnecessarily (it might be quite
1776 				 * long), so we catch this as early as
1777 				 * possible by detecting the hash marker.  In
1778 				 * this case, we simply set dvar to NULL and
1779 				 * break; the conditional after the loop will
1780 				 * send us back to top.
1781 				 */
1782 				dvar = NULL;
1783 				break;
1784 			}
1785 
1786 			goto next;
1787 		}
1788 
1789 		if (dtuple->dtt_nkeys != nkeys)
1790 			goto next;
1791 
1792 		for (i = 0; i < nkeys; i++, dkey++) {
1793 			if (dkey->dttk_size != key[i].dttk_size)
1794 				goto next; /* size or type mismatch */
1795 
1796 			if (dkey->dttk_size != 0) {
1797 				if (dtrace_bcmp(
1798 				    (void *)(uintptr_t)key[i].dttk_value,
1799 				    (void *)(uintptr_t)dkey->dttk_value,
1800 				    dkey->dttk_size))
1801 					goto next;
1802 			} else {
1803 				if (dkey->dttk_value != key[i].dttk_value)
1804 					goto next;
1805 			}
1806 		}
1807 
1808 		if (op != DTRACE_DYNVAR_DEALLOC)
1809 			return (dvar);
1810 
1811 		ASSERT(dvar->dtdv_next == NULL ||
1812 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1813 
1814 		if (prev != NULL) {
1815 			ASSERT(hash[bucket].dtdh_chain != dvar);
1816 			ASSERT(start != dvar);
1817 			ASSERT(prev->dtdv_next == dvar);
1818 			prev->dtdv_next = dvar->dtdv_next;
1819 		} else {
1820 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1821 			    start, dvar->dtdv_next) != start) {
1822 				/*
1823 				 * We have failed to atomically swing the
1824 				 * hash table head pointer, presumably because
1825 				 * of a conflicting allocation on another CPU.
1826 				 * We need to reread the hash chain and try
1827 				 * again.
1828 				 */
1829 				goto top;
1830 			}
1831 		}
1832 
1833 		dtrace_membar_producer();
1834 
1835 		/*
1836 		 * Now set the hash value to indicate that it's free.
1837 		 */
1838 		ASSERT(hash[bucket].dtdh_chain != dvar);
1839 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1840 
1841 		dtrace_membar_producer();
1842 
1843 		/*
1844 		 * Set the next pointer to point at the dirty list, and
1845 		 * atomically swing the dirty pointer to the newly freed dvar.
1846 		 */
1847 		do {
1848 			next = dcpu->dtdsc_dirty;
1849 			dvar->dtdv_next = next;
1850 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1851 
1852 		/*
1853 		 * Finally, unlock this hash bucket.
1854 		 */
1855 		ASSERT(hash[bucket].dtdh_lock == lock);
1856 		ASSERT(lock & 1);
1857 		hash[bucket].dtdh_lock++;
1858 
1859 		return (NULL);
1860 next:
1861 		prev = dvar;
1862 		continue;
1863 	}
1864 
1865 	if (dvar == NULL) {
1866 		/*
1867 		 * If dvar is NULL, it is because we went off the rails:
1868 		 * one of the elements that we traversed in the hash chain
1869 		 * was deleted while we were traversing it.  In this case,
1870 		 * we assert that we aren't doing a dealloc (deallocs lock
1871 		 * the hash bucket to prevent themselves from racing with
1872 		 * one another), and retry the hash chain traversal.
1873 		 */
1874 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1875 		goto top;
1876 	}
1877 
1878 	if (op != DTRACE_DYNVAR_ALLOC) {
1879 		/*
1880 		 * If we are not to allocate a new variable, we want to
1881 		 * return NULL now.  Before we return, check that the value
1882 		 * of the lock word hasn't changed.  If it has, we may have
1883 		 * seen an inconsistent snapshot.
1884 		 */
1885 		if (op == DTRACE_DYNVAR_NOALLOC) {
1886 			if (hash[bucket].dtdh_lock != lock)
1887 				goto top;
1888 		} else {
1889 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1890 			ASSERT(hash[bucket].dtdh_lock == lock);
1891 			ASSERT(lock & 1);
1892 			hash[bucket].dtdh_lock++;
1893 		}
1894 
1895 		return (NULL);
1896 	}
1897 
1898 	/*
1899 	 * We need to allocate a new dynamic variable.  The size we need is the
1900 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1901 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1902 	 * the size of any referred-to data (dsize).  We then round the final
1903 	 * size up to the chunksize for allocation.
1904 	 */
1905 	for (ksize = 0, i = 0; i < nkeys; i++)
1906 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1907 
1908 	/*
1909 	 * This should be pretty much impossible, but could happen if, say,
1910 	 * strange DIF specified the tuple.  Ideally, this should be an
1911 	 * assertion and not an error condition -- but that requires that the
1912 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1913 	 * bullet-proof.  (That is, it must not be able to be fooled by
1914 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1915 	 * solving this would presumably not amount to solving the Halting
1916 	 * Problem -- but it still seems awfully hard.
1917 	 */
1918 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1919 	    ksize + dsize > chunksize) {
1920 		dcpu->dtdsc_drops++;
1921 		return (NULL);
1922 	}
1923 
1924 	nstate = DTRACE_DSTATE_EMPTY;
1925 
1926 	do {
1927 retry:
1928 		free = dcpu->dtdsc_free;
1929 
1930 		if (free == NULL) {
1931 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1932 			void *rval;
1933 
1934 			if (clean == NULL) {
1935 				/*
1936 				 * We're out of dynamic variable space on
1937 				 * this CPU.  Unless we have tried all CPUs,
1938 				 * we'll try to allocate from a different
1939 				 * CPU.
1940 				 */
1941 				switch (dstate->dtds_state) {
1942 				case DTRACE_DSTATE_CLEAN: {
1943 					void *sp = &dstate->dtds_state;
1944 
1945 					if (++cpu >= NCPU)
1946 						cpu = 0;
1947 
1948 					if (dcpu->dtdsc_dirty != NULL &&
1949 					    nstate == DTRACE_DSTATE_EMPTY)
1950 						nstate = DTRACE_DSTATE_DIRTY;
1951 
1952 					if (dcpu->dtdsc_rinsing != NULL)
1953 						nstate = DTRACE_DSTATE_RINSING;
1954 
1955 					dcpu = &dstate->dtds_percpu[cpu];
1956 
1957 					if (cpu != me)
1958 						goto retry;
1959 
1960 					(void) dtrace_cas32(sp,
1961 					    DTRACE_DSTATE_CLEAN, nstate);
1962 
1963 					/*
1964 					 * To increment the correct bean
1965 					 * counter, take another lap.
1966 					 */
1967 					goto retry;
1968 				}
1969 
1970 				case DTRACE_DSTATE_DIRTY:
1971 					dcpu->dtdsc_dirty_drops++;
1972 					break;
1973 
1974 				case DTRACE_DSTATE_RINSING:
1975 					dcpu->dtdsc_rinsing_drops++;
1976 					break;
1977 
1978 				case DTRACE_DSTATE_EMPTY:
1979 					dcpu->dtdsc_drops++;
1980 					break;
1981 				}
1982 
1983 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1984 				return (NULL);
1985 			}
1986 
1987 			/*
1988 			 * The clean list appears to be non-empty.  We want to
1989 			 * move the clean list to the free list; we start by
1990 			 * moving the clean pointer aside.
1991 			 */
1992 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1993 			    clean, NULL) != clean) {
1994 				/*
1995 				 * We are in one of two situations:
1996 				 *
1997 				 *  (a)	The clean list was switched to the
1998 				 *	free list by another CPU.
1999 				 *
2000 				 *  (b)	The clean list was added to by the
2001 				 *	cleansing cyclic.
2002 				 *
2003 				 * In either of these situations, we can
2004 				 * just reattempt the free list allocation.
2005 				 */
2006 				goto retry;
2007 			}
2008 
2009 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2010 
2011 			/*
2012 			 * Now we'll move the clean list to our free list.
2013 			 * It's impossible for this to fail:  the only way
2014 			 * the free list can be updated is through this
2015 			 * code path, and only one CPU can own the clean list.
2016 			 * Thus, it would only be possible for this to fail if
2017 			 * this code were racing with dtrace_dynvar_clean().
2018 			 * (That is, if dtrace_dynvar_clean() updated the clean
2019 			 * list, and we ended up racing to update the free
2020 			 * list.)  This race is prevented by the dtrace_sync()
2021 			 * in dtrace_dynvar_clean() -- which flushes the
2022 			 * owners of the clean lists out before resetting
2023 			 * the clean lists.
2024 			 */
2025 			dcpu = &dstate->dtds_percpu[me];
2026 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2027 			ASSERT(rval == NULL);
2028 			goto retry;
2029 		}
2030 
2031 		dvar = free;
2032 		new_free = dvar->dtdv_next;
2033 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2034 
2035 	/*
2036 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2037 	 * tuple array and copy any referenced key data into the data space
2038 	 * following the tuple array.  As we do this, we relocate dttk_value
2039 	 * in the final tuple to point to the key data address in the chunk.
2040 	 */
2041 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2042 	dvar->dtdv_data = (void *)(kdata + ksize);
2043 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2044 
2045 	for (i = 0; i < nkeys; i++) {
2046 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2047 		size_t kesize = key[i].dttk_size;
2048 
2049 		if (kesize != 0) {
2050 			dtrace_bcopy(
2051 			    (const void *)(uintptr_t)key[i].dttk_value,
2052 			    (void *)kdata, kesize);
2053 			dkey->dttk_value = kdata;
2054 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2055 		} else {
2056 			dkey->dttk_value = key[i].dttk_value;
2057 		}
2058 
2059 		dkey->dttk_size = kesize;
2060 	}
2061 
2062 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2063 	dvar->dtdv_hashval = hashval;
2064 	dvar->dtdv_next = start;
2065 
2066 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2067 		return (dvar);
2068 
2069 	/*
2070 	 * The cas has failed.  Either another CPU is adding an element to
2071 	 * this hash chain, or another CPU is deleting an element from this
2072 	 * hash chain.  The simplest way to deal with both of these cases
2073 	 * (though not necessarily the most efficient) is to free our
2074 	 * allocated block and re-attempt it all.  Note that the free is
2075 	 * to the dirty list and _not_ to the free list.  This is to prevent
2076 	 * races with allocators, above.
2077 	 */
2078 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2079 
2080 	dtrace_membar_producer();
2081 
2082 	do {
2083 		free = dcpu->dtdsc_dirty;
2084 		dvar->dtdv_next = free;
2085 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2086 
2087 	goto top;
2088 }
2089 
2090 /*ARGSUSED*/
2091 static void
2092 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2093 {
2094 	if ((int64_t)nval < (int64_t)*oval)
2095 		*oval = nval;
2096 }
2097 
2098 /*ARGSUSED*/
2099 static void
2100 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2101 {
2102 	if ((int64_t)nval > (int64_t)*oval)
2103 		*oval = nval;
2104 }
2105 
2106 static void
2107 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2108 {
2109 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2110 	int64_t val = (int64_t)nval;
2111 
2112 	if (val < 0) {
2113 		for (i = 0; i < zero; i++) {
2114 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2115 				quanta[i] += incr;
2116 				return;
2117 			}
2118 		}
2119 	} else {
2120 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2121 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2122 				quanta[i - 1] += incr;
2123 				return;
2124 			}
2125 		}
2126 
2127 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2128 		return;
2129 	}
2130 
2131 	ASSERT(0);
2132 }
2133 
2134 static void
2135 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2136 {
2137 	uint64_t arg = *lquanta++;
2138 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2139 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2140 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2141 	int32_t val = (int32_t)nval, level;
2142 
2143 	ASSERT(step != 0);
2144 	ASSERT(levels != 0);
2145 
2146 	if (val < base) {
2147 		/*
2148 		 * This is an underflow.
2149 		 */
2150 		lquanta[0] += incr;
2151 		return;
2152 	}
2153 
2154 	level = (val - base) / step;
2155 
2156 	if (level < levels) {
2157 		lquanta[level + 1] += incr;
2158 		return;
2159 	}
2160 
2161 	/*
2162 	 * This is an overflow.
2163 	 */
2164 	lquanta[levels + 1] += incr;
2165 }
2166 
2167 static int
2168 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2169     uint16_t high, uint16_t nsteps, int64_t value)
2170 {
2171 	int64_t this = 1, last, next;
2172 	int base = 1, order;
2173 
2174 	ASSERT(factor <= nsteps);
2175 	ASSERT(nsteps % factor == 0);
2176 
2177 	for (order = 0; order < low; order++)
2178 		this *= factor;
2179 
2180 	/*
2181 	 * If our value is less than our factor taken to the power of the
2182 	 * low order of magnitude, it goes into the zeroth bucket.
2183 	 */
2184 	if (value < (last = this))
2185 		return (0);
2186 
2187 	for (this *= factor; order <= high; order++) {
2188 		int nbuckets = this > nsteps ? nsteps : this;
2189 
2190 		if ((next = this * factor) < this) {
2191 			/*
2192 			 * We should not generally get log/linear quantizations
2193 			 * with a high magnitude that allows 64-bits to
2194 			 * overflow, but we nonetheless protect against this
2195 			 * by explicitly checking for overflow, and clamping
2196 			 * our value accordingly.
2197 			 */
2198 			value = this - 1;
2199 		}
2200 
2201 		if (value < this) {
2202 			/*
2203 			 * If our value lies within this order of magnitude,
2204 			 * determine its position by taking the offset within
2205 			 * the order of magnitude, dividing by the bucket
2206 			 * width, and adding to our (accumulated) base.
2207 			 */
2208 			return (base + (value - last) / (this / nbuckets));
2209 		}
2210 
2211 		base += nbuckets - (nbuckets / factor);
2212 		last = this;
2213 		this = next;
2214 	}
2215 
2216 	/*
2217 	 * Our value is greater than or equal to our factor taken to the
2218 	 * power of one plus the high magnitude -- return the top bucket.
2219 	 */
2220 	return (base);
2221 }
2222 
2223 static void
2224 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2225 {
2226 	uint64_t arg = *llquanta++;
2227 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2228 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2229 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2230 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2231 
2232 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
2233 	    low, high, nsteps, nval)] += incr;
2234 }
2235 
2236 /*ARGSUSED*/
2237 static void
2238 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2239 {
2240 	data[0]++;
2241 	data[1] += nval;
2242 }
2243 
2244 /*ARGSUSED*/
2245 static void
2246 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2247 {
2248 	int64_t snval = (int64_t)nval;
2249 	uint64_t tmp[2];
2250 
2251 	data[0]++;
2252 	data[1] += nval;
2253 
2254 	/*
2255 	 * What we want to say here is:
2256 	 *
2257 	 * data[2] += nval * nval;
2258 	 *
2259 	 * But given that nval is 64-bit, we could easily overflow, so
2260 	 * we do this as 128-bit arithmetic.
2261 	 */
2262 	if (snval < 0)
2263 		snval = -snval;
2264 
2265 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2266 	dtrace_add_128(data + 2, tmp, data + 2);
2267 }
2268 
2269 /*ARGSUSED*/
2270 static void
2271 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2272 {
2273 	*oval = *oval + 1;
2274 }
2275 
2276 /*ARGSUSED*/
2277 static void
2278 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2279 {
2280 	*oval += nval;
2281 }
2282 
2283 /*
2284  * Aggregate given the tuple in the principal data buffer, and the aggregating
2285  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2286  * buffer is specified as the buf parameter.  This routine does not return
2287  * failure; if there is no space in the aggregation buffer, the data will be
2288  * dropped, and a corresponding counter incremented.
2289  */
2290 static void
2291 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2292     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2293 {
2294 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2295 	uint32_t i, ndx, size, fsize;
2296 	uint32_t align = sizeof (uint64_t) - 1;
2297 	dtrace_aggbuffer_t *agb;
2298 	dtrace_aggkey_t *key;
2299 	uint32_t hashval = 0, limit, isstr;
2300 	caddr_t tomax, data, kdata;
2301 	dtrace_actkind_t action;
2302 	dtrace_action_t *act;
2303 	uintptr_t offs;
2304 
2305 	if (buf == NULL)
2306 		return;
2307 
2308 	if (!agg->dtag_hasarg) {
2309 		/*
2310 		 * Currently, only quantize() and lquantize() take additional
2311 		 * arguments, and they have the same semantics:  an increment
2312 		 * value that defaults to 1 when not present.  If additional
2313 		 * aggregating actions take arguments, the setting of the
2314 		 * default argument value will presumably have to become more
2315 		 * sophisticated...
2316 		 */
2317 		arg = 1;
2318 	}
2319 
2320 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2321 	size = rec->dtrd_offset - agg->dtag_base;
2322 	fsize = size + rec->dtrd_size;
2323 
2324 	ASSERT(dbuf->dtb_tomax != NULL);
2325 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2326 
2327 	if ((tomax = buf->dtb_tomax) == NULL) {
2328 		dtrace_buffer_drop(buf);
2329 		return;
2330 	}
2331 
2332 	/*
2333 	 * The metastructure is always at the bottom of the buffer.
2334 	 */
2335 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2336 	    sizeof (dtrace_aggbuffer_t));
2337 
2338 	if (buf->dtb_offset == 0) {
2339 		/*
2340 		 * We just kludge up approximately 1/8th of the size to be
2341 		 * buckets.  If this guess ends up being routinely
2342 		 * off-the-mark, we may need to dynamically readjust this
2343 		 * based on past performance.
2344 		 */
2345 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2346 
2347 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2348 		    (uintptr_t)tomax || hashsize == 0) {
2349 			/*
2350 			 * We've been given a ludicrously small buffer;
2351 			 * increment our drop count and leave.
2352 			 */
2353 			dtrace_buffer_drop(buf);
2354 			return;
2355 		}
2356 
2357 		/*
2358 		 * And now, a pathetic attempt to try to get a an odd (or
2359 		 * perchance, a prime) hash size for better hash distribution.
2360 		 */
2361 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2362 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2363 
2364 		agb->dtagb_hashsize = hashsize;
2365 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2366 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2367 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2368 
2369 		for (i = 0; i < agb->dtagb_hashsize; i++)
2370 			agb->dtagb_hash[i] = NULL;
2371 	}
2372 
2373 	ASSERT(agg->dtag_first != NULL);
2374 	ASSERT(agg->dtag_first->dta_intuple);
2375 
2376 	/*
2377 	 * Calculate the hash value based on the key.  Note that we _don't_
2378 	 * include the aggid in the hashing (but we will store it as part of
2379 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2380 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2381 	 * gets good distribution in practice.  The efficacy of the hashing
2382 	 * algorithm (and a comparison with other algorithms) may be found by
2383 	 * running the ::dtrace_aggstat MDB dcmd.
2384 	 */
2385 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2386 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2387 		limit = i + act->dta_rec.dtrd_size;
2388 		ASSERT(limit <= size);
2389 		isstr = DTRACEACT_ISSTRING(act);
2390 
2391 		for (; i < limit; i++) {
2392 			hashval += data[i];
2393 			hashval += (hashval << 10);
2394 			hashval ^= (hashval >> 6);
2395 
2396 			if (isstr && data[i] == '\0')
2397 				break;
2398 		}
2399 	}
2400 
2401 	hashval += (hashval << 3);
2402 	hashval ^= (hashval >> 11);
2403 	hashval += (hashval << 15);
2404 
2405 	/*
2406 	 * Yes, the divide here is expensive -- but it's generally the least
2407 	 * of the performance issues given the amount of data that we iterate
2408 	 * over to compute hash values, compare data, etc.
2409 	 */
2410 	ndx = hashval % agb->dtagb_hashsize;
2411 
2412 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2413 		ASSERT((caddr_t)key >= tomax);
2414 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2415 
2416 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2417 			continue;
2418 
2419 		kdata = key->dtak_data;
2420 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2421 
2422 		for (act = agg->dtag_first; act->dta_intuple;
2423 		    act = act->dta_next) {
2424 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2425 			limit = i + act->dta_rec.dtrd_size;
2426 			ASSERT(limit <= size);
2427 			isstr = DTRACEACT_ISSTRING(act);
2428 
2429 			for (; i < limit; i++) {
2430 				if (kdata[i] != data[i])
2431 					goto next;
2432 
2433 				if (isstr && data[i] == '\0')
2434 					break;
2435 			}
2436 		}
2437 
2438 		if (action != key->dtak_action) {
2439 			/*
2440 			 * We are aggregating on the same value in the same
2441 			 * aggregation with two different aggregating actions.
2442 			 * (This should have been picked up in the compiler,
2443 			 * so we may be dealing with errant or devious DIF.)
2444 			 * This is an error condition; we indicate as much,
2445 			 * and return.
2446 			 */
2447 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2448 			return;
2449 		}
2450 
2451 		/*
2452 		 * This is a hit:  we need to apply the aggregator to
2453 		 * the value at this key.
2454 		 */
2455 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2456 		return;
2457 next:
2458 		continue;
2459 	}
2460 
2461 	/*
2462 	 * We didn't find it.  We need to allocate some zero-filled space,
2463 	 * link it into the hash table appropriately, and apply the aggregator
2464 	 * to the (zero-filled) value.
2465 	 */
2466 	offs = buf->dtb_offset;
2467 	while (offs & (align - 1))
2468 		offs += sizeof (uint32_t);
2469 
2470 	/*
2471 	 * If we don't have enough room to both allocate a new key _and_
2472 	 * its associated data, increment the drop count and return.
2473 	 */
2474 	if ((uintptr_t)tomax + offs + fsize >
2475 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2476 		dtrace_buffer_drop(buf);
2477 		return;
2478 	}
2479 
2480 	/*CONSTCOND*/
2481 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2482 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2483 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2484 
2485 	key->dtak_data = kdata = tomax + offs;
2486 	buf->dtb_offset = offs + fsize;
2487 
2488 	/*
2489 	 * Now copy the data across.
2490 	 */
2491 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2492 
2493 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2494 		kdata[i] = data[i];
2495 
2496 	/*
2497 	 * Because strings are not zeroed out by default, we need to iterate
2498 	 * looking for actions that store strings, and we need to explicitly
2499 	 * pad these strings out with zeroes.
2500 	 */
2501 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2502 		int nul;
2503 
2504 		if (!DTRACEACT_ISSTRING(act))
2505 			continue;
2506 
2507 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2508 		limit = i + act->dta_rec.dtrd_size;
2509 		ASSERT(limit <= size);
2510 
2511 		for (nul = 0; i < limit; i++) {
2512 			if (nul) {
2513 				kdata[i] = '\0';
2514 				continue;
2515 			}
2516 
2517 			if (data[i] != '\0')
2518 				continue;
2519 
2520 			nul = 1;
2521 		}
2522 	}
2523 
2524 	for (i = size; i < fsize; i++)
2525 		kdata[i] = 0;
2526 
2527 	key->dtak_hashval = hashval;
2528 	key->dtak_size = size;
2529 	key->dtak_action = action;
2530 	key->dtak_next = agb->dtagb_hash[ndx];
2531 	agb->dtagb_hash[ndx] = key;
2532 
2533 	/*
2534 	 * Finally, apply the aggregator.
2535 	 */
2536 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2537 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2538 }
2539 
2540 /*
2541  * Given consumer state, this routine finds a speculation in the INACTIVE
2542  * state and transitions it into the ACTIVE state.  If there is no speculation
2543  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2544  * incremented -- it is up to the caller to take appropriate action.
2545  */
2546 static int
2547 dtrace_speculation(dtrace_state_t *state)
2548 {
2549 	int i = 0;
2550 	dtrace_speculation_state_t current;
2551 	uint32_t *stat = &state->dts_speculations_unavail, count;
2552 
2553 	while (i < state->dts_nspeculations) {
2554 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2555 
2556 		current = spec->dtsp_state;
2557 
2558 		if (current != DTRACESPEC_INACTIVE) {
2559 			if (current == DTRACESPEC_COMMITTINGMANY ||
2560 			    current == DTRACESPEC_COMMITTING ||
2561 			    current == DTRACESPEC_DISCARDING)
2562 				stat = &state->dts_speculations_busy;
2563 			i++;
2564 			continue;
2565 		}
2566 
2567 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2568 		    current, DTRACESPEC_ACTIVE) == current)
2569 			return (i + 1);
2570 	}
2571 
2572 	/*
2573 	 * We couldn't find a speculation.  If we found as much as a single
2574 	 * busy speculation buffer, we'll attribute this failure as "busy"
2575 	 * instead of "unavail".
2576 	 */
2577 	do {
2578 		count = *stat;
2579 	} while (dtrace_cas32(stat, count, count + 1) != count);
2580 
2581 	return (0);
2582 }
2583 
2584 /*
2585  * This routine commits an active speculation.  If the specified speculation
2586  * is not in a valid state to perform a commit(), this routine will silently do
2587  * nothing.  The state of the specified speculation is transitioned according
2588  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2589  */
2590 static void
2591 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2592     dtrace_specid_t which)
2593 {
2594 	dtrace_speculation_t *spec;
2595 	dtrace_buffer_t *src, *dest;
2596 	uintptr_t daddr, saddr, dlimit, slimit;
2597 	dtrace_speculation_state_t current, new;
2598 	intptr_t offs;
2599 	uint64_t timestamp;
2600 
2601 	if (which == 0)
2602 		return;
2603 
2604 	if (which > state->dts_nspeculations) {
2605 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2606 		return;
2607 	}
2608 
2609 	spec = &state->dts_speculations[which - 1];
2610 	src = &spec->dtsp_buffer[cpu];
2611 	dest = &state->dts_buffer[cpu];
2612 
2613 	do {
2614 		current = spec->dtsp_state;
2615 
2616 		if (current == DTRACESPEC_COMMITTINGMANY)
2617 			break;
2618 
2619 		switch (current) {
2620 		case DTRACESPEC_INACTIVE:
2621 		case DTRACESPEC_DISCARDING:
2622 			return;
2623 
2624 		case DTRACESPEC_COMMITTING:
2625 			/*
2626 			 * This is only possible if we are (a) commit()'ing
2627 			 * without having done a prior speculate() on this CPU
2628 			 * and (b) racing with another commit() on a different
2629 			 * CPU.  There's nothing to do -- we just assert that
2630 			 * our offset is 0.
2631 			 */
2632 			ASSERT(src->dtb_offset == 0);
2633 			return;
2634 
2635 		case DTRACESPEC_ACTIVE:
2636 			new = DTRACESPEC_COMMITTING;
2637 			break;
2638 
2639 		case DTRACESPEC_ACTIVEONE:
2640 			/*
2641 			 * This speculation is active on one CPU.  If our
2642 			 * buffer offset is non-zero, we know that the one CPU
2643 			 * must be us.  Otherwise, we are committing on a
2644 			 * different CPU from the speculate(), and we must
2645 			 * rely on being asynchronously cleaned.
2646 			 */
2647 			if (src->dtb_offset != 0) {
2648 				new = DTRACESPEC_COMMITTING;
2649 				break;
2650 			}
2651 			/*FALLTHROUGH*/
2652 
2653 		case DTRACESPEC_ACTIVEMANY:
2654 			new = DTRACESPEC_COMMITTINGMANY;
2655 			break;
2656 
2657 		default:
2658 			ASSERT(0);
2659 		}
2660 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2661 	    current, new) != current);
2662 
2663 	/*
2664 	 * We have set the state to indicate that we are committing this
2665 	 * speculation.  Now reserve the necessary space in the destination
2666 	 * buffer.
2667 	 */
2668 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2669 	    sizeof (uint64_t), state, NULL)) < 0) {
2670 		dtrace_buffer_drop(dest);
2671 		goto out;
2672 	}
2673 
2674 	/*
2675 	 * We have sufficient space to copy the speculative buffer into the
2676 	 * primary buffer.  First, modify the speculative buffer, filling
2677 	 * in the timestamp of all entries with the current time.  The data
2678 	 * must have the commit() time rather than the time it was traced,
2679 	 * so that all entries in the primary buffer are in timestamp order.
2680 	 */
2681 	timestamp = dtrace_gethrtime();
2682 	saddr = (uintptr_t)src->dtb_tomax;
2683 	slimit = saddr + src->dtb_offset;
2684 	while (saddr < slimit) {
2685 		size_t size;
2686 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2687 
2688 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2689 			saddr += sizeof (dtrace_epid_t);
2690 			continue;
2691 		}
2692 		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2693 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2694 
2695 		ASSERT3U(saddr + size, <=, slimit);
2696 		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2697 		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2698 
2699 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2700 
2701 		saddr += size;
2702 	}
2703 
2704 	/*
2705 	 * Copy the buffer across.  (Note that this is a
2706 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2707 	 * a serious performance issue, a high-performance DTrace-specific
2708 	 * bcopy() should obviously be invented.)
2709 	 */
2710 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2711 	dlimit = daddr + src->dtb_offset;
2712 	saddr = (uintptr_t)src->dtb_tomax;
2713 
2714 	/*
2715 	 * First, the aligned portion.
2716 	 */
2717 	while (dlimit - daddr >= sizeof (uint64_t)) {
2718 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2719 
2720 		daddr += sizeof (uint64_t);
2721 		saddr += sizeof (uint64_t);
2722 	}
2723 
2724 	/*
2725 	 * Now any left-over bit...
2726 	 */
2727 	while (dlimit - daddr)
2728 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2729 
2730 	/*
2731 	 * Finally, commit the reserved space in the destination buffer.
2732 	 */
2733 	dest->dtb_offset = offs + src->dtb_offset;
2734 
2735 out:
2736 	/*
2737 	 * If we're lucky enough to be the only active CPU on this speculation
2738 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2739 	 */
2740 	if (current == DTRACESPEC_ACTIVE ||
2741 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2742 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2743 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2744 
2745 		ASSERT(rval == DTRACESPEC_COMMITTING);
2746 	}
2747 
2748 	src->dtb_offset = 0;
2749 	src->dtb_xamot_drops += src->dtb_drops;
2750 	src->dtb_drops = 0;
2751 }
2752 
2753 /*
2754  * This routine discards an active speculation.  If the specified speculation
2755  * is not in a valid state to perform a discard(), this routine will silently
2756  * do nothing.  The state of the specified speculation is transitioned
2757  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2758  */
2759 static void
2760 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2761     dtrace_specid_t which)
2762 {
2763 	dtrace_speculation_t *spec;
2764 	dtrace_speculation_state_t current, new;
2765 	dtrace_buffer_t *buf;
2766 
2767 	if (which == 0)
2768 		return;
2769 
2770 	if (which > state->dts_nspeculations) {
2771 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2772 		return;
2773 	}
2774 
2775 	spec = &state->dts_speculations[which - 1];
2776 	buf = &spec->dtsp_buffer[cpu];
2777 
2778 	do {
2779 		current = spec->dtsp_state;
2780 
2781 		switch (current) {
2782 		case DTRACESPEC_INACTIVE:
2783 		case DTRACESPEC_COMMITTINGMANY:
2784 		case DTRACESPEC_COMMITTING:
2785 		case DTRACESPEC_DISCARDING:
2786 			return;
2787 
2788 		case DTRACESPEC_ACTIVE:
2789 		case DTRACESPEC_ACTIVEMANY:
2790 			new = DTRACESPEC_DISCARDING;
2791 			break;
2792 
2793 		case DTRACESPEC_ACTIVEONE:
2794 			if (buf->dtb_offset != 0) {
2795 				new = DTRACESPEC_INACTIVE;
2796 			} else {
2797 				new = DTRACESPEC_DISCARDING;
2798 			}
2799 			break;
2800 
2801 		default:
2802 			ASSERT(0);
2803 		}
2804 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2805 	    current, new) != current);
2806 
2807 	buf->dtb_offset = 0;
2808 	buf->dtb_drops = 0;
2809 }
2810 
2811 /*
2812  * Note:  not called from probe context.  This function is called
2813  * asynchronously from cross call context to clean any speculations that are
2814  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2815  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2816  * speculation.
2817  */
2818 static void
2819 dtrace_speculation_clean_here(dtrace_state_t *state)
2820 {
2821 	dtrace_icookie_t cookie;
2822 	processorid_t cpu = CPU->cpu_id;
2823 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2824 	dtrace_specid_t i;
2825 
2826 	cookie = dtrace_interrupt_disable();
2827 
2828 	if (dest->dtb_tomax == NULL) {
2829 		dtrace_interrupt_enable(cookie);
2830 		return;
2831 	}
2832 
2833 	for (i = 0; i < state->dts_nspeculations; i++) {
2834 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2835 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2836 
2837 		if (src->dtb_tomax == NULL)
2838 			continue;
2839 
2840 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2841 			src->dtb_offset = 0;
2842 			continue;
2843 		}
2844 
2845 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2846 			continue;
2847 
2848 		if (src->dtb_offset == 0)
2849 			continue;
2850 
2851 		dtrace_speculation_commit(state, cpu, i + 1);
2852 	}
2853 
2854 	dtrace_interrupt_enable(cookie);
2855 }
2856 
2857 /*
2858  * Note:  not called from probe context.  This function is called
2859  * asynchronously (and at a regular interval) to clean any speculations that
2860  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2861  * is work to be done, it cross calls all CPUs to perform that work;
2862  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2863  * INACTIVE state until they have been cleaned by all CPUs.
2864  */
2865 static void
2866 dtrace_speculation_clean(dtrace_state_t *state)
2867 {
2868 	int work = 0, rv;
2869 	dtrace_specid_t i;
2870 
2871 	for (i = 0; i < state->dts_nspeculations; i++) {
2872 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2873 
2874 		ASSERT(!spec->dtsp_cleaning);
2875 
2876 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2877 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2878 			continue;
2879 
2880 		work++;
2881 		spec->dtsp_cleaning = 1;
2882 	}
2883 
2884 	if (!work)
2885 		return;
2886 
2887 	dtrace_xcall(DTRACE_CPUALL,
2888 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2889 
2890 	/*
2891 	 * We now know that all CPUs have committed or discarded their
2892 	 * speculation buffers, as appropriate.  We can now set the state
2893 	 * to inactive.
2894 	 */
2895 	for (i = 0; i < state->dts_nspeculations; i++) {
2896 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2897 		dtrace_speculation_state_t current, new;
2898 
2899 		if (!spec->dtsp_cleaning)
2900 			continue;
2901 
2902 		current = spec->dtsp_state;
2903 		ASSERT(current == DTRACESPEC_DISCARDING ||
2904 		    current == DTRACESPEC_COMMITTINGMANY);
2905 
2906 		new = DTRACESPEC_INACTIVE;
2907 
2908 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2909 		ASSERT(rv == current);
2910 		spec->dtsp_cleaning = 0;
2911 	}
2912 }
2913 
2914 /*
2915  * Called as part of a speculate() to get the speculative buffer associated
2916  * with a given speculation.  Returns NULL if the specified speculation is not
2917  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2918  * the active CPU is not the specified CPU -- the speculation will be
2919  * atomically transitioned into the ACTIVEMANY state.
2920  */
2921 static dtrace_buffer_t *
2922 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2923     dtrace_specid_t which)
2924 {
2925 	dtrace_speculation_t *spec;
2926 	dtrace_speculation_state_t current, new;
2927 	dtrace_buffer_t *buf;
2928 
2929 	if (which == 0)
2930 		return (NULL);
2931 
2932 	if (which > state->dts_nspeculations) {
2933 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2934 		return (NULL);
2935 	}
2936 
2937 	spec = &state->dts_speculations[which - 1];
2938 	buf = &spec->dtsp_buffer[cpuid];
2939 
2940 	do {
2941 		current = spec->dtsp_state;
2942 
2943 		switch (current) {
2944 		case DTRACESPEC_INACTIVE:
2945 		case DTRACESPEC_COMMITTINGMANY:
2946 		case DTRACESPEC_DISCARDING:
2947 			return (NULL);
2948 
2949 		case DTRACESPEC_COMMITTING:
2950 			ASSERT(buf->dtb_offset == 0);
2951 			return (NULL);
2952 
2953 		case DTRACESPEC_ACTIVEONE:
2954 			/*
2955 			 * This speculation is currently active on one CPU.
2956 			 * Check the offset in the buffer; if it's non-zero,
2957 			 * that CPU must be us (and we leave the state alone).
2958 			 * If it's zero, assume that we're starting on a new
2959 			 * CPU -- and change the state to indicate that the
2960 			 * speculation is active on more than one CPU.
2961 			 */
2962 			if (buf->dtb_offset != 0)
2963 				return (buf);
2964 
2965 			new = DTRACESPEC_ACTIVEMANY;
2966 			break;
2967 
2968 		case DTRACESPEC_ACTIVEMANY:
2969 			return (buf);
2970 
2971 		case DTRACESPEC_ACTIVE:
2972 			new = DTRACESPEC_ACTIVEONE;
2973 			break;
2974 
2975 		default:
2976 			ASSERT(0);
2977 		}
2978 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2979 	    current, new) != current);
2980 
2981 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2982 	return (buf);
2983 }
2984 
2985 /*
2986  * Return a string.  In the event that the user lacks the privilege to access
2987  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2988  * don't fail access checking.
2989  *
2990  * dtrace_dif_variable() uses this routine as a helper for various
2991  * builtin values such as 'execname' and 'probefunc.'
2992  */
2993 uintptr_t
2994 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2995     dtrace_mstate_t *mstate)
2996 {
2997 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2998 	uintptr_t ret;
2999 	size_t strsz;
3000 
3001 	/*
3002 	 * The easy case: this probe is allowed to read all of memory, so
3003 	 * we can just return this as a vanilla pointer.
3004 	 */
3005 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3006 		return (addr);
3007 
3008 	/*
3009 	 * This is the tougher case: we copy the string in question from
3010 	 * kernel memory into scratch memory and return it that way: this
3011 	 * ensures that we won't trip up when access checking tests the
3012 	 * BYREF return value.
3013 	 */
3014 	strsz = dtrace_strlen((char *)addr, size) + 1;
3015 
3016 	if (mstate->dtms_scratch_ptr + strsz >
3017 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3018 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3019 		return (NULL);
3020 	}
3021 
3022 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3023 	    strsz);
3024 	ret = mstate->dtms_scratch_ptr;
3025 	mstate->dtms_scratch_ptr += strsz;
3026 	return (ret);
3027 }
3028 
3029 /*
3030  * This function implements the DIF emulator's variable lookups.  The emulator
3031  * passes a reserved variable identifier and optional built-in array index.
3032  */
3033 static uint64_t
3034 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3035     uint64_t ndx)
3036 {
3037 	/*
3038 	 * If we're accessing one of the uncached arguments, we'll turn this
3039 	 * into a reference in the args array.
3040 	 */
3041 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3042 		ndx = v - DIF_VAR_ARG0;
3043 		v = DIF_VAR_ARGS;
3044 	}
3045 
3046 	switch (v) {
3047 	case DIF_VAR_ARGS:
3048 		if (!(mstate->dtms_access & DTRACE_ACCESS_ARGS)) {
3049 			cpu_core[CPU->cpu_id].cpuc_dtrace_flags |=
3050 			    CPU_DTRACE_KPRIV;
3051 			return (0);
3052 		}
3053 
3054 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3055 		if (ndx >= sizeof (mstate->dtms_arg) /
3056 		    sizeof (mstate->dtms_arg[0])) {
3057 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3058 			dtrace_provider_t *pv;
3059 			uint64_t val;
3060 
3061 			pv = mstate->dtms_probe->dtpr_provider;
3062 			if (pv->dtpv_pops.dtps_getargval != NULL)
3063 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3064 				    mstate->dtms_probe->dtpr_id,
3065 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
3066 			else
3067 				val = dtrace_getarg(ndx, aframes);
3068 
3069 			/*
3070 			 * This is regrettably required to keep the compiler
3071 			 * from tail-optimizing the call to dtrace_getarg().
3072 			 * The condition always evaluates to true, but the
3073 			 * compiler has no way of figuring that out a priori.
3074 			 * (None of this would be necessary if the compiler
3075 			 * could be relied upon to _always_ tail-optimize
3076 			 * the call to dtrace_getarg() -- but it can't.)
3077 			 */
3078 			if (mstate->dtms_probe != NULL)
3079 				return (val);
3080 
3081 			ASSERT(0);
3082 		}
3083 
3084 		return (mstate->dtms_arg[ndx]);
3085 
3086 	case DIF_VAR_UREGS: {
3087 		klwp_t *lwp;
3088 
3089 		if (!dtrace_priv_proc(state, mstate))
3090 			return (0);
3091 
3092 		if ((lwp = curthread->t_lwp) == NULL) {
3093 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3094 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
3095 			return (0);
3096 		}
3097 
3098 		return (dtrace_getreg(lwp->lwp_regs, ndx));
3099 	}
3100 
3101 	case DIF_VAR_VMREGS: {
3102 		uint64_t rval;
3103 
3104 		if (!dtrace_priv_kernel(state))
3105 			return (0);
3106 
3107 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3108 
3109 		rval = dtrace_getvmreg(ndx,
3110 		    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags);
3111 
3112 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3113 
3114 		return (rval);
3115 	}
3116 
3117 	case DIF_VAR_CURTHREAD:
3118 		if (!dtrace_priv_proc(state, mstate))
3119 			return (0);
3120 		return ((uint64_t)(uintptr_t)curthread);
3121 
3122 	case DIF_VAR_TIMESTAMP:
3123 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3124 			mstate->dtms_timestamp = dtrace_gethrtime();
3125 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3126 		}
3127 		return (mstate->dtms_timestamp);
3128 
3129 	case DIF_VAR_VTIMESTAMP:
3130 		ASSERT(dtrace_vtime_references != 0);
3131 		return (curthread->t_dtrace_vtime);
3132 
3133 	case DIF_VAR_WALLTIMESTAMP:
3134 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3135 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3136 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3137 		}
3138 		return (mstate->dtms_walltimestamp);
3139 
3140 	case DIF_VAR_IPL:
3141 		if (!dtrace_priv_kernel(state))
3142 			return (0);
3143 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3144 			mstate->dtms_ipl = dtrace_getipl();
3145 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3146 		}
3147 		return (mstate->dtms_ipl);
3148 
3149 	case DIF_VAR_EPID:
3150 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3151 		return (mstate->dtms_epid);
3152 
3153 	case DIF_VAR_ID:
3154 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3155 		return (mstate->dtms_probe->dtpr_id);
3156 
3157 	case DIF_VAR_STACKDEPTH:
3158 		if (!dtrace_priv_kernel(state))
3159 			return (0);
3160 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3161 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3162 
3163 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3164 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3165 		}
3166 		return (mstate->dtms_stackdepth);
3167 
3168 	case DIF_VAR_USTACKDEPTH:
3169 		if (!dtrace_priv_proc(state, mstate))
3170 			return (0);
3171 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3172 			/*
3173 			 * See comment in DIF_VAR_PID.
3174 			 */
3175 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3176 			    CPU_ON_INTR(CPU)) {
3177 				mstate->dtms_ustackdepth = 0;
3178 			} else {
3179 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3180 				mstate->dtms_ustackdepth =
3181 				    dtrace_getustackdepth();
3182 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3183 			}
3184 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3185 		}
3186 		return (mstate->dtms_ustackdepth);
3187 
3188 	case DIF_VAR_CALLER:
3189 		if (!dtrace_priv_kernel(state))
3190 			return (0);
3191 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3192 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3193 
3194 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3195 				/*
3196 				 * If this is an unanchored probe, we are
3197 				 * required to go through the slow path:
3198 				 * dtrace_caller() only guarantees correct
3199 				 * results for anchored probes.
3200 				 */
3201 				pc_t caller[2];
3202 
3203 				dtrace_getpcstack(caller, 2, aframes,
3204 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3205 				mstate->dtms_caller = caller[1];
3206 			} else if ((mstate->dtms_caller =
3207 			    dtrace_caller(aframes)) == -1) {
3208 				/*
3209 				 * We have failed to do this the quick way;
3210 				 * we must resort to the slower approach of
3211 				 * calling dtrace_getpcstack().
3212 				 */
3213 				pc_t caller;
3214 
3215 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3216 				mstate->dtms_caller = caller;
3217 			}
3218 
3219 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3220 		}
3221 		return (mstate->dtms_caller);
3222 
3223 	case DIF_VAR_UCALLER:
3224 		if (!dtrace_priv_proc(state, mstate))
3225 			return (0);
3226 
3227 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3228 			uint64_t ustack[3];
3229 
3230 			/*
3231 			 * dtrace_getupcstack() fills in the first uint64_t
3232 			 * with the current PID.  The second uint64_t will
3233 			 * be the program counter at user-level.  The third
3234 			 * uint64_t will contain the caller, which is what
3235 			 * we're after.
3236 			 */
3237 			ustack[2] = NULL;
3238 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3239 			dtrace_getupcstack(ustack, 3);
3240 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3241 			mstate->dtms_ucaller = ustack[2];
3242 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3243 		}
3244 
3245 		return (mstate->dtms_ucaller);
3246 
3247 	case DIF_VAR_PROBEPROV:
3248 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3249 		return (dtrace_dif_varstr(
3250 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3251 		    state, mstate));
3252 
3253 	case DIF_VAR_PROBEMOD:
3254 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3255 		return (dtrace_dif_varstr(
3256 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3257 		    state, mstate));
3258 
3259 	case DIF_VAR_PROBEFUNC:
3260 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3261 		return (dtrace_dif_varstr(
3262 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3263 		    state, mstate));
3264 
3265 	case DIF_VAR_PROBENAME:
3266 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3267 		return (dtrace_dif_varstr(
3268 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3269 		    state, mstate));
3270 
3271 	case DIF_VAR_PID:
3272 		if (!dtrace_priv_proc(state, mstate))
3273 			return (0);
3274 
3275 		/*
3276 		 * Note that we are assuming that an unanchored probe is
3277 		 * always due to a high-level interrupt.  (And we're assuming
3278 		 * that there is only a single high level interrupt.)
3279 		 */
3280 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3281 			return (pid0.pid_id);
3282 
3283 		/*
3284 		 * It is always safe to dereference one's own t_procp pointer:
3285 		 * it always points to a valid, allocated proc structure.
3286 		 * Further, it is always safe to dereference the p_pidp member
3287 		 * of one's own proc structure.  (These are truisms becuase
3288 		 * threads and processes don't clean up their own state --
3289 		 * they leave that task to whomever reaps them.)
3290 		 */
3291 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3292 
3293 	case DIF_VAR_PPID:
3294 		if (!dtrace_priv_proc(state, mstate))
3295 			return (0);
3296 
3297 		/*
3298 		 * See comment in DIF_VAR_PID.
3299 		 */
3300 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3301 			return (pid0.pid_id);
3302 
3303 		/*
3304 		 * It is always safe to dereference one's own t_procp pointer:
3305 		 * it always points to a valid, allocated proc structure.
3306 		 * (This is true because threads don't clean up their own
3307 		 * state -- they leave that task to whomever reaps them.)
3308 		 */
3309 		return ((uint64_t)curthread->t_procp->p_ppid);
3310 
3311 	case DIF_VAR_TID:
3312 		/*
3313 		 * See comment in DIF_VAR_PID.
3314 		 */
3315 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3316 			return (0);
3317 
3318 		return ((uint64_t)curthread->t_tid);
3319 
3320 	case DIF_VAR_EXECNAME:
3321 		if (!dtrace_priv_proc(state, mstate))
3322 			return (0);
3323 
3324 		/*
3325 		 * See comment in DIF_VAR_PID.
3326 		 */
3327 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3328 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3329 
3330 		/*
3331 		 * It is always safe to dereference one's own t_procp pointer:
3332 		 * it always points to a valid, allocated proc structure.
3333 		 * (This is true because threads don't clean up their own
3334 		 * state -- they leave that task to whomever reaps them.)
3335 		 */
3336 		return (dtrace_dif_varstr(
3337 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3338 		    state, mstate));
3339 
3340 	case DIF_VAR_ZONENAME:
3341 		if (!dtrace_priv_proc(state, mstate))
3342 			return (0);
3343 
3344 		/*
3345 		 * See comment in DIF_VAR_PID.
3346 		 */
3347 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3348 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3349 
3350 		/*
3351 		 * It is always safe to dereference one's own t_procp pointer:
3352 		 * it always points to a valid, allocated proc structure.
3353 		 * (This is true because threads don't clean up their own
3354 		 * state -- they leave that task to whomever reaps them.)
3355 		 */
3356 		return (dtrace_dif_varstr(
3357 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3358 		    state, mstate));
3359 
3360 	case DIF_VAR_UID:
3361 		if (!dtrace_priv_proc(state, mstate))
3362 			return (0);
3363 
3364 		/*
3365 		 * See comment in DIF_VAR_PID.
3366 		 */
3367 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3368 			return ((uint64_t)p0.p_cred->cr_uid);
3369 
3370 		/*
3371 		 * It is always safe to dereference one's own t_procp pointer:
3372 		 * it always points to a valid, allocated proc structure.
3373 		 * (This is true because threads don't clean up their own
3374 		 * state -- they leave that task to whomever reaps them.)
3375 		 *
3376 		 * Additionally, it is safe to dereference one's own process
3377 		 * credential, since this is never NULL after process birth.
3378 		 */
3379 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3380 
3381 	case DIF_VAR_GID:
3382 		if (!dtrace_priv_proc(state, mstate))
3383 			return (0);
3384 
3385 		/*
3386 		 * See comment in DIF_VAR_PID.
3387 		 */
3388 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3389 			return ((uint64_t)p0.p_cred->cr_gid);
3390 
3391 		/*
3392 		 * It is always safe to dereference one's own t_procp pointer:
3393 		 * it always points to a valid, allocated proc structure.
3394 		 * (This is true because threads don't clean up their own
3395 		 * state -- they leave that task to whomever reaps them.)
3396 		 *
3397 		 * Additionally, it is safe to dereference one's own process
3398 		 * credential, since this is never NULL after process birth.
3399 		 */
3400 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3401 
3402 	case DIF_VAR_ERRNO: {
3403 		klwp_t *lwp;
3404 		if (!dtrace_priv_proc(state, mstate))
3405 			return (0);
3406 
3407 		/*
3408 		 * See comment in DIF_VAR_PID.
3409 		 */
3410 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3411 			return (0);
3412 
3413 		/*
3414 		 * It is always safe to dereference one's own t_lwp pointer in
3415 		 * the event that this pointer is non-NULL.  (This is true
3416 		 * because threads and lwps don't clean up their own state --
3417 		 * they leave that task to whomever reaps them.)
3418 		 */
3419 		if ((lwp = curthread->t_lwp) == NULL)
3420 			return (0);
3421 
3422 		return ((uint64_t)lwp->lwp_errno);
3423 	}
3424 	default:
3425 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3426 		return (0);
3427 	}
3428 }
3429 
3430 
3431 typedef enum dtrace_json_state {
3432 	DTRACE_JSON_REST = 1,
3433 	DTRACE_JSON_OBJECT,
3434 	DTRACE_JSON_STRING,
3435 	DTRACE_JSON_STRING_ESCAPE,
3436 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3437 	DTRACE_JSON_COLON,
3438 	DTRACE_JSON_COMMA,
3439 	DTRACE_JSON_VALUE,
3440 	DTRACE_JSON_IDENTIFIER,
3441 	DTRACE_JSON_NUMBER,
3442 	DTRACE_JSON_NUMBER_FRAC,
3443 	DTRACE_JSON_NUMBER_EXP,
3444 	DTRACE_JSON_COLLECT_OBJECT
3445 } dtrace_json_state_t;
3446 
3447 /*
3448  * This function possesses just enough knowledge about JSON to extract a single
3449  * value from a JSON string and store it in the scratch buffer.  It is able
3450  * to extract nested object values, and members of arrays by index.
3451  *
3452  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3453  * be looked up as we descend into the object tree.  e.g.
3454  *
3455  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3456  *       with nelems = 5.
3457  *
3458  * The run time of this function must be bounded above by strsize to limit the
3459  * amount of work done in probe context.  As such, it is implemented as a
3460  * simple state machine, reading one character at a time using safe loads
3461  * until we find the requested element, hit a parsing error or run off the
3462  * end of the object or string.
3463  *
3464  * As there is no way for a subroutine to return an error without interrupting
3465  * clause execution, we simply return NULL in the event of a missing key or any
3466  * other error condition.  Each NULL return in this function is commented with
3467  * the error condition it represents -- parsing or otherwise.
3468  *
3469  * The set of states for the state machine closely matches the JSON
3470  * specification (http://json.org/).  Briefly:
3471  *
3472  *   DTRACE_JSON_REST:
3473  *     Skip whitespace until we find either a top-level Object, moving
3474  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3475  *
3476  *   DTRACE_JSON_OBJECT:
3477  *     Locate the next key String in an Object.  Sets a flag to denote
3478  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3479  *
3480  *   DTRACE_JSON_COLON:
3481  *     Skip whitespace until we find the colon that separates key Strings
3482  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3483  *
3484  *   DTRACE_JSON_VALUE:
3485  *     Detects the type of the next value (String, Number, Identifier, Object
3486  *     or Array) and routes to the states that process that type.  Here we also
3487  *     deal with the element selector list if we are requested to traverse down
3488  *     into the object tree.
3489  *
3490  *   DTRACE_JSON_COMMA:
3491  *     Skip whitespace until we find the comma that separates key-value pairs
3492  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3493  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3494  *     states return to this state at the end of their value, unless otherwise
3495  *     noted.
3496  *
3497  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3498  *     Processes a Number literal from the JSON, including any exponent
3499  *     component that may be present.  Numbers are returned as strings, which
3500  *     may be passed to strtoll() if an integer is required.
3501  *
3502  *   DTRACE_JSON_IDENTIFIER:
3503  *     Processes a "true", "false" or "null" literal in the JSON.
3504  *
3505  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3506  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3507  *     Processes a String literal from the JSON, whether the String denotes
3508  *     a key, a value or part of a larger Object.  Handles all escape sequences
3509  *     present in the specification, including four-digit unicode characters,
3510  *     but merely includes the escape sequence without converting it to the
3511  *     actual escaped character.  If the String is flagged as a key, we
3512  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3513  *
3514  *   DTRACE_JSON_COLLECT_OBJECT:
3515  *     This state collects an entire Object (or Array), correctly handling
3516  *     embedded strings.  If the full element selector list matches this nested
3517  *     object, we return the Object in full as a string.  If not, we use this
3518  *     state to skip to the next value at this level and continue processing.
3519  *
3520  * NOTE: This function uses various macros from strtolctype.h to manipulate
3521  * digit values, etc -- these have all been checked to ensure they make
3522  * no additional function calls.
3523  */
3524 static char *
3525 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3526     char *dest)
3527 {
3528 	dtrace_json_state_t state = DTRACE_JSON_REST;
3529 	int64_t array_elem = INT64_MIN;
3530 	int64_t array_pos = 0;
3531 	uint8_t escape_unicount = 0;
3532 	boolean_t string_is_key = B_FALSE;
3533 	boolean_t collect_object = B_FALSE;
3534 	boolean_t found_key = B_FALSE;
3535 	boolean_t in_array = B_FALSE;
3536 	uint32_t braces = 0, brackets = 0;
3537 	char *elem = elemlist;
3538 	char *dd = dest;
3539 	uintptr_t cur;
3540 
3541 	for (cur = json; cur < json + size; cur++) {
3542 		char cc = dtrace_load8(cur);
3543 		if (cc == '\0')
3544 			return (NULL);
3545 
3546 		switch (state) {
3547 		case DTRACE_JSON_REST:
3548 			if (isspace(cc))
3549 				break;
3550 
3551 			if (cc == '{') {
3552 				state = DTRACE_JSON_OBJECT;
3553 				break;
3554 			}
3555 
3556 			if (cc == '[') {
3557 				in_array = B_TRUE;
3558 				array_pos = 0;
3559 				array_elem = dtrace_strtoll(elem, 10, size);
3560 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3561 				state = DTRACE_JSON_VALUE;
3562 				break;
3563 			}
3564 
3565 			/*
3566 			 * ERROR: expected to find a top-level object or array.
3567 			 */
3568 			return (NULL);
3569 		case DTRACE_JSON_OBJECT:
3570 			if (isspace(cc))
3571 				break;
3572 
3573 			if (cc == '"') {
3574 				state = DTRACE_JSON_STRING;
3575 				string_is_key = B_TRUE;
3576 				break;
3577 			}
3578 
3579 			/*
3580 			 * ERROR: either the object did not start with a key
3581 			 * string, or we've run off the end of the object
3582 			 * without finding the requested key.
3583 			 */
3584 			return (NULL);
3585 		case DTRACE_JSON_STRING:
3586 			if (cc == '\\') {
3587 				*dd++ = '\\';
3588 				state = DTRACE_JSON_STRING_ESCAPE;
3589 				break;
3590 			}
3591 
3592 			if (cc == '"') {
3593 				if (collect_object) {
3594 					/*
3595 					 * We don't reset the dest here, as
3596 					 * the string is part of a larger
3597 					 * object being collected.
3598 					 */
3599 					*dd++ = cc;
3600 					collect_object = B_FALSE;
3601 					state = DTRACE_JSON_COLLECT_OBJECT;
3602 					break;
3603 				}
3604 				*dd = '\0';
3605 				dd = dest; /* reset string buffer */
3606 				if (string_is_key) {
3607 					if (dtrace_strncmp(dest, elem,
3608 					    size) == 0)
3609 						found_key = B_TRUE;
3610 				} else if (found_key) {
3611 					if (nelems > 1) {
3612 						/*
3613 						 * We expected an object, not
3614 						 * this string.
3615 						 */
3616 						return (NULL);
3617 					}
3618 					return (dest);
3619 				}
3620 				state = string_is_key ? DTRACE_JSON_COLON :
3621 				    DTRACE_JSON_COMMA;
3622 				string_is_key = B_FALSE;
3623 				break;
3624 			}
3625 
3626 			*dd++ = cc;
3627 			break;
3628 		case DTRACE_JSON_STRING_ESCAPE:
3629 			*dd++ = cc;
3630 			if (cc == 'u') {
3631 				escape_unicount = 0;
3632 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3633 			} else {
3634 				state = DTRACE_JSON_STRING;
3635 			}
3636 			break;
3637 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3638 			if (!isxdigit(cc)) {
3639 				/*
3640 				 * ERROR: invalid unicode escape, expected
3641 				 * four valid hexidecimal digits.
3642 				 */
3643 				return (NULL);
3644 			}
3645 
3646 			*dd++ = cc;
3647 			if (++escape_unicount == 4)
3648 				state = DTRACE_JSON_STRING;
3649 			break;
3650 		case DTRACE_JSON_COLON:
3651 			if (isspace(cc))
3652 				break;
3653 
3654 			if (cc == ':') {
3655 				state = DTRACE_JSON_VALUE;
3656 				break;
3657 			}
3658 
3659 			/*
3660 			 * ERROR: expected a colon.
3661 			 */
3662 			return (NULL);
3663 		case DTRACE_JSON_COMMA:
3664 			if (isspace(cc))
3665 				break;
3666 
3667 			if (cc == ',') {
3668 				if (in_array) {
3669 					state = DTRACE_JSON_VALUE;
3670 					if (++array_pos == array_elem)
3671 						found_key = B_TRUE;
3672 				} else {
3673 					state = DTRACE_JSON_OBJECT;
3674 				}
3675 				break;
3676 			}
3677 
3678 			/*
3679 			 * ERROR: either we hit an unexpected character, or
3680 			 * we reached the end of the object or array without
3681 			 * finding the requested key.
3682 			 */
3683 			return (NULL);
3684 		case DTRACE_JSON_IDENTIFIER:
3685 			if (islower(cc)) {
3686 				*dd++ = cc;
3687 				break;
3688 			}
3689 
3690 			*dd = '\0';
3691 			dd = dest; /* reset string buffer */
3692 
3693 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
3694 			    dtrace_strncmp(dest, "false", 6) == 0 ||
3695 			    dtrace_strncmp(dest, "null", 5) == 0) {
3696 				if (found_key) {
3697 					if (nelems > 1) {
3698 						/*
3699 						 * ERROR: We expected an object,
3700 						 * not this identifier.
3701 						 */
3702 						return (NULL);
3703 					}
3704 					return (dest);
3705 				} else {
3706 					cur--;
3707 					state = DTRACE_JSON_COMMA;
3708 					break;
3709 				}
3710 			}
3711 
3712 			/*
3713 			 * ERROR: we did not recognise the identifier as one
3714 			 * of those in the JSON specification.
3715 			 */
3716 			return (NULL);
3717 		case DTRACE_JSON_NUMBER:
3718 			if (cc == '.') {
3719 				*dd++ = cc;
3720 				state = DTRACE_JSON_NUMBER_FRAC;
3721 				break;
3722 			}
3723 
3724 			if (cc == 'x' || cc == 'X') {
3725 				/*
3726 				 * ERROR: specification explicitly excludes
3727 				 * hexidecimal or octal numbers.
3728 				 */
3729 				return (NULL);
3730 			}
3731 
3732 			/* FALLTHRU */
3733 		case DTRACE_JSON_NUMBER_FRAC:
3734 			if (cc == 'e' || cc == 'E') {
3735 				*dd++ = cc;
3736 				state = DTRACE_JSON_NUMBER_EXP;
3737 				break;
3738 			}
3739 
3740 			if (cc == '+' || cc == '-') {
3741 				/*
3742 				 * ERROR: expect sign as part of exponent only.
3743 				 */
3744 				return (NULL);
3745 			}
3746 			/* FALLTHRU */
3747 		case DTRACE_JSON_NUMBER_EXP:
3748 			if (isdigit(cc) || cc == '+' || cc == '-') {
3749 				*dd++ = cc;
3750 				break;
3751 			}
3752 
3753 			*dd = '\0';
3754 			dd = dest; /* reset string buffer */
3755 			if (found_key) {
3756 				if (nelems > 1) {
3757 					/*
3758 					 * ERROR: We expected an object, not
3759 					 * this number.
3760 					 */
3761 					return (NULL);
3762 				}
3763 				return (dest);
3764 			}
3765 
3766 			cur--;
3767 			state = DTRACE_JSON_COMMA;
3768 			break;
3769 		case DTRACE_JSON_VALUE:
3770 			if (isspace(cc))
3771 				break;
3772 
3773 			if (cc == '{' || cc == '[') {
3774 				if (nelems > 1 && found_key) {
3775 					in_array = cc == '[' ? B_TRUE : B_FALSE;
3776 					/*
3777 					 * If our element selector directs us
3778 					 * to descend into this nested object,
3779 					 * then move to the next selector
3780 					 * element in the list and restart the
3781 					 * state machine.
3782 					 */
3783 					while (*elem != '\0')
3784 						elem++;
3785 					elem++; /* skip the inter-element NUL */
3786 					nelems--;
3787 					dd = dest;
3788 					if (in_array) {
3789 						state = DTRACE_JSON_VALUE;
3790 						array_pos = 0;
3791 						array_elem = dtrace_strtoll(
3792 						    elem, 10, size);
3793 						found_key = array_elem == 0 ?
3794 						    B_TRUE : B_FALSE;
3795 					} else {
3796 						found_key = B_FALSE;
3797 						state = DTRACE_JSON_OBJECT;
3798 					}
3799 					break;
3800 				}
3801 
3802 				/*
3803 				 * Otherwise, we wish to either skip this
3804 				 * nested object or return it in full.
3805 				 */
3806 				if (cc == '[')
3807 					brackets = 1;
3808 				else
3809 					braces = 1;
3810 				*dd++ = cc;
3811 				state = DTRACE_JSON_COLLECT_OBJECT;
3812 				break;
3813 			}
3814 
3815 			if (cc == '"') {
3816 				state = DTRACE_JSON_STRING;
3817 				break;
3818 			}
3819 
3820 			if (islower(cc)) {
3821 				/*
3822 				 * Here we deal with true, false and null.
3823 				 */
3824 				*dd++ = cc;
3825 				state = DTRACE_JSON_IDENTIFIER;
3826 				break;
3827 			}
3828 
3829 			if (cc == '-' || isdigit(cc)) {
3830 				*dd++ = cc;
3831 				state = DTRACE_JSON_NUMBER;
3832 				break;
3833 			}
3834 
3835 			/*
3836 			 * ERROR: unexpected character at start of value.
3837 			 */
3838 			return (NULL);
3839 		case DTRACE_JSON_COLLECT_OBJECT:
3840 			if (cc == '\0')
3841 				/*
3842 				 * ERROR: unexpected end of input.
3843 				 */
3844 				return (NULL);
3845 
3846 			*dd++ = cc;
3847 			if (cc == '"') {
3848 				collect_object = B_TRUE;
3849 				state = DTRACE_JSON_STRING;
3850 				break;
3851 			}
3852 
3853 			if (cc == ']') {
3854 				if (brackets-- == 0) {
3855 					/*
3856 					 * ERROR: unbalanced brackets.
3857 					 */
3858 					return (NULL);
3859 				}
3860 			} else if (cc == '}') {
3861 				if (braces-- == 0) {
3862 					/*
3863 					 * ERROR: unbalanced braces.
3864 					 */
3865 					return (NULL);
3866 				}
3867 			} else if (cc == '{') {
3868 				braces++;
3869 			} else if (cc == '[') {
3870 				brackets++;
3871 			}
3872 
3873 			if (brackets == 0 && braces == 0) {
3874 				if (found_key) {
3875 					*dd = '\0';
3876 					return (dest);
3877 				}
3878 				dd = dest; /* reset string buffer */
3879 				state = DTRACE_JSON_COMMA;
3880 			}
3881 			break;
3882 		}
3883 	}
3884 	return (NULL);
3885 }
3886 
3887 /*
3888  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3889  * Notice that we don't bother validating the proper number of arguments or
3890  * their types in the tuple stack.  This isn't needed because all argument
3891  * interpretation is safe because of our load safety -- the worst that can
3892  * happen is that a bogus program can obtain bogus results.
3893  */
3894 static void
3895 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3896     dtrace_key_t *tupregs, int nargs,
3897     dtrace_mstate_t *mstate, dtrace_state_t *state)
3898 {
3899 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3900 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3901 	dtrace_vstate_t *vstate = &state->dts_vstate;
3902 
3903 	union {
3904 		mutex_impl_t mi;
3905 		uint64_t mx;
3906 	} m;
3907 
3908 	union {
3909 		krwlock_t ri;
3910 		uintptr_t rw;
3911 	} r;
3912 
3913 	switch (subr) {
3914 	case DIF_SUBR_RAND:
3915 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3916 		break;
3917 
3918 	case DIF_SUBR_MUTEX_OWNED:
3919 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3920 		    mstate, vstate)) {
3921 			regs[rd] = NULL;
3922 			break;
3923 		}
3924 
3925 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3926 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3927 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3928 		else
3929 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3930 		break;
3931 
3932 	case DIF_SUBR_MUTEX_OWNER:
3933 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3934 		    mstate, vstate)) {
3935 			regs[rd] = NULL;
3936 			break;
3937 		}
3938 
3939 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3940 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3941 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3942 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3943 		else
3944 			regs[rd] = 0;
3945 		break;
3946 
3947 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3948 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3949 		    mstate, vstate)) {
3950 			regs[rd] = NULL;
3951 			break;
3952 		}
3953 
3954 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3955 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3956 		break;
3957 
3958 	case DIF_SUBR_MUTEX_TYPE_SPIN:
3959 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3960 		    mstate, vstate)) {
3961 			regs[rd] = NULL;
3962 			break;
3963 		}
3964 
3965 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3966 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3967 		break;
3968 
3969 	case DIF_SUBR_RW_READ_HELD: {
3970 		uintptr_t tmp;
3971 
3972 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3973 		    mstate, vstate)) {
3974 			regs[rd] = NULL;
3975 			break;
3976 		}
3977 
3978 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3979 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3980 		break;
3981 	}
3982 
3983 	case DIF_SUBR_RW_WRITE_HELD:
3984 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3985 		    mstate, vstate)) {
3986 			regs[rd] = NULL;
3987 			break;
3988 		}
3989 
3990 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3991 		regs[rd] = _RW_WRITE_HELD(&r.ri);
3992 		break;
3993 
3994 	case DIF_SUBR_RW_ISWRITER:
3995 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3996 		    mstate, vstate)) {
3997 			regs[rd] = NULL;
3998 			break;
3999 		}
4000 
4001 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4002 		regs[rd] = _RW_ISWRITER(&r.ri);
4003 		break;
4004 
4005 	case DIF_SUBR_BCOPY: {
4006 		/*
4007 		 * We need to be sure that the destination is in the scratch
4008 		 * region -- no other region is allowed.
4009 		 */
4010 		uintptr_t src = tupregs[0].dttk_value;
4011 		uintptr_t dest = tupregs[1].dttk_value;
4012 		size_t size = tupregs[2].dttk_value;
4013 
4014 		if (!dtrace_inscratch(dest, size, mstate)) {
4015 			*flags |= CPU_DTRACE_BADADDR;
4016 			*illval = regs[rd];
4017 			break;
4018 		}
4019 
4020 		if (!dtrace_canload(src, size, mstate, vstate)) {
4021 			regs[rd] = NULL;
4022 			break;
4023 		}
4024 
4025 		dtrace_bcopy((void *)src, (void *)dest, size);
4026 		break;
4027 	}
4028 
4029 	case DIF_SUBR_ALLOCA:
4030 	case DIF_SUBR_COPYIN: {
4031 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4032 		uint64_t size =
4033 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4034 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4035 
4036 		/*
4037 		 * This action doesn't require any credential checks since
4038 		 * probes will not activate in user contexts to which the
4039 		 * enabling user does not have permissions.
4040 		 */
4041 
4042 		/*
4043 		 * Rounding up the user allocation size could have overflowed
4044 		 * a large, bogus allocation (like -1ULL) to 0.
4045 		 */
4046 		if (scratch_size < size ||
4047 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4048 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4049 			regs[rd] = NULL;
4050 			break;
4051 		}
4052 
4053 		if (subr == DIF_SUBR_COPYIN) {
4054 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4055 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4056 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4057 		}
4058 
4059 		mstate->dtms_scratch_ptr += scratch_size;
4060 		regs[rd] = dest;
4061 		break;
4062 	}
4063 
4064 	case DIF_SUBR_COPYINTO: {
4065 		uint64_t size = tupregs[1].dttk_value;
4066 		uintptr_t dest = tupregs[2].dttk_value;
4067 
4068 		/*
4069 		 * This action doesn't require any credential checks since
4070 		 * probes will not activate in user contexts to which the
4071 		 * enabling user does not have permissions.
4072 		 */
4073 		if (!dtrace_inscratch(dest, size, mstate)) {
4074 			*flags |= CPU_DTRACE_BADADDR;
4075 			*illval = regs[rd];
4076 			break;
4077 		}
4078 
4079 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4080 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4081 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4082 		break;
4083 	}
4084 
4085 	case DIF_SUBR_COPYINSTR: {
4086 		uintptr_t dest = mstate->dtms_scratch_ptr;
4087 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4088 
4089 		if (nargs > 1 && tupregs[1].dttk_value < size)
4090 			size = tupregs[1].dttk_value + 1;
4091 
4092 		/*
4093 		 * This action doesn't require any credential checks since
4094 		 * probes will not activate in user contexts to which the
4095 		 * enabling user does not have permissions.
4096 		 */
4097 		if (!DTRACE_INSCRATCH(mstate, size)) {
4098 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4099 			regs[rd] = NULL;
4100 			break;
4101 		}
4102 
4103 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4104 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4105 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4106 
4107 		((char *)dest)[size - 1] = '\0';
4108 		mstate->dtms_scratch_ptr += size;
4109 		regs[rd] = dest;
4110 		break;
4111 	}
4112 
4113 	case DIF_SUBR_MSGSIZE:
4114 	case DIF_SUBR_MSGDSIZE: {
4115 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
4116 		uintptr_t wptr, rptr;
4117 		size_t count = 0;
4118 		int cont = 0;
4119 
4120 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4121 
4122 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4123 			    vstate)) {
4124 				regs[rd] = NULL;
4125 				break;
4126 			}
4127 
4128 			wptr = dtrace_loadptr(baddr +
4129 			    offsetof(mblk_t, b_wptr));
4130 
4131 			rptr = dtrace_loadptr(baddr +
4132 			    offsetof(mblk_t, b_rptr));
4133 
4134 			if (wptr < rptr) {
4135 				*flags |= CPU_DTRACE_BADADDR;
4136 				*illval = tupregs[0].dttk_value;
4137 				break;
4138 			}
4139 
4140 			daddr = dtrace_loadptr(baddr +
4141 			    offsetof(mblk_t, b_datap));
4142 
4143 			baddr = dtrace_loadptr(baddr +
4144 			    offsetof(mblk_t, b_cont));
4145 
4146 			/*
4147 			 * We want to prevent against denial-of-service here,
4148 			 * so we're only going to search the list for
4149 			 * dtrace_msgdsize_max mblks.
4150 			 */
4151 			if (cont++ > dtrace_msgdsize_max) {
4152 				*flags |= CPU_DTRACE_ILLOP;
4153 				break;
4154 			}
4155 
4156 			if (subr == DIF_SUBR_MSGDSIZE) {
4157 				if (dtrace_load8(daddr +
4158 				    offsetof(dblk_t, db_type)) != M_DATA)
4159 					continue;
4160 			}
4161 
4162 			count += wptr - rptr;
4163 		}
4164 
4165 		if (!(*flags & CPU_DTRACE_FAULT))
4166 			regs[rd] = count;
4167 
4168 		break;
4169 	}
4170 
4171 	case DIF_SUBR_PROGENYOF: {
4172 		pid_t pid = tupregs[0].dttk_value;
4173 		proc_t *p;
4174 		int rval = 0;
4175 
4176 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4177 
4178 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4179 			if (p->p_pidp->pid_id == pid) {
4180 				rval = 1;
4181 				break;
4182 			}
4183 		}
4184 
4185 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4186 
4187 		regs[rd] = rval;
4188 		break;
4189 	}
4190 
4191 	case DIF_SUBR_SPECULATION:
4192 		regs[rd] = dtrace_speculation(state);
4193 		break;
4194 
4195 	case DIF_SUBR_COPYOUT: {
4196 		uintptr_t kaddr = tupregs[0].dttk_value;
4197 		uintptr_t uaddr = tupregs[1].dttk_value;
4198 		uint64_t size = tupregs[2].dttk_value;
4199 
4200 		if (!dtrace_destructive_disallow &&
4201 		    dtrace_priv_proc_control(state, mstate) &&
4202 		    !dtrace_istoxic(kaddr, size) &&
4203 		    dtrace_canload(kaddr, size, mstate, vstate)) {
4204 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4205 			dtrace_copyout(kaddr, uaddr, size, flags);
4206 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4207 		}
4208 		break;
4209 	}
4210 
4211 	case DIF_SUBR_COPYOUTSTR: {
4212 		uintptr_t kaddr = tupregs[0].dttk_value;
4213 		uintptr_t uaddr = tupregs[1].dttk_value;
4214 		uint64_t size = tupregs[2].dttk_value;
4215 
4216 		if (!dtrace_destructive_disallow &&
4217 		    dtrace_priv_proc_control(state, mstate) &&
4218 		    !dtrace_istoxic(kaddr, size) &&
4219 		    dtrace_strcanload(kaddr, size, mstate, vstate)) {
4220 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4221 			dtrace_copyoutstr(kaddr, uaddr, size, flags);
4222 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4223 		}
4224 		break;
4225 	}
4226 
4227 	case DIF_SUBR_STRLEN: {
4228 		size_t sz;
4229 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4230 		sz = dtrace_strlen((char *)addr,
4231 		    state->dts_options[DTRACEOPT_STRSIZE]);
4232 
4233 		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
4234 			regs[rd] = NULL;
4235 			break;
4236 		}
4237 
4238 		regs[rd] = sz;
4239 
4240 		break;
4241 	}
4242 
4243 	case DIF_SUBR_STRCHR:
4244 	case DIF_SUBR_STRRCHR: {
4245 		/*
4246 		 * We're going to iterate over the string looking for the
4247 		 * specified character.  We will iterate until we have reached
4248 		 * the string length or we have found the character.  If this
4249 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4250 		 * of the specified character instead of the first.
4251 		 */
4252 		uintptr_t saddr = tupregs[0].dttk_value;
4253 		uintptr_t addr = tupregs[0].dttk_value;
4254 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
4255 		char c, target = (char)tupregs[1].dttk_value;
4256 
4257 		for (regs[rd] = NULL; addr < limit; addr++) {
4258 			if ((c = dtrace_load8(addr)) == target) {
4259 				regs[rd] = addr;
4260 
4261 				if (subr == DIF_SUBR_STRCHR)
4262 					break;
4263 			}
4264 
4265 			if (c == '\0')
4266 				break;
4267 		}
4268 
4269 		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
4270 			regs[rd] = NULL;
4271 			break;
4272 		}
4273 
4274 		break;
4275 	}
4276 
4277 	case DIF_SUBR_STRSTR:
4278 	case DIF_SUBR_INDEX:
4279 	case DIF_SUBR_RINDEX: {
4280 		/*
4281 		 * We're going to iterate over the string looking for the
4282 		 * specified string.  We will iterate until we have reached
4283 		 * the string length or we have found the string.  (Yes, this
4284 		 * is done in the most naive way possible -- but considering
4285 		 * that the string we're searching for is likely to be
4286 		 * relatively short, the complexity of Rabin-Karp or similar
4287 		 * hardly seems merited.)
4288 		 */
4289 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4290 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4291 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4292 		size_t len = dtrace_strlen(addr, size);
4293 		size_t sublen = dtrace_strlen(substr, size);
4294 		char *limit = addr + len, *orig = addr;
4295 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4296 		int inc = 1;
4297 
4298 		regs[rd] = notfound;
4299 
4300 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4301 			regs[rd] = NULL;
4302 			break;
4303 		}
4304 
4305 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4306 		    vstate)) {
4307 			regs[rd] = NULL;
4308 			break;
4309 		}
4310 
4311 		/*
4312 		 * strstr() and index()/rindex() have similar semantics if
4313 		 * both strings are the empty string: strstr() returns a
4314 		 * pointer to the (empty) string, and index() and rindex()
4315 		 * both return index 0 (regardless of any position argument).
4316 		 */
4317 		if (sublen == 0 && len == 0) {
4318 			if (subr == DIF_SUBR_STRSTR)
4319 				regs[rd] = (uintptr_t)addr;
4320 			else
4321 				regs[rd] = 0;
4322 			break;
4323 		}
4324 
4325 		if (subr != DIF_SUBR_STRSTR) {
4326 			if (subr == DIF_SUBR_RINDEX) {
4327 				limit = orig - 1;
4328 				addr += len;
4329 				inc = -1;
4330 			}
4331 
4332 			/*
4333 			 * Both index() and rindex() take an optional position
4334 			 * argument that denotes the starting position.
4335 			 */
4336 			if (nargs == 3) {
4337 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4338 
4339 				/*
4340 				 * If the position argument to index() is
4341 				 * negative, Perl implicitly clamps it at
4342 				 * zero.  This semantic is a little surprising
4343 				 * given the special meaning of negative
4344 				 * positions to similar Perl functions like
4345 				 * substr(), but it appears to reflect a
4346 				 * notion that index() can start from a
4347 				 * negative index and increment its way up to
4348 				 * the string.  Given this notion, Perl's
4349 				 * rindex() is at least self-consistent in
4350 				 * that it implicitly clamps positions greater
4351 				 * than the string length to be the string
4352 				 * length.  Where Perl completely loses
4353 				 * coherence, however, is when the specified
4354 				 * substring is the empty string ("").  In
4355 				 * this case, even if the position is
4356 				 * negative, rindex() returns 0 -- and even if
4357 				 * the position is greater than the length,
4358 				 * index() returns the string length.  These
4359 				 * semantics violate the notion that index()
4360 				 * should never return a value less than the
4361 				 * specified position and that rindex() should
4362 				 * never return a value greater than the
4363 				 * specified position.  (One assumes that
4364 				 * these semantics are artifacts of Perl's
4365 				 * implementation and not the results of
4366 				 * deliberate design -- it beggars belief that
4367 				 * even Larry Wall could desire such oddness.)
4368 				 * While in the abstract one would wish for
4369 				 * consistent position semantics across
4370 				 * substr(), index() and rindex() -- or at the
4371 				 * very least self-consistent position
4372 				 * semantics for index() and rindex() -- we
4373 				 * instead opt to keep with the extant Perl
4374 				 * semantics, in all their broken glory.  (Do
4375 				 * we have more desire to maintain Perl's
4376 				 * semantics than Perl does?  Probably.)
4377 				 */
4378 				if (subr == DIF_SUBR_RINDEX) {
4379 					if (pos < 0) {
4380 						if (sublen == 0)
4381 							regs[rd] = 0;
4382 						break;
4383 					}
4384 
4385 					if (pos > len)
4386 						pos = len;
4387 				} else {
4388 					if (pos < 0)
4389 						pos = 0;
4390 
4391 					if (pos >= len) {
4392 						if (sublen == 0)
4393 							regs[rd] = len;
4394 						break;
4395 					}
4396 				}
4397 
4398 				addr = orig + pos;
4399 			}
4400 		}
4401 
4402 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4403 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4404 				if (subr != DIF_SUBR_STRSTR) {
4405 					/*
4406 					 * As D index() and rindex() are
4407 					 * modeled on Perl (and not on awk),
4408 					 * we return a zero-based (and not a
4409 					 * one-based) index.  (For you Perl
4410 					 * weenies: no, we're not going to add
4411 					 * $[ -- and shouldn't you be at a con
4412 					 * or something?)
4413 					 */
4414 					regs[rd] = (uintptr_t)(addr - orig);
4415 					break;
4416 				}
4417 
4418 				ASSERT(subr == DIF_SUBR_STRSTR);
4419 				regs[rd] = (uintptr_t)addr;
4420 				break;
4421 			}
4422 		}
4423 
4424 		break;
4425 	}
4426 
4427 	case DIF_SUBR_STRTOK: {
4428 		uintptr_t addr = tupregs[0].dttk_value;
4429 		uintptr_t tokaddr = tupregs[1].dttk_value;
4430 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4431 		uintptr_t limit, toklimit = tokaddr + size;
4432 		uint8_t c, tokmap[32];	 /* 256 / 8 */
4433 		char *dest = (char *)mstate->dtms_scratch_ptr;
4434 		int i;
4435 
4436 		/*
4437 		 * Check both the token buffer and (later) the input buffer,
4438 		 * since both could be non-scratch addresses.
4439 		 */
4440 		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
4441 			regs[rd] = NULL;
4442 			break;
4443 		}
4444 
4445 		if (!DTRACE_INSCRATCH(mstate, size)) {
4446 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4447 			regs[rd] = NULL;
4448 			break;
4449 		}
4450 
4451 		if (addr == NULL) {
4452 			/*
4453 			 * If the address specified is NULL, we use our saved
4454 			 * strtok pointer from the mstate.  Note that this
4455 			 * means that the saved strtok pointer is _only_
4456 			 * valid within multiple enablings of the same probe --
4457 			 * it behaves like an implicit clause-local variable.
4458 			 */
4459 			addr = mstate->dtms_strtok;
4460 		} else {
4461 			/*
4462 			 * If the user-specified address is non-NULL we must
4463 			 * access check it.  This is the only time we have
4464 			 * a chance to do so, since this address may reside
4465 			 * in the string table of this clause-- future calls
4466 			 * (when we fetch addr from mstate->dtms_strtok)
4467 			 * would fail this access check.
4468 			 */
4469 			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
4470 				regs[rd] = NULL;
4471 				break;
4472 			}
4473 		}
4474 
4475 		/*
4476 		 * First, zero the token map, and then process the token
4477 		 * string -- setting a bit in the map for every character
4478 		 * found in the token string.
4479 		 */
4480 		for (i = 0; i < sizeof (tokmap); i++)
4481 			tokmap[i] = 0;
4482 
4483 		for (; tokaddr < toklimit; tokaddr++) {
4484 			if ((c = dtrace_load8(tokaddr)) == '\0')
4485 				break;
4486 
4487 			ASSERT((c >> 3) < sizeof (tokmap));
4488 			tokmap[c >> 3] |= (1 << (c & 0x7));
4489 		}
4490 
4491 		for (limit = addr + size; addr < limit; addr++) {
4492 			/*
4493 			 * We're looking for a character that is _not_ contained
4494 			 * in the token string.
4495 			 */
4496 			if ((c = dtrace_load8(addr)) == '\0')
4497 				break;
4498 
4499 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4500 				break;
4501 		}
4502 
4503 		if (c == '\0') {
4504 			/*
4505 			 * We reached the end of the string without finding
4506 			 * any character that was not in the token string.
4507 			 * We return NULL in this case, and we set the saved
4508 			 * address to NULL as well.
4509 			 */
4510 			regs[rd] = NULL;
4511 			mstate->dtms_strtok = NULL;
4512 			break;
4513 		}
4514 
4515 		/*
4516 		 * From here on, we're copying into the destination string.
4517 		 */
4518 		for (i = 0; addr < limit && i < size - 1; addr++) {
4519 			if ((c = dtrace_load8(addr)) == '\0')
4520 				break;
4521 
4522 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4523 				break;
4524 
4525 			ASSERT(i < size);
4526 			dest[i++] = c;
4527 		}
4528 
4529 		ASSERT(i < size);
4530 		dest[i] = '\0';
4531 		regs[rd] = (uintptr_t)dest;
4532 		mstate->dtms_scratch_ptr += size;
4533 		mstate->dtms_strtok = addr;
4534 		break;
4535 	}
4536 
4537 	case DIF_SUBR_SUBSTR: {
4538 		uintptr_t s = tupregs[0].dttk_value;
4539 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4540 		char *d = (char *)mstate->dtms_scratch_ptr;
4541 		int64_t index = (int64_t)tupregs[1].dttk_value;
4542 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4543 		size_t len = dtrace_strlen((char *)s, size);
4544 		int64_t i;
4545 
4546 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4547 			regs[rd] = NULL;
4548 			break;
4549 		}
4550 
4551 		if (!DTRACE_INSCRATCH(mstate, size)) {
4552 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4553 			regs[rd] = NULL;
4554 			break;
4555 		}
4556 
4557 		if (nargs <= 2)
4558 			remaining = (int64_t)size;
4559 
4560 		if (index < 0) {
4561 			index += len;
4562 
4563 			if (index < 0 && index + remaining > 0) {
4564 				remaining += index;
4565 				index = 0;
4566 			}
4567 		}
4568 
4569 		if (index >= len || index < 0) {
4570 			remaining = 0;
4571 		} else if (remaining < 0) {
4572 			remaining += len - index;
4573 		} else if (index + remaining > size) {
4574 			remaining = size - index;
4575 		}
4576 
4577 		for (i = 0; i < remaining; i++) {
4578 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4579 				break;
4580 		}
4581 
4582 		d[i] = '\0';
4583 
4584 		mstate->dtms_scratch_ptr += size;
4585 		regs[rd] = (uintptr_t)d;
4586 		break;
4587 	}
4588 
4589 	case DIF_SUBR_JSON: {
4590 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4591 		uintptr_t json = tupregs[0].dttk_value;
4592 		size_t jsonlen = dtrace_strlen((char *)json, size);
4593 		uintptr_t elem = tupregs[1].dttk_value;
4594 		size_t elemlen = dtrace_strlen((char *)elem, size);
4595 
4596 		char *dest = (char *)mstate->dtms_scratch_ptr;
4597 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
4598 		char *ee = elemlist;
4599 		int nelems = 1;
4600 		uintptr_t cur;
4601 
4602 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
4603 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
4604 			regs[rd] = NULL;
4605 			break;
4606 		}
4607 
4608 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
4609 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4610 			regs[rd] = NULL;
4611 			break;
4612 		}
4613 
4614 		/*
4615 		 * Read the element selector and split it up into a packed list
4616 		 * of strings.
4617 		 */
4618 		for (cur = elem; cur < elem + elemlen; cur++) {
4619 			char cc = dtrace_load8(cur);
4620 
4621 			if (cur == elem && cc == '[') {
4622 				/*
4623 				 * If the first element selector key is
4624 				 * actually an array index then ignore the
4625 				 * bracket.
4626 				 */
4627 				continue;
4628 			}
4629 
4630 			if (cc == ']')
4631 				continue;
4632 
4633 			if (cc == '.' || cc == '[') {
4634 				nelems++;
4635 				cc = '\0';
4636 			}
4637 
4638 			*ee++ = cc;
4639 		}
4640 		*ee++ = '\0';
4641 
4642 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
4643 		    nelems, dest)) != NULL)
4644 			mstate->dtms_scratch_ptr += jsonlen + 1;
4645 		break;
4646 	}
4647 
4648 	case DIF_SUBR_TOUPPER:
4649 	case DIF_SUBR_TOLOWER: {
4650 		uintptr_t s = tupregs[0].dttk_value;
4651 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4652 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4653 		size_t len = dtrace_strlen((char *)s, size);
4654 		char lower, upper, convert;
4655 		int64_t i;
4656 
4657 		if (subr == DIF_SUBR_TOUPPER) {
4658 			lower = 'a';
4659 			upper = 'z';
4660 			convert = 'A';
4661 		} else {
4662 			lower = 'A';
4663 			upper = 'Z';
4664 			convert = 'a';
4665 		}
4666 
4667 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4668 			regs[rd] = NULL;
4669 			break;
4670 		}
4671 
4672 		if (!DTRACE_INSCRATCH(mstate, size)) {
4673 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4674 			regs[rd] = NULL;
4675 			break;
4676 		}
4677 
4678 		for (i = 0; i < size - 1; i++) {
4679 			if ((c = dtrace_load8(s + i)) == '\0')
4680 				break;
4681 
4682 			if (c >= lower && c <= upper)
4683 				c = convert + (c - lower);
4684 
4685 			dest[i] = c;
4686 		}
4687 
4688 		ASSERT(i < size);
4689 		dest[i] = '\0';
4690 		regs[rd] = (uintptr_t)dest;
4691 		mstate->dtms_scratch_ptr += size;
4692 		break;
4693 	}
4694 
4695 case DIF_SUBR_GETMAJOR:
4696 #ifdef _LP64
4697 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4698 #else
4699 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4700 #endif
4701 		break;
4702 
4703 	case DIF_SUBR_GETMINOR:
4704 #ifdef _LP64
4705 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4706 #else
4707 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
4708 #endif
4709 		break;
4710 
4711 	case DIF_SUBR_DDI_PATHNAME: {
4712 		/*
4713 		 * This one is a galactic mess.  We are going to roughly
4714 		 * emulate ddi_pathname(), but it's made more complicated
4715 		 * by the fact that we (a) want to include the minor name and
4716 		 * (b) must proceed iteratively instead of recursively.
4717 		 */
4718 		uintptr_t dest = mstate->dtms_scratch_ptr;
4719 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4720 		char *start = (char *)dest, *end = start + size - 1;
4721 		uintptr_t daddr = tupregs[0].dttk_value;
4722 		int64_t minor = (int64_t)tupregs[1].dttk_value;
4723 		char *s;
4724 		int i, len, depth = 0;
4725 
4726 		/*
4727 		 * Due to all the pointer jumping we do and context we must
4728 		 * rely upon, we just mandate that the user must have kernel
4729 		 * read privileges to use this routine.
4730 		 */
4731 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4732 			*flags |= CPU_DTRACE_KPRIV;
4733 			*illval = daddr;
4734 			regs[rd] = NULL;
4735 		}
4736 
4737 		if (!DTRACE_INSCRATCH(mstate, size)) {
4738 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4739 			regs[rd] = NULL;
4740 			break;
4741 		}
4742 
4743 		*end = '\0';
4744 
4745 		/*
4746 		 * We want to have a name for the minor.  In order to do this,
4747 		 * we need to walk the minor list from the devinfo.  We want
4748 		 * to be sure that we don't infinitely walk a circular list,
4749 		 * so we check for circularity by sending a scout pointer
4750 		 * ahead two elements for every element that we iterate over;
4751 		 * if the list is circular, these will ultimately point to the
4752 		 * same element.  You may recognize this little trick as the
4753 		 * answer to a stupid interview question -- one that always
4754 		 * seems to be asked by those who had to have it laboriously
4755 		 * explained to them, and who can't even concisely describe
4756 		 * the conditions under which one would be forced to resort to
4757 		 * this technique.  Needless to say, those conditions are
4758 		 * found here -- and probably only here.  Is this the only use
4759 		 * of this infamous trick in shipping, production code?  If it
4760 		 * isn't, it probably should be...
4761 		 */
4762 		if (minor != -1) {
4763 			uintptr_t maddr = dtrace_loadptr(daddr +
4764 			    offsetof(struct dev_info, devi_minor));
4765 
4766 			uintptr_t next = offsetof(struct ddi_minor_data, next);
4767 			uintptr_t name = offsetof(struct ddi_minor_data,
4768 			    d_minor) + offsetof(struct ddi_minor, name);
4769 			uintptr_t dev = offsetof(struct ddi_minor_data,
4770 			    d_minor) + offsetof(struct ddi_minor, dev);
4771 			uintptr_t scout;
4772 
4773 			if (maddr != NULL)
4774 				scout = dtrace_loadptr(maddr + next);
4775 
4776 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4777 				uint64_t m;
4778 #ifdef _LP64
4779 				m = dtrace_load64(maddr + dev) & MAXMIN64;
4780 #else
4781 				m = dtrace_load32(maddr + dev) & MAXMIN;
4782 #endif
4783 				if (m != minor) {
4784 					maddr = dtrace_loadptr(maddr + next);
4785 
4786 					if (scout == NULL)
4787 						continue;
4788 
4789 					scout = dtrace_loadptr(scout + next);
4790 
4791 					if (scout == NULL)
4792 						continue;
4793 
4794 					scout = dtrace_loadptr(scout + next);
4795 
4796 					if (scout == NULL)
4797 						continue;
4798 
4799 					if (scout == maddr) {
4800 						*flags |= CPU_DTRACE_ILLOP;
4801 						break;
4802 					}
4803 
4804 					continue;
4805 				}
4806 
4807 				/*
4808 				 * We have the minor data.  Now we need to
4809 				 * copy the minor's name into the end of the
4810 				 * pathname.
4811 				 */
4812 				s = (char *)dtrace_loadptr(maddr + name);
4813 				len = dtrace_strlen(s, size);
4814 
4815 				if (*flags & CPU_DTRACE_FAULT)
4816 					break;
4817 
4818 				if (len != 0) {
4819 					if ((end -= (len + 1)) < start)
4820 						break;
4821 
4822 					*end = ':';
4823 				}
4824 
4825 				for (i = 1; i <= len; i++)
4826 					end[i] = dtrace_load8((uintptr_t)s++);
4827 				break;
4828 			}
4829 		}
4830 
4831 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4832 			ddi_node_state_t devi_state;
4833 
4834 			devi_state = dtrace_load32(daddr +
4835 			    offsetof(struct dev_info, devi_node_state));
4836 
4837 			if (*flags & CPU_DTRACE_FAULT)
4838 				break;
4839 
4840 			if (devi_state >= DS_INITIALIZED) {
4841 				s = (char *)dtrace_loadptr(daddr +
4842 				    offsetof(struct dev_info, devi_addr));
4843 				len = dtrace_strlen(s, size);
4844 
4845 				if (*flags & CPU_DTRACE_FAULT)
4846 					break;
4847 
4848 				if (len != 0) {
4849 					if ((end -= (len + 1)) < start)
4850 						break;
4851 
4852 					*end = '@';
4853 				}
4854 
4855 				for (i = 1; i <= len; i++)
4856 					end[i] = dtrace_load8((uintptr_t)s++);
4857 			}
4858 
4859 			/*
4860 			 * Now for the node name...
4861 			 */
4862 			s = (char *)dtrace_loadptr(daddr +
4863 			    offsetof(struct dev_info, devi_node_name));
4864 
4865 			daddr = dtrace_loadptr(daddr +
4866 			    offsetof(struct dev_info, devi_parent));
4867 
4868 			/*
4869 			 * If our parent is NULL (that is, if we're the root
4870 			 * node), we're going to use the special path
4871 			 * "devices".
4872 			 */
4873 			if (daddr == NULL)
4874 				s = "devices";
4875 
4876 			len = dtrace_strlen(s, size);
4877 			if (*flags & CPU_DTRACE_FAULT)
4878 				break;
4879 
4880 			if ((end -= (len + 1)) < start)
4881 				break;
4882 
4883 			for (i = 1; i <= len; i++)
4884 				end[i] = dtrace_load8((uintptr_t)s++);
4885 			*end = '/';
4886 
4887 			if (depth++ > dtrace_devdepth_max) {
4888 				*flags |= CPU_DTRACE_ILLOP;
4889 				break;
4890 			}
4891 		}
4892 
4893 		if (end < start)
4894 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4895 
4896 		if (daddr == NULL) {
4897 			regs[rd] = (uintptr_t)end;
4898 			mstate->dtms_scratch_ptr += size;
4899 		}
4900 
4901 		break;
4902 	}
4903 
4904 	case DIF_SUBR_STRJOIN: {
4905 		char *d = (char *)mstate->dtms_scratch_ptr;
4906 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4907 		uintptr_t s1 = tupregs[0].dttk_value;
4908 		uintptr_t s2 = tupregs[1].dttk_value;
4909 		int i = 0;
4910 
4911 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4912 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
4913 			regs[rd] = NULL;
4914 			break;
4915 		}
4916 
4917 		if (!DTRACE_INSCRATCH(mstate, size)) {
4918 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4919 			regs[rd] = NULL;
4920 			break;
4921 		}
4922 
4923 		for (;;) {
4924 			if (i >= size) {
4925 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4926 				regs[rd] = NULL;
4927 				break;
4928 			}
4929 
4930 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4931 				i--;
4932 				break;
4933 			}
4934 		}
4935 
4936 		for (;;) {
4937 			if (i >= size) {
4938 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4939 				regs[rd] = NULL;
4940 				break;
4941 			}
4942 
4943 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
4944 				break;
4945 		}
4946 
4947 		if (i < size) {
4948 			mstate->dtms_scratch_ptr += i;
4949 			regs[rd] = (uintptr_t)d;
4950 		}
4951 
4952 		break;
4953 	}
4954 
4955 	case DIF_SUBR_STRTOLL: {
4956 		uintptr_t s = tupregs[0].dttk_value;
4957 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4958 		int base = 10;
4959 
4960 		if (nargs > 1) {
4961 			if ((base = tupregs[1].dttk_value) <= 1 ||
4962 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4963 				*flags |= CPU_DTRACE_ILLOP;
4964 				break;
4965 			}
4966 		}
4967 
4968 		if (!dtrace_strcanload(s, size, mstate, vstate)) {
4969 			regs[rd] = INT64_MIN;
4970 			break;
4971 		}
4972 
4973 		regs[rd] = dtrace_strtoll((char *)s, base, size);
4974 		break;
4975 	}
4976 
4977 	case DIF_SUBR_LLTOSTR: {
4978 		int64_t i = (int64_t)tupregs[0].dttk_value;
4979 		uint64_t val, digit;
4980 		uint64_t size = 65;	/* enough room for 2^64 in binary */
4981 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4982 		int base = 10;
4983 
4984 		if (nargs > 1) {
4985 			if ((base = tupregs[1].dttk_value) <= 1 ||
4986 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4987 				*flags |= CPU_DTRACE_ILLOP;
4988 				break;
4989 			}
4990 		}
4991 
4992 		val = (base == 10 && i < 0) ? i * -1 : i;
4993 
4994 		if (!DTRACE_INSCRATCH(mstate, size)) {
4995 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4996 			regs[rd] = NULL;
4997 			break;
4998 		}
4999 
5000 		for (*end-- = '\0'; val; val /= base) {
5001 			if ((digit = val % base) <= '9' - '0') {
5002 				*end-- = '0' + digit;
5003 			} else {
5004 				*end-- = 'a' + (digit - ('9' - '0') - 1);
5005 			}
5006 		}
5007 
5008 		if (i == 0 && base == 16)
5009 			*end-- = '0';
5010 
5011 		if (base == 16)
5012 			*end-- = 'x';
5013 
5014 		if (i == 0 || base == 8 || base == 16)
5015 			*end-- = '0';
5016 
5017 		if (i < 0 && base == 10)
5018 			*end-- = '-';
5019 
5020 		regs[rd] = (uintptr_t)end + 1;
5021 		mstate->dtms_scratch_ptr += size;
5022 		break;
5023 	}
5024 
5025 	case DIF_SUBR_HTONS:
5026 	case DIF_SUBR_NTOHS:
5027 #ifdef _BIG_ENDIAN
5028 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
5029 #else
5030 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5031 #endif
5032 		break;
5033 
5034 
5035 	case DIF_SUBR_HTONL:
5036 	case DIF_SUBR_NTOHL:
5037 #ifdef _BIG_ENDIAN
5038 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5039 #else
5040 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5041 #endif
5042 		break;
5043 
5044 
5045 	case DIF_SUBR_HTONLL:
5046 	case DIF_SUBR_NTOHLL:
5047 #ifdef _BIG_ENDIAN
5048 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5049 #else
5050 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5051 #endif
5052 		break;
5053 
5054 
5055 	case DIF_SUBR_DIRNAME:
5056 	case DIF_SUBR_BASENAME: {
5057 		char *dest = (char *)mstate->dtms_scratch_ptr;
5058 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5059 		uintptr_t src = tupregs[0].dttk_value;
5060 		int i, j, len = dtrace_strlen((char *)src, size);
5061 		int lastbase = -1, firstbase = -1, lastdir = -1;
5062 		int start, end;
5063 
5064 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5065 			regs[rd] = NULL;
5066 			break;
5067 		}
5068 
5069 		if (!DTRACE_INSCRATCH(mstate, size)) {
5070 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5071 			regs[rd] = NULL;
5072 			break;
5073 		}
5074 
5075 		/*
5076 		 * The basename and dirname for a zero-length string is
5077 		 * defined to be "."
5078 		 */
5079 		if (len == 0) {
5080 			len = 1;
5081 			src = (uintptr_t)".";
5082 		}
5083 
5084 		/*
5085 		 * Start from the back of the string, moving back toward the
5086 		 * front until we see a character that isn't a slash.  That
5087 		 * character is the last character in the basename.
5088 		 */
5089 		for (i = len - 1; i >= 0; i--) {
5090 			if (dtrace_load8(src + i) != '/')
5091 				break;
5092 		}
5093 
5094 		if (i >= 0)
5095 			lastbase = i;
5096 
5097 		/*
5098 		 * Starting from the last character in the basename, move
5099 		 * towards the front until we find a slash.  The character
5100 		 * that we processed immediately before that is the first
5101 		 * character in the basename.
5102 		 */
5103 		for (; i >= 0; i--) {
5104 			if (dtrace_load8(src + i) == '/')
5105 				break;
5106 		}
5107 
5108 		if (i >= 0)
5109 			firstbase = i + 1;
5110 
5111 		/*
5112 		 * Now keep going until we find a non-slash character.  That
5113 		 * character is the last character in the dirname.
5114 		 */
5115 		for (; i >= 0; i--) {
5116 			if (dtrace_load8(src + i) != '/')
5117 				break;
5118 		}
5119 
5120 		if (i >= 0)
5121 			lastdir = i;
5122 
5123 		ASSERT(!(lastbase == -1 && firstbase != -1));
5124 		ASSERT(!(firstbase == -1 && lastdir != -1));
5125 
5126 		if (lastbase == -1) {
5127 			/*
5128 			 * We didn't find a non-slash character.  We know that
5129 			 * the length is non-zero, so the whole string must be
5130 			 * slashes.  In either the dirname or the basename
5131 			 * case, we return '/'.
5132 			 */
5133 			ASSERT(firstbase == -1);
5134 			firstbase = lastbase = lastdir = 0;
5135 		}
5136 
5137 		if (firstbase == -1) {
5138 			/*
5139 			 * The entire string consists only of a basename
5140 			 * component.  If we're looking for dirname, we need
5141 			 * to change our string to be just "."; if we're
5142 			 * looking for a basename, we'll just set the first
5143 			 * character of the basename to be 0.
5144 			 */
5145 			if (subr == DIF_SUBR_DIRNAME) {
5146 				ASSERT(lastdir == -1);
5147 				src = (uintptr_t)".";
5148 				lastdir = 0;
5149 			} else {
5150 				firstbase = 0;
5151 			}
5152 		}
5153 
5154 		if (subr == DIF_SUBR_DIRNAME) {
5155 			if (lastdir == -1) {
5156 				/*
5157 				 * We know that we have a slash in the name --
5158 				 * or lastdir would be set to 0, above.  And
5159 				 * because lastdir is -1, we know that this
5160 				 * slash must be the first character.  (That
5161 				 * is, the full string must be of the form
5162 				 * "/basename".)  In this case, the last
5163 				 * character of the directory name is 0.
5164 				 */
5165 				lastdir = 0;
5166 			}
5167 
5168 			start = 0;
5169 			end = lastdir;
5170 		} else {
5171 			ASSERT(subr == DIF_SUBR_BASENAME);
5172 			ASSERT(firstbase != -1 && lastbase != -1);
5173 			start = firstbase;
5174 			end = lastbase;
5175 		}
5176 
5177 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5178 			dest[j] = dtrace_load8(src + i);
5179 
5180 		dest[j] = '\0';
5181 		regs[rd] = (uintptr_t)dest;
5182 		mstate->dtms_scratch_ptr += size;
5183 		break;
5184 	}
5185 
5186 	case DIF_SUBR_GETF: {
5187 		uintptr_t fd = tupregs[0].dttk_value;
5188 		uf_info_t *finfo = &curthread->t_procp->p_user.u_finfo;
5189 		file_t *fp;
5190 
5191 		if (!dtrace_priv_proc(state, mstate)) {
5192 			regs[rd] = NULL;
5193 			break;
5194 		}
5195 
5196 		/*
5197 		 * This is safe because fi_nfiles only increases, and the
5198 		 * fi_list array is not freed when the array size doubles.
5199 		 * (See the comment in flist_grow() for details on the
5200 		 * management of the u_finfo structure.)
5201 		 */
5202 		fp = fd < finfo->fi_nfiles ? finfo->fi_list[fd].uf_file : NULL;
5203 
5204 		mstate->dtms_getf = fp;
5205 		regs[rd] = (uintptr_t)fp;
5206 		break;
5207 	}
5208 
5209 	case DIF_SUBR_CLEANPATH: {
5210 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5211 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5212 		uintptr_t src = tupregs[0].dttk_value;
5213 		int i = 0, j = 0;
5214 		zone_t *z;
5215 
5216 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
5217 			regs[rd] = NULL;
5218 			break;
5219 		}
5220 
5221 		if (!DTRACE_INSCRATCH(mstate, size)) {
5222 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5223 			regs[rd] = NULL;
5224 			break;
5225 		}
5226 
5227 		/*
5228 		 * Move forward, loading each character.
5229 		 */
5230 		do {
5231 			c = dtrace_load8(src + i++);
5232 next:
5233 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
5234 				break;
5235 
5236 			if (c != '/') {
5237 				dest[j++] = c;
5238 				continue;
5239 			}
5240 
5241 			c = dtrace_load8(src + i++);
5242 
5243 			if (c == '/') {
5244 				/*
5245 				 * We have two slashes -- we can just advance
5246 				 * to the next character.
5247 				 */
5248 				goto next;
5249 			}
5250 
5251 			if (c != '.') {
5252 				/*
5253 				 * This is not "." and it's not ".." -- we can
5254 				 * just store the "/" and this character and
5255 				 * drive on.
5256 				 */
5257 				dest[j++] = '/';
5258 				dest[j++] = c;
5259 				continue;
5260 			}
5261 
5262 			c = dtrace_load8(src + i++);
5263 
5264 			if (c == '/') {
5265 				/*
5266 				 * This is a "/./" component.  We're not going
5267 				 * to store anything in the destination buffer;
5268 				 * we're just going to go to the next component.
5269 				 */
5270 				goto next;
5271 			}
5272 
5273 			if (c != '.') {
5274 				/*
5275 				 * This is not ".." -- we can just store the
5276 				 * "/." and this character and continue
5277 				 * processing.
5278 				 */
5279 				dest[j++] = '/';
5280 				dest[j++] = '.';
5281 				dest[j++] = c;
5282 				continue;
5283 			}
5284 
5285 			c = dtrace_load8(src + i++);
5286 
5287 			if (c != '/' && c != '\0') {
5288 				/*
5289 				 * This is not ".." -- it's "..[mumble]".
5290 				 * We'll store the "/.." and this character
5291 				 * and continue processing.
5292 				 */
5293 				dest[j++] = '/';
5294 				dest[j++] = '.';
5295 				dest[j++] = '.';
5296 				dest[j++] = c;
5297 				continue;
5298 			}
5299 
5300 			/*
5301 			 * This is "/../" or "/..\0".  We need to back up
5302 			 * our destination pointer until we find a "/".
5303 			 */
5304 			i--;
5305 			while (j != 0 && dest[--j] != '/')
5306 				continue;
5307 
5308 			if (c == '\0')
5309 				dest[++j] = '/';
5310 		} while (c != '\0');
5311 
5312 		dest[j] = '\0';
5313 
5314 		if (mstate->dtms_getf != NULL &&
5315 		    !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5316 		    (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5317 			/*
5318 			 * If we've done a getf() as a part of this ECB and we
5319 			 * don't have kernel access (and we're not in the global
5320 			 * zone), check if the path we cleaned up begins with
5321 			 * the zone's root path, and trim it off if so.  Note
5322 			 * that this is an output cleanliness issue, not a
5323 			 * security issue: knowing one's zone root path does
5324 			 * not enable privilege escalation.
5325 			 */
5326 			if (strstr(dest, z->zone_rootpath) == dest)
5327 				dest += strlen(z->zone_rootpath) - 1;
5328 		}
5329 
5330 		regs[rd] = (uintptr_t)dest;
5331 		mstate->dtms_scratch_ptr += size;
5332 		break;
5333 	}
5334 
5335 	case DIF_SUBR_INET_NTOA:
5336 	case DIF_SUBR_INET_NTOA6:
5337 	case DIF_SUBR_INET_NTOP: {
5338 		size_t size;
5339 		int af, argi, i;
5340 		char *base, *end;
5341 
5342 		if (subr == DIF_SUBR_INET_NTOP) {
5343 			af = (int)tupregs[0].dttk_value;
5344 			argi = 1;
5345 		} else {
5346 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5347 			argi = 0;
5348 		}
5349 
5350 		if (af == AF_INET) {
5351 			ipaddr_t ip4;
5352 			uint8_t *ptr8, val;
5353 
5354 			if (!dtrace_canload(tupregs[argi].dttk_value,
5355 			    sizeof (ipaddr_t), mstate, vstate)) {
5356 				regs[rd] = NULL;
5357 				break;
5358 			}
5359 
5360 			/*
5361 			 * Safely load the IPv4 address.
5362 			 */
5363 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5364 
5365 			/*
5366 			 * Check an IPv4 string will fit in scratch.
5367 			 */
5368 			size = INET_ADDRSTRLEN;
5369 			if (!DTRACE_INSCRATCH(mstate, size)) {
5370 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5371 				regs[rd] = NULL;
5372 				break;
5373 			}
5374 			base = (char *)mstate->dtms_scratch_ptr;
5375 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5376 
5377 			/*
5378 			 * Stringify as a dotted decimal quad.
5379 			 */
5380 			*end-- = '\0';
5381 			ptr8 = (uint8_t *)&ip4;
5382 			for (i = 3; i >= 0; i--) {
5383 				val = ptr8[i];
5384 
5385 				if (val == 0) {
5386 					*end-- = '0';
5387 				} else {
5388 					for (; val; val /= 10) {
5389 						*end-- = '0' + (val % 10);
5390 					}
5391 				}
5392 
5393 				if (i > 0)
5394 					*end-- = '.';
5395 			}
5396 			ASSERT(end + 1 >= base);
5397 
5398 		} else if (af == AF_INET6) {
5399 			struct in6_addr ip6;
5400 			int firstzero, tryzero, numzero, v6end;
5401 			uint16_t val;
5402 			const char digits[] = "0123456789abcdef";
5403 
5404 			/*
5405 			 * Stringify using RFC 1884 convention 2 - 16 bit
5406 			 * hexadecimal values with a zero-run compression.
5407 			 * Lower case hexadecimal digits are used.
5408 			 * 	eg, fe80::214:4fff:fe0b:76c8.
5409 			 * The IPv4 embedded form is returned for inet_ntop,
5410 			 * just the IPv4 string is returned for inet_ntoa6.
5411 			 */
5412 
5413 			if (!dtrace_canload(tupregs[argi].dttk_value,
5414 			    sizeof (struct in6_addr), mstate, vstate)) {
5415 				regs[rd] = NULL;
5416 				break;
5417 			}
5418 
5419 			/*
5420 			 * Safely load the IPv6 address.
5421 			 */
5422 			dtrace_bcopy(
5423 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5424 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5425 
5426 			/*
5427 			 * Check an IPv6 string will fit in scratch.
5428 			 */
5429 			size = INET6_ADDRSTRLEN;
5430 			if (!DTRACE_INSCRATCH(mstate, size)) {
5431 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5432 				regs[rd] = NULL;
5433 				break;
5434 			}
5435 			base = (char *)mstate->dtms_scratch_ptr;
5436 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5437 			*end-- = '\0';
5438 
5439 			/*
5440 			 * Find the longest run of 16 bit zero values
5441 			 * for the single allowed zero compression - "::".
5442 			 */
5443 			firstzero = -1;
5444 			tryzero = -1;
5445 			numzero = 1;
5446 			for (i = 0; i < sizeof (struct in6_addr); i++) {
5447 				if (ip6._S6_un._S6_u8[i] == 0 &&
5448 				    tryzero == -1 && i % 2 == 0) {
5449 					tryzero = i;
5450 					continue;
5451 				}
5452 
5453 				if (tryzero != -1 &&
5454 				    (ip6._S6_un._S6_u8[i] != 0 ||
5455 				    i == sizeof (struct in6_addr) - 1)) {
5456 
5457 					if (i - tryzero <= numzero) {
5458 						tryzero = -1;
5459 						continue;
5460 					}
5461 
5462 					firstzero = tryzero;
5463 					numzero = i - i % 2 - tryzero;
5464 					tryzero = -1;
5465 
5466 					if (ip6._S6_un._S6_u8[i] == 0 &&
5467 					    i == sizeof (struct in6_addr) - 1)
5468 						numzero += 2;
5469 				}
5470 			}
5471 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5472 
5473 			/*
5474 			 * Check for an IPv4 embedded address.
5475 			 */
5476 			v6end = sizeof (struct in6_addr) - 2;
5477 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5478 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5479 				for (i = sizeof (struct in6_addr) - 1;
5480 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
5481 					ASSERT(end >= base);
5482 
5483 					val = ip6._S6_un._S6_u8[i];
5484 
5485 					if (val == 0) {
5486 						*end-- = '0';
5487 					} else {
5488 						for (; val; val /= 10) {
5489 							*end-- = '0' + val % 10;
5490 						}
5491 					}
5492 
5493 					if (i > DTRACE_V4MAPPED_OFFSET)
5494 						*end-- = '.';
5495 				}
5496 
5497 				if (subr == DIF_SUBR_INET_NTOA6)
5498 					goto inetout;
5499 
5500 				/*
5501 				 * Set v6end to skip the IPv4 address that
5502 				 * we have already stringified.
5503 				 */
5504 				v6end = 10;
5505 			}
5506 
5507 			/*
5508 			 * Build the IPv6 string by working through the
5509 			 * address in reverse.
5510 			 */
5511 			for (i = v6end; i >= 0; i -= 2) {
5512 				ASSERT(end >= base);
5513 
5514 				if (i == firstzero + numzero - 2) {
5515 					*end-- = ':';
5516 					*end-- = ':';
5517 					i -= numzero - 2;
5518 					continue;
5519 				}
5520 
5521 				if (i < 14 && i != firstzero - 2)
5522 					*end-- = ':';
5523 
5524 				val = (ip6._S6_un._S6_u8[i] << 8) +
5525 				    ip6._S6_un._S6_u8[i + 1];
5526 
5527 				if (val == 0) {
5528 					*end-- = '0';
5529 				} else {
5530 					for (; val; val /= 16) {
5531 						*end-- = digits[val % 16];
5532 					}
5533 				}
5534 			}
5535 			ASSERT(end + 1 >= base);
5536 
5537 		} else {
5538 			/*
5539 			 * The user didn't use AH_INET or AH_INET6.
5540 			 */
5541 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5542 			regs[rd] = NULL;
5543 			break;
5544 		}
5545 
5546 inetout:	regs[rd] = (uintptr_t)end + 1;
5547 		mstate->dtms_scratch_ptr += size;
5548 		break;
5549 	}
5550 
5551 	}
5552 }
5553 
5554 /*
5555  * Emulate the execution of DTrace IR instructions specified by the given
5556  * DIF object.  This function is deliberately void of assertions as all of
5557  * the necessary checks are handled by a call to dtrace_difo_validate().
5558  */
5559 static uint64_t
5560 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5561     dtrace_vstate_t *vstate, dtrace_state_t *state)
5562 {
5563 	const dif_instr_t *text = difo->dtdo_buf;
5564 	const uint_t textlen = difo->dtdo_len;
5565 	const char *strtab = difo->dtdo_strtab;
5566 	const uint64_t *inttab = difo->dtdo_inttab;
5567 
5568 	uint64_t rval = 0;
5569 	dtrace_statvar_t *svar;
5570 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5571 	dtrace_difv_t *v;
5572 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5573 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
5574 
5575 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5576 	uint64_t regs[DIF_DIR_NREGS];
5577 	uint64_t *tmp;
5578 
5579 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5580 	int64_t cc_r;
5581 	uint_t pc = 0, id, opc;
5582 	uint8_t ttop = 0;
5583 	dif_instr_t instr;
5584 	uint_t r1, r2, rd;
5585 
5586 	/*
5587 	 * We stash the current DIF object into the machine state: we need it
5588 	 * for subsequent access checking.
5589 	 */
5590 	mstate->dtms_difo = difo;
5591 
5592 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
5593 
5594 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5595 		opc = pc;
5596 
5597 		instr = text[pc++];
5598 		r1 = DIF_INSTR_R1(instr);
5599 		r2 = DIF_INSTR_R2(instr);
5600 		rd = DIF_INSTR_RD(instr);
5601 
5602 		switch (DIF_INSTR_OP(instr)) {
5603 		case DIF_OP_OR:
5604 			regs[rd] = regs[r1] | regs[r2];
5605 			break;
5606 		case DIF_OP_XOR:
5607 			regs[rd] = regs[r1] ^ regs[r2];
5608 			break;
5609 		case DIF_OP_AND:
5610 			regs[rd] = regs[r1] & regs[r2];
5611 			break;
5612 		case DIF_OP_SLL:
5613 			regs[rd] = regs[r1] << regs[r2];
5614 			break;
5615 		case DIF_OP_SRL:
5616 			regs[rd] = regs[r1] >> regs[r2];
5617 			break;
5618 		case DIF_OP_SUB:
5619 			regs[rd] = regs[r1] - regs[r2];
5620 			break;
5621 		case DIF_OP_ADD:
5622 			regs[rd] = regs[r1] + regs[r2];
5623 			break;
5624 		case DIF_OP_MUL:
5625 			regs[rd] = regs[r1] * regs[r2];
5626 			break;
5627 		case DIF_OP_SDIV:
5628 			if (regs[r2] == 0) {
5629 				regs[rd] = 0;
5630 				*flags |= CPU_DTRACE_DIVZERO;
5631 			} else {
5632 				regs[rd] = (int64_t)regs[r1] /
5633 				    (int64_t)regs[r2];
5634 			}
5635 			break;
5636 
5637 		case DIF_OP_UDIV:
5638 			if (regs[r2] == 0) {
5639 				regs[rd] = 0;
5640 				*flags |= CPU_DTRACE_DIVZERO;
5641 			} else {
5642 				regs[rd] = regs[r1] / regs[r2];
5643 			}
5644 			break;
5645 
5646 		case DIF_OP_SREM:
5647 			if (regs[r2] == 0) {
5648 				regs[rd] = 0;
5649 				*flags |= CPU_DTRACE_DIVZERO;
5650 			} else {
5651 				regs[rd] = (int64_t)regs[r1] %
5652 				    (int64_t)regs[r2];
5653 			}
5654 			break;
5655 
5656 		case DIF_OP_UREM:
5657 			if (regs[r2] == 0) {
5658 				regs[rd] = 0;
5659 				*flags |= CPU_DTRACE_DIVZERO;
5660 			} else {
5661 				regs[rd] = regs[r1] % regs[r2];
5662 			}
5663 			break;
5664 
5665 		case DIF_OP_NOT:
5666 			regs[rd] = ~regs[r1];
5667 			break;
5668 		case DIF_OP_MOV:
5669 			regs[rd] = regs[r1];
5670 			break;
5671 		case DIF_OP_CMP:
5672 			cc_r = regs[r1] - regs[r2];
5673 			cc_n = cc_r < 0;
5674 			cc_z = cc_r == 0;
5675 			cc_v = 0;
5676 			cc_c = regs[r1] < regs[r2];
5677 			break;
5678 		case DIF_OP_TST:
5679 			cc_n = cc_v = cc_c = 0;
5680 			cc_z = regs[r1] == 0;
5681 			break;
5682 		case DIF_OP_BA:
5683 			pc = DIF_INSTR_LABEL(instr);
5684 			break;
5685 		case DIF_OP_BE:
5686 			if (cc_z)
5687 				pc = DIF_INSTR_LABEL(instr);
5688 			break;
5689 		case DIF_OP_BNE:
5690 			if (cc_z == 0)
5691 				pc = DIF_INSTR_LABEL(instr);
5692 			break;
5693 		case DIF_OP_BG:
5694 			if ((cc_z | (cc_n ^ cc_v)) == 0)
5695 				pc = DIF_INSTR_LABEL(instr);
5696 			break;
5697 		case DIF_OP_BGU:
5698 			if ((cc_c | cc_z) == 0)
5699 				pc = DIF_INSTR_LABEL(instr);
5700 			break;
5701 		case DIF_OP_BGE:
5702 			if ((cc_n ^ cc_v) == 0)
5703 				pc = DIF_INSTR_LABEL(instr);
5704 			break;
5705 		case DIF_OP_BGEU:
5706 			if (cc_c == 0)
5707 				pc = DIF_INSTR_LABEL(instr);
5708 			break;
5709 		case DIF_OP_BL:
5710 			if (cc_n ^ cc_v)
5711 				pc = DIF_INSTR_LABEL(instr);
5712 			break;
5713 		case DIF_OP_BLU:
5714 			if (cc_c)
5715 				pc = DIF_INSTR_LABEL(instr);
5716 			break;
5717 		case DIF_OP_BLE:
5718 			if (cc_z | (cc_n ^ cc_v))
5719 				pc = DIF_INSTR_LABEL(instr);
5720 			break;
5721 		case DIF_OP_BLEU:
5722 			if (cc_c | cc_z)
5723 				pc = DIF_INSTR_LABEL(instr);
5724 			break;
5725 		case DIF_OP_RLDSB:
5726 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5727 				break;
5728 			/*FALLTHROUGH*/
5729 		case DIF_OP_LDSB:
5730 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5731 			break;
5732 		case DIF_OP_RLDSH:
5733 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5734 				break;
5735 			/*FALLTHROUGH*/
5736 		case DIF_OP_LDSH:
5737 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5738 			break;
5739 		case DIF_OP_RLDSW:
5740 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5741 				break;
5742 			/*FALLTHROUGH*/
5743 		case DIF_OP_LDSW:
5744 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5745 			break;
5746 		case DIF_OP_RLDUB:
5747 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5748 				break;
5749 			/*FALLTHROUGH*/
5750 		case DIF_OP_LDUB:
5751 			regs[rd] = dtrace_load8(regs[r1]);
5752 			break;
5753 		case DIF_OP_RLDUH:
5754 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5755 				break;
5756 			/*FALLTHROUGH*/
5757 		case DIF_OP_LDUH:
5758 			regs[rd] = dtrace_load16(regs[r1]);
5759 			break;
5760 		case DIF_OP_RLDUW:
5761 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5762 				break;
5763 			/*FALLTHROUGH*/
5764 		case DIF_OP_LDUW:
5765 			regs[rd] = dtrace_load32(regs[r1]);
5766 			break;
5767 		case DIF_OP_RLDX:
5768 			if (!dtrace_canload(regs[r1], 8, mstate, vstate))
5769 				break;
5770 			/*FALLTHROUGH*/
5771 		case DIF_OP_LDX:
5772 			regs[rd] = dtrace_load64(regs[r1]);
5773 			break;
5774 		case DIF_OP_ULDSB:
5775 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5776 			regs[rd] = (int8_t)
5777 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5778 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5779 			break;
5780 		case DIF_OP_ULDSH:
5781 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5782 			regs[rd] = (int16_t)
5783 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5784 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5785 			break;
5786 		case DIF_OP_ULDSW:
5787 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5788 			regs[rd] = (int32_t)
5789 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5790 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5791 			break;
5792 		case DIF_OP_ULDUB:
5793 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5794 			regs[rd] =
5795 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5796 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5797 			break;
5798 		case DIF_OP_ULDUH:
5799 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5800 			regs[rd] =
5801 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5802 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5803 			break;
5804 		case DIF_OP_ULDUW:
5805 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5806 			regs[rd] =
5807 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5808 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5809 			break;
5810 		case DIF_OP_ULDX:
5811 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5812 			regs[rd] =
5813 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5814 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5815 			break;
5816 		case DIF_OP_RET:
5817 			rval = regs[rd];
5818 			pc = textlen;
5819 			break;
5820 		case DIF_OP_NOP:
5821 			break;
5822 		case DIF_OP_SETX:
5823 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5824 			break;
5825 		case DIF_OP_SETS:
5826 			regs[rd] = (uint64_t)(uintptr_t)
5827 			    (strtab + DIF_INSTR_STRING(instr));
5828 			break;
5829 		case DIF_OP_SCMP: {
5830 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5831 			uintptr_t s1 = regs[r1];
5832 			uintptr_t s2 = regs[r2];
5833 
5834 			if (s1 != NULL &&
5835 			    !dtrace_strcanload(s1, sz, mstate, vstate))
5836 				break;
5837 			if (s2 != NULL &&
5838 			    !dtrace_strcanload(s2, sz, mstate, vstate))
5839 				break;
5840 
5841 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5842 
5843 			cc_n = cc_r < 0;
5844 			cc_z = cc_r == 0;
5845 			cc_v = cc_c = 0;
5846 			break;
5847 		}
5848 		case DIF_OP_LDGA:
5849 			regs[rd] = dtrace_dif_variable(mstate, state,
5850 			    r1, regs[r2]);
5851 			break;
5852 		case DIF_OP_LDGS:
5853 			id = DIF_INSTR_VAR(instr);
5854 
5855 			if (id >= DIF_VAR_OTHER_UBASE) {
5856 				uintptr_t a;
5857 
5858 				id -= DIF_VAR_OTHER_UBASE;
5859 				svar = vstate->dtvs_globals[id];
5860 				ASSERT(svar != NULL);
5861 				v = &svar->dtsv_var;
5862 
5863 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5864 					regs[rd] = svar->dtsv_data;
5865 					break;
5866 				}
5867 
5868 				a = (uintptr_t)svar->dtsv_data;
5869 
5870 				if (*(uint8_t *)a == UINT8_MAX) {
5871 					/*
5872 					 * If the 0th byte is set to UINT8_MAX
5873 					 * then this is to be treated as a
5874 					 * reference to a NULL variable.
5875 					 */
5876 					regs[rd] = NULL;
5877 				} else {
5878 					regs[rd] = a + sizeof (uint64_t);
5879 				}
5880 
5881 				break;
5882 			}
5883 
5884 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5885 			break;
5886 
5887 		case DIF_OP_STGS:
5888 			id = DIF_INSTR_VAR(instr);
5889 
5890 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5891 			id -= DIF_VAR_OTHER_UBASE;
5892 
5893 			VERIFY(id < vstate->dtvs_nglobals);
5894 			svar = vstate->dtvs_globals[id];
5895 			ASSERT(svar != NULL);
5896 			v = &svar->dtsv_var;
5897 
5898 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5899 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5900 
5901 				ASSERT(a != NULL);
5902 				ASSERT(svar->dtsv_size != 0);
5903 
5904 				if (regs[rd] == NULL) {
5905 					*(uint8_t *)a = UINT8_MAX;
5906 					break;
5907 				} else {
5908 					*(uint8_t *)a = 0;
5909 					a += sizeof (uint64_t);
5910 				}
5911 				if (!dtrace_vcanload(
5912 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5913 				    mstate, vstate))
5914 					break;
5915 
5916 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5917 				    (void *)a, &v->dtdv_type);
5918 				break;
5919 			}
5920 
5921 			svar->dtsv_data = regs[rd];
5922 			break;
5923 
5924 		case DIF_OP_LDTA:
5925 			/*
5926 			 * There are no DTrace built-in thread-local arrays at
5927 			 * present.  This opcode is saved for future work.
5928 			 */
5929 			*flags |= CPU_DTRACE_ILLOP;
5930 			regs[rd] = 0;
5931 			break;
5932 
5933 		case DIF_OP_LDLS:
5934 			id = DIF_INSTR_VAR(instr);
5935 
5936 			if (id < DIF_VAR_OTHER_UBASE) {
5937 				/*
5938 				 * For now, this has no meaning.
5939 				 */
5940 				regs[rd] = 0;
5941 				break;
5942 			}
5943 
5944 			id -= DIF_VAR_OTHER_UBASE;
5945 
5946 			ASSERT(id < vstate->dtvs_nlocals);
5947 			ASSERT(vstate->dtvs_locals != NULL);
5948 
5949 			svar = vstate->dtvs_locals[id];
5950 			ASSERT(svar != NULL);
5951 			v = &svar->dtsv_var;
5952 
5953 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5954 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5955 				size_t sz = v->dtdv_type.dtdt_size;
5956 
5957 				sz += sizeof (uint64_t);
5958 				ASSERT(svar->dtsv_size == NCPU * sz);
5959 				a += CPU->cpu_id * sz;
5960 
5961 				if (*(uint8_t *)a == UINT8_MAX) {
5962 					/*
5963 					 * If the 0th byte is set to UINT8_MAX
5964 					 * then this is to be treated as a
5965 					 * reference to a NULL variable.
5966 					 */
5967 					regs[rd] = NULL;
5968 				} else {
5969 					regs[rd] = a + sizeof (uint64_t);
5970 				}
5971 
5972 				break;
5973 			}
5974 
5975 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5976 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5977 			regs[rd] = tmp[CPU->cpu_id];
5978 			break;
5979 
5980 		case DIF_OP_STLS:
5981 			id = DIF_INSTR_VAR(instr);
5982 
5983 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5984 			id -= DIF_VAR_OTHER_UBASE;
5985 			VERIFY(id < vstate->dtvs_nlocals);
5986 
5987 			ASSERT(vstate->dtvs_locals != NULL);
5988 			svar = vstate->dtvs_locals[id];
5989 			ASSERT(svar != NULL);
5990 			v = &svar->dtsv_var;
5991 
5992 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5993 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5994 				size_t sz = v->dtdv_type.dtdt_size;
5995 
5996 				sz += sizeof (uint64_t);
5997 				ASSERT(svar->dtsv_size == NCPU * sz);
5998 				a += CPU->cpu_id * sz;
5999 
6000 				if (regs[rd] == NULL) {
6001 					*(uint8_t *)a = UINT8_MAX;
6002 					break;
6003 				} else {
6004 					*(uint8_t *)a = 0;
6005 					a += sizeof (uint64_t);
6006 				}
6007 
6008 				if (!dtrace_vcanload(
6009 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6010 				    mstate, vstate))
6011 					break;
6012 
6013 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6014 				    (void *)a, &v->dtdv_type);
6015 				break;
6016 			}
6017 
6018 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6019 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6020 			tmp[CPU->cpu_id] = regs[rd];
6021 			break;
6022 
6023 		case DIF_OP_LDTS: {
6024 			dtrace_dynvar_t *dvar;
6025 			dtrace_key_t *key;
6026 
6027 			id = DIF_INSTR_VAR(instr);
6028 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6029 			id -= DIF_VAR_OTHER_UBASE;
6030 			v = &vstate->dtvs_tlocals[id];
6031 
6032 			key = &tupregs[DIF_DTR_NREGS];
6033 			key[0].dttk_value = (uint64_t)id;
6034 			key[0].dttk_size = 0;
6035 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6036 			key[1].dttk_size = 0;
6037 
6038 			dvar = dtrace_dynvar(dstate, 2, key,
6039 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6040 			    mstate, vstate);
6041 
6042 			if (dvar == NULL) {
6043 				regs[rd] = 0;
6044 				break;
6045 			}
6046 
6047 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6048 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6049 			} else {
6050 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6051 			}
6052 
6053 			break;
6054 		}
6055 
6056 		case DIF_OP_STTS: {
6057 			dtrace_dynvar_t *dvar;
6058 			dtrace_key_t *key;
6059 
6060 			id = DIF_INSTR_VAR(instr);
6061 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6062 			id -= DIF_VAR_OTHER_UBASE;
6063 			VERIFY(id < vstate->dtvs_ntlocals);
6064 
6065 			key = &tupregs[DIF_DTR_NREGS];
6066 			key[0].dttk_value = (uint64_t)id;
6067 			key[0].dttk_size = 0;
6068 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6069 			key[1].dttk_size = 0;
6070 			v = &vstate->dtvs_tlocals[id];
6071 
6072 			dvar = dtrace_dynvar(dstate, 2, key,
6073 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6074 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6075 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6076 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6077 
6078 			/*
6079 			 * Given that we're storing to thread-local data,
6080 			 * we need to flush our predicate cache.
6081 			 */
6082 			curthread->t_predcache = NULL;
6083 
6084 			if (dvar == NULL)
6085 				break;
6086 
6087 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6088 				if (!dtrace_vcanload(
6089 				    (void *)(uintptr_t)regs[rd],
6090 				    &v->dtdv_type, mstate, vstate))
6091 					break;
6092 
6093 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6094 				    dvar->dtdv_data, &v->dtdv_type);
6095 			} else {
6096 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6097 			}
6098 
6099 			break;
6100 		}
6101 
6102 		case DIF_OP_SRA:
6103 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6104 			break;
6105 
6106 		case DIF_OP_CALL:
6107 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6108 			    regs, tupregs, ttop, mstate, state);
6109 			break;
6110 
6111 		case DIF_OP_PUSHTR:
6112 			if (ttop == DIF_DTR_NREGS) {
6113 				*flags |= CPU_DTRACE_TUPOFLOW;
6114 				break;
6115 			}
6116 
6117 			if (r1 == DIF_TYPE_STRING) {
6118 				/*
6119 				 * If this is a string type and the size is 0,
6120 				 * we'll use the system-wide default string
6121 				 * size.  Note that we are _not_ looking at
6122 				 * the value of the DTRACEOPT_STRSIZE option;
6123 				 * had this been set, we would expect to have
6124 				 * a non-zero size value in the "pushtr".
6125 				 */
6126 				tupregs[ttop].dttk_size =
6127 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6128 				    regs[r2] ? regs[r2] :
6129 				    dtrace_strsize_default) + 1;
6130 			} else {
6131 				if (regs[r2] > LONG_MAX) {
6132 					*flags |= CPU_DTRACE_ILLOP;
6133 					break;
6134 				}
6135 
6136 				tupregs[ttop].dttk_size = regs[r2];
6137 			}
6138 
6139 			tupregs[ttop++].dttk_value = regs[rd];
6140 			break;
6141 
6142 		case DIF_OP_PUSHTV:
6143 			if (ttop == DIF_DTR_NREGS) {
6144 				*flags |= CPU_DTRACE_TUPOFLOW;
6145 				break;
6146 			}
6147 
6148 			tupregs[ttop].dttk_value = regs[rd];
6149 			tupregs[ttop++].dttk_size = 0;
6150 			break;
6151 
6152 		case DIF_OP_POPTS:
6153 			if (ttop != 0)
6154 				ttop--;
6155 			break;
6156 
6157 		case DIF_OP_FLUSHTS:
6158 			ttop = 0;
6159 			break;
6160 
6161 		case DIF_OP_LDGAA:
6162 		case DIF_OP_LDTAA: {
6163 			dtrace_dynvar_t *dvar;
6164 			dtrace_key_t *key = tupregs;
6165 			uint_t nkeys = ttop;
6166 
6167 			id = DIF_INSTR_VAR(instr);
6168 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6169 			id -= DIF_VAR_OTHER_UBASE;
6170 
6171 			key[nkeys].dttk_value = (uint64_t)id;
6172 			key[nkeys++].dttk_size = 0;
6173 
6174 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6175 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6176 				key[nkeys++].dttk_size = 0;
6177 				VERIFY(id < vstate->dtvs_ntlocals);
6178 				v = &vstate->dtvs_tlocals[id];
6179 			} else {
6180 				VERIFY(id < vstate->dtvs_nglobals);
6181 				v = &vstate->dtvs_globals[id]->dtsv_var;
6182 			}
6183 
6184 			dvar = dtrace_dynvar(dstate, nkeys, key,
6185 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6186 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6187 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6188 
6189 			if (dvar == NULL) {
6190 				regs[rd] = 0;
6191 				break;
6192 			}
6193 
6194 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6195 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6196 			} else {
6197 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6198 			}
6199 
6200 			break;
6201 		}
6202 
6203 		case DIF_OP_STGAA:
6204 		case DIF_OP_STTAA: {
6205 			dtrace_dynvar_t *dvar;
6206 			dtrace_key_t *key = tupregs;
6207 			uint_t nkeys = ttop;
6208 
6209 			id = DIF_INSTR_VAR(instr);
6210 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6211 			id -= DIF_VAR_OTHER_UBASE;
6212 
6213 			key[nkeys].dttk_value = (uint64_t)id;
6214 			key[nkeys++].dttk_size = 0;
6215 
6216 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6217 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6218 				key[nkeys++].dttk_size = 0;
6219 				VERIFY(id < vstate->dtvs_ntlocals);
6220 				v = &vstate->dtvs_tlocals[id];
6221 			} else {
6222 				VERIFY(id < vstate->dtvs_nglobals);
6223 				v = &vstate->dtvs_globals[id]->dtsv_var;
6224 			}
6225 
6226 			dvar = dtrace_dynvar(dstate, nkeys, key,
6227 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6228 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6229 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6230 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6231 
6232 			if (dvar == NULL)
6233 				break;
6234 
6235 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6236 				if (!dtrace_vcanload(
6237 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6238 				    mstate, vstate))
6239 					break;
6240 
6241 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6242 				    dvar->dtdv_data, &v->dtdv_type);
6243 			} else {
6244 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6245 			}
6246 
6247 			break;
6248 		}
6249 
6250 		case DIF_OP_ALLOCS: {
6251 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6252 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6253 
6254 			/*
6255 			 * Rounding up the user allocation size could have
6256 			 * overflowed large, bogus allocations (like -1ULL) to
6257 			 * 0.
6258 			 */
6259 			if (size < regs[r1] ||
6260 			    !DTRACE_INSCRATCH(mstate, size)) {
6261 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6262 				regs[rd] = NULL;
6263 				break;
6264 			}
6265 
6266 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6267 			mstate->dtms_scratch_ptr += size;
6268 			regs[rd] = ptr;
6269 			break;
6270 		}
6271 
6272 		case DIF_OP_COPYS:
6273 			if (!dtrace_canstore(regs[rd], regs[r2],
6274 			    mstate, vstate)) {
6275 				*flags |= CPU_DTRACE_BADADDR;
6276 				*illval = regs[rd];
6277 				break;
6278 			}
6279 
6280 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6281 				break;
6282 
6283 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6284 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6285 			break;
6286 
6287 		case DIF_OP_STB:
6288 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6289 				*flags |= CPU_DTRACE_BADADDR;
6290 				*illval = regs[rd];
6291 				break;
6292 			}
6293 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6294 			break;
6295 
6296 		case DIF_OP_STH:
6297 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6298 				*flags |= CPU_DTRACE_BADADDR;
6299 				*illval = regs[rd];
6300 				break;
6301 			}
6302 			if (regs[rd] & 1) {
6303 				*flags |= CPU_DTRACE_BADALIGN;
6304 				*illval = regs[rd];
6305 				break;
6306 			}
6307 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6308 			break;
6309 
6310 		case DIF_OP_STW:
6311 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6312 				*flags |= CPU_DTRACE_BADADDR;
6313 				*illval = regs[rd];
6314 				break;
6315 			}
6316 			if (regs[rd] & 3) {
6317 				*flags |= CPU_DTRACE_BADALIGN;
6318 				*illval = regs[rd];
6319 				break;
6320 			}
6321 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6322 			break;
6323 
6324 		case DIF_OP_STX:
6325 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6326 				*flags |= CPU_DTRACE_BADADDR;
6327 				*illval = regs[rd];
6328 				break;
6329 			}
6330 			if (regs[rd] & 7) {
6331 				*flags |= CPU_DTRACE_BADALIGN;
6332 				*illval = regs[rd];
6333 				break;
6334 			}
6335 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6336 			break;
6337 		}
6338 	}
6339 
6340 	if (!(*flags & CPU_DTRACE_FAULT))
6341 		return (rval);
6342 
6343 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6344 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6345 
6346 	return (0);
6347 }
6348 
6349 static void
6350 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6351 {
6352 	dtrace_probe_t *probe = ecb->dte_probe;
6353 	dtrace_provider_t *prov = probe->dtpr_provider;
6354 	char c[DTRACE_FULLNAMELEN + 80], *str;
6355 	char *msg = "dtrace: breakpoint action at probe ";
6356 	char *ecbmsg = " (ecb ";
6357 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6358 	uintptr_t val = (uintptr_t)ecb;
6359 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6360 
6361 	if (dtrace_destructive_disallow)
6362 		return;
6363 
6364 	/*
6365 	 * It's impossible to be taking action on the NULL probe.
6366 	 */
6367 	ASSERT(probe != NULL);
6368 
6369 	/*
6370 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6371 	 * print the provider name, module name, function name and name of
6372 	 * the probe, along with the hex address of the ECB with the breakpoint
6373 	 * action -- all of which we must place in the character buffer by
6374 	 * hand.
6375 	 */
6376 	while (*msg != '\0')
6377 		c[i++] = *msg++;
6378 
6379 	for (str = prov->dtpv_name; *str != '\0'; str++)
6380 		c[i++] = *str;
6381 	c[i++] = ':';
6382 
6383 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6384 		c[i++] = *str;
6385 	c[i++] = ':';
6386 
6387 	for (str = probe->dtpr_func; *str != '\0'; str++)
6388 		c[i++] = *str;
6389 	c[i++] = ':';
6390 
6391 	for (str = probe->dtpr_name; *str != '\0'; str++)
6392 		c[i++] = *str;
6393 
6394 	while (*ecbmsg != '\0')
6395 		c[i++] = *ecbmsg++;
6396 
6397 	while (shift >= 0) {
6398 		mask = (uintptr_t)0xf << shift;
6399 
6400 		if (val >= ((uintptr_t)1 << shift))
6401 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6402 		shift -= 4;
6403 	}
6404 
6405 	c[i++] = ')';
6406 	c[i] = '\0';
6407 
6408 	debug_enter(c);
6409 }
6410 
6411 static void
6412 dtrace_action_panic(dtrace_ecb_t *ecb)
6413 {
6414 	dtrace_probe_t *probe = ecb->dte_probe;
6415 
6416 	/*
6417 	 * It's impossible to be taking action on the NULL probe.
6418 	 */
6419 	ASSERT(probe != NULL);
6420 
6421 	if (dtrace_destructive_disallow)
6422 		return;
6423 
6424 	if (dtrace_panicked != NULL)
6425 		return;
6426 
6427 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6428 		return;
6429 
6430 	/*
6431 	 * We won the right to panic.  (We want to be sure that only one
6432 	 * thread calls panic() from dtrace_probe(), and that panic() is
6433 	 * called exactly once.)
6434 	 */
6435 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6436 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6437 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6438 }
6439 
6440 static void
6441 dtrace_action_raise(uint64_t sig)
6442 {
6443 	if (dtrace_destructive_disallow)
6444 		return;
6445 
6446 	if (sig >= NSIG) {
6447 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6448 		return;
6449 	}
6450 
6451 	/*
6452 	 * raise() has a queue depth of 1 -- we ignore all subsequent
6453 	 * invocations of the raise() action.
6454 	 */
6455 	if (curthread->t_dtrace_sig == 0)
6456 		curthread->t_dtrace_sig = (uint8_t)sig;
6457 
6458 	curthread->t_sig_check = 1;
6459 	aston(curthread);
6460 }
6461 
6462 static void
6463 dtrace_action_stop(void)
6464 {
6465 	if (dtrace_destructive_disallow)
6466 		return;
6467 
6468 	if (!curthread->t_dtrace_stop) {
6469 		curthread->t_dtrace_stop = 1;
6470 		curthread->t_sig_check = 1;
6471 		aston(curthread);
6472 	}
6473 }
6474 
6475 static void
6476 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6477 {
6478 	hrtime_t now;
6479 	volatile uint16_t *flags;
6480 	cpu_t *cpu = CPU;
6481 
6482 	if (dtrace_destructive_disallow)
6483 		return;
6484 
6485 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6486 
6487 	now = dtrace_gethrtime();
6488 
6489 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6490 		/*
6491 		 * We need to advance the mark to the current time.
6492 		 */
6493 		cpu->cpu_dtrace_chillmark = now;
6494 		cpu->cpu_dtrace_chilled = 0;
6495 	}
6496 
6497 	/*
6498 	 * Now check to see if the requested chill time would take us over
6499 	 * the maximum amount of time allowed in the chill interval.  (Or
6500 	 * worse, if the calculation itself induces overflow.)
6501 	 */
6502 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6503 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6504 		*flags |= CPU_DTRACE_ILLOP;
6505 		return;
6506 	}
6507 
6508 	while (dtrace_gethrtime() - now < val)
6509 		continue;
6510 
6511 	/*
6512 	 * Normally, we assure that the value of the variable "timestamp" does
6513 	 * not change within an ECB.  The presence of chill() represents an
6514 	 * exception to this rule, however.
6515 	 */
6516 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6517 	cpu->cpu_dtrace_chilled += val;
6518 }
6519 
6520 static void
6521 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6522     uint64_t *buf, uint64_t arg)
6523 {
6524 	int nframes = DTRACE_USTACK_NFRAMES(arg);
6525 	int strsize = DTRACE_USTACK_STRSIZE(arg);
6526 	uint64_t *pcs = &buf[1], *fps;
6527 	char *str = (char *)&pcs[nframes];
6528 	int size, offs = 0, i, j;
6529 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
6530 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6531 	char *sym;
6532 
6533 	/*
6534 	 * Should be taking a faster path if string space has not been
6535 	 * allocated.
6536 	 */
6537 	ASSERT(strsize != 0);
6538 
6539 	/*
6540 	 * We will first allocate some temporary space for the frame pointers.
6541 	 */
6542 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6543 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6544 	    (nframes * sizeof (uint64_t));
6545 
6546 	if (!DTRACE_INSCRATCH(mstate, size)) {
6547 		/*
6548 		 * Not enough room for our frame pointers -- need to indicate
6549 		 * that we ran out of scratch space.
6550 		 */
6551 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6552 		return;
6553 	}
6554 
6555 	mstate->dtms_scratch_ptr += size;
6556 	saved = mstate->dtms_scratch_ptr;
6557 
6558 	/*
6559 	 * Now get a stack with both program counters and frame pointers.
6560 	 */
6561 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6562 	dtrace_getufpstack(buf, fps, nframes + 1);
6563 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6564 
6565 	/*
6566 	 * If that faulted, we're cooked.
6567 	 */
6568 	if (*flags & CPU_DTRACE_FAULT)
6569 		goto out;
6570 
6571 	/*
6572 	 * Now we want to walk up the stack, calling the USTACK helper.  For
6573 	 * each iteration, we restore the scratch pointer.
6574 	 */
6575 	for (i = 0; i < nframes; i++) {
6576 		mstate->dtms_scratch_ptr = saved;
6577 
6578 		if (offs >= strsize)
6579 			break;
6580 
6581 		sym = (char *)(uintptr_t)dtrace_helper(
6582 		    DTRACE_HELPER_ACTION_USTACK,
6583 		    mstate, state, pcs[i], fps[i]);
6584 
6585 		/*
6586 		 * If we faulted while running the helper, we're going to
6587 		 * clear the fault and null out the corresponding string.
6588 		 */
6589 		if (*flags & CPU_DTRACE_FAULT) {
6590 			*flags &= ~CPU_DTRACE_FAULT;
6591 			str[offs++] = '\0';
6592 			continue;
6593 		}
6594 
6595 		if (sym == NULL) {
6596 			str[offs++] = '\0';
6597 			continue;
6598 		}
6599 
6600 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6601 
6602 		/*
6603 		 * Now copy in the string that the helper returned to us.
6604 		 */
6605 		for (j = 0; offs + j < strsize; j++) {
6606 			if ((str[offs + j] = sym[j]) == '\0')
6607 				break;
6608 		}
6609 
6610 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6611 
6612 		offs += j + 1;
6613 	}
6614 
6615 	if (offs >= strsize) {
6616 		/*
6617 		 * If we didn't have room for all of the strings, we don't
6618 		 * abort processing -- this needn't be a fatal error -- but we
6619 		 * still want to increment a counter (dts_stkstroverflows) to
6620 		 * allow this condition to be warned about.  (If this is from
6621 		 * a jstack() action, it is easily tuned via jstackstrsize.)
6622 		 */
6623 		dtrace_error(&state->dts_stkstroverflows);
6624 	}
6625 
6626 	while (offs < strsize)
6627 		str[offs++] = '\0';
6628 
6629 out:
6630 	mstate->dtms_scratch_ptr = old;
6631 }
6632 
6633 static void
6634 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
6635     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
6636 {
6637 	volatile uint16_t *flags;
6638 	uint64_t val = *valp;
6639 	size_t valoffs = *valoffsp;
6640 
6641 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6642 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
6643 
6644 	/*
6645 	 * If this is a string, we're going to only load until we find the zero
6646 	 * byte -- after which we'll store zero bytes.
6647 	 */
6648 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
6649 		char c = '\0' + 1;
6650 		size_t s;
6651 
6652 		for (s = 0; s < size; s++) {
6653 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
6654 				c = dtrace_load8(val++);
6655 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
6656 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6657 				c = dtrace_fuword8((void *)(uintptr_t)val++);
6658 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6659 				if (*flags & CPU_DTRACE_FAULT)
6660 					break;
6661 			}
6662 
6663 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
6664 
6665 			if (c == '\0' && intuple)
6666 				break;
6667 		}
6668 	} else {
6669 		uint8_t c;
6670 		while (valoffs < end) {
6671 			if (dtkind == DIF_TF_BYREF) {
6672 				c = dtrace_load8(val++);
6673 			} else if (dtkind == DIF_TF_BYUREF) {
6674 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6675 				c = dtrace_fuword8((void *)(uintptr_t)val++);
6676 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6677 				if (*flags & CPU_DTRACE_FAULT)
6678 					break;
6679 			}
6680 
6681 			DTRACE_STORE(uint8_t, tomax,
6682 			    valoffs++, c);
6683 		}
6684 	}
6685 
6686 	*valp = val;
6687 	*valoffsp = valoffs;
6688 }
6689 
6690 /*
6691  * If you're looking for the epicenter of DTrace, you just found it.  This
6692  * is the function called by the provider to fire a probe -- from which all
6693  * subsequent probe-context DTrace activity emanates.
6694  */
6695 void
6696 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6697     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6698 {
6699 	processorid_t cpuid;
6700 	dtrace_icookie_t cookie;
6701 	dtrace_probe_t *probe;
6702 	dtrace_mstate_t mstate;
6703 	dtrace_ecb_t *ecb;
6704 	dtrace_action_t *act;
6705 	intptr_t offs;
6706 	size_t size;
6707 	int vtime, onintr;
6708 	volatile uint16_t *flags;
6709 	hrtime_t now, end;
6710 
6711 	/*
6712 	 * Kick out immediately if this CPU is still being born (in which case
6713 	 * curthread will be set to -1) or the current thread can't allow
6714 	 * probes in its current context.
6715 	 */
6716 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6717 		return;
6718 
6719 	cookie = dtrace_interrupt_disable();
6720 	probe = dtrace_probes[id - 1];
6721 	cpuid = CPU->cpu_id;
6722 	onintr = CPU_ON_INTR(CPU);
6723 
6724 	CPU->cpu_dtrace_probes++;
6725 
6726 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6727 	    probe->dtpr_predcache == curthread->t_predcache) {
6728 		/*
6729 		 * We have hit in the predicate cache; we know that
6730 		 * this predicate would evaluate to be false.
6731 		 */
6732 		dtrace_interrupt_enable(cookie);
6733 		return;
6734 	}
6735 
6736 	if (panic_quiesce) {
6737 		/*
6738 		 * We don't trace anything if we're panicking.
6739 		 */
6740 		dtrace_interrupt_enable(cookie);
6741 		return;
6742 	}
6743 
6744 	now = mstate.dtms_timestamp = dtrace_gethrtime();
6745 	mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6746 	vtime = dtrace_vtime_references != 0;
6747 
6748 	if (vtime && curthread->t_dtrace_start)
6749 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6750 
6751 	mstate.dtms_difo = NULL;
6752 	mstate.dtms_probe = probe;
6753 	mstate.dtms_strtok = NULL;
6754 	mstate.dtms_arg[0] = arg0;
6755 	mstate.dtms_arg[1] = arg1;
6756 	mstate.dtms_arg[2] = arg2;
6757 	mstate.dtms_arg[3] = arg3;
6758 	mstate.dtms_arg[4] = arg4;
6759 
6760 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6761 
6762 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6763 		dtrace_predicate_t *pred = ecb->dte_predicate;
6764 		dtrace_state_t *state = ecb->dte_state;
6765 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6766 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6767 		dtrace_vstate_t *vstate = &state->dts_vstate;
6768 		dtrace_provider_t *prov = probe->dtpr_provider;
6769 		uint64_t tracememsize = 0;
6770 		int committed = 0;
6771 		caddr_t tomax;
6772 
6773 		/*
6774 		 * A little subtlety with the following (seemingly innocuous)
6775 		 * declaration of the automatic 'val':  by looking at the
6776 		 * code, you might think that it could be declared in the
6777 		 * action processing loop, below.  (That is, it's only used in
6778 		 * the action processing loop.)  However, it must be declared
6779 		 * out of that scope because in the case of DIF expression
6780 		 * arguments to aggregating actions, one iteration of the
6781 		 * action loop will use the last iteration's value.
6782 		 */
6783 #ifdef lint
6784 		uint64_t val = 0;
6785 #else
6786 		uint64_t val;
6787 #endif
6788 
6789 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6790 		mstate.dtms_access = DTRACE_ACCESS_ARGS | DTRACE_ACCESS_PROC;
6791 		mstate.dtms_getf = NULL;
6792 
6793 		*flags &= ~CPU_DTRACE_ERROR;
6794 
6795 		if (prov == dtrace_provider) {
6796 			/*
6797 			 * If dtrace itself is the provider of this probe,
6798 			 * we're only going to continue processing the ECB if
6799 			 * arg0 (the dtrace_state_t) is equal to the ECB's
6800 			 * creating state.  (This prevents disjoint consumers
6801 			 * from seeing one another's metaprobes.)
6802 			 */
6803 			if (arg0 != (uint64_t)(uintptr_t)state)
6804 				continue;
6805 		}
6806 
6807 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6808 			/*
6809 			 * We're not currently active.  If our provider isn't
6810 			 * the dtrace pseudo provider, we're not interested.
6811 			 */
6812 			if (prov != dtrace_provider)
6813 				continue;
6814 
6815 			/*
6816 			 * Now we must further check if we are in the BEGIN
6817 			 * probe.  If we are, we will only continue processing
6818 			 * if we're still in WARMUP -- if one BEGIN enabling
6819 			 * has invoked the exit() action, we don't want to
6820 			 * evaluate subsequent BEGIN enablings.
6821 			 */
6822 			if (probe->dtpr_id == dtrace_probeid_begin &&
6823 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6824 				ASSERT(state->dts_activity ==
6825 				    DTRACE_ACTIVITY_DRAINING);
6826 				continue;
6827 			}
6828 		}
6829 
6830 		if (ecb->dte_cond && !dtrace_priv_probe(state, &mstate, ecb))
6831 			continue;
6832 
6833 		if (now - state->dts_alive > dtrace_deadman_timeout) {
6834 			/*
6835 			 * We seem to be dead.  Unless we (a) have kernel
6836 			 * destructive permissions (b) have explicitly enabled
6837 			 * destructive actions and (c) destructive actions have
6838 			 * not been disabled, we're going to transition into
6839 			 * the KILLED state, from which no further processing
6840 			 * on this state will be performed.
6841 			 */
6842 			if (!dtrace_priv_kernel_destructive(state) ||
6843 			    !state->dts_cred.dcr_destructive ||
6844 			    dtrace_destructive_disallow) {
6845 				void *activity = &state->dts_activity;
6846 				dtrace_activity_t current;
6847 
6848 				do {
6849 					current = state->dts_activity;
6850 				} while (dtrace_cas32(activity, current,
6851 				    DTRACE_ACTIVITY_KILLED) != current);
6852 
6853 				continue;
6854 			}
6855 		}
6856 
6857 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6858 		    ecb->dte_alignment, state, &mstate)) < 0)
6859 			continue;
6860 
6861 		tomax = buf->dtb_tomax;
6862 		ASSERT(tomax != NULL);
6863 
6864 		if (ecb->dte_size != 0) {
6865 			dtrace_rechdr_t dtrh;
6866 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6867 				mstate.dtms_timestamp = dtrace_gethrtime();
6868 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6869 			}
6870 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
6871 			dtrh.dtrh_epid = ecb->dte_epid;
6872 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
6873 			    mstate.dtms_timestamp);
6874 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
6875 		}
6876 
6877 		mstate.dtms_epid = ecb->dte_epid;
6878 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
6879 
6880 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6881 			mstate.dtms_access |= DTRACE_ACCESS_KERNEL;
6882 
6883 		if (pred != NULL) {
6884 			dtrace_difo_t *dp = pred->dtp_difo;
6885 			int rval;
6886 
6887 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6888 
6889 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6890 				dtrace_cacheid_t cid = probe->dtpr_predcache;
6891 
6892 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
6893 					/*
6894 					 * Update the predicate cache...
6895 					 */
6896 					ASSERT(cid == pred->dtp_cacheid);
6897 					curthread->t_predcache = cid;
6898 				}
6899 
6900 				continue;
6901 			}
6902 		}
6903 
6904 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6905 		    act != NULL; act = act->dta_next) {
6906 			size_t valoffs;
6907 			dtrace_difo_t *dp;
6908 			dtrace_recdesc_t *rec = &act->dta_rec;
6909 
6910 			size = rec->dtrd_size;
6911 			valoffs = offs + rec->dtrd_offset;
6912 
6913 			if (DTRACEACT_ISAGG(act->dta_kind)) {
6914 				uint64_t v = 0xbad;
6915 				dtrace_aggregation_t *agg;
6916 
6917 				agg = (dtrace_aggregation_t *)act;
6918 
6919 				if ((dp = act->dta_difo) != NULL)
6920 					v = dtrace_dif_emulate(dp,
6921 					    &mstate, vstate, state);
6922 
6923 				if (*flags & CPU_DTRACE_ERROR)
6924 					continue;
6925 
6926 				/*
6927 				 * Note that we always pass the expression
6928 				 * value from the previous iteration of the
6929 				 * action loop.  This value will only be used
6930 				 * if there is an expression argument to the
6931 				 * aggregating action, denoted by the
6932 				 * dtag_hasarg field.
6933 				 */
6934 				dtrace_aggregate(agg, buf,
6935 				    offs, aggbuf, v, val);
6936 				continue;
6937 			}
6938 
6939 			switch (act->dta_kind) {
6940 			case DTRACEACT_STOP:
6941 				if (dtrace_priv_proc_destructive(state,
6942 				    &mstate))
6943 					dtrace_action_stop();
6944 				continue;
6945 
6946 			case DTRACEACT_BREAKPOINT:
6947 				if (dtrace_priv_kernel_destructive(state))
6948 					dtrace_action_breakpoint(ecb);
6949 				continue;
6950 
6951 			case DTRACEACT_PANIC:
6952 				if (dtrace_priv_kernel_destructive(state))
6953 					dtrace_action_panic(ecb);
6954 				continue;
6955 
6956 			case DTRACEACT_STACK:
6957 				if (!dtrace_priv_kernel(state))
6958 					continue;
6959 
6960 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
6961 				    size / sizeof (pc_t), probe->dtpr_aframes,
6962 				    DTRACE_ANCHORED(probe) ? NULL :
6963 				    (uint32_t *)arg0);
6964 
6965 				continue;
6966 
6967 			case DTRACEACT_JSTACK:
6968 			case DTRACEACT_USTACK:
6969 				if (!dtrace_priv_proc(state, &mstate))
6970 					continue;
6971 
6972 				/*
6973 				 * See comment in DIF_VAR_PID.
6974 				 */
6975 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6976 				    CPU_ON_INTR(CPU)) {
6977 					int depth = DTRACE_USTACK_NFRAMES(
6978 					    rec->dtrd_arg) + 1;
6979 
6980 					dtrace_bzero((void *)(tomax + valoffs),
6981 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6982 					    + depth * sizeof (uint64_t));
6983 
6984 					continue;
6985 				}
6986 
6987 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6988 				    curproc->p_dtrace_helpers != NULL) {
6989 					/*
6990 					 * This is the slow path -- we have
6991 					 * allocated string space, and we're
6992 					 * getting the stack of a process that
6993 					 * has helpers.  Call into a separate
6994 					 * routine to perform this processing.
6995 					 */
6996 					dtrace_action_ustack(&mstate, state,
6997 					    (uint64_t *)(tomax + valoffs),
6998 					    rec->dtrd_arg);
6999 					continue;
7000 				}
7001 
7002 				/*
7003 				 * Clear the string space, since there's no
7004 				 * helper to do it for us.
7005 				 */
7006 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0) {
7007 					int depth = DTRACE_USTACK_NFRAMES(
7008 					    rec->dtrd_arg);
7009 					size_t strsize = DTRACE_USTACK_STRSIZE(
7010 					    rec->dtrd_arg);
7011 					uint64_t *buf = (uint64_t *)(tomax +
7012 					    valoffs);
7013 					void *strspace = &buf[depth + 1];
7014 
7015 					dtrace_bzero(strspace,
7016 					    MIN(depth, strsize));
7017 				}
7018 
7019 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7020 				dtrace_getupcstack((uint64_t *)
7021 				    (tomax + valoffs),
7022 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7023 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7024 				continue;
7025 
7026 			default:
7027 				break;
7028 			}
7029 
7030 			dp = act->dta_difo;
7031 			ASSERT(dp != NULL);
7032 
7033 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7034 
7035 			if (*flags & CPU_DTRACE_ERROR)
7036 				continue;
7037 
7038 			switch (act->dta_kind) {
7039 			case DTRACEACT_SPECULATE: {
7040 				dtrace_rechdr_t *dtrh;
7041 
7042 				ASSERT(buf == &state->dts_buffer[cpuid]);
7043 				buf = dtrace_speculation_buffer(state,
7044 				    cpuid, val);
7045 
7046 				if (buf == NULL) {
7047 					*flags |= CPU_DTRACE_DROP;
7048 					continue;
7049 				}
7050 
7051 				offs = dtrace_buffer_reserve(buf,
7052 				    ecb->dte_needed, ecb->dte_alignment,
7053 				    state, NULL);
7054 
7055 				if (offs < 0) {
7056 					*flags |= CPU_DTRACE_DROP;
7057 					continue;
7058 				}
7059 
7060 				tomax = buf->dtb_tomax;
7061 				ASSERT(tomax != NULL);
7062 
7063 				if (ecb->dte_size == 0)
7064 					continue;
7065 
7066 				ASSERT3U(ecb->dte_size, >=,
7067 				    sizeof (dtrace_rechdr_t));
7068 				dtrh = ((void *)(tomax + offs));
7069 				dtrh->dtrh_epid = ecb->dte_epid;
7070 				/*
7071 				 * When the speculation is committed, all of
7072 				 * the records in the speculative buffer will
7073 				 * have their timestamps set to the commit
7074 				 * time.  Until then, it is set to a sentinel
7075 				 * value, for debugability.
7076 				 */
7077 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7078 				continue;
7079 			}
7080 
7081 			case DTRACEACT_CHILL:
7082 				if (dtrace_priv_kernel_destructive(state))
7083 					dtrace_action_chill(&mstate, val);
7084 				continue;
7085 
7086 			case DTRACEACT_RAISE:
7087 				if (dtrace_priv_proc_destructive(state,
7088 				    &mstate))
7089 					dtrace_action_raise(val);
7090 				continue;
7091 
7092 			case DTRACEACT_COMMIT:
7093 				ASSERT(!committed);
7094 
7095 				/*
7096 				 * We need to commit our buffer state.
7097 				 */
7098 				if (ecb->dte_size)
7099 					buf->dtb_offset = offs + ecb->dte_size;
7100 				buf = &state->dts_buffer[cpuid];
7101 				dtrace_speculation_commit(state, cpuid, val);
7102 				committed = 1;
7103 				continue;
7104 
7105 			case DTRACEACT_DISCARD:
7106 				dtrace_speculation_discard(state, cpuid, val);
7107 				continue;
7108 
7109 			case DTRACEACT_DIFEXPR:
7110 			case DTRACEACT_LIBACT:
7111 			case DTRACEACT_PRINTF:
7112 			case DTRACEACT_PRINTA:
7113 			case DTRACEACT_SYSTEM:
7114 			case DTRACEACT_FREOPEN:
7115 			case DTRACEACT_TRACEMEM:
7116 				break;
7117 
7118 			case DTRACEACT_TRACEMEM_DYNSIZE:
7119 				tracememsize = val;
7120 				break;
7121 
7122 			case DTRACEACT_SYM:
7123 			case DTRACEACT_MOD:
7124 				if (!dtrace_priv_kernel(state))
7125 					continue;
7126 				break;
7127 
7128 			case DTRACEACT_USYM:
7129 			case DTRACEACT_UMOD:
7130 			case DTRACEACT_UADDR: {
7131 				struct pid *pid = curthread->t_procp->p_pidp;
7132 
7133 				if (!dtrace_priv_proc(state, &mstate))
7134 					continue;
7135 
7136 				DTRACE_STORE(uint64_t, tomax,
7137 				    valoffs, (uint64_t)pid->pid_id);
7138 				DTRACE_STORE(uint64_t, tomax,
7139 				    valoffs + sizeof (uint64_t), val);
7140 
7141 				continue;
7142 			}
7143 
7144 			case DTRACEACT_EXIT: {
7145 				/*
7146 				 * For the exit action, we are going to attempt
7147 				 * to atomically set our activity to be
7148 				 * draining.  If this fails (either because
7149 				 * another CPU has beat us to the exit action,
7150 				 * or because our current activity is something
7151 				 * other than ACTIVE or WARMUP), we will
7152 				 * continue.  This assures that the exit action
7153 				 * can be successfully recorded at most once
7154 				 * when we're in the ACTIVE state.  If we're
7155 				 * encountering the exit() action while in
7156 				 * COOLDOWN, however, we want to honor the new
7157 				 * status code.  (We know that we're the only
7158 				 * thread in COOLDOWN, so there is no race.)
7159 				 */
7160 				void *activity = &state->dts_activity;
7161 				dtrace_activity_t current = state->dts_activity;
7162 
7163 				if (current == DTRACE_ACTIVITY_COOLDOWN)
7164 					break;
7165 
7166 				if (current != DTRACE_ACTIVITY_WARMUP)
7167 					current = DTRACE_ACTIVITY_ACTIVE;
7168 
7169 				if (dtrace_cas32(activity, current,
7170 				    DTRACE_ACTIVITY_DRAINING) != current) {
7171 					*flags |= CPU_DTRACE_DROP;
7172 					continue;
7173 				}
7174 
7175 				break;
7176 			}
7177 
7178 			default:
7179 				ASSERT(0);
7180 			}
7181 
7182 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7183 			    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7184 				uintptr_t end = valoffs + size;
7185 
7186 				if (tracememsize != 0 &&
7187 				    valoffs + tracememsize < end) {
7188 					end = valoffs + tracememsize;
7189 					tracememsize = 0;
7190 				}
7191 
7192 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7193 				    !dtrace_vcanload((void *)(uintptr_t)val,
7194 				    &dp->dtdo_rtype, &mstate, vstate))
7195 					continue;
7196 
7197 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7198 				    &val, end, act->dta_intuple,
7199 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7200 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7201 				continue;
7202 			}
7203 
7204 			switch (size) {
7205 			case 0:
7206 				break;
7207 
7208 			case sizeof (uint8_t):
7209 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7210 				break;
7211 			case sizeof (uint16_t):
7212 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7213 				break;
7214 			case sizeof (uint32_t):
7215 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7216 				break;
7217 			case sizeof (uint64_t):
7218 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7219 				break;
7220 			default:
7221 				/*
7222 				 * Any other size should have been returned by
7223 				 * reference, not by value.
7224 				 */
7225 				ASSERT(0);
7226 				break;
7227 			}
7228 		}
7229 
7230 		if (*flags & CPU_DTRACE_DROP)
7231 			continue;
7232 
7233 		if (*flags & CPU_DTRACE_FAULT) {
7234 			int ndx;
7235 			dtrace_action_t *err;
7236 
7237 			buf->dtb_errors++;
7238 
7239 			if (probe->dtpr_id == dtrace_probeid_error) {
7240 				/*
7241 				 * There's nothing we can do -- we had an
7242 				 * error on the error probe.  We bump an
7243 				 * error counter to at least indicate that
7244 				 * this condition happened.
7245 				 */
7246 				dtrace_error(&state->dts_dblerrors);
7247 				continue;
7248 			}
7249 
7250 			if (vtime) {
7251 				/*
7252 				 * Before recursing on dtrace_probe(), we
7253 				 * need to explicitly clear out our start
7254 				 * time to prevent it from being accumulated
7255 				 * into t_dtrace_vtime.
7256 				 */
7257 				curthread->t_dtrace_start = 0;
7258 			}
7259 
7260 			/*
7261 			 * Iterate over the actions to figure out which action
7262 			 * we were processing when we experienced the error.
7263 			 * Note that act points _past_ the faulting action; if
7264 			 * act is ecb->dte_action, the fault was in the
7265 			 * predicate, if it's ecb->dte_action->dta_next it's
7266 			 * in action #1, and so on.
7267 			 */
7268 			for (err = ecb->dte_action, ndx = 0;
7269 			    err != act; err = err->dta_next, ndx++)
7270 				continue;
7271 
7272 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7273 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7274 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7275 			    cpu_core[cpuid].cpuc_dtrace_illval);
7276 
7277 			continue;
7278 		}
7279 
7280 		if (!committed)
7281 			buf->dtb_offset = offs + ecb->dte_size;
7282 	}
7283 
7284 	end = dtrace_gethrtime();
7285 	if (vtime)
7286 		curthread->t_dtrace_start = end;
7287 
7288 	CPU->cpu_dtrace_nsec += end - now;
7289 
7290 	dtrace_interrupt_enable(cookie);
7291 }
7292 
7293 /*
7294  * DTrace Probe Hashing Functions
7295  *
7296  * The functions in this section (and indeed, the functions in remaining
7297  * sections) are not _called_ from probe context.  (Any exceptions to this are
7298  * marked with a "Note:".)  Rather, they are called from elsewhere in the
7299  * DTrace framework to look-up probes in, add probes to and remove probes from
7300  * the DTrace probe hashes.  (Each probe is hashed by each element of the
7301  * probe tuple -- allowing for fast lookups, regardless of what was
7302  * specified.)
7303  */
7304 static uint_t
7305 dtrace_hash_str(char *p)
7306 {
7307 	unsigned int g;
7308 	uint_t hval = 0;
7309 
7310 	while (*p) {
7311 		hval = (hval << 4) + *p++;
7312 		if ((g = (hval & 0xf0000000)) != 0)
7313 			hval ^= g >> 24;
7314 		hval &= ~g;
7315 	}
7316 	return (hval);
7317 }
7318 
7319 static dtrace_hash_t *
7320 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7321 {
7322 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7323 
7324 	hash->dth_stroffs = stroffs;
7325 	hash->dth_nextoffs = nextoffs;
7326 	hash->dth_prevoffs = prevoffs;
7327 
7328 	hash->dth_size = 1;
7329 	hash->dth_mask = hash->dth_size - 1;
7330 
7331 	hash->dth_tab = kmem_zalloc(hash->dth_size *
7332 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7333 
7334 	return (hash);
7335 }
7336 
7337 static void
7338 dtrace_hash_destroy(dtrace_hash_t *hash)
7339 {
7340 #ifdef DEBUG
7341 	int i;
7342 
7343 	for (i = 0; i < hash->dth_size; i++)
7344 		ASSERT(hash->dth_tab[i] == NULL);
7345 #endif
7346 
7347 	kmem_free(hash->dth_tab,
7348 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
7349 	kmem_free(hash, sizeof (dtrace_hash_t));
7350 }
7351 
7352 static void
7353 dtrace_hash_resize(dtrace_hash_t *hash)
7354 {
7355 	int size = hash->dth_size, i, ndx;
7356 	int new_size = hash->dth_size << 1;
7357 	int new_mask = new_size - 1;
7358 	dtrace_hashbucket_t **new_tab, *bucket, *next;
7359 
7360 	ASSERT((new_size & new_mask) == 0);
7361 
7362 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7363 
7364 	for (i = 0; i < size; i++) {
7365 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7366 			dtrace_probe_t *probe = bucket->dthb_chain;
7367 
7368 			ASSERT(probe != NULL);
7369 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7370 
7371 			next = bucket->dthb_next;
7372 			bucket->dthb_next = new_tab[ndx];
7373 			new_tab[ndx] = bucket;
7374 		}
7375 	}
7376 
7377 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7378 	hash->dth_tab = new_tab;
7379 	hash->dth_size = new_size;
7380 	hash->dth_mask = new_mask;
7381 }
7382 
7383 static void
7384 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7385 {
7386 	int hashval = DTRACE_HASHSTR(hash, new);
7387 	int ndx = hashval & hash->dth_mask;
7388 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7389 	dtrace_probe_t **nextp, **prevp;
7390 
7391 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7392 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7393 			goto add;
7394 	}
7395 
7396 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7397 		dtrace_hash_resize(hash);
7398 		dtrace_hash_add(hash, new);
7399 		return;
7400 	}
7401 
7402 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7403 	bucket->dthb_next = hash->dth_tab[ndx];
7404 	hash->dth_tab[ndx] = bucket;
7405 	hash->dth_nbuckets++;
7406 
7407 add:
7408 	nextp = DTRACE_HASHNEXT(hash, new);
7409 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7410 	*nextp = bucket->dthb_chain;
7411 
7412 	if (bucket->dthb_chain != NULL) {
7413 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7414 		ASSERT(*prevp == NULL);
7415 		*prevp = new;
7416 	}
7417 
7418 	bucket->dthb_chain = new;
7419 	bucket->dthb_len++;
7420 }
7421 
7422 static dtrace_probe_t *
7423 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7424 {
7425 	int hashval = DTRACE_HASHSTR(hash, template);
7426 	int ndx = hashval & hash->dth_mask;
7427 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7428 
7429 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7430 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7431 			return (bucket->dthb_chain);
7432 	}
7433 
7434 	return (NULL);
7435 }
7436 
7437 static int
7438 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7439 {
7440 	int hashval = DTRACE_HASHSTR(hash, template);
7441 	int ndx = hashval & hash->dth_mask;
7442 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7443 
7444 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7445 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7446 			return (bucket->dthb_len);
7447 	}
7448 
7449 	return (NULL);
7450 }
7451 
7452 static void
7453 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7454 {
7455 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7456 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7457 
7458 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7459 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7460 
7461 	/*
7462 	 * Find the bucket that we're removing this probe from.
7463 	 */
7464 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7465 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7466 			break;
7467 	}
7468 
7469 	ASSERT(bucket != NULL);
7470 
7471 	if (*prevp == NULL) {
7472 		if (*nextp == NULL) {
7473 			/*
7474 			 * The removed probe was the only probe on this
7475 			 * bucket; we need to remove the bucket.
7476 			 */
7477 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7478 
7479 			ASSERT(bucket->dthb_chain == probe);
7480 			ASSERT(b != NULL);
7481 
7482 			if (b == bucket) {
7483 				hash->dth_tab[ndx] = bucket->dthb_next;
7484 			} else {
7485 				while (b->dthb_next != bucket)
7486 					b = b->dthb_next;
7487 				b->dthb_next = bucket->dthb_next;
7488 			}
7489 
7490 			ASSERT(hash->dth_nbuckets > 0);
7491 			hash->dth_nbuckets--;
7492 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7493 			return;
7494 		}
7495 
7496 		bucket->dthb_chain = *nextp;
7497 	} else {
7498 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7499 	}
7500 
7501 	if (*nextp != NULL)
7502 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7503 }
7504 
7505 /*
7506  * DTrace Utility Functions
7507  *
7508  * These are random utility functions that are _not_ called from probe context.
7509  */
7510 static int
7511 dtrace_badattr(const dtrace_attribute_t *a)
7512 {
7513 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
7514 	    a->dtat_data > DTRACE_STABILITY_MAX ||
7515 	    a->dtat_class > DTRACE_CLASS_MAX);
7516 }
7517 
7518 /*
7519  * Return a duplicate copy of a string.  If the specified string is NULL,
7520  * this function returns a zero-length string.
7521  */
7522 static char *
7523 dtrace_strdup(const char *str)
7524 {
7525 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7526 
7527 	if (str != NULL)
7528 		(void) strcpy(new, str);
7529 
7530 	return (new);
7531 }
7532 
7533 #define	DTRACE_ISALPHA(c)	\
7534 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7535 
7536 static int
7537 dtrace_badname(const char *s)
7538 {
7539 	char c;
7540 
7541 	if (s == NULL || (c = *s++) == '\0')
7542 		return (0);
7543 
7544 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7545 		return (1);
7546 
7547 	while ((c = *s++) != '\0') {
7548 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7549 		    c != '-' && c != '_' && c != '.' && c != '`')
7550 			return (1);
7551 	}
7552 
7553 	return (0);
7554 }
7555 
7556 static void
7557 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7558 {
7559 	uint32_t priv;
7560 
7561 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7562 		/*
7563 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7564 		 */
7565 		priv = DTRACE_PRIV_ALL;
7566 	} else {
7567 		*uidp = crgetuid(cr);
7568 		*zoneidp = crgetzoneid(cr);
7569 
7570 		priv = 0;
7571 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7572 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7573 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7574 			priv |= DTRACE_PRIV_USER;
7575 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7576 			priv |= DTRACE_PRIV_PROC;
7577 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7578 			priv |= DTRACE_PRIV_OWNER;
7579 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7580 			priv |= DTRACE_PRIV_ZONEOWNER;
7581 	}
7582 
7583 	*privp = priv;
7584 }
7585 
7586 #ifdef DTRACE_ERRDEBUG
7587 static void
7588 dtrace_errdebug(const char *str)
7589 {
7590 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
7591 	int occupied = 0;
7592 
7593 	mutex_enter(&dtrace_errlock);
7594 	dtrace_errlast = str;
7595 	dtrace_errthread = curthread;
7596 
7597 	while (occupied++ < DTRACE_ERRHASHSZ) {
7598 		if (dtrace_errhash[hval].dter_msg == str) {
7599 			dtrace_errhash[hval].dter_count++;
7600 			goto out;
7601 		}
7602 
7603 		if (dtrace_errhash[hval].dter_msg != NULL) {
7604 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
7605 			continue;
7606 		}
7607 
7608 		dtrace_errhash[hval].dter_msg = str;
7609 		dtrace_errhash[hval].dter_count = 1;
7610 		goto out;
7611 	}
7612 
7613 	panic("dtrace: undersized error hash");
7614 out:
7615 	mutex_exit(&dtrace_errlock);
7616 }
7617 #endif
7618 
7619 /*
7620  * DTrace Matching Functions
7621  *
7622  * These functions are used to match groups of probes, given some elements of
7623  * a probe tuple, or some globbed expressions for elements of a probe tuple.
7624  */
7625 static int
7626 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7627     zoneid_t zoneid)
7628 {
7629 	if (priv != DTRACE_PRIV_ALL) {
7630 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7631 		uint32_t match = priv & ppriv;
7632 
7633 		/*
7634 		 * No PRIV_DTRACE_* privileges...
7635 		 */
7636 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7637 		    DTRACE_PRIV_KERNEL)) == 0)
7638 			return (0);
7639 
7640 		/*
7641 		 * No matching bits, but there were bits to match...
7642 		 */
7643 		if (match == 0 && ppriv != 0)
7644 			return (0);
7645 
7646 		/*
7647 		 * Need to have permissions to the process, but don't...
7648 		 */
7649 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7650 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7651 			return (0);
7652 		}
7653 
7654 		/*
7655 		 * Need to be in the same zone unless we possess the
7656 		 * privilege to examine all zones.
7657 		 */
7658 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7659 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7660 			return (0);
7661 		}
7662 	}
7663 
7664 	return (1);
7665 }
7666 
7667 /*
7668  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7669  * consists of input pattern strings and an ops-vector to evaluate them.
7670  * This function returns >0 for match, 0 for no match, and <0 for error.
7671  */
7672 static int
7673 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7674     uint32_t priv, uid_t uid, zoneid_t zoneid)
7675 {
7676 	dtrace_provider_t *pvp = prp->dtpr_provider;
7677 	int rv;
7678 
7679 	if (pvp->dtpv_defunct)
7680 		return (0);
7681 
7682 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7683 		return (rv);
7684 
7685 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7686 		return (rv);
7687 
7688 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7689 		return (rv);
7690 
7691 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7692 		return (rv);
7693 
7694 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7695 		return (0);
7696 
7697 	return (rv);
7698 }
7699 
7700 /*
7701  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7702  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
7703  * libc's version, the kernel version only applies to 8-bit ASCII strings.
7704  * In addition, all of the recursion cases except for '*' matching have been
7705  * unwound.  For '*', we still implement recursive evaluation, but a depth
7706  * counter is maintained and matching is aborted if we recurse too deep.
7707  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7708  */
7709 static int
7710 dtrace_match_glob(const char *s, const char *p, int depth)
7711 {
7712 	const char *olds;
7713 	char s1, c;
7714 	int gs;
7715 
7716 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7717 		return (-1);
7718 
7719 	if (s == NULL)
7720 		s = ""; /* treat NULL as empty string */
7721 
7722 top:
7723 	olds = s;
7724 	s1 = *s++;
7725 
7726 	if (p == NULL)
7727 		return (0);
7728 
7729 	if ((c = *p++) == '\0')
7730 		return (s1 == '\0');
7731 
7732 	switch (c) {
7733 	case '[': {
7734 		int ok = 0, notflag = 0;
7735 		char lc = '\0';
7736 
7737 		if (s1 == '\0')
7738 			return (0);
7739 
7740 		if (*p == '!') {
7741 			notflag = 1;
7742 			p++;
7743 		}
7744 
7745 		if ((c = *p++) == '\0')
7746 			return (0);
7747 
7748 		do {
7749 			if (c == '-' && lc != '\0' && *p != ']') {
7750 				if ((c = *p++) == '\0')
7751 					return (0);
7752 				if (c == '\\' && (c = *p++) == '\0')
7753 					return (0);
7754 
7755 				if (notflag) {
7756 					if (s1 < lc || s1 > c)
7757 						ok++;
7758 					else
7759 						return (0);
7760 				} else if (lc <= s1 && s1 <= c)
7761 					ok++;
7762 
7763 			} else if (c == '\\' && (c = *p++) == '\0')
7764 				return (0);
7765 
7766 			lc = c; /* save left-hand 'c' for next iteration */
7767 
7768 			if (notflag) {
7769 				if (s1 != c)
7770 					ok++;
7771 				else
7772 					return (0);
7773 			} else if (s1 == c)
7774 				ok++;
7775 
7776 			if ((c = *p++) == '\0')
7777 				return (0);
7778 
7779 		} while (c != ']');
7780 
7781 		if (ok)
7782 			goto top;
7783 
7784 		return (0);
7785 	}
7786 
7787 	case '\\':
7788 		if ((c = *p++) == '\0')
7789 			return (0);
7790 		/*FALLTHRU*/
7791 
7792 	default:
7793 		if (c != s1)
7794 			return (0);
7795 		/*FALLTHRU*/
7796 
7797 	case '?':
7798 		if (s1 != '\0')
7799 			goto top;
7800 		return (0);
7801 
7802 	case '*':
7803 		while (*p == '*')
7804 			p++; /* consecutive *'s are identical to a single one */
7805 
7806 		if (*p == '\0')
7807 			return (1);
7808 
7809 		for (s = olds; *s != '\0'; s++) {
7810 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7811 				return (gs);
7812 		}
7813 
7814 		return (0);
7815 	}
7816 }
7817 
7818 /*ARGSUSED*/
7819 static int
7820 dtrace_match_string(const char *s, const char *p, int depth)
7821 {
7822 	return (s != NULL && strcmp(s, p) == 0);
7823 }
7824 
7825 /*ARGSUSED*/
7826 static int
7827 dtrace_match_nul(const char *s, const char *p, int depth)
7828 {
7829 	return (1); /* always match the empty pattern */
7830 }
7831 
7832 /*ARGSUSED*/
7833 static int
7834 dtrace_match_nonzero(const char *s, const char *p, int depth)
7835 {
7836 	return (s != NULL && s[0] != '\0');
7837 }
7838 
7839 static int
7840 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7841     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7842 {
7843 	dtrace_probe_t template, *probe;
7844 	dtrace_hash_t *hash = NULL;
7845 	int len, rc, best = INT_MAX, nmatched = 0;
7846 	dtrace_id_t i;
7847 
7848 	ASSERT(MUTEX_HELD(&dtrace_lock));
7849 
7850 	/*
7851 	 * If the probe ID is specified in the key, just lookup by ID and
7852 	 * invoke the match callback once if a matching probe is found.
7853 	 */
7854 	if (pkp->dtpk_id != DTRACE_IDNONE) {
7855 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7856 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7857 			if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
7858 				return (DTRACE_MATCH_FAIL);
7859 			nmatched++;
7860 		}
7861 		return (nmatched);
7862 	}
7863 
7864 	template.dtpr_mod = (char *)pkp->dtpk_mod;
7865 	template.dtpr_func = (char *)pkp->dtpk_func;
7866 	template.dtpr_name = (char *)pkp->dtpk_name;
7867 
7868 	/*
7869 	 * We want to find the most distinct of the module name, function
7870 	 * name, and name.  So for each one that is not a glob pattern or
7871 	 * empty string, we perform a lookup in the corresponding hash and
7872 	 * use the hash table with the fewest collisions to do our search.
7873 	 */
7874 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
7875 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7876 		best = len;
7877 		hash = dtrace_bymod;
7878 	}
7879 
7880 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
7881 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7882 		best = len;
7883 		hash = dtrace_byfunc;
7884 	}
7885 
7886 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
7887 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7888 		best = len;
7889 		hash = dtrace_byname;
7890 	}
7891 
7892 	/*
7893 	 * If we did not select a hash table, iterate over every probe and
7894 	 * invoke our callback for each one that matches our input probe key.
7895 	 */
7896 	if (hash == NULL) {
7897 		for (i = 0; i < dtrace_nprobes; i++) {
7898 			if ((probe = dtrace_probes[i]) == NULL ||
7899 			    dtrace_match_probe(probe, pkp, priv, uid,
7900 			    zoneid) <= 0)
7901 				continue;
7902 
7903 			nmatched++;
7904 
7905 			if ((rc = (*matched)(probe, arg)) !=
7906 			    DTRACE_MATCH_NEXT) {
7907 				if (rc == DTRACE_MATCH_FAIL)
7908 					return (DTRACE_MATCH_FAIL);
7909 				break;
7910 			}
7911 		}
7912 
7913 		return (nmatched);
7914 	}
7915 
7916 	/*
7917 	 * If we selected a hash table, iterate over each probe of the same key
7918 	 * name and invoke the callback for every probe that matches the other
7919 	 * attributes of our input probe key.
7920 	 */
7921 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7922 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
7923 
7924 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7925 			continue;
7926 
7927 		nmatched++;
7928 
7929 		if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7930 			if (rc == DTRACE_MATCH_FAIL)
7931 				return (DTRACE_MATCH_FAIL);
7932 			break;
7933 		}
7934 	}
7935 
7936 	return (nmatched);
7937 }
7938 
7939 /*
7940  * Return the function pointer dtrace_probecmp() should use to compare the
7941  * specified pattern with a string.  For NULL or empty patterns, we select
7942  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
7943  * For non-empty non-glob strings, we use dtrace_match_string().
7944  */
7945 static dtrace_probekey_f *
7946 dtrace_probekey_func(const char *p)
7947 {
7948 	char c;
7949 
7950 	if (p == NULL || *p == '\0')
7951 		return (&dtrace_match_nul);
7952 
7953 	while ((c = *p++) != '\0') {
7954 		if (c == '[' || c == '?' || c == '*' || c == '\\')
7955 			return (&dtrace_match_glob);
7956 	}
7957 
7958 	return (&dtrace_match_string);
7959 }
7960 
7961 /*
7962  * Build a probe comparison key for use with dtrace_match_probe() from the
7963  * given probe description.  By convention, a null key only matches anchored
7964  * probes: if each field is the empty string, reset dtpk_fmatch to
7965  * dtrace_match_nonzero().
7966  */
7967 static void
7968 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7969 {
7970 	pkp->dtpk_prov = pdp->dtpd_provider;
7971 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7972 
7973 	pkp->dtpk_mod = pdp->dtpd_mod;
7974 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7975 
7976 	pkp->dtpk_func = pdp->dtpd_func;
7977 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7978 
7979 	pkp->dtpk_name = pdp->dtpd_name;
7980 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7981 
7982 	pkp->dtpk_id = pdp->dtpd_id;
7983 
7984 	if (pkp->dtpk_id == DTRACE_IDNONE &&
7985 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
7986 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
7987 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
7988 	    pkp->dtpk_nmatch == &dtrace_match_nul)
7989 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
7990 }
7991 
7992 /*
7993  * DTrace Provider-to-Framework API Functions
7994  *
7995  * These functions implement much of the Provider-to-Framework API, as
7996  * described in <sys/dtrace.h>.  The parts of the API not in this section are
7997  * the functions in the API for probe management (found below), and
7998  * dtrace_probe() itself (found above).
7999  */
8000 
8001 /*
8002  * Register the calling provider with the DTrace framework.  This should
8003  * generally be called by DTrace providers in their attach(9E) entry point.
8004  */
8005 int
8006 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8007     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8008 {
8009 	dtrace_provider_t *provider;
8010 
8011 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8012 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8013 		    "arguments", name ? name : "<NULL>");
8014 		return (EINVAL);
8015 	}
8016 
8017 	if (name[0] == '\0' || dtrace_badname(name)) {
8018 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8019 		    "provider name", name);
8020 		return (EINVAL);
8021 	}
8022 
8023 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8024 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8025 	    pops->dtps_destroy == NULL ||
8026 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8027 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8028 		    "provider ops", name);
8029 		return (EINVAL);
8030 	}
8031 
8032 	if (dtrace_badattr(&pap->dtpa_provider) ||
8033 	    dtrace_badattr(&pap->dtpa_mod) ||
8034 	    dtrace_badattr(&pap->dtpa_func) ||
8035 	    dtrace_badattr(&pap->dtpa_name) ||
8036 	    dtrace_badattr(&pap->dtpa_args)) {
8037 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8038 		    "provider attributes", name);
8039 		return (EINVAL);
8040 	}
8041 
8042 	if (priv & ~DTRACE_PRIV_ALL) {
8043 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8044 		    "privilege attributes", name);
8045 		return (EINVAL);
8046 	}
8047 
8048 	if ((priv & DTRACE_PRIV_KERNEL) &&
8049 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8050 	    pops->dtps_mode == NULL) {
8051 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8052 		    "dtps_mode() op for given privilege attributes", name);
8053 		return (EINVAL);
8054 	}
8055 
8056 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8057 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8058 	(void) strcpy(provider->dtpv_name, name);
8059 
8060 	provider->dtpv_attr = *pap;
8061 	provider->dtpv_priv.dtpp_flags = priv;
8062 	if (cr != NULL) {
8063 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8064 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8065 	}
8066 	provider->dtpv_pops = *pops;
8067 
8068 	if (pops->dtps_provide == NULL) {
8069 		ASSERT(pops->dtps_provide_module != NULL);
8070 		provider->dtpv_pops.dtps_provide =
8071 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
8072 	}
8073 
8074 	if (pops->dtps_provide_module == NULL) {
8075 		ASSERT(pops->dtps_provide != NULL);
8076 		provider->dtpv_pops.dtps_provide_module =
8077 		    (void (*)(void *, struct modctl *))dtrace_nullop;
8078 	}
8079 
8080 	if (pops->dtps_suspend == NULL) {
8081 		ASSERT(pops->dtps_resume == NULL);
8082 		provider->dtpv_pops.dtps_suspend =
8083 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8084 		provider->dtpv_pops.dtps_resume =
8085 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8086 	}
8087 
8088 	provider->dtpv_arg = arg;
8089 	*idp = (dtrace_provider_id_t)provider;
8090 
8091 	if (pops == &dtrace_provider_ops) {
8092 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8093 		ASSERT(MUTEX_HELD(&dtrace_lock));
8094 		ASSERT(dtrace_anon.dta_enabling == NULL);
8095 
8096 		/*
8097 		 * We make sure that the DTrace provider is at the head of
8098 		 * the provider chain.
8099 		 */
8100 		provider->dtpv_next = dtrace_provider;
8101 		dtrace_provider = provider;
8102 		return (0);
8103 	}
8104 
8105 	mutex_enter(&dtrace_provider_lock);
8106 	mutex_enter(&dtrace_lock);
8107 
8108 	/*
8109 	 * If there is at least one provider registered, we'll add this
8110 	 * provider after the first provider.
8111 	 */
8112 	if (dtrace_provider != NULL) {
8113 		provider->dtpv_next = dtrace_provider->dtpv_next;
8114 		dtrace_provider->dtpv_next = provider;
8115 	} else {
8116 		dtrace_provider = provider;
8117 	}
8118 
8119 	if (dtrace_retained != NULL) {
8120 		dtrace_enabling_provide(provider);
8121 
8122 		/*
8123 		 * Now we need to call dtrace_enabling_matchall() -- which
8124 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
8125 		 * to drop all of our locks before calling into it...
8126 		 */
8127 		mutex_exit(&dtrace_lock);
8128 		mutex_exit(&dtrace_provider_lock);
8129 		dtrace_enabling_matchall();
8130 
8131 		return (0);
8132 	}
8133 
8134 	mutex_exit(&dtrace_lock);
8135 	mutex_exit(&dtrace_provider_lock);
8136 
8137 	return (0);
8138 }
8139 
8140 /*
8141  * Unregister the specified provider from the DTrace framework.  This should
8142  * generally be called by DTrace providers in their detach(9E) entry point.
8143  */
8144 int
8145 dtrace_unregister(dtrace_provider_id_t id)
8146 {
8147 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8148 	dtrace_provider_t *prev = NULL;
8149 	int i, self = 0, noreap = 0;
8150 	dtrace_probe_t *probe, *first = NULL;
8151 
8152 	if (old->dtpv_pops.dtps_enable ==
8153 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
8154 		/*
8155 		 * If DTrace itself is the provider, we're called with locks
8156 		 * already held.
8157 		 */
8158 		ASSERT(old == dtrace_provider);
8159 		ASSERT(dtrace_devi != NULL);
8160 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8161 		ASSERT(MUTEX_HELD(&dtrace_lock));
8162 		self = 1;
8163 
8164 		if (dtrace_provider->dtpv_next != NULL) {
8165 			/*
8166 			 * There's another provider here; return failure.
8167 			 */
8168 			return (EBUSY);
8169 		}
8170 	} else {
8171 		mutex_enter(&dtrace_provider_lock);
8172 		mutex_enter(&mod_lock);
8173 		mutex_enter(&dtrace_lock);
8174 	}
8175 
8176 	/*
8177 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8178 	 * probes, we refuse to let providers slither away, unless this
8179 	 * provider has already been explicitly invalidated.
8180 	 */
8181 	if (!old->dtpv_defunct &&
8182 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8183 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8184 		if (!self) {
8185 			mutex_exit(&dtrace_lock);
8186 			mutex_exit(&mod_lock);
8187 			mutex_exit(&dtrace_provider_lock);
8188 		}
8189 		return (EBUSY);
8190 	}
8191 
8192 	/*
8193 	 * Attempt to destroy the probes associated with this provider.
8194 	 */
8195 	for (i = 0; i < dtrace_nprobes; i++) {
8196 		if ((probe = dtrace_probes[i]) == NULL)
8197 			continue;
8198 
8199 		if (probe->dtpr_provider != old)
8200 			continue;
8201 
8202 		if (probe->dtpr_ecb == NULL)
8203 			continue;
8204 
8205 		/*
8206 		 * If we are trying to unregister a defunct provider, and the
8207 		 * provider was made defunct within the interval dictated by
8208 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8209 		 * attempt to reap our enablings.  To denote that the provider
8210 		 * should reattempt to unregister itself at some point in the
8211 		 * future, we will return a differentiable error code (EAGAIN
8212 		 * instead of EBUSY) in this case.
8213 		 */
8214 		if (dtrace_gethrtime() - old->dtpv_defunct >
8215 		    dtrace_unregister_defunct_reap)
8216 			noreap = 1;
8217 
8218 		if (!self) {
8219 			mutex_exit(&dtrace_lock);
8220 			mutex_exit(&mod_lock);
8221 			mutex_exit(&dtrace_provider_lock);
8222 		}
8223 
8224 		if (noreap)
8225 			return (EBUSY);
8226 
8227 		(void) taskq_dispatch(dtrace_taskq,
8228 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8229 
8230 		return (EAGAIN);
8231 	}
8232 
8233 	/*
8234 	 * All of the probes for this provider are disabled; we can safely
8235 	 * remove all of them from their hash chains and from the probe array.
8236 	 */
8237 	for (i = 0; i < dtrace_nprobes; i++) {
8238 		if ((probe = dtrace_probes[i]) == NULL)
8239 			continue;
8240 
8241 		if (probe->dtpr_provider != old)
8242 			continue;
8243 
8244 		dtrace_probes[i] = NULL;
8245 
8246 		dtrace_hash_remove(dtrace_bymod, probe);
8247 		dtrace_hash_remove(dtrace_byfunc, probe);
8248 		dtrace_hash_remove(dtrace_byname, probe);
8249 
8250 		if (first == NULL) {
8251 			first = probe;
8252 			probe->dtpr_nextmod = NULL;
8253 		} else {
8254 			probe->dtpr_nextmod = first;
8255 			first = probe;
8256 		}
8257 	}
8258 
8259 	/*
8260 	 * The provider's probes have been removed from the hash chains and
8261 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8262 	 * everyone has cleared out from any probe array processing.
8263 	 */
8264 	dtrace_sync();
8265 
8266 	for (probe = first; probe != NULL; probe = first) {
8267 		first = probe->dtpr_nextmod;
8268 
8269 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8270 		    probe->dtpr_arg);
8271 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8272 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8273 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8274 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8275 		kmem_free(probe, sizeof (dtrace_probe_t));
8276 	}
8277 
8278 	if ((prev = dtrace_provider) == old) {
8279 		ASSERT(self || dtrace_devi == NULL);
8280 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8281 		dtrace_provider = old->dtpv_next;
8282 	} else {
8283 		while (prev != NULL && prev->dtpv_next != old)
8284 			prev = prev->dtpv_next;
8285 
8286 		if (prev == NULL) {
8287 			panic("attempt to unregister non-existent "
8288 			    "dtrace provider %p\n", (void *)id);
8289 		}
8290 
8291 		prev->dtpv_next = old->dtpv_next;
8292 	}
8293 
8294 	if (!self) {
8295 		mutex_exit(&dtrace_lock);
8296 		mutex_exit(&mod_lock);
8297 		mutex_exit(&dtrace_provider_lock);
8298 	}
8299 
8300 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8301 	kmem_free(old, sizeof (dtrace_provider_t));
8302 
8303 	return (0);
8304 }
8305 
8306 /*
8307  * Invalidate the specified provider.  All subsequent probe lookups for the
8308  * specified provider will fail, but its probes will not be removed.
8309  */
8310 void
8311 dtrace_invalidate(dtrace_provider_id_t id)
8312 {
8313 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8314 
8315 	ASSERT(pvp->dtpv_pops.dtps_enable !=
8316 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8317 
8318 	mutex_enter(&dtrace_provider_lock);
8319 	mutex_enter(&dtrace_lock);
8320 
8321 	pvp->dtpv_defunct = dtrace_gethrtime();
8322 
8323 	mutex_exit(&dtrace_lock);
8324 	mutex_exit(&dtrace_provider_lock);
8325 }
8326 
8327 /*
8328  * Indicate whether or not DTrace has attached.
8329  */
8330 int
8331 dtrace_attached(void)
8332 {
8333 	/*
8334 	 * dtrace_provider will be non-NULL iff the DTrace driver has
8335 	 * attached.  (It's non-NULL because DTrace is always itself a
8336 	 * provider.)
8337 	 */
8338 	return (dtrace_provider != NULL);
8339 }
8340 
8341 /*
8342  * Remove all the unenabled probes for the given provider.  This function is
8343  * not unlike dtrace_unregister(), except that it doesn't remove the provider
8344  * -- just as many of its associated probes as it can.
8345  */
8346 int
8347 dtrace_condense(dtrace_provider_id_t id)
8348 {
8349 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
8350 	int i;
8351 	dtrace_probe_t *probe;
8352 
8353 	/*
8354 	 * Make sure this isn't the dtrace provider itself.
8355 	 */
8356 	ASSERT(prov->dtpv_pops.dtps_enable !=
8357 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8358 
8359 	mutex_enter(&dtrace_provider_lock);
8360 	mutex_enter(&dtrace_lock);
8361 
8362 	/*
8363 	 * Attempt to destroy the probes associated with this provider.
8364 	 */
8365 	for (i = 0; i < dtrace_nprobes; i++) {
8366 		if ((probe = dtrace_probes[i]) == NULL)
8367 			continue;
8368 
8369 		if (probe->dtpr_provider != prov)
8370 			continue;
8371 
8372 		if (probe->dtpr_ecb != NULL)
8373 			continue;
8374 
8375 		dtrace_probes[i] = NULL;
8376 
8377 		dtrace_hash_remove(dtrace_bymod, probe);
8378 		dtrace_hash_remove(dtrace_byfunc, probe);
8379 		dtrace_hash_remove(dtrace_byname, probe);
8380 
8381 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8382 		    probe->dtpr_arg);
8383 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8384 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8385 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8386 		kmem_free(probe, sizeof (dtrace_probe_t));
8387 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8388 	}
8389 
8390 	mutex_exit(&dtrace_lock);
8391 	mutex_exit(&dtrace_provider_lock);
8392 
8393 	return (0);
8394 }
8395 
8396 /*
8397  * DTrace Probe Management Functions
8398  *
8399  * The functions in this section perform the DTrace probe management,
8400  * including functions to create probes, look-up probes, and call into the
8401  * providers to request that probes be provided.  Some of these functions are
8402  * in the Provider-to-Framework API; these functions can be identified by the
8403  * fact that they are not declared "static".
8404  */
8405 
8406 /*
8407  * Create a probe with the specified module name, function name, and name.
8408  */
8409 dtrace_id_t
8410 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8411     const char *func, const char *name, int aframes, void *arg)
8412 {
8413 	dtrace_probe_t *probe, **probes;
8414 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8415 	dtrace_id_t id;
8416 
8417 	if (provider == dtrace_provider) {
8418 		ASSERT(MUTEX_HELD(&dtrace_lock));
8419 	} else {
8420 		mutex_enter(&dtrace_lock);
8421 	}
8422 
8423 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8424 	    VM_BESTFIT | VM_SLEEP);
8425 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8426 
8427 	probe->dtpr_id = id;
8428 	probe->dtpr_gen = dtrace_probegen++;
8429 	probe->dtpr_mod = dtrace_strdup(mod);
8430 	probe->dtpr_func = dtrace_strdup(func);
8431 	probe->dtpr_name = dtrace_strdup(name);
8432 	probe->dtpr_arg = arg;
8433 	probe->dtpr_aframes = aframes;
8434 	probe->dtpr_provider = provider;
8435 
8436 	dtrace_hash_add(dtrace_bymod, probe);
8437 	dtrace_hash_add(dtrace_byfunc, probe);
8438 	dtrace_hash_add(dtrace_byname, probe);
8439 
8440 	if (id - 1 >= dtrace_nprobes) {
8441 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8442 		size_t nsize = osize << 1;
8443 
8444 		if (nsize == 0) {
8445 			ASSERT(osize == 0);
8446 			ASSERT(dtrace_probes == NULL);
8447 			nsize = sizeof (dtrace_probe_t *);
8448 		}
8449 
8450 		probes = kmem_zalloc(nsize, KM_SLEEP);
8451 
8452 		if (dtrace_probes == NULL) {
8453 			ASSERT(osize == 0);
8454 			dtrace_probes = probes;
8455 			dtrace_nprobes = 1;
8456 		} else {
8457 			dtrace_probe_t **oprobes = dtrace_probes;
8458 
8459 			bcopy(oprobes, probes, osize);
8460 			dtrace_membar_producer();
8461 			dtrace_probes = probes;
8462 
8463 			dtrace_sync();
8464 
8465 			/*
8466 			 * All CPUs are now seeing the new probes array; we can
8467 			 * safely free the old array.
8468 			 */
8469 			kmem_free(oprobes, osize);
8470 			dtrace_nprobes <<= 1;
8471 		}
8472 
8473 		ASSERT(id - 1 < dtrace_nprobes);
8474 	}
8475 
8476 	ASSERT(dtrace_probes[id - 1] == NULL);
8477 	dtrace_probes[id - 1] = probe;
8478 
8479 	if (provider != dtrace_provider)
8480 		mutex_exit(&dtrace_lock);
8481 
8482 	return (id);
8483 }
8484 
8485 static dtrace_probe_t *
8486 dtrace_probe_lookup_id(dtrace_id_t id)
8487 {
8488 	ASSERT(MUTEX_HELD(&dtrace_lock));
8489 
8490 	if (id == 0 || id > dtrace_nprobes)
8491 		return (NULL);
8492 
8493 	return (dtrace_probes[id - 1]);
8494 }
8495 
8496 static int
8497 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8498 {
8499 	*((dtrace_id_t *)arg) = probe->dtpr_id;
8500 
8501 	return (DTRACE_MATCH_DONE);
8502 }
8503 
8504 /*
8505  * Look up a probe based on provider and one or more of module name, function
8506  * name and probe name.
8507  */
8508 dtrace_id_t
8509 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
8510     const char *func, const char *name)
8511 {
8512 	dtrace_probekey_t pkey;
8513 	dtrace_id_t id;
8514 	int match;
8515 
8516 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8517 	pkey.dtpk_pmatch = &dtrace_match_string;
8518 	pkey.dtpk_mod = mod;
8519 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8520 	pkey.dtpk_func = func;
8521 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8522 	pkey.dtpk_name = name;
8523 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8524 	pkey.dtpk_id = DTRACE_IDNONE;
8525 
8526 	mutex_enter(&dtrace_lock);
8527 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8528 	    dtrace_probe_lookup_match, &id);
8529 	mutex_exit(&dtrace_lock);
8530 
8531 	ASSERT(match == 1 || match == 0);
8532 	return (match ? id : 0);
8533 }
8534 
8535 /*
8536  * Returns the probe argument associated with the specified probe.
8537  */
8538 void *
8539 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8540 {
8541 	dtrace_probe_t *probe;
8542 	void *rval = NULL;
8543 
8544 	mutex_enter(&dtrace_lock);
8545 
8546 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8547 	    probe->dtpr_provider == (dtrace_provider_t *)id)
8548 		rval = probe->dtpr_arg;
8549 
8550 	mutex_exit(&dtrace_lock);
8551 
8552 	return (rval);
8553 }
8554 
8555 /*
8556  * Copy a probe into a probe description.
8557  */
8558 static void
8559 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8560 {
8561 	bzero(pdp, sizeof (dtrace_probedesc_t));
8562 	pdp->dtpd_id = prp->dtpr_id;
8563 
8564 	(void) strncpy(pdp->dtpd_provider,
8565 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8566 
8567 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8568 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8569 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8570 }
8571 
8572 /*
8573  * Called to indicate that a probe -- or probes -- should be provided by a
8574  * specfied provider.  If the specified description is NULL, the provider will
8575  * be told to provide all of its probes.  (This is done whenever a new
8576  * consumer comes along, or whenever a retained enabling is to be matched.) If
8577  * the specified description is non-NULL, the provider is given the
8578  * opportunity to dynamically provide the specified probe, allowing providers
8579  * to support the creation of probes on-the-fly.  (So-called _autocreated_
8580  * probes.)  If the provider is NULL, the operations will be applied to all
8581  * providers; if the provider is non-NULL the operations will only be applied
8582  * to the specified provider.  The dtrace_provider_lock must be held, and the
8583  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8584  * will need to grab the dtrace_lock when it reenters the framework through
8585  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8586  */
8587 static void
8588 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8589 {
8590 	struct modctl *ctl;
8591 	int all = 0;
8592 
8593 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8594 
8595 	if (prv == NULL) {
8596 		all = 1;
8597 		prv = dtrace_provider;
8598 	}
8599 
8600 	do {
8601 		/*
8602 		 * First, call the blanket provide operation.
8603 		 */
8604 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8605 
8606 		/*
8607 		 * Now call the per-module provide operation.  We will grab
8608 		 * mod_lock to prevent the list from being modified.  Note
8609 		 * that this also prevents the mod_busy bits from changing.
8610 		 * (mod_busy can only be changed with mod_lock held.)
8611 		 */
8612 		mutex_enter(&mod_lock);
8613 
8614 		ctl = &modules;
8615 		do {
8616 			if (ctl->mod_busy || ctl->mod_mp == NULL)
8617 				continue;
8618 
8619 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8620 
8621 		} while ((ctl = ctl->mod_next) != &modules);
8622 
8623 		mutex_exit(&mod_lock);
8624 	} while (all && (prv = prv->dtpv_next) != NULL);
8625 }
8626 
8627 /*
8628  * Iterate over each probe, and call the Framework-to-Provider API function
8629  * denoted by offs.
8630  */
8631 static void
8632 dtrace_probe_foreach(uintptr_t offs)
8633 {
8634 	dtrace_provider_t *prov;
8635 	void (*func)(void *, dtrace_id_t, void *);
8636 	dtrace_probe_t *probe;
8637 	dtrace_icookie_t cookie;
8638 	int i;
8639 
8640 	/*
8641 	 * We disable interrupts to walk through the probe array.  This is
8642 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8643 	 * won't see stale data.
8644 	 */
8645 	cookie = dtrace_interrupt_disable();
8646 
8647 	for (i = 0; i < dtrace_nprobes; i++) {
8648 		if ((probe = dtrace_probes[i]) == NULL)
8649 			continue;
8650 
8651 		if (probe->dtpr_ecb == NULL) {
8652 			/*
8653 			 * This probe isn't enabled -- don't call the function.
8654 			 */
8655 			continue;
8656 		}
8657 
8658 		prov = probe->dtpr_provider;
8659 		func = *((void(**)(void *, dtrace_id_t, void *))
8660 		    ((uintptr_t)&prov->dtpv_pops + offs));
8661 
8662 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8663 	}
8664 
8665 	dtrace_interrupt_enable(cookie);
8666 }
8667 
8668 static int
8669 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8670 {
8671 	dtrace_probekey_t pkey;
8672 	uint32_t priv;
8673 	uid_t uid;
8674 	zoneid_t zoneid;
8675 
8676 	ASSERT(MUTEX_HELD(&dtrace_lock));
8677 	dtrace_ecb_create_cache = NULL;
8678 
8679 	if (desc == NULL) {
8680 		/*
8681 		 * If we're passed a NULL description, we're being asked to
8682 		 * create an ECB with a NULL probe.
8683 		 */
8684 		(void) dtrace_ecb_create_enable(NULL, enab);
8685 		return (0);
8686 	}
8687 
8688 	dtrace_probekey(desc, &pkey);
8689 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8690 	    &priv, &uid, &zoneid);
8691 
8692 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8693 	    enab));
8694 }
8695 
8696 /*
8697  * DTrace Helper Provider Functions
8698  */
8699 static void
8700 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8701 {
8702 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
8703 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
8704 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8705 }
8706 
8707 static void
8708 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8709     const dof_provider_t *dofprov, char *strtab)
8710 {
8711 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8712 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8713 	    dofprov->dofpv_provattr);
8714 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8715 	    dofprov->dofpv_modattr);
8716 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8717 	    dofprov->dofpv_funcattr);
8718 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8719 	    dofprov->dofpv_nameattr);
8720 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8721 	    dofprov->dofpv_argsattr);
8722 }
8723 
8724 static void
8725 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8726 {
8727 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8728 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8729 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8730 	dof_provider_t *provider;
8731 	dof_probe_t *probe;
8732 	uint32_t *off, *enoff;
8733 	uint8_t *arg;
8734 	char *strtab;
8735 	uint_t i, nprobes;
8736 	dtrace_helper_provdesc_t dhpv;
8737 	dtrace_helper_probedesc_t dhpb;
8738 	dtrace_meta_t *meta = dtrace_meta_pid;
8739 	dtrace_mops_t *mops = &meta->dtm_mops;
8740 	void *parg;
8741 
8742 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8743 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8744 	    provider->dofpv_strtab * dof->dofh_secsize);
8745 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8746 	    provider->dofpv_probes * dof->dofh_secsize);
8747 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8748 	    provider->dofpv_prargs * dof->dofh_secsize);
8749 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8750 	    provider->dofpv_proffs * dof->dofh_secsize);
8751 
8752 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8753 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8754 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8755 	enoff = NULL;
8756 
8757 	/*
8758 	 * See dtrace_helper_provider_validate().
8759 	 */
8760 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8761 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
8762 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8763 		    provider->dofpv_prenoffs * dof->dofh_secsize);
8764 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8765 	}
8766 
8767 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8768 
8769 	/*
8770 	 * Create the provider.
8771 	 */
8772 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
8773 
8774 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8775 		return;
8776 
8777 	meta->dtm_count++;
8778 
8779 	/*
8780 	 * Create the probes.
8781 	 */
8782 	for (i = 0; i < nprobes; i++) {
8783 		probe = (dof_probe_t *)(uintptr_t)(daddr +
8784 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8785 
8786 		dhpb.dthpb_mod = dhp->dofhp_mod;
8787 		dhpb.dthpb_func = strtab + probe->dofpr_func;
8788 		dhpb.dthpb_name = strtab + probe->dofpr_name;
8789 		dhpb.dthpb_base = probe->dofpr_addr;
8790 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
8791 		dhpb.dthpb_noffs = probe->dofpr_noffs;
8792 		if (enoff != NULL) {
8793 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8794 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8795 		} else {
8796 			dhpb.dthpb_enoffs = NULL;
8797 			dhpb.dthpb_nenoffs = 0;
8798 		}
8799 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
8800 		dhpb.dthpb_nargc = probe->dofpr_nargc;
8801 		dhpb.dthpb_xargc = probe->dofpr_xargc;
8802 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8803 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8804 
8805 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8806 	}
8807 }
8808 
8809 static void
8810 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8811 {
8812 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8813 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8814 	int i;
8815 
8816 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8817 
8818 	for (i = 0; i < dof->dofh_secnum; i++) {
8819 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8820 		    dof->dofh_secoff + i * dof->dofh_secsize);
8821 
8822 		if (sec->dofs_type != DOF_SECT_PROVIDER)
8823 			continue;
8824 
8825 		dtrace_helper_provide_one(dhp, sec, pid);
8826 	}
8827 
8828 	/*
8829 	 * We may have just created probes, so we must now rematch against
8830 	 * any retained enablings.  Note that this call will acquire both
8831 	 * cpu_lock and dtrace_lock; the fact that we are holding
8832 	 * dtrace_meta_lock now is what defines the ordering with respect to
8833 	 * these three locks.
8834 	 */
8835 	dtrace_enabling_matchall();
8836 }
8837 
8838 static void
8839 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8840 {
8841 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8842 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8843 	dof_sec_t *str_sec;
8844 	dof_provider_t *provider;
8845 	char *strtab;
8846 	dtrace_helper_provdesc_t dhpv;
8847 	dtrace_meta_t *meta = dtrace_meta_pid;
8848 	dtrace_mops_t *mops = &meta->dtm_mops;
8849 
8850 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8851 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8852 	    provider->dofpv_strtab * dof->dofh_secsize);
8853 
8854 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8855 
8856 	/*
8857 	 * Create the provider.
8858 	 */
8859 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
8860 
8861 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8862 
8863 	meta->dtm_count--;
8864 }
8865 
8866 static void
8867 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8868 {
8869 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8870 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8871 	int i;
8872 
8873 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8874 
8875 	for (i = 0; i < dof->dofh_secnum; i++) {
8876 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8877 		    dof->dofh_secoff + i * dof->dofh_secsize);
8878 
8879 		if (sec->dofs_type != DOF_SECT_PROVIDER)
8880 			continue;
8881 
8882 		dtrace_helper_provider_remove_one(dhp, sec, pid);
8883 	}
8884 }
8885 
8886 /*
8887  * DTrace Meta Provider-to-Framework API Functions
8888  *
8889  * These functions implement the Meta Provider-to-Framework API, as described
8890  * in <sys/dtrace.h>.
8891  */
8892 int
8893 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8894     dtrace_meta_provider_id_t *idp)
8895 {
8896 	dtrace_meta_t *meta;
8897 	dtrace_helpers_t *help, *next;
8898 	int i;
8899 
8900 	*idp = DTRACE_METAPROVNONE;
8901 
8902 	/*
8903 	 * We strictly don't need the name, but we hold onto it for
8904 	 * debuggability. All hail error queues!
8905 	 */
8906 	if (name == NULL) {
8907 		cmn_err(CE_WARN, "failed to register meta-provider: "
8908 		    "invalid name");
8909 		return (EINVAL);
8910 	}
8911 
8912 	if (mops == NULL ||
8913 	    mops->dtms_create_probe == NULL ||
8914 	    mops->dtms_provide_pid == NULL ||
8915 	    mops->dtms_remove_pid == NULL) {
8916 		cmn_err(CE_WARN, "failed to register meta-register %s: "
8917 		    "invalid ops", name);
8918 		return (EINVAL);
8919 	}
8920 
8921 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8922 	meta->dtm_mops = *mops;
8923 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8924 	(void) strcpy(meta->dtm_name, name);
8925 	meta->dtm_arg = arg;
8926 
8927 	mutex_enter(&dtrace_meta_lock);
8928 	mutex_enter(&dtrace_lock);
8929 
8930 	if (dtrace_meta_pid != NULL) {
8931 		mutex_exit(&dtrace_lock);
8932 		mutex_exit(&dtrace_meta_lock);
8933 		cmn_err(CE_WARN, "failed to register meta-register %s: "
8934 		    "user-land meta-provider exists", name);
8935 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8936 		kmem_free(meta, sizeof (dtrace_meta_t));
8937 		return (EINVAL);
8938 	}
8939 
8940 	dtrace_meta_pid = meta;
8941 	*idp = (dtrace_meta_provider_id_t)meta;
8942 
8943 	/*
8944 	 * If there are providers and probes ready to go, pass them
8945 	 * off to the new meta provider now.
8946 	 */
8947 
8948 	help = dtrace_deferred_pid;
8949 	dtrace_deferred_pid = NULL;
8950 
8951 	mutex_exit(&dtrace_lock);
8952 
8953 	while (help != NULL) {
8954 		for (i = 0; i < help->dthps_nprovs; i++) {
8955 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8956 			    help->dthps_pid);
8957 		}
8958 
8959 		next = help->dthps_next;
8960 		help->dthps_next = NULL;
8961 		help->dthps_prev = NULL;
8962 		help->dthps_deferred = 0;
8963 		help = next;
8964 	}
8965 
8966 	mutex_exit(&dtrace_meta_lock);
8967 
8968 	return (0);
8969 }
8970 
8971 int
8972 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8973 {
8974 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8975 
8976 	mutex_enter(&dtrace_meta_lock);
8977 	mutex_enter(&dtrace_lock);
8978 
8979 	if (old == dtrace_meta_pid) {
8980 		pp = &dtrace_meta_pid;
8981 	} else {
8982 		panic("attempt to unregister non-existent "
8983 		    "dtrace meta-provider %p\n", (void *)old);
8984 	}
8985 
8986 	if (old->dtm_count != 0) {
8987 		mutex_exit(&dtrace_lock);
8988 		mutex_exit(&dtrace_meta_lock);
8989 		return (EBUSY);
8990 	}
8991 
8992 	*pp = NULL;
8993 
8994 	mutex_exit(&dtrace_lock);
8995 	mutex_exit(&dtrace_meta_lock);
8996 
8997 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8998 	kmem_free(old, sizeof (dtrace_meta_t));
8999 
9000 	return (0);
9001 }
9002 
9003 
9004 /*
9005  * DTrace DIF Object Functions
9006  */
9007 static int
9008 dtrace_difo_err(uint_t pc, const char *format, ...)
9009 {
9010 	if (dtrace_err_verbose) {
9011 		va_list alist;
9012 
9013 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9014 		va_start(alist, format);
9015 		(void) vuprintf(format, alist);
9016 		va_end(alist);
9017 	}
9018 
9019 #ifdef DTRACE_ERRDEBUG
9020 	dtrace_errdebug(format);
9021 #endif
9022 	return (1);
9023 }
9024 
9025 /*
9026  * Validate a DTrace DIF object by checking the IR instructions.  The following
9027  * rules are currently enforced by dtrace_difo_validate():
9028  *
9029  * 1. Each instruction must have a valid opcode
9030  * 2. Each register, string, variable, or subroutine reference must be valid
9031  * 3. No instruction can modify register %r0 (must be zero)
9032  * 4. All instruction reserved bits must be set to zero
9033  * 5. The last instruction must be a "ret" instruction
9034  * 6. All branch targets must reference a valid instruction _after_ the branch
9035  */
9036 static int
9037 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9038     cred_t *cr)
9039 {
9040 	int err = 0, i;
9041 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9042 	int kcheckload;
9043 	uint_t pc;
9044 	int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9045 
9046 	kcheckload = cr == NULL ||
9047 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9048 
9049 	dp->dtdo_destructive = 0;
9050 
9051 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9052 		dif_instr_t instr = dp->dtdo_buf[pc];
9053 
9054 		uint_t r1 = DIF_INSTR_R1(instr);
9055 		uint_t r2 = DIF_INSTR_R2(instr);
9056 		uint_t rd = DIF_INSTR_RD(instr);
9057 		uint_t rs = DIF_INSTR_RS(instr);
9058 		uint_t label = DIF_INSTR_LABEL(instr);
9059 		uint_t v = DIF_INSTR_VAR(instr);
9060 		uint_t subr = DIF_INSTR_SUBR(instr);
9061 		uint_t type = DIF_INSTR_TYPE(instr);
9062 		uint_t op = DIF_INSTR_OP(instr);
9063 
9064 		switch (op) {
9065 		case DIF_OP_OR:
9066 		case DIF_OP_XOR:
9067 		case DIF_OP_AND:
9068 		case DIF_OP_SLL:
9069 		case DIF_OP_SRL:
9070 		case DIF_OP_SRA:
9071 		case DIF_OP_SUB:
9072 		case DIF_OP_ADD:
9073 		case DIF_OP_MUL:
9074 		case DIF_OP_SDIV:
9075 		case DIF_OP_UDIV:
9076 		case DIF_OP_SREM:
9077 		case DIF_OP_UREM:
9078 		case DIF_OP_COPYS:
9079 			if (r1 >= nregs)
9080 				err += efunc(pc, "invalid register %u\n", r1);
9081 			if (r2 >= nregs)
9082 				err += efunc(pc, "invalid register %u\n", r2);
9083 			if (rd >= nregs)
9084 				err += efunc(pc, "invalid register %u\n", rd);
9085 			if (rd == 0)
9086 				err += efunc(pc, "cannot write to %r0\n");
9087 			break;
9088 		case DIF_OP_NOT:
9089 		case DIF_OP_MOV:
9090 		case DIF_OP_ALLOCS:
9091 			if (r1 >= nregs)
9092 				err += efunc(pc, "invalid register %u\n", r1);
9093 			if (r2 != 0)
9094 				err += efunc(pc, "non-zero reserved bits\n");
9095 			if (rd >= nregs)
9096 				err += efunc(pc, "invalid register %u\n", rd);
9097 			if (rd == 0)
9098 				err += efunc(pc, "cannot write to %r0\n");
9099 			break;
9100 		case DIF_OP_LDSB:
9101 		case DIF_OP_LDSH:
9102 		case DIF_OP_LDSW:
9103 		case DIF_OP_LDUB:
9104 		case DIF_OP_LDUH:
9105 		case DIF_OP_LDUW:
9106 		case DIF_OP_LDX:
9107 			if (r1 >= nregs)
9108 				err += efunc(pc, "invalid register %u\n", r1);
9109 			if (r2 != 0)
9110 				err += efunc(pc, "non-zero reserved bits\n");
9111 			if (rd >= nregs)
9112 				err += efunc(pc, "invalid register %u\n", rd);
9113 			if (rd == 0)
9114 				err += efunc(pc, "cannot write to %r0\n");
9115 			if (kcheckload)
9116 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9117 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9118 			break;
9119 		case DIF_OP_RLDSB:
9120 		case DIF_OP_RLDSH:
9121 		case DIF_OP_RLDSW:
9122 		case DIF_OP_RLDUB:
9123 		case DIF_OP_RLDUH:
9124 		case DIF_OP_RLDUW:
9125 		case DIF_OP_RLDX:
9126 			if (r1 >= nregs)
9127 				err += efunc(pc, "invalid register %u\n", r1);
9128 			if (r2 != 0)
9129 				err += efunc(pc, "non-zero reserved bits\n");
9130 			if (rd >= nregs)
9131 				err += efunc(pc, "invalid register %u\n", rd);
9132 			if (rd == 0)
9133 				err += efunc(pc, "cannot write to %r0\n");
9134 			break;
9135 		case DIF_OP_ULDSB:
9136 		case DIF_OP_ULDSH:
9137 		case DIF_OP_ULDSW:
9138 		case DIF_OP_ULDUB:
9139 		case DIF_OP_ULDUH:
9140 		case DIF_OP_ULDUW:
9141 		case DIF_OP_ULDX:
9142 			if (r1 >= nregs)
9143 				err += efunc(pc, "invalid register %u\n", r1);
9144 			if (r2 != 0)
9145 				err += efunc(pc, "non-zero reserved bits\n");
9146 			if (rd >= nregs)
9147 				err += efunc(pc, "invalid register %u\n", rd);
9148 			if (rd == 0)
9149 				err += efunc(pc, "cannot write to %r0\n");
9150 			break;
9151 		case DIF_OP_STB:
9152 		case DIF_OP_STH:
9153 		case DIF_OP_STW:
9154 		case DIF_OP_STX:
9155 			if (r1 >= nregs)
9156 				err += efunc(pc, "invalid register %u\n", r1);
9157 			if (r2 != 0)
9158 				err += efunc(pc, "non-zero reserved bits\n");
9159 			if (rd >= nregs)
9160 				err += efunc(pc, "invalid register %u\n", rd);
9161 			if (rd == 0)
9162 				err += efunc(pc, "cannot write to 0 address\n");
9163 			break;
9164 		case DIF_OP_CMP:
9165 		case DIF_OP_SCMP:
9166 			if (r1 >= nregs)
9167 				err += efunc(pc, "invalid register %u\n", r1);
9168 			if (r2 >= nregs)
9169 				err += efunc(pc, "invalid register %u\n", r2);
9170 			if (rd != 0)
9171 				err += efunc(pc, "non-zero reserved bits\n");
9172 			break;
9173 		case DIF_OP_TST:
9174 			if (r1 >= nregs)
9175 				err += efunc(pc, "invalid register %u\n", r1);
9176 			if (r2 != 0 || rd != 0)
9177 				err += efunc(pc, "non-zero reserved bits\n");
9178 			break;
9179 		case DIF_OP_BA:
9180 		case DIF_OP_BE:
9181 		case DIF_OP_BNE:
9182 		case DIF_OP_BG:
9183 		case DIF_OP_BGU:
9184 		case DIF_OP_BGE:
9185 		case DIF_OP_BGEU:
9186 		case DIF_OP_BL:
9187 		case DIF_OP_BLU:
9188 		case DIF_OP_BLE:
9189 		case DIF_OP_BLEU:
9190 			if (label >= dp->dtdo_len) {
9191 				err += efunc(pc, "invalid branch target %u\n",
9192 				    label);
9193 			}
9194 			if (label <= pc) {
9195 				err += efunc(pc, "backward branch to %u\n",
9196 				    label);
9197 			}
9198 			break;
9199 		case DIF_OP_RET:
9200 			if (r1 != 0 || r2 != 0)
9201 				err += efunc(pc, "non-zero reserved bits\n");
9202 			if (rd >= nregs)
9203 				err += efunc(pc, "invalid register %u\n", rd);
9204 			break;
9205 		case DIF_OP_NOP:
9206 		case DIF_OP_POPTS:
9207 		case DIF_OP_FLUSHTS:
9208 			if (r1 != 0 || r2 != 0 || rd != 0)
9209 				err += efunc(pc, "non-zero reserved bits\n");
9210 			break;
9211 		case DIF_OP_SETX:
9212 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9213 				err += efunc(pc, "invalid integer ref %u\n",
9214 				    DIF_INSTR_INTEGER(instr));
9215 			}
9216 			if (rd >= nregs)
9217 				err += efunc(pc, "invalid register %u\n", rd);
9218 			if (rd == 0)
9219 				err += efunc(pc, "cannot write to %r0\n");
9220 			break;
9221 		case DIF_OP_SETS:
9222 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9223 				err += efunc(pc, "invalid string ref %u\n",
9224 				    DIF_INSTR_STRING(instr));
9225 			}
9226 			if (rd >= nregs)
9227 				err += efunc(pc, "invalid register %u\n", rd);
9228 			if (rd == 0)
9229 				err += efunc(pc, "cannot write to %r0\n");
9230 			break;
9231 		case DIF_OP_LDGA:
9232 		case DIF_OP_LDTA:
9233 			if (r1 > DIF_VAR_ARRAY_MAX)
9234 				err += efunc(pc, "invalid array %u\n", r1);
9235 			if (r2 >= nregs)
9236 				err += efunc(pc, "invalid register %u\n", r2);
9237 			if (rd >= nregs)
9238 				err += efunc(pc, "invalid register %u\n", rd);
9239 			if (rd == 0)
9240 				err += efunc(pc, "cannot write to %r0\n");
9241 			break;
9242 		case DIF_OP_LDGS:
9243 		case DIF_OP_LDTS:
9244 		case DIF_OP_LDLS:
9245 		case DIF_OP_LDGAA:
9246 		case DIF_OP_LDTAA:
9247 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9248 				err += efunc(pc, "invalid variable %u\n", v);
9249 			if (rd >= nregs)
9250 				err += efunc(pc, "invalid register %u\n", rd);
9251 			if (rd == 0)
9252 				err += efunc(pc, "cannot write to %r0\n");
9253 			break;
9254 		case DIF_OP_STGS:
9255 		case DIF_OP_STTS:
9256 		case DIF_OP_STLS:
9257 		case DIF_OP_STGAA:
9258 		case DIF_OP_STTAA:
9259 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9260 				err += efunc(pc, "invalid variable %u\n", v);
9261 			if (rs >= nregs)
9262 				err += efunc(pc, "invalid register %u\n", rd);
9263 			break;
9264 		case DIF_OP_CALL:
9265 			if (subr > DIF_SUBR_MAX)
9266 				err += efunc(pc, "invalid subr %u\n", subr);
9267 			if (rd >= nregs)
9268 				err += efunc(pc, "invalid register %u\n", rd);
9269 			if (rd == 0)
9270 				err += efunc(pc, "cannot write to %r0\n");
9271 
9272 			if (subr == DIF_SUBR_COPYOUT ||
9273 			    subr == DIF_SUBR_COPYOUTSTR) {
9274 				dp->dtdo_destructive = 1;
9275 			}
9276 
9277 			if (subr == DIF_SUBR_GETF) {
9278 				/*
9279 				 * If we have a getf() we need to record that
9280 				 * in our state.  Note that our state can be
9281 				 * NULL if this is a helper -- but in that
9282 				 * case, the call to getf() is itself illegal,
9283 				 * and will be caught (slightly later) when
9284 				 * the helper is validated.
9285 				 */
9286 				if (vstate->dtvs_state != NULL)
9287 					vstate->dtvs_state->dts_getf++;
9288 			}
9289 
9290 			break;
9291 		case DIF_OP_PUSHTR:
9292 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9293 				err += efunc(pc, "invalid ref type %u\n", type);
9294 			if (r2 >= nregs)
9295 				err += efunc(pc, "invalid register %u\n", r2);
9296 			if (rs >= nregs)
9297 				err += efunc(pc, "invalid register %u\n", rs);
9298 			break;
9299 		case DIF_OP_PUSHTV:
9300 			if (type != DIF_TYPE_CTF)
9301 				err += efunc(pc, "invalid val type %u\n", type);
9302 			if (r2 >= nregs)
9303 				err += efunc(pc, "invalid register %u\n", r2);
9304 			if (rs >= nregs)
9305 				err += efunc(pc, "invalid register %u\n", rs);
9306 			break;
9307 		default:
9308 			err += efunc(pc, "invalid opcode %u\n",
9309 			    DIF_INSTR_OP(instr));
9310 		}
9311 	}
9312 
9313 	if (dp->dtdo_len != 0 &&
9314 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9315 		err += efunc(dp->dtdo_len - 1,
9316 		    "expected 'ret' as last DIF instruction\n");
9317 	}
9318 
9319 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
9320 		/*
9321 		 * If we're not returning by reference, the size must be either
9322 		 * 0 or the size of one of the base types.
9323 		 */
9324 		switch (dp->dtdo_rtype.dtdt_size) {
9325 		case 0:
9326 		case sizeof (uint8_t):
9327 		case sizeof (uint16_t):
9328 		case sizeof (uint32_t):
9329 		case sizeof (uint64_t):
9330 			break;
9331 
9332 		default:
9333 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
9334 		}
9335 	}
9336 
9337 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9338 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9339 		dtrace_diftype_t *vt, *et;
9340 		uint_t id, ndx;
9341 
9342 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9343 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
9344 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9345 			err += efunc(i, "unrecognized variable scope %d\n",
9346 			    v->dtdv_scope);
9347 			break;
9348 		}
9349 
9350 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9351 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
9352 			err += efunc(i, "unrecognized variable type %d\n",
9353 			    v->dtdv_kind);
9354 			break;
9355 		}
9356 
9357 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9358 			err += efunc(i, "%d exceeds variable id limit\n", id);
9359 			break;
9360 		}
9361 
9362 		if (id < DIF_VAR_OTHER_UBASE)
9363 			continue;
9364 
9365 		/*
9366 		 * For user-defined variables, we need to check that this
9367 		 * definition is identical to any previous definition that we
9368 		 * encountered.
9369 		 */
9370 		ndx = id - DIF_VAR_OTHER_UBASE;
9371 
9372 		switch (v->dtdv_scope) {
9373 		case DIFV_SCOPE_GLOBAL:
9374 			if (maxglobal == -1 || ndx > maxglobal)
9375 				maxglobal = ndx;
9376 
9377 			if (ndx < vstate->dtvs_nglobals) {
9378 				dtrace_statvar_t *svar;
9379 
9380 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9381 					existing = &svar->dtsv_var;
9382 			}
9383 
9384 			break;
9385 
9386 		case DIFV_SCOPE_THREAD:
9387 			if (maxtlocal == -1 || ndx > maxtlocal)
9388 				maxtlocal = ndx;
9389 
9390 			if (ndx < vstate->dtvs_ntlocals)
9391 				existing = &vstate->dtvs_tlocals[ndx];
9392 			break;
9393 
9394 		case DIFV_SCOPE_LOCAL:
9395 			if (maxlocal == -1 || ndx > maxlocal)
9396 				maxlocal = ndx;
9397 
9398 			if (ndx < vstate->dtvs_nlocals) {
9399 				dtrace_statvar_t *svar;
9400 
9401 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9402 					existing = &svar->dtsv_var;
9403 			}
9404 
9405 			break;
9406 		}
9407 
9408 		vt = &v->dtdv_type;
9409 
9410 		if (vt->dtdt_flags & DIF_TF_BYREF) {
9411 			if (vt->dtdt_size == 0) {
9412 				err += efunc(i, "zero-sized variable\n");
9413 				break;
9414 			}
9415 
9416 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
9417 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
9418 			    vt->dtdt_size > dtrace_statvar_maxsize) {
9419 				err += efunc(i, "oversized by-ref static\n");
9420 				break;
9421 			}
9422 		}
9423 
9424 		if (existing == NULL || existing->dtdv_id == 0)
9425 			continue;
9426 
9427 		ASSERT(existing->dtdv_id == v->dtdv_id);
9428 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
9429 
9430 		if (existing->dtdv_kind != v->dtdv_kind)
9431 			err += efunc(i, "%d changed variable kind\n", id);
9432 
9433 		et = &existing->dtdv_type;
9434 
9435 		if (vt->dtdt_flags != et->dtdt_flags) {
9436 			err += efunc(i, "%d changed variable type flags\n", id);
9437 			break;
9438 		}
9439 
9440 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9441 			err += efunc(i, "%d changed variable type size\n", id);
9442 			break;
9443 		}
9444 	}
9445 
9446 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9447 		dif_instr_t instr = dp->dtdo_buf[pc];
9448 
9449 		uint_t v = DIF_INSTR_VAR(instr);
9450 		uint_t op = DIF_INSTR_OP(instr);
9451 
9452 		switch (op) {
9453 		case DIF_OP_LDGS:
9454 		case DIF_OP_LDGAA:
9455 		case DIF_OP_STGS:
9456 		case DIF_OP_STGAA:
9457 			if (v > DIF_VAR_OTHER_UBASE + maxglobal)
9458 				err += efunc(pc, "invalid variable %u\n", v);
9459 			break;
9460 		case DIF_OP_LDTS:
9461 		case DIF_OP_LDTAA:
9462 		case DIF_OP_STTS:
9463 		case DIF_OP_STTAA:
9464 			if (v > DIF_VAR_OTHER_UBASE + maxtlocal)
9465 				err += efunc(pc, "invalid variable %u\n", v);
9466 			break;
9467 		case DIF_OP_LDLS:
9468 		case DIF_OP_STLS:
9469 			if (v > DIF_VAR_OTHER_UBASE + maxlocal)
9470 				err += efunc(pc, "invalid variable %u\n", v);
9471 			break;
9472 		default:
9473 			break;
9474 		}
9475 	}
9476 
9477 	return (err);
9478 }
9479 
9480 /*
9481  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
9482  * are much more constrained than normal DIFOs.  Specifically, they may
9483  * not:
9484  *
9485  * 1. Make calls to subroutines other than copyin(), copyinstr() or
9486  *    miscellaneous string routines
9487  * 2. Access DTrace variables other than the args[] array, and the
9488  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9489  * 3. Have thread-local variables.
9490  * 4. Have dynamic variables.
9491  */
9492 static int
9493 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9494 {
9495 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9496 	int err = 0;
9497 	uint_t pc;
9498 
9499 	for (pc = 0; pc < dp->dtdo_len; pc++) {
9500 		dif_instr_t instr = dp->dtdo_buf[pc];
9501 
9502 		uint_t v = DIF_INSTR_VAR(instr);
9503 		uint_t subr = DIF_INSTR_SUBR(instr);
9504 		uint_t op = DIF_INSTR_OP(instr);
9505 
9506 		switch (op) {
9507 		case DIF_OP_OR:
9508 		case DIF_OP_XOR:
9509 		case DIF_OP_AND:
9510 		case DIF_OP_SLL:
9511 		case DIF_OP_SRL:
9512 		case DIF_OP_SRA:
9513 		case DIF_OP_SUB:
9514 		case DIF_OP_ADD:
9515 		case DIF_OP_MUL:
9516 		case DIF_OP_SDIV:
9517 		case DIF_OP_UDIV:
9518 		case DIF_OP_SREM:
9519 		case DIF_OP_UREM:
9520 		case DIF_OP_COPYS:
9521 		case DIF_OP_NOT:
9522 		case DIF_OP_MOV:
9523 		case DIF_OP_RLDSB:
9524 		case DIF_OP_RLDSH:
9525 		case DIF_OP_RLDSW:
9526 		case DIF_OP_RLDUB:
9527 		case DIF_OP_RLDUH:
9528 		case DIF_OP_RLDUW:
9529 		case DIF_OP_RLDX:
9530 		case DIF_OP_ULDSB:
9531 		case DIF_OP_ULDSH:
9532 		case DIF_OP_ULDSW:
9533 		case DIF_OP_ULDUB:
9534 		case DIF_OP_ULDUH:
9535 		case DIF_OP_ULDUW:
9536 		case DIF_OP_ULDX:
9537 		case DIF_OP_STB:
9538 		case DIF_OP_STH:
9539 		case DIF_OP_STW:
9540 		case DIF_OP_STX:
9541 		case DIF_OP_ALLOCS:
9542 		case DIF_OP_CMP:
9543 		case DIF_OP_SCMP:
9544 		case DIF_OP_TST:
9545 		case DIF_OP_BA:
9546 		case DIF_OP_BE:
9547 		case DIF_OP_BNE:
9548 		case DIF_OP_BG:
9549 		case DIF_OP_BGU:
9550 		case DIF_OP_BGE:
9551 		case DIF_OP_BGEU:
9552 		case DIF_OP_BL:
9553 		case DIF_OP_BLU:
9554 		case DIF_OP_BLE:
9555 		case DIF_OP_BLEU:
9556 		case DIF_OP_RET:
9557 		case DIF_OP_NOP:
9558 		case DIF_OP_POPTS:
9559 		case DIF_OP_FLUSHTS:
9560 		case DIF_OP_SETX:
9561 		case DIF_OP_SETS:
9562 		case DIF_OP_LDGA:
9563 		case DIF_OP_LDLS:
9564 		case DIF_OP_STGS:
9565 		case DIF_OP_STLS:
9566 		case DIF_OP_PUSHTR:
9567 		case DIF_OP_PUSHTV:
9568 			break;
9569 
9570 		case DIF_OP_LDGS:
9571 			if (v >= DIF_VAR_OTHER_UBASE)
9572 				break;
9573 
9574 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9575 				break;
9576 
9577 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9578 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9579 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9580 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
9581 				break;
9582 
9583 			err += efunc(pc, "illegal variable %u\n", v);
9584 			break;
9585 
9586 		case DIF_OP_LDTA:
9587 		case DIF_OP_LDTS:
9588 		case DIF_OP_LDGAA:
9589 		case DIF_OP_LDTAA:
9590 			err += efunc(pc, "illegal dynamic variable load\n");
9591 			break;
9592 
9593 		case DIF_OP_STTS:
9594 		case DIF_OP_STGAA:
9595 		case DIF_OP_STTAA:
9596 			err += efunc(pc, "illegal dynamic variable store\n");
9597 			break;
9598 
9599 		case DIF_OP_CALL:
9600 			if (subr == DIF_SUBR_ALLOCA ||
9601 			    subr == DIF_SUBR_BCOPY ||
9602 			    subr == DIF_SUBR_COPYIN ||
9603 			    subr == DIF_SUBR_COPYINTO ||
9604 			    subr == DIF_SUBR_COPYINSTR ||
9605 			    subr == DIF_SUBR_INDEX ||
9606 			    subr == DIF_SUBR_INET_NTOA ||
9607 			    subr == DIF_SUBR_INET_NTOA6 ||
9608 			    subr == DIF_SUBR_INET_NTOP ||
9609 			    subr == DIF_SUBR_JSON ||
9610 			    subr == DIF_SUBR_LLTOSTR ||
9611 			    subr == DIF_SUBR_STRTOLL ||
9612 			    subr == DIF_SUBR_RINDEX ||
9613 			    subr == DIF_SUBR_STRCHR ||
9614 			    subr == DIF_SUBR_STRJOIN ||
9615 			    subr == DIF_SUBR_STRRCHR ||
9616 			    subr == DIF_SUBR_STRSTR ||
9617 			    subr == DIF_SUBR_HTONS ||
9618 			    subr == DIF_SUBR_HTONL ||
9619 			    subr == DIF_SUBR_HTONLL ||
9620 			    subr == DIF_SUBR_NTOHS ||
9621 			    subr == DIF_SUBR_NTOHL ||
9622 			    subr == DIF_SUBR_NTOHLL)
9623 				break;
9624 
9625 			err += efunc(pc, "invalid subr %u\n", subr);
9626 			break;
9627 
9628 		default:
9629 			err += efunc(pc, "invalid opcode %u\n",
9630 			    DIF_INSTR_OP(instr));
9631 		}
9632 	}
9633 
9634 	return (err);
9635 }
9636 
9637 /*
9638  * Returns 1 if the expression in the DIF object can be cached on a per-thread
9639  * basis; 0 if not.
9640  */
9641 static int
9642 dtrace_difo_cacheable(dtrace_difo_t *dp)
9643 {
9644 	int i;
9645 
9646 	if (dp == NULL)
9647 		return (0);
9648 
9649 	for (i = 0; i < dp->dtdo_varlen; i++) {
9650 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9651 
9652 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9653 			continue;
9654 
9655 		switch (v->dtdv_id) {
9656 		case DIF_VAR_CURTHREAD:
9657 		case DIF_VAR_PID:
9658 		case DIF_VAR_TID:
9659 		case DIF_VAR_EXECNAME:
9660 		case DIF_VAR_ZONENAME:
9661 			break;
9662 
9663 		default:
9664 			return (0);
9665 		}
9666 	}
9667 
9668 	/*
9669 	 * This DIF object may be cacheable.  Now we need to look for any
9670 	 * array loading instructions, any memory loading instructions, or
9671 	 * any stores to thread-local variables.
9672 	 */
9673 	for (i = 0; i < dp->dtdo_len; i++) {
9674 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9675 
9676 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9677 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9678 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9679 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
9680 			return (0);
9681 	}
9682 
9683 	return (1);
9684 }
9685 
9686 static void
9687 dtrace_difo_hold(dtrace_difo_t *dp)
9688 {
9689 	int i;
9690 
9691 	ASSERT(MUTEX_HELD(&dtrace_lock));
9692 
9693 	dp->dtdo_refcnt++;
9694 	ASSERT(dp->dtdo_refcnt != 0);
9695 
9696 	/*
9697 	 * We need to check this DIF object for references to the variable
9698 	 * DIF_VAR_VTIMESTAMP.
9699 	 */
9700 	for (i = 0; i < dp->dtdo_varlen; i++) {
9701 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9702 
9703 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9704 			continue;
9705 
9706 		if (dtrace_vtime_references++ == 0)
9707 			dtrace_vtime_enable();
9708 	}
9709 }
9710 
9711 /*
9712  * This routine calculates the dynamic variable chunksize for a given DIF
9713  * object.  The calculation is not fool-proof, and can probably be tricked by
9714  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
9715  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9716  * if a dynamic variable size exceeds the chunksize.
9717  */
9718 static void
9719 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9720 {
9721 	uint64_t sval;
9722 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9723 	const dif_instr_t *text = dp->dtdo_buf;
9724 	uint_t pc, srd = 0;
9725 	uint_t ttop = 0;
9726 	size_t size, ksize;
9727 	uint_t id, i;
9728 
9729 	for (pc = 0; pc < dp->dtdo_len; pc++) {
9730 		dif_instr_t instr = text[pc];
9731 		uint_t op = DIF_INSTR_OP(instr);
9732 		uint_t rd = DIF_INSTR_RD(instr);
9733 		uint_t r1 = DIF_INSTR_R1(instr);
9734 		uint_t nkeys = 0;
9735 		uchar_t scope;
9736 
9737 		dtrace_key_t *key = tupregs;
9738 
9739 		switch (op) {
9740 		case DIF_OP_SETX:
9741 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9742 			srd = rd;
9743 			continue;
9744 
9745 		case DIF_OP_STTS:
9746 			key = &tupregs[DIF_DTR_NREGS];
9747 			key[0].dttk_size = 0;
9748 			key[1].dttk_size = 0;
9749 			nkeys = 2;
9750 			scope = DIFV_SCOPE_THREAD;
9751 			break;
9752 
9753 		case DIF_OP_STGAA:
9754 		case DIF_OP_STTAA:
9755 			nkeys = ttop;
9756 
9757 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9758 				key[nkeys++].dttk_size = 0;
9759 
9760 			key[nkeys++].dttk_size = 0;
9761 
9762 			if (op == DIF_OP_STTAA) {
9763 				scope = DIFV_SCOPE_THREAD;
9764 			} else {
9765 				scope = DIFV_SCOPE_GLOBAL;
9766 			}
9767 
9768 			break;
9769 
9770 		case DIF_OP_PUSHTR:
9771 			if (ttop == DIF_DTR_NREGS)
9772 				return;
9773 
9774 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9775 				/*
9776 				 * If the register for the size of the "pushtr"
9777 				 * is %r0 (or the value is 0) and the type is
9778 				 * a string, we'll use the system-wide default
9779 				 * string size.
9780 				 */
9781 				tupregs[ttop++].dttk_size =
9782 				    dtrace_strsize_default;
9783 			} else {
9784 				if (srd == 0)
9785 					return;
9786 
9787 				if (sval > LONG_MAX)
9788 					return;
9789 
9790 				tupregs[ttop++].dttk_size = sval;
9791 			}
9792 
9793 			break;
9794 
9795 		case DIF_OP_PUSHTV:
9796 			if (ttop == DIF_DTR_NREGS)
9797 				return;
9798 
9799 			tupregs[ttop++].dttk_size = 0;
9800 			break;
9801 
9802 		case DIF_OP_FLUSHTS:
9803 			ttop = 0;
9804 			break;
9805 
9806 		case DIF_OP_POPTS:
9807 			if (ttop != 0)
9808 				ttop--;
9809 			break;
9810 		}
9811 
9812 		sval = 0;
9813 		srd = 0;
9814 
9815 		if (nkeys == 0)
9816 			continue;
9817 
9818 		/*
9819 		 * We have a dynamic variable allocation; calculate its size.
9820 		 */
9821 		for (ksize = 0, i = 0; i < nkeys; i++)
9822 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9823 
9824 		size = sizeof (dtrace_dynvar_t);
9825 		size += sizeof (dtrace_key_t) * (nkeys - 1);
9826 		size += ksize;
9827 
9828 		/*
9829 		 * Now we need to determine the size of the stored data.
9830 		 */
9831 		id = DIF_INSTR_VAR(instr);
9832 
9833 		for (i = 0; i < dp->dtdo_varlen; i++) {
9834 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
9835 
9836 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
9837 				size += v->dtdv_type.dtdt_size;
9838 				break;
9839 			}
9840 		}
9841 
9842 		if (i == dp->dtdo_varlen)
9843 			return;
9844 
9845 		/*
9846 		 * We have the size.  If this is larger than the chunk size
9847 		 * for our dynamic variable state, reset the chunk size.
9848 		 */
9849 		size = P2ROUNDUP(size, sizeof (uint64_t));
9850 
9851 		/*
9852 		 * Before setting the chunk size, check that we're not going
9853 		 * to set it to a negative value...
9854 		 */
9855 		if (size > LONG_MAX)
9856 			return;
9857 
9858 		/*
9859 		 * ...and make certain that we didn't badly overflow.
9860 		 */
9861 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
9862 			return;
9863 
9864 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
9865 			vstate->dtvs_dynvars.dtds_chunksize = size;
9866 	}
9867 }
9868 
9869 static void
9870 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9871 {
9872 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
9873 	uint_t id;
9874 
9875 	ASSERT(MUTEX_HELD(&dtrace_lock));
9876 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9877 
9878 	for (i = 0; i < dp->dtdo_varlen; i++) {
9879 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9880 		dtrace_statvar_t *svar, ***svarp;
9881 		size_t dsize = 0;
9882 		uint8_t scope = v->dtdv_scope;
9883 		int *np;
9884 
9885 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9886 			continue;
9887 
9888 		id -= DIF_VAR_OTHER_UBASE;
9889 
9890 		switch (scope) {
9891 		case DIFV_SCOPE_THREAD:
9892 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9893 				dtrace_difv_t *tlocals;
9894 
9895 				if ((ntlocals = (otlocals << 1)) == 0)
9896 					ntlocals = 1;
9897 
9898 				osz = otlocals * sizeof (dtrace_difv_t);
9899 				nsz = ntlocals * sizeof (dtrace_difv_t);
9900 
9901 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
9902 
9903 				if (osz != 0) {
9904 					bcopy(vstate->dtvs_tlocals,
9905 					    tlocals, osz);
9906 					kmem_free(vstate->dtvs_tlocals, osz);
9907 				}
9908 
9909 				vstate->dtvs_tlocals = tlocals;
9910 				vstate->dtvs_ntlocals = ntlocals;
9911 			}
9912 
9913 			vstate->dtvs_tlocals[id] = *v;
9914 			continue;
9915 
9916 		case DIFV_SCOPE_LOCAL:
9917 			np = &vstate->dtvs_nlocals;
9918 			svarp = &vstate->dtvs_locals;
9919 
9920 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9921 				dsize = NCPU * (v->dtdv_type.dtdt_size +
9922 				    sizeof (uint64_t));
9923 			else
9924 				dsize = NCPU * sizeof (uint64_t);
9925 
9926 			break;
9927 
9928 		case DIFV_SCOPE_GLOBAL:
9929 			np = &vstate->dtvs_nglobals;
9930 			svarp = &vstate->dtvs_globals;
9931 
9932 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9933 				dsize = v->dtdv_type.dtdt_size +
9934 				    sizeof (uint64_t);
9935 
9936 			break;
9937 
9938 		default:
9939 			ASSERT(0);
9940 		}
9941 
9942 		while (id >= (oldsvars = *np)) {
9943 			dtrace_statvar_t **statics;
9944 			int newsvars, oldsize, newsize;
9945 
9946 			if ((newsvars = (oldsvars << 1)) == 0)
9947 				newsvars = 1;
9948 
9949 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9950 			newsize = newsvars * sizeof (dtrace_statvar_t *);
9951 
9952 			statics = kmem_zalloc(newsize, KM_SLEEP);
9953 
9954 			if (oldsize != 0) {
9955 				bcopy(*svarp, statics, oldsize);
9956 				kmem_free(*svarp, oldsize);
9957 			}
9958 
9959 			*svarp = statics;
9960 			*np = newsvars;
9961 		}
9962 
9963 		if ((svar = (*svarp)[id]) == NULL) {
9964 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9965 			svar->dtsv_var = *v;
9966 
9967 			if ((svar->dtsv_size = dsize) != 0) {
9968 				svar->dtsv_data = (uint64_t)(uintptr_t)
9969 				    kmem_zalloc(dsize, KM_SLEEP);
9970 			}
9971 
9972 			(*svarp)[id] = svar;
9973 		}
9974 
9975 		svar->dtsv_refcnt++;
9976 	}
9977 
9978 	dtrace_difo_chunksize(dp, vstate);
9979 	dtrace_difo_hold(dp);
9980 }
9981 
9982 static dtrace_difo_t *
9983 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9984 {
9985 	dtrace_difo_t *new;
9986 	size_t sz;
9987 
9988 	ASSERT(dp->dtdo_buf != NULL);
9989 	ASSERT(dp->dtdo_refcnt != 0);
9990 
9991 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9992 
9993 	ASSERT(dp->dtdo_buf != NULL);
9994 	sz = dp->dtdo_len * sizeof (dif_instr_t);
9995 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9996 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9997 	new->dtdo_len = dp->dtdo_len;
9998 
9999 	if (dp->dtdo_strtab != NULL) {
10000 		ASSERT(dp->dtdo_strlen != 0);
10001 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10002 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10003 		new->dtdo_strlen = dp->dtdo_strlen;
10004 	}
10005 
10006 	if (dp->dtdo_inttab != NULL) {
10007 		ASSERT(dp->dtdo_intlen != 0);
10008 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10009 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10010 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10011 		new->dtdo_intlen = dp->dtdo_intlen;
10012 	}
10013 
10014 	if (dp->dtdo_vartab != NULL) {
10015 		ASSERT(dp->dtdo_varlen != 0);
10016 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10017 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10018 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10019 		new->dtdo_varlen = dp->dtdo_varlen;
10020 	}
10021 
10022 	dtrace_difo_init(new, vstate);
10023 	return (new);
10024 }
10025 
10026 static void
10027 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10028 {
10029 	int i;
10030 
10031 	ASSERT(dp->dtdo_refcnt == 0);
10032 
10033 	for (i = 0; i < dp->dtdo_varlen; i++) {
10034 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10035 		dtrace_statvar_t *svar, **svarp;
10036 		uint_t id;
10037 		uint8_t scope = v->dtdv_scope;
10038 		int *np;
10039 
10040 		switch (scope) {
10041 		case DIFV_SCOPE_THREAD:
10042 			continue;
10043 
10044 		case DIFV_SCOPE_LOCAL:
10045 			np = &vstate->dtvs_nlocals;
10046 			svarp = vstate->dtvs_locals;
10047 			break;
10048 
10049 		case DIFV_SCOPE_GLOBAL:
10050 			np = &vstate->dtvs_nglobals;
10051 			svarp = vstate->dtvs_globals;
10052 			break;
10053 
10054 		default:
10055 			ASSERT(0);
10056 		}
10057 
10058 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10059 			continue;
10060 
10061 		id -= DIF_VAR_OTHER_UBASE;
10062 		ASSERT(id < *np);
10063 
10064 		svar = svarp[id];
10065 		ASSERT(svar != NULL);
10066 		ASSERT(svar->dtsv_refcnt > 0);
10067 
10068 		if (--svar->dtsv_refcnt > 0)
10069 			continue;
10070 
10071 		if (svar->dtsv_size != 0) {
10072 			ASSERT(svar->dtsv_data != NULL);
10073 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10074 			    svar->dtsv_size);
10075 		}
10076 
10077 		kmem_free(svar, sizeof (dtrace_statvar_t));
10078 		svarp[id] = NULL;
10079 	}
10080 
10081 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10082 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10083 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10084 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10085 
10086 	kmem_free(dp, sizeof (dtrace_difo_t));
10087 }
10088 
10089 static void
10090 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10091 {
10092 	int i;
10093 
10094 	ASSERT(MUTEX_HELD(&dtrace_lock));
10095 	ASSERT(dp->dtdo_refcnt != 0);
10096 
10097 	for (i = 0; i < dp->dtdo_varlen; i++) {
10098 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10099 
10100 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10101 			continue;
10102 
10103 		ASSERT(dtrace_vtime_references > 0);
10104 		if (--dtrace_vtime_references == 0)
10105 			dtrace_vtime_disable();
10106 	}
10107 
10108 	if (--dp->dtdo_refcnt == 0)
10109 		dtrace_difo_destroy(dp, vstate);
10110 }
10111 
10112 /*
10113  * DTrace Format Functions
10114  */
10115 static uint16_t
10116 dtrace_format_add(dtrace_state_t *state, char *str)
10117 {
10118 	char *fmt, **new;
10119 	uint16_t ndx, len = strlen(str) + 1;
10120 
10121 	fmt = kmem_zalloc(len, KM_SLEEP);
10122 	bcopy(str, fmt, len);
10123 
10124 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10125 		if (state->dts_formats[ndx] == NULL) {
10126 			state->dts_formats[ndx] = fmt;
10127 			return (ndx + 1);
10128 		}
10129 	}
10130 
10131 	if (state->dts_nformats == USHRT_MAX) {
10132 		/*
10133 		 * This is only likely if a denial-of-service attack is being
10134 		 * attempted.  As such, it's okay to fail silently here.
10135 		 */
10136 		kmem_free(fmt, len);
10137 		return (0);
10138 	}
10139 
10140 	/*
10141 	 * For simplicity, we always resize the formats array to be exactly the
10142 	 * number of formats.
10143 	 */
10144 	ndx = state->dts_nformats++;
10145 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10146 
10147 	if (state->dts_formats != NULL) {
10148 		ASSERT(ndx != 0);
10149 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
10150 		kmem_free(state->dts_formats, ndx * sizeof (char *));
10151 	}
10152 
10153 	state->dts_formats = new;
10154 	state->dts_formats[ndx] = fmt;
10155 
10156 	return (ndx + 1);
10157 }
10158 
10159 static void
10160 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10161 {
10162 	char *fmt;
10163 
10164 	ASSERT(state->dts_formats != NULL);
10165 	ASSERT(format <= state->dts_nformats);
10166 	ASSERT(state->dts_formats[format - 1] != NULL);
10167 
10168 	fmt = state->dts_formats[format - 1];
10169 	kmem_free(fmt, strlen(fmt) + 1);
10170 	state->dts_formats[format - 1] = NULL;
10171 }
10172 
10173 static void
10174 dtrace_format_destroy(dtrace_state_t *state)
10175 {
10176 	int i;
10177 
10178 	if (state->dts_nformats == 0) {
10179 		ASSERT(state->dts_formats == NULL);
10180 		return;
10181 	}
10182 
10183 	ASSERT(state->dts_formats != NULL);
10184 
10185 	for (i = 0; i < state->dts_nformats; i++) {
10186 		char *fmt = state->dts_formats[i];
10187 
10188 		if (fmt == NULL)
10189 			continue;
10190 
10191 		kmem_free(fmt, strlen(fmt) + 1);
10192 	}
10193 
10194 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10195 	state->dts_nformats = 0;
10196 	state->dts_formats = NULL;
10197 }
10198 
10199 /*
10200  * DTrace Predicate Functions
10201  */
10202 static dtrace_predicate_t *
10203 dtrace_predicate_create(dtrace_difo_t *dp)
10204 {
10205 	dtrace_predicate_t *pred;
10206 
10207 	ASSERT(MUTEX_HELD(&dtrace_lock));
10208 	ASSERT(dp->dtdo_refcnt != 0);
10209 
10210 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10211 	pred->dtp_difo = dp;
10212 	pred->dtp_refcnt = 1;
10213 
10214 	if (!dtrace_difo_cacheable(dp))
10215 		return (pred);
10216 
10217 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10218 		/*
10219 		 * This is only theoretically possible -- we have had 2^32
10220 		 * cacheable predicates on this machine.  We cannot allow any
10221 		 * more predicates to become cacheable:  as unlikely as it is,
10222 		 * there may be a thread caching a (now stale) predicate cache
10223 		 * ID. (N.B.: the temptation is being successfully resisted to
10224 		 * have this cmn_err() "Holy shit -- we executed this code!")
10225 		 */
10226 		return (pred);
10227 	}
10228 
10229 	pred->dtp_cacheid = dtrace_predcache_id++;
10230 
10231 	return (pred);
10232 }
10233 
10234 static void
10235 dtrace_predicate_hold(dtrace_predicate_t *pred)
10236 {
10237 	ASSERT(MUTEX_HELD(&dtrace_lock));
10238 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10239 	ASSERT(pred->dtp_refcnt > 0);
10240 
10241 	pred->dtp_refcnt++;
10242 }
10243 
10244 static void
10245 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10246 {
10247 	dtrace_difo_t *dp = pred->dtp_difo;
10248 
10249 	ASSERT(MUTEX_HELD(&dtrace_lock));
10250 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10251 	ASSERT(pred->dtp_refcnt > 0);
10252 
10253 	if (--pred->dtp_refcnt == 0) {
10254 		dtrace_difo_release(pred->dtp_difo, vstate);
10255 		kmem_free(pred, sizeof (dtrace_predicate_t));
10256 	}
10257 }
10258 
10259 /*
10260  * DTrace Action Description Functions
10261  */
10262 static dtrace_actdesc_t *
10263 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10264     uint64_t uarg, uint64_t arg)
10265 {
10266 	dtrace_actdesc_t *act;
10267 
10268 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
10269 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
10270 
10271 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10272 	act->dtad_kind = kind;
10273 	act->dtad_ntuple = ntuple;
10274 	act->dtad_uarg = uarg;
10275 	act->dtad_arg = arg;
10276 	act->dtad_refcnt = 1;
10277 
10278 	return (act);
10279 }
10280 
10281 static void
10282 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10283 {
10284 	ASSERT(act->dtad_refcnt >= 1);
10285 	act->dtad_refcnt++;
10286 }
10287 
10288 static void
10289 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10290 {
10291 	dtrace_actkind_t kind = act->dtad_kind;
10292 	dtrace_difo_t *dp;
10293 
10294 	ASSERT(act->dtad_refcnt >= 1);
10295 
10296 	if (--act->dtad_refcnt != 0)
10297 		return;
10298 
10299 	if ((dp = act->dtad_difo) != NULL)
10300 		dtrace_difo_release(dp, vstate);
10301 
10302 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
10303 		char *str = (char *)(uintptr_t)act->dtad_arg;
10304 
10305 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10306 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10307 
10308 		if (str != NULL)
10309 			kmem_free(str, strlen(str) + 1);
10310 	}
10311 
10312 	kmem_free(act, sizeof (dtrace_actdesc_t));
10313 }
10314 
10315 /*
10316  * DTrace ECB Functions
10317  */
10318 static dtrace_ecb_t *
10319 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10320 {
10321 	dtrace_ecb_t *ecb;
10322 	dtrace_epid_t epid;
10323 
10324 	ASSERT(MUTEX_HELD(&dtrace_lock));
10325 
10326 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10327 	ecb->dte_predicate = NULL;
10328 	ecb->dte_probe = probe;
10329 
10330 	/*
10331 	 * The default size is the size of the default action: recording
10332 	 * the header.
10333 	 */
10334 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10335 	ecb->dte_alignment = sizeof (dtrace_epid_t);
10336 
10337 	epid = state->dts_epid++;
10338 
10339 	if (epid - 1 >= state->dts_necbs) {
10340 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10341 		int necbs = state->dts_necbs << 1;
10342 
10343 		ASSERT(epid == state->dts_necbs + 1);
10344 
10345 		if (necbs == 0) {
10346 			ASSERT(oecbs == NULL);
10347 			necbs = 1;
10348 		}
10349 
10350 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10351 
10352 		if (oecbs != NULL)
10353 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10354 
10355 		dtrace_membar_producer();
10356 		state->dts_ecbs = ecbs;
10357 
10358 		if (oecbs != NULL) {
10359 			/*
10360 			 * If this state is active, we must dtrace_sync()
10361 			 * before we can free the old dts_ecbs array:  we're
10362 			 * coming in hot, and there may be active ring
10363 			 * buffer processing (which indexes into the dts_ecbs
10364 			 * array) on another CPU.
10365 			 */
10366 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10367 				dtrace_sync();
10368 
10369 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10370 		}
10371 
10372 		dtrace_membar_producer();
10373 		state->dts_necbs = necbs;
10374 	}
10375 
10376 	ecb->dte_state = state;
10377 
10378 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
10379 	dtrace_membar_producer();
10380 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10381 
10382 	return (ecb);
10383 }
10384 
10385 static int
10386 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10387 {
10388 	dtrace_probe_t *probe = ecb->dte_probe;
10389 
10390 	ASSERT(MUTEX_HELD(&cpu_lock));
10391 	ASSERT(MUTEX_HELD(&dtrace_lock));
10392 	ASSERT(ecb->dte_next == NULL);
10393 
10394 	if (probe == NULL) {
10395 		/*
10396 		 * This is the NULL probe -- there's nothing to do.
10397 		 */
10398 		return (0);
10399 	}
10400 
10401 	if (probe->dtpr_ecb == NULL) {
10402 		dtrace_provider_t *prov = probe->dtpr_provider;
10403 
10404 		/*
10405 		 * We're the first ECB on this probe.
10406 		 */
10407 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10408 
10409 		if (ecb->dte_predicate != NULL)
10410 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10411 
10412 		return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10413 		    probe->dtpr_id, probe->dtpr_arg));
10414 	} else {
10415 		/*
10416 		 * This probe is already active.  Swing the last pointer to
10417 		 * point to the new ECB, and issue a dtrace_sync() to assure
10418 		 * that all CPUs have seen the change.
10419 		 */
10420 		ASSERT(probe->dtpr_ecb_last != NULL);
10421 		probe->dtpr_ecb_last->dte_next = ecb;
10422 		probe->dtpr_ecb_last = ecb;
10423 		probe->dtpr_predcache = 0;
10424 
10425 		dtrace_sync();
10426 		return (0);
10427 	}
10428 }
10429 
10430 static void
10431 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10432 {
10433 	dtrace_action_t *act;
10434 	uint32_t curneeded = UINT32_MAX;
10435 	uint32_t aggbase = UINT32_MAX;
10436 
10437 	/*
10438 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
10439 	 * we always record it first.)
10440 	 */
10441 	ecb->dte_size = sizeof (dtrace_rechdr_t);
10442 	ecb->dte_alignment = sizeof (dtrace_epid_t);
10443 
10444 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10445 		dtrace_recdesc_t *rec = &act->dta_rec;
10446 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10447 
10448 		ecb->dte_alignment = MAX(ecb->dte_alignment,
10449 		    rec->dtrd_alignment);
10450 
10451 		if (DTRACEACT_ISAGG(act->dta_kind)) {
10452 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10453 
10454 			ASSERT(rec->dtrd_size != 0);
10455 			ASSERT(agg->dtag_first != NULL);
10456 			ASSERT(act->dta_prev->dta_intuple);
10457 			ASSERT(aggbase != UINT32_MAX);
10458 			ASSERT(curneeded != UINT32_MAX);
10459 
10460 			agg->dtag_base = aggbase;
10461 
10462 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10463 			rec->dtrd_offset = curneeded;
10464 			curneeded += rec->dtrd_size;
10465 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10466 
10467 			aggbase = UINT32_MAX;
10468 			curneeded = UINT32_MAX;
10469 		} else if (act->dta_intuple) {
10470 			if (curneeded == UINT32_MAX) {
10471 				/*
10472 				 * This is the first record in a tuple.  Align
10473 				 * curneeded to be at offset 4 in an 8-byte
10474 				 * aligned block.
10475 				 */
10476 				ASSERT(act->dta_prev == NULL ||
10477 				    !act->dta_prev->dta_intuple);
10478 				ASSERT3U(aggbase, ==, UINT32_MAX);
10479 				curneeded = P2PHASEUP(ecb->dte_size,
10480 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
10481 
10482 				aggbase = curneeded - sizeof (dtrace_aggid_t);
10483 				ASSERT(IS_P2ALIGNED(aggbase,
10484 				    sizeof (uint64_t)));
10485 			}
10486 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10487 			rec->dtrd_offset = curneeded;
10488 			curneeded += rec->dtrd_size;
10489 		} else {
10490 			/* tuples must be followed by an aggregation */
10491 			ASSERT(act->dta_prev == NULL ||
10492 			    !act->dta_prev->dta_intuple);
10493 
10494 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10495 			    rec->dtrd_alignment);
10496 			rec->dtrd_offset = ecb->dte_size;
10497 			ecb->dte_size += rec->dtrd_size;
10498 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10499 		}
10500 	}
10501 
10502 	if ((act = ecb->dte_action) != NULL &&
10503 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10504 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10505 		/*
10506 		 * If the size is still sizeof (dtrace_rechdr_t), then all
10507 		 * actions store no data; set the size to 0.
10508 		 */
10509 		ecb->dte_size = 0;
10510 	}
10511 
10512 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10513 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10514 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10515 	    ecb->dte_needed);
10516 }
10517 
10518 static dtrace_action_t *
10519 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10520 {
10521 	dtrace_aggregation_t *agg;
10522 	size_t size = sizeof (uint64_t);
10523 	int ntuple = desc->dtad_ntuple;
10524 	dtrace_action_t *act;
10525 	dtrace_recdesc_t *frec;
10526 	dtrace_aggid_t aggid;
10527 	dtrace_state_t *state = ecb->dte_state;
10528 
10529 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10530 	agg->dtag_ecb = ecb;
10531 
10532 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10533 
10534 	switch (desc->dtad_kind) {
10535 	case DTRACEAGG_MIN:
10536 		agg->dtag_initial = INT64_MAX;
10537 		agg->dtag_aggregate = dtrace_aggregate_min;
10538 		break;
10539 
10540 	case DTRACEAGG_MAX:
10541 		agg->dtag_initial = INT64_MIN;
10542 		agg->dtag_aggregate = dtrace_aggregate_max;
10543 		break;
10544 
10545 	case DTRACEAGG_COUNT:
10546 		agg->dtag_aggregate = dtrace_aggregate_count;
10547 		break;
10548 
10549 	case DTRACEAGG_QUANTIZE:
10550 		agg->dtag_aggregate = dtrace_aggregate_quantize;
10551 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10552 		    sizeof (uint64_t);
10553 		break;
10554 
10555 	case DTRACEAGG_LQUANTIZE: {
10556 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10557 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10558 
10559 		agg->dtag_initial = desc->dtad_arg;
10560 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
10561 
10562 		if (step == 0 || levels == 0)
10563 			goto err;
10564 
10565 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10566 		break;
10567 	}
10568 
10569 	case DTRACEAGG_LLQUANTIZE: {
10570 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10571 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10572 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10573 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10574 		int64_t v;
10575 
10576 		agg->dtag_initial = desc->dtad_arg;
10577 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
10578 
10579 		if (factor < 2 || low >= high || nsteps < factor)
10580 			goto err;
10581 
10582 		/*
10583 		 * Now check that the number of steps evenly divides a power
10584 		 * of the factor.  (This assures both integer bucket size and
10585 		 * linearity within each magnitude.)
10586 		 */
10587 		for (v = factor; v < nsteps; v *= factor)
10588 			continue;
10589 
10590 		if ((v % nsteps) || (nsteps % factor))
10591 			goto err;
10592 
10593 		size = (dtrace_aggregate_llquantize_bucket(factor,
10594 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10595 		break;
10596 	}
10597 
10598 	case DTRACEAGG_AVG:
10599 		agg->dtag_aggregate = dtrace_aggregate_avg;
10600 		size = sizeof (uint64_t) * 2;
10601 		break;
10602 
10603 	case DTRACEAGG_STDDEV:
10604 		agg->dtag_aggregate = dtrace_aggregate_stddev;
10605 		size = sizeof (uint64_t) * 4;
10606 		break;
10607 
10608 	case DTRACEAGG_SUM:
10609 		agg->dtag_aggregate = dtrace_aggregate_sum;
10610 		break;
10611 
10612 	default:
10613 		goto err;
10614 	}
10615 
10616 	agg->dtag_action.dta_rec.dtrd_size = size;
10617 
10618 	if (ntuple == 0)
10619 		goto err;
10620 
10621 	/*
10622 	 * We must make sure that we have enough actions for the n-tuple.
10623 	 */
10624 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10625 		if (DTRACEACT_ISAGG(act->dta_kind))
10626 			break;
10627 
10628 		if (--ntuple == 0) {
10629 			/*
10630 			 * This is the action with which our n-tuple begins.
10631 			 */
10632 			agg->dtag_first = act;
10633 			goto success;
10634 		}
10635 	}
10636 
10637 	/*
10638 	 * This n-tuple is short by ntuple elements.  Return failure.
10639 	 */
10640 	ASSERT(ntuple != 0);
10641 err:
10642 	kmem_free(agg, sizeof (dtrace_aggregation_t));
10643 	return (NULL);
10644 
10645 success:
10646 	/*
10647 	 * If the last action in the tuple has a size of zero, it's actually
10648 	 * an expression argument for the aggregating action.
10649 	 */
10650 	ASSERT(ecb->dte_action_last != NULL);
10651 	act = ecb->dte_action_last;
10652 
10653 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
10654 		ASSERT(act->dta_difo != NULL);
10655 
10656 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10657 			agg->dtag_hasarg = 1;
10658 	}
10659 
10660 	/*
10661 	 * We need to allocate an id for this aggregation.
10662 	 */
10663 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10664 	    VM_BESTFIT | VM_SLEEP);
10665 
10666 	if (aggid - 1 >= state->dts_naggregations) {
10667 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
10668 		dtrace_aggregation_t **aggs;
10669 		int naggs = state->dts_naggregations << 1;
10670 		int onaggs = state->dts_naggregations;
10671 
10672 		ASSERT(aggid == state->dts_naggregations + 1);
10673 
10674 		if (naggs == 0) {
10675 			ASSERT(oaggs == NULL);
10676 			naggs = 1;
10677 		}
10678 
10679 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10680 
10681 		if (oaggs != NULL) {
10682 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10683 			kmem_free(oaggs, onaggs * sizeof (*aggs));
10684 		}
10685 
10686 		state->dts_aggregations = aggs;
10687 		state->dts_naggregations = naggs;
10688 	}
10689 
10690 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10691 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10692 
10693 	frec = &agg->dtag_first->dta_rec;
10694 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10695 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10696 
10697 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10698 		ASSERT(!act->dta_intuple);
10699 		act->dta_intuple = 1;
10700 	}
10701 
10702 	return (&agg->dtag_action);
10703 }
10704 
10705 static void
10706 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10707 {
10708 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10709 	dtrace_state_t *state = ecb->dte_state;
10710 	dtrace_aggid_t aggid = agg->dtag_id;
10711 
10712 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10713 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10714 
10715 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
10716 	state->dts_aggregations[aggid - 1] = NULL;
10717 
10718 	kmem_free(agg, sizeof (dtrace_aggregation_t));
10719 }
10720 
10721 static int
10722 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10723 {
10724 	dtrace_action_t *action, *last;
10725 	dtrace_difo_t *dp = desc->dtad_difo;
10726 	uint32_t size = 0, align = sizeof (uint8_t), mask;
10727 	uint16_t format = 0;
10728 	dtrace_recdesc_t *rec;
10729 	dtrace_state_t *state = ecb->dte_state;
10730 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
10731 	uint64_t arg = desc->dtad_arg;
10732 
10733 	ASSERT(MUTEX_HELD(&dtrace_lock));
10734 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10735 
10736 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10737 		/*
10738 		 * If this is an aggregating action, there must be neither
10739 		 * a speculate nor a commit on the action chain.
10740 		 */
10741 		dtrace_action_t *act;
10742 
10743 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10744 			if (act->dta_kind == DTRACEACT_COMMIT)
10745 				return (EINVAL);
10746 
10747 			if (act->dta_kind == DTRACEACT_SPECULATE)
10748 				return (EINVAL);
10749 		}
10750 
10751 		action = dtrace_ecb_aggregation_create(ecb, desc);
10752 
10753 		if (action == NULL)
10754 			return (EINVAL);
10755 	} else {
10756 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10757 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10758 		    dp != NULL && dp->dtdo_destructive)) {
10759 			state->dts_destructive = 1;
10760 		}
10761 
10762 		switch (desc->dtad_kind) {
10763 		case DTRACEACT_PRINTF:
10764 		case DTRACEACT_PRINTA:
10765 		case DTRACEACT_SYSTEM:
10766 		case DTRACEACT_FREOPEN:
10767 		case DTRACEACT_DIFEXPR:
10768 			/*
10769 			 * We know that our arg is a string -- turn it into a
10770 			 * format.
10771 			 */
10772 			if (arg == NULL) {
10773 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10774 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
10775 				format = 0;
10776 			} else {
10777 				ASSERT(arg != NULL);
10778 				ASSERT(arg > KERNELBASE);
10779 				format = dtrace_format_add(state,
10780 				    (char *)(uintptr_t)arg);
10781 			}
10782 
10783 			/*FALLTHROUGH*/
10784 		case DTRACEACT_LIBACT:
10785 		case DTRACEACT_TRACEMEM:
10786 		case DTRACEACT_TRACEMEM_DYNSIZE:
10787 			if (dp == NULL)
10788 				return (EINVAL);
10789 
10790 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10791 				break;
10792 
10793 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10794 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10795 					return (EINVAL);
10796 
10797 				size = opt[DTRACEOPT_STRSIZE];
10798 			}
10799 
10800 			break;
10801 
10802 		case DTRACEACT_STACK:
10803 			if ((nframes = arg) == 0) {
10804 				nframes = opt[DTRACEOPT_STACKFRAMES];
10805 				ASSERT(nframes > 0);
10806 				arg = nframes;
10807 			}
10808 
10809 			size = nframes * sizeof (pc_t);
10810 			break;
10811 
10812 		case DTRACEACT_JSTACK:
10813 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10814 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10815 
10816 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10817 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
10818 
10819 			arg = DTRACE_USTACK_ARG(nframes, strsize);
10820 
10821 			/*FALLTHROUGH*/
10822 		case DTRACEACT_USTACK:
10823 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
10824 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10825 				strsize = DTRACE_USTACK_STRSIZE(arg);
10826 				nframes = opt[DTRACEOPT_USTACKFRAMES];
10827 				ASSERT(nframes > 0);
10828 				arg = DTRACE_USTACK_ARG(nframes, strsize);
10829 			}
10830 
10831 			/*
10832 			 * Save a slot for the pid.
10833 			 */
10834 			size = (nframes + 1) * sizeof (uint64_t);
10835 			size += DTRACE_USTACK_STRSIZE(arg);
10836 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10837 
10838 			break;
10839 
10840 		case DTRACEACT_SYM:
10841 		case DTRACEACT_MOD:
10842 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10843 			    sizeof (uint64_t)) ||
10844 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10845 				return (EINVAL);
10846 			break;
10847 
10848 		case DTRACEACT_USYM:
10849 		case DTRACEACT_UMOD:
10850 		case DTRACEACT_UADDR:
10851 			if (dp == NULL ||
10852 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10853 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10854 				return (EINVAL);
10855 
10856 			/*
10857 			 * We have a slot for the pid, plus a slot for the
10858 			 * argument.  To keep things simple (aligned with
10859 			 * bitness-neutral sizing), we store each as a 64-bit
10860 			 * quantity.
10861 			 */
10862 			size = 2 * sizeof (uint64_t);
10863 			break;
10864 
10865 		case DTRACEACT_STOP:
10866 		case DTRACEACT_BREAKPOINT:
10867 		case DTRACEACT_PANIC:
10868 			break;
10869 
10870 		case DTRACEACT_CHILL:
10871 		case DTRACEACT_DISCARD:
10872 		case DTRACEACT_RAISE:
10873 			if (dp == NULL)
10874 				return (EINVAL);
10875 			break;
10876 
10877 		case DTRACEACT_EXIT:
10878 			if (dp == NULL ||
10879 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10880 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10881 				return (EINVAL);
10882 			break;
10883 
10884 		case DTRACEACT_SPECULATE:
10885 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10886 				return (EINVAL);
10887 
10888 			if (dp == NULL)
10889 				return (EINVAL);
10890 
10891 			state->dts_speculates = 1;
10892 			break;
10893 
10894 		case DTRACEACT_COMMIT: {
10895 			dtrace_action_t *act = ecb->dte_action;
10896 
10897 			for (; act != NULL; act = act->dta_next) {
10898 				if (act->dta_kind == DTRACEACT_COMMIT)
10899 					return (EINVAL);
10900 			}
10901 
10902 			if (dp == NULL)
10903 				return (EINVAL);
10904 			break;
10905 		}
10906 
10907 		default:
10908 			return (EINVAL);
10909 		}
10910 
10911 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10912 			/*
10913 			 * If this is a data-storing action or a speculate,
10914 			 * we must be sure that there isn't a commit on the
10915 			 * action chain.
10916 			 */
10917 			dtrace_action_t *act = ecb->dte_action;
10918 
10919 			for (; act != NULL; act = act->dta_next) {
10920 				if (act->dta_kind == DTRACEACT_COMMIT)
10921 					return (EINVAL);
10922 			}
10923 		}
10924 
10925 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10926 		action->dta_rec.dtrd_size = size;
10927 	}
10928 
10929 	action->dta_refcnt = 1;
10930 	rec = &action->dta_rec;
10931 	size = rec->dtrd_size;
10932 
10933 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10934 		if (!(size & mask)) {
10935 			align = mask + 1;
10936 			break;
10937 		}
10938 	}
10939 
10940 	action->dta_kind = desc->dtad_kind;
10941 
10942 	if ((action->dta_difo = dp) != NULL)
10943 		dtrace_difo_hold(dp);
10944 
10945 	rec->dtrd_action = action->dta_kind;
10946 	rec->dtrd_arg = arg;
10947 	rec->dtrd_uarg = desc->dtad_uarg;
10948 	rec->dtrd_alignment = (uint16_t)align;
10949 	rec->dtrd_format = format;
10950 
10951 	if ((last = ecb->dte_action_last) != NULL) {
10952 		ASSERT(ecb->dte_action != NULL);
10953 		action->dta_prev = last;
10954 		last->dta_next = action;
10955 	} else {
10956 		ASSERT(ecb->dte_action == NULL);
10957 		ecb->dte_action = action;
10958 	}
10959 
10960 	ecb->dte_action_last = action;
10961 
10962 	return (0);
10963 }
10964 
10965 static void
10966 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10967 {
10968 	dtrace_action_t *act = ecb->dte_action, *next;
10969 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10970 	dtrace_difo_t *dp;
10971 	uint16_t format;
10972 
10973 	if (act != NULL && act->dta_refcnt > 1) {
10974 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10975 		act->dta_refcnt--;
10976 	} else {
10977 		for (; act != NULL; act = next) {
10978 			next = act->dta_next;
10979 			ASSERT(next != NULL || act == ecb->dte_action_last);
10980 			ASSERT(act->dta_refcnt == 1);
10981 
10982 			if ((format = act->dta_rec.dtrd_format) != 0)
10983 				dtrace_format_remove(ecb->dte_state, format);
10984 
10985 			if ((dp = act->dta_difo) != NULL)
10986 				dtrace_difo_release(dp, vstate);
10987 
10988 			if (DTRACEACT_ISAGG(act->dta_kind)) {
10989 				dtrace_ecb_aggregation_destroy(ecb, act);
10990 			} else {
10991 				kmem_free(act, sizeof (dtrace_action_t));
10992 			}
10993 		}
10994 	}
10995 
10996 	ecb->dte_action = NULL;
10997 	ecb->dte_action_last = NULL;
10998 	ecb->dte_size = 0;
10999 }
11000 
11001 static void
11002 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11003 {
11004 	/*
11005 	 * We disable the ECB by removing it from its probe.
11006 	 */
11007 	dtrace_ecb_t *pecb, *prev = NULL;
11008 	dtrace_probe_t *probe = ecb->dte_probe;
11009 
11010 	ASSERT(MUTEX_HELD(&dtrace_lock));
11011 
11012 	if (probe == NULL) {
11013 		/*
11014 		 * This is the NULL probe; there is nothing to disable.
11015 		 */
11016 		return;
11017 	}
11018 
11019 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11020 		if (pecb == ecb)
11021 			break;
11022 		prev = pecb;
11023 	}
11024 
11025 	ASSERT(pecb != NULL);
11026 
11027 	if (prev == NULL) {
11028 		probe->dtpr_ecb = ecb->dte_next;
11029 	} else {
11030 		prev->dte_next = ecb->dte_next;
11031 	}
11032 
11033 	if (ecb == probe->dtpr_ecb_last) {
11034 		ASSERT(ecb->dte_next == NULL);
11035 		probe->dtpr_ecb_last = prev;
11036 	}
11037 
11038 	/*
11039 	 * The ECB has been disconnected from the probe; now sync to assure
11040 	 * that all CPUs have seen the change before returning.
11041 	 */
11042 	dtrace_sync();
11043 
11044 	if (probe->dtpr_ecb == NULL) {
11045 		/*
11046 		 * That was the last ECB on the probe; clear the predicate
11047 		 * cache ID for the probe, disable it and sync one more time
11048 		 * to assure that we'll never hit it again.
11049 		 */
11050 		dtrace_provider_t *prov = probe->dtpr_provider;
11051 
11052 		ASSERT(ecb->dte_next == NULL);
11053 		ASSERT(probe->dtpr_ecb_last == NULL);
11054 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11055 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11056 		    probe->dtpr_id, probe->dtpr_arg);
11057 		dtrace_sync();
11058 	} else {
11059 		/*
11060 		 * There is at least one ECB remaining on the probe.  If there
11061 		 * is _exactly_ one, set the probe's predicate cache ID to be
11062 		 * the predicate cache ID of the remaining ECB.
11063 		 */
11064 		ASSERT(probe->dtpr_ecb_last != NULL);
11065 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11066 
11067 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11068 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11069 
11070 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11071 
11072 			if (p != NULL)
11073 				probe->dtpr_predcache = p->dtp_cacheid;
11074 		}
11075 
11076 		ecb->dte_next = NULL;
11077 	}
11078 }
11079 
11080 static void
11081 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11082 {
11083 	dtrace_state_t *state = ecb->dte_state;
11084 	dtrace_vstate_t *vstate = &state->dts_vstate;
11085 	dtrace_predicate_t *pred;
11086 	dtrace_epid_t epid = ecb->dte_epid;
11087 
11088 	ASSERT(MUTEX_HELD(&dtrace_lock));
11089 	ASSERT(ecb->dte_next == NULL);
11090 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11091 
11092 	if ((pred = ecb->dte_predicate) != NULL)
11093 		dtrace_predicate_release(pred, vstate);
11094 
11095 	dtrace_ecb_action_remove(ecb);
11096 
11097 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11098 	state->dts_ecbs[epid - 1] = NULL;
11099 
11100 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11101 }
11102 
11103 static dtrace_ecb_t *
11104 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11105     dtrace_enabling_t *enab)
11106 {
11107 	dtrace_ecb_t *ecb;
11108 	dtrace_predicate_t *pred;
11109 	dtrace_actdesc_t *act;
11110 	dtrace_provider_t *prov;
11111 	dtrace_ecbdesc_t *desc = enab->dten_current;
11112 
11113 	ASSERT(MUTEX_HELD(&dtrace_lock));
11114 	ASSERT(state != NULL);
11115 
11116 	ecb = dtrace_ecb_add(state, probe);
11117 	ecb->dte_uarg = desc->dted_uarg;
11118 
11119 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11120 		dtrace_predicate_hold(pred);
11121 		ecb->dte_predicate = pred;
11122 	}
11123 
11124 	if (probe != NULL) {
11125 		/*
11126 		 * If the provider shows more leg than the consumer is old
11127 		 * enough to see, we need to enable the appropriate implicit
11128 		 * predicate bits to prevent the ecb from activating at
11129 		 * revealing times.
11130 		 *
11131 		 * Providers specifying DTRACE_PRIV_USER at register time
11132 		 * are stating that they need the /proc-style privilege
11133 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11134 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11135 		 */
11136 		prov = probe->dtpr_provider;
11137 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11138 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11139 			ecb->dte_cond |= DTRACE_COND_OWNER;
11140 
11141 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11142 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11143 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11144 
11145 		/*
11146 		 * If the provider shows us kernel innards and the user
11147 		 * is lacking sufficient privilege, enable the
11148 		 * DTRACE_COND_USERMODE implicit predicate.
11149 		 */
11150 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11151 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11152 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11153 	}
11154 
11155 	if (dtrace_ecb_create_cache != NULL) {
11156 		/*
11157 		 * If we have a cached ecb, we'll use its action list instead
11158 		 * of creating our own (saving both time and space).
11159 		 */
11160 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11161 		dtrace_action_t *act = cached->dte_action;
11162 
11163 		if (act != NULL) {
11164 			ASSERT(act->dta_refcnt > 0);
11165 			act->dta_refcnt++;
11166 			ecb->dte_action = act;
11167 			ecb->dte_action_last = cached->dte_action_last;
11168 			ecb->dte_needed = cached->dte_needed;
11169 			ecb->dte_size = cached->dte_size;
11170 			ecb->dte_alignment = cached->dte_alignment;
11171 		}
11172 
11173 		return (ecb);
11174 	}
11175 
11176 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11177 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11178 			dtrace_ecb_destroy(ecb);
11179 			return (NULL);
11180 		}
11181 	}
11182 
11183 	dtrace_ecb_resize(ecb);
11184 
11185 	return (dtrace_ecb_create_cache = ecb);
11186 }
11187 
11188 static int
11189 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11190 {
11191 	dtrace_ecb_t *ecb;
11192 	dtrace_enabling_t *enab = arg;
11193 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11194 
11195 	ASSERT(state != NULL);
11196 
11197 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11198 		/*
11199 		 * This probe was created in a generation for which this
11200 		 * enabling has previously created ECBs; we don't want to
11201 		 * enable it again, so just kick out.
11202 		 */
11203 		return (DTRACE_MATCH_NEXT);
11204 	}
11205 
11206 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11207 		return (DTRACE_MATCH_DONE);
11208 
11209 	if (dtrace_ecb_enable(ecb) < 0)
11210 		return (DTRACE_MATCH_FAIL);
11211 
11212 	return (DTRACE_MATCH_NEXT);
11213 }
11214 
11215 static dtrace_ecb_t *
11216 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11217 {
11218 	dtrace_ecb_t *ecb;
11219 
11220 	ASSERT(MUTEX_HELD(&dtrace_lock));
11221 
11222 	if (id == 0 || id > state->dts_necbs)
11223 		return (NULL);
11224 
11225 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11226 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11227 
11228 	return (state->dts_ecbs[id - 1]);
11229 }
11230 
11231 static dtrace_aggregation_t *
11232 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11233 {
11234 	dtrace_aggregation_t *agg;
11235 
11236 	ASSERT(MUTEX_HELD(&dtrace_lock));
11237 
11238 	if (id == 0 || id > state->dts_naggregations)
11239 		return (NULL);
11240 
11241 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11242 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11243 	    agg->dtag_id == id);
11244 
11245 	return (state->dts_aggregations[id - 1]);
11246 }
11247 
11248 /*
11249  * DTrace Buffer Functions
11250  *
11251  * The following functions manipulate DTrace buffers.  Most of these functions
11252  * are called in the context of establishing or processing consumer state;
11253  * exceptions are explicitly noted.
11254  */
11255 
11256 /*
11257  * Note:  called from cross call context.  This function switches the two
11258  * buffers on a given CPU.  The atomicity of this operation is assured by
11259  * disabling interrupts while the actual switch takes place; the disabling of
11260  * interrupts serializes the execution with any execution of dtrace_probe() on
11261  * the same CPU.
11262  */
11263 static void
11264 dtrace_buffer_switch(dtrace_buffer_t *buf)
11265 {
11266 	caddr_t tomax = buf->dtb_tomax;
11267 	caddr_t xamot = buf->dtb_xamot;
11268 	dtrace_icookie_t cookie;
11269 	hrtime_t now;
11270 
11271 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11272 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11273 
11274 	cookie = dtrace_interrupt_disable();
11275 	now = dtrace_gethrtime();
11276 	buf->dtb_tomax = xamot;
11277 	buf->dtb_xamot = tomax;
11278 	buf->dtb_xamot_drops = buf->dtb_drops;
11279 	buf->dtb_xamot_offset = buf->dtb_offset;
11280 	buf->dtb_xamot_errors = buf->dtb_errors;
11281 	buf->dtb_xamot_flags = buf->dtb_flags;
11282 	buf->dtb_offset = 0;
11283 	buf->dtb_drops = 0;
11284 	buf->dtb_errors = 0;
11285 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11286 	buf->dtb_interval = now - buf->dtb_switched;
11287 	buf->dtb_switched = now;
11288 	dtrace_interrupt_enable(cookie);
11289 }
11290 
11291 /*
11292  * Note:  called from cross call context.  This function activates a buffer
11293  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
11294  * is guaranteed by the disabling of interrupts.
11295  */
11296 static void
11297 dtrace_buffer_activate(dtrace_state_t *state)
11298 {
11299 	dtrace_buffer_t *buf;
11300 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
11301 
11302 	buf = &state->dts_buffer[CPU->cpu_id];
11303 
11304 	if (buf->dtb_tomax != NULL) {
11305 		/*
11306 		 * We might like to assert that the buffer is marked inactive,
11307 		 * but this isn't necessarily true:  the buffer for the CPU
11308 		 * that processes the BEGIN probe has its buffer activated
11309 		 * manually.  In this case, we take the (harmless) action
11310 		 * re-clearing the bit INACTIVE bit.
11311 		 */
11312 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11313 	}
11314 
11315 	dtrace_interrupt_enable(cookie);
11316 }
11317 
11318 static int
11319 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11320     processorid_t cpu, int *factor)
11321 {
11322 	cpu_t *cp;
11323 	dtrace_buffer_t *buf;
11324 	int allocated = 0, desired = 0;
11325 
11326 	ASSERT(MUTEX_HELD(&cpu_lock));
11327 	ASSERT(MUTEX_HELD(&dtrace_lock));
11328 
11329 	*factor = 1;
11330 
11331 	if (size > dtrace_nonroot_maxsize &&
11332 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11333 		return (EFBIG);
11334 
11335 	cp = cpu_list;
11336 
11337 	do {
11338 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11339 			continue;
11340 
11341 		buf = &bufs[cp->cpu_id];
11342 
11343 		/*
11344 		 * If there is already a buffer allocated for this CPU, it
11345 		 * is only possible that this is a DR event.  In this case,
11346 		 * the buffer size must match our specified size.
11347 		 */
11348 		if (buf->dtb_tomax != NULL) {
11349 			ASSERT(buf->dtb_size == size);
11350 			continue;
11351 		}
11352 
11353 		ASSERT(buf->dtb_xamot == NULL);
11354 
11355 		if ((buf->dtb_tomax = kmem_zalloc(size,
11356 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11357 			goto err;
11358 
11359 		buf->dtb_size = size;
11360 		buf->dtb_flags = flags;
11361 		buf->dtb_offset = 0;
11362 		buf->dtb_drops = 0;
11363 
11364 		if (flags & DTRACEBUF_NOSWITCH)
11365 			continue;
11366 
11367 		if ((buf->dtb_xamot = kmem_zalloc(size,
11368 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11369 			goto err;
11370 	} while ((cp = cp->cpu_next) != cpu_list);
11371 
11372 	return (0);
11373 
11374 err:
11375 	cp = cpu_list;
11376 
11377 	do {
11378 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11379 			continue;
11380 
11381 		buf = &bufs[cp->cpu_id];
11382 		desired += 2;
11383 
11384 		if (buf->dtb_xamot != NULL) {
11385 			ASSERT(buf->dtb_tomax != NULL);
11386 			ASSERT(buf->dtb_size == size);
11387 			kmem_free(buf->dtb_xamot, size);
11388 			allocated++;
11389 		}
11390 
11391 		if (buf->dtb_tomax != NULL) {
11392 			ASSERT(buf->dtb_size == size);
11393 			kmem_free(buf->dtb_tomax, size);
11394 			allocated++;
11395 		}
11396 
11397 		buf->dtb_tomax = NULL;
11398 		buf->dtb_xamot = NULL;
11399 		buf->dtb_size = 0;
11400 	} while ((cp = cp->cpu_next) != cpu_list);
11401 
11402 	*factor = desired / (allocated > 0 ? allocated : 1);
11403 
11404 	return (ENOMEM);
11405 }
11406 
11407 /*
11408  * Note:  called from probe context.  This function just increments the drop
11409  * count on a buffer.  It has been made a function to allow for the
11410  * possibility of understanding the source of mysterious drop counts.  (A
11411  * problem for which one may be particularly disappointed that DTrace cannot
11412  * be used to understand DTrace.)
11413  */
11414 static void
11415 dtrace_buffer_drop(dtrace_buffer_t *buf)
11416 {
11417 	buf->dtb_drops++;
11418 }
11419 
11420 /*
11421  * Note:  called from probe context.  This function is called to reserve space
11422  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
11423  * mstate.  Returns the new offset in the buffer, or a negative value if an
11424  * error has occurred.
11425  */
11426 static intptr_t
11427 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11428     dtrace_state_t *state, dtrace_mstate_t *mstate)
11429 {
11430 	intptr_t offs = buf->dtb_offset, soffs;
11431 	intptr_t woffs;
11432 	caddr_t tomax;
11433 	size_t total;
11434 
11435 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11436 		return (-1);
11437 
11438 	if ((tomax = buf->dtb_tomax) == NULL) {
11439 		dtrace_buffer_drop(buf);
11440 		return (-1);
11441 	}
11442 
11443 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11444 		while (offs & (align - 1)) {
11445 			/*
11446 			 * Assert that our alignment is off by a number which
11447 			 * is itself sizeof (uint32_t) aligned.
11448 			 */
11449 			ASSERT(!((align - (offs & (align - 1))) &
11450 			    (sizeof (uint32_t) - 1)));
11451 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11452 			offs += sizeof (uint32_t);
11453 		}
11454 
11455 		if ((soffs = offs + needed) > buf->dtb_size) {
11456 			dtrace_buffer_drop(buf);
11457 			return (-1);
11458 		}
11459 
11460 		if (mstate == NULL)
11461 			return (offs);
11462 
11463 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11464 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
11465 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11466 
11467 		return (offs);
11468 	}
11469 
11470 	if (buf->dtb_flags & DTRACEBUF_FILL) {
11471 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11472 		    (buf->dtb_flags & DTRACEBUF_FULL))
11473 			return (-1);
11474 		goto out;
11475 	}
11476 
11477 	total = needed + (offs & (align - 1));
11478 
11479 	/*
11480 	 * For a ring buffer, life is quite a bit more complicated.  Before
11481 	 * we can store any padding, we need to adjust our wrapping offset.
11482 	 * (If we've never before wrapped or we're not about to, no adjustment
11483 	 * is required.)
11484 	 */
11485 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11486 	    offs + total > buf->dtb_size) {
11487 		woffs = buf->dtb_xamot_offset;
11488 
11489 		if (offs + total > buf->dtb_size) {
11490 			/*
11491 			 * We can't fit in the end of the buffer.  First, a
11492 			 * sanity check that we can fit in the buffer at all.
11493 			 */
11494 			if (total > buf->dtb_size) {
11495 				dtrace_buffer_drop(buf);
11496 				return (-1);
11497 			}
11498 
11499 			/*
11500 			 * We're going to be storing at the top of the buffer,
11501 			 * so now we need to deal with the wrapped offset.  We
11502 			 * only reset our wrapped offset to 0 if it is
11503 			 * currently greater than the current offset.  If it
11504 			 * is less than the current offset, it is because a
11505 			 * previous allocation induced a wrap -- but the
11506 			 * allocation didn't subsequently take the space due
11507 			 * to an error or false predicate evaluation.  In this
11508 			 * case, we'll just leave the wrapped offset alone: if
11509 			 * the wrapped offset hasn't been advanced far enough
11510 			 * for this allocation, it will be adjusted in the
11511 			 * lower loop.
11512 			 */
11513 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11514 				if (woffs >= offs)
11515 					woffs = 0;
11516 			} else {
11517 				woffs = 0;
11518 			}
11519 
11520 			/*
11521 			 * Now we know that we're going to be storing to the
11522 			 * top of the buffer and that there is room for us
11523 			 * there.  We need to clear the buffer from the current
11524 			 * offset to the end (there may be old gunk there).
11525 			 */
11526 			while (offs < buf->dtb_size)
11527 				tomax[offs++] = 0;
11528 
11529 			/*
11530 			 * We need to set our offset to zero.  And because we
11531 			 * are wrapping, we need to set the bit indicating as
11532 			 * much.  We can also adjust our needed space back
11533 			 * down to the space required by the ECB -- we know
11534 			 * that the top of the buffer is aligned.
11535 			 */
11536 			offs = 0;
11537 			total = needed;
11538 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
11539 		} else {
11540 			/*
11541 			 * There is room for us in the buffer, so we simply
11542 			 * need to check the wrapped offset.
11543 			 */
11544 			if (woffs < offs) {
11545 				/*
11546 				 * The wrapped offset is less than the offset.
11547 				 * This can happen if we allocated buffer space
11548 				 * that induced a wrap, but then we didn't
11549 				 * subsequently take the space due to an error
11550 				 * or false predicate evaluation.  This is
11551 				 * okay; we know that _this_ allocation isn't
11552 				 * going to induce a wrap.  We still can't
11553 				 * reset the wrapped offset to be zero,
11554 				 * however: the space may have been trashed in
11555 				 * the previous failed probe attempt.  But at
11556 				 * least the wrapped offset doesn't need to
11557 				 * be adjusted at all...
11558 				 */
11559 				goto out;
11560 			}
11561 		}
11562 
11563 		while (offs + total > woffs) {
11564 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11565 			size_t size;
11566 
11567 			if (epid == DTRACE_EPIDNONE) {
11568 				size = sizeof (uint32_t);
11569 			} else {
11570 				ASSERT3U(epid, <=, state->dts_necbs);
11571 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
11572 
11573 				size = state->dts_ecbs[epid - 1]->dte_size;
11574 			}
11575 
11576 			ASSERT(woffs + size <= buf->dtb_size);
11577 			ASSERT(size != 0);
11578 
11579 			if (woffs + size == buf->dtb_size) {
11580 				/*
11581 				 * We've reached the end of the buffer; we want
11582 				 * to set the wrapped offset to 0 and break
11583 				 * out.  However, if the offs is 0, then we're
11584 				 * in a strange edge-condition:  the amount of
11585 				 * space that we want to reserve plus the size
11586 				 * of the record that we're overwriting is
11587 				 * greater than the size of the buffer.  This
11588 				 * is problematic because if we reserve the
11589 				 * space but subsequently don't consume it (due
11590 				 * to a failed predicate or error) the wrapped
11591 				 * offset will be 0 -- yet the EPID at offset 0
11592 				 * will not be committed.  This situation is
11593 				 * relatively easy to deal with:  if we're in
11594 				 * this case, the buffer is indistinguishable
11595 				 * from one that hasn't wrapped; we need only
11596 				 * finish the job by clearing the wrapped bit,
11597 				 * explicitly setting the offset to be 0, and
11598 				 * zero'ing out the old data in the buffer.
11599 				 */
11600 				if (offs == 0) {
11601 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11602 					buf->dtb_offset = 0;
11603 					woffs = total;
11604 
11605 					while (woffs < buf->dtb_size)
11606 						tomax[woffs++] = 0;
11607 				}
11608 
11609 				woffs = 0;
11610 				break;
11611 			}
11612 
11613 			woffs += size;
11614 		}
11615 
11616 		/*
11617 		 * We have a wrapped offset.  It may be that the wrapped offset
11618 		 * has become zero -- that's okay.
11619 		 */
11620 		buf->dtb_xamot_offset = woffs;
11621 	}
11622 
11623 out:
11624 	/*
11625 	 * Now we can plow the buffer with any necessary padding.
11626 	 */
11627 	while (offs & (align - 1)) {
11628 		/*
11629 		 * Assert that our alignment is off by a number which
11630 		 * is itself sizeof (uint32_t) aligned.
11631 		 */
11632 		ASSERT(!((align - (offs & (align - 1))) &
11633 		    (sizeof (uint32_t) - 1)));
11634 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11635 		offs += sizeof (uint32_t);
11636 	}
11637 
11638 	if (buf->dtb_flags & DTRACEBUF_FILL) {
11639 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
11640 			buf->dtb_flags |= DTRACEBUF_FULL;
11641 			return (-1);
11642 		}
11643 	}
11644 
11645 	if (mstate == NULL)
11646 		return (offs);
11647 
11648 	/*
11649 	 * For ring buffers and fill buffers, the scratch space is always
11650 	 * the inactive buffer.
11651 	 */
11652 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11653 	mstate->dtms_scratch_size = buf->dtb_size;
11654 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11655 
11656 	return (offs);
11657 }
11658 
11659 static void
11660 dtrace_buffer_polish(dtrace_buffer_t *buf)
11661 {
11662 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11663 	ASSERT(MUTEX_HELD(&dtrace_lock));
11664 
11665 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11666 		return;
11667 
11668 	/*
11669 	 * We need to polish the ring buffer.  There are three cases:
11670 	 *
11671 	 * - The first (and presumably most common) is that there is no gap
11672 	 *   between the buffer offset and the wrapped offset.  In this case,
11673 	 *   there is nothing in the buffer that isn't valid data; we can
11674 	 *   mark the buffer as polished and return.
11675 	 *
11676 	 * - The second (less common than the first but still more common
11677 	 *   than the third) is that there is a gap between the buffer offset
11678 	 *   and the wrapped offset, and the wrapped offset is larger than the
11679 	 *   buffer offset.  This can happen because of an alignment issue, or
11680 	 *   can happen because of a call to dtrace_buffer_reserve() that
11681 	 *   didn't subsequently consume the buffer space.  In this case,
11682 	 *   we need to zero the data from the buffer offset to the wrapped
11683 	 *   offset.
11684 	 *
11685 	 * - The third (and least common) is that there is a gap between the
11686 	 *   buffer offset and the wrapped offset, but the wrapped offset is
11687 	 *   _less_ than the buffer offset.  This can only happen because a
11688 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
11689 	 *   was not subsequently consumed.  In this case, we need to zero the
11690 	 *   space from the offset to the end of the buffer _and_ from the
11691 	 *   top of the buffer to the wrapped offset.
11692 	 */
11693 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
11694 		bzero(buf->dtb_tomax + buf->dtb_offset,
11695 		    buf->dtb_xamot_offset - buf->dtb_offset);
11696 	}
11697 
11698 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
11699 		bzero(buf->dtb_tomax + buf->dtb_offset,
11700 		    buf->dtb_size - buf->dtb_offset);
11701 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11702 	}
11703 }
11704 
11705 /*
11706  * This routine determines if data generated at the specified time has likely
11707  * been entirely consumed at user-level.  This routine is called to determine
11708  * if an ECB on a defunct probe (but for an active enabling) can be safely
11709  * disabled and destroyed.
11710  */
11711 static int
11712 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
11713 {
11714 	int i;
11715 
11716 	for (i = 0; i < NCPU; i++) {
11717 		dtrace_buffer_t *buf = &bufs[i];
11718 
11719 		if (buf->dtb_size == 0)
11720 			continue;
11721 
11722 		if (buf->dtb_flags & DTRACEBUF_RING)
11723 			return (0);
11724 
11725 		if (!buf->dtb_switched && buf->dtb_offset != 0)
11726 			return (0);
11727 
11728 		if (buf->dtb_switched - buf->dtb_interval < when)
11729 			return (0);
11730 	}
11731 
11732 	return (1);
11733 }
11734 
11735 static void
11736 dtrace_buffer_free(dtrace_buffer_t *bufs)
11737 {
11738 	int i;
11739 
11740 	for (i = 0; i < NCPU; i++) {
11741 		dtrace_buffer_t *buf = &bufs[i];
11742 
11743 		if (buf->dtb_tomax == NULL) {
11744 			ASSERT(buf->dtb_xamot == NULL);
11745 			ASSERT(buf->dtb_size == 0);
11746 			continue;
11747 		}
11748 
11749 		if (buf->dtb_xamot != NULL) {
11750 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11751 			kmem_free(buf->dtb_xamot, buf->dtb_size);
11752 		}
11753 
11754 		kmem_free(buf->dtb_tomax, buf->dtb_size);
11755 		buf->dtb_size = 0;
11756 		buf->dtb_tomax = NULL;
11757 		buf->dtb_xamot = NULL;
11758 	}
11759 }
11760 
11761 /*
11762  * DTrace Enabling Functions
11763  */
11764 static dtrace_enabling_t *
11765 dtrace_enabling_create(dtrace_vstate_t *vstate)
11766 {
11767 	dtrace_enabling_t *enab;
11768 
11769 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11770 	enab->dten_vstate = vstate;
11771 
11772 	return (enab);
11773 }
11774 
11775 static void
11776 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11777 {
11778 	dtrace_ecbdesc_t **ndesc;
11779 	size_t osize, nsize;
11780 
11781 	/*
11782 	 * We can't add to enablings after we've enabled them, or after we've
11783 	 * retained them.
11784 	 */
11785 	ASSERT(enab->dten_probegen == 0);
11786 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11787 
11788 	if (enab->dten_ndesc < enab->dten_maxdesc) {
11789 		enab->dten_desc[enab->dten_ndesc++] = ecb;
11790 		return;
11791 	}
11792 
11793 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11794 
11795 	if (enab->dten_maxdesc == 0) {
11796 		enab->dten_maxdesc = 1;
11797 	} else {
11798 		enab->dten_maxdesc <<= 1;
11799 	}
11800 
11801 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11802 
11803 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11804 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
11805 	bcopy(enab->dten_desc, ndesc, osize);
11806 	kmem_free(enab->dten_desc, osize);
11807 
11808 	enab->dten_desc = ndesc;
11809 	enab->dten_desc[enab->dten_ndesc++] = ecb;
11810 }
11811 
11812 static void
11813 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11814     dtrace_probedesc_t *pd)
11815 {
11816 	dtrace_ecbdesc_t *new;
11817 	dtrace_predicate_t *pred;
11818 	dtrace_actdesc_t *act;
11819 
11820 	/*
11821 	 * We're going to create a new ECB description that matches the
11822 	 * specified ECB in every way, but has the specified probe description.
11823 	 */
11824 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11825 
11826 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11827 		dtrace_predicate_hold(pred);
11828 
11829 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11830 		dtrace_actdesc_hold(act);
11831 
11832 	new->dted_action = ecb->dted_action;
11833 	new->dted_pred = ecb->dted_pred;
11834 	new->dted_probe = *pd;
11835 	new->dted_uarg = ecb->dted_uarg;
11836 
11837 	dtrace_enabling_add(enab, new);
11838 }
11839 
11840 static void
11841 dtrace_enabling_dump(dtrace_enabling_t *enab)
11842 {
11843 	int i;
11844 
11845 	for (i = 0; i < enab->dten_ndesc; i++) {
11846 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11847 
11848 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11849 		    desc->dtpd_provider, desc->dtpd_mod,
11850 		    desc->dtpd_func, desc->dtpd_name);
11851 	}
11852 }
11853 
11854 static void
11855 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11856 {
11857 	int i;
11858 	dtrace_ecbdesc_t *ep;
11859 	dtrace_vstate_t *vstate = enab->dten_vstate;
11860 
11861 	ASSERT(MUTEX_HELD(&dtrace_lock));
11862 
11863 	for (i = 0; i < enab->dten_ndesc; i++) {
11864 		dtrace_actdesc_t *act, *next;
11865 		dtrace_predicate_t *pred;
11866 
11867 		ep = enab->dten_desc[i];
11868 
11869 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11870 			dtrace_predicate_release(pred, vstate);
11871 
11872 		for (act = ep->dted_action; act != NULL; act = next) {
11873 			next = act->dtad_next;
11874 			dtrace_actdesc_release(act, vstate);
11875 		}
11876 
11877 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11878 	}
11879 
11880 	kmem_free(enab->dten_desc,
11881 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11882 
11883 	/*
11884 	 * If this was a retained enabling, decrement the dts_nretained count
11885 	 * and take it off of the dtrace_retained list.
11886 	 */
11887 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11888 	    dtrace_retained == enab) {
11889 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11890 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11891 		enab->dten_vstate->dtvs_state->dts_nretained--;
11892 		dtrace_retained_gen++;
11893 	}
11894 
11895 	if (enab->dten_prev == NULL) {
11896 		if (dtrace_retained == enab) {
11897 			dtrace_retained = enab->dten_next;
11898 
11899 			if (dtrace_retained != NULL)
11900 				dtrace_retained->dten_prev = NULL;
11901 		}
11902 	} else {
11903 		ASSERT(enab != dtrace_retained);
11904 		ASSERT(dtrace_retained != NULL);
11905 		enab->dten_prev->dten_next = enab->dten_next;
11906 	}
11907 
11908 	if (enab->dten_next != NULL) {
11909 		ASSERT(dtrace_retained != NULL);
11910 		enab->dten_next->dten_prev = enab->dten_prev;
11911 	}
11912 
11913 	kmem_free(enab, sizeof (dtrace_enabling_t));
11914 }
11915 
11916 static int
11917 dtrace_enabling_retain(dtrace_enabling_t *enab)
11918 {
11919 	dtrace_state_t *state;
11920 
11921 	ASSERT(MUTEX_HELD(&dtrace_lock));
11922 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11923 	ASSERT(enab->dten_vstate != NULL);
11924 
11925 	state = enab->dten_vstate->dtvs_state;
11926 	ASSERT(state != NULL);
11927 
11928 	/*
11929 	 * We only allow each state to retain dtrace_retain_max enablings.
11930 	 */
11931 	if (state->dts_nretained >= dtrace_retain_max)
11932 		return (ENOSPC);
11933 
11934 	state->dts_nretained++;
11935 	dtrace_retained_gen++;
11936 
11937 	if (dtrace_retained == NULL) {
11938 		dtrace_retained = enab;
11939 		return (0);
11940 	}
11941 
11942 	enab->dten_next = dtrace_retained;
11943 	dtrace_retained->dten_prev = enab;
11944 	dtrace_retained = enab;
11945 
11946 	return (0);
11947 }
11948 
11949 static int
11950 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11951     dtrace_probedesc_t *create)
11952 {
11953 	dtrace_enabling_t *new, *enab;
11954 	int found = 0, err = ENOENT;
11955 
11956 	ASSERT(MUTEX_HELD(&dtrace_lock));
11957 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11958 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11959 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11960 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11961 
11962 	new = dtrace_enabling_create(&state->dts_vstate);
11963 
11964 	/*
11965 	 * Iterate over all retained enablings, looking for enablings that
11966 	 * match the specified state.
11967 	 */
11968 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11969 		int i;
11970 
11971 		/*
11972 		 * dtvs_state can only be NULL for helper enablings -- and
11973 		 * helper enablings can't be retained.
11974 		 */
11975 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11976 
11977 		if (enab->dten_vstate->dtvs_state != state)
11978 			continue;
11979 
11980 		/*
11981 		 * Now iterate over each probe description; we're looking for
11982 		 * an exact match to the specified probe description.
11983 		 */
11984 		for (i = 0; i < enab->dten_ndesc; i++) {
11985 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11986 			dtrace_probedesc_t *pd = &ep->dted_probe;
11987 
11988 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11989 				continue;
11990 
11991 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11992 				continue;
11993 
11994 			if (strcmp(pd->dtpd_func, match->dtpd_func))
11995 				continue;
11996 
11997 			if (strcmp(pd->dtpd_name, match->dtpd_name))
11998 				continue;
11999 
12000 			/*
12001 			 * We have a winning probe!  Add it to our growing
12002 			 * enabling.
12003 			 */
12004 			found = 1;
12005 			dtrace_enabling_addlike(new, ep, create);
12006 		}
12007 	}
12008 
12009 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12010 		dtrace_enabling_destroy(new);
12011 		return (err);
12012 	}
12013 
12014 	return (0);
12015 }
12016 
12017 static void
12018 dtrace_enabling_retract(dtrace_state_t *state)
12019 {
12020 	dtrace_enabling_t *enab, *next;
12021 
12022 	ASSERT(MUTEX_HELD(&dtrace_lock));
12023 
12024 	/*
12025 	 * Iterate over all retained enablings, destroy the enablings retained
12026 	 * for the specified state.
12027 	 */
12028 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12029 		next = enab->dten_next;
12030 
12031 		/*
12032 		 * dtvs_state can only be NULL for helper enablings -- and
12033 		 * helper enablings can't be retained.
12034 		 */
12035 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12036 
12037 		if (enab->dten_vstate->dtvs_state == state) {
12038 			ASSERT(state->dts_nretained > 0);
12039 			dtrace_enabling_destroy(enab);
12040 		}
12041 	}
12042 
12043 	ASSERT(state->dts_nretained == 0);
12044 }
12045 
12046 static int
12047 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12048 {
12049 	int i = 0;
12050 	int total_matched = 0, matched = 0;
12051 
12052 	ASSERT(MUTEX_HELD(&cpu_lock));
12053 	ASSERT(MUTEX_HELD(&dtrace_lock));
12054 
12055 	for (i = 0; i < enab->dten_ndesc; i++) {
12056 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12057 
12058 		enab->dten_current = ep;
12059 		enab->dten_error = 0;
12060 
12061 		/*
12062 		 * If a provider failed to enable a probe then get out and
12063 		 * let the consumer know we failed.
12064 		 */
12065 		if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
12066 			return (EBUSY);
12067 
12068 		total_matched += matched;
12069 
12070 		if (enab->dten_error != 0) {
12071 			/*
12072 			 * If we get an error half-way through enabling the
12073 			 * probes, we kick out -- perhaps with some number of
12074 			 * them enabled.  Leaving enabled probes enabled may
12075 			 * be slightly confusing for user-level, but we expect
12076 			 * that no one will attempt to actually drive on in
12077 			 * the face of such errors.  If this is an anonymous
12078 			 * enabling (indicated with a NULL nmatched pointer),
12079 			 * we cmn_err() a message.  We aren't expecting to
12080 			 * get such an error -- such as it can exist at all,
12081 			 * it would be a result of corrupted DOF in the driver
12082 			 * properties.
12083 			 */
12084 			if (nmatched == NULL) {
12085 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12086 				    "error on %p: %d", (void *)ep,
12087 				    enab->dten_error);
12088 			}
12089 
12090 			return (enab->dten_error);
12091 		}
12092 	}
12093 
12094 	enab->dten_probegen = dtrace_probegen;
12095 	if (nmatched != NULL)
12096 		*nmatched = total_matched;
12097 
12098 	return (0);
12099 }
12100 
12101 static void
12102 dtrace_enabling_matchall(void)
12103 {
12104 	dtrace_enabling_t *enab;
12105 
12106 	mutex_enter(&cpu_lock);
12107 	mutex_enter(&dtrace_lock);
12108 
12109 	/*
12110 	 * Iterate over all retained enablings to see if any probes match
12111 	 * against them.  We only perform this operation on enablings for which
12112 	 * we have sufficient permissions by virtue of being in the global zone
12113 	 * or in the same zone as the DTrace client.  Because we can be called
12114 	 * after dtrace_detach() has been called, we cannot assert that there
12115 	 * are retained enablings.  We can safely load from dtrace_retained,
12116 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
12117 	 * block pending our completion.
12118 	 */
12119 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12120 		dtrace_cred_t *dcr = &enab->dten_vstate->dtvs_state->dts_cred;
12121 		cred_t *cr = dcr->dcr_cred;
12122 		zoneid_t zone = cr != NULL ? crgetzoneid(cr) : 0;
12123 
12124 		if ((dcr->dcr_visible & DTRACE_CRV_ALLZONE) || (cr != NULL &&
12125 		    (zone == GLOBAL_ZONEID || getzoneid() == zone)))
12126 			(void) dtrace_enabling_match(enab, NULL);
12127 	}
12128 
12129 	mutex_exit(&dtrace_lock);
12130 	mutex_exit(&cpu_lock);
12131 }
12132 
12133 /*
12134  * If an enabling is to be enabled without having matched probes (that is, if
12135  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
12136  * enabling must be _primed_ by creating an ECB for every ECB description.
12137  * This must be done to assure that we know the number of speculations, the
12138  * number of aggregations, the minimum buffer size needed, etc. before we
12139  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
12140  * enabling any probes, we create ECBs for every ECB decription, but with a
12141  * NULL probe -- which is exactly what this function does.
12142  */
12143 static void
12144 dtrace_enabling_prime(dtrace_state_t *state)
12145 {
12146 	dtrace_enabling_t *enab;
12147 	int i;
12148 
12149 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12150 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12151 
12152 		if (enab->dten_vstate->dtvs_state != state)
12153 			continue;
12154 
12155 		/*
12156 		 * We don't want to prime an enabling more than once, lest
12157 		 * we allow a malicious user to induce resource exhaustion.
12158 		 * (The ECBs that result from priming an enabling aren't
12159 		 * leaked -- but they also aren't deallocated until the
12160 		 * consumer state is destroyed.)
12161 		 */
12162 		if (enab->dten_primed)
12163 			continue;
12164 
12165 		for (i = 0; i < enab->dten_ndesc; i++) {
12166 			enab->dten_current = enab->dten_desc[i];
12167 			(void) dtrace_probe_enable(NULL, enab);
12168 		}
12169 
12170 		enab->dten_primed = 1;
12171 	}
12172 }
12173 
12174 /*
12175  * Called to indicate that probes should be provided due to retained
12176  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
12177  * must take an initial lap through the enabling calling the dtps_provide()
12178  * entry point explicitly to allow for autocreated probes.
12179  */
12180 static void
12181 dtrace_enabling_provide(dtrace_provider_t *prv)
12182 {
12183 	int i, all = 0;
12184 	dtrace_probedesc_t desc;
12185 	dtrace_genid_t gen;
12186 
12187 	ASSERT(MUTEX_HELD(&dtrace_lock));
12188 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
12189 
12190 	if (prv == NULL) {
12191 		all = 1;
12192 		prv = dtrace_provider;
12193 	}
12194 
12195 	do {
12196 		dtrace_enabling_t *enab;
12197 		void *parg = prv->dtpv_arg;
12198 
12199 retry:
12200 		gen = dtrace_retained_gen;
12201 		for (enab = dtrace_retained; enab != NULL;
12202 		    enab = enab->dten_next) {
12203 			for (i = 0; i < enab->dten_ndesc; i++) {
12204 				desc = enab->dten_desc[i]->dted_probe;
12205 				mutex_exit(&dtrace_lock);
12206 				prv->dtpv_pops.dtps_provide(parg, &desc);
12207 				mutex_enter(&dtrace_lock);
12208 				/*
12209 				 * Process the retained enablings again if
12210 				 * they have changed while we weren't holding
12211 				 * dtrace_lock.
12212 				 */
12213 				if (gen != dtrace_retained_gen)
12214 					goto retry;
12215 			}
12216 		}
12217 	} while (all && (prv = prv->dtpv_next) != NULL);
12218 
12219 	mutex_exit(&dtrace_lock);
12220 	dtrace_probe_provide(NULL, all ? NULL : prv);
12221 	mutex_enter(&dtrace_lock);
12222 }
12223 
12224 /*
12225  * Called to reap ECBs that are attached to probes from defunct providers.
12226  */
12227 static void
12228 dtrace_enabling_reap(void)
12229 {
12230 	dtrace_provider_t *prov;
12231 	dtrace_probe_t *probe;
12232 	dtrace_ecb_t *ecb;
12233 	hrtime_t when;
12234 	int i;
12235 
12236 	mutex_enter(&cpu_lock);
12237 	mutex_enter(&dtrace_lock);
12238 
12239 	for (i = 0; i < dtrace_nprobes; i++) {
12240 		if ((probe = dtrace_probes[i]) == NULL)
12241 			continue;
12242 
12243 		if (probe->dtpr_ecb == NULL)
12244 			continue;
12245 
12246 		prov = probe->dtpr_provider;
12247 
12248 		if ((when = prov->dtpv_defunct) == 0)
12249 			continue;
12250 
12251 		/*
12252 		 * We have ECBs on a defunct provider:  we want to reap these
12253 		 * ECBs to allow the provider to unregister.  The destruction
12254 		 * of these ECBs must be done carefully:  if we destroy the ECB
12255 		 * and the consumer later wishes to consume an EPID that
12256 		 * corresponds to the destroyed ECB (and if the EPID metadata
12257 		 * has not been previously consumed), the consumer will abort
12258 		 * processing on the unknown EPID.  To reduce (but not, sadly,
12259 		 * eliminate) the possibility of this, we will only destroy an
12260 		 * ECB for a defunct provider if, for the state that
12261 		 * corresponds to the ECB:
12262 		 *
12263 		 *  (a)	There is no speculative tracing (which can effectively
12264 		 *	cache an EPID for an arbitrary amount of time).
12265 		 *
12266 		 *  (b)	The principal buffers have been switched twice since the
12267 		 *	provider became defunct.
12268 		 *
12269 		 *  (c)	The aggregation buffers are of zero size or have been
12270 		 *	switched twice since the provider became defunct.
12271 		 *
12272 		 * We use dts_speculates to determine (a) and call a function
12273 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
12274 		 * that as soon as we've been unable to destroy one of the ECBs
12275 		 * associated with the probe, we quit trying -- reaping is only
12276 		 * fruitful in as much as we can destroy all ECBs associated
12277 		 * with the defunct provider's probes.
12278 		 */
12279 		while ((ecb = probe->dtpr_ecb) != NULL) {
12280 			dtrace_state_t *state = ecb->dte_state;
12281 			dtrace_buffer_t *buf = state->dts_buffer;
12282 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12283 
12284 			if (state->dts_speculates)
12285 				break;
12286 
12287 			if (!dtrace_buffer_consumed(buf, when))
12288 				break;
12289 
12290 			if (!dtrace_buffer_consumed(aggbuf, when))
12291 				break;
12292 
12293 			dtrace_ecb_disable(ecb);
12294 			ASSERT(probe->dtpr_ecb != ecb);
12295 			dtrace_ecb_destroy(ecb);
12296 		}
12297 	}
12298 
12299 	mutex_exit(&dtrace_lock);
12300 	mutex_exit(&cpu_lock);
12301 }
12302 
12303 /*
12304  * DTrace DOF Functions
12305  */
12306 /*ARGSUSED*/
12307 static void
12308 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12309 {
12310 	if (dtrace_err_verbose)
12311 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
12312 
12313 #ifdef DTRACE_ERRDEBUG
12314 	dtrace_errdebug(str);
12315 #endif
12316 }
12317 
12318 /*
12319  * Create DOF out of a currently enabled state.  Right now, we only create
12320  * DOF containing the run-time options -- but this could be expanded to create
12321  * complete DOF representing the enabled state.
12322  */
12323 static dof_hdr_t *
12324 dtrace_dof_create(dtrace_state_t *state)
12325 {
12326 	dof_hdr_t *dof;
12327 	dof_sec_t *sec;
12328 	dof_optdesc_t *opt;
12329 	int i, len = sizeof (dof_hdr_t) +
12330 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12331 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12332 
12333 	ASSERT(MUTEX_HELD(&dtrace_lock));
12334 
12335 	dof = kmem_zalloc(len, KM_SLEEP);
12336 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12337 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12338 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12339 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12340 
12341 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12342 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12343 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12344 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12345 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12346 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12347 
12348 	dof->dofh_flags = 0;
12349 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
12350 	dof->dofh_secsize = sizeof (dof_sec_t);
12351 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
12352 	dof->dofh_secoff = sizeof (dof_hdr_t);
12353 	dof->dofh_loadsz = len;
12354 	dof->dofh_filesz = len;
12355 	dof->dofh_pad = 0;
12356 
12357 	/*
12358 	 * Fill in the option section header...
12359 	 */
12360 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12361 	sec->dofs_type = DOF_SECT_OPTDESC;
12362 	sec->dofs_align = sizeof (uint64_t);
12363 	sec->dofs_flags = DOF_SECF_LOAD;
12364 	sec->dofs_entsize = sizeof (dof_optdesc_t);
12365 
12366 	opt = (dof_optdesc_t *)((uintptr_t)sec +
12367 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12368 
12369 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12370 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12371 
12372 	for (i = 0; i < DTRACEOPT_MAX; i++) {
12373 		opt[i].dofo_option = i;
12374 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
12375 		opt[i].dofo_value = state->dts_options[i];
12376 	}
12377 
12378 	return (dof);
12379 }
12380 
12381 static dof_hdr_t *
12382 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12383 {
12384 	dof_hdr_t hdr, *dof;
12385 
12386 	ASSERT(!MUTEX_HELD(&dtrace_lock));
12387 
12388 	/*
12389 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
12390 	 */
12391 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
12392 		dtrace_dof_error(NULL, "failed to copyin DOF header");
12393 		*errp = EFAULT;
12394 		return (NULL);
12395 	}
12396 
12397 	/*
12398 	 * Now we'll allocate the entire DOF and copy it in -- provided
12399 	 * that the length isn't outrageous.
12400 	 */
12401 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12402 		dtrace_dof_error(&hdr, "load size exceeds maximum");
12403 		*errp = E2BIG;
12404 		return (NULL);
12405 	}
12406 
12407 	if (hdr.dofh_loadsz < sizeof (hdr)) {
12408 		dtrace_dof_error(&hdr, "invalid load size");
12409 		*errp = EINVAL;
12410 		return (NULL);
12411 	}
12412 
12413 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12414 
12415 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
12416 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
12417 		kmem_free(dof, hdr.dofh_loadsz);
12418 		*errp = EFAULT;
12419 		return (NULL);
12420 	}
12421 
12422 	return (dof);
12423 }
12424 
12425 static dof_hdr_t *
12426 dtrace_dof_property(const char *name)
12427 {
12428 	uchar_t *buf;
12429 	uint64_t loadsz;
12430 	unsigned int len, i;
12431 	dof_hdr_t *dof;
12432 
12433 	/*
12434 	 * Unfortunately, array of values in .conf files are always (and
12435 	 * only) interpreted to be integer arrays.  We must read our DOF
12436 	 * as an integer array, and then squeeze it into a byte array.
12437 	 */
12438 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12439 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12440 		return (NULL);
12441 
12442 	for (i = 0; i < len; i++)
12443 		buf[i] = (uchar_t)(((int *)buf)[i]);
12444 
12445 	if (len < sizeof (dof_hdr_t)) {
12446 		ddi_prop_free(buf);
12447 		dtrace_dof_error(NULL, "truncated header");
12448 		return (NULL);
12449 	}
12450 
12451 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12452 		ddi_prop_free(buf);
12453 		dtrace_dof_error(NULL, "truncated DOF");
12454 		return (NULL);
12455 	}
12456 
12457 	if (loadsz >= dtrace_dof_maxsize) {
12458 		ddi_prop_free(buf);
12459 		dtrace_dof_error(NULL, "oversized DOF");
12460 		return (NULL);
12461 	}
12462 
12463 	dof = kmem_alloc(loadsz, KM_SLEEP);
12464 	bcopy(buf, dof, loadsz);
12465 	ddi_prop_free(buf);
12466 
12467 	return (dof);
12468 }
12469 
12470 static void
12471 dtrace_dof_destroy(dof_hdr_t *dof)
12472 {
12473 	kmem_free(dof, dof->dofh_loadsz);
12474 }
12475 
12476 /*
12477  * Return the dof_sec_t pointer corresponding to a given section index.  If the
12478  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
12479  * a type other than DOF_SECT_NONE is specified, the header is checked against
12480  * this type and NULL is returned if the types do not match.
12481  */
12482 static dof_sec_t *
12483 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12484 {
12485 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12486 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12487 
12488 	if (i >= dof->dofh_secnum) {
12489 		dtrace_dof_error(dof, "referenced section index is invalid");
12490 		return (NULL);
12491 	}
12492 
12493 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12494 		dtrace_dof_error(dof, "referenced section is not loadable");
12495 		return (NULL);
12496 	}
12497 
12498 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12499 		dtrace_dof_error(dof, "referenced section is the wrong type");
12500 		return (NULL);
12501 	}
12502 
12503 	return (sec);
12504 }
12505 
12506 static dtrace_probedesc_t *
12507 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12508 {
12509 	dof_probedesc_t *probe;
12510 	dof_sec_t *strtab;
12511 	uintptr_t daddr = (uintptr_t)dof;
12512 	uintptr_t str;
12513 	size_t size;
12514 
12515 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12516 		dtrace_dof_error(dof, "invalid probe section");
12517 		return (NULL);
12518 	}
12519 
12520 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12521 		dtrace_dof_error(dof, "bad alignment in probe description");
12522 		return (NULL);
12523 	}
12524 
12525 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12526 		dtrace_dof_error(dof, "truncated probe description");
12527 		return (NULL);
12528 	}
12529 
12530 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12531 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12532 
12533 	if (strtab == NULL)
12534 		return (NULL);
12535 
12536 	str = daddr + strtab->dofs_offset;
12537 	size = strtab->dofs_size;
12538 
12539 	if (probe->dofp_provider >= strtab->dofs_size) {
12540 		dtrace_dof_error(dof, "corrupt probe provider");
12541 		return (NULL);
12542 	}
12543 
12544 	(void) strncpy(desc->dtpd_provider,
12545 	    (char *)(str + probe->dofp_provider),
12546 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12547 
12548 	if (probe->dofp_mod >= strtab->dofs_size) {
12549 		dtrace_dof_error(dof, "corrupt probe module");
12550 		return (NULL);
12551 	}
12552 
12553 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12554 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12555 
12556 	if (probe->dofp_func >= strtab->dofs_size) {
12557 		dtrace_dof_error(dof, "corrupt probe function");
12558 		return (NULL);
12559 	}
12560 
12561 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12562 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12563 
12564 	if (probe->dofp_name >= strtab->dofs_size) {
12565 		dtrace_dof_error(dof, "corrupt probe name");
12566 		return (NULL);
12567 	}
12568 
12569 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12570 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12571 
12572 	return (desc);
12573 }
12574 
12575 static dtrace_difo_t *
12576 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12577     cred_t *cr)
12578 {
12579 	dtrace_difo_t *dp;
12580 	size_t ttl = 0;
12581 	dof_difohdr_t *dofd;
12582 	uintptr_t daddr = (uintptr_t)dof;
12583 	size_t max = dtrace_difo_maxsize;
12584 	int i, l, n;
12585 
12586 	static const struct {
12587 		int section;
12588 		int bufoffs;
12589 		int lenoffs;
12590 		int entsize;
12591 		int align;
12592 		const char *msg;
12593 	} difo[] = {
12594 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12595 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12596 		sizeof (dif_instr_t), "multiple DIF sections" },
12597 
12598 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12599 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12600 		sizeof (uint64_t), "multiple integer tables" },
12601 
12602 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12603 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
12604 		sizeof (char), "multiple string tables" },
12605 
12606 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12607 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12608 		sizeof (uint_t), "multiple variable tables" },
12609 
12610 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
12611 	};
12612 
12613 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12614 		dtrace_dof_error(dof, "invalid DIFO header section");
12615 		return (NULL);
12616 	}
12617 
12618 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12619 		dtrace_dof_error(dof, "bad alignment in DIFO header");
12620 		return (NULL);
12621 	}
12622 
12623 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12624 	    sec->dofs_size % sizeof (dof_secidx_t)) {
12625 		dtrace_dof_error(dof, "bad size in DIFO header");
12626 		return (NULL);
12627 	}
12628 
12629 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12630 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12631 
12632 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12633 	dp->dtdo_rtype = dofd->dofd_rtype;
12634 
12635 	for (l = 0; l < n; l++) {
12636 		dof_sec_t *subsec;
12637 		void **bufp;
12638 		uint32_t *lenp;
12639 
12640 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12641 		    dofd->dofd_links[l])) == NULL)
12642 			goto err; /* invalid section link */
12643 
12644 		if (ttl + subsec->dofs_size > max) {
12645 			dtrace_dof_error(dof, "exceeds maximum size");
12646 			goto err;
12647 		}
12648 
12649 		ttl += subsec->dofs_size;
12650 
12651 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12652 			if (subsec->dofs_type != difo[i].section)
12653 				continue;
12654 
12655 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12656 				dtrace_dof_error(dof, "section not loaded");
12657 				goto err;
12658 			}
12659 
12660 			if (subsec->dofs_align != difo[i].align) {
12661 				dtrace_dof_error(dof, "bad alignment");
12662 				goto err;
12663 			}
12664 
12665 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12666 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12667 
12668 			if (*bufp != NULL) {
12669 				dtrace_dof_error(dof, difo[i].msg);
12670 				goto err;
12671 			}
12672 
12673 			if (difo[i].entsize != subsec->dofs_entsize) {
12674 				dtrace_dof_error(dof, "entry size mismatch");
12675 				goto err;
12676 			}
12677 
12678 			if (subsec->dofs_entsize != 0 &&
12679 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12680 				dtrace_dof_error(dof, "corrupt entry size");
12681 				goto err;
12682 			}
12683 
12684 			*lenp = subsec->dofs_size;
12685 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12686 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12687 			    *bufp, subsec->dofs_size);
12688 
12689 			if (subsec->dofs_entsize != 0)
12690 				*lenp /= subsec->dofs_entsize;
12691 
12692 			break;
12693 		}
12694 
12695 		/*
12696 		 * If we encounter a loadable DIFO sub-section that is not
12697 		 * known to us, assume this is a broken program and fail.
12698 		 */
12699 		if (difo[i].section == DOF_SECT_NONE &&
12700 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
12701 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
12702 			goto err;
12703 		}
12704 	}
12705 
12706 	if (dp->dtdo_buf == NULL) {
12707 		/*
12708 		 * We can't have a DIF object without DIF text.
12709 		 */
12710 		dtrace_dof_error(dof, "missing DIF text");
12711 		goto err;
12712 	}
12713 
12714 	/*
12715 	 * Before we validate the DIF object, run through the variable table
12716 	 * looking for the strings -- if any of their size are under, we'll set
12717 	 * their size to be the system-wide default string size.  Note that
12718 	 * this should _not_ happen if the "strsize" option has been set --
12719 	 * in this case, the compiler should have set the size to reflect the
12720 	 * setting of the option.
12721 	 */
12722 	for (i = 0; i < dp->dtdo_varlen; i++) {
12723 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
12724 		dtrace_diftype_t *t = &v->dtdv_type;
12725 
12726 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12727 			continue;
12728 
12729 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12730 			t->dtdt_size = dtrace_strsize_default;
12731 	}
12732 
12733 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12734 		goto err;
12735 
12736 	dtrace_difo_init(dp, vstate);
12737 	return (dp);
12738 
12739 err:
12740 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12741 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12742 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12743 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12744 
12745 	kmem_free(dp, sizeof (dtrace_difo_t));
12746 	return (NULL);
12747 }
12748 
12749 static dtrace_predicate_t *
12750 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12751     cred_t *cr)
12752 {
12753 	dtrace_difo_t *dp;
12754 
12755 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12756 		return (NULL);
12757 
12758 	return (dtrace_predicate_create(dp));
12759 }
12760 
12761 static dtrace_actdesc_t *
12762 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12763     cred_t *cr)
12764 {
12765 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12766 	dof_actdesc_t *desc;
12767 	dof_sec_t *difosec;
12768 	size_t offs;
12769 	uintptr_t daddr = (uintptr_t)dof;
12770 	uint64_t arg;
12771 	dtrace_actkind_t kind;
12772 
12773 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
12774 		dtrace_dof_error(dof, "invalid action section");
12775 		return (NULL);
12776 	}
12777 
12778 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12779 		dtrace_dof_error(dof, "truncated action description");
12780 		return (NULL);
12781 	}
12782 
12783 	if (sec->dofs_align != sizeof (uint64_t)) {
12784 		dtrace_dof_error(dof, "bad alignment in action description");
12785 		return (NULL);
12786 	}
12787 
12788 	if (sec->dofs_size < sec->dofs_entsize) {
12789 		dtrace_dof_error(dof, "section entry size exceeds total size");
12790 		return (NULL);
12791 	}
12792 
12793 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12794 		dtrace_dof_error(dof, "bad entry size in action description");
12795 		return (NULL);
12796 	}
12797 
12798 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12799 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12800 		return (NULL);
12801 	}
12802 
12803 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12804 		desc = (dof_actdesc_t *)(daddr +
12805 		    (uintptr_t)sec->dofs_offset + offs);
12806 		kind = (dtrace_actkind_t)desc->dofa_kind;
12807 
12808 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12809 		    (kind != DTRACEACT_PRINTA ||
12810 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12811 		    (kind == DTRACEACT_DIFEXPR &&
12812 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
12813 			dof_sec_t *strtab;
12814 			char *str, *fmt;
12815 			uint64_t i;
12816 
12817 			/*
12818 			 * The argument to these actions is an index into the
12819 			 * DOF string table.  For printf()-like actions, this
12820 			 * is the format string.  For print(), this is the
12821 			 * CTF type of the expression result.
12822 			 */
12823 			if ((strtab = dtrace_dof_sect(dof,
12824 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12825 				goto err;
12826 
12827 			str = (char *)((uintptr_t)dof +
12828 			    (uintptr_t)strtab->dofs_offset);
12829 
12830 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12831 				if (str[i] == '\0')
12832 					break;
12833 			}
12834 
12835 			if (i >= strtab->dofs_size) {
12836 				dtrace_dof_error(dof, "bogus format string");
12837 				goto err;
12838 			}
12839 
12840 			if (i == desc->dofa_arg) {
12841 				dtrace_dof_error(dof, "empty format string");
12842 				goto err;
12843 			}
12844 
12845 			i -= desc->dofa_arg;
12846 			fmt = kmem_alloc(i + 1, KM_SLEEP);
12847 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
12848 			arg = (uint64_t)(uintptr_t)fmt;
12849 		} else {
12850 			if (kind == DTRACEACT_PRINTA) {
12851 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12852 				arg = 0;
12853 			} else {
12854 				arg = desc->dofa_arg;
12855 			}
12856 		}
12857 
12858 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12859 		    desc->dofa_uarg, arg);
12860 
12861 		if (last != NULL) {
12862 			last->dtad_next = act;
12863 		} else {
12864 			first = act;
12865 		}
12866 
12867 		last = act;
12868 
12869 		if (desc->dofa_difo == DOF_SECIDX_NONE)
12870 			continue;
12871 
12872 		if ((difosec = dtrace_dof_sect(dof,
12873 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12874 			goto err;
12875 
12876 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12877 
12878 		if (act->dtad_difo == NULL)
12879 			goto err;
12880 	}
12881 
12882 	ASSERT(first != NULL);
12883 	return (first);
12884 
12885 err:
12886 	for (act = first; act != NULL; act = next) {
12887 		next = act->dtad_next;
12888 		dtrace_actdesc_release(act, vstate);
12889 	}
12890 
12891 	return (NULL);
12892 }
12893 
12894 static dtrace_ecbdesc_t *
12895 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12896     cred_t *cr)
12897 {
12898 	dtrace_ecbdesc_t *ep;
12899 	dof_ecbdesc_t *ecb;
12900 	dtrace_probedesc_t *desc;
12901 	dtrace_predicate_t *pred = NULL;
12902 
12903 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12904 		dtrace_dof_error(dof, "truncated ECB description");
12905 		return (NULL);
12906 	}
12907 
12908 	if (sec->dofs_align != sizeof (uint64_t)) {
12909 		dtrace_dof_error(dof, "bad alignment in ECB description");
12910 		return (NULL);
12911 	}
12912 
12913 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12914 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12915 
12916 	if (sec == NULL)
12917 		return (NULL);
12918 
12919 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12920 	ep->dted_uarg = ecb->dofe_uarg;
12921 	desc = &ep->dted_probe;
12922 
12923 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12924 		goto err;
12925 
12926 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12927 		if ((sec = dtrace_dof_sect(dof,
12928 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12929 			goto err;
12930 
12931 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12932 			goto err;
12933 
12934 		ep->dted_pred.dtpdd_predicate = pred;
12935 	}
12936 
12937 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12938 		if ((sec = dtrace_dof_sect(dof,
12939 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12940 			goto err;
12941 
12942 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12943 
12944 		if (ep->dted_action == NULL)
12945 			goto err;
12946 	}
12947 
12948 	return (ep);
12949 
12950 err:
12951 	if (pred != NULL)
12952 		dtrace_predicate_release(pred, vstate);
12953 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12954 	return (NULL);
12955 }
12956 
12957 /*
12958  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12959  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
12960  * site of any user SETX relocations to account for load object base address.
12961  * In the future, if we need other relocations, this function can be extended.
12962  */
12963 static int
12964 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12965 {
12966 	uintptr_t daddr = (uintptr_t)dof;
12967 	dof_relohdr_t *dofr =
12968 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12969 	dof_sec_t *ss, *rs, *ts;
12970 	dof_relodesc_t *r;
12971 	uint_t i, n;
12972 
12973 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12974 	    sec->dofs_align != sizeof (dof_secidx_t)) {
12975 		dtrace_dof_error(dof, "invalid relocation header");
12976 		return (-1);
12977 	}
12978 
12979 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12980 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12981 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12982 
12983 	if (ss == NULL || rs == NULL || ts == NULL)
12984 		return (-1); /* dtrace_dof_error() has been called already */
12985 
12986 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12987 	    rs->dofs_align != sizeof (uint64_t)) {
12988 		dtrace_dof_error(dof, "invalid relocation section");
12989 		return (-1);
12990 	}
12991 
12992 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12993 	n = rs->dofs_size / rs->dofs_entsize;
12994 
12995 	for (i = 0; i < n; i++) {
12996 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12997 
12998 		switch (r->dofr_type) {
12999 		case DOF_RELO_NONE:
13000 			break;
13001 		case DOF_RELO_SETX:
13002 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
13003 			    sizeof (uint64_t) > ts->dofs_size) {
13004 				dtrace_dof_error(dof, "bad relocation offset");
13005 				return (-1);
13006 			}
13007 
13008 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
13009 				dtrace_dof_error(dof, "misaligned setx relo");
13010 				return (-1);
13011 			}
13012 
13013 			*(uint64_t *)taddr += ubase;
13014 			break;
13015 		default:
13016 			dtrace_dof_error(dof, "invalid relocation type");
13017 			return (-1);
13018 		}
13019 
13020 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
13021 	}
13022 
13023 	return (0);
13024 }
13025 
13026 /*
13027  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
13028  * header:  it should be at the front of a memory region that is at least
13029  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
13030  * size.  It need not be validated in any other way.
13031  */
13032 static int
13033 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
13034     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
13035 {
13036 	uint64_t len = dof->dofh_loadsz, seclen;
13037 	uintptr_t daddr = (uintptr_t)dof;
13038 	dtrace_ecbdesc_t *ep;
13039 	dtrace_enabling_t *enab;
13040 	uint_t i;
13041 
13042 	ASSERT(MUTEX_HELD(&dtrace_lock));
13043 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
13044 
13045 	/*
13046 	 * Check the DOF header identification bytes.  In addition to checking
13047 	 * valid settings, we also verify that unused bits/bytes are zeroed so
13048 	 * we can use them later without fear of regressing existing binaries.
13049 	 */
13050 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
13051 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
13052 		dtrace_dof_error(dof, "DOF magic string mismatch");
13053 		return (-1);
13054 	}
13055 
13056 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
13057 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
13058 		dtrace_dof_error(dof, "DOF has invalid data model");
13059 		return (-1);
13060 	}
13061 
13062 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
13063 		dtrace_dof_error(dof, "DOF encoding mismatch");
13064 		return (-1);
13065 	}
13066 
13067 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13068 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
13069 		dtrace_dof_error(dof, "DOF version mismatch");
13070 		return (-1);
13071 	}
13072 
13073 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
13074 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
13075 		return (-1);
13076 	}
13077 
13078 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
13079 		dtrace_dof_error(dof, "DOF uses too many integer registers");
13080 		return (-1);
13081 	}
13082 
13083 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13084 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
13085 		return (-1);
13086 	}
13087 
13088 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13089 		if (dof->dofh_ident[i] != 0) {
13090 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
13091 			return (-1);
13092 		}
13093 	}
13094 
13095 	if (dof->dofh_flags & ~DOF_FL_VALID) {
13096 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
13097 		return (-1);
13098 	}
13099 
13100 	if (dof->dofh_secsize == 0) {
13101 		dtrace_dof_error(dof, "zero section header size");
13102 		return (-1);
13103 	}
13104 
13105 	/*
13106 	 * Check that the section headers don't exceed the amount of DOF
13107 	 * data.  Note that we cast the section size and number of sections
13108 	 * to uint64_t's to prevent possible overflow in the multiplication.
13109 	 */
13110 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13111 
13112 	if (dof->dofh_secoff > len || seclen > len ||
13113 	    dof->dofh_secoff + seclen > len) {
13114 		dtrace_dof_error(dof, "truncated section headers");
13115 		return (-1);
13116 	}
13117 
13118 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13119 		dtrace_dof_error(dof, "misaligned section headers");
13120 		return (-1);
13121 	}
13122 
13123 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13124 		dtrace_dof_error(dof, "misaligned section size");
13125 		return (-1);
13126 	}
13127 
13128 	/*
13129 	 * Take an initial pass through the section headers to be sure that
13130 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
13131 	 * set, do not permit sections relating to providers, probes, or args.
13132 	 */
13133 	for (i = 0; i < dof->dofh_secnum; i++) {
13134 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13135 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13136 
13137 		if (noprobes) {
13138 			switch (sec->dofs_type) {
13139 			case DOF_SECT_PROVIDER:
13140 			case DOF_SECT_PROBES:
13141 			case DOF_SECT_PRARGS:
13142 			case DOF_SECT_PROFFS:
13143 				dtrace_dof_error(dof, "illegal sections "
13144 				    "for enabling");
13145 				return (-1);
13146 			}
13147 		}
13148 
13149 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
13150 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
13151 			dtrace_dof_error(dof, "loadable section with load "
13152 			    "flag unset");
13153 			return (-1);
13154 		}
13155 
13156 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
13157 			continue; /* just ignore non-loadable sections */
13158 
13159 		if (!ISP2(sec->dofs_align)) {
13160 			dtrace_dof_error(dof, "bad section alignment");
13161 			return (-1);
13162 		}
13163 
13164 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
13165 			dtrace_dof_error(dof, "misaligned section");
13166 			return (-1);
13167 		}
13168 
13169 		if (sec->dofs_offset > len || sec->dofs_size > len ||
13170 		    sec->dofs_offset + sec->dofs_size > len) {
13171 			dtrace_dof_error(dof, "corrupt section header");
13172 			return (-1);
13173 		}
13174 
13175 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13176 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13177 			dtrace_dof_error(dof, "non-terminating string table");
13178 			return (-1);
13179 		}
13180 	}
13181 
13182 	/*
13183 	 * Take a second pass through the sections and locate and perform any
13184 	 * relocations that are present.  We do this after the first pass to
13185 	 * be sure that all sections have had their headers validated.
13186 	 */
13187 	for (i = 0; i < dof->dofh_secnum; i++) {
13188 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13189 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13190 
13191 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
13192 			continue; /* skip sections that are not loadable */
13193 
13194 		switch (sec->dofs_type) {
13195 		case DOF_SECT_URELHDR:
13196 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
13197 				return (-1);
13198 			break;
13199 		}
13200 	}
13201 
13202 	if ((enab = *enabp) == NULL)
13203 		enab = *enabp = dtrace_enabling_create(vstate);
13204 
13205 	for (i = 0; i < dof->dofh_secnum; i++) {
13206 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13207 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13208 
13209 		if (sec->dofs_type != DOF_SECT_ECBDESC)
13210 			continue;
13211 
13212 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
13213 			dtrace_enabling_destroy(enab);
13214 			*enabp = NULL;
13215 			return (-1);
13216 		}
13217 
13218 		dtrace_enabling_add(enab, ep);
13219 	}
13220 
13221 	return (0);
13222 }
13223 
13224 /*
13225  * Process DOF for any options.  This routine assumes that the DOF has been
13226  * at least processed by dtrace_dof_slurp().
13227  */
13228 static int
13229 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13230 {
13231 	int i, rval;
13232 	uint32_t entsize;
13233 	size_t offs;
13234 	dof_optdesc_t *desc;
13235 
13236 	for (i = 0; i < dof->dofh_secnum; i++) {
13237 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13238 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13239 
13240 		if (sec->dofs_type != DOF_SECT_OPTDESC)
13241 			continue;
13242 
13243 		if (sec->dofs_align != sizeof (uint64_t)) {
13244 			dtrace_dof_error(dof, "bad alignment in "
13245 			    "option description");
13246 			return (EINVAL);
13247 		}
13248 
13249 		if ((entsize = sec->dofs_entsize) == 0) {
13250 			dtrace_dof_error(dof, "zeroed option entry size");
13251 			return (EINVAL);
13252 		}
13253 
13254 		if (entsize < sizeof (dof_optdesc_t)) {
13255 			dtrace_dof_error(dof, "bad option entry size");
13256 			return (EINVAL);
13257 		}
13258 
13259 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13260 			desc = (dof_optdesc_t *)((uintptr_t)dof +
13261 			    (uintptr_t)sec->dofs_offset + offs);
13262 
13263 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13264 				dtrace_dof_error(dof, "non-zero option string");
13265 				return (EINVAL);
13266 			}
13267 
13268 			if (desc->dofo_value == DTRACEOPT_UNSET) {
13269 				dtrace_dof_error(dof, "unset option");
13270 				return (EINVAL);
13271 			}
13272 
13273 			if ((rval = dtrace_state_option(state,
13274 			    desc->dofo_option, desc->dofo_value)) != 0) {
13275 				dtrace_dof_error(dof, "rejected option");
13276 				return (rval);
13277 			}
13278 		}
13279 	}
13280 
13281 	return (0);
13282 }
13283 
13284 /*
13285  * DTrace Consumer State Functions
13286  */
13287 int
13288 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13289 {
13290 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
13291 	void *base;
13292 	uintptr_t limit;
13293 	dtrace_dynvar_t *dvar, *next, *start;
13294 	int i;
13295 
13296 	ASSERT(MUTEX_HELD(&dtrace_lock));
13297 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13298 
13299 	bzero(dstate, sizeof (dtrace_dstate_t));
13300 
13301 	if ((dstate->dtds_chunksize = chunksize) == 0)
13302 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13303 
13304 	VERIFY(dstate->dtds_chunksize < LONG_MAX);
13305 
13306 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13307 		size = min;
13308 
13309 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
13310 		return (ENOMEM);
13311 
13312 	dstate->dtds_size = size;
13313 	dstate->dtds_base = base;
13314 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
13315 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
13316 
13317 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13318 
13319 	if (hashsize != 1 && (hashsize & 1))
13320 		hashsize--;
13321 
13322 	dstate->dtds_hashsize = hashsize;
13323 	dstate->dtds_hash = dstate->dtds_base;
13324 
13325 	/*
13326 	 * Set all of our hash buckets to point to the single sink, and (if
13327 	 * it hasn't already been set), set the sink's hash value to be the
13328 	 * sink sentinel value.  The sink is needed for dynamic variable
13329 	 * lookups to know that they have iterated over an entire, valid hash
13330 	 * chain.
13331 	 */
13332 	for (i = 0; i < hashsize; i++)
13333 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13334 
13335 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13336 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13337 
13338 	/*
13339 	 * Determine number of active CPUs.  Divide free list evenly among
13340 	 * active CPUs.
13341 	 */
13342 	start = (dtrace_dynvar_t *)
13343 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13344 	limit = (uintptr_t)base + size;
13345 
13346 	VERIFY((uintptr_t)start < limit);
13347 	VERIFY((uintptr_t)start >= (uintptr_t)base);
13348 
13349 	maxper = (limit - (uintptr_t)start) / NCPU;
13350 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13351 
13352 	for (i = 0; i < NCPU; i++) {
13353 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13354 
13355 		/*
13356 		 * If we don't even have enough chunks to make it once through
13357 		 * NCPUs, we're just going to allocate everything to the first
13358 		 * CPU.  And if we're on the last CPU, we're going to allocate
13359 		 * whatever is left over.  In either case, we set the limit to
13360 		 * be the limit of the dynamic variable space.
13361 		 */
13362 		if (maxper == 0 || i == NCPU - 1) {
13363 			limit = (uintptr_t)base + size;
13364 			start = NULL;
13365 		} else {
13366 			limit = (uintptr_t)start + maxper;
13367 			start = (dtrace_dynvar_t *)limit;
13368 		}
13369 
13370 		VERIFY(limit <= (uintptr_t)base + size);
13371 
13372 		for (;;) {
13373 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13374 			    dstate->dtds_chunksize);
13375 
13376 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13377 				break;
13378 
13379 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
13380 			    (uintptr_t)dvar <= (uintptr_t)base + size);
13381 			dvar->dtdv_next = next;
13382 			dvar = next;
13383 		}
13384 
13385 		if (maxper == 0)
13386 			break;
13387 	}
13388 
13389 	return (0);
13390 }
13391 
13392 void
13393 dtrace_dstate_fini(dtrace_dstate_t *dstate)
13394 {
13395 	ASSERT(MUTEX_HELD(&cpu_lock));
13396 
13397 	if (dstate->dtds_base == NULL)
13398 		return;
13399 
13400 	kmem_free(dstate->dtds_base, dstate->dtds_size);
13401 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13402 }
13403 
13404 static void
13405 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13406 {
13407 	/*
13408 	 * Logical XOR, where are you?
13409 	 */
13410 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13411 
13412 	if (vstate->dtvs_nglobals > 0) {
13413 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13414 		    sizeof (dtrace_statvar_t *));
13415 	}
13416 
13417 	if (vstate->dtvs_ntlocals > 0) {
13418 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13419 		    sizeof (dtrace_difv_t));
13420 	}
13421 
13422 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13423 
13424 	if (vstate->dtvs_nlocals > 0) {
13425 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13426 		    sizeof (dtrace_statvar_t *));
13427 	}
13428 }
13429 
13430 static void
13431 dtrace_state_clean(dtrace_state_t *state)
13432 {
13433 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13434 		return;
13435 
13436 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13437 	dtrace_speculation_clean(state);
13438 }
13439 
13440 static void
13441 dtrace_state_deadman(dtrace_state_t *state)
13442 {
13443 	hrtime_t now;
13444 
13445 	dtrace_sync();
13446 
13447 	now = dtrace_gethrtime();
13448 
13449 	if (state != dtrace_anon.dta_state &&
13450 	    now - state->dts_laststatus >= dtrace_deadman_user)
13451 		return;
13452 
13453 	/*
13454 	 * We must be sure that dts_alive never appears to be less than the
13455 	 * value upon entry to dtrace_state_deadman(), and because we lack a
13456 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13457 	 * store INT64_MAX to it, followed by a memory barrier, followed by
13458 	 * the new value.  This assures that dts_alive never appears to be
13459 	 * less than its true value, regardless of the order in which the
13460 	 * stores to the underlying storage are issued.
13461 	 */
13462 	state->dts_alive = INT64_MAX;
13463 	dtrace_membar_producer();
13464 	state->dts_alive = now;
13465 }
13466 
13467 dtrace_state_t *
13468 dtrace_state_create(dev_t *devp, cred_t *cr)
13469 {
13470 	minor_t minor;
13471 	major_t major;
13472 	char c[30];
13473 	dtrace_state_t *state;
13474 	dtrace_optval_t *opt;
13475 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13476 
13477 	ASSERT(MUTEX_HELD(&dtrace_lock));
13478 	ASSERT(MUTEX_HELD(&cpu_lock));
13479 
13480 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13481 	    VM_BESTFIT | VM_SLEEP);
13482 
13483 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13484 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13485 		return (NULL);
13486 	}
13487 
13488 	state = ddi_get_soft_state(dtrace_softstate, minor);
13489 	state->dts_epid = DTRACE_EPIDNONE + 1;
13490 
13491 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
13492 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13493 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13494 
13495 	if (devp != NULL) {
13496 		major = getemajor(*devp);
13497 	} else {
13498 		major = ddi_driver_major(dtrace_devi);
13499 	}
13500 
13501 	state->dts_dev = makedevice(major, minor);
13502 
13503 	if (devp != NULL)
13504 		*devp = state->dts_dev;
13505 
13506 	/*
13507 	 * We allocate NCPU buffers.  On the one hand, this can be quite
13508 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
13509 	 * other hand, it saves an additional memory reference in the probe
13510 	 * path.
13511 	 */
13512 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13513 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13514 	state->dts_cleaner = CYCLIC_NONE;
13515 	state->dts_deadman = CYCLIC_NONE;
13516 	state->dts_vstate.dtvs_state = state;
13517 
13518 	for (i = 0; i < DTRACEOPT_MAX; i++)
13519 		state->dts_options[i] = DTRACEOPT_UNSET;
13520 
13521 	/*
13522 	 * Set the default options.
13523 	 */
13524 	opt = state->dts_options;
13525 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13526 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13527 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13528 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13529 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13530 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13531 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13532 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13533 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13534 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13535 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13536 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13537 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13538 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13539 
13540 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13541 
13542 	/*
13543 	 * Depending on the user credentials, we set flag bits which alter probe
13544 	 * visibility or the amount of destructiveness allowed.  In the case of
13545 	 * actual anonymous tracing, or the possession of all privileges, all of
13546 	 * the normal checks are bypassed.
13547 	 */
13548 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13549 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13550 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13551 	} else {
13552 		/*
13553 		 * Set up the credentials for this instantiation.  We take a
13554 		 * hold on the credential to prevent it from disappearing on
13555 		 * us; this in turn prevents the zone_t referenced by this
13556 		 * credential from disappearing.  This means that we can
13557 		 * examine the credential and the zone from probe context.
13558 		 */
13559 		crhold(cr);
13560 		state->dts_cred.dcr_cred = cr;
13561 
13562 		/*
13563 		 * CRA_PROC means "we have *some* privilege for dtrace" and
13564 		 * unlocks the use of variables like pid, zonename, etc.
13565 		 */
13566 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13567 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13568 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13569 		}
13570 
13571 		/*
13572 		 * dtrace_user allows use of syscall and profile providers.
13573 		 * If the user also has proc_owner and/or proc_zone, we
13574 		 * extend the scope to include additional visibility and
13575 		 * destructive power.
13576 		 */
13577 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13578 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13579 				state->dts_cred.dcr_visible |=
13580 				    DTRACE_CRV_ALLPROC;
13581 
13582 				state->dts_cred.dcr_action |=
13583 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13584 			}
13585 
13586 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13587 				state->dts_cred.dcr_visible |=
13588 				    DTRACE_CRV_ALLZONE;
13589 
13590 				state->dts_cred.dcr_action |=
13591 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13592 			}
13593 
13594 			/*
13595 			 * If we have all privs in whatever zone this is,
13596 			 * we can do destructive things to processes which
13597 			 * have altered credentials.
13598 			 */
13599 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13600 			    cr->cr_zone->zone_privset)) {
13601 				state->dts_cred.dcr_action |=
13602 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13603 			}
13604 		}
13605 
13606 		/*
13607 		 * Holding the dtrace_kernel privilege also implies that
13608 		 * the user has the dtrace_user privilege from a visibility
13609 		 * perspective.  But without further privileges, some
13610 		 * destructive actions are not available.
13611 		 */
13612 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13613 			/*
13614 			 * Make all probes in all zones visible.  However,
13615 			 * this doesn't mean that all actions become available
13616 			 * to all zones.
13617 			 */
13618 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13619 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13620 
13621 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13622 			    DTRACE_CRA_PROC;
13623 			/*
13624 			 * Holding proc_owner means that destructive actions
13625 			 * for *this* zone are allowed.
13626 			 */
13627 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13628 				state->dts_cred.dcr_action |=
13629 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13630 
13631 			/*
13632 			 * Holding proc_zone means that destructive actions
13633 			 * for this user/group ID in all zones is allowed.
13634 			 */
13635 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13636 				state->dts_cred.dcr_action |=
13637 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13638 
13639 			/*
13640 			 * If we have all privs in whatever zone this is,
13641 			 * we can do destructive things to processes which
13642 			 * have altered credentials.
13643 			 */
13644 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13645 			    cr->cr_zone->zone_privset)) {
13646 				state->dts_cred.dcr_action |=
13647 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13648 			}
13649 		}
13650 
13651 		/*
13652 		 * Holding the dtrace_proc privilege gives control over fasttrap
13653 		 * and pid providers.  We need to grant wider destructive
13654 		 * privileges in the event that the user has proc_owner and/or
13655 		 * proc_zone.
13656 		 */
13657 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13658 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13659 				state->dts_cred.dcr_action |=
13660 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13661 
13662 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13663 				state->dts_cred.dcr_action |=
13664 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13665 		}
13666 	}
13667 
13668 	return (state);
13669 }
13670 
13671 static int
13672 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13673 {
13674 	dtrace_optval_t *opt = state->dts_options, size;
13675 	processorid_t cpu;
13676 	int flags = 0, rval, factor, divisor = 1;
13677 
13678 	ASSERT(MUTEX_HELD(&dtrace_lock));
13679 	ASSERT(MUTEX_HELD(&cpu_lock));
13680 	ASSERT(which < DTRACEOPT_MAX);
13681 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13682 	    (state == dtrace_anon.dta_state &&
13683 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13684 
13685 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13686 		return (0);
13687 
13688 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13689 		cpu = opt[DTRACEOPT_CPU];
13690 
13691 	if (which == DTRACEOPT_SPECSIZE)
13692 		flags |= DTRACEBUF_NOSWITCH;
13693 
13694 	if (which == DTRACEOPT_BUFSIZE) {
13695 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13696 			flags |= DTRACEBUF_RING;
13697 
13698 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13699 			flags |= DTRACEBUF_FILL;
13700 
13701 		if (state != dtrace_anon.dta_state ||
13702 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13703 			flags |= DTRACEBUF_INACTIVE;
13704 	}
13705 
13706 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
13707 		/*
13708 		 * The size must be 8-byte aligned.  If the size is not 8-byte
13709 		 * aligned, drop it down by the difference.
13710 		 */
13711 		if (size & (sizeof (uint64_t) - 1))
13712 			size -= size & (sizeof (uint64_t) - 1);
13713 
13714 		if (size < state->dts_reserve) {
13715 			/*
13716 			 * Buffers always must be large enough to accommodate
13717 			 * their prereserved space.  We return E2BIG instead
13718 			 * of ENOMEM in this case to allow for user-level
13719 			 * software to differentiate the cases.
13720 			 */
13721 			return (E2BIG);
13722 		}
13723 
13724 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
13725 
13726 		if (rval != ENOMEM) {
13727 			opt[which] = size;
13728 			return (rval);
13729 		}
13730 
13731 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13732 			return (rval);
13733 
13734 		for (divisor = 2; divisor < factor; divisor <<= 1)
13735 			continue;
13736 	}
13737 
13738 	return (ENOMEM);
13739 }
13740 
13741 static int
13742 dtrace_state_buffers(dtrace_state_t *state)
13743 {
13744 	dtrace_speculation_t *spec = state->dts_speculations;
13745 	int rval, i;
13746 
13747 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13748 	    DTRACEOPT_BUFSIZE)) != 0)
13749 		return (rval);
13750 
13751 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13752 	    DTRACEOPT_AGGSIZE)) != 0)
13753 		return (rval);
13754 
13755 	for (i = 0; i < state->dts_nspeculations; i++) {
13756 		if ((rval = dtrace_state_buffer(state,
13757 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13758 			return (rval);
13759 	}
13760 
13761 	return (0);
13762 }
13763 
13764 static void
13765 dtrace_state_prereserve(dtrace_state_t *state)
13766 {
13767 	dtrace_ecb_t *ecb;
13768 	dtrace_probe_t *probe;
13769 
13770 	state->dts_reserve = 0;
13771 
13772 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13773 		return;
13774 
13775 	/*
13776 	 * If our buffer policy is a "fill" buffer policy, we need to set the
13777 	 * prereserved space to be the space required by the END probes.
13778 	 */
13779 	probe = dtrace_probes[dtrace_probeid_end - 1];
13780 	ASSERT(probe != NULL);
13781 
13782 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13783 		if (ecb->dte_state != state)
13784 			continue;
13785 
13786 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13787 	}
13788 }
13789 
13790 static int
13791 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13792 {
13793 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
13794 	dtrace_speculation_t *spec;
13795 	dtrace_buffer_t *buf;
13796 	cyc_handler_t hdlr;
13797 	cyc_time_t when;
13798 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13799 	dtrace_icookie_t cookie;
13800 
13801 	mutex_enter(&cpu_lock);
13802 	mutex_enter(&dtrace_lock);
13803 
13804 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13805 		rval = EBUSY;
13806 		goto out;
13807 	}
13808 
13809 	/*
13810 	 * Before we can perform any checks, we must prime all of the
13811 	 * retained enablings that correspond to this state.
13812 	 */
13813 	dtrace_enabling_prime(state);
13814 
13815 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13816 		rval = EACCES;
13817 		goto out;
13818 	}
13819 
13820 	dtrace_state_prereserve(state);
13821 
13822 	/*
13823 	 * Now we want to do is try to allocate our speculations.
13824 	 * We do not automatically resize the number of speculations; if
13825 	 * this fails, we will fail the operation.
13826 	 */
13827 	nspec = opt[DTRACEOPT_NSPEC];
13828 	ASSERT(nspec != DTRACEOPT_UNSET);
13829 
13830 	if (nspec > INT_MAX) {
13831 		rval = ENOMEM;
13832 		goto out;
13833 	}
13834 
13835 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
13836 	    KM_NOSLEEP | KM_NORMALPRI);
13837 
13838 	if (spec == NULL) {
13839 		rval = ENOMEM;
13840 		goto out;
13841 	}
13842 
13843 	state->dts_speculations = spec;
13844 	state->dts_nspeculations = (int)nspec;
13845 
13846 	for (i = 0; i < nspec; i++) {
13847 		if ((buf = kmem_zalloc(bufsize,
13848 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
13849 			rval = ENOMEM;
13850 			goto err;
13851 		}
13852 
13853 		spec[i].dtsp_buffer = buf;
13854 	}
13855 
13856 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13857 		if (dtrace_anon.dta_state == NULL) {
13858 			rval = ENOENT;
13859 			goto out;
13860 		}
13861 
13862 		if (state->dts_necbs != 0) {
13863 			rval = EALREADY;
13864 			goto out;
13865 		}
13866 
13867 		state->dts_anon = dtrace_anon_grab();
13868 		ASSERT(state->dts_anon != NULL);
13869 		state = state->dts_anon;
13870 
13871 		/*
13872 		 * We want "grabanon" to be set in the grabbed state, so we'll
13873 		 * copy that option value from the grabbing state into the
13874 		 * grabbed state.
13875 		 */
13876 		state->dts_options[DTRACEOPT_GRABANON] =
13877 		    opt[DTRACEOPT_GRABANON];
13878 
13879 		*cpu = dtrace_anon.dta_beganon;
13880 
13881 		/*
13882 		 * If the anonymous state is active (as it almost certainly
13883 		 * is if the anonymous enabling ultimately matched anything),
13884 		 * we don't allow any further option processing -- but we
13885 		 * don't return failure.
13886 		 */
13887 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13888 			goto out;
13889 	}
13890 
13891 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13892 	    opt[DTRACEOPT_AGGSIZE] != 0) {
13893 		if (state->dts_aggregations == NULL) {
13894 			/*
13895 			 * We're not going to create an aggregation buffer
13896 			 * because we don't have any ECBs that contain
13897 			 * aggregations -- set this option to 0.
13898 			 */
13899 			opt[DTRACEOPT_AGGSIZE] = 0;
13900 		} else {
13901 			/*
13902 			 * If we have an aggregation buffer, we must also have
13903 			 * a buffer to use as scratch.
13904 			 */
13905 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13906 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13907 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13908 			}
13909 		}
13910 	}
13911 
13912 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13913 	    opt[DTRACEOPT_SPECSIZE] != 0) {
13914 		if (!state->dts_speculates) {
13915 			/*
13916 			 * We're not going to create speculation buffers
13917 			 * because we don't have any ECBs that actually
13918 			 * speculate -- set the speculation size to 0.
13919 			 */
13920 			opt[DTRACEOPT_SPECSIZE] = 0;
13921 		}
13922 	}
13923 
13924 	/*
13925 	 * The bare minimum size for any buffer that we're actually going to
13926 	 * do anything to is sizeof (uint64_t).
13927 	 */
13928 	sz = sizeof (uint64_t);
13929 
13930 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13931 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13932 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13933 		/*
13934 		 * A buffer size has been explicitly set to 0 (or to a size
13935 		 * that will be adjusted to 0) and we need the space -- we
13936 		 * need to return failure.  We return ENOSPC to differentiate
13937 		 * it from failing to allocate a buffer due to failure to meet
13938 		 * the reserve (for which we return E2BIG).
13939 		 */
13940 		rval = ENOSPC;
13941 		goto out;
13942 	}
13943 
13944 	if ((rval = dtrace_state_buffers(state)) != 0)
13945 		goto err;
13946 
13947 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13948 		sz = dtrace_dstate_defsize;
13949 
13950 	do {
13951 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13952 
13953 		if (rval == 0)
13954 			break;
13955 
13956 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13957 			goto err;
13958 	} while (sz >>= 1);
13959 
13960 	opt[DTRACEOPT_DYNVARSIZE] = sz;
13961 
13962 	if (rval != 0)
13963 		goto err;
13964 
13965 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13966 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13967 
13968 	if (opt[DTRACEOPT_CLEANRATE] == 0)
13969 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13970 
13971 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13972 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13973 
13974 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13975 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13976 
13977 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13978 	hdlr.cyh_arg = state;
13979 	hdlr.cyh_level = CY_LOW_LEVEL;
13980 
13981 	when.cyt_when = 0;
13982 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13983 
13984 	state->dts_cleaner = cyclic_add(&hdlr, &when);
13985 
13986 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13987 	hdlr.cyh_arg = state;
13988 	hdlr.cyh_level = CY_LOW_LEVEL;
13989 
13990 	when.cyt_when = 0;
13991 	when.cyt_interval = dtrace_deadman_interval;
13992 
13993 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13994 	state->dts_deadman = cyclic_add(&hdlr, &when);
13995 
13996 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13997 
13998 	if (state->dts_getf != 0 &&
13999 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14000 		/*
14001 		 * We don't have kernel privs but we have at least one call
14002 		 * to getf(); we need to bump our zone's count, and (if
14003 		 * this is the first enabling to have an unprivileged call
14004 		 * to getf()) we need to hook into closef().
14005 		 */
14006 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
14007 
14008 		if (dtrace_getf++ == 0) {
14009 			ASSERT(dtrace_closef == NULL);
14010 			dtrace_closef = dtrace_getf_barrier;
14011 		}
14012 	}
14013 
14014 	/*
14015 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
14016 	 * interrupts here both to record the CPU on which we fired the BEGIN
14017 	 * probe (the data from this CPU will be processed first at user
14018 	 * level) and to manually activate the buffer for this CPU.
14019 	 */
14020 	cookie = dtrace_interrupt_disable();
14021 	*cpu = CPU->cpu_id;
14022 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14023 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14024 
14025 	dtrace_probe(dtrace_probeid_begin,
14026 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14027 	dtrace_interrupt_enable(cookie);
14028 	/*
14029 	 * We may have had an exit action from a BEGIN probe; only change our
14030 	 * state to ACTIVE if we're still in WARMUP.
14031 	 */
14032 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14033 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14034 
14035 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
14036 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
14037 
14038 	/*
14039 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
14040 	 * want each CPU to transition its principal buffer out of the
14041 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
14042 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
14043 	 * atomically transition from processing none of a state's ECBs to
14044 	 * processing all of them.
14045 	 */
14046 	dtrace_xcall(DTRACE_CPUALL,
14047 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
14048 	goto out;
14049 
14050 err:
14051 	dtrace_buffer_free(state->dts_buffer);
14052 	dtrace_buffer_free(state->dts_aggbuffer);
14053 
14054 	if ((nspec = state->dts_nspeculations) == 0) {
14055 		ASSERT(state->dts_speculations == NULL);
14056 		goto out;
14057 	}
14058 
14059 	spec = state->dts_speculations;
14060 	ASSERT(spec != NULL);
14061 
14062 	for (i = 0; i < state->dts_nspeculations; i++) {
14063 		if ((buf = spec[i].dtsp_buffer) == NULL)
14064 			break;
14065 
14066 		dtrace_buffer_free(buf);
14067 		kmem_free(buf, bufsize);
14068 	}
14069 
14070 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14071 	state->dts_nspeculations = 0;
14072 	state->dts_speculations = NULL;
14073 
14074 out:
14075 	mutex_exit(&dtrace_lock);
14076 	mutex_exit(&cpu_lock);
14077 
14078 	return (rval);
14079 }
14080 
14081 static int
14082 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14083 {
14084 	dtrace_icookie_t cookie;
14085 
14086 	ASSERT(MUTEX_HELD(&dtrace_lock));
14087 
14088 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14089 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14090 		return (EINVAL);
14091 
14092 	/*
14093 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14094 	 * to be sure that every CPU has seen it.  See below for the details
14095 	 * on why this is done.
14096 	 */
14097 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14098 	dtrace_sync();
14099 
14100 	/*
14101 	 * By this point, it is impossible for any CPU to be still processing
14102 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
14103 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14104 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
14105 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14106 	 * iff we're in the END probe.
14107 	 */
14108 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14109 	dtrace_sync();
14110 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14111 
14112 	/*
14113 	 * Finally, we can release the reserve and call the END probe.  We
14114 	 * disable interrupts across calling the END probe to allow us to
14115 	 * return the CPU on which we actually called the END probe.  This
14116 	 * allows user-land to be sure that this CPU's principal buffer is
14117 	 * processed last.
14118 	 */
14119 	state->dts_reserve = 0;
14120 
14121 	cookie = dtrace_interrupt_disable();
14122 	*cpu = CPU->cpu_id;
14123 	dtrace_probe(dtrace_probeid_end,
14124 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14125 	dtrace_interrupt_enable(cookie);
14126 
14127 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14128 	dtrace_sync();
14129 
14130 	if (state->dts_getf != 0 &&
14131 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14132 		/*
14133 		 * We don't have kernel privs but we have at least one call
14134 		 * to getf(); we need to lower our zone's count, and (if
14135 		 * this is the last enabling to have an unprivileged call
14136 		 * to getf()) we need to clear the closef() hook.
14137 		 */
14138 		ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
14139 		ASSERT(dtrace_closef == dtrace_getf_barrier);
14140 		ASSERT(dtrace_getf > 0);
14141 
14142 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
14143 
14144 		if (--dtrace_getf == 0)
14145 			dtrace_closef = NULL;
14146 	}
14147 
14148 	return (0);
14149 }
14150 
14151 static int
14152 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14153     dtrace_optval_t val)
14154 {
14155 	ASSERT(MUTEX_HELD(&dtrace_lock));
14156 
14157 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14158 		return (EBUSY);
14159 
14160 	if (option >= DTRACEOPT_MAX)
14161 		return (EINVAL);
14162 
14163 	if (option != DTRACEOPT_CPU && val < 0)
14164 		return (EINVAL);
14165 
14166 	switch (option) {
14167 	case DTRACEOPT_DESTRUCTIVE:
14168 		if (dtrace_destructive_disallow)
14169 			return (EACCES);
14170 
14171 		state->dts_cred.dcr_destructive = 1;
14172 		break;
14173 
14174 	case DTRACEOPT_BUFSIZE:
14175 	case DTRACEOPT_DYNVARSIZE:
14176 	case DTRACEOPT_AGGSIZE:
14177 	case DTRACEOPT_SPECSIZE:
14178 	case DTRACEOPT_STRSIZE:
14179 		if (val < 0)
14180 			return (EINVAL);
14181 
14182 		if (val >= LONG_MAX) {
14183 			/*
14184 			 * If this is an otherwise negative value, set it to
14185 			 * the highest multiple of 128m less than LONG_MAX.
14186 			 * Technically, we're adjusting the size without
14187 			 * regard to the buffer resizing policy, but in fact,
14188 			 * this has no effect -- if we set the buffer size to
14189 			 * ~LONG_MAX and the buffer policy is ultimately set to
14190 			 * be "manual", the buffer allocation is guaranteed to
14191 			 * fail, if only because the allocation requires two
14192 			 * buffers.  (We set the the size to the highest
14193 			 * multiple of 128m because it ensures that the size
14194 			 * will remain a multiple of a megabyte when
14195 			 * repeatedly halved -- all the way down to 15m.)
14196 			 */
14197 			val = LONG_MAX - (1 << 27) + 1;
14198 		}
14199 	}
14200 
14201 	state->dts_options[option] = val;
14202 
14203 	return (0);
14204 }
14205 
14206 static void
14207 dtrace_state_destroy(dtrace_state_t *state)
14208 {
14209 	dtrace_ecb_t *ecb;
14210 	dtrace_vstate_t *vstate = &state->dts_vstate;
14211 	minor_t minor = getminor(state->dts_dev);
14212 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14213 	dtrace_speculation_t *spec = state->dts_speculations;
14214 	int nspec = state->dts_nspeculations;
14215 	uint32_t match;
14216 
14217 	ASSERT(MUTEX_HELD(&dtrace_lock));
14218 	ASSERT(MUTEX_HELD(&cpu_lock));
14219 
14220 	/*
14221 	 * First, retract any retained enablings for this state.
14222 	 */
14223 	dtrace_enabling_retract(state);
14224 	ASSERT(state->dts_nretained == 0);
14225 
14226 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14227 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14228 		/*
14229 		 * We have managed to come into dtrace_state_destroy() on a
14230 		 * hot enabling -- almost certainly because of a disorderly
14231 		 * shutdown of a consumer.  (That is, a consumer that is
14232 		 * exiting without having called dtrace_stop().) In this case,
14233 		 * we're going to set our activity to be KILLED, and then
14234 		 * issue a sync to be sure that everyone is out of probe
14235 		 * context before we start blowing away ECBs.
14236 		 */
14237 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
14238 		dtrace_sync();
14239 	}
14240 
14241 	/*
14242 	 * Release the credential hold we took in dtrace_state_create().
14243 	 */
14244 	if (state->dts_cred.dcr_cred != NULL)
14245 		crfree(state->dts_cred.dcr_cred);
14246 
14247 	/*
14248 	 * Now we can safely disable and destroy any enabled probes.  Because
14249 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
14250 	 * (especially if they're all enabled), we take two passes through the
14251 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
14252 	 * in the second we disable whatever is left over.
14253 	 */
14254 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
14255 		for (i = 0; i < state->dts_necbs; i++) {
14256 			if ((ecb = state->dts_ecbs[i]) == NULL)
14257 				continue;
14258 
14259 			if (match && ecb->dte_probe != NULL) {
14260 				dtrace_probe_t *probe = ecb->dte_probe;
14261 				dtrace_provider_t *prov = probe->dtpr_provider;
14262 
14263 				if (!(prov->dtpv_priv.dtpp_flags & match))
14264 					continue;
14265 			}
14266 
14267 			dtrace_ecb_disable(ecb);
14268 			dtrace_ecb_destroy(ecb);
14269 		}
14270 
14271 		if (!match)
14272 			break;
14273 	}
14274 
14275 	/*
14276 	 * Before we free the buffers, perform one more sync to assure that
14277 	 * every CPU is out of probe context.
14278 	 */
14279 	dtrace_sync();
14280 
14281 	dtrace_buffer_free(state->dts_buffer);
14282 	dtrace_buffer_free(state->dts_aggbuffer);
14283 
14284 	for (i = 0; i < nspec; i++)
14285 		dtrace_buffer_free(spec[i].dtsp_buffer);
14286 
14287 	if (state->dts_cleaner != CYCLIC_NONE)
14288 		cyclic_remove(state->dts_cleaner);
14289 
14290 	if (state->dts_deadman != CYCLIC_NONE)
14291 		cyclic_remove(state->dts_deadman);
14292 
14293 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
14294 	dtrace_vstate_fini(vstate);
14295 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14296 
14297 	if (state->dts_aggregations != NULL) {
14298 #ifdef DEBUG
14299 		for (i = 0; i < state->dts_naggregations; i++)
14300 			ASSERT(state->dts_aggregations[i] == NULL);
14301 #endif
14302 		ASSERT(state->dts_naggregations > 0);
14303 		kmem_free(state->dts_aggregations,
14304 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14305 	}
14306 
14307 	kmem_free(state->dts_buffer, bufsize);
14308 	kmem_free(state->dts_aggbuffer, bufsize);
14309 
14310 	for (i = 0; i < nspec; i++)
14311 		kmem_free(spec[i].dtsp_buffer, bufsize);
14312 
14313 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14314 
14315 	dtrace_format_destroy(state);
14316 
14317 	vmem_destroy(state->dts_aggid_arena);
14318 	ddi_soft_state_free(dtrace_softstate, minor);
14319 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14320 }
14321 
14322 /*
14323  * DTrace Anonymous Enabling Functions
14324  */
14325 static dtrace_state_t *
14326 dtrace_anon_grab(void)
14327 {
14328 	dtrace_state_t *state;
14329 
14330 	ASSERT(MUTEX_HELD(&dtrace_lock));
14331 
14332 	if ((state = dtrace_anon.dta_state) == NULL) {
14333 		ASSERT(dtrace_anon.dta_enabling == NULL);
14334 		return (NULL);
14335 	}
14336 
14337 	ASSERT(dtrace_anon.dta_enabling != NULL);
14338 	ASSERT(dtrace_retained != NULL);
14339 
14340 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14341 	dtrace_anon.dta_enabling = NULL;
14342 	dtrace_anon.dta_state = NULL;
14343 
14344 	return (state);
14345 }
14346 
14347 static void
14348 dtrace_anon_property(void)
14349 {
14350 	int i, rv;
14351 	dtrace_state_t *state;
14352 	dof_hdr_t *dof;
14353 	char c[32];		/* enough for "dof-data-" + digits */
14354 
14355 	ASSERT(MUTEX_HELD(&dtrace_lock));
14356 	ASSERT(MUTEX_HELD(&cpu_lock));
14357 
14358 	for (i = 0; ; i++) {
14359 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
14360 
14361 		dtrace_err_verbose = 1;
14362 
14363 		if ((dof = dtrace_dof_property(c)) == NULL) {
14364 			dtrace_err_verbose = 0;
14365 			break;
14366 		}
14367 
14368 		/*
14369 		 * We want to create anonymous state, so we need to transition
14370 		 * the kernel debugger to indicate that DTrace is active.  If
14371 		 * this fails (e.g. because the debugger has modified text in
14372 		 * some way), we won't continue with the processing.
14373 		 */
14374 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14375 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14376 			    "enabling ignored.");
14377 			dtrace_dof_destroy(dof);
14378 			break;
14379 		}
14380 
14381 		/*
14382 		 * If we haven't allocated an anonymous state, we'll do so now.
14383 		 */
14384 		if ((state = dtrace_anon.dta_state) == NULL) {
14385 			state = dtrace_state_create(NULL, NULL);
14386 			dtrace_anon.dta_state = state;
14387 
14388 			if (state == NULL) {
14389 				/*
14390 				 * This basically shouldn't happen:  the only
14391 				 * failure mode from dtrace_state_create() is a
14392 				 * failure of ddi_soft_state_zalloc() that
14393 				 * itself should never happen.  Still, the
14394 				 * interface allows for a failure mode, and
14395 				 * we want to fail as gracefully as possible:
14396 				 * we'll emit an error message and cease
14397 				 * processing anonymous state in this case.
14398 				 */
14399 				cmn_err(CE_WARN, "failed to create "
14400 				    "anonymous state");
14401 				dtrace_dof_destroy(dof);
14402 				break;
14403 			}
14404 		}
14405 
14406 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14407 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
14408 
14409 		if (rv == 0)
14410 			rv = dtrace_dof_options(dof, state);
14411 
14412 		dtrace_err_verbose = 0;
14413 		dtrace_dof_destroy(dof);
14414 
14415 		if (rv != 0) {
14416 			/*
14417 			 * This is malformed DOF; chuck any anonymous state
14418 			 * that we created.
14419 			 */
14420 			ASSERT(dtrace_anon.dta_enabling == NULL);
14421 			dtrace_state_destroy(state);
14422 			dtrace_anon.dta_state = NULL;
14423 			break;
14424 		}
14425 
14426 		ASSERT(dtrace_anon.dta_enabling != NULL);
14427 	}
14428 
14429 	if (dtrace_anon.dta_enabling != NULL) {
14430 		int rval;
14431 
14432 		/*
14433 		 * dtrace_enabling_retain() can only fail because we are
14434 		 * trying to retain more enablings than are allowed -- but
14435 		 * we only have one anonymous enabling, and we are guaranteed
14436 		 * to be allowed at least one retained enabling; we assert
14437 		 * that dtrace_enabling_retain() returns success.
14438 		 */
14439 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14440 		ASSERT(rval == 0);
14441 
14442 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
14443 	}
14444 }
14445 
14446 /*
14447  * DTrace Helper Functions
14448  */
14449 static void
14450 dtrace_helper_trace(dtrace_helper_action_t *helper,
14451     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14452 {
14453 	uint32_t size, next, nnext, i;
14454 	dtrace_helptrace_t *ent, *buffer;
14455 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14456 
14457 	if ((buffer = dtrace_helptrace_buffer) == NULL)
14458 		return;
14459 
14460 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14461 
14462 	/*
14463 	 * What would a tracing framework be without its own tracing
14464 	 * framework?  (Well, a hell of a lot simpler, for starters...)
14465 	 */
14466 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14467 	    sizeof (uint64_t) - sizeof (uint64_t);
14468 
14469 	/*
14470 	 * Iterate until we can allocate a slot in the trace buffer.
14471 	 */
14472 	do {
14473 		next = dtrace_helptrace_next;
14474 
14475 		if (next + size < dtrace_helptrace_bufsize) {
14476 			nnext = next + size;
14477 		} else {
14478 			nnext = size;
14479 		}
14480 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14481 
14482 	/*
14483 	 * We have our slot; fill it in.
14484 	 */
14485 	if (nnext == size) {
14486 		dtrace_helptrace_wrapped++;
14487 		next = 0;
14488 	}
14489 
14490 	ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
14491 	ent->dtht_helper = helper;
14492 	ent->dtht_where = where;
14493 	ent->dtht_nlocals = vstate->dtvs_nlocals;
14494 
14495 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14496 	    mstate->dtms_fltoffs : -1;
14497 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14498 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
14499 
14500 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
14501 		dtrace_statvar_t *svar;
14502 
14503 		if ((svar = vstate->dtvs_locals[i]) == NULL)
14504 			continue;
14505 
14506 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14507 		ent->dtht_locals[i] =
14508 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
14509 	}
14510 }
14511 
14512 static uint64_t
14513 dtrace_helper(int which, dtrace_mstate_t *mstate,
14514     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14515 {
14516 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14517 	uint64_t sarg0 = mstate->dtms_arg[0];
14518 	uint64_t sarg1 = mstate->dtms_arg[1];
14519 	uint64_t rval;
14520 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14521 	dtrace_helper_action_t *helper;
14522 	dtrace_vstate_t *vstate;
14523 	dtrace_difo_t *pred;
14524 	int i, trace = dtrace_helptrace_buffer != NULL;
14525 
14526 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14527 
14528 	if (helpers == NULL)
14529 		return (0);
14530 
14531 	if ((helper = helpers->dthps_actions[which]) == NULL)
14532 		return (0);
14533 
14534 	vstate = &helpers->dthps_vstate;
14535 	mstate->dtms_arg[0] = arg0;
14536 	mstate->dtms_arg[1] = arg1;
14537 
14538 	/*
14539 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
14540 	 * we'll call the corresponding actions.  Note that the below calls
14541 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
14542 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
14543 	 * the stored DIF offset with its own (which is the desired behavior).
14544 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14545 	 * from machine state; this is okay, too.
14546 	 */
14547 	for (; helper != NULL; helper = helper->dtha_next) {
14548 		if ((pred = helper->dtha_predicate) != NULL) {
14549 			if (trace)
14550 				dtrace_helper_trace(helper, mstate, vstate, 0);
14551 
14552 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14553 				goto next;
14554 
14555 			if (*flags & CPU_DTRACE_FAULT)
14556 				goto err;
14557 		}
14558 
14559 		for (i = 0; i < helper->dtha_nactions; i++) {
14560 			if (trace)
14561 				dtrace_helper_trace(helper,
14562 				    mstate, vstate, i + 1);
14563 
14564 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
14565 			    mstate, vstate, state);
14566 
14567 			if (*flags & CPU_DTRACE_FAULT)
14568 				goto err;
14569 		}
14570 
14571 next:
14572 		if (trace)
14573 			dtrace_helper_trace(helper, mstate, vstate,
14574 			    DTRACE_HELPTRACE_NEXT);
14575 	}
14576 
14577 	if (trace)
14578 		dtrace_helper_trace(helper, mstate, vstate,
14579 		    DTRACE_HELPTRACE_DONE);
14580 
14581 	/*
14582 	 * Restore the arg0 that we saved upon entry.
14583 	 */
14584 	mstate->dtms_arg[0] = sarg0;
14585 	mstate->dtms_arg[1] = sarg1;
14586 
14587 	return (rval);
14588 
14589 err:
14590 	if (trace)
14591 		dtrace_helper_trace(helper, mstate, vstate,
14592 		    DTRACE_HELPTRACE_ERR);
14593 
14594 	/*
14595 	 * Restore the arg0 that we saved upon entry.
14596 	 */
14597 	mstate->dtms_arg[0] = sarg0;
14598 	mstate->dtms_arg[1] = sarg1;
14599 
14600 	return (NULL);
14601 }
14602 
14603 static void
14604 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14605     dtrace_vstate_t *vstate)
14606 {
14607 	int i;
14608 
14609 	if (helper->dtha_predicate != NULL)
14610 		dtrace_difo_release(helper->dtha_predicate, vstate);
14611 
14612 	for (i = 0; i < helper->dtha_nactions; i++) {
14613 		ASSERT(helper->dtha_actions[i] != NULL);
14614 		dtrace_difo_release(helper->dtha_actions[i], vstate);
14615 	}
14616 
14617 	kmem_free(helper->dtha_actions,
14618 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
14619 	kmem_free(helper, sizeof (dtrace_helper_action_t));
14620 }
14621 
14622 static int
14623 dtrace_helper_destroygen(int gen)
14624 {
14625 	proc_t *p = curproc;
14626 	dtrace_helpers_t *help = p->p_dtrace_helpers;
14627 	dtrace_vstate_t *vstate;
14628 	int i;
14629 
14630 	ASSERT(MUTEX_HELD(&dtrace_lock));
14631 
14632 	if (help == NULL || gen > help->dthps_generation)
14633 		return (EINVAL);
14634 
14635 	vstate = &help->dthps_vstate;
14636 
14637 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14638 		dtrace_helper_action_t *last = NULL, *h, *next;
14639 
14640 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
14641 			next = h->dtha_next;
14642 
14643 			if (h->dtha_generation == gen) {
14644 				if (last != NULL) {
14645 					last->dtha_next = next;
14646 				} else {
14647 					help->dthps_actions[i] = next;
14648 				}
14649 
14650 				dtrace_helper_action_destroy(h, vstate);
14651 			} else {
14652 				last = h;
14653 			}
14654 		}
14655 	}
14656 
14657 	/*
14658 	 * Interate until we've cleared out all helper providers with the
14659 	 * given generation number.
14660 	 */
14661 	for (;;) {
14662 		dtrace_helper_provider_t *prov;
14663 
14664 		/*
14665 		 * Look for a helper provider with the right generation. We
14666 		 * have to start back at the beginning of the list each time
14667 		 * because we drop dtrace_lock. It's unlikely that we'll make
14668 		 * more than two passes.
14669 		 */
14670 		for (i = 0; i < help->dthps_nprovs; i++) {
14671 			prov = help->dthps_provs[i];
14672 
14673 			if (prov->dthp_generation == gen)
14674 				break;
14675 		}
14676 
14677 		/*
14678 		 * If there were no matches, we're done.
14679 		 */
14680 		if (i == help->dthps_nprovs)
14681 			break;
14682 
14683 		/*
14684 		 * Move the last helper provider into this slot.
14685 		 */
14686 		help->dthps_nprovs--;
14687 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14688 		help->dthps_provs[help->dthps_nprovs] = NULL;
14689 
14690 		mutex_exit(&dtrace_lock);
14691 
14692 		/*
14693 		 * If we have a meta provider, remove this helper provider.
14694 		 */
14695 		mutex_enter(&dtrace_meta_lock);
14696 		if (dtrace_meta_pid != NULL) {
14697 			ASSERT(dtrace_deferred_pid == NULL);
14698 			dtrace_helper_provider_remove(&prov->dthp_prov,
14699 			    p->p_pid);
14700 		}
14701 		mutex_exit(&dtrace_meta_lock);
14702 
14703 		dtrace_helper_provider_destroy(prov);
14704 
14705 		mutex_enter(&dtrace_lock);
14706 	}
14707 
14708 	return (0);
14709 }
14710 
14711 static int
14712 dtrace_helper_validate(dtrace_helper_action_t *helper)
14713 {
14714 	int err = 0, i;
14715 	dtrace_difo_t *dp;
14716 
14717 	if ((dp = helper->dtha_predicate) != NULL)
14718 		err += dtrace_difo_validate_helper(dp);
14719 
14720 	for (i = 0; i < helper->dtha_nactions; i++)
14721 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14722 
14723 	return (err == 0);
14724 }
14725 
14726 static int
14727 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14728 {
14729 	dtrace_helpers_t *help;
14730 	dtrace_helper_action_t *helper, *last;
14731 	dtrace_actdesc_t *act;
14732 	dtrace_vstate_t *vstate;
14733 	dtrace_predicate_t *pred;
14734 	int count = 0, nactions = 0, i;
14735 
14736 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14737 		return (EINVAL);
14738 
14739 	help = curproc->p_dtrace_helpers;
14740 	last = help->dthps_actions[which];
14741 	vstate = &help->dthps_vstate;
14742 
14743 	for (count = 0; last != NULL; last = last->dtha_next) {
14744 		count++;
14745 		if (last->dtha_next == NULL)
14746 			break;
14747 	}
14748 
14749 	/*
14750 	 * If we already have dtrace_helper_actions_max helper actions for this
14751 	 * helper action type, we'll refuse to add a new one.
14752 	 */
14753 	if (count >= dtrace_helper_actions_max)
14754 		return (ENOSPC);
14755 
14756 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14757 	helper->dtha_generation = help->dthps_generation;
14758 
14759 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14760 		ASSERT(pred->dtp_difo != NULL);
14761 		dtrace_difo_hold(pred->dtp_difo);
14762 		helper->dtha_predicate = pred->dtp_difo;
14763 	}
14764 
14765 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14766 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
14767 			goto err;
14768 
14769 		if (act->dtad_difo == NULL)
14770 			goto err;
14771 
14772 		nactions++;
14773 	}
14774 
14775 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14776 	    (helper->dtha_nactions = nactions), KM_SLEEP);
14777 
14778 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14779 		dtrace_difo_hold(act->dtad_difo);
14780 		helper->dtha_actions[i++] = act->dtad_difo;
14781 	}
14782 
14783 	if (!dtrace_helper_validate(helper))
14784 		goto err;
14785 
14786 	if (last == NULL) {
14787 		help->dthps_actions[which] = helper;
14788 	} else {
14789 		last->dtha_next = helper;
14790 	}
14791 
14792 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14793 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14794 		dtrace_helptrace_next = 0;
14795 	}
14796 
14797 	return (0);
14798 err:
14799 	dtrace_helper_action_destroy(helper, vstate);
14800 	return (EINVAL);
14801 }
14802 
14803 static void
14804 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14805     dof_helper_t *dofhp)
14806 {
14807 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
14808 
14809 	mutex_enter(&dtrace_meta_lock);
14810 	mutex_enter(&dtrace_lock);
14811 
14812 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14813 		/*
14814 		 * If the dtrace module is loaded but not attached, or if
14815 		 * there aren't isn't a meta provider registered to deal with
14816 		 * these provider descriptions, we need to postpone creating
14817 		 * the actual providers until later.
14818 		 */
14819 
14820 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14821 		    dtrace_deferred_pid != help) {
14822 			help->dthps_deferred = 1;
14823 			help->dthps_pid = p->p_pid;
14824 			help->dthps_next = dtrace_deferred_pid;
14825 			help->dthps_prev = NULL;
14826 			if (dtrace_deferred_pid != NULL)
14827 				dtrace_deferred_pid->dthps_prev = help;
14828 			dtrace_deferred_pid = help;
14829 		}
14830 
14831 		mutex_exit(&dtrace_lock);
14832 
14833 	} else if (dofhp != NULL) {
14834 		/*
14835 		 * If the dtrace module is loaded and we have a particular
14836 		 * helper provider description, pass that off to the
14837 		 * meta provider.
14838 		 */
14839 
14840 		mutex_exit(&dtrace_lock);
14841 
14842 		dtrace_helper_provide(dofhp, p->p_pid);
14843 
14844 	} else {
14845 		/*
14846 		 * Otherwise, just pass all the helper provider descriptions
14847 		 * off to the meta provider.
14848 		 */
14849 
14850 		int i;
14851 		mutex_exit(&dtrace_lock);
14852 
14853 		for (i = 0; i < help->dthps_nprovs; i++) {
14854 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14855 			    p->p_pid);
14856 		}
14857 	}
14858 
14859 	mutex_exit(&dtrace_meta_lock);
14860 }
14861 
14862 static int
14863 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14864 {
14865 	dtrace_helpers_t *help;
14866 	dtrace_helper_provider_t *hprov, **tmp_provs;
14867 	uint_t tmp_maxprovs, i;
14868 
14869 	ASSERT(MUTEX_HELD(&dtrace_lock));
14870 
14871 	help = curproc->p_dtrace_helpers;
14872 	ASSERT(help != NULL);
14873 
14874 	/*
14875 	 * If we already have dtrace_helper_providers_max helper providers,
14876 	 * we're refuse to add a new one.
14877 	 */
14878 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
14879 		return (ENOSPC);
14880 
14881 	/*
14882 	 * Check to make sure this isn't a duplicate.
14883 	 */
14884 	for (i = 0; i < help->dthps_nprovs; i++) {
14885 		if (dofhp->dofhp_addr ==
14886 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
14887 			return (EALREADY);
14888 	}
14889 
14890 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14891 	hprov->dthp_prov = *dofhp;
14892 	hprov->dthp_ref = 1;
14893 	hprov->dthp_generation = gen;
14894 
14895 	/*
14896 	 * Allocate a bigger table for helper providers if it's already full.
14897 	 */
14898 	if (help->dthps_maxprovs == help->dthps_nprovs) {
14899 		tmp_maxprovs = help->dthps_maxprovs;
14900 		tmp_provs = help->dthps_provs;
14901 
14902 		if (help->dthps_maxprovs == 0)
14903 			help->dthps_maxprovs = 2;
14904 		else
14905 			help->dthps_maxprovs *= 2;
14906 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
14907 			help->dthps_maxprovs = dtrace_helper_providers_max;
14908 
14909 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14910 
14911 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14912 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14913 
14914 		if (tmp_provs != NULL) {
14915 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14916 			    sizeof (dtrace_helper_provider_t *));
14917 			kmem_free(tmp_provs, tmp_maxprovs *
14918 			    sizeof (dtrace_helper_provider_t *));
14919 		}
14920 	}
14921 
14922 	help->dthps_provs[help->dthps_nprovs] = hprov;
14923 	help->dthps_nprovs++;
14924 
14925 	return (0);
14926 }
14927 
14928 static void
14929 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14930 {
14931 	mutex_enter(&dtrace_lock);
14932 
14933 	if (--hprov->dthp_ref == 0) {
14934 		dof_hdr_t *dof;
14935 		mutex_exit(&dtrace_lock);
14936 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14937 		dtrace_dof_destroy(dof);
14938 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14939 	} else {
14940 		mutex_exit(&dtrace_lock);
14941 	}
14942 }
14943 
14944 static int
14945 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14946 {
14947 	uintptr_t daddr = (uintptr_t)dof;
14948 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14949 	dof_provider_t *provider;
14950 	dof_probe_t *probe;
14951 	uint8_t *arg;
14952 	char *strtab, *typestr;
14953 	dof_stridx_t typeidx;
14954 	size_t typesz;
14955 	uint_t nprobes, j, k;
14956 
14957 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14958 
14959 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14960 		dtrace_dof_error(dof, "misaligned section offset");
14961 		return (-1);
14962 	}
14963 
14964 	/*
14965 	 * The section needs to be large enough to contain the DOF provider
14966 	 * structure appropriate for the given version.
14967 	 */
14968 	if (sec->dofs_size <
14969 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14970 	    offsetof(dof_provider_t, dofpv_prenoffs) :
14971 	    sizeof (dof_provider_t))) {
14972 		dtrace_dof_error(dof, "provider section too small");
14973 		return (-1);
14974 	}
14975 
14976 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14977 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14978 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14979 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14980 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14981 
14982 	if (str_sec == NULL || prb_sec == NULL ||
14983 	    arg_sec == NULL || off_sec == NULL)
14984 		return (-1);
14985 
14986 	enoff_sec = NULL;
14987 
14988 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14989 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
14990 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14991 	    provider->dofpv_prenoffs)) == NULL)
14992 		return (-1);
14993 
14994 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14995 
14996 	if (provider->dofpv_name >= str_sec->dofs_size ||
14997 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14998 		dtrace_dof_error(dof, "invalid provider name");
14999 		return (-1);
15000 	}
15001 
15002 	if (prb_sec->dofs_entsize == 0 ||
15003 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
15004 		dtrace_dof_error(dof, "invalid entry size");
15005 		return (-1);
15006 	}
15007 
15008 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
15009 		dtrace_dof_error(dof, "misaligned entry size");
15010 		return (-1);
15011 	}
15012 
15013 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
15014 		dtrace_dof_error(dof, "invalid entry size");
15015 		return (-1);
15016 	}
15017 
15018 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
15019 		dtrace_dof_error(dof, "misaligned section offset");
15020 		return (-1);
15021 	}
15022 
15023 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
15024 		dtrace_dof_error(dof, "invalid entry size");
15025 		return (-1);
15026 	}
15027 
15028 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
15029 
15030 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
15031 
15032 	/*
15033 	 * Take a pass through the probes to check for errors.
15034 	 */
15035 	for (j = 0; j < nprobes; j++) {
15036 		probe = (dof_probe_t *)(uintptr_t)(daddr +
15037 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
15038 
15039 		if (probe->dofpr_func >= str_sec->dofs_size) {
15040 			dtrace_dof_error(dof, "invalid function name");
15041 			return (-1);
15042 		}
15043 
15044 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
15045 			dtrace_dof_error(dof, "function name too long");
15046 			return (-1);
15047 		}
15048 
15049 		if (probe->dofpr_name >= str_sec->dofs_size ||
15050 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
15051 			dtrace_dof_error(dof, "invalid probe name");
15052 			return (-1);
15053 		}
15054 
15055 		/*
15056 		 * The offset count must not wrap the index, and the offsets
15057 		 * must also not overflow the section's data.
15058 		 */
15059 		if (probe->dofpr_offidx + probe->dofpr_noffs <
15060 		    probe->dofpr_offidx ||
15061 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
15062 		    off_sec->dofs_entsize > off_sec->dofs_size) {
15063 			dtrace_dof_error(dof, "invalid probe offset");
15064 			return (-1);
15065 		}
15066 
15067 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
15068 			/*
15069 			 * If there's no is-enabled offset section, make sure
15070 			 * there aren't any is-enabled offsets. Otherwise
15071 			 * perform the same checks as for probe offsets
15072 			 * (immediately above).
15073 			 */
15074 			if (enoff_sec == NULL) {
15075 				if (probe->dofpr_enoffidx != 0 ||
15076 				    probe->dofpr_nenoffs != 0) {
15077 					dtrace_dof_error(dof, "is-enabled "
15078 					    "offsets with null section");
15079 					return (-1);
15080 				}
15081 			} else if (probe->dofpr_enoffidx +
15082 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15083 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15084 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15085 				dtrace_dof_error(dof, "invalid is-enabled "
15086 				    "offset");
15087 				return (-1);
15088 			}
15089 
15090 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15091 				dtrace_dof_error(dof, "zero probe and "
15092 				    "is-enabled offsets");
15093 				return (-1);
15094 			}
15095 		} else if (probe->dofpr_noffs == 0) {
15096 			dtrace_dof_error(dof, "zero probe offsets");
15097 			return (-1);
15098 		}
15099 
15100 		if (probe->dofpr_argidx + probe->dofpr_xargc <
15101 		    probe->dofpr_argidx ||
15102 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
15103 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
15104 			dtrace_dof_error(dof, "invalid args");
15105 			return (-1);
15106 		}
15107 
15108 		typeidx = probe->dofpr_nargv;
15109 		typestr = strtab + probe->dofpr_nargv;
15110 		for (k = 0; k < probe->dofpr_nargc; k++) {
15111 			if (typeidx >= str_sec->dofs_size) {
15112 				dtrace_dof_error(dof, "bad "
15113 				    "native argument type");
15114 				return (-1);
15115 			}
15116 
15117 			typesz = strlen(typestr) + 1;
15118 			if (typesz > DTRACE_ARGTYPELEN) {
15119 				dtrace_dof_error(dof, "native "
15120 				    "argument type too long");
15121 				return (-1);
15122 			}
15123 			typeidx += typesz;
15124 			typestr += typesz;
15125 		}
15126 
15127 		typeidx = probe->dofpr_xargv;
15128 		typestr = strtab + probe->dofpr_xargv;
15129 		for (k = 0; k < probe->dofpr_xargc; k++) {
15130 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15131 				dtrace_dof_error(dof, "bad "
15132 				    "native argument index");
15133 				return (-1);
15134 			}
15135 
15136 			if (typeidx >= str_sec->dofs_size) {
15137 				dtrace_dof_error(dof, "bad "
15138 				    "translated argument type");
15139 				return (-1);
15140 			}
15141 
15142 			typesz = strlen(typestr) + 1;
15143 			if (typesz > DTRACE_ARGTYPELEN) {
15144 				dtrace_dof_error(dof, "translated argument "
15145 				    "type too long");
15146 				return (-1);
15147 			}
15148 
15149 			typeidx += typesz;
15150 			typestr += typesz;
15151 		}
15152 	}
15153 
15154 	return (0);
15155 }
15156 
15157 static int
15158 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
15159 {
15160 	dtrace_helpers_t *help;
15161 	dtrace_vstate_t *vstate;
15162 	dtrace_enabling_t *enab = NULL;
15163 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15164 	uintptr_t daddr = (uintptr_t)dof;
15165 
15166 	ASSERT(MUTEX_HELD(&dtrace_lock));
15167 
15168 	if ((help = curproc->p_dtrace_helpers) == NULL)
15169 		help = dtrace_helpers_create(curproc);
15170 
15171 	vstate = &help->dthps_vstate;
15172 
15173 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15174 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15175 		dtrace_dof_destroy(dof);
15176 		return (rv);
15177 	}
15178 
15179 	/*
15180 	 * Look for helper providers and validate their descriptions.
15181 	 */
15182 	if (dhp != NULL) {
15183 		for (i = 0; i < dof->dofh_secnum; i++) {
15184 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15185 			    dof->dofh_secoff + i * dof->dofh_secsize);
15186 
15187 			if (sec->dofs_type != DOF_SECT_PROVIDER)
15188 				continue;
15189 
15190 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
15191 				dtrace_enabling_destroy(enab);
15192 				dtrace_dof_destroy(dof);
15193 				return (-1);
15194 			}
15195 
15196 			nprovs++;
15197 		}
15198 	}
15199 
15200 	/*
15201 	 * Now we need to walk through the ECB descriptions in the enabling.
15202 	 */
15203 	for (i = 0; i < enab->dten_ndesc; i++) {
15204 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15205 		dtrace_probedesc_t *desc = &ep->dted_probe;
15206 
15207 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
15208 			continue;
15209 
15210 		if (strcmp(desc->dtpd_mod, "helper") != 0)
15211 			continue;
15212 
15213 		if (strcmp(desc->dtpd_func, "ustack") != 0)
15214 			continue;
15215 
15216 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
15217 		    ep)) != 0) {
15218 			/*
15219 			 * Adding this helper action failed -- we are now going
15220 			 * to rip out the entire generation and return failure.
15221 			 */
15222 			(void) dtrace_helper_destroygen(help->dthps_generation);
15223 			dtrace_enabling_destroy(enab);
15224 			dtrace_dof_destroy(dof);
15225 			return (-1);
15226 		}
15227 
15228 		nhelpers++;
15229 	}
15230 
15231 	if (nhelpers < enab->dten_ndesc)
15232 		dtrace_dof_error(dof, "unmatched helpers");
15233 
15234 	gen = help->dthps_generation++;
15235 	dtrace_enabling_destroy(enab);
15236 
15237 	if (dhp != NULL && nprovs > 0) {
15238 		/*
15239 		 * Now that this is in-kernel, we change the sense of the
15240 		 * members:  dofhp_dof denotes the in-kernel copy of the DOF
15241 		 * and dofhp_addr denotes the address at user-level.
15242 		 */
15243 		dhp->dofhp_addr = dhp->dofhp_dof;
15244 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15245 
15246 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
15247 			mutex_exit(&dtrace_lock);
15248 			dtrace_helper_provider_register(curproc, help, dhp);
15249 			mutex_enter(&dtrace_lock);
15250 
15251 			destroy = 0;
15252 		}
15253 	}
15254 
15255 	if (destroy)
15256 		dtrace_dof_destroy(dof);
15257 
15258 	return (gen);
15259 }
15260 
15261 static dtrace_helpers_t *
15262 dtrace_helpers_create(proc_t *p)
15263 {
15264 	dtrace_helpers_t *help;
15265 
15266 	ASSERT(MUTEX_HELD(&dtrace_lock));
15267 	ASSERT(p->p_dtrace_helpers == NULL);
15268 
15269 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15270 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15271 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15272 
15273 	p->p_dtrace_helpers = help;
15274 	dtrace_helpers++;
15275 
15276 	return (help);
15277 }
15278 
15279 static void
15280 dtrace_helpers_destroy(void)
15281 {
15282 	dtrace_helpers_t *help;
15283 	dtrace_vstate_t *vstate;
15284 	proc_t *p = curproc;
15285 	int i;
15286 
15287 	mutex_enter(&dtrace_lock);
15288 
15289 	ASSERT(p->p_dtrace_helpers != NULL);
15290 	ASSERT(dtrace_helpers > 0);
15291 
15292 	help = p->p_dtrace_helpers;
15293 	vstate = &help->dthps_vstate;
15294 
15295 	/*
15296 	 * We're now going to lose the help from this process.
15297 	 */
15298 	p->p_dtrace_helpers = NULL;
15299 	dtrace_sync();
15300 
15301 	/*
15302 	 * Destory the helper actions.
15303 	 */
15304 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15305 		dtrace_helper_action_t *h, *next;
15306 
15307 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15308 			next = h->dtha_next;
15309 			dtrace_helper_action_destroy(h, vstate);
15310 			h = next;
15311 		}
15312 	}
15313 
15314 	mutex_exit(&dtrace_lock);
15315 
15316 	/*
15317 	 * Destroy the helper providers.
15318 	 */
15319 	if (help->dthps_maxprovs > 0) {
15320 		mutex_enter(&dtrace_meta_lock);
15321 		if (dtrace_meta_pid != NULL) {
15322 			ASSERT(dtrace_deferred_pid == NULL);
15323 
15324 			for (i = 0; i < help->dthps_nprovs; i++) {
15325 				dtrace_helper_provider_remove(
15326 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
15327 			}
15328 		} else {
15329 			mutex_enter(&dtrace_lock);
15330 			ASSERT(help->dthps_deferred == 0 ||
15331 			    help->dthps_next != NULL ||
15332 			    help->dthps_prev != NULL ||
15333 			    help == dtrace_deferred_pid);
15334 
15335 			/*
15336 			 * Remove the helper from the deferred list.
15337 			 */
15338 			if (help->dthps_next != NULL)
15339 				help->dthps_next->dthps_prev = help->dthps_prev;
15340 			if (help->dthps_prev != NULL)
15341 				help->dthps_prev->dthps_next = help->dthps_next;
15342 			if (dtrace_deferred_pid == help) {
15343 				dtrace_deferred_pid = help->dthps_next;
15344 				ASSERT(help->dthps_prev == NULL);
15345 			}
15346 
15347 			mutex_exit(&dtrace_lock);
15348 		}
15349 
15350 		mutex_exit(&dtrace_meta_lock);
15351 
15352 		for (i = 0; i < help->dthps_nprovs; i++) {
15353 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
15354 		}
15355 
15356 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
15357 		    sizeof (dtrace_helper_provider_t *));
15358 	}
15359 
15360 	mutex_enter(&dtrace_lock);
15361 
15362 	dtrace_vstate_fini(&help->dthps_vstate);
15363 	kmem_free(help->dthps_actions,
15364 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15365 	kmem_free(help, sizeof (dtrace_helpers_t));
15366 
15367 	--dtrace_helpers;
15368 	mutex_exit(&dtrace_lock);
15369 }
15370 
15371 static void
15372 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15373 {
15374 	dtrace_helpers_t *help, *newhelp;
15375 	dtrace_helper_action_t *helper, *new, *last;
15376 	dtrace_difo_t *dp;
15377 	dtrace_vstate_t *vstate;
15378 	int i, j, sz, hasprovs = 0;
15379 
15380 	mutex_enter(&dtrace_lock);
15381 	ASSERT(from->p_dtrace_helpers != NULL);
15382 	ASSERT(dtrace_helpers > 0);
15383 
15384 	help = from->p_dtrace_helpers;
15385 	newhelp = dtrace_helpers_create(to);
15386 	ASSERT(to->p_dtrace_helpers != NULL);
15387 
15388 	newhelp->dthps_generation = help->dthps_generation;
15389 	vstate = &newhelp->dthps_vstate;
15390 
15391 	/*
15392 	 * Duplicate the helper actions.
15393 	 */
15394 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15395 		if ((helper = help->dthps_actions[i]) == NULL)
15396 			continue;
15397 
15398 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15399 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15400 			    KM_SLEEP);
15401 			new->dtha_generation = helper->dtha_generation;
15402 
15403 			if ((dp = helper->dtha_predicate) != NULL) {
15404 				dp = dtrace_difo_duplicate(dp, vstate);
15405 				new->dtha_predicate = dp;
15406 			}
15407 
15408 			new->dtha_nactions = helper->dtha_nactions;
15409 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15410 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15411 
15412 			for (j = 0; j < new->dtha_nactions; j++) {
15413 				dtrace_difo_t *dp = helper->dtha_actions[j];
15414 
15415 				ASSERT(dp != NULL);
15416 				dp = dtrace_difo_duplicate(dp, vstate);
15417 				new->dtha_actions[j] = dp;
15418 			}
15419 
15420 			if (last != NULL) {
15421 				last->dtha_next = new;
15422 			} else {
15423 				newhelp->dthps_actions[i] = new;
15424 			}
15425 
15426 			last = new;
15427 		}
15428 	}
15429 
15430 	/*
15431 	 * Duplicate the helper providers and register them with the
15432 	 * DTrace framework.
15433 	 */
15434 	if (help->dthps_nprovs > 0) {
15435 		newhelp->dthps_nprovs = help->dthps_nprovs;
15436 		newhelp->dthps_maxprovs = help->dthps_nprovs;
15437 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15438 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15439 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
15440 			newhelp->dthps_provs[i] = help->dthps_provs[i];
15441 			newhelp->dthps_provs[i]->dthp_ref++;
15442 		}
15443 
15444 		hasprovs = 1;
15445 	}
15446 
15447 	mutex_exit(&dtrace_lock);
15448 
15449 	if (hasprovs)
15450 		dtrace_helper_provider_register(to, newhelp, NULL);
15451 }
15452 
15453 /*
15454  * DTrace Hook Functions
15455  */
15456 static void
15457 dtrace_module_loaded(struct modctl *ctl)
15458 {
15459 	dtrace_provider_t *prv;
15460 
15461 	mutex_enter(&dtrace_provider_lock);
15462 	mutex_enter(&mod_lock);
15463 
15464 	ASSERT(ctl->mod_busy);
15465 
15466 	/*
15467 	 * We're going to call each providers per-module provide operation
15468 	 * specifying only this module.
15469 	 */
15470 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15471 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15472 
15473 	mutex_exit(&mod_lock);
15474 	mutex_exit(&dtrace_provider_lock);
15475 
15476 	/*
15477 	 * If we have any retained enablings, we need to match against them.
15478 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
15479 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15480 	 * module.  (In particular, this happens when loading scheduling
15481 	 * classes.)  So if we have any retained enablings, we need to dispatch
15482 	 * our task queue to do the match for us.
15483 	 */
15484 	mutex_enter(&dtrace_lock);
15485 
15486 	if (dtrace_retained == NULL) {
15487 		mutex_exit(&dtrace_lock);
15488 		return;
15489 	}
15490 
15491 	(void) taskq_dispatch(dtrace_taskq,
15492 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15493 
15494 	mutex_exit(&dtrace_lock);
15495 
15496 	/*
15497 	 * And now, for a little heuristic sleaze:  in general, we want to
15498 	 * match modules as soon as they load.  However, we cannot guarantee
15499 	 * this, because it would lead us to the lock ordering violation
15500 	 * outlined above.  The common case, of course, is that cpu_lock is
15501 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
15502 	 * long enough for the task queue to do its work.  If it's not, it's
15503 	 * not a serious problem -- it just means that the module that we
15504 	 * just loaded may not be immediately instrumentable.
15505 	 */
15506 	delay(1);
15507 }
15508 
15509 static void
15510 dtrace_module_unloaded(struct modctl *ctl)
15511 {
15512 	dtrace_probe_t template, *probe, *first, *next;
15513 	dtrace_provider_t *prov;
15514 
15515 	template.dtpr_mod = ctl->mod_modname;
15516 
15517 	mutex_enter(&dtrace_provider_lock);
15518 	mutex_enter(&mod_lock);
15519 	mutex_enter(&dtrace_lock);
15520 
15521 	if (dtrace_bymod == NULL) {
15522 		/*
15523 		 * The DTrace module is loaded (obviously) but not attached;
15524 		 * we don't have any work to do.
15525 		 */
15526 		mutex_exit(&dtrace_provider_lock);
15527 		mutex_exit(&mod_lock);
15528 		mutex_exit(&dtrace_lock);
15529 		return;
15530 	}
15531 
15532 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15533 	    probe != NULL; probe = probe->dtpr_nextmod) {
15534 		if (probe->dtpr_ecb != NULL) {
15535 			mutex_exit(&dtrace_provider_lock);
15536 			mutex_exit(&mod_lock);
15537 			mutex_exit(&dtrace_lock);
15538 
15539 			/*
15540 			 * This shouldn't _actually_ be possible -- we're
15541 			 * unloading a module that has an enabled probe in it.
15542 			 * (It's normally up to the provider to make sure that
15543 			 * this can't happen.)  However, because dtps_enable()
15544 			 * doesn't have a failure mode, there can be an
15545 			 * enable/unload race.  Upshot:  we don't want to
15546 			 * assert, but we're not going to disable the
15547 			 * probe, either.
15548 			 */
15549 			if (dtrace_err_verbose) {
15550 				cmn_err(CE_WARN, "unloaded module '%s' had "
15551 				    "enabled probes", ctl->mod_modname);
15552 			}
15553 
15554 			return;
15555 		}
15556 	}
15557 
15558 	probe = first;
15559 
15560 	for (first = NULL; probe != NULL; probe = next) {
15561 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15562 
15563 		dtrace_probes[probe->dtpr_id - 1] = NULL;
15564 
15565 		next = probe->dtpr_nextmod;
15566 		dtrace_hash_remove(dtrace_bymod, probe);
15567 		dtrace_hash_remove(dtrace_byfunc, probe);
15568 		dtrace_hash_remove(dtrace_byname, probe);
15569 
15570 		if (first == NULL) {
15571 			first = probe;
15572 			probe->dtpr_nextmod = NULL;
15573 		} else {
15574 			probe->dtpr_nextmod = first;
15575 			first = probe;
15576 		}
15577 	}
15578 
15579 	/*
15580 	 * We've removed all of the module's probes from the hash chains and
15581 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
15582 	 * everyone has cleared out from any probe array processing.
15583 	 */
15584 	dtrace_sync();
15585 
15586 	for (probe = first; probe != NULL; probe = first) {
15587 		first = probe->dtpr_nextmod;
15588 		prov = probe->dtpr_provider;
15589 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15590 		    probe->dtpr_arg);
15591 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15592 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15593 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15594 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15595 		kmem_free(probe, sizeof (dtrace_probe_t));
15596 	}
15597 
15598 	mutex_exit(&dtrace_lock);
15599 	mutex_exit(&mod_lock);
15600 	mutex_exit(&dtrace_provider_lock);
15601 }
15602 
15603 void
15604 dtrace_suspend(void)
15605 {
15606 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15607 }
15608 
15609 void
15610 dtrace_resume(void)
15611 {
15612 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15613 }
15614 
15615 static int
15616 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15617 {
15618 	ASSERT(MUTEX_HELD(&cpu_lock));
15619 	mutex_enter(&dtrace_lock);
15620 
15621 	switch (what) {
15622 	case CPU_CONFIG: {
15623 		dtrace_state_t *state;
15624 		dtrace_optval_t *opt, rs, c;
15625 
15626 		/*
15627 		 * For now, we only allocate a new buffer for anonymous state.
15628 		 */
15629 		if ((state = dtrace_anon.dta_state) == NULL)
15630 			break;
15631 
15632 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15633 			break;
15634 
15635 		opt = state->dts_options;
15636 		c = opt[DTRACEOPT_CPU];
15637 
15638 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15639 			break;
15640 
15641 		/*
15642 		 * Regardless of what the actual policy is, we're going to
15643 		 * temporarily set our resize policy to be manual.  We're
15644 		 * also going to temporarily set our CPU option to denote
15645 		 * the newly configured CPU.
15646 		 */
15647 		rs = opt[DTRACEOPT_BUFRESIZE];
15648 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15649 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15650 
15651 		(void) dtrace_state_buffers(state);
15652 
15653 		opt[DTRACEOPT_BUFRESIZE] = rs;
15654 		opt[DTRACEOPT_CPU] = c;
15655 
15656 		break;
15657 	}
15658 
15659 	case CPU_UNCONFIG:
15660 		/*
15661 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
15662 		 * buffer will be freed when the consumer exits.)
15663 		 */
15664 		break;
15665 
15666 	default:
15667 		break;
15668 	}
15669 
15670 	mutex_exit(&dtrace_lock);
15671 	return (0);
15672 }
15673 
15674 static void
15675 dtrace_cpu_setup_initial(processorid_t cpu)
15676 {
15677 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15678 }
15679 
15680 static void
15681 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15682 {
15683 	if (dtrace_toxranges >= dtrace_toxranges_max) {
15684 		int osize, nsize;
15685 		dtrace_toxrange_t *range;
15686 
15687 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15688 
15689 		if (osize == 0) {
15690 			ASSERT(dtrace_toxrange == NULL);
15691 			ASSERT(dtrace_toxranges_max == 0);
15692 			dtrace_toxranges_max = 1;
15693 		} else {
15694 			dtrace_toxranges_max <<= 1;
15695 		}
15696 
15697 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15698 		range = kmem_zalloc(nsize, KM_SLEEP);
15699 
15700 		if (dtrace_toxrange != NULL) {
15701 			ASSERT(osize != 0);
15702 			bcopy(dtrace_toxrange, range, osize);
15703 			kmem_free(dtrace_toxrange, osize);
15704 		}
15705 
15706 		dtrace_toxrange = range;
15707 	}
15708 
15709 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
15710 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
15711 
15712 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15713 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15714 	dtrace_toxranges++;
15715 }
15716 
15717 static void
15718 dtrace_getf_barrier()
15719 {
15720 	/*
15721 	 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
15722 	 * that contain calls to getf(), this routine will be called on every
15723 	 * closef() before either the underlying vnode is released or the
15724 	 * file_t itself is freed.  By the time we are here, it is essential
15725 	 * that the file_t can no longer be accessed from a call to getf()
15726 	 * in probe context -- that assures that a dtrace_sync() can be used
15727 	 * to clear out any enablings referring to the old structures.
15728 	 */
15729 	if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
15730 	    kcred->cr_zone->zone_dtrace_getf != 0)
15731 		dtrace_sync();
15732 }
15733 
15734 /*
15735  * DTrace Driver Cookbook Functions
15736  */
15737 /*ARGSUSED*/
15738 static int
15739 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15740 {
15741 	dtrace_provider_id_t id;
15742 	dtrace_state_t *state = NULL;
15743 	dtrace_enabling_t *enab;
15744 
15745 	mutex_enter(&cpu_lock);
15746 	mutex_enter(&dtrace_provider_lock);
15747 	mutex_enter(&dtrace_lock);
15748 
15749 	if (ddi_soft_state_init(&dtrace_softstate,
15750 	    sizeof (dtrace_state_t), 0) != 0) {
15751 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15752 		mutex_exit(&cpu_lock);
15753 		mutex_exit(&dtrace_provider_lock);
15754 		mutex_exit(&dtrace_lock);
15755 		return (DDI_FAILURE);
15756 	}
15757 
15758 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
15759 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
15760 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
15761 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
15762 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
15763 		ddi_remove_minor_node(devi, NULL);
15764 		ddi_soft_state_fini(&dtrace_softstate);
15765 		mutex_exit(&cpu_lock);
15766 		mutex_exit(&dtrace_provider_lock);
15767 		mutex_exit(&dtrace_lock);
15768 		return (DDI_FAILURE);
15769 	}
15770 
15771 	ddi_report_dev(devi);
15772 	dtrace_devi = devi;
15773 
15774 	dtrace_modload = dtrace_module_loaded;
15775 	dtrace_modunload = dtrace_module_unloaded;
15776 	dtrace_cpu_init = dtrace_cpu_setup_initial;
15777 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
15778 	dtrace_helpers_fork = dtrace_helpers_duplicate;
15779 	dtrace_cpustart_init = dtrace_suspend;
15780 	dtrace_cpustart_fini = dtrace_resume;
15781 	dtrace_debugger_init = dtrace_suspend;
15782 	dtrace_debugger_fini = dtrace_resume;
15783 
15784 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15785 
15786 	ASSERT(MUTEX_HELD(&cpu_lock));
15787 
15788 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15789 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15790 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15791 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15792 	    VM_SLEEP | VMC_IDENTIFIER);
15793 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15794 	    1, INT_MAX, 0);
15795 
15796 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15797 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
15798 	    NULL, NULL, NULL, NULL, NULL, 0);
15799 
15800 	ASSERT(MUTEX_HELD(&cpu_lock));
15801 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15802 	    offsetof(dtrace_probe_t, dtpr_nextmod),
15803 	    offsetof(dtrace_probe_t, dtpr_prevmod));
15804 
15805 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15806 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
15807 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
15808 
15809 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15810 	    offsetof(dtrace_probe_t, dtpr_nextname),
15811 	    offsetof(dtrace_probe_t, dtpr_prevname));
15812 
15813 	if (dtrace_retain_max < 1) {
15814 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15815 		    "setting to 1", dtrace_retain_max);
15816 		dtrace_retain_max = 1;
15817 	}
15818 
15819 	/*
15820 	 * Now discover our toxic ranges.
15821 	 */
15822 	dtrace_toxic_ranges(dtrace_toxrange_add);
15823 
15824 	/*
15825 	 * Before we register ourselves as a provider to our own framework,
15826 	 * we would like to assert that dtrace_provider is NULL -- but that's
15827 	 * not true if we were loaded as a dependency of a DTrace provider.
15828 	 * Once we've registered, we can assert that dtrace_provider is our
15829 	 * pseudo provider.
15830 	 */
15831 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
15832 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15833 
15834 	ASSERT(dtrace_provider != NULL);
15835 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15836 
15837 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15838 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
15839 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15840 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
15841 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15842 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15843 
15844 	dtrace_anon_property();
15845 	mutex_exit(&cpu_lock);
15846 
15847 	/*
15848 	 * If there are already providers, we must ask them to provide their
15849 	 * probes, and then match any anonymous enabling against them.  Note
15850 	 * that there should be no other retained enablings at this time:
15851 	 * the only retained enablings at this time should be the anonymous
15852 	 * enabling.
15853 	 */
15854 	if (dtrace_anon.dta_enabling != NULL) {
15855 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15856 
15857 		dtrace_enabling_provide(NULL);
15858 		state = dtrace_anon.dta_state;
15859 
15860 		/*
15861 		 * We couldn't hold cpu_lock across the above call to
15862 		 * dtrace_enabling_provide(), but we must hold it to actually
15863 		 * enable the probes.  We have to drop all of our locks, pick
15864 		 * up cpu_lock, and regain our locks before matching the
15865 		 * retained anonymous enabling.
15866 		 */
15867 		mutex_exit(&dtrace_lock);
15868 		mutex_exit(&dtrace_provider_lock);
15869 
15870 		mutex_enter(&cpu_lock);
15871 		mutex_enter(&dtrace_provider_lock);
15872 		mutex_enter(&dtrace_lock);
15873 
15874 		if ((enab = dtrace_anon.dta_enabling) != NULL)
15875 			(void) dtrace_enabling_match(enab, NULL);
15876 
15877 		mutex_exit(&cpu_lock);
15878 	}
15879 
15880 	mutex_exit(&dtrace_lock);
15881 	mutex_exit(&dtrace_provider_lock);
15882 
15883 	if (state != NULL) {
15884 		/*
15885 		 * If we created any anonymous state, set it going now.
15886 		 */
15887 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15888 	}
15889 
15890 	return (DDI_SUCCESS);
15891 }
15892 
15893 /*ARGSUSED*/
15894 static int
15895 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15896 {
15897 	dtrace_state_t *state;
15898 	uint32_t priv;
15899 	uid_t uid;
15900 	zoneid_t zoneid;
15901 
15902 	if (getminor(*devp) == DTRACEMNRN_HELPER)
15903 		return (0);
15904 
15905 	/*
15906 	 * If this wasn't an open with the "helper" minor, then it must be
15907 	 * the "dtrace" minor.
15908 	 */
15909 	if (getminor(*devp) != DTRACEMNRN_DTRACE)
15910 		return (ENXIO);
15911 
15912 	/*
15913 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
15914 	 * caller lacks sufficient permission to do anything with DTrace.
15915 	 */
15916 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15917 	if (priv == DTRACE_PRIV_NONE)
15918 		return (EACCES);
15919 
15920 	/*
15921 	 * Ask all providers to provide all their probes.
15922 	 */
15923 	mutex_enter(&dtrace_provider_lock);
15924 	dtrace_probe_provide(NULL, NULL);
15925 	mutex_exit(&dtrace_provider_lock);
15926 
15927 	mutex_enter(&cpu_lock);
15928 	mutex_enter(&dtrace_lock);
15929 	dtrace_opens++;
15930 	dtrace_membar_producer();
15931 
15932 	/*
15933 	 * If the kernel debugger is active (that is, if the kernel debugger
15934 	 * modified text in some way), we won't allow the open.
15935 	 */
15936 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15937 		dtrace_opens--;
15938 		mutex_exit(&cpu_lock);
15939 		mutex_exit(&dtrace_lock);
15940 		return (EBUSY);
15941 	}
15942 
15943 	if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
15944 		/*
15945 		 * If DTrace helper tracing is enabled, we need to allocate the
15946 		 * trace buffer and initialize the values.
15947 		 */
15948 		dtrace_helptrace_buffer =
15949 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15950 		dtrace_helptrace_next = 0;
15951 		dtrace_helptrace_wrapped = 0;
15952 		dtrace_helptrace_enable = 0;
15953 	}
15954 
15955 	state = dtrace_state_create(devp, cred_p);
15956 	mutex_exit(&cpu_lock);
15957 
15958 	if (state == NULL) {
15959 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15960 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15961 		mutex_exit(&dtrace_lock);
15962 		return (EAGAIN);
15963 	}
15964 
15965 	mutex_exit(&dtrace_lock);
15966 
15967 	return (0);
15968 }
15969 
15970 /*ARGSUSED*/
15971 static int
15972 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15973 {
15974 	minor_t minor = getminor(dev);
15975 	dtrace_state_t *state;
15976 	dtrace_helptrace_t *buf = NULL;
15977 
15978 	if (minor == DTRACEMNRN_HELPER)
15979 		return (0);
15980 
15981 	state = ddi_get_soft_state(dtrace_softstate, minor);
15982 
15983 	mutex_enter(&cpu_lock);
15984 	mutex_enter(&dtrace_lock);
15985 
15986 	if (state->dts_anon) {
15987 		/*
15988 		 * There is anonymous state. Destroy that first.
15989 		 */
15990 		ASSERT(dtrace_anon.dta_state == NULL);
15991 		dtrace_state_destroy(state->dts_anon);
15992 	}
15993 
15994 	if (dtrace_helptrace_disable) {
15995 		/*
15996 		 * If we have been told to disable helper tracing, set the
15997 		 * buffer to NULL before calling into dtrace_state_destroy();
15998 		 * we take advantage of its dtrace_sync() to know that no
15999 		 * CPU is in probe context with enabled helper tracing
16000 		 * after it returns.
16001 		 */
16002 		buf = dtrace_helptrace_buffer;
16003 		dtrace_helptrace_buffer = NULL;
16004 	}
16005 
16006 	dtrace_state_destroy(state);
16007 	ASSERT(dtrace_opens > 0);
16008 
16009 	/*
16010 	 * Only relinquish control of the kernel debugger interface when there
16011 	 * are no consumers and no anonymous enablings.
16012 	 */
16013 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16014 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16015 
16016 	if (buf != NULL) {
16017 		kmem_free(buf, dtrace_helptrace_bufsize);
16018 		dtrace_helptrace_disable = 0;
16019 	}
16020 
16021 	mutex_exit(&dtrace_lock);
16022 	mutex_exit(&cpu_lock);
16023 
16024 	return (0);
16025 }
16026 
16027 /*ARGSUSED*/
16028 static int
16029 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
16030 {
16031 	int rval;
16032 	dof_helper_t help, *dhp = NULL;
16033 
16034 	switch (cmd) {
16035 	case DTRACEHIOC_ADDDOF:
16036 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
16037 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
16038 			return (EFAULT);
16039 		}
16040 
16041 		dhp = &help;
16042 		arg = (intptr_t)help.dofhp_dof;
16043 		/*FALLTHROUGH*/
16044 
16045 	case DTRACEHIOC_ADD: {
16046 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
16047 
16048 		if (dof == NULL)
16049 			return (rval);
16050 
16051 		mutex_enter(&dtrace_lock);
16052 
16053 		/*
16054 		 * dtrace_helper_slurp() takes responsibility for the dof --
16055 		 * it may free it now or it may save it and free it later.
16056 		 */
16057 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
16058 			*rv = rval;
16059 			rval = 0;
16060 		} else {
16061 			rval = EINVAL;
16062 		}
16063 
16064 		mutex_exit(&dtrace_lock);
16065 		return (rval);
16066 	}
16067 
16068 	case DTRACEHIOC_REMOVE: {
16069 		mutex_enter(&dtrace_lock);
16070 		rval = dtrace_helper_destroygen(arg);
16071 		mutex_exit(&dtrace_lock);
16072 
16073 		return (rval);
16074 	}
16075 
16076 	default:
16077 		break;
16078 	}
16079 
16080 	return (ENOTTY);
16081 }
16082 
16083 /*ARGSUSED*/
16084 static int
16085 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
16086 {
16087 	minor_t minor = getminor(dev);
16088 	dtrace_state_t *state;
16089 	int rval;
16090 
16091 	if (minor == DTRACEMNRN_HELPER)
16092 		return (dtrace_ioctl_helper(cmd, arg, rv));
16093 
16094 	state = ddi_get_soft_state(dtrace_softstate, minor);
16095 
16096 	if (state->dts_anon) {
16097 		ASSERT(dtrace_anon.dta_state == NULL);
16098 		state = state->dts_anon;
16099 	}
16100 
16101 	switch (cmd) {
16102 	case DTRACEIOC_PROVIDER: {
16103 		dtrace_providerdesc_t pvd;
16104 		dtrace_provider_t *pvp;
16105 
16106 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
16107 			return (EFAULT);
16108 
16109 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16110 		mutex_enter(&dtrace_provider_lock);
16111 
16112 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16113 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
16114 				break;
16115 		}
16116 
16117 		mutex_exit(&dtrace_provider_lock);
16118 
16119 		if (pvp == NULL)
16120 			return (ESRCH);
16121 
16122 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16123 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16124 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
16125 			return (EFAULT);
16126 
16127 		return (0);
16128 	}
16129 
16130 	case DTRACEIOC_EPROBE: {
16131 		dtrace_eprobedesc_t epdesc;
16132 		dtrace_ecb_t *ecb;
16133 		dtrace_action_t *act;
16134 		void *buf;
16135 		size_t size;
16136 		uintptr_t dest;
16137 		int nrecs;
16138 
16139 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
16140 			return (EFAULT);
16141 
16142 		mutex_enter(&dtrace_lock);
16143 
16144 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16145 			mutex_exit(&dtrace_lock);
16146 			return (EINVAL);
16147 		}
16148 
16149 		if (ecb->dte_probe == NULL) {
16150 			mutex_exit(&dtrace_lock);
16151 			return (EINVAL);
16152 		}
16153 
16154 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16155 		epdesc.dtepd_uarg = ecb->dte_uarg;
16156 		epdesc.dtepd_size = ecb->dte_size;
16157 
16158 		nrecs = epdesc.dtepd_nrecs;
16159 		epdesc.dtepd_nrecs = 0;
16160 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16161 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16162 				continue;
16163 
16164 			epdesc.dtepd_nrecs++;
16165 		}
16166 
16167 		/*
16168 		 * Now that we have the size, we need to allocate a temporary
16169 		 * buffer in which to store the complete description.  We need
16170 		 * the temporary buffer to be able to drop dtrace_lock()
16171 		 * across the copyout(), below.
16172 		 */
16173 		size = sizeof (dtrace_eprobedesc_t) +
16174 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16175 
16176 		buf = kmem_alloc(size, KM_SLEEP);
16177 		dest = (uintptr_t)buf;
16178 
16179 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16180 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16181 
16182 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16183 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16184 				continue;
16185 
16186 			if (nrecs-- == 0)
16187 				break;
16188 
16189 			bcopy(&act->dta_rec, (void *)dest,
16190 			    sizeof (dtrace_recdesc_t));
16191 			dest += sizeof (dtrace_recdesc_t);
16192 		}
16193 
16194 		mutex_exit(&dtrace_lock);
16195 
16196 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16197 			kmem_free(buf, size);
16198 			return (EFAULT);
16199 		}
16200 
16201 		kmem_free(buf, size);
16202 		return (0);
16203 	}
16204 
16205 	case DTRACEIOC_AGGDESC: {
16206 		dtrace_aggdesc_t aggdesc;
16207 		dtrace_action_t *act;
16208 		dtrace_aggregation_t *agg;
16209 		int nrecs;
16210 		uint32_t offs;
16211 		dtrace_recdesc_t *lrec;
16212 		void *buf;
16213 		size_t size;
16214 		uintptr_t dest;
16215 
16216 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
16217 			return (EFAULT);
16218 
16219 		mutex_enter(&dtrace_lock);
16220 
16221 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16222 			mutex_exit(&dtrace_lock);
16223 			return (EINVAL);
16224 		}
16225 
16226 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16227 
16228 		nrecs = aggdesc.dtagd_nrecs;
16229 		aggdesc.dtagd_nrecs = 0;
16230 
16231 		offs = agg->dtag_base;
16232 		lrec = &agg->dtag_action.dta_rec;
16233 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16234 
16235 		for (act = agg->dtag_first; ; act = act->dta_next) {
16236 			ASSERT(act->dta_intuple ||
16237 			    DTRACEACT_ISAGG(act->dta_kind));
16238 
16239 			/*
16240 			 * If this action has a record size of zero, it
16241 			 * denotes an argument to the aggregating action.
16242 			 * Because the presence of this record doesn't (or
16243 			 * shouldn't) affect the way the data is interpreted,
16244 			 * we don't copy it out to save user-level the
16245 			 * confusion of dealing with a zero-length record.
16246 			 */
16247 			if (act->dta_rec.dtrd_size == 0) {
16248 				ASSERT(agg->dtag_hasarg);
16249 				continue;
16250 			}
16251 
16252 			aggdesc.dtagd_nrecs++;
16253 
16254 			if (act == &agg->dtag_action)
16255 				break;
16256 		}
16257 
16258 		/*
16259 		 * Now that we have the size, we need to allocate a temporary
16260 		 * buffer in which to store the complete description.  We need
16261 		 * the temporary buffer to be able to drop dtrace_lock()
16262 		 * across the copyout(), below.
16263 		 */
16264 		size = sizeof (dtrace_aggdesc_t) +
16265 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16266 
16267 		buf = kmem_alloc(size, KM_SLEEP);
16268 		dest = (uintptr_t)buf;
16269 
16270 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16271 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16272 
16273 		for (act = agg->dtag_first; ; act = act->dta_next) {
16274 			dtrace_recdesc_t rec = act->dta_rec;
16275 
16276 			/*
16277 			 * See the comment in the above loop for why we pass
16278 			 * over zero-length records.
16279 			 */
16280 			if (rec.dtrd_size == 0) {
16281 				ASSERT(agg->dtag_hasarg);
16282 				continue;
16283 			}
16284 
16285 			if (nrecs-- == 0)
16286 				break;
16287 
16288 			rec.dtrd_offset -= offs;
16289 			bcopy(&rec, (void *)dest, sizeof (rec));
16290 			dest += sizeof (dtrace_recdesc_t);
16291 
16292 			if (act == &agg->dtag_action)
16293 				break;
16294 		}
16295 
16296 		mutex_exit(&dtrace_lock);
16297 
16298 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16299 			kmem_free(buf, size);
16300 			return (EFAULT);
16301 		}
16302 
16303 		kmem_free(buf, size);
16304 		return (0);
16305 	}
16306 
16307 	case DTRACEIOC_ENABLE: {
16308 		dof_hdr_t *dof;
16309 		dtrace_enabling_t *enab = NULL;
16310 		dtrace_vstate_t *vstate;
16311 		int err = 0;
16312 
16313 		*rv = 0;
16314 
16315 		/*
16316 		 * If a NULL argument has been passed, we take this as our
16317 		 * cue to reevaluate our enablings.
16318 		 */
16319 		if (arg == NULL) {
16320 			dtrace_enabling_matchall();
16321 
16322 			return (0);
16323 		}
16324 
16325 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16326 			return (rval);
16327 
16328 		mutex_enter(&cpu_lock);
16329 		mutex_enter(&dtrace_lock);
16330 		vstate = &state->dts_vstate;
16331 
16332 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16333 			mutex_exit(&dtrace_lock);
16334 			mutex_exit(&cpu_lock);
16335 			dtrace_dof_destroy(dof);
16336 			return (EBUSY);
16337 		}
16338 
16339 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16340 			mutex_exit(&dtrace_lock);
16341 			mutex_exit(&cpu_lock);
16342 			dtrace_dof_destroy(dof);
16343 			return (EINVAL);
16344 		}
16345 
16346 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
16347 			dtrace_enabling_destroy(enab);
16348 			mutex_exit(&dtrace_lock);
16349 			mutex_exit(&cpu_lock);
16350 			dtrace_dof_destroy(dof);
16351 			return (rval);
16352 		}
16353 
16354 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16355 			err = dtrace_enabling_retain(enab);
16356 		} else {
16357 			dtrace_enabling_destroy(enab);
16358 		}
16359 
16360 		mutex_exit(&cpu_lock);
16361 		mutex_exit(&dtrace_lock);
16362 		dtrace_dof_destroy(dof);
16363 
16364 		return (err);
16365 	}
16366 
16367 	case DTRACEIOC_REPLICATE: {
16368 		dtrace_repldesc_t desc;
16369 		dtrace_probedesc_t *match = &desc.dtrpd_match;
16370 		dtrace_probedesc_t *create = &desc.dtrpd_create;
16371 		int err;
16372 
16373 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16374 			return (EFAULT);
16375 
16376 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16377 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16378 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16379 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16380 
16381 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16382 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16383 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16384 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16385 
16386 		mutex_enter(&dtrace_lock);
16387 		err = dtrace_enabling_replicate(state, match, create);
16388 		mutex_exit(&dtrace_lock);
16389 
16390 		return (err);
16391 	}
16392 
16393 	case DTRACEIOC_PROBEMATCH:
16394 	case DTRACEIOC_PROBES: {
16395 		dtrace_probe_t *probe = NULL;
16396 		dtrace_probedesc_t desc;
16397 		dtrace_probekey_t pkey;
16398 		dtrace_id_t i;
16399 		int m = 0;
16400 		uint32_t priv;
16401 		uid_t uid;
16402 		zoneid_t zoneid;
16403 
16404 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16405 			return (EFAULT);
16406 
16407 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16408 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16409 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16410 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16411 
16412 		/*
16413 		 * Before we attempt to match this probe, we want to give
16414 		 * all providers the opportunity to provide it.
16415 		 */
16416 		if (desc.dtpd_id == DTRACE_IDNONE) {
16417 			mutex_enter(&dtrace_provider_lock);
16418 			dtrace_probe_provide(&desc, NULL);
16419 			mutex_exit(&dtrace_provider_lock);
16420 			desc.dtpd_id++;
16421 		}
16422 
16423 		if (cmd == DTRACEIOC_PROBEMATCH)  {
16424 			dtrace_probekey(&desc, &pkey);
16425 			pkey.dtpk_id = DTRACE_IDNONE;
16426 		}
16427 
16428 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16429 
16430 		mutex_enter(&dtrace_lock);
16431 
16432 		if (cmd == DTRACEIOC_PROBEMATCH) {
16433 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16434 				if ((probe = dtrace_probes[i - 1]) != NULL &&
16435 				    (m = dtrace_match_probe(probe, &pkey,
16436 				    priv, uid, zoneid)) != 0)
16437 					break;
16438 			}
16439 
16440 			if (m < 0) {
16441 				mutex_exit(&dtrace_lock);
16442 				return (EINVAL);
16443 			}
16444 
16445 		} else {
16446 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16447 				if ((probe = dtrace_probes[i - 1]) != NULL &&
16448 				    dtrace_match_priv(probe, priv, uid, zoneid))
16449 					break;
16450 			}
16451 		}
16452 
16453 		if (probe == NULL) {
16454 			mutex_exit(&dtrace_lock);
16455 			return (ESRCH);
16456 		}
16457 
16458 		dtrace_probe_description(probe, &desc);
16459 		mutex_exit(&dtrace_lock);
16460 
16461 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16462 			return (EFAULT);
16463 
16464 		return (0);
16465 	}
16466 
16467 	case DTRACEIOC_PROBEARG: {
16468 		dtrace_argdesc_t desc;
16469 		dtrace_probe_t *probe;
16470 		dtrace_provider_t *prov;
16471 
16472 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16473 			return (EFAULT);
16474 
16475 		if (desc.dtargd_id == DTRACE_IDNONE)
16476 			return (EINVAL);
16477 
16478 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
16479 			return (EINVAL);
16480 
16481 		mutex_enter(&dtrace_provider_lock);
16482 		mutex_enter(&mod_lock);
16483 		mutex_enter(&dtrace_lock);
16484 
16485 		if (desc.dtargd_id > dtrace_nprobes) {
16486 			mutex_exit(&dtrace_lock);
16487 			mutex_exit(&mod_lock);
16488 			mutex_exit(&dtrace_provider_lock);
16489 			return (EINVAL);
16490 		}
16491 
16492 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16493 			mutex_exit(&dtrace_lock);
16494 			mutex_exit(&mod_lock);
16495 			mutex_exit(&dtrace_provider_lock);
16496 			return (EINVAL);
16497 		}
16498 
16499 		mutex_exit(&dtrace_lock);
16500 
16501 		prov = probe->dtpr_provider;
16502 
16503 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16504 			/*
16505 			 * There isn't any typed information for this probe.
16506 			 * Set the argument number to DTRACE_ARGNONE.
16507 			 */
16508 			desc.dtargd_ndx = DTRACE_ARGNONE;
16509 		} else {
16510 			desc.dtargd_native[0] = '\0';
16511 			desc.dtargd_xlate[0] = '\0';
16512 			desc.dtargd_mapping = desc.dtargd_ndx;
16513 
16514 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16515 			    probe->dtpr_id, probe->dtpr_arg, &desc);
16516 		}
16517 
16518 		mutex_exit(&mod_lock);
16519 		mutex_exit(&dtrace_provider_lock);
16520 
16521 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16522 			return (EFAULT);
16523 
16524 		return (0);
16525 	}
16526 
16527 	case DTRACEIOC_GO: {
16528 		processorid_t cpuid;
16529 		rval = dtrace_state_go(state, &cpuid);
16530 
16531 		if (rval != 0)
16532 			return (rval);
16533 
16534 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16535 			return (EFAULT);
16536 
16537 		return (0);
16538 	}
16539 
16540 	case DTRACEIOC_STOP: {
16541 		processorid_t cpuid;
16542 
16543 		mutex_enter(&dtrace_lock);
16544 		rval = dtrace_state_stop(state, &cpuid);
16545 		mutex_exit(&dtrace_lock);
16546 
16547 		if (rval != 0)
16548 			return (rval);
16549 
16550 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16551 			return (EFAULT);
16552 
16553 		return (0);
16554 	}
16555 
16556 	case DTRACEIOC_DOFGET: {
16557 		dof_hdr_t hdr, *dof;
16558 		uint64_t len;
16559 
16560 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16561 			return (EFAULT);
16562 
16563 		mutex_enter(&dtrace_lock);
16564 		dof = dtrace_dof_create(state);
16565 		mutex_exit(&dtrace_lock);
16566 
16567 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16568 		rval = copyout(dof, (void *)arg, len);
16569 		dtrace_dof_destroy(dof);
16570 
16571 		return (rval == 0 ? 0 : EFAULT);
16572 	}
16573 
16574 	case DTRACEIOC_AGGSNAP:
16575 	case DTRACEIOC_BUFSNAP: {
16576 		dtrace_bufdesc_t desc;
16577 		caddr_t cached;
16578 		dtrace_buffer_t *buf;
16579 
16580 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16581 			return (EFAULT);
16582 
16583 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16584 			return (EINVAL);
16585 
16586 		mutex_enter(&dtrace_lock);
16587 
16588 		if (cmd == DTRACEIOC_BUFSNAP) {
16589 			buf = &state->dts_buffer[desc.dtbd_cpu];
16590 		} else {
16591 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16592 		}
16593 
16594 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16595 			size_t sz = buf->dtb_offset;
16596 
16597 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16598 				mutex_exit(&dtrace_lock);
16599 				return (EBUSY);
16600 			}
16601 
16602 			/*
16603 			 * If this buffer has already been consumed, we're
16604 			 * going to indicate that there's nothing left here
16605 			 * to consume.
16606 			 */
16607 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16608 				mutex_exit(&dtrace_lock);
16609 
16610 				desc.dtbd_size = 0;
16611 				desc.dtbd_drops = 0;
16612 				desc.dtbd_errors = 0;
16613 				desc.dtbd_oldest = 0;
16614 				sz = sizeof (desc);
16615 
16616 				if (copyout(&desc, (void *)arg, sz) != 0)
16617 					return (EFAULT);
16618 
16619 				return (0);
16620 			}
16621 
16622 			/*
16623 			 * If this is a ring buffer that has wrapped, we want
16624 			 * to copy the whole thing out.
16625 			 */
16626 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16627 				dtrace_buffer_polish(buf);
16628 				sz = buf->dtb_size;
16629 			}
16630 
16631 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
16632 				mutex_exit(&dtrace_lock);
16633 				return (EFAULT);
16634 			}
16635 
16636 			desc.dtbd_size = sz;
16637 			desc.dtbd_drops = buf->dtb_drops;
16638 			desc.dtbd_errors = buf->dtb_errors;
16639 			desc.dtbd_oldest = buf->dtb_xamot_offset;
16640 			desc.dtbd_timestamp = dtrace_gethrtime();
16641 
16642 			mutex_exit(&dtrace_lock);
16643 
16644 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16645 				return (EFAULT);
16646 
16647 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
16648 
16649 			return (0);
16650 		}
16651 
16652 		if (buf->dtb_tomax == NULL) {
16653 			ASSERT(buf->dtb_xamot == NULL);
16654 			mutex_exit(&dtrace_lock);
16655 			return (ENOENT);
16656 		}
16657 
16658 		cached = buf->dtb_tomax;
16659 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16660 
16661 		dtrace_xcall(desc.dtbd_cpu,
16662 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
16663 
16664 		state->dts_errors += buf->dtb_xamot_errors;
16665 
16666 		/*
16667 		 * If the buffers did not actually switch, then the cross call
16668 		 * did not take place -- presumably because the given CPU is
16669 		 * not in the ready set.  If this is the case, we'll return
16670 		 * ENOENT.
16671 		 */
16672 		if (buf->dtb_tomax == cached) {
16673 			ASSERT(buf->dtb_xamot != cached);
16674 			mutex_exit(&dtrace_lock);
16675 			return (ENOENT);
16676 		}
16677 
16678 		ASSERT(cached == buf->dtb_xamot);
16679 
16680 		/*
16681 		 * We have our snapshot; now copy it out.
16682 		 */
16683 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
16684 		    buf->dtb_xamot_offset) != 0) {
16685 			mutex_exit(&dtrace_lock);
16686 			return (EFAULT);
16687 		}
16688 
16689 		desc.dtbd_size = buf->dtb_xamot_offset;
16690 		desc.dtbd_drops = buf->dtb_xamot_drops;
16691 		desc.dtbd_errors = buf->dtb_xamot_errors;
16692 		desc.dtbd_oldest = 0;
16693 		desc.dtbd_timestamp = buf->dtb_switched;
16694 
16695 		mutex_exit(&dtrace_lock);
16696 
16697 		/*
16698 		 * Finally, copy out the buffer description.
16699 		 */
16700 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16701 			return (EFAULT);
16702 
16703 		return (0);
16704 	}
16705 
16706 	case DTRACEIOC_CONF: {
16707 		dtrace_conf_t conf;
16708 
16709 		bzero(&conf, sizeof (conf));
16710 		conf.dtc_difversion = DIF_VERSION;
16711 		conf.dtc_difintregs = DIF_DIR_NREGS;
16712 		conf.dtc_diftupregs = DIF_DTR_NREGS;
16713 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16714 
16715 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
16716 			return (EFAULT);
16717 
16718 		return (0);
16719 	}
16720 
16721 	case DTRACEIOC_STATUS: {
16722 		dtrace_status_t stat;
16723 		dtrace_dstate_t *dstate;
16724 		int i, j;
16725 		uint64_t nerrs;
16726 
16727 		/*
16728 		 * See the comment in dtrace_state_deadman() for the reason
16729 		 * for setting dts_laststatus to INT64_MAX before setting
16730 		 * it to the correct value.
16731 		 */
16732 		state->dts_laststatus = INT64_MAX;
16733 		dtrace_membar_producer();
16734 		state->dts_laststatus = dtrace_gethrtime();
16735 
16736 		bzero(&stat, sizeof (stat));
16737 
16738 		mutex_enter(&dtrace_lock);
16739 
16740 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16741 			mutex_exit(&dtrace_lock);
16742 			return (ENOENT);
16743 		}
16744 
16745 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16746 			stat.dtst_exiting = 1;
16747 
16748 		nerrs = state->dts_errors;
16749 		dstate = &state->dts_vstate.dtvs_dynvars;
16750 
16751 		for (i = 0; i < NCPU; i++) {
16752 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16753 
16754 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
16755 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16756 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16757 
16758 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16759 				stat.dtst_filled++;
16760 
16761 			nerrs += state->dts_buffer[i].dtb_errors;
16762 
16763 			for (j = 0; j < state->dts_nspeculations; j++) {
16764 				dtrace_speculation_t *spec;
16765 				dtrace_buffer_t *buf;
16766 
16767 				spec = &state->dts_speculations[j];
16768 				buf = &spec->dtsp_buffer[i];
16769 				stat.dtst_specdrops += buf->dtb_xamot_drops;
16770 			}
16771 		}
16772 
16773 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
16774 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16775 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16776 		stat.dtst_dblerrors = state->dts_dblerrors;
16777 		stat.dtst_killed =
16778 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16779 		stat.dtst_errors = nerrs;
16780 
16781 		mutex_exit(&dtrace_lock);
16782 
16783 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
16784 			return (EFAULT);
16785 
16786 		return (0);
16787 	}
16788 
16789 	case DTRACEIOC_FORMAT: {
16790 		dtrace_fmtdesc_t fmt;
16791 		char *str;
16792 		int len;
16793 
16794 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
16795 			return (EFAULT);
16796 
16797 		mutex_enter(&dtrace_lock);
16798 
16799 		if (fmt.dtfd_format == 0 ||
16800 		    fmt.dtfd_format > state->dts_nformats) {
16801 			mutex_exit(&dtrace_lock);
16802 			return (EINVAL);
16803 		}
16804 
16805 		/*
16806 		 * Format strings are allocated contiguously and they are
16807 		 * never freed; if a format index is less than the number
16808 		 * of formats, we can assert that the format map is non-NULL
16809 		 * and that the format for the specified index is non-NULL.
16810 		 */
16811 		ASSERT(state->dts_formats != NULL);
16812 		str = state->dts_formats[fmt.dtfd_format - 1];
16813 		ASSERT(str != NULL);
16814 
16815 		len = strlen(str) + 1;
16816 
16817 		if (len > fmt.dtfd_length) {
16818 			fmt.dtfd_length = len;
16819 
16820 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16821 				mutex_exit(&dtrace_lock);
16822 				return (EINVAL);
16823 			}
16824 		} else {
16825 			if (copyout(str, fmt.dtfd_string, len) != 0) {
16826 				mutex_exit(&dtrace_lock);
16827 				return (EINVAL);
16828 			}
16829 		}
16830 
16831 		mutex_exit(&dtrace_lock);
16832 		return (0);
16833 	}
16834 
16835 	default:
16836 		break;
16837 	}
16838 
16839 	return (ENOTTY);
16840 }
16841 
16842 /*ARGSUSED*/
16843 static int
16844 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16845 {
16846 	dtrace_state_t *state;
16847 
16848 	switch (cmd) {
16849 	case DDI_DETACH:
16850 		break;
16851 
16852 	case DDI_SUSPEND:
16853 		return (DDI_SUCCESS);
16854 
16855 	default:
16856 		return (DDI_FAILURE);
16857 	}
16858 
16859 	mutex_enter(&cpu_lock);
16860 	mutex_enter(&dtrace_provider_lock);
16861 	mutex_enter(&dtrace_lock);
16862 
16863 	ASSERT(dtrace_opens == 0);
16864 
16865 	if (dtrace_helpers > 0) {
16866 		mutex_exit(&dtrace_provider_lock);
16867 		mutex_exit(&dtrace_lock);
16868 		mutex_exit(&cpu_lock);
16869 		return (DDI_FAILURE);
16870 	}
16871 
16872 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
16873 		mutex_exit(&dtrace_provider_lock);
16874 		mutex_exit(&dtrace_lock);
16875 		mutex_exit(&cpu_lock);
16876 		return (DDI_FAILURE);
16877 	}
16878 
16879 	dtrace_provider = NULL;
16880 
16881 	if ((state = dtrace_anon_grab()) != NULL) {
16882 		/*
16883 		 * If there were ECBs on this state, the provider should
16884 		 * have not been allowed to detach; assert that there is
16885 		 * none.
16886 		 */
16887 		ASSERT(state->dts_necbs == 0);
16888 		dtrace_state_destroy(state);
16889 
16890 		/*
16891 		 * If we're being detached with anonymous state, we need to
16892 		 * indicate to the kernel debugger that DTrace is now inactive.
16893 		 */
16894 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16895 	}
16896 
16897 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
16898 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16899 	dtrace_cpu_init = NULL;
16900 	dtrace_helpers_cleanup = NULL;
16901 	dtrace_helpers_fork = NULL;
16902 	dtrace_cpustart_init = NULL;
16903 	dtrace_cpustart_fini = NULL;
16904 	dtrace_debugger_init = NULL;
16905 	dtrace_debugger_fini = NULL;
16906 	dtrace_modload = NULL;
16907 	dtrace_modunload = NULL;
16908 
16909 	ASSERT(dtrace_getf == 0);
16910 	ASSERT(dtrace_closef == NULL);
16911 
16912 	mutex_exit(&cpu_lock);
16913 
16914 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
16915 	dtrace_probes = NULL;
16916 	dtrace_nprobes = 0;
16917 
16918 	dtrace_hash_destroy(dtrace_bymod);
16919 	dtrace_hash_destroy(dtrace_byfunc);
16920 	dtrace_hash_destroy(dtrace_byname);
16921 	dtrace_bymod = NULL;
16922 	dtrace_byfunc = NULL;
16923 	dtrace_byname = NULL;
16924 
16925 	kmem_cache_destroy(dtrace_state_cache);
16926 	vmem_destroy(dtrace_minor);
16927 	vmem_destroy(dtrace_arena);
16928 
16929 	if (dtrace_toxrange != NULL) {
16930 		kmem_free(dtrace_toxrange,
16931 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
16932 		dtrace_toxrange = NULL;
16933 		dtrace_toxranges = 0;
16934 		dtrace_toxranges_max = 0;
16935 	}
16936 
16937 	ddi_remove_minor_node(dtrace_devi, NULL);
16938 	dtrace_devi = NULL;
16939 
16940 	ddi_soft_state_fini(&dtrace_softstate);
16941 
16942 	ASSERT(dtrace_vtime_references == 0);
16943 	ASSERT(dtrace_opens == 0);
16944 	ASSERT(dtrace_retained == NULL);
16945 
16946 	mutex_exit(&dtrace_lock);
16947 	mutex_exit(&dtrace_provider_lock);
16948 
16949 	/*
16950 	 * We don't destroy the task queue until after we have dropped our
16951 	 * locks (taskq_destroy() may block on running tasks).  To prevent
16952 	 * attempting to do work after we have effectively detached but before
16953 	 * the task queue has been destroyed, all tasks dispatched via the
16954 	 * task queue must check that DTrace is still attached before
16955 	 * performing any operation.
16956 	 */
16957 	taskq_destroy(dtrace_taskq);
16958 	dtrace_taskq = NULL;
16959 
16960 	return (DDI_SUCCESS);
16961 }
16962 
16963 /*ARGSUSED*/
16964 static int
16965 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
16966 {
16967 	int error;
16968 
16969 	switch (infocmd) {
16970 	case DDI_INFO_DEVT2DEVINFO:
16971 		*result = (void *)dtrace_devi;
16972 		error = DDI_SUCCESS;
16973 		break;
16974 	case DDI_INFO_DEVT2INSTANCE:
16975 		*result = (void *)0;
16976 		error = DDI_SUCCESS;
16977 		break;
16978 	default:
16979 		error = DDI_FAILURE;
16980 	}
16981 	return (error);
16982 }
16983 
16984 static struct cb_ops dtrace_cb_ops = {
16985 	dtrace_open,		/* open */
16986 	dtrace_close,		/* close */
16987 	nulldev,		/* strategy */
16988 	nulldev,		/* print */
16989 	nodev,			/* dump */
16990 	nodev,			/* read */
16991 	nodev,			/* write */
16992 	dtrace_ioctl,		/* ioctl */
16993 	nodev,			/* devmap */
16994 	nodev,			/* mmap */
16995 	nodev,			/* segmap */
16996 	nochpoll,		/* poll */
16997 	ddi_prop_op,		/* cb_prop_op */
16998 	0,			/* streamtab  */
16999 	D_NEW | D_MP		/* Driver compatibility flag */
17000 };
17001 
17002 static struct dev_ops dtrace_ops = {
17003 	DEVO_REV,		/* devo_rev */
17004 	0,			/* refcnt */
17005 	dtrace_info,		/* get_dev_info */
17006 	nulldev,		/* identify */
17007 	nulldev,		/* probe */
17008 	dtrace_attach,		/* attach */
17009 	dtrace_detach,		/* detach */
17010 	nodev,			/* reset */
17011 	&dtrace_cb_ops,		/* driver operations */
17012 	NULL,			/* bus operations */
17013 	nodev,			/* dev power */
17014 	ddi_quiesce_not_needed,		/* quiesce */
17015 };
17016 
17017 static struct modldrv modldrv = {
17018 	&mod_driverops,		/* module type (this is a pseudo driver) */
17019 	"Dynamic Tracing",	/* name of module */
17020 	&dtrace_ops,		/* driver ops */
17021 };
17022 
17023 static struct modlinkage modlinkage = {
17024 	MODREV_1,
17025 	(void *)&modldrv,
17026 	NULL
17027 };
17028 
17029 int
17030 _init(void)
17031 {
17032 	return (mod_install(&modlinkage));
17033 }
17034 
17035 int
17036 _info(struct modinfo *modinfop)
17037 {
17038 	return (mod_info(&modlinkage, modinfop));
17039 }
17040 
17041 int
17042 _fini(void)
17043 {
17044 	return (mod_remove(&modlinkage));
17045 }
17046