xref: /illumos-gate/usr/src/uts/common/dtrace/dtrace.c (revision 4e93fb0f6383eaac21897dcdae56b87118131e4d)
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 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * DTrace - Dynamic Tracing for Solaris
31  *
32  * This is the implementation of the Solaris Dynamic Tracing framework
33  * (DTrace).  The user-visible interface to DTrace is described at length in
34  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
35  * library, the in-kernel DTrace framework, and the DTrace providers are
36  * described in the block comments in the <sys/dtrace.h> header file.  The
37  * internal architecture of DTrace is described in the block comments in the
38  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
39  * implementation very much assume mastery of all of these sources; if one has
40  * an unanswered question about the implementation, one should consult them
41  * first.
42  *
43  * The functions here are ordered roughly as follows:
44  *
45  *   - Probe context functions
46  *   - Probe hashing functions
47  *   - Non-probe context utility functions
48  *   - Matching functions
49  *   - Provider-to-Framework API functions
50  *   - Probe management functions
51  *   - DIF object functions
52  *   - Format functions
53  *   - Predicate functions
54  *   - ECB functions
55  *   - Buffer functions
56  *   - Enabling functions
57  *   - DOF functions
58  *   - Anonymous enabling functions
59  *   - Consumer state functions
60  *   - Helper functions
61  *   - Hook functions
62  *   - Driver cookbook functions
63  *
64  * Each group of functions begins with a block comment labelled the "DTrace
65  * [Group] Functions", allowing one to find each block by searching forward
66  * on capital-f functions.
67  */
68 #include <sys/errno.h>
69 #include <sys/stat.h>
70 #include <sys/modctl.h>
71 #include <sys/conf.h>
72 #include <sys/systm.h>
73 #include <sys/ddi.h>
74 #include <sys/sunddi.h>
75 #include <sys/cpuvar.h>
76 #include <sys/kmem.h>
77 #include <sys/strsubr.h>
78 #include <sys/sysmacros.h>
79 #include <sys/dtrace_impl.h>
80 #include <sys/atomic.h>
81 #include <sys/cmn_err.h>
82 #include <sys/mutex_impl.h>
83 #include <sys/rwlock_impl.h>
84 #include <sys/ctf_api.h>
85 #include <sys/panic.h>
86 #include <sys/priv_impl.h>
87 #include <sys/policy.h>
88 #include <sys/cred_impl.h>
89 #include <sys/procfs_isa.h>
90 #include <sys/taskq.h>
91 #include <sys/mkdev.h>
92 #include <sys/kdi.h>
93 #include <sys/zone.h>
94 
95 /*
96  * DTrace Tunable Variables
97  *
98  * The following variables may be tuned by adding a line to /etc/system that
99  * includes both the name of the DTrace module ("dtrace") and the name of the
100  * variable.  For example:
101  *
102  *   set dtrace:dtrace_destructive_disallow = 1
103  *
104  * In general, the only variables that one should be tuning this way are those
105  * that affect system-wide DTrace behavior, and for which the default behavior
106  * is undesirable.  Most of these variables are tunable on a per-consumer
107  * basis using DTrace options, and need not be tuned on a system-wide basis.
108  * When tuning these variables, avoid pathological values; while some attempt
109  * is made to verify the integrity of these variables, they are not considered
110  * part of the supported interface to DTrace, and they are therefore not
111  * checked comprehensively.  Further, these variables should not be tuned
112  * dynamically via "mdb -kw" or other means; they should only be tuned via
113  * /etc/system.
114  */
115 int		dtrace_destructive_disallow = 0;
116 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
117 size_t		dtrace_difo_maxsize = (256 * 1024);
118 dtrace_optval_t	dtrace_dof_maxsize = (256 * 1024);
119 size_t		dtrace_global_maxsize = (16 * 1024);
120 size_t		dtrace_actions_max = (16 * 1024);
121 size_t		dtrace_retain_max = 1024;
122 dtrace_optval_t	dtrace_helper_actions_max = 32;
123 dtrace_optval_t	dtrace_helper_providers_max = 32;
124 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
125 size_t		dtrace_strsize_default = 256;
126 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
127 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
128 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
129 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
130 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
131 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
132 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
133 dtrace_optval_t	dtrace_nspec_default = 1;
134 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
135 dtrace_optval_t dtrace_stackframes_default = 20;
136 dtrace_optval_t dtrace_ustackframes_default = 20;
137 dtrace_optval_t dtrace_jstackframes_default = 50;
138 dtrace_optval_t dtrace_jstackstrsize_default = 512;
139 int		dtrace_msgdsize_max = 128;
140 hrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
141 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
142 int		dtrace_devdepth_max = 32;
143 int		dtrace_err_verbose;
144 hrtime_t	dtrace_deadman_interval = NANOSEC;
145 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
146 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
147 
148 /*
149  * DTrace External Variables
150  *
151  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
152  * available to DTrace consumers via the backtick (`) syntax.  One of these,
153  * dtrace_zero, is made deliberately so:  it is provided as a source of
154  * well-known, zero-filled memory.  While this variable is not documented,
155  * it is used by some translators as an implementation detail.
156  */
157 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
158 
159 /*
160  * DTrace Internal Variables
161  */
162 static dev_info_t	*dtrace_devi;		/* device info */
163 static vmem_t		*dtrace_arena;		/* probe ID arena */
164 static vmem_t		*dtrace_minor;		/* minor number arena */
165 static taskq_t		*dtrace_taskq;		/* task queue */
166 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
167 static int		dtrace_nprobes;		/* number of probes */
168 static dtrace_provider_t *dtrace_provider;	/* provider list */
169 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
170 static int		dtrace_opens;		/* number of opens */
171 static int		dtrace_helpers;		/* number of helpers */
172 static void		*dtrace_softstate;	/* softstate pointer */
173 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
174 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
175 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
176 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
177 static int		dtrace_toxranges;	/* number of toxic ranges */
178 static int		dtrace_toxranges_max;	/* size of toxic range array */
179 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
180 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
181 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
182 static kthread_t	*dtrace_panicked;	/* panicking thread */
183 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
184 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
185 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
186 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
187 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
188 
189 /*
190  * DTrace Locking
191  * DTrace is protected by three (relatively coarse-grained) locks:
192  *
193  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
194  *     including enabling state, probes, ECBs, consumer state, helper state,
195  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
196  *     probe context is lock-free -- synchronization is handled via the
197  *     dtrace_sync() cross call mechanism.
198  *
199  * (2) dtrace_provider_lock is required when manipulating provider state, or
200  *     when provider state must be held constant.
201  *
202  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
203  *     when meta provider state must be held constant.
204  *
205  * The lock ordering between these three locks is dtrace_meta_lock before
206  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
207  * several places where dtrace_provider_lock is held by the framework as it
208  * calls into the providers -- which then call back into the framework,
209  * grabbing dtrace_lock.)
210  *
211  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
212  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
213  * role as a coarse-grained lock; it is acquired before both of these locks.
214  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
215  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
216  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
217  * acquired _between_ dtrace_provider_lock and dtrace_lock.
218  */
219 static kmutex_t		dtrace_lock;		/* probe state lock */
220 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
221 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
222 
223 /*
224  * DTrace Provider Variables
225  *
226  * These are the variables relating to DTrace as a provider (that is, the
227  * provider of the BEGIN, END, and ERROR probes).
228  */
229 static dtrace_pattr_t	dtrace_provider_attr = {
230 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
231 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
232 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
233 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
234 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
235 };
236 
237 static void
238 dtrace_nullop(void)
239 {}
240 
241 static dtrace_pops_t	dtrace_provider_ops = {
242 	(void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
243 	(void (*)(void *, struct modctl *))dtrace_nullop,
244 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
245 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
246 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
247 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
248 	NULL,
249 	NULL,
250 	NULL,
251 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
252 };
253 
254 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
255 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
256 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
257 
258 /*
259  * DTrace Helper Tracing Variables
260  */
261 uint32_t dtrace_helptrace_next = 0;
262 uint32_t dtrace_helptrace_nlocals;
263 char	*dtrace_helptrace_buffer;
264 int	dtrace_helptrace_bufsize = 512 * 1024;
265 
266 #ifdef DEBUG
267 int	dtrace_helptrace_enabled = 1;
268 #else
269 int	dtrace_helptrace_enabled = 0;
270 #endif
271 
272 /*
273  * DTrace Error Hashing
274  *
275  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
276  * table.  This is very useful for checking coverage of tests that are
277  * expected to induce DIF or DOF processing errors, and may be useful for
278  * debugging problems in the DIF code generator or in DOF generation .  The
279  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
280  */
281 #ifdef DEBUG
282 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
283 static const char *dtrace_errlast;
284 static kthread_t *dtrace_errthread;
285 static kmutex_t dtrace_errlock;
286 #endif
287 
288 /*
289  * DTrace Macros and Constants
290  *
291  * These are various macros that are useful in various spots in the
292  * implementation, along with a few random constants that have no meaning
293  * outside of the implementation.  There is no real structure to this cpp
294  * mishmash -- but is there ever?
295  */
296 #define	DTRACE_HASHSTR(hash, probe)	\
297 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
298 
299 #define	DTRACE_HASHNEXT(hash, probe)	\
300 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
301 
302 #define	DTRACE_HASHPREV(hash, probe)	\
303 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
304 
305 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
306 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
307 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
308 
309 #define	DTRACE_AGGHASHSIZE_SLEW		17
310 
311 /*
312  * The key for a thread-local variable consists of the lower 61 bits of the
313  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
314  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
315  * equal to a variable identifier.  This is necessary (but not sufficient) to
316  * assure that global associative arrays never collide with thread-local
317  * variables.  To guarantee that they cannot collide, we must also define the
318  * order for keying dynamic variables.  That order is:
319  *
320  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
321  *
322  * Because the variable-key and the tls-key are in orthogonal spaces, there is
323  * no way for a global variable key signature to match a thread-local key
324  * signature.
325  */
326 #define	DTRACE_TLS_THRKEY(where) { \
327 	uint_t intr = 0; \
328 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
329 	for (; actv; actv >>= 1) \
330 		intr++; \
331 	ASSERT(intr < (1 << 3)); \
332 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
333 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
334 }
335 
336 #define	DT_BSWAP_8(x)	((x) & 0xff)
337 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
338 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
339 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
340 
341 #define	DTRACE_STORE(type, tomax, offset, what) \
342 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
343 
344 #ifndef __i386
345 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
346 	if (addr & (size - 1)) {					\
347 		*flags |= CPU_DTRACE_BADALIGN;				\
348 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
349 		return (0);						\
350 	}
351 #else
352 #define	DTRACE_ALIGNCHECK(addr, size, flags)
353 #endif
354 
355 /*
356  * Test whether a range of memory starting at testaddr of size testsz falls
357  * within the range of memory described by addr, sz.  We take care to avoid
358  * problems with overflow and underflow of the unsigned quantities, and
359  * disallow all negative sizes.  Ranges of size 0 are allowed.
360  */
361 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
362 	((testaddr) - (baseaddr) < (basesz) && \
363 	(testaddr) + (testsz) - (baseaddr) <= (basesz) && \
364 	(testaddr) + (testsz) >= (testaddr))
365 
366 /*
367  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
368  * alloc_sz on the righthand side of the comparison in order to avoid overflow
369  * or underflow in the comparison with it.  This is simpler than the INRANGE
370  * check above, because we know that the dtms_scratch_ptr is valid in the
371  * range.  Allocations of size zero are allowed.
372  */
373 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
374 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
375 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
376 
377 #define	DTRACE_LOADFUNC(bits)						\
378 /*CSTYLED*/								\
379 uint##bits##_t								\
380 dtrace_load##bits(uintptr_t addr)					\
381 {									\
382 	size_t size = bits / NBBY;					\
383 	/*CSTYLED*/							\
384 	uint##bits##_t rval;						\
385 	int i;								\
386 	volatile uint16_t *flags = (volatile uint16_t *)		\
387 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
388 									\
389 	DTRACE_ALIGNCHECK(addr, size, flags);				\
390 									\
391 	for (i = 0; i < dtrace_toxranges; i++) {			\
392 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
393 			continue;					\
394 									\
395 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
396 			continue;					\
397 									\
398 		/*							\
399 		 * This address falls within a toxic region; return 0.	\
400 		 */							\
401 		*flags |= CPU_DTRACE_BADADDR;				\
402 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
403 		return (0);						\
404 	}								\
405 									\
406 	*flags |= CPU_DTRACE_NOFAULT;					\
407 	/*CSTYLED*/							\
408 	rval = *((volatile uint##bits##_t *)addr);			\
409 	*flags &= ~CPU_DTRACE_NOFAULT;					\
410 									\
411 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
412 }
413 
414 #ifdef _LP64
415 #define	dtrace_loadptr	dtrace_load64
416 #else
417 #define	dtrace_loadptr	dtrace_load32
418 #endif
419 
420 #define	DTRACE_DYNHASH_FREE	0
421 #define	DTRACE_DYNHASH_SINK	1
422 #define	DTRACE_DYNHASH_VALID	2
423 
424 #define	DTRACE_MATCH_NEXT	0
425 #define	DTRACE_MATCH_DONE	1
426 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
427 #define	DTRACE_STATE_ALIGN	64
428 
429 #define	DTRACE_FLAGS2FLT(flags)						\
430 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
431 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
432 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
433 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
434 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
435 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
436 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
437 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
438 	DTRACEFLT_UNKNOWN)
439 
440 #define	DTRACEACT_ISSTRING(act)						\
441 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
442 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
443 
444 static size_t dtrace_strlen(const char *, size_t);
445 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
446 static void dtrace_enabling_provide(dtrace_provider_t *);
447 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
448 static void dtrace_enabling_matchall(void);
449 static dtrace_state_t *dtrace_anon_grab(void);
450 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
451     dtrace_state_t *, uint64_t, uint64_t);
452 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
453 static void dtrace_buffer_drop(dtrace_buffer_t *);
454 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
455     dtrace_state_t *, dtrace_mstate_t *);
456 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
457     dtrace_optval_t);
458 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
459 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
460 
461 /*
462  * DTrace Probe Context Functions
463  *
464  * These functions are called from probe context.  Because probe context is
465  * any context in which C may be called, arbitrarily locks may be held,
466  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
467  * As a result, functions called from probe context may only call other DTrace
468  * support functions -- they may not interact at all with the system at large.
469  * (Note that the ASSERT macro is made probe-context safe by redefining it in
470  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
471  * loads are to be performed from probe context, they _must_ be in terms of
472  * the safe dtrace_load*() variants.
473  *
474  * Some functions in this block are not actually called from probe context;
475  * for these functions, there will be a comment above the function reading
476  * "Note:  not called from probe context."
477  */
478 void
479 dtrace_panic(const char *format, ...)
480 {
481 	va_list alist;
482 
483 	va_start(alist, format);
484 	dtrace_vpanic(format, alist);
485 	va_end(alist);
486 }
487 
488 int
489 dtrace_assfail(const char *a, const char *f, int l)
490 {
491 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
492 
493 	/*
494 	 * We just need something here that even the most clever compiler
495 	 * cannot optimize away.
496 	 */
497 	return (a[(uintptr_t)f]);
498 }
499 
500 /*
501  * Atomically increment a specified error counter from probe context.
502  */
503 static void
504 dtrace_error(uint32_t *counter)
505 {
506 	/*
507 	 * Most counters stored to in probe context are per-CPU counters.
508 	 * However, there are some error conditions that are sufficiently
509 	 * arcane that they don't merit per-CPU storage.  If these counters
510 	 * are incremented concurrently on different CPUs, scalability will be
511 	 * adversely affected -- but we don't expect them to be white-hot in a
512 	 * correctly constructed enabling...
513 	 */
514 	uint32_t oval, nval;
515 
516 	do {
517 		oval = *counter;
518 
519 		if ((nval = oval + 1) == 0) {
520 			/*
521 			 * If the counter would wrap, set it to 1 -- assuring
522 			 * that the counter is never zero when we have seen
523 			 * errors.  (The counter must be 32-bits because we
524 			 * aren't guaranteed a 64-bit compare&swap operation.)
525 			 * To save this code both the infamy of being fingered
526 			 * by a priggish news story and the indignity of being
527 			 * the target of a neo-puritan witch trial, we're
528 			 * carefully avoiding any colorful description of the
529 			 * likelihood of this condition -- but suffice it to
530 			 * say that it is only slightly more likely than the
531 			 * overflow of predicate cache IDs, as discussed in
532 			 * dtrace_predicate_create().
533 			 */
534 			nval = 1;
535 		}
536 	} while (dtrace_cas32(counter, oval, nval) != oval);
537 }
538 
539 /*
540  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
541  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
542  */
543 DTRACE_LOADFUNC(8)
544 DTRACE_LOADFUNC(16)
545 DTRACE_LOADFUNC(32)
546 DTRACE_LOADFUNC(64)
547 
548 static int
549 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
550 {
551 	if (dest < mstate->dtms_scratch_base)
552 		return (0);
553 
554 	if (dest + size < dest)
555 		return (0);
556 
557 	if (dest + size > mstate->dtms_scratch_ptr)
558 		return (0);
559 
560 	return (1);
561 }
562 
563 static int
564 dtrace_canstore_statvar(uint64_t addr, size_t sz,
565     dtrace_statvar_t **svars, int nsvars)
566 {
567 	int i;
568 
569 	for (i = 0; i < nsvars; i++) {
570 		dtrace_statvar_t *svar = svars[i];
571 
572 		if (svar == NULL || svar->dtsv_size == 0)
573 			continue;
574 
575 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
576 			return (1);
577 	}
578 
579 	return (0);
580 }
581 
582 /*
583  * Check to see if the address is within a memory region to which a store may
584  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
585  * region.  The caller of dtrace_canstore() is responsible for performing any
586  * alignment checks that are needed before stores are actually executed.
587  */
588 static int
589 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
590     dtrace_vstate_t *vstate)
591 {
592 	/*
593 	 * First, check to see if the address is in scratch space...
594 	 */
595 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
596 	    mstate->dtms_scratch_size))
597 		return (1);
598 
599 	/*
600 	 * Now check to see if it's a dynamic variable.  This check will pick
601 	 * up both thread-local variables and any global dynamically-allocated
602 	 * variables.
603 	 */
604 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
605 	    vstate->dtvs_dynvars.dtds_size))
606 		return (1);
607 
608 	/*
609 	 * Finally, check the static local and global variables.  These checks
610 	 * take the longest, so we perform them last.
611 	 */
612 	if (dtrace_canstore_statvar(addr, sz,
613 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
614 		return (1);
615 
616 	if (dtrace_canstore_statvar(addr, sz,
617 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
618 		return (1);
619 
620 	return (0);
621 }
622 
623 
624 /*
625  * Convenience routine to check to see if the address is within a memory
626  * region in which a load may be issued given the user's privilege level;
627  * if not, it sets the appropriate error flags and loads 'addr' into the
628  * illegal value slot.
629  *
630  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
631  * appropriate memory access protection.
632  */
633 static int
634 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
635     dtrace_vstate_t *vstate)
636 {
637 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
638 
639 	/*
640 	 * If we hold the privilege to read from kernel memory, then
641 	 * everything is readable.
642 	 */
643 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
644 		return (1);
645 
646 	/*
647 	 * You can obviously read that which you can store.
648 	 */
649 	if (dtrace_canstore(addr, sz, mstate, vstate))
650 		return (1);
651 
652 	/*
653 	 * We're allowed to read from our own string table.
654 	 */
655 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
656 	    mstate->dtms_difo->dtdo_strlen))
657 		return (1);
658 
659 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
660 	*illval = addr;
661 	return (0);
662 }
663 
664 /*
665  * Convenience routine to check to see if a given string is within a memory
666  * region in which a load may be issued given the user's privilege level;
667  * this exists so that we don't need to issue unnecessary dtrace_strlen()
668  * calls in the event that the user has all privileges.
669  */
670 static int
671 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
672     dtrace_vstate_t *vstate)
673 {
674 	size_t strsz;
675 
676 	/*
677 	 * If we hold the privilege to read from kernel memory, then
678 	 * everything is readable.
679 	 */
680 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
681 		return (1);
682 
683 	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
684 	if (dtrace_canload(addr, strsz, mstate, vstate))
685 		return (1);
686 
687 	return (0);
688 }
689 
690 /*
691  * Convenience routine to check to see if a given variable is within a memory
692  * region in which a load may be issued given the user's privilege level.
693  */
694 static int
695 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
696     dtrace_vstate_t *vstate)
697 {
698 	size_t sz;
699 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
700 
701 	/*
702 	 * If we hold the privilege to read from kernel memory, then
703 	 * everything is readable.
704 	 */
705 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
706 		return (1);
707 
708 	if (type->dtdt_kind == DIF_TYPE_STRING)
709 		sz = dtrace_strlen(src,
710 		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
711 	else
712 		sz = type->dtdt_size;
713 
714 	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
715 }
716 
717 /*
718  * Compare two strings using safe loads.
719  */
720 static int
721 dtrace_strncmp(char *s1, char *s2, size_t limit)
722 {
723 	uint8_t c1, c2;
724 	volatile uint16_t *flags;
725 
726 	if (s1 == s2 || limit == 0)
727 		return (0);
728 
729 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
730 
731 	do {
732 		if (s1 == NULL) {
733 			c1 = '\0';
734 		} else {
735 			c1 = dtrace_load8((uintptr_t)s1++);
736 		}
737 
738 		if (s2 == NULL) {
739 			c2 = '\0';
740 		} else {
741 			c2 = dtrace_load8((uintptr_t)s2++);
742 		}
743 
744 		if (c1 != c2)
745 			return (c1 - c2);
746 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
747 
748 	return (0);
749 }
750 
751 /*
752  * Compute strlen(s) for a string using safe memory accesses.  The additional
753  * len parameter is used to specify a maximum length to ensure completion.
754  */
755 static size_t
756 dtrace_strlen(const char *s, size_t lim)
757 {
758 	uint_t len;
759 
760 	for (len = 0; len != lim; len++) {
761 		if (dtrace_load8((uintptr_t)s++) == '\0')
762 			break;
763 	}
764 
765 	return (len);
766 }
767 
768 /*
769  * Check if an address falls within a toxic region.
770  */
771 static int
772 dtrace_istoxic(uintptr_t kaddr, size_t size)
773 {
774 	uintptr_t taddr, tsize;
775 	int i;
776 
777 	for (i = 0; i < dtrace_toxranges; i++) {
778 		taddr = dtrace_toxrange[i].dtt_base;
779 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
780 
781 		if (kaddr - taddr < tsize) {
782 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
783 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
784 			return (1);
785 		}
786 
787 		if (taddr - kaddr < size) {
788 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
789 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
790 			return (1);
791 		}
792 	}
793 
794 	return (0);
795 }
796 
797 /*
798  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
799  * memory specified by the DIF program.  The dst is assumed to be safe memory
800  * that we can store to directly because it is managed by DTrace.  As with
801  * standard bcopy, overlapping copies are handled properly.
802  */
803 static void
804 dtrace_bcopy(const void *src, void *dst, size_t len)
805 {
806 	if (len != 0) {
807 		uint8_t *s1 = dst;
808 		const uint8_t *s2 = src;
809 
810 		if (s1 <= s2) {
811 			do {
812 				*s1++ = dtrace_load8((uintptr_t)s2++);
813 			} while (--len != 0);
814 		} else {
815 			s2 += len;
816 			s1 += len;
817 
818 			do {
819 				*--s1 = dtrace_load8((uintptr_t)--s2);
820 			} while (--len != 0);
821 		}
822 	}
823 }
824 
825 /*
826  * Copy src to dst using safe memory accesses, up to either the specified
827  * length, or the point that a nul byte is encountered.  The src is assumed to
828  * be unsafe memory specified by the DIF program.  The dst is assumed to be
829  * safe memory that we can store to directly because it is managed by DTrace.
830  * Unlike dtrace_bcopy(), overlapping regions are not handled.
831  */
832 static void
833 dtrace_strcpy(const void *src, void *dst, size_t len)
834 {
835 	if (len != 0) {
836 		uint8_t *s1 = dst, c;
837 		const uint8_t *s2 = src;
838 
839 		do {
840 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
841 		} while (--len != 0 && c != '\0');
842 	}
843 }
844 
845 /*
846  * Copy src to dst, deriving the size and type from the specified (BYREF)
847  * variable type.  The src is assumed to be unsafe memory specified by the DIF
848  * program.  The dst is assumed to be DTrace variable memory that is of the
849  * specified type; we assume that we can store to directly.
850  */
851 static void
852 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
853 {
854 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
855 
856 	if (type->dtdt_kind == DIF_TYPE_STRING) {
857 		dtrace_strcpy(src, dst, type->dtdt_size);
858 	} else {
859 		dtrace_bcopy(src, dst, type->dtdt_size);
860 	}
861 }
862 
863 /*
864  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
865  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
866  * safe memory that we can access directly because it is managed by DTrace.
867  */
868 static int
869 dtrace_bcmp(const void *s1, const void *s2, size_t len)
870 {
871 	volatile uint16_t *flags;
872 
873 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
874 
875 	if (s1 == s2)
876 		return (0);
877 
878 	if (s1 == NULL || s2 == NULL)
879 		return (1);
880 
881 	if (s1 != s2 && len != 0) {
882 		const uint8_t *ps1 = s1;
883 		const uint8_t *ps2 = s2;
884 
885 		do {
886 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
887 				return (1);
888 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
889 	}
890 	return (0);
891 }
892 
893 /*
894  * Zero the specified region using a simple byte-by-byte loop.  Note that this
895  * is for safe DTrace-managed memory only.
896  */
897 static void
898 dtrace_bzero(void *dst, size_t len)
899 {
900 	uchar_t *cp;
901 
902 	for (cp = dst; len != 0; len--)
903 		*cp++ = 0;
904 }
905 
906 /*
907  * This privilege check should be used by actions and subroutines to
908  * verify that the user credentials of the process that enabled the
909  * invoking ECB match the target credentials
910  */
911 static int
912 dtrace_priv_proc_common_user(dtrace_state_t *state)
913 {
914 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
915 
916 	/*
917 	 * We should always have a non-NULL state cred here, since if cred
918 	 * is null (anonymous tracing), we fast-path bypass this routine.
919 	 */
920 	ASSERT(s_cr != NULL);
921 
922 	if ((cr = CRED()) != NULL &&
923 	    s_cr->cr_uid == cr->cr_uid &&
924 	    s_cr->cr_uid == cr->cr_ruid &&
925 	    s_cr->cr_uid == cr->cr_suid &&
926 	    s_cr->cr_gid == cr->cr_gid &&
927 	    s_cr->cr_gid == cr->cr_rgid &&
928 	    s_cr->cr_gid == cr->cr_sgid)
929 		return (1);
930 
931 	return (0);
932 }
933 
934 /*
935  * This privilege check should be used by actions and subroutines to
936  * verify that the zone of the process that enabled the invoking ECB
937  * matches the target credentials
938  */
939 static int
940 dtrace_priv_proc_common_zone(dtrace_state_t *state)
941 {
942 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
943 
944 	/*
945 	 * We should always have a non-NULL state cred here, since if cred
946 	 * is null (anonymous tracing), we fast-path bypass this routine.
947 	 */
948 	ASSERT(s_cr != NULL);
949 
950 	if ((cr = CRED()) != NULL &&
951 	    s_cr->cr_zone == cr->cr_zone)
952 		return (1);
953 
954 	return (0);
955 }
956 
957 /*
958  * This privilege check should be used by actions and subroutines to
959  * verify that the process has not setuid or changed credentials.
960  */
961 static int
962 dtrace_priv_proc_common_nocd()
963 {
964 	proc_t *proc;
965 
966 	if ((proc = ttoproc(curthread)) != NULL &&
967 	    !(proc->p_flag & SNOCD))
968 		return (1);
969 
970 	return (0);
971 }
972 
973 static int
974 dtrace_priv_proc_destructive(dtrace_state_t *state)
975 {
976 	int action = state->dts_cred.dcr_action;
977 
978 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
979 	    dtrace_priv_proc_common_zone(state) == 0)
980 		goto bad;
981 
982 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
983 	    dtrace_priv_proc_common_user(state) == 0)
984 		goto bad;
985 
986 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
987 	    dtrace_priv_proc_common_nocd() == 0)
988 		goto bad;
989 
990 	return (1);
991 
992 bad:
993 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
994 
995 	return (0);
996 }
997 
998 static int
999 dtrace_priv_proc_control(dtrace_state_t *state)
1000 {
1001 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1002 		return (1);
1003 
1004 	if (dtrace_priv_proc_common_zone(state) &&
1005 	    dtrace_priv_proc_common_user(state) &&
1006 	    dtrace_priv_proc_common_nocd())
1007 		return (1);
1008 
1009 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1010 
1011 	return (0);
1012 }
1013 
1014 static int
1015 dtrace_priv_proc(dtrace_state_t *state)
1016 {
1017 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1018 		return (1);
1019 
1020 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1021 
1022 	return (0);
1023 }
1024 
1025 static int
1026 dtrace_priv_kernel(dtrace_state_t *state)
1027 {
1028 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1029 		return (1);
1030 
1031 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1032 
1033 	return (0);
1034 }
1035 
1036 static int
1037 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1038 {
1039 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1040 		return (1);
1041 
1042 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1043 
1044 	return (0);
1045 }
1046 
1047 /*
1048  * Note:  not called from probe context.  This function is called
1049  * asynchronously (and at a regular interval) from outside of probe context to
1050  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1051  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1052  */
1053 void
1054 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1055 {
1056 	dtrace_dynvar_t *dirty;
1057 	dtrace_dstate_percpu_t *dcpu;
1058 	int i, work = 0;
1059 
1060 	for (i = 0; i < NCPU; i++) {
1061 		dcpu = &dstate->dtds_percpu[i];
1062 
1063 		ASSERT(dcpu->dtdsc_rinsing == NULL);
1064 
1065 		/*
1066 		 * If the dirty list is NULL, there is no dirty work to do.
1067 		 */
1068 		if (dcpu->dtdsc_dirty == NULL)
1069 			continue;
1070 
1071 		/*
1072 		 * If the clean list is non-NULL, then we're not going to do
1073 		 * any work for this CPU -- it means that there has not been
1074 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1075 		 * since the last time we cleaned house.
1076 		 */
1077 		if (dcpu->dtdsc_clean != NULL)
1078 			continue;
1079 
1080 		work = 1;
1081 
1082 		/*
1083 		 * Atomically move the dirty list aside.
1084 		 */
1085 		do {
1086 			dirty = dcpu->dtdsc_dirty;
1087 
1088 			/*
1089 			 * Before we zap the dirty list, set the rinsing list.
1090 			 * (This allows for a potential assertion in
1091 			 * dtrace_dynvar():  if a free dynamic variable appears
1092 			 * on a hash chain, either the dirty list or the
1093 			 * rinsing list for some CPU must be non-NULL.)
1094 			 */
1095 			dcpu->dtdsc_rinsing = dirty;
1096 			dtrace_membar_producer();
1097 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1098 		    dirty, NULL) != dirty);
1099 	}
1100 
1101 	if (!work) {
1102 		/*
1103 		 * We have no work to do; we can simply return.
1104 		 */
1105 		return;
1106 	}
1107 
1108 	dtrace_sync();
1109 
1110 	for (i = 0; i < NCPU; i++) {
1111 		dcpu = &dstate->dtds_percpu[i];
1112 
1113 		if (dcpu->dtdsc_rinsing == NULL)
1114 			continue;
1115 
1116 		/*
1117 		 * We are now guaranteed that no hash chain contains a pointer
1118 		 * into this dirty list; we can make it clean.
1119 		 */
1120 		ASSERT(dcpu->dtdsc_clean == NULL);
1121 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1122 		dcpu->dtdsc_rinsing = NULL;
1123 	}
1124 
1125 	/*
1126 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1127 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1128 	 * This prevents a race whereby a CPU incorrectly decides that
1129 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1130 	 * after dtrace_dynvar_clean() has completed.
1131 	 */
1132 	dtrace_sync();
1133 
1134 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1135 }
1136 
1137 /*
1138  * Depending on the value of the op parameter, this function looks-up,
1139  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1140  * allocation is requested, this function will return a pointer to a
1141  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1142  * variable can be allocated.  If NULL is returned, the appropriate counter
1143  * will be incremented.
1144  */
1145 dtrace_dynvar_t *
1146 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1147     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1148     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1149 {
1150 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1151 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1152 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1153 	processorid_t me = CPU->cpu_id, cpu = me;
1154 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1155 	size_t bucket, ksize;
1156 	size_t chunksize = dstate->dtds_chunksize;
1157 	uintptr_t kdata, lock, nstate;
1158 	uint_t i;
1159 
1160 	ASSERT(nkeys != 0);
1161 
1162 	/*
1163 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1164 	 * algorithm.  For the by-value portions, we perform the algorithm in
1165 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1166 	 * bit, and seems to have only a minute effect on distribution.  For
1167 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1168 	 * over each referenced byte.  It's painful to do this, but it's much
1169 	 * better than pathological hash distribution.  The efficacy of the
1170 	 * hashing algorithm (and a comparison with other algorithms) may be
1171 	 * found by running the ::dtrace_dynstat MDB dcmd.
1172 	 */
1173 	for (i = 0; i < nkeys; i++) {
1174 		if (key[i].dttk_size == 0) {
1175 			uint64_t val = key[i].dttk_value;
1176 
1177 			hashval += (val >> 48) & 0xffff;
1178 			hashval += (hashval << 10);
1179 			hashval ^= (hashval >> 6);
1180 
1181 			hashval += (val >> 32) & 0xffff;
1182 			hashval += (hashval << 10);
1183 			hashval ^= (hashval >> 6);
1184 
1185 			hashval += (val >> 16) & 0xffff;
1186 			hashval += (hashval << 10);
1187 			hashval ^= (hashval >> 6);
1188 
1189 			hashval += val & 0xffff;
1190 			hashval += (hashval << 10);
1191 			hashval ^= (hashval >> 6);
1192 		} else {
1193 			/*
1194 			 * This is incredibly painful, but it beats the hell
1195 			 * out of the alternative.
1196 			 */
1197 			uint64_t j, size = key[i].dttk_size;
1198 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1199 
1200 			if (!dtrace_canload(base, size, mstate, vstate))
1201 				break;
1202 
1203 			for (j = 0; j < size; j++) {
1204 				hashval += dtrace_load8(base + j);
1205 				hashval += (hashval << 10);
1206 				hashval ^= (hashval >> 6);
1207 			}
1208 		}
1209 	}
1210 
1211 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1212 		return (NULL);
1213 
1214 	hashval += (hashval << 3);
1215 	hashval ^= (hashval >> 11);
1216 	hashval += (hashval << 15);
1217 
1218 	/*
1219 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1220 	 * comes out to be one of our two sentinel hash values.  If this
1221 	 * actually happens, we set the hashval to be a value known to be a
1222 	 * non-sentinel value.
1223 	 */
1224 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1225 		hashval = DTRACE_DYNHASH_VALID;
1226 
1227 	/*
1228 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1229 	 * important here, tricks can be pulled to reduce it.  (However, it's
1230 	 * critical that hash collisions be kept to an absolute minimum;
1231 	 * they're much more painful than a divide.)  It's better to have a
1232 	 * solution that generates few collisions and still keeps things
1233 	 * relatively simple.
1234 	 */
1235 	bucket = hashval % dstate->dtds_hashsize;
1236 
1237 	if (op == DTRACE_DYNVAR_DEALLOC) {
1238 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1239 
1240 		for (;;) {
1241 			while ((lock = *lockp) & 1)
1242 				continue;
1243 
1244 			if (dtrace_casptr((void *)lockp,
1245 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1246 				break;
1247 		}
1248 
1249 		dtrace_membar_producer();
1250 	}
1251 
1252 top:
1253 	prev = NULL;
1254 	lock = hash[bucket].dtdh_lock;
1255 
1256 	dtrace_membar_consumer();
1257 
1258 	start = hash[bucket].dtdh_chain;
1259 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1260 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1261 	    op != DTRACE_DYNVAR_DEALLOC));
1262 
1263 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1264 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1265 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1266 
1267 		if (dvar->dtdv_hashval != hashval) {
1268 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1269 				/*
1270 				 * We've reached the sink, and therefore the
1271 				 * end of the hash chain; we can kick out of
1272 				 * the loop knowing that we have seen a valid
1273 				 * snapshot of state.
1274 				 */
1275 				ASSERT(dvar->dtdv_next == NULL);
1276 				ASSERT(dvar == &dtrace_dynhash_sink);
1277 				break;
1278 			}
1279 
1280 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1281 				/*
1282 				 * We've gone off the rails:  somewhere along
1283 				 * the line, one of the members of this hash
1284 				 * chain was deleted.  Note that we could also
1285 				 * detect this by simply letting this loop run
1286 				 * to completion, as we would eventually hit
1287 				 * the end of the dirty list.  However, we
1288 				 * want to avoid running the length of the
1289 				 * dirty list unnecessarily (it might be quite
1290 				 * long), so we catch this as early as
1291 				 * possible by detecting the hash marker.  In
1292 				 * this case, we simply set dvar to NULL and
1293 				 * break; the conditional after the loop will
1294 				 * send us back to top.
1295 				 */
1296 				dvar = NULL;
1297 				break;
1298 			}
1299 
1300 			goto next;
1301 		}
1302 
1303 		if (dtuple->dtt_nkeys != nkeys)
1304 			goto next;
1305 
1306 		for (i = 0; i < nkeys; i++, dkey++) {
1307 			if (dkey->dttk_size != key[i].dttk_size)
1308 				goto next; /* size or type mismatch */
1309 
1310 			if (dkey->dttk_size != 0) {
1311 				if (dtrace_bcmp(
1312 				    (void *)(uintptr_t)key[i].dttk_value,
1313 				    (void *)(uintptr_t)dkey->dttk_value,
1314 				    dkey->dttk_size))
1315 					goto next;
1316 			} else {
1317 				if (dkey->dttk_value != key[i].dttk_value)
1318 					goto next;
1319 			}
1320 		}
1321 
1322 		if (op != DTRACE_DYNVAR_DEALLOC)
1323 			return (dvar);
1324 
1325 		ASSERT(dvar->dtdv_next == NULL ||
1326 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1327 
1328 		if (prev != NULL) {
1329 			ASSERT(hash[bucket].dtdh_chain != dvar);
1330 			ASSERT(start != dvar);
1331 			ASSERT(prev->dtdv_next == dvar);
1332 			prev->dtdv_next = dvar->dtdv_next;
1333 		} else {
1334 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1335 			    start, dvar->dtdv_next) != start) {
1336 				/*
1337 				 * We have failed to atomically swing the
1338 				 * hash table head pointer, presumably because
1339 				 * of a conflicting allocation on another CPU.
1340 				 * We need to reread the hash chain and try
1341 				 * again.
1342 				 */
1343 				goto top;
1344 			}
1345 		}
1346 
1347 		dtrace_membar_producer();
1348 
1349 		/*
1350 		 * Now set the hash value to indicate that it's free.
1351 		 */
1352 		ASSERT(hash[bucket].dtdh_chain != dvar);
1353 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1354 
1355 		dtrace_membar_producer();
1356 
1357 		/*
1358 		 * Set the next pointer to point at the dirty list, and
1359 		 * atomically swing the dirty pointer to the newly freed dvar.
1360 		 */
1361 		do {
1362 			next = dcpu->dtdsc_dirty;
1363 			dvar->dtdv_next = next;
1364 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1365 
1366 		/*
1367 		 * Finally, unlock this hash bucket.
1368 		 */
1369 		ASSERT(hash[bucket].dtdh_lock == lock);
1370 		ASSERT(lock & 1);
1371 		hash[bucket].dtdh_lock++;
1372 
1373 		return (NULL);
1374 next:
1375 		prev = dvar;
1376 		continue;
1377 	}
1378 
1379 	if (dvar == NULL) {
1380 		/*
1381 		 * If dvar is NULL, it is because we went off the rails:
1382 		 * one of the elements that we traversed in the hash chain
1383 		 * was deleted while we were traversing it.  In this case,
1384 		 * we assert that we aren't doing a dealloc (deallocs lock
1385 		 * the hash bucket to prevent themselves from racing with
1386 		 * one another), and retry the hash chain traversal.
1387 		 */
1388 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1389 		goto top;
1390 	}
1391 
1392 	if (op != DTRACE_DYNVAR_ALLOC) {
1393 		/*
1394 		 * If we are not to allocate a new variable, we want to
1395 		 * return NULL now.  Before we return, check that the value
1396 		 * of the lock word hasn't changed.  If it has, we may have
1397 		 * seen an inconsistent snapshot.
1398 		 */
1399 		if (op == DTRACE_DYNVAR_NOALLOC) {
1400 			if (hash[bucket].dtdh_lock != lock)
1401 				goto top;
1402 		} else {
1403 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1404 			ASSERT(hash[bucket].dtdh_lock == lock);
1405 			ASSERT(lock & 1);
1406 			hash[bucket].dtdh_lock++;
1407 		}
1408 
1409 		return (NULL);
1410 	}
1411 
1412 	/*
1413 	 * We need to allocate a new dynamic variable.  The size we need is the
1414 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1415 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1416 	 * the size of any referred-to data (dsize).  We then round the final
1417 	 * size up to the chunksize for allocation.
1418 	 */
1419 	for (ksize = 0, i = 0; i < nkeys; i++)
1420 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1421 
1422 	/*
1423 	 * This should be pretty much impossible, but could happen if, say,
1424 	 * strange DIF specified the tuple.  Ideally, this should be an
1425 	 * assertion and not an error condition -- but that requires that the
1426 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1427 	 * bullet-proof.  (That is, it must not be able to be fooled by
1428 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1429 	 * solving this would presumably not amount to solving the Halting
1430 	 * Problem -- but it still seems awfully hard.
1431 	 */
1432 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1433 	    ksize + dsize > chunksize) {
1434 		dcpu->dtdsc_drops++;
1435 		return (NULL);
1436 	}
1437 
1438 	nstate = DTRACE_DSTATE_EMPTY;
1439 
1440 	do {
1441 retry:
1442 		free = dcpu->dtdsc_free;
1443 
1444 		if (free == NULL) {
1445 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1446 			void *rval;
1447 
1448 			if (clean == NULL) {
1449 				/*
1450 				 * We're out of dynamic variable space on
1451 				 * this CPU.  Unless we have tried all CPUs,
1452 				 * we'll try to allocate from a different
1453 				 * CPU.
1454 				 */
1455 				switch (dstate->dtds_state) {
1456 				case DTRACE_DSTATE_CLEAN: {
1457 					void *sp = &dstate->dtds_state;
1458 
1459 					if (++cpu >= NCPU)
1460 						cpu = 0;
1461 
1462 					if (dcpu->dtdsc_dirty != NULL &&
1463 					    nstate == DTRACE_DSTATE_EMPTY)
1464 						nstate = DTRACE_DSTATE_DIRTY;
1465 
1466 					if (dcpu->dtdsc_rinsing != NULL)
1467 						nstate = DTRACE_DSTATE_RINSING;
1468 
1469 					dcpu = &dstate->dtds_percpu[cpu];
1470 
1471 					if (cpu != me)
1472 						goto retry;
1473 
1474 					(void) dtrace_cas32(sp,
1475 					    DTRACE_DSTATE_CLEAN, nstate);
1476 
1477 					/*
1478 					 * To increment the correct bean
1479 					 * counter, take another lap.
1480 					 */
1481 					goto retry;
1482 				}
1483 
1484 				case DTRACE_DSTATE_DIRTY:
1485 					dcpu->dtdsc_dirty_drops++;
1486 					break;
1487 
1488 				case DTRACE_DSTATE_RINSING:
1489 					dcpu->dtdsc_rinsing_drops++;
1490 					break;
1491 
1492 				case DTRACE_DSTATE_EMPTY:
1493 					dcpu->dtdsc_drops++;
1494 					break;
1495 				}
1496 
1497 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1498 				return (NULL);
1499 			}
1500 
1501 			/*
1502 			 * The clean list appears to be non-empty.  We want to
1503 			 * move the clean list to the free list; we start by
1504 			 * moving the clean pointer aside.
1505 			 */
1506 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1507 			    clean, NULL) != clean) {
1508 				/*
1509 				 * We are in one of two situations:
1510 				 *
1511 				 *  (a)	The clean list was switched to the
1512 				 *	free list by another CPU.
1513 				 *
1514 				 *  (b)	The clean list was added to by the
1515 				 *	cleansing cyclic.
1516 				 *
1517 				 * In either of these situations, we can
1518 				 * just reattempt the free list allocation.
1519 				 */
1520 				goto retry;
1521 			}
1522 
1523 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1524 
1525 			/*
1526 			 * Now we'll move the clean list to the free list.
1527 			 * It's impossible for this to fail:  the only way
1528 			 * the free list can be updated is through this
1529 			 * code path, and only one CPU can own the clean list.
1530 			 * Thus, it would only be possible for this to fail if
1531 			 * this code were racing with dtrace_dynvar_clean().
1532 			 * (That is, if dtrace_dynvar_clean() updated the clean
1533 			 * list, and we ended up racing to update the free
1534 			 * list.)  This race is prevented by the dtrace_sync()
1535 			 * in dtrace_dynvar_clean() -- which flushes the
1536 			 * owners of the clean lists out before resetting
1537 			 * the clean lists.
1538 			 */
1539 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1540 			ASSERT(rval == NULL);
1541 			goto retry;
1542 		}
1543 
1544 		dvar = free;
1545 		new_free = dvar->dtdv_next;
1546 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1547 
1548 	/*
1549 	 * We have now allocated a new chunk.  We copy the tuple keys into the
1550 	 * tuple array and copy any referenced key data into the data space
1551 	 * following the tuple array.  As we do this, we relocate dttk_value
1552 	 * in the final tuple to point to the key data address in the chunk.
1553 	 */
1554 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1555 	dvar->dtdv_data = (void *)(kdata + ksize);
1556 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
1557 
1558 	for (i = 0; i < nkeys; i++) {
1559 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1560 		size_t kesize = key[i].dttk_size;
1561 
1562 		if (kesize != 0) {
1563 			dtrace_bcopy(
1564 			    (const void *)(uintptr_t)key[i].dttk_value,
1565 			    (void *)kdata, kesize);
1566 			dkey->dttk_value = kdata;
1567 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1568 		} else {
1569 			dkey->dttk_value = key[i].dttk_value;
1570 		}
1571 
1572 		dkey->dttk_size = kesize;
1573 	}
1574 
1575 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1576 	dvar->dtdv_hashval = hashval;
1577 	dvar->dtdv_next = start;
1578 
1579 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1580 		return (dvar);
1581 
1582 	/*
1583 	 * The cas has failed.  Either another CPU is adding an element to
1584 	 * this hash chain, or another CPU is deleting an element from this
1585 	 * hash chain.  The simplest way to deal with both of these cases
1586 	 * (though not necessarily the most efficient) is to free our
1587 	 * allocated block and tail-call ourselves.  Note that the free is
1588 	 * to the dirty list and _not_ to the free list.  This is to prevent
1589 	 * races with allocators, above.
1590 	 */
1591 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1592 
1593 	dtrace_membar_producer();
1594 
1595 	do {
1596 		free = dcpu->dtdsc_dirty;
1597 		dvar->dtdv_next = free;
1598 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1599 
1600 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1601 }
1602 
1603 /*ARGSUSED*/
1604 static void
1605 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1606 {
1607 	if (nval < *oval)
1608 		*oval = nval;
1609 }
1610 
1611 /*ARGSUSED*/
1612 static void
1613 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1614 {
1615 	if (nval > *oval)
1616 		*oval = nval;
1617 }
1618 
1619 static void
1620 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1621 {
1622 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1623 	int64_t val = (int64_t)nval;
1624 
1625 	if (val < 0) {
1626 		for (i = 0; i < zero; i++) {
1627 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1628 				quanta[i] += incr;
1629 				return;
1630 			}
1631 		}
1632 	} else {
1633 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1634 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1635 				quanta[i - 1] += incr;
1636 				return;
1637 			}
1638 		}
1639 
1640 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1641 		return;
1642 	}
1643 
1644 	ASSERT(0);
1645 }
1646 
1647 static void
1648 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1649 {
1650 	uint64_t arg = *lquanta++;
1651 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1652 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1653 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1654 	int32_t val = (int32_t)nval, level;
1655 
1656 	ASSERT(step != 0);
1657 	ASSERT(levels != 0);
1658 
1659 	if (val < base) {
1660 		/*
1661 		 * This is an underflow.
1662 		 */
1663 		lquanta[0] += incr;
1664 		return;
1665 	}
1666 
1667 	level = (val - base) / step;
1668 
1669 	if (level < levels) {
1670 		lquanta[level + 1] += incr;
1671 		return;
1672 	}
1673 
1674 	/*
1675 	 * This is an overflow.
1676 	 */
1677 	lquanta[levels + 1] += incr;
1678 }
1679 
1680 /*ARGSUSED*/
1681 static void
1682 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
1683 {
1684 	data[0]++;
1685 	data[1] += nval;
1686 }
1687 
1688 /*ARGSUSED*/
1689 static void
1690 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
1691 {
1692 	*oval = *oval + 1;
1693 }
1694 
1695 /*ARGSUSED*/
1696 static void
1697 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
1698 {
1699 	*oval += nval;
1700 }
1701 
1702 /*
1703  * Aggregate given the tuple in the principal data buffer, and the aggregating
1704  * action denoted by the specified dtrace_aggregation_t.  The aggregation
1705  * buffer is specified as the buf parameter.  This routine does not return
1706  * failure; if there is no space in the aggregation buffer, the data will be
1707  * dropped, and a corresponding counter incremented.
1708  */
1709 static void
1710 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
1711     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
1712 {
1713 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
1714 	uint32_t i, ndx, size, fsize;
1715 	uint32_t align = sizeof (uint64_t) - 1;
1716 	dtrace_aggbuffer_t *agb;
1717 	dtrace_aggkey_t *key;
1718 	uint32_t hashval = 0, limit, isstr;
1719 	caddr_t tomax, data, kdata;
1720 	dtrace_actkind_t action;
1721 	dtrace_action_t *act;
1722 	uintptr_t offs;
1723 
1724 	if (buf == NULL)
1725 		return;
1726 
1727 	if (!agg->dtag_hasarg) {
1728 		/*
1729 		 * Currently, only quantize() and lquantize() take additional
1730 		 * arguments, and they have the same semantics:  an increment
1731 		 * value that defaults to 1 when not present.  If additional
1732 		 * aggregating actions take arguments, the setting of the
1733 		 * default argument value will presumably have to become more
1734 		 * sophisticated...
1735 		 */
1736 		arg = 1;
1737 	}
1738 
1739 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
1740 	size = rec->dtrd_offset - agg->dtag_base;
1741 	fsize = size + rec->dtrd_size;
1742 
1743 	ASSERT(dbuf->dtb_tomax != NULL);
1744 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
1745 
1746 	if ((tomax = buf->dtb_tomax) == NULL) {
1747 		dtrace_buffer_drop(buf);
1748 		return;
1749 	}
1750 
1751 	/*
1752 	 * The metastructure is always at the bottom of the buffer.
1753 	 */
1754 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
1755 	    sizeof (dtrace_aggbuffer_t));
1756 
1757 	if (buf->dtb_offset == 0) {
1758 		/*
1759 		 * We just kludge up approximately 1/8th of the size to be
1760 		 * buckets.  If this guess ends up being routinely
1761 		 * off-the-mark, we may need to dynamically readjust this
1762 		 * based on past performance.
1763 		 */
1764 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
1765 
1766 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
1767 		    (uintptr_t)tomax || hashsize == 0) {
1768 			/*
1769 			 * We've been given a ludicrously small buffer;
1770 			 * increment our drop count and leave.
1771 			 */
1772 			dtrace_buffer_drop(buf);
1773 			return;
1774 		}
1775 
1776 		/*
1777 		 * And now, a pathetic attempt to try to get a an odd (or
1778 		 * perchance, a prime) hash size for better hash distribution.
1779 		 */
1780 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
1781 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
1782 
1783 		agb->dtagb_hashsize = hashsize;
1784 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
1785 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
1786 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
1787 
1788 		for (i = 0; i < agb->dtagb_hashsize; i++)
1789 			agb->dtagb_hash[i] = NULL;
1790 	}
1791 
1792 	ASSERT(agg->dtag_first != NULL);
1793 	ASSERT(agg->dtag_first->dta_intuple);
1794 
1795 	/*
1796 	 * Calculate the hash value based on the key.  Note that we _don't_
1797 	 * include the aggid in the hashing (but we will store it as part of
1798 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
1799 	 * algorithm: a simple, quick algorithm that has no known funnels, and
1800 	 * gets good distribution in practice.  The efficacy of the hashing
1801 	 * algorithm (and a comparison with other algorithms) may be found by
1802 	 * running the ::dtrace_aggstat MDB dcmd.
1803 	 */
1804 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1805 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1806 		limit = i + act->dta_rec.dtrd_size;
1807 		ASSERT(limit <= size);
1808 		isstr = DTRACEACT_ISSTRING(act);
1809 
1810 		for (; i < limit; i++) {
1811 			hashval += data[i];
1812 			hashval += (hashval << 10);
1813 			hashval ^= (hashval >> 6);
1814 
1815 			if (isstr && data[i] == '\0')
1816 				break;
1817 		}
1818 	}
1819 
1820 	hashval += (hashval << 3);
1821 	hashval ^= (hashval >> 11);
1822 	hashval += (hashval << 15);
1823 
1824 	/*
1825 	 * Yes, the divide here is expensive -- but it's generally the least
1826 	 * of the performance issues given the amount of data that we iterate
1827 	 * over to compute hash values, compare data, etc.
1828 	 */
1829 	ndx = hashval % agb->dtagb_hashsize;
1830 
1831 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
1832 		ASSERT((caddr_t)key >= tomax);
1833 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
1834 
1835 		if (hashval != key->dtak_hashval || key->dtak_size != size)
1836 			continue;
1837 
1838 		kdata = key->dtak_data;
1839 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
1840 
1841 		for (act = agg->dtag_first; act->dta_intuple;
1842 		    act = act->dta_next) {
1843 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
1844 			limit = i + act->dta_rec.dtrd_size;
1845 			ASSERT(limit <= size);
1846 			isstr = DTRACEACT_ISSTRING(act);
1847 
1848 			for (; i < limit; i++) {
1849 				if (kdata[i] != data[i])
1850 					goto next;
1851 
1852 				if (isstr && data[i] == '\0')
1853 					break;
1854 			}
1855 		}
1856 
1857 		if (action != key->dtak_action) {
1858 			/*
1859 			 * We are aggregating on the same value in the same
1860 			 * aggregation with two different aggregating actions.
1861 			 * (This should have been picked up in the compiler,
1862 			 * so we may be dealing with errant or devious DIF.)
1863 			 * This is an error condition; we indicate as much,
1864 			 * and return.
1865 			 */
1866 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
1867 			return;
1868 		}
1869 
1870 		/*
1871 		 * This is a hit:  we need to apply the aggregator to
1872 		 * the value at this key.
1873 		 */
1874 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
1875 		return;
1876 next:
1877 		continue;
1878 	}
1879 
1880 	/*
1881 	 * We didn't find it.  We need to allocate some zero-filled space,
1882 	 * link it into the hash table appropriately, and apply the aggregator
1883 	 * to the (zero-filled) value.
1884 	 */
1885 	offs = buf->dtb_offset;
1886 	while (offs & (align - 1))
1887 		offs += sizeof (uint32_t);
1888 
1889 	/*
1890 	 * If we don't have enough room to both allocate a new key _and_
1891 	 * its associated data, increment the drop count and return.
1892 	 */
1893 	if ((uintptr_t)tomax + offs + fsize >
1894 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
1895 		dtrace_buffer_drop(buf);
1896 		return;
1897 	}
1898 
1899 	/*CONSTCOND*/
1900 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
1901 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
1902 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
1903 
1904 	key->dtak_data = kdata = tomax + offs;
1905 	buf->dtb_offset = offs + fsize;
1906 
1907 	/*
1908 	 * Now copy the data across.
1909 	 */
1910 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
1911 
1912 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
1913 		kdata[i] = data[i];
1914 
1915 	/*
1916 	 * Because strings are not zeroed out by default, we need to iterate
1917 	 * looking for actions that store strings, and we need to explicitly
1918 	 * pad these strings out with zeroes.
1919 	 */
1920 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1921 		int nul;
1922 
1923 		if (!DTRACEACT_ISSTRING(act))
1924 			continue;
1925 
1926 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1927 		limit = i + act->dta_rec.dtrd_size;
1928 		ASSERT(limit <= size);
1929 
1930 		for (nul = 0; i < limit; i++) {
1931 			if (nul) {
1932 				kdata[i] = '\0';
1933 				continue;
1934 			}
1935 
1936 			if (data[i] != '\0')
1937 				continue;
1938 
1939 			nul = 1;
1940 		}
1941 	}
1942 
1943 	for (i = size; i < fsize; i++)
1944 		kdata[i] = 0;
1945 
1946 	key->dtak_hashval = hashval;
1947 	key->dtak_size = size;
1948 	key->dtak_action = action;
1949 	key->dtak_next = agb->dtagb_hash[ndx];
1950 	agb->dtagb_hash[ndx] = key;
1951 
1952 	/*
1953 	 * Finally, apply the aggregator.
1954 	 */
1955 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
1956 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
1957 }
1958 
1959 /*
1960  * Given consumer state, this routine finds a speculation in the INACTIVE
1961  * state and transitions it into the ACTIVE state.  If there is no speculation
1962  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
1963  * incremented -- it is up to the caller to take appropriate action.
1964  */
1965 static int
1966 dtrace_speculation(dtrace_state_t *state)
1967 {
1968 	int i = 0;
1969 	dtrace_speculation_state_t current;
1970 	uint32_t *stat = &state->dts_speculations_unavail, count;
1971 
1972 	while (i < state->dts_nspeculations) {
1973 		dtrace_speculation_t *spec = &state->dts_speculations[i];
1974 
1975 		current = spec->dtsp_state;
1976 
1977 		if (current != DTRACESPEC_INACTIVE) {
1978 			if (current == DTRACESPEC_COMMITTINGMANY ||
1979 			    current == DTRACESPEC_COMMITTING ||
1980 			    current == DTRACESPEC_DISCARDING)
1981 				stat = &state->dts_speculations_busy;
1982 			i++;
1983 			continue;
1984 		}
1985 
1986 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
1987 		    current, DTRACESPEC_ACTIVE) == current)
1988 			return (i + 1);
1989 	}
1990 
1991 	/*
1992 	 * We couldn't find a speculation.  If we found as much as a single
1993 	 * busy speculation buffer, we'll attribute this failure as "busy"
1994 	 * instead of "unavail".
1995 	 */
1996 	do {
1997 		count = *stat;
1998 	} while (dtrace_cas32(stat, count, count + 1) != count);
1999 
2000 	return (0);
2001 }
2002 
2003 /*
2004  * This routine commits an active speculation.  If the specified speculation
2005  * is not in a valid state to perform a commit(), this routine will silently do
2006  * nothing.  The state of the specified speculation is transitioned according
2007  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2008  */
2009 static void
2010 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2011     dtrace_specid_t which)
2012 {
2013 	dtrace_speculation_t *spec;
2014 	dtrace_buffer_t *src, *dest;
2015 	uintptr_t daddr, saddr, dlimit;
2016 	dtrace_speculation_state_t current, new;
2017 	intptr_t offs;
2018 
2019 	if (which == 0)
2020 		return;
2021 
2022 	if (which > state->dts_nspeculations) {
2023 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2024 		return;
2025 	}
2026 
2027 	spec = &state->dts_speculations[which - 1];
2028 	src = &spec->dtsp_buffer[cpu];
2029 	dest = &state->dts_buffer[cpu];
2030 
2031 	do {
2032 		current = spec->dtsp_state;
2033 
2034 		if (current == DTRACESPEC_COMMITTINGMANY)
2035 			break;
2036 
2037 		switch (current) {
2038 		case DTRACESPEC_INACTIVE:
2039 		case DTRACESPEC_DISCARDING:
2040 			return;
2041 
2042 		case DTRACESPEC_COMMITTING:
2043 			/*
2044 			 * This is only possible if we are (a) commit()'ing
2045 			 * without having done a prior speculate() on this CPU
2046 			 * and (b) racing with another commit() on a different
2047 			 * CPU.  There's nothing to do -- we just assert that
2048 			 * our offset is 0.
2049 			 */
2050 			ASSERT(src->dtb_offset == 0);
2051 			return;
2052 
2053 		case DTRACESPEC_ACTIVE:
2054 			new = DTRACESPEC_COMMITTING;
2055 			break;
2056 
2057 		case DTRACESPEC_ACTIVEONE:
2058 			/*
2059 			 * This speculation is active on one CPU.  If our
2060 			 * buffer offset is non-zero, we know that the one CPU
2061 			 * must be us.  Otherwise, we are committing on a
2062 			 * different CPU from the speculate(), and we must
2063 			 * rely on being asynchronously cleaned.
2064 			 */
2065 			if (src->dtb_offset != 0) {
2066 				new = DTRACESPEC_COMMITTING;
2067 				break;
2068 			}
2069 			/*FALLTHROUGH*/
2070 
2071 		case DTRACESPEC_ACTIVEMANY:
2072 			new = DTRACESPEC_COMMITTINGMANY;
2073 			break;
2074 
2075 		default:
2076 			ASSERT(0);
2077 		}
2078 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2079 	    current, new) != current);
2080 
2081 	/*
2082 	 * We have set the state to indicate that we are committing this
2083 	 * speculation.  Now reserve the necessary space in the destination
2084 	 * buffer.
2085 	 */
2086 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2087 	    sizeof (uint64_t), state, NULL)) < 0) {
2088 		dtrace_buffer_drop(dest);
2089 		goto out;
2090 	}
2091 
2092 	/*
2093 	 * We have the space; copy the buffer across.  (Note that this is a
2094 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2095 	 * a serious performance issue, a high-performance DTrace-specific
2096 	 * bcopy() should obviously be invented.)
2097 	 */
2098 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2099 	dlimit = daddr + src->dtb_offset;
2100 	saddr = (uintptr_t)src->dtb_tomax;
2101 
2102 	/*
2103 	 * First, the aligned portion.
2104 	 */
2105 	while (dlimit - daddr >= sizeof (uint64_t)) {
2106 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2107 
2108 		daddr += sizeof (uint64_t);
2109 		saddr += sizeof (uint64_t);
2110 	}
2111 
2112 	/*
2113 	 * Now any left-over bit...
2114 	 */
2115 	while (dlimit - daddr)
2116 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2117 
2118 	/*
2119 	 * Finally, commit the reserved space in the destination buffer.
2120 	 */
2121 	dest->dtb_offset = offs + src->dtb_offset;
2122 
2123 out:
2124 	/*
2125 	 * If we're lucky enough to be the only active CPU on this speculation
2126 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2127 	 */
2128 	if (current == DTRACESPEC_ACTIVE ||
2129 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2130 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2131 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2132 
2133 		ASSERT(rval == DTRACESPEC_COMMITTING);
2134 	}
2135 
2136 	src->dtb_offset = 0;
2137 	src->dtb_xamot_drops += src->dtb_drops;
2138 	src->dtb_drops = 0;
2139 }
2140 
2141 /*
2142  * This routine discards an active speculation.  If the specified speculation
2143  * is not in a valid state to perform a discard(), this routine will silently
2144  * do nothing.  The state of the specified speculation is transitioned
2145  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2146  */
2147 static void
2148 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2149     dtrace_specid_t which)
2150 {
2151 	dtrace_speculation_t *spec;
2152 	dtrace_speculation_state_t current, new;
2153 	dtrace_buffer_t *buf;
2154 
2155 	if (which == 0)
2156 		return;
2157 
2158 	if (which > state->dts_nspeculations) {
2159 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2160 		return;
2161 	}
2162 
2163 	spec = &state->dts_speculations[which - 1];
2164 	buf = &spec->dtsp_buffer[cpu];
2165 
2166 	do {
2167 		current = spec->dtsp_state;
2168 
2169 		switch (current) {
2170 		case DTRACESPEC_INACTIVE:
2171 		case DTRACESPEC_COMMITTINGMANY:
2172 		case DTRACESPEC_COMMITTING:
2173 		case DTRACESPEC_DISCARDING:
2174 			return;
2175 
2176 		case DTRACESPEC_ACTIVE:
2177 		case DTRACESPEC_ACTIVEMANY:
2178 			new = DTRACESPEC_DISCARDING;
2179 			break;
2180 
2181 		case DTRACESPEC_ACTIVEONE:
2182 			if (buf->dtb_offset != 0) {
2183 				new = DTRACESPEC_INACTIVE;
2184 			} else {
2185 				new = DTRACESPEC_DISCARDING;
2186 			}
2187 			break;
2188 
2189 		default:
2190 			ASSERT(0);
2191 		}
2192 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2193 	    current, new) != current);
2194 
2195 	buf->dtb_offset = 0;
2196 	buf->dtb_drops = 0;
2197 }
2198 
2199 /*
2200  * Note:  not called from probe context.  This function is called
2201  * asynchronously from cross call context to clean any speculations that are
2202  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2203  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2204  * speculation.
2205  */
2206 static void
2207 dtrace_speculation_clean_here(dtrace_state_t *state)
2208 {
2209 	dtrace_icookie_t cookie;
2210 	processorid_t cpu = CPU->cpu_id;
2211 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2212 	dtrace_specid_t i;
2213 
2214 	cookie = dtrace_interrupt_disable();
2215 
2216 	if (dest->dtb_tomax == NULL) {
2217 		dtrace_interrupt_enable(cookie);
2218 		return;
2219 	}
2220 
2221 	for (i = 0; i < state->dts_nspeculations; i++) {
2222 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2223 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2224 
2225 		if (src->dtb_tomax == NULL)
2226 			continue;
2227 
2228 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2229 			src->dtb_offset = 0;
2230 			continue;
2231 		}
2232 
2233 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2234 			continue;
2235 
2236 		if (src->dtb_offset == 0)
2237 			continue;
2238 
2239 		dtrace_speculation_commit(state, cpu, i + 1);
2240 	}
2241 
2242 	dtrace_interrupt_enable(cookie);
2243 }
2244 
2245 /*
2246  * Note:  not called from probe context.  This function is called
2247  * asynchronously (and at a regular interval) to clean any speculations that
2248  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2249  * is work to be done, it cross calls all CPUs to perform that work;
2250  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2251  * INACTIVE state until they have been cleaned by all CPUs.
2252  */
2253 static void
2254 dtrace_speculation_clean(dtrace_state_t *state)
2255 {
2256 	int work = 0, rv;
2257 	dtrace_specid_t i;
2258 
2259 	for (i = 0; i < state->dts_nspeculations; i++) {
2260 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2261 
2262 		ASSERT(!spec->dtsp_cleaning);
2263 
2264 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2265 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2266 			continue;
2267 
2268 		work++;
2269 		spec->dtsp_cleaning = 1;
2270 	}
2271 
2272 	if (!work)
2273 		return;
2274 
2275 	dtrace_xcall(DTRACE_CPUALL,
2276 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2277 
2278 	/*
2279 	 * We now know that all CPUs have committed or discarded their
2280 	 * speculation buffers, as appropriate.  We can now set the state
2281 	 * to inactive.
2282 	 */
2283 	for (i = 0; i < state->dts_nspeculations; i++) {
2284 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2285 		dtrace_speculation_state_t current, new;
2286 
2287 		if (!spec->dtsp_cleaning)
2288 			continue;
2289 
2290 		current = spec->dtsp_state;
2291 		ASSERT(current == DTRACESPEC_DISCARDING ||
2292 		    current == DTRACESPEC_COMMITTINGMANY);
2293 
2294 		new = DTRACESPEC_INACTIVE;
2295 
2296 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2297 		ASSERT(rv == current);
2298 		spec->dtsp_cleaning = 0;
2299 	}
2300 }
2301 
2302 /*
2303  * Called as part of a speculate() to get the speculative buffer associated
2304  * with a given speculation.  Returns NULL if the specified speculation is not
2305  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2306  * the active CPU is not the specified CPU -- the speculation will be
2307  * atomically transitioned into the ACTIVEMANY state.
2308  */
2309 static dtrace_buffer_t *
2310 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2311     dtrace_specid_t which)
2312 {
2313 	dtrace_speculation_t *spec;
2314 	dtrace_speculation_state_t current, new;
2315 	dtrace_buffer_t *buf;
2316 
2317 	if (which == 0)
2318 		return (NULL);
2319 
2320 	if (which > state->dts_nspeculations) {
2321 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2322 		return (NULL);
2323 	}
2324 
2325 	spec = &state->dts_speculations[which - 1];
2326 	buf = &spec->dtsp_buffer[cpuid];
2327 
2328 	do {
2329 		current = spec->dtsp_state;
2330 
2331 		switch (current) {
2332 		case DTRACESPEC_INACTIVE:
2333 		case DTRACESPEC_COMMITTINGMANY:
2334 		case DTRACESPEC_DISCARDING:
2335 			return (NULL);
2336 
2337 		case DTRACESPEC_COMMITTING:
2338 			ASSERT(buf->dtb_offset == 0);
2339 			return (NULL);
2340 
2341 		case DTRACESPEC_ACTIVEONE:
2342 			/*
2343 			 * This speculation is currently active on one CPU.
2344 			 * Check the offset in the buffer; if it's non-zero,
2345 			 * that CPU must be us (and we leave the state alone).
2346 			 * If it's zero, assume that we're starting on a new
2347 			 * CPU -- and change the state to indicate that the
2348 			 * speculation is active on more than one CPU.
2349 			 */
2350 			if (buf->dtb_offset != 0)
2351 				return (buf);
2352 
2353 			new = DTRACESPEC_ACTIVEMANY;
2354 			break;
2355 
2356 		case DTRACESPEC_ACTIVEMANY:
2357 			return (buf);
2358 
2359 		case DTRACESPEC_ACTIVE:
2360 			new = DTRACESPEC_ACTIVEONE;
2361 			break;
2362 
2363 		default:
2364 			ASSERT(0);
2365 		}
2366 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2367 	    current, new) != current);
2368 
2369 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2370 	return (buf);
2371 }
2372 
2373 /*
2374  * Return a string.  In the event that the user lacks the privilege to access
2375  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2376  * don't fail access checking.
2377  *
2378  * dtrace_dif_variable() uses this routine as a helper for various
2379  * builtin values such as 'execname' and 'probefunc.'
2380  */
2381 uintptr_t
2382 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2383     dtrace_mstate_t *mstate)
2384 {
2385 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2386 	uintptr_t ret;
2387 	size_t strsz;
2388 
2389 	/*
2390 	 * The easy case: this probe is allowed to read all of memory, so
2391 	 * we can just return this as a vanilla pointer.
2392 	 */
2393 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2394 		return (addr);
2395 
2396 	/*
2397 	 * This is the tougher case: we copy the string in question from
2398 	 * kernel memory into scratch memory and return it that way: this
2399 	 * ensures that we won't trip up when access checking tests the
2400 	 * BYREF return value.
2401 	 */
2402 	strsz = dtrace_strlen((char *)addr, size) + 1;
2403 
2404 	if (mstate->dtms_scratch_ptr + strsz >
2405 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2406 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2407 		return (NULL);
2408 	}
2409 
2410 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2411 	    strsz);
2412 	ret = mstate->dtms_scratch_ptr;
2413 	mstate->dtms_scratch_ptr += strsz;
2414 	return (ret);
2415 }
2416 
2417 /*
2418  * This function implements the DIF emulator's variable lookups.  The emulator
2419  * passes a reserved variable identifier and optional built-in array index.
2420  */
2421 static uint64_t
2422 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2423     uint64_t ndx)
2424 {
2425 	/*
2426 	 * If we're accessing one of the uncached arguments, we'll turn this
2427 	 * into a reference in the args array.
2428 	 */
2429 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2430 		ndx = v - DIF_VAR_ARG0;
2431 		v = DIF_VAR_ARGS;
2432 	}
2433 
2434 	switch (v) {
2435 	case DIF_VAR_ARGS:
2436 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2437 		if (ndx >= sizeof (mstate->dtms_arg) /
2438 		    sizeof (mstate->dtms_arg[0])) {
2439 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2440 			dtrace_provider_t *pv;
2441 			uint64_t val;
2442 
2443 			pv = mstate->dtms_probe->dtpr_provider;
2444 			if (pv->dtpv_pops.dtps_getargval != NULL)
2445 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2446 				    mstate->dtms_probe->dtpr_id,
2447 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
2448 			else
2449 				val = dtrace_getarg(ndx, aframes);
2450 
2451 			/*
2452 			 * This is regrettably required to keep the compiler
2453 			 * from tail-optimizing the call to dtrace_getarg().
2454 			 * The condition always evaluates to true, but the
2455 			 * compiler has no way of figuring that out a priori.
2456 			 * (None of this would be necessary if the compiler
2457 			 * could be relied upon to _always_ tail-optimize
2458 			 * the call to dtrace_getarg() -- but it can't.)
2459 			 */
2460 			if (mstate->dtms_probe != NULL)
2461 				return (val);
2462 
2463 			ASSERT(0);
2464 		}
2465 
2466 		return (mstate->dtms_arg[ndx]);
2467 
2468 	case DIF_VAR_UREGS: {
2469 		klwp_t *lwp;
2470 
2471 		if (!dtrace_priv_proc(state))
2472 			return (0);
2473 
2474 		if ((lwp = curthread->t_lwp) == NULL) {
2475 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2476 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
2477 			return (0);
2478 		}
2479 
2480 		return (dtrace_getreg(lwp->lwp_regs, ndx));
2481 	}
2482 
2483 	case DIF_VAR_CURTHREAD:
2484 		if (!dtrace_priv_kernel(state))
2485 			return (0);
2486 		return ((uint64_t)(uintptr_t)curthread);
2487 
2488 	case DIF_VAR_TIMESTAMP:
2489 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2490 			mstate->dtms_timestamp = dtrace_gethrtime();
2491 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2492 		}
2493 		return (mstate->dtms_timestamp);
2494 
2495 	case DIF_VAR_VTIMESTAMP:
2496 		ASSERT(dtrace_vtime_references != 0);
2497 		return (curthread->t_dtrace_vtime);
2498 
2499 	case DIF_VAR_WALLTIMESTAMP:
2500 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2501 			mstate->dtms_walltimestamp = dtrace_gethrestime();
2502 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2503 		}
2504 		return (mstate->dtms_walltimestamp);
2505 
2506 	case DIF_VAR_IPL:
2507 		if (!dtrace_priv_kernel(state))
2508 			return (0);
2509 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2510 			mstate->dtms_ipl = dtrace_getipl();
2511 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
2512 		}
2513 		return (mstate->dtms_ipl);
2514 
2515 	case DIF_VAR_EPID:
2516 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2517 		return (mstate->dtms_epid);
2518 
2519 	case DIF_VAR_ID:
2520 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2521 		return (mstate->dtms_probe->dtpr_id);
2522 
2523 	case DIF_VAR_STACKDEPTH:
2524 		if (!dtrace_priv_kernel(state))
2525 			return (0);
2526 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2527 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2528 
2529 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2530 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2531 		}
2532 		return (mstate->dtms_stackdepth);
2533 
2534 	case DIF_VAR_USTACKDEPTH:
2535 		if (!dtrace_priv_proc(state))
2536 			return (0);
2537 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2538 			/*
2539 			 * See comment in DIF_VAR_PID.
2540 			 */
2541 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2542 			    CPU_ON_INTR(CPU)) {
2543 				mstate->dtms_ustackdepth = 0;
2544 			} else {
2545 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2546 				mstate->dtms_ustackdepth =
2547 				    dtrace_getustackdepth();
2548 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2549 			}
2550 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2551 		}
2552 		return (mstate->dtms_ustackdepth);
2553 
2554 	case DIF_VAR_CALLER:
2555 		if (!dtrace_priv_kernel(state))
2556 			return (0);
2557 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2558 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2559 
2560 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2561 				/*
2562 				 * If this is an unanchored probe, we are
2563 				 * required to go through the slow path:
2564 				 * dtrace_caller() only guarantees correct
2565 				 * results for anchored probes.
2566 				 */
2567 				pc_t caller[2];
2568 
2569 				dtrace_getpcstack(caller, 2, aframes,
2570 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2571 				mstate->dtms_caller = caller[1];
2572 			} else if ((mstate->dtms_caller =
2573 			    dtrace_caller(aframes)) == -1) {
2574 				/*
2575 				 * We have failed to do this the quick way;
2576 				 * we must resort to the slower approach of
2577 				 * calling dtrace_getpcstack().
2578 				 */
2579 				pc_t caller;
2580 
2581 				dtrace_getpcstack(&caller, 1, aframes, NULL);
2582 				mstate->dtms_caller = caller;
2583 			}
2584 
2585 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
2586 		}
2587 		return (mstate->dtms_caller);
2588 
2589 	case DIF_VAR_UCALLER:
2590 		if (!dtrace_priv_proc(state))
2591 			return (0);
2592 
2593 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
2594 			uint64_t ustack[3];
2595 
2596 			/*
2597 			 * dtrace_getupcstack() fills in the first uint64_t
2598 			 * with the current PID.  The second uint64_t will
2599 			 * be the program counter at user-level.  The third
2600 			 * uint64_t will contain the caller, which is what
2601 			 * we're after.
2602 			 */
2603 			ustack[2] = NULL;
2604 			dtrace_getupcstack(ustack, 3);
2605 			mstate->dtms_ucaller = ustack[2];
2606 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
2607 		}
2608 
2609 		return (mstate->dtms_ucaller);
2610 
2611 	case DIF_VAR_PROBEPROV:
2612 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2613 		return (dtrace_dif_varstr(
2614 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
2615 		    state, mstate));
2616 
2617 	case DIF_VAR_PROBEMOD:
2618 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2619 		return (dtrace_dif_varstr(
2620 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
2621 		    state, mstate));
2622 
2623 	case DIF_VAR_PROBEFUNC:
2624 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2625 		return (dtrace_dif_varstr(
2626 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
2627 		    state, mstate));
2628 
2629 	case DIF_VAR_PROBENAME:
2630 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2631 		return (dtrace_dif_varstr(
2632 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
2633 		    state, mstate));
2634 
2635 	case DIF_VAR_PID:
2636 		if (!dtrace_priv_proc(state))
2637 			return (0);
2638 
2639 		/*
2640 		 * Note that we are assuming that an unanchored probe is
2641 		 * always due to a high-level interrupt.  (And we're assuming
2642 		 * that there is only a single high level interrupt.)
2643 		 */
2644 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2645 			return (pid0.pid_id);
2646 
2647 		/*
2648 		 * It is always safe to dereference one's own t_procp pointer:
2649 		 * it always points to a valid, allocated proc structure.
2650 		 * Further, it is always safe to dereference the p_pidp member
2651 		 * of one's own proc structure.  (These are truisms becuase
2652 		 * threads and processes don't clean up their own state --
2653 		 * they leave that task to whomever reaps them.)
2654 		 */
2655 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
2656 
2657 	case DIF_VAR_PPID:
2658 		if (!dtrace_priv_proc(state))
2659 			return (0);
2660 
2661 		/*
2662 		 * See comment in DIF_VAR_PID.
2663 		 */
2664 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2665 			return (pid0.pid_id);
2666 
2667 		/*
2668 		 * It is always safe to dereference one's own t_procp pointer:
2669 		 * it always points to a valid, allocated proc structure.
2670 		 * (This is true because threads don't clean up their own
2671 		 * state -- they leave that task to whomever reaps them.)
2672 		 */
2673 		return ((uint64_t)curthread->t_procp->p_ppid);
2674 
2675 	case DIF_VAR_TID:
2676 		/*
2677 		 * See comment in DIF_VAR_PID.
2678 		 */
2679 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2680 			return (0);
2681 
2682 		return ((uint64_t)curthread->t_tid);
2683 
2684 	case DIF_VAR_EXECNAME:
2685 		if (!dtrace_priv_proc(state))
2686 			return (0);
2687 
2688 		/*
2689 		 * See comment in DIF_VAR_PID.
2690 		 */
2691 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2692 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
2693 
2694 		/*
2695 		 * It is always safe to dereference one's own t_procp pointer:
2696 		 * it always points to a valid, allocated proc structure.
2697 		 * (This is true because threads don't clean up their own
2698 		 * state -- they leave that task to whomever reaps them.)
2699 		 */
2700 		return (dtrace_dif_varstr(
2701 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
2702 		    state, mstate));
2703 
2704 	case DIF_VAR_ZONENAME:
2705 		if (!dtrace_priv_proc(state))
2706 			return (0);
2707 
2708 		/*
2709 		 * See comment in DIF_VAR_PID.
2710 		 */
2711 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2712 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
2713 
2714 		/*
2715 		 * It is always safe to dereference one's own t_procp pointer:
2716 		 * it always points to a valid, allocated proc structure.
2717 		 * (This is true because threads don't clean up their own
2718 		 * state -- they leave that task to whomever reaps them.)
2719 		 */
2720 		return (dtrace_dif_varstr(
2721 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
2722 		    state, mstate));
2723 
2724 	case DIF_VAR_UID:
2725 		if (!dtrace_priv_proc(state))
2726 			return (0);
2727 
2728 		/*
2729 		 * See comment in DIF_VAR_PID.
2730 		 */
2731 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2732 			return ((uint64_t)p0.p_cred->cr_uid);
2733 
2734 		/*
2735 		 * It is always safe to dereference one's own t_procp pointer:
2736 		 * it always points to a valid, allocated proc structure.
2737 		 * (This is true because threads don't clean up their own
2738 		 * state -- they leave that task to whomever reaps them.)
2739 		 *
2740 		 * Additionally, it is safe to dereference one's own process
2741 		 * credential, since this is never NULL after process birth.
2742 		 */
2743 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
2744 
2745 	case DIF_VAR_GID:
2746 		if (!dtrace_priv_proc(state))
2747 			return (0);
2748 
2749 		/*
2750 		 * See comment in DIF_VAR_PID.
2751 		 */
2752 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2753 			return ((uint64_t)p0.p_cred->cr_gid);
2754 
2755 		/*
2756 		 * It is always safe to dereference one's own t_procp pointer:
2757 		 * it always points to a valid, allocated proc structure.
2758 		 * (This is true because threads don't clean up their own
2759 		 * state -- they leave that task to whomever reaps them.)
2760 		 *
2761 		 * Additionally, it is safe to dereference one's own process
2762 		 * credential, since this is never NULL after process birth.
2763 		 */
2764 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
2765 
2766 	case DIF_VAR_ERRNO: {
2767 		klwp_t *lwp;
2768 		if (!dtrace_priv_proc(state))
2769 			return (0);
2770 
2771 		/*
2772 		 * See comment in DIF_VAR_PID.
2773 		 */
2774 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2775 			return (0);
2776 
2777 		/*
2778 		 * It is always safe to dereference one's own t_lwp pointer in
2779 		 * the event that this pointer is non-NULL.  (This is true
2780 		 * because threads and lwps don't clean up their own state --
2781 		 * they leave that task to whomever reaps them.)
2782 		 */
2783 		if ((lwp = curthread->t_lwp) == NULL)
2784 			return (0);
2785 
2786 		return ((uint64_t)lwp->lwp_errno);
2787 	}
2788 	default:
2789 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2790 		return (0);
2791 	}
2792 }
2793 
2794 /*
2795  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
2796  * Notice that we don't bother validating the proper number of arguments or
2797  * their types in the tuple stack.  This isn't needed because all argument
2798  * interpretation is safe because of our load safety -- the worst that can
2799  * happen is that a bogus program can obtain bogus results.
2800  */
2801 static void
2802 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
2803     dtrace_key_t *tupregs, int nargs,
2804     dtrace_mstate_t *mstate, dtrace_state_t *state)
2805 {
2806 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
2807 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
2808 	dtrace_vstate_t *vstate = &state->dts_vstate;
2809 
2810 	union {
2811 		mutex_impl_t mi;
2812 		uint64_t mx;
2813 	} m;
2814 
2815 	union {
2816 		krwlock_t ri;
2817 		uintptr_t rw;
2818 	} r;
2819 
2820 	switch (subr) {
2821 	case DIF_SUBR_RAND:
2822 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
2823 		break;
2824 
2825 	case DIF_SUBR_MUTEX_OWNED:
2826 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2827 		    mstate, vstate)) {
2828 			regs[rd] = NULL;
2829 			break;
2830 		}
2831 
2832 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2833 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
2834 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
2835 		else
2836 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
2837 		break;
2838 
2839 	case DIF_SUBR_MUTEX_OWNER:
2840 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2841 		    mstate, vstate)) {
2842 			regs[rd] = NULL;
2843 			break;
2844 		}
2845 
2846 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2847 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
2848 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
2849 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
2850 		else
2851 			regs[rd] = 0;
2852 		break;
2853 
2854 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
2855 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2856 		    mstate, vstate)) {
2857 			regs[rd] = NULL;
2858 			break;
2859 		}
2860 
2861 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2862 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
2863 		break;
2864 
2865 	case DIF_SUBR_MUTEX_TYPE_SPIN:
2866 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2867 		    mstate, vstate)) {
2868 			regs[rd] = NULL;
2869 			break;
2870 		}
2871 
2872 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2873 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
2874 		break;
2875 
2876 	case DIF_SUBR_RW_READ_HELD: {
2877 		uintptr_t tmp;
2878 
2879 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
2880 		    mstate, vstate)) {
2881 			regs[rd] = NULL;
2882 			break;
2883 		}
2884 
2885 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2886 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
2887 		break;
2888 	}
2889 
2890 	case DIF_SUBR_RW_WRITE_HELD:
2891 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
2892 		    mstate, vstate)) {
2893 			regs[rd] = NULL;
2894 			break;
2895 		}
2896 
2897 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2898 		regs[rd] = _RW_WRITE_HELD(&r.ri);
2899 		break;
2900 
2901 	case DIF_SUBR_RW_ISWRITER:
2902 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
2903 		    mstate, vstate)) {
2904 			regs[rd] = NULL;
2905 			break;
2906 		}
2907 
2908 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2909 		regs[rd] = _RW_ISWRITER(&r.ri);
2910 		break;
2911 
2912 	case DIF_SUBR_BCOPY: {
2913 		/*
2914 		 * We need to be sure that the destination is in the scratch
2915 		 * region -- no other region is allowed.
2916 		 */
2917 		uintptr_t src = tupregs[0].dttk_value;
2918 		uintptr_t dest = tupregs[1].dttk_value;
2919 		size_t size = tupregs[2].dttk_value;
2920 
2921 		if (!dtrace_inscratch(dest, size, mstate)) {
2922 			*flags |= CPU_DTRACE_BADADDR;
2923 			*illval = regs[rd];
2924 			break;
2925 		}
2926 
2927 		if (!dtrace_canload(src, size, mstate, vstate)) {
2928 			regs[rd] = NULL;
2929 			break;
2930 		}
2931 
2932 		dtrace_bcopy((void *)src, (void *)dest, size);
2933 		break;
2934 	}
2935 
2936 	case DIF_SUBR_ALLOCA:
2937 	case DIF_SUBR_COPYIN: {
2938 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
2939 		uint64_t size =
2940 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
2941 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
2942 
2943 		/*
2944 		 * This action doesn't require any credential checks since
2945 		 * probes will not activate in user contexts to which the
2946 		 * enabling user does not have permissions.
2947 		 */
2948 
2949 		/*
2950 		 * Rounding up the user allocation size could have overflowed
2951 		 * a large, bogus allocation (like -1ULL) to 0.
2952 		 */
2953 		if (scratch_size < size ||
2954 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
2955 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2956 			regs[rd] = NULL;
2957 			break;
2958 		}
2959 
2960 		if (subr == DIF_SUBR_COPYIN) {
2961 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2962 			dtrace_copyin(tupregs[0].dttk_value, dest, size);
2963 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2964 		}
2965 
2966 		mstate->dtms_scratch_ptr += scratch_size;
2967 		regs[rd] = dest;
2968 		break;
2969 	}
2970 
2971 	case DIF_SUBR_COPYINTO: {
2972 		uint64_t size = tupregs[1].dttk_value;
2973 		uintptr_t dest = tupregs[2].dttk_value;
2974 
2975 		/*
2976 		 * This action doesn't require any credential checks since
2977 		 * probes will not activate in user contexts to which the
2978 		 * enabling user does not have permissions.
2979 		 */
2980 		if (!dtrace_inscratch(dest, size, mstate)) {
2981 			*flags |= CPU_DTRACE_BADADDR;
2982 			*illval = regs[rd];
2983 			break;
2984 		}
2985 
2986 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2987 		dtrace_copyin(tupregs[0].dttk_value, dest, size);
2988 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2989 		break;
2990 	}
2991 
2992 	case DIF_SUBR_COPYINSTR: {
2993 		uintptr_t dest = mstate->dtms_scratch_ptr;
2994 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2995 
2996 		if (nargs > 1 && tupregs[1].dttk_value < size)
2997 			size = tupregs[1].dttk_value + 1;
2998 
2999 		/*
3000 		 * This action doesn't require any credential checks since
3001 		 * probes will not activate in user contexts to which the
3002 		 * enabling user does not have permissions.
3003 		 */
3004 		if (!DTRACE_INSCRATCH(mstate, size)) {
3005 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3006 			regs[rd] = NULL;
3007 			break;
3008 		}
3009 
3010 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3011 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size);
3012 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3013 
3014 		((char *)dest)[size - 1] = '\0';
3015 		mstate->dtms_scratch_ptr += size;
3016 		regs[rd] = dest;
3017 		break;
3018 	}
3019 
3020 	case DIF_SUBR_MSGSIZE:
3021 	case DIF_SUBR_MSGDSIZE: {
3022 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
3023 		uintptr_t wptr, rptr;
3024 		size_t count = 0;
3025 		int cont = 0;
3026 
3027 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3028 
3029 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3030 			    vstate)) {
3031 				regs[rd] = NULL;
3032 				break;
3033 			}
3034 
3035 			wptr = dtrace_loadptr(baddr +
3036 			    offsetof(mblk_t, b_wptr));
3037 
3038 			rptr = dtrace_loadptr(baddr +
3039 			    offsetof(mblk_t, b_rptr));
3040 
3041 			if (wptr < rptr) {
3042 				*flags |= CPU_DTRACE_BADADDR;
3043 				*illval = tupregs[0].dttk_value;
3044 				break;
3045 			}
3046 
3047 			daddr = dtrace_loadptr(baddr +
3048 			    offsetof(mblk_t, b_datap));
3049 
3050 			baddr = dtrace_loadptr(baddr +
3051 			    offsetof(mblk_t, b_cont));
3052 
3053 			/*
3054 			 * We want to prevent against denial-of-service here,
3055 			 * so we're only going to search the list for
3056 			 * dtrace_msgdsize_max mblks.
3057 			 */
3058 			if (cont++ > dtrace_msgdsize_max) {
3059 				*flags |= CPU_DTRACE_ILLOP;
3060 				break;
3061 			}
3062 
3063 			if (subr == DIF_SUBR_MSGDSIZE) {
3064 				if (dtrace_load8(daddr +
3065 				    offsetof(dblk_t, db_type)) != M_DATA)
3066 					continue;
3067 			}
3068 
3069 			count += wptr - rptr;
3070 		}
3071 
3072 		if (!(*flags & CPU_DTRACE_FAULT))
3073 			regs[rd] = count;
3074 
3075 		break;
3076 	}
3077 
3078 	case DIF_SUBR_PROGENYOF: {
3079 		pid_t pid = tupregs[0].dttk_value;
3080 		proc_t *p;
3081 		int rval = 0;
3082 
3083 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3084 
3085 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3086 			if (p->p_pidp->pid_id == pid) {
3087 				rval = 1;
3088 				break;
3089 			}
3090 		}
3091 
3092 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3093 
3094 		regs[rd] = rval;
3095 		break;
3096 	}
3097 
3098 	case DIF_SUBR_SPECULATION:
3099 		regs[rd] = dtrace_speculation(state);
3100 		break;
3101 
3102 	case DIF_SUBR_COPYOUT: {
3103 		uintptr_t kaddr = tupregs[0].dttk_value;
3104 		uintptr_t uaddr = tupregs[1].dttk_value;
3105 		uint64_t size = tupregs[2].dttk_value;
3106 
3107 		if (!dtrace_destructive_disallow &&
3108 		    dtrace_priv_proc_control(state) &&
3109 		    !dtrace_istoxic(kaddr, size)) {
3110 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3111 			dtrace_copyout(kaddr, uaddr, size);
3112 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3113 		}
3114 		break;
3115 	}
3116 
3117 	case DIF_SUBR_COPYOUTSTR: {
3118 		uintptr_t kaddr = tupregs[0].dttk_value;
3119 		uintptr_t uaddr = tupregs[1].dttk_value;
3120 		uint64_t size = tupregs[2].dttk_value;
3121 
3122 		if (!dtrace_destructive_disallow &&
3123 		    dtrace_priv_proc_control(state) &&
3124 		    !dtrace_istoxic(kaddr, size)) {
3125 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3126 			dtrace_copyoutstr(kaddr, uaddr, size);
3127 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3128 		}
3129 		break;
3130 	}
3131 
3132 	case DIF_SUBR_STRLEN: {
3133 		size_t sz;
3134 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3135 		sz = dtrace_strlen((char *)addr,
3136 		    state->dts_options[DTRACEOPT_STRSIZE]);
3137 
3138 		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3139 			regs[rd] = NULL;
3140 			break;
3141 		}
3142 
3143 		regs[rd] = sz;
3144 
3145 		break;
3146 	}
3147 
3148 	case DIF_SUBR_STRCHR:
3149 	case DIF_SUBR_STRRCHR: {
3150 		/*
3151 		 * We're going to iterate over the string looking for the
3152 		 * specified character.  We will iterate until we have reached
3153 		 * the string length or we have found the character.  If this
3154 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3155 		 * of the specified character instead of the first.
3156 		 */
3157 		uintptr_t saddr = tupregs[0].dttk_value;
3158 		uintptr_t addr = tupregs[0].dttk_value;
3159 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3160 		char c, target = (char)tupregs[1].dttk_value;
3161 
3162 		for (regs[rd] = NULL; addr < limit; addr++) {
3163 			if ((c = dtrace_load8(addr)) == target) {
3164 				regs[rd] = addr;
3165 
3166 				if (subr == DIF_SUBR_STRCHR)
3167 					break;
3168 			}
3169 
3170 			if (c == '\0')
3171 				break;
3172 		}
3173 
3174 		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3175 			regs[rd] = NULL;
3176 			break;
3177 		}
3178 
3179 		break;
3180 	}
3181 
3182 	case DIF_SUBR_STRSTR:
3183 	case DIF_SUBR_INDEX:
3184 	case DIF_SUBR_RINDEX: {
3185 		/*
3186 		 * We're going to iterate over the string looking for the
3187 		 * specified string.  We will iterate until we have reached
3188 		 * the string length or we have found the string.  (Yes, this
3189 		 * is done in the most naive way possible -- but considering
3190 		 * that the string we're searching for is likely to be
3191 		 * relatively short, the complexity of Rabin-Karp or similar
3192 		 * hardly seems merited.)
3193 		 */
3194 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3195 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3196 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3197 		size_t len = dtrace_strlen(addr, size);
3198 		size_t sublen = dtrace_strlen(substr, size);
3199 		char *limit = addr + len, *orig = addr;
3200 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3201 		int inc = 1;
3202 
3203 		regs[rd] = notfound;
3204 
3205 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3206 			regs[rd] = NULL;
3207 			break;
3208 		}
3209 
3210 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3211 		    vstate)) {
3212 			regs[rd] = NULL;
3213 			break;
3214 		}
3215 
3216 		/*
3217 		 * strstr() and index()/rindex() have similar semantics if
3218 		 * both strings are the empty string: strstr() returns a
3219 		 * pointer to the (empty) string, and index() and rindex()
3220 		 * both return index 0 (regardless of any position argument).
3221 		 */
3222 		if (sublen == 0 && len == 0) {
3223 			if (subr == DIF_SUBR_STRSTR)
3224 				regs[rd] = (uintptr_t)addr;
3225 			else
3226 				regs[rd] = 0;
3227 			break;
3228 		}
3229 
3230 		if (subr != DIF_SUBR_STRSTR) {
3231 			if (subr == DIF_SUBR_RINDEX) {
3232 				limit = orig - 1;
3233 				addr += len;
3234 				inc = -1;
3235 			}
3236 
3237 			/*
3238 			 * Both index() and rindex() take an optional position
3239 			 * argument that denotes the starting position.
3240 			 */
3241 			if (nargs == 3) {
3242 				int64_t pos = (int64_t)tupregs[2].dttk_value;
3243 
3244 				/*
3245 				 * If the position argument to index() is
3246 				 * negative, Perl implicitly clamps it at
3247 				 * zero.  This semantic is a little surprising
3248 				 * given the special meaning of negative
3249 				 * positions to similar Perl functions like
3250 				 * substr(), but it appears to reflect a
3251 				 * notion that index() can start from a
3252 				 * negative index and increment its way up to
3253 				 * the string.  Given this notion, Perl's
3254 				 * rindex() is at least self-consistent in
3255 				 * that it implicitly clamps positions greater
3256 				 * than the string length to be the string
3257 				 * length.  Where Perl completely loses
3258 				 * coherence, however, is when the specified
3259 				 * substring is the empty string ("").  In
3260 				 * this case, even if the position is
3261 				 * negative, rindex() returns 0 -- and even if
3262 				 * the position is greater than the length,
3263 				 * index() returns the string length.  These
3264 				 * semantics violate the notion that index()
3265 				 * should never return a value less than the
3266 				 * specified position and that rindex() should
3267 				 * never return a value greater than the
3268 				 * specified position.  (One assumes that
3269 				 * these semantics are artifacts of Perl's
3270 				 * implementation and not the results of
3271 				 * deliberate design -- it beggars belief that
3272 				 * even Larry Wall could desire such oddness.)
3273 				 * While in the abstract one would wish for
3274 				 * consistent position semantics across
3275 				 * substr(), index() and rindex() -- or at the
3276 				 * very least self-consistent position
3277 				 * semantics for index() and rindex() -- we
3278 				 * instead opt to keep with the extant Perl
3279 				 * semantics, in all their broken glory.  (Do
3280 				 * we have more desire to maintain Perl's
3281 				 * semantics than Perl does?  Probably.)
3282 				 */
3283 				if (subr == DIF_SUBR_RINDEX) {
3284 					if (pos < 0) {
3285 						if (sublen == 0)
3286 							regs[rd] = 0;
3287 						break;
3288 					}
3289 
3290 					if (pos > len)
3291 						pos = len;
3292 				} else {
3293 					if (pos < 0)
3294 						pos = 0;
3295 
3296 					if (pos >= len) {
3297 						if (sublen == 0)
3298 							regs[rd] = len;
3299 						break;
3300 					}
3301 				}
3302 
3303 				addr = orig + pos;
3304 			}
3305 		}
3306 
3307 		for (regs[rd] = notfound; addr != limit; addr += inc) {
3308 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
3309 				if (subr != DIF_SUBR_STRSTR) {
3310 					/*
3311 					 * As D index() and rindex() are
3312 					 * modeled on Perl (and not on awk),
3313 					 * we return a zero-based (and not a
3314 					 * one-based) index.  (For you Perl
3315 					 * weenies: no, we're not going to add
3316 					 * $[ -- and shouldn't you be at a con
3317 					 * or something?)
3318 					 */
3319 					regs[rd] = (uintptr_t)(addr - orig);
3320 					break;
3321 				}
3322 
3323 				ASSERT(subr == DIF_SUBR_STRSTR);
3324 				regs[rd] = (uintptr_t)addr;
3325 				break;
3326 			}
3327 		}
3328 
3329 		break;
3330 	}
3331 
3332 	case DIF_SUBR_STRTOK: {
3333 		uintptr_t addr = tupregs[0].dttk_value;
3334 		uintptr_t tokaddr = tupregs[1].dttk_value;
3335 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3336 		uintptr_t limit, toklimit = tokaddr + size;
3337 		uint8_t c, tokmap[32];	 /* 256 / 8 */
3338 		char *dest = (char *)mstate->dtms_scratch_ptr;
3339 		int i;
3340 
3341 		/*
3342 		 * Check both the token buffer and (later) the input buffer,
3343 		 * since both could be non-scratch addresses.
3344 		 */
3345 		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3346 			regs[rd] = NULL;
3347 			break;
3348 		}
3349 
3350 		if (!DTRACE_INSCRATCH(mstate, size)) {
3351 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3352 			regs[rd] = NULL;
3353 			break;
3354 		}
3355 
3356 		if (addr == NULL) {
3357 			/*
3358 			 * If the address specified is NULL, we use our saved
3359 			 * strtok pointer from the mstate.  Note that this
3360 			 * means that the saved strtok pointer is _only_
3361 			 * valid within multiple enablings of the same probe --
3362 			 * it behaves like an implicit clause-local variable.
3363 			 */
3364 			addr = mstate->dtms_strtok;
3365 		} else {
3366 			/*
3367 			 * If the user-specified address is non-NULL we must
3368 			 * access check it.  This is the only time we have
3369 			 * a chance to do so, since this address may reside
3370 			 * in the string table of this clause-- future calls
3371 			 * (when we fetch addr from mstate->dtms_strtok)
3372 			 * would fail this access check.
3373 			 */
3374 			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3375 				regs[rd] = NULL;
3376 				break;
3377 			}
3378 		}
3379 
3380 		/*
3381 		 * First, zero the token map, and then process the token
3382 		 * string -- setting a bit in the map for every character
3383 		 * found in the token string.
3384 		 */
3385 		for (i = 0; i < sizeof (tokmap); i++)
3386 			tokmap[i] = 0;
3387 
3388 		for (; tokaddr < toklimit; tokaddr++) {
3389 			if ((c = dtrace_load8(tokaddr)) == '\0')
3390 				break;
3391 
3392 			ASSERT((c >> 3) < sizeof (tokmap));
3393 			tokmap[c >> 3] |= (1 << (c & 0x7));
3394 		}
3395 
3396 		for (limit = addr + size; addr < limit; addr++) {
3397 			/*
3398 			 * We're looking for a character that is _not_ contained
3399 			 * in the token string.
3400 			 */
3401 			if ((c = dtrace_load8(addr)) == '\0')
3402 				break;
3403 
3404 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3405 				break;
3406 		}
3407 
3408 		if (c == '\0') {
3409 			/*
3410 			 * We reached the end of the string without finding
3411 			 * any character that was not in the token string.
3412 			 * We return NULL in this case, and we set the saved
3413 			 * address to NULL as well.
3414 			 */
3415 			regs[rd] = NULL;
3416 			mstate->dtms_strtok = NULL;
3417 			break;
3418 		}
3419 
3420 		/*
3421 		 * From here on, we're copying into the destination string.
3422 		 */
3423 		for (i = 0; addr < limit && i < size - 1; addr++) {
3424 			if ((c = dtrace_load8(addr)) == '\0')
3425 				break;
3426 
3427 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
3428 				break;
3429 
3430 			ASSERT(i < size);
3431 			dest[i++] = c;
3432 		}
3433 
3434 		ASSERT(i < size);
3435 		dest[i] = '\0';
3436 		regs[rd] = (uintptr_t)dest;
3437 		mstate->dtms_scratch_ptr += size;
3438 		mstate->dtms_strtok = addr;
3439 		break;
3440 	}
3441 
3442 	case DIF_SUBR_SUBSTR: {
3443 		uintptr_t s = tupregs[0].dttk_value;
3444 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3445 		char *d = (char *)mstate->dtms_scratch_ptr;
3446 		int64_t index = (int64_t)tupregs[1].dttk_value;
3447 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
3448 		size_t len = dtrace_strlen((char *)s, size);
3449 		int64_t i = 0;
3450 
3451 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
3452 			regs[rd] = NULL;
3453 			break;
3454 		}
3455 
3456 		if (nargs <= 2)
3457 			remaining = (int64_t)size;
3458 
3459 		if (!DTRACE_INSCRATCH(mstate, size)) {
3460 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3461 			regs[rd] = NULL;
3462 			break;
3463 		}
3464 
3465 		if (index < 0) {
3466 			index += len;
3467 
3468 			if (index < 0 && index + remaining > 0) {
3469 				remaining += index;
3470 				index = 0;
3471 			}
3472 		}
3473 
3474 		if (index >= len || index < 0)
3475 			index = len;
3476 
3477 		for (d[0] = '\0'; remaining > 0; remaining--) {
3478 			if ((d[i++] = dtrace_load8(s++ + index)) == '\0')
3479 				break;
3480 
3481 			if (i == size) {
3482 				d[i - 1] = '\0';
3483 				break;
3484 			}
3485 		}
3486 
3487 		mstate->dtms_scratch_ptr += size;
3488 		regs[rd] = (uintptr_t)d;
3489 		break;
3490 	}
3491 
3492 	case DIF_SUBR_GETMAJOR:
3493 #ifdef _LP64
3494 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
3495 #else
3496 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
3497 #endif
3498 		break;
3499 
3500 	case DIF_SUBR_GETMINOR:
3501 #ifdef _LP64
3502 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
3503 #else
3504 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
3505 #endif
3506 		break;
3507 
3508 	case DIF_SUBR_DDI_PATHNAME: {
3509 		/*
3510 		 * This one is a galactic mess.  We are going to roughly
3511 		 * emulate ddi_pathname(), but it's made more complicated
3512 		 * by the fact that we (a) want to include the minor name and
3513 		 * (b) must proceed iteratively instead of recursively.
3514 		 */
3515 		uintptr_t dest = mstate->dtms_scratch_ptr;
3516 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3517 		char *start = (char *)dest, *end = start + size - 1;
3518 		uintptr_t daddr = tupregs[0].dttk_value;
3519 		int64_t minor = (int64_t)tupregs[1].dttk_value;
3520 		char *s;
3521 		int i, len, depth = 0;
3522 
3523 		/*
3524 		 * Due to all the pointer jumping we do and context we must
3525 		 * rely upon, we just mandate that the user must have kernel
3526 		 * read privileges to use this routine.
3527 		 */
3528 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
3529 			*flags |= CPU_DTRACE_KPRIV;
3530 			*illval = daddr;
3531 			regs[rd] = NULL;
3532 		}
3533 
3534 		if (!DTRACE_INSCRATCH(mstate, size)) {
3535 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3536 			regs[rd] = NULL;
3537 			break;
3538 		}
3539 
3540 		*end = '\0';
3541 
3542 		/*
3543 		 * We want to have a name for the minor.  In order to do this,
3544 		 * we need to walk the minor list from the devinfo.  We want
3545 		 * to be sure that we don't infinitely walk a circular list,
3546 		 * so we check for circularity by sending a scout pointer
3547 		 * ahead two elements for every element that we iterate over;
3548 		 * if the list is circular, these will ultimately point to the
3549 		 * same element.  You may recognize this little trick as the
3550 		 * answer to a stupid interview question -- one that always
3551 		 * seems to be asked by those who had to have it laboriously
3552 		 * explained to them, and who can't even concisely describe
3553 		 * the conditions under which one would be forced to resort to
3554 		 * this technique.  Needless to say, those conditions are
3555 		 * found here -- and probably only here.  Is this is the only
3556 		 * use of this infamous trick in shipping, production code?
3557 		 * If it isn't, it probably should be...
3558 		 */
3559 		if (minor != -1) {
3560 			uintptr_t maddr = dtrace_loadptr(daddr +
3561 			    offsetof(struct dev_info, devi_minor));
3562 
3563 			uintptr_t next = offsetof(struct ddi_minor_data, next);
3564 			uintptr_t name = offsetof(struct ddi_minor_data,
3565 			    d_minor) + offsetof(struct ddi_minor, name);
3566 			uintptr_t dev = offsetof(struct ddi_minor_data,
3567 			    d_minor) + offsetof(struct ddi_minor, dev);
3568 			uintptr_t scout;
3569 
3570 			if (maddr != NULL)
3571 				scout = dtrace_loadptr(maddr + next);
3572 
3573 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3574 				uint64_t m;
3575 #ifdef _LP64
3576 				m = dtrace_load64(maddr + dev) & MAXMIN64;
3577 #else
3578 				m = dtrace_load32(maddr + dev) & MAXMIN;
3579 #endif
3580 				if (m != minor) {
3581 					maddr = dtrace_loadptr(maddr + next);
3582 
3583 					if (scout == NULL)
3584 						continue;
3585 
3586 					scout = dtrace_loadptr(scout + next);
3587 
3588 					if (scout == NULL)
3589 						continue;
3590 
3591 					scout = dtrace_loadptr(scout + next);
3592 
3593 					if (scout == NULL)
3594 						continue;
3595 
3596 					if (scout == maddr) {
3597 						*flags |= CPU_DTRACE_ILLOP;
3598 						break;
3599 					}
3600 
3601 					continue;
3602 				}
3603 
3604 				/*
3605 				 * We have the minor data.  Now we need to
3606 				 * copy the minor's name into the end of the
3607 				 * pathname.
3608 				 */
3609 				s = (char *)dtrace_loadptr(maddr + name);
3610 				len = dtrace_strlen(s, size);
3611 
3612 				if (*flags & CPU_DTRACE_FAULT)
3613 					break;
3614 
3615 				if (len != 0) {
3616 					if ((end -= (len + 1)) < start)
3617 						break;
3618 
3619 					*end = ':';
3620 				}
3621 
3622 				for (i = 1; i <= len; i++)
3623 					end[i] = dtrace_load8((uintptr_t)s++);
3624 				break;
3625 			}
3626 		}
3627 
3628 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3629 			ddi_node_state_t devi_state;
3630 
3631 			devi_state = dtrace_load32(daddr +
3632 			    offsetof(struct dev_info, devi_node_state));
3633 
3634 			if (*flags & CPU_DTRACE_FAULT)
3635 				break;
3636 
3637 			if (devi_state >= DS_INITIALIZED) {
3638 				s = (char *)dtrace_loadptr(daddr +
3639 				    offsetof(struct dev_info, devi_addr));
3640 				len = dtrace_strlen(s, size);
3641 
3642 				if (*flags & CPU_DTRACE_FAULT)
3643 					break;
3644 
3645 				if (len != 0) {
3646 					if ((end -= (len + 1)) < start)
3647 						break;
3648 
3649 					*end = '@';
3650 				}
3651 
3652 				for (i = 1; i <= len; i++)
3653 					end[i] = dtrace_load8((uintptr_t)s++);
3654 			}
3655 
3656 			/*
3657 			 * Now for the node name...
3658 			 */
3659 			s = (char *)dtrace_loadptr(daddr +
3660 			    offsetof(struct dev_info, devi_node_name));
3661 
3662 			daddr = dtrace_loadptr(daddr +
3663 			    offsetof(struct dev_info, devi_parent));
3664 
3665 			/*
3666 			 * If our parent is NULL (that is, if we're the root
3667 			 * node), we're going to use the special path
3668 			 * "devices".
3669 			 */
3670 			if (daddr == NULL)
3671 				s = "devices";
3672 
3673 			len = dtrace_strlen(s, size);
3674 			if (*flags & CPU_DTRACE_FAULT)
3675 				break;
3676 
3677 			if ((end -= (len + 1)) < start)
3678 				break;
3679 
3680 			for (i = 1; i <= len; i++)
3681 				end[i] = dtrace_load8((uintptr_t)s++);
3682 			*end = '/';
3683 
3684 			if (depth++ > dtrace_devdepth_max) {
3685 				*flags |= CPU_DTRACE_ILLOP;
3686 				break;
3687 			}
3688 		}
3689 
3690 		if (end < start)
3691 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3692 
3693 		if (daddr == NULL) {
3694 			regs[rd] = (uintptr_t)end;
3695 			mstate->dtms_scratch_ptr += size;
3696 		}
3697 
3698 		break;
3699 	}
3700 
3701 	case DIF_SUBR_STRJOIN: {
3702 		char *d = (char *)mstate->dtms_scratch_ptr;
3703 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3704 		uintptr_t s1 = tupregs[0].dttk_value;
3705 		uintptr_t s2 = tupregs[1].dttk_value;
3706 		int i = 0;
3707 
3708 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
3709 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
3710 			regs[rd] = NULL;
3711 			break;
3712 		}
3713 
3714 		if (!DTRACE_INSCRATCH(mstate, size)) {
3715 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3716 			regs[rd] = NULL;
3717 			break;
3718 		}
3719 
3720 		for (;;) {
3721 			if (i >= size) {
3722 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3723 				regs[rd] = NULL;
3724 				break;
3725 			}
3726 
3727 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
3728 				i--;
3729 				break;
3730 			}
3731 		}
3732 
3733 		for (;;) {
3734 			if (i >= size) {
3735 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3736 				regs[rd] = NULL;
3737 				break;
3738 			}
3739 
3740 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
3741 				break;
3742 		}
3743 
3744 		if (i < size) {
3745 			mstate->dtms_scratch_ptr += i;
3746 			regs[rd] = (uintptr_t)d;
3747 		}
3748 
3749 		break;
3750 	}
3751 
3752 	case DIF_SUBR_LLTOSTR: {
3753 		int64_t i = (int64_t)tupregs[0].dttk_value;
3754 		int64_t val = i < 0 ? i * -1 : i;
3755 		uint64_t size = 22;	/* enough room for 2^64 in decimal */
3756 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
3757 
3758 		if (!DTRACE_INSCRATCH(mstate, size)) {
3759 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3760 			regs[rd] = NULL;
3761 			break;
3762 		}
3763 
3764 		for (*end-- = '\0'; val; val /= 10)
3765 			*end-- = '0' + (val % 10);
3766 
3767 		if (i == 0)
3768 			*end-- = '0';
3769 
3770 		if (i < 0)
3771 			*end-- = '-';
3772 
3773 		regs[rd] = (uintptr_t)end + 1;
3774 		mstate->dtms_scratch_ptr += size;
3775 		break;
3776 	}
3777 
3778 	case DIF_SUBR_HTONS:
3779 	case DIF_SUBR_NTOHS:
3780 #ifdef _BIG_ENDIAN
3781 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
3782 #else
3783 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
3784 #endif
3785 		break;
3786 
3787 
3788 	case DIF_SUBR_HTONL:
3789 	case DIF_SUBR_NTOHL:
3790 #ifdef _BIG_ENDIAN
3791 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
3792 #else
3793 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
3794 #endif
3795 		break;
3796 
3797 
3798 	case DIF_SUBR_HTONLL:
3799 	case DIF_SUBR_NTOHLL:
3800 #ifdef _BIG_ENDIAN
3801 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
3802 #else
3803 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
3804 #endif
3805 		break;
3806 
3807 
3808 	case DIF_SUBR_DIRNAME:
3809 	case DIF_SUBR_BASENAME: {
3810 		char *dest = (char *)mstate->dtms_scratch_ptr;
3811 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3812 		uintptr_t src = tupregs[0].dttk_value;
3813 		int i, j, len = dtrace_strlen((char *)src, size);
3814 		int lastbase = -1, firstbase = -1, lastdir = -1;
3815 		int start, end;
3816 
3817 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
3818 			regs[rd] = NULL;
3819 			break;
3820 		}
3821 
3822 		if (!DTRACE_INSCRATCH(mstate, size)) {
3823 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3824 			regs[rd] = NULL;
3825 			break;
3826 		}
3827 
3828 		/*
3829 		 * The basename and dirname for a zero-length string is
3830 		 * defined to be "."
3831 		 */
3832 		if (len == 0) {
3833 			len = 1;
3834 			src = (uintptr_t)".";
3835 		}
3836 
3837 		/*
3838 		 * Start from the back of the string, moving back toward the
3839 		 * front until we see a character that isn't a slash.  That
3840 		 * character is the last character in the basename.
3841 		 */
3842 		for (i = len - 1; i >= 0; i--) {
3843 			if (dtrace_load8(src + i) != '/')
3844 				break;
3845 		}
3846 
3847 		if (i >= 0)
3848 			lastbase = i;
3849 
3850 		/*
3851 		 * Starting from the last character in the basename, move
3852 		 * towards the front until we find a slash.  The character
3853 		 * that we processed immediately before that is the first
3854 		 * character in the basename.
3855 		 */
3856 		for (; i >= 0; i--) {
3857 			if (dtrace_load8(src + i) == '/')
3858 				break;
3859 		}
3860 
3861 		if (i >= 0)
3862 			firstbase = i + 1;
3863 
3864 		/*
3865 		 * Now keep going until we find a non-slash character.  That
3866 		 * character is the last character in the dirname.
3867 		 */
3868 		for (; i >= 0; i--) {
3869 			if (dtrace_load8(src + i) != '/')
3870 				break;
3871 		}
3872 
3873 		if (i >= 0)
3874 			lastdir = i;
3875 
3876 		ASSERT(!(lastbase == -1 && firstbase != -1));
3877 		ASSERT(!(firstbase == -1 && lastdir != -1));
3878 
3879 		if (lastbase == -1) {
3880 			/*
3881 			 * We didn't find a non-slash character.  We know that
3882 			 * the length is non-zero, so the whole string must be
3883 			 * slashes.  In either the dirname or the basename
3884 			 * case, we return '/'.
3885 			 */
3886 			ASSERT(firstbase == -1);
3887 			firstbase = lastbase = lastdir = 0;
3888 		}
3889 
3890 		if (firstbase == -1) {
3891 			/*
3892 			 * The entire string consists only of a basename
3893 			 * component.  If we're looking for dirname, we need
3894 			 * to change our string to be just "."; if we're
3895 			 * looking for a basename, we'll just set the first
3896 			 * character of the basename to be 0.
3897 			 */
3898 			if (subr == DIF_SUBR_DIRNAME) {
3899 				ASSERT(lastdir == -1);
3900 				src = (uintptr_t)".";
3901 				lastdir = 0;
3902 			} else {
3903 				firstbase = 0;
3904 			}
3905 		}
3906 
3907 		if (subr == DIF_SUBR_DIRNAME) {
3908 			if (lastdir == -1) {
3909 				/*
3910 				 * We know that we have a slash in the name --
3911 				 * or lastdir would be set to 0, above.  And
3912 				 * because lastdir is -1, we know that this
3913 				 * slash must be the first character.  (That
3914 				 * is, the full string must be of the form
3915 				 * "/basename".)  In this case, the last
3916 				 * character of the directory name is 0.
3917 				 */
3918 				lastdir = 0;
3919 			}
3920 
3921 			start = 0;
3922 			end = lastdir;
3923 		} else {
3924 			ASSERT(subr == DIF_SUBR_BASENAME);
3925 			ASSERT(firstbase != -1 && lastbase != -1);
3926 			start = firstbase;
3927 			end = lastbase;
3928 		}
3929 
3930 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
3931 			dest[j] = dtrace_load8(src + i);
3932 
3933 		dest[j] = '\0';
3934 		regs[rd] = (uintptr_t)dest;
3935 		mstate->dtms_scratch_ptr += size;
3936 		break;
3937 	}
3938 
3939 	case DIF_SUBR_CLEANPATH: {
3940 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
3941 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3942 		uintptr_t src = tupregs[0].dttk_value;
3943 		int i = 0, j = 0;
3944 
3945 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
3946 			regs[rd] = NULL;
3947 			break;
3948 		}
3949 
3950 		if (!DTRACE_INSCRATCH(mstate, size)) {
3951 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3952 			regs[rd] = NULL;
3953 			break;
3954 		}
3955 
3956 		/*
3957 		 * Move forward, loading each character.
3958 		 */
3959 		do {
3960 			c = dtrace_load8(src + i++);
3961 next:
3962 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
3963 				break;
3964 
3965 			if (c != '/') {
3966 				dest[j++] = c;
3967 				continue;
3968 			}
3969 
3970 			c = dtrace_load8(src + i++);
3971 
3972 			if (c == '/') {
3973 				/*
3974 				 * We have two slashes -- we can just advance
3975 				 * to the next character.
3976 				 */
3977 				goto next;
3978 			}
3979 
3980 			if (c != '.') {
3981 				/*
3982 				 * This is not "." and it's not ".." -- we can
3983 				 * just store the "/" and this character and
3984 				 * drive on.
3985 				 */
3986 				dest[j++] = '/';
3987 				dest[j++] = c;
3988 				continue;
3989 			}
3990 
3991 			c = dtrace_load8(src + i++);
3992 
3993 			if (c == '/') {
3994 				/*
3995 				 * This is a "/./" component.  We're not going
3996 				 * to store anything in the destination buffer;
3997 				 * we're just going to go to the next component.
3998 				 */
3999 				goto next;
4000 			}
4001 
4002 			if (c != '.') {
4003 				/*
4004 				 * This is not ".." -- we can just store the
4005 				 * "/." and this character and continue
4006 				 * processing.
4007 				 */
4008 				dest[j++] = '/';
4009 				dest[j++] = '.';
4010 				dest[j++] = c;
4011 				continue;
4012 			}
4013 
4014 			c = dtrace_load8(src + i++);
4015 
4016 			if (c != '/' && c != '\0') {
4017 				/*
4018 				 * This is not ".." -- it's "..[mumble]".
4019 				 * We'll store the "/.." and this character
4020 				 * and continue processing.
4021 				 */
4022 				dest[j++] = '/';
4023 				dest[j++] = '.';
4024 				dest[j++] = '.';
4025 				dest[j++] = c;
4026 				continue;
4027 			}
4028 
4029 			/*
4030 			 * This is "/../" or "/..\0".  We need to back up
4031 			 * our destination pointer until we find a "/".
4032 			 */
4033 			i--;
4034 			while (j != 0 && dest[--j] != '/')
4035 				continue;
4036 
4037 			if (c == '\0')
4038 				dest[++j] = '/';
4039 		} while (c != '\0');
4040 
4041 		dest[j] = '\0';
4042 		regs[rd] = (uintptr_t)dest;
4043 		mstate->dtms_scratch_ptr += size;
4044 		break;
4045 	}
4046 	}
4047 }
4048 
4049 /*
4050  * Emulate the execution of DTrace IR instructions specified by the given
4051  * DIF object.  This function is deliberately void of assertions as all of
4052  * the necessary checks are handled by a call to dtrace_difo_validate().
4053  */
4054 static uint64_t
4055 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4056     dtrace_vstate_t *vstate, dtrace_state_t *state)
4057 {
4058 	const dif_instr_t *text = difo->dtdo_buf;
4059 	const uint_t textlen = difo->dtdo_len;
4060 	const char *strtab = difo->dtdo_strtab;
4061 	const uint64_t *inttab = difo->dtdo_inttab;
4062 
4063 	uint64_t rval = 0;
4064 	dtrace_statvar_t *svar;
4065 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4066 	dtrace_difv_t *v;
4067 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4068 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4069 
4070 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4071 	uint64_t regs[DIF_DIR_NREGS];
4072 	uint64_t *tmp;
4073 
4074 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4075 	int64_t cc_r;
4076 	uint_t pc = 0, id, opc;
4077 	uint8_t ttop = 0;
4078 	dif_instr_t instr;
4079 	uint_t r1, r2, rd;
4080 
4081 	/*
4082 	 * We stash the current DIF object into the machine state: we need it
4083 	 * for subsequent access checking.
4084 	 */
4085 	mstate->dtms_difo = difo;
4086 
4087 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
4088 
4089 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4090 		opc = pc;
4091 
4092 		instr = text[pc++];
4093 		r1 = DIF_INSTR_R1(instr);
4094 		r2 = DIF_INSTR_R2(instr);
4095 		rd = DIF_INSTR_RD(instr);
4096 
4097 		switch (DIF_INSTR_OP(instr)) {
4098 		case DIF_OP_OR:
4099 			regs[rd] = regs[r1] | regs[r2];
4100 			break;
4101 		case DIF_OP_XOR:
4102 			regs[rd] = regs[r1] ^ regs[r2];
4103 			break;
4104 		case DIF_OP_AND:
4105 			regs[rd] = regs[r1] & regs[r2];
4106 			break;
4107 		case DIF_OP_SLL:
4108 			regs[rd] = regs[r1] << regs[r2];
4109 			break;
4110 		case DIF_OP_SRL:
4111 			regs[rd] = regs[r1] >> regs[r2];
4112 			break;
4113 		case DIF_OP_SUB:
4114 			regs[rd] = regs[r1] - regs[r2];
4115 			break;
4116 		case DIF_OP_ADD:
4117 			regs[rd] = regs[r1] + regs[r2];
4118 			break;
4119 		case DIF_OP_MUL:
4120 			regs[rd] = regs[r1] * regs[r2];
4121 			break;
4122 		case DIF_OP_SDIV:
4123 			if (regs[r2] == 0) {
4124 				regs[rd] = 0;
4125 				*flags |= CPU_DTRACE_DIVZERO;
4126 			} else {
4127 				regs[rd] = (int64_t)regs[r1] /
4128 				    (int64_t)regs[r2];
4129 			}
4130 			break;
4131 
4132 		case DIF_OP_UDIV:
4133 			if (regs[r2] == 0) {
4134 				regs[rd] = 0;
4135 				*flags |= CPU_DTRACE_DIVZERO;
4136 			} else {
4137 				regs[rd] = regs[r1] / regs[r2];
4138 			}
4139 			break;
4140 
4141 		case DIF_OP_SREM:
4142 			if (regs[r2] == 0) {
4143 				regs[rd] = 0;
4144 				*flags |= CPU_DTRACE_DIVZERO;
4145 			} else {
4146 				regs[rd] = (int64_t)regs[r1] %
4147 				    (int64_t)regs[r2];
4148 			}
4149 			break;
4150 
4151 		case DIF_OP_UREM:
4152 			if (regs[r2] == 0) {
4153 				regs[rd] = 0;
4154 				*flags |= CPU_DTRACE_DIVZERO;
4155 			} else {
4156 				regs[rd] = regs[r1] % regs[r2];
4157 			}
4158 			break;
4159 
4160 		case DIF_OP_NOT:
4161 			regs[rd] = ~regs[r1];
4162 			break;
4163 		case DIF_OP_MOV:
4164 			regs[rd] = regs[r1];
4165 			break;
4166 		case DIF_OP_CMP:
4167 			cc_r = regs[r1] - regs[r2];
4168 			cc_n = cc_r < 0;
4169 			cc_z = cc_r == 0;
4170 			cc_v = 0;
4171 			cc_c = regs[r1] < regs[r2];
4172 			break;
4173 		case DIF_OP_TST:
4174 			cc_n = cc_v = cc_c = 0;
4175 			cc_z = regs[r1] == 0;
4176 			break;
4177 		case DIF_OP_BA:
4178 			pc = DIF_INSTR_LABEL(instr);
4179 			break;
4180 		case DIF_OP_BE:
4181 			if (cc_z)
4182 				pc = DIF_INSTR_LABEL(instr);
4183 			break;
4184 		case DIF_OP_BNE:
4185 			if (cc_z == 0)
4186 				pc = DIF_INSTR_LABEL(instr);
4187 			break;
4188 		case DIF_OP_BG:
4189 			if ((cc_z | (cc_n ^ cc_v)) == 0)
4190 				pc = DIF_INSTR_LABEL(instr);
4191 			break;
4192 		case DIF_OP_BGU:
4193 			if ((cc_c | cc_z) == 0)
4194 				pc = DIF_INSTR_LABEL(instr);
4195 			break;
4196 		case DIF_OP_BGE:
4197 			if ((cc_n ^ cc_v) == 0)
4198 				pc = DIF_INSTR_LABEL(instr);
4199 			break;
4200 		case DIF_OP_BGEU:
4201 			if (cc_c == 0)
4202 				pc = DIF_INSTR_LABEL(instr);
4203 			break;
4204 		case DIF_OP_BL:
4205 			if (cc_n ^ cc_v)
4206 				pc = DIF_INSTR_LABEL(instr);
4207 			break;
4208 		case DIF_OP_BLU:
4209 			if (cc_c)
4210 				pc = DIF_INSTR_LABEL(instr);
4211 			break;
4212 		case DIF_OP_BLE:
4213 			if (cc_z | (cc_n ^ cc_v))
4214 				pc = DIF_INSTR_LABEL(instr);
4215 			break;
4216 		case DIF_OP_BLEU:
4217 			if (cc_c | cc_z)
4218 				pc = DIF_INSTR_LABEL(instr);
4219 			break;
4220 		case DIF_OP_RLDSB:
4221 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4222 				*flags |= CPU_DTRACE_KPRIV;
4223 				*illval = regs[r1];
4224 				break;
4225 			}
4226 			/*FALLTHROUGH*/
4227 		case DIF_OP_LDSB:
4228 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
4229 			break;
4230 		case DIF_OP_RLDSH:
4231 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4232 				*flags |= CPU_DTRACE_KPRIV;
4233 				*illval = regs[r1];
4234 				break;
4235 			}
4236 			/*FALLTHROUGH*/
4237 		case DIF_OP_LDSH:
4238 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
4239 			break;
4240 		case DIF_OP_RLDSW:
4241 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4242 				*flags |= CPU_DTRACE_KPRIV;
4243 				*illval = regs[r1];
4244 				break;
4245 			}
4246 			/*FALLTHROUGH*/
4247 		case DIF_OP_LDSW:
4248 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
4249 			break;
4250 		case DIF_OP_RLDUB:
4251 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4252 				*flags |= CPU_DTRACE_KPRIV;
4253 				*illval = regs[r1];
4254 				break;
4255 			}
4256 			/*FALLTHROUGH*/
4257 		case DIF_OP_LDUB:
4258 			regs[rd] = dtrace_load8(regs[r1]);
4259 			break;
4260 		case DIF_OP_RLDUH:
4261 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4262 				*flags |= CPU_DTRACE_KPRIV;
4263 				*illval = regs[r1];
4264 				break;
4265 			}
4266 			/*FALLTHROUGH*/
4267 		case DIF_OP_LDUH:
4268 			regs[rd] = dtrace_load16(regs[r1]);
4269 			break;
4270 		case DIF_OP_RLDUW:
4271 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4272 				*flags |= CPU_DTRACE_KPRIV;
4273 				*illval = regs[r1];
4274 				break;
4275 			}
4276 			/*FALLTHROUGH*/
4277 		case DIF_OP_LDUW:
4278 			regs[rd] = dtrace_load32(regs[r1]);
4279 			break;
4280 		case DIF_OP_RLDX:
4281 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
4282 				*flags |= CPU_DTRACE_KPRIV;
4283 				*illval = regs[r1];
4284 				break;
4285 			}
4286 			/*FALLTHROUGH*/
4287 		case DIF_OP_LDX:
4288 			regs[rd] = dtrace_load64(regs[r1]);
4289 			break;
4290 		case DIF_OP_ULDSB:
4291 			regs[rd] = (int8_t)
4292 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4293 			break;
4294 		case DIF_OP_ULDSH:
4295 			regs[rd] = (int16_t)
4296 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4297 			break;
4298 		case DIF_OP_ULDSW:
4299 			regs[rd] = (int32_t)
4300 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4301 			break;
4302 		case DIF_OP_ULDUB:
4303 			regs[rd] =
4304 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4305 			break;
4306 		case DIF_OP_ULDUH:
4307 			regs[rd] =
4308 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4309 			break;
4310 		case DIF_OP_ULDUW:
4311 			regs[rd] =
4312 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4313 			break;
4314 		case DIF_OP_ULDX:
4315 			regs[rd] =
4316 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
4317 			break;
4318 		case DIF_OP_RET:
4319 			rval = regs[rd];
4320 			break;
4321 		case DIF_OP_NOP:
4322 			break;
4323 		case DIF_OP_SETX:
4324 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
4325 			break;
4326 		case DIF_OP_SETS:
4327 			regs[rd] = (uint64_t)(uintptr_t)
4328 			    (strtab + DIF_INSTR_STRING(instr));
4329 			break;
4330 		case DIF_OP_SCMP: {
4331 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
4332 			uintptr_t s1 = regs[r1];
4333 			uintptr_t s2 = regs[r2];
4334 
4335 			if (s1 != NULL &&
4336 			    !dtrace_strcanload(s1, sz, mstate, vstate))
4337 				break;
4338 			if (s2 != NULL &&
4339 			    !dtrace_strcanload(s2, sz, mstate, vstate))
4340 				break;
4341 
4342 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
4343 
4344 			cc_n = cc_r < 0;
4345 			cc_z = cc_r == 0;
4346 			cc_v = cc_c = 0;
4347 			break;
4348 		}
4349 		case DIF_OP_LDGA:
4350 			regs[rd] = dtrace_dif_variable(mstate, state,
4351 			    r1, regs[r2]);
4352 			break;
4353 		case DIF_OP_LDGS:
4354 			id = DIF_INSTR_VAR(instr);
4355 
4356 			if (id >= DIF_VAR_OTHER_UBASE) {
4357 				uintptr_t a;
4358 
4359 				id -= DIF_VAR_OTHER_UBASE;
4360 				svar = vstate->dtvs_globals[id];
4361 				ASSERT(svar != NULL);
4362 				v = &svar->dtsv_var;
4363 
4364 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
4365 					regs[rd] = svar->dtsv_data;
4366 					break;
4367 				}
4368 
4369 				a = (uintptr_t)svar->dtsv_data;
4370 
4371 				if (*(uint8_t *)a == UINT8_MAX) {
4372 					/*
4373 					 * If the 0th byte is set to UINT8_MAX
4374 					 * then this is to be treated as a
4375 					 * reference to a NULL variable.
4376 					 */
4377 					regs[rd] = NULL;
4378 				} else {
4379 					regs[rd] = a + sizeof (uint64_t);
4380 				}
4381 
4382 				break;
4383 			}
4384 
4385 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
4386 			break;
4387 
4388 		case DIF_OP_STGS:
4389 			id = DIF_INSTR_VAR(instr);
4390 
4391 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4392 			id -= DIF_VAR_OTHER_UBASE;
4393 
4394 			svar = vstate->dtvs_globals[id];
4395 			ASSERT(svar != NULL);
4396 			v = &svar->dtsv_var;
4397 
4398 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4399 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4400 
4401 				ASSERT(a != NULL);
4402 				ASSERT(svar->dtsv_size != 0);
4403 
4404 				if (regs[rd] == NULL) {
4405 					*(uint8_t *)a = UINT8_MAX;
4406 					break;
4407 				} else {
4408 					*(uint8_t *)a = 0;
4409 					a += sizeof (uint64_t);
4410 				}
4411 				if (!dtrace_vcanload(
4412 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4413 				    mstate, vstate))
4414 					break;
4415 
4416 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4417 				    (void *)a, &v->dtdv_type);
4418 				break;
4419 			}
4420 
4421 			svar->dtsv_data = regs[rd];
4422 			break;
4423 
4424 		case DIF_OP_LDTA:
4425 			/*
4426 			 * There are no DTrace built-in thread-local arrays at
4427 			 * present.  This opcode is saved for future work.
4428 			 */
4429 			*flags |= CPU_DTRACE_ILLOP;
4430 			regs[rd] = 0;
4431 			break;
4432 
4433 		case DIF_OP_LDLS:
4434 			id = DIF_INSTR_VAR(instr);
4435 
4436 			if (id < DIF_VAR_OTHER_UBASE) {
4437 				/*
4438 				 * For now, this has no meaning.
4439 				 */
4440 				regs[rd] = 0;
4441 				break;
4442 			}
4443 
4444 			id -= DIF_VAR_OTHER_UBASE;
4445 
4446 			ASSERT(id < vstate->dtvs_nlocals);
4447 			ASSERT(vstate->dtvs_locals != NULL);
4448 
4449 			svar = vstate->dtvs_locals[id];
4450 			ASSERT(svar != NULL);
4451 			v = &svar->dtsv_var;
4452 
4453 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4454 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4455 				size_t sz = v->dtdv_type.dtdt_size;
4456 
4457 				sz += sizeof (uint64_t);
4458 				ASSERT(svar->dtsv_size == NCPU * sz);
4459 				a += CPU->cpu_id * sz;
4460 
4461 				if (*(uint8_t *)a == UINT8_MAX) {
4462 					/*
4463 					 * If the 0th byte is set to UINT8_MAX
4464 					 * then this is to be treated as a
4465 					 * reference to a NULL variable.
4466 					 */
4467 					regs[rd] = NULL;
4468 				} else {
4469 					regs[rd] = a + sizeof (uint64_t);
4470 				}
4471 
4472 				break;
4473 			}
4474 
4475 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4476 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4477 			regs[rd] = tmp[CPU->cpu_id];
4478 			break;
4479 
4480 		case DIF_OP_STLS:
4481 			id = DIF_INSTR_VAR(instr);
4482 
4483 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4484 			id -= DIF_VAR_OTHER_UBASE;
4485 			ASSERT(id < vstate->dtvs_nlocals);
4486 
4487 			ASSERT(vstate->dtvs_locals != NULL);
4488 			svar = vstate->dtvs_locals[id];
4489 			ASSERT(svar != NULL);
4490 			v = &svar->dtsv_var;
4491 
4492 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4493 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4494 				size_t sz = v->dtdv_type.dtdt_size;
4495 
4496 				sz += sizeof (uint64_t);
4497 				ASSERT(svar->dtsv_size == NCPU * sz);
4498 				a += CPU->cpu_id * sz;
4499 
4500 				if (regs[rd] == NULL) {
4501 					*(uint8_t *)a = UINT8_MAX;
4502 					break;
4503 				} else {
4504 					*(uint8_t *)a = 0;
4505 					a += sizeof (uint64_t);
4506 				}
4507 
4508 				if (!dtrace_vcanload(
4509 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4510 				    mstate, vstate))
4511 					break;
4512 
4513 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4514 				    (void *)a, &v->dtdv_type);
4515 				break;
4516 			}
4517 
4518 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4519 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4520 			tmp[CPU->cpu_id] = regs[rd];
4521 			break;
4522 
4523 		case DIF_OP_LDTS: {
4524 			dtrace_dynvar_t *dvar;
4525 			dtrace_key_t *key;
4526 
4527 			id = DIF_INSTR_VAR(instr);
4528 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4529 			id -= DIF_VAR_OTHER_UBASE;
4530 			v = &vstate->dtvs_tlocals[id];
4531 
4532 			key = &tupregs[DIF_DTR_NREGS];
4533 			key[0].dttk_value = (uint64_t)id;
4534 			key[0].dttk_size = 0;
4535 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4536 			key[1].dttk_size = 0;
4537 
4538 			dvar = dtrace_dynvar(dstate, 2, key,
4539 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
4540 			    mstate, vstate);
4541 
4542 			if (dvar == NULL) {
4543 				regs[rd] = 0;
4544 				break;
4545 			}
4546 
4547 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4548 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4549 			} else {
4550 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4551 			}
4552 
4553 			break;
4554 		}
4555 
4556 		case DIF_OP_STTS: {
4557 			dtrace_dynvar_t *dvar;
4558 			dtrace_key_t *key;
4559 
4560 			id = DIF_INSTR_VAR(instr);
4561 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4562 			id -= DIF_VAR_OTHER_UBASE;
4563 
4564 			key = &tupregs[DIF_DTR_NREGS];
4565 			key[0].dttk_value = (uint64_t)id;
4566 			key[0].dttk_size = 0;
4567 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4568 			key[1].dttk_size = 0;
4569 			v = &vstate->dtvs_tlocals[id];
4570 
4571 			dvar = dtrace_dynvar(dstate, 2, key,
4572 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4573 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4574 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4575 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
4576 
4577 			/*
4578 			 * Given that we're storing to thread-local data,
4579 			 * we need to flush our predicate cache.
4580 			 */
4581 			curthread->t_predcache = NULL;
4582 
4583 			if (dvar == NULL)
4584 				break;
4585 
4586 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4587 				if (!dtrace_vcanload(
4588 				    (void *)(uintptr_t)regs[rd],
4589 				    &v->dtdv_type, mstate, vstate))
4590 					break;
4591 
4592 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4593 				    dvar->dtdv_data, &v->dtdv_type);
4594 			} else {
4595 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4596 			}
4597 
4598 			break;
4599 		}
4600 
4601 		case DIF_OP_SRA:
4602 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
4603 			break;
4604 
4605 		case DIF_OP_CALL:
4606 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
4607 			    regs, tupregs, ttop, mstate, state);
4608 			break;
4609 
4610 		case DIF_OP_PUSHTR:
4611 			if (ttop == DIF_DTR_NREGS) {
4612 				*flags |= CPU_DTRACE_TUPOFLOW;
4613 				break;
4614 			}
4615 
4616 			if (r1 == DIF_TYPE_STRING) {
4617 				/*
4618 				 * If this is a string type and the size is 0,
4619 				 * we'll use the system-wide default string
4620 				 * size.  Note that we are _not_ looking at
4621 				 * the value of the DTRACEOPT_STRSIZE option;
4622 				 * had this been set, we would expect to have
4623 				 * a non-zero size value in the "pushtr".
4624 				 */
4625 				tupregs[ttop].dttk_size =
4626 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
4627 				    regs[r2] ? regs[r2] :
4628 				    dtrace_strsize_default) + 1;
4629 			} else {
4630 				tupregs[ttop].dttk_size = regs[r2];
4631 			}
4632 
4633 			tupregs[ttop++].dttk_value = regs[rd];
4634 			break;
4635 
4636 		case DIF_OP_PUSHTV:
4637 			if (ttop == DIF_DTR_NREGS) {
4638 				*flags |= CPU_DTRACE_TUPOFLOW;
4639 				break;
4640 			}
4641 
4642 			tupregs[ttop].dttk_value = regs[rd];
4643 			tupregs[ttop++].dttk_size = 0;
4644 			break;
4645 
4646 		case DIF_OP_POPTS:
4647 			if (ttop != 0)
4648 				ttop--;
4649 			break;
4650 
4651 		case DIF_OP_FLUSHTS:
4652 			ttop = 0;
4653 			break;
4654 
4655 		case DIF_OP_LDGAA:
4656 		case DIF_OP_LDTAA: {
4657 			dtrace_dynvar_t *dvar;
4658 			dtrace_key_t *key = tupregs;
4659 			uint_t nkeys = ttop;
4660 
4661 			id = DIF_INSTR_VAR(instr);
4662 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4663 			id -= DIF_VAR_OTHER_UBASE;
4664 
4665 			key[nkeys].dttk_value = (uint64_t)id;
4666 			key[nkeys++].dttk_size = 0;
4667 
4668 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
4669 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4670 				key[nkeys++].dttk_size = 0;
4671 				v = &vstate->dtvs_tlocals[id];
4672 			} else {
4673 				v = &vstate->dtvs_globals[id]->dtsv_var;
4674 			}
4675 
4676 			dvar = dtrace_dynvar(dstate, nkeys, key,
4677 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4678 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4679 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
4680 
4681 			if (dvar == NULL) {
4682 				regs[rd] = 0;
4683 				break;
4684 			}
4685 
4686 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4687 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4688 			} else {
4689 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4690 			}
4691 
4692 			break;
4693 		}
4694 
4695 		case DIF_OP_STGAA:
4696 		case DIF_OP_STTAA: {
4697 			dtrace_dynvar_t *dvar;
4698 			dtrace_key_t *key = tupregs;
4699 			uint_t nkeys = ttop;
4700 
4701 			id = DIF_INSTR_VAR(instr);
4702 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4703 			id -= DIF_VAR_OTHER_UBASE;
4704 
4705 			key[nkeys].dttk_value = (uint64_t)id;
4706 			key[nkeys++].dttk_size = 0;
4707 
4708 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
4709 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4710 				key[nkeys++].dttk_size = 0;
4711 				v = &vstate->dtvs_tlocals[id];
4712 			} else {
4713 				v = &vstate->dtvs_globals[id]->dtsv_var;
4714 			}
4715 
4716 			dvar = dtrace_dynvar(dstate, nkeys, key,
4717 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4718 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4719 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4720 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
4721 
4722 			if (dvar == NULL)
4723 				break;
4724 
4725 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4726 				if (!dtrace_vcanload(
4727 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4728 				    mstate, vstate))
4729 					break;
4730 
4731 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4732 				    dvar->dtdv_data, &v->dtdv_type);
4733 			} else {
4734 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4735 			}
4736 
4737 			break;
4738 		}
4739 
4740 		case DIF_OP_ALLOCS: {
4741 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4742 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
4743 
4744 			/*
4745 			 * Rounding up the user allocation size could have
4746 			 * overflowed large, bogus allocations (like -1ULL) to
4747 			 * 0.
4748 			 */
4749 			if (size < regs[r1] ||
4750 			    !DTRACE_INSCRATCH(mstate, size)) {
4751 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4752 				regs[rd] = NULL;
4753 				break;
4754 			}
4755 
4756 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
4757 			mstate->dtms_scratch_ptr += size;
4758 			regs[rd] = ptr;
4759 			break;
4760 		}
4761 
4762 		case DIF_OP_COPYS:
4763 			if (!dtrace_canstore(regs[rd], regs[r2],
4764 			    mstate, vstate)) {
4765 				*flags |= CPU_DTRACE_BADADDR;
4766 				*illval = regs[rd];
4767 				break;
4768 			}
4769 
4770 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
4771 				break;
4772 
4773 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
4774 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
4775 			break;
4776 
4777 		case DIF_OP_STB:
4778 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
4779 				*flags |= CPU_DTRACE_BADADDR;
4780 				*illval = regs[rd];
4781 				break;
4782 			}
4783 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
4784 			break;
4785 
4786 		case DIF_OP_STH:
4787 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
4788 				*flags |= CPU_DTRACE_BADADDR;
4789 				*illval = regs[rd];
4790 				break;
4791 			}
4792 			if (regs[rd] & 1) {
4793 				*flags |= CPU_DTRACE_BADALIGN;
4794 				*illval = regs[rd];
4795 				break;
4796 			}
4797 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
4798 			break;
4799 
4800 		case DIF_OP_STW:
4801 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
4802 				*flags |= CPU_DTRACE_BADADDR;
4803 				*illval = regs[rd];
4804 				break;
4805 			}
4806 			if (regs[rd] & 3) {
4807 				*flags |= CPU_DTRACE_BADALIGN;
4808 				*illval = regs[rd];
4809 				break;
4810 			}
4811 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
4812 			break;
4813 
4814 		case DIF_OP_STX:
4815 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
4816 				*flags |= CPU_DTRACE_BADADDR;
4817 				*illval = regs[rd];
4818 				break;
4819 			}
4820 			if (regs[rd] & 7) {
4821 				*flags |= CPU_DTRACE_BADALIGN;
4822 				*illval = regs[rd];
4823 				break;
4824 			}
4825 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
4826 			break;
4827 		}
4828 	}
4829 
4830 	if (!(*flags & CPU_DTRACE_FAULT))
4831 		return (rval);
4832 
4833 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
4834 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
4835 
4836 	return (0);
4837 }
4838 
4839 static void
4840 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
4841 {
4842 	dtrace_probe_t *probe = ecb->dte_probe;
4843 	dtrace_provider_t *prov = probe->dtpr_provider;
4844 	char c[DTRACE_FULLNAMELEN + 80], *str;
4845 	char *msg = "dtrace: breakpoint action at probe ";
4846 	char *ecbmsg = " (ecb ";
4847 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
4848 	uintptr_t val = (uintptr_t)ecb;
4849 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
4850 
4851 	if (dtrace_destructive_disallow)
4852 		return;
4853 
4854 	/*
4855 	 * It's impossible to be taking action on the NULL probe.
4856 	 */
4857 	ASSERT(probe != NULL);
4858 
4859 	/*
4860 	 * This is a poor man's (destitute man's?) sprintf():  we want to
4861 	 * print the provider name, module name, function name and name of
4862 	 * the probe, along with the hex address of the ECB with the breakpoint
4863 	 * action -- all of which we must place in the character buffer by
4864 	 * hand.
4865 	 */
4866 	while (*msg != '\0')
4867 		c[i++] = *msg++;
4868 
4869 	for (str = prov->dtpv_name; *str != '\0'; str++)
4870 		c[i++] = *str;
4871 	c[i++] = ':';
4872 
4873 	for (str = probe->dtpr_mod; *str != '\0'; str++)
4874 		c[i++] = *str;
4875 	c[i++] = ':';
4876 
4877 	for (str = probe->dtpr_func; *str != '\0'; str++)
4878 		c[i++] = *str;
4879 	c[i++] = ':';
4880 
4881 	for (str = probe->dtpr_name; *str != '\0'; str++)
4882 		c[i++] = *str;
4883 
4884 	while (*ecbmsg != '\0')
4885 		c[i++] = *ecbmsg++;
4886 
4887 	while (shift >= 0) {
4888 		mask = (uintptr_t)0xf << shift;
4889 
4890 		if (val >= ((uintptr_t)1 << shift))
4891 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
4892 		shift -= 4;
4893 	}
4894 
4895 	c[i++] = ')';
4896 	c[i] = '\0';
4897 
4898 	debug_enter(c);
4899 }
4900 
4901 static void
4902 dtrace_action_panic(dtrace_ecb_t *ecb)
4903 {
4904 	dtrace_probe_t *probe = ecb->dte_probe;
4905 
4906 	/*
4907 	 * It's impossible to be taking action on the NULL probe.
4908 	 */
4909 	ASSERT(probe != NULL);
4910 
4911 	if (dtrace_destructive_disallow)
4912 		return;
4913 
4914 	if (dtrace_panicked != NULL)
4915 		return;
4916 
4917 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
4918 		return;
4919 
4920 	/*
4921 	 * We won the right to panic.  (We want to be sure that only one
4922 	 * thread calls panic() from dtrace_probe(), and that panic() is
4923 	 * called exactly once.)
4924 	 */
4925 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
4926 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
4927 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
4928 }
4929 
4930 static void
4931 dtrace_action_raise(uint64_t sig)
4932 {
4933 	if (dtrace_destructive_disallow)
4934 		return;
4935 
4936 	if (sig >= NSIG) {
4937 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4938 		return;
4939 	}
4940 
4941 	/*
4942 	 * raise() has a queue depth of 1 -- we ignore all subsequent
4943 	 * invocations of the raise() action.
4944 	 */
4945 	if (curthread->t_dtrace_sig == 0)
4946 		curthread->t_dtrace_sig = (uint8_t)sig;
4947 
4948 	curthread->t_sig_check = 1;
4949 	aston(curthread);
4950 }
4951 
4952 static void
4953 dtrace_action_stop(void)
4954 {
4955 	if (dtrace_destructive_disallow)
4956 		return;
4957 
4958 	if (!curthread->t_dtrace_stop) {
4959 		curthread->t_dtrace_stop = 1;
4960 		curthread->t_sig_check = 1;
4961 		aston(curthread);
4962 	}
4963 }
4964 
4965 static void
4966 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
4967 {
4968 	hrtime_t now;
4969 	volatile uint16_t *flags;
4970 	cpu_t *cpu = CPU;
4971 
4972 	if (dtrace_destructive_disallow)
4973 		return;
4974 
4975 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
4976 
4977 	now = dtrace_gethrtime();
4978 
4979 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
4980 		/*
4981 		 * We need to advance the mark to the current time.
4982 		 */
4983 		cpu->cpu_dtrace_chillmark = now;
4984 		cpu->cpu_dtrace_chilled = 0;
4985 	}
4986 
4987 	/*
4988 	 * Now check to see if the requested chill time would take us over
4989 	 * the maximum amount of time allowed in the chill interval.  (Or
4990 	 * worse, if the calculation itself induces overflow.)
4991 	 */
4992 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
4993 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
4994 		*flags |= CPU_DTRACE_ILLOP;
4995 		return;
4996 	}
4997 
4998 	while (dtrace_gethrtime() - now < val)
4999 		continue;
5000 
5001 	/*
5002 	 * Normally, we assure that the value of the variable "timestamp" does
5003 	 * not change within an ECB.  The presence of chill() represents an
5004 	 * exception to this rule, however.
5005 	 */
5006 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5007 	cpu->cpu_dtrace_chilled += val;
5008 }
5009 
5010 static void
5011 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5012     uint64_t *buf, uint64_t arg)
5013 {
5014 	int nframes = DTRACE_USTACK_NFRAMES(arg);
5015 	int strsize = DTRACE_USTACK_STRSIZE(arg);
5016 	uint64_t *pcs = &buf[1], *fps;
5017 	char *str = (char *)&pcs[nframes];
5018 	int size, offs = 0, i, j;
5019 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
5020 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5021 	char *sym;
5022 
5023 	/*
5024 	 * Should be taking a faster path if string space has not been
5025 	 * allocated.
5026 	 */
5027 	ASSERT(strsize != 0);
5028 
5029 	/*
5030 	 * We will first allocate some temporary space for the frame pointers.
5031 	 */
5032 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5033 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5034 	    (nframes * sizeof (uint64_t));
5035 
5036 	if (!DTRACE_INSCRATCH(mstate, size)) {
5037 		/*
5038 		 * Not enough room for our frame pointers -- need to indicate
5039 		 * that we ran out of scratch space.
5040 		 */
5041 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5042 		return;
5043 	}
5044 
5045 	mstate->dtms_scratch_ptr += size;
5046 	saved = mstate->dtms_scratch_ptr;
5047 
5048 	/*
5049 	 * Now get a stack with both program counters and frame pointers.
5050 	 */
5051 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5052 	dtrace_getufpstack(buf, fps, nframes + 1);
5053 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5054 
5055 	/*
5056 	 * If that faulted, we're cooked.
5057 	 */
5058 	if (*flags & CPU_DTRACE_FAULT)
5059 		goto out;
5060 
5061 	/*
5062 	 * Now we want to walk up the stack, calling the USTACK helper.  For
5063 	 * each iteration, we restore the scratch pointer.
5064 	 */
5065 	for (i = 0; i < nframes; i++) {
5066 		mstate->dtms_scratch_ptr = saved;
5067 
5068 		if (offs >= strsize)
5069 			break;
5070 
5071 		sym = (char *)(uintptr_t)dtrace_helper(
5072 		    DTRACE_HELPER_ACTION_USTACK,
5073 		    mstate, state, pcs[i], fps[i]);
5074 
5075 		/*
5076 		 * If we faulted while running the helper, we're going to
5077 		 * clear the fault and null out the corresponding string.
5078 		 */
5079 		if (*flags & CPU_DTRACE_FAULT) {
5080 			*flags &= ~CPU_DTRACE_FAULT;
5081 			str[offs++] = '\0';
5082 			continue;
5083 		}
5084 
5085 		if (sym == NULL) {
5086 			str[offs++] = '\0';
5087 			continue;
5088 		}
5089 
5090 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5091 
5092 		/*
5093 		 * Now copy in the string that the helper returned to us.
5094 		 */
5095 		for (j = 0; offs + j < strsize; j++) {
5096 			if ((str[offs + j] = sym[j]) == '\0')
5097 				break;
5098 		}
5099 
5100 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5101 
5102 		offs += j + 1;
5103 	}
5104 
5105 	if (offs >= strsize) {
5106 		/*
5107 		 * If we didn't have room for all of the strings, we don't
5108 		 * abort processing -- this needn't be a fatal error -- but we
5109 		 * still want to increment a counter (dts_stkstroverflows) to
5110 		 * allow this condition to be warned about.  (If this is from
5111 		 * a jstack() action, it is easily tuned via jstackstrsize.)
5112 		 */
5113 		dtrace_error(&state->dts_stkstroverflows);
5114 	}
5115 
5116 	while (offs < strsize)
5117 		str[offs++] = '\0';
5118 
5119 out:
5120 	mstate->dtms_scratch_ptr = old;
5121 }
5122 
5123 /*
5124  * If you're looking for the epicenter of DTrace, you just found it.  This
5125  * is the function called by the provider to fire a probe -- from which all
5126  * subsequent probe-context DTrace activity emanates.
5127  */
5128 void
5129 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
5130     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
5131 {
5132 	processorid_t cpuid;
5133 	dtrace_icookie_t cookie;
5134 	dtrace_probe_t *probe;
5135 	dtrace_mstate_t mstate;
5136 	dtrace_ecb_t *ecb;
5137 	dtrace_action_t *act;
5138 	intptr_t offs;
5139 	size_t size;
5140 	int vtime, onintr;
5141 	volatile uint16_t *flags;
5142 	hrtime_t now;
5143 
5144 	/*
5145 	 * Kick out immediately if this CPU is still being born (in which case
5146 	 * curthread will be set to -1)
5147 	 */
5148 	if ((uintptr_t)curthread & 1)
5149 		return;
5150 
5151 	cookie = dtrace_interrupt_disable();
5152 	probe = dtrace_probes[id - 1];
5153 	cpuid = CPU->cpu_id;
5154 	onintr = CPU_ON_INTR(CPU);
5155 
5156 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
5157 	    probe->dtpr_predcache == curthread->t_predcache) {
5158 		/*
5159 		 * We have hit in the predicate cache; we know that
5160 		 * this predicate would evaluate to be false.
5161 		 */
5162 		dtrace_interrupt_enable(cookie);
5163 		return;
5164 	}
5165 
5166 	if (panic_quiesce) {
5167 		/*
5168 		 * We don't trace anything if we're panicking.
5169 		 */
5170 		dtrace_interrupt_enable(cookie);
5171 		return;
5172 	}
5173 
5174 	now = dtrace_gethrtime();
5175 	vtime = dtrace_vtime_references != 0;
5176 
5177 	if (vtime && curthread->t_dtrace_start)
5178 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
5179 
5180 	mstate.dtms_difo = NULL;
5181 	mstate.dtms_probe = probe;
5182 	mstate.dtms_strtok = NULL;
5183 	mstate.dtms_arg[0] = arg0;
5184 	mstate.dtms_arg[1] = arg1;
5185 	mstate.dtms_arg[2] = arg2;
5186 	mstate.dtms_arg[3] = arg3;
5187 	mstate.dtms_arg[4] = arg4;
5188 
5189 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
5190 
5191 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
5192 		dtrace_predicate_t *pred = ecb->dte_predicate;
5193 		dtrace_state_t *state = ecb->dte_state;
5194 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
5195 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
5196 		dtrace_vstate_t *vstate = &state->dts_vstate;
5197 		dtrace_provider_t *prov = probe->dtpr_provider;
5198 		int committed = 0;
5199 		caddr_t tomax;
5200 
5201 		/*
5202 		 * A little subtlety with the following (seemingly innocuous)
5203 		 * declaration of the automatic 'val':  by looking at the
5204 		 * code, you might think that it could be declared in the
5205 		 * action processing loop, below.  (That is, it's only used in
5206 		 * the action processing loop.)  However, it must be declared
5207 		 * out of that scope because in the case of DIF expression
5208 		 * arguments to aggregating actions, one iteration of the
5209 		 * action loop will use the last iteration's value.
5210 		 */
5211 #ifdef lint
5212 		uint64_t val = 0;
5213 #else
5214 		uint64_t val;
5215 #endif
5216 
5217 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
5218 		*flags &= ~CPU_DTRACE_ERROR;
5219 
5220 		if (prov == dtrace_provider) {
5221 			/*
5222 			 * If dtrace itself is the provider of this probe,
5223 			 * we're only going to continue processing the ECB if
5224 			 * arg0 (the dtrace_state_t) is equal to the ECB's
5225 			 * creating state.  (This prevents disjoint consumers
5226 			 * from seeing one another's metaprobes.)
5227 			 */
5228 			if (arg0 != (uint64_t)(uintptr_t)state)
5229 				continue;
5230 		}
5231 
5232 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
5233 			/*
5234 			 * We're not currently active.  If our provider isn't
5235 			 * the dtrace pseudo provider, we're not interested.
5236 			 */
5237 			if (prov != dtrace_provider)
5238 				continue;
5239 
5240 			/*
5241 			 * Now we must further check if we are in the BEGIN
5242 			 * probe.  If we are, we will only continue processing
5243 			 * if we're still in WARMUP -- if one BEGIN enabling
5244 			 * has invoked the exit() action, we don't want to
5245 			 * evaluate subsequent BEGIN enablings.
5246 			 */
5247 			if (probe->dtpr_id == dtrace_probeid_begin &&
5248 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
5249 				ASSERT(state->dts_activity ==
5250 				    DTRACE_ACTIVITY_DRAINING);
5251 				continue;
5252 			}
5253 		}
5254 
5255 		if (ecb->dte_cond) {
5256 			/*
5257 			 * If the dte_cond bits indicate that this
5258 			 * consumer is only allowed to see user-mode firings
5259 			 * of this probe, call the provider's dtps_usermode()
5260 			 * entry point to check that the probe was fired
5261 			 * while in a user context. Skip this ECB if that's
5262 			 * not the case.
5263 			 */
5264 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
5265 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
5266 			    probe->dtpr_id, probe->dtpr_arg) == 0)
5267 				continue;
5268 
5269 			/*
5270 			 * This is more subtle than it looks. We have to be
5271 			 * absolutely certain that CRED() isn't going to
5272 			 * change out from under us so it's only legit to
5273 			 * examine that structure if we're in constrained
5274 			 * situations. Currently, the only times we'll this
5275 			 * check is if a non-super-user has enabled the
5276 			 * profile or syscall providers -- providers that
5277 			 * allow visibility of all processes. For the
5278 			 * profile case, the check above will ensure that
5279 			 * we're examining a user context.
5280 			 */
5281 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
5282 				cred_t *cr;
5283 				cred_t *s_cr =
5284 				    ecb->dte_state->dts_cred.dcr_cred;
5285 				proc_t *proc;
5286 
5287 				ASSERT(s_cr != NULL);
5288 
5289 				if ((cr = CRED()) == NULL ||
5290 				    s_cr->cr_uid != cr->cr_uid ||
5291 				    s_cr->cr_uid != cr->cr_ruid ||
5292 				    s_cr->cr_uid != cr->cr_suid ||
5293 				    s_cr->cr_gid != cr->cr_gid ||
5294 				    s_cr->cr_gid != cr->cr_rgid ||
5295 				    s_cr->cr_gid != cr->cr_sgid ||
5296 				    (proc = ttoproc(curthread)) == NULL ||
5297 				    (proc->p_flag & SNOCD))
5298 					continue;
5299 			}
5300 
5301 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
5302 				cred_t *cr;
5303 				cred_t *s_cr =
5304 				    ecb->dte_state->dts_cred.dcr_cred;
5305 
5306 				ASSERT(s_cr != NULL);
5307 
5308 				if ((cr = CRED()) == NULL ||
5309 				    s_cr->cr_zone->zone_id !=
5310 				    cr->cr_zone->zone_id)
5311 					continue;
5312 			}
5313 		}
5314 
5315 		if (now - state->dts_alive > dtrace_deadman_timeout) {
5316 			/*
5317 			 * We seem to be dead.  Unless we (a) have kernel
5318 			 * destructive permissions (b) have expicitly enabled
5319 			 * destructive actions and (c) destructive actions have
5320 			 * not been disabled, we're going to transition into
5321 			 * the KILLED state, from which no further processing
5322 			 * on this state will be performed.
5323 			 */
5324 			if (!dtrace_priv_kernel_destructive(state) ||
5325 			    !state->dts_cred.dcr_destructive ||
5326 			    dtrace_destructive_disallow) {
5327 				void *activity = &state->dts_activity;
5328 				dtrace_activity_t current;
5329 
5330 				do {
5331 					current = state->dts_activity;
5332 				} while (dtrace_cas32(activity, current,
5333 				    DTRACE_ACTIVITY_KILLED) != current);
5334 
5335 				continue;
5336 			}
5337 		}
5338 
5339 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
5340 		    ecb->dte_alignment, state, &mstate)) < 0)
5341 			continue;
5342 
5343 		tomax = buf->dtb_tomax;
5344 		ASSERT(tomax != NULL);
5345 
5346 		if (ecb->dte_size != 0)
5347 			DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
5348 
5349 		mstate.dtms_epid = ecb->dte_epid;
5350 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
5351 
5352 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
5353 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
5354 		else
5355 			mstate.dtms_access = 0;
5356 
5357 		if (pred != NULL) {
5358 			dtrace_difo_t *dp = pred->dtp_difo;
5359 			int rval;
5360 
5361 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
5362 
5363 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
5364 				dtrace_cacheid_t cid = probe->dtpr_predcache;
5365 
5366 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
5367 					/*
5368 					 * Update the predicate cache...
5369 					 */
5370 					ASSERT(cid == pred->dtp_cacheid);
5371 					curthread->t_predcache = cid;
5372 				}
5373 
5374 				continue;
5375 			}
5376 		}
5377 
5378 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
5379 		    act != NULL; act = act->dta_next) {
5380 			size_t valoffs;
5381 			dtrace_difo_t *dp;
5382 			dtrace_recdesc_t *rec = &act->dta_rec;
5383 
5384 			size = rec->dtrd_size;
5385 			valoffs = offs + rec->dtrd_offset;
5386 
5387 			if (DTRACEACT_ISAGG(act->dta_kind)) {
5388 				uint64_t v = 0xbad;
5389 				dtrace_aggregation_t *agg;
5390 
5391 				agg = (dtrace_aggregation_t *)act;
5392 
5393 				if ((dp = act->dta_difo) != NULL)
5394 					v = dtrace_dif_emulate(dp,
5395 					    &mstate, vstate, state);
5396 
5397 				if (*flags & CPU_DTRACE_ERROR)
5398 					continue;
5399 
5400 				/*
5401 				 * Note that we always pass the expression
5402 				 * value from the previous iteration of the
5403 				 * action loop.  This value will only be used
5404 				 * if there is an expression argument to the
5405 				 * aggregating action, denoted by the
5406 				 * dtag_hasarg field.
5407 				 */
5408 				dtrace_aggregate(agg, buf,
5409 				    offs, aggbuf, v, val);
5410 				continue;
5411 			}
5412 
5413 			switch (act->dta_kind) {
5414 			case DTRACEACT_STOP:
5415 				if (dtrace_priv_proc_destructive(state))
5416 					dtrace_action_stop();
5417 				continue;
5418 
5419 			case DTRACEACT_BREAKPOINT:
5420 				if (dtrace_priv_kernel_destructive(state))
5421 					dtrace_action_breakpoint(ecb);
5422 				continue;
5423 
5424 			case DTRACEACT_PANIC:
5425 				if (dtrace_priv_kernel_destructive(state))
5426 					dtrace_action_panic(ecb);
5427 				continue;
5428 
5429 			case DTRACEACT_STACK:
5430 				if (!dtrace_priv_kernel(state))
5431 					continue;
5432 
5433 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
5434 				    size / sizeof (pc_t), probe->dtpr_aframes,
5435 				    DTRACE_ANCHORED(probe) ? NULL :
5436 				    (uint32_t *)arg0);
5437 
5438 				continue;
5439 
5440 			case DTRACEACT_JSTACK:
5441 			case DTRACEACT_USTACK:
5442 				if (!dtrace_priv_proc(state))
5443 					continue;
5444 
5445 				/*
5446 				 * See comment in DIF_VAR_PID.
5447 				 */
5448 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
5449 				    CPU_ON_INTR(CPU)) {
5450 					int depth = DTRACE_USTACK_NFRAMES(
5451 					    rec->dtrd_arg) + 1;
5452 
5453 					dtrace_bzero((void *)(tomax + valoffs),
5454 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
5455 					    + depth * sizeof (uint64_t));
5456 
5457 					continue;
5458 				}
5459 
5460 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
5461 				    curproc->p_dtrace_helpers != NULL) {
5462 					/*
5463 					 * This is the slow path -- we have
5464 					 * allocated string space, and we're
5465 					 * getting the stack of a process that
5466 					 * has helpers.  Call into a separate
5467 					 * routine to perform this processing.
5468 					 */
5469 					dtrace_action_ustack(&mstate, state,
5470 					    (uint64_t *)(tomax + valoffs),
5471 					    rec->dtrd_arg);
5472 					continue;
5473 				}
5474 
5475 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5476 				dtrace_getupcstack((uint64_t *)
5477 				    (tomax + valoffs),
5478 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
5479 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5480 				continue;
5481 
5482 			default:
5483 				break;
5484 			}
5485 
5486 			dp = act->dta_difo;
5487 			ASSERT(dp != NULL);
5488 
5489 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
5490 
5491 			if (*flags & CPU_DTRACE_ERROR)
5492 				continue;
5493 
5494 			switch (act->dta_kind) {
5495 			case DTRACEACT_SPECULATE:
5496 				ASSERT(buf == &state->dts_buffer[cpuid]);
5497 				buf = dtrace_speculation_buffer(state,
5498 				    cpuid, val);
5499 
5500 				if (buf == NULL) {
5501 					*flags |= CPU_DTRACE_DROP;
5502 					continue;
5503 				}
5504 
5505 				offs = dtrace_buffer_reserve(buf,
5506 				    ecb->dte_needed, ecb->dte_alignment,
5507 				    state, NULL);
5508 
5509 				if (offs < 0) {
5510 					*flags |= CPU_DTRACE_DROP;
5511 					continue;
5512 				}
5513 
5514 				tomax = buf->dtb_tomax;
5515 				ASSERT(tomax != NULL);
5516 
5517 				if (ecb->dte_size != 0)
5518 					DTRACE_STORE(uint32_t, tomax, offs,
5519 					    ecb->dte_epid);
5520 				continue;
5521 
5522 			case DTRACEACT_CHILL:
5523 				if (dtrace_priv_kernel_destructive(state))
5524 					dtrace_action_chill(&mstate, val);
5525 				continue;
5526 
5527 			case DTRACEACT_RAISE:
5528 				if (dtrace_priv_proc_destructive(state))
5529 					dtrace_action_raise(val);
5530 				continue;
5531 
5532 			case DTRACEACT_COMMIT:
5533 				ASSERT(!committed);
5534 
5535 				/*
5536 				 * We need to commit our buffer state.
5537 				 */
5538 				if (ecb->dte_size)
5539 					buf->dtb_offset = offs + ecb->dte_size;
5540 				buf = &state->dts_buffer[cpuid];
5541 				dtrace_speculation_commit(state, cpuid, val);
5542 				committed = 1;
5543 				continue;
5544 
5545 			case DTRACEACT_DISCARD:
5546 				dtrace_speculation_discard(state, cpuid, val);
5547 				continue;
5548 
5549 			case DTRACEACT_DIFEXPR:
5550 			case DTRACEACT_LIBACT:
5551 			case DTRACEACT_PRINTF:
5552 			case DTRACEACT_PRINTA:
5553 			case DTRACEACT_SYSTEM:
5554 			case DTRACEACT_FREOPEN:
5555 				break;
5556 
5557 			case DTRACEACT_SYM:
5558 			case DTRACEACT_MOD:
5559 				if (!dtrace_priv_kernel(state))
5560 					continue;
5561 				break;
5562 
5563 			case DTRACEACT_USYM:
5564 			case DTRACEACT_UMOD:
5565 			case DTRACEACT_UADDR: {
5566 				struct pid *pid = curthread->t_procp->p_pidp;
5567 
5568 				if (!dtrace_priv_proc(state))
5569 					continue;
5570 
5571 				DTRACE_STORE(uint64_t, tomax,
5572 				    valoffs, (uint64_t)pid->pid_id);
5573 				DTRACE_STORE(uint64_t, tomax,
5574 				    valoffs + sizeof (uint64_t), val);
5575 
5576 				continue;
5577 			}
5578 
5579 			case DTRACEACT_EXIT: {
5580 				/*
5581 				 * For the exit action, we are going to attempt
5582 				 * to atomically set our activity to be
5583 				 * draining.  If this fails (either because
5584 				 * another CPU has beat us to the exit action,
5585 				 * or because our current activity is something
5586 				 * other than ACTIVE or WARMUP), we will
5587 				 * continue.  This assures that the exit action
5588 				 * can be successfully recorded at most once
5589 				 * when we're in the ACTIVE state.  If we're
5590 				 * encountering the exit() action while in
5591 				 * COOLDOWN, however, we want to honor the new
5592 				 * status code.  (We know that we're the only
5593 				 * thread in COOLDOWN, so there is no race.)
5594 				 */
5595 				void *activity = &state->dts_activity;
5596 				dtrace_activity_t current = state->dts_activity;
5597 
5598 				if (current == DTRACE_ACTIVITY_COOLDOWN)
5599 					break;
5600 
5601 				if (current != DTRACE_ACTIVITY_WARMUP)
5602 					current = DTRACE_ACTIVITY_ACTIVE;
5603 
5604 				if (dtrace_cas32(activity, current,
5605 				    DTRACE_ACTIVITY_DRAINING) != current) {
5606 					*flags |= CPU_DTRACE_DROP;
5607 					continue;
5608 				}
5609 
5610 				break;
5611 			}
5612 
5613 			default:
5614 				ASSERT(0);
5615 			}
5616 
5617 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
5618 				uintptr_t end = valoffs + size;
5619 
5620 				if (!dtrace_vcanload((void *)(uintptr_t)val,
5621 				    &dp->dtdo_rtype, &mstate, vstate))
5622 					continue;
5623 
5624 				/*
5625 				 * If this is a string, we're going to only
5626 				 * load until we find the zero byte -- after
5627 				 * which we'll store zero bytes.
5628 				 */
5629 				if (dp->dtdo_rtype.dtdt_kind ==
5630 				    DIF_TYPE_STRING) {
5631 					char c = '\0' + 1;
5632 					int intuple = act->dta_intuple;
5633 					size_t s;
5634 
5635 					for (s = 0; s < size; s++) {
5636 						if (c != '\0')
5637 							c = dtrace_load8(val++);
5638 
5639 						DTRACE_STORE(uint8_t, tomax,
5640 						    valoffs++, c);
5641 
5642 						if (c == '\0' && intuple)
5643 							break;
5644 					}
5645 
5646 					continue;
5647 				}
5648 
5649 				while (valoffs < end) {
5650 					DTRACE_STORE(uint8_t, tomax, valoffs++,
5651 					    dtrace_load8(val++));
5652 				}
5653 
5654 				continue;
5655 			}
5656 
5657 			switch (size) {
5658 			case 0:
5659 				break;
5660 
5661 			case sizeof (uint8_t):
5662 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
5663 				break;
5664 			case sizeof (uint16_t):
5665 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
5666 				break;
5667 			case sizeof (uint32_t):
5668 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
5669 				break;
5670 			case sizeof (uint64_t):
5671 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
5672 				break;
5673 			default:
5674 				/*
5675 				 * Any other size should have been returned by
5676 				 * reference, not by value.
5677 				 */
5678 				ASSERT(0);
5679 				break;
5680 			}
5681 		}
5682 
5683 		if (*flags & CPU_DTRACE_DROP)
5684 			continue;
5685 
5686 		if (*flags & CPU_DTRACE_FAULT) {
5687 			int ndx;
5688 			dtrace_action_t *err;
5689 
5690 			buf->dtb_errors++;
5691 
5692 			if (probe->dtpr_id == dtrace_probeid_error) {
5693 				/*
5694 				 * There's nothing we can do -- we had an
5695 				 * error on the error probe.  We bump an
5696 				 * error counter to at least indicate that
5697 				 * this condition happened.
5698 				 */
5699 				dtrace_error(&state->dts_dblerrors);
5700 				continue;
5701 			}
5702 
5703 			if (vtime) {
5704 				/*
5705 				 * Before recursing on dtrace_probe(), we
5706 				 * need to explicitly clear out our start
5707 				 * time to prevent it from being accumulated
5708 				 * into t_dtrace_vtime.
5709 				 */
5710 				curthread->t_dtrace_start = 0;
5711 			}
5712 
5713 			/*
5714 			 * Iterate over the actions to figure out which action
5715 			 * we were processing when we experienced the error.
5716 			 * Note that act points _past_ the faulting action; if
5717 			 * act is ecb->dte_action, the fault was in the
5718 			 * predicate, if it's ecb->dte_action->dta_next it's
5719 			 * in action #1, and so on.
5720 			 */
5721 			for (err = ecb->dte_action, ndx = 0;
5722 			    err != act; err = err->dta_next, ndx++)
5723 				continue;
5724 
5725 			dtrace_probe_error(state, ecb->dte_epid, ndx,
5726 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
5727 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
5728 			    cpu_core[cpuid].cpuc_dtrace_illval);
5729 
5730 			continue;
5731 		}
5732 
5733 		if (!committed)
5734 			buf->dtb_offset = offs + ecb->dte_size;
5735 	}
5736 
5737 	if (vtime)
5738 		curthread->t_dtrace_start = dtrace_gethrtime();
5739 
5740 	dtrace_interrupt_enable(cookie);
5741 }
5742 
5743 /*
5744  * DTrace Probe Hashing Functions
5745  *
5746  * The functions in this section (and indeed, the functions in remaining
5747  * sections) are not _called_ from probe context.  (Any exceptions to this are
5748  * marked with a "Note:".)  Rather, they are called from elsewhere in the
5749  * DTrace framework to look-up probes in, add probes to and remove probes from
5750  * the DTrace probe hashes.  (Each probe is hashed by each element of the
5751  * probe tuple -- allowing for fast lookups, regardless of what was
5752  * specified.)
5753  */
5754 static uint_t
5755 dtrace_hash_str(char *p)
5756 {
5757 	unsigned int g;
5758 	uint_t hval = 0;
5759 
5760 	while (*p) {
5761 		hval = (hval << 4) + *p++;
5762 		if ((g = (hval & 0xf0000000)) != 0)
5763 			hval ^= g >> 24;
5764 		hval &= ~g;
5765 	}
5766 	return (hval);
5767 }
5768 
5769 static dtrace_hash_t *
5770 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
5771 {
5772 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
5773 
5774 	hash->dth_stroffs = stroffs;
5775 	hash->dth_nextoffs = nextoffs;
5776 	hash->dth_prevoffs = prevoffs;
5777 
5778 	hash->dth_size = 1;
5779 	hash->dth_mask = hash->dth_size - 1;
5780 
5781 	hash->dth_tab = kmem_zalloc(hash->dth_size *
5782 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
5783 
5784 	return (hash);
5785 }
5786 
5787 static void
5788 dtrace_hash_destroy(dtrace_hash_t *hash)
5789 {
5790 #ifdef DEBUG
5791 	int i;
5792 
5793 	for (i = 0; i < hash->dth_size; i++)
5794 		ASSERT(hash->dth_tab[i] == NULL);
5795 #endif
5796 
5797 	kmem_free(hash->dth_tab,
5798 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
5799 	kmem_free(hash, sizeof (dtrace_hash_t));
5800 }
5801 
5802 static void
5803 dtrace_hash_resize(dtrace_hash_t *hash)
5804 {
5805 	int size = hash->dth_size, i, ndx;
5806 	int new_size = hash->dth_size << 1;
5807 	int new_mask = new_size - 1;
5808 	dtrace_hashbucket_t **new_tab, *bucket, *next;
5809 
5810 	ASSERT((new_size & new_mask) == 0);
5811 
5812 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
5813 
5814 	for (i = 0; i < size; i++) {
5815 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
5816 			dtrace_probe_t *probe = bucket->dthb_chain;
5817 
5818 			ASSERT(probe != NULL);
5819 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
5820 
5821 			next = bucket->dthb_next;
5822 			bucket->dthb_next = new_tab[ndx];
5823 			new_tab[ndx] = bucket;
5824 		}
5825 	}
5826 
5827 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
5828 	hash->dth_tab = new_tab;
5829 	hash->dth_size = new_size;
5830 	hash->dth_mask = new_mask;
5831 }
5832 
5833 static void
5834 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
5835 {
5836 	int hashval = DTRACE_HASHSTR(hash, new);
5837 	int ndx = hashval & hash->dth_mask;
5838 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5839 	dtrace_probe_t **nextp, **prevp;
5840 
5841 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5842 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
5843 			goto add;
5844 	}
5845 
5846 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
5847 		dtrace_hash_resize(hash);
5848 		dtrace_hash_add(hash, new);
5849 		return;
5850 	}
5851 
5852 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
5853 	bucket->dthb_next = hash->dth_tab[ndx];
5854 	hash->dth_tab[ndx] = bucket;
5855 	hash->dth_nbuckets++;
5856 
5857 add:
5858 	nextp = DTRACE_HASHNEXT(hash, new);
5859 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
5860 	*nextp = bucket->dthb_chain;
5861 
5862 	if (bucket->dthb_chain != NULL) {
5863 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
5864 		ASSERT(*prevp == NULL);
5865 		*prevp = new;
5866 	}
5867 
5868 	bucket->dthb_chain = new;
5869 	bucket->dthb_len++;
5870 }
5871 
5872 static dtrace_probe_t *
5873 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
5874 {
5875 	int hashval = DTRACE_HASHSTR(hash, template);
5876 	int ndx = hashval & hash->dth_mask;
5877 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5878 
5879 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5880 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
5881 			return (bucket->dthb_chain);
5882 	}
5883 
5884 	return (NULL);
5885 }
5886 
5887 static int
5888 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
5889 {
5890 	int hashval = DTRACE_HASHSTR(hash, template);
5891 	int ndx = hashval & hash->dth_mask;
5892 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5893 
5894 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5895 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
5896 			return (bucket->dthb_len);
5897 	}
5898 
5899 	return (NULL);
5900 }
5901 
5902 static void
5903 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
5904 {
5905 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
5906 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5907 
5908 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
5909 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
5910 
5911 	/*
5912 	 * Find the bucket that we're removing this probe from.
5913 	 */
5914 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5915 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
5916 			break;
5917 	}
5918 
5919 	ASSERT(bucket != NULL);
5920 
5921 	if (*prevp == NULL) {
5922 		if (*nextp == NULL) {
5923 			/*
5924 			 * The removed probe was the only probe on this
5925 			 * bucket; we need to remove the bucket.
5926 			 */
5927 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
5928 
5929 			ASSERT(bucket->dthb_chain == probe);
5930 			ASSERT(b != NULL);
5931 
5932 			if (b == bucket) {
5933 				hash->dth_tab[ndx] = bucket->dthb_next;
5934 			} else {
5935 				while (b->dthb_next != bucket)
5936 					b = b->dthb_next;
5937 				b->dthb_next = bucket->dthb_next;
5938 			}
5939 
5940 			ASSERT(hash->dth_nbuckets > 0);
5941 			hash->dth_nbuckets--;
5942 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
5943 			return;
5944 		}
5945 
5946 		bucket->dthb_chain = *nextp;
5947 	} else {
5948 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
5949 	}
5950 
5951 	if (*nextp != NULL)
5952 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
5953 }
5954 
5955 /*
5956  * DTrace Utility Functions
5957  *
5958  * These are random utility functions that are _not_ called from probe context.
5959  */
5960 static int
5961 dtrace_badattr(const dtrace_attribute_t *a)
5962 {
5963 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
5964 	    a->dtat_data > DTRACE_STABILITY_MAX ||
5965 	    a->dtat_class > DTRACE_CLASS_MAX);
5966 }
5967 
5968 /*
5969  * Return a duplicate copy of a string.  If the specified string is NULL,
5970  * this function returns a zero-length string.
5971  */
5972 static char *
5973 dtrace_strdup(const char *str)
5974 {
5975 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
5976 
5977 	if (str != NULL)
5978 		(void) strcpy(new, str);
5979 
5980 	return (new);
5981 }
5982 
5983 #define	DTRACE_ISALPHA(c)	\
5984 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
5985 
5986 static int
5987 dtrace_badname(const char *s)
5988 {
5989 	char c;
5990 
5991 	if (s == NULL || (c = *s++) == '\0')
5992 		return (0);
5993 
5994 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
5995 		return (1);
5996 
5997 	while ((c = *s++) != '\0') {
5998 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
5999 		    c != '-' && c != '_' && c != '.' && c != '`')
6000 			return (1);
6001 	}
6002 
6003 	return (0);
6004 }
6005 
6006 static void
6007 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
6008 {
6009 	uint32_t priv;
6010 
6011 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
6012 		/*
6013 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
6014 		 */
6015 		priv = DTRACE_PRIV_ALL;
6016 	} else {
6017 		*uidp = crgetuid(cr);
6018 		*zoneidp = crgetzoneid(cr);
6019 
6020 		priv = 0;
6021 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
6022 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
6023 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
6024 			priv |= DTRACE_PRIV_USER;
6025 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
6026 			priv |= DTRACE_PRIV_PROC;
6027 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
6028 			priv |= DTRACE_PRIV_OWNER;
6029 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
6030 			priv |= DTRACE_PRIV_ZONEOWNER;
6031 	}
6032 
6033 	*privp = priv;
6034 }
6035 
6036 #ifdef DTRACE_ERRDEBUG
6037 static void
6038 dtrace_errdebug(const char *str)
6039 {
6040 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
6041 	int occupied = 0;
6042 
6043 	mutex_enter(&dtrace_errlock);
6044 	dtrace_errlast = str;
6045 	dtrace_errthread = curthread;
6046 
6047 	while (occupied++ < DTRACE_ERRHASHSZ) {
6048 		if (dtrace_errhash[hval].dter_msg == str) {
6049 			dtrace_errhash[hval].dter_count++;
6050 			goto out;
6051 		}
6052 
6053 		if (dtrace_errhash[hval].dter_msg != NULL) {
6054 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
6055 			continue;
6056 		}
6057 
6058 		dtrace_errhash[hval].dter_msg = str;
6059 		dtrace_errhash[hval].dter_count = 1;
6060 		goto out;
6061 	}
6062 
6063 	panic("dtrace: undersized error hash");
6064 out:
6065 	mutex_exit(&dtrace_errlock);
6066 }
6067 #endif
6068 
6069 /*
6070  * DTrace Matching Functions
6071  *
6072  * These functions are used to match groups of probes, given some elements of
6073  * a probe tuple, or some globbed expressions for elements of a probe tuple.
6074  */
6075 static int
6076 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
6077     zoneid_t zoneid)
6078 {
6079 	if (priv != DTRACE_PRIV_ALL) {
6080 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
6081 		uint32_t match = priv & ppriv;
6082 
6083 		/*
6084 		 * No PRIV_DTRACE_* privileges...
6085 		 */
6086 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
6087 		    DTRACE_PRIV_KERNEL)) == 0)
6088 			return (0);
6089 
6090 		/*
6091 		 * No matching bits, but there were bits to match...
6092 		 */
6093 		if (match == 0 && ppriv != 0)
6094 			return (0);
6095 
6096 		/*
6097 		 * Need to have permissions to the process, but don't...
6098 		 */
6099 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
6100 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
6101 			return (0);
6102 		}
6103 
6104 		/*
6105 		 * Need to be in the same zone unless we possess the
6106 		 * privilege to examine all zones.
6107 		 */
6108 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
6109 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
6110 			return (0);
6111 		}
6112 	}
6113 
6114 	return (1);
6115 }
6116 
6117 /*
6118  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
6119  * consists of input pattern strings and an ops-vector to evaluate them.
6120  * This function returns >0 for match, 0 for no match, and <0 for error.
6121  */
6122 static int
6123 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
6124     uint32_t priv, uid_t uid, zoneid_t zoneid)
6125 {
6126 	dtrace_provider_t *pvp = prp->dtpr_provider;
6127 	int rv;
6128 
6129 	if (pvp->dtpv_defunct)
6130 		return (0);
6131 
6132 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
6133 		return (rv);
6134 
6135 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
6136 		return (rv);
6137 
6138 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
6139 		return (rv);
6140 
6141 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
6142 		return (rv);
6143 
6144 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
6145 		return (0);
6146 
6147 	return (rv);
6148 }
6149 
6150 /*
6151  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
6152  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
6153  * libc's version, the kernel version only applies to 8-bit ASCII strings.
6154  * In addition, all of the recursion cases except for '*' matching have been
6155  * unwound.  For '*', we still implement recursive evaluation, but a depth
6156  * counter is maintained and matching is aborted if we recurse too deep.
6157  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
6158  */
6159 static int
6160 dtrace_match_glob(const char *s, const char *p, int depth)
6161 {
6162 	const char *olds;
6163 	char s1, c;
6164 	int gs;
6165 
6166 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
6167 		return (-1);
6168 
6169 	if (s == NULL)
6170 		s = ""; /* treat NULL as empty string */
6171 
6172 top:
6173 	olds = s;
6174 	s1 = *s++;
6175 
6176 	if (p == NULL)
6177 		return (0);
6178 
6179 	if ((c = *p++) == '\0')
6180 		return (s1 == '\0');
6181 
6182 	switch (c) {
6183 	case '[': {
6184 		int ok = 0, notflag = 0;
6185 		char lc = '\0';
6186 
6187 		if (s1 == '\0')
6188 			return (0);
6189 
6190 		if (*p == '!') {
6191 			notflag = 1;
6192 			p++;
6193 		}
6194 
6195 		if ((c = *p++) == '\0')
6196 			return (0);
6197 
6198 		do {
6199 			if (c == '-' && lc != '\0' && *p != ']') {
6200 				if ((c = *p++) == '\0')
6201 					return (0);
6202 				if (c == '\\' && (c = *p++) == '\0')
6203 					return (0);
6204 
6205 				if (notflag) {
6206 					if (s1 < lc || s1 > c)
6207 						ok++;
6208 					else
6209 						return (0);
6210 				} else if (lc <= s1 && s1 <= c)
6211 					ok++;
6212 
6213 			} else if (c == '\\' && (c = *p++) == '\0')
6214 				return (0);
6215 
6216 			lc = c; /* save left-hand 'c' for next iteration */
6217 
6218 			if (notflag) {
6219 				if (s1 != c)
6220 					ok++;
6221 				else
6222 					return (0);
6223 			} else if (s1 == c)
6224 				ok++;
6225 
6226 			if ((c = *p++) == '\0')
6227 				return (0);
6228 
6229 		} while (c != ']');
6230 
6231 		if (ok)
6232 			goto top;
6233 
6234 		return (0);
6235 	}
6236 
6237 	case '\\':
6238 		if ((c = *p++) == '\0')
6239 			return (0);
6240 		/*FALLTHRU*/
6241 
6242 	default:
6243 		if (c != s1)
6244 			return (0);
6245 		/*FALLTHRU*/
6246 
6247 	case '?':
6248 		if (s1 != '\0')
6249 			goto top;
6250 		return (0);
6251 
6252 	case '*':
6253 		while (*p == '*')
6254 			p++; /* consecutive *'s are identical to a single one */
6255 
6256 		if (*p == '\0')
6257 			return (1);
6258 
6259 		for (s = olds; *s != '\0'; s++) {
6260 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
6261 				return (gs);
6262 		}
6263 
6264 		return (0);
6265 	}
6266 }
6267 
6268 /*ARGSUSED*/
6269 static int
6270 dtrace_match_string(const char *s, const char *p, int depth)
6271 {
6272 	return (s != NULL && strcmp(s, p) == 0);
6273 }
6274 
6275 /*ARGSUSED*/
6276 static int
6277 dtrace_match_nul(const char *s, const char *p, int depth)
6278 {
6279 	return (1); /* always match the empty pattern */
6280 }
6281 
6282 /*ARGSUSED*/
6283 static int
6284 dtrace_match_nonzero(const char *s, const char *p, int depth)
6285 {
6286 	return (s != NULL && s[0] != '\0');
6287 }
6288 
6289 static int
6290 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
6291     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
6292 {
6293 	dtrace_probe_t template, *probe;
6294 	dtrace_hash_t *hash = NULL;
6295 	int len, best = INT_MAX, nmatched = 0;
6296 	dtrace_id_t i;
6297 
6298 	ASSERT(MUTEX_HELD(&dtrace_lock));
6299 
6300 	/*
6301 	 * If the probe ID is specified in the key, just lookup by ID and
6302 	 * invoke the match callback once if a matching probe is found.
6303 	 */
6304 	if (pkp->dtpk_id != DTRACE_IDNONE) {
6305 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
6306 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
6307 			(void) (*matched)(probe, arg);
6308 			nmatched++;
6309 		}
6310 		return (nmatched);
6311 	}
6312 
6313 	template.dtpr_mod = (char *)pkp->dtpk_mod;
6314 	template.dtpr_func = (char *)pkp->dtpk_func;
6315 	template.dtpr_name = (char *)pkp->dtpk_name;
6316 
6317 	/*
6318 	 * We want to find the most distinct of the module name, function
6319 	 * name, and name.  So for each one that is not a glob pattern or
6320 	 * empty string, we perform a lookup in the corresponding hash and
6321 	 * use the hash table with the fewest collisions to do our search.
6322 	 */
6323 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
6324 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
6325 		best = len;
6326 		hash = dtrace_bymod;
6327 	}
6328 
6329 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
6330 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
6331 		best = len;
6332 		hash = dtrace_byfunc;
6333 	}
6334 
6335 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
6336 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
6337 		best = len;
6338 		hash = dtrace_byname;
6339 	}
6340 
6341 	/*
6342 	 * If we did not select a hash table, iterate over every probe and
6343 	 * invoke our callback for each one that matches our input probe key.
6344 	 */
6345 	if (hash == NULL) {
6346 		for (i = 0; i < dtrace_nprobes; i++) {
6347 			if ((probe = dtrace_probes[i]) == NULL ||
6348 			    dtrace_match_probe(probe, pkp, priv, uid,
6349 			    zoneid) <= 0)
6350 				continue;
6351 
6352 			nmatched++;
6353 
6354 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
6355 				break;
6356 		}
6357 
6358 		return (nmatched);
6359 	}
6360 
6361 	/*
6362 	 * If we selected a hash table, iterate over each probe of the same key
6363 	 * name and invoke the callback for every probe that matches the other
6364 	 * attributes of our input probe key.
6365 	 */
6366 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
6367 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
6368 
6369 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
6370 			continue;
6371 
6372 		nmatched++;
6373 
6374 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
6375 			break;
6376 	}
6377 
6378 	return (nmatched);
6379 }
6380 
6381 /*
6382  * Return the function pointer dtrace_probecmp() should use to compare the
6383  * specified pattern with a string.  For NULL or empty patterns, we select
6384  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
6385  * For non-empty non-glob strings, we use dtrace_match_string().
6386  */
6387 static dtrace_probekey_f *
6388 dtrace_probekey_func(const char *p)
6389 {
6390 	char c;
6391 
6392 	if (p == NULL || *p == '\0')
6393 		return (&dtrace_match_nul);
6394 
6395 	while ((c = *p++) != '\0') {
6396 		if (c == '[' || c == '?' || c == '*' || c == '\\')
6397 			return (&dtrace_match_glob);
6398 	}
6399 
6400 	return (&dtrace_match_string);
6401 }
6402 
6403 /*
6404  * Build a probe comparison key for use with dtrace_match_probe() from the
6405  * given probe description.  By convention, a null key only matches anchored
6406  * probes: if each field is the empty string, reset dtpk_fmatch to
6407  * dtrace_match_nonzero().
6408  */
6409 static void
6410 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
6411 {
6412 	pkp->dtpk_prov = pdp->dtpd_provider;
6413 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
6414 
6415 	pkp->dtpk_mod = pdp->dtpd_mod;
6416 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
6417 
6418 	pkp->dtpk_func = pdp->dtpd_func;
6419 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
6420 
6421 	pkp->dtpk_name = pdp->dtpd_name;
6422 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
6423 
6424 	pkp->dtpk_id = pdp->dtpd_id;
6425 
6426 	if (pkp->dtpk_id == DTRACE_IDNONE &&
6427 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
6428 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
6429 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
6430 	    pkp->dtpk_nmatch == &dtrace_match_nul)
6431 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
6432 }
6433 
6434 /*
6435  * DTrace Provider-to-Framework API Functions
6436  *
6437  * These functions implement much of the Provider-to-Framework API, as
6438  * described in <sys/dtrace.h>.  The parts of the API not in this section are
6439  * the functions in the API for probe management (found below), and
6440  * dtrace_probe() itself (found above).
6441  */
6442 
6443 /*
6444  * Register the calling provider with the DTrace framework.  This should
6445  * generally be called by DTrace providers in their attach(9E) entry point.
6446  */
6447 int
6448 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
6449     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
6450 {
6451 	dtrace_provider_t *provider;
6452 
6453 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
6454 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6455 		    "arguments", name ? name : "<NULL>");
6456 		return (EINVAL);
6457 	}
6458 
6459 	if (name[0] == '\0' || dtrace_badname(name)) {
6460 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6461 		    "provider name", name);
6462 		return (EINVAL);
6463 	}
6464 
6465 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
6466 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
6467 	    pops->dtps_destroy == NULL ||
6468 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
6469 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6470 		    "provider ops", name);
6471 		return (EINVAL);
6472 	}
6473 
6474 	if (dtrace_badattr(&pap->dtpa_provider) ||
6475 	    dtrace_badattr(&pap->dtpa_mod) ||
6476 	    dtrace_badattr(&pap->dtpa_func) ||
6477 	    dtrace_badattr(&pap->dtpa_name) ||
6478 	    dtrace_badattr(&pap->dtpa_args)) {
6479 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6480 		    "provider attributes", name);
6481 		return (EINVAL);
6482 	}
6483 
6484 	if (priv & ~DTRACE_PRIV_ALL) {
6485 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6486 		    "privilege attributes", name);
6487 		return (EINVAL);
6488 	}
6489 
6490 	if ((priv & DTRACE_PRIV_KERNEL) &&
6491 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
6492 	    pops->dtps_usermode == NULL) {
6493 		cmn_err(CE_WARN, "failed to register provider '%s': need "
6494 		    "dtps_usermode() op for given privilege attributes", name);
6495 		return (EINVAL);
6496 	}
6497 
6498 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
6499 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
6500 	(void) strcpy(provider->dtpv_name, name);
6501 
6502 	provider->dtpv_attr = *pap;
6503 	provider->dtpv_priv.dtpp_flags = priv;
6504 	if (cr != NULL) {
6505 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
6506 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
6507 	}
6508 	provider->dtpv_pops = *pops;
6509 
6510 	if (pops->dtps_provide == NULL) {
6511 		ASSERT(pops->dtps_provide_module != NULL);
6512 		provider->dtpv_pops.dtps_provide =
6513 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
6514 	}
6515 
6516 	if (pops->dtps_provide_module == NULL) {
6517 		ASSERT(pops->dtps_provide != NULL);
6518 		provider->dtpv_pops.dtps_provide_module =
6519 		    (void (*)(void *, struct modctl *))dtrace_nullop;
6520 	}
6521 
6522 	if (pops->dtps_suspend == NULL) {
6523 		ASSERT(pops->dtps_resume == NULL);
6524 		provider->dtpv_pops.dtps_suspend =
6525 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6526 		provider->dtpv_pops.dtps_resume =
6527 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6528 	}
6529 
6530 	provider->dtpv_arg = arg;
6531 	*idp = (dtrace_provider_id_t)provider;
6532 
6533 	if (pops == &dtrace_provider_ops) {
6534 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6535 		ASSERT(MUTEX_HELD(&dtrace_lock));
6536 		ASSERT(dtrace_anon.dta_enabling == NULL);
6537 
6538 		/*
6539 		 * We make sure that the DTrace provider is at the head of
6540 		 * the provider chain.
6541 		 */
6542 		provider->dtpv_next = dtrace_provider;
6543 		dtrace_provider = provider;
6544 		return (0);
6545 	}
6546 
6547 	mutex_enter(&dtrace_provider_lock);
6548 	mutex_enter(&dtrace_lock);
6549 
6550 	/*
6551 	 * If there is at least one provider registered, we'll add this
6552 	 * provider after the first provider.
6553 	 */
6554 	if (dtrace_provider != NULL) {
6555 		provider->dtpv_next = dtrace_provider->dtpv_next;
6556 		dtrace_provider->dtpv_next = provider;
6557 	} else {
6558 		dtrace_provider = provider;
6559 	}
6560 
6561 	if (dtrace_retained != NULL) {
6562 		dtrace_enabling_provide(provider);
6563 
6564 		/*
6565 		 * Now we need to call dtrace_enabling_matchall() -- which
6566 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
6567 		 * to drop all of our locks before calling into it...
6568 		 */
6569 		mutex_exit(&dtrace_lock);
6570 		mutex_exit(&dtrace_provider_lock);
6571 		dtrace_enabling_matchall();
6572 
6573 		return (0);
6574 	}
6575 
6576 	mutex_exit(&dtrace_lock);
6577 	mutex_exit(&dtrace_provider_lock);
6578 
6579 	return (0);
6580 }
6581 
6582 /*
6583  * Unregister the specified provider from the DTrace framework.  This should
6584  * generally be called by DTrace providers in their detach(9E) entry point.
6585  */
6586 int
6587 dtrace_unregister(dtrace_provider_id_t id)
6588 {
6589 	dtrace_provider_t *old = (dtrace_provider_t *)id;
6590 	dtrace_provider_t *prev = NULL;
6591 	int i, self = 0;
6592 	dtrace_probe_t *probe, *first = NULL;
6593 
6594 	if (old->dtpv_pops.dtps_enable ==
6595 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
6596 		/*
6597 		 * If DTrace itself is the provider, we're called with locks
6598 		 * already held.
6599 		 */
6600 		ASSERT(old == dtrace_provider);
6601 		ASSERT(dtrace_devi != NULL);
6602 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6603 		ASSERT(MUTEX_HELD(&dtrace_lock));
6604 		self = 1;
6605 
6606 		if (dtrace_provider->dtpv_next != NULL) {
6607 			/*
6608 			 * There's another provider here; return failure.
6609 			 */
6610 			return (EBUSY);
6611 		}
6612 	} else {
6613 		mutex_enter(&dtrace_provider_lock);
6614 		mutex_enter(&mod_lock);
6615 		mutex_enter(&dtrace_lock);
6616 	}
6617 
6618 	/*
6619 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
6620 	 * probes, we refuse to let providers slither away, unless this
6621 	 * provider has already been explicitly invalidated.
6622 	 */
6623 	if (!old->dtpv_defunct &&
6624 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
6625 	    dtrace_anon.dta_state->dts_necbs > 0))) {
6626 		if (!self) {
6627 			mutex_exit(&dtrace_lock);
6628 			mutex_exit(&mod_lock);
6629 			mutex_exit(&dtrace_provider_lock);
6630 		}
6631 		return (EBUSY);
6632 	}
6633 
6634 	/*
6635 	 * Attempt to destroy the probes associated with this provider.
6636 	 */
6637 	for (i = 0; i < dtrace_nprobes; i++) {
6638 		if ((probe = dtrace_probes[i]) == NULL)
6639 			continue;
6640 
6641 		if (probe->dtpr_provider != old)
6642 			continue;
6643 
6644 		if (probe->dtpr_ecb == NULL)
6645 			continue;
6646 
6647 		/*
6648 		 * We have at least one ECB; we can't remove this provider.
6649 		 */
6650 		if (!self) {
6651 			mutex_exit(&dtrace_lock);
6652 			mutex_exit(&mod_lock);
6653 			mutex_exit(&dtrace_provider_lock);
6654 		}
6655 		return (EBUSY);
6656 	}
6657 
6658 	/*
6659 	 * All of the probes for this provider are disabled; we can safely
6660 	 * remove all of them from their hash chains and from the probe array.
6661 	 */
6662 	for (i = 0; i < dtrace_nprobes; i++) {
6663 		if ((probe = dtrace_probes[i]) == NULL)
6664 			continue;
6665 
6666 		if (probe->dtpr_provider != old)
6667 			continue;
6668 
6669 		dtrace_probes[i] = NULL;
6670 
6671 		dtrace_hash_remove(dtrace_bymod, probe);
6672 		dtrace_hash_remove(dtrace_byfunc, probe);
6673 		dtrace_hash_remove(dtrace_byname, probe);
6674 
6675 		if (first == NULL) {
6676 			first = probe;
6677 			probe->dtpr_nextmod = NULL;
6678 		} else {
6679 			probe->dtpr_nextmod = first;
6680 			first = probe;
6681 		}
6682 	}
6683 
6684 	/*
6685 	 * The provider's probes have been removed from the hash chains and
6686 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
6687 	 * everyone has cleared out from any probe array processing.
6688 	 */
6689 	dtrace_sync();
6690 
6691 	for (probe = first; probe != NULL; probe = first) {
6692 		first = probe->dtpr_nextmod;
6693 
6694 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
6695 		    probe->dtpr_arg);
6696 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
6697 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
6698 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
6699 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
6700 		kmem_free(probe, sizeof (dtrace_probe_t));
6701 	}
6702 
6703 	if ((prev = dtrace_provider) == old) {
6704 		ASSERT(self || dtrace_devi == NULL);
6705 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
6706 		dtrace_provider = old->dtpv_next;
6707 	} else {
6708 		while (prev != NULL && prev->dtpv_next != old)
6709 			prev = prev->dtpv_next;
6710 
6711 		if (prev == NULL) {
6712 			panic("attempt to unregister non-existent "
6713 			    "dtrace provider %p\n", (void *)id);
6714 		}
6715 
6716 		prev->dtpv_next = old->dtpv_next;
6717 	}
6718 
6719 	if (!self) {
6720 		mutex_exit(&dtrace_lock);
6721 		mutex_exit(&mod_lock);
6722 		mutex_exit(&dtrace_provider_lock);
6723 	}
6724 
6725 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
6726 	kmem_free(old, sizeof (dtrace_provider_t));
6727 
6728 	return (0);
6729 }
6730 
6731 /*
6732  * Invalidate the specified provider.  All subsequent probe lookups for the
6733  * specified provider will fail, but its probes will not be removed.
6734  */
6735 void
6736 dtrace_invalidate(dtrace_provider_id_t id)
6737 {
6738 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
6739 
6740 	ASSERT(pvp->dtpv_pops.dtps_enable !=
6741 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6742 
6743 	mutex_enter(&dtrace_provider_lock);
6744 	mutex_enter(&dtrace_lock);
6745 
6746 	pvp->dtpv_defunct = 1;
6747 
6748 	mutex_exit(&dtrace_lock);
6749 	mutex_exit(&dtrace_provider_lock);
6750 }
6751 
6752 /*
6753  * Indicate whether or not DTrace has attached.
6754  */
6755 int
6756 dtrace_attached(void)
6757 {
6758 	/*
6759 	 * dtrace_provider will be non-NULL iff the DTrace driver has
6760 	 * attached.  (It's non-NULL because DTrace is always itself a
6761 	 * provider.)
6762 	 */
6763 	return (dtrace_provider != NULL);
6764 }
6765 
6766 /*
6767  * Remove all the unenabled probes for the given provider.  This function is
6768  * not unlike dtrace_unregister(), except that it doesn't remove the provider
6769  * -- just as many of its associated probes as it can.
6770  */
6771 int
6772 dtrace_condense(dtrace_provider_id_t id)
6773 {
6774 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
6775 	int i;
6776 	dtrace_probe_t *probe;
6777 
6778 	/*
6779 	 * Make sure this isn't the dtrace provider itself.
6780 	 */
6781 	ASSERT(prov->dtpv_pops.dtps_enable !=
6782 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6783 
6784 	mutex_enter(&dtrace_provider_lock);
6785 	mutex_enter(&dtrace_lock);
6786 
6787 	/*
6788 	 * Attempt to destroy the probes associated with this provider.
6789 	 */
6790 	for (i = 0; i < dtrace_nprobes; i++) {
6791 		if ((probe = dtrace_probes[i]) == NULL)
6792 			continue;
6793 
6794 		if (probe->dtpr_provider != prov)
6795 			continue;
6796 
6797 		if (probe->dtpr_ecb != NULL)
6798 			continue;
6799 
6800 		dtrace_probes[i] = NULL;
6801 
6802 		dtrace_hash_remove(dtrace_bymod, probe);
6803 		dtrace_hash_remove(dtrace_byfunc, probe);
6804 		dtrace_hash_remove(dtrace_byname, probe);
6805 
6806 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
6807 		    probe->dtpr_arg);
6808 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
6809 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
6810 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
6811 		kmem_free(probe, sizeof (dtrace_probe_t));
6812 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
6813 	}
6814 
6815 	mutex_exit(&dtrace_lock);
6816 	mutex_exit(&dtrace_provider_lock);
6817 
6818 	return (0);
6819 }
6820 
6821 /*
6822  * DTrace Probe Management Functions
6823  *
6824  * The functions in this section perform the DTrace probe management,
6825  * including functions to create probes, look-up probes, and call into the
6826  * providers to request that probes be provided.  Some of these functions are
6827  * in the Provider-to-Framework API; these functions can be identified by the
6828  * fact that they are not declared "static".
6829  */
6830 
6831 /*
6832  * Create a probe with the specified module name, function name, and name.
6833  */
6834 dtrace_id_t
6835 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
6836     const char *func, const char *name, int aframes, void *arg)
6837 {
6838 	dtrace_probe_t *probe, **probes;
6839 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
6840 	dtrace_id_t id;
6841 
6842 	if (provider == dtrace_provider) {
6843 		ASSERT(MUTEX_HELD(&dtrace_lock));
6844 	} else {
6845 		mutex_enter(&dtrace_lock);
6846 	}
6847 
6848 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
6849 	    VM_BESTFIT | VM_SLEEP);
6850 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
6851 
6852 	probe->dtpr_id = id;
6853 	probe->dtpr_gen = dtrace_probegen++;
6854 	probe->dtpr_mod = dtrace_strdup(mod);
6855 	probe->dtpr_func = dtrace_strdup(func);
6856 	probe->dtpr_name = dtrace_strdup(name);
6857 	probe->dtpr_arg = arg;
6858 	probe->dtpr_aframes = aframes;
6859 	probe->dtpr_provider = provider;
6860 
6861 	dtrace_hash_add(dtrace_bymod, probe);
6862 	dtrace_hash_add(dtrace_byfunc, probe);
6863 	dtrace_hash_add(dtrace_byname, probe);
6864 
6865 	if (id - 1 >= dtrace_nprobes) {
6866 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
6867 		size_t nsize = osize << 1;
6868 
6869 		if (nsize == 0) {
6870 			ASSERT(osize == 0);
6871 			ASSERT(dtrace_probes == NULL);
6872 			nsize = sizeof (dtrace_probe_t *);
6873 		}
6874 
6875 		probes = kmem_zalloc(nsize, KM_SLEEP);
6876 
6877 		if (dtrace_probes == NULL) {
6878 			ASSERT(osize == 0);
6879 			dtrace_probes = probes;
6880 			dtrace_nprobes = 1;
6881 		} else {
6882 			dtrace_probe_t **oprobes = dtrace_probes;
6883 
6884 			bcopy(oprobes, probes, osize);
6885 			dtrace_membar_producer();
6886 			dtrace_probes = probes;
6887 
6888 			dtrace_sync();
6889 
6890 			/*
6891 			 * All CPUs are now seeing the new probes array; we can
6892 			 * safely free the old array.
6893 			 */
6894 			kmem_free(oprobes, osize);
6895 			dtrace_nprobes <<= 1;
6896 		}
6897 
6898 		ASSERT(id - 1 < dtrace_nprobes);
6899 	}
6900 
6901 	ASSERT(dtrace_probes[id - 1] == NULL);
6902 	dtrace_probes[id - 1] = probe;
6903 
6904 	if (provider != dtrace_provider)
6905 		mutex_exit(&dtrace_lock);
6906 
6907 	return (id);
6908 }
6909 
6910 static dtrace_probe_t *
6911 dtrace_probe_lookup_id(dtrace_id_t id)
6912 {
6913 	ASSERT(MUTEX_HELD(&dtrace_lock));
6914 
6915 	if (id == 0 || id > dtrace_nprobes)
6916 		return (NULL);
6917 
6918 	return (dtrace_probes[id - 1]);
6919 }
6920 
6921 static int
6922 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
6923 {
6924 	*((dtrace_id_t *)arg) = probe->dtpr_id;
6925 
6926 	return (DTRACE_MATCH_DONE);
6927 }
6928 
6929 /*
6930  * Look up a probe based on provider and one or more of module name, function
6931  * name and probe name.
6932  */
6933 dtrace_id_t
6934 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
6935     const char *func, const char *name)
6936 {
6937 	dtrace_probekey_t pkey;
6938 	dtrace_id_t id;
6939 	int match;
6940 
6941 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
6942 	pkey.dtpk_pmatch = &dtrace_match_string;
6943 	pkey.dtpk_mod = mod;
6944 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
6945 	pkey.dtpk_func = func;
6946 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
6947 	pkey.dtpk_name = name;
6948 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
6949 	pkey.dtpk_id = DTRACE_IDNONE;
6950 
6951 	mutex_enter(&dtrace_lock);
6952 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
6953 	    dtrace_probe_lookup_match, &id);
6954 	mutex_exit(&dtrace_lock);
6955 
6956 	ASSERT(match == 1 || match == 0);
6957 	return (match ? id : 0);
6958 }
6959 
6960 /*
6961  * Returns the probe argument associated with the specified probe.
6962  */
6963 void *
6964 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
6965 {
6966 	dtrace_probe_t *probe;
6967 	void *rval = NULL;
6968 
6969 	mutex_enter(&dtrace_lock);
6970 
6971 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
6972 	    probe->dtpr_provider == (dtrace_provider_t *)id)
6973 		rval = probe->dtpr_arg;
6974 
6975 	mutex_exit(&dtrace_lock);
6976 
6977 	return (rval);
6978 }
6979 
6980 /*
6981  * Copy a probe into a probe description.
6982  */
6983 static void
6984 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
6985 {
6986 	bzero(pdp, sizeof (dtrace_probedesc_t));
6987 	pdp->dtpd_id = prp->dtpr_id;
6988 
6989 	(void) strncpy(pdp->dtpd_provider,
6990 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
6991 
6992 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
6993 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
6994 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
6995 }
6996 
6997 /*
6998  * Called to indicate that a probe -- or probes -- should be provided by a
6999  * specfied provider.  If the specified description is NULL, the provider will
7000  * be told to provide all of its probes.  (This is done whenever a new
7001  * consumer comes along, or whenever a retained enabling is to be matched.) If
7002  * the specified description is non-NULL, the provider is given the
7003  * opportunity to dynamically provide the specified probe, allowing providers
7004  * to support the creation of probes on-the-fly.  (So-called _autocreated_
7005  * probes.)  If the provider is NULL, the operations will be applied to all
7006  * providers; if the provider is non-NULL the operations will only be applied
7007  * to the specified provider.  The dtrace_provider_lock must be held, and the
7008  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
7009  * will need to grab the dtrace_lock when it reenters the framework through
7010  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
7011  */
7012 static void
7013 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
7014 {
7015 	struct modctl *ctl;
7016 	int all = 0;
7017 
7018 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7019 
7020 	if (prv == NULL) {
7021 		all = 1;
7022 		prv = dtrace_provider;
7023 	}
7024 
7025 	do {
7026 		/*
7027 		 * First, call the blanket provide operation.
7028 		 */
7029 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
7030 
7031 		/*
7032 		 * Now call the per-module provide operation.  We will grab
7033 		 * mod_lock to prevent the list from being modified.  Note
7034 		 * that this also prevents the mod_busy bits from changing.
7035 		 * (mod_busy can only be changed with mod_lock held.)
7036 		 */
7037 		mutex_enter(&mod_lock);
7038 
7039 		ctl = &modules;
7040 		do {
7041 			if (ctl->mod_busy || ctl->mod_mp == NULL)
7042 				continue;
7043 
7044 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
7045 
7046 		} while ((ctl = ctl->mod_next) != &modules);
7047 
7048 		mutex_exit(&mod_lock);
7049 	} while (all && (prv = prv->dtpv_next) != NULL);
7050 }
7051 
7052 /*
7053  * Iterate over each probe, and call the Framework-to-Provider API function
7054  * denoted by offs.
7055  */
7056 static void
7057 dtrace_probe_foreach(uintptr_t offs)
7058 {
7059 	dtrace_provider_t *prov;
7060 	void (*func)(void *, dtrace_id_t, void *);
7061 	dtrace_probe_t *probe;
7062 	dtrace_icookie_t cookie;
7063 	int i;
7064 
7065 	/*
7066 	 * We disable interrupts to walk through the probe array.  This is
7067 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
7068 	 * won't see stale data.
7069 	 */
7070 	cookie = dtrace_interrupt_disable();
7071 
7072 	for (i = 0; i < dtrace_nprobes; i++) {
7073 		if ((probe = dtrace_probes[i]) == NULL)
7074 			continue;
7075 
7076 		if (probe->dtpr_ecb == NULL) {
7077 			/*
7078 			 * This probe isn't enabled -- don't call the function.
7079 			 */
7080 			continue;
7081 		}
7082 
7083 		prov = probe->dtpr_provider;
7084 		func = *((void(**)(void *, dtrace_id_t, void *))
7085 		    ((uintptr_t)&prov->dtpv_pops + offs));
7086 
7087 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
7088 	}
7089 
7090 	dtrace_interrupt_enable(cookie);
7091 }
7092 
7093 static int
7094 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
7095 {
7096 	dtrace_probekey_t pkey;
7097 	uint32_t priv;
7098 	uid_t uid;
7099 	zoneid_t zoneid;
7100 
7101 	ASSERT(MUTEX_HELD(&dtrace_lock));
7102 	dtrace_ecb_create_cache = NULL;
7103 
7104 	if (desc == NULL) {
7105 		/*
7106 		 * If we're passed a NULL description, we're being asked to
7107 		 * create an ECB with a NULL probe.
7108 		 */
7109 		(void) dtrace_ecb_create_enable(NULL, enab);
7110 		return (0);
7111 	}
7112 
7113 	dtrace_probekey(desc, &pkey);
7114 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
7115 	    &priv, &uid, &zoneid);
7116 
7117 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
7118 	    enab));
7119 }
7120 
7121 /*
7122  * DTrace Helper Provider Functions
7123  */
7124 static void
7125 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
7126 {
7127 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
7128 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
7129 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
7130 }
7131 
7132 static void
7133 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
7134     const dof_provider_t *dofprov, char *strtab)
7135 {
7136 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
7137 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
7138 	    dofprov->dofpv_provattr);
7139 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
7140 	    dofprov->dofpv_modattr);
7141 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
7142 	    dofprov->dofpv_funcattr);
7143 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
7144 	    dofprov->dofpv_nameattr);
7145 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
7146 	    dofprov->dofpv_argsattr);
7147 }
7148 
7149 static void
7150 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7151 {
7152 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7153 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7154 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
7155 	dof_provider_t *provider;
7156 	dof_probe_t *probe;
7157 	uint32_t *off, *enoff;
7158 	uint8_t *arg;
7159 	char *strtab;
7160 	uint_t i, nprobes;
7161 	dtrace_helper_provdesc_t dhpv;
7162 	dtrace_helper_probedesc_t dhpb;
7163 	dtrace_meta_t *meta = dtrace_meta_pid;
7164 	dtrace_mops_t *mops = &meta->dtm_mops;
7165 	void *parg;
7166 
7167 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7168 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7169 	    provider->dofpv_strtab * dof->dofh_secsize);
7170 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7171 	    provider->dofpv_probes * dof->dofh_secsize);
7172 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7173 	    provider->dofpv_prargs * dof->dofh_secsize);
7174 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7175 	    provider->dofpv_proffs * dof->dofh_secsize);
7176 
7177 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7178 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
7179 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
7180 	enoff = NULL;
7181 
7182 	/*
7183 	 * See dtrace_helper_provider_validate().
7184 	 */
7185 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
7186 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
7187 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7188 		    provider->dofpv_prenoffs * dof->dofh_secsize);
7189 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
7190 	}
7191 
7192 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
7193 
7194 	/*
7195 	 * Create the provider.
7196 	 */
7197 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7198 
7199 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
7200 		return;
7201 
7202 	meta->dtm_count++;
7203 
7204 	/*
7205 	 * Create the probes.
7206 	 */
7207 	for (i = 0; i < nprobes; i++) {
7208 		probe = (dof_probe_t *)(uintptr_t)(daddr +
7209 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
7210 
7211 		dhpb.dthpb_mod = dhp->dofhp_mod;
7212 		dhpb.dthpb_func = strtab + probe->dofpr_func;
7213 		dhpb.dthpb_name = strtab + probe->dofpr_name;
7214 		dhpb.dthpb_base = probe->dofpr_addr;
7215 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
7216 		dhpb.dthpb_noffs = probe->dofpr_noffs;
7217 		if (enoff != NULL) {
7218 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
7219 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
7220 		} else {
7221 			dhpb.dthpb_enoffs = NULL;
7222 			dhpb.dthpb_nenoffs = 0;
7223 		}
7224 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
7225 		dhpb.dthpb_nargc = probe->dofpr_nargc;
7226 		dhpb.dthpb_xargc = probe->dofpr_xargc;
7227 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
7228 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
7229 
7230 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
7231 	}
7232 }
7233 
7234 static void
7235 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
7236 {
7237 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7238 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7239 	int i;
7240 
7241 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7242 
7243 	for (i = 0; i < dof->dofh_secnum; i++) {
7244 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7245 		    dof->dofh_secoff + i * dof->dofh_secsize);
7246 
7247 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7248 			continue;
7249 
7250 		dtrace_helper_provide_one(dhp, sec, pid);
7251 	}
7252 
7253 	/*
7254 	 * We may have just created probes, so we must now rematch against
7255 	 * any retained enablings.  Note that this call will acquire both
7256 	 * cpu_lock and dtrace_lock; the fact that we are holding
7257 	 * dtrace_meta_lock now is what defines the ordering with respect to
7258 	 * these three locks.
7259 	 */
7260 	dtrace_enabling_matchall();
7261 }
7262 
7263 static void
7264 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7265 {
7266 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7267 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7268 	dof_sec_t *str_sec;
7269 	dof_provider_t *provider;
7270 	char *strtab;
7271 	dtrace_helper_provdesc_t dhpv;
7272 	dtrace_meta_t *meta = dtrace_meta_pid;
7273 	dtrace_mops_t *mops = &meta->dtm_mops;
7274 
7275 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7276 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7277 	    provider->dofpv_strtab * dof->dofh_secsize);
7278 
7279 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7280 
7281 	/*
7282 	 * Create the provider.
7283 	 */
7284 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7285 
7286 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
7287 
7288 	meta->dtm_count--;
7289 }
7290 
7291 static void
7292 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
7293 {
7294 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7295 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7296 	int i;
7297 
7298 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7299 
7300 	for (i = 0; i < dof->dofh_secnum; i++) {
7301 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7302 		    dof->dofh_secoff + i * dof->dofh_secsize);
7303 
7304 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7305 			continue;
7306 
7307 		dtrace_helper_provider_remove_one(dhp, sec, pid);
7308 	}
7309 }
7310 
7311 /*
7312  * DTrace Meta Provider-to-Framework API Functions
7313  *
7314  * These functions implement the Meta Provider-to-Framework API, as described
7315  * in <sys/dtrace.h>.
7316  */
7317 int
7318 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
7319     dtrace_meta_provider_id_t *idp)
7320 {
7321 	dtrace_meta_t *meta;
7322 	dtrace_helpers_t *help, *next;
7323 	int i;
7324 
7325 	*idp = DTRACE_METAPROVNONE;
7326 
7327 	/*
7328 	 * We strictly don't need the name, but we hold onto it for
7329 	 * debuggability. All hail error queues!
7330 	 */
7331 	if (name == NULL) {
7332 		cmn_err(CE_WARN, "failed to register meta-provider: "
7333 		    "invalid name");
7334 		return (EINVAL);
7335 	}
7336 
7337 	if (mops == NULL ||
7338 	    mops->dtms_create_probe == NULL ||
7339 	    mops->dtms_provide_pid == NULL ||
7340 	    mops->dtms_remove_pid == NULL) {
7341 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7342 		    "invalid ops", name);
7343 		return (EINVAL);
7344 	}
7345 
7346 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
7347 	meta->dtm_mops = *mops;
7348 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7349 	(void) strcpy(meta->dtm_name, name);
7350 	meta->dtm_arg = arg;
7351 
7352 	mutex_enter(&dtrace_meta_lock);
7353 	mutex_enter(&dtrace_lock);
7354 
7355 	if (dtrace_meta_pid != NULL) {
7356 		mutex_exit(&dtrace_lock);
7357 		mutex_exit(&dtrace_meta_lock);
7358 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7359 		    "user-land meta-provider exists", name);
7360 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
7361 		kmem_free(meta, sizeof (dtrace_meta_t));
7362 		return (EINVAL);
7363 	}
7364 
7365 	dtrace_meta_pid = meta;
7366 	*idp = (dtrace_meta_provider_id_t)meta;
7367 
7368 	/*
7369 	 * If there are providers and probes ready to go, pass them
7370 	 * off to the new meta provider now.
7371 	 */
7372 
7373 	help = dtrace_deferred_pid;
7374 	dtrace_deferred_pid = NULL;
7375 
7376 	mutex_exit(&dtrace_lock);
7377 
7378 	while (help != NULL) {
7379 		for (i = 0; i < help->dthps_nprovs; i++) {
7380 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
7381 			    help->dthps_pid);
7382 		}
7383 
7384 		next = help->dthps_next;
7385 		help->dthps_next = NULL;
7386 		help->dthps_prev = NULL;
7387 		help->dthps_deferred = 0;
7388 		help = next;
7389 	}
7390 
7391 	mutex_exit(&dtrace_meta_lock);
7392 
7393 	return (0);
7394 }
7395 
7396 int
7397 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
7398 {
7399 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
7400 
7401 	mutex_enter(&dtrace_meta_lock);
7402 	mutex_enter(&dtrace_lock);
7403 
7404 	if (old == dtrace_meta_pid) {
7405 		pp = &dtrace_meta_pid;
7406 	} else {
7407 		panic("attempt to unregister non-existent "
7408 		    "dtrace meta-provider %p\n", (void *)old);
7409 	}
7410 
7411 	if (old->dtm_count != 0) {
7412 		mutex_exit(&dtrace_lock);
7413 		mutex_exit(&dtrace_meta_lock);
7414 		return (EBUSY);
7415 	}
7416 
7417 	*pp = NULL;
7418 
7419 	mutex_exit(&dtrace_lock);
7420 	mutex_exit(&dtrace_meta_lock);
7421 
7422 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
7423 	kmem_free(old, sizeof (dtrace_meta_t));
7424 
7425 	return (0);
7426 }
7427 
7428 
7429 /*
7430  * DTrace DIF Object Functions
7431  */
7432 static int
7433 dtrace_difo_err(uint_t pc, const char *format, ...)
7434 {
7435 	if (dtrace_err_verbose) {
7436 		va_list alist;
7437 
7438 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
7439 		va_start(alist, format);
7440 		(void) vuprintf(format, alist);
7441 		va_end(alist);
7442 	}
7443 
7444 #ifdef DTRACE_ERRDEBUG
7445 	dtrace_errdebug(format);
7446 #endif
7447 	return (1);
7448 }
7449 
7450 /*
7451  * Validate a DTrace DIF object by checking the IR instructions.  The following
7452  * rules are currently enforced by dtrace_difo_validate():
7453  *
7454  * 1. Each instruction must have a valid opcode
7455  * 2. Each register, string, variable, or subroutine reference must be valid
7456  * 3. No instruction can modify register %r0 (must be zero)
7457  * 4. All instruction reserved bits must be set to zero
7458  * 5. The last instruction must be a "ret" instruction
7459  * 6. All branch targets must reference a valid instruction _after_ the branch
7460  */
7461 static int
7462 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
7463     cred_t *cr)
7464 {
7465 	int err = 0, i;
7466 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
7467 	int kcheckload;
7468 	uint_t pc;
7469 
7470 	kcheckload = cr == NULL ||
7471 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
7472 
7473 	dp->dtdo_destructive = 0;
7474 
7475 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
7476 		dif_instr_t instr = dp->dtdo_buf[pc];
7477 
7478 		uint_t r1 = DIF_INSTR_R1(instr);
7479 		uint_t r2 = DIF_INSTR_R2(instr);
7480 		uint_t rd = DIF_INSTR_RD(instr);
7481 		uint_t rs = DIF_INSTR_RS(instr);
7482 		uint_t label = DIF_INSTR_LABEL(instr);
7483 		uint_t v = DIF_INSTR_VAR(instr);
7484 		uint_t subr = DIF_INSTR_SUBR(instr);
7485 		uint_t type = DIF_INSTR_TYPE(instr);
7486 		uint_t op = DIF_INSTR_OP(instr);
7487 
7488 		switch (op) {
7489 		case DIF_OP_OR:
7490 		case DIF_OP_XOR:
7491 		case DIF_OP_AND:
7492 		case DIF_OP_SLL:
7493 		case DIF_OP_SRL:
7494 		case DIF_OP_SRA:
7495 		case DIF_OP_SUB:
7496 		case DIF_OP_ADD:
7497 		case DIF_OP_MUL:
7498 		case DIF_OP_SDIV:
7499 		case DIF_OP_UDIV:
7500 		case DIF_OP_SREM:
7501 		case DIF_OP_UREM:
7502 		case DIF_OP_COPYS:
7503 			if (r1 >= nregs)
7504 				err += efunc(pc, "invalid register %u\n", r1);
7505 			if (r2 >= nregs)
7506 				err += efunc(pc, "invalid register %u\n", r2);
7507 			if (rd >= nregs)
7508 				err += efunc(pc, "invalid register %u\n", rd);
7509 			if (rd == 0)
7510 				err += efunc(pc, "cannot write to %r0\n");
7511 			break;
7512 		case DIF_OP_NOT:
7513 		case DIF_OP_MOV:
7514 		case DIF_OP_ALLOCS:
7515 			if (r1 >= nregs)
7516 				err += efunc(pc, "invalid register %u\n", r1);
7517 			if (r2 != 0)
7518 				err += efunc(pc, "non-zero reserved bits\n");
7519 			if (rd >= nregs)
7520 				err += efunc(pc, "invalid register %u\n", rd);
7521 			if (rd == 0)
7522 				err += efunc(pc, "cannot write to %r0\n");
7523 			break;
7524 		case DIF_OP_LDSB:
7525 		case DIF_OP_LDSH:
7526 		case DIF_OP_LDSW:
7527 		case DIF_OP_LDUB:
7528 		case DIF_OP_LDUH:
7529 		case DIF_OP_LDUW:
7530 		case DIF_OP_LDX:
7531 			if (r1 >= nregs)
7532 				err += efunc(pc, "invalid register %u\n", r1);
7533 			if (r2 != 0)
7534 				err += efunc(pc, "non-zero reserved bits\n");
7535 			if (rd >= nregs)
7536 				err += efunc(pc, "invalid register %u\n", rd);
7537 			if (rd == 0)
7538 				err += efunc(pc, "cannot write to %r0\n");
7539 			if (kcheckload)
7540 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
7541 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
7542 			break;
7543 		case DIF_OP_RLDSB:
7544 		case DIF_OP_RLDSH:
7545 		case DIF_OP_RLDSW:
7546 		case DIF_OP_RLDUB:
7547 		case DIF_OP_RLDUH:
7548 		case DIF_OP_RLDUW:
7549 		case DIF_OP_RLDX:
7550 			if (r1 >= nregs)
7551 				err += efunc(pc, "invalid register %u\n", r1);
7552 			if (r2 != 0)
7553 				err += efunc(pc, "non-zero reserved bits\n");
7554 			if (rd >= nregs)
7555 				err += efunc(pc, "invalid register %u\n", rd);
7556 			if (rd == 0)
7557 				err += efunc(pc, "cannot write to %r0\n");
7558 			break;
7559 		case DIF_OP_ULDSB:
7560 		case DIF_OP_ULDSH:
7561 		case DIF_OP_ULDSW:
7562 		case DIF_OP_ULDUB:
7563 		case DIF_OP_ULDUH:
7564 		case DIF_OP_ULDUW:
7565 		case DIF_OP_ULDX:
7566 			if (r1 >= nregs)
7567 				err += efunc(pc, "invalid register %u\n", r1);
7568 			if (r2 != 0)
7569 				err += efunc(pc, "non-zero reserved bits\n");
7570 			if (rd >= nregs)
7571 				err += efunc(pc, "invalid register %u\n", rd);
7572 			if (rd == 0)
7573 				err += efunc(pc, "cannot write to %r0\n");
7574 			break;
7575 		case DIF_OP_STB:
7576 		case DIF_OP_STH:
7577 		case DIF_OP_STW:
7578 		case DIF_OP_STX:
7579 			if (r1 >= nregs)
7580 				err += efunc(pc, "invalid register %u\n", r1);
7581 			if (r2 != 0)
7582 				err += efunc(pc, "non-zero reserved bits\n");
7583 			if (rd >= nregs)
7584 				err += efunc(pc, "invalid register %u\n", rd);
7585 			if (rd == 0)
7586 				err += efunc(pc, "cannot write to 0 address\n");
7587 			break;
7588 		case DIF_OP_CMP:
7589 		case DIF_OP_SCMP:
7590 			if (r1 >= nregs)
7591 				err += efunc(pc, "invalid register %u\n", r1);
7592 			if (r2 >= nregs)
7593 				err += efunc(pc, "invalid register %u\n", r2);
7594 			if (rd != 0)
7595 				err += efunc(pc, "non-zero reserved bits\n");
7596 			break;
7597 		case DIF_OP_TST:
7598 			if (r1 >= nregs)
7599 				err += efunc(pc, "invalid register %u\n", r1);
7600 			if (r2 != 0 || rd != 0)
7601 				err += efunc(pc, "non-zero reserved bits\n");
7602 			break;
7603 		case DIF_OP_BA:
7604 		case DIF_OP_BE:
7605 		case DIF_OP_BNE:
7606 		case DIF_OP_BG:
7607 		case DIF_OP_BGU:
7608 		case DIF_OP_BGE:
7609 		case DIF_OP_BGEU:
7610 		case DIF_OP_BL:
7611 		case DIF_OP_BLU:
7612 		case DIF_OP_BLE:
7613 		case DIF_OP_BLEU:
7614 			if (label >= dp->dtdo_len) {
7615 				err += efunc(pc, "invalid branch target %u\n",
7616 				    label);
7617 			}
7618 			if (label <= pc) {
7619 				err += efunc(pc, "backward branch to %u\n",
7620 				    label);
7621 			}
7622 			break;
7623 		case DIF_OP_RET:
7624 			if (r1 != 0 || r2 != 0)
7625 				err += efunc(pc, "non-zero reserved bits\n");
7626 			if (rd >= nregs)
7627 				err += efunc(pc, "invalid register %u\n", rd);
7628 			break;
7629 		case DIF_OP_NOP:
7630 		case DIF_OP_POPTS:
7631 		case DIF_OP_FLUSHTS:
7632 			if (r1 != 0 || r2 != 0 || rd != 0)
7633 				err += efunc(pc, "non-zero reserved bits\n");
7634 			break;
7635 		case DIF_OP_SETX:
7636 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
7637 				err += efunc(pc, "invalid integer ref %u\n",
7638 				    DIF_INSTR_INTEGER(instr));
7639 			}
7640 			if (rd >= nregs)
7641 				err += efunc(pc, "invalid register %u\n", rd);
7642 			if (rd == 0)
7643 				err += efunc(pc, "cannot write to %r0\n");
7644 			break;
7645 		case DIF_OP_SETS:
7646 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
7647 				err += efunc(pc, "invalid string ref %u\n",
7648 				    DIF_INSTR_STRING(instr));
7649 			}
7650 			if (rd >= nregs)
7651 				err += efunc(pc, "invalid register %u\n", rd);
7652 			if (rd == 0)
7653 				err += efunc(pc, "cannot write to %r0\n");
7654 			break;
7655 		case DIF_OP_LDGA:
7656 		case DIF_OP_LDTA:
7657 			if (r1 > DIF_VAR_ARRAY_MAX)
7658 				err += efunc(pc, "invalid array %u\n", r1);
7659 			if (r2 >= nregs)
7660 				err += efunc(pc, "invalid register %u\n", r2);
7661 			if (rd >= nregs)
7662 				err += efunc(pc, "invalid register %u\n", rd);
7663 			if (rd == 0)
7664 				err += efunc(pc, "cannot write to %r0\n");
7665 			break;
7666 		case DIF_OP_LDGS:
7667 		case DIF_OP_LDTS:
7668 		case DIF_OP_LDLS:
7669 		case DIF_OP_LDGAA:
7670 		case DIF_OP_LDTAA:
7671 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
7672 				err += efunc(pc, "invalid variable %u\n", v);
7673 			if (rd >= nregs)
7674 				err += efunc(pc, "invalid register %u\n", rd);
7675 			if (rd == 0)
7676 				err += efunc(pc, "cannot write to %r0\n");
7677 			break;
7678 		case DIF_OP_STGS:
7679 		case DIF_OP_STTS:
7680 		case DIF_OP_STLS:
7681 		case DIF_OP_STGAA:
7682 		case DIF_OP_STTAA:
7683 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
7684 				err += efunc(pc, "invalid variable %u\n", v);
7685 			if (rs >= nregs)
7686 				err += efunc(pc, "invalid register %u\n", rd);
7687 			break;
7688 		case DIF_OP_CALL:
7689 			if (subr > DIF_SUBR_MAX)
7690 				err += efunc(pc, "invalid subr %u\n", subr);
7691 			if (rd >= nregs)
7692 				err += efunc(pc, "invalid register %u\n", rd);
7693 			if (rd == 0)
7694 				err += efunc(pc, "cannot write to %r0\n");
7695 
7696 			if (subr == DIF_SUBR_COPYOUT ||
7697 			    subr == DIF_SUBR_COPYOUTSTR) {
7698 				dp->dtdo_destructive = 1;
7699 			}
7700 			break;
7701 		case DIF_OP_PUSHTR:
7702 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
7703 				err += efunc(pc, "invalid ref type %u\n", type);
7704 			if (r2 >= nregs)
7705 				err += efunc(pc, "invalid register %u\n", r2);
7706 			if (rs >= nregs)
7707 				err += efunc(pc, "invalid register %u\n", rs);
7708 			break;
7709 		case DIF_OP_PUSHTV:
7710 			if (type != DIF_TYPE_CTF)
7711 				err += efunc(pc, "invalid val type %u\n", type);
7712 			if (r2 >= nregs)
7713 				err += efunc(pc, "invalid register %u\n", r2);
7714 			if (rs >= nregs)
7715 				err += efunc(pc, "invalid register %u\n", rs);
7716 			break;
7717 		default:
7718 			err += efunc(pc, "invalid opcode %u\n",
7719 			    DIF_INSTR_OP(instr));
7720 		}
7721 	}
7722 
7723 	if (dp->dtdo_len != 0 &&
7724 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
7725 		err += efunc(dp->dtdo_len - 1,
7726 		    "expected 'ret' as last DIF instruction\n");
7727 	}
7728 
7729 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
7730 		/*
7731 		 * If we're not returning by reference, the size must be either
7732 		 * 0 or the size of one of the base types.
7733 		 */
7734 		switch (dp->dtdo_rtype.dtdt_size) {
7735 		case 0:
7736 		case sizeof (uint8_t):
7737 		case sizeof (uint16_t):
7738 		case sizeof (uint32_t):
7739 		case sizeof (uint64_t):
7740 			break;
7741 
7742 		default:
7743 			err += efunc(dp->dtdo_len - 1, "bad return size");
7744 		}
7745 	}
7746 
7747 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
7748 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
7749 		dtrace_diftype_t *vt, *et;
7750 		uint_t id, ndx;
7751 
7752 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
7753 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
7754 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
7755 			err += efunc(i, "unrecognized variable scope %d\n",
7756 			    v->dtdv_scope);
7757 			break;
7758 		}
7759 
7760 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
7761 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
7762 			err += efunc(i, "unrecognized variable type %d\n",
7763 			    v->dtdv_kind);
7764 			break;
7765 		}
7766 
7767 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
7768 			err += efunc(i, "%d exceeds variable id limit\n", id);
7769 			break;
7770 		}
7771 
7772 		if (id < DIF_VAR_OTHER_UBASE)
7773 			continue;
7774 
7775 		/*
7776 		 * For user-defined variables, we need to check that this
7777 		 * definition is identical to any previous definition that we
7778 		 * encountered.
7779 		 */
7780 		ndx = id - DIF_VAR_OTHER_UBASE;
7781 
7782 		switch (v->dtdv_scope) {
7783 		case DIFV_SCOPE_GLOBAL:
7784 			if (ndx < vstate->dtvs_nglobals) {
7785 				dtrace_statvar_t *svar;
7786 
7787 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
7788 					existing = &svar->dtsv_var;
7789 			}
7790 
7791 			break;
7792 
7793 		case DIFV_SCOPE_THREAD:
7794 			if (ndx < vstate->dtvs_ntlocals)
7795 				existing = &vstate->dtvs_tlocals[ndx];
7796 			break;
7797 
7798 		case DIFV_SCOPE_LOCAL:
7799 			if (ndx < vstate->dtvs_nlocals) {
7800 				dtrace_statvar_t *svar;
7801 
7802 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
7803 					existing = &svar->dtsv_var;
7804 			}
7805 
7806 			break;
7807 		}
7808 
7809 		vt = &v->dtdv_type;
7810 
7811 		if (vt->dtdt_flags & DIF_TF_BYREF) {
7812 			if (vt->dtdt_size == 0) {
7813 				err += efunc(i, "zero-sized variable\n");
7814 				break;
7815 			}
7816 
7817 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
7818 			    vt->dtdt_size > dtrace_global_maxsize) {
7819 				err += efunc(i, "oversized by-ref global\n");
7820 				break;
7821 			}
7822 		}
7823 
7824 		if (existing == NULL || existing->dtdv_id == 0)
7825 			continue;
7826 
7827 		ASSERT(existing->dtdv_id == v->dtdv_id);
7828 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
7829 
7830 		if (existing->dtdv_kind != v->dtdv_kind)
7831 			err += efunc(i, "%d changed variable kind\n", id);
7832 
7833 		et = &existing->dtdv_type;
7834 
7835 		if (vt->dtdt_flags != et->dtdt_flags) {
7836 			err += efunc(i, "%d changed variable type flags\n", id);
7837 			break;
7838 		}
7839 
7840 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
7841 			err += efunc(i, "%d changed variable type size\n", id);
7842 			break;
7843 		}
7844 	}
7845 
7846 	return (err);
7847 }
7848 
7849 /*
7850  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
7851  * are much more constrained than normal DIFOs.  Specifically, they may
7852  * not:
7853  *
7854  * 1. Make calls to subroutines other than copyin(), copyinstr() or
7855  *    miscellaneous string routines
7856  * 2. Access DTrace variables other than the args[] array, and the
7857  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
7858  * 3. Have thread-local variables.
7859  * 4. Have dynamic variables.
7860  */
7861 static int
7862 dtrace_difo_validate_helper(dtrace_difo_t *dp)
7863 {
7864 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
7865 	int err = 0;
7866 	uint_t pc;
7867 
7868 	for (pc = 0; pc < dp->dtdo_len; pc++) {
7869 		dif_instr_t instr = dp->dtdo_buf[pc];
7870 
7871 		uint_t v = DIF_INSTR_VAR(instr);
7872 		uint_t subr = DIF_INSTR_SUBR(instr);
7873 		uint_t op = DIF_INSTR_OP(instr);
7874 
7875 		switch (op) {
7876 		case DIF_OP_OR:
7877 		case DIF_OP_XOR:
7878 		case DIF_OP_AND:
7879 		case DIF_OP_SLL:
7880 		case DIF_OP_SRL:
7881 		case DIF_OP_SRA:
7882 		case DIF_OP_SUB:
7883 		case DIF_OP_ADD:
7884 		case DIF_OP_MUL:
7885 		case DIF_OP_SDIV:
7886 		case DIF_OP_UDIV:
7887 		case DIF_OP_SREM:
7888 		case DIF_OP_UREM:
7889 		case DIF_OP_COPYS:
7890 		case DIF_OP_NOT:
7891 		case DIF_OP_MOV:
7892 		case DIF_OP_RLDSB:
7893 		case DIF_OP_RLDSH:
7894 		case DIF_OP_RLDSW:
7895 		case DIF_OP_RLDUB:
7896 		case DIF_OP_RLDUH:
7897 		case DIF_OP_RLDUW:
7898 		case DIF_OP_RLDX:
7899 		case DIF_OP_ULDSB:
7900 		case DIF_OP_ULDSH:
7901 		case DIF_OP_ULDSW:
7902 		case DIF_OP_ULDUB:
7903 		case DIF_OP_ULDUH:
7904 		case DIF_OP_ULDUW:
7905 		case DIF_OP_ULDX:
7906 		case DIF_OP_STB:
7907 		case DIF_OP_STH:
7908 		case DIF_OP_STW:
7909 		case DIF_OP_STX:
7910 		case DIF_OP_ALLOCS:
7911 		case DIF_OP_CMP:
7912 		case DIF_OP_SCMP:
7913 		case DIF_OP_TST:
7914 		case DIF_OP_BA:
7915 		case DIF_OP_BE:
7916 		case DIF_OP_BNE:
7917 		case DIF_OP_BG:
7918 		case DIF_OP_BGU:
7919 		case DIF_OP_BGE:
7920 		case DIF_OP_BGEU:
7921 		case DIF_OP_BL:
7922 		case DIF_OP_BLU:
7923 		case DIF_OP_BLE:
7924 		case DIF_OP_BLEU:
7925 		case DIF_OP_RET:
7926 		case DIF_OP_NOP:
7927 		case DIF_OP_POPTS:
7928 		case DIF_OP_FLUSHTS:
7929 		case DIF_OP_SETX:
7930 		case DIF_OP_SETS:
7931 		case DIF_OP_LDGA:
7932 		case DIF_OP_LDLS:
7933 		case DIF_OP_STGS:
7934 		case DIF_OP_STLS:
7935 		case DIF_OP_PUSHTR:
7936 		case DIF_OP_PUSHTV:
7937 			break;
7938 
7939 		case DIF_OP_LDGS:
7940 			if (v >= DIF_VAR_OTHER_UBASE)
7941 				break;
7942 
7943 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
7944 				break;
7945 
7946 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
7947 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
7948 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
7949 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
7950 				break;
7951 
7952 			err += efunc(pc, "illegal variable %u\n", v);
7953 			break;
7954 
7955 		case DIF_OP_LDTA:
7956 		case DIF_OP_LDTS:
7957 		case DIF_OP_LDGAA:
7958 		case DIF_OP_LDTAA:
7959 			err += efunc(pc, "illegal dynamic variable load\n");
7960 			break;
7961 
7962 		case DIF_OP_STTS:
7963 		case DIF_OP_STGAA:
7964 		case DIF_OP_STTAA:
7965 			err += efunc(pc, "illegal dynamic variable store\n");
7966 			break;
7967 
7968 		case DIF_OP_CALL:
7969 			if (subr == DIF_SUBR_ALLOCA ||
7970 			    subr == DIF_SUBR_BCOPY ||
7971 			    subr == DIF_SUBR_COPYIN ||
7972 			    subr == DIF_SUBR_COPYINTO ||
7973 			    subr == DIF_SUBR_COPYINSTR ||
7974 			    subr == DIF_SUBR_INDEX ||
7975 			    subr == DIF_SUBR_LLTOSTR ||
7976 			    subr == DIF_SUBR_RINDEX ||
7977 			    subr == DIF_SUBR_STRCHR ||
7978 			    subr == DIF_SUBR_STRJOIN ||
7979 			    subr == DIF_SUBR_STRRCHR ||
7980 			    subr == DIF_SUBR_STRSTR ||
7981 			    subr == DIF_SUBR_HTONS ||
7982 			    subr == DIF_SUBR_HTONL ||
7983 			    subr == DIF_SUBR_HTONLL ||
7984 			    subr == DIF_SUBR_NTOHS ||
7985 			    subr == DIF_SUBR_NTOHL ||
7986 			    subr == DIF_SUBR_NTOHLL)
7987 				break;
7988 
7989 			err += efunc(pc, "invalid subr %u\n", subr);
7990 			break;
7991 
7992 		default:
7993 			err += efunc(pc, "invalid opcode %u\n",
7994 			    DIF_INSTR_OP(instr));
7995 		}
7996 	}
7997 
7998 	return (err);
7999 }
8000 
8001 /*
8002  * Returns 1 if the expression in the DIF object can be cached on a per-thread
8003  * basis; 0 if not.
8004  */
8005 static int
8006 dtrace_difo_cacheable(dtrace_difo_t *dp)
8007 {
8008 	int i;
8009 
8010 	if (dp == NULL)
8011 		return (0);
8012 
8013 	for (i = 0; i < dp->dtdo_varlen; i++) {
8014 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8015 
8016 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
8017 			continue;
8018 
8019 		switch (v->dtdv_id) {
8020 		case DIF_VAR_CURTHREAD:
8021 		case DIF_VAR_PID:
8022 		case DIF_VAR_TID:
8023 		case DIF_VAR_EXECNAME:
8024 		case DIF_VAR_ZONENAME:
8025 			break;
8026 
8027 		default:
8028 			return (0);
8029 		}
8030 	}
8031 
8032 	/*
8033 	 * This DIF object may be cacheable.  Now we need to look for any
8034 	 * array loading instructions, any memory loading instructions, or
8035 	 * any stores to thread-local variables.
8036 	 */
8037 	for (i = 0; i < dp->dtdo_len; i++) {
8038 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
8039 
8040 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
8041 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
8042 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
8043 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
8044 			return (0);
8045 	}
8046 
8047 	return (1);
8048 }
8049 
8050 static void
8051 dtrace_difo_hold(dtrace_difo_t *dp)
8052 {
8053 	int i;
8054 
8055 	ASSERT(MUTEX_HELD(&dtrace_lock));
8056 
8057 	dp->dtdo_refcnt++;
8058 	ASSERT(dp->dtdo_refcnt != 0);
8059 
8060 	/*
8061 	 * We need to check this DIF object for references to the variable
8062 	 * DIF_VAR_VTIMESTAMP.
8063 	 */
8064 	for (i = 0; i < dp->dtdo_varlen; i++) {
8065 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8066 
8067 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8068 			continue;
8069 
8070 		if (dtrace_vtime_references++ == 0)
8071 			dtrace_vtime_enable();
8072 	}
8073 }
8074 
8075 /*
8076  * This routine calculates the dynamic variable chunksize for a given DIF
8077  * object.  The calculation is not fool-proof, and can probably be tricked by
8078  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
8079  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
8080  * if a dynamic variable size exceeds the chunksize.
8081  */
8082 static void
8083 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8084 {
8085 	uint64_t sval;
8086 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
8087 	const dif_instr_t *text = dp->dtdo_buf;
8088 	uint_t pc, srd = 0;
8089 	uint_t ttop = 0;
8090 	size_t size, ksize;
8091 	uint_t id, i;
8092 
8093 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8094 		dif_instr_t instr = text[pc];
8095 		uint_t op = DIF_INSTR_OP(instr);
8096 		uint_t rd = DIF_INSTR_RD(instr);
8097 		uint_t r1 = DIF_INSTR_R1(instr);
8098 		uint_t nkeys = 0;
8099 		uchar_t scope;
8100 
8101 		dtrace_key_t *key = tupregs;
8102 
8103 		switch (op) {
8104 		case DIF_OP_SETX:
8105 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
8106 			srd = rd;
8107 			continue;
8108 
8109 		case DIF_OP_STTS:
8110 			key = &tupregs[DIF_DTR_NREGS];
8111 			key[0].dttk_size = 0;
8112 			key[1].dttk_size = 0;
8113 			nkeys = 2;
8114 			scope = DIFV_SCOPE_THREAD;
8115 			break;
8116 
8117 		case DIF_OP_STGAA:
8118 		case DIF_OP_STTAA:
8119 			nkeys = ttop;
8120 
8121 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
8122 				key[nkeys++].dttk_size = 0;
8123 
8124 			key[nkeys++].dttk_size = 0;
8125 
8126 			if (op == DIF_OP_STTAA) {
8127 				scope = DIFV_SCOPE_THREAD;
8128 			} else {
8129 				scope = DIFV_SCOPE_GLOBAL;
8130 			}
8131 
8132 			break;
8133 
8134 		case DIF_OP_PUSHTR:
8135 			if (ttop == DIF_DTR_NREGS)
8136 				return;
8137 
8138 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
8139 				/*
8140 				 * If the register for the size of the "pushtr"
8141 				 * is %r0 (or the value is 0) and the type is
8142 				 * a string, we'll use the system-wide default
8143 				 * string size.
8144 				 */
8145 				tupregs[ttop++].dttk_size =
8146 				    dtrace_strsize_default;
8147 			} else {
8148 				if (srd == 0)
8149 					return;
8150 
8151 				tupregs[ttop++].dttk_size = sval;
8152 			}
8153 
8154 			break;
8155 
8156 		case DIF_OP_PUSHTV:
8157 			if (ttop == DIF_DTR_NREGS)
8158 				return;
8159 
8160 			tupregs[ttop++].dttk_size = 0;
8161 			break;
8162 
8163 		case DIF_OP_FLUSHTS:
8164 			ttop = 0;
8165 			break;
8166 
8167 		case DIF_OP_POPTS:
8168 			if (ttop != 0)
8169 				ttop--;
8170 			break;
8171 		}
8172 
8173 		sval = 0;
8174 		srd = 0;
8175 
8176 		if (nkeys == 0)
8177 			continue;
8178 
8179 		/*
8180 		 * We have a dynamic variable allocation; calculate its size.
8181 		 */
8182 		for (ksize = 0, i = 0; i < nkeys; i++)
8183 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
8184 
8185 		size = sizeof (dtrace_dynvar_t);
8186 		size += sizeof (dtrace_key_t) * (nkeys - 1);
8187 		size += ksize;
8188 
8189 		/*
8190 		 * Now we need to determine the size of the stored data.
8191 		 */
8192 		id = DIF_INSTR_VAR(instr);
8193 
8194 		for (i = 0; i < dp->dtdo_varlen; i++) {
8195 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
8196 
8197 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
8198 				size += v->dtdv_type.dtdt_size;
8199 				break;
8200 			}
8201 		}
8202 
8203 		if (i == dp->dtdo_varlen)
8204 			return;
8205 
8206 		/*
8207 		 * We have the size.  If this is larger than the chunk size
8208 		 * for our dynamic variable state, reset the chunk size.
8209 		 */
8210 		size = P2ROUNDUP(size, sizeof (uint64_t));
8211 
8212 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
8213 			vstate->dtvs_dynvars.dtds_chunksize = size;
8214 	}
8215 }
8216 
8217 static void
8218 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8219 {
8220 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
8221 	uint_t id;
8222 
8223 	ASSERT(MUTEX_HELD(&dtrace_lock));
8224 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
8225 
8226 	for (i = 0; i < dp->dtdo_varlen; i++) {
8227 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8228 		dtrace_statvar_t *svar, ***svarp;
8229 		size_t dsize = 0;
8230 		uint8_t scope = v->dtdv_scope;
8231 		int *np;
8232 
8233 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8234 			continue;
8235 
8236 		id -= DIF_VAR_OTHER_UBASE;
8237 
8238 		switch (scope) {
8239 		case DIFV_SCOPE_THREAD:
8240 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
8241 				dtrace_difv_t *tlocals;
8242 
8243 				if ((ntlocals = (otlocals << 1)) == 0)
8244 					ntlocals = 1;
8245 
8246 				osz = otlocals * sizeof (dtrace_difv_t);
8247 				nsz = ntlocals * sizeof (dtrace_difv_t);
8248 
8249 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
8250 
8251 				if (osz != 0) {
8252 					bcopy(vstate->dtvs_tlocals,
8253 					    tlocals, osz);
8254 					kmem_free(vstate->dtvs_tlocals, osz);
8255 				}
8256 
8257 				vstate->dtvs_tlocals = tlocals;
8258 				vstate->dtvs_ntlocals = ntlocals;
8259 			}
8260 
8261 			vstate->dtvs_tlocals[id] = *v;
8262 			continue;
8263 
8264 		case DIFV_SCOPE_LOCAL:
8265 			np = &vstate->dtvs_nlocals;
8266 			svarp = &vstate->dtvs_locals;
8267 
8268 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8269 				dsize = NCPU * (v->dtdv_type.dtdt_size +
8270 				    sizeof (uint64_t));
8271 			else
8272 				dsize = NCPU * sizeof (uint64_t);
8273 
8274 			break;
8275 
8276 		case DIFV_SCOPE_GLOBAL:
8277 			np = &vstate->dtvs_nglobals;
8278 			svarp = &vstate->dtvs_globals;
8279 
8280 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8281 				dsize = v->dtdv_type.dtdt_size +
8282 				    sizeof (uint64_t);
8283 
8284 			break;
8285 
8286 		default:
8287 			ASSERT(0);
8288 		}
8289 
8290 		while (id >= (oldsvars = *np)) {
8291 			dtrace_statvar_t **statics;
8292 			int newsvars, oldsize, newsize;
8293 
8294 			if ((newsvars = (oldsvars << 1)) == 0)
8295 				newsvars = 1;
8296 
8297 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
8298 			newsize = newsvars * sizeof (dtrace_statvar_t *);
8299 
8300 			statics = kmem_zalloc(newsize, KM_SLEEP);
8301 
8302 			if (oldsize != 0) {
8303 				bcopy(*svarp, statics, oldsize);
8304 				kmem_free(*svarp, oldsize);
8305 			}
8306 
8307 			*svarp = statics;
8308 			*np = newsvars;
8309 		}
8310 
8311 		if ((svar = (*svarp)[id]) == NULL) {
8312 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
8313 			svar->dtsv_var = *v;
8314 
8315 			if ((svar->dtsv_size = dsize) != 0) {
8316 				svar->dtsv_data = (uint64_t)(uintptr_t)
8317 				    kmem_zalloc(dsize, KM_SLEEP);
8318 			}
8319 
8320 			(*svarp)[id] = svar;
8321 		}
8322 
8323 		svar->dtsv_refcnt++;
8324 	}
8325 
8326 	dtrace_difo_chunksize(dp, vstate);
8327 	dtrace_difo_hold(dp);
8328 }
8329 
8330 static dtrace_difo_t *
8331 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8332 {
8333 	dtrace_difo_t *new;
8334 	size_t sz;
8335 
8336 	ASSERT(dp->dtdo_buf != NULL);
8337 	ASSERT(dp->dtdo_refcnt != 0);
8338 
8339 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
8340 
8341 	ASSERT(dp->dtdo_buf != NULL);
8342 	sz = dp->dtdo_len * sizeof (dif_instr_t);
8343 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
8344 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
8345 	new->dtdo_len = dp->dtdo_len;
8346 
8347 	if (dp->dtdo_strtab != NULL) {
8348 		ASSERT(dp->dtdo_strlen != 0);
8349 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
8350 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
8351 		new->dtdo_strlen = dp->dtdo_strlen;
8352 	}
8353 
8354 	if (dp->dtdo_inttab != NULL) {
8355 		ASSERT(dp->dtdo_intlen != 0);
8356 		sz = dp->dtdo_intlen * sizeof (uint64_t);
8357 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
8358 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
8359 		new->dtdo_intlen = dp->dtdo_intlen;
8360 	}
8361 
8362 	if (dp->dtdo_vartab != NULL) {
8363 		ASSERT(dp->dtdo_varlen != 0);
8364 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
8365 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
8366 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
8367 		new->dtdo_varlen = dp->dtdo_varlen;
8368 	}
8369 
8370 	dtrace_difo_init(new, vstate);
8371 	return (new);
8372 }
8373 
8374 static void
8375 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8376 {
8377 	int i;
8378 
8379 	ASSERT(dp->dtdo_refcnt == 0);
8380 
8381 	for (i = 0; i < dp->dtdo_varlen; i++) {
8382 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8383 		dtrace_statvar_t *svar, **svarp;
8384 		uint_t id;
8385 		uint8_t scope = v->dtdv_scope;
8386 		int *np;
8387 
8388 		switch (scope) {
8389 		case DIFV_SCOPE_THREAD:
8390 			continue;
8391 
8392 		case DIFV_SCOPE_LOCAL:
8393 			np = &vstate->dtvs_nlocals;
8394 			svarp = vstate->dtvs_locals;
8395 			break;
8396 
8397 		case DIFV_SCOPE_GLOBAL:
8398 			np = &vstate->dtvs_nglobals;
8399 			svarp = vstate->dtvs_globals;
8400 			break;
8401 
8402 		default:
8403 			ASSERT(0);
8404 		}
8405 
8406 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8407 			continue;
8408 
8409 		id -= DIF_VAR_OTHER_UBASE;
8410 		ASSERT(id < *np);
8411 
8412 		svar = svarp[id];
8413 		ASSERT(svar != NULL);
8414 		ASSERT(svar->dtsv_refcnt > 0);
8415 
8416 		if (--svar->dtsv_refcnt > 0)
8417 			continue;
8418 
8419 		if (svar->dtsv_size != 0) {
8420 			ASSERT(svar->dtsv_data != NULL);
8421 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
8422 			    svar->dtsv_size);
8423 		}
8424 
8425 		kmem_free(svar, sizeof (dtrace_statvar_t));
8426 		svarp[id] = NULL;
8427 	}
8428 
8429 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
8430 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
8431 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
8432 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
8433 
8434 	kmem_free(dp, sizeof (dtrace_difo_t));
8435 }
8436 
8437 static void
8438 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8439 {
8440 	int i;
8441 
8442 	ASSERT(MUTEX_HELD(&dtrace_lock));
8443 	ASSERT(dp->dtdo_refcnt != 0);
8444 
8445 	for (i = 0; i < dp->dtdo_varlen; i++) {
8446 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8447 
8448 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8449 			continue;
8450 
8451 		ASSERT(dtrace_vtime_references > 0);
8452 		if (--dtrace_vtime_references == 0)
8453 			dtrace_vtime_disable();
8454 	}
8455 
8456 	if (--dp->dtdo_refcnt == 0)
8457 		dtrace_difo_destroy(dp, vstate);
8458 }
8459 
8460 /*
8461  * DTrace Format Functions
8462  */
8463 static uint16_t
8464 dtrace_format_add(dtrace_state_t *state, char *str)
8465 {
8466 	char *fmt, **new;
8467 	uint16_t ndx, len = strlen(str) + 1;
8468 
8469 	fmt = kmem_zalloc(len, KM_SLEEP);
8470 	bcopy(str, fmt, len);
8471 
8472 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
8473 		if (state->dts_formats[ndx] == NULL) {
8474 			state->dts_formats[ndx] = fmt;
8475 			return (ndx + 1);
8476 		}
8477 	}
8478 
8479 	if (state->dts_nformats == USHRT_MAX) {
8480 		/*
8481 		 * This is only likely if a denial-of-service attack is being
8482 		 * attempted.  As such, it's okay to fail silently here.
8483 		 */
8484 		kmem_free(fmt, len);
8485 		return (0);
8486 	}
8487 
8488 	/*
8489 	 * For simplicity, we always resize the formats array to be exactly the
8490 	 * number of formats.
8491 	 */
8492 	ndx = state->dts_nformats++;
8493 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
8494 
8495 	if (state->dts_formats != NULL) {
8496 		ASSERT(ndx != 0);
8497 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
8498 		kmem_free(state->dts_formats, ndx * sizeof (char *));
8499 	}
8500 
8501 	state->dts_formats = new;
8502 	state->dts_formats[ndx] = fmt;
8503 
8504 	return (ndx + 1);
8505 }
8506 
8507 static void
8508 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
8509 {
8510 	char *fmt;
8511 
8512 	ASSERT(state->dts_formats != NULL);
8513 	ASSERT(format <= state->dts_nformats);
8514 	ASSERT(state->dts_formats[format - 1] != NULL);
8515 
8516 	fmt = state->dts_formats[format - 1];
8517 	kmem_free(fmt, strlen(fmt) + 1);
8518 	state->dts_formats[format - 1] = NULL;
8519 }
8520 
8521 static void
8522 dtrace_format_destroy(dtrace_state_t *state)
8523 {
8524 	int i;
8525 
8526 	if (state->dts_nformats == 0) {
8527 		ASSERT(state->dts_formats == NULL);
8528 		return;
8529 	}
8530 
8531 	ASSERT(state->dts_formats != NULL);
8532 
8533 	for (i = 0; i < state->dts_nformats; i++) {
8534 		char *fmt = state->dts_formats[i];
8535 
8536 		if (fmt == NULL)
8537 			continue;
8538 
8539 		kmem_free(fmt, strlen(fmt) + 1);
8540 	}
8541 
8542 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
8543 	state->dts_nformats = 0;
8544 	state->dts_formats = NULL;
8545 }
8546 
8547 /*
8548  * DTrace Predicate Functions
8549  */
8550 static dtrace_predicate_t *
8551 dtrace_predicate_create(dtrace_difo_t *dp)
8552 {
8553 	dtrace_predicate_t *pred;
8554 
8555 	ASSERT(MUTEX_HELD(&dtrace_lock));
8556 	ASSERT(dp->dtdo_refcnt != 0);
8557 
8558 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
8559 	pred->dtp_difo = dp;
8560 	pred->dtp_refcnt = 1;
8561 
8562 	if (!dtrace_difo_cacheable(dp))
8563 		return (pred);
8564 
8565 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
8566 		/*
8567 		 * This is only theoretically possible -- we have had 2^32
8568 		 * cacheable predicates on this machine.  We cannot allow any
8569 		 * more predicates to become cacheable:  as unlikely as it is,
8570 		 * there may be a thread caching a (now stale) predicate cache
8571 		 * ID. (N.B.: the temptation is being successfully resisted to
8572 		 * have this cmn_err() "Holy shit -- we executed this code!")
8573 		 */
8574 		return (pred);
8575 	}
8576 
8577 	pred->dtp_cacheid = dtrace_predcache_id++;
8578 
8579 	return (pred);
8580 }
8581 
8582 static void
8583 dtrace_predicate_hold(dtrace_predicate_t *pred)
8584 {
8585 	ASSERT(MUTEX_HELD(&dtrace_lock));
8586 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
8587 	ASSERT(pred->dtp_refcnt > 0);
8588 
8589 	pred->dtp_refcnt++;
8590 }
8591 
8592 static void
8593 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
8594 {
8595 	dtrace_difo_t *dp = pred->dtp_difo;
8596 
8597 	ASSERT(MUTEX_HELD(&dtrace_lock));
8598 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
8599 	ASSERT(pred->dtp_refcnt > 0);
8600 
8601 	if (--pred->dtp_refcnt == 0) {
8602 		dtrace_difo_release(pred->dtp_difo, vstate);
8603 		kmem_free(pred, sizeof (dtrace_predicate_t));
8604 	}
8605 }
8606 
8607 /*
8608  * DTrace Action Description Functions
8609  */
8610 static dtrace_actdesc_t *
8611 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
8612     uint64_t uarg, uint64_t arg)
8613 {
8614 	dtrace_actdesc_t *act;
8615 
8616 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
8617 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
8618 
8619 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
8620 	act->dtad_kind = kind;
8621 	act->dtad_ntuple = ntuple;
8622 	act->dtad_uarg = uarg;
8623 	act->dtad_arg = arg;
8624 	act->dtad_refcnt = 1;
8625 
8626 	return (act);
8627 }
8628 
8629 static void
8630 dtrace_actdesc_hold(dtrace_actdesc_t *act)
8631 {
8632 	ASSERT(act->dtad_refcnt >= 1);
8633 	act->dtad_refcnt++;
8634 }
8635 
8636 static void
8637 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
8638 {
8639 	dtrace_actkind_t kind = act->dtad_kind;
8640 	dtrace_difo_t *dp;
8641 
8642 	ASSERT(act->dtad_refcnt >= 1);
8643 
8644 	if (--act->dtad_refcnt != 0)
8645 		return;
8646 
8647 	if ((dp = act->dtad_difo) != NULL)
8648 		dtrace_difo_release(dp, vstate);
8649 
8650 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
8651 		char *str = (char *)(uintptr_t)act->dtad_arg;
8652 
8653 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
8654 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
8655 
8656 		if (str != NULL)
8657 			kmem_free(str, strlen(str) + 1);
8658 	}
8659 
8660 	kmem_free(act, sizeof (dtrace_actdesc_t));
8661 }
8662 
8663 /*
8664  * DTrace ECB Functions
8665  */
8666 static dtrace_ecb_t *
8667 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
8668 {
8669 	dtrace_ecb_t *ecb;
8670 	dtrace_epid_t epid;
8671 
8672 	ASSERT(MUTEX_HELD(&dtrace_lock));
8673 
8674 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
8675 	ecb->dte_predicate = NULL;
8676 	ecb->dte_probe = probe;
8677 
8678 	/*
8679 	 * The default size is the size of the default action: recording
8680 	 * the epid.
8681 	 */
8682 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
8683 	ecb->dte_alignment = sizeof (dtrace_epid_t);
8684 
8685 	epid = state->dts_epid++;
8686 
8687 	if (epid - 1 >= state->dts_necbs) {
8688 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
8689 		int necbs = state->dts_necbs << 1;
8690 
8691 		ASSERT(epid == state->dts_necbs + 1);
8692 
8693 		if (necbs == 0) {
8694 			ASSERT(oecbs == NULL);
8695 			necbs = 1;
8696 		}
8697 
8698 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
8699 
8700 		if (oecbs != NULL)
8701 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
8702 
8703 		dtrace_membar_producer();
8704 		state->dts_ecbs = ecbs;
8705 
8706 		if (oecbs != NULL) {
8707 			/*
8708 			 * If this state is active, we must dtrace_sync()
8709 			 * before we can free the old dts_ecbs array:  we're
8710 			 * coming in hot, and there may be active ring
8711 			 * buffer processing (which indexes into the dts_ecbs
8712 			 * array) on another CPU.
8713 			 */
8714 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
8715 				dtrace_sync();
8716 
8717 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
8718 		}
8719 
8720 		dtrace_membar_producer();
8721 		state->dts_necbs = necbs;
8722 	}
8723 
8724 	ecb->dte_state = state;
8725 
8726 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
8727 	dtrace_membar_producer();
8728 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
8729 
8730 	return (ecb);
8731 }
8732 
8733 static void
8734 dtrace_ecb_enable(dtrace_ecb_t *ecb)
8735 {
8736 	dtrace_probe_t *probe = ecb->dte_probe;
8737 
8738 	ASSERT(MUTEX_HELD(&cpu_lock));
8739 	ASSERT(MUTEX_HELD(&dtrace_lock));
8740 	ASSERT(ecb->dte_next == NULL);
8741 
8742 	if (probe == NULL) {
8743 		/*
8744 		 * This is the NULL probe -- there's nothing to do.
8745 		 */
8746 		return;
8747 	}
8748 
8749 	if (probe->dtpr_ecb == NULL) {
8750 		dtrace_provider_t *prov = probe->dtpr_provider;
8751 
8752 		/*
8753 		 * We're the first ECB on this probe.
8754 		 */
8755 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
8756 
8757 		if (ecb->dte_predicate != NULL)
8758 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
8759 
8760 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
8761 		    probe->dtpr_id, probe->dtpr_arg);
8762 	} else {
8763 		/*
8764 		 * This probe is already active.  Swing the last pointer to
8765 		 * point to the new ECB, and issue a dtrace_sync() to assure
8766 		 * that all CPUs have seen the change.
8767 		 */
8768 		ASSERT(probe->dtpr_ecb_last != NULL);
8769 		probe->dtpr_ecb_last->dte_next = ecb;
8770 		probe->dtpr_ecb_last = ecb;
8771 		probe->dtpr_predcache = 0;
8772 
8773 		dtrace_sync();
8774 	}
8775 }
8776 
8777 static void
8778 dtrace_ecb_resize(dtrace_ecb_t *ecb)
8779 {
8780 	uint32_t maxalign = sizeof (dtrace_epid_t);
8781 	uint32_t align = sizeof (uint8_t), offs, diff;
8782 	dtrace_action_t *act;
8783 	int wastuple = 0;
8784 	uint32_t aggbase = UINT32_MAX;
8785 	dtrace_state_t *state = ecb->dte_state;
8786 
8787 	/*
8788 	 * If we record anything, we always record the epid.  (And we always
8789 	 * record it first.)
8790 	 */
8791 	offs = sizeof (dtrace_epid_t);
8792 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
8793 
8794 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
8795 		dtrace_recdesc_t *rec = &act->dta_rec;
8796 
8797 		if ((align = rec->dtrd_alignment) > maxalign)
8798 			maxalign = align;
8799 
8800 		if (!wastuple && act->dta_intuple) {
8801 			/*
8802 			 * This is the first record in a tuple.  Align the
8803 			 * offset to be at offset 4 in an 8-byte aligned
8804 			 * block.
8805 			 */
8806 			diff = offs + sizeof (dtrace_aggid_t);
8807 
8808 			if (diff = (diff & (sizeof (uint64_t) - 1)))
8809 				offs += sizeof (uint64_t) - diff;
8810 
8811 			aggbase = offs - sizeof (dtrace_aggid_t);
8812 			ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
8813 		}
8814 
8815 		/*LINTED*/
8816 		if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
8817 			/*
8818 			 * The current offset is not properly aligned; align it.
8819 			 */
8820 			offs += align - diff;
8821 		}
8822 
8823 		rec->dtrd_offset = offs;
8824 
8825 		if (offs + rec->dtrd_size > ecb->dte_needed) {
8826 			ecb->dte_needed = offs + rec->dtrd_size;
8827 
8828 			if (ecb->dte_needed > state->dts_needed)
8829 				state->dts_needed = ecb->dte_needed;
8830 		}
8831 
8832 		if (DTRACEACT_ISAGG(act->dta_kind)) {
8833 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
8834 			dtrace_action_t *first = agg->dtag_first, *prev;
8835 
8836 			ASSERT(rec->dtrd_size != 0 && first != NULL);
8837 			ASSERT(wastuple);
8838 			ASSERT(aggbase != UINT32_MAX);
8839 
8840 			agg->dtag_base = aggbase;
8841 
8842 			while ((prev = first->dta_prev) != NULL &&
8843 			    DTRACEACT_ISAGG(prev->dta_kind)) {
8844 				agg = (dtrace_aggregation_t *)prev;
8845 				first = agg->dtag_first;
8846 			}
8847 
8848 			if (prev != NULL) {
8849 				offs = prev->dta_rec.dtrd_offset +
8850 				    prev->dta_rec.dtrd_size;
8851 			} else {
8852 				offs = sizeof (dtrace_epid_t);
8853 			}
8854 			wastuple = 0;
8855 		} else {
8856 			if (!act->dta_intuple)
8857 				ecb->dte_size = offs + rec->dtrd_size;
8858 
8859 			offs += rec->dtrd_size;
8860 		}
8861 
8862 		wastuple = act->dta_intuple;
8863 	}
8864 
8865 	if ((act = ecb->dte_action) != NULL &&
8866 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
8867 	    ecb->dte_size == sizeof (dtrace_epid_t)) {
8868 		/*
8869 		 * If the size is still sizeof (dtrace_epid_t), then all
8870 		 * actions store no data; set the size to 0.
8871 		 */
8872 		ecb->dte_alignment = maxalign;
8873 		ecb->dte_size = 0;
8874 
8875 		/*
8876 		 * If the needed space is still sizeof (dtrace_epid_t), then
8877 		 * all actions need no additional space; set the needed
8878 		 * size to 0.
8879 		 */
8880 		if (ecb->dte_needed == sizeof (dtrace_epid_t))
8881 			ecb->dte_needed = 0;
8882 
8883 		return;
8884 	}
8885 
8886 	/*
8887 	 * Set our alignment, and make sure that the dte_size and dte_needed
8888 	 * are aligned to the size of an EPID.
8889 	 */
8890 	ecb->dte_alignment = maxalign;
8891 	ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
8892 	    ~(sizeof (dtrace_epid_t) - 1);
8893 	ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
8894 	    ~(sizeof (dtrace_epid_t) - 1);
8895 	ASSERT(ecb->dte_size <= ecb->dte_needed);
8896 }
8897 
8898 static dtrace_action_t *
8899 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
8900 {
8901 	dtrace_aggregation_t *agg;
8902 	size_t size = sizeof (uint64_t);
8903 	int ntuple = desc->dtad_ntuple;
8904 	dtrace_action_t *act;
8905 	dtrace_recdesc_t *frec;
8906 	dtrace_aggid_t aggid;
8907 	dtrace_state_t *state = ecb->dte_state;
8908 
8909 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
8910 	agg->dtag_ecb = ecb;
8911 
8912 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
8913 
8914 	switch (desc->dtad_kind) {
8915 	case DTRACEAGG_MIN:
8916 		agg->dtag_initial = UINT64_MAX;
8917 		agg->dtag_aggregate = dtrace_aggregate_min;
8918 		break;
8919 
8920 	case DTRACEAGG_MAX:
8921 		agg->dtag_aggregate = dtrace_aggregate_max;
8922 		break;
8923 
8924 	case DTRACEAGG_COUNT:
8925 		agg->dtag_aggregate = dtrace_aggregate_count;
8926 		break;
8927 
8928 	case DTRACEAGG_QUANTIZE:
8929 		agg->dtag_aggregate = dtrace_aggregate_quantize;
8930 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
8931 		    sizeof (uint64_t);
8932 		break;
8933 
8934 	case DTRACEAGG_LQUANTIZE: {
8935 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
8936 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
8937 
8938 		agg->dtag_initial = desc->dtad_arg;
8939 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
8940 
8941 		if (step == 0 || levels == 0)
8942 			goto err;
8943 
8944 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
8945 		break;
8946 	}
8947 
8948 	case DTRACEAGG_AVG:
8949 		agg->dtag_aggregate = dtrace_aggregate_avg;
8950 		size = sizeof (uint64_t) * 2;
8951 		break;
8952 
8953 	case DTRACEAGG_SUM:
8954 		agg->dtag_aggregate = dtrace_aggregate_sum;
8955 		break;
8956 
8957 	default:
8958 		goto err;
8959 	}
8960 
8961 	agg->dtag_action.dta_rec.dtrd_size = size;
8962 
8963 	if (ntuple == 0)
8964 		goto err;
8965 
8966 	/*
8967 	 * We must make sure that we have enough actions for the n-tuple.
8968 	 */
8969 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
8970 		if (DTRACEACT_ISAGG(act->dta_kind))
8971 			break;
8972 
8973 		if (--ntuple == 0) {
8974 			/*
8975 			 * This is the action with which our n-tuple begins.
8976 			 */
8977 			agg->dtag_first = act;
8978 			goto success;
8979 		}
8980 	}
8981 
8982 	/*
8983 	 * This n-tuple is short by ntuple elements.  Return failure.
8984 	 */
8985 	ASSERT(ntuple != 0);
8986 err:
8987 	kmem_free(agg, sizeof (dtrace_aggregation_t));
8988 	return (NULL);
8989 
8990 success:
8991 	/*
8992 	 * If the last action in the tuple has a size of zero, it's actually
8993 	 * an expression argument for the aggregating action.
8994 	 */
8995 	ASSERT(ecb->dte_action_last != NULL);
8996 	act = ecb->dte_action_last;
8997 
8998 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
8999 		ASSERT(act->dta_difo != NULL);
9000 
9001 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
9002 			agg->dtag_hasarg = 1;
9003 	}
9004 
9005 	/*
9006 	 * We need to allocate an id for this aggregation.
9007 	 */
9008 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
9009 	    VM_BESTFIT | VM_SLEEP);
9010 
9011 	if (aggid - 1 >= state->dts_naggregations) {
9012 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
9013 		dtrace_aggregation_t **aggs;
9014 		int naggs = state->dts_naggregations << 1;
9015 		int onaggs = state->dts_naggregations;
9016 
9017 		ASSERT(aggid == state->dts_naggregations + 1);
9018 
9019 		if (naggs == 0) {
9020 			ASSERT(oaggs == NULL);
9021 			naggs = 1;
9022 		}
9023 
9024 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
9025 
9026 		if (oaggs != NULL) {
9027 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
9028 			kmem_free(oaggs, onaggs * sizeof (*aggs));
9029 		}
9030 
9031 		state->dts_aggregations = aggs;
9032 		state->dts_naggregations = naggs;
9033 	}
9034 
9035 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
9036 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
9037 
9038 	frec = &agg->dtag_first->dta_rec;
9039 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
9040 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
9041 
9042 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
9043 		ASSERT(!act->dta_intuple);
9044 		act->dta_intuple = 1;
9045 	}
9046 
9047 	return (&agg->dtag_action);
9048 }
9049 
9050 static void
9051 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
9052 {
9053 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9054 	dtrace_state_t *state = ecb->dte_state;
9055 	dtrace_aggid_t aggid = agg->dtag_id;
9056 
9057 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
9058 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
9059 
9060 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
9061 	state->dts_aggregations[aggid - 1] = NULL;
9062 
9063 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9064 }
9065 
9066 static int
9067 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9068 {
9069 	dtrace_action_t *action, *last;
9070 	dtrace_difo_t *dp = desc->dtad_difo;
9071 	uint32_t size = 0, align = sizeof (uint8_t), mask;
9072 	uint16_t format = 0;
9073 	dtrace_recdesc_t *rec;
9074 	dtrace_state_t *state = ecb->dte_state;
9075 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
9076 	uint64_t arg = desc->dtad_arg;
9077 
9078 	ASSERT(MUTEX_HELD(&dtrace_lock));
9079 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
9080 
9081 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
9082 		/*
9083 		 * If this is an aggregating action, there must be neither
9084 		 * a speculate nor a commit on the action chain.
9085 		 */
9086 		dtrace_action_t *act;
9087 
9088 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9089 			if (act->dta_kind == DTRACEACT_COMMIT)
9090 				return (EINVAL);
9091 
9092 			if (act->dta_kind == DTRACEACT_SPECULATE)
9093 				return (EINVAL);
9094 		}
9095 
9096 		action = dtrace_ecb_aggregation_create(ecb, desc);
9097 
9098 		if (action == NULL)
9099 			return (EINVAL);
9100 	} else {
9101 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
9102 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
9103 		    dp != NULL && dp->dtdo_destructive)) {
9104 			state->dts_destructive = 1;
9105 		}
9106 
9107 		switch (desc->dtad_kind) {
9108 		case DTRACEACT_PRINTF:
9109 		case DTRACEACT_PRINTA:
9110 		case DTRACEACT_SYSTEM:
9111 		case DTRACEACT_FREOPEN:
9112 			/*
9113 			 * We know that our arg is a string -- turn it into a
9114 			 * format.
9115 			 */
9116 			if (arg == NULL) {
9117 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
9118 				format = 0;
9119 			} else {
9120 				ASSERT(arg != NULL);
9121 				ASSERT(arg > KERNELBASE);
9122 				format = dtrace_format_add(state,
9123 				    (char *)(uintptr_t)arg);
9124 			}
9125 
9126 			/*FALLTHROUGH*/
9127 		case DTRACEACT_LIBACT:
9128 		case DTRACEACT_DIFEXPR:
9129 			if (dp == NULL)
9130 				return (EINVAL);
9131 
9132 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
9133 				break;
9134 
9135 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
9136 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9137 					return (EINVAL);
9138 
9139 				size = opt[DTRACEOPT_STRSIZE];
9140 			}
9141 
9142 			break;
9143 
9144 		case DTRACEACT_STACK:
9145 			if ((nframes = arg) == 0) {
9146 				nframes = opt[DTRACEOPT_STACKFRAMES];
9147 				ASSERT(nframes > 0);
9148 				arg = nframes;
9149 			}
9150 
9151 			size = nframes * sizeof (pc_t);
9152 			break;
9153 
9154 		case DTRACEACT_JSTACK:
9155 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
9156 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
9157 
9158 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
9159 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
9160 
9161 			arg = DTRACE_USTACK_ARG(nframes, strsize);
9162 
9163 			/*FALLTHROUGH*/
9164 		case DTRACEACT_USTACK:
9165 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
9166 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
9167 				strsize = DTRACE_USTACK_STRSIZE(arg);
9168 				nframes = opt[DTRACEOPT_USTACKFRAMES];
9169 				ASSERT(nframes > 0);
9170 				arg = DTRACE_USTACK_ARG(nframes, strsize);
9171 			}
9172 
9173 			/*
9174 			 * Save a slot for the pid.
9175 			 */
9176 			size = (nframes + 1) * sizeof (uint64_t);
9177 			size += DTRACE_USTACK_STRSIZE(arg);
9178 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
9179 
9180 			break;
9181 
9182 		case DTRACEACT_SYM:
9183 		case DTRACEACT_MOD:
9184 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
9185 			    sizeof (uint64_t)) ||
9186 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9187 				return (EINVAL);
9188 			break;
9189 
9190 		case DTRACEACT_USYM:
9191 		case DTRACEACT_UMOD:
9192 		case DTRACEACT_UADDR:
9193 			if (dp == NULL ||
9194 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
9195 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9196 				return (EINVAL);
9197 
9198 			/*
9199 			 * We have a slot for the pid, plus a slot for the
9200 			 * argument.  To keep things simple (aligned with
9201 			 * bitness-neutral sizing), we store each as a 64-bit
9202 			 * quantity.
9203 			 */
9204 			size = 2 * sizeof (uint64_t);
9205 			break;
9206 
9207 		case DTRACEACT_STOP:
9208 		case DTRACEACT_BREAKPOINT:
9209 		case DTRACEACT_PANIC:
9210 			break;
9211 
9212 		case DTRACEACT_CHILL:
9213 		case DTRACEACT_DISCARD:
9214 		case DTRACEACT_RAISE:
9215 			if (dp == NULL)
9216 				return (EINVAL);
9217 			break;
9218 
9219 		case DTRACEACT_EXIT:
9220 			if (dp == NULL ||
9221 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
9222 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9223 				return (EINVAL);
9224 			break;
9225 
9226 		case DTRACEACT_SPECULATE:
9227 			if (ecb->dte_size > sizeof (dtrace_epid_t))
9228 				return (EINVAL);
9229 
9230 			if (dp == NULL)
9231 				return (EINVAL);
9232 
9233 			state->dts_speculates = 1;
9234 			break;
9235 
9236 		case DTRACEACT_COMMIT: {
9237 			dtrace_action_t *act = ecb->dte_action;
9238 
9239 			for (; act != NULL; act = act->dta_next) {
9240 				if (act->dta_kind == DTRACEACT_COMMIT)
9241 					return (EINVAL);
9242 			}
9243 
9244 			if (dp == NULL)
9245 				return (EINVAL);
9246 			break;
9247 		}
9248 
9249 		default:
9250 			return (EINVAL);
9251 		}
9252 
9253 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
9254 			/*
9255 			 * If this is a data-storing action or a speculate,
9256 			 * we must be sure that there isn't a commit on the
9257 			 * action chain.
9258 			 */
9259 			dtrace_action_t *act = ecb->dte_action;
9260 
9261 			for (; act != NULL; act = act->dta_next) {
9262 				if (act->dta_kind == DTRACEACT_COMMIT)
9263 					return (EINVAL);
9264 			}
9265 		}
9266 
9267 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
9268 		action->dta_rec.dtrd_size = size;
9269 	}
9270 
9271 	action->dta_refcnt = 1;
9272 	rec = &action->dta_rec;
9273 	size = rec->dtrd_size;
9274 
9275 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
9276 		if (!(size & mask)) {
9277 			align = mask + 1;
9278 			break;
9279 		}
9280 	}
9281 
9282 	action->dta_kind = desc->dtad_kind;
9283 
9284 	if ((action->dta_difo = dp) != NULL)
9285 		dtrace_difo_hold(dp);
9286 
9287 	rec->dtrd_action = action->dta_kind;
9288 	rec->dtrd_arg = arg;
9289 	rec->dtrd_uarg = desc->dtad_uarg;
9290 	rec->dtrd_alignment = (uint16_t)align;
9291 	rec->dtrd_format = format;
9292 
9293 	if ((last = ecb->dte_action_last) != NULL) {
9294 		ASSERT(ecb->dte_action != NULL);
9295 		action->dta_prev = last;
9296 		last->dta_next = action;
9297 	} else {
9298 		ASSERT(ecb->dte_action == NULL);
9299 		ecb->dte_action = action;
9300 	}
9301 
9302 	ecb->dte_action_last = action;
9303 
9304 	return (0);
9305 }
9306 
9307 static void
9308 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
9309 {
9310 	dtrace_action_t *act = ecb->dte_action, *next;
9311 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
9312 	dtrace_difo_t *dp;
9313 	uint16_t format;
9314 
9315 	if (act != NULL && act->dta_refcnt > 1) {
9316 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
9317 		act->dta_refcnt--;
9318 	} else {
9319 		for (; act != NULL; act = next) {
9320 			next = act->dta_next;
9321 			ASSERT(next != NULL || act == ecb->dte_action_last);
9322 			ASSERT(act->dta_refcnt == 1);
9323 
9324 			if ((format = act->dta_rec.dtrd_format) != 0)
9325 				dtrace_format_remove(ecb->dte_state, format);
9326 
9327 			if ((dp = act->dta_difo) != NULL)
9328 				dtrace_difo_release(dp, vstate);
9329 
9330 			if (DTRACEACT_ISAGG(act->dta_kind)) {
9331 				dtrace_ecb_aggregation_destroy(ecb, act);
9332 			} else {
9333 				kmem_free(act, sizeof (dtrace_action_t));
9334 			}
9335 		}
9336 	}
9337 
9338 	ecb->dte_action = NULL;
9339 	ecb->dte_action_last = NULL;
9340 	ecb->dte_size = sizeof (dtrace_epid_t);
9341 }
9342 
9343 static void
9344 dtrace_ecb_disable(dtrace_ecb_t *ecb)
9345 {
9346 	/*
9347 	 * We disable the ECB by removing it from its probe.
9348 	 */
9349 	dtrace_ecb_t *pecb, *prev = NULL;
9350 	dtrace_probe_t *probe = ecb->dte_probe;
9351 
9352 	ASSERT(MUTEX_HELD(&dtrace_lock));
9353 
9354 	if (probe == NULL) {
9355 		/*
9356 		 * This is the NULL probe; there is nothing to disable.
9357 		 */
9358 		return;
9359 	}
9360 
9361 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
9362 		if (pecb == ecb)
9363 			break;
9364 		prev = pecb;
9365 	}
9366 
9367 	ASSERT(pecb != NULL);
9368 
9369 	if (prev == NULL) {
9370 		probe->dtpr_ecb = ecb->dte_next;
9371 	} else {
9372 		prev->dte_next = ecb->dte_next;
9373 	}
9374 
9375 	if (ecb == probe->dtpr_ecb_last) {
9376 		ASSERT(ecb->dte_next == NULL);
9377 		probe->dtpr_ecb_last = prev;
9378 	}
9379 
9380 	/*
9381 	 * The ECB has been disconnected from the probe; now sync to assure
9382 	 * that all CPUs have seen the change before returning.
9383 	 */
9384 	dtrace_sync();
9385 
9386 	if (probe->dtpr_ecb == NULL) {
9387 		/*
9388 		 * That was the last ECB on the probe; clear the predicate
9389 		 * cache ID for the probe, disable it and sync one more time
9390 		 * to assure that we'll never hit it again.
9391 		 */
9392 		dtrace_provider_t *prov = probe->dtpr_provider;
9393 
9394 		ASSERT(ecb->dte_next == NULL);
9395 		ASSERT(probe->dtpr_ecb_last == NULL);
9396 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
9397 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
9398 		    probe->dtpr_id, probe->dtpr_arg);
9399 		dtrace_sync();
9400 	} else {
9401 		/*
9402 		 * There is at least one ECB remaining on the probe.  If there
9403 		 * is _exactly_ one, set the probe's predicate cache ID to be
9404 		 * the predicate cache ID of the remaining ECB.
9405 		 */
9406 		ASSERT(probe->dtpr_ecb_last != NULL);
9407 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
9408 
9409 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
9410 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
9411 
9412 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
9413 
9414 			if (p != NULL)
9415 				probe->dtpr_predcache = p->dtp_cacheid;
9416 		}
9417 
9418 		ecb->dte_next = NULL;
9419 	}
9420 }
9421 
9422 static void
9423 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
9424 {
9425 	dtrace_state_t *state = ecb->dte_state;
9426 	dtrace_vstate_t *vstate = &state->dts_vstate;
9427 	dtrace_predicate_t *pred;
9428 	dtrace_epid_t epid = ecb->dte_epid;
9429 
9430 	ASSERT(MUTEX_HELD(&dtrace_lock));
9431 	ASSERT(ecb->dte_next == NULL);
9432 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
9433 
9434 	if ((pred = ecb->dte_predicate) != NULL)
9435 		dtrace_predicate_release(pred, vstate);
9436 
9437 	dtrace_ecb_action_remove(ecb);
9438 
9439 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
9440 	state->dts_ecbs[epid - 1] = NULL;
9441 
9442 	kmem_free(ecb, sizeof (dtrace_ecb_t));
9443 }
9444 
9445 static dtrace_ecb_t *
9446 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
9447     dtrace_enabling_t *enab)
9448 {
9449 	dtrace_ecb_t *ecb;
9450 	dtrace_predicate_t *pred;
9451 	dtrace_actdesc_t *act;
9452 	dtrace_provider_t *prov;
9453 	dtrace_ecbdesc_t *desc = enab->dten_current;
9454 
9455 	ASSERT(MUTEX_HELD(&dtrace_lock));
9456 	ASSERT(state != NULL);
9457 
9458 	ecb = dtrace_ecb_add(state, probe);
9459 	ecb->dte_uarg = desc->dted_uarg;
9460 
9461 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
9462 		dtrace_predicate_hold(pred);
9463 		ecb->dte_predicate = pred;
9464 	}
9465 
9466 	if (probe != NULL) {
9467 		/*
9468 		 * If the provider shows more leg than the consumer is old
9469 		 * enough to see, we need to enable the appropriate implicit
9470 		 * predicate bits to prevent the ecb from activating at
9471 		 * revealing times.
9472 		 *
9473 		 * Providers specifying DTRACE_PRIV_USER at register time
9474 		 * are stating that they need the /proc-style privilege
9475 		 * model to be enforced, and this is what DTRACE_COND_OWNER
9476 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
9477 		 */
9478 		prov = probe->dtpr_provider;
9479 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
9480 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9481 			ecb->dte_cond |= DTRACE_COND_OWNER;
9482 
9483 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
9484 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9485 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
9486 
9487 		/*
9488 		 * If the provider shows us kernel innards and the user
9489 		 * is lacking sufficient privilege, enable the
9490 		 * DTRACE_COND_USERMODE implicit predicate.
9491 		 */
9492 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
9493 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
9494 			ecb->dte_cond |= DTRACE_COND_USERMODE;
9495 	}
9496 
9497 	if (dtrace_ecb_create_cache != NULL) {
9498 		/*
9499 		 * If we have a cached ecb, we'll use its action list instead
9500 		 * of creating our own (saving both time and space).
9501 		 */
9502 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
9503 		dtrace_action_t *act = cached->dte_action;
9504 
9505 		if (act != NULL) {
9506 			ASSERT(act->dta_refcnt > 0);
9507 			act->dta_refcnt++;
9508 			ecb->dte_action = act;
9509 			ecb->dte_action_last = cached->dte_action_last;
9510 			ecb->dte_needed = cached->dte_needed;
9511 			ecb->dte_size = cached->dte_size;
9512 			ecb->dte_alignment = cached->dte_alignment;
9513 		}
9514 
9515 		return (ecb);
9516 	}
9517 
9518 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
9519 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
9520 			dtrace_ecb_destroy(ecb);
9521 			return (NULL);
9522 		}
9523 	}
9524 
9525 	dtrace_ecb_resize(ecb);
9526 
9527 	return (dtrace_ecb_create_cache = ecb);
9528 }
9529 
9530 static int
9531 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
9532 {
9533 	dtrace_ecb_t *ecb;
9534 	dtrace_enabling_t *enab = arg;
9535 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
9536 
9537 	ASSERT(state != NULL);
9538 
9539 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
9540 		/*
9541 		 * This probe was created in a generation for which this
9542 		 * enabling has previously created ECBs; we don't want to
9543 		 * enable it again, so just kick out.
9544 		 */
9545 		return (DTRACE_MATCH_NEXT);
9546 	}
9547 
9548 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
9549 		return (DTRACE_MATCH_DONE);
9550 
9551 	dtrace_ecb_enable(ecb);
9552 	return (DTRACE_MATCH_NEXT);
9553 }
9554 
9555 static dtrace_ecb_t *
9556 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
9557 {
9558 	dtrace_ecb_t *ecb;
9559 
9560 	ASSERT(MUTEX_HELD(&dtrace_lock));
9561 
9562 	if (id == 0 || id > state->dts_necbs)
9563 		return (NULL);
9564 
9565 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
9566 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
9567 
9568 	return (state->dts_ecbs[id - 1]);
9569 }
9570 
9571 static dtrace_aggregation_t *
9572 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
9573 {
9574 	dtrace_aggregation_t *agg;
9575 
9576 	ASSERT(MUTEX_HELD(&dtrace_lock));
9577 
9578 	if (id == 0 || id > state->dts_naggregations)
9579 		return (NULL);
9580 
9581 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
9582 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
9583 	    agg->dtag_id == id);
9584 
9585 	return (state->dts_aggregations[id - 1]);
9586 }
9587 
9588 /*
9589  * DTrace Buffer Functions
9590  *
9591  * The following functions manipulate DTrace buffers.  Most of these functions
9592  * are called in the context of establishing or processing consumer state;
9593  * exceptions are explicitly noted.
9594  */
9595 
9596 /*
9597  * Note:  called from cross call context.  This function switches the two
9598  * buffers on a given CPU.  The atomicity of this operation is assured by
9599  * disabling interrupts while the actual switch takes place; the disabling of
9600  * interrupts serializes the execution with any execution of dtrace_probe() on
9601  * the same CPU.
9602  */
9603 static void
9604 dtrace_buffer_switch(dtrace_buffer_t *buf)
9605 {
9606 	caddr_t tomax = buf->dtb_tomax;
9607 	caddr_t xamot = buf->dtb_xamot;
9608 	dtrace_icookie_t cookie;
9609 
9610 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
9611 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
9612 
9613 	cookie = dtrace_interrupt_disable();
9614 	buf->dtb_tomax = xamot;
9615 	buf->dtb_xamot = tomax;
9616 	buf->dtb_xamot_drops = buf->dtb_drops;
9617 	buf->dtb_xamot_offset = buf->dtb_offset;
9618 	buf->dtb_xamot_errors = buf->dtb_errors;
9619 	buf->dtb_xamot_flags = buf->dtb_flags;
9620 	buf->dtb_offset = 0;
9621 	buf->dtb_drops = 0;
9622 	buf->dtb_errors = 0;
9623 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
9624 	dtrace_interrupt_enable(cookie);
9625 }
9626 
9627 /*
9628  * Note:  called from cross call context.  This function activates a buffer
9629  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
9630  * is guaranteed by the disabling of interrupts.
9631  */
9632 static void
9633 dtrace_buffer_activate(dtrace_state_t *state)
9634 {
9635 	dtrace_buffer_t *buf;
9636 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
9637 
9638 	buf = &state->dts_buffer[CPU->cpu_id];
9639 
9640 	if (buf->dtb_tomax != NULL) {
9641 		/*
9642 		 * We might like to assert that the buffer is marked inactive,
9643 		 * but this isn't necessarily true:  the buffer for the CPU
9644 		 * that processes the BEGIN probe has its buffer activated
9645 		 * manually.  In this case, we take the (harmless) action
9646 		 * re-clearing the bit INACTIVE bit.
9647 		 */
9648 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
9649 	}
9650 
9651 	dtrace_interrupt_enable(cookie);
9652 }
9653 
9654 static int
9655 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
9656     processorid_t cpu)
9657 {
9658 	cpu_t *cp;
9659 	dtrace_buffer_t *buf;
9660 
9661 	ASSERT(MUTEX_HELD(&cpu_lock));
9662 	ASSERT(MUTEX_HELD(&dtrace_lock));
9663 
9664 	if (size > dtrace_nonroot_maxsize &&
9665 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
9666 		return (EFBIG);
9667 
9668 	cp = cpu_list;
9669 
9670 	do {
9671 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9672 			continue;
9673 
9674 		buf = &bufs[cp->cpu_id];
9675 
9676 		/*
9677 		 * If there is already a buffer allocated for this CPU, it
9678 		 * is only possible that this is a DR event.  In this case,
9679 		 * the buffer size must match our specified size.
9680 		 */
9681 		if (buf->dtb_tomax != NULL) {
9682 			ASSERT(buf->dtb_size == size);
9683 			continue;
9684 		}
9685 
9686 		ASSERT(buf->dtb_xamot == NULL);
9687 
9688 		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9689 			goto err;
9690 
9691 		buf->dtb_size = size;
9692 		buf->dtb_flags = flags;
9693 		buf->dtb_offset = 0;
9694 		buf->dtb_drops = 0;
9695 
9696 		if (flags & DTRACEBUF_NOSWITCH)
9697 			continue;
9698 
9699 		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9700 			goto err;
9701 	} while ((cp = cp->cpu_next) != cpu_list);
9702 
9703 	return (0);
9704 
9705 err:
9706 	cp = cpu_list;
9707 
9708 	do {
9709 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9710 			continue;
9711 
9712 		buf = &bufs[cp->cpu_id];
9713 
9714 		if (buf->dtb_xamot != NULL) {
9715 			ASSERT(buf->dtb_tomax != NULL);
9716 			ASSERT(buf->dtb_size == size);
9717 			kmem_free(buf->dtb_xamot, size);
9718 		}
9719 
9720 		if (buf->dtb_tomax != NULL) {
9721 			ASSERT(buf->dtb_size == size);
9722 			kmem_free(buf->dtb_tomax, size);
9723 		}
9724 
9725 		buf->dtb_tomax = NULL;
9726 		buf->dtb_xamot = NULL;
9727 		buf->dtb_size = 0;
9728 	} while ((cp = cp->cpu_next) != cpu_list);
9729 
9730 	return (ENOMEM);
9731 }
9732 
9733 /*
9734  * Note:  called from probe context.  This function just increments the drop
9735  * count on a buffer.  It has been made a function to allow for the
9736  * possibility of understanding the source of mysterious drop counts.  (A
9737  * problem for which one may be particularly disappointed that DTrace cannot
9738  * be used to understand DTrace.)
9739  */
9740 static void
9741 dtrace_buffer_drop(dtrace_buffer_t *buf)
9742 {
9743 	buf->dtb_drops++;
9744 }
9745 
9746 /*
9747  * Note:  called from probe context.  This function is called to reserve space
9748  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
9749  * mstate.  Returns the new offset in the buffer, or a negative value if an
9750  * error has occurred.
9751  */
9752 static intptr_t
9753 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
9754     dtrace_state_t *state, dtrace_mstate_t *mstate)
9755 {
9756 	intptr_t offs = buf->dtb_offset, soffs;
9757 	intptr_t woffs;
9758 	caddr_t tomax;
9759 	size_t total;
9760 
9761 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
9762 		return (-1);
9763 
9764 	if ((tomax = buf->dtb_tomax) == NULL) {
9765 		dtrace_buffer_drop(buf);
9766 		return (-1);
9767 	}
9768 
9769 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
9770 		while (offs & (align - 1)) {
9771 			/*
9772 			 * Assert that our alignment is off by a number which
9773 			 * is itself sizeof (uint32_t) aligned.
9774 			 */
9775 			ASSERT(!((align - (offs & (align - 1))) &
9776 			    (sizeof (uint32_t) - 1)));
9777 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
9778 			offs += sizeof (uint32_t);
9779 		}
9780 
9781 		if ((soffs = offs + needed) > buf->dtb_size) {
9782 			dtrace_buffer_drop(buf);
9783 			return (-1);
9784 		}
9785 
9786 		if (mstate == NULL)
9787 			return (offs);
9788 
9789 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
9790 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
9791 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
9792 
9793 		return (offs);
9794 	}
9795 
9796 	if (buf->dtb_flags & DTRACEBUF_FILL) {
9797 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
9798 		    (buf->dtb_flags & DTRACEBUF_FULL))
9799 			return (-1);
9800 		goto out;
9801 	}
9802 
9803 	total = needed + (offs & (align - 1));
9804 
9805 	/*
9806 	 * For a ring buffer, life is quite a bit more complicated.  Before
9807 	 * we can store any padding, we need to adjust our wrapping offset.
9808 	 * (If we've never before wrapped or we're not about to, no adjustment
9809 	 * is required.)
9810 	 */
9811 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
9812 	    offs + total > buf->dtb_size) {
9813 		woffs = buf->dtb_xamot_offset;
9814 
9815 		if (offs + total > buf->dtb_size) {
9816 			/*
9817 			 * We can't fit in the end of the buffer.  First, a
9818 			 * sanity check that we can fit in the buffer at all.
9819 			 */
9820 			if (total > buf->dtb_size) {
9821 				dtrace_buffer_drop(buf);
9822 				return (-1);
9823 			}
9824 
9825 			/*
9826 			 * We're going to be storing at the top of the buffer,
9827 			 * so now we need to deal with the wrapped offset.  We
9828 			 * only reset our wrapped offset to 0 if it is
9829 			 * currently greater than the current offset.  If it
9830 			 * is less than the current offset, it is because a
9831 			 * previous allocation induced a wrap -- but the
9832 			 * allocation didn't subsequently take the space due
9833 			 * to an error or false predicate evaluation.  In this
9834 			 * case, we'll just leave the wrapped offset alone: if
9835 			 * the wrapped offset hasn't been advanced far enough
9836 			 * for this allocation, it will be adjusted in the
9837 			 * lower loop.
9838 			 */
9839 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
9840 				if (woffs >= offs)
9841 					woffs = 0;
9842 			} else {
9843 				woffs = 0;
9844 			}
9845 
9846 			/*
9847 			 * Now we know that we're going to be storing to the
9848 			 * top of the buffer and that there is room for us
9849 			 * there.  We need to clear the buffer from the current
9850 			 * offset to the end (there may be old gunk there).
9851 			 */
9852 			while (offs < buf->dtb_size)
9853 				tomax[offs++] = 0;
9854 
9855 			/*
9856 			 * We need to set our offset to zero.  And because we
9857 			 * are wrapping, we need to set the bit indicating as
9858 			 * much.  We can also adjust our needed space back
9859 			 * down to the space required by the ECB -- we know
9860 			 * that the top of the buffer is aligned.
9861 			 */
9862 			offs = 0;
9863 			total = needed;
9864 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
9865 		} else {
9866 			/*
9867 			 * There is room for us in the buffer, so we simply
9868 			 * need to check the wrapped offset.
9869 			 */
9870 			if (woffs < offs) {
9871 				/*
9872 				 * The wrapped offset is less than the offset.
9873 				 * This can happen if we allocated buffer space
9874 				 * that induced a wrap, but then we didn't
9875 				 * subsequently take the space due to an error
9876 				 * or false predicate evaluation.  This is
9877 				 * okay; we know that _this_ allocation isn't
9878 				 * going to induce a wrap.  We still can't
9879 				 * reset the wrapped offset to be zero,
9880 				 * however: the space may have been trashed in
9881 				 * the previous failed probe attempt.  But at
9882 				 * least the wrapped offset doesn't need to
9883 				 * be adjusted at all...
9884 				 */
9885 				goto out;
9886 			}
9887 		}
9888 
9889 		while (offs + total > woffs) {
9890 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
9891 			size_t size;
9892 
9893 			if (epid == DTRACE_EPIDNONE) {
9894 				size = sizeof (uint32_t);
9895 			} else {
9896 				ASSERT(epid <= state->dts_necbs);
9897 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
9898 
9899 				size = state->dts_ecbs[epid - 1]->dte_size;
9900 			}
9901 
9902 			ASSERT(woffs + size <= buf->dtb_size);
9903 			ASSERT(size != 0);
9904 
9905 			if (woffs + size == buf->dtb_size) {
9906 				/*
9907 				 * We've reached the end of the buffer; we want
9908 				 * to set the wrapped offset to 0 and break
9909 				 * out.  However, if the offs is 0, then we're
9910 				 * in a strange edge-condition:  the amount of
9911 				 * space that we want to reserve plus the size
9912 				 * of the record that we're overwriting is
9913 				 * greater than the size of the buffer.  This
9914 				 * is problematic because if we reserve the
9915 				 * space but subsequently don't consume it (due
9916 				 * to a failed predicate or error) the wrapped
9917 				 * offset will be 0 -- yet the EPID at offset 0
9918 				 * will not be committed.  This situation is
9919 				 * relatively easy to deal with:  if we're in
9920 				 * this case, the buffer is indistinguishable
9921 				 * from one that hasn't wrapped; we need only
9922 				 * finish the job by clearing the wrapped bit,
9923 				 * explicitly setting the offset to be 0, and
9924 				 * zero'ing out the old data in the buffer.
9925 				 */
9926 				if (offs == 0) {
9927 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
9928 					buf->dtb_offset = 0;
9929 					woffs = total;
9930 
9931 					while (woffs < buf->dtb_size)
9932 						tomax[woffs++] = 0;
9933 				}
9934 
9935 				woffs = 0;
9936 				break;
9937 			}
9938 
9939 			woffs += size;
9940 		}
9941 
9942 		/*
9943 		 * We have a wrapped offset.  It may be that the wrapped offset
9944 		 * has become zero -- that's okay.
9945 		 */
9946 		buf->dtb_xamot_offset = woffs;
9947 	}
9948 
9949 out:
9950 	/*
9951 	 * Now we can plow the buffer with any necessary padding.
9952 	 */
9953 	while (offs & (align - 1)) {
9954 		/*
9955 		 * Assert that our alignment is off by a number which
9956 		 * is itself sizeof (uint32_t) aligned.
9957 		 */
9958 		ASSERT(!((align - (offs & (align - 1))) &
9959 		    (sizeof (uint32_t) - 1)));
9960 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
9961 		offs += sizeof (uint32_t);
9962 	}
9963 
9964 	if (buf->dtb_flags & DTRACEBUF_FILL) {
9965 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
9966 			buf->dtb_flags |= DTRACEBUF_FULL;
9967 			return (-1);
9968 		}
9969 	}
9970 
9971 	if (mstate == NULL)
9972 		return (offs);
9973 
9974 	/*
9975 	 * For ring buffers and fill buffers, the scratch space is always
9976 	 * the inactive buffer.
9977 	 */
9978 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
9979 	mstate->dtms_scratch_size = buf->dtb_size;
9980 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
9981 
9982 	return (offs);
9983 }
9984 
9985 static void
9986 dtrace_buffer_polish(dtrace_buffer_t *buf)
9987 {
9988 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
9989 	ASSERT(MUTEX_HELD(&dtrace_lock));
9990 
9991 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
9992 		return;
9993 
9994 	/*
9995 	 * We need to polish the ring buffer.  There are three cases:
9996 	 *
9997 	 * - The first (and presumably most common) is that there is no gap
9998 	 *   between the buffer offset and the wrapped offset.  In this case,
9999 	 *   there is nothing in the buffer that isn't valid data; we can
10000 	 *   mark the buffer as polished and return.
10001 	 *
10002 	 * - The second (less common than the first but still more common
10003 	 *   than the third) is that there is a gap between the buffer offset
10004 	 *   and the wrapped offset, and the wrapped offset is larger than the
10005 	 *   buffer offset.  This can happen because of an alignment issue, or
10006 	 *   can happen because of a call to dtrace_buffer_reserve() that
10007 	 *   didn't subsequently consume the buffer space.  In this case,
10008 	 *   we need to zero the data from the buffer offset to the wrapped
10009 	 *   offset.
10010 	 *
10011 	 * - The third (and least common) is that there is a gap between the
10012 	 *   buffer offset and the wrapped offset, but the wrapped offset is
10013 	 *   _less_ than the buffer offset.  This can only happen because a
10014 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
10015 	 *   was not subsequently consumed.  In this case, we need to zero the
10016 	 *   space from the offset to the end of the buffer _and_ from the
10017 	 *   top of the buffer to the wrapped offset.
10018 	 */
10019 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
10020 		bzero(buf->dtb_tomax + buf->dtb_offset,
10021 		    buf->dtb_xamot_offset - buf->dtb_offset);
10022 	}
10023 
10024 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
10025 		bzero(buf->dtb_tomax + buf->dtb_offset,
10026 		    buf->dtb_size - buf->dtb_offset);
10027 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
10028 	}
10029 }
10030 
10031 static void
10032 dtrace_buffer_free(dtrace_buffer_t *bufs)
10033 {
10034 	int i;
10035 
10036 	for (i = 0; i < NCPU; i++) {
10037 		dtrace_buffer_t *buf = &bufs[i];
10038 
10039 		if (buf->dtb_tomax == NULL) {
10040 			ASSERT(buf->dtb_xamot == NULL);
10041 			ASSERT(buf->dtb_size == 0);
10042 			continue;
10043 		}
10044 
10045 		if (buf->dtb_xamot != NULL) {
10046 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10047 			kmem_free(buf->dtb_xamot, buf->dtb_size);
10048 		}
10049 
10050 		kmem_free(buf->dtb_tomax, buf->dtb_size);
10051 		buf->dtb_size = 0;
10052 		buf->dtb_tomax = NULL;
10053 		buf->dtb_xamot = NULL;
10054 	}
10055 }
10056 
10057 /*
10058  * DTrace Enabling Functions
10059  */
10060 static dtrace_enabling_t *
10061 dtrace_enabling_create(dtrace_vstate_t *vstate)
10062 {
10063 	dtrace_enabling_t *enab;
10064 
10065 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
10066 	enab->dten_vstate = vstate;
10067 
10068 	return (enab);
10069 }
10070 
10071 static void
10072 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
10073 {
10074 	dtrace_ecbdesc_t **ndesc;
10075 	size_t osize, nsize;
10076 
10077 	/*
10078 	 * We can't add to enablings after we've enabled them, or after we've
10079 	 * retained them.
10080 	 */
10081 	ASSERT(enab->dten_probegen == 0);
10082 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10083 
10084 	if (enab->dten_ndesc < enab->dten_maxdesc) {
10085 		enab->dten_desc[enab->dten_ndesc++] = ecb;
10086 		return;
10087 	}
10088 
10089 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10090 
10091 	if (enab->dten_maxdesc == 0) {
10092 		enab->dten_maxdesc = 1;
10093 	} else {
10094 		enab->dten_maxdesc <<= 1;
10095 	}
10096 
10097 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
10098 
10099 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10100 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
10101 	bcopy(enab->dten_desc, ndesc, osize);
10102 	kmem_free(enab->dten_desc, osize);
10103 
10104 	enab->dten_desc = ndesc;
10105 	enab->dten_desc[enab->dten_ndesc++] = ecb;
10106 }
10107 
10108 static void
10109 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
10110     dtrace_probedesc_t *pd)
10111 {
10112 	dtrace_ecbdesc_t *new;
10113 	dtrace_predicate_t *pred;
10114 	dtrace_actdesc_t *act;
10115 
10116 	/*
10117 	 * We're going to create a new ECB description that matches the
10118 	 * specified ECB in every way, but has the specified probe description.
10119 	 */
10120 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
10121 
10122 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
10123 		dtrace_predicate_hold(pred);
10124 
10125 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
10126 		dtrace_actdesc_hold(act);
10127 
10128 	new->dted_action = ecb->dted_action;
10129 	new->dted_pred = ecb->dted_pred;
10130 	new->dted_probe = *pd;
10131 	new->dted_uarg = ecb->dted_uarg;
10132 
10133 	dtrace_enabling_add(enab, new);
10134 }
10135 
10136 static void
10137 dtrace_enabling_dump(dtrace_enabling_t *enab)
10138 {
10139 	int i;
10140 
10141 	for (i = 0; i < enab->dten_ndesc; i++) {
10142 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
10143 
10144 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
10145 		    desc->dtpd_provider, desc->dtpd_mod,
10146 		    desc->dtpd_func, desc->dtpd_name);
10147 	}
10148 }
10149 
10150 static void
10151 dtrace_enabling_destroy(dtrace_enabling_t *enab)
10152 {
10153 	int i;
10154 	dtrace_ecbdesc_t *ep;
10155 	dtrace_vstate_t *vstate = enab->dten_vstate;
10156 
10157 	ASSERT(MUTEX_HELD(&dtrace_lock));
10158 
10159 	for (i = 0; i < enab->dten_ndesc; i++) {
10160 		dtrace_actdesc_t *act, *next;
10161 		dtrace_predicate_t *pred;
10162 
10163 		ep = enab->dten_desc[i];
10164 
10165 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
10166 			dtrace_predicate_release(pred, vstate);
10167 
10168 		for (act = ep->dted_action; act != NULL; act = next) {
10169 			next = act->dtad_next;
10170 			dtrace_actdesc_release(act, vstate);
10171 		}
10172 
10173 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
10174 	}
10175 
10176 	kmem_free(enab->dten_desc,
10177 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
10178 
10179 	/*
10180 	 * If this was a retained enabling, decrement the dts_nretained count
10181 	 * and take it off of the dtrace_retained list.
10182 	 */
10183 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
10184 	    dtrace_retained == enab) {
10185 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10186 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
10187 		enab->dten_vstate->dtvs_state->dts_nretained--;
10188 	}
10189 
10190 	if (enab->dten_prev == NULL) {
10191 		if (dtrace_retained == enab) {
10192 			dtrace_retained = enab->dten_next;
10193 
10194 			if (dtrace_retained != NULL)
10195 				dtrace_retained->dten_prev = NULL;
10196 		}
10197 	} else {
10198 		ASSERT(enab != dtrace_retained);
10199 		ASSERT(dtrace_retained != NULL);
10200 		enab->dten_prev->dten_next = enab->dten_next;
10201 	}
10202 
10203 	if (enab->dten_next != NULL) {
10204 		ASSERT(dtrace_retained != NULL);
10205 		enab->dten_next->dten_prev = enab->dten_prev;
10206 	}
10207 
10208 	kmem_free(enab, sizeof (dtrace_enabling_t));
10209 }
10210 
10211 static int
10212 dtrace_enabling_retain(dtrace_enabling_t *enab)
10213 {
10214 	dtrace_state_t *state;
10215 
10216 	ASSERT(MUTEX_HELD(&dtrace_lock));
10217 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10218 	ASSERT(enab->dten_vstate != NULL);
10219 
10220 	state = enab->dten_vstate->dtvs_state;
10221 	ASSERT(state != NULL);
10222 
10223 	/*
10224 	 * We only allow each state to retain dtrace_retain_max enablings.
10225 	 */
10226 	if (state->dts_nretained >= dtrace_retain_max)
10227 		return (ENOSPC);
10228 
10229 	state->dts_nretained++;
10230 
10231 	if (dtrace_retained == NULL) {
10232 		dtrace_retained = enab;
10233 		return (0);
10234 	}
10235 
10236 	enab->dten_next = dtrace_retained;
10237 	dtrace_retained->dten_prev = enab;
10238 	dtrace_retained = enab;
10239 
10240 	return (0);
10241 }
10242 
10243 static int
10244 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
10245     dtrace_probedesc_t *create)
10246 {
10247 	dtrace_enabling_t *new, *enab;
10248 	int found = 0, err = ENOENT;
10249 
10250 	ASSERT(MUTEX_HELD(&dtrace_lock));
10251 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
10252 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
10253 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
10254 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
10255 
10256 	new = dtrace_enabling_create(&state->dts_vstate);
10257 
10258 	/*
10259 	 * Iterate over all retained enablings, looking for enablings that
10260 	 * match the specified state.
10261 	 */
10262 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10263 		int i;
10264 
10265 		/*
10266 		 * dtvs_state can only be NULL for helper enablings -- and
10267 		 * helper enablings can't be retained.
10268 		 */
10269 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10270 
10271 		if (enab->dten_vstate->dtvs_state != state)
10272 			continue;
10273 
10274 		/*
10275 		 * Now iterate over each probe description; we're looking for
10276 		 * an exact match to the specified probe description.
10277 		 */
10278 		for (i = 0; i < enab->dten_ndesc; i++) {
10279 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
10280 			dtrace_probedesc_t *pd = &ep->dted_probe;
10281 
10282 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
10283 				continue;
10284 
10285 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
10286 				continue;
10287 
10288 			if (strcmp(pd->dtpd_func, match->dtpd_func))
10289 				continue;
10290 
10291 			if (strcmp(pd->dtpd_name, match->dtpd_name))
10292 				continue;
10293 
10294 			/*
10295 			 * We have a winning probe!  Add it to our growing
10296 			 * enabling.
10297 			 */
10298 			found = 1;
10299 			dtrace_enabling_addlike(new, ep, create);
10300 		}
10301 	}
10302 
10303 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
10304 		dtrace_enabling_destroy(new);
10305 		return (err);
10306 	}
10307 
10308 	return (0);
10309 }
10310 
10311 static void
10312 dtrace_enabling_retract(dtrace_state_t *state)
10313 {
10314 	dtrace_enabling_t *enab, *next;
10315 
10316 	ASSERT(MUTEX_HELD(&dtrace_lock));
10317 
10318 	/*
10319 	 * Iterate over all retained enablings, destroy the enablings retained
10320 	 * for the specified state.
10321 	 */
10322 	for (enab = dtrace_retained; enab != NULL; enab = next) {
10323 		next = enab->dten_next;
10324 
10325 		/*
10326 		 * dtvs_state can only be NULL for helper enablings -- and
10327 		 * helper enablings can't be retained.
10328 		 */
10329 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10330 
10331 		if (enab->dten_vstate->dtvs_state == state) {
10332 			ASSERT(state->dts_nretained > 0);
10333 			dtrace_enabling_destroy(enab);
10334 		}
10335 	}
10336 
10337 	ASSERT(state->dts_nretained == 0);
10338 }
10339 
10340 static int
10341 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
10342 {
10343 	int i = 0;
10344 	int matched = 0;
10345 
10346 	ASSERT(MUTEX_HELD(&cpu_lock));
10347 	ASSERT(MUTEX_HELD(&dtrace_lock));
10348 
10349 	for (i = 0; i < enab->dten_ndesc; i++) {
10350 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
10351 
10352 		enab->dten_current = ep;
10353 		enab->dten_error = 0;
10354 
10355 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
10356 
10357 		if (enab->dten_error != 0) {
10358 			/*
10359 			 * If we get an error half-way through enabling the
10360 			 * probes, we kick out -- perhaps with some number of
10361 			 * them enabled.  Leaving enabled probes enabled may
10362 			 * be slightly confusing for user-level, but we expect
10363 			 * that no one will attempt to actually drive on in
10364 			 * the face of such errors.  If this is an anonymous
10365 			 * enabling (indicated with a NULL nmatched pointer),
10366 			 * we cmn_err() a message.  We aren't expecting to
10367 			 * get such an error -- such as it can exist at all,
10368 			 * it would be a result of corrupted DOF in the driver
10369 			 * properties.
10370 			 */
10371 			if (nmatched == NULL) {
10372 				cmn_err(CE_WARN, "dtrace_enabling_match() "
10373 				    "error on %p: %d", (void *)ep,
10374 				    enab->dten_error);
10375 			}
10376 
10377 			return (enab->dten_error);
10378 		}
10379 	}
10380 
10381 	enab->dten_probegen = dtrace_probegen;
10382 	if (nmatched != NULL)
10383 		*nmatched = matched;
10384 
10385 	return (0);
10386 }
10387 
10388 static void
10389 dtrace_enabling_matchall(void)
10390 {
10391 	dtrace_enabling_t *enab;
10392 
10393 	mutex_enter(&cpu_lock);
10394 	mutex_enter(&dtrace_lock);
10395 
10396 	/*
10397 	 * Because we can be called after dtrace_detach() has been called, we
10398 	 * cannot assert that there are retained enablings.  We can safely
10399 	 * load from dtrace_retained, however:  the taskq_destroy() at the
10400 	 * end of dtrace_detach() will block pending our completion.
10401 	 */
10402 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next)
10403 		(void) dtrace_enabling_match(enab, NULL);
10404 
10405 	mutex_exit(&dtrace_lock);
10406 	mutex_exit(&cpu_lock);
10407 }
10408 
10409 static int
10410 dtrace_enabling_matchstate(dtrace_state_t *state, int *nmatched)
10411 {
10412 	dtrace_enabling_t *enab;
10413 	int matched, total = 0, err;
10414 
10415 	ASSERT(MUTEX_HELD(&cpu_lock));
10416 	ASSERT(MUTEX_HELD(&dtrace_lock));
10417 
10418 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10419 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10420 
10421 		if (enab->dten_vstate->dtvs_state != state)
10422 			continue;
10423 
10424 		if ((err = dtrace_enabling_match(enab, &matched)) != 0)
10425 			return (err);
10426 
10427 		total += matched;
10428 	}
10429 
10430 	if (nmatched != NULL)
10431 		*nmatched = total;
10432 
10433 	return (0);
10434 }
10435 
10436 /*
10437  * If an enabling is to be enabled without having matched probes (that is, if
10438  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
10439  * enabling must be _primed_ by creating an ECB for every ECB description.
10440  * This must be done to assure that we know the number of speculations, the
10441  * number of aggregations, the minimum buffer size needed, etc. before we
10442  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
10443  * enabling any probes, we create ECBs for every ECB decription, but with a
10444  * NULL probe -- which is exactly what this function does.
10445  */
10446 static void
10447 dtrace_enabling_prime(dtrace_state_t *state)
10448 {
10449 	dtrace_enabling_t *enab;
10450 	int i;
10451 
10452 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10453 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10454 
10455 		if (enab->dten_vstate->dtvs_state != state)
10456 			continue;
10457 
10458 		/*
10459 		 * We don't want to prime an enabling more than once, lest
10460 		 * we allow a malicious user to induce resource exhaustion.
10461 		 * (The ECBs that result from priming an enabling aren't
10462 		 * leaked -- but they also aren't deallocated until the
10463 		 * consumer state is destroyed.)
10464 		 */
10465 		if (enab->dten_primed)
10466 			continue;
10467 
10468 		for (i = 0; i < enab->dten_ndesc; i++) {
10469 			enab->dten_current = enab->dten_desc[i];
10470 			(void) dtrace_probe_enable(NULL, enab);
10471 		}
10472 
10473 		enab->dten_primed = 1;
10474 	}
10475 }
10476 
10477 /*
10478  * Called to indicate that probes should be provided due to retained
10479  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
10480  * must take an initial lap through the enabling calling the dtps_provide()
10481  * entry point explicitly to allow for autocreated probes.
10482  */
10483 static void
10484 dtrace_enabling_provide(dtrace_provider_t *prv)
10485 {
10486 	int i, all = 0;
10487 	dtrace_probedesc_t desc;
10488 
10489 	ASSERT(MUTEX_HELD(&dtrace_lock));
10490 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
10491 
10492 	if (prv == NULL) {
10493 		all = 1;
10494 		prv = dtrace_provider;
10495 	}
10496 
10497 	do {
10498 		dtrace_enabling_t *enab = dtrace_retained;
10499 		void *parg = prv->dtpv_arg;
10500 
10501 		for (; enab != NULL; enab = enab->dten_next) {
10502 			for (i = 0; i < enab->dten_ndesc; i++) {
10503 				desc = enab->dten_desc[i]->dted_probe;
10504 				mutex_exit(&dtrace_lock);
10505 				prv->dtpv_pops.dtps_provide(parg, &desc);
10506 				mutex_enter(&dtrace_lock);
10507 			}
10508 		}
10509 	} while (all && (prv = prv->dtpv_next) != NULL);
10510 
10511 	mutex_exit(&dtrace_lock);
10512 	dtrace_probe_provide(NULL, all ? NULL : prv);
10513 	mutex_enter(&dtrace_lock);
10514 }
10515 
10516 /*
10517  * DTrace DOF Functions
10518  */
10519 /*ARGSUSED*/
10520 static void
10521 dtrace_dof_error(dof_hdr_t *dof, const char *str)
10522 {
10523 	if (dtrace_err_verbose)
10524 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
10525 
10526 #ifdef DTRACE_ERRDEBUG
10527 	dtrace_errdebug(str);
10528 #endif
10529 }
10530 
10531 /*
10532  * Create DOF out of a currently enabled state.  Right now, we only create
10533  * DOF containing the run-time options -- but this could be expanded to create
10534  * complete DOF representing the enabled state.
10535  */
10536 static dof_hdr_t *
10537 dtrace_dof_create(dtrace_state_t *state)
10538 {
10539 	dof_hdr_t *dof;
10540 	dof_sec_t *sec;
10541 	dof_optdesc_t *opt;
10542 	int i, len = sizeof (dof_hdr_t) +
10543 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
10544 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10545 
10546 	ASSERT(MUTEX_HELD(&dtrace_lock));
10547 
10548 	dof = kmem_zalloc(len, KM_SLEEP);
10549 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
10550 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
10551 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
10552 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
10553 
10554 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
10555 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
10556 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
10557 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
10558 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
10559 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
10560 
10561 	dof->dofh_flags = 0;
10562 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
10563 	dof->dofh_secsize = sizeof (dof_sec_t);
10564 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
10565 	dof->dofh_secoff = sizeof (dof_hdr_t);
10566 	dof->dofh_loadsz = len;
10567 	dof->dofh_filesz = len;
10568 	dof->dofh_pad = 0;
10569 
10570 	/*
10571 	 * Fill in the option section header...
10572 	 */
10573 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
10574 	sec->dofs_type = DOF_SECT_OPTDESC;
10575 	sec->dofs_align = sizeof (uint64_t);
10576 	sec->dofs_flags = DOF_SECF_LOAD;
10577 	sec->dofs_entsize = sizeof (dof_optdesc_t);
10578 
10579 	opt = (dof_optdesc_t *)((uintptr_t)sec +
10580 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
10581 
10582 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
10583 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10584 
10585 	for (i = 0; i < DTRACEOPT_MAX; i++) {
10586 		opt[i].dofo_option = i;
10587 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
10588 		opt[i].dofo_value = state->dts_options[i];
10589 	}
10590 
10591 	return (dof);
10592 }
10593 
10594 static dof_hdr_t *
10595 dtrace_dof_copyin(uintptr_t uarg, int *errp)
10596 {
10597 	dof_hdr_t hdr, *dof;
10598 
10599 	ASSERT(!MUTEX_HELD(&dtrace_lock));
10600 
10601 	/*
10602 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
10603 	 */
10604 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
10605 		dtrace_dof_error(NULL, "failed to copyin DOF header");
10606 		*errp = EFAULT;
10607 		return (NULL);
10608 	}
10609 
10610 	/*
10611 	 * Now we'll allocate the entire DOF and copy it in -- provided
10612 	 * that the length isn't outrageous.
10613 	 */
10614 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
10615 		dtrace_dof_error(&hdr, "load size exceeds maximum");
10616 		*errp = E2BIG;
10617 		return (NULL);
10618 	}
10619 
10620 	if (hdr.dofh_loadsz < sizeof (hdr)) {
10621 		dtrace_dof_error(&hdr, "invalid load size");
10622 		*errp = EINVAL;
10623 		return (NULL);
10624 	}
10625 
10626 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
10627 
10628 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
10629 		kmem_free(dof, hdr.dofh_loadsz);
10630 		*errp = EFAULT;
10631 		return (NULL);
10632 	}
10633 
10634 	return (dof);
10635 }
10636 
10637 static dof_hdr_t *
10638 dtrace_dof_property(const char *name)
10639 {
10640 	uchar_t *buf;
10641 	uint64_t loadsz;
10642 	unsigned int len, i;
10643 	dof_hdr_t *dof;
10644 
10645 	/*
10646 	 * Unfortunately, array of values in .conf files are always (and
10647 	 * only) interpreted to be integer arrays.  We must read our DOF
10648 	 * as an integer array, and then squeeze it into a byte array.
10649 	 */
10650 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
10651 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
10652 		return (NULL);
10653 
10654 	for (i = 0; i < len; i++)
10655 		buf[i] = (uchar_t)(((int *)buf)[i]);
10656 
10657 	if (len < sizeof (dof_hdr_t)) {
10658 		ddi_prop_free(buf);
10659 		dtrace_dof_error(NULL, "truncated header");
10660 		return (NULL);
10661 	}
10662 
10663 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
10664 		ddi_prop_free(buf);
10665 		dtrace_dof_error(NULL, "truncated DOF");
10666 		return (NULL);
10667 	}
10668 
10669 	if (loadsz >= dtrace_dof_maxsize) {
10670 		ddi_prop_free(buf);
10671 		dtrace_dof_error(NULL, "oversized DOF");
10672 		return (NULL);
10673 	}
10674 
10675 	dof = kmem_alloc(loadsz, KM_SLEEP);
10676 	bcopy(buf, dof, loadsz);
10677 	ddi_prop_free(buf);
10678 
10679 	return (dof);
10680 }
10681 
10682 static void
10683 dtrace_dof_destroy(dof_hdr_t *dof)
10684 {
10685 	kmem_free(dof, dof->dofh_loadsz);
10686 }
10687 
10688 /*
10689  * Return the dof_sec_t pointer corresponding to a given section index.  If the
10690  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
10691  * a type other than DOF_SECT_NONE is specified, the header is checked against
10692  * this type and NULL is returned if the types do not match.
10693  */
10694 static dof_sec_t *
10695 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
10696 {
10697 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
10698 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
10699 
10700 	if (i >= dof->dofh_secnum) {
10701 		dtrace_dof_error(dof, "referenced section index is invalid");
10702 		return (NULL);
10703 	}
10704 
10705 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
10706 		dtrace_dof_error(dof, "referenced section is not loadable");
10707 		return (NULL);
10708 	}
10709 
10710 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
10711 		dtrace_dof_error(dof, "referenced section is the wrong type");
10712 		return (NULL);
10713 	}
10714 
10715 	return (sec);
10716 }
10717 
10718 static dtrace_probedesc_t *
10719 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
10720 {
10721 	dof_probedesc_t *probe;
10722 	dof_sec_t *strtab;
10723 	uintptr_t daddr = (uintptr_t)dof;
10724 	uintptr_t str;
10725 	size_t size;
10726 
10727 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
10728 		dtrace_dof_error(dof, "invalid probe section");
10729 		return (NULL);
10730 	}
10731 
10732 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
10733 		dtrace_dof_error(dof, "bad alignment in probe description");
10734 		return (NULL);
10735 	}
10736 
10737 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
10738 		dtrace_dof_error(dof, "truncated probe description");
10739 		return (NULL);
10740 	}
10741 
10742 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
10743 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
10744 
10745 	if (strtab == NULL)
10746 		return (NULL);
10747 
10748 	str = daddr + strtab->dofs_offset;
10749 	size = strtab->dofs_size;
10750 
10751 	if (probe->dofp_provider >= strtab->dofs_size) {
10752 		dtrace_dof_error(dof, "corrupt probe provider");
10753 		return (NULL);
10754 	}
10755 
10756 	(void) strncpy(desc->dtpd_provider,
10757 	    (char *)(str + probe->dofp_provider),
10758 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
10759 
10760 	if (probe->dofp_mod >= strtab->dofs_size) {
10761 		dtrace_dof_error(dof, "corrupt probe module");
10762 		return (NULL);
10763 	}
10764 
10765 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
10766 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
10767 
10768 	if (probe->dofp_func >= strtab->dofs_size) {
10769 		dtrace_dof_error(dof, "corrupt probe function");
10770 		return (NULL);
10771 	}
10772 
10773 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
10774 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
10775 
10776 	if (probe->dofp_name >= strtab->dofs_size) {
10777 		dtrace_dof_error(dof, "corrupt probe name");
10778 		return (NULL);
10779 	}
10780 
10781 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
10782 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
10783 
10784 	return (desc);
10785 }
10786 
10787 static dtrace_difo_t *
10788 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10789     cred_t *cr)
10790 {
10791 	dtrace_difo_t *dp;
10792 	size_t ttl = 0;
10793 	dof_difohdr_t *dofd;
10794 	uintptr_t daddr = (uintptr_t)dof;
10795 	size_t max = dtrace_difo_maxsize;
10796 	int i, l, n;
10797 
10798 	static const struct {
10799 		int section;
10800 		int bufoffs;
10801 		int lenoffs;
10802 		int entsize;
10803 		int align;
10804 		const char *msg;
10805 	} difo[] = {
10806 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
10807 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
10808 		sizeof (dif_instr_t), "multiple DIF sections" },
10809 
10810 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
10811 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
10812 		sizeof (uint64_t), "multiple integer tables" },
10813 
10814 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
10815 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
10816 		sizeof (char), "multiple string tables" },
10817 
10818 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
10819 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
10820 		sizeof (uint_t), "multiple variable tables" },
10821 
10822 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
10823 	};
10824 
10825 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
10826 		dtrace_dof_error(dof, "invalid DIFO header section");
10827 		return (NULL);
10828 	}
10829 
10830 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
10831 		dtrace_dof_error(dof, "bad alignment in DIFO header");
10832 		return (NULL);
10833 	}
10834 
10835 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
10836 	    sec->dofs_size % sizeof (dof_secidx_t)) {
10837 		dtrace_dof_error(dof, "bad size in DIFO header");
10838 		return (NULL);
10839 	}
10840 
10841 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
10842 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
10843 
10844 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10845 	dp->dtdo_rtype = dofd->dofd_rtype;
10846 
10847 	for (l = 0; l < n; l++) {
10848 		dof_sec_t *subsec;
10849 		void **bufp;
10850 		uint32_t *lenp;
10851 
10852 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
10853 		    dofd->dofd_links[l])) == NULL)
10854 			goto err; /* invalid section link */
10855 
10856 		if (ttl + subsec->dofs_size > max) {
10857 			dtrace_dof_error(dof, "exceeds maximum size");
10858 			goto err;
10859 		}
10860 
10861 		ttl += subsec->dofs_size;
10862 
10863 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
10864 			if (subsec->dofs_type != difo[i].section)
10865 				continue;
10866 
10867 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
10868 				dtrace_dof_error(dof, "section not loaded");
10869 				goto err;
10870 			}
10871 
10872 			if (subsec->dofs_align != difo[i].align) {
10873 				dtrace_dof_error(dof, "bad alignment");
10874 				goto err;
10875 			}
10876 
10877 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
10878 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
10879 
10880 			if (*bufp != NULL) {
10881 				dtrace_dof_error(dof, difo[i].msg);
10882 				goto err;
10883 			}
10884 
10885 			if (difo[i].entsize != subsec->dofs_entsize) {
10886 				dtrace_dof_error(dof, "entry size mismatch");
10887 				goto err;
10888 			}
10889 
10890 			if (subsec->dofs_entsize != 0 &&
10891 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
10892 				dtrace_dof_error(dof, "corrupt entry size");
10893 				goto err;
10894 			}
10895 
10896 			*lenp = subsec->dofs_size;
10897 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
10898 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
10899 			    *bufp, subsec->dofs_size);
10900 
10901 			if (subsec->dofs_entsize != 0)
10902 				*lenp /= subsec->dofs_entsize;
10903 
10904 			break;
10905 		}
10906 
10907 		/*
10908 		 * If we encounter a loadable DIFO sub-section that is not
10909 		 * known to us, assume this is a broken program and fail.
10910 		 */
10911 		if (difo[i].section == DOF_SECT_NONE &&
10912 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
10913 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
10914 			goto err;
10915 		}
10916 	}
10917 
10918 	if (dp->dtdo_buf == NULL) {
10919 		/*
10920 		 * We can't have a DIF object without DIF text.
10921 		 */
10922 		dtrace_dof_error(dof, "missing DIF text");
10923 		goto err;
10924 	}
10925 
10926 	/*
10927 	 * Before we validate the DIF object, run through the variable table
10928 	 * looking for the strings -- if any of their size are under, we'll set
10929 	 * their size to be the system-wide default string size.  Note that
10930 	 * this should _not_ happen if the "strsize" option has been set --
10931 	 * in this case, the compiler should have set the size to reflect the
10932 	 * setting of the option.
10933 	 */
10934 	for (i = 0; i < dp->dtdo_varlen; i++) {
10935 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10936 		dtrace_diftype_t *t = &v->dtdv_type;
10937 
10938 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
10939 			continue;
10940 
10941 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
10942 			t->dtdt_size = dtrace_strsize_default;
10943 	}
10944 
10945 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
10946 		goto err;
10947 
10948 	dtrace_difo_init(dp, vstate);
10949 	return (dp);
10950 
10951 err:
10952 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10953 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10954 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10955 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10956 
10957 	kmem_free(dp, sizeof (dtrace_difo_t));
10958 	return (NULL);
10959 }
10960 
10961 static dtrace_predicate_t *
10962 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10963     cred_t *cr)
10964 {
10965 	dtrace_difo_t *dp;
10966 
10967 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
10968 		return (NULL);
10969 
10970 	return (dtrace_predicate_create(dp));
10971 }
10972 
10973 static dtrace_actdesc_t *
10974 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10975     cred_t *cr)
10976 {
10977 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
10978 	dof_actdesc_t *desc;
10979 	dof_sec_t *difosec;
10980 	size_t offs;
10981 	uintptr_t daddr = (uintptr_t)dof;
10982 	uint64_t arg;
10983 	dtrace_actkind_t kind;
10984 
10985 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
10986 		dtrace_dof_error(dof, "invalid action section");
10987 		return (NULL);
10988 	}
10989 
10990 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
10991 		dtrace_dof_error(dof, "truncated action description");
10992 		return (NULL);
10993 	}
10994 
10995 	if (sec->dofs_align != sizeof (uint64_t)) {
10996 		dtrace_dof_error(dof, "bad alignment in action description");
10997 		return (NULL);
10998 	}
10999 
11000 	if (sec->dofs_size < sec->dofs_entsize) {
11001 		dtrace_dof_error(dof, "section entry size exceeds total size");
11002 		return (NULL);
11003 	}
11004 
11005 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
11006 		dtrace_dof_error(dof, "bad entry size in action description");
11007 		return (NULL);
11008 	}
11009 
11010 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
11011 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
11012 		return (NULL);
11013 	}
11014 
11015 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
11016 		desc = (dof_actdesc_t *)(daddr +
11017 		    (uintptr_t)sec->dofs_offset + offs);
11018 		kind = (dtrace_actkind_t)desc->dofa_kind;
11019 
11020 		if (DTRACEACT_ISPRINTFLIKE(kind) &&
11021 		    (kind != DTRACEACT_PRINTA ||
11022 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
11023 			dof_sec_t *strtab;
11024 			char *str, *fmt;
11025 			uint64_t i;
11026 
11027 			/*
11028 			 * printf()-like actions must have a format string.
11029 			 */
11030 			if ((strtab = dtrace_dof_sect(dof,
11031 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
11032 				goto err;
11033 
11034 			str = (char *)((uintptr_t)dof +
11035 			    (uintptr_t)strtab->dofs_offset);
11036 
11037 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
11038 				if (str[i] == '\0')
11039 					break;
11040 			}
11041 
11042 			if (i >= strtab->dofs_size) {
11043 				dtrace_dof_error(dof, "bogus format string");
11044 				goto err;
11045 			}
11046 
11047 			if (i == desc->dofa_arg) {
11048 				dtrace_dof_error(dof, "empty format string");
11049 				goto err;
11050 			}
11051 
11052 			i -= desc->dofa_arg;
11053 			fmt = kmem_alloc(i + 1, KM_SLEEP);
11054 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
11055 			arg = (uint64_t)(uintptr_t)fmt;
11056 		} else {
11057 			if (kind == DTRACEACT_PRINTA) {
11058 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
11059 				arg = 0;
11060 			} else {
11061 				arg = desc->dofa_arg;
11062 			}
11063 		}
11064 
11065 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
11066 		    desc->dofa_uarg, arg);
11067 
11068 		if (last != NULL) {
11069 			last->dtad_next = act;
11070 		} else {
11071 			first = act;
11072 		}
11073 
11074 		last = act;
11075 
11076 		if (desc->dofa_difo == DOF_SECIDX_NONE)
11077 			continue;
11078 
11079 		if ((difosec = dtrace_dof_sect(dof,
11080 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
11081 			goto err;
11082 
11083 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
11084 
11085 		if (act->dtad_difo == NULL)
11086 			goto err;
11087 	}
11088 
11089 	ASSERT(first != NULL);
11090 	return (first);
11091 
11092 err:
11093 	for (act = first; act != NULL; act = next) {
11094 		next = act->dtad_next;
11095 		dtrace_actdesc_release(act, vstate);
11096 	}
11097 
11098 	return (NULL);
11099 }
11100 
11101 static dtrace_ecbdesc_t *
11102 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11103     cred_t *cr)
11104 {
11105 	dtrace_ecbdesc_t *ep;
11106 	dof_ecbdesc_t *ecb;
11107 	dtrace_probedesc_t *desc;
11108 	dtrace_predicate_t *pred = NULL;
11109 
11110 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
11111 		dtrace_dof_error(dof, "truncated ECB description");
11112 		return (NULL);
11113 	}
11114 
11115 	if (sec->dofs_align != sizeof (uint64_t)) {
11116 		dtrace_dof_error(dof, "bad alignment in ECB description");
11117 		return (NULL);
11118 	}
11119 
11120 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
11121 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
11122 
11123 	if (sec == NULL)
11124 		return (NULL);
11125 
11126 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11127 	ep->dted_uarg = ecb->dofe_uarg;
11128 	desc = &ep->dted_probe;
11129 
11130 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
11131 		goto err;
11132 
11133 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
11134 		if ((sec = dtrace_dof_sect(dof,
11135 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
11136 			goto err;
11137 
11138 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
11139 			goto err;
11140 
11141 		ep->dted_pred.dtpdd_predicate = pred;
11142 	}
11143 
11144 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
11145 		if ((sec = dtrace_dof_sect(dof,
11146 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
11147 			goto err;
11148 
11149 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
11150 
11151 		if (ep->dted_action == NULL)
11152 			goto err;
11153 	}
11154 
11155 	return (ep);
11156 
11157 err:
11158 	if (pred != NULL)
11159 		dtrace_predicate_release(pred, vstate);
11160 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11161 	return (NULL);
11162 }
11163 
11164 /*
11165  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
11166  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
11167  * site of any user SETX relocations to account for load object base address.
11168  * In the future, if we need other relocations, this function can be extended.
11169  */
11170 static int
11171 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
11172 {
11173 	uintptr_t daddr = (uintptr_t)dof;
11174 	dof_relohdr_t *dofr =
11175 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11176 	dof_sec_t *ss, *rs, *ts;
11177 	dof_relodesc_t *r;
11178 	uint_t i, n;
11179 
11180 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
11181 	    sec->dofs_align != sizeof (dof_secidx_t)) {
11182 		dtrace_dof_error(dof, "invalid relocation header");
11183 		return (-1);
11184 	}
11185 
11186 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
11187 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
11188 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
11189 
11190 	if (ss == NULL || rs == NULL || ts == NULL)
11191 		return (-1); /* dtrace_dof_error() has been called already */
11192 
11193 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
11194 	    rs->dofs_align != sizeof (uint64_t)) {
11195 		dtrace_dof_error(dof, "invalid relocation section");
11196 		return (-1);
11197 	}
11198 
11199 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
11200 	n = rs->dofs_size / rs->dofs_entsize;
11201 
11202 	for (i = 0; i < n; i++) {
11203 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
11204 
11205 		switch (r->dofr_type) {
11206 		case DOF_RELO_NONE:
11207 			break;
11208 		case DOF_RELO_SETX:
11209 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
11210 			    sizeof (uint64_t) > ts->dofs_size) {
11211 				dtrace_dof_error(dof, "bad relocation offset");
11212 				return (-1);
11213 			}
11214 
11215 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
11216 				dtrace_dof_error(dof, "misaligned setx relo");
11217 				return (-1);
11218 			}
11219 
11220 			*(uint64_t *)taddr += ubase;
11221 			break;
11222 		default:
11223 			dtrace_dof_error(dof, "invalid relocation type");
11224 			return (-1);
11225 		}
11226 
11227 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
11228 	}
11229 
11230 	return (0);
11231 }
11232 
11233 /*
11234  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
11235  * header:  it should be at the front of a memory region that is at least
11236  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
11237  * size.  It need not be validated in any other way.
11238  */
11239 static int
11240 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
11241     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
11242 {
11243 	uint64_t len = dof->dofh_loadsz, seclen;
11244 	uintptr_t daddr = (uintptr_t)dof;
11245 	dtrace_ecbdesc_t *ep;
11246 	dtrace_enabling_t *enab;
11247 	uint_t i;
11248 
11249 	ASSERT(MUTEX_HELD(&dtrace_lock));
11250 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
11251 
11252 	/*
11253 	 * Check the DOF header identification bytes.  In addition to checking
11254 	 * valid settings, we also verify that unused bits/bytes are zeroed so
11255 	 * we can use them later without fear of regressing existing binaries.
11256 	 */
11257 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
11258 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
11259 		dtrace_dof_error(dof, "DOF magic string mismatch");
11260 		return (-1);
11261 	}
11262 
11263 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
11264 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
11265 		dtrace_dof_error(dof, "DOF has invalid data model");
11266 		return (-1);
11267 	}
11268 
11269 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
11270 		dtrace_dof_error(dof, "DOF encoding mismatch");
11271 		return (-1);
11272 	}
11273 
11274 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
11275 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
11276 		dtrace_dof_error(dof, "DOF version mismatch");
11277 		return (-1);
11278 	}
11279 
11280 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
11281 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
11282 		return (-1);
11283 	}
11284 
11285 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
11286 		dtrace_dof_error(dof, "DOF uses too many integer registers");
11287 		return (-1);
11288 	}
11289 
11290 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
11291 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
11292 		return (-1);
11293 	}
11294 
11295 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
11296 		if (dof->dofh_ident[i] != 0) {
11297 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
11298 			return (-1);
11299 		}
11300 	}
11301 
11302 	if (dof->dofh_flags & ~DOF_FL_VALID) {
11303 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
11304 		return (-1);
11305 	}
11306 
11307 	if (dof->dofh_secsize == 0) {
11308 		dtrace_dof_error(dof, "zero section header size");
11309 		return (-1);
11310 	}
11311 
11312 	/*
11313 	 * Check that the section headers don't exceed the amount of DOF
11314 	 * data.  Note that we cast the section size and number of sections
11315 	 * to uint64_t's to prevent possible overflow in the multiplication.
11316 	 */
11317 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
11318 
11319 	if (dof->dofh_secoff > len || seclen > len ||
11320 	    dof->dofh_secoff + seclen > len) {
11321 		dtrace_dof_error(dof, "truncated section headers");
11322 		return (-1);
11323 	}
11324 
11325 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
11326 		dtrace_dof_error(dof, "misaligned section headers");
11327 		return (-1);
11328 	}
11329 
11330 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
11331 		dtrace_dof_error(dof, "misaligned section size");
11332 		return (-1);
11333 	}
11334 
11335 	/*
11336 	 * Take an initial pass through the section headers to be sure that
11337 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
11338 	 * set, do not permit sections relating to providers, probes, or args.
11339 	 */
11340 	for (i = 0; i < dof->dofh_secnum; i++) {
11341 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11342 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11343 
11344 		if (noprobes) {
11345 			switch (sec->dofs_type) {
11346 			case DOF_SECT_PROVIDER:
11347 			case DOF_SECT_PROBES:
11348 			case DOF_SECT_PRARGS:
11349 			case DOF_SECT_PROFFS:
11350 				dtrace_dof_error(dof, "illegal sections "
11351 				    "for enabling");
11352 				return (-1);
11353 			}
11354 		}
11355 
11356 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
11357 			continue; /* just ignore non-loadable sections */
11358 
11359 		if (sec->dofs_align & (sec->dofs_align - 1)) {
11360 			dtrace_dof_error(dof, "bad section alignment");
11361 			return (-1);
11362 		}
11363 
11364 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
11365 			dtrace_dof_error(dof, "misaligned section");
11366 			return (-1);
11367 		}
11368 
11369 		if (sec->dofs_offset > len || sec->dofs_size > len ||
11370 		    sec->dofs_offset + sec->dofs_size > len) {
11371 			dtrace_dof_error(dof, "corrupt section header");
11372 			return (-1);
11373 		}
11374 
11375 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
11376 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
11377 			dtrace_dof_error(dof, "non-terminating string table");
11378 			return (-1);
11379 		}
11380 	}
11381 
11382 	/*
11383 	 * Take a second pass through the sections and locate and perform any
11384 	 * relocations that are present.  We do this after the first pass to
11385 	 * be sure that all sections have had their headers validated.
11386 	 */
11387 	for (i = 0; i < dof->dofh_secnum; i++) {
11388 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11389 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11390 
11391 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
11392 			continue; /* skip sections that are not loadable */
11393 
11394 		switch (sec->dofs_type) {
11395 		case DOF_SECT_URELHDR:
11396 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
11397 				return (-1);
11398 			break;
11399 		}
11400 	}
11401 
11402 	if ((enab = *enabp) == NULL)
11403 		enab = *enabp = dtrace_enabling_create(vstate);
11404 
11405 	for (i = 0; i < dof->dofh_secnum; i++) {
11406 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11407 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11408 
11409 		if (sec->dofs_type != DOF_SECT_ECBDESC)
11410 			continue;
11411 
11412 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
11413 			dtrace_enabling_destroy(enab);
11414 			*enabp = NULL;
11415 			return (-1);
11416 		}
11417 
11418 		dtrace_enabling_add(enab, ep);
11419 	}
11420 
11421 	return (0);
11422 }
11423 
11424 /*
11425  * Process DOF for any options.  This routine assumes that the DOF has been
11426  * at least processed by dtrace_dof_slurp().
11427  */
11428 static int
11429 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
11430 {
11431 	int i, rval;
11432 	uint32_t entsize;
11433 	size_t offs;
11434 	dof_optdesc_t *desc;
11435 
11436 	for (i = 0; i < dof->dofh_secnum; i++) {
11437 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
11438 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11439 
11440 		if (sec->dofs_type != DOF_SECT_OPTDESC)
11441 			continue;
11442 
11443 		if (sec->dofs_align != sizeof (uint64_t)) {
11444 			dtrace_dof_error(dof, "bad alignment in "
11445 			    "option description");
11446 			return (EINVAL);
11447 		}
11448 
11449 		if ((entsize = sec->dofs_entsize) == 0) {
11450 			dtrace_dof_error(dof, "zeroed option entry size");
11451 			return (EINVAL);
11452 		}
11453 
11454 		if (entsize < sizeof (dof_optdesc_t)) {
11455 			dtrace_dof_error(dof, "bad option entry size");
11456 			return (EINVAL);
11457 		}
11458 
11459 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
11460 			desc = (dof_optdesc_t *)((uintptr_t)dof +
11461 			    (uintptr_t)sec->dofs_offset + offs);
11462 
11463 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
11464 				dtrace_dof_error(dof, "non-zero option string");
11465 				return (EINVAL);
11466 			}
11467 
11468 			if (desc->dofo_value == DTRACEOPT_UNSET) {
11469 				dtrace_dof_error(dof, "unset option");
11470 				return (EINVAL);
11471 			}
11472 
11473 			if ((rval = dtrace_state_option(state,
11474 			    desc->dofo_option, desc->dofo_value)) != 0) {
11475 				dtrace_dof_error(dof, "rejected option");
11476 				return (rval);
11477 			}
11478 		}
11479 	}
11480 
11481 	return (0);
11482 }
11483 
11484 /*
11485  * DTrace Consumer State Functions
11486  */
11487 int
11488 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
11489 {
11490 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
11491 	void *base;
11492 	uintptr_t limit;
11493 	dtrace_dynvar_t *dvar, *next, *start;
11494 	int i;
11495 
11496 	ASSERT(MUTEX_HELD(&dtrace_lock));
11497 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
11498 
11499 	bzero(dstate, sizeof (dtrace_dstate_t));
11500 
11501 	if ((dstate->dtds_chunksize = chunksize) == 0)
11502 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
11503 
11504 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
11505 		size = min;
11506 
11507 	if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11508 		return (ENOMEM);
11509 
11510 	dstate->dtds_size = size;
11511 	dstate->dtds_base = base;
11512 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
11513 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
11514 
11515 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
11516 
11517 	if (hashsize != 1 && (hashsize & 1))
11518 		hashsize--;
11519 
11520 	dstate->dtds_hashsize = hashsize;
11521 	dstate->dtds_hash = dstate->dtds_base;
11522 
11523 	/*
11524 	 * Set all of our hash buckets to point to the single sink, and (if
11525 	 * it hasn't already been set), set the sink's hash value to be the
11526 	 * sink sentinel value.  The sink is needed for dynamic variable
11527 	 * lookups to know that they have iterated over an entire, valid hash
11528 	 * chain.
11529 	 */
11530 	for (i = 0; i < hashsize; i++)
11531 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
11532 
11533 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
11534 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
11535 
11536 	/*
11537 	 * Determine number of active CPUs.  Divide free list evenly among
11538 	 * active CPUs.
11539 	 */
11540 	start = (dtrace_dynvar_t *)
11541 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
11542 	limit = (uintptr_t)base + size;
11543 
11544 	maxper = (limit - (uintptr_t)start) / NCPU;
11545 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
11546 
11547 	for (i = 0; i < NCPU; i++) {
11548 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
11549 
11550 		/*
11551 		 * If we don't even have enough chunks to make it once through
11552 		 * NCPUs, we're just going to allocate everything to the first
11553 		 * CPU.  And if we're on the last CPU, we're going to allocate
11554 		 * whatever is left over.  In either case, we set the limit to
11555 		 * be the limit of the dynamic variable space.
11556 		 */
11557 		if (maxper == 0 || i == NCPU - 1) {
11558 			limit = (uintptr_t)base + size;
11559 			start = NULL;
11560 		} else {
11561 			limit = (uintptr_t)start + maxper;
11562 			start = (dtrace_dynvar_t *)limit;
11563 		}
11564 
11565 		ASSERT(limit <= (uintptr_t)base + size);
11566 
11567 		for (;;) {
11568 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
11569 			    dstate->dtds_chunksize);
11570 
11571 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
11572 				break;
11573 
11574 			dvar->dtdv_next = next;
11575 			dvar = next;
11576 		}
11577 
11578 		if (maxper == 0)
11579 			break;
11580 	}
11581 
11582 	return (0);
11583 }
11584 
11585 void
11586 dtrace_dstate_fini(dtrace_dstate_t *dstate)
11587 {
11588 	ASSERT(MUTEX_HELD(&cpu_lock));
11589 
11590 	if (dstate->dtds_base == NULL)
11591 		return;
11592 
11593 	kmem_free(dstate->dtds_base, dstate->dtds_size);
11594 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
11595 }
11596 
11597 static void
11598 dtrace_vstate_fini(dtrace_vstate_t *vstate)
11599 {
11600 	/*
11601 	 * Logical XOR, where are you?
11602 	 */
11603 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
11604 
11605 	if (vstate->dtvs_nglobals > 0) {
11606 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
11607 		    sizeof (dtrace_statvar_t *));
11608 	}
11609 
11610 	if (vstate->dtvs_ntlocals > 0) {
11611 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
11612 		    sizeof (dtrace_difv_t));
11613 	}
11614 
11615 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
11616 
11617 	if (vstate->dtvs_nlocals > 0) {
11618 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
11619 		    sizeof (dtrace_statvar_t *));
11620 	}
11621 }
11622 
11623 static void
11624 dtrace_state_clean(dtrace_state_t *state)
11625 {
11626 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
11627 		return;
11628 
11629 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
11630 	dtrace_speculation_clean(state);
11631 }
11632 
11633 static void
11634 dtrace_state_deadman(dtrace_state_t *state)
11635 {
11636 	hrtime_t now;
11637 
11638 	dtrace_sync();
11639 
11640 	now = dtrace_gethrtime();
11641 
11642 	if (state != dtrace_anon.dta_state &&
11643 	    now - state->dts_laststatus >= dtrace_deadman_user)
11644 		return;
11645 
11646 	/*
11647 	 * We must be sure that dts_alive never appears to be less than the
11648 	 * value upon entry to dtrace_state_deadman(), and because we lack a
11649 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
11650 	 * store INT64_MAX to it, followed by a memory barrier, followed by
11651 	 * the new value.  This assures that dts_alive never appears to be
11652 	 * less than its true value, regardless of the order in which the
11653 	 * stores to the underlying storage are issued.
11654 	 */
11655 	state->dts_alive = INT64_MAX;
11656 	dtrace_membar_producer();
11657 	state->dts_alive = now;
11658 }
11659 
11660 dtrace_state_t *
11661 dtrace_state_create(dev_t *devp, cred_t *cr)
11662 {
11663 	minor_t minor;
11664 	major_t major;
11665 	char c[30];
11666 	dtrace_state_t *state;
11667 	dtrace_optval_t *opt;
11668 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
11669 
11670 	ASSERT(MUTEX_HELD(&dtrace_lock));
11671 	ASSERT(MUTEX_HELD(&cpu_lock));
11672 
11673 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
11674 	    VM_BESTFIT | VM_SLEEP);
11675 
11676 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
11677 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
11678 		return (NULL);
11679 	}
11680 
11681 	state = ddi_get_soft_state(dtrace_softstate, minor);
11682 	state->dts_epid = DTRACE_EPIDNONE + 1;
11683 
11684 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
11685 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
11686 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
11687 
11688 	if (devp != NULL) {
11689 		major = getemajor(*devp);
11690 	} else {
11691 		major = ddi_driver_major(dtrace_devi);
11692 	}
11693 
11694 	state->dts_dev = makedevice(major, minor);
11695 
11696 	if (devp != NULL)
11697 		*devp = state->dts_dev;
11698 
11699 	/*
11700 	 * We allocate NCPU buffers.  On the one hand, this can be quite
11701 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
11702 	 * other hand, it saves an additional memory reference in the probe
11703 	 * path.
11704 	 */
11705 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
11706 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
11707 	state->dts_cleaner = CYCLIC_NONE;
11708 	state->dts_deadman = CYCLIC_NONE;
11709 	state->dts_vstate.dtvs_state = state;
11710 
11711 	for (i = 0; i < DTRACEOPT_MAX; i++)
11712 		state->dts_options[i] = DTRACEOPT_UNSET;
11713 
11714 	/*
11715 	 * Set the default options.
11716 	 */
11717 	opt = state->dts_options;
11718 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
11719 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
11720 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
11721 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
11722 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
11723 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
11724 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
11725 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
11726 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
11727 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
11728 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
11729 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
11730 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
11731 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
11732 
11733 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
11734 
11735 	/*
11736 	 * Depending on the user credentials, we set flag bits which alter probe
11737 	 * visibility or the amount of destructiveness allowed.  In the case of
11738 	 * actual anonymous tracing, or the possession of all privileges, all of
11739 	 * the normal checks are bypassed.
11740 	 */
11741 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
11742 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
11743 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
11744 	} else {
11745 		/*
11746 		 * Set up the credentials for this instantiation.  We take a
11747 		 * hold on the credential to prevent it from disappearing on
11748 		 * us; this in turn prevents the zone_t referenced by this
11749 		 * credential from disappearing.  This means that we can
11750 		 * examine the credential and the zone from probe context.
11751 		 */
11752 		crhold(cr);
11753 		state->dts_cred.dcr_cred = cr;
11754 
11755 		/*
11756 		 * CRA_PROC means "we have *some* privilege for dtrace" and
11757 		 * unlocks the use of variables like pid, zonename, etc.
11758 		 */
11759 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
11760 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
11761 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
11762 		}
11763 
11764 		/*
11765 		 * dtrace_user allows use of syscall and profile providers.
11766 		 * If the user also has proc_owner and/or proc_zone, we
11767 		 * extend the scope to include additional visibility and
11768 		 * destructive power.
11769 		 */
11770 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
11771 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
11772 				state->dts_cred.dcr_visible |=
11773 				    DTRACE_CRV_ALLPROC;
11774 
11775 				state->dts_cred.dcr_action |=
11776 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
11777 			}
11778 
11779 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
11780 				state->dts_cred.dcr_visible |=
11781 				    DTRACE_CRV_ALLZONE;
11782 
11783 				state->dts_cred.dcr_action |=
11784 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
11785 			}
11786 
11787 			/*
11788 			 * If we have all privs in whatever zone this is,
11789 			 * we can do destructive things to processes which
11790 			 * have altered credentials.
11791 			 */
11792 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
11793 			    cr->cr_zone->zone_privset)) {
11794 				state->dts_cred.dcr_action |=
11795 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
11796 			}
11797 		}
11798 
11799 		/*
11800 		 * Holding the dtrace_kernel privilege also implies that
11801 		 * the user has the dtrace_user privilege from a visibility
11802 		 * perspective.  But without further privileges, some
11803 		 * destructive actions are not available.
11804 		 */
11805 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
11806 			/*
11807 			 * Make all probes in all zones visible.  However,
11808 			 * this doesn't mean that all actions become available
11809 			 * to all zones.
11810 			 */
11811 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
11812 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
11813 
11814 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
11815 			    DTRACE_CRA_PROC;
11816 			/*
11817 			 * Holding proc_owner means that destructive actions
11818 			 * for *this* zone are allowed.
11819 			 */
11820 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
11821 				state->dts_cred.dcr_action |=
11822 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
11823 
11824 			/*
11825 			 * Holding proc_zone means that destructive actions
11826 			 * for this user/group ID in all zones is allowed.
11827 			 */
11828 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
11829 				state->dts_cred.dcr_action |=
11830 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
11831 
11832 			/*
11833 			 * If we have all privs in whatever zone this is,
11834 			 * we can do destructive things to processes which
11835 			 * have altered credentials.
11836 			 */
11837 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
11838 			    cr->cr_zone->zone_privset)) {
11839 				state->dts_cred.dcr_action |=
11840 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
11841 			}
11842 		}
11843 
11844 		/*
11845 		 * Holding the dtrace_proc privilege gives control over fasttrap
11846 		 * and pid providers.  We need to grant wider destructive
11847 		 * privileges in the event that the user has proc_owner and/or
11848 		 * proc_zone.
11849 		 */
11850 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
11851 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
11852 				state->dts_cred.dcr_action |=
11853 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
11854 
11855 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
11856 				state->dts_cred.dcr_action |=
11857 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
11858 		}
11859 	}
11860 
11861 	return (state);
11862 }
11863 
11864 static int
11865 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
11866 {
11867 	dtrace_optval_t *opt = state->dts_options, size;
11868 	processorid_t cpu;
11869 	int flags = 0, rval;
11870 
11871 	ASSERT(MUTEX_HELD(&dtrace_lock));
11872 	ASSERT(MUTEX_HELD(&cpu_lock));
11873 	ASSERT(which < DTRACEOPT_MAX);
11874 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
11875 	    (state == dtrace_anon.dta_state &&
11876 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
11877 
11878 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
11879 		return (0);
11880 
11881 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
11882 		cpu = opt[DTRACEOPT_CPU];
11883 
11884 	if (which == DTRACEOPT_SPECSIZE)
11885 		flags |= DTRACEBUF_NOSWITCH;
11886 
11887 	if (which == DTRACEOPT_BUFSIZE) {
11888 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
11889 			flags |= DTRACEBUF_RING;
11890 
11891 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
11892 			flags |= DTRACEBUF_FILL;
11893 
11894 		if (state != dtrace_anon.dta_state ||
11895 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
11896 			flags |= DTRACEBUF_INACTIVE;
11897 	}
11898 
11899 	for (size = opt[which]; size >= sizeof (uint64_t); size >>= 1) {
11900 		/*
11901 		 * The size must be 8-byte aligned.  If the size is not 8-byte
11902 		 * aligned, drop it down by the difference.
11903 		 */
11904 		if (size & (sizeof (uint64_t) - 1))
11905 			size -= size & (sizeof (uint64_t) - 1);
11906 
11907 		if (size < state->dts_reserve) {
11908 			/*
11909 			 * Buffers always must be large enough to accommodate
11910 			 * their prereserved space.  We return E2BIG instead
11911 			 * of ENOMEM in this case to allow for user-level
11912 			 * software to differentiate the cases.
11913 			 */
11914 			return (E2BIG);
11915 		}
11916 
11917 		rval = dtrace_buffer_alloc(buf, size, flags, cpu);
11918 
11919 		if (rval != ENOMEM) {
11920 			opt[which] = size;
11921 			return (rval);
11922 		}
11923 
11924 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
11925 			return (rval);
11926 	}
11927 
11928 	return (ENOMEM);
11929 }
11930 
11931 static int
11932 dtrace_state_buffers(dtrace_state_t *state)
11933 {
11934 	dtrace_speculation_t *spec = state->dts_speculations;
11935 	int rval, i;
11936 
11937 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
11938 	    DTRACEOPT_BUFSIZE)) != 0)
11939 		return (rval);
11940 
11941 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
11942 	    DTRACEOPT_AGGSIZE)) != 0)
11943 		return (rval);
11944 
11945 	for (i = 0; i < state->dts_nspeculations; i++) {
11946 		if ((rval = dtrace_state_buffer(state,
11947 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
11948 			return (rval);
11949 	}
11950 
11951 	return (0);
11952 }
11953 
11954 static void
11955 dtrace_state_prereserve(dtrace_state_t *state)
11956 {
11957 	dtrace_ecb_t *ecb;
11958 	dtrace_probe_t *probe;
11959 
11960 	state->dts_reserve = 0;
11961 
11962 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
11963 		return;
11964 
11965 	/*
11966 	 * If our buffer policy is a "fill" buffer policy, we need to set the
11967 	 * prereserved space to be the space required by the END probes.
11968 	 */
11969 	probe = dtrace_probes[dtrace_probeid_end - 1];
11970 	ASSERT(probe != NULL);
11971 
11972 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
11973 		if (ecb->dte_state != state)
11974 			continue;
11975 
11976 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
11977 	}
11978 }
11979 
11980 static int
11981 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
11982 {
11983 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
11984 	dtrace_speculation_t *spec;
11985 	dtrace_buffer_t *buf;
11986 	cyc_handler_t hdlr;
11987 	cyc_time_t when;
11988 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
11989 	dtrace_icookie_t cookie;
11990 
11991 	mutex_enter(&cpu_lock);
11992 	mutex_enter(&dtrace_lock);
11993 
11994 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
11995 		rval = EBUSY;
11996 		goto out;
11997 	}
11998 
11999 	/*
12000 	 * Before we can perform any checks, we must prime all of the
12001 	 * retained enablings that correspond to this state.
12002 	 */
12003 	dtrace_enabling_prime(state);
12004 
12005 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
12006 		rval = EACCES;
12007 		goto out;
12008 	}
12009 
12010 	dtrace_state_prereserve(state);
12011 
12012 	/*
12013 	 * Now we want to do is try to allocate our speculations.
12014 	 * We do not automatically resize the number of speculations; if
12015 	 * this fails, we will fail the operation.
12016 	 */
12017 	nspec = opt[DTRACEOPT_NSPEC];
12018 	ASSERT(nspec != DTRACEOPT_UNSET);
12019 
12020 	if (nspec > INT_MAX) {
12021 		rval = ENOMEM;
12022 		goto out;
12023 	}
12024 
12025 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
12026 
12027 	if (spec == NULL) {
12028 		rval = ENOMEM;
12029 		goto out;
12030 	}
12031 
12032 	state->dts_speculations = spec;
12033 	state->dts_nspeculations = (int)nspec;
12034 
12035 	for (i = 0; i < nspec; i++) {
12036 		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
12037 			rval = ENOMEM;
12038 			goto err;
12039 		}
12040 
12041 		spec[i].dtsp_buffer = buf;
12042 	}
12043 
12044 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
12045 		if (dtrace_anon.dta_state == NULL) {
12046 			rval = ENOENT;
12047 			goto out;
12048 		}
12049 
12050 		if (state->dts_necbs != 0) {
12051 			rval = EALREADY;
12052 			goto out;
12053 		}
12054 
12055 		state->dts_anon = dtrace_anon_grab();
12056 		ASSERT(state->dts_anon != NULL);
12057 		state = state->dts_anon;
12058 
12059 		/*
12060 		 * We want "grabanon" to be set in the grabbed state, so we'll
12061 		 * copy that option value from the grabbing state into the
12062 		 * grabbed state.
12063 		 */
12064 		state->dts_options[DTRACEOPT_GRABANON] =
12065 		    opt[DTRACEOPT_GRABANON];
12066 
12067 		*cpu = dtrace_anon.dta_beganon;
12068 
12069 		/*
12070 		 * If the anonymous state is active (as it almost certainly
12071 		 * is if the anonymous enabling ultimately matched anything),
12072 		 * we don't allow any further option processing -- but we
12073 		 * don't return failure.
12074 		 */
12075 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12076 			goto out;
12077 	}
12078 
12079 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
12080 	    opt[DTRACEOPT_AGGSIZE] != 0) {
12081 		if (state->dts_aggregations == NULL) {
12082 			/*
12083 			 * We're not going to create an aggregation buffer
12084 			 * because we don't have any ECBs that contain
12085 			 * aggregations -- set this option to 0.
12086 			 */
12087 			opt[DTRACEOPT_AGGSIZE] = 0;
12088 		} else {
12089 			/*
12090 			 * If we have an aggregation buffer, we must also have
12091 			 * a buffer to use as scratch.
12092 			 */
12093 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
12094 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
12095 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
12096 			}
12097 		}
12098 	}
12099 
12100 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
12101 	    opt[DTRACEOPT_SPECSIZE] != 0) {
12102 		if (!state->dts_speculates) {
12103 			/*
12104 			 * We're not going to create speculation buffers
12105 			 * because we don't have any ECBs that actually
12106 			 * speculate -- set the speculation size to 0.
12107 			 */
12108 			opt[DTRACEOPT_SPECSIZE] = 0;
12109 		}
12110 	}
12111 
12112 	/*
12113 	 * The bare minimum size for any buffer that we're actually going to
12114 	 * do anything to is sizeof (uint64_t).
12115 	 */
12116 	sz = sizeof (uint64_t);
12117 
12118 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
12119 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
12120 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
12121 		/*
12122 		 * A buffer size has been explicitly set to 0 (or to a size
12123 		 * that will be adjusted to 0) and we need the space -- we
12124 		 * need to return failure.  We return ENOSPC to differentiate
12125 		 * it from failing to allocate a buffer due to failure to meet
12126 		 * the reserve (for which we return E2BIG).
12127 		 */
12128 		rval = ENOSPC;
12129 		goto out;
12130 	}
12131 
12132 	if ((rval = dtrace_state_buffers(state)) != 0)
12133 		goto err;
12134 
12135 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
12136 		sz = dtrace_dstate_defsize;
12137 
12138 	do {
12139 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
12140 
12141 		if (rval == 0)
12142 			break;
12143 
12144 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12145 			goto err;
12146 	} while (sz >>= 1);
12147 
12148 	opt[DTRACEOPT_DYNVARSIZE] = sz;
12149 
12150 	if (rval != 0)
12151 		goto err;
12152 
12153 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
12154 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
12155 
12156 	if (opt[DTRACEOPT_CLEANRATE] == 0)
12157 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12158 
12159 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
12160 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
12161 
12162 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
12163 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12164 
12165 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
12166 	hdlr.cyh_arg = state;
12167 	hdlr.cyh_level = CY_LOW_LEVEL;
12168 
12169 	when.cyt_when = 0;
12170 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
12171 
12172 	state->dts_cleaner = cyclic_add(&hdlr, &when);
12173 
12174 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
12175 	hdlr.cyh_arg = state;
12176 	hdlr.cyh_level = CY_LOW_LEVEL;
12177 
12178 	when.cyt_when = 0;
12179 	when.cyt_interval = dtrace_deadman_interval;
12180 
12181 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
12182 	state->dts_deadman = cyclic_add(&hdlr, &when);
12183 
12184 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
12185 
12186 	/*
12187 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
12188 	 * interrupts here both to record the CPU on which we fired the BEGIN
12189 	 * probe (the data from this CPU will be processed first at user
12190 	 * level) and to manually activate the buffer for this CPU.
12191 	 */
12192 	cookie = dtrace_interrupt_disable();
12193 	*cpu = CPU->cpu_id;
12194 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
12195 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12196 
12197 	dtrace_probe(dtrace_probeid_begin,
12198 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
12199 	dtrace_interrupt_enable(cookie);
12200 	/*
12201 	 * We may have had an exit action from a BEGIN probe; only change our
12202 	 * state to ACTIVE if we're still in WARMUP.
12203 	 */
12204 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
12205 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
12206 
12207 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
12208 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
12209 
12210 	/*
12211 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
12212 	 * want each CPU to transition its principal buffer out of the
12213 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
12214 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
12215 	 * atomically transition from processing none of a state's ECBs to
12216 	 * processing all of them.
12217 	 */
12218 	dtrace_xcall(DTRACE_CPUALL,
12219 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
12220 	goto out;
12221 
12222 err:
12223 	dtrace_buffer_free(state->dts_buffer);
12224 	dtrace_buffer_free(state->dts_aggbuffer);
12225 
12226 	if ((nspec = state->dts_nspeculations) == 0) {
12227 		ASSERT(state->dts_speculations == NULL);
12228 		goto out;
12229 	}
12230 
12231 	spec = state->dts_speculations;
12232 	ASSERT(spec != NULL);
12233 
12234 	for (i = 0; i < state->dts_nspeculations; i++) {
12235 		if ((buf = spec[i].dtsp_buffer) == NULL)
12236 			break;
12237 
12238 		dtrace_buffer_free(buf);
12239 		kmem_free(buf, bufsize);
12240 	}
12241 
12242 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
12243 	state->dts_nspeculations = 0;
12244 	state->dts_speculations = NULL;
12245 
12246 out:
12247 	mutex_exit(&dtrace_lock);
12248 	mutex_exit(&cpu_lock);
12249 
12250 	return (rval);
12251 }
12252 
12253 static int
12254 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
12255 {
12256 	dtrace_icookie_t cookie;
12257 
12258 	ASSERT(MUTEX_HELD(&dtrace_lock));
12259 
12260 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
12261 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
12262 		return (EINVAL);
12263 
12264 	/*
12265 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
12266 	 * to be sure that every CPU has seen it.  See below for the details
12267 	 * on why this is done.
12268 	 */
12269 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
12270 	dtrace_sync();
12271 
12272 	/*
12273 	 * By this point, it is impossible for any CPU to be still processing
12274 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
12275 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
12276 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
12277 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
12278 	 * iff we're in the END probe.
12279 	 */
12280 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
12281 	dtrace_sync();
12282 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
12283 
12284 	/*
12285 	 * Finally, we can release the reserve and call the END probe.  We
12286 	 * disable interrupts across calling the END probe to allow us to
12287 	 * return the CPU on which we actually called the END probe.  This
12288 	 * allows user-land to be sure that this CPU's principal buffer is
12289 	 * processed last.
12290 	 */
12291 	state->dts_reserve = 0;
12292 
12293 	cookie = dtrace_interrupt_disable();
12294 	*cpu = CPU->cpu_id;
12295 	dtrace_probe(dtrace_probeid_end,
12296 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
12297 	dtrace_interrupt_enable(cookie);
12298 
12299 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
12300 	dtrace_sync();
12301 
12302 	return (0);
12303 }
12304 
12305 static int
12306 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
12307     dtrace_optval_t val)
12308 {
12309 	ASSERT(MUTEX_HELD(&dtrace_lock));
12310 
12311 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12312 		return (EBUSY);
12313 
12314 	if (option >= DTRACEOPT_MAX)
12315 		return (EINVAL);
12316 
12317 	if (option != DTRACEOPT_CPU && val < 0)
12318 		return (EINVAL);
12319 
12320 	switch (option) {
12321 	case DTRACEOPT_DESTRUCTIVE:
12322 		if (dtrace_destructive_disallow)
12323 			return (EACCES);
12324 
12325 		state->dts_cred.dcr_destructive = 1;
12326 		break;
12327 
12328 	case DTRACEOPT_BUFSIZE:
12329 	case DTRACEOPT_DYNVARSIZE:
12330 	case DTRACEOPT_AGGSIZE:
12331 	case DTRACEOPT_SPECSIZE:
12332 	case DTRACEOPT_STRSIZE:
12333 		if (val < 0)
12334 			return (EINVAL);
12335 
12336 		if (val >= LONG_MAX) {
12337 			/*
12338 			 * If this is an otherwise negative value, set it to
12339 			 * the highest multiple of 128m less than LONG_MAX.
12340 			 * Technically, we're adjusting the size without
12341 			 * regard to the buffer resizing policy, but in fact,
12342 			 * this has no effect -- if we set the buffer size to
12343 			 * ~LONG_MAX and the buffer policy is ultimately set to
12344 			 * be "manual", the buffer allocation is guaranteed to
12345 			 * fail, if only because the allocation requires two
12346 			 * buffers.  (We set the the size to the highest
12347 			 * multiple of 128m because it ensures that the size
12348 			 * will remain a multiple of a megabyte when
12349 			 * repeatedly halved -- all the way down to 15m.)
12350 			 */
12351 			val = LONG_MAX - (1 << 27) + 1;
12352 		}
12353 	}
12354 
12355 	state->dts_options[option] = val;
12356 
12357 	return (0);
12358 }
12359 
12360 static void
12361 dtrace_state_destroy(dtrace_state_t *state)
12362 {
12363 	dtrace_ecb_t *ecb;
12364 	dtrace_vstate_t *vstate = &state->dts_vstate;
12365 	minor_t minor = getminor(state->dts_dev);
12366 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12367 	dtrace_speculation_t *spec = state->dts_speculations;
12368 	int nspec = state->dts_nspeculations;
12369 	uint32_t match;
12370 
12371 	ASSERT(MUTEX_HELD(&dtrace_lock));
12372 	ASSERT(MUTEX_HELD(&cpu_lock));
12373 
12374 	/*
12375 	 * First, retract any retained enablings for this state.
12376 	 */
12377 	dtrace_enabling_retract(state);
12378 	ASSERT(state->dts_nretained == 0);
12379 
12380 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
12381 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
12382 		/*
12383 		 * We have managed to come into dtrace_state_destroy() on a
12384 		 * hot enabling -- almost certainly because of a disorderly
12385 		 * shutdown of a consumer.  (That is, a consumer that is
12386 		 * exiting without having called dtrace_stop().) In this case,
12387 		 * we're going to set our activity to be KILLED, and then
12388 		 * issue a sync to be sure that everyone is out of probe
12389 		 * context before we start blowing away ECBs.
12390 		 */
12391 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
12392 		dtrace_sync();
12393 	}
12394 
12395 	/*
12396 	 * Release the credential hold we took in dtrace_state_create().
12397 	 */
12398 	if (state->dts_cred.dcr_cred != NULL)
12399 		crfree(state->dts_cred.dcr_cred);
12400 
12401 	/*
12402 	 * Now we can safely disable and destroy any enabled probes.  Because
12403 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
12404 	 * (especially if they're all enabled), we take two passes through the
12405 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
12406 	 * in the second we disable whatever is left over.
12407 	 */
12408 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
12409 		for (i = 0; i < state->dts_necbs; i++) {
12410 			if ((ecb = state->dts_ecbs[i]) == NULL)
12411 				continue;
12412 
12413 			if (match && ecb->dte_probe != NULL) {
12414 				dtrace_probe_t *probe = ecb->dte_probe;
12415 				dtrace_provider_t *prov = probe->dtpr_provider;
12416 
12417 				if (!(prov->dtpv_priv.dtpp_flags & match))
12418 					continue;
12419 			}
12420 
12421 			dtrace_ecb_disable(ecb);
12422 			dtrace_ecb_destroy(ecb);
12423 		}
12424 
12425 		if (!match)
12426 			break;
12427 	}
12428 
12429 	/*
12430 	 * Before we free the buffers, perform one more sync to assure that
12431 	 * every CPU is out of probe context.
12432 	 */
12433 	dtrace_sync();
12434 
12435 	dtrace_buffer_free(state->dts_buffer);
12436 	dtrace_buffer_free(state->dts_aggbuffer);
12437 
12438 	for (i = 0; i < nspec; i++)
12439 		dtrace_buffer_free(spec[i].dtsp_buffer);
12440 
12441 	if (state->dts_cleaner != CYCLIC_NONE)
12442 		cyclic_remove(state->dts_cleaner);
12443 
12444 	if (state->dts_deadman != CYCLIC_NONE)
12445 		cyclic_remove(state->dts_deadman);
12446 
12447 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
12448 	dtrace_vstate_fini(vstate);
12449 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
12450 
12451 	if (state->dts_aggregations != NULL) {
12452 #ifdef DEBUG
12453 		for (i = 0; i < state->dts_naggregations; i++)
12454 			ASSERT(state->dts_aggregations[i] == NULL);
12455 #endif
12456 		ASSERT(state->dts_naggregations > 0);
12457 		kmem_free(state->dts_aggregations,
12458 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
12459 	}
12460 
12461 	kmem_free(state->dts_buffer, bufsize);
12462 	kmem_free(state->dts_aggbuffer, bufsize);
12463 
12464 	for (i = 0; i < nspec; i++)
12465 		kmem_free(spec[i].dtsp_buffer, bufsize);
12466 
12467 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
12468 
12469 	dtrace_format_destroy(state);
12470 
12471 	vmem_destroy(state->dts_aggid_arena);
12472 	ddi_soft_state_free(dtrace_softstate, minor);
12473 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12474 }
12475 
12476 /*
12477  * DTrace Anonymous Enabling Functions
12478  */
12479 static dtrace_state_t *
12480 dtrace_anon_grab(void)
12481 {
12482 	dtrace_state_t *state;
12483 
12484 	ASSERT(MUTEX_HELD(&dtrace_lock));
12485 
12486 	if ((state = dtrace_anon.dta_state) == NULL) {
12487 		ASSERT(dtrace_anon.dta_enabling == NULL);
12488 		return (NULL);
12489 	}
12490 
12491 	ASSERT(dtrace_anon.dta_enabling != NULL);
12492 	ASSERT(dtrace_retained != NULL);
12493 
12494 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
12495 	dtrace_anon.dta_enabling = NULL;
12496 	dtrace_anon.dta_state = NULL;
12497 
12498 	return (state);
12499 }
12500 
12501 static void
12502 dtrace_anon_property(void)
12503 {
12504 	int i, rv;
12505 	dtrace_state_t *state;
12506 	dof_hdr_t *dof;
12507 	char c[32];		/* enough for "dof-data-" + digits */
12508 
12509 	ASSERT(MUTEX_HELD(&dtrace_lock));
12510 	ASSERT(MUTEX_HELD(&cpu_lock));
12511 
12512 	for (i = 0; ; i++) {
12513 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
12514 
12515 		dtrace_err_verbose = 1;
12516 
12517 		if ((dof = dtrace_dof_property(c)) == NULL) {
12518 			dtrace_err_verbose = 0;
12519 			break;
12520 		}
12521 
12522 		/*
12523 		 * We want to create anonymous state, so we need to transition
12524 		 * the kernel debugger to indicate that DTrace is active.  If
12525 		 * this fails (e.g. because the debugger has modified text in
12526 		 * some way), we won't continue with the processing.
12527 		 */
12528 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
12529 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
12530 			    "enabling ignored.");
12531 			dtrace_dof_destroy(dof);
12532 			break;
12533 		}
12534 
12535 		/*
12536 		 * If we haven't allocated an anonymous state, we'll do so now.
12537 		 */
12538 		if ((state = dtrace_anon.dta_state) == NULL) {
12539 			state = dtrace_state_create(NULL, NULL);
12540 			dtrace_anon.dta_state = state;
12541 
12542 			if (state == NULL) {
12543 				/*
12544 				 * This basically shouldn't happen:  the only
12545 				 * failure mode from dtrace_state_create() is a
12546 				 * failure of ddi_soft_state_zalloc() that
12547 				 * itself should never happen.  Still, the
12548 				 * interface allows for a failure mode, and
12549 				 * we want to fail as gracefully as possible:
12550 				 * we'll emit an error message and cease
12551 				 * processing anonymous state in this case.
12552 				 */
12553 				cmn_err(CE_WARN, "failed to create "
12554 				    "anonymous state");
12555 				dtrace_dof_destroy(dof);
12556 				break;
12557 			}
12558 		}
12559 
12560 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
12561 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
12562 
12563 		if (rv == 0)
12564 			rv = dtrace_dof_options(dof, state);
12565 
12566 		dtrace_err_verbose = 0;
12567 		dtrace_dof_destroy(dof);
12568 
12569 		if (rv != 0) {
12570 			/*
12571 			 * This is malformed DOF; chuck any anonymous state
12572 			 * that we created.
12573 			 */
12574 			ASSERT(dtrace_anon.dta_enabling == NULL);
12575 			dtrace_state_destroy(state);
12576 			dtrace_anon.dta_state = NULL;
12577 			break;
12578 		}
12579 
12580 		ASSERT(dtrace_anon.dta_enabling != NULL);
12581 	}
12582 
12583 	if (dtrace_anon.dta_enabling != NULL) {
12584 		int rval;
12585 
12586 		/*
12587 		 * dtrace_enabling_retain() can only fail because we are
12588 		 * trying to retain more enablings than are allowed -- but
12589 		 * we only have one anonymous enabling, and we are guaranteed
12590 		 * to be allowed at least one retained enabling; we assert
12591 		 * that dtrace_enabling_retain() returns success.
12592 		 */
12593 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
12594 		ASSERT(rval == 0);
12595 
12596 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
12597 	}
12598 }
12599 
12600 /*
12601  * DTrace Helper Functions
12602  */
12603 static void
12604 dtrace_helper_trace(dtrace_helper_action_t *helper,
12605     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
12606 {
12607 	uint32_t size, next, nnext, i;
12608 	dtrace_helptrace_t *ent;
12609 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12610 
12611 	if (!dtrace_helptrace_enabled)
12612 		return;
12613 
12614 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
12615 
12616 	/*
12617 	 * What would a tracing framework be without its own tracing
12618 	 * framework?  (Well, a hell of a lot simpler, for starters...)
12619 	 */
12620 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
12621 	    sizeof (uint64_t) - sizeof (uint64_t);
12622 
12623 	/*
12624 	 * Iterate until we can allocate a slot in the trace buffer.
12625 	 */
12626 	do {
12627 		next = dtrace_helptrace_next;
12628 
12629 		if (next + size < dtrace_helptrace_bufsize) {
12630 			nnext = next + size;
12631 		} else {
12632 			nnext = size;
12633 		}
12634 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
12635 
12636 	/*
12637 	 * We have our slot; fill it in.
12638 	 */
12639 	if (nnext == size)
12640 		next = 0;
12641 
12642 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
12643 	ent->dtht_helper = helper;
12644 	ent->dtht_where = where;
12645 	ent->dtht_nlocals = vstate->dtvs_nlocals;
12646 
12647 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
12648 	    mstate->dtms_fltoffs : -1;
12649 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
12650 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
12651 
12652 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
12653 		dtrace_statvar_t *svar;
12654 
12655 		if ((svar = vstate->dtvs_locals[i]) == NULL)
12656 			continue;
12657 
12658 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
12659 		ent->dtht_locals[i] =
12660 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
12661 	}
12662 }
12663 
12664 static uint64_t
12665 dtrace_helper(int which, dtrace_mstate_t *mstate,
12666     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
12667 {
12668 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12669 	uint64_t sarg0 = mstate->dtms_arg[0];
12670 	uint64_t sarg1 = mstate->dtms_arg[1];
12671 	uint64_t rval;
12672 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
12673 	dtrace_helper_action_t *helper;
12674 	dtrace_vstate_t *vstate;
12675 	dtrace_difo_t *pred;
12676 	int i, trace = dtrace_helptrace_enabled;
12677 
12678 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
12679 
12680 	if (helpers == NULL)
12681 		return (0);
12682 
12683 	if ((helper = helpers->dthps_actions[which]) == NULL)
12684 		return (0);
12685 
12686 	vstate = &helpers->dthps_vstate;
12687 	mstate->dtms_arg[0] = arg0;
12688 	mstate->dtms_arg[1] = arg1;
12689 
12690 	/*
12691 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
12692 	 * we'll call the corresponding actions.  Note that the below calls
12693 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
12694 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
12695 	 * the stored DIF offset with its own (which is the desired behavior).
12696 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
12697 	 * from machine state; this is okay, too.
12698 	 */
12699 	for (; helper != NULL; helper = helper->dtha_next) {
12700 		if ((pred = helper->dtha_predicate) != NULL) {
12701 			if (trace)
12702 				dtrace_helper_trace(helper, mstate, vstate, 0);
12703 
12704 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
12705 				goto next;
12706 
12707 			if (*flags & CPU_DTRACE_FAULT)
12708 				goto err;
12709 		}
12710 
12711 		for (i = 0; i < helper->dtha_nactions; i++) {
12712 			if (trace)
12713 				dtrace_helper_trace(helper,
12714 				    mstate, vstate, i + 1);
12715 
12716 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
12717 			    mstate, vstate, state);
12718 
12719 			if (*flags & CPU_DTRACE_FAULT)
12720 				goto err;
12721 		}
12722 
12723 next:
12724 		if (trace)
12725 			dtrace_helper_trace(helper, mstate, vstate,
12726 			    DTRACE_HELPTRACE_NEXT);
12727 	}
12728 
12729 	if (trace)
12730 		dtrace_helper_trace(helper, mstate, vstate,
12731 		    DTRACE_HELPTRACE_DONE);
12732 
12733 	/*
12734 	 * Restore the arg0 that we saved upon entry.
12735 	 */
12736 	mstate->dtms_arg[0] = sarg0;
12737 	mstate->dtms_arg[1] = sarg1;
12738 
12739 	return (rval);
12740 
12741 err:
12742 	if (trace)
12743 		dtrace_helper_trace(helper, mstate, vstate,
12744 		    DTRACE_HELPTRACE_ERR);
12745 
12746 	/*
12747 	 * Restore the arg0 that we saved upon entry.
12748 	 */
12749 	mstate->dtms_arg[0] = sarg0;
12750 	mstate->dtms_arg[1] = sarg1;
12751 
12752 	return (NULL);
12753 }
12754 
12755 static void
12756 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
12757     dtrace_vstate_t *vstate)
12758 {
12759 	int i;
12760 
12761 	if (helper->dtha_predicate != NULL)
12762 		dtrace_difo_release(helper->dtha_predicate, vstate);
12763 
12764 	for (i = 0; i < helper->dtha_nactions; i++) {
12765 		ASSERT(helper->dtha_actions[i] != NULL);
12766 		dtrace_difo_release(helper->dtha_actions[i], vstate);
12767 	}
12768 
12769 	kmem_free(helper->dtha_actions,
12770 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
12771 	kmem_free(helper, sizeof (dtrace_helper_action_t));
12772 }
12773 
12774 static int
12775 dtrace_helper_destroygen(int gen)
12776 {
12777 	proc_t *p = curproc;
12778 	dtrace_helpers_t *help = p->p_dtrace_helpers;
12779 	dtrace_vstate_t *vstate;
12780 	int i;
12781 
12782 	ASSERT(MUTEX_HELD(&dtrace_lock));
12783 
12784 	if (help == NULL || gen > help->dthps_generation)
12785 		return (EINVAL);
12786 
12787 	vstate = &help->dthps_vstate;
12788 
12789 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
12790 		dtrace_helper_action_t *last = NULL, *h, *next;
12791 
12792 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
12793 			next = h->dtha_next;
12794 
12795 			if (h->dtha_generation == gen) {
12796 				if (last != NULL) {
12797 					last->dtha_next = next;
12798 				} else {
12799 					help->dthps_actions[i] = next;
12800 				}
12801 
12802 				dtrace_helper_action_destroy(h, vstate);
12803 			} else {
12804 				last = h;
12805 			}
12806 		}
12807 	}
12808 
12809 	/*
12810 	 * Interate until we've cleared out all helper providers with the
12811 	 * given generation number.
12812 	 */
12813 	for (;;) {
12814 		dtrace_helper_provider_t *prov;
12815 
12816 		/*
12817 		 * Look for a helper provider with the right generation. We
12818 		 * have to start back at the beginning of the list each time
12819 		 * because we drop dtrace_lock. It's unlikely that we'll make
12820 		 * more than two passes.
12821 		 */
12822 		for (i = 0; i < help->dthps_nprovs; i++) {
12823 			prov = help->dthps_provs[i];
12824 
12825 			if (prov->dthp_generation == gen)
12826 				break;
12827 		}
12828 
12829 		/*
12830 		 * If there were no matches, we're done.
12831 		 */
12832 		if (i == help->dthps_nprovs)
12833 			break;
12834 
12835 		/*
12836 		 * Move the last helper provider into this slot.
12837 		 */
12838 		help->dthps_nprovs--;
12839 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
12840 		help->dthps_provs[help->dthps_nprovs] = NULL;
12841 
12842 		mutex_exit(&dtrace_lock);
12843 
12844 		/*
12845 		 * If we have a meta provider, remove this helper provider.
12846 		 */
12847 		mutex_enter(&dtrace_meta_lock);
12848 		if (dtrace_meta_pid != NULL) {
12849 			ASSERT(dtrace_deferred_pid == NULL);
12850 			dtrace_helper_provider_remove(&prov->dthp_prov,
12851 			    p->p_pid);
12852 		}
12853 		mutex_exit(&dtrace_meta_lock);
12854 
12855 		dtrace_helper_provider_destroy(prov);
12856 
12857 		mutex_enter(&dtrace_lock);
12858 	}
12859 
12860 	return (0);
12861 }
12862 
12863 static int
12864 dtrace_helper_validate(dtrace_helper_action_t *helper)
12865 {
12866 	int err = 0, i;
12867 	dtrace_difo_t *dp;
12868 
12869 	if ((dp = helper->dtha_predicate) != NULL)
12870 		err += dtrace_difo_validate_helper(dp);
12871 
12872 	for (i = 0; i < helper->dtha_nactions; i++)
12873 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
12874 
12875 	return (err == 0);
12876 }
12877 
12878 static int
12879 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
12880 {
12881 	dtrace_helpers_t *help;
12882 	dtrace_helper_action_t *helper, *last;
12883 	dtrace_actdesc_t *act;
12884 	dtrace_vstate_t *vstate;
12885 	dtrace_predicate_t *pred;
12886 	int count = 0, nactions = 0, i;
12887 
12888 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
12889 		return (EINVAL);
12890 
12891 	help = curproc->p_dtrace_helpers;
12892 	last = help->dthps_actions[which];
12893 	vstate = &help->dthps_vstate;
12894 
12895 	for (count = 0; last != NULL; last = last->dtha_next) {
12896 		count++;
12897 		if (last->dtha_next == NULL)
12898 			break;
12899 	}
12900 
12901 	/*
12902 	 * If we already have dtrace_helper_actions_max helper actions for this
12903 	 * helper action type, we'll refuse to add a new one.
12904 	 */
12905 	if (count >= dtrace_helper_actions_max)
12906 		return (ENOSPC);
12907 
12908 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
12909 	helper->dtha_generation = help->dthps_generation;
12910 
12911 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
12912 		ASSERT(pred->dtp_difo != NULL);
12913 		dtrace_difo_hold(pred->dtp_difo);
12914 		helper->dtha_predicate = pred->dtp_difo;
12915 	}
12916 
12917 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
12918 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
12919 			goto err;
12920 
12921 		if (act->dtad_difo == NULL)
12922 			goto err;
12923 
12924 		nactions++;
12925 	}
12926 
12927 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
12928 	    (helper->dtha_nactions = nactions), KM_SLEEP);
12929 
12930 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
12931 		dtrace_difo_hold(act->dtad_difo);
12932 		helper->dtha_actions[i++] = act->dtad_difo;
12933 	}
12934 
12935 	if (!dtrace_helper_validate(helper))
12936 		goto err;
12937 
12938 	if (last == NULL) {
12939 		help->dthps_actions[which] = helper;
12940 	} else {
12941 		last->dtha_next = helper;
12942 	}
12943 
12944 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
12945 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
12946 		dtrace_helptrace_next = 0;
12947 	}
12948 
12949 	return (0);
12950 err:
12951 	dtrace_helper_action_destroy(helper, vstate);
12952 	return (EINVAL);
12953 }
12954 
12955 static void
12956 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
12957     dof_helper_t *dofhp)
12958 {
12959 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
12960 
12961 	mutex_enter(&dtrace_meta_lock);
12962 	mutex_enter(&dtrace_lock);
12963 
12964 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
12965 		/*
12966 		 * If the dtrace module is loaded but not attached, or if
12967 		 * there aren't isn't a meta provider registered to deal with
12968 		 * these provider descriptions, we need to postpone creating
12969 		 * the actual providers until later.
12970 		 */
12971 
12972 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
12973 		    dtrace_deferred_pid != help) {
12974 			help->dthps_deferred = 1;
12975 			help->dthps_pid = p->p_pid;
12976 			help->dthps_next = dtrace_deferred_pid;
12977 			help->dthps_prev = NULL;
12978 			if (dtrace_deferred_pid != NULL)
12979 				dtrace_deferred_pid->dthps_prev = help;
12980 			dtrace_deferred_pid = help;
12981 		}
12982 
12983 		mutex_exit(&dtrace_lock);
12984 
12985 	} else if (dofhp != NULL) {
12986 		/*
12987 		 * If the dtrace module is loaded and we have a particular
12988 		 * helper provider description, pass that off to the
12989 		 * meta provider.
12990 		 */
12991 
12992 		mutex_exit(&dtrace_lock);
12993 
12994 		dtrace_helper_provide(dofhp, p->p_pid);
12995 
12996 	} else {
12997 		/*
12998 		 * Otherwise, just pass all the helper provider descriptions
12999 		 * off to the meta provider.
13000 		 */
13001 
13002 		int i;
13003 		mutex_exit(&dtrace_lock);
13004 
13005 		for (i = 0; i < help->dthps_nprovs; i++) {
13006 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
13007 			    p->p_pid);
13008 		}
13009 	}
13010 
13011 	mutex_exit(&dtrace_meta_lock);
13012 }
13013 
13014 static int
13015 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
13016 {
13017 	dtrace_helpers_t *help;
13018 	dtrace_helper_provider_t *hprov, **tmp_provs;
13019 	uint_t tmp_maxprovs, i;
13020 
13021 	ASSERT(MUTEX_HELD(&dtrace_lock));
13022 
13023 	help = curproc->p_dtrace_helpers;
13024 	ASSERT(help != NULL);
13025 
13026 	/*
13027 	 * If we already have dtrace_helper_providers_max helper providers,
13028 	 * we're refuse to add a new one.
13029 	 */
13030 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
13031 		return (ENOSPC);
13032 
13033 	/*
13034 	 * Check to make sure this isn't a duplicate.
13035 	 */
13036 	for (i = 0; i < help->dthps_nprovs; i++) {
13037 		if (dofhp->dofhp_addr ==
13038 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
13039 			return (EALREADY);
13040 	}
13041 
13042 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
13043 	hprov->dthp_prov = *dofhp;
13044 	hprov->dthp_ref = 1;
13045 	hprov->dthp_generation = gen;
13046 
13047 	/*
13048 	 * Allocate a bigger table for helper providers if it's already full.
13049 	 */
13050 	if (help->dthps_maxprovs == help->dthps_nprovs) {
13051 		tmp_maxprovs = help->dthps_maxprovs;
13052 		tmp_provs = help->dthps_provs;
13053 
13054 		if (help->dthps_maxprovs == 0)
13055 			help->dthps_maxprovs = 2;
13056 		else
13057 			help->dthps_maxprovs *= 2;
13058 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
13059 			help->dthps_maxprovs = dtrace_helper_providers_max;
13060 
13061 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
13062 
13063 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
13064 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13065 
13066 		if (tmp_provs != NULL) {
13067 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
13068 			    sizeof (dtrace_helper_provider_t *));
13069 			kmem_free(tmp_provs, tmp_maxprovs *
13070 			    sizeof (dtrace_helper_provider_t *));
13071 		}
13072 	}
13073 
13074 	help->dthps_provs[help->dthps_nprovs] = hprov;
13075 	help->dthps_nprovs++;
13076 
13077 	return (0);
13078 }
13079 
13080 static void
13081 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
13082 {
13083 	mutex_enter(&dtrace_lock);
13084 
13085 	if (--hprov->dthp_ref == 0) {
13086 		dof_hdr_t *dof;
13087 		mutex_exit(&dtrace_lock);
13088 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
13089 		dtrace_dof_destroy(dof);
13090 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
13091 	} else {
13092 		mutex_exit(&dtrace_lock);
13093 	}
13094 }
13095 
13096 static int
13097 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
13098 {
13099 	uintptr_t daddr = (uintptr_t)dof;
13100 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
13101 	dof_provider_t *provider;
13102 	dof_probe_t *probe;
13103 	uint8_t *arg;
13104 	char *strtab, *typestr;
13105 	dof_stridx_t typeidx;
13106 	size_t typesz;
13107 	uint_t nprobes, j, k;
13108 
13109 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
13110 
13111 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
13112 		dtrace_dof_error(dof, "misaligned section offset");
13113 		return (-1);
13114 	}
13115 
13116 	/*
13117 	 * The section needs to be large enough to contain the DOF provider
13118 	 * structure appropriate for the given version.
13119 	 */
13120 	if (sec->dofs_size <
13121 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
13122 	    offsetof(dof_provider_t, dofpv_prenoffs) :
13123 	    sizeof (dof_provider_t))) {
13124 		dtrace_dof_error(dof, "provider section too small");
13125 		return (-1);
13126 	}
13127 
13128 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
13129 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
13130 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
13131 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
13132 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
13133 
13134 	if (str_sec == NULL || prb_sec == NULL ||
13135 	    arg_sec == NULL || off_sec == NULL)
13136 		return (-1);
13137 
13138 	enoff_sec = NULL;
13139 
13140 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13141 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
13142 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
13143 	    provider->dofpv_prenoffs)) == NULL)
13144 		return (-1);
13145 
13146 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
13147 
13148 	if (provider->dofpv_name >= str_sec->dofs_size ||
13149 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
13150 		dtrace_dof_error(dof, "invalid provider name");
13151 		return (-1);
13152 	}
13153 
13154 	if (prb_sec->dofs_entsize == 0 ||
13155 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
13156 		dtrace_dof_error(dof, "invalid entry size");
13157 		return (-1);
13158 	}
13159 
13160 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
13161 		dtrace_dof_error(dof, "misaligned entry size");
13162 		return (-1);
13163 	}
13164 
13165 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
13166 		dtrace_dof_error(dof, "invalid entry size");
13167 		return (-1);
13168 	}
13169 
13170 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
13171 		dtrace_dof_error(dof, "misaligned section offset");
13172 		return (-1);
13173 	}
13174 
13175 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
13176 		dtrace_dof_error(dof, "invalid entry size");
13177 		return (-1);
13178 	}
13179 
13180 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
13181 
13182 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
13183 
13184 	/*
13185 	 * Take a pass through the probes to check for errors.
13186 	 */
13187 	for (j = 0; j < nprobes; j++) {
13188 		probe = (dof_probe_t *)(uintptr_t)(daddr +
13189 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
13190 
13191 		if (probe->dofpr_func >= str_sec->dofs_size) {
13192 			dtrace_dof_error(dof, "invalid function name");
13193 			return (-1);
13194 		}
13195 
13196 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
13197 			dtrace_dof_error(dof, "function name too long");
13198 			return (-1);
13199 		}
13200 
13201 		if (probe->dofpr_name >= str_sec->dofs_size ||
13202 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
13203 			dtrace_dof_error(dof, "invalid probe name");
13204 			return (-1);
13205 		}
13206 
13207 		/*
13208 		 * The offset count must not wrap the index, and the offsets
13209 		 * must also not overflow the section's data.
13210 		 */
13211 		if (probe->dofpr_offidx + probe->dofpr_noffs <
13212 		    probe->dofpr_offidx ||
13213 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
13214 		    off_sec->dofs_entsize > off_sec->dofs_size) {
13215 			dtrace_dof_error(dof, "invalid probe offset");
13216 			return (-1);
13217 		}
13218 
13219 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
13220 			/*
13221 			 * If there's no is-enabled offset section, make sure
13222 			 * there aren't any is-enabled offsets. Otherwise
13223 			 * perform the same checks as for probe offsets
13224 			 * (immediately above).
13225 			 */
13226 			if (enoff_sec == NULL) {
13227 				if (probe->dofpr_enoffidx != 0 ||
13228 				    probe->dofpr_nenoffs != 0) {
13229 					dtrace_dof_error(dof, "is-enabled "
13230 					    "offsets with null section");
13231 					return (-1);
13232 				}
13233 			} else if (probe->dofpr_enoffidx +
13234 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
13235 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
13236 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
13237 				dtrace_dof_error(dof, "invalid is-enabled "
13238 				    "offset");
13239 				return (-1);
13240 			}
13241 
13242 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
13243 				dtrace_dof_error(dof, "zero probe and "
13244 				    "is-enabled offsets");
13245 				return (-1);
13246 			}
13247 		} else if (probe->dofpr_noffs == 0) {
13248 			dtrace_dof_error(dof, "zero probe offsets");
13249 			return (-1);
13250 		}
13251 
13252 		if (probe->dofpr_argidx + probe->dofpr_xargc <
13253 		    probe->dofpr_argidx ||
13254 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
13255 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
13256 			dtrace_dof_error(dof, "invalid args");
13257 			return (-1);
13258 		}
13259 
13260 		typeidx = probe->dofpr_nargv;
13261 		typestr = strtab + probe->dofpr_nargv;
13262 		for (k = 0; k < probe->dofpr_nargc; k++) {
13263 			if (typeidx >= str_sec->dofs_size) {
13264 				dtrace_dof_error(dof, "bad "
13265 				    "native argument type");
13266 				return (-1);
13267 			}
13268 
13269 			typesz = strlen(typestr) + 1;
13270 			if (typesz > DTRACE_ARGTYPELEN) {
13271 				dtrace_dof_error(dof, "native "
13272 				    "argument type too long");
13273 				return (-1);
13274 			}
13275 			typeidx += typesz;
13276 			typestr += typesz;
13277 		}
13278 
13279 		typeidx = probe->dofpr_xargv;
13280 		typestr = strtab + probe->dofpr_xargv;
13281 		for (k = 0; k < probe->dofpr_xargc; k++) {
13282 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
13283 				dtrace_dof_error(dof, "bad "
13284 				    "native argument index");
13285 				return (-1);
13286 			}
13287 
13288 			if (typeidx >= str_sec->dofs_size) {
13289 				dtrace_dof_error(dof, "bad "
13290 				    "translated argument type");
13291 				return (-1);
13292 			}
13293 
13294 			typesz = strlen(typestr) + 1;
13295 			if (typesz > DTRACE_ARGTYPELEN) {
13296 				dtrace_dof_error(dof, "translated argument "
13297 				    "type too long");
13298 				return (-1);
13299 			}
13300 
13301 			typeidx += typesz;
13302 			typestr += typesz;
13303 		}
13304 	}
13305 
13306 	return (0);
13307 }
13308 
13309 static int
13310 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
13311 {
13312 	dtrace_helpers_t *help;
13313 	dtrace_vstate_t *vstate;
13314 	dtrace_enabling_t *enab = NULL;
13315 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
13316 	uintptr_t daddr = (uintptr_t)dof;
13317 
13318 	ASSERT(MUTEX_HELD(&dtrace_lock));
13319 
13320 	if ((help = curproc->p_dtrace_helpers) == NULL)
13321 		help = dtrace_helpers_create(curproc);
13322 
13323 	vstate = &help->dthps_vstate;
13324 
13325 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
13326 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
13327 		dtrace_dof_destroy(dof);
13328 		return (rv);
13329 	}
13330 
13331 	/*
13332 	 * Look for helper providers and validate their descriptions.
13333 	 */
13334 	if (dhp != NULL) {
13335 		for (i = 0; i < dof->dofh_secnum; i++) {
13336 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
13337 			    dof->dofh_secoff + i * dof->dofh_secsize);
13338 
13339 			if (sec->dofs_type != DOF_SECT_PROVIDER)
13340 				continue;
13341 
13342 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
13343 				dtrace_enabling_destroy(enab);
13344 				dtrace_dof_destroy(dof);
13345 				return (-1);
13346 			}
13347 
13348 			nprovs++;
13349 		}
13350 	}
13351 
13352 	/*
13353 	 * Now we need to walk through the ECB descriptions in the enabling.
13354 	 */
13355 	for (i = 0; i < enab->dten_ndesc; i++) {
13356 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
13357 		dtrace_probedesc_t *desc = &ep->dted_probe;
13358 
13359 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
13360 			continue;
13361 
13362 		if (strcmp(desc->dtpd_mod, "helper") != 0)
13363 			continue;
13364 
13365 		if (strcmp(desc->dtpd_func, "ustack") != 0)
13366 			continue;
13367 
13368 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
13369 		    ep)) != 0) {
13370 			/*
13371 			 * Adding this helper action failed -- we are now going
13372 			 * to rip out the entire generation and return failure.
13373 			 */
13374 			(void) dtrace_helper_destroygen(help->dthps_generation);
13375 			dtrace_enabling_destroy(enab);
13376 			dtrace_dof_destroy(dof);
13377 			return (-1);
13378 		}
13379 
13380 		nhelpers++;
13381 	}
13382 
13383 	if (nhelpers < enab->dten_ndesc)
13384 		dtrace_dof_error(dof, "unmatched helpers");
13385 
13386 	gen = help->dthps_generation++;
13387 	dtrace_enabling_destroy(enab);
13388 
13389 	if (dhp != NULL && nprovs > 0) {
13390 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
13391 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
13392 			mutex_exit(&dtrace_lock);
13393 			dtrace_helper_provider_register(curproc, help, dhp);
13394 			mutex_enter(&dtrace_lock);
13395 
13396 			destroy = 0;
13397 		}
13398 	}
13399 
13400 	if (destroy)
13401 		dtrace_dof_destroy(dof);
13402 
13403 	return (gen);
13404 }
13405 
13406 static dtrace_helpers_t *
13407 dtrace_helpers_create(proc_t *p)
13408 {
13409 	dtrace_helpers_t *help;
13410 
13411 	ASSERT(MUTEX_HELD(&dtrace_lock));
13412 	ASSERT(p->p_dtrace_helpers == NULL);
13413 
13414 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
13415 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
13416 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
13417 
13418 	p->p_dtrace_helpers = help;
13419 	dtrace_helpers++;
13420 
13421 	return (help);
13422 }
13423 
13424 static void
13425 dtrace_helpers_destroy(void)
13426 {
13427 	dtrace_helpers_t *help;
13428 	dtrace_vstate_t *vstate;
13429 	proc_t *p = curproc;
13430 	int i;
13431 
13432 	mutex_enter(&dtrace_lock);
13433 
13434 	ASSERT(p->p_dtrace_helpers != NULL);
13435 	ASSERT(dtrace_helpers > 0);
13436 
13437 	help = p->p_dtrace_helpers;
13438 	vstate = &help->dthps_vstate;
13439 
13440 	/*
13441 	 * We're now going to lose the help from this process.
13442 	 */
13443 	p->p_dtrace_helpers = NULL;
13444 	dtrace_sync();
13445 
13446 	/*
13447 	 * Destory the helper actions.
13448 	 */
13449 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13450 		dtrace_helper_action_t *h, *next;
13451 
13452 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13453 			next = h->dtha_next;
13454 			dtrace_helper_action_destroy(h, vstate);
13455 			h = next;
13456 		}
13457 	}
13458 
13459 	mutex_exit(&dtrace_lock);
13460 
13461 	/*
13462 	 * Destroy the helper providers.
13463 	 */
13464 	if (help->dthps_maxprovs > 0) {
13465 		mutex_enter(&dtrace_meta_lock);
13466 		if (dtrace_meta_pid != NULL) {
13467 			ASSERT(dtrace_deferred_pid == NULL);
13468 
13469 			for (i = 0; i < help->dthps_nprovs; i++) {
13470 				dtrace_helper_provider_remove(
13471 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
13472 			}
13473 		} else {
13474 			mutex_enter(&dtrace_lock);
13475 			ASSERT(help->dthps_deferred == 0 ||
13476 			    help->dthps_next != NULL ||
13477 			    help->dthps_prev != NULL ||
13478 			    help == dtrace_deferred_pid);
13479 
13480 			/*
13481 			 * Remove the helper from the deferred list.
13482 			 */
13483 			if (help->dthps_next != NULL)
13484 				help->dthps_next->dthps_prev = help->dthps_prev;
13485 			if (help->dthps_prev != NULL)
13486 				help->dthps_prev->dthps_next = help->dthps_next;
13487 			if (dtrace_deferred_pid == help) {
13488 				dtrace_deferred_pid = help->dthps_next;
13489 				ASSERT(help->dthps_prev == NULL);
13490 			}
13491 
13492 			mutex_exit(&dtrace_lock);
13493 		}
13494 
13495 		mutex_exit(&dtrace_meta_lock);
13496 
13497 		for (i = 0; i < help->dthps_nprovs; i++) {
13498 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
13499 		}
13500 
13501 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
13502 		    sizeof (dtrace_helper_provider_t *));
13503 	}
13504 
13505 	mutex_enter(&dtrace_lock);
13506 
13507 	dtrace_vstate_fini(&help->dthps_vstate);
13508 	kmem_free(help->dthps_actions,
13509 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
13510 	kmem_free(help, sizeof (dtrace_helpers_t));
13511 
13512 	--dtrace_helpers;
13513 	mutex_exit(&dtrace_lock);
13514 }
13515 
13516 static void
13517 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
13518 {
13519 	dtrace_helpers_t *help, *newhelp;
13520 	dtrace_helper_action_t *helper, *new, *last;
13521 	dtrace_difo_t *dp;
13522 	dtrace_vstate_t *vstate;
13523 	int i, j, sz, hasprovs = 0;
13524 
13525 	mutex_enter(&dtrace_lock);
13526 	ASSERT(from->p_dtrace_helpers != NULL);
13527 	ASSERT(dtrace_helpers > 0);
13528 
13529 	help = from->p_dtrace_helpers;
13530 	newhelp = dtrace_helpers_create(to);
13531 	ASSERT(to->p_dtrace_helpers != NULL);
13532 
13533 	newhelp->dthps_generation = help->dthps_generation;
13534 	vstate = &newhelp->dthps_vstate;
13535 
13536 	/*
13537 	 * Duplicate the helper actions.
13538 	 */
13539 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13540 		if ((helper = help->dthps_actions[i]) == NULL)
13541 			continue;
13542 
13543 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
13544 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
13545 			    KM_SLEEP);
13546 			new->dtha_generation = helper->dtha_generation;
13547 
13548 			if ((dp = helper->dtha_predicate) != NULL) {
13549 				dp = dtrace_difo_duplicate(dp, vstate);
13550 				new->dtha_predicate = dp;
13551 			}
13552 
13553 			new->dtha_nactions = helper->dtha_nactions;
13554 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
13555 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
13556 
13557 			for (j = 0; j < new->dtha_nactions; j++) {
13558 				dtrace_difo_t *dp = helper->dtha_actions[j];
13559 
13560 				ASSERT(dp != NULL);
13561 				dp = dtrace_difo_duplicate(dp, vstate);
13562 				new->dtha_actions[j] = dp;
13563 			}
13564 
13565 			if (last != NULL) {
13566 				last->dtha_next = new;
13567 			} else {
13568 				newhelp->dthps_actions[i] = new;
13569 			}
13570 
13571 			last = new;
13572 		}
13573 	}
13574 
13575 	/*
13576 	 * Duplicate the helper providers and register them with the
13577 	 * DTrace framework.
13578 	 */
13579 	if (help->dthps_nprovs > 0) {
13580 		newhelp->dthps_nprovs = help->dthps_nprovs;
13581 		newhelp->dthps_maxprovs = help->dthps_nprovs;
13582 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
13583 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13584 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
13585 			newhelp->dthps_provs[i] = help->dthps_provs[i];
13586 			newhelp->dthps_provs[i]->dthp_ref++;
13587 		}
13588 
13589 		hasprovs = 1;
13590 	}
13591 
13592 	mutex_exit(&dtrace_lock);
13593 
13594 	if (hasprovs)
13595 		dtrace_helper_provider_register(to, newhelp, NULL);
13596 }
13597 
13598 /*
13599  * DTrace Hook Functions
13600  */
13601 static void
13602 dtrace_module_loaded(struct modctl *ctl)
13603 {
13604 	dtrace_provider_t *prv;
13605 
13606 	mutex_enter(&dtrace_provider_lock);
13607 	mutex_enter(&mod_lock);
13608 
13609 	ASSERT(ctl->mod_busy);
13610 
13611 	/*
13612 	 * We're going to call each providers per-module provide operation
13613 	 * specifying only this module.
13614 	 */
13615 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
13616 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
13617 
13618 	mutex_exit(&mod_lock);
13619 	mutex_exit(&dtrace_provider_lock);
13620 
13621 	/*
13622 	 * If we have any retained enablings, we need to match against them.
13623 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
13624 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
13625 	 * module.  (In particular, this happens when loading scheduling
13626 	 * classes.)  So if we have any retained enablings, we need to dispatch
13627 	 * our task queue to do the match for us.
13628 	 */
13629 	mutex_enter(&dtrace_lock);
13630 
13631 	if (dtrace_retained == NULL) {
13632 		mutex_exit(&dtrace_lock);
13633 		return;
13634 	}
13635 
13636 	(void) taskq_dispatch(dtrace_taskq,
13637 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
13638 
13639 	mutex_exit(&dtrace_lock);
13640 
13641 	/*
13642 	 * And now, for a little heuristic sleaze:  in general, we want to
13643 	 * match modules as soon as they load.  However, we cannot guarantee
13644 	 * this, because it would lead us to the lock ordering violation
13645 	 * outlined above.  The common case, of course, is that cpu_lock is
13646 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
13647 	 * long enough for the task queue to do its work.  If it's not, it's
13648 	 * not a serious problem -- it just means that the module that we
13649 	 * just loaded may not be immediately instrumentable.
13650 	 */
13651 	delay(1);
13652 }
13653 
13654 static void
13655 dtrace_module_unloaded(struct modctl *ctl)
13656 {
13657 	dtrace_probe_t template, *probe, *first, *next;
13658 	dtrace_provider_t *prov;
13659 
13660 	template.dtpr_mod = ctl->mod_modname;
13661 
13662 	mutex_enter(&dtrace_provider_lock);
13663 	mutex_enter(&mod_lock);
13664 	mutex_enter(&dtrace_lock);
13665 
13666 	if (dtrace_bymod == NULL) {
13667 		/*
13668 		 * The DTrace module is loaded (obviously) but not attached;
13669 		 * we don't have any work to do.
13670 		 */
13671 		mutex_exit(&dtrace_provider_lock);
13672 		mutex_exit(&mod_lock);
13673 		mutex_exit(&dtrace_lock);
13674 		return;
13675 	}
13676 
13677 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
13678 	    probe != NULL; probe = probe->dtpr_nextmod) {
13679 		if (probe->dtpr_ecb != NULL) {
13680 			mutex_exit(&dtrace_provider_lock);
13681 			mutex_exit(&mod_lock);
13682 			mutex_exit(&dtrace_lock);
13683 
13684 			/*
13685 			 * This shouldn't _actually_ be possible -- we're
13686 			 * unloading a module that has an enabled probe in it.
13687 			 * (It's normally up to the provider to make sure that
13688 			 * this can't happen.)  However, because dtps_enable()
13689 			 * doesn't have a failure mode, there can be an
13690 			 * enable/unload race.  Upshot:  we don't want to
13691 			 * assert, but we're not going to disable the
13692 			 * probe, either.
13693 			 */
13694 			if (dtrace_err_verbose) {
13695 				cmn_err(CE_WARN, "unloaded module '%s' had "
13696 				    "enabled probes", ctl->mod_modname);
13697 			}
13698 
13699 			return;
13700 		}
13701 	}
13702 
13703 	probe = first;
13704 
13705 	for (first = NULL; probe != NULL; probe = next) {
13706 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
13707 
13708 		dtrace_probes[probe->dtpr_id - 1] = NULL;
13709 
13710 		next = probe->dtpr_nextmod;
13711 		dtrace_hash_remove(dtrace_bymod, probe);
13712 		dtrace_hash_remove(dtrace_byfunc, probe);
13713 		dtrace_hash_remove(dtrace_byname, probe);
13714 
13715 		if (first == NULL) {
13716 			first = probe;
13717 			probe->dtpr_nextmod = NULL;
13718 		} else {
13719 			probe->dtpr_nextmod = first;
13720 			first = probe;
13721 		}
13722 	}
13723 
13724 	/*
13725 	 * We've removed all of the module's probes from the hash chains and
13726 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
13727 	 * everyone has cleared out from any probe array processing.
13728 	 */
13729 	dtrace_sync();
13730 
13731 	for (probe = first; probe != NULL; probe = first) {
13732 		first = probe->dtpr_nextmod;
13733 		prov = probe->dtpr_provider;
13734 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
13735 		    probe->dtpr_arg);
13736 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
13737 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
13738 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
13739 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
13740 		kmem_free(probe, sizeof (dtrace_probe_t));
13741 	}
13742 
13743 	mutex_exit(&dtrace_lock);
13744 	mutex_exit(&mod_lock);
13745 	mutex_exit(&dtrace_provider_lock);
13746 }
13747 
13748 void
13749 dtrace_suspend(void)
13750 {
13751 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
13752 }
13753 
13754 void
13755 dtrace_resume(void)
13756 {
13757 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
13758 }
13759 
13760 static int
13761 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
13762 {
13763 	ASSERT(MUTEX_HELD(&cpu_lock));
13764 	mutex_enter(&dtrace_lock);
13765 
13766 	switch (what) {
13767 	case CPU_CONFIG: {
13768 		dtrace_state_t *state;
13769 		dtrace_optval_t *opt, rs, c;
13770 
13771 		/*
13772 		 * For now, we only allocate a new buffer for anonymous state.
13773 		 */
13774 		if ((state = dtrace_anon.dta_state) == NULL)
13775 			break;
13776 
13777 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13778 			break;
13779 
13780 		opt = state->dts_options;
13781 		c = opt[DTRACEOPT_CPU];
13782 
13783 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
13784 			break;
13785 
13786 		/*
13787 		 * Regardless of what the actual policy is, we're going to
13788 		 * temporarily set our resize policy to be manual.  We're
13789 		 * also going to temporarily set our CPU option to denote
13790 		 * the newly configured CPU.
13791 		 */
13792 		rs = opt[DTRACEOPT_BUFRESIZE];
13793 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
13794 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
13795 
13796 		(void) dtrace_state_buffers(state);
13797 
13798 		opt[DTRACEOPT_BUFRESIZE] = rs;
13799 		opt[DTRACEOPT_CPU] = c;
13800 
13801 		break;
13802 	}
13803 
13804 	case CPU_UNCONFIG:
13805 		/*
13806 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
13807 		 * buffer will be freed when the consumer exits.)
13808 		 */
13809 		break;
13810 
13811 	default:
13812 		break;
13813 	}
13814 
13815 	mutex_exit(&dtrace_lock);
13816 	return (0);
13817 }
13818 
13819 static void
13820 dtrace_cpu_setup_initial(processorid_t cpu)
13821 {
13822 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
13823 }
13824 
13825 static void
13826 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
13827 {
13828 	if (dtrace_toxranges >= dtrace_toxranges_max) {
13829 		int osize, nsize;
13830 		dtrace_toxrange_t *range;
13831 
13832 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
13833 
13834 		if (osize == 0) {
13835 			ASSERT(dtrace_toxrange == NULL);
13836 			ASSERT(dtrace_toxranges_max == 0);
13837 			dtrace_toxranges_max = 1;
13838 		} else {
13839 			dtrace_toxranges_max <<= 1;
13840 		}
13841 
13842 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
13843 		range = kmem_zalloc(nsize, KM_SLEEP);
13844 
13845 		if (dtrace_toxrange != NULL) {
13846 			ASSERT(osize != 0);
13847 			bcopy(dtrace_toxrange, range, osize);
13848 			kmem_free(dtrace_toxrange, osize);
13849 		}
13850 
13851 		dtrace_toxrange = range;
13852 	}
13853 
13854 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
13855 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
13856 
13857 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
13858 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
13859 	dtrace_toxranges++;
13860 }
13861 
13862 /*
13863  * DTrace Driver Cookbook Functions
13864  */
13865 /*ARGSUSED*/
13866 static int
13867 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
13868 {
13869 	dtrace_provider_id_t id;
13870 	dtrace_state_t *state = NULL;
13871 	dtrace_enabling_t *enab;
13872 
13873 	mutex_enter(&cpu_lock);
13874 	mutex_enter(&dtrace_provider_lock);
13875 	mutex_enter(&dtrace_lock);
13876 
13877 	if (ddi_soft_state_init(&dtrace_softstate,
13878 	    sizeof (dtrace_state_t), 0) != 0) {
13879 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
13880 		mutex_exit(&cpu_lock);
13881 		mutex_exit(&dtrace_provider_lock);
13882 		mutex_exit(&dtrace_lock);
13883 		return (DDI_FAILURE);
13884 	}
13885 
13886 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
13887 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
13888 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
13889 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
13890 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
13891 		ddi_remove_minor_node(devi, NULL);
13892 		ddi_soft_state_fini(&dtrace_softstate);
13893 		mutex_exit(&cpu_lock);
13894 		mutex_exit(&dtrace_provider_lock);
13895 		mutex_exit(&dtrace_lock);
13896 		return (DDI_FAILURE);
13897 	}
13898 
13899 	ddi_report_dev(devi);
13900 	dtrace_devi = devi;
13901 
13902 	dtrace_modload = dtrace_module_loaded;
13903 	dtrace_modunload = dtrace_module_unloaded;
13904 	dtrace_cpu_init = dtrace_cpu_setup_initial;
13905 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
13906 	dtrace_helpers_fork = dtrace_helpers_duplicate;
13907 	dtrace_cpustart_init = dtrace_suspend;
13908 	dtrace_cpustart_fini = dtrace_resume;
13909 	dtrace_debugger_init = dtrace_suspend;
13910 	dtrace_debugger_fini = dtrace_resume;
13911 	dtrace_kreloc_init = dtrace_suspend;
13912 	dtrace_kreloc_fini = dtrace_resume;
13913 
13914 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
13915 
13916 	ASSERT(MUTEX_HELD(&cpu_lock));
13917 
13918 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
13919 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13920 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
13921 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
13922 	    VM_SLEEP | VMC_IDENTIFIER);
13923 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
13924 	    1, INT_MAX, 0);
13925 
13926 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
13927 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
13928 	    NULL, NULL, NULL, NULL, NULL, 0);
13929 
13930 	ASSERT(MUTEX_HELD(&cpu_lock));
13931 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
13932 	    offsetof(dtrace_probe_t, dtpr_nextmod),
13933 	    offsetof(dtrace_probe_t, dtpr_prevmod));
13934 
13935 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
13936 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
13937 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
13938 
13939 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
13940 	    offsetof(dtrace_probe_t, dtpr_nextname),
13941 	    offsetof(dtrace_probe_t, dtpr_prevname));
13942 
13943 	if (dtrace_retain_max < 1) {
13944 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
13945 		    "setting to 1", dtrace_retain_max);
13946 		dtrace_retain_max = 1;
13947 	}
13948 
13949 	/*
13950 	 * Now discover our toxic ranges.
13951 	 */
13952 	dtrace_toxic_ranges(dtrace_toxrange_add);
13953 
13954 	/*
13955 	 * Before we register ourselves as a provider to our own framework,
13956 	 * we would like to assert that dtrace_provider is NULL -- but that's
13957 	 * not true if we were loaded as a dependency of a DTrace provider.
13958 	 * Once we've registered, we can assert that dtrace_provider is our
13959 	 * pseudo provider.
13960 	 */
13961 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
13962 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
13963 
13964 	ASSERT(dtrace_provider != NULL);
13965 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
13966 
13967 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
13968 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
13969 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
13970 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
13971 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
13972 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
13973 
13974 	dtrace_anon_property();
13975 	mutex_exit(&cpu_lock);
13976 
13977 	/*
13978 	 * If DTrace helper tracing is enabled, we need to allocate the
13979 	 * trace buffer and initialize the values.
13980 	 */
13981 	if (dtrace_helptrace_enabled) {
13982 		ASSERT(dtrace_helptrace_buffer == NULL);
13983 		dtrace_helptrace_buffer =
13984 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
13985 		dtrace_helptrace_next = 0;
13986 	}
13987 
13988 	/*
13989 	 * If there are already providers, we must ask them to provide their
13990 	 * probes, and then match any anonymous enabling against them.  Note
13991 	 * that there should be no other retained enablings at this time:
13992 	 * the only retained enablings at this time should be the anonymous
13993 	 * enabling.
13994 	 */
13995 	if (dtrace_anon.dta_enabling != NULL) {
13996 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
13997 
13998 		dtrace_enabling_provide(NULL);
13999 		state = dtrace_anon.dta_state;
14000 
14001 		/*
14002 		 * We couldn't hold cpu_lock across the above call to
14003 		 * dtrace_enabling_provide(), but we must hold it to actually
14004 		 * enable the probes.  We have to drop all of our locks, pick
14005 		 * up cpu_lock, and regain our locks before matching the
14006 		 * retained anonymous enabling.
14007 		 */
14008 		mutex_exit(&dtrace_lock);
14009 		mutex_exit(&dtrace_provider_lock);
14010 
14011 		mutex_enter(&cpu_lock);
14012 		mutex_enter(&dtrace_provider_lock);
14013 		mutex_enter(&dtrace_lock);
14014 
14015 		if ((enab = dtrace_anon.dta_enabling) != NULL)
14016 			(void) dtrace_enabling_match(enab, NULL);
14017 
14018 		mutex_exit(&cpu_lock);
14019 	}
14020 
14021 	mutex_exit(&dtrace_lock);
14022 	mutex_exit(&dtrace_provider_lock);
14023 
14024 	if (state != NULL) {
14025 		/*
14026 		 * If we created any anonymous state, set it going now.
14027 		 */
14028 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
14029 	}
14030 
14031 	return (DDI_SUCCESS);
14032 }
14033 
14034 /*ARGSUSED*/
14035 static int
14036 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
14037 {
14038 	dtrace_state_t *state;
14039 	uint32_t priv;
14040 	uid_t uid;
14041 	zoneid_t zoneid;
14042 
14043 	if (getminor(*devp) == DTRACEMNRN_HELPER)
14044 		return (0);
14045 
14046 	/*
14047 	 * If this wasn't an open with the "helper" minor, then it must be
14048 	 * the "dtrace" minor.
14049 	 */
14050 	ASSERT(getminor(*devp) == DTRACEMNRN_DTRACE);
14051 
14052 	/*
14053 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
14054 	 * caller lacks sufficient permission to do anything with DTrace.
14055 	 */
14056 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
14057 	if (priv == DTRACE_PRIV_NONE)
14058 		return (EACCES);
14059 
14060 	/*
14061 	 * Ask all providers to provide all their probes.
14062 	 */
14063 	mutex_enter(&dtrace_provider_lock);
14064 	dtrace_probe_provide(NULL, NULL);
14065 	mutex_exit(&dtrace_provider_lock);
14066 
14067 	mutex_enter(&cpu_lock);
14068 	mutex_enter(&dtrace_lock);
14069 	dtrace_opens++;
14070 	dtrace_membar_producer();
14071 
14072 	/*
14073 	 * If the kernel debugger is active (that is, if the kernel debugger
14074 	 * modified text in some way), we won't allow the open.
14075 	 */
14076 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14077 		dtrace_opens--;
14078 		mutex_exit(&cpu_lock);
14079 		mutex_exit(&dtrace_lock);
14080 		return (EBUSY);
14081 	}
14082 
14083 	state = dtrace_state_create(devp, cred_p);
14084 	mutex_exit(&cpu_lock);
14085 
14086 	if (state == NULL) {
14087 		if (--dtrace_opens == 0)
14088 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14089 		mutex_exit(&dtrace_lock);
14090 		return (EAGAIN);
14091 	}
14092 
14093 	mutex_exit(&dtrace_lock);
14094 
14095 	return (0);
14096 }
14097 
14098 /*ARGSUSED*/
14099 static int
14100 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
14101 {
14102 	minor_t minor = getminor(dev);
14103 	dtrace_state_t *state;
14104 
14105 	if (minor == DTRACEMNRN_HELPER)
14106 		return (0);
14107 
14108 	state = ddi_get_soft_state(dtrace_softstate, minor);
14109 
14110 	mutex_enter(&cpu_lock);
14111 	mutex_enter(&dtrace_lock);
14112 
14113 	if (state->dts_anon) {
14114 		/*
14115 		 * There is anonymous state. Destroy that first.
14116 		 */
14117 		ASSERT(dtrace_anon.dta_state == NULL);
14118 		dtrace_state_destroy(state->dts_anon);
14119 	}
14120 
14121 	dtrace_state_destroy(state);
14122 	ASSERT(dtrace_opens > 0);
14123 	if (--dtrace_opens == 0)
14124 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14125 
14126 	mutex_exit(&dtrace_lock);
14127 	mutex_exit(&cpu_lock);
14128 
14129 	return (0);
14130 }
14131 
14132 /*ARGSUSED*/
14133 static int
14134 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
14135 {
14136 	int rval;
14137 	dof_helper_t help, *dhp = NULL;
14138 
14139 	switch (cmd) {
14140 	case DTRACEHIOC_ADDDOF:
14141 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
14142 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
14143 			return (EFAULT);
14144 		}
14145 
14146 		dhp = &help;
14147 		arg = (intptr_t)help.dofhp_dof;
14148 		/*FALLTHROUGH*/
14149 
14150 	case DTRACEHIOC_ADD: {
14151 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
14152 
14153 		if (dof == NULL)
14154 			return (rval);
14155 
14156 		mutex_enter(&dtrace_lock);
14157 
14158 		/*
14159 		 * dtrace_helper_slurp() takes responsibility for the dof --
14160 		 * it may free it now or it may save it and free it later.
14161 		 */
14162 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
14163 			*rv = rval;
14164 			rval = 0;
14165 		} else {
14166 			rval = EINVAL;
14167 		}
14168 
14169 		mutex_exit(&dtrace_lock);
14170 		return (rval);
14171 	}
14172 
14173 	case DTRACEHIOC_REMOVE: {
14174 		mutex_enter(&dtrace_lock);
14175 		rval = dtrace_helper_destroygen(arg);
14176 		mutex_exit(&dtrace_lock);
14177 
14178 		return (rval);
14179 	}
14180 
14181 	default:
14182 		break;
14183 	}
14184 
14185 	return (ENOTTY);
14186 }
14187 
14188 /*ARGSUSED*/
14189 static int
14190 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
14191 {
14192 	minor_t minor = getminor(dev);
14193 	dtrace_state_t *state;
14194 	int rval;
14195 
14196 	if (minor == DTRACEMNRN_HELPER)
14197 		return (dtrace_ioctl_helper(cmd, arg, rv));
14198 
14199 	state = ddi_get_soft_state(dtrace_softstate, minor);
14200 
14201 	if (state->dts_anon) {
14202 		ASSERT(dtrace_anon.dta_state == NULL);
14203 		state = state->dts_anon;
14204 	}
14205 
14206 	switch (cmd) {
14207 	case DTRACEIOC_PROVIDER: {
14208 		dtrace_providerdesc_t pvd;
14209 		dtrace_provider_t *pvp;
14210 
14211 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
14212 			return (EFAULT);
14213 
14214 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
14215 		mutex_enter(&dtrace_provider_lock);
14216 
14217 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
14218 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
14219 				break;
14220 		}
14221 
14222 		mutex_exit(&dtrace_provider_lock);
14223 
14224 		if (pvp == NULL)
14225 			return (ESRCH);
14226 
14227 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
14228 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
14229 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
14230 			return (EFAULT);
14231 
14232 		return (0);
14233 	}
14234 
14235 	case DTRACEIOC_EPROBE: {
14236 		dtrace_eprobedesc_t epdesc;
14237 		dtrace_ecb_t *ecb;
14238 		dtrace_action_t *act;
14239 		void *buf;
14240 		size_t size;
14241 		uintptr_t dest;
14242 		int nrecs;
14243 
14244 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
14245 			return (EFAULT);
14246 
14247 		mutex_enter(&dtrace_lock);
14248 
14249 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
14250 			mutex_exit(&dtrace_lock);
14251 			return (EINVAL);
14252 		}
14253 
14254 		if (ecb->dte_probe == NULL) {
14255 			mutex_exit(&dtrace_lock);
14256 			return (EINVAL);
14257 		}
14258 
14259 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
14260 		epdesc.dtepd_uarg = ecb->dte_uarg;
14261 		epdesc.dtepd_size = ecb->dte_size;
14262 
14263 		nrecs = epdesc.dtepd_nrecs;
14264 		epdesc.dtepd_nrecs = 0;
14265 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
14266 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
14267 				continue;
14268 
14269 			epdesc.dtepd_nrecs++;
14270 		}
14271 
14272 		/*
14273 		 * Now that we have the size, we need to allocate a temporary
14274 		 * buffer in which to store the complete description.  We need
14275 		 * the temporary buffer to be able to drop dtrace_lock()
14276 		 * across the copyout(), below.
14277 		 */
14278 		size = sizeof (dtrace_eprobedesc_t) +
14279 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
14280 
14281 		buf = kmem_alloc(size, KM_SLEEP);
14282 		dest = (uintptr_t)buf;
14283 
14284 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
14285 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
14286 
14287 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
14288 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
14289 				continue;
14290 
14291 			if (nrecs-- == 0)
14292 				break;
14293 
14294 			bcopy(&act->dta_rec, (void *)dest,
14295 			    sizeof (dtrace_recdesc_t));
14296 			dest += sizeof (dtrace_recdesc_t);
14297 		}
14298 
14299 		mutex_exit(&dtrace_lock);
14300 
14301 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
14302 			kmem_free(buf, size);
14303 			return (EFAULT);
14304 		}
14305 
14306 		kmem_free(buf, size);
14307 		return (0);
14308 	}
14309 
14310 	case DTRACEIOC_AGGDESC: {
14311 		dtrace_aggdesc_t aggdesc;
14312 		dtrace_action_t *act;
14313 		dtrace_aggregation_t *agg;
14314 		int nrecs;
14315 		uint32_t offs;
14316 		dtrace_recdesc_t *lrec;
14317 		void *buf;
14318 		size_t size;
14319 		uintptr_t dest;
14320 
14321 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
14322 			return (EFAULT);
14323 
14324 		mutex_enter(&dtrace_lock);
14325 
14326 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
14327 			mutex_exit(&dtrace_lock);
14328 			return (EINVAL);
14329 		}
14330 
14331 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
14332 
14333 		nrecs = aggdesc.dtagd_nrecs;
14334 		aggdesc.dtagd_nrecs = 0;
14335 
14336 		offs = agg->dtag_base;
14337 		lrec = &agg->dtag_action.dta_rec;
14338 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
14339 
14340 		for (act = agg->dtag_first; ; act = act->dta_next) {
14341 			ASSERT(act->dta_intuple ||
14342 			    DTRACEACT_ISAGG(act->dta_kind));
14343 
14344 			/*
14345 			 * If this action has a record size of zero, it
14346 			 * denotes an argument to the aggregating action.
14347 			 * Because the presence of this record doesn't (or
14348 			 * shouldn't) affect the way the data is interpreted,
14349 			 * we don't copy it out to save user-level the
14350 			 * confusion of dealing with a zero-length record.
14351 			 */
14352 			if (act->dta_rec.dtrd_size == 0) {
14353 				ASSERT(agg->dtag_hasarg);
14354 				continue;
14355 			}
14356 
14357 			aggdesc.dtagd_nrecs++;
14358 
14359 			if (act == &agg->dtag_action)
14360 				break;
14361 		}
14362 
14363 		/*
14364 		 * Now that we have the size, we need to allocate a temporary
14365 		 * buffer in which to store the complete description.  We need
14366 		 * the temporary buffer to be able to drop dtrace_lock()
14367 		 * across the copyout(), below.
14368 		 */
14369 		size = sizeof (dtrace_aggdesc_t) +
14370 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
14371 
14372 		buf = kmem_alloc(size, KM_SLEEP);
14373 		dest = (uintptr_t)buf;
14374 
14375 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
14376 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
14377 
14378 		for (act = agg->dtag_first; ; act = act->dta_next) {
14379 			dtrace_recdesc_t rec = act->dta_rec;
14380 
14381 			/*
14382 			 * See the comment in the above loop for why we pass
14383 			 * over zero-length records.
14384 			 */
14385 			if (rec.dtrd_size == 0) {
14386 				ASSERT(agg->dtag_hasarg);
14387 				continue;
14388 			}
14389 
14390 			if (nrecs-- == 0)
14391 				break;
14392 
14393 			rec.dtrd_offset -= offs;
14394 			bcopy(&rec, (void *)dest, sizeof (rec));
14395 			dest += sizeof (dtrace_recdesc_t);
14396 
14397 			if (act == &agg->dtag_action)
14398 				break;
14399 		}
14400 
14401 		mutex_exit(&dtrace_lock);
14402 
14403 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
14404 			kmem_free(buf, size);
14405 			return (EFAULT);
14406 		}
14407 
14408 		kmem_free(buf, size);
14409 		return (0);
14410 	}
14411 
14412 	case DTRACEIOC_ENABLE: {
14413 		dof_hdr_t *dof;
14414 		dtrace_enabling_t *enab = NULL;
14415 		dtrace_vstate_t *vstate;
14416 		int err = 0;
14417 
14418 		*rv = 0;
14419 
14420 		/*
14421 		 * If a NULL argument has been passed, we take this as our
14422 		 * cue to reevaluate our enablings.
14423 		 */
14424 		if (arg == NULL) {
14425 			mutex_enter(&cpu_lock);
14426 			mutex_enter(&dtrace_lock);
14427 			err = dtrace_enabling_matchstate(state, rv);
14428 			mutex_exit(&dtrace_lock);
14429 			mutex_exit(&cpu_lock);
14430 
14431 			return (err);
14432 		}
14433 
14434 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
14435 			return (rval);
14436 
14437 		mutex_enter(&cpu_lock);
14438 		mutex_enter(&dtrace_lock);
14439 		vstate = &state->dts_vstate;
14440 
14441 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14442 			mutex_exit(&dtrace_lock);
14443 			mutex_exit(&cpu_lock);
14444 			dtrace_dof_destroy(dof);
14445 			return (EBUSY);
14446 		}
14447 
14448 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
14449 			mutex_exit(&dtrace_lock);
14450 			mutex_exit(&cpu_lock);
14451 			dtrace_dof_destroy(dof);
14452 			return (EINVAL);
14453 		}
14454 
14455 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
14456 			dtrace_enabling_destroy(enab);
14457 			mutex_exit(&dtrace_lock);
14458 			mutex_exit(&cpu_lock);
14459 			dtrace_dof_destroy(dof);
14460 			return (rval);
14461 		}
14462 
14463 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
14464 			err = dtrace_enabling_retain(enab);
14465 		} else {
14466 			dtrace_enabling_destroy(enab);
14467 		}
14468 
14469 		mutex_exit(&cpu_lock);
14470 		mutex_exit(&dtrace_lock);
14471 		dtrace_dof_destroy(dof);
14472 
14473 		return (err);
14474 	}
14475 
14476 	case DTRACEIOC_REPLICATE: {
14477 		dtrace_repldesc_t desc;
14478 		dtrace_probedesc_t *match = &desc.dtrpd_match;
14479 		dtrace_probedesc_t *create = &desc.dtrpd_create;
14480 		int err;
14481 
14482 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14483 			return (EFAULT);
14484 
14485 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14486 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14487 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14488 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14489 
14490 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14491 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14492 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14493 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14494 
14495 		mutex_enter(&dtrace_lock);
14496 		err = dtrace_enabling_replicate(state, match, create);
14497 		mutex_exit(&dtrace_lock);
14498 
14499 		return (err);
14500 	}
14501 
14502 	case DTRACEIOC_PROBEMATCH:
14503 	case DTRACEIOC_PROBES: {
14504 		dtrace_probe_t *probe = NULL;
14505 		dtrace_probedesc_t desc;
14506 		dtrace_probekey_t pkey;
14507 		dtrace_id_t i;
14508 		int m = 0;
14509 		uint32_t priv;
14510 		uid_t uid;
14511 		zoneid_t zoneid;
14512 
14513 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14514 			return (EFAULT);
14515 
14516 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14517 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14518 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14519 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14520 
14521 		/*
14522 		 * Before we attempt to match this probe, we want to give
14523 		 * all providers the opportunity to provide it.
14524 		 */
14525 		if (desc.dtpd_id == DTRACE_IDNONE) {
14526 			mutex_enter(&dtrace_provider_lock);
14527 			dtrace_probe_provide(&desc, NULL);
14528 			mutex_exit(&dtrace_provider_lock);
14529 			desc.dtpd_id++;
14530 		}
14531 
14532 		if (cmd == DTRACEIOC_PROBEMATCH)  {
14533 			dtrace_probekey(&desc, &pkey);
14534 			pkey.dtpk_id = DTRACE_IDNONE;
14535 		}
14536 
14537 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
14538 
14539 		mutex_enter(&dtrace_lock);
14540 
14541 		if (cmd == DTRACEIOC_PROBEMATCH) {
14542 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14543 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14544 				    (m = dtrace_match_probe(probe, &pkey,
14545 				    priv, uid, zoneid)) != 0)
14546 					break;
14547 			}
14548 
14549 			if (m < 0) {
14550 				mutex_exit(&dtrace_lock);
14551 				return (EINVAL);
14552 			}
14553 
14554 		} else {
14555 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14556 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14557 				    dtrace_match_priv(probe, priv, uid, zoneid))
14558 					break;
14559 			}
14560 		}
14561 
14562 		if (probe == NULL) {
14563 			mutex_exit(&dtrace_lock);
14564 			return (ESRCH);
14565 		}
14566 
14567 		dtrace_probe_description(probe, &desc);
14568 		mutex_exit(&dtrace_lock);
14569 
14570 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14571 			return (EFAULT);
14572 
14573 		return (0);
14574 	}
14575 
14576 	case DTRACEIOC_PROBEARG: {
14577 		dtrace_argdesc_t desc;
14578 		dtrace_probe_t *probe;
14579 		dtrace_provider_t *prov;
14580 
14581 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14582 			return (EFAULT);
14583 
14584 		if (desc.dtargd_id == DTRACE_IDNONE)
14585 			return (EINVAL);
14586 
14587 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
14588 			return (EINVAL);
14589 
14590 		mutex_enter(&dtrace_provider_lock);
14591 		mutex_enter(&mod_lock);
14592 		mutex_enter(&dtrace_lock);
14593 
14594 		if (desc.dtargd_id > dtrace_nprobes) {
14595 			mutex_exit(&dtrace_lock);
14596 			mutex_exit(&mod_lock);
14597 			mutex_exit(&dtrace_provider_lock);
14598 			return (EINVAL);
14599 		}
14600 
14601 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
14602 			mutex_exit(&dtrace_lock);
14603 			mutex_exit(&mod_lock);
14604 			mutex_exit(&dtrace_provider_lock);
14605 			return (EINVAL);
14606 		}
14607 
14608 		mutex_exit(&dtrace_lock);
14609 
14610 		prov = probe->dtpr_provider;
14611 
14612 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
14613 			/*
14614 			 * There isn't any typed information for this probe.
14615 			 * Set the argument number to DTRACE_ARGNONE.
14616 			 */
14617 			desc.dtargd_ndx = DTRACE_ARGNONE;
14618 		} else {
14619 			desc.dtargd_native[0] = '\0';
14620 			desc.dtargd_xlate[0] = '\0';
14621 			desc.dtargd_mapping = desc.dtargd_ndx;
14622 
14623 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
14624 			    probe->dtpr_id, probe->dtpr_arg, &desc);
14625 		}
14626 
14627 		mutex_exit(&mod_lock);
14628 		mutex_exit(&dtrace_provider_lock);
14629 
14630 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14631 			return (EFAULT);
14632 
14633 		return (0);
14634 	}
14635 
14636 	case DTRACEIOC_GO: {
14637 		processorid_t cpuid;
14638 		rval = dtrace_state_go(state, &cpuid);
14639 
14640 		if (rval != 0)
14641 			return (rval);
14642 
14643 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14644 			return (EFAULT);
14645 
14646 		return (0);
14647 	}
14648 
14649 	case DTRACEIOC_STOP: {
14650 		processorid_t cpuid;
14651 
14652 		mutex_enter(&dtrace_lock);
14653 		rval = dtrace_state_stop(state, &cpuid);
14654 		mutex_exit(&dtrace_lock);
14655 
14656 		if (rval != 0)
14657 			return (rval);
14658 
14659 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14660 			return (EFAULT);
14661 
14662 		return (0);
14663 	}
14664 
14665 	case DTRACEIOC_DOFGET: {
14666 		dof_hdr_t hdr, *dof;
14667 		uint64_t len;
14668 
14669 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
14670 			return (EFAULT);
14671 
14672 		mutex_enter(&dtrace_lock);
14673 		dof = dtrace_dof_create(state);
14674 		mutex_exit(&dtrace_lock);
14675 
14676 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
14677 		rval = copyout(dof, (void *)arg, len);
14678 		dtrace_dof_destroy(dof);
14679 
14680 		return (rval == 0 ? 0 : EFAULT);
14681 	}
14682 
14683 	case DTRACEIOC_AGGSNAP:
14684 	case DTRACEIOC_BUFSNAP: {
14685 		dtrace_bufdesc_t desc;
14686 		caddr_t cached;
14687 		dtrace_buffer_t *buf;
14688 
14689 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14690 			return (EFAULT);
14691 
14692 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
14693 			return (EINVAL);
14694 
14695 		mutex_enter(&dtrace_lock);
14696 
14697 		if (cmd == DTRACEIOC_BUFSNAP) {
14698 			buf = &state->dts_buffer[desc.dtbd_cpu];
14699 		} else {
14700 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
14701 		}
14702 
14703 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
14704 			size_t sz = buf->dtb_offset;
14705 
14706 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
14707 				mutex_exit(&dtrace_lock);
14708 				return (EBUSY);
14709 			}
14710 
14711 			/*
14712 			 * If this buffer has already been consumed, we're
14713 			 * going to indicate that there's nothing left here
14714 			 * to consume.
14715 			 */
14716 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
14717 				mutex_exit(&dtrace_lock);
14718 
14719 				desc.dtbd_size = 0;
14720 				desc.dtbd_drops = 0;
14721 				desc.dtbd_errors = 0;
14722 				desc.dtbd_oldest = 0;
14723 				sz = sizeof (desc);
14724 
14725 				if (copyout(&desc, (void *)arg, sz) != 0)
14726 					return (EFAULT);
14727 
14728 				return (0);
14729 			}
14730 
14731 			/*
14732 			 * If this is a ring buffer that has wrapped, we want
14733 			 * to copy the whole thing out.
14734 			 */
14735 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
14736 				dtrace_buffer_polish(buf);
14737 				sz = buf->dtb_size;
14738 			}
14739 
14740 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
14741 				mutex_exit(&dtrace_lock);
14742 				return (EFAULT);
14743 			}
14744 
14745 			desc.dtbd_size = sz;
14746 			desc.dtbd_drops = buf->dtb_drops;
14747 			desc.dtbd_errors = buf->dtb_errors;
14748 			desc.dtbd_oldest = buf->dtb_xamot_offset;
14749 
14750 			mutex_exit(&dtrace_lock);
14751 
14752 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14753 				return (EFAULT);
14754 
14755 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
14756 
14757 			return (0);
14758 		}
14759 
14760 		if (buf->dtb_tomax == NULL) {
14761 			ASSERT(buf->dtb_xamot == NULL);
14762 			mutex_exit(&dtrace_lock);
14763 			return (ENOENT);
14764 		}
14765 
14766 		cached = buf->dtb_tomax;
14767 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
14768 
14769 		dtrace_xcall(desc.dtbd_cpu,
14770 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
14771 
14772 		state->dts_errors += buf->dtb_xamot_errors;
14773 
14774 		/*
14775 		 * If the buffers did not actually switch, then the cross call
14776 		 * did not take place -- presumably because the given CPU is
14777 		 * not in the ready set.  If this is the case, we'll return
14778 		 * ENOENT.
14779 		 */
14780 		if (buf->dtb_tomax == cached) {
14781 			ASSERT(buf->dtb_xamot != cached);
14782 			mutex_exit(&dtrace_lock);
14783 			return (ENOENT);
14784 		}
14785 
14786 		ASSERT(cached == buf->dtb_xamot);
14787 
14788 		/*
14789 		 * We have our snapshot; now copy it out.
14790 		 */
14791 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
14792 		    buf->dtb_xamot_offset) != 0) {
14793 			mutex_exit(&dtrace_lock);
14794 			return (EFAULT);
14795 		}
14796 
14797 		desc.dtbd_size = buf->dtb_xamot_offset;
14798 		desc.dtbd_drops = buf->dtb_xamot_drops;
14799 		desc.dtbd_errors = buf->dtb_xamot_errors;
14800 		desc.dtbd_oldest = 0;
14801 
14802 		mutex_exit(&dtrace_lock);
14803 
14804 		/*
14805 		 * Finally, copy out the buffer description.
14806 		 */
14807 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14808 			return (EFAULT);
14809 
14810 		return (0);
14811 	}
14812 
14813 	case DTRACEIOC_CONF: {
14814 		dtrace_conf_t conf;
14815 
14816 		bzero(&conf, sizeof (conf));
14817 		conf.dtc_difversion = DIF_VERSION;
14818 		conf.dtc_difintregs = DIF_DIR_NREGS;
14819 		conf.dtc_diftupregs = DIF_DTR_NREGS;
14820 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
14821 
14822 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
14823 			return (EFAULT);
14824 
14825 		return (0);
14826 	}
14827 
14828 	case DTRACEIOC_STATUS: {
14829 		dtrace_status_t stat;
14830 		dtrace_dstate_t *dstate;
14831 		int i, j;
14832 		uint64_t nerrs;
14833 
14834 		/*
14835 		 * See the comment in dtrace_state_deadman() for the reason
14836 		 * for setting dts_laststatus to INT64_MAX before setting
14837 		 * it to the correct value.
14838 		 */
14839 		state->dts_laststatus = INT64_MAX;
14840 		dtrace_membar_producer();
14841 		state->dts_laststatus = dtrace_gethrtime();
14842 
14843 		bzero(&stat, sizeof (stat));
14844 
14845 		mutex_enter(&dtrace_lock);
14846 
14847 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
14848 			mutex_exit(&dtrace_lock);
14849 			return (ENOENT);
14850 		}
14851 
14852 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
14853 			stat.dtst_exiting = 1;
14854 
14855 		nerrs = state->dts_errors;
14856 		dstate = &state->dts_vstate.dtvs_dynvars;
14857 
14858 		for (i = 0; i < NCPU; i++) {
14859 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
14860 
14861 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
14862 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
14863 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
14864 
14865 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
14866 				stat.dtst_filled++;
14867 
14868 			nerrs += state->dts_buffer[i].dtb_errors;
14869 
14870 			for (j = 0; j < state->dts_nspeculations; j++) {
14871 				dtrace_speculation_t *spec;
14872 				dtrace_buffer_t *buf;
14873 
14874 				spec = &state->dts_speculations[j];
14875 				buf = &spec->dtsp_buffer[i];
14876 				stat.dtst_specdrops += buf->dtb_xamot_drops;
14877 			}
14878 		}
14879 
14880 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
14881 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
14882 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
14883 		stat.dtst_dblerrors = state->dts_dblerrors;
14884 		stat.dtst_killed =
14885 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
14886 		stat.dtst_errors = nerrs;
14887 
14888 		mutex_exit(&dtrace_lock);
14889 
14890 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
14891 			return (EFAULT);
14892 
14893 		return (0);
14894 	}
14895 
14896 	case DTRACEIOC_FORMAT: {
14897 		dtrace_fmtdesc_t fmt;
14898 		char *str;
14899 		int len;
14900 
14901 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
14902 			return (EFAULT);
14903 
14904 		mutex_enter(&dtrace_lock);
14905 
14906 		if (fmt.dtfd_format == 0 ||
14907 		    fmt.dtfd_format > state->dts_nformats) {
14908 			mutex_exit(&dtrace_lock);
14909 			return (EINVAL);
14910 		}
14911 
14912 		/*
14913 		 * Format strings are allocated contiguously and they are
14914 		 * never freed; if a format index is less than the number
14915 		 * of formats, we can assert that the format map is non-NULL
14916 		 * and that the format for the specified index is non-NULL.
14917 		 */
14918 		ASSERT(state->dts_formats != NULL);
14919 		str = state->dts_formats[fmt.dtfd_format - 1];
14920 		ASSERT(str != NULL);
14921 
14922 		len = strlen(str) + 1;
14923 
14924 		if (len > fmt.dtfd_length) {
14925 			fmt.dtfd_length = len;
14926 
14927 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
14928 				mutex_exit(&dtrace_lock);
14929 				return (EINVAL);
14930 			}
14931 		} else {
14932 			if (copyout(str, fmt.dtfd_string, len) != 0) {
14933 				mutex_exit(&dtrace_lock);
14934 				return (EINVAL);
14935 			}
14936 		}
14937 
14938 		mutex_exit(&dtrace_lock);
14939 		return (0);
14940 	}
14941 
14942 	default:
14943 		break;
14944 	}
14945 
14946 	return (ENOTTY);
14947 }
14948 
14949 /*ARGSUSED*/
14950 static int
14951 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
14952 {
14953 	dtrace_state_t *state;
14954 
14955 	switch (cmd) {
14956 	case DDI_DETACH:
14957 		break;
14958 
14959 	case DDI_SUSPEND:
14960 		return (DDI_SUCCESS);
14961 
14962 	default:
14963 		return (DDI_FAILURE);
14964 	}
14965 
14966 	mutex_enter(&cpu_lock);
14967 	mutex_enter(&dtrace_provider_lock);
14968 	mutex_enter(&dtrace_lock);
14969 
14970 	ASSERT(dtrace_opens == 0);
14971 
14972 	if (dtrace_helpers > 0) {
14973 		mutex_exit(&dtrace_provider_lock);
14974 		mutex_exit(&dtrace_lock);
14975 		mutex_exit(&cpu_lock);
14976 		return (DDI_FAILURE);
14977 	}
14978 
14979 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
14980 		mutex_exit(&dtrace_provider_lock);
14981 		mutex_exit(&dtrace_lock);
14982 		mutex_exit(&cpu_lock);
14983 		return (DDI_FAILURE);
14984 	}
14985 
14986 	dtrace_provider = NULL;
14987 
14988 	if ((state = dtrace_anon_grab()) != NULL) {
14989 		/*
14990 		 * If there were ECBs on this state, the provider should
14991 		 * have not been allowed to detach; assert that there is
14992 		 * none.
14993 		 */
14994 		ASSERT(state->dts_necbs == 0);
14995 		dtrace_state_destroy(state);
14996 
14997 		/*
14998 		 * If we're being detached with anonymous state, we need to
14999 		 * indicate to the kernel debugger that DTrace is now inactive.
15000 		 */
15001 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15002 	}
15003 
15004 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
15005 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15006 	dtrace_cpu_init = NULL;
15007 	dtrace_helpers_cleanup = NULL;
15008 	dtrace_helpers_fork = NULL;
15009 	dtrace_cpustart_init = NULL;
15010 	dtrace_cpustart_fini = NULL;
15011 	dtrace_debugger_init = NULL;
15012 	dtrace_debugger_fini = NULL;
15013 	dtrace_kreloc_init = NULL;
15014 	dtrace_kreloc_fini = NULL;
15015 	dtrace_modload = NULL;
15016 	dtrace_modunload = NULL;
15017 
15018 	mutex_exit(&cpu_lock);
15019 
15020 	if (dtrace_helptrace_enabled) {
15021 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
15022 		dtrace_helptrace_buffer = NULL;
15023 	}
15024 
15025 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
15026 	dtrace_probes = NULL;
15027 	dtrace_nprobes = 0;
15028 
15029 	dtrace_hash_destroy(dtrace_bymod);
15030 	dtrace_hash_destroy(dtrace_byfunc);
15031 	dtrace_hash_destroy(dtrace_byname);
15032 	dtrace_bymod = NULL;
15033 	dtrace_byfunc = NULL;
15034 	dtrace_byname = NULL;
15035 
15036 	kmem_cache_destroy(dtrace_state_cache);
15037 	vmem_destroy(dtrace_minor);
15038 	vmem_destroy(dtrace_arena);
15039 
15040 	if (dtrace_toxrange != NULL) {
15041 		kmem_free(dtrace_toxrange,
15042 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
15043 		dtrace_toxrange = NULL;
15044 		dtrace_toxranges = 0;
15045 		dtrace_toxranges_max = 0;
15046 	}
15047 
15048 	ddi_remove_minor_node(dtrace_devi, NULL);
15049 	dtrace_devi = NULL;
15050 
15051 	ddi_soft_state_fini(&dtrace_softstate);
15052 
15053 	ASSERT(dtrace_vtime_references == 0);
15054 	ASSERT(dtrace_opens == 0);
15055 	ASSERT(dtrace_retained == NULL);
15056 
15057 	mutex_exit(&dtrace_lock);
15058 	mutex_exit(&dtrace_provider_lock);
15059 
15060 	/*
15061 	 * We don't destroy the task queue until after we have dropped our
15062 	 * locks (taskq_destroy() may block on running tasks).  To prevent
15063 	 * attempting to do work after we have effectively detached but before
15064 	 * the task queue has been destroyed, all tasks dispatched via the
15065 	 * task queue must check that DTrace is still attached before
15066 	 * performing any operation.
15067 	 */
15068 	taskq_destroy(dtrace_taskq);
15069 	dtrace_taskq = NULL;
15070 
15071 	return (DDI_SUCCESS);
15072 }
15073 
15074 /*ARGSUSED*/
15075 static int
15076 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
15077 {
15078 	int error;
15079 
15080 	switch (infocmd) {
15081 	case DDI_INFO_DEVT2DEVINFO:
15082 		*result = (void *)dtrace_devi;
15083 		error = DDI_SUCCESS;
15084 		break;
15085 	case DDI_INFO_DEVT2INSTANCE:
15086 		*result = (void *)0;
15087 		error = DDI_SUCCESS;
15088 		break;
15089 	default:
15090 		error = DDI_FAILURE;
15091 	}
15092 	return (error);
15093 }
15094 
15095 static struct cb_ops dtrace_cb_ops = {
15096 	dtrace_open,		/* open */
15097 	dtrace_close,		/* close */
15098 	nulldev,		/* strategy */
15099 	nulldev,		/* print */
15100 	nodev,			/* dump */
15101 	nodev,			/* read */
15102 	nodev,			/* write */
15103 	dtrace_ioctl,		/* ioctl */
15104 	nodev,			/* devmap */
15105 	nodev,			/* mmap */
15106 	nodev,			/* segmap */
15107 	nochpoll,		/* poll */
15108 	ddi_prop_op,		/* cb_prop_op */
15109 	0,			/* streamtab  */
15110 	D_NEW | D_MP		/* Driver compatibility flag */
15111 };
15112 
15113 static struct dev_ops dtrace_ops = {
15114 	DEVO_REV,		/* devo_rev */
15115 	0,			/* refcnt */
15116 	dtrace_info,		/* get_dev_info */
15117 	nulldev,		/* identify */
15118 	nulldev,		/* probe */
15119 	dtrace_attach,		/* attach */
15120 	dtrace_detach,		/* detach */
15121 	nodev,			/* reset */
15122 	&dtrace_cb_ops,		/* driver operations */
15123 	NULL,			/* bus operations */
15124 	nodev			/* dev power */
15125 };
15126 
15127 static struct modldrv modldrv = {
15128 	&mod_driverops,		/* module type (this is a pseudo driver) */
15129 	"Dynamic Tracing",	/* name of module */
15130 	&dtrace_ops,		/* driver ops */
15131 };
15132 
15133 static struct modlinkage modlinkage = {
15134 	MODREV_1,
15135 	(void *)&modldrv,
15136 	NULL
15137 };
15138 
15139 int
15140 _init(void)
15141 {
15142 	return (mod_install(&modlinkage));
15143 }
15144 
15145 int
15146 _info(struct modinfo *modinfop)
15147 {
15148 	return (mod_info(&modlinkage, modinfop));
15149 }
15150 
15151 int
15152 _fini(void)
15153 {
15154 	return (mod_remove(&modlinkage));
15155 }
15156