xref: /titanic_52/usr/src/uts/common/dtrace/dtrace.c (revision 17ad7f9fd28ceea21aea94421cb8ada963285765)
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) 2015, 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 DTRACE_LOADFUNC(8)
571 DTRACE_LOADFUNC(16)
572 DTRACE_LOADFUNC(32)
573 DTRACE_LOADFUNC(64)
574 
575 static int
576 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
577 {
578 	if (dest < mstate->dtms_scratch_base)
579 		return (0);
580 
581 	if (dest + size < dest)
582 		return (0);
583 
584 	if (dest + size > mstate->dtms_scratch_ptr)
585 		return (0);
586 
587 	return (1);
588 }
589 
590 static int
591 dtrace_canstore_statvar(uint64_t addr, size_t sz,
592     dtrace_statvar_t **svars, int nsvars)
593 {
594 	int i;
595 	size_t maxglobalsize, maxlocalsize;
596 
597 	if (nsvars == 0)
598 		return (0);
599 
600 	maxglobalsize = dtrace_statvar_maxsize;
601 	maxlocalsize = (maxglobalsize + sizeof (uint64_t)) * NCPU;
602 
603 	for (i = 0; i < nsvars; i++) {
604 		dtrace_statvar_t *svar = svars[i];
605 		uint8_t scope;
606 		size_t size;
607 
608 		if (svar == NULL || (size = svar->dtsv_size) == 0)
609 			continue;
610 
611 		scope = svar->dtsv_var.dtdv_scope;
612 
613 		/*
614 		 * We verify that our size is valid in the spirit of providing
615 		 * defense in depth:  we want to prevent attackers from using
616 		 * DTrace to escalate an orthogonal kernel heap corruption bug
617 		 * into the ability to store to arbitrary locations in memory.
618 		 */
619 		VERIFY((scope == DIFV_SCOPE_GLOBAL && size < maxglobalsize) ||
620 		    (scope == DIFV_SCOPE_LOCAL && size < maxlocalsize));
621 
622 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
623 			return (1);
624 	}
625 
626 	return (0);
627 }
628 
629 /*
630  * Check to see if the address is within a memory region to which a store may
631  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
632  * region.  The caller of dtrace_canstore() is responsible for performing any
633  * alignment checks that are needed before stores are actually executed.
634  */
635 static int
636 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
637     dtrace_vstate_t *vstate)
638 {
639 	/*
640 	 * First, check to see if the address is in scratch space...
641 	 */
642 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
643 	    mstate->dtms_scratch_size))
644 		return (1);
645 
646 	/*
647 	 * Now check to see if it's a dynamic variable.  This check will pick
648 	 * up both thread-local variables and any global dynamically-allocated
649 	 * variables.
650 	 */
651 	if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
652 	    vstate->dtvs_dynvars.dtds_size)) {
653 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
654 		uintptr_t base = (uintptr_t)dstate->dtds_base +
655 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
656 		uintptr_t chunkoffs;
657 
658 		/*
659 		 * Before we assume that we can store here, we need to make
660 		 * sure that it isn't in our metadata -- storing to our
661 		 * dynamic variable metadata would corrupt our state.  For
662 		 * the range to not include any dynamic variable metadata,
663 		 * it must:
664 		 *
665 		 *	(1) Start above the hash table that is at the base of
666 		 *	the dynamic variable space
667 		 *
668 		 *	(2) Have a starting chunk offset that is beyond the
669 		 *	dtrace_dynvar_t that is at the base of every chunk
670 		 *
671 		 *	(3) Not span a chunk boundary
672 		 *
673 		 */
674 		if (addr < base)
675 			return (0);
676 
677 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
678 
679 		if (chunkoffs < sizeof (dtrace_dynvar_t))
680 			return (0);
681 
682 		if (chunkoffs + sz > dstate->dtds_chunksize)
683 			return (0);
684 
685 		return (1);
686 	}
687 
688 	/*
689 	 * Finally, check the static local and global variables.  These checks
690 	 * take the longest, so we perform them last.
691 	 */
692 	if (dtrace_canstore_statvar(addr, sz,
693 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
694 		return (1);
695 
696 	if (dtrace_canstore_statvar(addr, sz,
697 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
698 		return (1);
699 
700 	return (0);
701 }
702 
703 
704 /*
705  * Convenience routine to check to see if the address is within a memory
706  * region in which a load may be issued given the user's privilege level;
707  * if not, it sets the appropriate error flags and loads 'addr' into the
708  * illegal value slot.
709  *
710  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
711  * appropriate memory access protection.
712  */
713 static int
714 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
715     dtrace_vstate_t *vstate)
716 {
717 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
718 	file_t *fp;
719 
720 	/*
721 	 * If we hold the privilege to read from kernel memory, then
722 	 * everything is readable.
723 	 */
724 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
725 		return (1);
726 
727 	/*
728 	 * You can obviously read that which you can store.
729 	 */
730 	if (dtrace_canstore(addr, sz, mstate, vstate))
731 		return (1);
732 
733 	/*
734 	 * We're allowed to read from our own string table.
735 	 */
736 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
737 	    mstate->dtms_difo->dtdo_strlen))
738 		return (1);
739 
740 	if (vstate->dtvs_state != NULL &&
741 	    dtrace_priv_proc(vstate->dtvs_state, mstate)) {
742 		proc_t *p;
743 
744 		/*
745 		 * When we have privileges to the current process, there are
746 		 * several context-related kernel structures that are safe to
747 		 * read, even absent the privilege to read from kernel memory.
748 		 * These reads are safe because these structures contain only
749 		 * state that (1) we're permitted to read, (2) is harmless or
750 		 * (3) contains pointers to additional kernel state that we're
751 		 * not permitted to read (and as such, do not present an
752 		 * opportunity for privilege escalation).  Finally (and
753 		 * critically), because of the nature of their relation with
754 		 * the current thread context, the memory associated with these
755 		 * structures cannot change over the duration of probe context,
756 		 * and it is therefore impossible for this memory to be
757 		 * deallocated and reallocated as something else while it's
758 		 * being operated upon.
759 		 */
760 		if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t)))
761 			return (1);
762 
763 		if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
764 		    sz, curthread->t_procp, sizeof (proc_t))) {
765 			return (1);
766 		}
767 
768 		if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
769 		    curthread->t_cred, sizeof (cred_t))) {
770 			return (1);
771 		}
772 
773 		if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
774 		    &(p->p_pidp->pid_id), sizeof (pid_t))) {
775 			return (1);
776 		}
777 
778 		if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
779 		    curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
780 			return (1);
781 		}
782 	}
783 
784 	if ((fp = mstate->dtms_getf) != NULL) {
785 		uintptr_t psz = sizeof (void *);
786 		vnode_t *vp;
787 		vnodeops_t *op;
788 
789 		/*
790 		 * When getf() returns a file_t, the enabling is implicitly
791 		 * granted the (transient) right to read the returned file_t
792 		 * as well as the v_path and v_op->vnop_name of the underlying
793 		 * vnode.  These accesses are allowed after a successful
794 		 * getf() because the members that they refer to cannot change
795 		 * once set -- and the barrier logic in the kernel's closef()
796 		 * path assures that the file_t and its referenced vode_t
797 		 * cannot themselves be stale (that is, it impossible for
798 		 * either dtms_getf itself or its f_vnode member to reference
799 		 * freed memory).
800 		 */
801 		if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t)))
802 			return (1);
803 
804 		if ((vp = fp->f_vnode) != NULL) {
805 			if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz))
806 				return (1);
807 
808 			if (vp->v_path != NULL && DTRACE_INRANGE(addr, sz,
809 			    vp->v_path, strlen(vp->v_path) + 1)) {
810 				return (1);
811 			}
812 
813 			if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz))
814 				return (1);
815 
816 			if ((op = vp->v_op) != NULL &&
817 			    DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
818 				return (1);
819 			}
820 
821 			if (op != NULL && op->vnop_name != NULL &&
822 			    DTRACE_INRANGE(addr, sz, op->vnop_name,
823 			    strlen(op->vnop_name) + 1)) {
824 				return (1);
825 			}
826 		}
827 	}
828 
829 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
830 	*illval = addr;
831 	return (0);
832 }
833 
834 /*
835  * Convenience routine to check to see if a given string is within a memory
836  * region in which a load may be issued given the user's privilege level;
837  * this exists so that we don't need to issue unnecessary dtrace_strlen()
838  * calls in the event that the user has all privileges.
839  */
840 static int
841 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
842     dtrace_vstate_t *vstate)
843 {
844 	size_t strsz;
845 
846 	/*
847 	 * If we hold the privilege to read from kernel memory, then
848 	 * everything is readable.
849 	 */
850 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
851 		return (1);
852 
853 	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
854 	if (dtrace_canload(addr, strsz, mstate, vstate))
855 		return (1);
856 
857 	return (0);
858 }
859 
860 /*
861  * Convenience routine to check to see if a given variable is within a memory
862  * region in which a load may be issued given the user's privilege level.
863  */
864 static int
865 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
866     dtrace_vstate_t *vstate)
867 {
868 	size_t sz;
869 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
870 
871 	/*
872 	 * If we hold the privilege to read from kernel memory, then
873 	 * everything is readable.
874 	 */
875 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
876 		return (1);
877 
878 	if (type->dtdt_kind == DIF_TYPE_STRING)
879 		sz = dtrace_strlen(src,
880 		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
881 	else
882 		sz = type->dtdt_size;
883 
884 	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
885 }
886 
887 /*
888  * Convert a string to a signed integer using safe loads.
889  *
890  * NOTE: This function uses various macros from strtolctype.h to manipulate
891  * digit values, etc -- these have all been checked to ensure they make
892  * no additional function calls.
893  */
894 static int64_t
895 dtrace_strtoll(char *input, int base, size_t limit)
896 {
897 	uintptr_t pos = (uintptr_t)input;
898 	int64_t val = 0;
899 	int x;
900 	boolean_t neg = B_FALSE;
901 	char c, cc, ccc;
902 	uintptr_t end = pos + limit;
903 
904 	/*
905 	 * Consume any whitespace preceding digits.
906 	 */
907 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
908 		pos++;
909 
910 	/*
911 	 * Handle an explicit sign if one is present.
912 	 */
913 	if (c == '-' || c == '+') {
914 		if (c == '-')
915 			neg = B_TRUE;
916 		c = dtrace_load8(++pos);
917 	}
918 
919 	/*
920 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
921 	 * if present.
922 	 */
923 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
924 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
925 		pos += 2;
926 		c = ccc;
927 	}
928 
929 	/*
930 	 * Read in contiguous digits until the first non-digit character.
931 	 */
932 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
933 	    c = dtrace_load8(++pos))
934 		val = val * base + x;
935 
936 	return (neg ? -val : val);
937 }
938 
939 /*
940  * Compare two strings using safe loads.
941  */
942 static int
943 dtrace_strncmp(char *s1, char *s2, size_t limit)
944 {
945 	uint8_t c1, c2;
946 	volatile uint16_t *flags;
947 
948 	if (s1 == s2 || limit == 0)
949 		return (0);
950 
951 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
952 
953 	do {
954 		if (s1 == NULL) {
955 			c1 = '\0';
956 		} else {
957 			c1 = dtrace_load8((uintptr_t)s1++);
958 		}
959 
960 		if (s2 == NULL) {
961 			c2 = '\0';
962 		} else {
963 			c2 = dtrace_load8((uintptr_t)s2++);
964 		}
965 
966 		if (c1 != c2)
967 			return (c1 - c2);
968 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
969 
970 	return (0);
971 }
972 
973 /*
974  * Compute strlen(s) for a string using safe memory accesses.  The additional
975  * len parameter is used to specify a maximum length to ensure completion.
976  */
977 static size_t
978 dtrace_strlen(const char *s, size_t lim)
979 {
980 	uint_t len;
981 
982 	for (len = 0; len != lim; len++) {
983 		if (dtrace_load8((uintptr_t)s++) == '\0')
984 			break;
985 	}
986 
987 	return (len);
988 }
989 
990 /*
991  * Check if an address falls within a toxic region.
992  */
993 static int
994 dtrace_istoxic(uintptr_t kaddr, size_t size)
995 {
996 	uintptr_t taddr, tsize;
997 	int i;
998 
999 	for (i = 0; i < dtrace_toxranges; i++) {
1000 		taddr = dtrace_toxrange[i].dtt_base;
1001 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1002 
1003 		if (kaddr - taddr < tsize) {
1004 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1005 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
1006 			return (1);
1007 		}
1008 
1009 		if (taddr - kaddr < size) {
1010 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1011 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1012 			return (1);
1013 		}
1014 	}
1015 
1016 	return (0);
1017 }
1018 
1019 /*
1020  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1021  * memory specified by the DIF program.  The dst is assumed to be safe memory
1022  * that we can store to directly because it is managed by DTrace.  As with
1023  * standard bcopy, overlapping copies are handled properly.
1024  */
1025 static void
1026 dtrace_bcopy(const void *src, void *dst, size_t len)
1027 {
1028 	if (len != 0) {
1029 		uint8_t *s1 = dst;
1030 		const uint8_t *s2 = src;
1031 
1032 		if (s1 <= s2) {
1033 			do {
1034 				*s1++ = dtrace_load8((uintptr_t)s2++);
1035 			} while (--len != 0);
1036 		} else {
1037 			s2 += len;
1038 			s1 += len;
1039 
1040 			do {
1041 				*--s1 = dtrace_load8((uintptr_t)--s2);
1042 			} while (--len != 0);
1043 		}
1044 	}
1045 }
1046 
1047 /*
1048  * Copy src to dst using safe memory accesses, up to either the specified
1049  * length, or the point that a nul byte is encountered.  The src is assumed to
1050  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1051  * safe memory that we can store to directly because it is managed by DTrace.
1052  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1053  */
1054 static void
1055 dtrace_strcpy(const void *src, void *dst, size_t len)
1056 {
1057 	if (len != 0) {
1058 		uint8_t *s1 = dst, c;
1059 		const uint8_t *s2 = src;
1060 
1061 		do {
1062 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1063 		} while (--len != 0 && c != '\0');
1064 	}
1065 }
1066 
1067 /*
1068  * Copy src to dst, deriving the size and type from the specified (BYREF)
1069  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1070  * program.  The dst is assumed to be DTrace variable memory that is of the
1071  * specified type; we assume that we can store to directly.
1072  */
1073 static void
1074 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
1075 {
1076 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1077 
1078 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1079 		dtrace_strcpy(src, dst, type->dtdt_size);
1080 	} else {
1081 		dtrace_bcopy(src, dst, type->dtdt_size);
1082 	}
1083 }
1084 
1085 /*
1086  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1087  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1088  * safe memory that we can access directly because it is managed by DTrace.
1089  */
1090 static int
1091 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1092 {
1093 	volatile uint16_t *flags;
1094 
1095 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1096 
1097 	if (s1 == s2)
1098 		return (0);
1099 
1100 	if (s1 == NULL || s2 == NULL)
1101 		return (1);
1102 
1103 	if (s1 != s2 && len != 0) {
1104 		const uint8_t *ps1 = s1;
1105 		const uint8_t *ps2 = s2;
1106 
1107 		do {
1108 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1109 				return (1);
1110 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1111 	}
1112 	return (0);
1113 }
1114 
1115 /*
1116  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1117  * is for safe DTrace-managed memory only.
1118  */
1119 static void
1120 dtrace_bzero(void *dst, size_t len)
1121 {
1122 	uchar_t *cp;
1123 
1124 	for (cp = dst; len != 0; len--)
1125 		*cp++ = 0;
1126 }
1127 
1128 static void
1129 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1130 {
1131 	uint64_t result[2];
1132 
1133 	result[0] = addend1[0] + addend2[0];
1134 	result[1] = addend1[1] + addend2[1] +
1135 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1136 
1137 	sum[0] = result[0];
1138 	sum[1] = result[1];
1139 }
1140 
1141 /*
1142  * Shift the 128-bit value in a by b. If b is positive, shift left.
1143  * If b is negative, shift right.
1144  */
1145 static void
1146 dtrace_shift_128(uint64_t *a, int b)
1147 {
1148 	uint64_t mask;
1149 
1150 	if (b == 0)
1151 		return;
1152 
1153 	if (b < 0) {
1154 		b = -b;
1155 		if (b >= 64) {
1156 			a[0] = a[1] >> (b - 64);
1157 			a[1] = 0;
1158 		} else {
1159 			a[0] >>= b;
1160 			mask = 1LL << (64 - b);
1161 			mask -= 1;
1162 			a[0] |= ((a[1] & mask) << (64 - b));
1163 			a[1] >>= b;
1164 		}
1165 	} else {
1166 		if (b >= 64) {
1167 			a[1] = a[0] << (b - 64);
1168 			a[0] = 0;
1169 		} else {
1170 			a[1] <<= b;
1171 			mask = a[0] >> (64 - b);
1172 			a[1] |= mask;
1173 			a[0] <<= b;
1174 		}
1175 	}
1176 }
1177 
1178 /*
1179  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1180  * use native multiplication on those, and then re-combine into the
1181  * resulting 128-bit value.
1182  *
1183  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1184  *     hi1 * hi2 << 64 +
1185  *     hi1 * lo2 << 32 +
1186  *     hi2 * lo1 << 32 +
1187  *     lo1 * lo2
1188  */
1189 static void
1190 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1191 {
1192 	uint64_t hi1, hi2, lo1, lo2;
1193 	uint64_t tmp[2];
1194 
1195 	hi1 = factor1 >> 32;
1196 	hi2 = factor2 >> 32;
1197 
1198 	lo1 = factor1 & DT_MASK_LO;
1199 	lo2 = factor2 & DT_MASK_LO;
1200 
1201 	product[0] = lo1 * lo2;
1202 	product[1] = hi1 * hi2;
1203 
1204 	tmp[0] = hi1 * lo2;
1205 	tmp[1] = 0;
1206 	dtrace_shift_128(tmp, 32);
1207 	dtrace_add_128(product, tmp, product);
1208 
1209 	tmp[0] = hi2 * lo1;
1210 	tmp[1] = 0;
1211 	dtrace_shift_128(tmp, 32);
1212 	dtrace_add_128(product, tmp, product);
1213 }
1214 
1215 /*
1216  * This privilege check should be used by actions and subroutines to
1217  * verify that the user credentials of the process that enabled the
1218  * invoking ECB match the target credentials
1219  */
1220 static int
1221 dtrace_priv_proc_common_user(dtrace_state_t *state)
1222 {
1223 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1224 
1225 	/*
1226 	 * We should always have a non-NULL state cred here, since if cred
1227 	 * is null (anonymous tracing), we fast-path bypass this routine.
1228 	 */
1229 	ASSERT(s_cr != NULL);
1230 
1231 	if ((cr = CRED()) != NULL &&
1232 	    s_cr->cr_uid == cr->cr_uid &&
1233 	    s_cr->cr_uid == cr->cr_ruid &&
1234 	    s_cr->cr_uid == cr->cr_suid &&
1235 	    s_cr->cr_gid == cr->cr_gid &&
1236 	    s_cr->cr_gid == cr->cr_rgid &&
1237 	    s_cr->cr_gid == cr->cr_sgid)
1238 		return (1);
1239 
1240 	return (0);
1241 }
1242 
1243 /*
1244  * This privilege check should be used by actions and subroutines to
1245  * verify that the zone of the process that enabled the invoking ECB
1246  * matches the target credentials
1247  */
1248 static int
1249 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1250 {
1251 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1252 
1253 	/*
1254 	 * We should always have a non-NULL state cred here, since if cred
1255 	 * is null (anonymous tracing), we fast-path bypass this routine.
1256 	 */
1257 	ASSERT(s_cr != NULL);
1258 
1259 	if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1260 		return (1);
1261 
1262 	return (0);
1263 }
1264 
1265 /*
1266  * This privilege check should be used by actions and subroutines to
1267  * verify that the process has not setuid or changed credentials.
1268  */
1269 static int
1270 dtrace_priv_proc_common_nocd()
1271 {
1272 	proc_t *proc;
1273 
1274 	if ((proc = ttoproc(curthread)) != NULL &&
1275 	    !(proc->p_flag & SNOCD))
1276 		return (1);
1277 
1278 	return (0);
1279 }
1280 
1281 static int
1282 dtrace_priv_proc_destructive(dtrace_state_t *state, dtrace_mstate_t *mstate)
1283 {
1284 	int action = state->dts_cred.dcr_action;
1285 
1286 	if (!(mstate->dtms_access & DTRACE_ACCESS_PROC))
1287 		goto bad;
1288 
1289 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1290 	    dtrace_priv_proc_common_zone(state) == 0)
1291 		goto bad;
1292 
1293 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1294 	    dtrace_priv_proc_common_user(state) == 0)
1295 		goto bad;
1296 
1297 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1298 	    dtrace_priv_proc_common_nocd() == 0)
1299 		goto bad;
1300 
1301 	return (1);
1302 
1303 bad:
1304 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1305 
1306 	return (0);
1307 }
1308 
1309 static int
1310 dtrace_priv_proc_control(dtrace_state_t *state, dtrace_mstate_t *mstate)
1311 {
1312 	if (mstate->dtms_access & DTRACE_ACCESS_PROC) {
1313 		if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1314 			return (1);
1315 
1316 		if (dtrace_priv_proc_common_zone(state) &&
1317 		    dtrace_priv_proc_common_user(state) &&
1318 		    dtrace_priv_proc_common_nocd())
1319 			return (1);
1320 	}
1321 
1322 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1323 
1324 	return (0);
1325 }
1326 
1327 static int
1328 dtrace_priv_proc(dtrace_state_t *state, dtrace_mstate_t *mstate)
1329 {
1330 	if ((mstate->dtms_access & DTRACE_ACCESS_PROC) &&
1331 	    (state->dts_cred.dcr_action & DTRACE_CRA_PROC))
1332 		return (1);
1333 
1334 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1335 
1336 	return (0);
1337 }
1338 
1339 static int
1340 dtrace_priv_kernel(dtrace_state_t *state)
1341 {
1342 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1343 		return (1);
1344 
1345 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1346 
1347 	return (0);
1348 }
1349 
1350 static int
1351 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1352 {
1353 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1354 		return (1);
1355 
1356 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1357 
1358 	return (0);
1359 }
1360 
1361 /*
1362  * Determine if the dte_cond of the specified ECB allows for processing of
1363  * the current probe to continue.  Note that this routine may allow continued
1364  * processing, but with access(es) stripped from the mstate's dtms_access
1365  * field.
1366  */
1367 static int
1368 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1369     dtrace_ecb_t *ecb)
1370 {
1371 	dtrace_probe_t *probe = ecb->dte_probe;
1372 	dtrace_provider_t *prov = probe->dtpr_provider;
1373 	dtrace_pops_t *pops = &prov->dtpv_pops;
1374 	int mode = DTRACE_MODE_NOPRIV_DROP;
1375 
1376 	ASSERT(ecb->dte_cond);
1377 
1378 	if (pops->dtps_mode != NULL) {
1379 		mode = pops->dtps_mode(prov->dtpv_arg,
1380 		    probe->dtpr_id, probe->dtpr_arg);
1381 
1382 		ASSERT(mode & (DTRACE_MODE_USER | DTRACE_MODE_KERNEL));
1383 		ASSERT(mode & (DTRACE_MODE_NOPRIV_RESTRICT |
1384 		    DTRACE_MODE_NOPRIV_DROP));
1385 	}
1386 
1387 	/*
1388 	 * If the dte_cond bits indicate that this consumer is only allowed to
1389 	 * see user-mode firings of this probe, check that the probe was fired
1390 	 * while in a user context.  If that's not the case, use the policy
1391 	 * specified by the provider to determine if we drop the probe or
1392 	 * merely restrict operation.
1393 	 */
1394 	if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1395 		ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1396 
1397 		if (!(mode & DTRACE_MODE_USER)) {
1398 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1399 				return (0);
1400 
1401 			mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1402 		}
1403 	}
1404 
1405 	/*
1406 	 * This is more subtle than it looks. We have to be absolutely certain
1407 	 * that CRED() isn't going to change out from under us so it's only
1408 	 * legit to examine that structure if we're in constrained situations.
1409 	 * Currently, the only times we'll this check is if a non-super-user
1410 	 * has enabled the profile or syscall providers -- providers that
1411 	 * allow visibility of all processes. For the profile case, the check
1412 	 * above will ensure that we're examining a user context.
1413 	 */
1414 	if (ecb->dte_cond & DTRACE_COND_OWNER) {
1415 		cred_t *cr;
1416 		cred_t *s_cr = state->dts_cred.dcr_cred;
1417 		proc_t *proc;
1418 
1419 		ASSERT(s_cr != NULL);
1420 
1421 		if ((cr = CRED()) == NULL ||
1422 		    s_cr->cr_uid != cr->cr_uid ||
1423 		    s_cr->cr_uid != cr->cr_ruid ||
1424 		    s_cr->cr_uid != cr->cr_suid ||
1425 		    s_cr->cr_gid != cr->cr_gid ||
1426 		    s_cr->cr_gid != cr->cr_rgid ||
1427 		    s_cr->cr_gid != cr->cr_sgid ||
1428 		    (proc = ttoproc(curthread)) == NULL ||
1429 		    (proc->p_flag & SNOCD)) {
1430 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1431 				return (0);
1432 
1433 			mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1434 		}
1435 	}
1436 
1437 	/*
1438 	 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1439 	 * in our zone, check to see if our mode policy is to restrict rather
1440 	 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1441 	 * and DTRACE_ACCESS_ARGS
1442 	 */
1443 	if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1444 		cred_t *cr;
1445 		cred_t *s_cr = state->dts_cred.dcr_cred;
1446 
1447 		ASSERT(s_cr != NULL);
1448 
1449 		if ((cr = CRED()) == NULL ||
1450 		    s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1451 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1452 				return (0);
1453 
1454 			mstate->dtms_access &=
1455 			    ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1456 		}
1457 	}
1458 
1459 	/*
1460 	 * By merits of being in this code path at all, we have limited
1461 	 * privileges.  If the provider has indicated that limited privileges
1462 	 * are to denote restricted operation, strip off the ability to access
1463 	 * arguments.
1464 	 */
1465 	if (mode & DTRACE_MODE_LIMITEDPRIV_RESTRICT)
1466 		mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1467 
1468 	return (1);
1469 }
1470 
1471 /*
1472  * Note:  not called from probe context.  This function is called
1473  * asynchronously (and at a regular interval) from outside of probe context to
1474  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1475  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1476  */
1477 void
1478 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1479 {
1480 	dtrace_dynvar_t *dirty;
1481 	dtrace_dstate_percpu_t *dcpu;
1482 	dtrace_dynvar_t **rinsep;
1483 	int i, j, work = 0;
1484 
1485 	for (i = 0; i < NCPU; i++) {
1486 		dcpu = &dstate->dtds_percpu[i];
1487 		rinsep = &dcpu->dtdsc_rinsing;
1488 
1489 		/*
1490 		 * If the dirty list is NULL, there is no dirty work to do.
1491 		 */
1492 		if (dcpu->dtdsc_dirty == NULL)
1493 			continue;
1494 
1495 		if (dcpu->dtdsc_rinsing != NULL) {
1496 			/*
1497 			 * If the rinsing list is non-NULL, then it is because
1498 			 * this CPU was selected to accept another CPU's
1499 			 * dirty list -- and since that time, dirty buffers
1500 			 * have accumulated.  This is a highly unlikely
1501 			 * condition, but we choose to ignore the dirty
1502 			 * buffers -- they'll be picked up a future cleanse.
1503 			 */
1504 			continue;
1505 		}
1506 
1507 		if (dcpu->dtdsc_clean != NULL) {
1508 			/*
1509 			 * If the clean list is non-NULL, then we're in a
1510 			 * situation where a CPU has done deallocations (we
1511 			 * have a non-NULL dirty list) but no allocations (we
1512 			 * also have a non-NULL clean list).  We can't simply
1513 			 * move the dirty list into the clean list on this
1514 			 * CPU, yet we also don't want to allow this condition
1515 			 * to persist, lest a short clean list prevent a
1516 			 * massive dirty list from being cleaned (which in
1517 			 * turn could lead to otherwise avoidable dynamic
1518 			 * drops).  To deal with this, we look for some CPU
1519 			 * with a NULL clean list, NULL dirty list, and NULL
1520 			 * rinsing list -- and then we borrow this CPU to
1521 			 * rinse our dirty list.
1522 			 */
1523 			for (j = 0; j < NCPU; j++) {
1524 				dtrace_dstate_percpu_t *rinser;
1525 
1526 				rinser = &dstate->dtds_percpu[j];
1527 
1528 				if (rinser->dtdsc_rinsing != NULL)
1529 					continue;
1530 
1531 				if (rinser->dtdsc_dirty != NULL)
1532 					continue;
1533 
1534 				if (rinser->dtdsc_clean != NULL)
1535 					continue;
1536 
1537 				rinsep = &rinser->dtdsc_rinsing;
1538 				break;
1539 			}
1540 
1541 			if (j == NCPU) {
1542 				/*
1543 				 * We were unable to find another CPU that
1544 				 * could accept this dirty list -- we are
1545 				 * therefore unable to clean it now.
1546 				 */
1547 				dtrace_dynvar_failclean++;
1548 				continue;
1549 			}
1550 		}
1551 
1552 		work = 1;
1553 
1554 		/*
1555 		 * Atomically move the dirty list aside.
1556 		 */
1557 		do {
1558 			dirty = dcpu->dtdsc_dirty;
1559 
1560 			/*
1561 			 * Before we zap the dirty list, set the rinsing list.
1562 			 * (This allows for a potential assertion in
1563 			 * dtrace_dynvar():  if a free dynamic variable appears
1564 			 * on a hash chain, either the dirty list or the
1565 			 * rinsing list for some CPU must be non-NULL.)
1566 			 */
1567 			*rinsep = dirty;
1568 			dtrace_membar_producer();
1569 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1570 		    dirty, NULL) != dirty);
1571 	}
1572 
1573 	if (!work) {
1574 		/*
1575 		 * We have no work to do; we can simply return.
1576 		 */
1577 		return;
1578 	}
1579 
1580 	dtrace_sync();
1581 
1582 	for (i = 0; i < NCPU; i++) {
1583 		dcpu = &dstate->dtds_percpu[i];
1584 
1585 		if (dcpu->dtdsc_rinsing == NULL)
1586 			continue;
1587 
1588 		/*
1589 		 * We are now guaranteed that no hash chain contains a pointer
1590 		 * into this dirty list; we can make it clean.
1591 		 */
1592 		ASSERT(dcpu->dtdsc_clean == NULL);
1593 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1594 		dcpu->dtdsc_rinsing = NULL;
1595 	}
1596 
1597 	/*
1598 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1599 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1600 	 * This prevents a race whereby a CPU incorrectly decides that
1601 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1602 	 * after dtrace_dynvar_clean() has completed.
1603 	 */
1604 	dtrace_sync();
1605 
1606 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1607 }
1608 
1609 /*
1610  * Depending on the value of the op parameter, this function looks-up,
1611  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1612  * allocation is requested, this function will return a pointer to a
1613  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1614  * variable can be allocated.  If NULL is returned, the appropriate counter
1615  * will be incremented.
1616  */
1617 dtrace_dynvar_t *
1618 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1619     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1620     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1621 {
1622 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1623 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1624 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1625 	processorid_t me = CPU->cpu_id, cpu = me;
1626 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1627 	size_t bucket, ksize;
1628 	size_t chunksize = dstate->dtds_chunksize;
1629 	uintptr_t kdata, lock, nstate;
1630 	uint_t i;
1631 
1632 	ASSERT(nkeys != 0);
1633 
1634 	/*
1635 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1636 	 * algorithm.  For the by-value portions, we perform the algorithm in
1637 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1638 	 * bit, and seems to have only a minute effect on distribution.  For
1639 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1640 	 * over each referenced byte.  It's painful to do this, but it's much
1641 	 * better than pathological hash distribution.  The efficacy of the
1642 	 * hashing algorithm (and a comparison with other algorithms) may be
1643 	 * found by running the ::dtrace_dynstat MDB dcmd.
1644 	 */
1645 	for (i = 0; i < nkeys; i++) {
1646 		if (key[i].dttk_size == 0) {
1647 			uint64_t val = key[i].dttk_value;
1648 
1649 			hashval += (val >> 48) & 0xffff;
1650 			hashval += (hashval << 10);
1651 			hashval ^= (hashval >> 6);
1652 
1653 			hashval += (val >> 32) & 0xffff;
1654 			hashval += (hashval << 10);
1655 			hashval ^= (hashval >> 6);
1656 
1657 			hashval += (val >> 16) & 0xffff;
1658 			hashval += (hashval << 10);
1659 			hashval ^= (hashval >> 6);
1660 
1661 			hashval += val & 0xffff;
1662 			hashval += (hashval << 10);
1663 			hashval ^= (hashval >> 6);
1664 		} else {
1665 			/*
1666 			 * This is incredibly painful, but it beats the hell
1667 			 * out of the alternative.
1668 			 */
1669 			uint64_t j, size = key[i].dttk_size;
1670 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1671 
1672 			if (!dtrace_canload(base, size, mstate, vstate))
1673 				break;
1674 
1675 			for (j = 0; j < size; j++) {
1676 				hashval += dtrace_load8(base + j);
1677 				hashval += (hashval << 10);
1678 				hashval ^= (hashval >> 6);
1679 			}
1680 		}
1681 	}
1682 
1683 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1684 		return (NULL);
1685 
1686 	hashval += (hashval << 3);
1687 	hashval ^= (hashval >> 11);
1688 	hashval += (hashval << 15);
1689 
1690 	/*
1691 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1692 	 * comes out to be one of our two sentinel hash values.  If this
1693 	 * actually happens, we set the hashval to be a value known to be a
1694 	 * non-sentinel value.
1695 	 */
1696 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1697 		hashval = DTRACE_DYNHASH_VALID;
1698 
1699 	/*
1700 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1701 	 * important here, tricks can be pulled to reduce it.  (However, it's
1702 	 * critical that hash collisions be kept to an absolute minimum;
1703 	 * they're much more painful than a divide.)  It's better to have a
1704 	 * solution that generates few collisions and still keeps things
1705 	 * relatively simple.
1706 	 */
1707 	bucket = hashval % dstate->dtds_hashsize;
1708 
1709 	if (op == DTRACE_DYNVAR_DEALLOC) {
1710 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1711 
1712 		for (;;) {
1713 			while ((lock = *lockp) & 1)
1714 				continue;
1715 
1716 			if (dtrace_casptr((void *)lockp,
1717 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1718 				break;
1719 		}
1720 
1721 		dtrace_membar_producer();
1722 	}
1723 
1724 top:
1725 	prev = NULL;
1726 	lock = hash[bucket].dtdh_lock;
1727 
1728 	dtrace_membar_consumer();
1729 
1730 	start = hash[bucket].dtdh_chain;
1731 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1732 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1733 	    op != DTRACE_DYNVAR_DEALLOC));
1734 
1735 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1736 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1737 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1738 
1739 		if (dvar->dtdv_hashval != hashval) {
1740 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1741 				/*
1742 				 * We've reached the sink, and therefore the
1743 				 * end of the hash chain; we can kick out of
1744 				 * the loop knowing that we have seen a valid
1745 				 * snapshot of state.
1746 				 */
1747 				ASSERT(dvar->dtdv_next == NULL);
1748 				ASSERT(dvar == &dtrace_dynhash_sink);
1749 				break;
1750 			}
1751 
1752 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1753 				/*
1754 				 * We've gone off the rails:  somewhere along
1755 				 * the line, one of the members of this hash
1756 				 * chain was deleted.  Note that we could also
1757 				 * detect this by simply letting this loop run
1758 				 * to completion, as we would eventually hit
1759 				 * the end of the dirty list.  However, we
1760 				 * want to avoid running the length of the
1761 				 * dirty list unnecessarily (it might be quite
1762 				 * long), so we catch this as early as
1763 				 * possible by detecting the hash marker.  In
1764 				 * this case, we simply set dvar to NULL and
1765 				 * break; the conditional after the loop will
1766 				 * send us back to top.
1767 				 */
1768 				dvar = NULL;
1769 				break;
1770 			}
1771 
1772 			goto next;
1773 		}
1774 
1775 		if (dtuple->dtt_nkeys != nkeys)
1776 			goto next;
1777 
1778 		for (i = 0; i < nkeys; i++, dkey++) {
1779 			if (dkey->dttk_size != key[i].dttk_size)
1780 				goto next; /* size or type mismatch */
1781 
1782 			if (dkey->dttk_size != 0) {
1783 				if (dtrace_bcmp(
1784 				    (void *)(uintptr_t)key[i].dttk_value,
1785 				    (void *)(uintptr_t)dkey->dttk_value,
1786 				    dkey->dttk_size))
1787 					goto next;
1788 			} else {
1789 				if (dkey->dttk_value != key[i].dttk_value)
1790 					goto next;
1791 			}
1792 		}
1793 
1794 		if (op != DTRACE_DYNVAR_DEALLOC)
1795 			return (dvar);
1796 
1797 		ASSERT(dvar->dtdv_next == NULL ||
1798 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1799 
1800 		if (prev != NULL) {
1801 			ASSERT(hash[bucket].dtdh_chain != dvar);
1802 			ASSERT(start != dvar);
1803 			ASSERT(prev->dtdv_next == dvar);
1804 			prev->dtdv_next = dvar->dtdv_next;
1805 		} else {
1806 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1807 			    start, dvar->dtdv_next) != start) {
1808 				/*
1809 				 * We have failed to atomically swing the
1810 				 * hash table head pointer, presumably because
1811 				 * of a conflicting allocation on another CPU.
1812 				 * We need to reread the hash chain and try
1813 				 * again.
1814 				 */
1815 				goto top;
1816 			}
1817 		}
1818 
1819 		dtrace_membar_producer();
1820 
1821 		/*
1822 		 * Now set the hash value to indicate that it's free.
1823 		 */
1824 		ASSERT(hash[bucket].dtdh_chain != dvar);
1825 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1826 
1827 		dtrace_membar_producer();
1828 
1829 		/*
1830 		 * Set the next pointer to point at the dirty list, and
1831 		 * atomically swing the dirty pointer to the newly freed dvar.
1832 		 */
1833 		do {
1834 			next = dcpu->dtdsc_dirty;
1835 			dvar->dtdv_next = next;
1836 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1837 
1838 		/*
1839 		 * Finally, unlock this hash bucket.
1840 		 */
1841 		ASSERT(hash[bucket].dtdh_lock == lock);
1842 		ASSERT(lock & 1);
1843 		hash[bucket].dtdh_lock++;
1844 
1845 		return (NULL);
1846 next:
1847 		prev = dvar;
1848 		continue;
1849 	}
1850 
1851 	if (dvar == NULL) {
1852 		/*
1853 		 * If dvar is NULL, it is because we went off the rails:
1854 		 * one of the elements that we traversed in the hash chain
1855 		 * was deleted while we were traversing it.  In this case,
1856 		 * we assert that we aren't doing a dealloc (deallocs lock
1857 		 * the hash bucket to prevent themselves from racing with
1858 		 * one another), and retry the hash chain traversal.
1859 		 */
1860 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1861 		goto top;
1862 	}
1863 
1864 	if (op != DTRACE_DYNVAR_ALLOC) {
1865 		/*
1866 		 * If we are not to allocate a new variable, we want to
1867 		 * return NULL now.  Before we return, check that the value
1868 		 * of the lock word hasn't changed.  If it has, we may have
1869 		 * seen an inconsistent snapshot.
1870 		 */
1871 		if (op == DTRACE_DYNVAR_NOALLOC) {
1872 			if (hash[bucket].dtdh_lock != lock)
1873 				goto top;
1874 		} else {
1875 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1876 			ASSERT(hash[bucket].dtdh_lock == lock);
1877 			ASSERT(lock & 1);
1878 			hash[bucket].dtdh_lock++;
1879 		}
1880 
1881 		return (NULL);
1882 	}
1883 
1884 	/*
1885 	 * We need to allocate a new dynamic variable.  The size we need is the
1886 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1887 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1888 	 * the size of any referred-to data (dsize).  We then round the final
1889 	 * size up to the chunksize for allocation.
1890 	 */
1891 	for (ksize = 0, i = 0; i < nkeys; i++)
1892 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1893 
1894 	/*
1895 	 * This should be pretty much impossible, but could happen if, say,
1896 	 * strange DIF specified the tuple.  Ideally, this should be an
1897 	 * assertion and not an error condition -- but that requires that the
1898 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1899 	 * bullet-proof.  (That is, it must not be able to be fooled by
1900 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1901 	 * solving this would presumably not amount to solving the Halting
1902 	 * Problem -- but it still seems awfully hard.
1903 	 */
1904 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1905 	    ksize + dsize > chunksize) {
1906 		dcpu->dtdsc_drops++;
1907 		return (NULL);
1908 	}
1909 
1910 	nstate = DTRACE_DSTATE_EMPTY;
1911 
1912 	do {
1913 retry:
1914 		free = dcpu->dtdsc_free;
1915 
1916 		if (free == NULL) {
1917 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1918 			void *rval;
1919 
1920 			if (clean == NULL) {
1921 				/*
1922 				 * We're out of dynamic variable space on
1923 				 * this CPU.  Unless we have tried all CPUs,
1924 				 * we'll try to allocate from a different
1925 				 * CPU.
1926 				 */
1927 				switch (dstate->dtds_state) {
1928 				case DTRACE_DSTATE_CLEAN: {
1929 					void *sp = &dstate->dtds_state;
1930 
1931 					if (++cpu >= NCPU)
1932 						cpu = 0;
1933 
1934 					if (dcpu->dtdsc_dirty != NULL &&
1935 					    nstate == DTRACE_DSTATE_EMPTY)
1936 						nstate = DTRACE_DSTATE_DIRTY;
1937 
1938 					if (dcpu->dtdsc_rinsing != NULL)
1939 						nstate = DTRACE_DSTATE_RINSING;
1940 
1941 					dcpu = &dstate->dtds_percpu[cpu];
1942 
1943 					if (cpu != me)
1944 						goto retry;
1945 
1946 					(void) dtrace_cas32(sp,
1947 					    DTRACE_DSTATE_CLEAN, nstate);
1948 
1949 					/*
1950 					 * To increment the correct bean
1951 					 * counter, take another lap.
1952 					 */
1953 					goto retry;
1954 				}
1955 
1956 				case DTRACE_DSTATE_DIRTY:
1957 					dcpu->dtdsc_dirty_drops++;
1958 					break;
1959 
1960 				case DTRACE_DSTATE_RINSING:
1961 					dcpu->dtdsc_rinsing_drops++;
1962 					break;
1963 
1964 				case DTRACE_DSTATE_EMPTY:
1965 					dcpu->dtdsc_drops++;
1966 					break;
1967 				}
1968 
1969 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1970 				return (NULL);
1971 			}
1972 
1973 			/*
1974 			 * The clean list appears to be non-empty.  We want to
1975 			 * move the clean list to the free list; we start by
1976 			 * moving the clean pointer aside.
1977 			 */
1978 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1979 			    clean, NULL) != clean) {
1980 				/*
1981 				 * We are in one of two situations:
1982 				 *
1983 				 *  (a)	The clean list was switched to the
1984 				 *	free list by another CPU.
1985 				 *
1986 				 *  (b)	The clean list was added to by the
1987 				 *	cleansing cyclic.
1988 				 *
1989 				 * In either of these situations, we can
1990 				 * just reattempt the free list allocation.
1991 				 */
1992 				goto retry;
1993 			}
1994 
1995 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1996 
1997 			/*
1998 			 * Now we'll move the clean list to our free list.
1999 			 * It's impossible for this to fail:  the only way
2000 			 * the free list can be updated is through this
2001 			 * code path, and only one CPU can own the clean list.
2002 			 * Thus, it would only be possible for this to fail if
2003 			 * this code were racing with dtrace_dynvar_clean().
2004 			 * (That is, if dtrace_dynvar_clean() updated the clean
2005 			 * list, and we ended up racing to update the free
2006 			 * list.)  This race is prevented by the dtrace_sync()
2007 			 * in dtrace_dynvar_clean() -- which flushes the
2008 			 * owners of the clean lists out before resetting
2009 			 * the clean lists.
2010 			 */
2011 			dcpu = &dstate->dtds_percpu[me];
2012 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2013 			ASSERT(rval == NULL);
2014 			goto retry;
2015 		}
2016 
2017 		dvar = free;
2018 		new_free = dvar->dtdv_next;
2019 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2020 
2021 	/*
2022 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2023 	 * tuple array and copy any referenced key data into the data space
2024 	 * following the tuple array.  As we do this, we relocate dttk_value
2025 	 * in the final tuple to point to the key data address in the chunk.
2026 	 */
2027 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2028 	dvar->dtdv_data = (void *)(kdata + ksize);
2029 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2030 
2031 	for (i = 0; i < nkeys; i++) {
2032 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2033 		size_t kesize = key[i].dttk_size;
2034 
2035 		if (kesize != 0) {
2036 			dtrace_bcopy(
2037 			    (const void *)(uintptr_t)key[i].dttk_value,
2038 			    (void *)kdata, kesize);
2039 			dkey->dttk_value = kdata;
2040 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2041 		} else {
2042 			dkey->dttk_value = key[i].dttk_value;
2043 		}
2044 
2045 		dkey->dttk_size = kesize;
2046 	}
2047 
2048 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2049 	dvar->dtdv_hashval = hashval;
2050 	dvar->dtdv_next = start;
2051 
2052 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2053 		return (dvar);
2054 
2055 	/*
2056 	 * The cas has failed.  Either another CPU is adding an element to
2057 	 * this hash chain, or another CPU is deleting an element from this
2058 	 * hash chain.  The simplest way to deal with both of these cases
2059 	 * (though not necessarily the most efficient) is to free our
2060 	 * allocated block and re-attempt it all.  Note that the free is
2061 	 * to the dirty list and _not_ to the free list.  This is to prevent
2062 	 * races with allocators, above.
2063 	 */
2064 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2065 
2066 	dtrace_membar_producer();
2067 
2068 	do {
2069 		free = dcpu->dtdsc_dirty;
2070 		dvar->dtdv_next = free;
2071 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2072 
2073 	goto top;
2074 }
2075 
2076 /*ARGSUSED*/
2077 static void
2078 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2079 {
2080 	if ((int64_t)nval < (int64_t)*oval)
2081 		*oval = nval;
2082 }
2083 
2084 /*ARGSUSED*/
2085 static void
2086 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2087 {
2088 	if ((int64_t)nval > (int64_t)*oval)
2089 		*oval = nval;
2090 }
2091 
2092 static void
2093 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2094 {
2095 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2096 	int64_t val = (int64_t)nval;
2097 
2098 	if (val < 0) {
2099 		for (i = 0; i < zero; i++) {
2100 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2101 				quanta[i] += incr;
2102 				return;
2103 			}
2104 		}
2105 	} else {
2106 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2107 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2108 				quanta[i - 1] += incr;
2109 				return;
2110 			}
2111 		}
2112 
2113 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2114 		return;
2115 	}
2116 
2117 	ASSERT(0);
2118 }
2119 
2120 static void
2121 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2122 {
2123 	uint64_t arg = *lquanta++;
2124 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2125 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2126 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2127 	int32_t val = (int32_t)nval, level;
2128 
2129 	ASSERT(step != 0);
2130 	ASSERT(levels != 0);
2131 
2132 	if (val < base) {
2133 		/*
2134 		 * This is an underflow.
2135 		 */
2136 		lquanta[0] += incr;
2137 		return;
2138 	}
2139 
2140 	level = (val - base) / step;
2141 
2142 	if (level < levels) {
2143 		lquanta[level + 1] += incr;
2144 		return;
2145 	}
2146 
2147 	/*
2148 	 * This is an overflow.
2149 	 */
2150 	lquanta[levels + 1] += incr;
2151 }
2152 
2153 static int
2154 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2155     uint16_t high, uint16_t nsteps, int64_t value)
2156 {
2157 	int64_t this = 1, last, next;
2158 	int base = 1, order;
2159 
2160 	ASSERT(factor <= nsteps);
2161 	ASSERT(nsteps % factor == 0);
2162 
2163 	for (order = 0; order < low; order++)
2164 		this *= factor;
2165 
2166 	/*
2167 	 * If our value is less than our factor taken to the power of the
2168 	 * low order of magnitude, it goes into the zeroth bucket.
2169 	 */
2170 	if (value < (last = this))
2171 		return (0);
2172 
2173 	for (this *= factor; order <= high; order++) {
2174 		int nbuckets = this > nsteps ? nsteps : this;
2175 
2176 		if ((next = this * factor) < this) {
2177 			/*
2178 			 * We should not generally get log/linear quantizations
2179 			 * with a high magnitude that allows 64-bits to
2180 			 * overflow, but we nonetheless protect against this
2181 			 * by explicitly checking for overflow, and clamping
2182 			 * our value accordingly.
2183 			 */
2184 			value = this - 1;
2185 		}
2186 
2187 		if (value < this) {
2188 			/*
2189 			 * If our value lies within this order of magnitude,
2190 			 * determine its position by taking the offset within
2191 			 * the order of magnitude, dividing by the bucket
2192 			 * width, and adding to our (accumulated) base.
2193 			 */
2194 			return (base + (value - last) / (this / nbuckets));
2195 		}
2196 
2197 		base += nbuckets - (nbuckets / factor);
2198 		last = this;
2199 		this = next;
2200 	}
2201 
2202 	/*
2203 	 * Our value is greater than or equal to our factor taken to the
2204 	 * power of one plus the high magnitude -- return the top bucket.
2205 	 */
2206 	return (base);
2207 }
2208 
2209 static void
2210 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2211 {
2212 	uint64_t arg = *llquanta++;
2213 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2214 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2215 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2216 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2217 
2218 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
2219 	    low, high, nsteps, nval)] += incr;
2220 }
2221 
2222 /*ARGSUSED*/
2223 static void
2224 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2225 {
2226 	data[0]++;
2227 	data[1] += nval;
2228 }
2229 
2230 /*ARGSUSED*/
2231 static void
2232 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2233 {
2234 	int64_t snval = (int64_t)nval;
2235 	uint64_t tmp[2];
2236 
2237 	data[0]++;
2238 	data[1] += nval;
2239 
2240 	/*
2241 	 * What we want to say here is:
2242 	 *
2243 	 * data[2] += nval * nval;
2244 	 *
2245 	 * But given that nval is 64-bit, we could easily overflow, so
2246 	 * we do this as 128-bit arithmetic.
2247 	 */
2248 	if (snval < 0)
2249 		snval = -snval;
2250 
2251 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2252 	dtrace_add_128(data + 2, tmp, data + 2);
2253 }
2254 
2255 /*ARGSUSED*/
2256 static void
2257 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2258 {
2259 	*oval = *oval + 1;
2260 }
2261 
2262 /*ARGSUSED*/
2263 static void
2264 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2265 {
2266 	*oval += nval;
2267 }
2268 
2269 /*
2270  * Aggregate given the tuple in the principal data buffer, and the aggregating
2271  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2272  * buffer is specified as the buf parameter.  This routine does not return
2273  * failure; if there is no space in the aggregation buffer, the data will be
2274  * dropped, and a corresponding counter incremented.
2275  */
2276 static void
2277 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2278     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2279 {
2280 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2281 	uint32_t i, ndx, size, fsize;
2282 	uint32_t align = sizeof (uint64_t) - 1;
2283 	dtrace_aggbuffer_t *agb;
2284 	dtrace_aggkey_t *key;
2285 	uint32_t hashval = 0, limit, isstr;
2286 	caddr_t tomax, data, kdata;
2287 	dtrace_actkind_t action;
2288 	dtrace_action_t *act;
2289 	uintptr_t offs;
2290 
2291 	if (buf == NULL)
2292 		return;
2293 
2294 	if (!agg->dtag_hasarg) {
2295 		/*
2296 		 * Currently, only quantize() and lquantize() take additional
2297 		 * arguments, and they have the same semantics:  an increment
2298 		 * value that defaults to 1 when not present.  If additional
2299 		 * aggregating actions take arguments, the setting of the
2300 		 * default argument value will presumably have to become more
2301 		 * sophisticated...
2302 		 */
2303 		arg = 1;
2304 	}
2305 
2306 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2307 	size = rec->dtrd_offset - agg->dtag_base;
2308 	fsize = size + rec->dtrd_size;
2309 
2310 	ASSERT(dbuf->dtb_tomax != NULL);
2311 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2312 
2313 	if ((tomax = buf->dtb_tomax) == NULL) {
2314 		dtrace_buffer_drop(buf);
2315 		return;
2316 	}
2317 
2318 	/*
2319 	 * The metastructure is always at the bottom of the buffer.
2320 	 */
2321 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2322 	    sizeof (dtrace_aggbuffer_t));
2323 
2324 	if (buf->dtb_offset == 0) {
2325 		/*
2326 		 * We just kludge up approximately 1/8th of the size to be
2327 		 * buckets.  If this guess ends up being routinely
2328 		 * off-the-mark, we may need to dynamically readjust this
2329 		 * based on past performance.
2330 		 */
2331 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2332 
2333 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2334 		    (uintptr_t)tomax || hashsize == 0) {
2335 			/*
2336 			 * We've been given a ludicrously small buffer;
2337 			 * increment our drop count and leave.
2338 			 */
2339 			dtrace_buffer_drop(buf);
2340 			return;
2341 		}
2342 
2343 		/*
2344 		 * And now, a pathetic attempt to try to get a an odd (or
2345 		 * perchance, a prime) hash size for better hash distribution.
2346 		 */
2347 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2348 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2349 
2350 		agb->dtagb_hashsize = hashsize;
2351 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2352 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2353 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2354 
2355 		for (i = 0; i < agb->dtagb_hashsize; i++)
2356 			agb->dtagb_hash[i] = NULL;
2357 	}
2358 
2359 	ASSERT(agg->dtag_first != NULL);
2360 	ASSERT(agg->dtag_first->dta_intuple);
2361 
2362 	/*
2363 	 * Calculate the hash value based on the key.  Note that we _don't_
2364 	 * include the aggid in the hashing (but we will store it as part of
2365 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2366 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2367 	 * gets good distribution in practice.  The efficacy of the hashing
2368 	 * algorithm (and a comparison with other algorithms) may be found by
2369 	 * running the ::dtrace_aggstat MDB dcmd.
2370 	 */
2371 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2372 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2373 		limit = i + act->dta_rec.dtrd_size;
2374 		ASSERT(limit <= size);
2375 		isstr = DTRACEACT_ISSTRING(act);
2376 
2377 		for (; i < limit; i++) {
2378 			hashval += data[i];
2379 			hashval += (hashval << 10);
2380 			hashval ^= (hashval >> 6);
2381 
2382 			if (isstr && data[i] == '\0')
2383 				break;
2384 		}
2385 	}
2386 
2387 	hashval += (hashval << 3);
2388 	hashval ^= (hashval >> 11);
2389 	hashval += (hashval << 15);
2390 
2391 	/*
2392 	 * Yes, the divide here is expensive -- but it's generally the least
2393 	 * of the performance issues given the amount of data that we iterate
2394 	 * over to compute hash values, compare data, etc.
2395 	 */
2396 	ndx = hashval % agb->dtagb_hashsize;
2397 
2398 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2399 		ASSERT((caddr_t)key >= tomax);
2400 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2401 
2402 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2403 			continue;
2404 
2405 		kdata = key->dtak_data;
2406 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2407 
2408 		for (act = agg->dtag_first; act->dta_intuple;
2409 		    act = act->dta_next) {
2410 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2411 			limit = i + act->dta_rec.dtrd_size;
2412 			ASSERT(limit <= size);
2413 			isstr = DTRACEACT_ISSTRING(act);
2414 
2415 			for (; i < limit; i++) {
2416 				if (kdata[i] != data[i])
2417 					goto next;
2418 
2419 				if (isstr && data[i] == '\0')
2420 					break;
2421 			}
2422 		}
2423 
2424 		if (action != key->dtak_action) {
2425 			/*
2426 			 * We are aggregating on the same value in the same
2427 			 * aggregation with two different aggregating actions.
2428 			 * (This should have been picked up in the compiler,
2429 			 * so we may be dealing with errant or devious DIF.)
2430 			 * This is an error condition; we indicate as much,
2431 			 * and return.
2432 			 */
2433 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2434 			return;
2435 		}
2436 
2437 		/*
2438 		 * This is a hit:  we need to apply the aggregator to
2439 		 * the value at this key.
2440 		 */
2441 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2442 		return;
2443 next:
2444 		continue;
2445 	}
2446 
2447 	/*
2448 	 * We didn't find it.  We need to allocate some zero-filled space,
2449 	 * link it into the hash table appropriately, and apply the aggregator
2450 	 * to the (zero-filled) value.
2451 	 */
2452 	offs = buf->dtb_offset;
2453 	while (offs & (align - 1))
2454 		offs += sizeof (uint32_t);
2455 
2456 	/*
2457 	 * If we don't have enough room to both allocate a new key _and_
2458 	 * its associated data, increment the drop count and return.
2459 	 */
2460 	if ((uintptr_t)tomax + offs + fsize >
2461 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2462 		dtrace_buffer_drop(buf);
2463 		return;
2464 	}
2465 
2466 	/*CONSTCOND*/
2467 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2468 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2469 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2470 
2471 	key->dtak_data = kdata = tomax + offs;
2472 	buf->dtb_offset = offs + fsize;
2473 
2474 	/*
2475 	 * Now copy the data across.
2476 	 */
2477 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2478 
2479 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2480 		kdata[i] = data[i];
2481 
2482 	/*
2483 	 * Because strings are not zeroed out by default, we need to iterate
2484 	 * looking for actions that store strings, and we need to explicitly
2485 	 * pad these strings out with zeroes.
2486 	 */
2487 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2488 		int nul;
2489 
2490 		if (!DTRACEACT_ISSTRING(act))
2491 			continue;
2492 
2493 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2494 		limit = i + act->dta_rec.dtrd_size;
2495 		ASSERT(limit <= size);
2496 
2497 		for (nul = 0; i < limit; i++) {
2498 			if (nul) {
2499 				kdata[i] = '\0';
2500 				continue;
2501 			}
2502 
2503 			if (data[i] != '\0')
2504 				continue;
2505 
2506 			nul = 1;
2507 		}
2508 	}
2509 
2510 	for (i = size; i < fsize; i++)
2511 		kdata[i] = 0;
2512 
2513 	key->dtak_hashval = hashval;
2514 	key->dtak_size = size;
2515 	key->dtak_action = action;
2516 	key->dtak_next = agb->dtagb_hash[ndx];
2517 	agb->dtagb_hash[ndx] = key;
2518 
2519 	/*
2520 	 * Finally, apply the aggregator.
2521 	 */
2522 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2523 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2524 }
2525 
2526 /*
2527  * Given consumer state, this routine finds a speculation in the INACTIVE
2528  * state and transitions it into the ACTIVE state.  If there is no speculation
2529  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2530  * incremented -- it is up to the caller to take appropriate action.
2531  */
2532 static int
2533 dtrace_speculation(dtrace_state_t *state)
2534 {
2535 	int i = 0;
2536 	dtrace_speculation_state_t current;
2537 	uint32_t *stat = &state->dts_speculations_unavail, count;
2538 
2539 	while (i < state->dts_nspeculations) {
2540 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2541 
2542 		current = spec->dtsp_state;
2543 
2544 		if (current != DTRACESPEC_INACTIVE) {
2545 			if (current == DTRACESPEC_COMMITTINGMANY ||
2546 			    current == DTRACESPEC_COMMITTING ||
2547 			    current == DTRACESPEC_DISCARDING)
2548 				stat = &state->dts_speculations_busy;
2549 			i++;
2550 			continue;
2551 		}
2552 
2553 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2554 		    current, DTRACESPEC_ACTIVE) == current)
2555 			return (i + 1);
2556 	}
2557 
2558 	/*
2559 	 * We couldn't find a speculation.  If we found as much as a single
2560 	 * busy speculation buffer, we'll attribute this failure as "busy"
2561 	 * instead of "unavail".
2562 	 */
2563 	do {
2564 		count = *stat;
2565 	} while (dtrace_cas32(stat, count, count + 1) != count);
2566 
2567 	return (0);
2568 }
2569 
2570 /*
2571  * This routine commits an active speculation.  If the specified speculation
2572  * is not in a valid state to perform a commit(), this routine will silently do
2573  * nothing.  The state of the specified speculation is transitioned according
2574  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2575  */
2576 static void
2577 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2578     dtrace_specid_t which)
2579 {
2580 	dtrace_speculation_t *spec;
2581 	dtrace_buffer_t *src, *dest;
2582 	uintptr_t daddr, saddr, dlimit, slimit;
2583 	dtrace_speculation_state_t current, new;
2584 	intptr_t offs;
2585 	uint64_t timestamp;
2586 
2587 	if (which == 0)
2588 		return;
2589 
2590 	if (which > state->dts_nspeculations) {
2591 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2592 		return;
2593 	}
2594 
2595 	spec = &state->dts_speculations[which - 1];
2596 	src = &spec->dtsp_buffer[cpu];
2597 	dest = &state->dts_buffer[cpu];
2598 
2599 	do {
2600 		current = spec->dtsp_state;
2601 
2602 		if (current == DTRACESPEC_COMMITTINGMANY)
2603 			break;
2604 
2605 		switch (current) {
2606 		case DTRACESPEC_INACTIVE:
2607 		case DTRACESPEC_DISCARDING:
2608 			return;
2609 
2610 		case DTRACESPEC_COMMITTING:
2611 			/*
2612 			 * This is only possible if we are (a) commit()'ing
2613 			 * without having done a prior speculate() on this CPU
2614 			 * and (b) racing with another commit() on a different
2615 			 * CPU.  There's nothing to do -- we just assert that
2616 			 * our offset is 0.
2617 			 */
2618 			ASSERT(src->dtb_offset == 0);
2619 			return;
2620 
2621 		case DTRACESPEC_ACTIVE:
2622 			new = DTRACESPEC_COMMITTING;
2623 			break;
2624 
2625 		case DTRACESPEC_ACTIVEONE:
2626 			/*
2627 			 * This speculation is active on one CPU.  If our
2628 			 * buffer offset is non-zero, we know that the one CPU
2629 			 * must be us.  Otherwise, we are committing on a
2630 			 * different CPU from the speculate(), and we must
2631 			 * rely on being asynchronously cleaned.
2632 			 */
2633 			if (src->dtb_offset != 0) {
2634 				new = DTRACESPEC_COMMITTING;
2635 				break;
2636 			}
2637 			/*FALLTHROUGH*/
2638 
2639 		case DTRACESPEC_ACTIVEMANY:
2640 			new = DTRACESPEC_COMMITTINGMANY;
2641 			break;
2642 
2643 		default:
2644 			ASSERT(0);
2645 		}
2646 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2647 	    current, new) != current);
2648 
2649 	/*
2650 	 * We have set the state to indicate that we are committing this
2651 	 * speculation.  Now reserve the necessary space in the destination
2652 	 * buffer.
2653 	 */
2654 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2655 	    sizeof (uint64_t), state, NULL)) < 0) {
2656 		dtrace_buffer_drop(dest);
2657 		goto out;
2658 	}
2659 
2660 	/*
2661 	 * We have sufficient space to copy the speculative buffer into the
2662 	 * primary buffer.  First, modify the speculative buffer, filling
2663 	 * in the timestamp of all entries with the current time.  The data
2664 	 * must have the commit() time rather than the time it was traced,
2665 	 * so that all entries in the primary buffer are in timestamp order.
2666 	 */
2667 	timestamp = dtrace_gethrtime();
2668 	saddr = (uintptr_t)src->dtb_tomax;
2669 	slimit = saddr + src->dtb_offset;
2670 	while (saddr < slimit) {
2671 		size_t size;
2672 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2673 
2674 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2675 			saddr += sizeof (dtrace_epid_t);
2676 			continue;
2677 		}
2678 		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2679 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2680 
2681 		ASSERT3U(saddr + size, <=, slimit);
2682 		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2683 		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2684 
2685 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2686 
2687 		saddr += size;
2688 	}
2689 
2690 	/*
2691 	 * Copy the buffer across.  (Note that this is a
2692 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2693 	 * a serious performance issue, a high-performance DTrace-specific
2694 	 * bcopy() should obviously be invented.)
2695 	 */
2696 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2697 	dlimit = daddr + src->dtb_offset;
2698 	saddr = (uintptr_t)src->dtb_tomax;
2699 
2700 	/*
2701 	 * First, the aligned portion.
2702 	 */
2703 	while (dlimit - daddr >= sizeof (uint64_t)) {
2704 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2705 
2706 		daddr += sizeof (uint64_t);
2707 		saddr += sizeof (uint64_t);
2708 	}
2709 
2710 	/*
2711 	 * Now any left-over bit...
2712 	 */
2713 	while (dlimit - daddr)
2714 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2715 
2716 	/*
2717 	 * Finally, commit the reserved space in the destination buffer.
2718 	 */
2719 	dest->dtb_offset = offs + src->dtb_offset;
2720 
2721 out:
2722 	/*
2723 	 * If we're lucky enough to be the only active CPU on this speculation
2724 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2725 	 */
2726 	if (current == DTRACESPEC_ACTIVE ||
2727 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2728 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2729 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2730 
2731 		ASSERT(rval == DTRACESPEC_COMMITTING);
2732 	}
2733 
2734 	src->dtb_offset = 0;
2735 	src->dtb_xamot_drops += src->dtb_drops;
2736 	src->dtb_drops = 0;
2737 }
2738 
2739 /*
2740  * This routine discards an active speculation.  If the specified speculation
2741  * is not in a valid state to perform a discard(), this routine will silently
2742  * do nothing.  The state of the specified speculation is transitioned
2743  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2744  */
2745 static void
2746 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2747     dtrace_specid_t which)
2748 {
2749 	dtrace_speculation_t *spec;
2750 	dtrace_speculation_state_t current, new;
2751 	dtrace_buffer_t *buf;
2752 
2753 	if (which == 0)
2754 		return;
2755 
2756 	if (which > state->dts_nspeculations) {
2757 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2758 		return;
2759 	}
2760 
2761 	spec = &state->dts_speculations[which - 1];
2762 	buf = &spec->dtsp_buffer[cpu];
2763 
2764 	do {
2765 		current = spec->dtsp_state;
2766 
2767 		switch (current) {
2768 		case DTRACESPEC_INACTIVE:
2769 		case DTRACESPEC_COMMITTINGMANY:
2770 		case DTRACESPEC_COMMITTING:
2771 		case DTRACESPEC_DISCARDING:
2772 			return;
2773 
2774 		case DTRACESPEC_ACTIVE:
2775 		case DTRACESPEC_ACTIVEMANY:
2776 			new = DTRACESPEC_DISCARDING;
2777 			break;
2778 
2779 		case DTRACESPEC_ACTIVEONE:
2780 			if (buf->dtb_offset != 0) {
2781 				new = DTRACESPEC_INACTIVE;
2782 			} else {
2783 				new = DTRACESPEC_DISCARDING;
2784 			}
2785 			break;
2786 
2787 		default:
2788 			ASSERT(0);
2789 		}
2790 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2791 	    current, new) != current);
2792 
2793 	buf->dtb_offset = 0;
2794 	buf->dtb_drops = 0;
2795 }
2796 
2797 /*
2798  * Note:  not called from probe context.  This function is called
2799  * asynchronously from cross call context to clean any speculations that are
2800  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2801  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2802  * speculation.
2803  */
2804 static void
2805 dtrace_speculation_clean_here(dtrace_state_t *state)
2806 {
2807 	dtrace_icookie_t cookie;
2808 	processorid_t cpu = CPU->cpu_id;
2809 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2810 	dtrace_specid_t i;
2811 
2812 	cookie = dtrace_interrupt_disable();
2813 
2814 	if (dest->dtb_tomax == NULL) {
2815 		dtrace_interrupt_enable(cookie);
2816 		return;
2817 	}
2818 
2819 	for (i = 0; i < state->dts_nspeculations; i++) {
2820 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2821 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2822 
2823 		if (src->dtb_tomax == NULL)
2824 			continue;
2825 
2826 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2827 			src->dtb_offset = 0;
2828 			continue;
2829 		}
2830 
2831 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2832 			continue;
2833 
2834 		if (src->dtb_offset == 0)
2835 			continue;
2836 
2837 		dtrace_speculation_commit(state, cpu, i + 1);
2838 	}
2839 
2840 	dtrace_interrupt_enable(cookie);
2841 }
2842 
2843 /*
2844  * Note:  not called from probe context.  This function is called
2845  * asynchronously (and at a regular interval) to clean any speculations that
2846  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2847  * is work to be done, it cross calls all CPUs to perform that work;
2848  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2849  * INACTIVE state until they have been cleaned by all CPUs.
2850  */
2851 static void
2852 dtrace_speculation_clean(dtrace_state_t *state)
2853 {
2854 	int work = 0, rv;
2855 	dtrace_specid_t i;
2856 
2857 	for (i = 0; i < state->dts_nspeculations; i++) {
2858 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2859 
2860 		ASSERT(!spec->dtsp_cleaning);
2861 
2862 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2863 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2864 			continue;
2865 
2866 		work++;
2867 		spec->dtsp_cleaning = 1;
2868 	}
2869 
2870 	if (!work)
2871 		return;
2872 
2873 	dtrace_xcall(DTRACE_CPUALL,
2874 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2875 
2876 	/*
2877 	 * We now know that all CPUs have committed or discarded their
2878 	 * speculation buffers, as appropriate.  We can now set the state
2879 	 * to inactive.
2880 	 */
2881 	for (i = 0; i < state->dts_nspeculations; i++) {
2882 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2883 		dtrace_speculation_state_t current, new;
2884 
2885 		if (!spec->dtsp_cleaning)
2886 			continue;
2887 
2888 		current = spec->dtsp_state;
2889 		ASSERT(current == DTRACESPEC_DISCARDING ||
2890 		    current == DTRACESPEC_COMMITTINGMANY);
2891 
2892 		new = DTRACESPEC_INACTIVE;
2893 
2894 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2895 		ASSERT(rv == current);
2896 		spec->dtsp_cleaning = 0;
2897 	}
2898 }
2899 
2900 /*
2901  * Called as part of a speculate() to get the speculative buffer associated
2902  * with a given speculation.  Returns NULL if the specified speculation is not
2903  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2904  * the active CPU is not the specified CPU -- the speculation will be
2905  * atomically transitioned into the ACTIVEMANY state.
2906  */
2907 static dtrace_buffer_t *
2908 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2909     dtrace_specid_t which)
2910 {
2911 	dtrace_speculation_t *spec;
2912 	dtrace_speculation_state_t current, new;
2913 	dtrace_buffer_t *buf;
2914 
2915 	if (which == 0)
2916 		return (NULL);
2917 
2918 	if (which > state->dts_nspeculations) {
2919 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2920 		return (NULL);
2921 	}
2922 
2923 	spec = &state->dts_speculations[which - 1];
2924 	buf = &spec->dtsp_buffer[cpuid];
2925 
2926 	do {
2927 		current = spec->dtsp_state;
2928 
2929 		switch (current) {
2930 		case DTRACESPEC_INACTIVE:
2931 		case DTRACESPEC_COMMITTINGMANY:
2932 		case DTRACESPEC_DISCARDING:
2933 			return (NULL);
2934 
2935 		case DTRACESPEC_COMMITTING:
2936 			ASSERT(buf->dtb_offset == 0);
2937 			return (NULL);
2938 
2939 		case DTRACESPEC_ACTIVEONE:
2940 			/*
2941 			 * This speculation is currently active on one CPU.
2942 			 * Check the offset in the buffer; if it's non-zero,
2943 			 * that CPU must be us (and we leave the state alone).
2944 			 * If it's zero, assume that we're starting on a new
2945 			 * CPU -- and change the state to indicate that the
2946 			 * speculation is active on more than one CPU.
2947 			 */
2948 			if (buf->dtb_offset != 0)
2949 				return (buf);
2950 
2951 			new = DTRACESPEC_ACTIVEMANY;
2952 			break;
2953 
2954 		case DTRACESPEC_ACTIVEMANY:
2955 			return (buf);
2956 
2957 		case DTRACESPEC_ACTIVE:
2958 			new = DTRACESPEC_ACTIVEONE;
2959 			break;
2960 
2961 		default:
2962 			ASSERT(0);
2963 		}
2964 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2965 	    current, new) != current);
2966 
2967 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2968 	return (buf);
2969 }
2970 
2971 /*
2972  * Return a string.  In the event that the user lacks the privilege to access
2973  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2974  * don't fail access checking.
2975  *
2976  * dtrace_dif_variable() uses this routine as a helper for various
2977  * builtin values such as 'execname' and 'probefunc.'
2978  */
2979 uintptr_t
2980 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2981     dtrace_mstate_t *mstate)
2982 {
2983 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2984 	uintptr_t ret;
2985 	size_t strsz;
2986 
2987 	/*
2988 	 * The easy case: this probe is allowed to read all of memory, so
2989 	 * we can just return this as a vanilla pointer.
2990 	 */
2991 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2992 		return (addr);
2993 
2994 	/*
2995 	 * This is the tougher case: we copy the string in question from
2996 	 * kernel memory into scratch memory and return it that way: this
2997 	 * ensures that we won't trip up when access checking tests the
2998 	 * BYREF return value.
2999 	 */
3000 	strsz = dtrace_strlen((char *)addr, size) + 1;
3001 
3002 	if (mstate->dtms_scratch_ptr + strsz >
3003 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3004 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3005 		return (NULL);
3006 	}
3007 
3008 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3009 	    strsz);
3010 	ret = mstate->dtms_scratch_ptr;
3011 	mstate->dtms_scratch_ptr += strsz;
3012 	return (ret);
3013 }
3014 
3015 /*
3016  * This function implements the DIF emulator's variable lookups.  The emulator
3017  * passes a reserved variable identifier and optional built-in array index.
3018  */
3019 static uint64_t
3020 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3021     uint64_t ndx)
3022 {
3023 	/*
3024 	 * If we're accessing one of the uncached arguments, we'll turn this
3025 	 * into a reference in the args array.
3026 	 */
3027 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3028 		ndx = v - DIF_VAR_ARG0;
3029 		v = DIF_VAR_ARGS;
3030 	}
3031 
3032 	switch (v) {
3033 	case DIF_VAR_ARGS:
3034 		if (!(mstate->dtms_access & DTRACE_ACCESS_ARGS)) {
3035 			cpu_core[CPU->cpu_id].cpuc_dtrace_flags |=
3036 			    CPU_DTRACE_KPRIV;
3037 			return (0);
3038 		}
3039 
3040 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3041 		if (ndx >= sizeof (mstate->dtms_arg) /
3042 		    sizeof (mstate->dtms_arg[0])) {
3043 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3044 			dtrace_provider_t *pv;
3045 			uint64_t val;
3046 
3047 			pv = mstate->dtms_probe->dtpr_provider;
3048 			if (pv->dtpv_pops.dtps_getargval != NULL)
3049 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3050 				    mstate->dtms_probe->dtpr_id,
3051 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
3052 			else
3053 				val = dtrace_getarg(ndx, aframes);
3054 
3055 			/*
3056 			 * This is regrettably required to keep the compiler
3057 			 * from tail-optimizing the call to dtrace_getarg().
3058 			 * The condition always evaluates to true, but the
3059 			 * compiler has no way of figuring that out a priori.
3060 			 * (None of this would be necessary if the compiler
3061 			 * could be relied upon to _always_ tail-optimize
3062 			 * the call to dtrace_getarg() -- but it can't.)
3063 			 */
3064 			if (mstate->dtms_probe != NULL)
3065 				return (val);
3066 
3067 			ASSERT(0);
3068 		}
3069 
3070 		return (mstate->dtms_arg[ndx]);
3071 
3072 	case DIF_VAR_UREGS: {
3073 		klwp_t *lwp;
3074 
3075 		if (!dtrace_priv_proc(state, mstate))
3076 			return (0);
3077 
3078 		if ((lwp = curthread->t_lwp) == NULL) {
3079 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3080 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
3081 			return (0);
3082 		}
3083 
3084 		return (dtrace_getreg(lwp->lwp_regs, ndx));
3085 	}
3086 
3087 	case DIF_VAR_VMREGS: {
3088 		uint64_t rval;
3089 
3090 		if (!dtrace_priv_kernel(state))
3091 			return (0);
3092 
3093 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3094 
3095 		rval = dtrace_getvmreg(ndx,
3096 		    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags);
3097 
3098 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3099 
3100 		return (rval);
3101 	}
3102 
3103 	case DIF_VAR_CURTHREAD:
3104 		if (!dtrace_priv_proc(state, mstate))
3105 			return (0);
3106 		return ((uint64_t)(uintptr_t)curthread);
3107 
3108 	case DIF_VAR_TIMESTAMP:
3109 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3110 			mstate->dtms_timestamp = dtrace_gethrtime();
3111 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3112 		}
3113 		return (mstate->dtms_timestamp);
3114 
3115 	case DIF_VAR_VTIMESTAMP:
3116 		ASSERT(dtrace_vtime_references != 0);
3117 		return (curthread->t_dtrace_vtime);
3118 
3119 	case DIF_VAR_WALLTIMESTAMP:
3120 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3121 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3122 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3123 		}
3124 		return (mstate->dtms_walltimestamp);
3125 
3126 	case DIF_VAR_IPL:
3127 		if (!dtrace_priv_kernel(state))
3128 			return (0);
3129 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3130 			mstate->dtms_ipl = dtrace_getipl();
3131 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3132 		}
3133 		return (mstate->dtms_ipl);
3134 
3135 	case DIF_VAR_EPID:
3136 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3137 		return (mstate->dtms_epid);
3138 
3139 	case DIF_VAR_ID:
3140 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3141 		return (mstate->dtms_probe->dtpr_id);
3142 
3143 	case DIF_VAR_STACKDEPTH:
3144 		if (!dtrace_priv_kernel(state))
3145 			return (0);
3146 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3147 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3148 
3149 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3150 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3151 		}
3152 		return (mstate->dtms_stackdepth);
3153 
3154 	case DIF_VAR_USTACKDEPTH:
3155 		if (!dtrace_priv_proc(state, mstate))
3156 			return (0);
3157 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3158 			/*
3159 			 * See comment in DIF_VAR_PID.
3160 			 */
3161 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3162 			    CPU_ON_INTR(CPU)) {
3163 				mstate->dtms_ustackdepth = 0;
3164 			} else {
3165 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3166 				mstate->dtms_ustackdepth =
3167 				    dtrace_getustackdepth();
3168 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3169 			}
3170 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3171 		}
3172 		return (mstate->dtms_ustackdepth);
3173 
3174 	case DIF_VAR_CALLER:
3175 		if (!dtrace_priv_kernel(state))
3176 			return (0);
3177 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3178 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3179 
3180 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3181 				/*
3182 				 * If this is an unanchored probe, we are
3183 				 * required to go through the slow path:
3184 				 * dtrace_caller() only guarantees correct
3185 				 * results for anchored probes.
3186 				 */
3187 				pc_t caller[2];
3188 
3189 				dtrace_getpcstack(caller, 2, aframes,
3190 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3191 				mstate->dtms_caller = caller[1];
3192 			} else if ((mstate->dtms_caller =
3193 			    dtrace_caller(aframes)) == -1) {
3194 				/*
3195 				 * We have failed to do this the quick way;
3196 				 * we must resort to the slower approach of
3197 				 * calling dtrace_getpcstack().
3198 				 */
3199 				pc_t caller;
3200 
3201 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3202 				mstate->dtms_caller = caller;
3203 			}
3204 
3205 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3206 		}
3207 		return (mstate->dtms_caller);
3208 
3209 	case DIF_VAR_UCALLER:
3210 		if (!dtrace_priv_proc(state, mstate))
3211 			return (0);
3212 
3213 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3214 			uint64_t ustack[3];
3215 
3216 			/*
3217 			 * dtrace_getupcstack() fills in the first uint64_t
3218 			 * with the current PID.  The second uint64_t will
3219 			 * be the program counter at user-level.  The third
3220 			 * uint64_t will contain the caller, which is what
3221 			 * we're after.
3222 			 */
3223 			ustack[2] = NULL;
3224 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3225 			dtrace_getupcstack(ustack, 3);
3226 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3227 			mstate->dtms_ucaller = ustack[2];
3228 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3229 		}
3230 
3231 		return (mstate->dtms_ucaller);
3232 
3233 	case DIF_VAR_PROBEPROV:
3234 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3235 		return (dtrace_dif_varstr(
3236 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3237 		    state, mstate));
3238 
3239 	case DIF_VAR_PROBEMOD:
3240 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3241 		return (dtrace_dif_varstr(
3242 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3243 		    state, mstate));
3244 
3245 	case DIF_VAR_PROBEFUNC:
3246 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3247 		return (dtrace_dif_varstr(
3248 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3249 		    state, mstate));
3250 
3251 	case DIF_VAR_PROBENAME:
3252 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3253 		return (dtrace_dif_varstr(
3254 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3255 		    state, mstate));
3256 
3257 	case DIF_VAR_PID:
3258 		if (!dtrace_priv_proc(state, mstate))
3259 			return (0);
3260 
3261 		/*
3262 		 * Note that we are assuming that an unanchored probe is
3263 		 * always due to a high-level interrupt.  (And we're assuming
3264 		 * that there is only a single high level interrupt.)
3265 		 */
3266 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3267 			return (pid0.pid_id);
3268 
3269 		/*
3270 		 * It is always safe to dereference one's own t_procp pointer:
3271 		 * it always points to a valid, allocated proc structure.
3272 		 * Further, it is always safe to dereference the p_pidp member
3273 		 * of one's own proc structure.  (These are truisms becuase
3274 		 * threads and processes don't clean up their own state --
3275 		 * they leave that task to whomever reaps them.)
3276 		 */
3277 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3278 
3279 	case DIF_VAR_PPID:
3280 		if (!dtrace_priv_proc(state, mstate))
3281 			return (0);
3282 
3283 		/*
3284 		 * See comment in DIF_VAR_PID.
3285 		 */
3286 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3287 			return (pid0.pid_id);
3288 
3289 		/*
3290 		 * It is always safe to dereference one's own t_procp pointer:
3291 		 * it always points to a valid, allocated proc structure.
3292 		 * (This is true because threads don't clean up their own
3293 		 * state -- they leave that task to whomever reaps them.)
3294 		 */
3295 		return ((uint64_t)curthread->t_procp->p_ppid);
3296 
3297 	case DIF_VAR_TID:
3298 		/*
3299 		 * See comment in DIF_VAR_PID.
3300 		 */
3301 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3302 			return (0);
3303 
3304 		return ((uint64_t)curthread->t_tid);
3305 
3306 	case DIF_VAR_EXECNAME:
3307 		if (!dtrace_priv_proc(state, mstate))
3308 			return (0);
3309 
3310 		/*
3311 		 * See comment in DIF_VAR_PID.
3312 		 */
3313 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3314 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3315 
3316 		/*
3317 		 * It is always safe to dereference one's own t_procp pointer:
3318 		 * it always points to a valid, allocated proc structure.
3319 		 * (This is true because threads don't clean up their own
3320 		 * state -- they leave that task to whomever reaps them.)
3321 		 */
3322 		return (dtrace_dif_varstr(
3323 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3324 		    state, mstate));
3325 
3326 	case DIF_VAR_ZONENAME:
3327 		if (!dtrace_priv_proc(state, mstate))
3328 			return (0);
3329 
3330 		/*
3331 		 * See comment in DIF_VAR_PID.
3332 		 */
3333 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3334 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3335 
3336 		/*
3337 		 * It is always safe to dereference one's own t_procp pointer:
3338 		 * it always points to a valid, allocated proc structure.
3339 		 * (This is true because threads don't clean up their own
3340 		 * state -- they leave that task to whomever reaps them.)
3341 		 */
3342 		return (dtrace_dif_varstr(
3343 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3344 		    state, mstate));
3345 
3346 	case DIF_VAR_UID:
3347 		if (!dtrace_priv_proc(state, mstate))
3348 			return (0);
3349 
3350 		/*
3351 		 * See comment in DIF_VAR_PID.
3352 		 */
3353 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3354 			return ((uint64_t)p0.p_cred->cr_uid);
3355 
3356 		/*
3357 		 * It is always safe to dereference one's own t_procp pointer:
3358 		 * it always points to a valid, allocated proc structure.
3359 		 * (This is true because threads don't clean up their own
3360 		 * state -- they leave that task to whomever reaps them.)
3361 		 *
3362 		 * Additionally, it is safe to dereference one's own process
3363 		 * credential, since this is never NULL after process birth.
3364 		 */
3365 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3366 
3367 	case DIF_VAR_GID:
3368 		if (!dtrace_priv_proc(state, mstate))
3369 			return (0);
3370 
3371 		/*
3372 		 * See comment in DIF_VAR_PID.
3373 		 */
3374 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3375 			return ((uint64_t)p0.p_cred->cr_gid);
3376 
3377 		/*
3378 		 * It is always safe to dereference one's own t_procp pointer:
3379 		 * it always points to a valid, allocated proc structure.
3380 		 * (This is true because threads don't clean up their own
3381 		 * state -- they leave that task to whomever reaps them.)
3382 		 *
3383 		 * Additionally, it is safe to dereference one's own process
3384 		 * credential, since this is never NULL after process birth.
3385 		 */
3386 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3387 
3388 	case DIF_VAR_ERRNO: {
3389 		klwp_t *lwp;
3390 		if (!dtrace_priv_proc(state, mstate))
3391 			return (0);
3392 
3393 		/*
3394 		 * See comment in DIF_VAR_PID.
3395 		 */
3396 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3397 			return (0);
3398 
3399 		/*
3400 		 * It is always safe to dereference one's own t_lwp pointer in
3401 		 * the event that this pointer is non-NULL.  (This is true
3402 		 * because threads and lwps don't clean up their own state --
3403 		 * they leave that task to whomever reaps them.)
3404 		 */
3405 		if ((lwp = curthread->t_lwp) == NULL)
3406 			return (0);
3407 
3408 		return ((uint64_t)lwp->lwp_errno);
3409 	}
3410 	default:
3411 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3412 		return (0);
3413 	}
3414 }
3415 
3416 
3417 typedef enum dtrace_json_state {
3418 	DTRACE_JSON_REST = 1,
3419 	DTRACE_JSON_OBJECT,
3420 	DTRACE_JSON_STRING,
3421 	DTRACE_JSON_STRING_ESCAPE,
3422 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3423 	DTRACE_JSON_COLON,
3424 	DTRACE_JSON_COMMA,
3425 	DTRACE_JSON_VALUE,
3426 	DTRACE_JSON_IDENTIFIER,
3427 	DTRACE_JSON_NUMBER,
3428 	DTRACE_JSON_NUMBER_FRAC,
3429 	DTRACE_JSON_NUMBER_EXP,
3430 	DTRACE_JSON_COLLECT_OBJECT
3431 } dtrace_json_state_t;
3432 
3433 /*
3434  * This function possesses just enough knowledge about JSON to extract a single
3435  * value from a JSON string and store it in the scratch buffer.  It is able
3436  * to extract nested object values, and members of arrays by index.
3437  *
3438  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3439  * be looked up as we descend into the object tree.  e.g.
3440  *
3441  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3442  *       with nelems = 5.
3443  *
3444  * The run time of this function must be bounded above by strsize to limit the
3445  * amount of work done in probe context.  As such, it is implemented as a
3446  * simple state machine, reading one character at a time using safe loads
3447  * until we find the requested element, hit a parsing error or run off the
3448  * end of the object or string.
3449  *
3450  * As there is no way for a subroutine to return an error without interrupting
3451  * clause execution, we simply return NULL in the event of a missing key or any
3452  * other error condition.  Each NULL return in this function is commented with
3453  * the error condition it represents -- parsing or otherwise.
3454  *
3455  * The set of states for the state machine closely matches the JSON
3456  * specification (http://json.org/).  Briefly:
3457  *
3458  *   DTRACE_JSON_REST:
3459  *     Skip whitespace until we find either a top-level Object, moving
3460  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3461  *
3462  *   DTRACE_JSON_OBJECT:
3463  *     Locate the next key String in an Object.  Sets a flag to denote
3464  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3465  *
3466  *   DTRACE_JSON_COLON:
3467  *     Skip whitespace until we find the colon that separates key Strings
3468  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3469  *
3470  *   DTRACE_JSON_VALUE:
3471  *     Detects the type of the next value (String, Number, Identifier, Object
3472  *     or Array) and routes to the states that process that type.  Here we also
3473  *     deal with the element selector list if we are requested to traverse down
3474  *     into the object tree.
3475  *
3476  *   DTRACE_JSON_COMMA:
3477  *     Skip whitespace until we find the comma that separates key-value pairs
3478  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3479  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3480  *     states return to this state at the end of their value, unless otherwise
3481  *     noted.
3482  *
3483  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3484  *     Processes a Number literal from the JSON, including any exponent
3485  *     component that may be present.  Numbers are returned as strings, which
3486  *     may be passed to strtoll() if an integer is required.
3487  *
3488  *   DTRACE_JSON_IDENTIFIER:
3489  *     Processes a "true", "false" or "null" literal in the JSON.
3490  *
3491  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3492  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3493  *     Processes a String literal from the JSON, whether the String denotes
3494  *     a key, a value or part of a larger Object.  Handles all escape sequences
3495  *     present in the specification, including four-digit unicode characters,
3496  *     but merely includes the escape sequence without converting it to the
3497  *     actual escaped character.  If the String is flagged as a key, we
3498  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3499  *
3500  *   DTRACE_JSON_COLLECT_OBJECT:
3501  *     This state collects an entire Object (or Array), correctly handling
3502  *     embedded strings.  If the full element selector list matches this nested
3503  *     object, we return the Object in full as a string.  If not, we use this
3504  *     state to skip to the next value at this level and continue processing.
3505  *
3506  * NOTE: This function uses various macros from strtolctype.h to manipulate
3507  * digit values, etc -- these have all been checked to ensure they make
3508  * no additional function calls.
3509  */
3510 static char *
3511 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3512     char *dest)
3513 {
3514 	dtrace_json_state_t state = DTRACE_JSON_REST;
3515 	int64_t array_elem = INT64_MIN;
3516 	int64_t array_pos = 0;
3517 	uint8_t escape_unicount = 0;
3518 	boolean_t string_is_key = B_FALSE;
3519 	boolean_t collect_object = B_FALSE;
3520 	boolean_t found_key = B_FALSE;
3521 	boolean_t in_array = B_FALSE;
3522 	uint32_t braces = 0, brackets = 0;
3523 	char *elem = elemlist;
3524 	char *dd = dest;
3525 	uintptr_t cur;
3526 
3527 	for (cur = json; cur < json + size; cur++) {
3528 		char cc = dtrace_load8(cur);
3529 		if (cc == '\0')
3530 			return (NULL);
3531 
3532 		switch (state) {
3533 		case DTRACE_JSON_REST:
3534 			if (isspace(cc))
3535 				break;
3536 
3537 			if (cc == '{') {
3538 				state = DTRACE_JSON_OBJECT;
3539 				break;
3540 			}
3541 
3542 			if (cc == '[') {
3543 				in_array = B_TRUE;
3544 				array_pos = 0;
3545 				array_elem = dtrace_strtoll(elem, 10, size);
3546 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3547 				state = DTRACE_JSON_VALUE;
3548 				break;
3549 			}
3550 
3551 			/*
3552 			 * ERROR: expected to find a top-level object or array.
3553 			 */
3554 			return (NULL);
3555 		case DTRACE_JSON_OBJECT:
3556 			if (isspace(cc))
3557 				break;
3558 
3559 			if (cc == '"') {
3560 				state = DTRACE_JSON_STRING;
3561 				string_is_key = B_TRUE;
3562 				break;
3563 			}
3564 
3565 			/*
3566 			 * ERROR: either the object did not start with a key
3567 			 * string, or we've run off the end of the object
3568 			 * without finding the requested key.
3569 			 */
3570 			return (NULL);
3571 		case DTRACE_JSON_STRING:
3572 			if (cc == '\\') {
3573 				*dd++ = '\\';
3574 				state = DTRACE_JSON_STRING_ESCAPE;
3575 				break;
3576 			}
3577 
3578 			if (cc == '"') {
3579 				if (collect_object) {
3580 					/*
3581 					 * We don't reset the dest here, as
3582 					 * the string is part of a larger
3583 					 * object being collected.
3584 					 */
3585 					*dd++ = cc;
3586 					collect_object = B_FALSE;
3587 					state = DTRACE_JSON_COLLECT_OBJECT;
3588 					break;
3589 				}
3590 				*dd = '\0';
3591 				dd = dest; /* reset string buffer */
3592 				if (string_is_key) {
3593 					if (dtrace_strncmp(dest, elem,
3594 					    size) == 0)
3595 						found_key = B_TRUE;
3596 				} else if (found_key) {
3597 					if (nelems > 1) {
3598 						/*
3599 						 * We expected an object, not
3600 						 * this string.
3601 						 */
3602 						return (NULL);
3603 					}
3604 					return (dest);
3605 				}
3606 				state = string_is_key ? DTRACE_JSON_COLON :
3607 				    DTRACE_JSON_COMMA;
3608 				string_is_key = B_FALSE;
3609 				break;
3610 			}
3611 
3612 			*dd++ = cc;
3613 			break;
3614 		case DTRACE_JSON_STRING_ESCAPE:
3615 			*dd++ = cc;
3616 			if (cc == 'u') {
3617 				escape_unicount = 0;
3618 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3619 			} else {
3620 				state = DTRACE_JSON_STRING;
3621 			}
3622 			break;
3623 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3624 			if (!isxdigit(cc)) {
3625 				/*
3626 				 * ERROR: invalid unicode escape, expected
3627 				 * four valid hexidecimal digits.
3628 				 */
3629 				return (NULL);
3630 			}
3631 
3632 			*dd++ = cc;
3633 			if (++escape_unicount == 4)
3634 				state = DTRACE_JSON_STRING;
3635 			break;
3636 		case DTRACE_JSON_COLON:
3637 			if (isspace(cc))
3638 				break;
3639 
3640 			if (cc == ':') {
3641 				state = DTRACE_JSON_VALUE;
3642 				break;
3643 			}
3644 
3645 			/*
3646 			 * ERROR: expected a colon.
3647 			 */
3648 			return (NULL);
3649 		case DTRACE_JSON_COMMA:
3650 			if (isspace(cc))
3651 				break;
3652 
3653 			if (cc == ',') {
3654 				if (in_array) {
3655 					state = DTRACE_JSON_VALUE;
3656 					if (++array_pos == array_elem)
3657 						found_key = B_TRUE;
3658 				} else {
3659 					state = DTRACE_JSON_OBJECT;
3660 				}
3661 				break;
3662 			}
3663 
3664 			/*
3665 			 * ERROR: either we hit an unexpected character, or
3666 			 * we reached the end of the object or array without
3667 			 * finding the requested key.
3668 			 */
3669 			return (NULL);
3670 		case DTRACE_JSON_IDENTIFIER:
3671 			if (islower(cc)) {
3672 				*dd++ = cc;
3673 				break;
3674 			}
3675 
3676 			*dd = '\0';
3677 			dd = dest; /* reset string buffer */
3678 
3679 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
3680 			    dtrace_strncmp(dest, "false", 6) == 0 ||
3681 			    dtrace_strncmp(dest, "null", 5) == 0) {
3682 				if (found_key) {
3683 					if (nelems > 1) {
3684 						/*
3685 						 * ERROR: We expected an object,
3686 						 * not this identifier.
3687 						 */
3688 						return (NULL);
3689 					}
3690 					return (dest);
3691 				} else {
3692 					cur--;
3693 					state = DTRACE_JSON_COMMA;
3694 					break;
3695 				}
3696 			}
3697 
3698 			/*
3699 			 * ERROR: we did not recognise the identifier as one
3700 			 * of those in the JSON specification.
3701 			 */
3702 			return (NULL);
3703 		case DTRACE_JSON_NUMBER:
3704 			if (cc == '.') {
3705 				*dd++ = cc;
3706 				state = DTRACE_JSON_NUMBER_FRAC;
3707 				break;
3708 			}
3709 
3710 			if (cc == 'x' || cc == 'X') {
3711 				/*
3712 				 * ERROR: specification explicitly excludes
3713 				 * hexidecimal or octal numbers.
3714 				 */
3715 				return (NULL);
3716 			}
3717 
3718 			/* FALLTHRU */
3719 		case DTRACE_JSON_NUMBER_FRAC:
3720 			if (cc == 'e' || cc == 'E') {
3721 				*dd++ = cc;
3722 				state = DTRACE_JSON_NUMBER_EXP;
3723 				break;
3724 			}
3725 
3726 			if (cc == '+' || cc == '-') {
3727 				/*
3728 				 * ERROR: expect sign as part of exponent only.
3729 				 */
3730 				return (NULL);
3731 			}
3732 			/* FALLTHRU */
3733 		case DTRACE_JSON_NUMBER_EXP:
3734 			if (isdigit(cc) || cc == '+' || cc == '-') {
3735 				*dd++ = cc;
3736 				break;
3737 			}
3738 
3739 			*dd = '\0';
3740 			dd = dest; /* reset string buffer */
3741 			if (found_key) {
3742 				if (nelems > 1) {
3743 					/*
3744 					 * ERROR: We expected an object, not
3745 					 * this number.
3746 					 */
3747 					return (NULL);
3748 				}
3749 				return (dest);
3750 			}
3751 
3752 			cur--;
3753 			state = DTRACE_JSON_COMMA;
3754 			break;
3755 		case DTRACE_JSON_VALUE:
3756 			if (isspace(cc))
3757 				break;
3758 
3759 			if (cc == '{' || cc == '[') {
3760 				if (nelems > 1 && found_key) {
3761 					in_array = cc == '[' ? B_TRUE : B_FALSE;
3762 					/*
3763 					 * If our element selector directs us
3764 					 * to descend into this nested object,
3765 					 * then move to the next selector
3766 					 * element in the list and restart the
3767 					 * state machine.
3768 					 */
3769 					while (*elem != '\0')
3770 						elem++;
3771 					elem++; /* skip the inter-element NUL */
3772 					nelems--;
3773 					dd = dest;
3774 					if (in_array) {
3775 						state = DTRACE_JSON_VALUE;
3776 						array_pos = 0;
3777 						array_elem = dtrace_strtoll(
3778 						    elem, 10, size);
3779 						found_key = array_elem == 0 ?
3780 						    B_TRUE : B_FALSE;
3781 					} else {
3782 						found_key = B_FALSE;
3783 						state = DTRACE_JSON_OBJECT;
3784 					}
3785 					break;
3786 				}
3787 
3788 				/*
3789 				 * Otherwise, we wish to either skip this
3790 				 * nested object or return it in full.
3791 				 */
3792 				if (cc == '[')
3793 					brackets = 1;
3794 				else
3795 					braces = 1;
3796 				*dd++ = cc;
3797 				state = DTRACE_JSON_COLLECT_OBJECT;
3798 				break;
3799 			}
3800 
3801 			if (cc == '"') {
3802 				state = DTRACE_JSON_STRING;
3803 				break;
3804 			}
3805 
3806 			if (islower(cc)) {
3807 				/*
3808 				 * Here we deal with true, false and null.
3809 				 */
3810 				*dd++ = cc;
3811 				state = DTRACE_JSON_IDENTIFIER;
3812 				break;
3813 			}
3814 
3815 			if (cc == '-' || isdigit(cc)) {
3816 				*dd++ = cc;
3817 				state = DTRACE_JSON_NUMBER;
3818 				break;
3819 			}
3820 
3821 			/*
3822 			 * ERROR: unexpected character at start of value.
3823 			 */
3824 			return (NULL);
3825 		case DTRACE_JSON_COLLECT_OBJECT:
3826 			if (cc == '\0')
3827 				/*
3828 				 * ERROR: unexpected end of input.
3829 				 */
3830 				return (NULL);
3831 
3832 			*dd++ = cc;
3833 			if (cc == '"') {
3834 				collect_object = B_TRUE;
3835 				state = DTRACE_JSON_STRING;
3836 				break;
3837 			}
3838 
3839 			if (cc == ']') {
3840 				if (brackets-- == 0) {
3841 					/*
3842 					 * ERROR: unbalanced brackets.
3843 					 */
3844 					return (NULL);
3845 				}
3846 			} else if (cc == '}') {
3847 				if (braces-- == 0) {
3848 					/*
3849 					 * ERROR: unbalanced braces.
3850 					 */
3851 					return (NULL);
3852 				}
3853 			} else if (cc == '{') {
3854 				braces++;
3855 			} else if (cc == '[') {
3856 				brackets++;
3857 			}
3858 
3859 			if (brackets == 0 && braces == 0) {
3860 				if (found_key) {
3861 					*dd = '\0';
3862 					return (dest);
3863 				}
3864 				dd = dest; /* reset string buffer */
3865 				state = DTRACE_JSON_COMMA;
3866 			}
3867 			break;
3868 		}
3869 	}
3870 	return (NULL);
3871 }
3872 
3873 /*
3874  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3875  * Notice that we don't bother validating the proper number of arguments or
3876  * their types in the tuple stack.  This isn't needed because all argument
3877  * interpretation is safe because of our load safety -- the worst that can
3878  * happen is that a bogus program can obtain bogus results.
3879  */
3880 static void
3881 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3882     dtrace_key_t *tupregs, int nargs,
3883     dtrace_mstate_t *mstate, dtrace_state_t *state)
3884 {
3885 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3886 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3887 	dtrace_vstate_t *vstate = &state->dts_vstate;
3888 
3889 	union {
3890 		mutex_impl_t mi;
3891 		uint64_t mx;
3892 	} m;
3893 
3894 	union {
3895 		krwlock_t ri;
3896 		uintptr_t rw;
3897 	} r;
3898 
3899 	switch (subr) {
3900 	case DIF_SUBR_RAND:
3901 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3902 		break;
3903 
3904 	case DIF_SUBR_MUTEX_OWNED:
3905 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3906 		    mstate, vstate)) {
3907 			regs[rd] = NULL;
3908 			break;
3909 		}
3910 
3911 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3912 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3913 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3914 		else
3915 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3916 		break;
3917 
3918 	case DIF_SUBR_MUTEX_OWNER:
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 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3928 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3929 		else
3930 			regs[rd] = 0;
3931 		break;
3932 
3933 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3934 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3935 		    mstate, vstate)) {
3936 			regs[rd] = NULL;
3937 			break;
3938 		}
3939 
3940 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3941 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3942 		break;
3943 
3944 	case DIF_SUBR_MUTEX_TYPE_SPIN:
3945 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3946 		    mstate, vstate)) {
3947 			regs[rd] = NULL;
3948 			break;
3949 		}
3950 
3951 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3952 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3953 		break;
3954 
3955 	case DIF_SUBR_RW_READ_HELD: {
3956 		uintptr_t tmp;
3957 
3958 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3959 		    mstate, vstate)) {
3960 			regs[rd] = NULL;
3961 			break;
3962 		}
3963 
3964 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3965 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3966 		break;
3967 	}
3968 
3969 	case DIF_SUBR_RW_WRITE_HELD:
3970 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3971 		    mstate, vstate)) {
3972 			regs[rd] = NULL;
3973 			break;
3974 		}
3975 
3976 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3977 		regs[rd] = _RW_WRITE_HELD(&r.ri);
3978 		break;
3979 
3980 	case DIF_SUBR_RW_ISWRITER:
3981 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3982 		    mstate, vstate)) {
3983 			regs[rd] = NULL;
3984 			break;
3985 		}
3986 
3987 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3988 		regs[rd] = _RW_ISWRITER(&r.ri);
3989 		break;
3990 
3991 	case DIF_SUBR_BCOPY: {
3992 		/*
3993 		 * We need to be sure that the destination is in the scratch
3994 		 * region -- no other region is allowed.
3995 		 */
3996 		uintptr_t src = tupregs[0].dttk_value;
3997 		uintptr_t dest = tupregs[1].dttk_value;
3998 		size_t size = tupregs[2].dttk_value;
3999 
4000 		if (!dtrace_inscratch(dest, size, mstate)) {
4001 			*flags |= CPU_DTRACE_BADADDR;
4002 			*illval = regs[rd];
4003 			break;
4004 		}
4005 
4006 		if (!dtrace_canload(src, size, mstate, vstate)) {
4007 			regs[rd] = NULL;
4008 			break;
4009 		}
4010 
4011 		dtrace_bcopy((void *)src, (void *)dest, size);
4012 		break;
4013 	}
4014 
4015 	case DIF_SUBR_ALLOCA:
4016 	case DIF_SUBR_COPYIN: {
4017 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4018 		uint64_t size =
4019 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4020 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4021 
4022 		/*
4023 		 * This action doesn't require any credential checks since
4024 		 * probes will not activate in user contexts to which the
4025 		 * enabling user does not have permissions.
4026 		 */
4027 
4028 		/*
4029 		 * Rounding up the user allocation size could have overflowed
4030 		 * a large, bogus allocation (like -1ULL) to 0.
4031 		 */
4032 		if (scratch_size < size ||
4033 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4034 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4035 			regs[rd] = NULL;
4036 			break;
4037 		}
4038 
4039 		if (subr == DIF_SUBR_COPYIN) {
4040 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4041 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4042 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4043 		}
4044 
4045 		mstate->dtms_scratch_ptr += scratch_size;
4046 		regs[rd] = dest;
4047 		break;
4048 	}
4049 
4050 	case DIF_SUBR_COPYINTO: {
4051 		uint64_t size = tupregs[1].dttk_value;
4052 		uintptr_t dest = tupregs[2].dttk_value;
4053 
4054 		/*
4055 		 * This action doesn't require any credential checks since
4056 		 * probes will not activate in user contexts to which the
4057 		 * enabling user does not have permissions.
4058 		 */
4059 		if (!dtrace_inscratch(dest, size, mstate)) {
4060 			*flags |= CPU_DTRACE_BADADDR;
4061 			*illval = regs[rd];
4062 			break;
4063 		}
4064 
4065 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4066 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4067 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4068 		break;
4069 	}
4070 
4071 	case DIF_SUBR_COPYINSTR: {
4072 		uintptr_t dest = mstate->dtms_scratch_ptr;
4073 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4074 
4075 		if (nargs > 1 && tupregs[1].dttk_value < size)
4076 			size = tupregs[1].dttk_value + 1;
4077 
4078 		/*
4079 		 * This action doesn't require any credential checks since
4080 		 * probes will not activate in user contexts to which the
4081 		 * enabling user does not have permissions.
4082 		 */
4083 		if (!DTRACE_INSCRATCH(mstate, size)) {
4084 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4085 			regs[rd] = NULL;
4086 			break;
4087 		}
4088 
4089 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4090 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4091 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4092 
4093 		((char *)dest)[size - 1] = '\0';
4094 		mstate->dtms_scratch_ptr += size;
4095 		regs[rd] = dest;
4096 		break;
4097 	}
4098 
4099 	case DIF_SUBR_MSGSIZE:
4100 	case DIF_SUBR_MSGDSIZE: {
4101 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
4102 		uintptr_t wptr, rptr;
4103 		size_t count = 0;
4104 		int cont = 0;
4105 
4106 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4107 
4108 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4109 			    vstate)) {
4110 				regs[rd] = NULL;
4111 				break;
4112 			}
4113 
4114 			wptr = dtrace_loadptr(baddr +
4115 			    offsetof(mblk_t, b_wptr));
4116 
4117 			rptr = dtrace_loadptr(baddr +
4118 			    offsetof(mblk_t, b_rptr));
4119 
4120 			if (wptr < rptr) {
4121 				*flags |= CPU_DTRACE_BADADDR;
4122 				*illval = tupregs[0].dttk_value;
4123 				break;
4124 			}
4125 
4126 			daddr = dtrace_loadptr(baddr +
4127 			    offsetof(mblk_t, b_datap));
4128 
4129 			baddr = dtrace_loadptr(baddr +
4130 			    offsetof(mblk_t, b_cont));
4131 
4132 			/*
4133 			 * We want to prevent against denial-of-service here,
4134 			 * so we're only going to search the list for
4135 			 * dtrace_msgdsize_max mblks.
4136 			 */
4137 			if (cont++ > dtrace_msgdsize_max) {
4138 				*flags |= CPU_DTRACE_ILLOP;
4139 				break;
4140 			}
4141 
4142 			if (subr == DIF_SUBR_MSGDSIZE) {
4143 				if (dtrace_load8(daddr +
4144 				    offsetof(dblk_t, db_type)) != M_DATA)
4145 					continue;
4146 			}
4147 
4148 			count += wptr - rptr;
4149 		}
4150 
4151 		if (!(*flags & CPU_DTRACE_FAULT))
4152 			regs[rd] = count;
4153 
4154 		break;
4155 	}
4156 
4157 	case DIF_SUBR_PROGENYOF: {
4158 		pid_t pid = tupregs[0].dttk_value;
4159 		proc_t *p;
4160 		int rval = 0;
4161 
4162 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4163 
4164 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4165 			if (p->p_pidp->pid_id == pid) {
4166 				rval = 1;
4167 				break;
4168 			}
4169 		}
4170 
4171 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4172 
4173 		regs[rd] = rval;
4174 		break;
4175 	}
4176 
4177 	case DIF_SUBR_SPECULATION:
4178 		regs[rd] = dtrace_speculation(state);
4179 		break;
4180 
4181 	case DIF_SUBR_COPYOUT: {
4182 		uintptr_t kaddr = tupregs[0].dttk_value;
4183 		uintptr_t uaddr = tupregs[1].dttk_value;
4184 		uint64_t size = tupregs[2].dttk_value;
4185 
4186 		if (!dtrace_destructive_disallow &&
4187 		    dtrace_priv_proc_control(state, mstate) &&
4188 		    !dtrace_istoxic(kaddr, size) &&
4189 		    dtrace_canload(kaddr, size, mstate, vstate)) {
4190 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4191 			dtrace_copyout(kaddr, uaddr, size, flags);
4192 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4193 		}
4194 		break;
4195 	}
4196 
4197 	case DIF_SUBR_COPYOUTSTR: {
4198 		uintptr_t kaddr = tupregs[0].dttk_value;
4199 		uintptr_t uaddr = tupregs[1].dttk_value;
4200 		uint64_t size = tupregs[2].dttk_value;
4201 
4202 		if (!dtrace_destructive_disallow &&
4203 		    dtrace_priv_proc_control(state, mstate) &&
4204 		    !dtrace_istoxic(kaddr, size) &&
4205 		    dtrace_strcanload(kaddr, size, mstate, vstate)) {
4206 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4207 			dtrace_copyoutstr(kaddr, uaddr, size, flags);
4208 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4209 		}
4210 		break;
4211 	}
4212 
4213 	case DIF_SUBR_STRLEN: {
4214 		size_t sz;
4215 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4216 		sz = dtrace_strlen((char *)addr,
4217 		    state->dts_options[DTRACEOPT_STRSIZE]);
4218 
4219 		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
4220 			regs[rd] = NULL;
4221 			break;
4222 		}
4223 
4224 		regs[rd] = sz;
4225 
4226 		break;
4227 	}
4228 
4229 	case DIF_SUBR_STRCHR:
4230 	case DIF_SUBR_STRRCHR: {
4231 		/*
4232 		 * We're going to iterate over the string looking for the
4233 		 * specified character.  We will iterate until we have reached
4234 		 * the string length or we have found the character.  If this
4235 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4236 		 * of the specified character instead of the first.
4237 		 */
4238 		uintptr_t saddr = tupregs[0].dttk_value;
4239 		uintptr_t addr = tupregs[0].dttk_value;
4240 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
4241 		char c, target = (char)tupregs[1].dttk_value;
4242 
4243 		for (regs[rd] = NULL; addr < limit; addr++) {
4244 			if ((c = dtrace_load8(addr)) == target) {
4245 				regs[rd] = addr;
4246 
4247 				if (subr == DIF_SUBR_STRCHR)
4248 					break;
4249 			}
4250 
4251 			if (c == '\0')
4252 				break;
4253 		}
4254 
4255 		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
4256 			regs[rd] = NULL;
4257 			break;
4258 		}
4259 
4260 		break;
4261 	}
4262 
4263 	case DIF_SUBR_STRSTR:
4264 	case DIF_SUBR_INDEX:
4265 	case DIF_SUBR_RINDEX: {
4266 		/*
4267 		 * We're going to iterate over the string looking for the
4268 		 * specified string.  We will iterate until we have reached
4269 		 * the string length or we have found the string.  (Yes, this
4270 		 * is done in the most naive way possible -- but considering
4271 		 * that the string we're searching for is likely to be
4272 		 * relatively short, the complexity of Rabin-Karp or similar
4273 		 * hardly seems merited.)
4274 		 */
4275 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4276 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4277 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4278 		size_t len = dtrace_strlen(addr, size);
4279 		size_t sublen = dtrace_strlen(substr, size);
4280 		char *limit = addr + len, *orig = addr;
4281 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4282 		int inc = 1;
4283 
4284 		regs[rd] = notfound;
4285 
4286 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4287 			regs[rd] = NULL;
4288 			break;
4289 		}
4290 
4291 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4292 		    vstate)) {
4293 			regs[rd] = NULL;
4294 			break;
4295 		}
4296 
4297 		/*
4298 		 * strstr() and index()/rindex() have similar semantics if
4299 		 * both strings are the empty string: strstr() returns a
4300 		 * pointer to the (empty) string, and index() and rindex()
4301 		 * both return index 0 (regardless of any position argument).
4302 		 */
4303 		if (sublen == 0 && len == 0) {
4304 			if (subr == DIF_SUBR_STRSTR)
4305 				regs[rd] = (uintptr_t)addr;
4306 			else
4307 				regs[rd] = 0;
4308 			break;
4309 		}
4310 
4311 		if (subr != DIF_SUBR_STRSTR) {
4312 			if (subr == DIF_SUBR_RINDEX) {
4313 				limit = orig - 1;
4314 				addr += len;
4315 				inc = -1;
4316 			}
4317 
4318 			/*
4319 			 * Both index() and rindex() take an optional position
4320 			 * argument that denotes the starting position.
4321 			 */
4322 			if (nargs == 3) {
4323 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4324 
4325 				/*
4326 				 * If the position argument to index() is
4327 				 * negative, Perl implicitly clamps it at
4328 				 * zero.  This semantic is a little surprising
4329 				 * given the special meaning of negative
4330 				 * positions to similar Perl functions like
4331 				 * substr(), but it appears to reflect a
4332 				 * notion that index() can start from a
4333 				 * negative index and increment its way up to
4334 				 * the string.  Given this notion, Perl's
4335 				 * rindex() is at least self-consistent in
4336 				 * that it implicitly clamps positions greater
4337 				 * than the string length to be the string
4338 				 * length.  Where Perl completely loses
4339 				 * coherence, however, is when the specified
4340 				 * substring is the empty string ("").  In
4341 				 * this case, even if the position is
4342 				 * negative, rindex() returns 0 -- and even if
4343 				 * the position is greater than the length,
4344 				 * index() returns the string length.  These
4345 				 * semantics violate the notion that index()
4346 				 * should never return a value less than the
4347 				 * specified position and that rindex() should
4348 				 * never return a value greater than the
4349 				 * specified position.  (One assumes that
4350 				 * these semantics are artifacts of Perl's
4351 				 * implementation and not the results of
4352 				 * deliberate design -- it beggars belief that
4353 				 * even Larry Wall could desire such oddness.)
4354 				 * While in the abstract one would wish for
4355 				 * consistent position semantics across
4356 				 * substr(), index() and rindex() -- or at the
4357 				 * very least self-consistent position
4358 				 * semantics for index() and rindex() -- we
4359 				 * instead opt to keep with the extant Perl
4360 				 * semantics, in all their broken glory.  (Do
4361 				 * we have more desire to maintain Perl's
4362 				 * semantics than Perl does?  Probably.)
4363 				 */
4364 				if (subr == DIF_SUBR_RINDEX) {
4365 					if (pos < 0) {
4366 						if (sublen == 0)
4367 							regs[rd] = 0;
4368 						break;
4369 					}
4370 
4371 					if (pos > len)
4372 						pos = len;
4373 				} else {
4374 					if (pos < 0)
4375 						pos = 0;
4376 
4377 					if (pos >= len) {
4378 						if (sublen == 0)
4379 							regs[rd] = len;
4380 						break;
4381 					}
4382 				}
4383 
4384 				addr = orig + pos;
4385 			}
4386 		}
4387 
4388 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4389 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4390 				if (subr != DIF_SUBR_STRSTR) {
4391 					/*
4392 					 * As D index() and rindex() are
4393 					 * modeled on Perl (and not on awk),
4394 					 * we return a zero-based (and not a
4395 					 * one-based) index.  (For you Perl
4396 					 * weenies: no, we're not going to add
4397 					 * $[ -- and shouldn't you be at a con
4398 					 * or something?)
4399 					 */
4400 					regs[rd] = (uintptr_t)(addr - orig);
4401 					break;
4402 				}
4403 
4404 				ASSERT(subr == DIF_SUBR_STRSTR);
4405 				regs[rd] = (uintptr_t)addr;
4406 				break;
4407 			}
4408 		}
4409 
4410 		break;
4411 	}
4412 
4413 	case DIF_SUBR_STRTOK: {
4414 		uintptr_t addr = tupregs[0].dttk_value;
4415 		uintptr_t tokaddr = tupregs[1].dttk_value;
4416 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4417 		uintptr_t limit, toklimit = tokaddr + size;
4418 		uint8_t c, tokmap[32];	 /* 256 / 8 */
4419 		char *dest = (char *)mstate->dtms_scratch_ptr;
4420 		int i;
4421 
4422 		/*
4423 		 * Check both the token buffer and (later) the input buffer,
4424 		 * since both could be non-scratch addresses.
4425 		 */
4426 		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
4427 			regs[rd] = NULL;
4428 			break;
4429 		}
4430 
4431 		if (!DTRACE_INSCRATCH(mstate, size)) {
4432 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4433 			regs[rd] = NULL;
4434 			break;
4435 		}
4436 
4437 		if (addr == NULL) {
4438 			/*
4439 			 * If the address specified is NULL, we use our saved
4440 			 * strtok pointer from the mstate.  Note that this
4441 			 * means that the saved strtok pointer is _only_
4442 			 * valid within multiple enablings of the same probe --
4443 			 * it behaves like an implicit clause-local variable.
4444 			 */
4445 			addr = mstate->dtms_strtok;
4446 		} else {
4447 			/*
4448 			 * If the user-specified address is non-NULL we must
4449 			 * access check it.  This is the only time we have
4450 			 * a chance to do so, since this address may reside
4451 			 * in the string table of this clause-- future calls
4452 			 * (when we fetch addr from mstate->dtms_strtok)
4453 			 * would fail this access check.
4454 			 */
4455 			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
4456 				regs[rd] = NULL;
4457 				break;
4458 			}
4459 		}
4460 
4461 		/*
4462 		 * First, zero the token map, and then process the token
4463 		 * string -- setting a bit in the map for every character
4464 		 * found in the token string.
4465 		 */
4466 		for (i = 0; i < sizeof (tokmap); i++)
4467 			tokmap[i] = 0;
4468 
4469 		for (; tokaddr < toklimit; tokaddr++) {
4470 			if ((c = dtrace_load8(tokaddr)) == '\0')
4471 				break;
4472 
4473 			ASSERT((c >> 3) < sizeof (tokmap));
4474 			tokmap[c >> 3] |= (1 << (c & 0x7));
4475 		}
4476 
4477 		for (limit = addr + size; addr < limit; addr++) {
4478 			/*
4479 			 * We're looking for a character that is _not_ contained
4480 			 * in the token string.
4481 			 */
4482 			if ((c = dtrace_load8(addr)) == '\0')
4483 				break;
4484 
4485 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4486 				break;
4487 		}
4488 
4489 		if (c == '\0') {
4490 			/*
4491 			 * We reached the end of the string without finding
4492 			 * any character that was not in the token string.
4493 			 * We return NULL in this case, and we set the saved
4494 			 * address to NULL as well.
4495 			 */
4496 			regs[rd] = NULL;
4497 			mstate->dtms_strtok = NULL;
4498 			break;
4499 		}
4500 
4501 		/*
4502 		 * From here on, we're copying into the destination string.
4503 		 */
4504 		for (i = 0; addr < limit && i < size - 1; addr++) {
4505 			if ((c = dtrace_load8(addr)) == '\0')
4506 				break;
4507 
4508 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4509 				break;
4510 
4511 			ASSERT(i < size);
4512 			dest[i++] = c;
4513 		}
4514 
4515 		ASSERT(i < size);
4516 		dest[i] = '\0';
4517 		regs[rd] = (uintptr_t)dest;
4518 		mstate->dtms_scratch_ptr += size;
4519 		mstate->dtms_strtok = addr;
4520 		break;
4521 	}
4522 
4523 	case DIF_SUBR_SUBSTR: {
4524 		uintptr_t s = tupregs[0].dttk_value;
4525 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4526 		char *d = (char *)mstate->dtms_scratch_ptr;
4527 		int64_t index = (int64_t)tupregs[1].dttk_value;
4528 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4529 		size_t len = dtrace_strlen((char *)s, size);
4530 		int64_t i;
4531 
4532 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4533 			regs[rd] = NULL;
4534 			break;
4535 		}
4536 
4537 		if (!DTRACE_INSCRATCH(mstate, size)) {
4538 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4539 			regs[rd] = NULL;
4540 			break;
4541 		}
4542 
4543 		if (nargs <= 2)
4544 			remaining = (int64_t)size;
4545 
4546 		if (index < 0) {
4547 			index += len;
4548 
4549 			if (index < 0 && index + remaining > 0) {
4550 				remaining += index;
4551 				index = 0;
4552 			}
4553 		}
4554 
4555 		if (index >= len || index < 0) {
4556 			remaining = 0;
4557 		} else if (remaining < 0) {
4558 			remaining += len - index;
4559 		} else if (index + remaining > size) {
4560 			remaining = size - index;
4561 		}
4562 
4563 		for (i = 0; i < remaining; i++) {
4564 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4565 				break;
4566 		}
4567 
4568 		d[i] = '\0';
4569 
4570 		mstate->dtms_scratch_ptr += size;
4571 		regs[rd] = (uintptr_t)d;
4572 		break;
4573 	}
4574 
4575 	case DIF_SUBR_JSON: {
4576 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4577 		uintptr_t json = tupregs[0].dttk_value;
4578 		size_t jsonlen = dtrace_strlen((char *)json, size);
4579 		uintptr_t elem = tupregs[1].dttk_value;
4580 		size_t elemlen = dtrace_strlen((char *)elem, size);
4581 
4582 		char *dest = (char *)mstate->dtms_scratch_ptr;
4583 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
4584 		char *ee = elemlist;
4585 		int nelems = 1;
4586 		uintptr_t cur;
4587 
4588 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
4589 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
4590 			regs[rd] = NULL;
4591 			break;
4592 		}
4593 
4594 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
4595 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4596 			regs[rd] = NULL;
4597 			break;
4598 		}
4599 
4600 		/*
4601 		 * Read the element selector and split it up into a packed list
4602 		 * of strings.
4603 		 */
4604 		for (cur = elem; cur < elem + elemlen; cur++) {
4605 			char cc = dtrace_load8(cur);
4606 
4607 			if (cur == elem && cc == '[') {
4608 				/*
4609 				 * If the first element selector key is
4610 				 * actually an array index then ignore the
4611 				 * bracket.
4612 				 */
4613 				continue;
4614 			}
4615 
4616 			if (cc == ']')
4617 				continue;
4618 
4619 			if (cc == '.' || cc == '[') {
4620 				nelems++;
4621 				cc = '\0';
4622 			}
4623 
4624 			*ee++ = cc;
4625 		}
4626 		*ee++ = '\0';
4627 
4628 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
4629 		    nelems, dest)) != NULL)
4630 			mstate->dtms_scratch_ptr += jsonlen + 1;
4631 		break;
4632 	}
4633 
4634 	case DIF_SUBR_TOUPPER:
4635 	case DIF_SUBR_TOLOWER: {
4636 		uintptr_t s = tupregs[0].dttk_value;
4637 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4638 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4639 		size_t len = dtrace_strlen((char *)s, size);
4640 		char lower, upper, convert;
4641 		int64_t i;
4642 
4643 		if (subr == DIF_SUBR_TOUPPER) {
4644 			lower = 'a';
4645 			upper = 'z';
4646 			convert = 'A';
4647 		} else {
4648 			lower = 'A';
4649 			upper = 'Z';
4650 			convert = 'a';
4651 		}
4652 
4653 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4654 			regs[rd] = NULL;
4655 			break;
4656 		}
4657 
4658 		if (!DTRACE_INSCRATCH(mstate, size)) {
4659 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4660 			regs[rd] = NULL;
4661 			break;
4662 		}
4663 
4664 		for (i = 0; i < size - 1; i++) {
4665 			if ((c = dtrace_load8(s + i)) == '\0')
4666 				break;
4667 
4668 			if (c >= lower && c <= upper)
4669 				c = convert + (c - lower);
4670 
4671 			dest[i] = c;
4672 		}
4673 
4674 		ASSERT(i < size);
4675 		dest[i] = '\0';
4676 		regs[rd] = (uintptr_t)dest;
4677 		mstate->dtms_scratch_ptr += size;
4678 		break;
4679 	}
4680 
4681 case DIF_SUBR_GETMAJOR:
4682 #ifdef _LP64
4683 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4684 #else
4685 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4686 #endif
4687 		break;
4688 
4689 	case DIF_SUBR_GETMINOR:
4690 #ifdef _LP64
4691 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4692 #else
4693 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
4694 #endif
4695 		break;
4696 
4697 	case DIF_SUBR_DDI_PATHNAME: {
4698 		/*
4699 		 * This one is a galactic mess.  We are going to roughly
4700 		 * emulate ddi_pathname(), but it's made more complicated
4701 		 * by the fact that we (a) want to include the minor name and
4702 		 * (b) must proceed iteratively instead of recursively.
4703 		 */
4704 		uintptr_t dest = mstate->dtms_scratch_ptr;
4705 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4706 		char *start = (char *)dest, *end = start + size - 1;
4707 		uintptr_t daddr = tupregs[0].dttk_value;
4708 		int64_t minor = (int64_t)tupregs[1].dttk_value;
4709 		char *s;
4710 		int i, len, depth = 0;
4711 
4712 		/*
4713 		 * Due to all the pointer jumping we do and context we must
4714 		 * rely upon, we just mandate that the user must have kernel
4715 		 * read privileges to use this routine.
4716 		 */
4717 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4718 			*flags |= CPU_DTRACE_KPRIV;
4719 			*illval = daddr;
4720 			regs[rd] = NULL;
4721 		}
4722 
4723 		if (!DTRACE_INSCRATCH(mstate, size)) {
4724 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4725 			regs[rd] = NULL;
4726 			break;
4727 		}
4728 
4729 		*end = '\0';
4730 
4731 		/*
4732 		 * We want to have a name for the minor.  In order to do this,
4733 		 * we need to walk the minor list from the devinfo.  We want
4734 		 * to be sure that we don't infinitely walk a circular list,
4735 		 * so we check for circularity by sending a scout pointer
4736 		 * ahead two elements for every element that we iterate over;
4737 		 * if the list is circular, these will ultimately point to the
4738 		 * same element.  You may recognize this little trick as the
4739 		 * answer to a stupid interview question -- one that always
4740 		 * seems to be asked by those who had to have it laboriously
4741 		 * explained to them, and who can't even concisely describe
4742 		 * the conditions under which one would be forced to resort to
4743 		 * this technique.  Needless to say, those conditions are
4744 		 * found here -- and probably only here.  Is this the only use
4745 		 * of this infamous trick in shipping, production code?  If it
4746 		 * isn't, it probably should be...
4747 		 */
4748 		if (minor != -1) {
4749 			uintptr_t maddr = dtrace_loadptr(daddr +
4750 			    offsetof(struct dev_info, devi_minor));
4751 
4752 			uintptr_t next = offsetof(struct ddi_minor_data, next);
4753 			uintptr_t name = offsetof(struct ddi_minor_data,
4754 			    d_minor) + offsetof(struct ddi_minor, name);
4755 			uintptr_t dev = offsetof(struct ddi_minor_data,
4756 			    d_minor) + offsetof(struct ddi_minor, dev);
4757 			uintptr_t scout;
4758 
4759 			if (maddr != NULL)
4760 				scout = dtrace_loadptr(maddr + next);
4761 
4762 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4763 				uint64_t m;
4764 #ifdef _LP64
4765 				m = dtrace_load64(maddr + dev) & MAXMIN64;
4766 #else
4767 				m = dtrace_load32(maddr + dev) & MAXMIN;
4768 #endif
4769 				if (m != minor) {
4770 					maddr = dtrace_loadptr(maddr + next);
4771 
4772 					if (scout == NULL)
4773 						continue;
4774 
4775 					scout = dtrace_loadptr(scout + next);
4776 
4777 					if (scout == NULL)
4778 						continue;
4779 
4780 					scout = dtrace_loadptr(scout + next);
4781 
4782 					if (scout == NULL)
4783 						continue;
4784 
4785 					if (scout == maddr) {
4786 						*flags |= CPU_DTRACE_ILLOP;
4787 						break;
4788 					}
4789 
4790 					continue;
4791 				}
4792 
4793 				/*
4794 				 * We have the minor data.  Now we need to
4795 				 * copy the minor's name into the end of the
4796 				 * pathname.
4797 				 */
4798 				s = (char *)dtrace_loadptr(maddr + name);
4799 				len = dtrace_strlen(s, size);
4800 
4801 				if (*flags & CPU_DTRACE_FAULT)
4802 					break;
4803 
4804 				if (len != 0) {
4805 					if ((end -= (len + 1)) < start)
4806 						break;
4807 
4808 					*end = ':';
4809 				}
4810 
4811 				for (i = 1; i <= len; i++)
4812 					end[i] = dtrace_load8((uintptr_t)s++);
4813 				break;
4814 			}
4815 		}
4816 
4817 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4818 			ddi_node_state_t devi_state;
4819 
4820 			devi_state = dtrace_load32(daddr +
4821 			    offsetof(struct dev_info, devi_node_state));
4822 
4823 			if (*flags & CPU_DTRACE_FAULT)
4824 				break;
4825 
4826 			if (devi_state >= DS_INITIALIZED) {
4827 				s = (char *)dtrace_loadptr(daddr +
4828 				    offsetof(struct dev_info, devi_addr));
4829 				len = dtrace_strlen(s, size);
4830 
4831 				if (*flags & CPU_DTRACE_FAULT)
4832 					break;
4833 
4834 				if (len != 0) {
4835 					if ((end -= (len + 1)) < start)
4836 						break;
4837 
4838 					*end = '@';
4839 				}
4840 
4841 				for (i = 1; i <= len; i++)
4842 					end[i] = dtrace_load8((uintptr_t)s++);
4843 			}
4844 
4845 			/*
4846 			 * Now for the node name...
4847 			 */
4848 			s = (char *)dtrace_loadptr(daddr +
4849 			    offsetof(struct dev_info, devi_node_name));
4850 
4851 			daddr = dtrace_loadptr(daddr +
4852 			    offsetof(struct dev_info, devi_parent));
4853 
4854 			/*
4855 			 * If our parent is NULL (that is, if we're the root
4856 			 * node), we're going to use the special path
4857 			 * "devices".
4858 			 */
4859 			if (daddr == NULL)
4860 				s = "devices";
4861 
4862 			len = dtrace_strlen(s, size);
4863 			if (*flags & CPU_DTRACE_FAULT)
4864 				break;
4865 
4866 			if ((end -= (len + 1)) < start)
4867 				break;
4868 
4869 			for (i = 1; i <= len; i++)
4870 				end[i] = dtrace_load8((uintptr_t)s++);
4871 			*end = '/';
4872 
4873 			if (depth++ > dtrace_devdepth_max) {
4874 				*flags |= CPU_DTRACE_ILLOP;
4875 				break;
4876 			}
4877 		}
4878 
4879 		if (end < start)
4880 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4881 
4882 		if (daddr == NULL) {
4883 			regs[rd] = (uintptr_t)end;
4884 			mstate->dtms_scratch_ptr += size;
4885 		}
4886 
4887 		break;
4888 	}
4889 
4890 	case DIF_SUBR_STRJOIN: {
4891 		char *d = (char *)mstate->dtms_scratch_ptr;
4892 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4893 		uintptr_t s1 = tupregs[0].dttk_value;
4894 		uintptr_t s2 = tupregs[1].dttk_value;
4895 		int i = 0;
4896 
4897 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4898 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
4899 			regs[rd] = NULL;
4900 			break;
4901 		}
4902 
4903 		if (!DTRACE_INSCRATCH(mstate, size)) {
4904 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4905 			regs[rd] = NULL;
4906 			break;
4907 		}
4908 
4909 		for (;;) {
4910 			if (i >= size) {
4911 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4912 				regs[rd] = NULL;
4913 				break;
4914 			}
4915 
4916 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4917 				i--;
4918 				break;
4919 			}
4920 		}
4921 
4922 		for (;;) {
4923 			if (i >= size) {
4924 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4925 				regs[rd] = NULL;
4926 				break;
4927 			}
4928 
4929 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
4930 				break;
4931 		}
4932 
4933 		if (i < size) {
4934 			mstate->dtms_scratch_ptr += i;
4935 			regs[rd] = (uintptr_t)d;
4936 		}
4937 
4938 		break;
4939 	}
4940 
4941 	case DIF_SUBR_STRTOLL: {
4942 		uintptr_t s = tupregs[0].dttk_value;
4943 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4944 		int base = 10;
4945 
4946 		if (nargs > 1) {
4947 			if ((base = tupregs[1].dttk_value) <= 1 ||
4948 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4949 				*flags |= CPU_DTRACE_ILLOP;
4950 				break;
4951 			}
4952 		}
4953 
4954 		if (!dtrace_strcanload(s, size, mstate, vstate)) {
4955 			regs[rd] = INT64_MIN;
4956 			break;
4957 		}
4958 
4959 		regs[rd] = dtrace_strtoll((char *)s, base, size);
4960 		break;
4961 	}
4962 
4963 	case DIF_SUBR_LLTOSTR: {
4964 		int64_t i = (int64_t)tupregs[0].dttk_value;
4965 		uint64_t val, digit;
4966 		uint64_t size = 65;	/* enough room for 2^64 in binary */
4967 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4968 		int base = 10;
4969 
4970 		if (nargs > 1) {
4971 			if ((base = tupregs[1].dttk_value) <= 1 ||
4972 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4973 				*flags |= CPU_DTRACE_ILLOP;
4974 				break;
4975 			}
4976 		}
4977 
4978 		val = (base == 10 && i < 0) ? i * -1 : i;
4979 
4980 		if (!DTRACE_INSCRATCH(mstate, size)) {
4981 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4982 			regs[rd] = NULL;
4983 			break;
4984 		}
4985 
4986 		for (*end-- = '\0'; val; val /= base) {
4987 			if ((digit = val % base) <= '9' - '0') {
4988 				*end-- = '0' + digit;
4989 			} else {
4990 				*end-- = 'a' + (digit - ('9' - '0') - 1);
4991 			}
4992 		}
4993 
4994 		if (i == 0 && base == 16)
4995 			*end-- = '0';
4996 
4997 		if (base == 16)
4998 			*end-- = 'x';
4999 
5000 		if (i == 0 || base == 8 || base == 16)
5001 			*end-- = '0';
5002 
5003 		if (i < 0 && base == 10)
5004 			*end-- = '-';
5005 
5006 		regs[rd] = (uintptr_t)end + 1;
5007 		mstate->dtms_scratch_ptr += size;
5008 		break;
5009 	}
5010 
5011 	case DIF_SUBR_HTONS:
5012 	case DIF_SUBR_NTOHS:
5013 #ifdef _BIG_ENDIAN
5014 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
5015 #else
5016 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5017 #endif
5018 		break;
5019 
5020 
5021 	case DIF_SUBR_HTONL:
5022 	case DIF_SUBR_NTOHL:
5023 #ifdef _BIG_ENDIAN
5024 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5025 #else
5026 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5027 #endif
5028 		break;
5029 
5030 
5031 	case DIF_SUBR_HTONLL:
5032 	case DIF_SUBR_NTOHLL:
5033 #ifdef _BIG_ENDIAN
5034 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5035 #else
5036 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5037 #endif
5038 		break;
5039 
5040 
5041 	case DIF_SUBR_DIRNAME:
5042 	case DIF_SUBR_BASENAME: {
5043 		char *dest = (char *)mstate->dtms_scratch_ptr;
5044 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5045 		uintptr_t src = tupregs[0].dttk_value;
5046 		int i, j, len = dtrace_strlen((char *)src, size);
5047 		int lastbase = -1, firstbase = -1, lastdir = -1;
5048 		int start, end;
5049 
5050 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5051 			regs[rd] = NULL;
5052 			break;
5053 		}
5054 
5055 		if (!DTRACE_INSCRATCH(mstate, size)) {
5056 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5057 			regs[rd] = NULL;
5058 			break;
5059 		}
5060 
5061 		/*
5062 		 * The basename and dirname for a zero-length string is
5063 		 * defined to be "."
5064 		 */
5065 		if (len == 0) {
5066 			len = 1;
5067 			src = (uintptr_t)".";
5068 		}
5069 
5070 		/*
5071 		 * Start from the back of the string, moving back toward the
5072 		 * front until we see a character that isn't a slash.  That
5073 		 * character is the last character in the basename.
5074 		 */
5075 		for (i = len - 1; i >= 0; i--) {
5076 			if (dtrace_load8(src + i) != '/')
5077 				break;
5078 		}
5079 
5080 		if (i >= 0)
5081 			lastbase = i;
5082 
5083 		/*
5084 		 * Starting from the last character in the basename, move
5085 		 * towards the front until we find a slash.  The character
5086 		 * that we processed immediately before that is the first
5087 		 * character in the basename.
5088 		 */
5089 		for (; i >= 0; i--) {
5090 			if (dtrace_load8(src + i) == '/')
5091 				break;
5092 		}
5093 
5094 		if (i >= 0)
5095 			firstbase = i + 1;
5096 
5097 		/*
5098 		 * Now keep going until we find a non-slash character.  That
5099 		 * character is the last character in the dirname.
5100 		 */
5101 		for (; i >= 0; i--) {
5102 			if (dtrace_load8(src + i) != '/')
5103 				break;
5104 		}
5105 
5106 		if (i >= 0)
5107 			lastdir = i;
5108 
5109 		ASSERT(!(lastbase == -1 && firstbase != -1));
5110 		ASSERT(!(firstbase == -1 && lastdir != -1));
5111 
5112 		if (lastbase == -1) {
5113 			/*
5114 			 * We didn't find a non-slash character.  We know that
5115 			 * the length is non-zero, so the whole string must be
5116 			 * slashes.  In either the dirname or the basename
5117 			 * case, we return '/'.
5118 			 */
5119 			ASSERT(firstbase == -1);
5120 			firstbase = lastbase = lastdir = 0;
5121 		}
5122 
5123 		if (firstbase == -1) {
5124 			/*
5125 			 * The entire string consists only of a basename
5126 			 * component.  If we're looking for dirname, we need
5127 			 * to change our string to be just "."; if we're
5128 			 * looking for a basename, we'll just set the first
5129 			 * character of the basename to be 0.
5130 			 */
5131 			if (subr == DIF_SUBR_DIRNAME) {
5132 				ASSERT(lastdir == -1);
5133 				src = (uintptr_t)".";
5134 				lastdir = 0;
5135 			} else {
5136 				firstbase = 0;
5137 			}
5138 		}
5139 
5140 		if (subr == DIF_SUBR_DIRNAME) {
5141 			if (lastdir == -1) {
5142 				/*
5143 				 * We know that we have a slash in the name --
5144 				 * or lastdir would be set to 0, above.  And
5145 				 * because lastdir is -1, we know that this
5146 				 * slash must be the first character.  (That
5147 				 * is, the full string must be of the form
5148 				 * "/basename".)  In this case, the last
5149 				 * character of the directory name is 0.
5150 				 */
5151 				lastdir = 0;
5152 			}
5153 
5154 			start = 0;
5155 			end = lastdir;
5156 		} else {
5157 			ASSERT(subr == DIF_SUBR_BASENAME);
5158 			ASSERT(firstbase != -1 && lastbase != -1);
5159 			start = firstbase;
5160 			end = lastbase;
5161 		}
5162 
5163 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5164 			dest[j] = dtrace_load8(src + i);
5165 
5166 		dest[j] = '\0';
5167 		regs[rd] = (uintptr_t)dest;
5168 		mstate->dtms_scratch_ptr += size;
5169 		break;
5170 	}
5171 
5172 	case DIF_SUBR_GETF: {
5173 		uintptr_t fd = tupregs[0].dttk_value;
5174 		uf_info_t *finfo = &curthread->t_procp->p_user.u_finfo;
5175 		file_t *fp;
5176 
5177 		if (!dtrace_priv_proc(state, mstate)) {
5178 			regs[rd] = NULL;
5179 			break;
5180 		}
5181 
5182 		/*
5183 		 * This is safe because fi_nfiles only increases, and the
5184 		 * fi_list array is not freed when the array size doubles.
5185 		 * (See the comment in flist_grow() for details on the
5186 		 * management of the u_finfo structure.)
5187 		 */
5188 		fp = fd < finfo->fi_nfiles ? finfo->fi_list[fd].uf_file : NULL;
5189 
5190 		mstate->dtms_getf = fp;
5191 		regs[rd] = (uintptr_t)fp;
5192 		break;
5193 	}
5194 
5195 	case DIF_SUBR_CLEANPATH: {
5196 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5197 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5198 		uintptr_t src = tupregs[0].dttk_value;
5199 		int i = 0, j = 0;
5200 		zone_t *z;
5201 
5202 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
5203 			regs[rd] = NULL;
5204 			break;
5205 		}
5206 
5207 		if (!DTRACE_INSCRATCH(mstate, size)) {
5208 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5209 			regs[rd] = NULL;
5210 			break;
5211 		}
5212 
5213 		/*
5214 		 * Move forward, loading each character.
5215 		 */
5216 		do {
5217 			c = dtrace_load8(src + i++);
5218 next:
5219 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
5220 				break;
5221 
5222 			if (c != '/') {
5223 				dest[j++] = c;
5224 				continue;
5225 			}
5226 
5227 			c = dtrace_load8(src + i++);
5228 
5229 			if (c == '/') {
5230 				/*
5231 				 * We have two slashes -- we can just advance
5232 				 * to the next character.
5233 				 */
5234 				goto next;
5235 			}
5236 
5237 			if (c != '.') {
5238 				/*
5239 				 * This is not "." and it's not ".." -- we can
5240 				 * just store the "/" and this character and
5241 				 * drive on.
5242 				 */
5243 				dest[j++] = '/';
5244 				dest[j++] = c;
5245 				continue;
5246 			}
5247 
5248 			c = dtrace_load8(src + i++);
5249 
5250 			if (c == '/') {
5251 				/*
5252 				 * This is a "/./" component.  We're not going
5253 				 * to store anything in the destination buffer;
5254 				 * we're just going to go to the next component.
5255 				 */
5256 				goto next;
5257 			}
5258 
5259 			if (c != '.') {
5260 				/*
5261 				 * This is not ".." -- we can just store the
5262 				 * "/." and this character and continue
5263 				 * processing.
5264 				 */
5265 				dest[j++] = '/';
5266 				dest[j++] = '.';
5267 				dest[j++] = c;
5268 				continue;
5269 			}
5270 
5271 			c = dtrace_load8(src + i++);
5272 
5273 			if (c != '/' && c != '\0') {
5274 				/*
5275 				 * This is not ".." -- it's "..[mumble]".
5276 				 * We'll store the "/.." and this character
5277 				 * and continue processing.
5278 				 */
5279 				dest[j++] = '/';
5280 				dest[j++] = '.';
5281 				dest[j++] = '.';
5282 				dest[j++] = c;
5283 				continue;
5284 			}
5285 
5286 			/*
5287 			 * This is "/../" or "/..\0".  We need to back up
5288 			 * our destination pointer until we find a "/".
5289 			 */
5290 			i--;
5291 			while (j != 0 && dest[--j] != '/')
5292 				continue;
5293 
5294 			if (c == '\0')
5295 				dest[++j] = '/';
5296 		} while (c != '\0');
5297 
5298 		dest[j] = '\0';
5299 
5300 		if (mstate->dtms_getf != NULL &&
5301 		    !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5302 		    (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5303 			/*
5304 			 * If we've done a getf() as a part of this ECB and we
5305 			 * don't have kernel access (and we're not in the global
5306 			 * zone), check if the path we cleaned up begins with
5307 			 * the zone's root path, and trim it off if so.  Note
5308 			 * that this is an output cleanliness issue, not a
5309 			 * security issue: knowing one's zone root path does
5310 			 * not enable privilege escalation.
5311 			 */
5312 			if (strstr(dest, z->zone_rootpath) == dest)
5313 				dest += strlen(z->zone_rootpath) - 1;
5314 		}
5315 
5316 		regs[rd] = (uintptr_t)dest;
5317 		mstate->dtms_scratch_ptr += size;
5318 		break;
5319 	}
5320 
5321 	case DIF_SUBR_INET_NTOA:
5322 	case DIF_SUBR_INET_NTOA6:
5323 	case DIF_SUBR_INET_NTOP: {
5324 		size_t size;
5325 		int af, argi, i;
5326 		char *base, *end;
5327 
5328 		if (subr == DIF_SUBR_INET_NTOP) {
5329 			af = (int)tupregs[0].dttk_value;
5330 			argi = 1;
5331 		} else {
5332 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5333 			argi = 0;
5334 		}
5335 
5336 		if (af == AF_INET) {
5337 			ipaddr_t ip4;
5338 			uint8_t *ptr8, val;
5339 
5340 			/*
5341 			 * Safely load the IPv4 address.
5342 			 */
5343 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5344 
5345 			/*
5346 			 * Check an IPv4 string will fit in scratch.
5347 			 */
5348 			size = INET_ADDRSTRLEN;
5349 			if (!DTRACE_INSCRATCH(mstate, size)) {
5350 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5351 				regs[rd] = NULL;
5352 				break;
5353 			}
5354 			base = (char *)mstate->dtms_scratch_ptr;
5355 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5356 
5357 			/*
5358 			 * Stringify as a dotted decimal quad.
5359 			 */
5360 			*end-- = '\0';
5361 			ptr8 = (uint8_t *)&ip4;
5362 			for (i = 3; i >= 0; i--) {
5363 				val = ptr8[i];
5364 
5365 				if (val == 0) {
5366 					*end-- = '0';
5367 				} else {
5368 					for (; val; val /= 10) {
5369 						*end-- = '0' + (val % 10);
5370 					}
5371 				}
5372 
5373 				if (i > 0)
5374 					*end-- = '.';
5375 			}
5376 			ASSERT(end + 1 >= base);
5377 
5378 		} else if (af == AF_INET6) {
5379 			struct in6_addr ip6;
5380 			int firstzero, tryzero, numzero, v6end;
5381 			uint16_t val;
5382 			const char digits[] = "0123456789abcdef";
5383 
5384 			/*
5385 			 * Stringify using RFC 1884 convention 2 - 16 bit
5386 			 * hexadecimal values with a zero-run compression.
5387 			 * Lower case hexadecimal digits are used.
5388 			 * 	eg, fe80::214:4fff:fe0b:76c8.
5389 			 * The IPv4 embedded form is returned for inet_ntop,
5390 			 * just the IPv4 string is returned for inet_ntoa6.
5391 			 */
5392 
5393 			/*
5394 			 * Safely load the IPv6 address.
5395 			 */
5396 			dtrace_bcopy(
5397 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5398 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5399 
5400 			/*
5401 			 * Check an IPv6 string will fit in scratch.
5402 			 */
5403 			size = INET6_ADDRSTRLEN;
5404 			if (!DTRACE_INSCRATCH(mstate, size)) {
5405 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5406 				regs[rd] = NULL;
5407 				break;
5408 			}
5409 			base = (char *)mstate->dtms_scratch_ptr;
5410 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5411 			*end-- = '\0';
5412 
5413 			/*
5414 			 * Find the longest run of 16 bit zero values
5415 			 * for the single allowed zero compression - "::".
5416 			 */
5417 			firstzero = -1;
5418 			tryzero = -1;
5419 			numzero = 1;
5420 			for (i = 0; i < sizeof (struct in6_addr); i++) {
5421 				if (ip6._S6_un._S6_u8[i] == 0 &&
5422 				    tryzero == -1 && i % 2 == 0) {
5423 					tryzero = i;
5424 					continue;
5425 				}
5426 
5427 				if (tryzero != -1 &&
5428 				    (ip6._S6_un._S6_u8[i] != 0 ||
5429 				    i == sizeof (struct in6_addr) - 1)) {
5430 
5431 					if (i - tryzero <= numzero) {
5432 						tryzero = -1;
5433 						continue;
5434 					}
5435 
5436 					firstzero = tryzero;
5437 					numzero = i - i % 2 - tryzero;
5438 					tryzero = -1;
5439 
5440 					if (ip6._S6_un._S6_u8[i] == 0 &&
5441 					    i == sizeof (struct in6_addr) - 1)
5442 						numzero += 2;
5443 				}
5444 			}
5445 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5446 
5447 			/*
5448 			 * Check for an IPv4 embedded address.
5449 			 */
5450 			v6end = sizeof (struct in6_addr) - 2;
5451 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5452 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5453 				for (i = sizeof (struct in6_addr) - 1;
5454 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
5455 					ASSERT(end >= base);
5456 
5457 					val = ip6._S6_un._S6_u8[i];
5458 
5459 					if (val == 0) {
5460 						*end-- = '0';
5461 					} else {
5462 						for (; val; val /= 10) {
5463 							*end-- = '0' + val % 10;
5464 						}
5465 					}
5466 
5467 					if (i > DTRACE_V4MAPPED_OFFSET)
5468 						*end-- = '.';
5469 				}
5470 
5471 				if (subr == DIF_SUBR_INET_NTOA6)
5472 					goto inetout;
5473 
5474 				/*
5475 				 * Set v6end to skip the IPv4 address that
5476 				 * we have already stringified.
5477 				 */
5478 				v6end = 10;
5479 			}
5480 
5481 			/*
5482 			 * Build the IPv6 string by working through the
5483 			 * address in reverse.
5484 			 */
5485 			for (i = v6end; i >= 0; i -= 2) {
5486 				ASSERT(end >= base);
5487 
5488 				if (i == firstzero + numzero - 2) {
5489 					*end-- = ':';
5490 					*end-- = ':';
5491 					i -= numzero - 2;
5492 					continue;
5493 				}
5494 
5495 				if (i < 14 && i != firstzero - 2)
5496 					*end-- = ':';
5497 
5498 				val = (ip6._S6_un._S6_u8[i] << 8) +
5499 				    ip6._S6_un._S6_u8[i + 1];
5500 
5501 				if (val == 0) {
5502 					*end-- = '0';
5503 				} else {
5504 					for (; val; val /= 16) {
5505 						*end-- = digits[val % 16];
5506 					}
5507 				}
5508 			}
5509 			ASSERT(end + 1 >= base);
5510 
5511 		} else {
5512 			/*
5513 			 * The user didn't use AH_INET or AH_INET6.
5514 			 */
5515 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5516 			regs[rd] = NULL;
5517 			break;
5518 		}
5519 
5520 inetout:	regs[rd] = (uintptr_t)end + 1;
5521 		mstate->dtms_scratch_ptr += size;
5522 		break;
5523 	}
5524 
5525 	}
5526 }
5527 
5528 /*
5529  * Emulate the execution of DTrace IR instructions specified by the given
5530  * DIF object.  This function is deliberately void of assertions as all of
5531  * the necessary checks are handled by a call to dtrace_difo_validate().
5532  */
5533 static uint64_t
5534 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5535     dtrace_vstate_t *vstate, dtrace_state_t *state)
5536 {
5537 	const dif_instr_t *text = difo->dtdo_buf;
5538 	const uint_t textlen = difo->dtdo_len;
5539 	const char *strtab = difo->dtdo_strtab;
5540 	const uint64_t *inttab = difo->dtdo_inttab;
5541 
5542 	uint64_t rval = 0;
5543 	dtrace_statvar_t *svar;
5544 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5545 	dtrace_difv_t *v;
5546 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5547 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
5548 
5549 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5550 	uint64_t regs[DIF_DIR_NREGS];
5551 	uint64_t *tmp;
5552 
5553 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5554 	int64_t cc_r;
5555 	uint_t pc = 0, id, opc;
5556 	uint8_t ttop = 0;
5557 	dif_instr_t instr;
5558 	uint_t r1, r2, rd;
5559 
5560 	/*
5561 	 * We stash the current DIF object into the machine state: we need it
5562 	 * for subsequent access checking.
5563 	 */
5564 	mstate->dtms_difo = difo;
5565 
5566 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
5567 
5568 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5569 		opc = pc;
5570 
5571 		instr = text[pc++];
5572 		r1 = DIF_INSTR_R1(instr);
5573 		r2 = DIF_INSTR_R2(instr);
5574 		rd = DIF_INSTR_RD(instr);
5575 
5576 		switch (DIF_INSTR_OP(instr)) {
5577 		case DIF_OP_OR:
5578 			regs[rd] = regs[r1] | regs[r2];
5579 			break;
5580 		case DIF_OP_XOR:
5581 			regs[rd] = regs[r1] ^ regs[r2];
5582 			break;
5583 		case DIF_OP_AND:
5584 			regs[rd] = regs[r1] & regs[r2];
5585 			break;
5586 		case DIF_OP_SLL:
5587 			regs[rd] = regs[r1] << regs[r2];
5588 			break;
5589 		case DIF_OP_SRL:
5590 			regs[rd] = regs[r1] >> regs[r2];
5591 			break;
5592 		case DIF_OP_SUB:
5593 			regs[rd] = regs[r1] - regs[r2];
5594 			break;
5595 		case DIF_OP_ADD:
5596 			regs[rd] = regs[r1] + regs[r2];
5597 			break;
5598 		case DIF_OP_MUL:
5599 			regs[rd] = regs[r1] * regs[r2];
5600 			break;
5601 		case DIF_OP_SDIV:
5602 			if (regs[r2] == 0) {
5603 				regs[rd] = 0;
5604 				*flags |= CPU_DTRACE_DIVZERO;
5605 			} else {
5606 				regs[rd] = (int64_t)regs[r1] /
5607 				    (int64_t)regs[r2];
5608 			}
5609 			break;
5610 
5611 		case DIF_OP_UDIV:
5612 			if (regs[r2] == 0) {
5613 				regs[rd] = 0;
5614 				*flags |= CPU_DTRACE_DIVZERO;
5615 			} else {
5616 				regs[rd] = regs[r1] / regs[r2];
5617 			}
5618 			break;
5619 
5620 		case DIF_OP_SREM:
5621 			if (regs[r2] == 0) {
5622 				regs[rd] = 0;
5623 				*flags |= CPU_DTRACE_DIVZERO;
5624 			} else {
5625 				regs[rd] = (int64_t)regs[r1] %
5626 				    (int64_t)regs[r2];
5627 			}
5628 			break;
5629 
5630 		case DIF_OP_UREM:
5631 			if (regs[r2] == 0) {
5632 				regs[rd] = 0;
5633 				*flags |= CPU_DTRACE_DIVZERO;
5634 			} else {
5635 				regs[rd] = regs[r1] % regs[r2];
5636 			}
5637 			break;
5638 
5639 		case DIF_OP_NOT:
5640 			regs[rd] = ~regs[r1];
5641 			break;
5642 		case DIF_OP_MOV:
5643 			regs[rd] = regs[r1];
5644 			break;
5645 		case DIF_OP_CMP:
5646 			cc_r = regs[r1] - regs[r2];
5647 			cc_n = cc_r < 0;
5648 			cc_z = cc_r == 0;
5649 			cc_v = 0;
5650 			cc_c = regs[r1] < regs[r2];
5651 			break;
5652 		case DIF_OP_TST:
5653 			cc_n = cc_v = cc_c = 0;
5654 			cc_z = regs[r1] == 0;
5655 			break;
5656 		case DIF_OP_BA:
5657 			pc = DIF_INSTR_LABEL(instr);
5658 			break;
5659 		case DIF_OP_BE:
5660 			if (cc_z)
5661 				pc = DIF_INSTR_LABEL(instr);
5662 			break;
5663 		case DIF_OP_BNE:
5664 			if (cc_z == 0)
5665 				pc = DIF_INSTR_LABEL(instr);
5666 			break;
5667 		case DIF_OP_BG:
5668 			if ((cc_z | (cc_n ^ cc_v)) == 0)
5669 				pc = DIF_INSTR_LABEL(instr);
5670 			break;
5671 		case DIF_OP_BGU:
5672 			if ((cc_c | cc_z) == 0)
5673 				pc = DIF_INSTR_LABEL(instr);
5674 			break;
5675 		case DIF_OP_BGE:
5676 			if ((cc_n ^ cc_v) == 0)
5677 				pc = DIF_INSTR_LABEL(instr);
5678 			break;
5679 		case DIF_OP_BGEU:
5680 			if (cc_c == 0)
5681 				pc = DIF_INSTR_LABEL(instr);
5682 			break;
5683 		case DIF_OP_BL:
5684 			if (cc_n ^ cc_v)
5685 				pc = DIF_INSTR_LABEL(instr);
5686 			break;
5687 		case DIF_OP_BLU:
5688 			if (cc_c)
5689 				pc = DIF_INSTR_LABEL(instr);
5690 			break;
5691 		case DIF_OP_BLE:
5692 			if (cc_z | (cc_n ^ cc_v))
5693 				pc = DIF_INSTR_LABEL(instr);
5694 			break;
5695 		case DIF_OP_BLEU:
5696 			if (cc_c | cc_z)
5697 				pc = DIF_INSTR_LABEL(instr);
5698 			break;
5699 		case DIF_OP_RLDSB:
5700 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5701 				break;
5702 			/*FALLTHROUGH*/
5703 		case DIF_OP_LDSB:
5704 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5705 			break;
5706 		case DIF_OP_RLDSH:
5707 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5708 				break;
5709 			/*FALLTHROUGH*/
5710 		case DIF_OP_LDSH:
5711 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5712 			break;
5713 		case DIF_OP_RLDSW:
5714 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5715 				break;
5716 			/*FALLTHROUGH*/
5717 		case DIF_OP_LDSW:
5718 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5719 			break;
5720 		case DIF_OP_RLDUB:
5721 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5722 				break;
5723 			/*FALLTHROUGH*/
5724 		case DIF_OP_LDUB:
5725 			regs[rd] = dtrace_load8(regs[r1]);
5726 			break;
5727 		case DIF_OP_RLDUH:
5728 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5729 				break;
5730 			/*FALLTHROUGH*/
5731 		case DIF_OP_LDUH:
5732 			regs[rd] = dtrace_load16(regs[r1]);
5733 			break;
5734 		case DIF_OP_RLDUW:
5735 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5736 				break;
5737 			/*FALLTHROUGH*/
5738 		case DIF_OP_LDUW:
5739 			regs[rd] = dtrace_load32(regs[r1]);
5740 			break;
5741 		case DIF_OP_RLDX:
5742 			if (!dtrace_canload(regs[r1], 8, mstate, vstate))
5743 				break;
5744 			/*FALLTHROUGH*/
5745 		case DIF_OP_LDX:
5746 			regs[rd] = dtrace_load64(regs[r1]);
5747 			break;
5748 		case DIF_OP_ULDSB:
5749 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5750 			regs[rd] = (int8_t)
5751 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5752 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5753 			break;
5754 		case DIF_OP_ULDSH:
5755 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5756 			regs[rd] = (int16_t)
5757 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5758 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5759 			break;
5760 		case DIF_OP_ULDSW:
5761 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5762 			regs[rd] = (int32_t)
5763 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5764 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5765 			break;
5766 		case DIF_OP_ULDUB:
5767 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5768 			regs[rd] =
5769 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5770 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5771 			break;
5772 		case DIF_OP_ULDUH:
5773 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5774 			regs[rd] =
5775 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5776 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5777 			break;
5778 		case DIF_OP_ULDUW:
5779 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5780 			regs[rd] =
5781 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5782 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5783 			break;
5784 		case DIF_OP_ULDX:
5785 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5786 			regs[rd] =
5787 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5788 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5789 			break;
5790 		case DIF_OP_RET:
5791 			rval = regs[rd];
5792 			pc = textlen;
5793 			break;
5794 		case DIF_OP_NOP:
5795 			break;
5796 		case DIF_OP_SETX:
5797 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5798 			break;
5799 		case DIF_OP_SETS:
5800 			regs[rd] = (uint64_t)(uintptr_t)
5801 			    (strtab + DIF_INSTR_STRING(instr));
5802 			break;
5803 		case DIF_OP_SCMP: {
5804 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5805 			uintptr_t s1 = regs[r1];
5806 			uintptr_t s2 = regs[r2];
5807 
5808 			if (s1 != NULL &&
5809 			    !dtrace_strcanload(s1, sz, mstate, vstate))
5810 				break;
5811 			if (s2 != NULL &&
5812 			    !dtrace_strcanload(s2, sz, mstate, vstate))
5813 				break;
5814 
5815 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5816 
5817 			cc_n = cc_r < 0;
5818 			cc_z = cc_r == 0;
5819 			cc_v = cc_c = 0;
5820 			break;
5821 		}
5822 		case DIF_OP_LDGA:
5823 			regs[rd] = dtrace_dif_variable(mstate, state,
5824 			    r1, regs[r2]);
5825 			break;
5826 		case DIF_OP_LDGS:
5827 			id = DIF_INSTR_VAR(instr);
5828 
5829 			if (id >= DIF_VAR_OTHER_UBASE) {
5830 				uintptr_t a;
5831 
5832 				id -= DIF_VAR_OTHER_UBASE;
5833 				svar = vstate->dtvs_globals[id];
5834 				ASSERT(svar != NULL);
5835 				v = &svar->dtsv_var;
5836 
5837 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5838 					regs[rd] = svar->dtsv_data;
5839 					break;
5840 				}
5841 
5842 				a = (uintptr_t)svar->dtsv_data;
5843 
5844 				if (*(uint8_t *)a == UINT8_MAX) {
5845 					/*
5846 					 * If the 0th byte is set to UINT8_MAX
5847 					 * then this is to be treated as a
5848 					 * reference to a NULL variable.
5849 					 */
5850 					regs[rd] = NULL;
5851 				} else {
5852 					regs[rd] = a + sizeof (uint64_t);
5853 				}
5854 
5855 				break;
5856 			}
5857 
5858 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5859 			break;
5860 
5861 		case DIF_OP_STGS:
5862 			id = DIF_INSTR_VAR(instr);
5863 
5864 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5865 			id -= DIF_VAR_OTHER_UBASE;
5866 
5867 			svar = vstate->dtvs_globals[id];
5868 			ASSERT(svar != NULL);
5869 			v = &svar->dtsv_var;
5870 
5871 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5872 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5873 
5874 				ASSERT(a != NULL);
5875 				ASSERT(svar->dtsv_size != 0);
5876 
5877 				if (regs[rd] == NULL) {
5878 					*(uint8_t *)a = UINT8_MAX;
5879 					break;
5880 				} else {
5881 					*(uint8_t *)a = 0;
5882 					a += sizeof (uint64_t);
5883 				}
5884 				if (!dtrace_vcanload(
5885 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5886 				    mstate, vstate))
5887 					break;
5888 
5889 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5890 				    (void *)a, &v->dtdv_type);
5891 				break;
5892 			}
5893 
5894 			svar->dtsv_data = regs[rd];
5895 			break;
5896 
5897 		case DIF_OP_LDTA:
5898 			/*
5899 			 * There are no DTrace built-in thread-local arrays at
5900 			 * present.  This opcode is saved for future work.
5901 			 */
5902 			*flags |= CPU_DTRACE_ILLOP;
5903 			regs[rd] = 0;
5904 			break;
5905 
5906 		case DIF_OP_LDLS:
5907 			id = DIF_INSTR_VAR(instr);
5908 
5909 			if (id < DIF_VAR_OTHER_UBASE) {
5910 				/*
5911 				 * For now, this has no meaning.
5912 				 */
5913 				regs[rd] = 0;
5914 				break;
5915 			}
5916 
5917 			id -= DIF_VAR_OTHER_UBASE;
5918 
5919 			ASSERT(id < vstate->dtvs_nlocals);
5920 			ASSERT(vstate->dtvs_locals != NULL);
5921 
5922 			svar = vstate->dtvs_locals[id];
5923 			ASSERT(svar != NULL);
5924 			v = &svar->dtsv_var;
5925 
5926 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5927 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5928 				size_t sz = v->dtdv_type.dtdt_size;
5929 
5930 				sz += sizeof (uint64_t);
5931 				ASSERT(svar->dtsv_size == NCPU * sz);
5932 				a += CPU->cpu_id * sz;
5933 
5934 				if (*(uint8_t *)a == UINT8_MAX) {
5935 					/*
5936 					 * If the 0th byte is set to UINT8_MAX
5937 					 * then this is to be treated as a
5938 					 * reference to a NULL variable.
5939 					 */
5940 					regs[rd] = NULL;
5941 				} else {
5942 					regs[rd] = a + sizeof (uint64_t);
5943 				}
5944 
5945 				break;
5946 			}
5947 
5948 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5949 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5950 			regs[rd] = tmp[CPU->cpu_id];
5951 			break;
5952 
5953 		case DIF_OP_STLS:
5954 			id = DIF_INSTR_VAR(instr);
5955 
5956 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5957 			id -= DIF_VAR_OTHER_UBASE;
5958 			ASSERT(id < vstate->dtvs_nlocals);
5959 
5960 			ASSERT(vstate->dtvs_locals != NULL);
5961 			svar = vstate->dtvs_locals[id];
5962 			ASSERT(svar != NULL);
5963 			v = &svar->dtsv_var;
5964 
5965 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5966 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5967 				size_t sz = v->dtdv_type.dtdt_size;
5968 
5969 				sz += sizeof (uint64_t);
5970 				ASSERT(svar->dtsv_size == NCPU * sz);
5971 				a += CPU->cpu_id * sz;
5972 
5973 				if (regs[rd] == NULL) {
5974 					*(uint8_t *)a = UINT8_MAX;
5975 					break;
5976 				} else {
5977 					*(uint8_t *)a = 0;
5978 					a += sizeof (uint64_t);
5979 				}
5980 
5981 				if (!dtrace_vcanload(
5982 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5983 				    mstate, vstate))
5984 					break;
5985 
5986 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5987 				    (void *)a, &v->dtdv_type);
5988 				break;
5989 			}
5990 
5991 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5992 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5993 			tmp[CPU->cpu_id] = regs[rd];
5994 			break;
5995 
5996 		case DIF_OP_LDTS: {
5997 			dtrace_dynvar_t *dvar;
5998 			dtrace_key_t *key;
5999 
6000 			id = DIF_INSTR_VAR(instr);
6001 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6002 			id -= DIF_VAR_OTHER_UBASE;
6003 			v = &vstate->dtvs_tlocals[id];
6004 
6005 			key = &tupregs[DIF_DTR_NREGS];
6006 			key[0].dttk_value = (uint64_t)id;
6007 			key[0].dttk_size = 0;
6008 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6009 			key[1].dttk_size = 0;
6010 
6011 			dvar = dtrace_dynvar(dstate, 2, key,
6012 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6013 			    mstate, vstate);
6014 
6015 			if (dvar == NULL) {
6016 				regs[rd] = 0;
6017 				break;
6018 			}
6019 
6020 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6021 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6022 			} else {
6023 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6024 			}
6025 
6026 			break;
6027 		}
6028 
6029 		case DIF_OP_STTS: {
6030 			dtrace_dynvar_t *dvar;
6031 			dtrace_key_t *key;
6032 
6033 			id = DIF_INSTR_VAR(instr);
6034 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6035 			id -= DIF_VAR_OTHER_UBASE;
6036 
6037 			key = &tupregs[DIF_DTR_NREGS];
6038 			key[0].dttk_value = (uint64_t)id;
6039 			key[0].dttk_size = 0;
6040 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6041 			key[1].dttk_size = 0;
6042 			v = &vstate->dtvs_tlocals[id];
6043 
6044 			dvar = dtrace_dynvar(dstate, 2, key,
6045 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6046 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6047 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6048 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6049 
6050 			/*
6051 			 * Given that we're storing to thread-local data,
6052 			 * we need to flush our predicate cache.
6053 			 */
6054 			curthread->t_predcache = NULL;
6055 
6056 			if (dvar == NULL)
6057 				break;
6058 
6059 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6060 				if (!dtrace_vcanload(
6061 				    (void *)(uintptr_t)regs[rd],
6062 				    &v->dtdv_type, mstate, vstate))
6063 					break;
6064 
6065 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6066 				    dvar->dtdv_data, &v->dtdv_type);
6067 			} else {
6068 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6069 			}
6070 
6071 			break;
6072 		}
6073 
6074 		case DIF_OP_SRA:
6075 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6076 			break;
6077 
6078 		case DIF_OP_CALL:
6079 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6080 			    regs, tupregs, ttop, mstate, state);
6081 			break;
6082 
6083 		case DIF_OP_PUSHTR:
6084 			if (ttop == DIF_DTR_NREGS) {
6085 				*flags |= CPU_DTRACE_TUPOFLOW;
6086 				break;
6087 			}
6088 
6089 			if (r1 == DIF_TYPE_STRING) {
6090 				/*
6091 				 * If this is a string type and the size is 0,
6092 				 * we'll use the system-wide default string
6093 				 * size.  Note that we are _not_ looking at
6094 				 * the value of the DTRACEOPT_STRSIZE option;
6095 				 * had this been set, we would expect to have
6096 				 * a non-zero size value in the "pushtr".
6097 				 */
6098 				tupregs[ttop].dttk_size =
6099 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6100 				    regs[r2] ? regs[r2] :
6101 				    dtrace_strsize_default) + 1;
6102 			} else {
6103 				if (regs[r2] > LONG_MAX) {
6104 					*flags |= CPU_DTRACE_ILLOP;
6105 					break;
6106 				}
6107 
6108 				tupregs[ttop].dttk_size = regs[r2];
6109 			}
6110 
6111 			tupregs[ttop++].dttk_value = regs[rd];
6112 			break;
6113 
6114 		case DIF_OP_PUSHTV:
6115 			if (ttop == DIF_DTR_NREGS) {
6116 				*flags |= CPU_DTRACE_TUPOFLOW;
6117 				break;
6118 			}
6119 
6120 			tupregs[ttop].dttk_value = regs[rd];
6121 			tupregs[ttop++].dttk_size = 0;
6122 			break;
6123 
6124 		case DIF_OP_POPTS:
6125 			if (ttop != 0)
6126 				ttop--;
6127 			break;
6128 
6129 		case DIF_OP_FLUSHTS:
6130 			ttop = 0;
6131 			break;
6132 
6133 		case DIF_OP_LDGAA:
6134 		case DIF_OP_LDTAA: {
6135 			dtrace_dynvar_t *dvar;
6136 			dtrace_key_t *key = tupregs;
6137 			uint_t nkeys = ttop;
6138 
6139 			id = DIF_INSTR_VAR(instr);
6140 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6141 			id -= DIF_VAR_OTHER_UBASE;
6142 
6143 			key[nkeys].dttk_value = (uint64_t)id;
6144 			key[nkeys++].dttk_size = 0;
6145 
6146 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6147 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6148 				key[nkeys++].dttk_size = 0;
6149 				v = &vstate->dtvs_tlocals[id];
6150 			} else {
6151 				v = &vstate->dtvs_globals[id]->dtsv_var;
6152 			}
6153 
6154 			dvar = dtrace_dynvar(dstate, nkeys, key,
6155 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6156 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6157 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6158 
6159 			if (dvar == NULL) {
6160 				regs[rd] = 0;
6161 				break;
6162 			}
6163 
6164 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6165 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6166 			} else {
6167 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6168 			}
6169 
6170 			break;
6171 		}
6172 
6173 		case DIF_OP_STGAA:
6174 		case DIF_OP_STTAA: {
6175 			dtrace_dynvar_t *dvar;
6176 			dtrace_key_t *key = tupregs;
6177 			uint_t nkeys = ttop;
6178 
6179 			id = DIF_INSTR_VAR(instr);
6180 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6181 			id -= DIF_VAR_OTHER_UBASE;
6182 
6183 			key[nkeys].dttk_value = (uint64_t)id;
6184 			key[nkeys++].dttk_size = 0;
6185 
6186 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6187 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6188 				key[nkeys++].dttk_size = 0;
6189 				v = &vstate->dtvs_tlocals[id];
6190 			} else {
6191 				v = &vstate->dtvs_globals[id]->dtsv_var;
6192 			}
6193 
6194 			dvar = dtrace_dynvar(dstate, nkeys, key,
6195 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6196 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6197 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6198 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6199 
6200 			if (dvar == NULL)
6201 				break;
6202 
6203 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6204 				if (!dtrace_vcanload(
6205 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6206 				    mstate, vstate))
6207 					break;
6208 
6209 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6210 				    dvar->dtdv_data, &v->dtdv_type);
6211 			} else {
6212 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6213 			}
6214 
6215 			break;
6216 		}
6217 
6218 		case DIF_OP_ALLOCS: {
6219 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6220 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6221 
6222 			/*
6223 			 * Rounding up the user allocation size could have
6224 			 * overflowed large, bogus allocations (like -1ULL) to
6225 			 * 0.
6226 			 */
6227 			if (size < regs[r1] ||
6228 			    !DTRACE_INSCRATCH(mstate, size)) {
6229 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6230 				regs[rd] = NULL;
6231 				break;
6232 			}
6233 
6234 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6235 			mstate->dtms_scratch_ptr += size;
6236 			regs[rd] = ptr;
6237 			break;
6238 		}
6239 
6240 		case DIF_OP_COPYS:
6241 			if (!dtrace_canstore(regs[rd], regs[r2],
6242 			    mstate, vstate)) {
6243 				*flags |= CPU_DTRACE_BADADDR;
6244 				*illval = regs[rd];
6245 				break;
6246 			}
6247 
6248 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6249 				break;
6250 
6251 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6252 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6253 			break;
6254 
6255 		case DIF_OP_STB:
6256 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6257 				*flags |= CPU_DTRACE_BADADDR;
6258 				*illval = regs[rd];
6259 				break;
6260 			}
6261 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6262 			break;
6263 
6264 		case DIF_OP_STH:
6265 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6266 				*flags |= CPU_DTRACE_BADADDR;
6267 				*illval = regs[rd];
6268 				break;
6269 			}
6270 			if (regs[rd] & 1) {
6271 				*flags |= CPU_DTRACE_BADALIGN;
6272 				*illval = regs[rd];
6273 				break;
6274 			}
6275 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6276 			break;
6277 
6278 		case DIF_OP_STW:
6279 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6280 				*flags |= CPU_DTRACE_BADADDR;
6281 				*illval = regs[rd];
6282 				break;
6283 			}
6284 			if (regs[rd] & 3) {
6285 				*flags |= CPU_DTRACE_BADALIGN;
6286 				*illval = regs[rd];
6287 				break;
6288 			}
6289 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6290 			break;
6291 
6292 		case DIF_OP_STX:
6293 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6294 				*flags |= CPU_DTRACE_BADADDR;
6295 				*illval = regs[rd];
6296 				break;
6297 			}
6298 			if (regs[rd] & 7) {
6299 				*flags |= CPU_DTRACE_BADALIGN;
6300 				*illval = regs[rd];
6301 				break;
6302 			}
6303 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6304 			break;
6305 		}
6306 	}
6307 
6308 	if (!(*flags & CPU_DTRACE_FAULT))
6309 		return (rval);
6310 
6311 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6312 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6313 
6314 	return (0);
6315 }
6316 
6317 static void
6318 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6319 {
6320 	dtrace_probe_t *probe = ecb->dte_probe;
6321 	dtrace_provider_t *prov = probe->dtpr_provider;
6322 	char c[DTRACE_FULLNAMELEN + 80], *str;
6323 	char *msg = "dtrace: breakpoint action at probe ";
6324 	char *ecbmsg = " (ecb ";
6325 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6326 	uintptr_t val = (uintptr_t)ecb;
6327 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6328 
6329 	if (dtrace_destructive_disallow)
6330 		return;
6331 
6332 	/*
6333 	 * It's impossible to be taking action on the NULL probe.
6334 	 */
6335 	ASSERT(probe != NULL);
6336 
6337 	/*
6338 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6339 	 * print the provider name, module name, function name and name of
6340 	 * the probe, along with the hex address of the ECB with the breakpoint
6341 	 * action -- all of which we must place in the character buffer by
6342 	 * hand.
6343 	 */
6344 	while (*msg != '\0')
6345 		c[i++] = *msg++;
6346 
6347 	for (str = prov->dtpv_name; *str != '\0'; str++)
6348 		c[i++] = *str;
6349 	c[i++] = ':';
6350 
6351 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6352 		c[i++] = *str;
6353 	c[i++] = ':';
6354 
6355 	for (str = probe->dtpr_func; *str != '\0'; str++)
6356 		c[i++] = *str;
6357 	c[i++] = ':';
6358 
6359 	for (str = probe->dtpr_name; *str != '\0'; str++)
6360 		c[i++] = *str;
6361 
6362 	while (*ecbmsg != '\0')
6363 		c[i++] = *ecbmsg++;
6364 
6365 	while (shift >= 0) {
6366 		mask = (uintptr_t)0xf << shift;
6367 
6368 		if (val >= ((uintptr_t)1 << shift))
6369 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6370 		shift -= 4;
6371 	}
6372 
6373 	c[i++] = ')';
6374 	c[i] = '\0';
6375 
6376 	debug_enter(c);
6377 }
6378 
6379 static void
6380 dtrace_action_panic(dtrace_ecb_t *ecb)
6381 {
6382 	dtrace_probe_t *probe = ecb->dte_probe;
6383 
6384 	/*
6385 	 * It's impossible to be taking action on the NULL probe.
6386 	 */
6387 	ASSERT(probe != NULL);
6388 
6389 	if (dtrace_destructive_disallow)
6390 		return;
6391 
6392 	if (dtrace_panicked != NULL)
6393 		return;
6394 
6395 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6396 		return;
6397 
6398 	/*
6399 	 * We won the right to panic.  (We want to be sure that only one
6400 	 * thread calls panic() from dtrace_probe(), and that panic() is
6401 	 * called exactly once.)
6402 	 */
6403 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6404 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6405 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6406 }
6407 
6408 static void
6409 dtrace_action_raise(uint64_t sig)
6410 {
6411 	if (dtrace_destructive_disallow)
6412 		return;
6413 
6414 	if (sig >= NSIG) {
6415 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6416 		return;
6417 	}
6418 
6419 	/*
6420 	 * raise() has a queue depth of 1 -- we ignore all subsequent
6421 	 * invocations of the raise() action.
6422 	 */
6423 	if (curthread->t_dtrace_sig == 0)
6424 		curthread->t_dtrace_sig = (uint8_t)sig;
6425 
6426 	curthread->t_sig_check = 1;
6427 	aston(curthread);
6428 }
6429 
6430 static void
6431 dtrace_action_stop(void)
6432 {
6433 	if (dtrace_destructive_disallow)
6434 		return;
6435 
6436 	if (!curthread->t_dtrace_stop) {
6437 		curthread->t_dtrace_stop = 1;
6438 		curthread->t_sig_check = 1;
6439 		aston(curthread);
6440 	}
6441 }
6442 
6443 static void
6444 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6445 {
6446 	hrtime_t now;
6447 	volatile uint16_t *flags;
6448 	cpu_t *cpu = CPU;
6449 
6450 	if (dtrace_destructive_disallow)
6451 		return;
6452 
6453 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6454 
6455 	now = dtrace_gethrtime();
6456 
6457 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6458 		/*
6459 		 * We need to advance the mark to the current time.
6460 		 */
6461 		cpu->cpu_dtrace_chillmark = now;
6462 		cpu->cpu_dtrace_chilled = 0;
6463 	}
6464 
6465 	/*
6466 	 * Now check to see if the requested chill time would take us over
6467 	 * the maximum amount of time allowed in the chill interval.  (Or
6468 	 * worse, if the calculation itself induces overflow.)
6469 	 */
6470 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6471 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6472 		*flags |= CPU_DTRACE_ILLOP;
6473 		return;
6474 	}
6475 
6476 	while (dtrace_gethrtime() - now < val)
6477 		continue;
6478 
6479 	/*
6480 	 * Normally, we assure that the value of the variable "timestamp" does
6481 	 * not change within an ECB.  The presence of chill() represents an
6482 	 * exception to this rule, however.
6483 	 */
6484 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6485 	cpu->cpu_dtrace_chilled += val;
6486 }
6487 
6488 static void
6489 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6490     uint64_t *buf, uint64_t arg)
6491 {
6492 	int nframes = DTRACE_USTACK_NFRAMES(arg);
6493 	int strsize = DTRACE_USTACK_STRSIZE(arg);
6494 	uint64_t *pcs = &buf[1], *fps;
6495 	char *str = (char *)&pcs[nframes];
6496 	int size, offs = 0, i, j;
6497 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
6498 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6499 	char *sym;
6500 
6501 	/*
6502 	 * Should be taking a faster path if string space has not been
6503 	 * allocated.
6504 	 */
6505 	ASSERT(strsize != 0);
6506 
6507 	/*
6508 	 * We will first allocate some temporary space for the frame pointers.
6509 	 */
6510 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6511 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6512 	    (nframes * sizeof (uint64_t));
6513 
6514 	if (!DTRACE_INSCRATCH(mstate, size)) {
6515 		/*
6516 		 * Not enough room for our frame pointers -- need to indicate
6517 		 * that we ran out of scratch space.
6518 		 */
6519 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6520 		return;
6521 	}
6522 
6523 	mstate->dtms_scratch_ptr += size;
6524 	saved = mstate->dtms_scratch_ptr;
6525 
6526 	/*
6527 	 * Now get a stack with both program counters and frame pointers.
6528 	 */
6529 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6530 	dtrace_getufpstack(buf, fps, nframes + 1);
6531 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6532 
6533 	/*
6534 	 * If that faulted, we're cooked.
6535 	 */
6536 	if (*flags & CPU_DTRACE_FAULT)
6537 		goto out;
6538 
6539 	/*
6540 	 * Now we want to walk up the stack, calling the USTACK helper.  For
6541 	 * each iteration, we restore the scratch pointer.
6542 	 */
6543 	for (i = 0; i < nframes; i++) {
6544 		mstate->dtms_scratch_ptr = saved;
6545 
6546 		if (offs >= strsize)
6547 			break;
6548 
6549 		sym = (char *)(uintptr_t)dtrace_helper(
6550 		    DTRACE_HELPER_ACTION_USTACK,
6551 		    mstate, state, pcs[i], fps[i]);
6552 
6553 		/*
6554 		 * If we faulted while running the helper, we're going to
6555 		 * clear the fault and null out the corresponding string.
6556 		 */
6557 		if (*flags & CPU_DTRACE_FAULT) {
6558 			*flags &= ~CPU_DTRACE_FAULT;
6559 			str[offs++] = '\0';
6560 			continue;
6561 		}
6562 
6563 		if (sym == NULL) {
6564 			str[offs++] = '\0';
6565 			continue;
6566 		}
6567 
6568 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6569 
6570 		/*
6571 		 * Now copy in the string that the helper returned to us.
6572 		 */
6573 		for (j = 0; offs + j < strsize; j++) {
6574 			if ((str[offs + j] = sym[j]) == '\0')
6575 				break;
6576 		}
6577 
6578 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6579 
6580 		offs += j + 1;
6581 	}
6582 
6583 	if (offs >= strsize) {
6584 		/*
6585 		 * If we didn't have room for all of the strings, we don't
6586 		 * abort processing -- this needn't be a fatal error -- but we
6587 		 * still want to increment a counter (dts_stkstroverflows) to
6588 		 * allow this condition to be warned about.  (If this is from
6589 		 * a jstack() action, it is easily tuned via jstackstrsize.)
6590 		 */
6591 		dtrace_error(&state->dts_stkstroverflows);
6592 	}
6593 
6594 	while (offs < strsize)
6595 		str[offs++] = '\0';
6596 
6597 out:
6598 	mstate->dtms_scratch_ptr = old;
6599 }
6600 
6601 static void
6602 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
6603     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
6604 {
6605 	volatile uint16_t *flags;
6606 	uint64_t val = *valp;
6607 	size_t valoffs = *valoffsp;
6608 
6609 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6610 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
6611 
6612 	/*
6613 	 * If this is a string, we're going to only load until we find the zero
6614 	 * byte -- after which we'll store zero bytes.
6615 	 */
6616 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
6617 		char c = '\0' + 1;
6618 		size_t s;
6619 
6620 		for (s = 0; s < size; s++) {
6621 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
6622 				c = dtrace_load8(val++);
6623 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
6624 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6625 				c = dtrace_fuword8((void *)(uintptr_t)val++);
6626 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6627 				if (*flags & CPU_DTRACE_FAULT)
6628 					break;
6629 			}
6630 
6631 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
6632 
6633 			if (c == '\0' && intuple)
6634 				break;
6635 		}
6636 	} else {
6637 		uint8_t c;
6638 		while (valoffs < end) {
6639 			if (dtkind == DIF_TF_BYREF) {
6640 				c = dtrace_load8(val++);
6641 			} else if (dtkind == DIF_TF_BYUREF) {
6642 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6643 				c = dtrace_fuword8((void *)(uintptr_t)val++);
6644 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6645 				if (*flags & CPU_DTRACE_FAULT)
6646 					break;
6647 			}
6648 
6649 			DTRACE_STORE(uint8_t, tomax,
6650 			    valoffs++, c);
6651 		}
6652 	}
6653 
6654 	*valp = val;
6655 	*valoffsp = valoffs;
6656 }
6657 
6658 /*
6659  * If you're looking for the epicenter of DTrace, you just found it.  This
6660  * is the function called by the provider to fire a probe -- from which all
6661  * subsequent probe-context DTrace activity emanates.
6662  */
6663 void
6664 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6665     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6666 {
6667 	processorid_t cpuid;
6668 	dtrace_icookie_t cookie;
6669 	dtrace_probe_t *probe;
6670 	dtrace_mstate_t mstate;
6671 	dtrace_ecb_t *ecb;
6672 	dtrace_action_t *act;
6673 	intptr_t offs;
6674 	size_t size;
6675 	int vtime, onintr;
6676 	volatile uint16_t *flags;
6677 	hrtime_t now, end;
6678 
6679 	/*
6680 	 * Kick out immediately if this CPU is still being born (in which case
6681 	 * curthread will be set to -1) or the current thread can't allow
6682 	 * probes in its current context.
6683 	 */
6684 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6685 		return;
6686 
6687 	cookie = dtrace_interrupt_disable();
6688 	probe = dtrace_probes[id - 1];
6689 	cpuid = CPU->cpu_id;
6690 	onintr = CPU_ON_INTR(CPU);
6691 
6692 	CPU->cpu_dtrace_probes++;
6693 
6694 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6695 	    probe->dtpr_predcache == curthread->t_predcache) {
6696 		/*
6697 		 * We have hit in the predicate cache; we know that
6698 		 * this predicate would evaluate to be false.
6699 		 */
6700 		dtrace_interrupt_enable(cookie);
6701 		return;
6702 	}
6703 
6704 	if (panic_quiesce) {
6705 		/*
6706 		 * We don't trace anything if we're panicking.
6707 		 */
6708 		dtrace_interrupt_enable(cookie);
6709 		return;
6710 	}
6711 
6712 	now = mstate.dtms_timestamp = dtrace_gethrtime();
6713 	mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6714 	vtime = dtrace_vtime_references != 0;
6715 
6716 	if (vtime && curthread->t_dtrace_start)
6717 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6718 
6719 	mstate.dtms_difo = NULL;
6720 	mstate.dtms_probe = probe;
6721 	mstate.dtms_strtok = NULL;
6722 	mstate.dtms_arg[0] = arg0;
6723 	mstate.dtms_arg[1] = arg1;
6724 	mstate.dtms_arg[2] = arg2;
6725 	mstate.dtms_arg[3] = arg3;
6726 	mstate.dtms_arg[4] = arg4;
6727 
6728 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6729 
6730 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6731 		dtrace_predicate_t *pred = ecb->dte_predicate;
6732 		dtrace_state_t *state = ecb->dte_state;
6733 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6734 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6735 		dtrace_vstate_t *vstate = &state->dts_vstate;
6736 		dtrace_provider_t *prov = probe->dtpr_provider;
6737 		uint64_t tracememsize = 0;
6738 		int committed = 0;
6739 		caddr_t tomax;
6740 
6741 		/*
6742 		 * A little subtlety with the following (seemingly innocuous)
6743 		 * declaration of the automatic 'val':  by looking at the
6744 		 * code, you might think that it could be declared in the
6745 		 * action processing loop, below.  (That is, it's only used in
6746 		 * the action processing loop.)  However, it must be declared
6747 		 * out of that scope because in the case of DIF expression
6748 		 * arguments to aggregating actions, one iteration of the
6749 		 * action loop will use the last iteration's value.
6750 		 */
6751 #ifdef lint
6752 		uint64_t val = 0;
6753 #else
6754 		uint64_t val;
6755 #endif
6756 
6757 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
6758 		mstate.dtms_access = DTRACE_ACCESS_ARGS | DTRACE_ACCESS_PROC;
6759 		mstate.dtms_getf = NULL;
6760 
6761 		*flags &= ~CPU_DTRACE_ERROR;
6762 
6763 		if (prov == dtrace_provider) {
6764 			/*
6765 			 * If dtrace itself is the provider of this probe,
6766 			 * we're only going to continue processing the ECB if
6767 			 * arg0 (the dtrace_state_t) is equal to the ECB's
6768 			 * creating state.  (This prevents disjoint consumers
6769 			 * from seeing one another's metaprobes.)
6770 			 */
6771 			if (arg0 != (uint64_t)(uintptr_t)state)
6772 				continue;
6773 		}
6774 
6775 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
6776 			/*
6777 			 * We're not currently active.  If our provider isn't
6778 			 * the dtrace pseudo provider, we're not interested.
6779 			 */
6780 			if (prov != dtrace_provider)
6781 				continue;
6782 
6783 			/*
6784 			 * Now we must further check if we are in the BEGIN
6785 			 * probe.  If we are, we will only continue processing
6786 			 * if we're still in WARMUP -- if one BEGIN enabling
6787 			 * has invoked the exit() action, we don't want to
6788 			 * evaluate subsequent BEGIN enablings.
6789 			 */
6790 			if (probe->dtpr_id == dtrace_probeid_begin &&
6791 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
6792 				ASSERT(state->dts_activity ==
6793 				    DTRACE_ACTIVITY_DRAINING);
6794 				continue;
6795 			}
6796 		}
6797 
6798 		if (ecb->dte_cond && !dtrace_priv_probe(state, &mstate, ecb))
6799 			continue;
6800 
6801 		if (now - state->dts_alive > dtrace_deadman_timeout) {
6802 			/*
6803 			 * We seem to be dead.  Unless we (a) have kernel
6804 			 * destructive permissions (b) have explicitly enabled
6805 			 * destructive actions and (c) destructive actions have
6806 			 * not been disabled, we're going to transition into
6807 			 * the KILLED state, from which no further processing
6808 			 * on this state will be performed.
6809 			 */
6810 			if (!dtrace_priv_kernel_destructive(state) ||
6811 			    !state->dts_cred.dcr_destructive ||
6812 			    dtrace_destructive_disallow) {
6813 				void *activity = &state->dts_activity;
6814 				dtrace_activity_t current;
6815 
6816 				do {
6817 					current = state->dts_activity;
6818 				} while (dtrace_cas32(activity, current,
6819 				    DTRACE_ACTIVITY_KILLED) != current);
6820 
6821 				continue;
6822 			}
6823 		}
6824 
6825 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
6826 		    ecb->dte_alignment, state, &mstate)) < 0)
6827 			continue;
6828 
6829 		tomax = buf->dtb_tomax;
6830 		ASSERT(tomax != NULL);
6831 
6832 		if (ecb->dte_size != 0) {
6833 			dtrace_rechdr_t dtrh;
6834 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
6835 				mstate.dtms_timestamp = dtrace_gethrtime();
6836 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6837 			}
6838 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
6839 			dtrh.dtrh_epid = ecb->dte_epid;
6840 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
6841 			    mstate.dtms_timestamp);
6842 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
6843 		}
6844 
6845 		mstate.dtms_epid = ecb->dte_epid;
6846 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
6847 
6848 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
6849 			mstate.dtms_access |= DTRACE_ACCESS_KERNEL;
6850 
6851 		if (pred != NULL) {
6852 			dtrace_difo_t *dp = pred->dtp_difo;
6853 			int rval;
6854 
6855 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
6856 
6857 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
6858 				dtrace_cacheid_t cid = probe->dtpr_predcache;
6859 
6860 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
6861 					/*
6862 					 * Update the predicate cache...
6863 					 */
6864 					ASSERT(cid == pred->dtp_cacheid);
6865 					curthread->t_predcache = cid;
6866 				}
6867 
6868 				continue;
6869 			}
6870 		}
6871 
6872 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6873 		    act != NULL; act = act->dta_next) {
6874 			size_t valoffs;
6875 			dtrace_difo_t *dp;
6876 			dtrace_recdesc_t *rec = &act->dta_rec;
6877 
6878 			size = rec->dtrd_size;
6879 			valoffs = offs + rec->dtrd_offset;
6880 
6881 			if (DTRACEACT_ISAGG(act->dta_kind)) {
6882 				uint64_t v = 0xbad;
6883 				dtrace_aggregation_t *agg;
6884 
6885 				agg = (dtrace_aggregation_t *)act;
6886 
6887 				if ((dp = act->dta_difo) != NULL)
6888 					v = dtrace_dif_emulate(dp,
6889 					    &mstate, vstate, state);
6890 
6891 				if (*flags & CPU_DTRACE_ERROR)
6892 					continue;
6893 
6894 				/*
6895 				 * Note that we always pass the expression
6896 				 * value from the previous iteration of the
6897 				 * action loop.  This value will only be used
6898 				 * if there is an expression argument to the
6899 				 * aggregating action, denoted by the
6900 				 * dtag_hasarg field.
6901 				 */
6902 				dtrace_aggregate(agg, buf,
6903 				    offs, aggbuf, v, val);
6904 				continue;
6905 			}
6906 
6907 			switch (act->dta_kind) {
6908 			case DTRACEACT_STOP:
6909 				if (dtrace_priv_proc_destructive(state,
6910 				    &mstate))
6911 					dtrace_action_stop();
6912 				continue;
6913 
6914 			case DTRACEACT_BREAKPOINT:
6915 				if (dtrace_priv_kernel_destructive(state))
6916 					dtrace_action_breakpoint(ecb);
6917 				continue;
6918 
6919 			case DTRACEACT_PANIC:
6920 				if (dtrace_priv_kernel_destructive(state))
6921 					dtrace_action_panic(ecb);
6922 				continue;
6923 
6924 			case DTRACEACT_STACK:
6925 				if (!dtrace_priv_kernel(state))
6926 					continue;
6927 
6928 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
6929 				    size / sizeof (pc_t), probe->dtpr_aframes,
6930 				    DTRACE_ANCHORED(probe) ? NULL :
6931 				    (uint32_t *)arg0);
6932 
6933 				continue;
6934 
6935 			case DTRACEACT_JSTACK:
6936 			case DTRACEACT_USTACK:
6937 				if (!dtrace_priv_proc(state, &mstate))
6938 					continue;
6939 
6940 				/*
6941 				 * See comment in DIF_VAR_PID.
6942 				 */
6943 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6944 				    CPU_ON_INTR(CPU)) {
6945 					int depth = DTRACE_USTACK_NFRAMES(
6946 					    rec->dtrd_arg) + 1;
6947 
6948 					dtrace_bzero((void *)(tomax + valoffs),
6949 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6950 					    + depth * sizeof (uint64_t));
6951 
6952 					continue;
6953 				}
6954 
6955 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6956 				    curproc->p_dtrace_helpers != NULL) {
6957 					/*
6958 					 * This is the slow path -- we have
6959 					 * allocated string space, and we're
6960 					 * getting the stack of a process that
6961 					 * has helpers.  Call into a separate
6962 					 * routine to perform this processing.
6963 					 */
6964 					dtrace_action_ustack(&mstate, state,
6965 					    (uint64_t *)(tomax + valoffs),
6966 					    rec->dtrd_arg);
6967 					continue;
6968 				}
6969 
6970 				/*
6971 				 * Clear the string space, since there's no
6972 				 * helper to do it for us.
6973 				 */
6974 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0) {
6975 					int depth = DTRACE_USTACK_NFRAMES(
6976 					    rec->dtrd_arg);
6977 					size_t strsize = DTRACE_USTACK_STRSIZE(
6978 					    rec->dtrd_arg);
6979 					uint64_t *buf = (uint64_t *)(tomax +
6980 					    valoffs);
6981 					void *strspace = &buf[depth + 1];
6982 
6983 					dtrace_bzero(strspace,
6984 					    MIN(depth, strsize));
6985 				}
6986 
6987 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6988 				dtrace_getupcstack((uint64_t *)
6989 				    (tomax + valoffs),
6990 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6991 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6992 				continue;
6993 
6994 			default:
6995 				break;
6996 			}
6997 
6998 			dp = act->dta_difo;
6999 			ASSERT(dp != NULL);
7000 
7001 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7002 
7003 			if (*flags & CPU_DTRACE_ERROR)
7004 				continue;
7005 
7006 			switch (act->dta_kind) {
7007 			case DTRACEACT_SPECULATE: {
7008 				dtrace_rechdr_t *dtrh;
7009 
7010 				ASSERT(buf == &state->dts_buffer[cpuid]);
7011 				buf = dtrace_speculation_buffer(state,
7012 				    cpuid, val);
7013 
7014 				if (buf == NULL) {
7015 					*flags |= CPU_DTRACE_DROP;
7016 					continue;
7017 				}
7018 
7019 				offs = dtrace_buffer_reserve(buf,
7020 				    ecb->dte_needed, ecb->dte_alignment,
7021 				    state, NULL);
7022 
7023 				if (offs < 0) {
7024 					*flags |= CPU_DTRACE_DROP;
7025 					continue;
7026 				}
7027 
7028 				tomax = buf->dtb_tomax;
7029 				ASSERT(tomax != NULL);
7030 
7031 				if (ecb->dte_size == 0)
7032 					continue;
7033 
7034 				ASSERT3U(ecb->dte_size, >=,
7035 				    sizeof (dtrace_rechdr_t));
7036 				dtrh = ((void *)(tomax + offs));
7037 				dtrh->dtrh_epid = ecb->dte_epid;
7038 				/*
7039 				 * When the speculation is committed, all of
7040 				 * the records in the speculative buffer will
7041 				 * have their timestamps set to the commit
7042 				 * time.  Until then, it is set to a sentinel
7043 				 * value, for debugability.
7044 				 */
7045 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7046 				continue;
7047 			}
7048 
7049 			case DTRACEACT_CHILL:
7050 				if (dtrace_priv_kernel_destructive(state))
7051 					dtrace_action_chill(&mstate, val);
7052 				continue;
7053 
7054 			case DTRACEACT_RAISE:
7055 				if (dtrace_priv_proc_destructive(state,
7056 				    &mstate))
7057 					dtrace_action_raise(val);
7058 				continue;
7059 
7060 			case DTRACEACT_COMMIT:
7061 				ASSERT(!committed);
7062 
7063 				/*
7064 				 * We need to commit our buffer state.
7065 				 */
7066 				if (ecb->dte_size)
7067 					buf->dtb_offset = offs + ecb->dte_size;
7068 				buf = &state->dts_buffer[cpuid];
7069 				dtrace_speculation_commit(state, cpuid, val);
7070 				committed = 1;
7071 				continue;
7072 
7073 			case DTRACEACT_DISCARD:
7074 				dtrace_speculation_discard(state, cpuid, val);
7075 				continue;
7076 
7077 			case DTRACEACT_DIFEXPR:
7078 			case DTRACEACT_LIBACT:
7079 			case DTRACEACT_PRINTF:
7080 			case DTRACEACT_PRINTA:
7081 			case DTRACEACT_SYSTEM:
7082 			case DTRACEACT_FREOPEN:
7083 			case DTRACEACT_TRACEMEM:
7084 				break;
7085 
7086 			case DTRACEACT_TRACEMEM_DYNSIZE:
7087 				tracememsize = val;
7088 				break;
7089 
7090 			case DTRACEACT_SYM:
7091 			case DTRACEACT_MOD:
7092 				if (!dtrace_priv_kernel(state))
7093 					continue;
7094 				break;
7095 
7096 			case DTRACEACT_USYM:
7097 			case DTRACEACT_UMOD:
7098 			case DTRACEACT_UADDR: {
7099 				struct pid *pid = curthread->t_procp->p_pidp;
7100 
7101 				if (!dtrace_priv_proc(state, &mstate))
7102 					continue;
7103 
7104 				DTRACE_STORE(uint64_t, tomax,
7105 				    valoffs, (uint64_t)pid->pid_id);
7106 				DTRACE_STORE(uint64_t, tomax,
7107 				    valoffs + sizeof (uint64_t), val);
7108 
7109 				continue;
7110 			}
7111 
7112 			case DTRACEACT_EXIT: {
7113 				/*
7114 				 * For the exit action, we are going to attempt
7115 				 * to atomically set our activity to be
7116 				 * draining.  If this fails (either because
7117 				 * another CPU has beat us to the exit action,
7118 				 * or because our current activity is something
7119 				 * other than ACTIVE or WARMUP), we will
7120 				 * continue.  This assures that the exit action
7121 				 * can be successfully recorded at most once
7122 				 * when we're in the ACTIVE state.  If we're
7123 				 * encountering the exit() action while in
7124 				 * COOLDOWN, however, we want to honor the new
7125 				 * status code.  (We know that we're the only
7126 				 * thread in COOLDOWN, so there is no race.)
7127 				 */
7128 				void *activity = &state->dts_activity;
7129 				dtrace_activity_t current = state->dts_activity;
7130 
7131 				if (current == DTRACE_ACTIVITY_COOLDOWN)
7132 					break;
7133 
7134 				if (current != DTRACE_ACTIVITY_WARMUP)
7135 					current = DTRACE_ACTIVITY_ACTIVE;
7136 
7137 				if (dtrace_cas32(activity, current,
7138 				    DTRACE_ACTIVITY_DRAINING) != current) {
7139 					*flags |= CPU_DTRACE_DROP;
7140 					continue;
7141 				}
7142 
7143 				break;
7144 			}
7145 
7146 			default:
7147 				ASSERT(0);
7148 			}
7149 
7150 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7151 			    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7152 				uintptr_t end = valoffs + size;
7153 
7154 				if (tracememsize != 0 &&
7155 				    valoffs + tracememsize < end) {
7156 					end = valoffs + tracememsize;
7157 					tracememsize = 0;
7158 				}
7159 
7160 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7161 				    !dtrace_vcanload((void *)(uintptr_t)val,
7162 				    &dp->dtdo_rtype, &mstate, vstate))
7163 					continue;
7164 
7165 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7166 				    &val, end, act->dta_intuple,
7167 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7168 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7169 				continue;
7170 			}
7171 
7172 			switch (size) {
7173 			case 0:
7174 				break;
7175 
7176 			case sizeof (uint8_t):
7177 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7178 				break;
7179 			case sizeof (uint16_t):
7180 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7181 				break;
7182 			case sizeof (uint32_t):
7183 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7184 				break;
7185 			case sizeof (uint64_t):
7186 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7187 				break;
7188 			default:
7189 				/*
7190 				 * Any other size should have been returned by
7191 				 * reference, not by value.
7192 				 */
7193 				ASSERT(0);
7194 				break;
7195 			}
7196 		}
7197 
7198 		if (*flags & CPU_DTRACE_DROP)
7199 			continue;
7200 
7201 		if (*flags & CPU_DTRACE_FAULT) {
7202 			int ndx;
7203 			dtrace_action_t *err;
7204 
7205 			buf->dtb_errors++;
7206 
7207 			if (probe->dtpr_id == dtrace_probeid_error) {
7208 				/*
7209 				 * There's nothing we can do -- we had an
7210 				 * error on the error probe.  We bump an
7211 				 * error counter to at least indicate that
7212 				 * this condition happened.
7213 				 */
7214 				dtrace_error(&state->dts_dblerrors);
7215 				continue;
7216 			}
7217 
7218 			if (vtime) {
7219 				/*
7220 				 * Before recursing on dtrace_probe(), we
7221 				 * need to explicitly clear out our start
7222 				 * time to prevent it from being accumulated
7223 				 * into t_dtrace_vtime.
7224 				 */
7225 				curthread->t_dtrace_start = 0;
7226 			}
7227 
7228 			/*
7229 			 * Iterate over the actions to figure out which action
7230 			 * we were processing when we experienced the error.
7231 			 * Note that act points _past_ the faulting action; if
7232 			 * act is ecb->dte_action, the fault was in the
7233 			 * predicate, if it's ecb->dte_action->dta_next it's
7234 			 * in action #1, and so on.
7235 			 */
7236 			for (err = ecb->dte_action, ndx = 0;
7237 			    err != act; err = err->dta_next, ndx++)
7238 				continue;
7239 
7240 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7241 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7242 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7243 			    cpu_core[cpuid].cpuc_dtrace_illval);
7244 
7245 			continue;
7246 		}
7247 
7248 		if (!committed)
7249 			buf->dtb_offset = offs + ecb->dte_size;
7250 	}
7251 
7252 	end = dtrace_gethrtime();
7253 	if (vtime)
7254 		curthread->t_dtrace_start = end;
7255 
7256 	CPU->cpu_dtrace_nsec += end - now;
7257 
7258 	dtrace_interrupt_enable(cookie);
7259 }
7260 
7261 /*
7262  * DTrace Probe Hashing Functions
7263  *
7264  * The functions in this section (and indeed, the functions in remaining
7265  * sections) are not _called_ from probe context.  (Any exceptions to this are
7266  * marked with a "Note:".)  Rather, they are called from elsewhere in the
7267  * DTrace framework to look-up probes in, add probes to and remove probes from
7268  * the DTrace probe hashes.  (Each probe is hashed by each element of the
7269  * probe tuple -- allowing for fast lookups, regardless of what was
7270  * specified.)
7271  */
7272 static uint_t
7273 dtrace_hash_str(char *p)
7274 {
7275 	unsigned int g;
7276 	uint_t hval = 0;
7277 
7278 	while (*p) {
7279 		hval = (hval << 4) + *p++;
7280 		if ((g = (hval & 0xf0000000)) != 0)
7281 			hval ^= g >> 24;
7282 		hval &= ~g;
7283 	}
7284 	return (hval);
7285 }
7286 
7287 static dtrace_hash_t *
7288 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7289 {
7290 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7291 
7292 	hash->dth_stroffs = stroffs;
7293 	hash->dth_nextoffs = nextoffs;
7294 	hash->dth_prevoffs = prevoffs;
7295 
7296 	hash->dth_size = 1;
7297 	hash->dth_mask = hash->dth_size - 1;
7298 
7299 	hash->dth_tab = kmem_zalloc(hash->dth_size *
7300 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7301 
7302 	return (hash);
7303 }
7304 
7305 static void
7306 dtrace_hash_destroy(dtrace_hash_t *hash)
7307 {
7308 #ifdef DEBUG
7309 	int i;
7310 
7311 	for (i = 0; i < hash->dth_size; i++)
7312 		ASSERT(hash->dth_tab[i] == NULL);
7313 #endif
7314 
7315 	kmem_free(hash->dth_tab,
7316 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
7317 	kmem_free(hash, sizeof (dtrace_hash_t));
7318 }
7319 
7320 static void
7321 dtrace_hash_resize(dtrace_hash_t *hash)
7322 {
7323 	int size = hash->dth_size, i, ndx;
7324 	int new_size = hash->dth_size << 1;
7325 	int new_mask = new_size - 1;
7326 	dtrace_hashbucket_t **new_tab, *bucket, *next;
7327 
7328 	ASSERT((new_size & new_mask) == 0);
7329 
7330 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7331 
7332 	for (i = 0; i < size; i++) {
7333 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7334 			dtrace_probe_t *probe = bucket->dthb_chain;
7335 
7336 			ASSERT(probe != NULL);
7337 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7338 
7339 			next = bucket->dthb_next;
7340 			bucket->dthb_next = new_tab[ndx];
7341 			new_tab[ndx] = bucket;
7342 		}
7343 	}
7344 
7345 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7346 	hash->dth_tab = new_tab;
7347 	hash->dth_size = new_size;
7348 	hash->dth_mask = new_mask;
7349 }
7350 
7351 static void
7352 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7353 {
7354 	int hashval = DTRACE_HASHSTR(hash, new);
7355 	int ndx = hashval & hash->dth_mask;
7356 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7357 	dtrace_probe_t **nextp, **prevp;
7358 
7359 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7360 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7361 			goto add;
7362 	}
7363 
7364 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7365 		dtrace_hash_resize(hash);
7366 		dtrace_hash_add(hash, new);
7367 		return;
7368 	}
7369 
7370 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7371 	bucket->dthb_next = hash->dth_tab[ndx];
7372 	hash->dth_tab[ndx] = bucket;
7373 	hash->dth_nbuckets++;
7374 
7375 add:
7376 	nextp = DTRACE_HASHNEXT(hash, new);
7377 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7378 	*nextp = bucket->dthb_chain;
7379 
7380 	if (bucket->dthb_chain != NULL) {
7381 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7382 		ASSERT(*prevp == NULL);
7383 		*prevp = new;
7384 	}
7385 
7386 	bucket->dthb_chain = new;
7387 	bucket->dthb_len++;
7388 }
7389 
7390 static dtrace_probe_t *
7391 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7392 {
7393 	int hashval = DTRACE_HASHSTR(hash, template);
7394 	int ndx = hashval & hash->dth_mask;
7395 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7396 
7397 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7398 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7399 			return (bucket->dthb_chain);
7400 	}
7401 
7402 	return (NULL);
7403 }
7404 
7405 static int
7406 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7407 {
7408 	int hashval = DTRACE_HASHSTR(hash, template);
7409 	int ndx = hashval & hash->dth_mask;
7410 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7411 
7412 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7413 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7414 			return (bucket->dthb_len);
7415 	}
7416 
7417 	return (NULL);
7418 }
7419 
7420 static void
7421 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7422 {
7423 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7424 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7425 
7426 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7427 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7428 
7429 	/*
7430 	 * Find the bucket that we're removing this probe from.
7431 	 */
7432 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7433 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7434 			break;
7435 	}
7436 
7437 	ASSERT(bucket != NULL);
7438 
7439 	if (*prevp == NULL) {
7440 		if (*nextp == NULL) {
7441 			/*
7442 			 * The removed probe was the only probe on this
7443 			 * bucket; we need to remove the bucket.
7444 			 */
7445 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7446 
7447 			ASSERT(bucket->dthb_chain == probe);
7448 			ASSERT(b != NULL);
7449 
7450 			if (b == bucket) {
7451 				hash->dth_tab[ndx] = bucket->dthb_next;
7452 			} else {
7453 				while (b->dthb_next != bucket)
7454 					b = b->dthb_next;
7455 				b->dthb_next = bucket->dthb_next;
7456 			}
7457 
7458 			ASSERT(hash->dth_nbuckets > 0);
7459 			hash->dth_nbuckets--;
7460 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7461 			return;
7462 		}
7463 
7464 		bucket->dthb_chain = *nextp;
7465 	} else {
7466 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7467 	}
7468 
7469 	if (*nextp != NULL)
7470 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7471 }
7472 
7473 /*
7474  * DTrace Utility Functions
7475  *
7476  * These are random utility functions that are _not_ called from probe context.
7477  */
7478 static int
7479 dtrace_badattr(const dtrace_attribute_t *a)
7480 {
7481 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
7482 	    a->dtat_data > DTRACE_STABILITY_MAX ||
7483 	    a->dtat_class > DTRACE_CLASS_MAX);
7484 }
7485 
7486 /*
7487  * Return a duplicate copy of a string.  If the specified string is NULL,
7488  * this function returns a zero-length string.
7489  */
7490 static char *
7491 dtrace_strdup(const char *str)
7492 {
7493 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7494 
7495 	if (str != NULL)
7496 		(void) strcpy(new, str);
7497 
7498 	return (new);
7499 }
7500 
7501 #define	DTRACE_ISALPHA(c)	\
7502 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7503 
7504 static int
7505 dtrace_badname(const char *s)
7506 {
7507 	char c;
7508 
7509 	if (s == NULL || (c = *s++) == '\0')
7510 		return (0);
7511 
7512 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7513 		return (1);
7514 
7515 	while ((c = *s++) != '\0') {
7516 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7517 		    c != '-' && c != '_' && c != '.' && c != '`')
7518 			return (1);
7519 	}
7520 
7521 	return (0);
7522 }
7523 
7524 static void
7525 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7526 {
7527 	uint32_t priv;
7528 
7529 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7530 		/*
7531 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7532 		 */
7533 		priv = DTRACE_PRIV_ALL;
7534 	} else {
7535 		*uidp = crgetuid(cr);
7536 		*zoneidp = crgetzoneid(cr);
7537 
7538 		priv = 0;
7539 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7540 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7541 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7542 			priv |= DTRACE_PRIV_USER;
7543 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7544 			priv |= DTRACE_PRIV_PROC;
7545 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7546 			priv |= DTRACE_PRIV_OWNER;
7547 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7548 			priv |= DTRACE_PRIV_ZONEOWNER;
7549 	}
7550 
7551 	*privp = priv;
7552 }
7553 
7554 #ifdef DTRACE_ERRDEBUG
7555 static void
7556 dtrace_errdebug(const char *str)
7557 {
7558 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
7559 	int occupied = 0;
7560 
7561 	mutex_enter(&dtrace_errlock);
7562 	dtrace_errlast = str;
7563 	dtrace_errthread = curthread;
7564 
7565 	while (occupied++ < DTRACE_ERRHASHSZ) {
7566 		if (dtrace_errhash[hval].dter_msg == str) {
7567 			dtrace_errhash[hval].dter_count++;
7568 			goto out;
7569 		}
7570 
7571 		if (dtrace_errhash[hval].dter_msg != NULL) {
7572 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
7573 			continue;
7574 		}
7575 
7576 		dtrace_errhash[hval].dter_msg = str;
7577 		dtrace_errhash[hval].dter_count = 1;
7578 		goto out;
7579 	}
7580 
7581 	panic("dtrace: undersized error hash");
7582 out:
7583 	mutex_exit(&dtrace_errlock);
7584 }
7585 #endif
7586 
7587 /*
7588  * DTrace Matching Functions
7589  *
7590  * These functions are used to match groups of probes, given some elements of
7591  * a probe tuple, or some globbed expressions for elements of a probe tuple.
7592  */
7593 static int
7594 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7595     zoneid_t zoneid)
7596 {
7597 	if (priv != DTRACE_PRIV_ALL) {
7598 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7599 		uint32_t match = priv & ppriv;
7600 
7601 		/*
7602 		 * No PRIV_DTRACE_* privileges...
7603 		 */
7604 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7605 		    DTRACE_PRIV_KERNEL)) == 0)
7606 			return (0);
7607 
7608 		/*
7609 		 * No matching bits, but there were bits to match...
7610 		 */
7611 		if (match == 0 && ppriv != 0)
7612 			return (0);
7613 
7614 		/*
7615 		 * Need to have permissions to the process, but don't...
7616 		 */
7617 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7618 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7619 			return (0);
7620 		}
7621 
7622 		/*
7623 		 * Need to be in the same zone unless we possess the
7624 		 * privilege to examine all zones.
7625 		 */
7626 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7627 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7628 			return (0);
7629 		}
7630 	}
7631 
7632 	return (1);
7633 }
7634 
7635 /*
7636  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7637  * consists of input pattern strings and an ops-vector to evaluate them.
7638  * This function returns >0 for match, 0 for no match, and <0 for error.
7639  */
7640 static int
7641 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7642     uint32_t priv, uid_t uid, zoneid_t zoneid)
7643 {
7644 	dtrace_provider_t *pvp = prp->dtpr_provider;
7645 	int rv;
7646 
7647 	if (pvp->dtpv_defunct)
7648 		return (0);
7649 
7650 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7651 		return (rv);
7652 
7653 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7654 		return (rv);
7655 
7656 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7657 		return (rv);
7658 
7659 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7660 		return (rv);
7661 
7662 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7663 		return (0);
7664 
7665 	return (rv);
7666 }
7667 
7668 /*
7669  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7670  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
7671  * libc's version, the kernel version only applies to 8-bit ASCII strings.
7672  * In addition, all of the recursion cases except for '*' matching have been
7673  * unwound.  For '*', we still implement recursive evaluation, but a depth
7674  * counter is maintained and matching is aborted if we recurse too deep.
7675  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7676  */
7677 static int
7678 dtrace_match_glob(const char *s, const char *p, int depth)
7679 {
7680 	const char *olds;
7681 	char s1, c;
7682 	int gs;
7683 
7684 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7685 		return (-1);
7686 
7687 	if (s == NULL)
7688 		s = ""; /* treat NULL as empty string */
7689 
7690 top:
7691 	olds = s;
7692 	s1 = *s++;
7693 
7694 	if (p == NULL)
7695 		return (0);
7696 
7697 	if ((c = *p++) == '\0')
7698 		return (s1 == '\0');
7699 
7700 	switch (c) {
7701 	case '[': {
7702 		int ok = 0, notflag = 0;
7703 		char lc = '\0';
7704 
7705 		if (s1 == '\0')
7706 			return (0);
7707 
7708 		if (*p == '!') {
7709 			notflag = 1;
7710 			p++;
7711 		}
7712 
7713 		if ((c = *p++) == '\0')
7714 			return (0);
7715 
7716 		do {
7717 			if (c == '-' && lc != '\0' && *p != ']') {
7718 				if ((c = *p++) == '\0')
7719 					return (0);
7720 				if (c == '\\' && (c = *p++) == '\0')
7721 					return (0);
7722 
7723 				if (notflag) {
7724 					if (s1 < lc || s1 > c)
7725 						ok++;
7726 					else
7727 						return (0);
7728 				} else if (lc <= s1 && s1 <= c)
7729 					ok++;
7730 
7731 			} else if (c == '\\' && (c = *p++) == '\0')
7732 				return (0);
7733 
7734 			lc = c; /* save left-hand 'c' for next iteration */
7735 
7736 			if (notflag) {
7737 				if (s1 != c)
7738 					ok++;
7739 				else
7740 					return (0);
7741 			} else if (s1 == c)
7742 				ok++;
7743 
7744 			if ((c = *p++) == '\0')
7745 				return (0);
7746 
7747 		} while (c != ']');
7748 
7749 		if (ok)
7750 			goto top;
7751 
7752 		return (0);
7753 	}
7754 
7755 	case '\\':
7756 		if ((c = *p++) == '\0')
7757 			return (0);
7758 		/*FALLTHRU*/
7759 
7760 	default:
7761 		if (c != s1)
7762 			return (0);
7763 		/*FALLTHRU*/
7764 
7765 	case '?':
7766 		if (s1 != '\0')
7767 			goto top;
7768 		return (0);
7769 
7770 	case '*':
7771 		while (*p == '*')
7772 			p++; /* consecutive *'s are identical to a single one */
7773 
7774 		if (*p == '\0')
7775 			return (1);
7776 
7777 		for (s = olds; *s != '\0'; s++) {
7778 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
7779 				return (gs);
7780 		}
7781 
7782 		return (0);
7783 	}
7784 }
7785 
7786 /*ARGSUSED*/
7787 static int
7788 dtrace_match_string(const char *s, const char *p, int depth)
7789 {
7790 	return (s != NULL && strcmp(s, p) == 0);
7791 }
7792 
7793 /*ARGSUSED*/
7794 static int
7795 dtrace_match_nul(const char *s, const char *p, int depth)
7796 {
7797 	return (1); /* always match the empty pattern */
7798 }
7799 
7800 /*ARGSUSED*/
7801 static int
7802 dtrace_match_nonzero(const char *s, const char *p, int depth)
7803 {
7804 	return (s != NULL && s[0] != '\0');
7805 }
7806 
7807 static int
7808 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
7809     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
7810 {
7811 	dtrace_probe_t template, *probe;
7812 	dtrace_hash_t *hash = NULL;
7813 	int len, rc, best = INT_MAX, nmatched = 0;
7814 	dtrace_id_t i;
7815 
7816 	ASSERT(MUTEX_HELD(&dtrace_lock));
7817 
7818 	/*
7819 	 * If the probe ID is specified in the key, just lookup by ID and
7820 	 * invoke the match callback once if a matching probe is found.
7821 	 */
7822 	if (pkp->dtpk_id != DTRACE_IDNONE) {
7823 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
7824 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
7825 			if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
7826 				return (DTRACE_MATCH_FAIL);
7827 			nmatched++;
7828 		}
7829 		return (nmatched);
7830 	}
7831 
7832 	template.dtpr_mod = (char *)pkp->dtpk_mod;
7833 	template.dtpr_func = (char *)pkp->dtpk_func;
7834 	template.dtpr_name = (char *)pkp->dtpk_name;
7835 
7836 	/*
7837 	 * We want to find the most distinct of the module name, function
7838 	 * name, and name.  So for each one that is not a glob pattern or
7839 	 * empty string, we perform a lookup in the corresponding hash and
7840 	 * use the hash table with the fewest collisions to do our search.
7841 	 */
7842 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
7843 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
7844 		best = len;
7845 		hash = dtrace_bymod;
7846 	}
7847 
7848 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
7849 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
7850 		best = len;
7851 		hash = dtrace_byfunc;
7852 	}
7853 
7854 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
7855 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7856 		best = len;
7857 		hash = dtrace_byname;
7858 	}
7859 
7860 	/*
7861 	 * If we did not select a hash table, iterate over every probe and
7862 	 * invoke our callback for each one that matches our input probe key.
7863 	 */
7864 	if (hash == NULL) {
7865 		for (i = 0; i < dtrace_nprobes; i++) {
7866 			if ((probe = dtrace_probes[i]) == NULL ||
7867 			    dtrace_match_probe(probe, pkp, priv, uid,
7868 			    zoneid) <= 0)
7869 				continue;
7870 
7871 			nmatched++;
7872 
7873 			if ((rc = (*matched)(probe, arg)) !=
7874 			    DTRACE_MATCH_NEXT) {
7875 				if (rc == DTRACE_MATCH_FAIL)
7876 					return (DTRACE_MATCH_FAIL);
7877 				break;
7878 			}
7879 		}
7880 
7881 		return (nmatched);
7882 	}
7883 
7884 	/*
7885 	 * If we selected a hash table, iterate over each probe of the same key
7886 	 * name and invoke the callback for every probe that matches the other
7887 	 * attributes of our input probe key.
7888 	 */
7889 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7890 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
7891 
7892 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7893 			continue;
7894 
7895 		nmatched++;
7896 
7897 		if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7898 			if (rc == DTRACE_MATCH_FAIL)
7899 				return (DTRACE_MATCH_FAIL);
7900 			break;
7901 		}
7902 	}
7903 
7904 	return (nmatched);
7905 }
7906 
7907 /*
7908  * Return the function pointer dtrace_probecmp() should use to compare the
7909  * specified pattern with a string.  For NULL or empty patterns, we select
7910  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
7911  * For non-empty non-glob strings, we use dtrace_match_string().
7912  */
7913 static dtrace_probekey_f *
7914 dtrace_probekey_func(const char *p)
7915 {
7916 	char c;
7917 
7918 	if (p == NULL || *p == '\0')
7919 		return (&dtrace_match_nul);
7920 
7921 	while ((c = *p++) != '\0') {
7922 		if (c == '[' || c == '?' || c == '*' || c == '\\')
7923 			return (&dtrace_match_glob);
7924 	}
7925 
7926 	return (&dtrace_match_string);
7927 }
7928 
7929 /*
7930  * Build a probe comparison key for use with dtrace_match_probe() from the
7931  * given probe description.  By convention, a null key only matches anchored
7932  * probes: if each field is the empty string, reset dtpk_fmatch to
7933  * dtrace_match_nonzero().
7934  */
7935 static void
7936 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7937 {
7938 	pkp->dtpk_prov = pdp->dtpd_provider;
7939 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7940 
7941 	pkp->dtpk_mod = pdp->dtpd_mod;
7942 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7943 
7944 	pkp->dtpk_func = pdp->dtpd_func;
7945 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7946 
7947 	pkp->dtpk_name = pdp->dtpd_name;
7948 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7949 
7950 	pkp->dtpk_id = pdp->dtpd_id;
7951 
7952 	if (pkp->dtpk_id == DTRACE_IDNONE &&
7953 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
7954 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
7955 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
7956 	    pkp->dtpk_nmatch == &dtrace_match_nul)
7957 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
7958 }
7959 
7960 /*
7961  * DTrace Provider-to-Framework API Functions
7962  *
7963  * These functions implement much of the Provider-to-Framework API, as
7964  * described in <sys/dtrace.h>.  The parts of the API not in this section are
7965  * the functions in the API for probe management (found below), and
7966  * dtrace_probe() itself (found above).
7967  */
7968 
7969 /*
7970  * Register the calling provider with the DTrace framework.  This should
7971  * generally be called by DTrace providers in their attach(9E) entry point.
7972  */
7973 int
7974 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7975     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7976 {
7977 	dtrace_provider_t *provider;
7978 
7979 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7980 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7981 		    "arguments", name ? name : "<NULL>");
7982 		return (EINVAL);
7983 	}
7984 
7985 	if (name[0] == '\0' || dtrace_badname(name)) {
7986 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7987 		    "provider name", name);
7988 		return (EINVAL);
7989 	}
7990 
7991 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7992 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7993 	    pops->dtps_destroy == NULL ||
7994 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7995 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7996 		    "provider ops", name);
7997 		return (EINVAL);
7998 	}
7999 
8000 	if (dtrace_badattr(&pap->dtpa_provider) ||
8001 	    dtrace_badattr(&pap->dtpa_mod) ||
8002 	    dtrace_badattr(&pap->dtpa_func) ||
8003 	    dtrace_badattr(&pap->dtpa_name) ||
8004 	    dtrace_badattr(&pap->dtpa_args)) {
8005 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8006 		    "provider attributes", name);
8007 		return (EINVAL);
8008 	}
8009 
8010 	if (priv & ~DTRACE_PRIV_ALL) {
8011 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8012 		    "privilege attributes", name);
8013 		return (EINVAL);
8014 	}
8015 
8016 	if ((priv & DTRACE_PRIV_KERNEL) &&
8017 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8018 	    pops->dtps_mode == NULL) {
8019 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8020 		    "dtps_mode() op for given privilege attributes", name);
8021 		return (EINVAL);
8022 	}
8023 
8024 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8025 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8026 	(void) strcpy(provider->dtpv_name, name);
8027 
8028 	provider->dtpv_attr = *pap;
8029 	provider->dtpv_priv.dtpp_flags = priv;
8030 	if (cr != NULL) {
8031 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8032 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8033 	}
8034 	provider->dtpv_pops = *pops;
8035 
8036 	if (pops->dtps_provide == NULL) {
8037 		ASSERT(pops->dtps_provide_module != NULL);
8038 		provider->dtpv_pops.dtps_provide =
8039 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
8040 	}
8041 
8042 	if (pops->dtps_provide_module == NULL) {
8043 		ASSERT(pops->dtps_provide != NULL);
8044 		provider->dtpv_pops.dtps_provide_module =
8045 		    (void (*)(void *, struct modctl *))dtrace_nullop;
8046 	}
8047 
8048 	if (pops->dtps_suspend == NULL) {
8049 		ASSERT(pops->dtps_resume == NULL);
8050 		provider->dtpv_pops.dtps_suspend =
8051 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8052 		provider->dtpv_pops.dtps_resume =
8053 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8054 	}
8055 
8056 	provider->dtpv_arg = arg;
8057 	*idp = (dtrace_provider_id_t)provider;
8058 
8059 	if (pops == &dtrace_provider_ops) {
8060 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8061 		ASSERT(MUTEX_HELD(&dtrace_lock));
8062 		ASSERT(dtrace_anon.dta_enabling == NULL);
8063 
8064 		/*
8065 		 * We make sure that the DTrace provider is at the head of
8066 		 * the provider chain.
8067 		 */
8068 		provider->dtpv_next = dtrace_provider;
8069 		dtrace_provider = provider;
8070 		return (0);
8071 	}
8072 
8073 	mutex_enter(&dtrace_provider_lock);
8074 	mutex_enter(&dtrace_lock);
8075 
8076 	/*
8077 	 * If there is at least one provider registered, we'll add this
8078 	 * provider after the first provider.
8079 	 */
8080 	if (dtrace_provider != NULL) {
8081 		provider->dtpv_next = dtrace_provider->dtpv_next;
8082 		dtrace_provider->dtpv_next = provider;
8083 	} else {
8084 		dtrace_provider = provider;
8085 	}
8086 
8087 	if (dtrace_retained != NULL) {
8088 		dtrace_enabling_provide(provider);
8089 
8090 		/*
8091 		 * Now we need to call dtrace_enabling_matchall() -- which
8092 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
8093 		 * to drop all of our locks before calling into it...
8094 		 */
8095 		mutex_exit(&dtrace_lock);
8096 		mutex_exit(&dtrace_provider_lock);
8097 		dtrace_enabling_matchall();
8098 
8099 		return (0);
8100 	}
8101 
8102 	mutex_exit(&dtrace_lock);
8103 	mutex_exit(&dtrace_provider_lock);
8104 
8105 	return (0);
8106 }
8107 
8108 /*
8109  * Unregister the specified provider from the DTrace framework.  This should
8110  * generally be called by DTrace providers in their detach(9E) entry point.
8111  */
8112 int
8113 dtrace_unregister(dtrace_provider_id_t id)
8114 {
8115 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8116 	dtrace_provider_t *prev = NULL;
8117 	int i, self = 0, noreap = 0;
8118 	dtrace_probe_t *probe, *first = NULL;
8119 
8120 	if (old->dtpv_pops.dtps_enable ==
8121 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
8122 		/*
8123 		 * If DTrace itself is the provider, we're called with locks
8124 		 * already held.
8125 		 */
8126 		ASSERT(old == dtrace_provider);
8127 		ASSERT(dtrace_devi != NULL);
8128 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8129 		ASSERT(MUTEX_HELD(&dtrace_lock));
8130 		self = 1;
8131 
8132 		if (dtrace_provider->dtpv_next != NULL) {
8133 			/*
8134 			 * There's another provider here; return failure.
8135 			 */
8136 			return (EBUSY);
8137 		}
8138 	} else {
8139 		mutex_enter(&dtrace_provider_lock);
8140 		mutex_enter(&mod_lock);
8141 		mutex_enter(&dtrace_lock);
8142 	}
8143 
8144 	/*
8145 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8146 	 * probes, we refuse to let providers slither away, unless this
8147 	 * provider has already been explicitly invalidated.
8148 	 */
8149 	if (!old->dtpv_defunct &&
8150 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8151 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8152 		if (!self) {
8153 			mutex_exit(&dtrace_lock);
8154 			mutex_exit(&mod_lock);
8155 			mutex_exit(&dtrace_provider_lock);
8156 		}
8157 		return (EBUSY);
8158 	}
8159 
8160 	/*
8161 	 * Attempt to destroy the probes associated with this provider.
8162 	 */
8163 	for (i = 0; i < dtrace_nprobes; i++) {
8164 		if ((probe = dtrace_probes[i]) == NULL)
8165 			continue;
8166 
8167 		if (probe->dtpr_provider != old)
8168 			continue;
8169 
8170 		if (probe->dtpr_ecb == NULL)
8171 			continue;
8172 
8173 		/*
8174 		 * If we are trying to unregister a defunct provider, and the
8175 		 * provider was made defunct within the interval dictated by
8176 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8177 		 * attempt to reap our enablings.  To denote that the provider
8178 		 * should reattempt to unregister itself at some point in the
8179 		 * future, we will return a differentiable error code (EAGAIN
8180 		 * instead of EBUSY) in this case.
8181 		 */
8182 		if (dtrace_gethrtime() - old->dtpv_defunct >
8183 		    dtrace_unregister_defunct_reap)
8184 			noreap = 1;
8185 
8186 		if (!self) {
8187 			mutex_exit(&dtrace_lock);
8188 			mutex_exit(&mod_lock);
8189 			mutex_exit(&dtrace_provider_lock);
8190 		}
8191 
8192 		if (noreap)
8193 			return (EBUSY);
8194 
8195 		(void) taskq_dispatch(dtrace_taskq,
8196 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8197 
8198 		return (EAGAIN);
8199 	}
8200 
8201 	/*
8202 	 * All of the probes for this provider are disabled; we can safely
8203 	 * remove all of them from their hash chains and from the probe array.
8204 	 */
8205 	for (i = 0; i < dtrace_nprobes; i++) {
8206 		if ((probe = dtrace_probes[i]) == NULL)
8207 			continue;
8208 
8209 		if (probe->dtpr_provider != old)
8210 			continue;
8211 
8212 		dtrace_probes[i] = NULL;
8213 
8214 		dtrace_hash_remove(dtrace_bymod, probe);
8215 		dtrace_hash_remove(dtrace_byfunc, probe);
8216 		dtrace_hash_remove(dtrace_byname, probe);
8217 
8218 		if (first == NULL) {
8219 			first = probe;
8220 			probe->dtpr_nextmod = NULL;
8221 		} else {
8222 			probe->dtpr_nextmod = first;
8223 			first = probe;
8224 		}
8225 	}
8226 
8227 	/*
8228 	 * The provider's probes have been removed from the hash chains and
8229 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8230 	 * everyone has cleared out from any probe array processing.
8231 	 */
8232 	dtrace_sync();
8233 
8234 	for (probe = first; probe != NULL; probe = first) {
8235 		first = probe->dtpr_nextmod;
8236 
8237 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8238 		    probe->dtpr_arg);
8239 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8240 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8241 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8242 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8243 		kmem_free(probe, sizeof (dtrace_probe_t));
8244 	}
8245 
8246 	if ((prev = dtrace_provider) == old) {
8247 		ASSERT(self || dtrace_devi == NULL);
8248 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8249 		dtrace_provider = old->dtpv_next;
8250 	} else {
8251 		while (prev != NULL && prev->dtpv_next != old)
8252 			prev = prev->dtpv_next;
8253 
8254 		if (prev == NULL) {
8255 			panic("attempt to unregister non-existent "
8256 			    "dtrace provider %p\n", (void *)id);
8257 		}
8258 
8259 		prev->dtpv_next = old->dtpv_next;
8260 	}
8261 
8262 	if (!self) {
8263 		mutex_exit(&dtrace_lock);
8264 		mutex_exit(&mod_lock);
8265 		mutex_exit(&dtrace_provider_lock);
8266 	}
8267 
8268 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8269 	kmem_free(old, sizeof (dtrace_provider_t));
8270 
8271 	return (0);
8272 }
8273 
8274 /*
8275  * Invalidate the specified provider.  All subsequent probe lookups for the
8276  * specified provider will fail, but its probes will not be removed.
8277  */
8278 void
8279 dtrace_invalidate(dtrace_provider_id_t id)
8280 {
8281 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8282 
8283 	ASSERT(pvp->dtpv_pops.dtps_enable !=
8284 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8285 
8286 	mutex_enter(&dtrace_provider_lock);
8287 	mutex_enter(&dtrace_lock);
8288 
8289 	pvp->dtpv_defunct = dtrace_gethrtime();
8290 
8291 	mutex_exit(&dtrace_lock);
8292 	mutex_exit(&dtrace_provider_lock);
8293 }
8294 
8295 /*
8296  * Indicate whether or not DTrace has attached.
8297  */
8298 int
8299 dtrace_attached(void)
8300 {
8301 	/*
8302 	 * dtrace_provider will be non-NULL iff the DTrace driver has
8303 	 * attached.  (It's non-NULL because DTrace is always itself a
8304 	 * provider.)
8305 	 */
8306 	return (dtrace_provider != NULL);
8307 }
8308 
8309 /*
8310  * Remove all the unenabled probes for the given provider.  This function is
8311  * not unlike dtrace_unregister(), except that it doesn't remove the provider
8312  * -- just as many of its associated probes as it can.
8313  */
8314 int
8315 dtrace_condense(dtrace_provider_id_t id)
8316 {
8317 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
8318 	int i;
8319 	dtrace_probe_t *probe;
8320 
8321 	/*
8322 	 * Make sure this isn't the dtrace provider itself.
8323 	 */
8324 	ASSERT(prov->dtpv_pops.dtps_enable !=
8325 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8326 
8327 	mutex_enter(&dtrace_provider_lock);
8328 	mutex_enter(&dtrace_lock);
8329 
8330 	/*
8331 	 * Attempt to destroy the probes associated with this provider.
8332 	 */
8333 	for (i = 0; i < dtrace_nprobes; i++) {
8334 		if ((probe = dtrace_probes[i]) == NULL)
8335 			continue;
8336 
8337 		if (probe->dtpr_provider != prov)
8338 			continue;
8339 
8340 		if (probe->dtpr_ecb != NULL)
8341 			continue;
8342 
8343 		dtrace_probes[i] = NULL;
8344 
8345 		dtrace_hash_remove(dtrace_bymod, probe);
8346 		dtrace_hash_remove(dtrace_byfunc, probe);
8347 		dtrace_hash_remove(dtrace_byname, probe);
8348 
8349 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8350 		    probe->dtpr_arg);
8351 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8352 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8353 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8354 		kmem_free(probe, sizeof (dtrace_probe_t));
8355 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8356 	}
8357 
8358 	mutex_exit(&dtrace_lock);
8359 	mutex_exit(&dtrace_provider_lock);
8360 
8361 	return (0);
8362 }
8363 
8364 /*
8365  * DTrace Probe Management Functions
8366  *
8367  * The functions in this section perform the DTrace probe management,
8368  * including functions to create probes, look-up probes, and call into the
8369  * providers to request that probes be provided.  Some of these functions are
8370  * in the Provider-to-Framework API; these functions can be identified by the
8371  * fact that they are not declared "static".
8372  */
8373 
8374 /*
8375  * Create a probe with the specified module name, function name, and name.
8376  */
8377 dtrace_id_t
8378 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8379     const char *func, const char *name, int aframes, void *arg)
8380 {
8381 	dtrace_probe_t *probe, **probes;
8382 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8383 	dtrace_id_t id;
8384 
8385 	if (provider == dtrace_provider) {
8386 		ASSERT(MUTEX_HELD(&dtrace_lock));
8387 	} else {
8388 		mutex_enter(&dtrace_lock);
8389 	}
8390 
8391 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8392 	    VM_BESTFIT | VM_SLEEP);
8393 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8394 
8395 	probe->dtpr_id = id;
8396 	probe->dtpr_gen = dtrace_probegen++;
8397 	probe->dtpr_mod = dtrace_strdup(mod);
8398 	probe->dtpr_func = dtrace_strdup(func);
8399 	probe->dtpr_name = dtrace_strdup(name);
8400 	probe->dtpr_arg = arg;
8401 	probe->dtpr_aframes = aframes;
8402 	probe->dtpr_provider = provider;
8403 
8404 	dtrace_hash_add(dtrace_bymod, probe);
8405 	dtrace_hash_add(dtrace_byfunc, probe);
8406 	dtrace_hash_add(dtrace_byname, probe);
8407 
8408 	if (id - 1 >= dtrace_nprobes) {
8409 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8410 		size_t nsize = osize << 1;
8411 
8412 		if (nsize == 0) {
8413 			ASSERT(osize == 0);
8414 			ASSERT(dtrace_probes == NULL);
8415 			nsize = sizeof (dtrace_probe_t *);
8416 		}
8417 
8418 		probes = kmem_zalloc(nsize, KM_SLEEP);
8419 
8420 		if (dtrace_probes == NULL) {
8421 			ASSERT(osize == 0);
8422 			dtrace_probes = probes;
8423 			dtrace_nprobes = 1;
8424 		} else {
8425 			dtrace_probe_t **oprobes = dtrace_probes;
8426 
8427 			bcopy(oprobes, probes, osize);
8428 			dtrace_membar_producer();
8429 			dtrace_probes = probes;
8430 
8431 			dtrace_sync();
8432 
8433 			/*
8434 			 * All CPUs are now seeing the new probes array; we can
8435 			 * safely free the old array.
8436 			 */
8437 			kmem_free(oprobes, osize);
8438 			dtrace_nprobes <<= 1;
8439 		}
8440 
8441 		ASSERT(id - 1 < dtrace_nprobes);
8442 	}
8443 
8444 	ASSERT(dtrace_probes[id - 1] == NULL);
8445 	dtrace_probes[id - 1] = probe;
8446 
8447 	if (provider != dtrace_provider)
8448 		mutex_exit(&dtrace_lock);
8449 
8450 	return (id);
8451 }
8452 
8453 static dtrace_probe_t *
8454 dtrace_probe_lookup_id(dtrace_id_t id)
8455 {
8456 	ASSERT(MUTEX_HELD(&dtrace_lock));
8457 
8458 	if (id == 0 || id > dtrace_nprobes)
8459 		return (NULL);
8460 
8461 	return (dtrace_probes[id - 1]);
8462 }
8463 
8464 static int
8465 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8466 {
8467 	*((dtrace_id_t *)arg) = probe->dtpr_id;
8468 
8469 	return (DTRACE_MATCH_DONE);
8470 }
8471 
8472 /*
8473  * Look up a probe based on provider and one or more of module name, function
8474  * name and probe name.
8475  */
8476 dtrace_id_t
8477 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
8478     const char *func, const char *name)
8479 {
8480 	dtrace_probekey_t pkey;
8481 	dtrace_id_t id;
8482 	int match;
8483 
8484 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8485 	pkey.dtpk_pmatch = &dtrace_match_string;
8486 	pkey.dtpk_mod = mod;
8487 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8488 	pkey.dtpk_func = func;
8489 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8490 	pkey.dtpk_name = name;
8491 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8492 	pkey.dtpk_id = DTRACE_IDNONE;
8493 
8494 	mutex_enter(&dtrace_lock);
8495 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8496 	    dtrace_probe_lookup_match, &id);
8497 	mutex_exit(&dtrace_lock);
8498 
8499 	ASSERT(match == 1 || match == 0);
8500 	return (match ? id : 0);
8501 }
8502 
8503 /*
8504  * Returns the probe argument associated with the specified probe.
8505  */
8506 void *
8507 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8508 {
8509 	dtrace_probe_t *probe;
8510 	void *rval = NULL;
8511 
8512 	mutex_enter(&dtrace_lock);
8513 
8514 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8515 	    probe->dtpr_provider == (dtrace_provider_t *)id)
8516 		rval = probe->dtpr_arg;
8517 
8518 	mutex_exit(&dtrace_lock);
8519 
8520 	return (rval);
8521 }
8522 
8523 /*
8524  * Copy a probe into a probe description.
8525  */
8526 static void
8527 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8528 {
8529 	bzero(pdp, sizeof (dtrace_probedesc_t));
8530 	pdp->dtpd_id = prp->dtpr_id;
8531 
8532 	(void) strncpy(pdp->dtpd_provider,
8533 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8534 
8535 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8536 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8537 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8538 }
8539 
8540 /*
8541  * Called to indicate that a probe -- or probes -- should be provided by a
8542  * specfied provider.  If the specified description is NULL, the provider will
8543  * be told to provide all of its probes.  (This is done whenever a new
8544  * consumer comes along, or whenever a retained enabling is to be matched.) If
8545  * the specified description is non-NULL, the provider is given the
8546  * opportunity to dynamically provide the specified probe, allowing providers
8547  * to support the creation of probes on-the-fly.  (So-called _autocreated_
8548  * probes.)  If the provider is NULL, the operations will be applied to all
8549  * providers; if the provider is non-NULL the operations will only be applied
8550  * to the specified provider.  The dtrace_provider_lock must be held, and the
8551  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8552  * will need to grab the dtrace_lock when it reenters the framework through
8553  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8554  */
8555 static void
8556 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8557 {
8558 	struct modctl *ctl;
8559 	int all = 0;
8560 
8561 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8562 
8563 	if (prv == NULL) {
8564 		all = 1;
8565 		prv = dtrace_provider;
8566 	}
8567 
8568 	do {
8569 		/*
8570 		 * First, call the blanket provide operation.
8571 		 */
8572 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8573 
8574 		/*
8575 		 * Now call the per-module provide operation.  We will grab
8576 		 * mod_lock to prevent the list from being modified.  Note
8577 		 * that this also prevents the mod_busy bits from changing.
8578 		 * (mod_busy can only be changed with mod_lock held.)
8579 		 */
8580 		mutex_enter(&mod_lock);
8581 
8582 		ctl = &modules;
8583 		do {
8584 			if (ctl->mod_busy || ctl->mod_mp == NULL)
8585 				continue;
8586 
8587 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8588 
8589 		} while ((ctl = ctl->mod_next) != &modules);
8590 
8591 		mutex_exit(&mod_lock);
8592 	} while (all && (prv = prv->dtpv_next) != NULL);
8593 }
8594 
8595 /*
8596  * Iterate over each probe, and call the Framework-to-Provider API function
8597  * denoted by offs.
8598  */
8599 static void
8600 dtrace_probe_foreach(uintptr_t offs)
8601 {
8602 	dtrace_provider_t *prov;
8603 	void (*func)(void *, dtrace_id_t, void *);
8604 	dtrace_probe_t *probe;
8605 	dtrace_icookie_t cookie;
8606 	int i;
8607 
8608 	/*
8609 	 * We disable interrupts to walk through the probe array.  This is
8610 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8611 	 * won't see stale data.
8612 	 */
8613 	cookie = dtrace_interrupt_disable();
8614 
8615 	for (i = 0; i < dtrace_nprobes; i++) {
8616 		if ((probe = dtrace_probes[i]) == NULL)
8617 			continue;
8618 
8619 		if (probe->dtpr_ecb == NULL) {
8620 			/*
8621 			 * This probe isn't enabled -- don't call the function.
8622 			 */
8623 			continue;
8624 		}
8625 
8626 		prov = probe->dtpr_provider;
8627 		func = *((void(**)(void *, dtrace_id_t, void *))
8628 		    ((uintptr_t)&prov->dtpv_pops + offs));
8629 
8630 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8631 	}
8632 
8633 	dtrace_interrupt_enable(cookie);
8634 }
8635 
8636 static int
8637 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8638 {
8639 	dtrace_probekey_t pkey;
8640 	uint32_t priv;
8641 	uid_t uid;
8642 	zoneid_t zoneid;
8643 
8644 	ASSERT(MUTEX_HELD(&dtrace_lock));
8645 	dtrace_ecb_create_cache = NULL;
8646 
8647 	if (desc == NULL) {
8648 		/*
8649 		 * If we're passed a NULL description, we're being asked to
8650 		 * create an ECB with a NULL probe.
8651 		 */
8652 		(void) dtrace_ecb_create_enable(NULL, enab);
8653 		return (0);
8654 	}
8655 
8656 	dtrace_probekey(desc, &pkey);
8657 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8658 	    &priv, &uid, &zoneid);
8659 
8660 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8661 	    enab));
8662 }
8663 
8664 /*
8665  * DTrace Helper Provider Functions
8666  */
8667 static void
8668 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8669 {
8670 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
8671 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
8672 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8673 }
8674 
8675 static void
8676 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8677     const dof_provider_t *dofprov, char *strtab)
8678 {
8679 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8680 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8681 	    dofprov->dofpv_provattr);
8682 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8683 	    dofprov->dofpv_modattr);
8684 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8685 	    dofprov->dofpv_funcattr);
8686 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8687 	    dofprov->dofpv_nameattr);
8688 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8689 	    dofprov->dofpv_argsattr);
8690 }
8691 
8692 static void
8693 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8694 {
8695 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8696 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8697 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8698 	dof_provider_t *provider;
8699 	dof_probe_t *probe;
8700 	uint32_t *off, *enoff;
8701 	uint8_t *arg;
8702 	char *strtab;
8703 	uint_t i, nprobes;
8704 	dtrace_helper_provdesc_t dhpv;
8705 	dtrace_helper_probedesc_t dhpb;
8706 	dtrace_meta_t *meta = dtrace_meta_pid;
8707 	dtrace_mops_t *mops = &meta->dtm_mops;
8708 	void *parg;
8709 
8710 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8711 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8712 	    provider->dofpv_strtab * dof->dofh_secsize);
8713 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8714 	    provider->dofpv_probes * dof->dofh_secsize);
8715 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8716 	    provider->dofpv_prargs * dof->dofh_secsize);
8717 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8718 	    provider->dofpv_proffs * dof->dofh_secsize);
8719 
8720 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8721 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8722 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8723 	enoff = NULL;
8724 
8725 	/*
8726 	 * See dtrace_helper_provider_validate().
8727 	 */
8728 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8729 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
8730 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8731 		    provider->dofpv_prenoffs * dof->dofh_secsize);
8732 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8733 	}
8734 
8735 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8736 
8737 	/*
8738 	 * Create the provider.
8739 	 */
8740 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
8741 
8742 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8743 		return;
8744 
8745 	meta->dtm_count++;
8746 
8747 	/*
8748 	 * Create the probes.
8749 	 */
8750 	for (i = 0; i < nprobes; i++) {
8751 		probe = (dof_probe_t *)(uintptr_t)(daddr +
8752 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
8753 
8754 		dhpb.dthpb_mod = dhp->dofhp_mod;
8755 		dhpb.dthpb_func = strtab + probe->dofpr_func;
8756 		dhpb.dthpb_name = strtab + probe->dofpr_name;
8757 		dhpb.dthpb_base = probe->dofpr_addr;
8758 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
8759 		dhpb.dthpb_noffs = probe->dofpr_noffs;
8760 		if (enoff != NULL) {
8761 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
8762 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
8763 		} else {
8764 			dhpb.dthpb_enoffs = NULL;
8765 			dhpb.dthpb_nenoffs = 0;
8766 		}
8767 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
8768 		dhpb.dthpb_nargc = probe->dofpr_nargc;
8769 		dhpb.dthpb_xargc = probe->dofpr_xargc;
8770 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
8771 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
8772 
8773 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
8774 	}
8775 }
8776 
8777 static void
8778 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
8779 {
8780 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8781 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8782 	int i;
8783 
8784 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8785 
8786 	for (i = 0; i < dof->dofh_secnum; i++) {
8787 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8788 		    dof->dofh_secoff + i * dof->dofh_secsize);
8789 
8790 		if (sec->dofs_type != DOF_SECT_PROVIDER)
8791 			continue;
8792 
8793 		dtrace_helper_provide_one(dhp, sec, pid);
8794 	}
8795 
8796 	/*
8797 	 * We may have just created probes, so we must now rematch against
8798 	 * any retained enablings.  Note that this call will acquire both
8799 	 * cpu_lock and dtrace_lock; the fact that we are holding
8800 	 * dtrace_meta_lock now is what defines the ordering with respect to
8801 	 * these three locks.
8802 	 */
8803 	dtrace_enabling_matchall();
8804 }
8805 
8806 static void
8807 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8808 {
8809 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8810 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8811 	dof_sec_t *str_sec;
8812 	dof_provider_t *provider;
8813 	char *strtab;
8814 	dtrace_helper_provdesc_t dhpv;
8815 	dtrace_meta_t *meta = dtrace_meta_pid;
8816 	dtrace_mops_t *mops = &meta->dtm_mops;
8817 
8818 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8819 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8820 	    provider->dofpv_strtab * dof->dofh_secsize);
8821 
8822 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8823 
8824 	/*
8825 	 * Create the provider.
8826 	 */
8827 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
8828 
8829 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
8830 
8831 	meta->dtm_count--;
8832 }
8833 
8834 static void
8835 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
8836 {
8837 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8838 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8839 	int i;
8840 
8841 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
8842 
8843 	for (i = 0; i < dof->dofh_secnum; i++) {
8844 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
8845 		    dof->dofh_secoff + i * dof->dofh_secsize);
8846 
8847 		if (sec->dofs_type != DOF_SECT_PROVIDER)
8848 			continue;
8849 
8850 		dtrace_helper_provider_remove_one(dhp, sec, pid);
8851 	}
8852 }
8853 
8854 /*
8855  * DTrace Meta Provider-to-Framework API Functions
8856  *
8857  * These functions implement the Meta Provider-to-Framework API, as described
8858  * in <sys/dtrace.h>.
8859  */
8860 int
8861 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8862     dtrace_meta_provider_id_t *idp)
8863 {
8864 	dtrace_meta_t *meta;
8865 	dtrace_helpers_t *help, *next;
8866 	int i;
8867 
8868 	*idp = DTRACE_METAPROVNONE;
8869 
8870 	/*
8871 	 * We strictly don't need the name, but we hold onto it for
8872 	 * debuggability. All hail error queues!
8873 	 */
8874 	if (name == NULL) {
8875 		cmn_err(CE_WARN, "failed to register meta-provider: "
8876 		    "invalid name");
8877 		return (EINVAL);
8878 	}
8879 
8880 	if (mops == NULL ||
8881 	    mops->dtms_create_probe == NULL ||
8882 	    mops->dtms_provide_pid == NULL ||
8883 	    mops->dtms_remove_pid == NULL) {
8884 		cmn_err(CE_WARN, "failed to register meta-register %s: "
8885 		    "invalid ops", name);
8886 		return (EINVAL);
8887 	}
8888 
8889 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8890 	meta->dtm_mops = *mops;
8891 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8892 	(void) strcpy(meta->dtm_name, name);
8893 	meta->dtm_arg = arg;
8894 
8895 	mutex_enter(&dtrace_meta_lock);
8896 	mutex_enter(&dtrace_lock);
8897 
8898 	if (dtrace_meta_pid != NULL) {
8899 		mutex_exit(&dtrace_lock);
8900 		mutex_exit(&dtrace_meta_lock);
8901 		cmn_err(CE_WARN, "failed to register meta-register %s: "
8902 		    "user-land meta-provider exists", name);
8903 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8904 		kmem_free(meta, sizeof (dtrace_meta_t));
8905 		return (EINVAL);
8906 	}
8907 
8908 	dtrace_meta_pid = meta;
8909 	*idp = (dtrace_meta_provider_id_t)meta;
8910 
8911 	/*
8912 	 * If there are providers and probes ready to go, pass them
8913 	 * off to the new meta provider now.
8914 	 */
8915 
8916 	help = dtrace_deferred_pid;
8917 	dtrace_deferred_pid = NULL;
8918 
8919 	mutex_exit(&dtrace_lock);
8920 
8921 	while (help != NULL) {
8922 		for (i = 0; i < help->dthps_nprovs; i++) {
8923 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8924 			    help->dthps_pid);
8925 		}
8926 
8927 		next = help->dthps_next;
8928 		help->dthps_next = NULL;
8929 		help->dthps_prev = NULL;
8930 		help->dthps_deferred = 0;
8931 		help = next;
8932 	}
8933 
8934 	mutex_exit(&dtrace_meta_lock);
8935 
8936 	return (0);
8937 }
8938 
8939 int
8940 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8941 {
8942 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8943 
8944 	mutex_enter(&dtrace_meta_lock);
8945 	mutex_enter(&dtrace_lock);
8946 
8947 	if (old == dtrace_meta_pid) {
8948 		pp = &dtrace_meta_pid;
8949 	} else {
8950 		panic("attempt to unregister non-existent "
8951 		    "dtrace meta-provider %p\n", (void *)old);
8952 	}
8953 
8954 	if (old->dtm_count != 0) {
8955 		mutex_exit(&dtrace_lock);
8956 		mutex_exit(&dtrace_meta_lock);
8957 		return (EBUSY);
8958 	}
8959 
8960 	*pp = NULL;
8961 
8962 	mutex_exit(&dtrace_lock);
8963 	mutex_exit(&dtrace_meta_lock);
8964 
8965 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8966 	kmem_free(old, sizeof (dtrace_meta_t));
8967 
8968 	return (0);
8969 }
8970 
8971 
8972 /*
8973  * DTrace DIF Object Functions
8974  */
8975 static int
8976 dtrace_difo_err(uint_t pc, const char *format, ...)
8977 {
8978 	if (dtrace_err_verbose) {
8979 		va_list alist;
8980 
8981 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
8982 		va_start(alist, format);
8983 		(void) vuprintf(format, alist);
8984 		va_end(alist);
8985 	}
8986 
8987 #ifdef DTRACE_ERRDEBUG
8988 	dtrace_errdebug(format);
8989 #endif
8990 	return (1);
8991 }
8992 
8993 /*
8994  * Validate a DTrace DIF object by checking the IR instructions.  The following
8995  * rules are currently enforced by dtrace_difo_validate():
8996  *
8997  * 1. Each instruction must have a valid opcode
8998  * 2. Each register, string, variable, or subroutine reference must be valid
8999  * 3. No instruction can modify register %r0 (must be zero)
9000  * 4. All instruction reserved bits must be set to zero
9001  * 5. The last instruction must be a "ret" instruction
9002  * 6. All branch targets must reference a valid instruction _after_ the branch
9003  */
9004 static int
9005 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9006     cred_t *cr)
9007 {
9008 	int err = 0, i;
9009 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9010 	int kcheckload;
9011 	uint_t pc;
9012 
9013 	kcheckload = cr == NULL ||
9014 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9015 
9016 	dp->dtdo_destructive = 0;
9017 
9018 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9019 		dif_instr_t instr = dp->dtdo_buf[pc];
9020 
9021 		uint_t r1 = DIF_INSTR_R1(instr);
9022 		uint_t r2 = DIF_INSTR_R2(instr);
9023 		uint_t rd = DIF_INSTR_RD(instr);
9024 		uint_t rs = DIF_INSTR_RS(instr);
9025 		uint_t label = DIF_INSTR_LABEL(instr);
9026 		uint_t v = DIF_INSTR_VAR(instr);
9027 		uint_t subr = DIF_INSTR_SUBR(instr);
9028 		uint_t type = DIF_INSTR_TYPE(instr);
9029 		uint_t op = DIF_INSTR_OP(instr);
9030 
9031 		switch (op) {
9032 		case DIF_OP_OR:
9033 		case DIF_OP_XOR:
9034 		case DIF_OP_AND:
9035 		case DIF_OP_SLL:
9036 		case DIF_OP_SRL:
9037 		case DIF_OP_SRA:
9038 		case DIF_OP_SUB:
9039 		case DIF_OP_ADD:
9040 		case DIF_OP_MUL:
9041 		case DIF_OP_SDIV:
9042 		case DIF_OP_UDIV:
9043 		case DIF_OP_SREM:
9044 		case DIF_OP_UREM:
9045 		case DIF_OP_COPYS:
9046 			if (r1 >= nregs)
9047 				err += efunc(pc, "invalid register %u\n", r1);
9048 			if (r2 >= nregs)
9049 				err += efunc(pc, "invalid register %u\n", r2);
9050 			if (rd >= nregs)
9051 				err += efunc(pc, "invalid register %u\n", rd);
9052 			if (rd == 0)
9053 				err += efunc(pc, "cannot write to %r0\n");
9054 			break;
9055 		case DIF_OP_NOT:
9056 		case DIF_OP_MOV:
9057 		case DIF_OP_ALLOCS:
9058 			if (r1 >= nregs)
9059 				err += efunc(pc, "invalid register %u\n", r1);
9060 			if (r2 != 0)
9061 				err += efunc(pc, "non-zero reserved bits\n");
9062 			if (rd >= nregs)
9063 				err += efunc(pc, "invalid register %u\n", rd);
9064 			if (rd == 0)
9065 				err += efunc(pc, "cannot write to %r0\n");
9066 			break;
9067 		case DIF_OP_LDSB:
9068 		case DIF_OP_LDSH:
9069 		case DIF_OP_LDSW:
9070 		case DIF_OP_LDUB:
9071 		case DIF_OP_LDUH:
9072 		case DIF_OP_LDUW:
9073 		case DIF_OP_LDX:
9074 			if (r1 >= nregs)
9075 				err += efunc(pc, "invalid register %u\n", r1);
9076 			if (r2 != 0)
9077 				err += efunc(pc, "non-zero reserved bits\n");
9078 			if (rd >= nregs)
9079 				err += efunc(pc, "invalid register %u\n", rd);
9080 			if (rd == 0)
9081 				err += efunc(pc, "cannot write to %r0\n");
9082 			if (kcheckload)
9083 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9084 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9085 			break;
9086 		case DIF_OP_RLDSB:
9087 		case DIF_OP_RLDSH:
9088 		case DIF_OP_RLDSW:
9089 		case DIF_OP_RLDUB:
9090 		case DIF_OP_RLDUH:
9091 		case DIF_OP_RLDUW:
9092 		case DIF_OP_RLDX:
9093 			if (r1 >= nregs)
9094 				err += efunc(pc, "invalid register %u\n", r1);
9095 			if (r2 != 0)
9096 				err += efunc(pc, "non-zero reserved bits\n");
9097 			if (rd >= nregs)
9098 				err += efunc(pc, "invalid register %u\n", rd);
9099 			if (rd == 0)
9100 				err += efunc(pc, "cannot write to %r0\n");
9101 			break;
9102 		case DIF_OP_ULDSB:
9103 		case DIF_OP_ULDSH:
9104 		case DIF_OP_ULDSW:
9105 		case DIF_OP_ULDUB:
9106 		case DIF_OP_ULDUH:
9107 		case DIF_OP_ULDUW:
9108 		case DIF_OP_ULDX:
9109 			if (r1 >= nregs)
9110 				err += efunc(pc, "invalid register %u\n", r1);
9111 			if (r2 != 0)
9112 				err += efunc(pc, "non-zero reserved bits\n");
9113 			if (rd >= nregs)
9114 				err += efunc(pc, "invalid register %u\n", rd);
9115 			if (rd == 0)
9116 				err += efunc(pc, "cannot write to %r0\n");
9117 			break;
9118 		case DIF_OP_STB:
9119 		case DIF_OP_STH:
9120 		case DIF_OP_STW:
9121 		case DIF_OP_STX:
9122 			if (r1 >= nregs)
9123 				err += efunc(pc, "invalid register %u\n", r1);
9124 			if (r2 != 0)
9125 				err += efunc(pc, "non-zero reserved bits\n");
9126 			if (rd >= nregs)
9127 				err += efunc(pc, "invalid register %u\n", rd);
9128 			if (rd == 0)
9129 				err += efunc(pc, "cannot write to 0 address\n");
9130 			break;
9131 		case DIF_OP_CMP:
9132 		case DIF_OP_SCMP:
9133 			if (r1 >= nregs)
9134 				err += efunc(pc, "invalid register %u\n", r1);
9135 			if (r2 >= nregs)
9136 				err += efunc(pc, "invalid register %u\n", r2);
9137 			if (rd != 0)
9138 				err += efunc(pc, "non-zero reserved bits\n");
9139 			break;
9140 		case DIF_OP_TST:
9141 			if (r1 >= nregs)
9142 				err += efunc(pc, "invalid register %u\n", r1);
9143 			if (r2 != 0 || rd != 0)
9144 				err += efunc(pc, "non-zero reserved bits\n");
9145 			break;
9146 		case DIF_OP_BA:
9147 		case DIF_OP_BE:
9148 		case DIF_OP_BNE:
9149 		case DIF_OP_BG:
9150 		case DIF_OP_BGU:
9151 		case DIF_OP_BGE:
9152 		case DIF_OP_BGEU:
9153 		case DIF_OP_BL:
9154 		case DIF_OP_BLU:
9155 		case DIF_OP_BLE:
9156 		case DIF_OP_BLEU:
9157 			if (label >= dp->dtdo_len) {
9158 				err += efunc(pc, "invalid branch target %u\n",
9159 				    label);
9160 			}
9161 			if (label <= pc) {
9162 				err += efunc(pc, "backward branch to %u\n",
9163 				    label);
9164 			}
9165 			break;
9166 		case DIF_OP_RET:
9167 			if (r1 != 0 || r2 != 0)
9168 				err += efunc(pc, "non-zero reserved bits\n");
9169 			if (rd >= nregs)
9170 				err += efunc(pc, "invalid register %u\n", rd);
9171 			break;
9172 		case DIF_OP_NOP:
9173 		case DIF_OP_POPTS:
9174 		case DIF_OP_FLUSHTS:
9175 			if (r1 != 0 || r2 != 0 || rd != 0)
9176 				err += efunc(pc, "non-zero reserved bits\n");
9177 			break;
9178 		case DIF_OP_SETX:
9179 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9180 				err += efunc(pc, "invalid integer ref %u\n",
9181 				    DIF_INSTR_INTEGER(instr));
9182 			}
9183 			if (rd >= nregs)
9184 				err += efunc(pc, "invalid register %u\n", rd);
9185 			if (rd == 0)
9186 				err += efunc(pc, "cannot write to %r0\n");
9187 			break;
9188 		case DIF_OP_SETS:
9189 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9190 				err += efunc(pc, "invalid string ref %u\n",
9191 				    DIF_INSTR_STRING(instr));
9192 			}
9193 			if (rd >= nregs)
9194 				err += efunc(pc, "invalid register %u\n", rd);
9195 			if (rd == 0)
9196 				err += efunc(pc, "cannot write to %r0\n");
9197 			break;
9198 		case DIF_OP_LDGA:
9199 		case DIF_OP_LDTA:
9200 			if (r1 > DIF_VAR_ARRAY_MAX)
9201 				err += efunc(pc, "invalid array %u\n", r1);
9202 			if (r2 >= nregs)
9203 				err += efunc(pc, "invalid register %u\n", r2);
9204 			if (rd >= nregs)
9205 				err += efunc(pc, "invalid register %u\n", rd);
9206 			if (rd == 0)
9207 				err += efunc(pc, "cannot write to %r0\n");
9208 			break;
9209 		case DIF_OP_LDGS:
9210 		case DIF_OP_LDTS:
9211 		case DIF_OP_LDLS:
9212 		case DIF_OP_LDGAA:
9213 		case DIF_OP_LDTAA:
9214 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9215 				err += efunc(pc, "invalid variable %u\n", v);
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_STGS:
9222 		case DIF_OP_STTS:
9223 		case DIF_OP_STLS:
9224 		case DIF_OP_STGAA:
9225 		case DIF_OP_STTAA:
9226 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9227 				err += efunc(pc, "invalid variable %u\n", v);
9228 			if (rs >= nregs)
9229 				err += efunc(pc, "invalid register %u\n", rd);
9230 			break;
9231 		case DIF_OP_CALL:
9232 			if (subr > DIF_SUBR_MAX)
9233 				err += efunc(pc, "invalid subr %u\n", subr);
9234 			if (rd >= nregs)
9235 				err += efunc(pc, "invalid register %u\n", rd);
9236 			if (rd == 0)
9237 				err += efunc(pc, "cannot write to %r0\n");
9238 
9239 			if (subr == DIF_SUBR_COPYOUT ||
9240 			    subr == DIF_SUBR_COPYOUTSTR) {
9241 				dp->dtdo_destructive = 1;
9242 			}
9243 
9244 			if (subr == DIF_SUBR_GETF) {
9245 				/*
9246 				 * If we have a getf() we need to record that
9247 				 * in our state.  Note that our state can be
9248 				 * NULL if this is a helper -- but in that
9249 				 * case, the call to getf() is itself illegal,
9250 				 * and will be caught (slightly later) when
9251 				 * the helper is validated.
9252 				 */
9253 				if (vstate->dtvs_state != NULL)
9254 					vstate->dtvs_state->dts_getf++;
9255 			}
9256 
9257 			break;
9258 		case DIF_OP_PUSHTR:
9259 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9260 				err += efunc(pc, "invalid ref type %u\n", type);
9261 			if (r2 >= nregs)
9262 				err += efunc(pc, "invalid register %u\n", r2);
9263 			if (rs >= nregs)
9264 				err += efunc(pc, "invalid register %u\n", rs);
9265 			break;
9266 		case DIF_OP_PUSHTV:
9267 			if (type != DIF_TYPE_CTF)
9268 				err += efunc(pc, "invalid val type %u\n", type);
9269 			if (r2 >= nregs)
9270 				err += efunc(pc, "invalid register %u\n", r2);
9271 			if (rs >= nregs)
9272 				err += efunc(pc, "invalid register %u\n", rs);
9273 			break;
9274 		default:
9275 			err += efunc(pc, "invalid opcode %u\n",
9276 			    DIF_INSTR_OP(instr));
9277 		}
9278 	}
9279 
9280 	if (dp->dtdo_len != 0 &&
9281 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9282 		err += efunc(dp->dtdo_len - 1,
9283 		    "expected 'ret' as last DIF instruction\n");
9284 	}
9285 
9286 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
9287 		/*
9288 		 * If we're not returning by reference, the size must be either
9289 		 * 0 or the size of one of the base types.
9290 		 */
9291 		switch (dp->dtdo_rtype.dtdt_size) {
9292 		case 0:
9293 		case sizeof (uint8_t):
9294 		case sizeof (uint16_t):
9295 		case sizeof (uint32_t):
9296 		case sizeof (uint64_t):
9297 			break;
9298 
9299 		default:
9300 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
9301 		}
9302 	}
9303 
9304 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9305 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9306 		dtrace_diftype_t *vt, *et;
9307 		uint_t id, ndx;
9308 
9309 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9310 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
9311 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9312 			err += efunc(i, "unrecognized variable scope %d\n",
9313 			    v->dtdv_scope);
9314 			break;
9315 		}
9316 
9317 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9318 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
9319 			err += efunc(i, "unrecognized variable type %d\n",
9320 			    v->dtdv_kind);
9321 			break;
9322 		}
9323 
9324 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9325 			err += efunc(i, "%d exceeds variable id limit\n", id);
9326 			break;
9327 		}
9328 
9329 		if (id < DIF_VAR_OTHER_UBASE)
9330 			continue;
9331 
9332 		/*
9333 		 * For user-defined variables, we need to check that this
9334 		 * definition is identical to any previous definition that we
9335 		 * encountered.
9336 		 */
9337 		ndx = id - DIF_VAR_OTHER_UBASE;
9338 
9339 		switch (v->dtdv_scope) {
9340 		case DIFV_SCOPE_GLOBAL:
9341 			if (ndx < vstate->dtvs_nglobals) {
9342 				dtrace_statvar_t *svar;
9343 
9344 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9345 					existing = &svar->dtsv_var;
9346 			}
9347 
9348 			break;
9349 
9350 		case DIFV_SCOPE_THREAD:
9351 			if (ndx < vstate->dtvs_ntlocals)
9352 				existing = &vstate->dtvs_tlocals[ndx];
9353 			break;
9354 
9355 		case DIFV_SCOPE_LOCAL:
9356 			if (ndx < vstate->dtvs_nlocals) {
9357 				dtrace_statvar_t *svar;
9358 
9359 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9360 					existing = &svar->dtsv_var;
9361 			}
9362 
9363 			break;
9364 		}
9365 
9366 		vt = &v->dtdv_type;
9367 
9368 		if (vt->dtdt_flags & DIF_TF_BYREF) {
9369 			if (vt->dtdt_size == 0) {
9370 				err += efunc(i, "zero-sized variable\n");
9371 				break;
9372 			}
9373 
9374 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
9375 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
9376 			    vt->dtdt_size > dtrace_statvar_maxsize) {
9377 				err += efunc(i, "oversized by-ref static\n");
9378 				break;
9379 			}
9380 		}
9381 
9382 		if (existing == NULL || existing->dtdv_id == 0)
9383 			continue;
9384 
9385 		ASSERT(existing->dtdv_id == v->dtdv_id);
9386 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
9387 
9388 		if (existing->dtdv_kind != v->dtdv_kind)
9389 			err += efunc(i, "%d changed variable kind\n", id);
9390 
9391 		et = &existing->dtdv_type;
9392 
9393 		if (vt->dtdt_flags != et->dtdt_flags) {
9394 			err += efunc(i, "%d changed variable type flags\n", id);
9395 			break;
9396 		}
9397 
9398 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9399 			err += efunc(i, "%d changed variable type size\n", id);
9400 			break;
9401 		}
9402 	}
9403 
9404 	return (err);
9405 }
9406 
9407 /*
9408  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
9409  * are much more constrained than normal DIFOs.  Specifically, they may
9410  * not:
9411  *
9412  * 1. Make calls to subroutines other than copyin(), copyinstr() or
9413  *    miscellaneous string routines
9414  * 2. Access DTrace variables other than the args[] array, and the
9415  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9416  * 3. Have thread-local variables.
9417  * 4. Have dynamic variables.
9418  */
9419 static int
9420 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9421 {
9422 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9423 	int err = 0;
9424 	uint_t pc;
9425 
9426 	for (pc = 0; pc < dp->dtdo_len; pc++) {
9427 		dif_instr_t instr = dp->dtdo_buf[pc];
9428 
9429 		uint_t v = DIF_INSTR_VAR(instr);
9430 		uint_t subr = DIF_INSTR_SUBR(instr);
9431 		uint_t op = DIF_INSTR_OP(instr);
9432 
9433 		switch (op) {
9434 		case DIF_OP_OR:
9435 		case DIF_OP_XOR:
9436 		case DIF_OP_AND:
9437 		case DIF_OP_SLL:
9438 		case DIF_OP_SRL:
9439 		case DIF_OP_SRA:
9440 		case DIF_OP_SUB:
9441 		case DIF_OP_ADD:
9442 		case DIF_OP_MUL:
9443 		case DIF_OP_SDIV:
9444 		case DIF_OP_UDIV:
9445 		case DIF_OP_SREM:
9446 		case DIF_OP_UREM:
9447 		case DIF_OP_COPYS:
9448 		case DIF_OP_NOT:
9449 		case DIF_OP_MOV:
9450 		case DIF_OP_RLDSB:
9451 		case DIF_OP_RLDSH:
9452 		case DIF_OP_RLDSW:
9453 		case DIF_OP_RLDUB:
9454 		case DIF_OP_RLDUH:
9455 		case DIF_OP_RLDUW:
9456 		case DIF_OP_RLDX:
9457 		case DIF_OP_ULDSB:
9458 		case DIF_OP_ULDSH:
9459 		case DIF_OP_ULDSW:
9460 		case DIF_OP_ULDUB:
9461 		case DIF_OP_ULDUH:
9462 		case DIF_OP_ULDUW:
9463 		case DIF_OP_ULDX:
9464 		case DIF_OP_STB:
9465 		case DIF_OP_STH:
9466 		case DIF_OP_STW:
9467 		case DIF_OP_STX:
9468 		case DIF_OP_ALLOCS:
9469 		case DIF_OP_CMP:
9470 		case DIF_OP_SCMP:
9471 		case DIF_OP_TST:
9472 		case DIF_OP_BA:
9473 		case DIF_OP_BE:
9474 		case DIF_OP_BNE:
9475 		case DIF_OP_BG:
9476 		case DIF_OP_BGU:
9477 		case DIF_OP_BGE:
9478 		case DIF_OP_BGEU:
9479 		case DIF_OP_BL:
9480 		case DIF_OP_BLU:
9481 		case DIF_OP_BLE:
9482 		case DIF_OP_BLEU:
9483 		case DIF_OP_RET:
9484 		case DIF_OP_NOP:
9485 		case DIF_OP_POPTS:
9486 		case DIF_OP_FLUSHTS:
9487 		case DIF_OP_SETX:
9488 		case DIF_OP_SETS:
9489 		case DIF_OP_LDGA:
9490 		case DIF_OP_LDLS:
9491 		case DIF_OP_STGS:
9492 		case DIF_OP_STLS:
9493 		case DIF_OP_PUSHTR:
9494 		case DIF_OP_PUSHTV:
9495 			break;
9496 
9497 		case DIF_OP_LDGS:
9498 			if (v >= DIF_VAR_OTHER_UBASE)
9499 				break;
9500 
9501 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9502 				break;
9503 
9504 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9505 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9506 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9507 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
9508 				break;
9509 
9510 			err += efunc(pc, "illegal variable %u\n", v);
9511 			break;
9512 
9513 		case DIF_OP_LDTA:
9514 		case DIF_OP_LDTS:
9515 		case DIF_OP_LDGAA:
9516 		case DIF_OP_LDTAA:
9517 			err += efunc(pc, "illegal dynamic variable load\n");
9518 			break;
9519 
9520 		case DIF_OP_STTS:
9521 		case DIF_OP_STGAA:
9522 		case DIF_OP_STTAA:
9523 			err += efunc(pc, "illegal dynamic variable store\n");
9524 			break;
9525 
9526 		case DIF_OP_CALL:
9527 			if (subr == DIF_SUBR_ALLOCA ||
9528 			    subr == DIF_SUBR_BCOPY ||
9529 			    subr == DIF_SUBR_COPYIN ||
9530 			    subr == DIF_SUBR_COPYINTO ||
9531 			    subr == DIF_SUBR_COPYINSTR ||
9532 			    subr == DIF_SUBR_INDEX ||
9533 			    subr == DIF_SUBR_INET_NTOA ||
9534 			    subr == DIF_SUBR_INET_NTOA6 ||
9535 			    subr == DIF_SUBR_INET_NTOP ||
9536 			    subr == DIF_SUBR_JSON ||
9537 			    subr == DIF_SUBR_LLTOSTR ||
9538 			    subr == DIF_SUBR_STRTOLL ||
9539 			    subr == DIF_SUBR_RINDEX ||
9540 			    subr == DIF_SUBR_STRCHR ||
9541 			    subr == DIF_SUBR_STRJOIN ||
9542 			    subr == DIF_SUBR_STRRCHR ||
9543 			    subr == DIF_SUBR_STRSTR ||
9544 			    subr == DIF_SUBR_HTONS ||
9545 			    subr == DIF_SUBR_HTONL ||
9546 			    subr == DIF_SUBR_HTONLL ||
9547 			    subr == DIF_SUBR_NTOHS ||
9548 			    subr == DIF_SUBR_NTOHL ||
9549 			    subr == DIF_SUBR_NTOHLL)
9550 				break;
9551 
9552 			err += efunc(pc, "invalid subr %u\n", subr);
9553 			break;
9554 
9555 		default:
9556 			err += efunc(pc, "invalid opcode %u\n",
9557 			    DIF_INSTR_OP(instr));
9558 		}
9559 	}
9560 
9561 	return (err);
9562 }
9563 
9564 /*
9565  * Returns 1 if the expression in the DIF object can be cached on a per-thread
9566  * basis; 0 if not.
9567  */
9568 static int
9569 dtrace_difo_cacheable(dtrace_difo_t *dp)
9570 {
9571 	int i;
9572 
9573 	if (dp == NULL)
9574 		return (0);
9575 
9576 	for (i = 0; i < dp->dtdo_varlen; i++) {
9577 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9578 
9579 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9580 			continue;
9581 
9582 		switch (v->dtdv_id) {
9583 		case DIF_VAR_CURTHREAD:
9584 		case DIF_VAR_PID:
9585 		case DIF_VAR_TID:
9586 		case DIF_VAR_EXECNAME:
9587 		case DIF_VAR_ZONENAME:
9588 			break;
9589 
9590 		default:
9591 			return (0);
9592 		}
9593 	}
9594 
9595 	/*
9596 	 * This DIF object may be cacheable.  Now we need to look for any
9597 	 * array loading instructions, any memory loading instructions, or
9598 	 * any stores to thread-local variables.
9599 	 */
9600 	for (i = 0; i < dp->dtdo_len; i++) {
9601 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9602 
9603 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9604 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9605 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9606 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
9607 			return (0);
9608 	}
9609 
9610 	return (1);
9611 }
9612 
9613 static void
9614 dtrace_difo_hold(dtrace_difo_t *dp)
9615 {
9616 	int i;
9617 
9618 	ASSERT(MUTEX_HELD(&dtrace_lock));
9619 
9620 	dp->dtdo_refcnt++;
9621 	ASSERT(dp->dtdo_refcnt != 0);
9622 
9623 	/*
9624 	 * We need to check this DIF object for references to the variable
9625 	 * DIF_VAR_VTIMESTAMP.
9626 	 */
9627 	for (i = 0; i < dp->dtdo_varlen; i++) {
9628 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9629 
9630 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9631 			continue;
9632 
9633 		if (dtrace_vtime_references++ == 0)
9634 			dtrace_vtime_enable();
9635 	}
9636 }
9637 
9638 /*
9639  * This routine calculates the dynamic variable chunksize for a given DIF
9640  * object.  The calculation is not fool-proof, and can probably be tricked by
9641  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
9642  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9643  * if a dynamic variable size exceeds the chunksize.
9644  */
9645 static void
9646 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9647 {
9648 	uint64_t sval;
9649 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9650 	const dif_instr_t *text = dp->dtdo_buf;
9651 	uint_t pc, srd = 0;
9652 	uint_t ttop = 0;
9653 	size_t size, ksize;
9654 	uint_t id, i;
9655 
9656 	for (pc = 0; pc < dp->dtdo_len; pc++) {
9657 		dif_instr_t instr = text[pc];
9658 		uint_t op = DIF_INSTR_OP(instr);
9659 		uint_t rd = DIF_INSTR_RD(instr);
9660 		uint_t r1 = DIF_INSTR_R1(instr);
9661 		uint_t nkeys = 0;
9662 		uchar_t scope;
9663 
9664 		dtrace_key_t *key = tupregs;
9665 
9666 		switch (op) {
9667 		case DIF_OP_SETX:
9668 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9669 			srd = rd;
9670 			continue;
9671 
9672 		case DIF_OP_STTS:
9673 			key = &tupregs[DIF_DTR_NREGS];
9674 			key[0].dttk_size = 0;
9675 			key[1].dttk_size = 0;
9676 			nkeys = 2;
9677 			scope = DIFV_SCOPE_THREAD;
9678 			break;
9679 
9680 		case DIF_OP_STGAA:
9681 		case DIF_OP_STTAA:
9682 			nkeys = ttop;
9683 
9684 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9685 				key[nkeys++].dttk_size = 0;
9686 
9687 			key[nkeys++].dttk_size = 0;
9688 
9689 			if (op == DIF_OP_STTAA) {
9690 				scope = DIFV_SCOPE_THREAD;
9691 			} else {
9692 				scope = DIFV_SCOPE_GLOBAL;
9693 			}
9694 
9695 			break;
9696 
9697 		case DIF_OP_PUSHTR:
9698 			if (ttop == DIF_DTR_NREGS)
9699 				return;
9700 
9701 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
9702 				/*
9703 				 * If the register for the size of the "pushtr"
9704 				 * is %r0 (or the value is 0) and the type is
9705 				 * a string, we'll use the system-wide default
9706 				 * string size.
9707 				 */
9708 				tupregs[ttop++].dttk_size =
9709 				    dtrace_strsize_default;
9710 			} else {
9711 				if (srd == 0)
9712 					return;
9713 
9714 				if (sval > LONG_MAX)
9715 					return;
9716 
9717 				tupregs[ttop++].dttk_size = sval;
9718 			}
9719 
9720 			break;
9721 
9722 		case DIF_OP_PUSHTV:
9723 			if (ttop == DIF_DTR_NREGS)
9724 				return;
9725 
9726 			tupregs[ttop++].dttk_size = 0;
9727 			break;
9728 
9729 		case DIF_OP_FLUSHTS:
9730 			ttop = 0;
9731 			break;
9732 
9733 		case DIF_OP_POPTS:
9734 			if (ttop != 0)
9735 				ttop--;
9736 			break;
9737 		}
9738 
9739 		sval = 0;
9740 		srd = 0;
9741 
9742 		if (nkeys == 0)
9743 			continue;
9744 
9745 		/*
9746 		 * We have a dynamic variable allocation; calculate its size.
9747 		 */
9748 		for (ksize = 0, i = 0; i < nkeys; i++)
9749 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
9750 
9751 		size = sizeof (dtrace_dynvar_t);
9752 		size += sizeof (dtrace_key_t) * (nkeys - 1);
9753 		size += ksize;
9754 
9755 		/*
9756 		 * Now we need to determine the size of the stored data.
9757 		 */
9758 		id = DIF_INSTR_VAR(instr);
9759 
9760 		for (i = 0; i < dp->dtdo_varlen; i++) {
9761 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
9762 
9763 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
9764 				size += v->dtdv_type.dtdt_size;
9765 				break;
9766 			}
9767 		}
9768 
9769 		if (i == dp->dtdo_varlen)
9770 			return;
9771 
9772 		/*
9773 		 * We have the size.  If this is larger than the chunk size
9774 		 * for our dynamic variable state, reset the chunk size.
9775 		 */
9776 		size = P2ROUNDUP(size, sizeof (uint64_t));
9777 
9778 		/*
9779 		 * Before setting the chunk size, check that we're not going
9780 		 * to set it to a negative value...
9781 		 */
9782 		if (size > LONG_MAX)
9783 			return;
9784 
9785 		/*
9786 		 * ...and make certain that we didn't badly overflow.
9787 		 */
9788 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
9789 			return;
9790 
9791 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
9792 			vstate->dtvs_dynvars.dtds_chunksize = size;
9793 	}
9794 }
9795 
9796 static void
9797 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9798 {
9799 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
9800 	uint_t id;
9801 
9802 	ASSERT(MUTEX_HELD(&dtrace_lock));
9803 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
9804 
9805 	for (i = 0; i < dp->dtdo_varlen; i++) {
9806 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9807 		dtrace_statvar_t *svar, ***svarp;
9808 		size_t dsize = 0;
9809 		uint8_t scope = v->dtdv_scope;
9810 		int *np;
9811 
9812 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9813 			continue;
9814 
9815 		id -= DIF_VAR_OTHER_UBASE;
9816 
9817 		switch (scope) {
9818 		case DIFV_SCOPE_THREAD:
9819 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
9820 				dtrace_difv_t *tlocals;
9821 
9822 				if ((ntlocals = (otlocals << 1)) == 0)
9823 					ntlocals = 1;
9824 
9825 				osz = otlocals * sizeof (dtrace_difv_t);
9826 				nsz = ntlocals * sizeof (dtrace_difv_t);
9827 
9828 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
9829 
9830 				if (osz != 0) {
9831 					bcopy(vstate->dtvs_tlocals,
9832 					    tlocals, osz);
9833 					kmem_free(vstate->dtvs_tlocals, osz);
9834 				}
9835 
9836 				vstate->dtvs_tlocals = tlocals;
9837 				vstate->dtvs_ntlocals = ntlocals;
9838 			}
9839 
9840 			vstate->dtvs_tlocals[id] = *v;
9841 			continue;
9842 
9843 		case DIFV_SCOPE_LOCAL:
9844 			np = &vstate->dtvs_nlocals;
9845 			svarp = &vstate->dtvs_locals;
9846 
9847 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9848 				dsize = NCPU * (v->dtdv_type.dtdt_size +
9849 				    sizeof (uint64_t));
9850 			else
9851 				dsize = NCPU * sizeof (uint64_t);
9852 
9853 			break;
9854 
9855 		case DIFV_SCOPE_GLOBAL:
9856 			np = &vstate->dtvs_nglobals;
9857 			svarp = &vstate->dtvs_globals;
9858 
9859 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
9860 				dsize = v->dtdv_type.dtdt_size +
9861 				    sizeof (uint64_t);
9862 
9863 			break;
9864 
9865 		default:
9866 			ASSERT(0);
9867 		}
9868 
9869 		while (id >= (oldsvars = *np)) {
9870 			dtrace_statvar_t **statics;
9871 			int newsvars, oldsize, newsize;
9872 
9873 			if ((newsvars = (oldsvars << 1)) == 0)
9874 				newsvars = 1;
9875 
9876 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
9877 			newsize = newsvars * sizeof (dtrace_statvar_t *);
9878 
9879 			statics = kmem_zalloc(newsize, KM_SLEEP);
9880 
9881 			if (oldsize != 0) {
9882 				bcopy(*svarp, statics, oldsize);
9883 				kmem_free(*svarp, oldsize);
9884 			}
9885 
9886 			*svarp = statics;
9887 			*np = newsvars;
9888 		}
9889 
9890 		if ((svar = (*svarp)[id]) == NULL) {
9891 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9892 			svar->dtsv_var = *v;
9893 
9894 			if ((svar->dtsv_size = dsize) != 0) {
9895 				svar->dtsv_data = (uint64_t)(uintptr_t)
9896 				    kmem_zalloc(dsize, KM_SLEEP);
9897 			}
9898 
9899 			(*svarp)[id] = svar;
9900 		}
9901 
9902 		svar->dtsv_refcnt++;
9903 	}
9904 
9905 	dtrace_difo_chunksize(dp, vstate);
9906 	dtrace_difo_hold(dp);
9907 }
9908 
9909 static dtrace_difo_t *
9910 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9911 {
9912 	dtrace_difo_t *new;
9913 	size_t sz;
9914 
9915 	ASSERT(dp->dtdo_buf != NULL);
9916 	ASSERT(dp->dtdo_refcnt != 0);
9917 
9918 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9919 
9920 	ASSERT(dp->dtdo_buf != NULL);
9921 	sz = dp->dtdo_len * sizeof (dif_instr_t);
9922 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9923 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9924 	new->dtdo_len = dp->dtdo_len;
9925 
9926 	if (dp->dtdo_strtab != NULL) {
9927 		ASSERT(dp->dtdo_strlen != 0);
9928 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9929 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9930 		new->dtdo_strlen = dp->dtdo_strlen;
9931 	}
9932 
9933 	if (dp->dtdo_inttab != NULL) {
9934 		ASSERT(dp->dtdo_intlen != 0);
9935 		sz = dp->dtdo_intlen * sizeof (uint64_t);
9936 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9937 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9938 		new->dtdo_intlen = dp->dtdo_intlen;
9939 	}
9940 
9941 	if (dp->dtdo_vartab != NULL) {
9942 		ASSERT(dp->dtdo_varlen != 0);
9943 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9944 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9945 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9946 		new->dtdo_varlen = dp->dtdo_varlen;
9947 	}
9948 
9949 	dtrace_difo_init(new, vstate);
9950 	return (new);
9951 }
9952 
9953 static void
9954 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9955 {
9956 	int i;
9957 
9958 	ASSERT(dp->dtdo_refcnt == 0);
9959 
9960 	for (i = 0; i < dp->dtdo_varlen; i++) {
9961 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9962 		dtrace_statvar_t *svar, **svarp;
9963 		uint_t id;
9964 		uint8_t scope = v->dtdv_scope;
9965 		int *np;
9966 
9967 		switch (scope) {
9968 		case DIFV_SCOPE_THREAD:
9969 			continue;
9970 
9971 		case DIFV_SCOPE_LOCAL:
9972 			np = &vstate->dtvs_nlocals;
9973 			svarp = vstate->dtvs_locals;
9974 			break;
9975 
9976 		case DIFV_SCOPE_GLOBAL:
9977 			np = &vstate->dtvs_nglobals;
9978 			svarp = vstate->dtvs_globals;
9979 			break;
9980 
9981 		default:
9982 			ASSERT(0);
9983 		}
9984 
9985 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9986 			continue;
9987 
9988 		id -= DIF_VAR_OTHER_UBASE;
9989 		ASSERT(id < *np);
9990 
9991 		svar = svarp[id];
9992 		ASSERT(svar != NULL);
9993 		ASSERT(svar->dtsv_refcnt > 0);
9994 
9995 		if (--svar->dtsv_refcnt > 0)
9996 			continue;
9997 
9998 		if (svar->dtsv_size != 0) {
9999 			ASSERT(svar->dtsv_data != NULL);
10000 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10001 			    svar->dtsv_size);
10002 		}
10003 
10004 		kmem_free(svar, sizeof (dtrace_statvar_t));
10005 		svarp[id] = NULL;
10006 	}
10007 
10008 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10009 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10010 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10011 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10012 
10013 	kmem_free(dp, sizeof (dtrace_difo_t));
10014 }
10015 
10016 static void
10017 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10018 {
10019 	int i;
10020 
10021 	ASSERT(MUTEX_HELD(&dtrace_lock));
10022 	ASSERT(dp->dtdo_refcnt != 0);
10023 
10024 	for (i = 0; i < dp->dtdo_varlen; i++) {
10025 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10026 
10027 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10028 			continue;
10029 
10030 		ASSERT(dtrace_vtime_references > 0);
10031 		if (--dtrace_vtime_references == 0)
10032 			dtrace_vtime_disable();
10033 	}
10034 
10035 	if (--dp->dtdo_refcnt == 0)
10036 		dtrace_difo_destroy(dp, vstate);
10037 }
10038 
10039 /*
10040  * DTrace Format Functions
10041  */
10042 static uint16_t
10043 dtrace_format_add(dtrace_state_t *state, char *str)
10044 {
10045 	char *fmt, **new;
10046 	uint16_t ndx, len = strlen(str) + 1;
10047 
10048 	fmt = kmem_zalloc(len, KM_SLEEP);
10049 	bcopy(str, fmt, len);
10050 
10051 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10052 		if (state->dts_formats[ndx] == NULL) {
10053 			state->dts_formats[ndx] = fmt;
10054 			return (ndx + 1);
10055 		}
10056 	}
10057 
10058 	if (state->dts_nformats == USHRT_MAX) {
10059 		/*
10060 		 * This is only likely if a denial-of-service attack is being
10061 		 * attempted.  As such, it's okay to fail silently here.
10062 		 */
10063 		kmem_free(fmt, len);
10064 		return (0);
10065 	}
10066 
10067 	/*
10068 	 * For simplicity, we always resize the formats array to be exactly the
10069 	 * number of formats.
10070 	 */
10071 	ndx = state->dts_nformats++;
10072 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10073 
10074 	if (state->dts_formats != NULL) {
10075 		ASSERT(ndx != 0);
10076 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
10077 		kmem_free(state->dts_formats, ndx * sizeof (char *));
10078 	}
10079 
10080 	state->dts_formats = new;
10081 	state->dts_formats[ndx] = fmt;
10082 
10083 	return (ndx + 1);
10084 }
10085 
10086 static void
10087 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10088 {
10089 	char *fmt;
10090 
10091 	ASSERT(state->dts_formats != NULL);
10092 	ASSERT(format <= state->dts_nformats);
10093 	ASSERT(state->dts_formats[format - 1] != NULL);
10094 
10095 	fmt = state->dts_formats[format - 1];
10096 	kmem_free(fmt, strlen(fmt) + 1);
10097 	state->dts_formats[format - 1] = NULL;
10098 }
10099 
10100 static void
10101 dtrace_format_destroy(dtrace_state_t *state)
10102 {
10103 	int i;
10104 
10105 	if (state->dts_nformats == 0) {
10106 		ASSERT(state->dts_formats == NULL);
10107 		return;
10108 	}
10109 
10110 	ASSERT(state->dts_formats != NULL);
10111 
10112 	for (i = 0; i < state->dts_nformats; i++) {
10113 		char *fmt = state->dts_formats[i];
10114 
10115 		if (fmt == NULL)
10116 			continue;
10117 
10118 		kmem_free(fmt, strlen(fmt) + 1);
10119 	}
10120 
10121 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10122 	state->dts_nformats = 0;
10123 	state->dts_formats = NULL;
10124 }
10125 
10126 /*
10127  * DTrace Predicate Functions
10128  */
10129 static dtrace_predicate_t *
10130 dtrace_predicate_create(dtrace_difo_t *dp)
10131 {
10132 	dtrace_predicate_t *pred;
10133 
10134 	ASSERT(MUTEX_HELD(&dtrace_lock));
10135 	ASSERT(dp->dtdo_refcnt != 0);
10136 
10137 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10138 	pred->dtp_difo = dp;
10139 	pred->dtp_refcnt = 1;
10140 
10141 	if (!dtrace_difo_cacheable(dp))
10142 		return (pred);
10143 
10144 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10145 		/*
10146 		 * This is only theoretically possible -- we have had 2^32
10147 		 * cacheable predicates on this machine.  We cannot allow any
10148 		 * more predicates to become cacheable:  as unlikely as it is,
10149 		 * there may be a thread caching a (now stale) predicate cache
10150 		 * ID. (N.B.: the temptation is being successfully resisted to
10151 		 * have this cmn_err() "Holy shit -- we executed this code!")
10152 		 */
10153 		return (pred);
10154 	}
10155 
10156 	pred->dtp_cacheid = dtrace_predcache_id++;
10157 
10158 	return (pred);
10159 }
10160 
10161 static void
10162 dtrace_predicate_hold(dtrace_predicate_t *pred)
10163 {
10164 	ASSERT(MUTEX_HELD(&dtrace_lock));
10165 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10166 	ASSERT(pred->dtp_refcnt > 0);
10167 
10168 	pred->dtp_refcnt++;
10169 }
10170 
10171 static void
10172 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10173 {
10174 	dtrace_difo_t *dp = pred->dtp_difo;
10175 
10176 	ASSERT(MUTEX_HELD(&dtrace_lock));
10177 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10178 	ASSERT(pred->dtp_refcnt > 0);
10179 
10180 	if (--pred->dtp_refcnt == 0) {
10181 		dtrace_difo_release(pred->dtp_difo, vstate);
10182 		kmem_free(pred, sizeof (dtrace_predicate_t));
10183 	}
10184 }
10185 
10186 /*
10187  * DTrace Action Description Functions
10188  */
10189 static dtrace_actdesc_t *
10190 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10191     uint64_t uarg, uint64_t arg)
10192 {
10193 	dtrace_actdesc_t *act;
10194 
10195 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
10196 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
10197 
10198 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10199 	act->dtad_kind = kind;
10200 	act->dtad_ntuple = ntuple;
10201 	act->dtad_uarg = uarg;
10202 	act->dtad_arg = arg;
10203 	act->dtad_refcnt = 1;
10204 
10205 	return (act);
10206 }
10207 
10208 static void
10209 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10210 {
10211 	ASSERT(act->dtad_refcnt >= 1);
10212 	act->dtad_refcnt++;
10213 }
10214 
10215 static void
10216 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10217 {
10218 	dtrace_actkind_t kind = act->dtad_kind;
10219 	dtrace_difo_t *dp;
10220 
10221 	ASSERT(act->dtad_refcnt >= 1);
10222 
10223 	if (--act->dtad_refcnt != 0)
10224 		return;
10225 
10226 	if ((dp = act->dtad_difo) != NULL)
10227 		dtrace_difo_release(dp, vstate);
10228 
10229 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
10230 		char *str = (char *)(uintptr_t)act->dtad_arg;
10231 
10232 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10233 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10234 
10235 		if (str != NULL)
10236 			kmem_free(str, strlen(str) + 1);
10237 	}
10238 
10239 	kmem_free(act, sizeof (dtrace_actdesc_t));
10240 }
10241 
10242 /*
10243  * DTrace ECB Functions
10244  */
10245 static dtrace_ecb_t *
10246 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10247 {
10248 	dtrace_ecb_t *ecb;
10249 	dtrace_epid_t epid;
10250 
10251 	ASSERT(MUTEX_HELD(&dtrace_lock));
10252 
10253 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10254 	ecb->dte_predicate = NULL;
10255 	ecb->dte_probe = probe;
10256 
10257 	/*
10258 	 * The default size is the size of the default action: recording
10259 	 * the header.
10260 	 */
10261 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10262 	ecb->dte_alignment = sizeof (dtrace_epid_t);
10263 
10264 	epid = state->dts_epid++;
10265 
10266 	if (epid - 1 >= state->dts_necbs) {
10267 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10268 		int necbs = state->dts_necbs << 1;
10269 
10270 		ASSERT(epid == state->dts_necbs + 1);
10271 
10272 		if (necbs == 0) {
10273 			ASSERT(oecbs == NULL);
10274 			necbs = 1;
10275 		}
10276 
10277 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10278 
10279 		if (oecbs != NULL)
10280 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10281 
10282 		dtrace_membar_producer();
10283 		state->dts_ecbs = ecbs;
10284 
10285 		if (oecbs != NULL) {
10286 			/*
10287 			 * If this state is active, we must dtrace_sync()
10288 			 * before we can free the old dts_ecbs array:  we're
10289 			 * coming in hot, and there may be active ring
10290 			 * buffer processing (which indexes into the dts_ecbs
10291 			 * array) on another CPU.
10292 			 */
10293 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10294 				dtrace_sync();
10295 
10296 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10297 		}
10298 
10299 		dtrace_membar_producer();
10300 		state->dts_necbs = necbs;
10301 	}
10302 
10303 	ecb->dte_state = state;
10304 
10305 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
10306 	dtrace_membar_producer();
10307 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10308 
10309 	return (ecb);
10310 }
10311 
10312 static int
10313 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10314 {
10315 	dtrace_probe_t *probe = ecb->dte_probe;
10316 
10317 	ASSERT(MUTEX_HELD(&cpu_lock));
10318 	ASSERT(MUTEX_HELD(&dtrace_lock));
10319 	ASSERT(ecb->dte_next == NULL);
10320 
10321 	if (probe == NULL) {
10322 		/*
10323 		 * This is the NULL probe -- there's nothing to do.
10324 		 */
10325 		return (0);
10326 	}
10327 
10328 	if (probe->dtpr_ecb == NULL) {
10329 		dtrace_provider_t *prov = probe->dtpr_provider;
10330 
10331 		/*
10332 		 * We're the first ECB on this probe.
10333 		 */
10334 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10335 
10336 		if (ecb->dte_predicate != NULL)
10337 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10338 
10339 		return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10340 		    probe->dtpr_id, probe->dtpr_arg));
10341 	} else {
10342 		/*
10343 		 * This probe is already active.  Swing the last pointer to
10344 		 * point to the new ECB, and issue a dtrace_sync() to assure
10345 		 * that all CPUs have seen the change.
10346 		 */
10347 		ASSERT(probe->dtpr_ecb_last != NULL);
10348 		probe->dtpr_ecb_last->dte_next = ecb;
10349 		probe->dtpr_ecb_last = ecb;
10350 		probe->dtpr_predcache = 0;
10351 
10352 		dtrace_sync();
10353 		return (0);
10354 	}
10355 }
10356 
10357 static void
10358 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10359 {
10360 	dtrace_action_t *act;
10361 	uint32_t curneeded = UINT32_MAX;
10362 	uint32_t aggbase = UINT32_MAX;
10363 
10364 	/*
10365 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
10366 	 * we always record it first.)
10367 	 */
10368 	ecb->dte_size = sizeof (dtrace_rechdr_t);
10369 	ecb->dte_alignment = sizeof (dtrace_epid_t);
10370 
10371 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10372 		dtrace_recdesc_t *rec = &act->dta_rec;
10373 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10374 
10375 		ecb->dte_alignment = MAX(ecb->dte_alignment,
10376 		    rec->dtrd_alignment);
10377 
10378 		if (DTRACEACT_ISAGG(act->dta_kind)) {
10379 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10380 
10381 			ASSERT(rec->dtrd_size != 0);
10382 			ASSERT(agg->dtag_first != NULL);
10383 			ASSERT(act->dta_prev->dta_intuple);
10384 			ASSERT(aggbase != UINT32_MAX);
10385 			ASSERT(curneeded != UINT32_MAX);
10386 
10387 			agg->dtag_base = aggbase;
10388 
10389 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10390 			rec->dtrd_offset = curneeded;
10391 			curneeded += rec->dtrd_size;
10392 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10393 
10394 			aggbase = UINT32_MAX;
10395 			curneeded = UINT32_MAX;
10396 		} else if (act->dta_intuple) {
10397 			if (curneeded == UINT32_MAX) {
10398 				/*
10399 				 * This is the first record in a tuple.  Align
10400 				 * curneeded to be at offset 4 in an 8-byte
10401 				 * aligned block.
10402 				 */
10403 				ASSERT(act->dta_prev == NULL ||
10404 				    !act->dta_prev->dta_intuple);
10405 				ASSERT3U(aggbase, ==, UINT32_MAX);
10406 				curneeded = P2PHASEUP(ecb->dte_size,
10407 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
10408 
10409 				aggbase = curneeded - sizeof (dtrace_aggid_t);
10410 				ASSERT(IS_P2ALIGNED(aggbase,
10411 				    sizeof (uint64_t)));
10412 			}
10413 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10414 			rec->dtrd_offset = curneeded;
10415 			curneeded += rec->dtrd_size;
10416 		} else {
10417 			/* tuples must be followed by an aggregation */
10418 			ASSERT(act->dta_prev == NULL ||
10419 			    !act->dta_prev->dta_intuple);
10420 
10421 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10422 			    rec->dtrd_alignment);
10423 			rec->dtrd_offset = ecb->dte_size;
10424 			ecb->dte_size += rec->dtrd_size;
10425 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10426 		}
10427 	}
10428 
10429 	if ((act = ecb->dte_action) != NULL &&
10430 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10431 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10432 		/*
10433 		 * If the size is still sizeof (dtrace_rechdr_t), then all
10434 		 * actions store no data; set the size to 0.
10435 		 */
10436 		ecb->dte_size = 0;
10437 	}
10438 
10439 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10440 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10441 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10442 	    ecb->dte_needed);
10443 }
10444 
10445 static dtrace_action_t *
10446 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10447 {
10448 	dtrace_aggregation_t *agg;
10449 	size_t size = sizeof (uint64_t);
10450 	int ntuple = desc->dtad_ntuple;
10451 	dtrace_action_t *act;
10452 	dtrace_recdesc_t *frec;
10453 	dtrace_aggid_t aggid;
10454 	dtrace_state_t *state = ecb->dte_state;
10455 
10456 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10457 	agg->dtag_ecb = ecb;
10458 
10459 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10460 
10461 	switch (desc->dtad_kind) {
10462 	case DTRACEAGG_MIN:
10463 		agg->dtag_initial = INT64_MAX;
10464 		agg->dtag_aggregate = dtrace_aggregate_min;
10465 		break;
10466 
10467 	case DTRACEAGG_MAX:
10468 		agg->dtag_initial = INT64_MIN;
10469 		agg->dtag_aggregate = dtrace_aggregate_max;
10470 		break;
10471 
10472 	case DTRACEAGG_COUNT:
10473 		agg->dtag_aggregate = dtrace_aggregate_count;
10474 		break;
10475 
10476 	case DTRACEAGG_QUANTIZE:
10477 		agg->dtag_aggregate = dtrace_aggregate_quantize;
10478 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10479 		    sizeof (uint64_t);
10480 		break;
10481 
10482 	case DTRACEAGG_LQUANTIZE: {
10483 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10484 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10485 
10486 		agg->dtag_initial = desc->dtad_arg;
10487 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
10488 
10489 		if (step == 0 || levels == 0)
10490 			goto err;
10491 
10492 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10493 		break;
10494 	}
10495 
10496 	case DTRACEAGG_LLQUANTIZE: {
10497 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10498 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10499 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10500 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10501 		int64_t v;
10502 
10503 		agg->dtag_initial = desc->dtad_arg;
10504 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
10505 
10506 		if (factor < 2 || low >= high || nsteps < factor)
10507 			goto err;
10508 
10509 		/*
10510 		 * Now check that the number of steps evenly divides a power
10511 		 * of the factor.  (This assures both integer bucket size and
10512 		 * linearity within each magnitude.)
10513 		 */
10514 		for (v = factor; v < nsteps; v *= factor)
10515 			continue;
10516 
10517 		if ((v % nsteps) || (nsteps % factor))
10518 			goto err;
10519 
10520 		size = (dtrace_aggregate_llquantize_bucket(factor,
10521 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10522 		break;
10523 	}
10524 
10525 	case DTRACEAGG_AVG:
10526 		agg->dtag_aggregate = dtrace_aggregate_avg;
10527 		size = sizeof (uint64_t) * 2;
10528 		break;
10529 
10530 	case DTRACEAGG_STDDEV:
10531 		agg->dtag_aggregate = dtrace_aggregate_stddev;
10532 		size = sizeof (uint64_t) * 4;
10533 		break;
10534 
10535 	case DTRACEAGG_SUM:
10536 		agg->dtag_aggregate = dtrace_aggregate_sum;
10537 		break;
10538 
10539 	default:
10540 		goto err;
10541 	}
10542 
10543 	agg->dtag_action.dta_rec.dtrd_size = size;
10544 
10545 	if (ntuple == 0)
10546 		goto err;
10547 
10548 	/*
10549 	 * We must make sure that we have enough actions for the n-tuple.
10550 	 */
10551 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10552 		if (DTRACEACT_ISAGG(act->dta_kind))
10553 			break;
10554 
10555 		if (--ntuple == 0) {
10556 			/*
10557 			 * This is the action with which our n-tuple begins.
10558 			 */
10559 			agg->dtag_first = act;
10560 			goto success;
10561 		}
10562 	}
10563 
10564 	/*
10565 	 * This n-tuple is short by ntuple elements.  Return failure.
10566 	 */
10567 	ASSERT(ntuple != 0);
10568 err:
10569 	kmem_free(agg, sizeof (dtrace_aggregation_t));
10570 	return (NULL);
10571 
10572 success:
10573 	/*
10574 	 * If the last action in the tuple has a size of zero, it's actually
10575 	 * an expression argument for the aggregating action.
10576 	 */
10577 	ASSERT(ecb->dte_action_last != NULL);
10578 	act = ecb->dte_action_last;
10579 
10580 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
10581 		ASSERT(act->dta_difo != NULL);
10582 
10583 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10584 			agg->dtag_hasarg = 1;
10585 	}
10586 
10587 	/*
10588 	 * We need to allocate an id for this aggregation.
10589 	 */
10590 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10591 	    VM_BESTFIT | VM_SLEEP);
10592 
10593 	if (aggid - 1 >= state->dts_naggregations) {
10594 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
10595 		dtrace_aggregation_t **aggs;
10596 		int naggs = state->dts_naggregations << 1;
10597 		int onaggs = state->dts_naggregations;
10598 
10599 		ASSERT(aggid == state->dts_naggregations + 1);
10600 
10601 		if (naggs == 0) {
10602 			ASSERT(oaggs == NULL);
10603 			naggs = 1;
10604 		}
10605 
10606 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10607 
10608 		if (oaggs != NULL) {
10609 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10610 			kmem_free(oaggs, onaggs * sizeof (*aggs));
10611 		}
10612 
10613 		state->dts_aggregations = aggs;
10614 		state->dts_naggregations = naggs;
10615 	}
10616 
10617 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10618 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10619 
10620 	frec = &agg->dtag_first->dta_rec;
10621 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10622 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10623 
10624 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10625 		ASSERT(!act->dta_intuple);
10626 		act->dta_intuple = 1;
10627 	}
10628 
10629 	return (&agg->dtag_action);
10630 }
10631 
10632 static void
10633 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10634 {
10635 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10636 	dtrace_state_t *state = ecb->dte_state;
10637 	dtrace_aggid_t aggid = agg->dtag_id;
10638 
10639 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10640 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10641 
10642 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
10643 	state->dts_aggregations[aggid - 1] = NULL;
10644 
10645 	kmem_free(agg, sizeof (dtrace_aggregation_t));
10646 }
10647 
10648 static int
10649 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10650 {
10651 	dtrace_action_t *action, *last;
10652 	dtrace_difo_t *dp = desc->dtad_difo;
10653 	uint32_t size = 0, align = sizeof (uint8_t), mask;
10654 	uint16_t format = 0;
10655 	dtrace_recdesc_t *rec;
10656 	dtrace_state_t *state = ecb->dte_state;
10657 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
10658 	uint64_t arg = desc->dtad_arg;
10659 
10660 	ASSERT(MUTEX_HELD(&dtrace_lock));
10661 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10662 
10663 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10664 		/*
10665 		 * If this is an aggregating action, there must be neither
10666 		 * a speculate nor a commit on the action chain.
10667 		 */
10668 		dtrace_action_t *act;
10669 
10670 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10671 			if (act->dta_kind == DTRACEACT_COMMIT)
10672 				return (EINVAL);
10673 
10674 			if (act->dta_kind == DTRACEACT_SPECULATE)
10675 				return (EINVAL);
10676 		}
10677 
10678 		action = dtrace_ecb_aggregation_create(ecb, desc);
10679 
10680 		if (action == NULL)
10681 			return (EINVAL);
10682 	} else {
10683 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10684 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
10685 		    dp != NULL && dp->dtdo_destructive)) {
10686 			state->dts_destructive = 1;
10687 		}
10688 
10689 		switch (desc->dtad_kind) {
10690 		case DTRACEACT_PRINTF:
10691 		case DTRACEACT_PRINTA:
10692 		case DTRACEACT_SYSTEM:
10693 		case DTRACEACT_FREOPEN:
10694 		case DTRACEACT_DIFEXPR:
10695 			/*
10696 			 * We know that our arg is a string -- turn it into a
10697 			 * format.
10698 			 */
10699 			if (arg == NULL) {
10700 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
10701 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
10702 				format = 0;
10703 			} else {
10704 				ASSERT(arg != NULL);
10705 				ASSERT(arg > KERNELBASE);
10706 				format = dtrace_format_add(state,
10707 				    (char *)(uintptr_t)arg);
10708 			}
10709 
10710 			/*FALLTHROUGH*/
10711 		case DTRACEACT_LIBACT:
10712 		case DTRACEACT_TRACEMEM:
10713 		case DTRACEACT_TRACEMEM_DYNSIZE:
10714 			if (dp == NULL)
10715 				return (EINVAL);
10716 
10717 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
10718 				break;
10719 
10720 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
10721 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10722 					return (EINVAL);
10723 
10724 				size = opt[DTRACEOPT_STRSIZE];
10725 			}
10726 
10727 			break;
10728 
10729 		case DTRACEACT_STACK:
10730 			if ((nframes = arg) == 0) {
10731 				nframes = opt[DTRACEOPT_STACKFRAMES];
10732 				ASSERT(nframes > 0);
10733 				arg = nframes;
10734 			}
10735 
10736 			size = nframes * sizeof (pc_t);
10737 			break;
10738 
10739 		case DTRACEACT_JSTACK:
10740 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
10741 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
10742 
10743 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
10744 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
10745 
10746 			arg = DTRACE_USTACK_ARG(nframes, strsize);
10747 
10748 			/*FALLTHROUGH*/
10749 		case DTRACEACT_USTACK:
10750 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
10751 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
10752 				strsize = DTRACE_USTACK_STRSIZE(arg);
10753 				nframes = opt[DTRACEOPT_USTACKFRAMES];
10754 				ASSERT(nframes > 0);
10755 				arg = DTRACE_USTACK_ARG(nframes, strsize);
10756 			}
10757 
10758 			/*
10759 			 * Save a slot for the pid.
10760 			 */
10761 			size = (nframes + 1) * sizeof (uint64_t);
10762 			size += DTRACE_USTACK_STRSIZE(arg);
10763 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
10764 
10765 			break;
10766 
10767 		case DTRACEACT_SYM:
10768 		case DTRACEACT_MOD:
10769 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
10770 			    sizeof (uint64_t)) ||
10771 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10772 				return (EINVAL);
10773 			break;
10774 
10775 		case DTRACEACT_USYM:
10776 		case DTRACEACT_UMOD:
10777 		case DTRACEACT_UADDR:
10778 			if (dp == NULL ||
10779 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
10780 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10781 				return (EINVAL);
10782 
10783 			/*
10784 			 * We have a slot for the pid, plus a slot for the
10785 			 * argument.  To keep things simple (aligned with
10786 			 * bitness-neutral sizing), we store each as a 64-bit
10787 			 * quantity.
10788 			 */
10789 			size = 2 * sizeof (uint64_t);
10790 			break;
10791 
10792 		case DTRACEACT_STOP:
10793 		case DTRACEACT_BREAKPOINT:
10794 		case DTRACEACT_PANIC:
10795 			break;
10796 
10797 		case DTRACEACT_CHILL:
10798 		case DTRACEACT_DISCARD:
10799 		case DTRACEACT_RAISE:
10800 			if (dp == NULL)
10801 				return (EINVAL);
10802 			break;
10803 
10804 		case DTRACEACT_EXIT:
10805 			if (dp == NULL ||
10806 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
10807 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
10808 				return (EINVAL);
10809 			break;
10810 
10811 		case DTRACEACT_SPECULATE:
10812 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
10813 				return (EINVAL);
10814 
10815 			if (dp == NULL)
10816 				return (EINVAL);
10817 
10818 			state->dts_speculates = 1;
10819 			break;
10820 
10821 		case DTRACEACT_COMMIT: {
10822 			dtrace_action_t *act = ecb->dte_action;
10823 
10824 			for (; act != NULL; act = act->dta_next) {
10825 				if (act->dta_kind == DTRACEACT_COMMIT)
10826 					return (EINVAL);
10827 			}
10828 
10829 			if (dp == NULL)
10830 				return (EINVAL);
10831 			break;
10832 		}
10833 
10834 		default:
10835 			return (EINVAL);
10836 		}
10837 
10838 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
10839 			/*
10840 			 * If this is a data-storing action or a speculate,
10841 			 * we must be sure that there isn't a commit on the
10842 			 * action chain.
10843 			 */
10844 			dtrace_action_t *act = ecb->dte_action;
10845 
10846 			for (; act != NULL; act = act->dta_next) {
10847 				if (act->dta_kind == DTRACEACT_COMMIT)
10848 					return (EINVAL);
10849 			}
10850 		}
10851 
10852 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
10853 		action->dta_rec.dtrd_size = size;
10854 	}
10855 
10856 	action->dta_refcnt = 1;
10857 	rec = &action->dta_rec;
10858 	size = rec->dtrd_size;
10859 
10860 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10861 		if (!(size & mask)) {
10862 			align = mask + 1;
10863 			break;
10864 		}
10865 	}
10866 
10867 	action->dta_kind = desc->dtad_kind;
10868 
10869 	if ((action->dta_difo = dp) != NULL)
10870 		dtrace_difo_hold(dp);
10871 
10872 	rec->dtrd_action = action->dta_kind;
10873 	rec->dtrd_arg = arg;
10874 	rec->dtrd_uarg = desc->dtad_uarg;
10875 	rec->dtrd_alignment = (uint16_t)align;
10876 	rec->dtrd_format = format;
10877 
10878 	if ((last = ecb->dte_action_last) != NULL) {
10879 		ASSERT(ecb->dte_action != NULL);
10880 		action->dta_prev = last;
10881 		last->dta_next = action;
10882 	} else {
10883 		ASSERT(ecb->dte_action == NULL);
10884 		ecb->dte_action = action;
10885 	}
10886 
10887 	ecb->dte_action_last = action;
10888 
10889 	return (0);
10890 }
10891 
10892 static void
10893 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10894 {
10895 	dtrace_action_t *act = ecb->dte_action, *next;
10896 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10897 	dtrace_difo_t *dp;
10898 	uint16_t format;
10899 
10900 	if (act != NULL && act->dta_refcnt > 1) {
10901 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10902 		act->dta_refcnt--;
10903 	} else {
10904 		for (; act != NULL; act = next) {
10905 			next = act->dta_next;
10906 			ASSERT(next != NULL || act == ecb->dte_action_last);
10907 			ASSERT(act->dta_refcnt == 1);
10908 
10909 			if ((format = act->dta_rec.dtrd_format) != 0)
10910 				dtrace_format_remove(ecb->dte_state, format);
10911 
10912 			if ((dp = act->dta_difo) != NULL)
10913 				dtrace_difo_release(dp, vstate);
10914 
10915 			if (DTRACEACT_ISAGG(act->dta_kind)) {
10916 				dtrace_ecb_aggregation_destroy(ecb, act);
10917 			} else {
10918 				kmem_free(act, sizeof (dtrace_action_t));
10919 			}
10920 		}
10921 	}
10922 
10923 	ecb->dte_action = NULL;
10924 	ecb->dte_action_last = NULL;
10925 	ecb->dte_size = 0;
10926 }
10927 
10928 static void
10929 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10930 {
10931 	/*
10932 	 * We disable the ECB by removing it from its probe.
10933 	 */
10934 	dtrace_ecb_t *pecb, *prev = NULL;
10935 	dtrace_probe_t *probe = ecb->dte_probe;
10936 
10937 	ASSERT(MUTEX_HELD(&dtrace_lock));
10938 
10939 	if (probe == NULL) {
10940 		/*
10941 		 * This is the NULL probe; there is nothing to disable.
10942 		 */
10943 		return;
10944 	}
10945 
10946 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10947 		if (pecb == ecb)
10948 			break;
10949 		prev = pecb;
10950 	}
10951 
10952 	ASSERT(pecb != NULL);
10953 
10954 	if (prev == NULL) {
10955 		probe->dtpr_ecb = ecb->dte_next;
10956 	} else {
10957 		prev->dte_next = ecb->dte_next;
10958 	}
10959 
10960 	if (ecb == probe->dtpr_ecb_last) {
10961 		ASSERT(ecb->dte_next == NULL);
10962 		probe->dtpr_ecb_last = prev;
10963 	}
10964 
10965 	/*
10966 	 * The ECB has been disconnected from the probe; now sync to assure
10967 	 * that all CPUs have seen the change before returning.
10968 	 */
10969 	dtrace_sync();
10970 
10971 	if (probe->dtpr_ecb == NULL) {
10972 		/*
10973 		 * That was the last ECB on the probe; clear the predicate
10974 		 * cache ID for the probe, disable it and sync one more time
10975 		 * to assure that we'll never hit it again.
10976 		 */
10977 		dtrace_provider_t *prov = probe->dtpr_provider;
10978 
10979 		ASSERT(ecb->dte_next == NULL);
10980 		ASSERT(probe->dtpr_ecb_last == NULL);
10981 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10982 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10983 		    probe->dtpr_id, probe->dtpr_arg);
10984 		dtrace_sync();
10985 	} else {
10986 		/*
10987 		 * There is at least one ECB remaining on the probe.  If there
10988 		 * is _exactly_ one, set the probe's predicate cache ID to be
10989 		 * the predicate cache ID of the remaining ECB.
10990 		 */
10991 		ASSERT(probe->dtpr_ecb_last != NULL);
10992 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10993 
10994 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10995 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10996 
10997 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
10998 
10999 			if (p != NULL)
11000 				probe->dtpr_predcache = p->dtp_cacheid;
11001 		}
11002 
11003 		ecb->dte_next = NULL;
11004 	}
11005 }
11006 
11007 static void
11008 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11009 {
11010 	dtrace_state_t *state = ecb->dte_state;
11011 	dtrace_vstate_t *vstate = &state->dts_vstate;
11012 	dtrace_predicate_t *pred;
11013 	dtrace_epid_t epid = ecb->dte_epid;
11014 
11015 	ASSERT(MUTEX_HELD(&dtrace_lock));
11016 	ASSERT(ecb->dte_next == NULL);
11017 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11018 
11019 	if ((pred = ecb->dte_predicate) != NULL)
11020 		dtrace_predicate_release(pred, vstate);
11021 
11022 	dtrace_ecb_action_remove(ecb);
11023 
11024 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11025 	state->dts_ecbs[epid - 1] = NULL;
11026 
11027 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11028 }
11029 
11030 static dtrace_ecb_t *
11031 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11032     dtrace_enabling_t *enab)
11033 {
11034 	dtrace_ecb_t *ecb;
11035 	dtrace_predicate_t *pred;
11036 	dtrace_actdesc_t *act;
11037 	dtrace_provider_t *prov;
11038 	dtrace_ecbdesc_t *desc = enab->dten_current;
11039 
11040 	ASSERT(MUTEX_HELD(&dtrace_lock));
11041 	ASSERT(state != NULL);
11042 
11043 	ecb = dtrace_ecb_add(state, probe);
11044 	ecb->dte_uarg = desc->dted_uarg;
11045 
11046 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11047 		dtrace_predicate_hold(pred);
11048 		ecb->dte_predicate = pred;
11049 	}
11050 
11051 	if (probe != NULL) {
11052 		/*
11053 		 * If the provider shows more leg than the consumer is old
11054 		 * enough to see, we need to enable the appropriate implicit
11055 		 * predicate bits to prevent the ecb from activating at
11056 		 * revealing times.
11057 		 *
11058 		 * Providers specifying DTRACE_PRIV_USER at register time
11059 		 * are stating that they need the /proc-style privilege
11060 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11061 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11062 		 */
11063 		prov = probe->dtpr_provider;
11064 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11065 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11066 			ecb->dte_cond |= DTRACE_COND_OWNER;
11067 
11068 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11069 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11070 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11071 
11072 		/*
11073 		 * If the provider shows us kernel innards and the user
11074 		 * is lacking sufficient privilege, enable the
11075 		 * DTRACE_COND_USERMODE implicit predicate.
11076 		 */
11077 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11078 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11079 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11080 	}
11081 
11082 	if (dtrace_ecb_create_cache != NULL) {
11083 		/*
11084 		 * If we have a cached ecb, we'll use its action list instead
11085 		 * of creating our own (saving both time and space).
11086 		 */
11087 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11088 		dtrace_action_t *act = cached->dte_action;
11089 
11090 		if (act != NULL) {
11091 			ASSERT(act->dta_refcnt > 0);
11092 			act->dta_refcnt++;
11093 			ecb->dte_action = act;
11094 			ecb->dte_action_last = cached->dte_action_last;
11095 			ecb->dte_needed = cached->dte_needed;
11096 			ecb->dte_size = cached->dte_size;
11097 			ecb->dte_alignment = cached->dte_alignment;
11098 		}
11099 
11100 		return (ecb);
11101 	}
11102 
11103 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11104 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11105 			dtrace_ecb_destroy(ecb);
11106 			return (NULL);
11107 		}
11108 	}
11109 
11110 	dtrace_ecb_resize(ecb);
11111 
11112 	return (dtrace_ecb_create_cache = ecb);
11113 }
11114 
11115 static int
11116 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11117 {
11118 	dtrace_ecb_t *ecb;
11119 	dtrace_enabling_t *enab = arg;
11120 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11121 
11122 	ASSERT(state != NULL);
11123 
11124 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11125 		/*
11126 		 * This probe was created in a generation for which this
11127 		 * enabling has previously created ECBs; we don't want to
11128 		 * enable it again, so just kick out.
11129 		 */
11130 		return (DTRACE_MATCH_NEXT);
11131 	}
11132 
11133 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11134 		return (DTRACE_MATCH_DONE);
11135 
11136 	if (dtrace_ecb_enable(ecb) < 0)
11137 		return (DTRACE_MATCH_FAIL);
11138 
11139 	return (DTRACE_MATCH_NEXT);
11140 }
11141 
11142 static dtrace_ecb_t *
11143 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11144 {
11145 	dtrace_ecb_t *ecb;
11146 
11147 	ASSERT(MUTEX_HELD(&dtrace_lock));
11148 
11149 	if (id == 0 || id > state->dts_necbs)
11150 		return (NULL);
11151 
11152 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11153 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11154 
11155 	return (state->dts_ecbs[id - 1]);
11156 }
11157 
11158 static dtrace_aggregation_t *
11159 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11160 {
11161 	dtrace_aggregation_t *agg;
11162 
11163 	ASSERT(MUTEX_HELD(&dtrace_lock));
11164 
11165 	if (id == 0 || id > state->dts_naggregations)
11166 		return (NULL);
11167 
11168 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11169 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11170 	    agg->dtag_id == id);
11171 
11172 	return (state->dts_aggregations[id - 1]);
11173 }
11174 
11175 /*
11176  * DTrace Buffer Functions
11177  *
11178  * The following functions manipulate DTrace buffers.  Most of these functions
11179  * are called in the context of establishing or processing consumer state;
11180  * exceptions are explicitly noted.
11181  */
11182 
11183 /*
11184  * Note:  called from cross call context.  This function switches the two
11185  * buffers on a given CPU.  The atomicity of this operation is assured by
11186  * disabling interrupts while the actual switch takes place; the disabling of
11187  * interrupts serializes the execution with any execution of dtrace_probe() on
11188  * the same CPU.
11189  */
11190 static void
11191 dtrace_buffer_switch(dtrace_buffer_t *buf)
11192 {
11193 	caddr_t tomax = buf->dtb_tomax;
11194 	caddr_t xamot = buf->dtb_xamot;
11195 	dtrace_icookie_t cookie;
11196 	hrtime_t now;
11197 
11198 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11199 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11200 
11201 	cookie = dtrace_interrupt_disable();
11202 	now = dtrace_gethrtime();
11203 	buf->dtb_tomax = xamot;
11204 	buf->dtb_xamot = tomax;
11205 	buf->dtb_xamot_drops = buf->dtb_drops;
11206 	buf->dtb_xamot_offset = buf->dtb_offset;
11207 	buf->dtb_xamot_errors = buf->dtb_errors;
11208 	buf->dtb_xamot_flags = buf->dtb_flags;
11209 	buf->dtb_offset = 0;
11210 	buf->dtb_drops = 0;
11211 	buf->dtb_errors = 0;
11212 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11213 	buf->dtb_interval = now - buf->dtb_switched;
11214 	buf->dtb_switched = now;
11215 	dtrace_interrupt_enable(cookie);
11216 }
11217 
11218 /*
11219  * Note:  called from cross call context.  This function activates a buffer
11220  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
11221  * is guaranteed by the disabling of interrupts.
11222  */
11223 static void
11224 dtrace_buffer_activate(dtrace_state_t *state)
11225 {
11226 	dtrace_buffer_t *buf;
11227 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
11228 
11229 	buf = &state->dts_buffer[CPU->cpu_id];
11230 
11231 	if (buf->dtb_tomax != NULL) {
11232 		/*
11233 		 * We might like to assert that the buffer is marked inactive,
11234 		 * but this isn't necessarily true:  the buffer for the CPU
11235 		 * that processes the BEGIN probe has its buffer activated
11236 		 * manually.  In this case, we take the (harmless) action
11237 		 * re-clearing the bit INACTIVE bit.
11238 		 */
11239 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11240 	}
11241 
11242 	dtrace_interrupt_enable(cookie);
11243 }
11244 
11245 static int
11246 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11247     processorid_t cpu, int *factor)
11248 {
11249 	cpu_t *cp;
11250 	dtrace_buffer_t *buf;
11251 	int allocated = 0, desired = 0;
11252 
11253 	ASSERT(MUTEX_HELD(&cpu_lock));
11254 	ASSERT(MUTEX_HELD(&dtrace_lock));
11255 
11256 	*factor = 1;
11257 
11258 	if (size > dtrace_nonroot_maxsize &&
11259 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11260 		return (EFBIG);
11261 
11262 	cp = cpu_list;
11263 
11264 	do {
11265 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11266 			continue;
11267 
11268 		buf = &bufs[cp->cpu_id];
11269 
11270 		/*
11271 		 * If there is already a buffer allocated for this CPU, it
11272 		 * is only possible that this is a DR event.  In this case,
11273 		 * the buffer size must match our specified size.
11274 		 */
11275 		if (buf->dtb_tomax != NULL) {
11276 			ASSERT(buf->dtb_size == size);
11277 			continue;
11278 		}
11279 
11280 		ASSERT(buf->dtb_xamot == NULL);
11281 
11282 		if ((buf->dtb_tomax = kmem_zalloc(size,
11283 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11284 			goto err;
11285 
11286 		buf->dtb_size = size;
11287 		buf->dtb_flags = flags;
11288 		buf->dtb_offset = 0;
11289 		buf->dtb_drops = 0;
11290 
11291 		if (flags & DTRACEBUF_NOSWITCH)
11292 			continue;
11293 
11294 		if ((buf->dtb_xamot = kmem_zalloc(size,
11295 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11296 			goto err;
11297 	} while ((cp = cp->cpu_next) != cpu_list);
11298 
11299 	return (0);
11300 
11301 err:
11302 	cp = cpu_list;
11303 
11304 	do {
11305 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11306 			continue;
11307 
11308 		buf = &bufs[cp->cpu_id];
11309 		desired += 2;
11310 
11311 		if (buf->dtb_xamot != NULL) {
11312 			ASSERT(buf->dtb_tomax != NULL);
11313 			ASSERT(buf->dtb_size == size);
11314 			kmem_free(buf->dtb_xamot, size);
11315 			allocated++;
11316 		}
11317 
11318 		if (buf->dtb_tomax != NULL) {
11319 			ASSERT(buf->dtb_size == size);
11320 			kmem_free(buf->dtb_tomax, size);
11321 			allocated++;
11322 		}
11323 
11324 		buf->dtb_tomax = NULL;
11325 		buf->dtb_xamot = NULL;
11326 		buf->dtb_size = 0;
11327 	} while ((cp = cp->cpu_next) != cpu_list);
11328 
11329 	*factor = desired / (allocated > 0 ? allocated : 1);
11330 
11331 	return (ENOMEM);
11332 }
11333 
11334 /*
11335  * Note:  called from probe context.  This function just increments the drop
11336  * count on a buffer.  It has been made a function to allow for the
11337  * possibility of understanding the source of mysterious drop counts.  (A
11338  * problem for which one may be particularly disappointed that DTrace cannot
11339  * be used to understand DTrace.)
11340  */
11341 static void
11342 dtrace_buffer_drop(dtrace_buffer_t *buf)
11343 {
11344 	buf->dtb_drops++;
11345 }
11346 
11347 /*
11348  * Note:  called from probe context.  This function is called to reserve space
11349  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
11350  * mstate.  Returns the new offset in the buffer, or a negative value if an
11351  * error has occurred.
11352  */
11353 static intptr_t
11354 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11355     dtrace_state_t *state, dtrace_mstate_t *mstate)
11356 {
11357 	intptr_t offs = buf->dtb_offset, soffs;
11358 	intptr_t woffs;
11359 	caddr_t tomax;
11360 	size_t total;
11361 
11362 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11363 		return (-1);
11364 
11365 	if ((tomax = buf->dtb_tomax) == NULL) {
11366 		dtrace_buffer_drop(buf);
11367 		return (-1);
11368 	}
11369 
11370 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11371 		while (offs & (align - 1)) {
11372 			/*
11373 			 * Assert that our alignment is off by a number which
11374 			 * is itself sizeof (uint32_t) aligned.
11375 			 */
11376 			ASSERT(!((align - (offs & (align - 1))) &
11377 			    (sizeof (uint32_t) - 1)));
11378 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11379 			offs += sizeof (uint32_t);
11380 		}
11381 
11382 		if ((soffs = offs + needed) > buf->dtb_size) {
11383 			dtrace_buffer_drop(buf);
11384 			return (-1);
11385 		}
11386 
11387 		if (mstate == NULL)
11388 			return (offs);
11389 
11390 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11391 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
11392 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11393 
11394 		return (offs);
11395 	}
11396 
11397 	if (buf->dtb_flags & DTRACEBUF_FILL) {
11398 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11399 		    (buf->dtb_flags & DTRACEBUF_FULL))
11400 			return (-1);
11401 		goto out;
11402 	}
11403 
11404 	total = needed + (offs & (align - 1));
11405 
11406 	/*
11407 	 * For a ring buffer, life is quite a bit more complicated.  Before
11408 	 * we can store any padding, we need to adjust our wrapping offset.
11409 	 * (If we've never before wrapped or we're not about to, no adjustment
11410 	 * is required.)
11411 	 */
11412 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11413 	    offs + total > buf->dtb_size) {
11414 		woffs = buf->dtb_xamot_offset;
11415 
11416 		if (offs + total > buf->dtb_size) {
11417 			/*
11418 			 * We can't fit in the end of the buffer.  First, a
11419 			 * sanity check that we can fit in the buffer at all.
11420 			 */
11421 			if (total > buf->dtb_size) {
11422 				dtrace_buffer_drop(buf);
11423 				return (-1);
11424 			}
11425 
11426 			/*
11427 			 * We're going to be storing at the top of the buffer,
11428 			 * so now we need to deal with the wrapped offset.  We
11429 			 * only reset our wrapped offset to 0 if it is
11430 			 * currently greater than the current offset.  If it
11431 			 * is less than the current offset, it is because a
11432 			 * previous allocation induced a wrap -- but the
11433 			 * allocation didn't subsequently take the space due
11434 			 * to an error or false predicate evaluation.  In this
11435 			 * case, we'll just leave the wrapped offset alone: if
11436 			 * the wrapped offset hasn't been advanced far enough
11437 			 * for this allocation, it will be adjusted in the
11438 			 * lower loop.
11439 			 */
11440 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11441 				if (woffs >= offs)
11442 					woffs = 0;
11443 			} else {
11444 				woffs = 0;
11445 			}
11446 
11447 			/*
11448 			 * Now we know that we're going to be storing to the
11449 			 * top of the buffer and that there is room for us
11450 			 * there.  We need to clear the buffer from the current
11451 			 * offset to the end (there may be old gunk there).
11452 			 */
11453 			while (offs < buf->dtb_size)
11454 				tomax[offs++] = 0;
11455 
11456 			/*
11457 			 * We need to set our offset to zero.  And because we
11458 			 * are wrapping, we need to set the bit indicating as
11459 			 * much.  We can also adjust our needed space back
11460 			 * down to the space required by the ECB -- we know
11461 			 * that the top of the buffer is aligned.
11462 			 */
11463 			offs = 0;
11464 			total = needed;
11465 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
11466 		} else {
11467 			/*
11468 			 * There is room for us in the buffer, so we simply
11469 			 * need to check the wrapped offset.
11470 			 */
11471 			if (woffs < offs) {
11472 				/*
11473 				 * The wrapped offset is less than the offset.
11474 				 * This can happen if we allocated buffer space
11475 				 * that induced a wrap, but then we didn't
11476 				 * subsequently take the space due to an error
11477 				 * or false predicate evaluation.  This is
11478 				 * okay; we know that _this_ allocation isn't
11479 				 * going to induce a wrap.  We still can't
11480 				 * reset the wrapped offset to be zero,
11481 				 * however: the space may have been trashed in
11482 				 * the previous failed probe attempt.  But at
11483 				 * least the wrapped offset doesn't need to
11484 				 * be adjusted at all...
11485 				 */
11486 				goto out;
11487 			}
11488 		}
11489 
11490 		while (offs + total > woffs) {
11491 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11492 			size_t size;
11493 
11494 			if (epid == DTRACE_EPIDNONE) {
11495 				size = sizeof (uint32_t);
11496 			} else {
11497 				ASSERT3U(epid, <=, state->dts_necbs);
11498 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
11499 
11500 				size = state->dts_ecbs[epid - 1]->dte_size;
11501 			}
11502 
11503 			ASSERT(woffs + size <= buf->dtb_size);
11504 			ASSERT(size != 0);
11505 
11506 			if (woffs + size == buf->dtb_size) {
11507 				/*
11508 				 * We've reached the end of the buffer; we want
11509 				 * to set the wrapped offset to 0 and break
11510 				 * out.  However, if the offs is 0, then we're
11511 				 * in a strange edge-condition:  the amount of
11512 				 * space that we want to reserve plus the size
11513 				 * of the record that we're overwriting is
11514 				 * greater than the size of the buffer.  This
11515 				 * is problematic because if we reserve the
11516 				 * space but subsequently don't consume it (due
11517 				 * to a failed predicate or error) the wrapped
11518 				 * offset will be 0 -- yet the EPID at offset 0
11519 				 * will not be committed.  This situation is
11520 				 * relatively easy to deal with:  if we're in
11521 				 * this case, the buffer is indistinguishable
11522 				 * from one that hasn't wrapped; we need only
11523 				 * finish the job by clearing the wrapped bit,
11524 				 * explicitly setting the offset to be 0, and
11525 				 * zero'ing out the old data in the buffer.
11526 				 */
11527 				if (offs == 0) {
11528 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11529 					buf->dtb_offset = 0;
11530 					woffs = total;
11531 
11532 					while (woffs < buf->dtb_size)
11533 						tomax[woffs++] = 0;
11534 				}
11535 
11536 				woffs = 0;
11537 				break;
11538 			}
11539 
11540 			woffs += size;
11541 		}
11542 
11543 		/*
11544 		 * We have a wrapped offset.  It may be that the wrapped offset
11545 		 * has become zero -- that's okay.
11546 		 */
11547 		buf->dtb_xamot_offset = woffs;
11548 	}
11549 
11550 out:
11551 	/*
11552 	 * Now we can plow the buffer with any necessary padding.
11553 	 */
11554 	while (offs & (align - 1)) {
11555 		/*
11556 		 * Assert that our alignment is off by a number which
11557 		 * is itself sizeof (uint32_t) aligned.
11558 		 */
11559 		ASSERT(!((align - (offs & (align - 1))) &
11560 		    (sizeof (uint32_t) - 1)));
11561 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11562 		offs += sizeof (uint32_t);
11563 	}
11564 
11565 	if (buf->dtb_flags & DTRACEBUF_FILL) {
11566 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
11567 			buf->dtb_flags |= DTRACEBUF_FULL;
11568 			return (-1);
11569 		}
11570 	}
11571 
11572 	if (mstate == NULL)
11573 		return (offs);
11574 
11575 	/*
11576 	 * For ring buffers and fill buffers, the scratch space is always
11577 	 * the inactive buffer.
11578 	 */
11579 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11580 	mstate->dtms_scratch_size = buf->dtb_size;
11581 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11582 
11583 	return (offs);
11584 }
11585 
11586 static void
11587 dtrace_buffer_polish(dtrace_buffer_t *buf)
11588 {
11589 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11590 	ASSERT(MUTEX_HELD(&dtrace_lock));
11591 
11592 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11593 		return;
11594 
11595 	/*
11596 	 * We need to polish the ring buffer.  There are three cases:
11597 	 *
11598 	 * - The first (and presumably most common) is that there is no gap
11599 	 *   between the buffer offset and the wrapped offset.  In this case,
11600 	 *   there is nothing in the buffer that isn't valid data; we can
11601 	 *   mark the buffer as polished and return.
11602 	 *
11603 	 * - The second (less common than the first but still more common
11604 	 *   than the third) is that there is a gap between the buffer offset
11605 	 *   and the wrapped offset, and the wrapped offset is larger than the
11606 	 *   buffer offset.  This can happen because of an alignment issue, or
11607 	 *   can happen because of a call to dtrace_buffer_reserve() that
11608 	 *   didn't subsequently consume the buffer space.  In this case,
11609 	 *   we need to zero the data from the buffer offset to the wrapped
11610 	 *   offset.
11611 	 *
11612 	 * - The third (and least common) is that there is a gap between the
11613 	 *   buffer offset and the wrapped offset, but the wrapped offset is
11614 	 *   _less_ than the buffer offset.  This can only happen because a
11615 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
11616 	 *   was not subsequently consumed.  In this case, we need to zero the
11617 	 *   space from the offset to the end of the buffer _and_ from the
11618 	 *   top of the buffer to the wrapped offset.
11619 	 */
11620 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
11621 		bzero(buf->dtb_tomax + buf->dtb_offset,
11622 		    buf->dtb_xamot_offset - buf->dtb_offset);
11623 	}
11624 
11625 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
11626 		bzero(buf->dtb_tomax + buf->dtb_offset,
11627 		    buf->dtb_size - buf->dtb_offset);
11628 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11629 	}
11630 }
11631 
11632 /*
11633  * This routine determines if data generated at the specified time has likely
11634  * been entirely consumed at user-level.  This routine is called to determine
11635  * if an ECB on a defunct probe (but for an active enabling) can be safely
11636  * disabled and destroyed.
11637  */
11638 static int
11639 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
11640 {
11641 	int i;
11642 
11643 	for (i = 0; i < NCPU; i++) {
11644 		dtrace_buffer_t *buf = &bufs[i];
11645 
11646 		if (buf->dtb_size == 0)
11647 			continue;
11648 
11649 		if (buf->dtb_flags & DTRACEBUF_RING)
11650 			return (0);
11651 
11652 		if (!buf->dtb_switched && buf->dtb_offset != 0)
11653 			return (0);
11654 
11655 		if (buf->dtb_switched - buf->dtb_interval < when)
11656 			return (0);
11657 	}
11658 
11659 	return (1);
11660 }
11661 
11662 static void
11663 dtrace_buffer_free(dtrace_buffer_t *bufs)
11664 {
11665 	int i;
11666 
11667 	for (i = 0; i < NCPU; i++) {
11668 		dtrace_buffer_t *buf = &bufs[i];
11669 
11670 		if (buf->dtb_tomax == NULL) {
11671 			ASSERT(buf->dtb_xamot == NULL);
11672 			ASSERT(buf->dtb_size == 0);
11673 			continue;
11674 		}
11675 
11676 		if (buf->dtb_xamot != NULL) {
11677 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11678 			kmem_free(buf->dtb_xamot, buf->dtb_size);
11679 		}
11680 
11681 		kmem_free(buf->dtb_tomax, buf->dtb_size);
11682 		buf->dtb_size = 0;
11683 		buf->dtb_tomax = NULL;
11684 		buf->dtb_xamot = NULL;
11685 	}
11686 }
11687 
11688 /*
11689  * DTrace Enabling Functions
11690  */
11691 static dtrace_enabling_t *
11692 dtrace_enabling_create(dtrace_vstate_t *vstate)
11693 {
11694 	dtrace_enabling_t *enab;
11695 
11696 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
11697 	enab->dten_vstate = vstate;
11698 
11699 	return (enab);
11700 }
11701 
11702 static void
11703 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
11704 {
11705 	dtrace_ecbdesc_t **ndesc;
11706 	size_t osize, nsize;
11707 
11708 	/*
11709 	 * We can't add to enablings after we've enabled them, or after we've
11710 	 * retained them.
11711 	 */
11712 	ASSERT(enab->dten_probegen == 0);
11713 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11714 
11715 	if (enab->dten_ndesc < enab->dten_maxdesc) {
11716 		enab->dten_desc[enab->dten_ndesc++] = ecb;
11717 		return;
11718 	}
11719 
11720 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11721 
11722 	if (enab->dten_maxdesc == 0) {
11723 		enab->dten_maxdesc = 1;
11724 	} else {
11725 		enab->dten_maxdesc <<= 1;
11726 	}
11727 
11728 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
11729 
11730 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
11731 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
11732 	bcopy(enab->dten_desc, ndesc, osize);
11733 	kmem_free(enab->dten_desc, osize);
11734 
11735 	enab->dten_desc = ndesc;
11736 	enab->dten_desc[enab->dten_ndesc++] = ecb;
11737 }
11738 
11739 static void
11740 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
11741     dtrace_probedesc_t *pd)
11742 {
11743 	dtrace_ecbdesc_t *new;
11744 	dtrace_predicate_t *pred;
11745 	dtrace_actdesc_t *act;
11746 
11747 	/*
11748 	 * We're going to create a new ECB description that matches the
11749 	 * specified ECB in every way, but has the specified probe description.
11750 	 */
11751 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11752 
11753 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
11754 		dtrace_predicate_hold(pred);
11755 
11756 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
11757 		dtrace_actdesc_hold(act);
11758 
11759 	new->dted_action = ecb->dted_action;
11760 	new->dted_pred = ecb->dted_pred;
11761 	new->dted_probe = *pd;
11762 	new->dted_uarg = ecb->dted_uarg;
11763 
11764 	dtrace_enabling_add(enab, new);
11765 }
11766 
11767 static void
11768 dtrace_enabling_dump(dtrace_enabling_t *enab)
11769 {
11770 	int i;
11771 
11772 	for (i = 0; i < enab->dten_ndesc; i++) {
11773 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
11774 
11775 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
11776 		    desc->dtpd_provider, desc->dtpd_mod,
11777 		    desc->dtpd_func, desc->dtpd_name);
11778 	}
11779 }
11780 
11781 static void
11782 dtrace_enabling_destroy(dtrace_enabling_t *enab)
11783 {
11784 	int i;
11785 	dtrace_ecbdesc_t *ep;
11786 	dtrace_vstate_t *vstate = enab->dten_vstate;
11787 
11788 	ASSERT(MUTEX_HELD(&dtrace_lock));
11789 
11790 	for (i = 0; i < enab->dten_ndesc; i++) {
11791 		dtrace_actdesc_t *act, *next;
11792 		dtrace_predicate_t *pred;
11793 
11794 		ep = enab->dten_desc[i];
11795 
11796 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
11797 			dtrace_predicate_release(pred, vstate);
11798 
11799 		for (act = ep->dted_action; act != NULL; act = next) {
11800 			next = act->dtad_next;
11801 			dtrace_actdesc_release(act, vstate);
11802 		}
11803 
11804 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11805 	}
11806 
11807 	kmem_free(enab->dten_desc,
11808 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
11809 
11810 	/*
11811 	 * If this was a retained enabling, decrement the dts_nretained count
11812 	 * and take it off of the dtrace_retained list.
11813 	 */
11814 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
11815 	    dtrace_retained == enab) {
11816 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11817 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
11818 		enab->dten_vstate->dtvs_state->dts_nretained--;
11819 		dtrace_retained_gen++;
11820 	}
11821 
11822 	if (enab->dten_prev == NULL) {
11823 		if (dtrace_retained == enab) {
11824 			dtrace_retained = enab->dten_next;
11825 
11826 			if (dtrace_retained != NULL)
11827 				dtrace_retained->dten_prev = NULL;
11828 		}
11829 	} else {
11830 		ASSERT(enab != dtrace_retained);
11831 		ASSERT(dtrace_retained != NULL);
11832 		enab->dten_prev->dten_next = enab->dten_next;
11833 	}
11834 
11835 	if (enab->dten_next != NULL) {
11836 		ASSERT(dtrace_retained != NULL);
11837 		enab->dten_next->dten_prev = enab->dten_prev;
11838 	}
11839 
11840 	kmem_free(enab, sizeof (dtrace_enabling_t));
11841 }
11842 
11843 static int
11844 dtrace_enabling_retain(dtrace_enabling_t *enab)
11845 {
11846 	dtrace_state_t *state;
11847 
11848 	ASSERT(MUTEX_HELD(&dtrace_lock));
11849 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
11850 	ASSERT(enab->dten_vstate != NULL);
11851 
11852 	state = enab->dten_vstate->dtvs_state;
11853 	ASSERT(state != NULL);
11854 
11855 	/*
11856 	 * We only allow each state to retain dtrace_retain_max enablings.
11857 	 */
11858 	if (state->dts_nretained >= dtrace_retain_max)
11859 		return (ENOSPC);
11860 
11861 	state->dts_nretained++;
11862 	dtrace_retained_gen++;
11863 
11864 	if (dtrace_retained == NULL) {
11865 		dtrace_retained = enab;
11866 		return (0);
11867 	}
11868 
11869 	enab->dten_next = dtrace_retained;
11870 	dtrace_retained->dten_prev = enab;
11871 	dtrace_retained = enab;
11872 
11873 	return (0);
11874 }
11875 
11876 static int
11877 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11878     dtrace_probedesc_t *create)
11879 {
11880 	dtrace_enabling_t *new, *enab;
11881 	int found = 0, err = ENOENT;
11882 
11883 	ASSERT(MUTEX_HELD(&dtrace_lock));
11884 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11885 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11886 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11887 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11888 
11889 	new = dtrace_enabling_create(&state->dts_vstate);
11890 
11891 	/*
11892 	 * Iterate over all retained enablings, looking for enablings that
11893 	 * match the specified state.
11894 	 */
11895 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11896 		int i;
11897 
11898 		/*
11899 		 * dtvs_state can only be NULL for helper enablings -- and
11900 		 * helper enablings can't be retained.
11901 		 */
11902 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11903 
11904 		if (enab->dten_vstate->dtvs_state != state)
11905 			continue;
11906 
11907 		/*
11908 		 * Now iterate over each probe description; we're looking for
11909 		 * an exact match to the specified probe description.
11910 		 */
11911 		for (i = 0; i < enab->dten_ndesc; i++) {
11912 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11913 			dtrace_probedesc_t *pd = &ep->dted_probe;
11914 
11915 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11916 				continue;
11917 
11918 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11919 				continue;
11920 
11921 			if (strcmp(pd->dtpd_func, match->dtpd_func))
11922 				continue;
11923 
11924 			if (strcmp(pd->dtpd_name, match->dtpd_name))
11925 				continue;
11926 
11927 			/*
11928 			 * We have a winning probe!  Add it to our growing
11929 			 * enabling.
11930 			 */
11931 			found = 1;
11932 			dtrace_enabling_addlike(new, ep, create);
11933 		}
11934 	}
11935 
11936 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11937 		dtrace_enabling_destroy(new);
11938 		return (err);
11939 	}
11940 
11941 	return (0);
11942 }
11943 
11944 static void
11945 dtrace_enabling_retract(dtrace_state_t *state)
11946 {
11947 	dtrace_enabling_t *enab, *next;
11948 
11949 	ASSERT(MUTEX_HELD(&dtrace_lock));
11950 
11951 	/*
11952 	 * Iterate over all retained enablings, destroy the enablings retained
11953 	 * for the specified state.
11954 	 */
11955 	for (enab = dtrace_retained; enab != NULL; enab = next) {
11956 		next = enab->dten_next;
11957 
11958 		/*
11959 		 * dtvs_state can only be NULL for helper enablings -- and
11960 		 * helper enablings can't be retained.
11961 		 */
11962 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11963 
11964 		if (enab->dten_vstate->dtvs_state == state) {
11965 			ASSERT(state->dts_nretained > 0);
11966 			dtrace_enabling_destroy(enab);
11967 		}
11968 	}
11969 
11970 	ASSERT(state->dts_nretained == 0);
11971 }
11972 
11973 static int
11974 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11975 {
11976 	int i = 0;
11977 	int total_matched = 0, matched = 0;
11978 
11979 	ASSERT(MUTEX_HELD(&cpu_lock));
11980 	ASSERT(MUTEX_HELD(&dtrace_lock));
11981 
11982 	for (i = 0; i < enab->dten_ndesc; i++) {
11983 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11984 
11985 		enab->dten_current = ep;
11986 		enab->dten_error = 0;
11987 
11988 		/*
11989 		 * If a provider failed to enable a probe then get out and
11990 		 * let the consumer know we failed.
11991 		 */
11992 		if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
11993 			return (EBUSY);
11994 
11995 		total_matched += matched;
11996 
11997 		if (enab->dten_error != 0) {
11998 			/*
11999 			 * If we get an error half-way through enabling the
12000 			 * probes, we kick out -- perhaps with some number of
12001 			 * them enabled.  Leaving enabled probes enabled may
12002 			 * be slightly confusing for user-level, but we expect
12003 			 * that no one will attempt to actually drive on in
12004 			 * the face of such errors.  If this is an anonymous
12005 			 * enabling (indicated with a NULL nmatched pointer),
12006 			 * we cmn_err() a message.  We aren't expecting to
12007 			 * get such an error -- such as it can exist at all,
12008 			 * it would be a result of corrupted DOF in the driver
12009 			 * properties.
12010 			 */
12011 			if (nmatched == NULL) {
12012 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12013 				    "error on %p: %d", (void *)ep,
12014 				    enab->dten_error);
12015 			}
12016 
12017 			return (enab->dten_error);
12018 		}
12019 	}
12020 
12021 	enab->dten_probegen = dtrace_probegen;
12022 	if (nmatched != NULL)
12023 		*nmatched = total_matched;
12024 
12025 	return (0);
12026 }
12027 
12028 static void
12029 dtrace_enabling_matchall(void)
12030 {
12031 	dtrace_enabling_t *enab;
12032 
12033 	mutex_enter(&cpu_lock);
12034 	mutex_enter(&dtrace_lock);
12035 
12036 	/*
12037 	 * Iterate over all retained enablings to see if any probes match
12038 	 * against them.  We only perform this operation on enablings for which
12039 	 * we have sufficient permissions by virtue of being in the global zone
12040 	 * or in the same zone as the DTrace client.  Because we can be called
12041 	 * after dtrace_detach() has been called, we cannot assert that there
12042 	 * are retained enablings.  We can safely load from dtrace_retained,
12043 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
12044 	 * block pending our completion.
12045 	 */
12046 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12047 		dtrace_cred_t *dcr = &enab->dten_vstate->dtvs_state->dts_cred;
12048 		cred_t *cr = dcr->dcr_cred;
12049 		zoneid_t zone = cr != NULL ? crgetzoneid(cr) : 0;
12050 
12051 		if ((dcr->dcr_visible & DTRACE_CRV_ALLZONE) || (cr != NULL &&
12052 		    (zone == GLOBAL_ZONEID || getzoneid() == zone)))
12053 			(void) dtrace_enabling_match(enab, NULL);
12054 	}
12055 
12056 	mutex_exit(&dtrace_lock);
12057 	mutex_exit(&cpu_lock);
12058 }
12059 
12060 /*
12061  * If an enabling is to be enabled without having matched probes (that is, if
12062  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
12063  * enabling must be _primed_ by creating an ECB for every ECB description.
12064  * This must be done to assure that we know the number of speculations, the
12065  * number of aggregations, the minimum buffer size needed, etc. before we
12066  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
12067  * enabling any probes, we create ECBs for every ECB decription, but with a
12068  * NULL probe -- which is exactly what this function does.
12069  */
12070 static void
12071 dtrace_enabling_prime(dtrace_state_t *state)
12072 {
12073 	dtrace_enabling_t *enab;
12074 	int i;
12075 
12076 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12077 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12078 
12079 		if (enab->dten_vstate->dtvs_state != state)
12080 			continue;
12081 
12082 		/*
12083 		 * We don't want to prime an enabling more than once, lest
12084 		 * we allow a malicious user to induce resource exhaustion.
12085 		 * (The ECBs that result from priming an enabling aren't
12086 		 * leaked -- but they also aren't deallocated until the
12087 		 * consumer state is destroyed.)
12088 		 */
12089 		if (enab->dten_primed)
12090 			continue;
12091 
12092 		for (i = 0; i < enab->dten_ndesc; i++) {
12093 			enab->dten_current = enab->dten_desc[i];
12094 			(void) dtrace_probe_enable(NULL, enab);
12095 		}
12096 
12097 		enab->dten_primed = 1;
12098 	}
12099 }
12100 
12101 /*
12102  * Called to indicate that probes should be provided due to retained
12103  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
12104  * must take an initial lap through the enabling calling the dtps_provide()
12105  * entry point explicitly to allow for autocreated probes.
12106  */
12107 static void
12108 dtrace_enabling_provide(dtrace_provider_t *prv)
12109 {
12110 	int i, all = 0;
12111 	dtrace_probedesc_t desc;
12112 	dtrace_genid_t gen;
12113 
12114 	ASSERT(MUTEX_HELD(&dtrace_lock));
12115 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
12116 
12117 	if (prv == NULL) {
12118 		all = 1;
12119 		prv = dtrace_provider;
12120 	}
12121 
12122 	do {
12123 		dtrace_enabling_t *enab;
12124 		void *parg = prv->dtpv_arg;
12125 
12126 retry:
12127 		gen = dtrace_retained_gen;
12128 		for (enab = dtrace_retained; enab != NULL;
12129 		    enab = enab->dten_next) {
12130 			for (i = 0; i < enab->dten_ndesc; i++) {
12131 				desc = enab->dten_desc[i]->dted_probe;
12132 				mutex_exit(&dtrace_lock);
12133 				prv->dtpv_pops.dtps_provide(parg, &desc);
12134 				mutex_enter(&dtrace_lock);
12135 				/*
12136 				 * Process the retained enablings again if
12137 				 * they have changed while we weren't holding
12138 				 * dtrace_lock.
12139 				 */
12140 				if (gen != dtrace_retained_gen)
12141 					goto retry;
12142 			}
12143 		}
12144 	} while (all && (prv = prv->dtpv_next) != NULL);
12145 
12146 	mutex_exit(&dtrace_lock);
12147 	dtrace_probe_provide(NULL, all ? NULL : prv);
12148 	mutex_enter(&dtrace_lock);
12149 }
12150 
12151 /*
12152  * Called to reap ECBs that are attached to probes from defunct providers.
12153  */
12154 static void
12155 dtrace_enabling_reap(void)
12156 {
12157 	dtrace_provider_t *prov;
12158 	dtrace_probe_t *probe;
12159 	dtrace_ecb_t *ecb;
12160 	hrtime_t when;
12161 	int i;
12162 
12163 	mutex_enter(&cpu_lock);
12164 	mutex_enter(&dtrace_lock);
12165 
12166 	for (i = 0; i < dtrace_nprobes; i++) {
12167 		if ((probe = dtrace_probes[i]) == NULL)
12168 			continue;
12169 
12170 		if (probe->dtpr_ecb == NULL)
12171 			continue;
12172 
12173 		prov = probe->dtpr_provider;
12174 
12175 		if ((when = prov->dtpv_defunct) == 0)
12176 			continue;
12177 
12178 		/*
12179 		 * We have ECBs on a defunct provider:  we want to reap these
12180 		 * ECBs to allow the provider to unregister.  The destruction
12181 		 * of these ECBs must be done carefully:  if we destroy the ECB
12182 		 * and the consumer later wishes to consume an EPID that
12183 		 * corresponds to the destroyed ECB (and if the EPID metadata
12184 		 * has not been previously consumed), the consumer will abort
12185 		 * processing on the unknown EPID.  To reduce (but not, sadly,
12186 		 * eliminate) the possibility of this, we will only destroy an
12187 		 * ECB for a defunct provider if, for the state that
12188 		 * corresponds to the ECB:
12189 		 *
12190 		 *  (a)	There is no speculative tracing (which can effectively
12191 		 *	cache an EPID for an arbitrary amount of time).
12192 		 *
12193 		 *  (b)	The principal buffers have been switched twice since the
12194 		 *	provider became defunct.
12195 		 *
12196 		 *  (c)	The aggregation buffers are of zero size or have been
12197 		 *	switched twice since the provider became defunct.
12198 		 *
12199 		 * We use dts_speculates to determine (a) and call a function
12200 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
12201 		 * that as soon as we've been unable to destroy one of the ECBs
12202 		 * associated with the probe, we quit trying -- reaping is only
12203 		 * fruitful in as much as we can destroy all ECBs associated
12204 		 * with the defunct provider's probes.
12205 		 */
12206 		while ((ecb = probe->dtpr_ecb) != NULL) {
12207 			dtrace_state_t *state = ecb->dte_state;
12208 			dtrace_buffer_t *buf = state->dts_buffer;
12209 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12210 
12211 			if (state->dts_speculates)
12212 				break;
12213 
12214 			if (!dtrace_buffer_consumed(buf, when))
12215 				break;
12216 
12217 			if (!dtrace_buffer_consumed(aggbuf, when))
12218 				break;
12219 
12220 			dtrace_ecb_disable(ecb);
12221 			ASSERT(probe->dtpr_ecb != ecb);
12222 			dtrace_ecb_destroy(ecb);
12223 		}
12224 	}
12225 
12226 	mutex_exit(&dtrace_lock);
12227 	mutex_exit(&cpu_lock);
12228 }
12229 
12230 /*
12231  * DTrace DOF Functions
12232  */
12233 /*ARGSUSED*/
12234 static void
12235 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12236 {
12237 	if (dtrace_err_verbose)
12238 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
12239 
12240 #ifdef DTRACE_ERRDEBUG
12241 	dtrace_errdebug(str);
12242 #endif
12243 }
12244 
12245 /*
12246  * Create DOF out of a currently enabled state.  Right now, we only create
12247  * DOF containing the run-time options -- but this could be expanded to create
12248  * complete DOF representing the enabled state.
12249  */
12250 static dof_hdr_t *
12251 dtrace_dof_create(dtrace_state_t *state)
12252 {
12253 	dof_hdr_t *dof;
12254 	dof_sec_t *sec;
12255 	dof_optdesc_t *opt;
12256 	int i, len = sizeof (dof_hdr_t) +
12257 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12258 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12259 
12260 	ASSERT(MUTEX_HELD(&dtrace_lock));
12261 
12262 	dof = kmem_zalloc(len, KM_SLEEP);
12263 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12264 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12265 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12266 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12267 
12268 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12269 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12270 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12271 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12272 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12273 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12274 
12275 	dof->dofh_flags = 0;
12276 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
12277 	dof->dofh_secsize = sizeof (dof_sec_t);
12278 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
12279 	dof->dofh_secoff = sizeof (dof_hdr_t);
12280 	dof->dofh_loadsz = len;
12281 	dof->dofh_filesz = len;
12282 	dof->dofh_pad = 0;
12283 
12284 	/*
12285 	 * Fill in the option section header...
12286 	 */
12287 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12288 	sec->dofs_type = DOF_SECT_OPTDESC;
12289 	sec->dofs_align = sizeof (uint64_t);
12290 	sec->dofs_flags = DOF_SECF_LOAD;
12291 	sec->dofs_entsize = sizeof (dof_optdesc_t);
12292 
12293 	opt = (dof_optdesc_t *)((uintptr_t)sec +
12294 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12295 
12296 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12297 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12298 
12299 	for (i = 0; i < DTRACEOPT_MAX; i++) {
12300 		opt[i].dofo_option = i;
12301 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
12302 		opt[i].dofo_value = state->dts_options[i];
12303 	}
12304 
12305 	return (dof);
12306 }
12307 
12308 static dof_hdr_t *
12309 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12310 {
12311 	dof_hdr_t hdr, *dof;
12312 
12313 	ASSERT(!MUTEX_HELD(&dtrace_lock));
12314 
12315 	/*
12316 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
12317 	 */
12318 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
12319 		dtrace_dof_error(NULL, "failed to copyin DOF header");
12320 		*errp = EFAULT;
12321 		return (NULL);
12322 	}
12323 
12324 	/*
12325 	 * Now we'll allocate the entire DOF and copy it in -- provided
12326 	 * that the length isn't outrageous.
12327 	 */
12328 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12329 		dtrace_dof_error(&hdr, "load size exceeds maximum");
12330 		*errp = E2BIG;
12331 		return (NULL);
12332 	}
12333 
12334 	if (hdr.dofh_loadsz < sizeof (hdr)) {
12335 		dtrace_dof_error(&hdr, "invalid load size");
12336 		*errp = EINVAL;
12337 		return (NULL);
12338 	}
12339 
12340 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12341 
12342 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
12343 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
12344 		kmem_free(dof, hdr.dofh_loadsz);
12345 		*errp = EFAULT;
12346 		return (NULL);
12347 	}
12348 
12349 	return (dof);
12350 }
12351 
12352 static dof_hdr_t *
12353 dtrace_dof_property(const char *name)
12354 {
12355 	uchar_t *buf;
12356 	uint64_t loadsz;
12357 	unsigned int len, i;
12358 	dof_hdr_t *dof;
12359 
12360 	/*
12361 	 * Unfortunately, array of values in .conf files are always (and
12362 	 * only) interpreted to be integer arrays.  We must read our DOF
12363 	 * as an integer array, and then squeeze it into a byte array.
12364 	 */
12365 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12366 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12367 		return (NULL);
12368 
12369 	for (i = 0; i < len; i++)
12370 		buf[i] = (uchar_t)(((int *)buf)[i]);
12371 
12372 	if (len < sizeof (dof_hdr_t)) {
12373 		ddi_prop_free(buf);
12374 		dtrace_dof_error(NULL, "truncated header");
12375 		return (NULL);
12376 	}
12377 
12378 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12379 		ddi_prop_free(buf);
12380 		dtrace_dof_error(NULL, "truncated DOF");
12381 		return (NULL);
12382 	}
12383 
12384 	if (loadsz >= dtrace_dof_maxsize) {
12385 		ddi_prop_free(buf);
12386 		dtrace_dof_error(NULL, "oversized DOF");
12387 		return (NULL);
12388 	}
12389 
12390 	dof = kmem_alloc(loadsz, KM_SLEEP);
12391 	bcopy(buf, dof, loadsz);
12392 	ddi_prop_free(buf);
12393 
12394 	return (dof);
12395 }
12396 
12397 static void
12398 dtrace_dof_destroy(dof_hdr_t *dof)
12399 {
12400 	kmem_free(dof, dof->dofh_loadsz);
12401 }
12402 
12403 /*
12404  * Return the dof_sec_t pointer corresponding to a given section index.  If the
12405  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
12406  * a type other than DOF_SECT_NONE is specified, the header is checked against
12407  * this type and NULL is returned if the types do not match.
12408  */
12409 static dof_sec_t *
12410 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12411 {
12412 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12413 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12414 
12415 	if (i >= dof->dofh_secnum) {
12416 		dtrace_dof_error(dof, "referenced section index is invalid");
12417 		return (NULL);
12418 	}
12419 
12420 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12421 		dtrace_dof_error(dof, "referenced section is not loadable");
12422 		return (NULL);
12423 	}
12424 
12425 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12426 		dtrace_dof_error(dof, "referenced section is the wrong type");
12427 		return (NULL);
12428 	}
12429 
12430 	return (sec);
12431 }
12432 
12433 static dtrace_probedesc_t *
12434 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12435 {
12436 	dof_probedesc_t *probe;
12437 	dof_sec_t *strtab;
12438 	uintptr_t daddr = (uintptr_t)dof;
12439 	uintptr_t str;
12440 	size_t size;
12441 
12442 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12443 		dtrace_dof_error(dof, "invalid probe section");
12444 		return (NULL);
12445 	}
12446 
12447 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12448 		dtrace_dof_error(dof, "bad alignment in probe description");
12449 		return (NULL);
12450 	}
12451 
12452 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12453 		dtrace_dof_error(dof, "truncated probe description");
12454 		return (NULL);
12455 	}
12456 
12457 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12458 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12459 
12460 	if (strtab == NULL)
12461 		return (NULL);
12462 
12463 	str = daddr + strtab->dofs_offset;
12464 	size = strtab->dofs_size;
12465 
12466 	if (probe->dofp_provider >= strtab->dofs_size) {
12467 		dtrace_dof_error(dof, "corrupt probe provider");
12468 		return (NULL);
12469 	}
12470 
12471 	(void) strncpy(desc->dtpd_provider,
12472 	    (char *)(str + probe->dofp_provider),
12473 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12474 
12475 	if (probe->dofp_mod >= strtab->dofs_size) {
12476 		dtrace_dof_error(dof, "corrupt probe module");
12477 		return (NULL);
12478 	}
12479 
12480 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12481 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12482 
12483 	if (probe->dofp_func >= strtab->dofs_size) {
12484 		dtrace_dof_error(dof, "corrupt probe function");
12485 		return (NULL);
12486 	}
12487 
12488 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12489 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12490 
12491 	if (probe->dofp_name >= strtab->dofs_size) {
12492 		dtrace_dof_error(dof, "corrupt probe name");
12493 		return (NULL);
12494 	}
12495 
12496 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12497 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12498 
12499 	return (desc);
12500 }
12501 
12502 static dtrace_difo_t *
12503 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12504     cred_t *cr)
12505 {
12506 	dtrace_difo_t *dp;
12507 	size_t ttl = 0;
12508 	dof_difohdr_t *dofd;
12509 	uintptr_t daddr = (uintptr_t)dof;
12510 	size_t max = dtrace_difo_maxsize;
12511 	int i, l, n;
12512 
12513 	static const struct {
12514 		int section;
12515 		int bufoffs;
12516 		int lenoffs;
12517 		int entsize;
12518 		int align;
12519 		const char *msg;
12520 	} difo[] = {
12521 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12522 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12523 		sizeof (dif_instr_t), "multiple DIF sections" },
12524 
12525 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12526 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12527 		sizeof (uint64_t), "multiple integer tables" },
12528 
12529 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12530 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
12531 		sizeof (char), "multiple string tables" },
12532 
12533 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12534 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12535 		sizeof (uint_t), "multiple variable tables" },
12536 
12537 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
12538 	};
12539 
12540 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12541 		dtrace_dof_error(dof, "invalid DIFO header section");
12542 		return (NULL);
12543 	}
12544 
12545 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12546 		dtrace_dof_error(dof, "bad alignment in DIFO header");
12547 		return (NULL);
12548 	}
12549 
12550 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12551 	    sec->dofs_size % sizeof (dof_secidx_t)) {
12552 		dtrace_dof_error(dof, "bad size in DIFO header");
12553 		return (NULL);
12554 	}
12555 
12556 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12557 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12558 
12559 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12560 	dp->dtdo_rtype = dofd->dofd_rtype;
12561 
12562 	for (l = 0; l < n; l++) {
12563 		dof_sec_t *subsec;
12564 		void **bufp;
12565 		uint32_t *lenp;
12566 
12567 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12568 		    dofd->dofd_links[l])) == NULL)
12569 			goto err; /* invalid section link */
12570 
12571 		if (ttl + subsec->dofs_size > max) {
12572 			dtrace_dof_error(dof, "exceeds maximum size");
12573 			goto err;
12574 		}
12575 
12576 		ttl += subsec->dofs_size;
12577 
12578 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12579 			if (subsec->dofs_type != difo[i].section)
12580 				continue;
12581 
12582 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12583 				dtrace_dof_error(dof, "section not loaded");
12584 				goto err;
12585 			}
12586 
12587 			if (subsec->dofs_align != difo[i].align) {
12588 				dtrace_dof_error(dof, "bad alignment");
12589 				goto err;
12590 			}
12591 
12592 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12593 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12594 
12595 			if (*bufp != NULL) {
12596 				dtrace_dof_error(dof, difo[i].msg);
12597 				goto err;
12598 			}
12599 
12600 			if (difo[i].entsize != subsec->dofs_entsize) {
12601 				dtrace_dof_error(dof, "entry size mismatch");
12602 				goto err;
12603 			}
12604 
12605 			if (subsec->dofs_entsize != 0 &&
12606 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12607 				dtrace_dof_error(dof, "corrupt entry size");
12608 				goto err;
12609 			}
12610 
12611 			*lenp = subsec->dofs_size;
12612 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12613 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12614 			    *bufp, subsec->dofs_size);
12615 
12616 			if (subsec->dofs_entsize != 0)
12617 				*lenp /= subsec->dofs_entsize;
12618 
12619 			break;
12620 		}
12621 
12622 		/*
12623 		 * If we encounter a loadable DIFO sub-section that is not
12624 		 * known to us, assume this is a broken program and fail.
12625 		 */
12626 		if (difo[i].section == DOF_SECT_NONE &&
12627 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
12628 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
12629 			goto err;
12630 		}
12631 	}
12632 
12633 	if (dp->dtdo_buf == NULL) {
12634 		/*
12635 		 * We can't have a DIF object without DIF text.
12636 		 */
12637 		dtrace_dof_error(dof, "missing DIF text");
12638 		goto err;
12639 	}
12640 
12641 	/*
12642 	 * Before we validate the DIF object, run through the variable table
12643 	 * looking for the strings -- if any of their size are under, we'll set
12644 	 * their size to be the system-wide default string size.  Note that
12645 	 * this should _not_ happen if the "strsize" option has been set --
12646 	 * in this case, the compiler should have set the size to reflect the
12647 	 * setting of the option.
12648 	 */
12649 	for (i = 0; i < dp->dtdo_varlen; i++) {
12650 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
12651 		dtrace_diftype_t *t = &v->dtdv_type;
12652 
12653 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12654 			continue;
12655 
12656 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12657 			t->dtdt_size = dtrace_strsize_default;
12658 	}
12659 
12660 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12661 		goto err;
12662 
12663 	dtrace_difo_init(dp, vstate);
12664 	return (dp);
12665 
12666 err:
12667 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12668 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12669 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12670 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12671 
12672 	kmem_free(dp, sizeof (dtrace_difo_t));
12673 	return (NULL);
12674 }
12675 
12676 static dtrace_predicate_t *
12677 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12678     cred_t *cr)
12679 {
12680 	dtrace_difo_t *dp;
12681 
12682 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
12683 		return (NULL);
12684 
12685 	return (dtrace_predicate_create(dp));
12686 }
12687 
12688 static dtrace_actdesc_t *
12689 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12690     cred_t *cr)
12691 {
12692 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
12693 	dof_actdesc_t *desc;
12694 	dof_sec_t *difosec;
12695 	size_t offs;
12696 	uintptr_t daddr = (uintptr_t)dof;
12697 	uint64_t arg;
12698 	dtrace_actkind_t kind;
12699 
12700 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
12701 		dtrace_dof_error(dof, "invalid action section");
12702 		return (NULL);
12703 	}
12704 
12705 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
12706 		dtrace_dof_error(dof, "truncated action description");
12707 		return (NULL);
12708 	}
12709 
12710 	if (sec->dofs_align != sizeof (uint64_t)) {
12711 		dtrace_dof_error(dof, "bad alignment in action description");
12712 		return (NULL);
12713 	}
12714 
12715 	if (sec->dofs_size < sec->dofs_entsize) {
12716 		dtrace_dof_error(dof, "section entry size exceeds total size");
12717 		return (NULL);
12718 	}
12719 
12720 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
12721 		dtrace_dof_error(dof, "bad entry size in action description");
12722 		return (NULL);
12723 	}
12724 
12725 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
12726 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
12727 		return (NULL);
12728 	}
12729 
12730 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
12731 		desc = (dof_actdesc_t *)(daddr +
12732 		    (uintptr_t)sec->dofs_offset + offs);
12733 		kind = (dtrace_actkind_t)desc->dofa_kind;
12734 
12735 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
12736 		    (kind != DTRACEACT_PRINTA ||
12737 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
12738 		    (kind == DTRACEACT_DIFEXPR &&
12739 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
12740 			dof_sec_t *strtab;
12741 			char *str, *fmt;
12742 			uint64_t i;
12743 
12744 			/*
12745 			 * The argument to these actions is an index into the
12746 			 * DOF string table.  For printf()-like actions, this
12747 			 * is the format string.  For print(), this is the
12748 			 * CTF type of the expression result.
12749 			 */
12750 			if ((strtab = dtrace_dof_sect(dof,
12751 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
12752 				goto err;
12753 
12754 			str = (char *)((uintptr_t)dof +
12755 			    (uintptr_t)strtab->dofs_offset);
12756 
12757 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
12758 				if (str[i] == '\0')
12759 					break;
12760 			}
12761 
12762 			if (i >= strtab->dofs_size) {
12763 				dtrace_dof_error(dof, "bogus format string");
12764 				goto err;
12765 			}
12766 
12767 			if (i == desc->dofa_arg) {
12768 				dtrace_dof_error(dof, "empty format string");
12769 				goto err;
12770 			}
12771 
12772 			i -= desc->dofa_arg;
12773 			fmt = kmem_alloc(i + 1, KM_SLEEP);
12774 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
12775 			arg = (uint64_t)(uintptr_t)fmt;
12776 		} else {
12777 			if (kind == DTRACEACT_PRINTA) {
12778 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
12779 				arg = 0;
12780 			} else {
12781 				arg = desc->dofa_arg;
12782 			}
12783 		}
12784 
12785 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
12786 		    desc->dofa_uarg, arg);
12787 
12788 		if (last != NULL) {
12789 			last->dtad_next = act;
12790 		} else {
12791 			first = act;
12792 		}
12793 
12794 		last = act;
12795 
12796 		if (desc->dofa_difo == DOF_SECIDX_NONE)
12797 			continue;
12798 
12799 		if ((difosec = dtrace_dof_sect(dof,
12800 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
12801 			goto err;
12802 
12803 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
12804 
12805 		if (act->dtad_difo == NULL)
12806 			goto err;
12807 	}
12808 
12809 	ASSERT(first != NULL);
12810 	return (first);
12811 
12812 err:
12813 	for (act = first; act != NULL; act = next) {
12814 		next = act->dtad_next;
12815 		dtrace_actdesc_release(act, vstate);
12816 	}
12817 
12818 	return (NULL);
12819 }
12820 
12821 static dtrace_ecbdesc_t *
12822 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12823     cred_t *cr)
12824 {
12825 	dtrace_ecbdesc_t *ep;
12826 	dof_ecbdesc_t *ecb;
12827 	dtrace_probedesc_t *desc;
12828 	dtrace_predicate_t *pred = NULL;
12829 
12830 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
12831 		dtrace_dof_error(dof, "truncated ECB description");
12832 		return (NULL);
12833 	}
12834 
12835 	if (sec->dofs_align != sizeof (uint64_t)) {
12836 		dtrace_dof_error(dof, "bad alignment in ECB description");
12837 		return (NULL);
12838 	}
12839 
12840 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
12841 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
12842 
12843 	if (sec == NULL)
12844 		return (NULL);
12845 
12846 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12847 	ep->dted_uarg = ecb->dofe_uarg;
12848 	desc = &ep->dted_probe;
12849 
12850 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
12851 		goto err;
12852 
12853 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
12854 		if ((sec = dtrace_dof_sect(dof,
12855 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12856 			goto err;
12857 
12858 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12859 			goto err;
12860 
12861 		ep->dted_pred.dtpdd_predicate = pred;
12862 	}
12863 
12864 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12865 		if ((sec = dtrace_dof_sect(dof,
12866 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12867 			goto err;
12868 
12869 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12870 
12871 		if (ep->dted_action == NULL)
12872 			goto err;
12873 	}
12874 
12875 	return (ep);
12876 
12877 err:
12878 	if (pred != NULL)
12879 		dtrace_predicate_release(pred, vstate);
12880 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12881 	return (NULL);
12882 }
12883 
12884 /*
12885  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12886  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
12887  * site of any user SETX relocations to account for load object base address.
12888  * In the future, if we need other relocations, this function can be extended.
12889  */
12890 static int
12891 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12892 {
12893 	uintptr_t daddr = (uintptr_t)dof;
12894 	dof_relohdr_t *dofr =
12895 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12896 	dof_sec_t *ss, *rs, *ts;
12897 	dof_relodesc_t *r;
12898 	uint_t i, n;
12899 
12900 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12901 	    sec->dofs_align != sizeof (dof_secidx_t)) {
12902 		dtrace_dof_error(dof, "invalid relocation header");
12903 		return (-1);
12904 	}
12905 
12906 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12907 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12908 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12909 
12910 	if (ss == NULL || rs == NULL || ts == NULL)
12911 		return (-1); /* dtrace_dof_error() has been called already */
12912 
12913 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12914 	    rs->dofs_align != sizeof (uint64_t)) {
12915 		dtrace_dof_error(dof, "invalid relocation section");
12916 		return (-1);
12917 	}
12918 
12919 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12920 	n = rs->dofs_size / rs->dofs_entsize;
12921 
12922 	for (i = 0; i < n; i++) {
12923 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12924 
12925 		switch (r->dofr_type) {
12926 		case DOF_RELO_NONE:
12927 			break;
12928 		case DOF_RELO_SETX:
12929 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12930 			    sizeof (uint64_t) > ts->dofs_size) {
12931 				dtrace_dof_error(dof, "bad relocation offset");
12932 				return (-1);
12933 			}
12934 
12935 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12936 				dtrace_dof_error(dof, "misaligned setx relo");
12937 				return (-1);
12938 			}
12939 
12940 			*(uint64_t *)taddr += ubase;
12941 			break;
12942 		default:
12943 			dtrace_dof_error(dof, "invalid relocation type");
12944 			return (-1);
12945 		}
12946 
12947 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12948 	}
12949 
12950 	return (0);
12951 }
12952 
12953 /*
12954  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12955  * header:  it should be at the front of a memory region that is at least
12956  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12957  * size.  It need not be validated in any other way.
12958  */
12959 static int
12960 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12961     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12962 {
12963 	uint64_t len = dof->dofh_loadsz, seclen;
12964 	uintptr_t daddr = (uintptr_t)dof;
12965 	dtrace_ecbdesc_t *ep;
12966 	dtrace_enabling_t *enab;
12967 	uint_t i;
12968 
12969 	ASSERT(MUTEX_HELD(&dtrace_lock));
12970 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12971 
12972 	/*
12973 	 * Check the DOF header identification bytes.  In addition to checking
12974 	 * valid settings, we also verify that unused bits/bytes are zeroed so
12975 	 * we can use them later without fear of regressing existing binaries.
12976 	 */
12977 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12978 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12979 		dtrace_dof_error(dof, "DOF magic string mismatch");
12980 		return (-1);
12981 	}
12982 
12983 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12984 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12985 		dtrace_dof_error(dof, "DOF has invalid data model");
12986 		return (-1);
12987 	}
12988 
12989 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12990 		dtrace_dof_error(dof, "DOF encoding mismatch");
12991 		return (-1);
12992 	}
12993 
12994 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12995 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12996 		dtrace_dof_error(dof, "DOF version mismatch");
12997 		return (-1);
12998 	}
12999 
13000 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
13001 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
13002 		return (-1);
13003 	}
13004 
13005 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
13006 		dtrace_dof_error(dof, "DOF uses too many integer registers");
13007 		return (-1);
13008 	}
13009 
13010 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13011 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
13012 		return (-1);
13013 	}
13014 
13015 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13016 		if (dof->dofh_ident[i] != 0) {
13017 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
13018 			return (-1);
13019 		}
13020 	}
13021 
13022 	if (dof->dofh_flags & ~DOF_FL_VALID) {
13023 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
13024 		return (-1);
13025 	}
13026 
13027 	if (dof->dofh_secsize == 0) {
13028 		dtrace_dof_error(dof, "zero section header size");
13029 		return (-1);
13030 	}
13031 
13032 	/*
13033 	 * Check that the section headers don't exceed the amount of DOF
13034 	 * data.  Note that we cast the section size and number of sections
13035 	 * to uint64_t's to prevent possible overflow in the multiplication.
13036 	 */
13037 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13038 
13039 	if (dof->dofh_secoff > len || seclen > len ||
13040 	    dof->dofh_secoff + seclen > len) {
13041 		dtrace_dof_error(dof, "truncated section headers");
13042 		return (-1);
13043 	}
13044 
13045 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13046 		dtrace_dof_error(dof, "misaligned section headers");
13047 		return (-1);
13048 	}
13049 
13050 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13051 		dtrace_dof_error(dof, "misaligned section size");
13052 		return (-1);
13053 	}
13054 
13055 	/*
13056 	 * Take an initial pass through the section headers to be sure that
13057 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
13058 	 * set, do not permit sections relating to providers, probes, or args.
13059 	 */
13060 	for (i = 0; i < dof->dofh_secnum; i++) {
13061 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13062 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13063 
13064 		if (noprobes) {
13065 			switch (sec->dofs_type) {
13066 			case DOF_SECT_PROVIDER:
13067 			case DOF_SECT_PROBES:
13068 			case DOF_SECT_PRARGS:
13069 			case DOF_SECT_PROFFS:
13070 				dtrace_dof_error(dof, "illegal sections "
13071 				    "for enabling");
13072 				return (-1);
13073 			}
13074 		}
13075 
13076 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
13077 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
13078 			dtrace_dof_error(dof, "loadable section with load "
13079 			    "flag unset");
13080 			return (-1);
13081 		}
13082 
13083 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
13084 			continue; /* just ignore non-loadable sections */
13085 
13086 		if (!ISP2(sec->dofs_align)) {
13087 			dtrace_dof_error(dof, "bad section alignment");
13088 			return (-1);
13089 		}
13090 
13091 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
13092 			dtrace_dof_error(dof, "misaligned section");
13093 			return (-1);
13094 		}
13095 
13096 		if (sec->dofs_offset > len || sec->dofs_size > len ||
13097 		    sec->dofs_offset + sec->dofs_size > len) {
13098 			dtrace_dof_error(dof, "corrupt section header");
13099 			return (-1);
13100 		}
13101 
13102 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13103 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13104 			dtrace_dof_error(dof, "non-terminating string table");
13105 			return (-1);
13106 		}
13107 	}
13108 
13109 	/*
13110 	 * Take a second pass through the sections and locate and perform any
13111 	 * relocations that are present.  We do this after the first pass to
13112 	 * be sure that all sections have had their headers validated.
13113 	 */
13114 	for (i = 0; i < dof->dofh_secnum; i++) {
13115 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13116 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13117 
13118 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
13119 			continue; /* skip sections that are not loadable */
13120 
13121 		switch (sec->dofs_type) {
13122 		case DOF_SECT_URELHDR:
13123 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
13124 				return (-1);
13125 			break;
13126 		}
13127 	}
13128 
13129 	if ((enab = *enabp) == NULL)
13130 		enab = *enabp = dtrace_enabling_create(vstate);
13131 
13132 	for (i = 0; i < dof->dofh_secnum; i++) {
13133 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13134 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13135 
13136 		if (sec->dofs_type != DOF_SECT_ECBDESC)
13137 			continue;
13138 
13139 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
13140 			dtrace_enabling_destroy(enab);
13141 			*enabp = NULL;
13142 			return (-1);
13143 		}
13144 
13145 		dtrace_enabling_add(enab, ep);
13146 	}
13147 
13148 	return (0);
13149 }
13150 
13151 /*
13152  * Process DOF for any options.  This routine assumes that the DOF has been
13153  * at least processed by dtrace_dof_slurp().
13154  */
13155 static int
13156 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13157 {
13158 	int i, rval;
13159 	uint32_t entsize;
13160 	size_t offs;
13161 	dof_optdesc_t *desc;
13162 
13163 	for (i = 0; i < dof->dofh_secnum; i++) {
13164 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13165 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13166 
13167 		if (sec->dofs_type != DOF_SECT_OPTDESC)
13168 			continue;
13169 
13170 		if (sec->dofs_align != sizeof (uint64_t)) {
13171 			dtrace_dof_error(dof, "bad alignment in "
13172 			    "option description");
13173 			return (EINVAL);
13174 		}
13175 
13176 		if ((entsize = sec->dofs_entsize) == 0) {
13177 			dtrace_dof_error(dof, "zeroed option entry size");
13178 			return (EINVAL);
13179 		}
13180 
13181 		if (entsize < sizeof (dof_optdesc_t)) {
13182 			dtrace_dof_error(dof, "bad option entry size");
13183 			return (EINVAL);
13184 		}
13185 
13186 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13187 			desc = (dof_optdesc_t *)((uintptr_t)dof +
13188 			    (uintptr_t)sec->dofs_offset + offs);
13189 
13190 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13191 				dtrace_dof_error(dof, "non-zero option string");
13192 				return (EINVAL);
13193 			}
13194 
13195 			if (desc->dofo_value == DTRACEOPT_UNSET) {
13196 				dtrace_dof_error(dof, "unset option");
13197 				return (EINVAL);
13198 			}
13199 
13200 			if ((rval = dtrace_state_option(state,
13201 			    desc->dofo_option, desc->dofo_value)) != 0) {
13202 				dtrace_dof_error(dof, "rejected option");
13203 				return (rval);
13204 			}
13205 		}
13206 	}
13207 
13208 	return (0);
13209 }
13210 
13211 /*
13212  * DTrace Consumer State Functions
13213  */
13214 int
13215 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13216 {
13217 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
13218 	void *base;
13219 	uintptr_t limit;
13220 	dtrace_dynvar_t *dvar, *next, *start;
13221 	int i;
13222 
13223 	ASSERT(MUTEX_HELD(&dtrace_lock));
13224 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13225 
13226 	bzero(dstate, sizeof (dtrace_dstate_t));
13227 
13228 	if ((dstate->dtds_chunksize = chunksize) == 0)
13229 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13230 
13231 	VERIFY(dstate->dtds_chunksize < LONG_MAX);
13232 
13233 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13234 		size = min;
13235 
13236 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
13237 		return (ENOMEM);
13238 
13239 	dstate->dtds_size = size;
13240 	dstate->dtds_base = base;
13241 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
13242 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
13243 
13244 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13245 
13246 	if (hashsize != 1 && (hashsize & 1))
13247 		hashsize--;
13248 
13249 	dstate->dtds_hashsize = hashsize;
13250 	dstate->dtds_hash = dstate->dtds_base;
13251 
13252 	/*
13253 	 * Set all of our hash buckets to point to the single sink, and (if
13254 	 * it hasn't already been set), set the sink's hash value to be the
13255 	 * sink sentinel value.  The sink is needed for dynamic variable
13256 	 * lookups to know that they have iterated over an entire, valid hash
13257 	 * chain.
13258 	 */
13259 	for (i = 0; i < hashsize; i++)
13260 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13261 
13262 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13263 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13264 
13265 	/*
13266 	 * Determine number of active CPUs.  Divide free list evenly among
13267 	 * active CPUs.
13268 	 */
13269 	start = (dtrace_dynvar_t *)
13270 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13271 	limit = (uintptr_t)base + size;
13272 
13273 	VERIFY((uintptr_t)start < limit);
13274 	VERIFY((uintptr_t)start >= (uintptr_t)base);
13275 
13276 	maxper = (limit - (uintptr_t)start) / NCPU;
13277 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13278 
13279 	for (i = 0; i < NCPU; i++) {
13280 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13281 
13282 		/*
13283 		 * If we don't even have enough chunks to make it once through
13284 		 * NCPUs, we're just going to allocate everything to the first
13285 		 * CPU.  And if we're on the last CPU, we're going to allocate
13286 		 * whatever is left over.  In either case, we set the limit to
13287 		 * be the limit of the dynamic variable space.
13288 		 */
13289 		if (maxper == 0 || i == NCPU - 1) {
13290 			limit = (uintptr_t)base + size;
13291 			start = NULL;
13292 		} else {
13293 			limit = (uintptr_t)start + maxper;
13294 			start = (dtrace_dynvar_t *)limit;
13295 		}
13296 
13297 		VERIFY(limit <= (uintptr_t)base + size);
13298 
13299 		for (;;) {
13300 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13301 			    dstate->dtds_chunksize);
13302 
13303 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13304 				break;
13305 
13306 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
13307 			    (uintptr_t)dvar <= (uintptr_t)base + size);
13308 			dvar->dtdv_next = next;
13309 			dvar = next;
13310 		}
13311 
13312 		if (maxper == 0)
13313 			break;
13314 	}
13315 
13316 	return (0);
13317 }
13318 
13319 void
13320 dtrace_dstate_fini(dtrace_dstate_t *dstate)
13321 {
13322 	ASSERT(MUTEX_HELD(&cpu_lock));
13323 
13324 	if (dstate->dtds_base == NULL)
13325 		return;
13326 
13327 	kmem_free(dstate->dtds_base, dstate->dtds_size);
13328 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13329 }
13330 
13331 static void
13332 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13333 {
13334 	/*
13335 	 * Logical XOR, where are you?
13336 	 */
13337 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13338 
13339 	if (vstate->dtvs_nglobals > 0) {
13340 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13341 		    sizeof (dtrace_statvar_t *));
13342 	}
13343 
13344 	if (vstate->dtvs_ntlocals > 0) {
13345 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13346 		    sizeof (dtrace_difv_t));
13347 	}
13348 
13349 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13350 
13351 	if (vstate->dtvs_nlocals > 0) {
13352 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13353 		    sizeof (dtrace_statvar_t *));
13354 	}
13355 }
13356 
13357 static void
13358 dtrace_state_clean(dtrace_state_t *state)
13359 {
13360 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13361 		return;
13362 
13363 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13364 	dtrace_speculation_clean(state);
13365 }
13366 
13367 static void
13368 dtrace_state_deadman(dtrace_state_t *state)
13369 {
13370 	hrtime_t now;
13371 
13372 	dtrace_sync();
13373 
13374 	now = dtrace_gethrtime();
13375 
13376 	if (state != dtrace_anon.dta_state &&
13377 	    now - state->dts_laststatus >= dtrace_deadman_user)
13378 		return;
13379 
13380 	/*
13381 	 * We must be sure that dts_alive never appears to be less than the
13382 	 * value upon entry to dtrace_state_deadman(), and because we lack a
13383 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13384 	 * store INT64_MAX to it, followed by a memory barrier, followed by
13385 	 * the new value.  This assures that dts_alive never appears to be
13386 	 * less than its true value, regardless of the order in which the
13387 	 * stores to the underlying storage are issued.
13388 	 */
13389 	state->dts_alive = INT64_MAX;
13390 	dtrace_membar_producer();
13391 	state->dts_alive = now;
13392 }
13393 
13394 dtrace_state_t *
13395 dtrace_state_create(dev_t *devp, cred_t *cr)
13396 {
13397 	minor_t minor;
13398 	major_t major;
13399 	char c[30];
13400 	dtrace_state_t *state;
13401 	dtrace_optval_t *opt;
13402 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13403 
13404 	ASSERT(MUTEX_HELD(&dtrace_lock));
13405 	ASSERT(MUTEX_HELD(&cpu_lock));
13406 
13407 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13408 	    VM_BESTFIT | VM_SLEEP);
13409 
13410 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13411 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13412 		return (NULL);
13413 	}
13414 
13415 	state = ddi_get_soft_state(dtrace_softstate, minor);
13416 	state->dts_epid = DTRACE_EPIDNONE + 1;
13417 
13418 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
13419 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13420 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13421 
13422 	if (devp != NULL) {
13423 		major = getemajor(*devp);
13424 	} else {
13425 		major = ddi_driver_major(dtrace_devi);
13426 	}
13427 
13428 	state->dts_dev = makedevice(major, minor);
13429 
13430 	if (devp != NULL)
13431 		*devp = state->dts_dev;
13432 
13433 	/*
13434 	 * We allocate NCPU buffers.  On the one hand, this can be quite
13435 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
13436 	 * other hand, it saves an additional memory reference in the probe
13437 	 * path.
13438 	 */
13439 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13440 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13441 	state->dts_cleaner = CYCLIC_NONE;
13442 	state->dts_deadman = CYCLIC_NONE;
13443 	state->dts_vstate.dtvs_state = state;
13444 
13445 	for (i = 0; i < DTRACEOPT_MAX; i++)
13446 		state->dts_options[i] = DTRACEOPT_UNSET;
13447 
13448 	/*
13449 	 * Set the default options.
13450 	 */
13451 	opt = state->dts_options;
13452 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13453 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13454 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13455 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13456 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13457 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13458 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13459 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13460 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13461 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13462 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13463 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13464 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13465 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13466 
13467 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13468 
13469 	/*
13470 	 * Depending on the user credentials, we set flag bits which alter probe
13471 	 * visibility or the amount of destructiveness allowed.  In the case of
13472 	 * actual anonymous tracing, or the possession of all privileges, all of
13473 	 * the normal checks are bypassed.
13474 	 */
13475 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13476 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13477 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13478 	} else {
13479 		/*
13480 		 * Set up the credentials for this instantiation.  We take a
13481 		 * hold on the credential to prevent it from disappearing on
13482 		 * us; this in turn prevents the zone_t referenced by this
13483 		 * credential from disappearing.  This means that we can
13484 		 * examine the credential and the zone from probe context.
13485 		 */
13486 		crhold(cr);
13487 		state->dts_cred.dcr_cred = cr;
13488 
13489 		/*
13490 		 * CRA_PROC means "we have *some* privilege for dtrace" and
13491 		 * unlocks the use of variables like pid, zonename, etc.
13492 		 */
13493 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13494 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13495 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13496 		}
13497 
13498 		/*
13499 		 * dtrace_user allows use of syscall and profile providers.
13500 		 * If the user also has proc_owner and/or proc_zone, we
13501 		 * extend the scope to include additional visibility and
13502 		 * destructive power.
13503 		 */
13504 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13505 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13506 				state->dts_cred.dcr_visible |=
13507 				    DTRACE_CRV_ALLPROC;
13508 
13509 				state->dts_cred.dcr_action |=
13510 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13511 			}
13512 
13513 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13514 				state->dts_cred.dcr_visible |=
13515 				    DTRACE_CRV_ALLZONE;
13516 
13517 				state->dts_cred.dcr_action |=
13518 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13519 			}
13520 
13521 			/*
13522 			 * If we have all privs in whatever zone this is,
13523 			 * we can do destructive things to processes which
13524 			 * have altered credentials.
13525 			 */
13526 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13527 			    cr->cr_zone->zone_privset)) {
13528 				state->dts_cred.dcr_action |=
13529 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13530 			}
13531 		}
13532 
13533 		/*
13534 		 * Holding the dtrace_kernel privilege also implies that
13535 		 * the user has the dtrace_user privilege from a visibility
13536 		 * perspective.  But without further privileges, some
13537 		 * destructive actions are not available.
13538 		 */
13539 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13540 			/*
13541 			 * Make all probes in all zones visible.  However,
13542 			 * this doesn't mean that all actions become available
13543 			 * to all zones.
13544 			 */
13545 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13546 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13547 
13548 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13549 			    DTRACE_CRA_PROC;
13550 			/*
13551 			 * Holding proc_owner means that destructive actions
13552 			 * for *this* zone are allowed.
13553 			 */
13554 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13555 				state->dts_cred.dcr_action |=
13556 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13557 
13558 			/*
13559 			 * Holding proc_zone means that destructive actions
13560 			 * for this user/group ID in all zones is allowed.
13561 			 */
13562 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13563 				state->dts_cred.dcr_action |=
13564 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13565 
13566 			/*
13567 			 * If we have all privs in whatever zone this is,
13568 			 * we can do destructive things to processes which
13569 			 * have altered credentials.
13570 			 */
13571 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13572 			    cr->cr_zone->zone_privset)) {
13573 				state->dts_cred.dcr_action |=
13574 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13575 			}
13576 		}
13577 
13578 		/*
13579 		 * Holding the dtrace_proc privilege gives control over fasttrap
13580 		 * and pid providers.  We need to grant wider destructive
13581 		 * privileges in the event that the user has proc_owner and/or
13582 		 * proc_zone.
13583 		 */
13584 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13585 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13586 				state->dts_cred.dcr_action |=
13587 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13588 
13589 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13590 				state->dts_cred.dcr_action |=
13591 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13592 		}
13593 	}
13594 
13595 	return (state);
13596 }
13597 
13598 static int
13599 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13600 {
13601 	dtrace_optval_t *opt = state->dts_options, size;
13602 	processorid_t cpu;
13603 	int flags = 0, rval, factor, divisor = 1;
13604 
13605 	ASSERT(MUTEX_HELD(&dtrace_lock));
13606 	ASSERT(MUTEX_HELD(&cpu_lock));
13607 	ASSERT(which < DTRACEOPT_MAX);
13608 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13609 	    (state == dtrace_anon.dta_state &&
13610 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13611 
13612 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13613 		return (0);
13614 
13615 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13616 		cpu = opt[DTRACEOPT_CPU];
13617 
13618 	if (which == DTRACEOPT_SPECSIZE)
13619 		flags |= DTRACEBUF_NOSWITCH;
13620 
13621 	if (which == DTRACEOPT_BUFSIZE) {
13622 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13623 			flags |= DTRACEBUF_RING;
13624 
13625 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13626 			flags |= DTRACEBUF_FILL;
13627 
13628 		if (state != dtrace_anon.dta_state ||
13629 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13630 			flags |= DTRACEBUF_INACTIVE;
13631 	}
13632 
13633 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
13634 		/*
13635 		 * The size must be 8-byte aligned.  If the size is not 8-byte
13636 		 * aligned, drop it down by the difference.
13637 		 */
13638 		if (size & (sizeof (uint64_t) - 1))
13639 			size -= size & (sizeof (uint64_t) - 1);
13640 
13641 		if (size < state->dts_reserve) {
13642 			/*
13643 			 * Buffers always must be large enough to accommodate
13644 			 * their prereserved space.  We return E2BIG instead
13645 			 * of ENOMEM in this case to allow for user-level
13646 			 * software to differentiate the cases.
13647 			 */
13648 			return (E2BIG);
13649 		}
13650 
13651 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
13652 
13653 		if (rval != ENOMEM) {
13654 			opt[which] = size;
13655 			return (rval);
13656 		}
13657 
13658 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13659 			return (rval);
13660 
13661 		for (divisor = 2; divisor < factor; divisor <<= 1)
13662 			continue;
13663 	}
13664 
13665 	return (ENOMEM);
13666 }
13667 
13668 static int
13669 dtrace_state_buffers(dtrace_state_t *state)
13670 {
13671 	dtrace_speculation_t *spec = state->dts_speculations;
13672 	int rval, i;
13673 
13674 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
13675 	    DTRACEOPT_BUFSIZE)) != 0)
13676 		return (rval);
13677 
13678 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
13679 	    DTRACEOPT_AGGSIZE)) != 0)
13680 		return (rval);
13681 
13682 	for (i = 0; i < state->dts_nspeculations; i++) {
13683 		if ((rval = dtrace_state_buffer(state,
13684 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
13685 			return (rval);
13686 	}
13687 
13688 	return (0);
13689 }
13690 
13691 static void
13692 dtrace_state_prereserve(dtrace_state_t *state)
13693 {
13694 	dtrace_ecb_t *ecb;
13695 	dtrace_probe_t *probe;
13696 
13697 	state->dts_reserve = 0;
13698 
13699 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
13700 		return;
13701 
13702 	/*
13703 	 * If our buffer policy is a "fill" buffer policy, we need to set the
13704 	 * prereserved space to be the space required by the END probes.
13705 	 */
13706 	probe = dtrace_probes[dtrace_probeid_end - 1];
13707 	ASSERT(probe != NULL);
13708 
13709 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
13710 		if (ecb->dte_state != state)
13711 			continue;
13712 
13713 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
13714 	}
13715 }
13716 
13717 static int
13718 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
13719 {
13720 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
13721 	dtrace_speculation_t *spec;
13722 	dtrace_buffer_t *buf;
13723 	cyc_handler_t hdlr;
13724 	cyc_time_t when;
13725 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13726 	dtrace_icookie_t cookie;
13727 
13728 	mutex_enter(&cpu_lock);
13729 	mutex_enter(&dtrace_lock);
13730 
13731 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13732 		rval = EBUSY;
13733 		goto out;
13734 	}
13735 
13736 	/*
13737 	 * Before we can perform any checks, we must prime all of the
13738 	 * retained enablings that correspond to this state.
13739 	 */
13740 	dtrace_enabling_prime(state);
13741 
13742 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
13743 		rval = EACCES;
13744 		goto out;
13745 	}
13746 
13747 	dtrace_state_prereserve(state);
13748 
13749 	/*
13750 	 * Now we want to do is try to allocate our speculations.
13751 	 * We do not automatically resize the number of speculations; if
13752 	 * this fails, we will fail the operation.
13753 	 */
13754 	nspec = opt[DTRACEOPT_NSPEC];
13755 	ASSERT(nspec != DTRACEOPT_UNSET);
13756 
13757 	if (nspec > INT_MAX) {
13758 		rval = ENOMEM;
13759 		goto out;
13760 	}
13761 
13762 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
13763 	    KM_NOSLEEP | KM_NORMALPRI);
13764 
13765 	if (spec == NULL) {
13766 		rval = ENOMEM;
13767 		goto out;
13768 	}
13769 
13770 	state->dts_speculations = spec;
13771 	state->dts_nspeculations = (int)nspec;
13772 
13773 	for (i = 0; i < nspec; i++) {
13774 		if ((buf = kmem_zalloc(bufsize,
13775 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
13776 			rval = ENOMEM;
13777 			goto err;
13778 		}
13779 
13780 		spec[i].dtsp_buffer = buf;
13781 	}
13782 
13783 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
13784 		if (dtrace_anon.dta_state == NULL) {
13785 			rval = ENOENT;
13786 			goto out;
13787 		}
13788 
13789 		if (state->dts_necbs != 0) {
13790 			rval = EALREADY;
13791 			goto out;
13792 		}
13793 
13794 		state->dts_anon = dtrace_anon_grab();
13795 		ASSERT(state->dts_anon != NULL);
13796 		state = state->dts_anon;
13797 
13798 		/*
13799 		 * We want "grabanon" to be set in the grabbed state, so we'll
13800 		 * copy that option value from the grabbing state into the
13801 		 * grabbed state.
13802 		 */
13803 		state->dts_options[DTRACEOPT_GRABANON] =
13804 		    opt[DTRACEOPT_GRABANON];
13805 
13806 		*cpu = dtrace_anon.dta_beganon;
13807 
13808 		/*
13809 		 * If the anonymous state is active (as it almost certainly
13810 		 * is if the anonymous enabling ultimately matched anything),
13811 		 * we don't allow any further option processing -- but we
13812 		 * don't return failure.
13813 		 */
13814 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13815 			goto out;
13816 	}
13817 
13818 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
13819 	    opt[DTRACEOPT_AGGSIZE] != 0) {
13820 		if (state->dts_aggregations == NULL) {
13821 			/*
13822 			 * We're not going to create an aggregation buffer
13823 			 * because we don't have any ECBs that contain
13824 			 * aggregations -- set this option to 0.
13825 			 */
13826 			opt[DTRACEOPT_AGGSIZE] = 0;
13827 		} else {
13828 			/*
13829 			 * If we have an aggregation buffer, we must also have
13830 			 * a buffer to use as scratch.
13831 			 */
13832 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
13833 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
13834 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
13835 			}
13836 		}
13837 	}
13838 
13839 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
13840 	    opt[DTRACEOPT_SPECSIZE] != 0) {
13841 		if (!state->dts_speculates) {
13842 			/*
13843 			 * We're not going to create speculation buffers
13844 			 * because we don't have any ECBs that actually
13845 			 * speculate -- set the speculation size to 0.
13846 			 */
13847 			opt[DTRACEOPT_SPECSIZE] = 0;
13848 		}
13849 	}
13850 
13851 	/*
13852 	 * The bare minimum size for any buffer that we're actually going to
13853 	 * do anything to is sizeof (uint64_t).
13854 	 */
13855 	sz = sizeof (uint64_t);
13856 
13857 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
13858 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
13859 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
13860 		/*
13861 		 * A buffer size has been explicitly set to 0 (or to a size
13862 		 * that will be adjusted to 0) and we need the space -- we
13863 		 * need to return failure.  We return ENOSPC to differentiate
13864 		 * it from failing to allocate a buffer due to failure to meet
13865 		 * the reserve (for which we return E2BIG).
13866 		 */
13867 		rval = ENOSPC;
13868 		goto out;
13869 	}
13870 
13871 	if ((rval = dtrace_state_buffers(state)) != 0)
13872 		goto err;
13873 
13874 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13875 		sz = dtrace_dstate_defsize;
13876 
13877 	do {
13878 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13879 
13880 		if (rval == 0)
13881 			break;
13882 
13883 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13884 			goto err;
13885 	} while (sz >>= 1);
13886 
13887 	opt[DTRACEOPT_DYNVARSIZE] = sz;
13888 
13889 	if (rval != 0)
13890 		goto err;
13891 
13892 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13893 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13894 
13895 	if (opt[DTRACEOPT_CLEANRATE] == 0)
13896 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13897 
13898 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13899 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13900 
13901 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13902 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13903 
13904 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13905 	hdlr.cyh_arg = state;
13906 	hdlr.cyh_level = CY_LOW_LEVEL;
13907 
13908 	when.cyt_when = 0;
13909 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13910 
13911 	state->dts_cleaner = cyclic_add(&hdlr, &when);
13912 
13913 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13914 	hdlr.cyh_arg = state;
13915 	hdlr.cyh_level = CY_LOW_LEVEL;
13916 
13917 	when.cyt_when = 0;
13918 	when.cyt_interval = dtrace_deadman_interval;
13919 
13920 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13921 	state->dts_deadman = cyclic_add(&hdlr, &when);
13922 
13923 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13924 
13925 	if (state->dts_getf != 0 &&
13926 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
13927 		/*
13928 		 * We don't have kernel privs but we have at least one call
13929 		 * to getf(); we need to bump our zone's count, and (if
13930 		 * this is the first enabling to have an unprivileged call
13931 		 * to getf()) we need to hook into closef().
13932 		 */
13933 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
13934 
13935 		if (dtrace_getf++ == 0) {
13936 			ASSERT(dtrace_closef == NULL);
13937 			dtrace_closef = dtrace_getf_barrier;
13938 		}
13939 	}
13940 
13941 	/*
13942 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
13943 	 * interrupts here both to record the CPU on which we fired the BEGIN
13944 	 * probe (the data from this CPU will be processed first at user
13945 	 * level) and to manually activate the buffer for this CPU.
13946 	 */
13947 	cookie = dtrace_interrupt_disable();
13948 	*cpu = CPU->cpu_id;
13949 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13950 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13951 
13952 	dtrace_probe(dtrace_probeid_begin,
13953 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13954 	dtrace_interrupt_enable(cookie);
13955 	/*
13956 	 * We may have had an exit action from a BEGIN probe; only change our
13957 	 * state to ACTIVE if we're still in WARMUP.
13958 	 */
13959 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13960 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13961 
13962 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13963 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13964 
13965 	/*
13966 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13967 	 * want each CPU to transition its principal buffer out of the
13968 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
13969 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13970 	 * atomically transition from processing none of a state's ECBs to
13971 	 * processing all of them.
13972 	 */
13973 	dtrace_xcall(DTRACE_CPUALL,
13974 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
13975 	goto out;
13976 
13977 err:
13978 	dtrace_buffer_free(state->dts_buffer);
13979 	dtrace_buffer_free(state->dts_aggbuffer);
13980 
13981 	if ((nspec = state->dts_nspeculations) == 0) {
13982 		ASSERT(state->dts_speculations == NULL);
13983 		goto out;
13984 	}
13985 
13986 	spec = state->dts_speculations;
13987 	ASSERT(spec != NULL);
13988 
13989 	for (i = 0; i < state->dts_nspeculations; i++) {
13990 		if ((buf = spec[i].dtsp_buffer) == NULL)
13991 			break;
13992 
13993 		dtrace_buffer_free(buf);
13994 		kmem_free(buf, bufsize);
13995 	}
13996 
13997 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13998 	state->dts_nspeculations = 0;
13999 	state->dts_speculations = NULL;
14000 
14001 out:
14002 	mutex_exit(&dtrace_lock);
14003 	mutex_exit(&cpu_lock);
14004 
14005 	return (rval);
14006 }
14007 
14008 static int
14009 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14010 {
14011 	dtrace_icookie_t cookie;
14012 
14013 	ASSERT(MUTEX_HELD(&dtrace_lock));
14014 
14015 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14016 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14017 		return (EINVAL);
14018 
14019 	/*
14020 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14021 	 * to be sure that every CPU has seen it.  See below for the details
14022 	 * on why this is done.
14023 	 */
14024 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14025 	dtrace_sync();
14026 
14027 	/*
14028 	 * By this point, it is impossible for any CPU to be still processing
14029 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
14030 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14031 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
14032 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14033 	 * iff we're in the END probe.
14034 	 */
14035 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14036 	dtrace_sync();
14037 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14038 
14039 	/*
14040 	 * Finally, we can release the reserve and call the END probe.  We
14041 	 * disable interrupts across calling the END probe to allow us to
14042 	 * return the CPU on which we actually called the END probe.  This
14043 	 * allows user-land to be sure that this CPU's principal buffer is
14044 	 * processed last.
14045 	 */
14046 	state->dts_reserve = 0;
14047 
14048 	cookie = dtrace_interrupt_disable();
14049 	*cpu = CPU->cpu_id;
14050 	dtrace_probe(dtrace_probeid_end,
14051 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14052 	dtrace_interrupt_enable(cookie);
14053 
14054 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14055 	dtrace_sync();
14056 
14057 	if (state->dts_getf != 0 &&
14058 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14059 		/*
14060 		 * We don't have kernel privs but we have at least one call
14061 		 * to getf(); we need to lower our zone's count, and (if
14062 		 * this is the last enabling to have an unprivileged call
14063 		 * to getf()) we need to clear the closef() hook.
14064 		 */
14065 		ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
14066 		ASSERT(dtrace_closef == dtrace_getf_barrier);
14067 		ASSERT(dtrace_getf > 0);
14068 
14069 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
14070 
14071 		if (--dtrace_getf == 0)
14072 			dtrace_closef = NULL;
14073 	}
14074 
14075 	return (0);
14076 }
14077 
14078 static int
14079 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14080     dtrace_optval_t val)
14081 {
14082 	ASSERT(MUTEX_HELD(&dtrace_lock));
14083 
14084 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14085 		return (EBUSY);
14086 
14087 	if (option >= DTRACEOPT_MAX)
14088 		return (EINVAL);
14089 
14090 	if (option != DTRACEOPT_CPU && val < 0)
14091 		return (EINVAL);
14092 
14093 	switch (option) {
14094 	case DTRACEOPT_DESTRUCTIVE:
14095 		if (dtrace_destructive_disallow)
14096 			return (EACCES);
14097 
14098 		state->dts_cred.dcr_destructive = 1;
14099 		break;
14100 
14101 	case DTRACEOPT_BUFSIZE:
14102 	case DTRACEOPT_DYNVARSIZE:
14103 	case DTRACEOPT_AGGSIZE:
14104 	case DTRACEOPT_SPECSIZE:
14105 	case DTRACEOPT_STRSIZE:
14106 		if (val < 0)
14107 			return (EINVAL);
14108 
14109 		if (val >= LONG_MAX) {
14110 			/*
14111 			 * If this is an otherwise negative value, set it to
14112 			 * the highest multiple of 128m less than LONG_MAX.
14113 			 * Technically, we're adjusting the size without
14114 			 * regard to the buffer resizing policy, but in fact,
14115 			 * this has no effect -- if we set the buffer size to
14116 			 * ~LONG_MAX and the buffer policy is ultimately set to
14117 			 * be "manual", the buffer allocation is guaranteed to
14118 			 * fail, if only because the allocation requires two
14119 			 * buffers.  (We set the the size to the highest
14120 			 * multiple of 128m because it ensures that the size
14121 			 * will remain a multiple of a megabyte when
14122 			 * repeatedly halved -- all the way down to 15m.)
14123 			 */
14124 			val = LONG_MAX - (1 << 27) + 1;
14125 		}
14126 	}
14127 
14128 	state->dts_options[option] = val;
14129 
14130 	return (0);
14131 }
14132 
14133 static void
14134 dtrace_state_destroy(dtrace_state_t *state)
14135 {
14136 	dtrace_ecb_t *ecb;
14137 	dtrace_vstate_t *vstate = &state->dts_vstate;
14138 	minor_t minor = getminor(state->dts_dev);
14139 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14140 	dtrace_speculation_t *spec = state->dts_speculations;
14141 	int nspec = state->dts_nspeculations;
14142 	uint32_t match;
14143 
14144 	ASSERT(MUTEX_HELD(&dtrace_lock));
14145 	ASSERT(MUTEX_HELD(&cpu_lock));
14146 
14147 	/*
14148 	 * First, retract any retained enablings for this state.
14149 	 */
14150 	dtrace_enabling_retract(state);
14151 	ASSERT(state->dts_nretained == 0);
14152 
14153 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14154 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14155 		/*
14156 		 * We have managed to come into dtrace_state_destroy() on a
14157 		 * hot enabling -- almost certainly because of a disorderly
14158 		 * shutdown of a consumer.  (That is, a consumer that is
14159 		 * exiting without having called dtrace_stop().) In this case,
14160 		 * we're going to set our activity to be KILLED, and then
14161 		 * issue a sync to be sure that everyone is out of probe
14162 		 * context before we start blowing away ECBs.
14163 		 */
14164 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
14165 		dtrace_sync();
14166 	}
14167 
14168 	/*
14169 	 * Release the credential hold we took in dtrace_state_create().
14170 	 */
14171 	if (state->dts_cred.dcr_cred != NULL)
14172 		crfree(state->dts_cred.dcr_cred);
14173 
14174 	/*
14175 	 * Now we can safely disable and destroy any enabled probes.  Because
14176 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
14177 	 * (especially if they're all enabled), we take two passes through the
14178 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
14179 	 * in the second we disable whatever is left over.
14180 	 */
14181 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
14182 		for (i = 0; i < state->dts_necbs; i++) {
14183 			if ((ecb = state->dts_ecbs[i]) == NULL)
14184 				continue;
14185 
14186 			if (match && ecb->dte_probe != NULL) {
14187 				dtrace_probe_t *probe = ecb->dte_probe;
14188 				dtrace_provider_t *prov = probe->dtpr_provider;
14189 
14190 				if (!(prov->dtpv_priv.dtpp_flags & match))
14191 					continue;
14192 			}
14193 
14194 			dtrace_ecb_disable(ecb);
14195 			dtrace_ecb_destroy(ecb);
14196 		}
14197 
14198 		if (!match)
14199 			break;
14200 	}
14201 
14202 	/*
14203 	 * Before we free the buffers, perform one more sync to assure that
14204 	 * every CPU is out of probe context.
14205 	 */
14206 	dtrace_sync();
14207 
14208 	dtrace_buffer_free(state->dts_buffer);
14209 	dtrace_buffer_free(state->dts_aggbuffer);
14210 
14211 	for (i = 0; i < nspec; i++)
14212 		dtrace_buffer_free(spec[i].dtsp_buffer);
14213 
14214 	if (state->dts_cleaner != CYCLIC_NONE)
14215 		cyclic_remove(state->dts_cleaner);
14216 
14217 	if (state->dts_deadman != CYCLIC_NONE)
14218 		cyclic_remove(state->dts_deadman);
14219 
14220 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
14221 	dtrace_vstate_fini(vstate);
14222 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14223 
14224 	if (state->dts_aggregations != NULL) {
14225 #ifdef DEBUG
14226 		for (i = 0; i < state->dts_naggregations; i++)
14227 			ASSERT(state->dts_aggregations[i] == NULL);
14228 #endif
14229 		ASSERT(state->dts_naggregations > 0);
14230 		kmem_free(state->dts_aggregations,
14231 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14232 	}
14233 
14234 	kmem_free(state->dts_buffer, bufsize);
14235 	kmem_free(state->dts_aggbuffer, bufsize);
14236 
14237 	for (i = 0; i < nspec; i++)
14238 		kmem_free(spec[i].dtsp_buffer, bufsize);
14239 
14240 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14241 
14242 	dtrace_format_destroy(state);
14243 
14244 	vmem_destroy(state->dts_aggid_arena);
14245 	ddi_soft_state_free(dtrace_softstate, minor);
14246 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14247 }
14248 
14249 /*
14250  * DTrace Anonymous Enabling Functions
14251  */
14252 static dtrace_state_t *
14253 dtrace_anon_grab(void)
14254 {
14255 	dtrace_state_t *state;
14256 
14257 	ASSERT(MUTEX_HELD(&dtrace_lock));
14258 
14259 	if ((state = dtrace_anon.dta_state) == NULL) {
14260 		ASSERT(dtrace_anon.dta_enabling == NULL);
14261 		return (NULL);
14262 	}
14263 
14264 	ASSERT(dtrace_anon.dta_enabling != NULL);
14265 	ASSERT(dtrace_retained != NULL);
14266 
14267 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14268 	dtrace_anon.dta_enabling = NULL;
14269 	dtrace_anon.dta_state = NULL;
14270 
14271 	return (state);
14272 }
14273 
14274 static void
14275 dtrace_anon_property(void)
14276 {
14277 	int i, rv;
14278 	dtrace_state_t *state;
14279 	dof_hdr_t *dof;
14280 	char c[32];		/* enough for "dof-data-" + digits */
14281 
14282 	ASSERT(MUTEX_HELD(&dtrace_lock));
14283 	ASSERT(MUTEX_HELD(&cpu_lock));
14284 
14285 	for (i = 0; ; i++) {
14286 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
14287 
14288 		dtrace_err_verbose = 1;
14289 
14290 		if ((dof = dtrace_dof_property(c)) == NULL) {
14291 			dtrace_err_verbose = 0;
14292 			break;
14293 		}
14294 
14295 		/*
14296 		 * We want to create anonymous state, so we need to transition
14297 		 * the kernel debugger to indicate that DTrace is active.  If
14298 		 * this fails (e.g. because the debugger has modified text in
14299 		 * some way), we won't continue with the processing.
14300 		 */
14301 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14302 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14303 			    "enabling ignored.");
14304 			dtrace_dof_destroy(dof);
14305 			break;
14306 		}
14307 
14308 		/*
14309 		 * If we haven't allocated an anonymous state, we'll do so now.
14310 		 */
14311 		if ((state = dtrace_anon.dta_state) == NULL) {
14312 			state = dtrace_state_create(NULL, NULL);
14313 			dtrace_anon.dta_state = state;
14314 
14315 			if (state == NULL) {
14316 				/*
14317 				 * This basically shouldn't happen:  the only
14318 				 * failure mode from dtrace_state_create() is a
14319 				 * failure of ddi_soft_state_zalloc() that
14320 				 * itself should never happen.  Still, the
14321 				 * interface allows for a failure mode, and
14322 				 * we want to fail as gracefully as possible:
14323 				 * we'll emit an error message and cease
14324 				 * processing anonymous state in this case.
14325 				 */
14326 				cmn_err(CE_WARN, "failed to create "
14327 				    "anonymous state");
14328 				dtrace_dof_destroy(dof);
14329 				break;
14330 			}
14331 		}
14332 
14333 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14334 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
14335 
14336 		if (rv == 0)
14337 			rv = dtrace_dof_options(dof, state);
14338 
14339 		dtrace_err_verbose = 0;
14340 		dtrace_dof_destroy(dof);
14341 
14342 		if (rv != 0) {
14343 			/*
14344 			 * This is malformed DOF; chuck any anonymous state
14345 			 * that we created.
14346 			 */
14347 			ASSERT(dtrace_anon.dta_enabling == NULL);
14348 			dtrace_state_destroy(state);
14349 			dtrace_anon.dta_state = NULL;
14350 			break;
14351 		}
14352 
14353 		ASSERT(dtrace_anon.dta_enabling != NULL);
14354 	}
14355 
14356 	if (dtrace_anon.dta_enabling != NULL) {
14357 		int rval;
14358 
14359 		/*
14360 		 * dtrace_enabling_retain() can only fail because we are
14361 		 * trying to retain more enablings than are allowed -- but
14362 		 * we only have one anonymous enabling, and we are guaranteed
14363 		 * to be allowed at least one retained enabling; we assert
14364 		 * that dtrace_enabling_retain() returns success.
14365 		 */
14366 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14367 		ASSERT(rval == 0);
14368 
14369 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
14370 	}
14371 }
14372 
14373 /*
14374  * DTrace Helper Functions
14375  */
14376 static void
14377 dtrace_helper_trace(dtrace_helper_action_t *helper,
14378     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14379 {
14380 	uint32_t size, next, nnext, i;
14381 	dtrace_helptrace_t *ent, *buffer;
14382 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14383 
14384 	if ((buffer = dtrace_helptrace_buffer) == NULL)
14385 		return;
14386 
14387 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14388 
14389 	/*
14390 	 * What would a tracing framework be without its own tracing
14391 	 * framework?  (Well, a hell of a lot simpler, for starters...)
14392 	 */
14393 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14394 	    sizeof (uint64_t) - sizeof (uint64_t);
14395 
14396 	/*
14397 	 * Iterate until we can allocate a slot in the trace buffer.
14398 	 */
14399 	do {
14400 		next = dtrace_helptrace_next;
14401 
14402 		if (next + size < dtrace_helptrace_bufsize) {
14403 			nnext = next + size;
14404 		} else {
14405 			nnext = size;
14406 		}
14407 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14408 
14409 	/*
14410 	 * We have our slot; fill it in.
14411 	 */
14412 	if (nnext == size) {
14413 		dtrace_helptrace_wrapped++;
14414 		next = 0;
14415 	}
14416 
14417 	ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
14418 	ent->dtht_helper = helper;
14419 	ent->dtht_where = where;
14420 	ent->dtht_nlocals = vstate->dtvs_nlocals;
14421 
14422 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14423 	    mstate->dtms_fltoffs : -1;
14424 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14425 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
14426 
14427 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
14428 		dtrace_statvar_t *svar;
14429 
14430 		if ((svar = vstate->dtvs_locals[i]) == NULL)
14431 			continue;
14432 
14433 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14434 		ent->dtht_locals[i] =
14435 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
14436 	}
14437 }
14438 
14439 static uint64_t
14440 dtrace_helper(int which, dtrace_mstate_t *mstate,
14441     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14442 {
14443 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14444 	uint64_t sarg0 = mstate->dtms_arg[0];
14445 	uint64_t sarg1 = mstate->dtms_arg[1];
14446 	uint64_t rval;
14447 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14448 	dtrace_helper_action_t *helper;
14449 	dtrace_vstate_t *vstate;
14450 	dtrace_difo_t *pred;
14451 	int i, trace = dtrace_helptrace_buffer != NULL;
14452 
14453 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14454 
14455 	if (helpers == NULL)
14456 		return (0);
14457 
14458 	if ((helper = helpers->dthps_actions[which]) == NULL)
14459 		return (0);
14460 
14461 	vstate = &helpers->dthps_vstate;
14462 	mstate->dtms_arg[0] = arg0;
14463 	mstate->dtms_arg[1] = arg1;
14464 
14465 	/*
14466 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
14467 	 * we'll call the corresponding actions.  Note that the below calls
14468 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
14469 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
14470 	 * the stored DIF offset with its own (which is the desired behavior).
14471 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14472 	 * from machine state; this is okay, too.
14473 	 */
14474 	for (; helper != NULL; helper = helper->dtha_next) {
14475 		if ((pred = helper->dtha_predicate) != NULL) {
14476 			if (trace)
14477 				dtrace_helper_trace(helper, mstate, vstate, 0);
14478 
14479 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14480 				goto next;
14481 
14482 			if (*flags & CPU_DTRACE_FAULT)
14483 				goto err;
14484 		}
14485 
14486 		for (i = 0; i < helper->dtha_nactions; i++) {
14487 			if (trace)
14488 				dtrace_helper_trace(helper,
14489 				    mstate, vstate, i + 1);
14490 
14491 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
14492 			    mstate, vstate, state);
14493 
14494 			if (*flags & CPU_DTRACE_FAULT)
14495 				goto err;
14496 		}
14497 
14498 next:
14499 		if (trace)
14500 			dtrace_helper_trace(helper, mstate, vstate,
14501 			    DTRACE_HELPTRACE_NEXT);
14502 	}
14503 
14504 	if (trace)
14505 		dtrace_helper_trace(helper, mstate, vstate,
14506 		    DTRACE_HELPTRACE_DONE);
14507 
14508 	/*
14509 	 * Restore the arg0 that we saved upon entry.
14510 	 */
14511 	mstate->dtms_arg[0] = sarg0;
14512 	mstate->dtms_arg[1] = sarg1;
14513 
14514 	return (rval);
14515 
14516 err:
14517 	if (trace)
14518 		dtrace_helper_trace(helper, mstate, vstate,
14519 		    DTRACE_HELPTRACE_ERR);
14520 
14521 	/*
14522 	 * Restore the arg0 that we saved upon entry.
14523 	 */
14524 	mstate->dtms_arg[0] = sarg0;
14525 	mstate->dtms_arg[1] = sarg1;
14526 
14527 	return (NULL);
14528 }
14529 
14530 static void
14531 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14532     dtrace_vstate_t *vstate)
14533 {
14534 	int i;
14535 
14536 	if (helper->dtha_predicate != NULL)
14537 		dtrace_difo_release(helper->dtha_predicate, vstate);
14538 
14539 	for (i = 0; i < helper->dtha_nactions; i++) {
14540 		ASSERT(helper->dtha_actions[i] != NULL);
14541 		dtrace_difo_release(helper->dtha_actions[i], vstate);
14542 	}
14543 
14544 	kmem_free(helper->dtha_actions,
14545 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
14546 	kmem_free(helper, sizeof (dtrace_helper_action_t));
14547 }
14548 
14549 static int
14550 dtrace_helper_destroygen(int gen)
14551 {
14552 	proc_t *p = curproc;
14553 	dtrace_helpers_t *help = p->p_dtrace_helpers;
14554 	dtrace_vstate_t *vstate;
14555 	int i;
14556 
14557 	ASSERT(MUTEX_HELD(&dtrace_lock));
14558 
14559 	if (help == NULL || gen > help->dthps_generation)
14560 		return (EINVAL);
14561 
14562 	vstate = &help->dthps_vstate;
14563 
14564 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14565 		dtrace_helper_action_t *last = NULL, *h, *next;
14566 
14567 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
14568 			next = h->dtha_next;
14569 
14570 			if (h->dtha_generation == gen) {
14571 				if (last != NULL) {
14572 					last->dtha_next = next;
14573 				} else {
14574 					help->dthps_actions[i] = next;
14575 				}
14576 
14577 				dtrace_helper_action_destroy(h, vstate);
14578 			} else {
14579 				last = h;
14580 			}
14581 		}
14582 	}
14583 
14584 	/*
14585 	 * Interate until we've cleared out all helper providers with the
14586 	 * given generation number.
14587 	 */
14588 	for (;;) {
14589 		dtrace_helper_provider_t *prov;
14590 
14591 		/*
14592 		 * Look for a helper provider with the right generation. We
14593 		 * have to start back at the beginning of the list each time
14594 		 * because we drop dtrace_lock. It's unlikely that we'll make
14595 		 * more than two passes.
14596 		 */
14597 		for (i = 0; i < help->dthps_nprovs; i++) {
14598 			prov = help->dthps_provs[i];
14599 
14600 			if (prov->dthp_generation == gen)
14601 				break;
14602 		}
14603 
14604 		/*
14605 		 * If there were no matches, we're done.
14606 		 */
14607 		if (i == help->dthps_nprovs)
14608 			break;
14609 
14610 		/*
14611 		 * Move the last helper provider into this slot.
14612 		 */
14613 		help->dthps_nprovs--;
14614 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14615 		help->dthps_provs[help->dthps_nprovs] = NULL;
14616 
14617 		mutex_exit(&dtrace_lock);
14618 
14619 		/*
14620 		 * If we have a meta provider, remove this helper provider.
14621 		 */
14622 		mutex_enter(&dtrace_meta_lock);
14623 		if (dtrace_meta_pid != NULL) {
14624 			ASSERT(dtrace_deferred_pid == NULL);
14625 			dtrace_helper_provider_remove(&prov->dthp_prov,
14626 			    p->p_pid);
14627 		}
14628 		mutex_exit(&dtrace_meta_lock);
14629 
14630 		dtrace_helper_provider_destroy(prov);
14631 
14632 		mutex_enter(&dtrace_lock);
14633 	}
14634 
14635 	return (0);
14636 }
14637 
14638 static int
14639 dtrace_helper_validate(dtrace_helper_action_t *helper)
14640 {
14641 	int err = 0, i;
14642 	dtrace_difo_t *dp;
14643 
14644 	if ((dp = helper->dtha_predicate) != NULL)
14645 		err += dtrace_difo_validate_helper(dp);
14646 
14647 	for (i = 0; i < helper->dtha_nactions; i++)
14648 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14649 
14650 	return (err == 0);
14651 }
14652 
14653 static int
14654 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14655 {
14656 	dtrace_helpers_t *help;
14657 	dtrace_helper_action_t *helper, *last;
14658 	dtrace_actdesc_t *act;
14659 	dtrace_vstate_t *vstate;
14660 	dtrace_predicate_t *pred;
14661 	int count = 0, nactions = 0, i;
14662 
14663 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14664 		return (EINVAL);
14665 
14666 	help = curproc->p_dtrace_helpers;
14667 	last = help->dthps_actions[which];
14668 	vstate = &help->dthps_vstate;
14669 
14670 	for (count = 0; last != NULL; last = last->dtha_next) {
14671 		count++;
14672 		if (last->dtha_next == NULL)
14673 			break;
14674 	}
14675 
14676 	/*
14677 	 * If we already have dtrace_helper_actions_max helper actions for this
14678 	 * helper action type, we'll refuse to add a new one.
14679 	 */
14680 	if (count >= dtrace_helper_actions_max)
14681 		return (ENOSPC);
14682 
14683 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
14684 	helper->dtha_generation = help->dthps_generation;
14685 
14686 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
14687 		ASSERT(pred->dtp_difo != NULL);
14688 		dtrace_difo_hold(pred->dtp_difo);
14689 		helper->dtha_predicate = pred->dtp_difo;
14690 	}
14691 
14692 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
14693 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
14694 			goto err;
14695 
14696 		if (act->dtad_difo == NULL)
14697 			goto err;
14698 
14699 		nactions++;
14700 	}
14701 
14702 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
14703 	    (helper->dtha_nactions = nactions), KM_SLEEP);
14704 
14705 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
14706 		dtrace_difo_hold(act->dtad_difo);
14707 		helper->dtha_actions[i++] = act->dtad_difo;
14708 	}
14709 
14710 	if (!dtrace_helper_validate(helper))
14711 		goto err;
14712 
14713 	if (last == NULL) {
14714 		help->dthps_actions[which] = helper;
14715 	} else {
14716 		last->dtha_next = helper;
14717 	}
14718 
14719 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
14720 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
14721 		dtrace_helptrace_next = 0;
14722 	}
14723 
14724 	return (0);
14725 err:
14726 	dtrace_helper_action_destroy(helper, vstate);
14727 	return (EINVAL);
14728 }
14729 
14730 static void
14731 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
14732     dof_helper_t *dofhp)
14733 {
14734 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
14735 
14736 	mutex_enter(&dtrace_meta_lock);
14737 	mutex_enter(&dtrace_lock);
14738 
14739 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
14740 		/*
14741 		 * If the dtrace module is loaded but not attached, or if
14742 		 * there aren't isn't a meta provider registered to deal with
14743 		 * these provider descriptions, we need to postpone creating
14744 		 * the actual providers until later.
14745 		 */
14746 
14747 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
14748 		    dtrace_deferred_pid != help) {
14749 			help->dthps_deferred = 1;
14750 			help->dthps_pid = p->p_pid;
14751 			help->dthps_next = dtrace_deferred_pid;
14752 			help->dthps_prev = NULL;
14753 			if (dtrace_deferred_pid != NULL)
14754 				dtrace_deferred_pid->dthps_prev = help;
14755 			dtrace_deferred_pid = help;
14756 		}
14757 
14758 		mutex_exit(&dtrace_lock);
14759 
14760 	} else if (dofhp != NULL) {
14761 		/*
14762 		 * If the dtrace module is loaded and we have a particular
14763 		 * helper provider description, pass that off to the
14764 		 * meta provider.
14765 		 */
14766 
14767 		mutex_exit(&dtrace_lock);
14768 
14769 		dtrace_helper_provide(dofhp, p->p_pid);
14770 
14771 	} else {
14772 		/*
14773 		 * Otherwise, just pass all the helper provider descriptions
14774 		 * off to the meta provider.
14775 		 */
14776 
14777 		int i;
14778 		mutex_exit(&dtrace_lock);
14779 
14780 		for (i = 0; i < help->dthps_nprovs; i++) {
14781 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
14782 			    p->p_pid);
14783 		}
14784 	}
14785 
14786 	mutex_exit(&dtrace_meta_lock);
14787 }
14788 
14789 static int
14790 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
14791 {
14792 	dtrace_helpers_t *help;
14793 	dtrace_helper_provider_t *hprov, **tmp_provs;
14794 	uint_t tmp_maxprovs, i;
14795 
14796 	ASSERT(MUTEX_HELD(&dtrace_lock));
14797 
14798 	help = curproc->p_dtrace_helpers;
14799 	ASSERT(help != NULL);
14800 
14801 	/*
14802 	 * If we already have dtrace_helper_providers_max helper providers,
14803 	 * we're refuse to add a new one.
14804 	 */
14805 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
14806 		return (ENOSPC);
14807 
14808 	/*
14809 	 * Check to make sure this isn't a duplicate.
14810 	 */
14811 	for (i = 0; i < help->dthps_nprovs; i++) {
14812 		if (dofhp->dofhp_addr ==
14813 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
14814 			return (EALREADY);
14815 	}
14816 
14817 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
14818 	hprov->dthp_prov = *dofhp;
14819 	hprov->dthp_ref = 1;
14820 	hprov->dthp_generation = gen;
14821 
14822 	/*
14823 	 * Allocate a bigger table for helper providers if it's already full.
14824 	 */
14825 	if (help->dthps_maxprovs == help->dthps_nprovs) {
14826 		tmp_maxprovs = help->dthps_maxprovs;
14827 		tmp_provs = help->dthps_provs;
14828 
14829 		if (help->dthps_maxprovs == 0)
14830 			help->dthps_maxprovs = 2;
14831 		else
14832 			help->dthps_maxprovs *= 2;
14833 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
14834 			help->dthps_maxprovs = dtrace_helper_providers_max;
14835 
14836 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
14837 
14838 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
14839 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14840 
14841 		if (tmp_provs != NULL) {
14842 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
14843 			    sizeof (dtrace_helper_provider_t *));
14844 			kmem_free(tmp_provs, tmp_maxprovs *
14845 			    sizeof (dtrace_helper_provider_t *));
14846 		}
14847 	}
14848 
14849 	help->dthps_provs[help->dthps_nprovs] = hprov;
14850 	help->dthps_nprovs++;
14851 
14852 	return (0);
14853 }
14854 
14855 static void
14856 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
14857 {
14858 	mutex_enter(&dtrace_lock);
14859 
14860 	if (--hprov->dthp_ref == 0) {
14861 		dof_hdr_t *dof;
14862 		mutex_exit(&dtrace_lock);
14863 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
14864 		dtrace_dof_destroy(dof);
14865 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
14866 	} else {
14867 		mutex_exit(&dtrace_lock);
14868 	}
14869 }
14870 
14871 static int
14872 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
14873 {
14874 	uintptr_t daddr = (uintptr_t)dof;
14875 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
14876 	dof_provider_t *provider;
14877 	dof_probe_t *probe;
14878 	uint8_t *arg;
14879 	char *strtab, *typestr;
14880 	dof_stridx_t typeidx;
14881 	size_t typesz;
14882 	uint_t nprobes, j, k;
14883 
14884 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
14885 
14886 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
14887 		dtrace_dof_error(dof, "misaligned section offset");
14888 		return (-1);
14889 	}
14890 
14891 	/*
14892 	 * The section needs to be large enough to contain the DOF provider
14893 	 * structure appropriate for the given version.
14894 	 */
14895 	if (sec->dofs_size <
14896 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
14897 	    offsetof(dof_provider_t, dofpv_prenoffs) :
14898 	    sizeof (dof_provider_t))) {
14899 		dtrace_dof_error(dof, "provider section too small");
14900 		return (-1);
14901 	}
14902 
14903 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14904 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14905 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14906 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14907 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14908 
14909 	if (str_sec == NULL || prb_sec == NULL ||
14910 	    arg_sec == NULL || off_sec == NULL)
14911 		return (-1);
14912 
14913 	enoff_sec = NULL;
14914 
14915 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14916 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
14917 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14918 	    provider->dofpv_prenoffs)) == NULL)
14919 		return (-1);
14920 
14921 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14922 
14923 	if (provider->dofpv_name >= str_sec->dofs_size ||
14924 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14925 		dtrace_dof_error(dof, "invalid provider name");
14926 		return (-1);
14927 	}
14928 
14929 	if (prb_sec->dofs_entsize == 0 ||
14930 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
14931 		dtrace_dof_error(dof, "invalid entry size");
14932 		return (-1);
14933 	}
14934 
14935 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14936 		dtrace_dof_error(dof, "misaligned entry size");
14937 		return (-1);
14938 	}
14939 
14940 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14941 		dtrace_dof_error(dof, "invalid entry size");
14942 		return (-1);
14943 	}
14944 
14945 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14946 		dtrace_dof_error(dof, "misaligned section offset");
14947 		return (-1);
14948 	}
14949 
14950 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14951 		dtrace_dof_error(dof, "invalid entry size");
14952 		return (-1);
14953 	}
14954 
14955 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14956 
14957 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14958 
14959 	/*
14960 	 * Take a pass through the probes to check for errors.
14961 	 */
14962 	for (j = 0; j < nprobes; j++) {
14963 		probe = (dof_probe_t *)(uintptr_t)(daddr +
14964 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14965 
14966 		if (probe->dofpr_func >= str_sec->dofs_size) {
14967 			dtrace_dof_error(dof, "invalid function name");
14968 			return (-1);
14969 		}
14970 
14971 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14972 			dtrace_dof_error(dof, "function name too long");
14973 			return (-1);
14974 		}
14975 
14976 		if (probe->dofpr_name >= str_sec->dofs_size ||
14977 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14978 			dtrace_dof_error(dof, "invalid probe name");
14979 			return (-1);
14980 		}
14981 
14982 		/*
14983 		 * The offset count must not wrap the index, and the offsets
14984 		 * must also not overflow the section's data.
14985 		 */
14986 		if (probe->dofpr_offidx + probe->dofpr_noffs <
14987 		    probe->dofpr_offidx ||
14988 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
14989 		    off_sec->dofs_entsize > off_sec->dofs_size) {
14990 			dtrace_dof_error(dof, "invalid probe offset");
14991 			return (-1);
14992 		}
14993 
14994 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14995 			/*
14996 			 * If there's no is-enabled offset section, make sure
14997 			 * there aren't any is-enabled offsets. Otherwise
14998 			 * perform the same checks as for probe offsets
14999 			 * (immediately above).
15000 			 */
15001 			if (enoff_sec == NULL) {
15002 				if (probe->dofpr_enoffidx != 0 ||
15003 				    probe->dofpr_nenoffs != 0) {
15004 					dtrace_dof_error(dof, "is-enabled "
15005 					    "offsets with null section");
15006 					return (-1);
15007 				}
15008 			} else if (probe->dofpr_enoffidx +
15009 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15010 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15011 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15012 				dtrace_dof_error(dof, "invalid is-enabled "
15013 				    "offset");
15014 				return (-1);
15015 			}
15016 
15017 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15018 				dtrace_dof_error(dof, "zero probe and "
15019 				    "is-enabled offsets");
15020 				return (-1);
15021 			}
15022 		} else if (probe->dofpr_noffs == 0) {
15023 			dtrace_dof_error(dof, "zero probe offsets");
15024 			return (-1);
15025 		}
15026 
15027 		if (probe->dofpr_argidx + probe->dofpr_xargc <
15028 		    probe->dofpr_argidx ||
15029 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
15030 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
15031 			dtrace_dof_error(dof, "invalid args");
15032 			return (-1);
15033 		}
15034 
15035 		typeidx = probe->dofpr_nargv;
15036 		typestr = strtab + probe->dofpr_nargv;
15037 		for (k = 0; k < probe->dofpr_nargc; k++) {
15038 			if (typeidx >= str_sec->dofs_size) {
15039 				dtrace_dof_error(dof, "bad "
15040 				    "native argument type");
15041 				return (-1);
15042 			}
15043 
15044 			typesz = strlen(typestr) + 1;
15045 			if (typesz > DTRACE_ARGTYPELEN) {
15046 				dtrace_dof_error(dof, "native "
15047 				    "argument type too long");
15048 				return (-1);
15049 			}
15050 			typeidx += typesz;
15051 			typestr += typesz;
15052 		}
15053 
15054 		typeidx = probe->dofpr_xargv;
15055 		typestr = strtab + probe->dofpr_xargv;
15056 		for (k = 0; k < probe->dofpr_xargc; k++) {
15057 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15058 				dtrace_dof_error(dof, "bad "
15059 				    "native argument index");
15060 				return (-1);
15061 			}
15062 
15063 			if (typeidx >= str_sec->dofs_size) {
15064 				dtrace_dof_error(dof, "bad "
15065 				    "translated argument type");
15066 				return (-1);
15067 			}
15068 
15069 			typesz = strlen(typestr) + 1;
15070 			if (typesz > DTRACE_ARGTYPELEN) {
15071 				dtrace_dof_error(dof, "translated argument "
15072 				    "type too long");
15073 				return (-1);
15074 			}
15075 
15076 			typeidx += typesz;
15077 			typestr += typesz;
15078 		}
15079 	}
15080 
15081 	return (0);
15082 }
15083 
15084 static int
15085 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
15086 {
15087 	dtrace_helpers_t *help;
15088 	dtrace_vstate_t *vstate;
15089 	dtrace_enabling_t *enab = NULL;
15090 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15091 	uintptr_t daddr = (uintptr_t)dof;
15092 
15093 	ASSERT(MUTEX_HELD(&dtrace_lock));
15094 
15095 	if ((help = curproc->p_dtrace_helpers) == NULL)
15096 		help = dtrace_helpers_create(curproc);
15097 
15098 	vstate = &help->dthps_vstate;
15099 
15100 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15101 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15102 		dtrace_dof_destroy(dof);
15103 		return (rv);
15104 	}
15105 
15106 	/*
15107 	 * Look for helper providers and validate their descriptions.
15108 	 */
15109 	if (dhp != NULL) {
15110 		for (i = 0; i < dof->dofh_secnum; i++) {
15111 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15112 			    dof->dofh_secoff + i * dof->dofh_secsize);
15113 
15114 			if (sec->dofs_type != DOF_SECT_PROVIDER)
15115 				continue;
15116 
15117 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
15118 				dtrace_enabling_destroy(enab);
15119 				dtrace_dof_destroy(dof);
15120 				return (-1);
15121 			}
15122 
15123 			nprovs++;
15124 		}
15125 	}
15126 
15127 	/*
15128 	 * Now we need to walk through the ECB descriptions in the enabling.
15129 	 */
15130 	for (i = 0; i < enab->dten_ndesc; i++) {
15131 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15132 		dtrace_probedesc_t *desc = &ep->dted_probe;
15133 
15134 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
15135 			continue;
15136 
15137 		if (strcmp(desc->dtpd_mod, "helper") != 0)
15138 			continue;
15139 
15140 		if (strcmp(desc->dtpd_func, "ustack") != 0)
15141 			continue;
15142 
15143 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
15144 		    ep)) != 0) {
15145 			/*
15146 			 * Adding this helper action failed -- we are now going
15147 			 * to rip out the entire generation and return failure.
15148 			 */
15149 			(void) dtrace_helper_destroygen(help->dthps_generation);
15150 			dtrace_enabling_destroy(enab);
15151 			dtrace_dof_destroy(dof);
15152 			return (-1);
15153 		}
15154 
15155 		nhelpers++;
15156 	}
15157 
15158 	if (nhelpers < enab->dten_ndesc)
15159 		dtrace_dof_error(dof, "unmatched helpers");
15160 
15161 	gen = help->dthps_generation++;
15162 	dtrace_enabling_destroy(enab);
15163 
15164 	if (dhp != NULL && nprovs > 0) {
15165 		/*
15166 		 * Now that this is in-kernel, we change the sense of the
15167 		 * members:  dofhp_dof denotes the in-kernel copy of the DOF
15168 		 * and dofhp_addr denotes the address at user-level.
15169 		 */
15170 		dhp->dofhp_addr = dhp->dofhp_dof;
15171 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15172 
15173 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
15174 			mutex_exit(&dtrace_lock);
15175 			dtrace_helper_provider_register(curproc, help, dhp);
15176 			mutex_enter(&dtrace_lock);
15177 
15178 			destroy = 0;
15179 		}
15180 	}
15181 
15182 	if (destroy)
15183 		dtrace_dof_destroy(dof);
15184 
15185 	return (gen);
15186 }
15187 
15188 static dtrace_helpers_t *
15189 dtrace_helpers_create(proc_t *p)
15190 {
15191 	dtrace_helpers_t *help;
15192 
15193 	ASSERT(MUTEX_HELD(&dtrace_lock));
15194 	ASSERT(p->p_dtrace_helpers == NULL);
15195 
15196 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15197 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15198 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15199 
15200 	p->p_dtrace_helpers = help;
15201 	dtrace_helpers++;
15202 
15203 	return (help);
15204 }
15205 
15206 static void
15207 dtrace_helpers_destroy(void)
15208 {
15209 	dtrace_helpers_t *help;
15210 	dtrace_vstate_t *vstate;
15211 	proc_t *p = curproc;
15212 	int i;
15213 
15214 	mutex_enter(&dtrace_lock);
15215 
15216 	ASSERT(p->p_dtrace_helpers != NULL);
15217 	ASSERT(dtrace_helpers > 0);
15218 
15219 	help = p->p_dtrace_helpers;
15220 	vstate = &help->dthps_vstate;
15221 
15222 	/*
15223 	 * We're now going to lose the help from this process.
15224 	 */
15225 	p->p_dtrace_helpers = NULL;
15226 	dtrace_sync();
15227 
15228 	/*
15229 	 * Destory the helper actions.
15230 	 */
15231 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15232 		dtrace_helper_action_t *h, *next;
15233 
15234 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15235 			next = h->dtha_next;
15236 			dtrace_helper_action_destroy(h, vstate);
15237 			h = next;
15238 		}
15239 	}
15240 
15241 	mutex_exit(&dtrace_lock);
15242 
15243 	/*
15244 	 * Destroy the helper providers.
15245 	 */
15246 	if (help->dthps_maxprovs > 0) {
15247 		mutex_enter(&dtrace_meta_lock);
15248 		if (dtrace_meta_pid != NULL) {
15249 			ASSERT(dtrace_deferred_pid == NULL);
15250 
15251 			for (i = 0; i < help->dthps_nprovs; i++) {
15252 				dtrace_helper_provider_remove(
15253 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
15254 			}
15255 		} else {
15256 			mutex_enter(&dtrace_lock);
15257 			ASSERT(help->dthps_deferred == 0 ||
15258 			    help->dthps_next != NULL ||
15259 			    help->dthps_prev != NULL ||
15260 			    help == dtrace_deferred_pid);
15261 
15262 			/*
15263 			 * Remove the helper from the deferred list.
15264 			 */
15265 			if (help->dthps_next != NULL)
15266 				help->dthps_next->dthps_prev = help->dthps_prev;
15267 			if (help->dthps_prev != NULL)
15268 				help->dthps_prev->dthps_next = help->dthps_next;
15269 			if (dtrace_deferred_pid == help) {
15270 				dtrace_deferred_pid = help->dthps_next;
15271 				ASSERT(help->dthps_prev == NULL);
15272 			}
15273 
15274 			mutex_exit(&dtrace_lock);
15275 		}
15276 
15277 		mutex_exit(&dtrace_meta_lock);
15278 
15279 		for (i = 0; i < help->dthps_nprovs; i++) {
15280 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
15281 		}
15282 
15283 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
15284 		    sizeof (dtrace_helper_provider_t *));
15285 	}
15286 
15287 	mutex_enter(&dtrace_lock);
15288 
15289 	dtrace_vstate_fini(&help->dthps_vstate);
15290 	kmem_free(help->dthps_actions,
15291 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15292 	kmem_free(help, sizeof (dtrace_helpers_t));
15293 
15294 	--dtrace_helpers;
15295 	mutex_exit(&dtrace_lock);
15296 }
15297 
15298 static void
15299 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15300 {
15301 	dtrace_helpers_t *help, *newhelp;
15302 	dtrace_helper_action_t *helper, *new, *last;
15303 	dtrace_difo_t *dp;
15304 	dtrace_vstate_t *vstate;
15305 	int i, j, sz, hasprovs = 0;
15306 
15307 	mutex_enter(&dtrace_lock);
15308 	ASSERT(from->p_dtrace_helpers != NULL);
15309 	ASSERT(dtrace_helpers > 0);
15310 
15311 	help = from->p_dtrace_helpers;
15312 	newhelp = dtrace_helpers_create(to);
15313 	ASSERT(to->p_dtrace_helpers != NULL);
15314 
15315 	newhelp->dthps_generation = help->dthps_generation;
15316 	vstate = &newhelp->dthps_vstate;
15317 
15318 	/*
15319 	 * Duplicate the helper actions.
15320 	 */
15321 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15322 		if ((helper = help->dthps_actions[i]) == NULL)
15323 			continue;
15324 
15325 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15326 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15327 			    KM_SLEEP);
15328 			new->dtha_generation = helper->dtha_generation;
15329 
15330 			if ((dp = helper->dtha_predicate) != NULL) {
15331 				dp = dtrace_difo_duplicate(dp, vstate);
15332 				new->dtha_predicate = dp;
15333 			}
15334 
15335 			new->dtha_nactions = helper->dtha_nactions;
15336 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15337 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15338 
15339 			for (j = 0; j < new->dtha_nactions; j++) {
15340 				dtrace_difo_t *dp = helper->dtha_actions[j];
15341 
15342 				ASSERT(dp != NULL);
15343 				dp = dtrace_difo_duplicate(dp, vstate);
15344 				new->dtha_actions[j] = dp;
15345 			}
15346 
15347 			if (last != NULL) {
15348 				last->dtha_next = new;
15349 			} else {
15350 				newhelp->dthps_actions[i] = new;
15351 			}
15352 
15353 			last = new;
15354 		}
15355 	}
15356 
15357 	/*
15358 	 * Duplicate the helper providers and register them with the
15359 	 * DTrace framework.
15360 	 */
15361 	if (help->dthps_nprovs > 0) {
15362 		newhelp->dthps_nprovs = help->dthps_nprovs;
15363 		newhelp->dthps_maxprovs = help->dthps_nprovs;
15364 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15365 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15366 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
15367 			newhelp->dthps_provs[i] = help->dthps_provs[i];
15368 			newhelp->dthps_provs[i]->dthp_ref++;
15369 		}
15370 
15371 		hasprovs = 1;
15372 	}
15373 
15374 	mutex_exit(&dtrace_lock);
15375 
15376 	if (hasprovs)
15377 		dtrace_helper_provider_register(to, newhelp, NULL);
15378 }
15379 
15380 /*
15381  * DTrace Hook Functions
15382  */
15383 static void
15384 dtrace_module_loaded(struct modctl *ctl)
15385 {
15386 	dtrace_provider_t *prv;
15387 
15388 	mutex_enter(&dtrace_provider_lock);
15389 	mutex_enter(&mod_lock);
15390 
15391 	ASSERT(ctl->mod_busy);
15392 
15393 	/*
15394 	 * We're going to call each providers per-module provide operation
15395 	 * specifying only this module.
15396 	 */
15397 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15398 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15399 
15400 	mutex_exit(&mod_lock);
15401 	mutex_exit(&dtrace_provider_lock);
15402 
15403 	/*
15404 	 * If we have any retained enablings, we need to match against them.
15405 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
15406 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15407 	 * module.  (In particular, this happens when loading scheduling
15408 	 * classes.)  So if we have any retained enablings, we need to dispatch
15409 	 * our task queue to do the match for us.
15410 	 */
15411 	mutex_enter(&dtrace_lock);
15412 
15413 	if (dtrace_retained == NULL) {
15414 		mutex_exit(&dtrace_lock);
15415 		return;
15416 	}
15417 
15418 	(void) taskq_dispatch(dtrace_taskq,
15419 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15420 
15421 	mutex_exit(&dtrace_lock);
15422 
15423 	/*
15424 	 * And now, for a little heuristic sleaze:  in general, we want to
15425 	 * match modules as soon as they load.  However, we cannot guarantee
15426 	 * this, because it would lead us to the lock ordering violation
15427 	 * outlined above.  The common case, of course, is that cpu_lock is
15428 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
15429 	 * long enough for the task queue to do its work.  If it's not, it's
15430 	 * not a serious problem -- it just means that the module that we
15431 	 * just loaded may not be immediately instrumentable.
15432 	 */
15433 	delay(1);
15434 }
15435 
15436 static void
15437 dtrace_module_unloaded(struct modctl *ctl)
15438 {
15439 	dtrace_probe_t template, *probe, *first, *next;
15440 	dtrace_provider_t *prov;
15441 
15442 	template.dtpr_mod = ctl->mod_modname;
15443 
15444 	mutex_enter(&dtrace_provider_lock);
15445 	mutex_enter(&mod_lock);
15446 	mutex_enter(&dtrace_lock);
15447 
15448 	if (dtrace_bymod == NULL) {
15449 		/*
15450 		 * The DTrace module is loaded (obviously) but not attached;
15451 		 * we don't have any work to do.
15452 		 */
15453 		mutex_exit(&dtrace_provider_lock);
15454 		mutex_exit(&mod_lock);
15455 		mutex_exit(&dtrace_lock);
15456 		return;
15457 	}
15458 
15459 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15460 	    probe != NULL; probe = probe->dtpr_nextmod) {
15461 		if (probe->dtpr_ecb != NULL) {
15462 			mutex_exit(&dtrace_provider_lock);
15463 			mutex_exit(&mod_lock);
15464 			mutex_exit(&dtrace_lock);
15465 
15466 			/*
15467 			 * This shouldn't _actually_ be possible -- we're
15468 			 * unloading a module that has an enabled probe in it.
15469 			 * (It's normally up to the provider to make sure that
15470 			 * this can't happen.)  However, because dtps_enable()
15471 			 * doesn't have a failure mode, there can be an
15472 			 * enable/unload race.  Upshot:  we don't want to
15473 			 * assert, but we're not going to disable the
15474 			 * probe, either.
15475 			 */
15476 			if (dtrace_err_verbose) {
15477 				cmn_err(CE_WARN, "unloaded module '%s' had "
15478 				    "enabled probes", ctl->mod_modname);
15479 			}
15480 
15481 			return;
15482 		}
15483 	}
15484 
15485 	probe = first;
15486 
15487 	for (first = NULL; probe != NULL; probe = next) {
15488 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15489 
15490 		dtrace_probes[probe->dtpr_id - 1] = NULL;
15491 
15492 		next = probe->dtpr_nextmod;
15493 		dtrace_hash_remove(dtrace_bymod, probe);
15494 		dtrace_hash_remove(dtrace_byfunc, probe);
15495 		dtrace_hash_remove(dtrace_byname, probe);
15496 
15497 		if (first == NULL) {
15498 			first = probe;
15499 			probe->dtpr_nextmod = NULL;
15500 		} else {
15501 			probe->dtpr_nextmod = first;
15502 			first = probe;
15503 		}
15504 	}
15505 
15506 	/*
15507 	 * We've removed all of the module's probes from the hash chains and
15508 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
15509 	 * everyone has cleared out from any probe array processing.
15510 	 */
15511 	dtrace_sync();
15512 
15513 	for (probe = first; probe != NULL; probe = first) {
15514 		first = probe->dtpr_nextmod;
15515 		prov = probe->dtpr_provider;
15516 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15517 		    probe->dtpr_arg);
15518 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15519 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15520 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15521 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15522 		kmem_free(probe, sizeof (dtrace_probe_t));
15523 	}
15524 
15525 	mutex_exit(&dtrace_lock);
15526 	mutex_exit(&mod_lock);
15527 	mutex_exit(&dtrace_provider_lock);
15528 }
15529 
15530 void
15531 dtrace_suspend(void)
15532 {
15533 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15534 }
15535 
15536 void
15537 dtrace_resume(void)
15538 {
15539 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15540 }
15541 
15542 static int
15543 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15544 {
15545 	ASSERT(MUTEX_HELD(&cpu_lock));
15546 	mutex_enter(&dtrace_lock);
15547 
15548 	switch (what) {
15549 	case CPU_CONFIG: {
15550 		dtrace_state_t *state;
15551 		dtrace_optval_t *opt, rs, c;
15552 
15553 		/*
15554 		 * For now, we only allocate a new buffer for anonymous state.
15555 		 */
15556 		if ((state = dtrace_anon.dta_state) == NULL)
15557 			break;
15558 
15559 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15560 			break;
15561 
15562 		opt = state->dts_options;
15563 		c = opt[DTRACEOPT_CPU];
15564 
15565 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15566 			break;
15567 
15568 		/*
15569 		 * Regardless of what the actual policy is, we're going to
15570 		 * temporarily set our resize policy to be manual.  We're
15571 		 * also going to temporarily set our CPU option to denote
15572 		 * the newly configured CPU.
15573 		 */
15574 		rs = opt[DTRACEOPT_BUFRESIZE];
15575 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15576 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15577 
15578 		(void) dtrace_state_buffers(state);
15579 
15580 		opt[DTRACEOPT_BUFRESIZE] = rs;
15581 		opt[DTRACEOPT_CPU] = c;
15582 
15583 		break;
15584 	}
15585 
15586 	case CPU_UNCONFIG:
15587 		/*
15588 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
15589 		 * buffer will be freed when the consumer exits.)
15590 		 */
15591 		break;
15592 
15593 	default:
15594 		break;
15595 	}
15596 
15597 	mutex_exit(&dtrace_lock);
15598 	return (0);
15599 }
15600 
15601 static void
15602 dtrace_cpu_setup_initial(processorid_t cpu)
15603 {
15604 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15605 }
15606 
15607 static void
15608 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15609 {
15610 	if (dtrace_toxranges >= dtrace_toxranges_max) {
15611 		int osize, nsize;
15612 		dtrace_toxrange_t *range;
15613 
15614 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15615 
15616 		if (osize == 0) {
15617 			ASSERT(dtrace_toxrange == NULL);
15618 			ASSERT(dtrace_toxranges_max == 0);
15619 			dtrace_toxranges_max = 1;
15620 		} else {
15621 			dtrace_toxranges_max <<= 1;
15622 		}
15623 
15624 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15625 		range = kmem_zalloc(nsize, KM_SLEEP);
15626 
15627 		if (dtrace_toxrange != NULL) {
15628 			ASSERT(osize != 0);
15629 			bcopy(dtrace_toxrange, range, osize);
15630 			kmem_free(dtrace_toxrange, osize);
15631 		}
15632 
15633 		dtrace_toxrange = range;
15634 	}
15635 
15636 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
15637 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
15638 
15639 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15640 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15641 	dtrace_toxranges++;
15642 }
15643 
15644 static void
15645 dtrace_getf_barrier()
15646 {
15647 	/*
15648 	 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
15649 	 * that contain calls to getf(), this routine will be called on every
15650 	 * closef() before either the underlying vnode is released or the
15651 	 * file_t itself is freed.  By the time we are here, it is essential
15652 	 * that the file_t can no longer be accessed from a call to getf()
15653 	 * in probe context -- that assures that a dtrace_sync() can be used
15654 	 * to clear out any enablings referring to the old structures.
15655 	 */
15656 	if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
15657 	    kcred->cr_zone->zone_dtrace_getf != 0)
15658 		dtrace_sync();
15659 }
15660 
15661 /*
15662  * DTrace Driver Cookbook Functions
15663  */
15664 /*ARGSUSED*/
15665 static int
15666 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
15667 {
15668 	dtrace_provider_id_t id;
15669 	dtrace_state_t *state = NULL;
15670 	dtrace_enabling_t *enab;
15671 
15672 	mutex_enter(&cpu_lock);
15673 	mutex_enter(&dtrace_provider_lock);
15674 	mutex_enter(&dtrace_lock);
15675 
15676 	if (ddi_soft_state_init(&dtrace_softstate,
15677 	    sizeof (dtrace_state_t), 0) != 0) {
15678 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
15679 		mutex_exit(&cpu_lock);
15680 		mutex_exit(&dtrace_provider_lock);
15681 		mutex_exit(&dtrace_lock);
15682 		return (DDI_FAILURE);
15683 	}
15684 
15685 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
15686 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
15687 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
15688 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
15689 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
15690 		ddi_remove_minor_node(devi, NULL);
15691 		ddi_soft_state_fini(&dtrace_softstate);
15692 		mutex_exit(&cpu_lock);
15693 		mutex_exit(&dtrace_provider_lock);
15694 		mutex_exit(&dtrace_lock);
15695 		return (DDI_FAILURE);
15696 	}
15697 
15698 	ddi_report_dev(devi);
15699 	dtrace_devi = devi;
15700 
15701 	dtrace_modload = dtrace_module_loaded;
15702 	dtrace_modunload = dtrace_module_unloaded;
15703 	dtrace_cpu_init = dtrace_cpu_setup_initial;
15704 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
15705 	dtrace_helpers_fork = dtrace_helpers_duplicate;
15706 	dtrace_cpustart_init = dtrace_suspend;
15707 	dtrace_cpustart_fini = dtrace_resume;
15708 	dtrace_debugger_init = dtrace_suspend;
15709 	dtrace_debugger_fini = dtrace_resume;
15710 
15711 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15712 
15713 	ASSERT(MUTEX_HELD(&cpu_lock));
15714 
15715 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
15716 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
15717 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
15718 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
15719 	    VM_SLEEP | VMC_IDENTIFIER);
15720 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
15721 	    1, INT_MAX, 0);
15722 
15723 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
15724 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
15725 	    NULL, NULL, NULL, NULL, NULL, 0);
15726 
15727 	ASSERT(MUTEX_HELD(&cpu_lock));
15728 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
15729 	    offsetof(dtrace_probe_t, dtpr_nextmod),
15730 	    offsetof(dtrace_probe_t, dtpr_prevmod));
15731 
15732 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
15733 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
15734 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
15735 
15736 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
15737 	    offsetof(dtrace_probe_t, dtpr_nextname),
15738 	    offsetof(dtrace_probe_t, dtpr_prevname));
15739 
15740 	if (dtrace_retain_max < 1) {
15741 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
15742 		    "setting to 1", dtrace_retain_max);
15743 		dtrace_retain_max = 1;
15744 	}
15745 
15746 	/*
15747 	 * Now discover our toxic ranges.
15748 	 */
15749 	dtrace_toxic_ranges(dtrace_toxrange_add);
15750 
15751 	/*
15752 	 * Before we register ourselves as a provider to our own framework,
15753 	 * we would like to assert that dtrace_provider is NULL -- but that's
15754 	 * not true if we were loaded as a dependency of a DTrace provider.
15755 	 * Once we've registered, we can assert that dtrace_provider is our
15756 	 * pseudo provider.
15757 	 */
15758 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
15759 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
15760 
15761 	ASSERT(dtrace_provider != NULL);
15762 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
15763 
15764 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
15765 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
15766 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
15767 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
15768 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
15769 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
15770 
15771 	dtrace_anon_property();
15772 	mutex_exit(&cpu_lock);
15773 
15774 	/*
15775 	 * If there are already providers, we must ask them to provide their
15776 	 * probes, and then match any anonymous enabling against them.  Note
15777 	 * that there should be no other retained enablings at this time:
15778 	 * the only retained enablings at this time should be the anonymous
15779 	 * enabling.
15780 	 */
15781 	if (dtrace_anon.dta_enabling != NULL) {
15782 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
15783 
15784 		dtrace_enabling_provide(NULL);
15785 		state = dtrace_anon.dta_state;
15786 
15787 		/*
15788 		 * We couldn't hold cpu_lock across the above call to
15789 		 * dtrace_enabling_provide(), but we must hold it to actually
15790 		 * enable the probes.  We have to drop all of our locks, pick
15791 		 * up cpu_lock, and regain our locks before matching the
15792 		 * retained anonymous enabling.
15793 		 */
15794 		mutex_exit(&dtrace_lock);
15795 		mutex_exit(&dtrace_provider_lock);
15796 
15797 		mutex_enter(&cpu_lock);
15798 		mutex_enter(&dtrace_provider_lock);
15799 		mutex_enter(&dtrace_lock);
15800 
15801 		if ((enab = dtrace_anon.dta_enabling) != NULL)
15802 			(void) dtrace_enabling_match(enab, NULL);
15803 
15804 		mutex_exit(&cpu_lock);
15805 	}
15806 
15807 	mutex_exit(&dtrace_lock);
15808 	mutex_exit(&dtrace_provider_lock);
15809 
15810 	if (state != NULL) {
15811 		/*
15812 		 * If we created any anonymous state, set it going now.
15813 		 */
15814 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
15815 	}
15816 
15817 	return (DDI_SUCCESS);
15818 }
15819 
15820 /*ARGSUSED*/
15821 static int
15822 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
15823 {
15824 	dtrace_state_t *state;
15825 	uint32_t priv;
15826 	uid_t uid;
15827 	zoneid_t zoneid;
15828 
15829 	if (getminor(*devp) == DTRACEMNRN_HELPER)
15830 		return (0);
15831 
15832 	/*
15833 	 * If this wasn't an open with the "helper" minor, then it must be
15834 	 * the "dtrace" minor.
15835 	 */
15836 	if (getminor(*devp) != DTRACEMNRN_DTRACE)
15837 		return (ENXIO);
15838 
15839 	/*
15840 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
15841 	 * caller lacks sufficient permission to do anything with DTrace.
15842 	 */
15843 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
15844 	if (priv == DTRACE_PRIV_NONE)
15845 		return (EACCES);
15846 
15847 	/*
15848 	 * Ask all providers to provide all their probes.
15849 	 */
15850 	mutex_enter(&dtrace_provider_lock);
15851 	dtrace_probe_provide(NULL, NULL);
15852 	mutex_exit(&dtrace_provider_lock);
15853 
15854 	mutex_enter(&cpu_lock);
15855 	mutex_enter(&dtrace_lock);
15856 	dtrace_opens++;
15857 	dtrace_membar_producer();
15858 
15859 	/*
15860 	 * If the kernel debugger is active (that is, if the kernel debugger
15861 	 * modified text in some way), we won't allow the open.
15862 	 */
15863 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
15864 		dtrace_opens--;
15865 		mutex_exit(&cpu_lock);
15866 		mutex_exit(&dtrace_lock);
15867 		return (EBUSY);
15868 	}
15869 
15870 	if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
15871 		/*
15872 		 * If DTrace helper tracing is enabled, we need to allocate the
15873 		 * trace buffer and initialize the values.
15874 		 */
15875 		dtrace_helptrace_buffer =
15876 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
15877 		dtrace_helptrace_next = 0;
15878 		dtrace_helptrace_wrapped = 0;
15879 		dtrace_helptrace_enable = 0;
15880 	}
15881 
15882 	state = dtrace_state_create(devp, cred_p);
15883 	mutex_exit(&cpu_lock);
15884 
15885 	if (state == NULL) {
15886 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15887 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15888 		mutex_exit(&dtrace_lock);
15889 		return (EAGAIN);
15890 	}
15891 
15892 	mutex_exit(&dtrace_lock);
15893 
15894 	return (0);
15895 }
15896 
15897 /*ARGSUSED*/
15898 static int
15899 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
15900 {
15901 	minor_t minor = getminor(dev);
15902 	dtrace_state_t *state;
15903 	dtrace_helptrace_t *buf = NULL;
15904 
15905 	if (minor == DTRACEMNRN_HELPER)
15906 		return (0);
15907 
15908 	state = ddi_get_soft_state(dtrace_softstate, minor);
15909 
15910 	mutex_enter(&cpu_lock);
15911 	mutex_enter(&dtrace_lock);
15912 
15913 	if (state->dts_anon) {
15914 		/*
15915 		 * There is anonymous state. Destroy that first.
15916 		 */
15917 		ASSERT(dtrace_anon.dta_state == NULL);
15918 		dtrace_state_destroy(state->dts_anon);
15919 	}
15920 
15921 	if (dtrace_helptrace_disable) {
15922 		/*
15923 		 * If we have been told to disable helper tracing, set the
15924 		 * buffer to NULL before calling into dtrace_state_destroy();
15925 		 * we take advantage of its dtrace_sync() to know that no
15926 		 * CPU is in probe context with enabled helper tracing
15927 		 * after it returns.
15928 		 */
15929 		buf = dtrace_helptrace_buffer;
15930 		dtrace_helptrace_buffer = NULL;
15931 	}
15932 
15933 	dtrace_state_destroy(state);
15934 	ASSERT(dtrace_opens > 0);
15935 
15936 	/*
15937 	 * Only relinquish control of the kernel debugger interface when there
15938 	 * are no consumers and no anonymous enablings.
15939 	 */
15940 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15941 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15942 
15943 	if (buf != NULL) {
15944 		kmem_free(buf, dtrace_helptrace_bufsize);
15945 		dtrace_helptrace_disable = 0;
15946 	}
15947 
15948 	mutex_exit(&dtrace_lock);
15949 	mutex_exit(&cpu_lock);
15950 
15951 	return (0);
15952 }
15953 
15954 /*ARGSUSED*/
15955 static int
15956 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
15957 {
15958 	int rval;
15959 	dof_helper_t help, *dhp = NULL;
15960 
15961 	switch (cmd) {
15962 	case DTRACEHIOC_ADDDOF:
15963 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
15964 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
15965 			return (EFAULT);
15966 		}
15967 
15968 		dhp = &help;
15969 		arg = (intptr_t)help.dofhp_dof;
15970 		/*FALLTHROUGH*/
15971 
15972 	case DTRACEHIOC_ADD: {
15973 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
15974 
15975 		if (dof == NULL)
15976 			return (rval);
15977 
15978 		mutex_enter(&dtrace_lock);
15979 
15980 		/*
15981 		 * dtrace_helper_slurp() takes responsibility for the dof --
15982 		 * it may free it now or it may save it and free it later.
15983 		 */
15984 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
15985 			*rv = rval;
15986 			rval = 0;
15987 		} else {
15988 			rval = EINVAL;
15989 		}
15990 
15991 		mutex_exit(&dtrace_lock);
15992 		return (rval);
15993 	}
15994 
15995 	case DTRACEHIOC_REMOVE: {
15996 		mutex_enter(&dtrace_lock);
15997 		rval = dtrace_helper_destroygen(arg);
15998 		mutex_exit(&dtrace_lock);
15999 
16000 		return (rval);
16001 	}
16002 
16003 	default:
16004 		break;
16005 	}
16006 
16007 	return (ENOTTY);
16008 }
16009 
16010 /*ARGSUSED*/
16011 static int
16012 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
16013 {
16014 	minor_t minor = getminor(dev);
16015 	dtrace_state_t *state;
16016 	int rval;
16017 
16018 	if (minor == DTRACEMNRN_HELPER)
16019 		return (dtrace_ioctl_helper(cmd, arg, rv));
16020 
16021 	state = ddi_get_soft_state(dtrace_softstate, minor);
16022 
16023 	if (state->dts_anon) {
16024 		ASSERT(dtrace_anon.dta_state == NULL);
16025 		state = state->dts_anon;
16026 	}
16027 
16028 	switch (cmd) {
16029 	case DTRACEIOC_PROVIDER: {
16030 		dtrace_providerdesc_t pvd;
16031 		dtrace_provider_t *pvp;
16032 
16033 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
16034 			return (EFAULT);
16035 
16036 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16037 		mutex_enter(&dtrace_provider_lock);
16038 
16039 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16040 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
16041 				break;
16042 		}
16043 
16044 		mutex_exit(&dtrace_provider_lock);
16045 
16046 		if (pvp == NULL)
16047 			return (ESRCH);
16048 
16049 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16050 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16051 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
16052 			return (EFAULT);
16053 
16054 		return (0);
16055 	}
16056 
16057 	case DTRACEIOC_EPROBE: {
16058 		dtrace_eprobedesc_t epdesc;
16059 		dtrace_ecb_t *ecb;
16060 		dtrace_action_t *act;
16061 		void *buf;
16062 		size_t size;
16063 		uintptr_t dest;
16064 		int nrecs;
16065 
16066 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
16067 			return (EFAULT);
16068 
16069 		mutex_enter(&dtrace_lock);
16070 
16071 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16072 			mutex_exit(&dtrace_lock);
16073 			return (EINVAL);
16074 		}
16075 
16076 		if (ecb->dte_probe == NULL) {
16077 			mutex_exit(&dtrace_lock);
16078 			return (EINVAL);
16079 		}
16080 
16081 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16082 		epdesc.dtepd_uarg = ecb->dte_uarg;
16083 		epdesc.dtepd_size = ecb->dte_size;
16084 
16085 		nrecs = epdesc.dtepd_nrecs;
16086 		epdesc.dtepd_nrecs = 0;
16087 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16088 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16089 				continue;
16090 
16091 			epdesc.dtepd_nrecs++;
16092 		}
16093 
16094 		/*
16095 		 * Now that we have the size, we need to allocate a temporary
16096 		 * buffer in which to store the complete description.  We need
16097 		 * the temporary buffer to be able to drop dtrace_lock()
16098 		 * across the copyout(), below.
16099 		 */
16100 		size = sizeof (dtrace_eprobedesc_t) +
16101 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16102 
16103 		buf = kmem_alloc(size, KM_SLEEP);
16104 		dest = (uintptr_t)buf;
16105 
16106 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16107 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16108 
16109 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16110 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16111 				continue;
16112 
16113 			if (nrecs-- == 0)
16114 				break;
16115 
16116 			bcopy(&act->dta_rec, (void *)dest,
16117 			    sizeof (dtrace_recdesc_t));
16118 			dest += sizeof (dtrace_recdesc_t);
16119 		}
16120 
16121 		mutex_exit(&dtrace_lock);
16122 
16123 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16124 			kmem_free(buf, size);
16125 			return (EFAULT);
16126 		}
16127 
16128 		kmem_free(buf, size);
16129 		return (0);
16130 	}
16131 
16132 	case DTRACEIOC_AGGDESC: {
16133 		dtrace_aggdesc_t aggdesc;
16134 		dtrace_action_t *act;
16135 		dtrace_aggregation_t *agg;
16136 		int nrecs;
16137 		uint32_t offs;
16138 		dtrace_recdesc_t *lrec;
16139 		void *buf;
16140 		size_t size;
16141 		uintptr_t dest;
16142 
16143 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
16144 			return (EFAULT);
16145 
16146 		mutex_enter(&dtrace_lock);
16147 
16148 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16149 			mutex_exit(&dtrace_lock);
16150 			return (EINVAL);
16151 		}
16152 
16153 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16154 
16155 		nrecs = aggdesc.dtagd_nrecs;
16156 		aggdesc.dtagd_nrecs = 0;
16157 
16158 		offs = agg->dtag_base;
16159 		lrec = &agg->dtag_action.dta_rec;
16160 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16161 
16162 		for (act = agg->dtag_first; ; act = act->dta_next) {
16163 			ASSERT(act->dta_intuple ||
16164 			    DTRACEACT_ISAGG(act->dta_kind));
16165 
16166 			/*
16167 			 * If this action has a record size of zero, it
16168 			 * denotes an argument to the aggregating action.
16169 			 * Because the presence of this record doesn't (or
16170 			 * shouldn't) affect the way the data is interpreted,
16171 			 * we don't copy it out to save user-level the
16172 			 * confusion of dealing with a zero-length record.
16173 			 */
16174 			if (act->dta_rec.dtrd_size == 0) {
16175 				ASSERT(agg->dtag_hasarg);
16176 				continue;
16177 			}
16178 
16179 			aggdesc.dtagd_nrecs++;
16180 
16181 			if (act == &agg->dtag_action)
16182 				break;
16183 		}
16184 
16185 		/*
16186 		 * Now that we have the size, we need to allocate a temporary
16187 		 * buffer in which to store the complete description.  We need
16188 		 * the temporary buffer to be able to drop dtrace_lock()
16189 		 * across the copyout(), below.
16190 		 */
16191 		size = sizeof (dtrace_aggdesc_t) +
16192 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16193 
16194 		buf = kmem_alloc(size, KM_SLEEP);
16195 		dest = (uintptr_t)buf;
16196 
16197 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16198 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16199 
16200 		for (act = agg->dtag_first; ; act = act->dta_next) {
16201 			dtrace_recdesc_t rec = act->dta_rec;
16202 
16203 			/*
16204 			 * See the comment in the above loop for why we pass
16205 			 * over zero-length records.
16206 			 */
16207 			if (rec.dtrd_size == 0) {
16208 				ASSERT(agg->dtag_hasarg);
16209 				continue;
16210 			}
16211 
16212 			if (nrecs-- == 0)
16213 				break;
16214 
16215 			rec.dtrd_offset -= offs;
16216 			bcopy(&rec, (void *)dest, sizeof (rec));
16217 			dest += sizeof (dtrace_recdesc_t);
16218 
16219 			if (act == &agg->dtag_action)
16220 				break;
16221 		}
16222 
16223 		mutex_exit(&dtrace_lock);
16224 
16225 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16226 			kmem_free(buf, size);
16227 			return (EFAULT);
16228 		}
16229 
16230 		kmem_free(buf, size);
16231 		return (0);
16232 	}
16233 
16234 	case DTRACEIOC_ENABLE: {
16235 		dof_hdr_t *dof;
16236 		dtrace_enabling_t *enab = NULL;
16237 		dtrace_vstate_t *vstate;
16238 		int err = 0;
16239 
16240 		*rv = 0;
16241 
16242 		/*
16243 		 * If a NULL argument has been passed, we take this as our
16244 		 * cue to reevaluate our enablings.
16245 		 */
16246 		if (arg == NULL) {
16247 			dtrace_enabling_matchall();
16248 
16249 			return (0);
16250 		}
16251 
16252 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16253 			return (rval);
16254 
16255 		mutex_enter(&cpu_lock);
16256 		mutex_enter(&dtrace_lock);
16257 		vstate = &state->dts_vstate;
16258 
16259 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16260 			mutex_exit(&dtrace_lock);
16261 			mutex_exit(&cpu_lock);
16262 			dtrace_dof_destroy(dof);
16263 			return (EBUSY);
16264 		}
16265 
16266 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16267 			mutex_exit(&dtrace_lock);
16268 			mutex_exit(&cpu_lock);
16269 			dtrace_dof_destroy(dof);
16270 			return (EINVAL);
16271 		}
16272 
16273 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
16274 			dtrace_enabling_destroy(enab);
16275 			mutex_exit(&dtrace_lock);
16276 			mutex_exit(&cpu_lock);
16277 			dtrace_dof_destroy(dof);
16278 			return (rval);
16279 		}
16280 
16281 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16282 			err = dtrace_enabling_retain(enab);
16283 		} else {
16284 			dtrace_enabling_destroy(enab);
16285 		}
16286 
16287 		mutex_exit(&cpu_lock);
16288 		mutex_exit(&dtrace_lock);
16289 		dtrace_dof_destroy(dof);
16290 
16291 		return (err);
16292 	}
16293 
16294 	case DTRACEIOC_REPLICATE: {
16295 		dtrace_repldesc_t desc;
16296 		dtrace_probedesc_t *match = &desc.dtrpd_match;
16297 		dtrace_probedesc_t *create = &desc.dtrpd_create;
16298 		int err;
16299 
16300 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16301 			return (EFAULT);
16302 
16303 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16304 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16305 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16306 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16307 
16308 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16309 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16310 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16311 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16312 
16313 		mutex_enter(&dtrace_lock);
16314 		err = dtrace_enabling_replicate(state, match, create);
16315 		mutex_exit(&dtrace_lock);
16316 
16317 		return (err);
16318 	}
16319 
16320 	case DTRACEIOC_PROBEMATCH:
16321 	case DTRACEIOC_PROBES: {
16322 		dtrace_probe_t *probe = NULL;
16323 		dtrace_probedesc_t desc;
16324 		dtrace_probekey_t pkey;
16325 		dtrace_id_t i;
16326 		int m = 0;
16327 		uint32_t priv;
16328 		uid_t uid;
16329 		zoneid_t zoneid;
16330 
16331 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16332 			return (EFAULT);
16333 
16334 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16335 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16336 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16337 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16338 
16339 		/*
16340 		 * Before we attempt to match this probe, we want to give
16341 		 * all providers the opportunity to provide it.
16342 		 */
16343 		if (desc.dtpd_id == DTRACE_IDNONE) {
16344 			mutex_enter(&dtrace_provider_lock);
16345 			dtrace_probe_provide(&desc, NULL);
16346 			mutex_exit(&dtrace_provider_lock);
16347 			desc.dtpd_id++;
16348 		}
16349 
16350 		if (cmd == DTRACEIOC_PROBEMATCH)  {
16351 			dtrace_probekey(&desc, &pkey);
16352 			pkey.dtpk_id = DTRACE_IDNONE;
16353 		}
16354 
16355 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16356 
16357 		mutex_enter(&dtrace_lock);
16358 
16359 		if (cmd == DTRACEIOC_PROBEMATCH) {
16360 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16361 				if ((probe = dtrace_probes[i - 1]) != NULL &&
16362 				    (m = dtrace_match_probe(probe, &pkey,
16363 				    priv, uid, zoneid)) != 0)
16364 					break;
16365 			}
16366 
16367 			if (m < 0) {
16368 				mutex_exit(&dtrace_lock);
16369 				return (EINVAL);
16370 			}
16371 
16372 		} else {
16373 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16374 				if ((probe = dtrace_probes[i - 1]) != NULL &&
16375 				    dtrace_match_priv(probe, priv, uid, zoneid))
16376 					break;
16377 			}
16378 		}
16379 
16380 		if (probe == NULL) {
16381 			mutex_exit(&dtrace_lock);
16382 			return (ESRCH);
16383 		}
16384 
16385 		dtrace_probe_description(probe, &desc);
16386 		mutex_exit(&dtrace_lock);
16387 
16388 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16389 			return (EFAULT);
16390 
16391 		return (0);
16392 	}
16393 
16394 	case DTRACEIOC_PROBEARG: {
16395 		dtrace_argdesc_t desc;
16396 		dtrace_probe_t *probe;
16397 		dtrace_provider_t *prov;
16398 
16399 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16400 			return (EFAULT);
16401 
16402 		if (desc.dtargd_id == DTRACE_IDNONE)
16403 			return (EINVAL);
16404 
16405 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
16406 			return (EINVAL);
16407 
16408 		mutex_enter(&dtrace_provider_lock);
16409 		mutex_enter(&mod_lock);
16410 		mutex_enter(&dtrace_lock);
16411 
16412 		if (desc.dtargd_id > dtrace_nprobes) {
16413 			mutex_exit(&dtrace_lock);
16414 			mutex_exit(&mod_lock);
16415 			mutex_exit(&dtrace_provider_lock);
16416 			return (EINVAL);
16417 		}
16418 
16419 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16420 			mutex_exit(&dtrace_lock);
16421 			mutex_exit(&mod_lock);
16422 			mutex_exit(&dtrace_provider_lock);
16423 			return (EINVAL);
16424 		}
16425 
16426 		mutex_exit(&dtrace_lock);
16427 
16428 		prov = probe->dtpr_provider;
16429 
16430 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16431 			/*
16432 			 * There isn't any typed information for this probe.
16433 			 * Set the argument number to DTRACE_ARGNONE.
16434 			 */
16435 			desc.dtargd_ndx = DTRACE_ARGNONE;
16436 		} else {
16437 			desc.dtargd_native[0] = '\0';
16438 			desc.dtargd_xlate[0] = '\0';
16439 			desc.dtargd_mapping = desc.dtargd_ndx;
16440 
16441 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16442 			    probe->dtpr_id, probe->dtpr_arg, &desc);
16443 		}
16444 
16445 		mutex_exit(&mod_lock);
16446 		mutex_exit(&dtrace_provider_lock);
16447 
16448 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16449 			return (EFAULT);
16450 
16451 		return (0);
16452 	}
16453 
16454 	case DTRACEIOC_GO: {
16455 		processorid_t cpuid;
16456 		rval = dtrace_state_go(state, &cpuid);
16457 
16458 		if (rval != 0)
16459 			return (rval);
16460 
16461 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16462 			return (EFAULT);
16463 
16464 		return (0);
16465 	}
16466 
16467 	case DTRACEIOC_STOP: {
16468 		processorid_t cpuid;
16469 
16470 		mutex_enter(&dtrace_lock);
16471 		rval = dtrace_state_stop(state, &cpuid);
16472 		mutex_exit(&dtrace_lock);
16473 
16474 		if (rval != 0)
16475 			return (rval);
16476 
16477 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16478 			return (EFAULT);
16479 
16480 		return (0);
16481 	}
16482 
16483 	case DTRACEIOC_DOFGET: {
16484 		dof_hdr_t hdr, *dof;
16485 		uint64_t len;
16486 
16487 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16488 			return (EFAULT);
16489 
16490 		mutex_enter(&dtrace_lock);
16491 		dof = dtrace_dof_create(state);
16492 		mutex_exit(&dtrace_lock);
16493 
16494 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16495 		rval = copyout(dof, (void *)arg, len);
16496 		dtrace_dof_destroy(dof);
16497 
16498 		return (rval == 0 ? 0 : EFAULT);
16499 	}
16500 
16501 	case DTRACEIOC_AGGSNAP:
16502 	case DTRACEIOC_BUFSNAP: {
16503 		dtrace_bufdesc_t desc;
16504 		caddr_t cached;
16505 		dtrace_buffer_t *buf;
16506 
16507 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16508 			return (EFAULT);
16509 
16510 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16511 			return (EINVAL);
16512 
16513 		mutex_enter(&dtrace_lock);
16514 
16515 		if (cmd == DTRACEIOC_BUFSNAP) {
16516 			buf = &state->dts_buffer[desc.dtbd_cpu];
16517 		} else {
16518 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16519 		}
16520 
16521 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16522 			size_t sz = buf->dtb_offset;
16523 
16524 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16525 				mutex_exit(&dtrace_lock);
16526 				return (EBUSY);
16527 			}
16528 
16529 			/*
16530 			 * If this buffer has already been consumed, we're
16531 			 * going to indicate that there's nothing left here
16532 			 * to consume.
16533 			 */
16534 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16535 				mutex_exit(&dtrace_lock);
16536 
16537 				desc.dtbd_size = 0;
16538 				desc.dtbd_drops = 0;
16539 				desc.dtbd_errors = 0;
16540 				desc.dtbd_oldest = 0;
16541 				sz = sizeof (desc);
16542 
16543 				if (copyout(&desc, (void *)arg, sz) != 0)
16544 					return (EFAULT);
16545 
16546 				return (0);
16547 			}
16548 
16549 			/*
16550 			 * If this is a ring buffer that has wrapped, we want
16551 			 * to copy the whole thing out.
16552 			 */
16553 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16554 				dtrace_buffer_polish(buf);
16555 				sz = buf->dtb_size;
16556 			}
16557 
16558 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
16559 				mutex_exit(&dtrace_lock);
16560 				return (EFAULT);
16561 			}
16562 
16563 			desc.dtbd_size = sz;
16564 			desc.dtbd_drops = buf->dtb_drops;
16565 			desc.dtbd_errors = buf->dtb_errors;
16566 			desc.dtbd_oldest = buf->dtb_xamot_offset;
16567 			desc.dtbd_timestamp = dtrace_gethrtime();
16568 
16569 			mutex_exit(&dtrace_lock);
16570 
16571 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16572 				return (EFAULT);
16573 
16574 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
16575 
16576 			return (0);
16577 		}
16578 
16579 		if (buf->dtb_tomax == NULL) {
16580 			ASSERT(buf->dtb_xamot == NULL);
16581 			mutex_exit(&dtrace_lock);
16582 			return (ENOENT);
16583 		}
16584 
16585 		cached = buf->dtb_tomax;
16586 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16587 
16588 		dtrace_xcall(desc.dtbd_cpu,
16589 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
16590 
16591 		state->dts_errors += buf->dtb_xamot_errors;
16592 
16593 		/*
16594 		 * If the buffers did not actually switch, then the cross call
16595 		 * did not take place -- presumably because the given CPU is
16596 		 * not in the ready set.  If this is the case, we'll return
16597 		 * ENOENT.
16598 		 */
16599 		if (buf->dtb_tomax == cached) {
16600 			ASSERT(buf->dtb_xamot != cached);
16601 			mutex_exit(&dtrace_lock);
16602 			return (ENOENT);
16603 		}
16604 
16605 		ASSERT(cached == buf->dtb_xamot);
16606 
16607 		/*
16608 		 * We have our snapshot; now copy it out.
16609 		 */
16610 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
16611 		    buf->dtb_xamot_offset) != 0) {
16612 			mutex_exit(&dtrace_lock);
16613 			return (EFAULT);
16614 		}
16615 
16616 		desc.dtbd_size = buf->dtb_xamot_offset;
16617 		desc.dtbd_drops = buf->dtb_xamot_drops;
16618 		desc.dtbd_errors = buf->dtb_xamot_errors;
16619 		desc.dtbd_oldest = 0;
16620 		desc.dtbd_timestamp = buf->dtb_switched;
16621 
16622 		mutex_exit(&dtrace_lock);
16623 
16624 		/*
16625 		 * Finally, copy out the buffer description.
16626 		 */
16627 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16628 			return (EFAULT);
16629 
16630 		return (0);
16631 	}
16632 
16633 	case DTRACEIOC_CONF: {
16634 		dtrace_conf_t conf;
16635 
16636 		bzero(&conf, sizeof (conf));
16637 		conf.dtc_difversion = DIF_VERSION;
16638 		conf.dtc_difintregs = DIF_DIR_NREGS;
16639 		conf.dtc_diftupregs = DIF_DTR_NREGS;
16640 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16641 
16642 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
16643 			return (EFAULT);
16644 
16645 		return (0);
16646 	}
16647 
16648 	case DTRACEIOC_STATUS: {
16649 		dtrace_status_t stat;
16650 		dtrace_dstate_t *dstate;
16651 		int i, j;
16652 		uint64_t nerrs;
16653 
16654 		/*
16655 		 * See the comment in dtrace_state_deadman() for the reason
16656 		 * for setting dts_laststatus to INT64_MAX before setting
16657 		 * it to the correct value.
16658 		 */
16659 		state->dts_laststatus = INT64_MAX;
16660 		dtrace_membar_producer();
16661 		state->dts_laststatus = dtrace_gethrtime();
16662 
16663 		bzero(&stat, sizeof (stat));
16664 
16665 		mutex_enter(&dtrace_lock);
16666 
16667 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
16668 			mutex_exit(&dtrace_lock);
16669 			return (ENOENT);
16670 		}
16671 
16672 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
16673 			stat.dtst_exiting = 1;
16674 
16675 		nerrs = state->dts_errors;
16676 		dstate = &state->dts_vstate.dtvs_dynvars;
16677 
16678 		for (i = 0; i < NCPU; i++) {
16679 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
16680 
16681 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
16682 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
16683 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
16684 
16685 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
16686 				stat.dtst_filled++;
16687 
16688 			nerrs += state->dts_buffer[i].dtb_errors;
16689 
16690 			for (j = 0; j < state->dts_nspeculations; j++) {
16691 				dtrace_speculation_t *spec;
16692 				dtrace_buffer_t *buf;
16693 
16694 				spec = &state->dts_speculations[j];
16695 				buf = &spec->dtsp_buffer[i];
16696 				stat.dtst_specdrops += buf->dtb_xamot_drops;
16697 			}
16698 		}
16699 
16700 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
16701 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
16702 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
16703 		stat.dtst_dblerrors = state->dts_dblerrors;
16704 		stat.dtst_killed =
16705 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
16706 		stat.dtst_errors = nerrs;
16707 
16708 		mutex_exit(&dtrace_lock);
16709 
16710 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
16711 			return (EFAULT);
16712 
16713 		return (0);
16714 	}
16715 
16716 	case DTRACEIOC_FORMAT: {
16717 		dtrace_fmtdesc_t fmt;
16718 		char *str;
16719 		int len;
16720 
16721 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
16722 			return (EFAULT);
16723 
16724 		mutex_enter(&dtrace_lock);
16725 
16726 		if (fmt.dtfd_format == 0 ||
16727 		    fmt.dtfd_format > state->dts_nformats) {
16728 			mutex_exit(&dtrace_lock);
16729 			return (EINVAL);
16730 		}
16731 
16732 		/*
16733 		 * Format strings are allocated contiguously and they are
16734 		 * never freed; if a format index is less than the number
16735 		 * of formats, we can assert that the format map is non-NULL
16736 		 * and that the format for the specified index is non-NULL.
16737 		 */
16738 		ASSERT(state->dts_formats != NULL);
16739 		str = state->dts_formats[fmt.dtfd_format - 1];
16740 		ASSERT(str != NULL);
16741 
16742 		len = strlen(str) + 1;
16743 
16744 		if (len > fmt.dtfd_length) {
16745 			fmt.dtfd_length = len;
16746 
16747 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
16748 				mutex_exit(&dtrace_lock);
16749 				return (EINVAL);
16750 			}
16751 		} else {
16752 			if (copyout(str, fmt.dtfd_string, len) != 0) {
16753 				mutex_exit(&dtrace_lock);
16754 				return (EINVAL);
16755 			}
16756 		}
16757 
16758 		mutex_exit(&dtrace_lock);
16759 		return (0);
16760 	}
16761 
16762 	default:
16763 		break;
16764 	}
16765 
16766 	return (ENOTTY);
16767 }
16768 
16769 /*ARGSUSED*/
16770 static int
16771 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
16772 {
16773 	dtrace_state_t *state;
16774 
16775 	switch (cmd) {
16776 	case DDI_DETACH:
16777 		break;
16778 
16779 	case DDI_SUSPEND:
16780 		return (DDI_SUCCESS);
16781 
16782 	default:
16783 		return (DDI_FAILURE);
16784 	}
16785 
16786 	mutex_enter(&cpu_lock);
16787 	mutex_enter(&dtrace_provider_lock);
16788 	mutex_enter(&dtrace_lock);
16789 
16790 	ASSERT(dtrace_opens == 0);
16791 
16792 	if (dtrace_helpers > 0) {
16793 		mutex_exit(&dtrace_provider_lock);
16794 		mutex_exit(&dtrace_lock);
16795 		mutex_exit(&cpu_lock);
16796 		return (DDI_FAILURE);
16797 	}
16798 
16799 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
16800 		mutex_exit(&dtrace_provider_lock);
16801 		mutex_exit(&dtrace_lock);
16802 		mutex_exit(&cpu_lock);
16803 		return (DDI_FAILURE);
16804 	}
16805 
16806 	dtrace_provider = NULL;
16807 
16808 	if ((state = dtrace_anon_grab()) != NULL) {
16809 		/*
16810 		 * If there were ECBs on this state, the provider should
16811 		 * have not been allowed to detach; assert that there is
16812 		 * none.
16813 		 */
16814 		ASSERT(state->dts_necbs == 0);
16815 		dtrace_state_destroy(state);
16816 
16817 		/*
16818 		 * If we're being detached with anonymous state, we need to
16819 		 * indicate to the kernel debugger that DTrace is now inactive.
16820 		 */
16821 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16822 	}
16823 
16824 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
16825 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16826 	dtrace_cpu_init = NULL;
16827 	dtrace_helpers_cleanup = NULL;
16828 	dtrace_helpers_fork = NULL;
16829 	dtrace_cpustart_init = NULL;
16830 	dtrace_cpustart_fini = NULL;
16831 	dtrace_debugger_init = NULL;
16832 	dtrace_debugger_fini = NULL;
16833 	dtrace_modload = NULL;
16834 	dtrace_modunload = NULL;
16835 
16836 	ASSERT(dtrace_getf == 0);
16837 	ASSERT(dtrace_closef == NULL);
16838 
16839 	mutex_exit(&cpu_lock);
16840 
16841 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
16842 	dtrace_probes = NULL;
16843 	dtrace_nprobes = 0;
16844 
16845 	dtrace_hash_destroy(dtrace_bymod);
16846 	dtrace_hash_destroy(dtrace_byfunc);
16847 	dtrace_hash_destroy(dtrace_byname);
16848 	dtrace_bymod = NULL;
16849 	dtrace_byfunc = NULL;
16850 	dtrace_byname = NULL;
16851 
16852 	kmem_cache_destroy(dtrace_state_cache);
16853 	vmem_destroy(dtrace_minor);
16854 	vmem_destroy(dtrace_arena);
16855 
16856 	if (dtrace_toxrange != NULL) {
16857 		kmem_free(dtrace_toxrange,
16858 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
16859 		dtrace_toxrange = NULL;
16860 		dtrace_toxranges = 0;
16861 		dtrace_toxranges_max = 0;
16862 	}
16863 
16864 	ddi_remove_minor_node(dtrace_devi, NULL);
16865 	dtrace_devi = NULL;
16866 
16867 	ddi_soft_state_fini(&dtrace_softstate);
16868 
16869 	ASSERT(dtrace_vtime_references == 0);
16870 	ASSERT(dtrace_opens == 0);
16871 	ASSERT(dtrace_retained == NULL);
16872 
16873 	mutex_exit(&dtrace_lock);
16874 	mutex_exit(&dtrace_provider_lock);
16875 
16876 	/*
16877 	 * We don't destroy the task queue until after we have dropped our
16878 	 * locks (taskq_destroy() may block on running tasks).  To prevent
16879 	 * attempting to do work after we have effectively detached but before
16880 	 * the task queue has been destroyed, all tasks dispatched via the
16881 	 * task queue must check that DTrace is still attached before
16882 	 * performing any operation.
16883 	 */
16884 	taskq_destroy(dtrace_taskq);
16885 	dtrace_taskq = NULL;
16886 
16887 	return (DDI_SUCCESS);
16888 }
16889 
16890 /*ARGSUSED*/
16891 static int
16892 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
16893 {
16894 	int error;
16895 
16896 	switch (infocmd) {
16897 	case DDI_INFO_DEVT2DEVINFO:
16898 		*result = (void *)dtrace_devi;
16899 		error = DDI_SUCCESS;
16900 		break;
16901 	case DDI_INFO_DEVT2INSTANCE:
16902 		*result = (void *)0;
16903 		error = DDI_SUCCESS;
16904 		break;
16905 	default:
16906 		error = DDI_FAILURE;
16907 	}
16908 	return (error);
16909 }
16910 
16911 static struct cb_ops dtrace_cb_ops = {
16912 	dtrace_open,		/* open */
16913 	dtrace_close,		/* close */
16914 	nulldev,		/* strategy */
16915 	nulldev,		/* print */
16916 	nodev,			/* dump */
16917 	nodev,			/* read */
16918 	nodev,			/* write */
16919 	dtrace_ioctl,		/* ioctl */
16920 	nodev,			/* devmap */
16921 	nodev,			/* mmap */
16922 	nodev,			/* segmap */
16923 	nochpoll,		/* poll */
16924 	ddi_prop_op,		/* cb_prop_op */
16925 	0,			/* streamtab  */
16926 	D_NEW | D_MP		/* Driver compatibility flag */
16927 };
16928 
16929 static struct dev_ops dtrace_ops = {
16930 	DEVO_REV,		/* devo_rev */
16931 	0,			/* refcnt */
16932 	dtrace_info,		/* get_dev_info */
16933 	nulldev,		/* identify */
16934 	nulldev,		/* probe */
16935 	dtrace_attach,		/* attach */
16936 	dtrace_detach,		/* detach */
16937 	nodev,			/* reset */
16938 	&dtrace_cb_ops,		/* driver operations */
16939 	NULL,			/* bus operations */
16940 	nodev,			/* dev power */
16941 	ddi_quiesce_not_needed,		/* quiesce */
16942 };
16943 
16944 static struct modldrv modldrv = {
16945 	&mod_driverops,		/* module type (this is a pseudo driver) */
16946 	"Dynamic Tracing",	/* name of module */
16947 	&dtrace_ops,		/* driver ops */
16948 };
16949 
16950 static struct modlinkage modlinkage = {
16951 	MODREV_1,
16952 	(void *)&modldrv,
16953 	NULL
16954 };
16955 
16956 int
16957 _init(void)
16958 {
16959 	return (mod_install(&modlinkage));
16960 }
16961 
16962 int
16963 _info(struct modinfo *modinfop)
16964 {
16965 	return (mod_info(&modlinkage, modinfop));
16966 }
16967 
16968 int
16969 _fini(void)
16970 {
16971 	return (mod_remove(&modlinkage));
16972 }
16973