xref: /illumos-gate/usr/src/uts/common/dtrace/dtrace.c (revision bea83d026ee1bd1b2a2419e1d0232f107a5d7d9b)
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 2007 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 #include <sys/socket.h>
95 #include <netinet/in.h>
96 
97 /*
98  * DTrace Tunable Variables
99  *
100  * The following variables may be tuned by adding a line to /etc/system that
101  * includes both the name of the DTrace module ("dtrace") and the name of the
102  * variable.  For example:
103  *
104  *   set dtrace:dtrace_destructive_disallow = 1
105  *
106  * In general, the only variables that one should be tuning this way are those
107  * that affect system-wide DTrace behavior, and for which the default behavior
108  * is undesirable.  Most of these variables are tunable on a per-consumer
109  * basis using DTrace options, and need not be tuned on a system-wide basis.
110  * When tuning these variables, avoid pathological values; while some attempt
111  * is made to verify the integrity of these variables, they are not considered
112  * part of the supported interface to DTrace, and they are therefore not
113  * checked comprehensively.  Further, these variables should not be tuned
114  * dynamically via "mdb -kw" or other means; they should only be tuned via
115  * /etc/system.
116  */
117 int		dtrace_destructive_disallow = 0;
118 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
119 size_t		dtrace_difo_maxsize = (256 * 1024);
120 dtrace_optval_t	dtrace_dof_maxsize = (256 * 1024);
121 size_t		dtrace_global_maxsize = (16 * 1024);
122 size_t		dtrace_actions_max = (16 * 1024);
123 size_t		dtrace_retain_max = 1024;
124 dtrace_optval_t	dtrace_helper_actions_max = 32;
125 dtrace_optval_t	dtrace_helper_providers_max = 32;
126 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
127 size_t		dtrace_strsize_default = 256;
128 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
129 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
130 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
131 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
132 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
133 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
134 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
135 dtrace_optval_t	dtrace_nspec_default = 1;
136 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
137 dtrace_optval_t dtrace_stackframes_default = 20;
138 dtrace_optval_t dtrace_ustackframes_default = 20;
139 dtrace_optval_t dtrace_jstackframes_default = 50;
140 dtrace_optval_t dtrace_jstackstrsize_default = 512;
141 int		dtrace_msgdsize_max = 128;
142 hrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
143 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
144 int		dtrace_devdepth_max = 32;
145 int		dtrace_err_verbose;
146 hrtime_t	dtrace_deadman_interval = NANOSEC;
147 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
148 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
149 
150 /*
151  * DTrace External Variables
152  *
153  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
154  * available to DTrace consumers via the backtick (`) syntax.  One of these,
155  * dtrace_zero, is made deliberately so:  it is provided as a source of
156  * well-known, zero-filled memory.  While this variable is not documented,
157  * it is used by some translators as an implementation detail.
158  */
159 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
160 
161 /*
162  * DTrace Internal Variables
163  */
164 static dev_info_t	*dtrace_devi;		/* device info */
165 static vmem_t		*dtrace_arena;		/* probe ID arena */
166 static vmem_t		*dtrace_minor;		/* minor number arena */
167 static taskq_t		*dtrace_taskq;		/* task queue */
168 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
169 static int		dtrace_nprobes;		/* number of probes */
170 static dtrace_provider_t *dtrace_provider;	/* provider list */
171 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
172 static int		dtrace_opens;		/* number of opens */
173 static int		dtrace_helpers;		/* number of helpers */
174 static void		*dtrace_softstate;	/* softstate pointer */
175 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
176 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
177 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
178 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
179 static int		dtrace_toxranges;	/* number of toxic ranges */
180 static int		dtrace_toxranges_max;	/* size of toxic range array */
181 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
182 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
183 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
184 static kthread_t	*dtrace_panicked;	/* panicking thread */
185 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
186 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
187 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
188 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
189 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
190 
191 /*
192  * DTrace Locking
193  * DTrace is protected by three (relatively coarse-grained) locks:
194  *
195  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
196  *     including enabling state, probes, ECBs, consumer state, helper state,
197  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
198  *     probe context is lock-free -- synchronization is handled via the
199  *     dtrace_sync() cross call mechanism.
200  *
201  * (2) dtrace_provider_lock is required when manipulating provider state, or
202  *     when provider state must be held constant.
203  *
204  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
205  *     when meta provider state must be held constant.
206  *
207  * The lock ordering between these three locks is dtrace_meta_lock before
208  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
209  * several places where dtrace_provider_lock is held by the framework as it
210  * calls into the providers -- which then call back into the framework,
211  * grabbing dtrace_lock.)
212  *
213  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
214  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
215  * role as a coarse-grained lock; it is acquired before both of these locks.
216  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
217  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
218  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
219  * acquired _between_ dtrace_provider_lock and dtrace_lock.
220  */
221 static kmutex_t		dtrace_lock;		/* probe state lock */
222 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
223 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
224 
225 /*
226  * DTrace Provider Variables
227  *
228  * These are the variables relating to DTrace as a provider (that is, the
229  * provider of the BEGIN, END, and ERROR probes).
230  */
231 static dtrace_pattr_t	dtrace_provider_attr = {
232 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
233 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
234 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
235 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
236 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
237 };
238 
239 static void
240 dtrace_nullop(void)
241 {}
242 
243 static dtrace_pops_t	dtrace_provider_ops = {
244 	(void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
245 	(void (*)(void *, struct modctl *))dtrace_nullop,
246 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
247 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
248 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
249 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
250 	NULL,
251 	NULL,
252 	NULL,
253 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
254 };
255 
256 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
257 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
258 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
259 
260 /*
261  * DTrace Helper Tracing Variables
262  */
263 uint32_t dtrace_helptrace_next = 0;
264 uint32_t dtrace_helptrace_nlocals;
265 char	*dtrace_helptrace_buffer;
266 int	dtrace_helptrace_bufsize = 512 * 1024;
267 
268 #ifdef DEBUG
269 int	dtrace_helptrace_enabled = 1;
270 #else
271 int	dtrace_helptrace_enabled = 0;
272 #endif
273 
274 /*
275  * DTrace Error Hashing
276  *
277  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
278  * table.  This is very useful for checking coverage of tests that are
279  * expected to induce DIF or DOF processing errors, and may be useful for
280  * debugging problems in the DIF code generator or in DOF generation .  The
281  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
282  */
283 #ifdef DEBUG
284 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
285 static const char *dtrace_errlast;
286 static kthread_t *dtrace_errthread;
287 static kmutex_t dtrace_errlock;
288 #endif
289 
290 /*
291  * DTrace Macros and Constants
292  *
293  * These are various macros that are useful in various spots in the
294  * implementation, along with a few random constants that have no meaning
295  * outside of the implementation.  There is no real structure to this cpp
296  * mishmash -- but is there ever?
297  */
298 #define	DTRACE_HASHSTR(hash, probe)	\
299 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
300 
301 #define	DTRACE_HASHNEXT(hash, probe)	\
302 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
303 
304 #define	DTRACE_HASHPREV(hash, probe)	\
305 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
306 
307 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
308 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
309 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
310 
311 #define	DTRACE_AGGHASHSIZE_SLEW		17
312 
313 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
314 
315 /*
316  * The key for a thread-local variable consists of the lower 61 bits of the
317  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
318  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
319  * equal to a variable identifier.  This is necessary (but not sufficient) to
320  * assure that global associative arrays never collide with thread-local
321  * variables.  To guarantee that they cannot collide, we must also define the
322  * order for keying dynamic variables.  That order is:
323  *
324  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
325  *
326  * Because the variable-key and the tls-key are in orthogonal spaces, there is
327  * no way for a global variable key signature to match a thread-local key
328  * signature.
329  */
330 #define	DTRACE_TLS_THRKEY(where) { \
331 	uint_t intr = 0; \
332 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
333 	for (; actv; actv >>= 1) \
334 		intr++; \
335 	ASSERT(intr < (1 << 3)); \
336 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
337 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
338 }
339 
340 #define	DT_BSWAP_8(x)	((x) & 0xff)
341 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
342 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
343 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
344 
345 #define	DTRACE_STORE(type, tomax, offset, what) \
346 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
347 
348 #ifndef __i386
349 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
350 	if (addr & (size - 1)) {					\
351 		*flags |= CPU_DTRACE_BADALIGN;				\
352 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
353 		return (0);						\
354 	}
355 #else
356 #define	DTRACE_ALIGNCHECK(addr, size, flags)
357 #endif
358 
359 /*
360  * Test whether a range of memory starting at testaddr of size testsz falls
361  * within the range of memory described by addr, sz.  We take care to avoid
362  * problems with overflow and underflow of the unsigned quantities, and
363  * disallow all negative sizes.  Ranges of size 0 are allowed.
364  */
365 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
366 	((testaddr) - (baseaddr) < (basesz) && \
367 	(testaddr) + (testsz) - (baseaddr) <= (basesz) && \
368 	(testaddr) + (testsz) >= (testaddr))
369 
370 /*
371  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
372  * alloc_sz on the righthand side of the comparison in order to avoid overflow
373  * or underflow in the comparison with it.  This is simpler than the INRANGE
374  * check above, because we know that the dtms_scratch_ptr is valid in the
375  * range.  Allocations of size zero are allowed.
376  */
377 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
378 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
379 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
380 
381 #define	DTRACE_LOADFUNC(bits)						\
382 /*CSTYLED*/								\
383 uint##bits##_t								\
384 dtrace_load##bits(uintptr_t addr)					\
385 {									\
386 	size_t size = bits / NBBY;					\
387 	/*CSTYLED*/							\
388 	uint##bits##_t rval;						\
389 	int i;								\
390 	volatile uint16_t *flags = (volatile uint16_t *)		\
391 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
392 									\
393 	DTRACE_ALIGNCHECK(addr, size, flags);				\
394 									\
395 	for (i = 0; i < dtrace_toxranges; i++) {			\
396 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
397 			continue;					\
398 									\
399 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
400 			continue;					\
401 									\
402 		/*							\
403 		 * This address falls within a toxic region; return 0.	\
404 		 */							\
405 		*flags |= CPU_DTRACE_BADADDR;				\
406 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
407 		return (0);						\
408 	}								\
409 									\
410 	*flags |= CPU_DTRACE_NOFAULT;					\
411 	/*CSTYLED*/							\
412 	rval = *((volatile uint##bits##_t *)addr);			\
413 	*flags &= ~CPU_DTRACE_NOFAULT;					\
414 									\
415 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
416 }
417 
418 #ifdef _LP64
419 #define	dtrace_loadptr	dtrace_load64
420 #else
421 #define	dtrace_loadptr	dtrace_load32
422 #endif
423 
424 #define	DTRACE_DYNHASH_FREE	0
425 #define	DTRACE_DYNHASH_SINK	1
426 #define	DTRACE_DYNHASH_VALID	2
427 
428 #define	DTRACE_MATCH_NEXT	0
429 #define	DTRACE_MATCH_DONE	1
430 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
431 #define	DTRACE_STATE_ALIGN	64
432 
433 #define	DTRACE_FLAGS2FLT(flags)						\
434 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
435 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
436 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
437 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
438 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
439 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
440 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
441 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
442 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
443 	DTRACEFLT_UNKNOWN)
444 
445 #define	DTRACEACT_ISSTRING(act)						\
446 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
447 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
448 
449 static size_t dtrace_strlen(const char *, size_t);
450 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
451 static void dtrace_enabling_provide(dtrace_provider_t *);
452 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
453 static void dtrace_enabling_matchall(void);
454 static dtrace_state_t *dtrace_anon_grab(void);
455 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
456     dtrace_state_t *, uint64_t, uint64_t);
457 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
458 static void dtrace_buffer_drop(dtrace_buffer_t *);
459 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
460     dtrace_state_t *, dtrace_mstate_t *);
461 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
462     dtrace_optval_t);
463 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
464 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
465 
466 /*
467  * DTrace Probe Context Functions
468  *
469  * These functions are called from probe context.  Because probe context is
470  * any context in which C may be called, arbitrarily locks may be held,
471  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
472  * As a result, functions called from probe context may only call other DTrace
473  * support functions -- they may not interact at all with the system at large.
474  * (Note that the ASSERT macro is made probe-context safe by redefining it in
475  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
476  * loads are to be performed from probe context, they _must_ be in terms of
477  * the safe dtrace_load*() variants.
478  *
479  * Some functions in this block are not actually called from probe context;
480  * for these functions, there will be a comment above the function reading
481  * "Note:  not called from probe context."
482  */
483 void
484 dtrace_panic(const char *format, ...)
485 {
486 	va_list alist;
487 
488 	va_start(alist, format);
489 	dtrace_vpanic(format, alist);
490 	va_end(alist);
491 }
492 
493 int
494 dtrace_assfail(const char *a, const char *f, int l)
495 {
496 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
497 
498 	/*
499 	 * We just need something here that even the most clever compiler
500 	 * cannot optimize away.
501 	 */
502 	return (a[(uintptr_t)f]);
503 }
504 
505 /*
506  * Atomically increment a specified error counter from probe context.
507  */
508 static void
509 dtrace_error(uint32_t *counter)
510 {
511 	/*
512 	 * Most counters stored to in probe context are per-CPU counters.
513 	 * However, there are some error conditions that are sufficiently
514 	 * arcane that they don't merit per-CPU storage.  If these counters
515 	 * are incremented concurrently on different CPUs, scalability will be
516 	 * adversely affected -- but we don't expect them to be white-hot in a
517 	 * correctly constructed enabling...
518 	 */
519 	uint32_t oval, nval;
520 
521 	do {
522 		oval = *counter;
523 
524 		if ((nval = oval + 1) == 0) {
525 			/*
526 			 * If the counter would wrap, set it to 1 -- assuring
527 			 * that the counter is never zero when we have seen
528 			 * errors.  (The counter must be 32-bits because we
529 			 * aren't guaranteed a 64-bit compare&swap operation.)
530 			 * To save this code both the infamy of being fingered
531 			 * by a priggish news story and the indignity of being
532 			 * the target of a neo-puritan witch trial, we're
533 			 * carefully avoiding any colorful description of the
534 			 * likelihood of this condition -- but suffice it to
535 			 * say that it is only slightly more likely than the
536 			 * overflow of predicate cache IDs, as discussed in
537 			 * dtrace_predicate_create().
538 			 */
539 			nval = 1;
540 		}
541 	} while (dtrace_cas32(counter, oval, nval) != oval);
542 }
543 
544 /*
545  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
546  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
547  */
548 DTRACE_LOADFUNC(8)
549 DTRACE_LOADFUNC(16)
550 DTRACE_LOADFUNC(32)
551 DTRACE_LOADFUNC(64)
552 
553 static int
554 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
555 {
556 	if (dest < mstate->dtms_scratch_base)
557 		return (0);
558 
559 	if (dest + size < dest)
560 		return (0);
561 
562 	if (dest + size > mstate->dtms_scratch_ptr)
563 		return (0);
564 
565 	return (1);
566 }
567 
568 static int
569 dtrace_canstore_statvar(uint64_t addr, size_t sz,
570     dtrace_statvar_t **svars, int nsvars)
571 {
572 	int i;
573 
574 	for (i = 0; i < nsvars; i++) {
575 		dtrace_statvar_t *svar = svars[i];
576 
577 		if (svar == NULL || svar->dtsv_size == 0)
578 			continue;
579 
580 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
581 			return (1);
582 	}
583 
584 	return (0);
585 }
586 
587 /*
588  * Check to see if the address is within a memory region to which a store may
589  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
590  * region.  The caller of dtrace_canstore() is responsible for performing any
591  * alignment checks that are needed before stores are actually executed.
592  */
593 static int
594 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
595     dtrace_vstate_t *vstate)
596 {
597 	/*
598 	 * First, check to see if the address is in scratch space...
599 	 */
600 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
601 	    mstate->dtms_scratch_size))
602 		return (1);
603 
604 	/*
605 	 * Now check to see if it's a dynamic variable.  This check will pick
606 	 * up both thread-local variables and any global dynamically-allocated
607 	 * variables.
608 	 */
609 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
610 	    vstate->dtvs_dynvars.dtds_size)) {
611 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
612 		uintptr_t base = (uintptr_t)dstate->dtds_base +
613 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
614 		uintptr_t chunkoffs;
615 
616 		/*
617 		 * Before we assume that we can store here, we need to make
618 		 * sure that it isn't in our metadata -- storing to our
619 		 * dynamic variable metadata would corrupt our state.  For
620 		 * the range to not include any dynamic variable metadata,
621 		 * it must:
622 		 *
623 		 *	(1) Start above the hash table that is at the base of
624 		 *	the dynamic variable space
625 		 *
626 		 *	(2) Have a starting chunk offset that is beyond the
627 		 *	dtrace_dynvar_t that is at the base of every chunk
628 		 *
629 		 *	(3) Not span a chunk boundary
630 		 *
631 		 */
632 		if (addr < base)
633 			return (0);
634 
635 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
636 
637 		if (chunkoffs < sizeof (dtrace_dynvar_t))
638 			return (0);
639 
640 		if (chunkoffs + sz > dstate->dtds_chunksize)
641 			return (0);
642 
643 		return (1);
644 	}
645 
646 	/*
647 	 * Finally, check the static local and global variables.  These checks
648 	 * take the longest, so we perform them last.
649 	 */
650 	if (dtrace_canstore_statvar(addr, sz,
651 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
652 		return (1);
653 
654 	if (dtrace_canstore_statvar(addr, sz,
655 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
656 		return (1);
657 
658 	return (0);
659 }
660 
661 
662 /*
663  * Convenience routine to check to see if the address is within a memory
664  * region in which a load may be issued given the user's privilege level;
665  * if not, it sets the appropriate error flags and loads 'addr' into the
666  * illegal value slot.
667  *
668  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
669  * appropriate memory access protection.
670  */
671 static int
672 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
673     dtrace_vstate_t *vstate)
674 {
675 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
676 
677 	/*
678 	 * If we hold the privilege to read from kernel memory, then
679 	 * everything is readable.
680 	 */
681 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
682 		return (1);
683 
684 	/*
685 	 * You can obviously read that which you can store.
686 	 */
687 	if (dtrace_canstore(addr, sz, mstate, vstate))
688 		return (1);
689 
690 	/*
691 	 * We're allowed to read from our own string table.
692 	 */
693 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
694 	    mstate->dtms_difo->dtdo_strlen))
695 		return (1);
696 
697 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
698 	*illval = addr;
699 	return (0);
700 }
701 
702 /*
703  * Convenience routine to check to see if a given string is within a memory
704  * region in which a load may be issued given the user's privilege level;
705  * this exists so that we don't need to issue unnecessary dtrace_strlen()
706  * calls in the event that the user has all privileges.
707  */
708 static int
709 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
710     dtrace_vstate_t *vstate)
711 {
712 	size_t strsz;
713 
714 	/*
715 	 * If we hold the privilege to read from kernel memory, then
716 	 * everything is readable.
717 	 */
718 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
719 		return (1);
720 
721 	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
722 	if (dtrace_canload(addr, strsz, mstate, vstate))
723 		return (1);
724 
725 	return (0);
726 }
727 
728 /*
729  * Convenience routine to check to see if a given variable is within a memory
730  * region in which a load may be issued given the user's privilege level.
731  */
732 static int
733 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
734     dtrace_vstate_t *vstate)
735 {
736 	size_t sz;
737 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
738 
739 	/*
740 	 * If we hold the privilege to read from kernel memory, then
741 	 * everything is readable.
742 	 */
743 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
744 		return (1);
745 
746 	if (type->dtdt_kind == DIF_TYPE_STRING)
747 		sz = dtrace_strlen(src,
748 		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
749 	else
750 		sz = type->dtdt_size;
751 
752 	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
753 }
754 
755 /*
756  * Compare two strings using safe loads.
757  */
758 static int
759 dtrace_strncmp(char *s1, char *s2, size_t limit)
760 {
761 	uint8_t c1, c2;
762 	volatile uint16_t *flags;
763 
764 	if (s1 == s2 || limit == 0)
765 		return (0);
766 
767 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
768 
769 	do {
770 		if (s1 == NULL) {
771 			c1 = '\0';
772 		} else {
773 			c1 = dtrace_load8((uintptr_t)s1++);
774 		}
775 
776 		if (s2 == NULL) {
777 			c2 = '\0';
778 		} else {
779 			c2 = dtrace_load8((uintptr_t)s2++);
780 		}
781 
782 		if (c1 != c2)
783 			return (c1 - c2);
784 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
785 
786 	return (0);
787 }
788 
789 /*
790  * Compute strlen(s) for a string using safe memory accesses.  The additional
791  * len parameter is used to specify a maximum length to ensure completion.
792  */
793 static size_t
794 dtrace_strlen(const char *s, size_t lim)
795 {
796 	uint_t len;
797 
798 	for (len = 0; len != lim; len++) {
799 		if (dtrace_load8((uintptr_t)s++) == '\0')
800 			break;
801 	}
802 
803 	return (len);
804 }
805 
806 /*
807  * Check if an address falls within a toxic region.
808  */
809 static int
810 dtrace_istoxic(uintptr_t kaddr, size_t size)
811 {
812 	uintptr_t taddr, tsize;
813 	int i;
814 
815 	for (i = 0; i < dtrace_toxranges; i++) {
816 		taddr = dtrace_toxrange[i].dtt_base;
817 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
818 
819 		if (kaddr - taddr < tsize) {
820 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
821 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
822 			return (1);
823 		}
824 
825 		if (taddr - kaddr < size) {
826 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
827 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
828 			return (1);
829 		}
830 	}
831 
832 	return (0);
833 }
834 
835 /*
836  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
837  * memory specified by the DIF program.  The dst is assumed to be safe memory
838  * that we can store to directly because it is managed by DTrace.  As with
839  * standard bcopy, overlapping copies are handled properly.
840  */
841 static void
842 dtrace_bcopy(const void *src, void *dst, size_t len)
843 {
844 	if (len != 0) {
845 		uint8_t *s1 = dst;
846 		const uint8_t *s2 = src;
847 
848 		if (s1 <= s2) {
849 			do {
850 				*s1++ = dtrace_load8((uintptr_t)s2++);
851 			} while (--len != 0);
852 		} else {
853 			s2 += len;
854 			s1 += len;
855 
856 			do {
857 				*--s1 = dtrace_load8((uintptr_t)--s2);
858 			} while (--len != 0);
859 		}
860 	}
861 }
862 
863 /*
864  * Copy src to dst using safe memory accesses, up to either the specified
865  * length, or the point that a nul byte is encountered.  The src is assumed to
866  * be unsafe memory specified by the DIF program.  The dst is assumed to be
867  * safe memory that we can store to directly because it is managed by DTrace.
868  * Unlike dtrace_bcopy(), overlapping regions are not handled.
869  */
870 static void
871 dtrace_strcpy(const void *src, void *dst, size_t len)
872 {
873 	if (len != 0) {
874 		uint8_t *s1 = dst, c;
875 		const uint8_t *s2 = src;
876 
877 		do {
878 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
879 		} while (--len != 0 && c != '\0');
880 	}
881 }
882 
883 /*
884  * Copy src to dst, deriving the size and type from the specified (BYREF)
885  * variable type.  The src is assumed to be unsafe memory specified by the DIF
886  * program.  The dst is assumed to be DTrace variable memory that is of the
887  * specified type; we assume that we can store to directly.
888  */
889 static void
890 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
891 {
892 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
893 
894 	if (type->dtdt_kind == DIF_TYPE_STRING) {
895 		dtrace_strcpy(src, dst, type->dtdt_size);
896 	} else {
897 		dtrace_bcopy(src, dst, type->dtdt_size);
898 	}
899 }
900 
901 /*
902  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
903  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
904  * safe memory that we can access directly because it is managed by DTrace.
905  */
906 static int
907 dtrace_bcmp(const void *s1, const void *s2, size_t len)
908 {
909 	volatile uint16_t *flags;
910 
911 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
912 
913 	if (s1 == s2)
914 		return (0);
915 
916 	if (s1 == NULL || s2 == NULL)
917 		return (1);
918 
919 	if (s1 != s2 && len != 0) {
920 		const uint8_t *ps1 = s1;
921 		const uint8_t *ps2 = s2;
922 
923 		do {
924 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
925 				return (1);
926 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
927 	}
928 	return (0);
929 }
930 
931 /*
932  * Zero the specified region using a simple byte-by-byte loop.  Note that this
933  * is for safe DTrace-managed memory only.
934  */
935 static void
936 dtrace_bzero(void *dst, size_t len)
937 {
938 	uchar_t *cp;
939 
940 	for (cp = dst; len != 0; len--)
941 		*cp++ = 0;
942 }
943 
944 /*
945  * This privilege check should be used by actions and subroutines to
946  * verify that the user credentials of the process that enabled the
947  * invoking ECB match the target credentials
948  */
949 static int
950 dtrace_priv_proc_common_user(dtrace_state_t *state)
951 {
952 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
953 
954 	/*
955 	 * We should always have a non-NULL state cred here, since if cred
956 	 * is null (anonymous tracing), we fast-path bypass this routine.
957 	 */
958 	ASSERT(s_cr != NULL);
959 
960 	if ((cr = CRED()) != NULL &&
961 	    s_cr->cr_uid == cr->cr_uid &&
962 	    s_cr->cr_uid == cr->cr_ruid &&
963 	    s_cr->cr_uid == cr->cr_suid &&
964 	    s_cr->cr_gid == cr->cr_gid &&
965 	    s_cr->cr_gid == cr->cr_rgid &&
966 	    s_cr->cr_gid == cr->cr_sgid)
967 		return (1);
968 
969 	return (0);
970 }
971 
972 /*
973  * This privilege check should be used by actions and subroutines to
974  * verify that the zone of the process that enabled the invoking ECB
975  * matches the target credentials
976  */
977 static int
978 dtrace_priv_proc_common_zone(dtrace_state_t *state)
979 {
980 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
981 
982 	/*
983 	 * We should always have a non-NULL state cred here, since if cred
984 	 * is null (anonymous tracing), we fast-path bypass this routine.
985 	 */
986 	ASSERT(s_cr != NULL);
987 
988 	if ((cr = CRED()) != NULL &&
989 	    s_cr->cr_zone == cr->cr_zone)
990 		return (1);
991 
992 	return (0);
993 }
994 
995 /*
996  * This privilege check should be used by actions and subroutines to
997  * verify that the process has not setuid or changed credentials.
998  */
999 static int
1000 dtrace_priv_proc_common_nocd()
1001 {
1002 	proc_t *proc;
1003 
1004 	if ((proc = ttoproc(curthread)) != NULL &&
1005 	    !(proc->p_flag & SNOCD))
1006 		return (1);
1007 
1008 	return (0);
1009 }
1010 
1011 static int
1012 dtrace_priv_proc_destructive(dtrace_state_t *state)
1013 {
1014 	int action = state->dts_cred.dcr_action;
1015 
1016 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1017 	    dtrace_priv_proc_common_zone(state) == 0)
1018 		goto bad;
1019 
1020 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1021 	    dtrace_priv_proc_common_user(state) == 0)
1022 		goto bad;
1023 
1024 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1025 	    dtrace_priv_proc_common_nocd() == 0)
1026 		goto bad;
1027 
1028 	return (1);
1029 
1030 bad:
1031 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1032 
1033 	return (0);
1034 }
1035 
1036 static int
1037 dtrace_priv_proc_control(dtrace_state_t *state)
1038 {
1039 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1040 		return (1);
1041 
1042 	if (dtrace_priv_proc_common_zone(state) &&
1043 	    dtrace_priv_proc_common_user(state) &&
1044 	    dtrace_priv_proc_common_nocd())
1045 		return (1);
1046 
1047 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1048 
1049 	return (0);
1050 }
1051 
1052 static int
1053 dtrace_priv_proc(dtrace_state_t *state)
1054 {
1055 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1056 		return (1);
1057 
1058 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1059 
1060 	return (0);
1061 }
1062 
1063 static int
1064 dtrace_priv_kernel(dtrace_state_t *state)
1065 {
1066 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1067 		return (1);
1068 
1069 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1070 
1071 	return (0);
1072 }
1073 
1074 static int
1075 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1076 {
1077 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1078 		return (1);
1079 
1080 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1081 
1082 	return (0);
1083 }
1084 
1085 /*
1086  * Note:  not called from probe context.  This function is called
1087  * asynchronously (and at a regular interval) from outside of probe context to
1088  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1089  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1090  */
1091 void
1092 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1093 {
1094 	dtrace_dynvar_t *dirty;
1095 	dtrace_dstate_percpu_t *dcpu;
1096 	int i, work = 0;
1097 
1098 	for (i = 0; i < NCPU; i++) {
1099 		dcpu = &dstate->dtds_percpu[i];
1100 
1101 		ASSERT(dcpu->dtdsc_rinsing == NULL);
1102 
1103 		/*
1104 		 * If the dirty list is NULL, there is no dirty work to do.
1105 		 */
1106 		if (dcpu->dtdsc_dirty == NULL)
1107 			continue;
1108 
1109 		/*
1110 		 * If the clean list is non-NULL, then we're not going to do
1111 		 * any work for this CPU -- it means that there has not been
1112 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1113 		 * since the last time we cleaned house.
1114 		 */
1115 		if (dcpu->dtdsc_clean != NULL)
1116 			continue;
1117 
1118 		work = 1;
1119 
1120 		/*
1121 		 * Atomically move the dirty list aside.
1122 		 */
1123 		do {
1124 			dirty = dcpu->dtdsc_dirty;
1125 
1126 			/*
1127 			 * Before we zap the dirty list, set the rinsing list.
1128 			 * (This allows for a potential assertion in
1129 			 * dtrace_dynvar():  if a free dynamic variable appears
1130 			 * on a hash chain, either the dirty list or the
1131 			 * rinsing list for some CPU must be non-NULL.)
1132 			 */
1133 			dcpu->dtdsc_rinsing = dirty;
1134 			dtrace_membar_producer();
1135 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1136 		    dirty, NULL) != dirty);
1137 	}
1138 
1139 	if (!work) {
1140 		/*
1141 		 * We have no work to do; we can simply return.
1142 		 */
1143 		return;
1144 	}
1145 
1146 	dtrace_sync();
1147 
1148 	for (i = 0; i < NCPU; i++) {
1149 		dcpu = &dstate->dtds_percpu[i];
1150 
1151 		if (dcpu->dtdsc_rinsing == NULL)
1152 			continue;
1153 
1154 		/*
1155 		 * We are now guaranteed that no hash chain contains a pointer
1156 		 * into this dirty list; we can make it clean.
1157 		 */
1158 		ASSERT(dcpu->dtdsc_clean == NULL);
1159 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1160 		dcpu->dtdsc_rinsing = NULL;
1161 	}
1162 
1163 	/*
1164 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1165 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1166 	 * This prevents a race whereby a CPU incorrectly decides that
1167 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1168 	 * after dtrace_dynvar_clean() has completed.
1169 	 */
1170 	dtrace_sync();
1171 
1172 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1173 }
1174 
1175 /*
1176  * Depending on the value of the op parameter, this function looks-up,
1177  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1178  * allocation is requested, this function will return a pointer to a
1179  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1180  * variable can be allocated.  If NULL is returned, the appropriate counter
1181  * will be incremented.
1182  */
1183 dtrace_dynvar_t *
1184 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1185     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1186     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1187 {
1188 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1189 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1190 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1191 	processorid_t me = CPU->cpu_id, cpu = me;
1192 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1193 	size_t bucket, ksize;
1194 	size_t chunksize = dstate->dtds_chunksize;
1195 	uintptr_t kdata, lock, nstate;
1196 	uint_t i;
1197 
1198 	ASSERT(nkeys != 0);
1199 
1200 	/*
1201 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1202 	 * algorithm.  For the by-value portions, we perform the algorithm in
1203 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1204 	 * bit, and seems to have only a minute effect on distribution.  For
1205 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1206 	 * over each referenced byte.  It's painful to do this, but it's much
1207 	 * better than pathological hash distribution.  The efficacy of the
1208 	 * hashing algorithm (and a comparison with other algorithms) may be
1209 	 * found by running the ::dtrace_dynstat MDB dcmd.
1210 	 */
1211 	for (i = 0; i < nkeys; i++) {
1212 		if (key[i].dttk_size == 0) {
1213 			uint64_t val = key[i].dttk_value;
1214 
1215 			hashval += (val >> 48) & 0xffff;
1216 			hashval += (hashval << 10);
1217 			hashval ^= (hashval >> 6);
1218 
1219 			hashval += (val >> 32) & 0xffff;
1220 			hashval += (hashval << 10);
1221 			hashval ^= (hashval >> 6);
1222 
1223 			hashval += (val >> 16) & 0xffff;
1224 			hashval += (hashval << 10);
1225 			hashval ^= (hashval >> 6);
1226 
1227 			hashval += val & 0xffff;
1228 			hashval += (hashval << 10);
1229 			hashval ^= (hashval >> 6);
1230 		} else {
1231 			/*
1232 			 * This is incredibly painful, but it beats the hell
1233 			 * out of the alternative.
1234 			 */
1235 			uint64_t j, size = key[i].dttk_size;
1236 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1237 
1238 			if (!dtrace_canload(base, size, mstate, vstate))
1239 				break;
1240 
1241 			for (j = 0; j < size; j++) {
1242 				hashval += dtrace_load8(base + j);
1243 				hashval += (hashval << 10);
1244 				hashval ^= (hashval >> 6);
1245 			}
1246 		}
1247 	}
1248 
1249 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1250 		return (NULL);
1251 
1252 	hashval += (hashval << 3);
1253 	hashval ^= (hashval >> 11);
1254 	hashval += (hashval << 15);
1255 
1256 	/*
1257 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1258 	 * comes out to be one of our two sentinel hash values.  If this
1259 	 * actually happens, we set the hashval to be a value known to be a
1260 	 * non-sentinel value.
1261 	 */
1262 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1263 		hashval = DTRACE_DYNHASH_VALID;
1264 
1265 	/*
1266 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1267 	 * important here, tricks can be pulled to reduce it.  (However, it's
1268 	 * critical that hash collisions be kept to an absolute minimum;
1269 	 * they're much more painful than a divide.)  It's better to have a
1270 	 * solution that generates few collisions and still keeps things
1271 	 * relatively simple.
1272 	 */
1273 	bucket = hashval % dstate->dtds_hashsize;
1274 
1275 	if (op == DTRACE_DYNVAR_DEALLOC) {
1276 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1277 
1278 		for (;;) {
1279 			while ((lock = *lockp) & 1)
1280 				continue;
1281 
1282 			if (dtrace_casptr((void *)lockp,
1283 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1284 				break;
1285 		}
1286 
1287 		dtrace_membar_producer();
1288 	}
1289 
1290 top:
1291 	prev = NULL;
1292 	lock = hash[bucket].dtdh_lock;
1293 
1294 	dtrace_membar_consumer();
1295 
1296 	start = hash[bucket].dtdh_chain;
1297 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1298 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1299 	    op != DTRACE_DYNVAR_DEALLOC));
1300 
1301 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1302 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1303 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1304 
1305 		if (dvar->dtdv_hashval != hashval) {
1306 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1307 				/*
1308 				 * We've reached the sink, and therefore the
1309 				 * end of the hash chain; we can kick out of
1310 				 * the loop knowing that we have seen a valid
1311 				 * snapshot of state.
1312 				 */
1313 				ASSERT(dvar->dtdv_next == NULL);
1314 				ASSERT(dvar == &dtrace_dynhash_sink);
1315 				break;
1316 			}
1317 
1318 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1319 				/*
1320 				 * We've gone off the rails:  somewhere along
1321 				 * the line, one of the members of this hash
1322 				 * chain was deleted.  Note that we could also
1323 				 * detect this by simply letting this loop run
1324 				 * to completion, as we would eventually hit
1325 				 * the end of the dirty list.  However, we
1326 				 * want to avoid running the length of the
1327 				 * dirty list unnecessarily (it might be quite
1328 				 * long), so we catch this as early as
1329 				 * possible by detecting the hash marker.  In
1330 				 * this case, we simply set dvar to NULL and
1331 				 * break; the conditional after the loop will
1332 				 * send us back to top.
1333 				 */
1334 				dvar = NULL;
1335 				break;
1336 			}
1337 
1338 			goto next;
1339 		}
1340 
1341 		if (dtuple->dtt_nkeys != nkeys)
1342 			goto next;
1343 
1344 		for (i = 0; i < nkeys; i++, dkey++) {
1345 			if (dkey->dttk_size != key[i].dttk_size)
1346 				goto next; /* size or type mismatch */
1347 
1348 			if (dkey->dttk_size != 0) {
1349 				if (dtrace_bcmp(
1350 				    (void *)(uintptr_t)key[i].dttk_value,
1351 				    (void *)(uintptr_t)dkey->dttk_value,
1352 				    dkey->dttk_size))
1353 					goto next;
1354 			} else {
1355 				if (dkey->dttk_value != key[i].dttk_value)
1356 					goto next;
1357 			}
1358 		}
1359 
1360 		if (op != DTRACE_DYNVAR_DEALLOC)
1361 			return (dvar);
1362 
1363 		ASSERT(dvar->dtdv_next == NULL ||
1364 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1365 
1366 		if (prev != NULL) {
1367 			ASSERT(hash[bucket].dtdh_chain != dvar);
1368 			ASSERT(start != dvar);
1369 			ASSERT(prev->dtdv_next == dvar);
1370 			prev->dtdv_next = dvar->dtdv_next;
1371 		} else {
1372 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1373 			    start, dvar->dtdv_next) != start) {
1374 				/*
1375 				 * We have failed to atomically swing the
1376 				 * hash table head pointer, presumably because
1377 				 * of a conflicting allocation on another CPU.
1378 				 * We need to reread the hash chain and try
1379 				 * again.
1380 				 */
1381 				goto top;
1382 			}
1383 		}
1384 
1385 		dtrace_membar_producer();
1386 
1387 		/*
1388 		 * Now set the hash value to indicate that it's free.
1389 		 */
1390 		ASSERT(hash[bucket].dtdh_chain != dvar);
1391 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1392 
1393 		dtrace_membar_producer();
1394 
1395 		/*
1396 		 * Set the next pointer to point at the dirty list, and
1397 		 * atomically swing the dirty pointer to the newly freed dvar.
1398 		 */
1399 		do {
1400 			next = dcpu->dtdsc_dirty;
1401 			dvar->dtdv_next = next;
1402 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1403 
1404 		/*
1405 		 * Finally, unlock this hash bucket.
1406 		 */
1407 		ASSERT(hash[bucket].dtdh_lock == lock);
1408 		ASSERT(lock & 1);
1409 		hash[bucket].dtdh_lock++;
1410 
1411 		return (NULL);
1412 next:
1413 		prev = dvar;
1414 		continue;
1415 	}
1416 
1417 	if (dvar == NULL) {
1418 		/*
1419 		 * If dvar is NULL, it is because we went off the rails:
1420 		 * one of the elements that we traversed in the hash chain
1421 		 * was deleted while we were traversing it.  In this case,
1422 		 * we assert that we aren't doing a dealloc (deallocs lock
1423 		 * the hash bucket to prevent themselves from racing with
1424 		 * one another), and retry the hash chain traversal.
1425 		 */
1426 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1427 		goto top;
1428 	}
1429 
1430 	if (op != DTRACE_DYNVAR_ALLOC) {
1431 		/*
1432 		 * If we are not to allocate a new variable, we want to
1433 		 * return NULL now.  Before we return, check that the value
1434 		 * of the lock word hasn't changed.  If it has, we may have
1435 		 * seen an inconsistent snapshot.
1436 		 */
1437 		if (op == DTRACE_DYNVAR_NOALLOC) {
1438 			if (hash[bucket].dtdh_lock != lock)
1439 				goto top;
1440 		} else {
1441 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1442 			ASSERT(hash[bucket].dtdh_lock == lock);
1443 			ASSERT(lock & 1);
1444 			hash[bucket].dtdh_lock++;
1445 		}
1446 
1447 		return (NULL);
1448 	}
1449 
1450 	/*
1451 	 * We need to allocate a new dynamic variable.  The size we need is the
1452 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1453 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1454 	 * the size of any referred-to data (dsize).  We then round the final
1455 	 * size up to the chunksize for allocation.
1456 	 */
1457 	for (ksize = 0, i = 0; i < nkeys; i++)
1458 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1459 
1460 	/*
1461 	 * This should be pretty much impossible, but could happen if, say,
1462 	 * strange DIF specified the tuple.  Ideally, this should be an
1463 	 * assertion and not an error condition -- but that requires that the
1464 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1465 	 * bullet-proof.  (That is, it must not be able to be fooled by
1466 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1467 	 * solving this would presumably not amount to solving the Halting
1468 	 * Problem -- but it still seems awfully hard.
1469 	 */
1470 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1471 	    ksize + dsize > chunksize) {
1472 		dcpu->dtdsc_drops++;
1473 		return (NULL);
1474 	}
1475 
1476 	nstate = DTRACE_DSTATE_EMPTY;
1477 
1478 	do {
1479 retry:
1480 		free = dcpu->dtdsc_free;
1481 
1482 		if (free == NULL) {
1483 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1484 			void *rval;
1485 
1486 			if (clean == NULL) {
1487 				/*
1488 				 * We're out of dynamic variable space on
1489 				 * this CPU.  Unless we have tried all CPUs,
1490 				 * we'll try to allocate from a different
1491 				 * CPU.
1492 				 */
1493 				switch (dstate->dtds_state) {
1494 				case DTRACE_DSTATE_CLEAN: {
1495 					void *sp = &dstate->dtds_state;
1496 
1497 					if (++cpu >= NCPU)
1498 						cpu = 0;
1499 
1500 					if (dcpu->dtdsc_dirty != NULL &&
1501 					    nstate == DTRACE_DSTATE_EMPTY)
1502 						nstate = DTRACE_DSTATE_DIRTY;
1503 
1504 					if (dcpu->dtdsc_rinsing != NULL)
1505 						nstate = DTRACE_DSTATE_RINSING;
1506 
1507 					dcpu = &dstate->dtds_percpu[cpu];
1508 
1509 					if (cpu != me)
1510 						goto retry;
1511 
1512 					(void) dtrace_cas32(sp,
1513 					    DTRACE_DSTATE_CLEAN, nstate);
1514 
1515 					/*
1516 					 * To increment the correct bean
1517 					 * counter, take another lap.
1518 					 */
1519 					goto retry;
1520 				}
1521 
1522 				case DTRACE_DSTATE_DIRTY:
1523 					dcpu->dtdsc_dirty_drops++;
1524 					break;
1525 
1526 				case DTRACE_DSTATE_RINSING:
1527 					dcpu->dtdsc_rinsing_drops++;
1528 					break;
1529 
1530 				case DTRACE_DSTATE_EMPTY:
1531 					dcpu->dtdsc_drops++;
1532 					break;
1533 				}
1534 
1535 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1536 				return (NULL);
1537 			}
1538 
1539 			/*
1540 			 * The clean list appears to be non-empty.  We want to
1541 			 * move the clean list to the free list; we start by
1542 			 * moving the clean pointer aside.
1543 			 */
1544 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1545 			    clean, NULL) != clean) {
1546 				/*
1547 				 * We are in one of two situations:
1548 				 *
1549 				 *  (a)	The clean list was switched to the
1550 				 *	free list by another CPU.
1551 				 *
1552 				 *  (b)	The clean list was added to by the
1553 				 *	cleansing cyclic.
1554 				 *
1555 				 * In either of these situations, we can
1556 				 * just reattempt the free list allocation.
1557 				 */
1558 				goto retry;
1559 			}
1560 
1561 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1562 
1563 			/*
1564 			 * Now we'll move the clean list to the free list.
1565 			 * It's impossible for this to fail:  the only way
1566 			 * the free list can be updated is through this
1567 			 * code path, and only one CPU can own the clean list.
1568 			 * Thus, it would only be possible for this to fail if
1569 			 * this code were racing with dtrace_dynvar_clean().
1570 			 * (That is, if dtrace_dynvar_clean() updated the clean
1571 			 * list, and we ended up racing to update the free
1572 			 * list.)  This race is prevented by the dtrace_sync()
1573 			 * in dtrace_dynvar_clean() -- which flushes the
1574 			 * owners of the clean lists out before resetting
1575 			 * the clean lists.
1576 			 */
1577 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1578 			ASSERT(rval == NULL);
1579 			goto retry;
1580 		}
1581 
1582 		dvar = free;
1583 		new_free = dvar->dtdv_next;
1584 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1585 
1586 	/*
1587 	 * We have now allocated a new chunk.  We copy the tuple keys into the
1588 	 * tuple array and copy any referenced key data into the data space
1589 	 * following the tuple array.  As we do this, we relocate dttk_value
1590 	 * in the final tuple to point to the key data address in the chunk.
1591 	 */
1592 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1593 	dvar->dtdv_data = (void *)(kdata + ksize);
1594 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
1595 
1596 	for (i = 0; i < nkeys; i++) {
1597 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1598 		size_t kesize = key[i].dttk_size;
1599 
1600 		if (kesize != 0) {
1601 			dtrace_bcopy(
1602 			    (const void *)(uintptr_t)key[i].dttk_value,
1603 			    (void *)kdata, kesize);
1604 			dkey->dttk_value = kdata;
1605 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1606 		} else {
1607 			dkey->dttk_value = key[i].dttk_value;
1608 		}
1609 
1610 		dkey->dttk_size = kesize;
1611 	}
1612 
1613 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1614 	dvar->dtdv_hashval = hashval;
1615 	dvar->dtdv_next = start;
1616 
1617 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1618 		return (dvar);
1619 
1620 	/*
1621 	 * The cas has failed.  Either another CPU is adding an element to
1622 	 * this hash chain, or another CPU is deleting an element from this
1623 	 * hash chain.  The simplest way to deal with both of these cases
1624 	 * (though not necessarily the most efficient) is to free our
1625 	 * allocated block and tail-call ourselves.  Note that the free is
1626 	 * to the dirty list and _not_ to the free list.  This is to prevent
1627 	 * races with allocators, above.
1628 	 */
1629 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1630 
1631 	dtrace_membar_producer();
1632 
1633 	do {
1634 		free = dcpu->dtdsc_dirty;
1635 		dvar->dtdv_next = free;
1636 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1637 
1638 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1639 }
1640 
1641 /*ARGSUSED*/
1642 static void
1643 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1644 {
1645 	if (nval < *oval)
1646 		*oval = nval;
1647 }
1648 
1649 /*ARGSUSED*/
1650 static void
1651 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1652 {
1653 	if (nval > *oval)
1654 		*oval = nval;
1655 }
1656 
1657 static void
1658 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1659 {
1660 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1661 	int64_t val = (int64_t)nval;
1662 
1663 	if (val < 0) {
1664 		for (i = 0; i < zero; i++) {
1665 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1666 				quanta[i] += incr;
1667 				return;
1668 			}
1669 		}
1670 	} else {
1671 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1672 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1673 				quanta[i - 1] += incr;
1674 				return;
1675 			}
1676 		}
1677 
1678 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1679 		return;
1680 	}
1681 
1682 	ASSERT(0);
1683 }
1684 
1685 static void
1686 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1687 {
1688 	uint64_t arg = *lquanta++;
1689 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1690 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1691 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1692 	int32_t val = (int32_t)nval, level;
1693 
1694 	ASSERT(step != 0);
1695 	ASSERT(levels != 0);
1696 
1697 	if (val < base) {
1698 		/*
1699 		 * This is an underflow.
1700 		 */
1701 		lquanta[0] += incr;
1702 		return;
1703 	}
1704 
1705 	level = (val - base) / step;
1706 
1707 	if (level < levels) {
1708 		lquanta[level + 1] += incr;
1709 		return;
1710 	}
1711 
1712 	/*
1713 	 * This is an overflow.
1714 	 */
1715 	lquanta[levels + 1] += incr;
1716 }
1717 
1718 /*ARGSUSED*/
1719 static void
1720 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
1721 {
1722 	data[0]++;
1723 	data[1] += nval;
1724 }
1725 
1726 /*ARGSUSED*/
1727 static void
1728 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
1729 {
1730 	*oval = *oval + 1;
1731 }
1732 
1733 /*ARGSUSED*/
1734 static void
1735 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
1736 {
1737 	*oval += nval;
1738 }
1739 
1740 /*
1741  * Aggregate given the tuple in the principal data buffer, and the aggregating
1742  * action denoted by the specified dtrace_aggregation_t.  The aggregation
1743  * buffer is specified as the buf parameter.  This routine does not return
1744  * failure; if there is no space in the aggregation buffer, the data will be
1745  * dropped, and a corresponding counter incremented.
1746  */
1747 static void
1748 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
1749     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
1750 {
1751 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
1752 	uint32_t i, ndx, size, fsize;
1753 	uint32_t align = sizeof (uint64_t) - 1;
1754 	dtrace_aggbuffer_t *agb;
1755 	dtrace_aggkey_t *key;
1756 	uint32_t hashval = 0, limit, isstr;
1757 	caddr_t tomax, data, kdata;
1758 	dtrace_actkind_t action;
1759 	dtrace_action_t *act;
1760 	uintptr_t offs;
1761 
1762 	if (buf == NULL)
1763 		return;
1764 
1765 	if (!agg->dtag_hasarg) {
1766 		/*
1767 		 * Currently, only quantize() and lquantize() take additional
1768 		 * arguments, and they have the same semantics:  an increment
1769 		 * value that defaults to 1 when not present.  If additional
1770 		 * aggregating actions take arguments, the setting of the
1771 		 * default argument value will presumably have to become more
1772 		 * sophisticated...
1773 		 */
1774 		arg = 1;
1775 	}
1776 
1777 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
1778 	size = rec->dtrd_offset - agg->dtag_base;
1779 	fsize = size + rec->dtrd_size;
1780 
1781 	ASSERT(dbuf->dtb_tomax != NULL);
1782 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
1783 
1784 	if ((tomax = buf->dtb_tomax) == NULL) {
1785 		dtrace_buffer_drop(buf);
1786 		return;
1787 	}
1788 
1789 	/*
1790 	 * The metastructure is always at the bottom of the buffer.
1791 	 */
1792 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
1793 	    sizeof (dtrace_aggbuffer_t));
1794 
1795 	if (buf->dtb_offset == 0) {
1796 		/*
1797 		 * We just kludge up approximately 1/8th of the size to be
1798 		 * buckets.  If this guess ends up being routinely
1799 		 * off-the-mark, we may need to dynamically readjust this
1800 		 * based on past performance.
1801 		 */
1802 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
1803 
1804 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
1805 		    (uintptr_t)tomax || hashsize == 0) {
1806 			/*
1807 			 * We've been given a ludicrously small buffer;
1808 			 * increment our drop count and leave.
1809 			 */
1810 			dtrace_buffer_drop(buf);
1811 			return;
1812 		}
1813 
1814 		/*
1815 		 * And now, a pathetic attempt to try to get a an odd (or
1816 		 * perchance, a prime) hash size for better hash distribution.
1817 		 */
1818 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
1819 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
1820 
1821 		agb->dtagb_hashsize = hashsize;
1822 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
1823 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
1824 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
1825 
1826 		for (i = 0; i < agb->dtagb_hashsize; i++)
1827 			agb->dtagb_hash[i] = NULL;
1828 	}
1829 
1830 	ASSERT(agg->dtag_first != NULL);
1831 	ASSERT(agg->dtag_first->dta_intuple);
1832 
1833 	/*
1834 	 * Calculate the hash value based on the key.  Note that we _don't_
1835 	 * include the aggid in the hashing (but we will store it as part of
1836 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
1837 	 * algorithm: a simple, quick algorithm that has no known funnels, and
1838 	 * gets good distribution in practice.  The efficacy of the hashing
1839 	 * algorithm (and a comparison with other algorithms) may be found by
1840 	 * running the ::dtrace_aggstat MDB dcmd.
1841 	 */
1842 	for (act = agg->dtag_first; act->dta_intuple; 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 			hashval += data[i];
1850 			hashval += (hashval << 10);
1851 			hashval ^= (hashval >> 6);
1852 
1853 			if (isstr && data[i] == '\0')
1854 				break;
1855 		}
1856 	}
1857 
1858 	hashval += (hashval << 3);
1859 	hashval ^= (hashval >> 11);
1860 	hashval += (hashval << 15);
1861 
1862 	/*
1863 	 * Yes, the divide here is expensive -- but it's generally the least
1864 	 * of the performance issues given the amount of data that we iterate
1865 	 * over to compute hash values, compare data, etc.
1866 	 */
1867 	ndx = hashval % agb->dtagb_hashsize;
1868 
1869 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
1870 		ASSERT((caddr_t)key >= tomax);
1871 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
1872 
1873 		if (hashval != key->dtak_hashval || key->dtak_size != size)
1874 			continue;
1875 
1876 		kdata = key->dtak_data;
1877 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
1878 
1879 		for (act = agg->dtag_first; act->dta_intuple;
1880 		    act = act->dta_next) {
1881 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
1882 			limit = i + act->dta_rec.dtrd_size;
1883 			ASSERT(limit <= size);
1884 			isstr = DTRACEACT_ISSTRING(act);
1885 
1886 			for (; i < limit; i++) {
1887 				if (kdata[i] != data[i])
1888 					goto next;
1889 
1890 				if (isstr && data[i] == '\0')
1891 					break;
1892 			}
1893 		}
1894 
1895 		if (action != key->dtak_action) {
1896 			/*
1897 			 * We are aggregating on the same value in the same
1898 			 * aggregation with two different aggregating actions.
1899 			 * (This should have been picked up in the compiler,
1900 			 * so we may be dealing with errant or devious DIF.)
1901 			 * This is an error condition; we indicate as much,
1902 			 * and return.
1903 			 */
1904 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
1905 			return;
1906 		}
1907 
1908 		/*
1909 		 * This is a hit:  we need to apply the aggregator to
1910 		 * the value at this key.
1911 		 */
1912 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
1913 		return;
1914 next:
1915 		continue;
1916 	}
1917 
1918 	/*
1919 	 * We didn't find it.  We need to allocate some zero-filled space,
1920 	 * link it into the hash table appropriately, and apply the aggregator
1921 	 * to the (zero-filled) value.
1922 	 */
1923 	offs = buf->dtb_offset;
1924 	while (offs & (align - 1))
1925 		offs += sizeof (uint32_t);
1926 
1927 	/*
1928 	 * If we don't have enough room to both allocate a new key _and_
1929 	 * its associated data, increment the drop count and return.
1930 	 */
1931 	if ((uintptr_t)tomax + offs + fsize >
1932 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
1933 		dtrace_buffer_drop(buf);
1934 		return;
1935 	}
1936 
1937 	/*CONSTCOND*/
1938 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
1939 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
1940 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
1941 
1942 	key->dtak_data = kdata = tomax + offs;
1943 	buf->dtb_offset = offs + fsize;
1944 
1945 	/*
1946 	 * Now copy the data across.
1947 	 */
1948 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
1949 
1950 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
1951 		kdata[i] = data[i];
1952 
1953 	/*
1954 	 * Because strings are not zeroed out by default, we need to iterate
1955 	 * looking for actions that store strings, and we need to explicitly
1956 	 * pad these strings out with zeroes.
1957 	 */
1958 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1959 		int nul;
1960 
1961 		if (!DTRACEACT_ISSTRING(act))
1962 			continue;
1963 
1964 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1965 		limit = i + act->dta_rec.dtrd_size;
1966 		ASSERT(limit <= size);
1967 
1968 		for (nul = 0; i < limit; i++) {
1969 			if (nul) {
1970 				kdata[i] = '\0';
1971 				continue;
1972 			}
1973 
1974 			if (data[i] != '\0')
1975 				continue;
1976 
1977 			nul = 1;
1978 		}
1979 	}
1980 
1981 	for (i = size; i < fsize; i++)
1982 		kdata[i] = 0;
1983 
1984 	key->dtak_hashval = hashval;
1985 	key->dtak_size = size;
1986 	key->dtak_action = action;
1987 	key->dtak_next = agb->dtagb_hash[ndx];
1988 	agb->dtagb_hash[ndx] = key;
1989 
1990 	/*
1991 	 * Finally, apply the aggregator.
1992 	 */
1993 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
1994 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
1995 }
1996 
1997 /*
1998  * Given consumer state, this routine finds a speculation in the INACTIVE
1999  * state and transitions it into the ACTIVE state.  If there is no speculation
2000  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2001  * incremented -- it is up to the caller to take appropriate action.
2002  */
2003 static int
2004 dtrace_speculation(dtrace_state_t *state)
2005 {
2006 	int i = 0;
2007 	dtrace_speculation_state_t current;
2008 	uint32_t *stat = &state->dts_speculations_unavail, count;
2009 
2010 	while (i < state->dts_nspeculations) {
2011 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2012 
2013 		current = spec->dtsp_state;
2014 
2015 		if (current != DTRACESPEC_INACTIVE) {
2016 			if (current == DTRACESPEC_COMMITTINGMANY ||
2017 			    current == DTRACESPEC_COMMITTING ||
2018 			    current == DTRACESPEC_DISCARDING)
2019 				stat = &state->dts_speculations_busy;
2020 			i++;
2021 			continue;
2022 		}
2023 
2024 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2025 		    current, DTRACESPEC_ACTIVE) == current)
2026 			return (i + 1);
2027 	}
2028 
2029 	/*
2030 	 * We couldn't find a speculation.  If we found as much as a single
2031 	 * busy speculation buffer, we'll attribute this failure as "busy"
2032 	 * instead of "unavail".
2033 	 */
2034 	do {
2035 		count = *stat;
2036 	} while (dtrace_cas32(stat, count, count + 1) != count);
2037 
2038 	return (0);
2039 }
2040 
2041 /*
2042  * This routine commits an active speculation.  If the specified speculation
2043  * is not in a valid state to perform a commit(), this routine will silently do
2044  * nothing.  The state of the specified speculation is transitioned according
2045  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2046  */
2047 static void
2048 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2049     dtrace_specid_t which)
2050 {
2051 	dtrace_speculation_t *spec;
2052 	dtrace_buffer_t *src, *dest;
2053 	uintptr_t daddr, saddr, dlimit;
2054 	dtrace_speculation_state_t current, new;
2055 	intptr_t offs;
2056 
2057 	if (which == 0)
2058 		return;
2059 
2060 	if (which > state->dts_nspeculations) {
2061 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2062 		return;
2063 	}
2064 
2065 	spec = &state->dts_speculations[which - 1];
2066 	src = &spec->dtsp_buffer[cpu];
2067 	dest = &state->dts_buffer[cpu];
2068 
2069 	do {
2070 		current = spec->dtsp_state;
2071 
2072 		if (current == DTRACESPEC_COMMITTINGMANY)
2073 			break;
2074 
2075 		switch (current) {
2076 		case DTRACESPEC_INACTIVE:
2077 		case DTRACESPEC_DISCARDING:
2078 			return;
2079 
2080 		case DTRACESPEC_COMMITTING:
2081 			/*
2082 			 * This is only possible if we are (a) commit()'ing
2083 			 * without having done a prior speculate() on this CPU
2084 			 * and (b) racing with another commit() on a different
2085 			 * CPU.  There's nothing to do -- we just assert that
2086 			 * our offset is 0.
2087 			 */
2088 			ASSERT(src->dtb_offset == 0);
2089 			return;
2090 
2091 		case DTRACESPEC_ACTIVE:
2092 			new = DTRACESPEC_COMMITTING;
2093 			break;
2094 
2095 		case DTRACESPEC_ACTIVEONE:
2096 			/*
2097 			 * This speculation is active on one CPU.  If our
2098 			 * buffer offset is non-zero, we know that the one CPU
2099 			 * must be us.  Otherwise, we are committing on a
2100 			 * different CPU from the speculate(), and we must
2101 			 * rely on being asynchronously cleaned.
2102 			 */
2103 			if (src->dtb_offset != 0) {
2104 				new = DTRACESPEC_COMMITTING;
2105 				break;
2106 			}
2107 			/*FALLTHROUGH*/
2108 
2109 		case DTRACESPEC_ACTIVEMANY:
2110 			new = DTRACESPEC_COMMITTINGMANY;
2111 			break;
2112 
2113 		default:
2114 			ASSERT(0);
2115 		}
2116 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2117 	    current, new) != current);
2118 
2119 	/*
2120 	 * We have set the state to indicate that we are committing this
2121 	 * speculation.  Now reserve the necessary space in the destination
2122 	 * buffer.
2123 	 */
2124 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2125 	    sizeof (uint64_t), state, NULL)) < 0) {
2126 		dtrace_buffer_drop(dest);
2127 		goto out;
2128 	}
2129 
2130 	/*
2131 	 * We have the space; copy the buffer across.  (Note that this is a
2132 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2133 	 * a serious performance issue, a high-performance DTrace-specific
2134 	 * bcopy() should obviously be invented.)
2135 	 */
2136 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2137 	dlimit = daddr + src->dtb_offset;
2138 	saddr = (uintptr_t)src->dtb_tomax;
2139 
2140 	/*
2141 	 * First, the aligned portion.
2142 	 */
2143 	while (dlimit - daddr >= sizeof (uint64_t)) {
2144 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2145 
2146 		daddr += sizeof (uint64_t);
2147 		saddr += sizeof (uint64_t);
2148 	}
2149 
2150 	/*
2151 	 * Now any left-over bit...
2152 	 */
2153 	while (dlimit - daddr)
2154 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2155 
2156 	/*
2157 	 * Finally, commit the reserved space in the destination buffer.
2158 	 */
2159 	dest->dtb_offset = offs + src->dtb_offset;
2160 
2161 out:
2162 	/*
2163 	 * If we're lucky enough to be the only active CPU on this speculation
2164 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2165 	 */
2166 	if (current == DTRACESPEC_ACTIVE ||
2167 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2168 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2169 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2170 
2171 		ASSERT(rval == DTRACESPEC_COMMITTING);
2172 	}
2173 
2174 	src->dtb_offset = 0;
2175 	src->dtb_xamot_drops += src->dtb_drops;
2176 	src->dtb_drops = 0;
2177 }
2178 
2179 /*
2180  * This routine discards an active speculation.  If the specified speculation
2181  * is not in a valid state to perform a discard(), this routine will silently
2182  * do nothing.  The state of the specified speculation is transitioned
2183  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2184  */
2185 static void
2186 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2187     dtrace_specid_t which)
2188 {
2189 	dtrace_speculation_t *spec;
2190 	dtrace_speculation_state_t current, new;
2191 	dtrace_buffer_t *buf;
2192 
2193 	if (which == 0)
2194 		return;
2195 
2196 	if (which > state->dts_nspeculations) {
2197 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2198 		return;
2199 	}
2200 
2201 	spec = &state->dts_speculations[which - 1];
2202 	buf = &spec->dtsp_buffer[cpu];
2203 
2204 	do {
2205 		current = spec->dtsp_state;
2206 
2207 		switch (current) {
2208 		case DTRACESPEC_INACTIVE:
2209 		case DTRACESPEC_COMMITTINGMANY:
2210 		case DTRACESPEC_COMMITTING:
2211 		case DTRACESPEC_DISCARDING:
2212 			return;
2213 
2214 		case DTRACESPEC_ACTIVE:
2215 		case DTRACESPEC_ACTIVEMANY:
2216 			new = DTRACESPEC_DISCARDING;
2217 			break;
2218 
2219 		case DTRACESPEC_ACTIVEONE:
2220 			if (buf->dtb_offset != 0) {
2221 				new = DTRACESPEC_INACTIVE;
2222 			} else {
2223 				new = DTRACESPEC_DISCARDING;
2224 			}
2225 			break;
2226 
2227 		default:
2228 			ASSERT(0);
2229 		}
2230 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2231 	    current, new) != current);
2232 
2233 	buf->dtb_offset = 0;
2234 	buf->dtb_drops = 0;
2235 }
2236 
2237 /*
2238  * Note:  not called from probe context.  This function is called
2239  * asynchronously from cross call context to clean any speculations that are
2240  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2241  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2242  * speculation.
2243  */
2244 static void
2245 dtrace_speculation_clean_here(dtrace_state_t *state)
2246 {
2247 	dtrace_icookie_t cookie;
2248 	processorid_t cpu = CPU->cpu_id;
2249 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2250 	dtrace_specid_t i;
2251 
2252 	cookie = dtrace_interrupt_disable();
2253 
2254 	if (dest->dtb_tomax == NULL) {
2255 		dtrace_interrupt_enable(cookie);
2256 		return;
2257 	}
2258 
2259 	for (i = 0; i < state->dts_nspeculations; i++) {
2260 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2261 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2262 
2263 		if (src->dtb_tomax == NULL)
2264 			continue;
2265 
2266 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2267 			src->dtb_offset = 0;
2268 			continue;
2269 		}
2270 
2271 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2272 			continue;
2273 
2274 		if (src->dtb_offset == 0)
2275 			continue;
2276 
2277 		dtrace_speculation_commit(state, cpu, i + 1);
2278 	}
2279 
2280 	dtrace_interrupt_enable(cookie);
2281 }
2282 
2283 /*
2284  * Note:  not called from probe context.  This function is called
2285  * asynchronously (and at a regular interval) to clean any speculations that
2286  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2287  * is work to be done, it cross calls all CPUs to perform that work;
2288  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2289  * INACTIVE state until they have been cleaned by all CPUs.
2290  */
2291 static void
2292 dtrace_speculation_clean(dtrace_state_t *state)
2293 {
2294 	int work = 0, rv;
2295 	dtrace_specid_t i;
2296 
2297 	for (i = 0; i < state->dts_nspeculations; i++) {
2298 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2299 
2300 		ASSERT(!spec->dtsp_cleaning);
2301 
2302 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2303 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2304 			continue;
2305 
2306 		work++;
2307 		spec->dtsp_cleaning = 1;
2308 	}
2309 
2310 	if (!work)
2311 		return;
2312 
2313 	dtrace_xcall(DTRACE_CPUALL,
2314 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2315 
2316 	/*
2317 	 * We now know that all CPUs have committed or discarded their
2318 	 * speculation buffers, as appropriate.  We can now set the state
2319 	 * to inactive.
2320 	 */
2321 	for (i = 0; i < state->dts_nspeculations; i++) {
2322 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2323 		dtrace_speculation_state_t current, new;
2324 
2325 		if (!spec->dtsp_cleaning)
2326 			continue;
2327 
2328 		current = spec->dtsp_state;
2329 		ASSERT(current == DTRACESPEC_DISCARDING ||
2330 		    current == DTRACESPEC_COMMITTINGMANY);
2331 
2332 		new = DTRACESPEC_INACTIVE;
2333 
2334 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2335 		ASSERT(rv == current);
2336 		spec->dtsp_cleaning = 0;
2337 	}
2338 }
2339 
2340 /*
2341  * Called as part of a speculate() to get the speculative buffer associated
2342  * with a given speculation.  Returns NULL if the specified speculation is not
2343  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2344  * the active CPU is not the specified CPU -- the speculation will be
2345  * atomically transitioned into the ACTIVEMANY state.
2346  */
2347 static dtrace_buffer_t *
2348 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2349     dtrace_specid_t which)
2350 {
2351 	dtrace_speculation_t *spec;
2352 	dtrace_speculation_state_t current, new;
2353 	dtrace_buffer_t *buf;
2354 
2355 	if (which == 0)
2356 		return (NULL);
2357 
2358 	if (which > state->dts_nspeculations) {
2359 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2360 		return (NULL);
2361 	}
2362 
2363 	spec = &state->dts_speculations[which - 1];
2364 	buf = &spec->dtsp_buffer[cpuid];
2365 
2366 	do {
2367 		current = spec->dtsp_state;
2368 
2369 		switch (current) {
2370 		case DTRACESPEC_INACTIVE:
2371 		case DTRACESPEC_COMMITTINGMANY:
2372 		case DTRACESPEC_DISCARDING:
2373 			return (NULL);
2374 
2375 		case DTRACESPEC_COMMITTING:
2376 			ASSERT(buf->dtb_offset == 0);
2377 			return (NULL);
2378 
2379 		case DTRACESPEC_ACTIVEONE:
2380 			/*
2381 			 * This speculation is currently active on one CPU.
2382 			 * Check the offset in the buffer; if it's non-zero,
2383 			 * that CPU must be us (and we leave the state alone).
2384 			 * If it's zero, assume that we're starting on a new
2385 			 * CPU -- and change the state to indicate that the
2386 			 * speculation is active on more than one CPU.
2387 			 */
2388 			if (buf->dtb_offset != 0)
2389 				return (buf);
2390 
2391 			new = DTRACESPEC_ACTIVEMANY;
2392 			break;
2393 
2394 		case DTRACESPEC_ACTIVEMANY:
2395 			return (buf);
2396 
2397 		case DTRACESPEC_ACTIVE:
2398 			new = DTRACESPEC_ACTIVEONE;
2399 			break;
2400 
2401 		default:
2402 			ASSERT(0);
2403 		}
2404 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2405 	    current, new) != current);
2406 
2407 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2408 	return (buf);
2409 }
2410 
2411 /*
2412  * Return a string.  In the event that the user lacks the privilege to access
2413  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2414  * don't fail access checking.
2415  *
2416  * dtrace_dif_variable() uses this routine as a helper for various
2417  * builtin values such as 'execname' and 'probefunc.'
2418  */
2419 uintptr_t
2420 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2421     dtrace_mstate_t *mstate)
2422 {
2423 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2424 	uintptr_t ret;
2425 	size_t strsz;
2426 
2427 	/*
2428 	 * The easy case: this probe is allowed to read all of memory, so
2429 	 * we can just return this as a vanilla pointer.
2430 	 */
2431 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2432 		return (addr);
2433 
2434 	/*
2435 	 * This is the tougher case: we copy the string in question from
2436 	 * kernel memory into scratch memory and return it that way: this
2437 	 * ensures that we won't trip up when access checking tests the
2438 	 * BYREF return value.
2439 	 */
2440 	strsz = dtrace_strlen((char *)addr, size) + 1;
2441 
2442 	if (mstate->dtms_scratch_ptr + strsz >
2443 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2444 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2445 		return (NULL);
2446 	}
2447 
2448 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2449 	    strsz);
2450 	ret = mstate->dtms_scratch_ptr;
2451 	mstate->dtms_scratch_ptr += strsz;
2452 	return (ret);
2453 }
2454 
2455 /*
2456  * This function implements the DIF emulator's variable lookups.  The emulator
2457  * passes a reserved variable identifier and optional built-in array index.
2458  */
2459 static uint64_t
2460 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2461     uint64_t ndx)
2462 {
2463 	/*
2464 	 * If we're accessing one of the uncached arguments, we'll turn this
2465 	 * into a reference in the args array.
2466 	 */
2467 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2468 		ndx = v - DIF_VAR_ARG0;
2469 		v = DIF_VAR_ARGS;
2470 	}
2471 
2472 	switch (v) {
2473 	case DIF_VAR_ARGS:
2474 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2475 		if (ndx >= sizeof (mstate->dtms_arg) /
2476 		    sizeof (mstate->dtms_arg[0])) {
2477 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2478 			dtrace_provider_t *pv;
2479 			uint64_t val;
2480 
2481 			pv = mstate->dtms_probe->dtpr_provider;
2482 			if (pv->dtpv_pops.dtps_getargval != NULL)
2483 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2484 				    mstate->dtms_probe->dtpr_id,
2485 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
2486 			else
2487 				val = dtrace_getarg(ndx, aframes);
2488 
2489 			/*
2490 			 * This is regrettably required to keep the compiler
2491 			 * from tail-optimizing the call to dtrace_getarg().
2492 			 * The condition always evaluates to true, but the
2493 			 * compiler has no way of figuring that out a priori.
2494 			 * (None of this would be necessary if the compiler
2495 			 * could be relied upon to _always_ tail-optimize
2496 			 * the call to dtrace_getarg() -- but it can't.)
2497 			 */
2498 			if (mstate->dtms_probe != NULL)
2499 				return (val);
2500 
2501 			ASSERT(0);
2502 		}
2503 
2504 		return (mstate->dtms_arg[ndx]);
2505 
2506 	case DIF_VAR_UREGS: {
2507 		klwp_t *lwp;
2508 
2509 		if (!dtrace_priv_proc(state))
2510 			return (0);
2511 
2512 		if ((lwp = curthread->t_lwp) == NULL) {
2513 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2514 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
2515 			return (0);
2516 		}
2517 
2518 		return (dtrace_getreg(lwp->lwp_regs, ndx));
2519 	}
2520 
2521 	case DIF_VAR_CURTHREAD:
2522 		if (!dtrace_priv_kernel(state))
2523 			return (0);
2524 		return ((uint64_t)(uintptr_t)curthread);
2525 
2526 	case DIF_VAR_TIMESTAMP:
2527 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2528 			mstate->dtms_timestamp = dtrace_gethrtime();
2529 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2530 		}
2531 		return (mstate->dtms_timestamp);
2532 
2533 	case DIF_VAR_VTIMESTAMP:
2534 		ASSERT(dtrace_vtime_references != 0);
2535 		return (curthread->t_dtrace_vtime);
2536 
2537 	case DIF_VAR_WALLTIMESTAMP:
2538 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2539 			mstate->dtms_walltimestamp = dtrace_gethrestime();
2540 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2541 		}
2542 		return (mstate->dtms_walltimestamp);
2543 
2544 	case DIF_VAR_IPL:
2545 		if (!dtrace_priv_kernel(state))
2546 			return (0);
2547 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2548 			mstate->dtms_ipl = dtrace_getipl();
2549 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
2550 		}
2551 		return (mstate->dtms_ipl);
2552 
2553 	case DIF_VAR_EPID:
2554 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2555 		return (mstate->dtms_epid);
2556 
2557 	case DIF_VAR_ID:
2558 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2559 		return (mstate->dtms_probe->dtpr_id);
2560 
2561 	case DIF_VAR_STACKDEPTH:
2562 		if (!dtrace_priv_kernel(state))
2563 			return (0);
2564 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2565 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2566 
2567 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2568 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2569 		}
2570 		return (mstate->dtms_stackdepth);
2571 
2572 	case DIF_VAR_USTACKDEPTH:
2573 		if (!dtrace_priv_proc(state))
2574 			return (0);
2575 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2576 			/*
2577 			 * See comment in DIF_VAR_PID.
2578 			 */
2579 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2580 			    CPU_ON_INTR(CPU)) {
2581 				mstate->dtms_ustackdepth = 0;
2582 			} else {
2583 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2584 				mstate->dtms_ustackdepth =
2585 				    dtrace_getustackdepth();
2586 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2587 			}
2588 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2589 		}
2590 		return (mstate->dtms_ustackdepth);
2591 
2592 	case DIF_VAR_CALLER:
2593 		if (!dtrace_priv_kernel(state))
2594 			return (0);
2595 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2596 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2597 
2598 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2599 				/*
2600 				 * If this is an unanchored probe, we are
2601 				 * required to go through the slow path:
2602 				 * dtrace_caller() only guarantees correct
2603 				 * results for anchored probes.
2604 				 */
2605 				pc_t caller[2];
2606 
2607 				dtrace_getpcstack(caller, 2, aframes,
2608 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2609 				mstate->dtms_caller = caller[1];
2610 			} else if ((mstate->dtms_caller =
2611 			    dtrace_caller(aframes)) == -1) {
2612 				/*
2613 				 * We have failed to do this the quick way;
2614 				 * we must resort to the slower approach of
2615 				 * calling dtrace_getpcstack().
2616 				 */
2617 				pc_t caller;
2618 
2619 				dtrace_getpcstack(&caller, 1, aframes, NULL);
2620 				mstate->dtms_caller = caller;
2621 			}
2622 
2623 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
2624 		}
2625 		return (mstate->dtms_caller);
2626 
2627 	case DIF_VAR_UCALLER:
2628 		if (!dtrace_priv_proc(state))
2629 			return (0);
2630 
2631 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
2632 			uint64_t ustack[3];
2633 
2634 			/*
2635 			 * dtrace_getupcstack() fills in the first uint64_t
2636 			 * with the current PID.  The second uint64_t will
2637 			 * be the program counter at user-level.  The third
2638 			 * uint64_t will contain the caller, which is what
2639 			 * we're after.
2640 			 */
2641 			ustack[2] = NULL;
2642 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2643 			dtrace_getupcstack(ustack, 3);
2644 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2645 			mstate->dtms_ucaller = ustack[2];
2646 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
2647 		}
2648 
2649 		return (mstate->dtms_ucaller);
2650 
2651 	case DIF_VAR_PROBEPROV:
2652 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2653 		return (dtrace_dif_varstr(
2654 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
2655 		    state, mstate));
2656 
2657 	case DIF_VAR_PROBEMOD:
2658 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2659 		return (dtrace_dif_varstr(
2660 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
2661 		    state, mstate));
2662 
2663 	case DIF_VAR_PROBEFUNC:
2664 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2665 		return (dtrace_dif_varstr(
2666 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
2667 		    state, mstate));
2668 
2669 	case DIF_VAR_PROBENAME:
2670 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2671 		return (dtrace_dif_varstr(
2672 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
2673 		    state, mstate));
2674 
2675 	case DIF_VAR_PID:
2676 		if (!dtrace_priv_proc(state))
2677 			return (0);
2678 
2679 		/*
2680 		 * Note that we are assuming that an unanchored probe is
2681 		 * always due to a high-level interrupt.  (And we're assuming
2682 		 * that there is only a single high level interrupt.)
2683 		 */
2684 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2685 			return (pid0.pid_id);
2686 
2687 		/*
2688 		 * It is always safe to dereference one's own t_procp pointer:
2689 		 * it always points to a valid, allocated proc structure.
2690 		 * Further, it is always safe to dereference the p_pidp member
2691 		 * of one's own proc structure.  (These are truisms becuase
2692 		 * threads and processes don't clean up their own state --
2693 		 * they leave that task to whomever reaps them.)
2694 		 */
2695 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
2696 
2697 	case DIF_VAR_PPID:
2698 		if (!dtrace_priv_proc(state))
2699 			return (0);
2700 
2701 		/*
2702 		 * See comment in DIF_VAR_PID.
2703 		 */
2704 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2705 			return (pid0.pid_id);
2706 
2707 		/*
2708 		 * It is always safe to dereference one's own t_procp pointer:
2709 		 * it always points to a valid, allocated proc structure.
2710 		 * (This is true because threads don't clean up their own
2711 		 * state -- they leave that task to whomever reaps them.)
2712 		 */
2713 		return ((uint64_t)curthread->t_procp->p_ppid);
2714 
2715 	case DIF_VAR_TID:
2716 		/*
2717 		 * See comment in DIF_VAR_PID.
2718 		 */
2719 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2720 			return (0);
2721 
2722 		return ((uint64_t)curthread->t_tid);
2723 
2724 	case DIF_VAR_EXECNAME:
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)(uintptr_t)p0.p_user.u_comm);
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 		return (dtrace_dif_varstr(
2741 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
2742 		    state, mstate));
2743 
2744 	case DIF_VAR_ZONENAME:
2745 		if (!dtrace_priv_proc(state))
2746 			return (0);
2747 
2748 		/*
2749 		 * See comment in DIF_VAR_PID.
2750 		 */
2751 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2752 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
2753 
2754 		/*
2755 		 * It is always safe to dereference one's own t_procp pointer:
2756 		 * it always points to a valid, allocated proc structure.
2757 		 * (This is true because threads don't clean up their own
2758 		 * state -- they leave that task to whomever reaps them.)
2759 		 */
2760 		return (dtrace_dif_varstr(
2761 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
2762 		    state, mstate));
2763 
2764 	case DIF_VAR_UID:
2765 		if (!dtrace_priv_proc(state))
2766 			return (0);
2767 
2768 		/*
2769 		 * See comment in DIF_VAR_PID.
2770 		 */
2771 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2772 			return ((uint64_t)p0.p_cred->cr_uid);
2773 
2774 		/*
2775 		 * It is always safe to dereference one's own t_procp pointer:
2776 		 * it always points to a valid, allocated proc structure.
2777 		 * (This is true because threads don't clean up their own
2778 		 * state -- they leave that task to whomever reaps them.)
2779 		 *
2780 		 * Additionally, it is safe to dereference one's own process
2781 		 * credential, since this is never NULL after process birth.
2782 		 */
2783 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
2784 
2785 	case DIF_VAR_GID:
2786 		if (!dtrace_priv_proc(state))
2787 			return (0);
2788 
2789 		/*
2790 		 * See comment in DIF_VAR_PID.
2791 		 */
2792 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2793 			return ((uint64_t)p0.p_cred->cr_gid);
2794 
2795 		/*
2796 		 * It is always safe to dereference one's own t_procp pointer:
2797 		 * it always points to a valid, allocated proc structure.
2798 		 * (This is true because threads don't clean up their own
2799 		 * state -- they leave that task to whomever reaps them.)
2800 		 *
2801 		 * Additionally, it is safe to dereference one's own process
2802 		 * credential, since this is never NULL after process birth.
2803 		 */
2804 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
2805 
2806 	case DIF_VAR_ERRNO: {
2807 		klwp_t *lwp;
2808 		if (!dtrace_priv_proc(state))
2809 			return (0);
2810 
2811 		/*
2812 		 * See comment in DIF_VAR_PID.
2813 		 */
2814 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2815 			return (0);
2816 
2817 		/*
2818 		 * It is always safe to dereference one's own t_lwp pointer in
2819 		 * the event that this pointer is non-NULL.  (This is true
2820 		 * because threads and lwps don't clean up their own state --
2821 		 * they leave that task to whomever reaps them.)
2822 		 */
2823 		if ((lwp = curthread->t_lwp) == NULL)
2824 			return (0);
2825 
2826 		return ((uint64_t)lwp->lwp_errno);
2827 	}
2828 	default:
2829 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2830 		return (0);
2831 	}
2832 }
2833 
2834 /*
2835  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
2836  * Notice that we don't bother validating the proper number of arguments or
2837  * their types in the tuple stack.  This isn't needed because all argument
2838  * interpretation is safe because of our load safety -- the worst that can
2839  * happen is that a bogus program can obtain bogus results.
2840  */
2841 static void
2842 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
2843     dtrace_key_t *tupregs, int nargs,
2844     dtrace_mstate_t *mstate, dtrace_state_t *state)
2845 {
2846 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
2847 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
2848 	dtrace_vstate_t *vstate = &state->dts_vstate;
2849 
2850 	union {
2851 		mutex_impl_t mi;
2852 		uint64_t mx;
2853 	} m;
2854 
2855 	union {
2856 		krwlock_t ri;
2857 		uintptr_t rw;
2858 	} r;
2859 
2860 	switch (subr) {
2861 	case DIF_SUBR_RAND:
2862 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
2863 		break;
2864 
2865 	case DIF_SUBR_MUTEX_OWNED:
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 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
2874 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
2875 		else
2876 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
2877 		break;
2878 
2879 	case DIF_SUBR_MUTEX_OWNER:
2880 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2881 		    mstate, vstate)) {
2882 			regs[rd] = NULL;
2883 			break;
2884 		}
2885 
2886 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2887 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
2888 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
2889 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
2890 		else
2891 			regs[rd] = 0;
2892 		break;
2893 
2894 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
2895 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2896 		    mstate, vstate)) {
2897 			regs[rd] = NULL;
2898 			break;
2899 		}
2900 
2901 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2902 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
2903 		break;
2904 
2905 	case DIF_SUBR_MUTEX_TYPE_SPIN:
2906 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2907 		    mstate, vstate)) {
2908 			regs[rd] = NULL;
2909 			break;
2910 		}
2911 
2912 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2913 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
2914 		break;
2915 
2916 	case DIF_SUBR_RW_READ_HELD: {
2917 		uintptr_t tmp;
2918 
2919 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
2920 		    mstate, vstate)) {
2921 			regs[rd] = NULL;
2922 			break;
2923 		}
2924 
2925 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2926 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
2927 		break;
2928 	}
2929 
2930 	case DIF_SUBR_RW_WRITE_HELD:
2931 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
2932 		    mstate, vstate)) {
2933 			regs[rd] = NULL;
2934 			break;
2935 		}
2936 
2937 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2938 		regs[rd] = _RW_WRITE_HELD(&r.ri);
2939 		break;
2940 
2941 	case DIF_SUBR_RW_ISWRITER:
2942 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
2943 		    mstate, vstate)) {
2944 			regs[rd] = NULL;
2945 			break;
2946 		}
2947 
2948 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2949 		regs[rd] = _RW_ISWRITER(&r.ri);
2950 		break;
2951 
2952 	case DIF_SUBR_BCOPY: {
2953 		/*
2954 		 * We need to be sure that the destination is in the scratch
2955 		 * region -- no other region is allowed.
2956 		 */
2957 		uintptr_t src = tupregs[0].dttk_value;
2958 		uintptr_t dest = tupregs[1].dttk_value;
2959 		size_t size = tupregs[2].dttk_value;
2960 
2961 		if (!dtrace_inscratch(dest, size, mstate)) {
2962 			*flags |= CPU_DTRACE_BADADDR;
2963 			*illval = regs[rd];
2964 			break;
2965 		}
2966 
2967 		if (!dtrace_canload(src, size, mstate, vstate)) {
2968 			regs[rd] = NULL;
2969 			break;
2970 		}
2971 
2972 		dtrace_bcopy((void *)src, (void *)dest, size);
2973 		break;
2974 	}
2975 
2976 	case DIF_SUBR_ALLOCA:
2977 	case DIF_SUBR_COPYIN: {
2978 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
2979 		uint64_t size =
2980 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
2981 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
2982 
2983 		/*
2984 		 * This action doesn't require any credential checks since
2985 		 * probes will not activate in user contexts to which the
2986 		 * enabling user does not have permissions.
2987 		 */
2988 
2989 		/*
2990 		 * Rounding up the user allocation size could have overflowed
2991 		 * a large, bogus allocation (like -1ULL) to 0.
2992 		 */
2993 		if (scratch_size < size ||
2994 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
2995 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2996 			regs[rd] = NULL;
2997 			break;
2998 		}
2999 
3000 		if (subr == DIF_SUBR_COPYIN) {
3001 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3002 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3003 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3004 		}
3005 
3006 		mstate->dtms_scratch_ptr += scratch_size;
3007 		regs[rd] = dest;
3008 		break;
3009 	}
3010 
3011 	case DIF_SUBR_COPYINTO: {
3012 		uint64_t size = tupregs[1].dttk_value;
3013 		uintptr_t dest = tupregs[2].dttk_value;
3014 
3015 		/*
3016 		 * This action doesn't require any credential checks since
3017 		 * probes will not activate in user contexts to which the
3018 		 * enabling user does not have permissions.
3019 		 */
3020 		if (!dtrace_inscratch(dest, size, mstate)) {
3021 			*flags |= CPU_DTRACE_BADADDR;
3022 			*illval = regs[rd];
3023 			break;
3024 		}
3025 
3026 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3027 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3028 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3029 		break;
3030 	}
3031 
3032 	case DIF_SUBR_COPYINSTR: {
3033 		uintptr_t dest = mstate->dtms_scratch_ptr;
3034 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3035 
3036 		if (nargs > 1 && tupregs[1].dttk_value < size)
3037 			size = tupregs[1].dttk_value + 1;
3038 
3039 		/*
3040 		 * This action doesn't require any credential checks since
3041 		 * probes will not activate in user contexts to which the
3042 		 * enabling user does not have permissions.
3043 		 */
3044 		if (!DTRACE_INSCRATCH(mstate, size)) {
3045 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3046 			regs[rd] = NULL;
3047 			break;
3048 		}
3049 
3050 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3051 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3052 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3053 
3054 		((char *)dest)[size - 1] = '\0';
3055 		mstate->dtms_scratch_ptr += size;
3056 		regs[rd] = dest;
3057 		break;
3058 	}
3059 
3060 	case DIF_SUBR_MSGSIZE:
3061 	case DIF_SUBR_MSGDSIZE: {
3062 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
3063 		uintptr_t wptr, rptr;
3064 		size_t count = 0;
3065 		int cont = 0;
3066 
3067 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3068 
3069 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3070 			    vstate)) {
3071 				regs[rd] = NULL;
3072 				break;
3073 			}
3074 
3075 			wptr = dtrace_loadptr(baddr +
3076 			    offsetof(mblk_t, b_wptr));
3077 
3078 			rptr = dtrace_loadptr(baddr +
3079 			    offsetof(mblk_t, b_rptr));
3080 
3081 			if (wptr < rptr) {
3082 				*flags |= CPU_DTRACE_BADADDR;
3083 				*illval = tupregs[0].dttk_value;
3084 				break;
3085 			}
3086 
3087 			daddr = dtrace_loadptr(baddr +
3088 			    offsetof(mblk_t, b_datap));
3089 
3090 			baddr = dtrace_loadptr(baddr +
3091 			    offsetof(mblk_t, b_cont));
3092 
3093 			/*
3094 			 * We want to prevent against denial-of-service here,
3095 			 * so we're only going to search the list for
3096 			 * dtrace_msgdsize_max mblks.
3097 			 */
3098 			if (cont++ > dtrace_msgdsize_max) {
3099 				*flags |= CPU_DTRACE_ILLOP;
3100 				break;
3101 			}
3102 
3103 			if (subr == DIF_SUBR_MSGDSIZE) {
3104 				if (dtrace_load8(daddr +
3105 				    offsetof(dblk_t, db_type)) != M_DATA)
3106 					continue;
3107 			}
3108 
3109 			count += wptr - rptr;
3110 		}
3111 
3112 		if (!(*flags & CPU_DTRACE_FAULT))
3113 			regs[rd] = count;
3114 
3115 		break;
3116 	}
3117 
3118 	case DIF_SUBR_PROGENYOF: {
3119 		pid_t pid = tupregs[0].dttk_value;
3120 		proc_t *p;
3121 		int rval = 0;
3122 
3123 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3124 
3125 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3126 			if (p->p_pidp->pid_id == pid) {
3127 				rval = 1;
3128 				break;
3129 			}
3130 		}
3131 
3132 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3133 
3134 		regs[rd] = rval;
3135 		break;
3136 	}
3137 
3138 	case DIF_SUBR_SPECULATION:
3139 		regs[rd] = dtrace_speculation(state);
3140 		break;
3141 
3142 	case DIF_SUBR_COPYOUT: {
3143 		uintptr_t kaddr = tupregs[0].dttk_value;
3144 		uintptr_t uaddr = tupregs[1].dttk_value;
3145 		uint64_t size = tupregs[2].dttk_value;
3146 
3147 		if (!dtrace_destructive_disallow &&
3148 		    dtrace_priv_proc_control(state) &&
3149 		    !dtrace_istoxic(kaddr, size)) {
3150 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3151 			dtrace_copyout(kaddr, uaddr, size, flags);
3152 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3153 		}
3154 		break;
3155 	}
3156 
3157 	case DIF_SUBR_COPYOUTSTR: {
3158 		uintptr_t kaddr = tupregs[0].dttk_value;
3159 		uintptr_t uaddr = tupregs[1].dttk_value;
3160 		uint64_t size = tupregs[2].dttk_value;
3161 
3162 		if (!dtrace_destructive_disallow &&
3163 		    dtrace_priv_proc_control(state) &&
3164 		    !dtrace_istoxic(kaddr, size)) {
3165 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3166 			dtrace_copyoutstr(kaddr, uaddr, size, flags);
3167 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3168 		}
3169 		break;
3170 	}
3171 
3172 	case DIF_SUBR_STRLEN: {
3173 		size_t sz;
3174 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3175 		sz = dtrace_strlen((char *)addr,
3176 		    state->dts_options[DTRACEOPT_STRSIZE]);
3177 
3178 		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3179 			regs[rd] = NULL;
3180 			break;
3181 		}
3182 
3183 		regs[rd] = sz;
3184 
3185 		break;
3186 	}
3187 
3188 	case DIF_SUBR_STRCHR:
3189 	case DIF_SUBR_STRRCHR: {
3190 		/*
3191 		 * We're going to iterate over the string looking for the
3192 		 * specified character.  We will iterate until we have reached
3193 		 * the string length or we have found the character.  If this
3194 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3195 		 * of the specified character instead of the first.
3196 		 */
3197 		uintptr_t saddr = tupregs[0].dttk_value;
3198 		uintptr_t addr = tupregs[0].dttk_value;
3199 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3200 		char c, target = (char)tupregs[1].dttk_value;
3201 
3202 		for (regs[rd] = NULL; addr < limit; addr++) {
3203 			if ((c = dtrace_load8(addr)) == target) {
3204 				regs[rd] = addr;
3205 
3206 				if (subr == DIF_SUBR_STRCHR)
3207 					break;
3208 			}
3209 
3210 			if (c == '\0')
3211 				break;
3212 		}
3213 
3214 		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3215 			regs[rd] = NULL;
3216 			break;
3217 		}
3218 
3219 		break;
3220 	}
3221 
3222 	case DIF_SUBR_STRSTR:
3223 	case DIF_SUBR_INDEX:
3224 	case DIF_SUBR_RINDEX: {
3225 		/*
3226 		 * We're going to iterate over the string looking for the
3227 		 * specified string.  We will iterate until we have reached
3228 		 * the string length or we have found the string.  (Yes, this
3229 		 * is done in the most naive way possible -- but considering
3230 		 * that the string we're searching for is likely to be
3231 		 * relatively short, the complexity of Rabin-Karp or similar
3232 		 * hardly seems merited.)
3233 		 */
3234 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3235 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3236 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3237 		size_t len = dtrace_strlen(addr, size);
3238 		size_t sublen = dtrace_strlen(substr, size);
3239 		char *limit = addr + len, *orig = addr;
3240 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3241 		int inc = 1;
3242 
3243 		regs[rd] = notfound;
3244 
3245 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3246 			regs[rd] = NULL;
3247 			break;
3248 		}
3249 
3250 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3251 		    vstate)) {
3252 			regs[rd] = NULL;
3253 			break;
3254 		}
3255 
3256 		/*
3257 		 * strstr() and index()/rindex() have similar semantics if
3258 		 * both strings are the empty string: strstr() returns a
3259 		 * pointer to the (empty) string, and index() and rindex()
3260 		 * both return index 0 (regardless of any position argument).
3261 		 */
3262 		if (sublen == 0 && len == 0) {
3263 			if (subr == DIF_SUBR_STRSTR)
3264 				regs[rd] = (uintptr_t)addr;
3265 			else
3266 				regs[rd] = 0;
3267 			break;
3268 		}
3269 
3270 		if (subr != DIF_SUBR_STRSTR) {
3271 			if (subr == DIF_SUBR_RINDEX) {
3272 				limit = orig - 1;
3273 				addr += len;
3274 				inc = -1;
3275 			}
3276 
3277 			/*
3278 			 * Both index() and rindex() take an optional position
3279 			 * argument that denotes the starting position.
3280 			 */
3281 			if (nargs == 3) {
3282 				int64_t pos = (int64_t)tupregs[2].dttk_value;
3283 
3284 				/*
3285 				 * If the position argument to index() is
3286 				 * negative, Perl implicitly clamps it at
3287 				 * zero.  This semantic is a little surprising
3288 				 * given the special meaning of negative
3289 				 * positions to similar Perl functions like
3290 				 * substr(), but it appears to reflect a
3291 				 * notion that index() can start from a
3292 				 * negative index and increment its way up to
3293 				 * the string.  Given this notion, Perl's
3294 				 * rindex() is at least self-consistent in
3295 				 * that it implicitly clamps positions greater
3296 				 * than the string length to be the string
3297 				 * length.  Where Perl completely loses
3298 				 * coherence, however, is when the specified
3299 				 * substring is the empty string ("").  In
3300 				 * this case, even if the position is
3301 				 * negative, rindex() returns 0 -- and even if
3302 				 * the position is greater than the length,
3303 				 * index() returns the string length.  These
3304 				 * semantics violate the notion that index()
3305 				 * should never return a value less than the
3306 				 * specified position and that rindex() should
3307 				 * never return a value greater than the
3308 				 * specified position.  (One assumes that
3309 				 * these semantics are artifacts of Perl's
3310 				 * implementation and not the results of
3311 				 * deliberate design -- it beggars belief that
3312 				 * even Larry Wall could desire such oddness.)
3313 				 * While in the abstract one would wish for
3314 				 * consistent position semantics across
3315 				 * substr(), index() and rindex() -- or at the
3316 				 * very least self-consistent position
3317 				 * semantics for index() and rindex() -- we
3318 				 * instead opt to keep with the extant Perl
3319 				 * semantics, in all their broken glory.  (Do
3320 				 * we have more desire to maintain Perl's
3321 				 * semantics than Perl does?  Probably.)
3322 				 */
3323 				if (subr == DIF_SUBR_RINDEX) {
3324 					if (pos < 0) {
3325 						if (sublen == 0)
3326 							regs[rd] = 0;
3327 						break;
3328 					}
3329 
3330 					if (pos > len)
3331 						pos = len;
3332 				} else {
3333 					if (pos < 0)
3334 						pos = 0;
3335 
3336 					if (pos >= len) {
3337 						if (sublen == 0)
3338 							regs[rd] = len;
3339 						break;
3340 					}
3341 				}
3342 
3343 				addr = orig + pos;
3344 			}
3345 		}
3346 
3347 		for (regs[rd] = notfound; addr != limit; addr += inc) {
3348 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
3349 				if (subr != DIF_SUBR_STRSTR) {
3350 					/*
3351 					 * As D index() and rindex() are
3352 					 * modeled on Perl (and not on awk),
3353 					 * we return a zero-based (and not a
3354 					 * one-based) index.  (For you Perl
3355 					 * weenies: no, we're not going to add
3356 					 * $[ -- and shouldn't you be at a con
3357 					 * or something?)
3358 					 */
3359 					regs[rd] = (uintptr_t)(addr - orig);
3360 					break;
3361 				}
3362 
3363 				ASSERT(subr == DIF_SUBR_STRSTR);
3364 				regs[rd] = (uintptr_t)addr;
3365 				break;
3366 			}
3367 		}
3368 
3369 		break;
3370 	}
3371 
3372 	case DIF_SUBR_STRTOK: {
3373 		uintptr_t addr = tupregs[0].dttk_value;
3374 		uintptr_t tokaddr = tupregs[1].dttk_value;
3375 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3376 		uintptr_t limit, toklimit = tokaddr + size;
3377 		uint8_t c, tokmap[32];	 /* 256 / 8 */
3378 		char *dest = (char *)mstate->dtms_scratch_ptr;
3379 		int i;
3380 
3381 		/*
3382 		 * Check both the token buffer and (later) the input buffer,
3383 		 * since both could be non-scratch addresses.
3384 		 */
3385 		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3386 			regs[rd] = NULL;
3387 			break;
3388 		}
3389 
3390 		if (!DTRACE_INSCRATCH(mstate, size)) {
3391 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3392 			regs[rd] = NULL;
3393 			break;
3394 		}
3395 
3396 		if (addr == NULL) {
3397 			/*
3398 			 * If the address specified is NULL, we use our saved
3399 			 * strtok pointer from the mstate.  Note that this
3400 			 * means that the saved strtok pointer is _only_
3401 			 * valid within multiple enablings of the same probe --
3402 			 * it behaves like an implicit clause-local variable.
3403 			 */
3404 			addr = mstate->dtms_strtok;
3405 		} else {
3406 			/*
3407 			 * If the user-specified address is non-NULL we must
3408 			 * access check it.  This is the only time we have
3409 			 * a chance to do so, since this address may reside
3410 			 * in the string table of this clause-- future calls
3411 			 * (when we fetch addr from mstate->dtms_strtok)
3412 			 * would fail this access check.
3413 			 */
3414 			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3415 				regs[rd] = NULL;
3416 				break;
3417 			}
3418 		}
3419 
3420 		/*
3421 		 * First, zero the token map, and then process the token
3422 		 * string -- setting a bit in the map for every character
3423 		 * found in the token string.
3424 		 */
3425 		for (i = 0; i < sizeof (tokmap); i++)
3426 			tokmap[i] = 0;
3427 
3428 		for (; tokaddr < toklimit; tokaddr++) {
3429 			if ((c = dtrace_load8(tokaddr)) == '\0')
3430 				break;
3431 
3432 			ASSERT((c >> 3) < sizeof (tokmap));
3433 			tokmap[c >> 3] |= (1 << (c & 0x7));
3434 		}
3435 
3436 		for (limit = addr + size; addr < limit; addr++) {
3437 			/*
3438 			 * We're looking for a character that is _not_ contained
3439 			 * in the token string.
3440 			 */
3441 			if ((c = dtrace_load8(addr)) == '\0')
3442 				break;
3443 
3444 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3445 				break;
3446 		}
3447 
3448 		if (c == '\0') {
3449 			/*
3450 			 * We reached the end of the string without finding
3451 			 * any character that was not in the token string.
3452 			 * We return NULL in this case, and we set the saved
3453 			 * address to NULL as well.
3454 			 */
3455 			regs[rd] = NULL;
3456 			mstate->dtms_strtok = NULL;
3457 			break;
3458 		}
3459 
3460 		/*
3461 		 * From here on, we're copying into the destination string.
3462 		 */
3463 		for (i = 0; addr < limit && i < size - 1; addr++) {
3464 			if ((c = dtrace_load8(addr)) == '\0')
3465 				break;
3466 
3467 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
3468 				break;
3469 
3470 			ASSERT(i < size);
3471 			dest[i++] = c;
3472 		}
3473 
3474 		ASSERT(i < size);
3475 		dest[i] = '\0';
3476 		regs[rd] = (uintptr_t)dest;
3477 		mstate->dtms_scratch_ptr += size;
3478 		mstate->dtms_strtok = addr;
3479 		break;
3480 	}
3481 
3482 	case DIF_SUBR_SUBSTR: {
3483 		uintptr_t s = tupregs[0].dttk_value;
3484 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3485 		char *d = (char *)mstate->dtms_scratch_ptr;
3486 		int64_t index = (int64_t)tupregs[1].dttk_value;
3487 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
3488 		size_t len = dtrace_strlen((char *)s, size);
3489 		int64_t i = 0;
3490 
3491 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
3492 			regs[rd] = NULL;
3493 			break;
3494 		}
3495 
3496 		if (nargs <= 2)
3497 			remaining = (int64_t)size;
3498 
3499 		if (!DTRACE_INSCRATCH(mstate, size)) {
3500 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3501 			regs[rd] = NULL;
3502 			break;
3503 		}
3504 
3505 		if (index < 0) {
3506 			index += len;
3507 
3508 			if (index < 0 && index + remaining > 0) {
3509 				remaining += index;
3510 				index = 0;
3511 			}
3512 		}
3513 
3514 		if (index >= len || index < 0)
3515 			index = len;
3516 
3517 		for (d[0] = '\0'; remaining > 0; remaining--) {
3518 			if ((d[i++] = dtrace_load8(s++ + index)) == '\0')
3519 				break;
3520 
3521 			if (i == size) {
3522 				d[i - 1] = '\0';
3523 				break;
3524 			}
3525 		}
3526 
3527 		mstate->dtms_scratch_ptr += size;
3528 		regs[rd] = (uintptr_t)d;
3529 		break;
3530 	}
3531 
3532 	case DIF_SUBR_GETMAJOR:
3533 #ifdef _LP64
3534 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
3535 #else
3536 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
3537 #endif
3538 		break;
3539 
3540 	case DIF_SUBR_GETMINOR:
3541 #ifdef _LP64
3542 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
3543 #else
3544 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
3545 #endif
3546 		break;
3547 
3548 	case DIF_SUBR_DDI_PATHNAME: {
3549 		/*
3550 		 * This one is a galactic mess.  We are going to roughly
3551 		 * emulate ddi_pathname(), but it's made more complicated
3552 		 * by the fact that we (a) want to include the minor name and
3553 		 * (b) must proceed iteratively instead of recursively.
3554 		 */
3555 		uintptr_t dest = mstate->dtms_scratch_ptr;
3556 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3557 		char *start = (char *)dest, *end = start + size - 1;
3558 		uintptr_t daddr = tupregs[0].dttk_value;
3559 		int64_t minor = (int64_t)tupregs[1].dttk_value;
3560 		char *s;
3561 		int i, len, depth = 0;
3562 
3563 		/*
3564 		 * Due to all the pointer jumping we do and context we must
3565 		 * rely upon, we just mandate that the user must have kernel
3566 		 * read privileges to use this routine.
3567 		 */
3568 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
3569 			*flags |= CPU_DTRACE_KPRIV;
3570 			*illval = daddr;
3571 			regs[rd] = NULL;
3572 		}
3573 
3574 		if (!DTRACE_INSCRATCH(mstate, size)) {
3575 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3576 			regs[rd] = NULL;
3577 			break;
3578 		}
3579 
3580 		*end = '\0';
3581 
3582 		/*
3583 		 * We want to have a name for the minor.  In order to do this,
3584 		 * we need to walk the minor list from the devinfo.  We want
3585 		 * to be sure that we don't infinitely walk a circular list,
3586 		 * so we check for circularity by sending a scout pointer
3587 		 * ahead two elements for every element that we iterate over;
3588 		 * if the list is circular, these will ultimately point to the
3589 		 * same element.  You may recognize this little trick as the
3590 		 * answer to a stupid interview question -- one that always
3591 		 * seems to be asked by those who had to have it laboriously
3592 		 * explained to them, and who can't even concisely describe
3593 		 * the conditions under which one would be forced to resort to
3594 		 * this technique.  Needless to say, those conditions are
3595 		 * found here -- and probably only here.  Is this is the only
3596 		 * use of this infamous trick in shipping, production code?
3597 		 * If it isn't, it probably should be...
3598 		 */
3599 		if (minor != -1) {
3600 			uintptr_t maddr = dtrace_loadptr(daddr +
3601 			    offsetof(struct dev_info, devi_minor));
3602 
3603 			uintptr_t next = offsetof(struct ddi_minor_data, next);
3604 			uintptr_t name = offsetof(struct ddi_minor_data,
3605 			    d_minor) + offsetof(struct ddi_minor, name);
3606 			uintptr_t dev = offsetof(struct ddi_minor_data,
3607 			    d_minor) + offsetof(struct ddi_minor, dev);
3608 			uintptr_t scout;
3609 
3610 			if (maddr != NULL)
3611 				scout = dtrace_loadptr(maddr + next);
3612 
3613 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3614 				uint64_t m;
3615 #ifdef _LP64
3616 				m = dtrace_load64(maddr + dev) & MAXMIN64;
3617 #else
3618 				m = dtrace_load32(maddr + dev) & MAXMIN;
3619 #endif
3620 				if (m != minor) {
3621 					maddr = dtrace_loadptr(maddr + next);
3622 
3623 					if (scout == NULL)
3624 						continue;
3625 
3626 					scout = dtrace_loadptr(scout + next);
3627 
3628 					if (scout == NULL)
3629 						continue;
3630 
3631 					scout = dtrace_loadptr(scout + next);
3632 
3633 					if (scout == NULL)
3634 						continue;
3635 
3636 					if (scout == maddr) {
3637 						*flags |= CPU_DTRACE_ILLOP;
3638 						break;
3639 					}
3640 
3641 					continue;
3642 				}
3643 
3644 				/*
3645 				 * We have the minor data.  Now we need to
3646 				 * copy the minor's name into the end of the
3647 				 * pathname.
3648 				 */
3649 				s = (char *)dtrace_loadptr(maddr + name);
3650 				len = dtrace_strlen(s, size);
3651 
3652 				if (*flags & CPU_DTRACE_FAULT)
3653 					break;
3654 
3655 				if (len != 0) {
3656 					if ((end -= (len + 1)) < start)
3657 						break;
3658 
3659 					*end = ':';
3660 				}
3661 
3662 				for (i = 1; i <= len; i++)
3663 					end[i] = dtrace_load8((uintptr_t)s++);
3664 				break;
3665 			}
3666 		}
3667 
3668 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3669 			ddi_node_state_t devi_state;
3670 
3671 			devi_state = dtrace_load32(daddr +
3672 			    offsetof(struct dev_info, devi_node_state));
3673 
3674 			if (*flags & CPU_DTRACE_FAULT)
3675 				break;
3676 
3677 			if (devi_state >= DS_INITIALIZED) {
3678 				s = (char *)dtrace_loadptr(daddr +
3679 				    offsetof(struct dev_info, devi_addr));
3680 				len = dtrace_strlen(s, size);
3681 
3682 				if (*flags & CPU_DTRACE_FAULT)
3683 					break;
3684 
3685 				if (len != 0) {
3686 					if ((end -= (len + 1)) < start)
3687 						break;
3688 
3689 					*end = '@';
3690 				}
3691 
3692 				for (i = 1; i <= len; i++)
3693 					end[i] = dtrace_load8((uintptr_t)s++);
3694 			}
3695 
3696 			/*
3697 			 * Now for the node name...
3698 			 */
3699 			s = (char *)dtrace_loadptr(daddr +
3700 			    offsetof(struct dev_info, devi_node_name));
3701 
3702 			daddr = dtrace_loadptr(daddr +
3703 			    offsetof(struct dev_info, devi_parent));
3704 
3705 			/*
3706 			 * If our parent is NULL (that is, if we're the root
3707 			 * node), we're going to use the special path
3708 			 * "devices".
3709 			 */
3710 			if (daddr == NULL)
3711 				s = "devices";
3712 
3713 			len = dtrace_strlen(s, size);
3714 			if (*flags & CPU_DTRACE_FAULT)
3715 				break;
3716 
3717 			if ((end -= (len + 1)) < start)
3718 				break;
3719 
3720 			for (i = 1; i <= len; i++)
3721 				end[i] = dtrace_load8((uintptr_t)s++);
3722 			*end = '/';
3723 
3724 			if (depth++ > dtrace_devdepth_max) {
3725 				*flags |= CPU_DTRACE_ILLOP;
3726 				break;
3727 			}
3728 		}
3729 
3730 		if (end < start)
3731 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3732 
3733 		if (daddr == NULL) {
3734 			regs[rd] = (uintptr_t)end;
3735 			mstate->dtms_scratch_ptr += size;
3736 		}
3737 
3738 		break;
3739 	}
3740 
3741 	case DIF_SUBR_STRJOIN: {
3742 		char *d = (char *)mstate->dtms_scratch_ptr;
3743 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3744 		uintptr_t s1 = tupregs[0].dttk_value;
3745 		uintptr_t s2 = tupregs[1].dttk_value;
3746 		int i = 0;
3747 
3748 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
3749 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
3750 			regs[rd] = NULL;
3751 			break;
3752 		}
3753 
3754 		if (!DTRACE_INSCRATCH(mstate, size)) {
3755 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3756 			regs[rd] = NULL;
3757 			break;
3758 		}
3759 
3760 		for (;;) {
3761 			if (i >= size) {
3762 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3763 				regs[rd] = NULL;
3764 				break;
3765 			}
3766 
3767 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
3768 				i--;
3769 				break;
3770 			}
3771 		}
3772 
3773 		for (;;) {
3774 			if (i >= size) {
3775 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3776 				regs[rd] = NULL;
3777 				break;
3778 			}
3779 
3780 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
3781 				break;
3782 		}
3783 
3784 		if (i < size) {
3785 			mstate->dtms_scratch_ptr += i;
3786 			regs[rd] = (uintptr_t)d;
3787 		}
3788 
3789 		break;
3790 	}
3791 
3792 	case DIF_SUBR_LLTOSTR: {
3793 		int64_t i = (int64_t)tupregs[0].dttk_value;
3794 		int64_t val = i < 0 ? i * -1 : i;
3795 		uint64_t size = 22;	/* enough room for 2^64 in decimal */
3796 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
3797 
3798 		if (!DTRACE_INSCRATCH(mstate, size)) {
3799 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3800 			regs[rd] = NULL;
3801 			break;
3802 		}
3803 
3804 		for (*end-- = '\0'; val; val /= 10)
3805 			*end-- = '0' + (val % 10);
3806 
3807 		if (i == 0)
3808 			*end-- = '0';
3809 
3810 		if (i < 0)
3811 			*end-- = '-';
3812 
3813 		regs[rd] = (uintptr_t)end + 1;
3814 		mstate->dtms_scratch_ptr += size;
3815 		break;
3816 	}
3817 
3818 	case DIF_SUBR_HTONS:
3819 	case DIF_SUBR_NTOHS:
3820 #ifdef _BIG_ENDIAN
3821 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
3822 #else
3823 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
3824 #endif
3825 		break;
3826 
3827 
3828 	case DIF_SUBR_HTONL:
3829 	case DIF_SUBR_NTOHL:
3830 #ifdef _BIG_ENDIAN
3831 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
3832 #else
3833 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
3834 #endif
3835 		break;
3836 
3837 
3838 	case DIF_SUBR_HTONLL:
3839 	case DIF_SUBR_NTOHLL:
3840 #ifdef _BIG_ENDIAN
3841 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
3842 #else
3843 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
3844 #endif
3845 		break;
3846 
3847 
3848 	case DIF_SUBR_DIRNAME:
3849 	case DIF_SUBR_BASENAME: {
3850 		char *dest = (char *)mstate->dtms_scratch_ptr;
3851 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3852 		uintptr_t src = tupregs[0].dttk_value;
3853 		int i, j, len = dtrace_strlen((char *)src, size);
3854 		int lastbase = -1, firstbase = -1, lastdir = -1;
3855 		int start, end;
3856 
3857 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
3858 			regs[rd] = NULL;
3859 			break;
3860 		}
3861 
3862 		if (!DTRACE_INSCRATCH(mstate, size)) {
3863 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3864 			regs[rd] = NULL;
3865 			break;
3866 		}
3867 
3868 		/*
3869 		 * The basename and dirname for a zero-length string is
3870 		 * defined to be "."
3871 		 */
3872 		if (len == 0) {
3873 			len = 1;
3874 			src = (uintptr_t)".";
3875 		}
3876 
3877 		/*
3878 		 * Start from the back of the string, moving back toward the
3879 		 * front until we see a character that isn't a slash.  That
3880 		 * character is the last character in the basename.
3881 		 */
3882 		for (i = len - 1; i >= 0; i--) {
3883 			if (dtrace_load8(src + i) != '/')
3884 				break;
3885 		}
3886 
3887 		if (i >= 0)
3888 			lastbase = i;
3889 
3890 		/*
3891 		 * Starting from the last character in the basename, move
3892 		 * towards the front until we find a slash.  The character
3893 		 * that we processed immediately before that is the first
3894 		 * character in the basename.
3895 		 */
3896 		for (; i >= 0; i--) {
3897 			if (dtrace_load8(src + i) == '/')
3898 				break;
3899 		}
3900 
3901 		if (i >= 0)
3902 			firstbase = i + 1;
3903 
3904 		/*
3905 		 * Now keep going until we find a non-slash character.  That
3906 		 * character is the last character in the dirname.
3907 		 */
3908 		for (; i >= 0; i--) {
3909 			if (dtrace_load8(src + i) != '/')
3910 				break;
3911 		}
3912 
3913 		if (i >= 0)
3914 			lastdir = i;
3915 
3916 		ASSERT(!(lastbase == -1 && firstbase != -1));
3917 		ASSERT(!(firstbase == -1 && lastdir != -1));
3918 
3919 		if (lastbase == -1) {
3920 			/*
3921 			 * We didn't find a non-slash character.  We know that
3922 			 * the length is non-zero, so the whole string must be
3923 			 * slashes.  In either the dirname or the basename
3924 			 * case, we return '/'.
3925 			 */
3926 			ASSERT(firstbase == -1);
3927 			firstbase = lastbase = lastdir = 0;
3928 		}
3929 
3930 		if (firstbase == -1) {
3931 			/*
3932 			 * The entire string consists only of a basename
3933 			 * component.  If we're looking for dirname, we need
3934 			 * to change our string to be just "."; if we're
3935 			 * looking for a basename, we'll just set the first
3936 			 * character of the basename to be 0.
3937 			 */
3938 			if (subr == DIF_SUBR_DIRNAME) {
3939 				ASSERT(lastdir == -1);
3940 				src = (uintptr_t)".";
3941 				lastdir = 0;
3942 			} else {
3943 				firstbase = 0;
3944 			}
3945 		}
3946 
3947 		if (subr == DIF_SUBR_DIRNAME) {
3948 			if (lastdir == -1) {
3949 				/*
3950 				 * We know that we have a slash in the name --
3951 				 * or lastdir would be set to 0, above.  And
3952 				 * because lastdir is -1, we know that this
3953 				 * slash must be the first character.  (That
3954 				 * is, the full string must be of the form
3955 				 * "/basename".)  In this case, the last
3956 				 * character of the directory name is 0.
3957 				 */
3958 				lastdir = 0;
3959 			}
3960 
3961 			start = 0;
3962 			end = lastdir;
3963 		} else {
3964 			ASSERT(subr == DIF_SUBR_BASENAME);
3965 			ASSERT(firstbase != -1 && lastbase != -1);
3966 			start = firstbase;
3967 			end = lastbase;
3968 		}
3969 
3970 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
3971 			dest[j] = dtrace_load8(src + i);
3972 
3973 		dest[j] = '\0';
3974 		regs[rd] = (uintptr_t)dest;
3975 		mstate->dtms_scratch_ptr += size;
3976 		break;
3977 	}
3978 
3979 	case DIF_SUBR_CLEANPATH: {
3980 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
3981 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3982 		uintptr_t src = tupregs[0].dttk_value;
3983 		int i = 0, j = 0;
3984 
3985 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
3986 			regs[rd] = NULL;
3987 			break;
3988 		}
3989 
3990 		if (!DTRACE_INSCRATCH(mstate, size)) {
3991 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3992 			regs[rd] = NULL;
3993 			break;
3994 		}
3995 
3996 		/*
3997 		 * Move forward, loading each character.
3998 		 */
3999 		do {
4000 			c = dtrace_load8(src + i++);
4001 next:
4002 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
4003 				break;
4004 
4005 			if (c != '/') {
4006 				dest[j++] = c;
4007 				continue;
4008 			}
4009 
4010 			c = dtrace_load8(src + i++);
4011 
4012 			if (c == '/') {
4013 				/*
4014 				 * We have two slashes -- we can just advance
4015 				 * to the next character.
4016 				 */
4017 				goto next;
4018 			}
4019 
4020 			if (c != '.') {
4021 				/*
4022 				 * This is not "." and it's not ".." -- we can
4023 				 * just store the "/" and this character and
4024 				 * drive on.
4025 				 */
4026 				dest[j++] = '/';
4027 				dest[j++] = c;
4028 				continue;
4029 			}
4030 
4031 			c = dtrace_load8(src + i++);
4032 
4033 			if (c == '/') {
4034 				/*
4035 				 * This is a "/./" component.  We're not going
4036 				 * to store anything in the destination buffer;
4037 				 * we're just going to go to the next component.
4038 				 */
4039 				goto next;
4040 			}
4041 
4042 			if (c != '.') {
4043 				/*
4044 				 * This is not ".." -- we can just store the
4045 				 * "/." and this character and continue
4046 				 * processing.
4047 				 */
4048 				dest[j++] = '/';
4049 				dest[j++] = '.';
4050 				dest[j++] = c;
4051 				continue;
4052 			}
4053 
4054 			c = dtrace_load8(src + i++);
4055 
4056 			if (c != '/' && c != '\0') {
4057 				/*
4058 				 * This is not ".." -- it's "..[mumble]".
4059 				 * We'll store the "/.." and this character
4060 				 * and continue processing.
4061 				 */
4062 				dest[j++] = '/';
4063 				dest[j++] = '.';
4064 				dest[j++] = '.';
4065 				dest[j++] = c;
4066 				continue;
4067 			}
4068 
4069 			/*
4070 			 * This is "/../" or "/..\0".  We need to back up
4071 			 * our destination pointer until we find a "/".
4072 			 */
4073 			i--;
4074 			while (j != 0 && dest[--j] != '/')
4075 				continue;
4076 
4077 			if (c == '\0')
4078 				dest[++j] = '/';
4079 		} while (c != '\0');
4080 
4081 		dest[j] = '\0';
4082 		regs[rd] = (uintptr_t)dest;
4083 		mstate->dtms_scratch_ptr += size;
4084 		break;
4085 	}
4086 
4087 	case DIF_SUBR_INET_NTOA:
4088 	case DIF_SUBR_INET_NTOA6:
4089 	case DIF_SUBR_INET_NTOP: {
4090 		size_t size;
4091 		int af, argi, i;
4092 		char *base, *end;
4093 
4094 		if (subr == DIF_SUBR_INET_NTOP) {
4095 			af = (int)tupregs[0].dttk_value;
4096 			argi = 1;
4097 		} else {
4098 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4099 			argi = 0;
4100 		}
4101 
4102 		if (af == AF_INET) {
4103 			ipaddr_t ip4;
4104 			uint8_t *ptr8, val;
4105 
4106 			/*
4107 			 * Safely load the IPv4 address.
4108 			 */
4109 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
4110 
4111 			/*
4112 			 * Check an IPv4 string will fit in scratch.
4113 			 */
4114 			size = INET_ADDRSTRLEN;
4115 			if (!DTRACE_INSCRATCH(mstate, size)) {
4116 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4117 				regs[rd] = NULL;
4118 				break;
4119 			}
4120 			base = (char *)mstate->dtms_scratch_ptr;
4121 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4122 
4123 			/*
4124 			 * Stringify as a dotted decimal quad.
4125 			 */
4126 			*end-- = '\0';
4127 			ptr8 = (uint8_t *)&ip4;
4128 			for (i = 3; i >= 0; i--) {
4129 				val = ptr8[i];
4130 
4131 				if (val == 0) {
4132 					*end-- = '0';
4133 				} else {
4134 					for (; val; val /= 10) {
4135 						*end-- = '0' + (val % 10);
4136 					}
4137 				}
4138 
4139 				if (i > 0)
4140 					*end-- = '.';
4141 			}
4142 			ASSERT(end + 1 >= base);
4143 
4144 		} else if (af == AF_INET6) {
4145 			struct in6_addr ip6;
4146 			int firstzero, tryzero, numzero, v6end;
4147 			uint16_t val;
4148 			const char digits[] = "0123456789abcdef";
4149 
4150 			/*
4151 			 * Stringify using RFC 1884 convention 2 - 16 bit
4152 			 * hexadecimal values with a zero-run compression.
4153 			 * Lower case hexadecimal digits are used.
4154 			 * 	eg, fe80::214:4fff:fe0b:76c8.
4155 			 * The IPv4 embedded form is returned for inet_ntop,
4156 			 * just the IPv4 string is returned for inet_ntoa6.
4157 			 */
4158 
4159 			/*
4160 			 * Safely load the IPv6 address.
4161 			 */
4162 			dtrace_bcopy(
4163 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
4164 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4165 
4166 			/*
4167 			 * Check an IPv6 string will fit in scratch.
4168 			 */
4169 			size = INET6_ADDRSTRLEN;
4170 			if (!DTRACE_INSCRATCH(mstate, size)) {
4171 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4172 				regs[rd] = NULL;
4173 				break;
4174 			}
4175 			base = (char *)mstate->dtms_scratch_ptr;
4176 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4177 			*end-- = '\0';
4178 
4179 			/*
4180 			 * Find the longest run of 16 bit zero values
4181 			 * for the single allowed zero compression - "::".
4182 			 */
4183 			firstzero = -1;
4184 			tryzero = -1;
4185 			numzero = 1;
4186 			for (i = 0; i < sizeof (struct in6_addr); i++) {
4187 				if (ip6._S6_un._S6_u8[i] == 0 &&
4188 				    tryzero == -1 && i % 2 == 0) {
4189 					tryzero = i;
4190 					continue;
4191 				}
4192 
4193 				if (tryzero != -1 &&
4194 				    (ip6._S6_un._S6_u8[i] != 0 ||
4195 				    i == sizeof (struct in6_addr) - 1)) {
4196 
4197 					if (i - tryzero <= numzero) {
4198 						tryzero = -1;
4199 						continue;
4200 					}
4201 
4202 					firstzero = tryzero;
4203 					numzero = i - i % 2 - tryzero;
4204 					tryzero = -1;
4205 
4206 					if (ip6._S6_un._S6_u8[i] == 0 &&
4207 					    i == sizeof (struct in6_addr) - 1)
4208 						numzero += 2;
4209 				}
4210 			}
4211 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4212 
4213 			/*
4214 			 * Check for an IPv4 embedded address.
4215 			 */
4216 			v6end = sizeof (struct in6_addr) - 2;
4217 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4218 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
4219 				for (i = sizeof (struct in6_addr) - 1;
4220 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
4221 					ASSERT(end >= base);
4222 
4223 					val = ip6._S6_un._S6_u8[i];
4224 
4225 					if (val == 0) {
4226 						*end-- = '0';
4227 					} else {
4228 						for (; val; val /= 10) {
4229 							*end-- = '0' + val % 10;
4230 						}
4231 					}
4232 
4233 					if (i > DTRACE_V4MAPPED_OFFSET)
4234 						*end-- = '.';
4235 				}
4236 
4237 				if (subr == DIF_SUBR_INET_NTOA6)
4238 					goto inetout;
4239 
4240 				/*
4241 				 * Set v6end to skip the IPv4 address that
4242 				 * we have already stringified.
4243 				 */
4244 				v6end = 10;
4245 			}
4246 
4247 			/*
4248 			 * Build the IPv6 string by working through the
4249 			 * address in reverse.
4250 			 */
4251 			for (i = v6end; i >= 0; i -= 2) {
4252 				ASSERT(end >= base);
4253 
4254 				if (i == firstzero + numzero - 2) {
4255 					*end-- = ':';
4256 					*end-- = ':';
4257 					i -= numzero - 2;
4258 					continue;
4259 				}
4260 
4261 				if (i < 14 && i != firstzero - 2)
4262 					*end-- = ':';
4263 
4264 				val = (ip6._S6_un._S6_u8[i] << 8) +
4265 				    ip6._S6_un._S6_u8[i + 1];
4266 
4267 				if (val == 0) {
4268 					*end-- = '0';
4269 				} else {
4270 					for (; val; val /= 16) {
4271 						*end-- = digits[val % 16];
4272 					}
4273 				}
4274 			}
4275 			ASSERT(end + 1 >= base);
4276 
4277 		} else {
4278 			/*
4279 			 * The user didn't use AH_INET or AH_INET6.
4280 			 */
4281 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4282 			regs[rd] = NULL;
4283 			break;
4284 		}
4285 
4286 inetout:	regs[rd] = (uintptr_t)end + 1;
4287 		mstate->dtms_scratch_ptr += size;
4288 		break;
4289 	}
4290 
4291 	}
4292 }
4293 
4294 /*
4295  * Emulate the execution of DTrace IR instructions specified by the given
4296  * DIF object.  This function is deliberately void of assertions as all of
4297  * the necessary checks are handled by a call to dtrace_difo_validate().
4298  */
4299 static uint64_t
4300 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4301     dtrace_vstate_t *vstate, dtrace_state_t *state)
4302 {
4303 	const dif_instr_t *text = difo->dtdo_buf;
4304 	const uint_t textlen = difo->dtdo_len;
4305 	const char *strtab = difo->dtdo_strtab;
4306 	const uint64_t *inttab = difo->dtdo_inttab;
4307 
4308 	uint64_t rval = 0;
4309 	dtrace_statvar_t *svar;
4310 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4311 	dtrace_difv_t *v;
4312 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4313 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4314 
4315 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4316 	uint64_t regs[DIF_DIR_NREGS];
4317 	uint64_t *tmp;
4318 
4319 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4320 	int64_t cc_r;
4321 	uint_t pc = 0, id, opc;
4322 	uint8_t ttop = 0;
4323 	dif_instr_t instr;
4324 	uint_t r1, r2, rd;
4325 
4326 	/*
4327 	 * We stash the current DIF object into the machine state: we need it
4328 	 * for subsequent access checking.
4329 	 */
4330 	mstate->dtms_difo = difo;
4331 
4332 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
4333 
4334 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4335 		opc = pc;
4336 
4337 		instr = text[pc++];
4338 		r1 = DIF_INSTR_R1(instr);
4339 		r2 = DIF_INSTR_R2(instr);
4340 		rd = DIF_INSTR_RD(instr);
4341 
4342 		switch (DIF_INSTR_OP(instr)) {
4343 		case DIF_OP_OR:
4344 			regs[rd] = regs[r1] | regs[r2];
4345 			break;
4346 		case DIF_OP_XOR:
4347 			regs[rd] = regs[r1] ^ regs[r2];
4348 			break;
4349 		case DIF_OP_AND:
4350 			regs[rd] = regs[r1] & regs[r2];
4351 			break;
4352 		case DIF_OP_SLL:
4353 			regs[rd] = regs[r1] << regs[r2];
4354 			break;
4355 		case DIF_OP_SRL:
4356 			regs[rd] = regs[r1] >> regs[r2];
4357 			break;
4358 		case DIF_OP_SUB:
4359 			regs[rd] = regs[r1] - regs[r2];
4360 			break;
4361 		case DIF_OP_ADD:
4362 			regs[rd] = regs[r1] + regs[r2];
4363 			break;
4364 		case DIF_OP_MUL:
4365 			regs[rd] = regs[r1] * regs[r2];
4366 			break;
4367 		case DIF_OP_SDIV:
4368 			if (regs[r2] == 0) {
4369 				regs[rd] = 0;
4370 				*flags |= CPU_DTRACE_DIVZERO;
4371 			} else {
4372 				regs[rd] = (int64_t)regs[r1] /
4373 				    (int64_t)regs[r2];
4374 			}
4375 			break;
4376 
4377 		case DIF_OP_UDIV:
4378 			if (regs[r2] == 0) {
4379 				regs[rd] = 0;
4380 				*flags |= CPU_DTRACE_DIVZERO;
4381 			} else {
4382 				regs[rd] = regs[r1] / regs[r2];
4383 			}
4384 			break;
4385 
4386 		case DIF_OP_SREM:
4387 			if (regs[r2] == 0) {
4388 				regs[rd] = 0;
4389 				*flags |= CPU_DTRACE_DIVZERO;
4390 			} else {
4391 				regs[rd] = (int64_t)regs[r1] %
4392 				    (int64_t)regs[r2];
4393 			}
4394 			break;
4395 
4396 		case DIF_OP_UREM:
4397 			if (regs[r2] == 0) {
4398 				regs[rd] = 0;
4399 				*flags |= CPU_DTRACE_DIVZERO;
4400 			} else {
4401 				regs[rd] = regs[r1] % regs[r2];
4402 			}
4403 			break;
4404 
4405 		case DIF_OP_NOT:
4406 			regs[rd] = ~regs[r1];
4407 			break;
4408 		case DIF_OP_MOV:
4409 			regs[rd] = regs[r1];
4410 			break;
4411 		case DIF_OP_CMP:
4412 			cc_r = regs[r1] - regs[r2];
4413 			cc_n = cc_r < 0;
4414 			cc_z = cc_r == 0;
4415 			cc_v = 0;
4416 			cc_c = regs[r1] < regs[r2];
4417 			break;
4418 		case DIF_OP_TST:
4419 			cc_n = cc_v = cc_c = 0;
4420 			cc_z = regs[r1] == 0;
4421 			break;
4422 		case DIF_OP_BA:
4423 			pc = DIF_INSTR_LABEL(instr);
4424 			break;
4425 		case DIF_OP_BE:
4426 			if (cc_z)
4427 				pc = DIF_INSTR_LABEL(instr);
4428 			break;
4429 		case DIF_OP_BNE:
4430 			if (cc_z == 0)
4431 				pc = DIF_INSTR_LABEL(instr);
4432 			break;
4433 		case DIF_OP_BG:
4434 			if ((cc_z | (cc_n ^ cc_v)) == 0)
4435 				pc = DIF_INSTR_LABEL(instr);
4436 			break;
4437 		case DIF_OP_BGU:
4438 			if ((cc_c | cc_z) == 0)
4439 				pc = DIF_INSTR_LABEL(instr);
4440 			break;
4441 		case DIF_OP_BGE:
4442 			if ((cc_n ^ cc_v) == 0)
4443 				pc = DIF_INSTR_LABEL(instr);
4444 			break;
4445 		case DIF_OP_BGEU:
4446 			if (cc_c == 0)
4447 				pc = DIF_INSTR_LABEL(instr);
4448 			break;
4449 		case DIF_OP_BL:
4450 			if (cc_n ^ cc_v)
4451 				pc = DIF_INSTR_LABEL(instr);
4452 			break;
4453 		case DIF_OP_BLU:
4454 			if (cc_c)
4455 				pc = DIF_INSTR_LABEL(instr);
4456 			break;
4457 		case DIF_OP_BLE:
4458 			if (cc_z | (cc_n ^ cc_v))
4459 				pc = DIF_INSTR_LABEL(instr);
4460 			break;
4461 		case DIF_OP_BLEU:
4462 			if (cc_c | cc_z)
4463 				pc = DIF_INSTR_LABEL(instr);
4464 			break;
4465 		case DIF_OP_RLDSB:
4466 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4467 				*flags |= CPU_DTRACE_KPRIV;
4468 				*illval = regs[r1];
4469 				break;
4470 			}
4471 			/*FALLTHROUGH*/
4472 		case DIF_OP_LDSB:
4473 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
4474 			break;
4475 		case DIF_OP_RLDSH:
4476 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4477 				*flags |= CPU_DTRACE_KPRIV;
4478 				*illval = regs[r1];
4479 				break;
4480 			}
4481 			/*FALLTHROUGH*/
4482 		case DIF_OP_LDSH:
4483 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
4484 			break;
4485 		case DIF_OP_RLDSW:
4486 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4487 				*flags |= CPU_DTRACE_KPRIV;
4488 				*illval = regs[r1];
4489 				break;
4490 			}
4491 			/*FALLTHROUGH*/
4492 		case DIF_OP_LDSW:
4493 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
4494 			break;
4495 		case DIF_OP_RLDUB:
4496 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4497 				*flags |= CPU_DTRACE_KPRIV;
4498 				*illval = regs[r1];
4499 				break;
4500 			}
4501 			/*FALLTHROUGH*/
4502 		case DIF_OP_LDUB:
4503 			regs[rd] = dtrace_load8(regs[r1]);
4504 			break;
4505 		case DIF_OP_RLDUH:
4506 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4507 				*flags |= CPU_DTRACE_KPRIV;
4508 				*illval = regs[r1];
4509 				break;
4510 			}
4511 			/*FALLTHROUGH*/
4512 		case DIF_OP_LDUH:
4513 			regs[rd] = dtrace_load16(regs[r1]);
4514 			break;
4515 		case DIF_OP_RLDUW:
4516 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4517 				*flags |= CPU_DTRACE_KPRIV;
4518 				*illval = regs[r1];
4519 				break;
4520 			}
4521 			/*FALLTHROUGH*/
4522 		case DIF_OP_LDUW:
4523 			regs[rd] = dtrace_load32(regs[r1]);
4524 			break;
4525 		case DIF_OP_RLDX:
4526 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
4527 				*flags |= CPU_DTRACE_KPRIV;
4528 				*illval = regs[r1];
4529 				break;
4530 			}
4531 			/*FALLTHROUGH*/
4532 		case DIF_OP_LDX:
4533 			regs[rd] = dtrace_load64(regs[r1]);
4534 			break;
4535 		case DIF_OP_ULDSB:
4536 			regs[rd] = (int8_t)
4537 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4538 			break;
4539 		case DIF_OP_ULDSH:
4540 			regs[rd] = (int16_t)
4541 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4542 			break;
4543 		case DIF_OP_ULDSW:
4544 			regs[rd] = (int32_t)
4545 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4546 			break;
4547 		case DIF_OP_ULDUB:
4548 			regs[rd] =
4549 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4550 			break;
4551 		case DIF_OP_ULDUH:
4552 			regs[rd] =
4553 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4554 			break;
4555 		case DIF_OP_ULDUW:
4556 			regs[rd] =
4557 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4558 			break;
4559 		case DIF_OP_ULDX:
4560 			regs[rd] =
4561 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
4562 			break;
4563 		case DIF_OP_RET:
4564 			rval = regs[rd];
4565 			pc = textlen;
4566 			break;
4567 		case DIF_OP_NOP:
4568 			break;
4569 		case DIF_OP_SETX:
4570 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
4571 			break;
4572 		case DIF_OP_SETS:
4573 			regs[rd] = (uint64_t)(uintptr_t)
4574 			    (strtab + DIF_INSTR_STRING(instr));
4575 			break;
4576 		case DIF_OP_SCMP: {
4577 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
4578 			uintptr_t s1 = regs[r1];
4579 			uintptr_t s2 = regs[r2];
4580 
4581 			if (s1 != NULL &&
4582 			    !dtrace_strcanload(s1, sz, mstate, vstate))
4583 				break;
4584 			if (s2 != NULL &&
4585 			    !dtrace_strcanload(s2, sz, mstate, vstate))
4586 				break;
4587 
4588 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
4589 
4590 			cc_n = cc_r < 0;
4591 			cc_z = cc_r == 0;
4592 			cc_v = cc_c = 0;
4593 			break;
4594 		}
4595 		case DIF_OP_LDGA:
4596 			regs[rd] = dtrace_dif_variable(mstate, state,
4597 			    r1, regs[r2]);
4598 			break;
4599 		case DIF_OP_LDGS:
4600 			id = DIF_INSTR_VAR(instr);
4601 
4602 			if (id >= DIF_VAR_OTHER_UBASE) {
4603 				uintptr_t a;
4604 
4605 				id -= DIF_VAR_OTHER_UBASE;
4606 				svar = vstate->dtvs_globals[id];
4607 				ASSERT(svar != NULL);
4608 				v = &svar->dtsv_var;
4609 
4610 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
4611 					regs[rd] = svar->dtsv_data;
4612 					break;
4613 				}
4614 
4615 				a = (uintptr_t)svar->dtsv_data;
4616 
4617 				if (*(uint8_t *)a == UINT8_MAX) {
4618 					/*
4619 					 * If the 0th byte is set to UINT8_MAX
4620 					 * then this is to be treated as a
4621 					 * reference to a NULL variable.
4622 					 */
4623 					regs[rd] = NULL;
4624 				} else {
4625 					regs[rd] = a + sizeof (uint64_t);
4626 				}
4627 
4628 				break;
4629 			}
4630 
4631 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
4632 			break;
4633 
4634 		case DIF_OP_STGS:
4635 			id = DIF_INSTR_VAR(instr);
4636 
4637 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4638 			id -= DIF_VAR_OTHER_UBASE;
4639 
4640 			svar = vstate->dtvs_globals[id];
4641 			ASSERT(svar != NULL);
4642 			v = &svar->dtsv_var;
4643 
4644 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4645 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4646 
4647 				ASSERT(a != NULL);
4648 				ASSERT(svar->dtsv_size != 0);
4649 
4650 				if (regs[rd] == NULL) {
4651 					*(uint8_t *)a = UINT8_MAX;
4652 					break;
4653 				} else {
4654 					*(uint8_t *)a = 0;
4655 					a += sizeof (uint64_t);
4656 				}
4657 				if (!dtrace_vcanload(
4658 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4659 				    mstate, vstate))
4660 					break;
4661 
4662 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4663 				    (void *)a, &v->dtdv_type);
4664 				break;
4665 			}
4666 
4667 			svar->dtsv_data = regs[rd];
4668 			break;
4669 
4670 		case DIF_OP_LDTA:
4671 			/*
4672 			 * There are no DTrace built-in thread-local arrays at
4673 			 * present.  This opcode is saved for future work.
4674 			 */
4675 			*flags |= CPU_DTRACE_ILLOP;
4676 			regs[rd] = 0;
4677 			break;
4678 
4679 		case DIF_OP_LDLS:
4680 			id = DIF_INSTR_VAR(instr);
4681 
4682 			if (id < DIF_VAR_OTHER_UBASE) {
4683 				/*
4684 				 * For now, this has no meaning.
4685 				 */
4686 				regs[rd] = 0;
4687 				break;
4688 			}
4689 
4690 			id -= DIF_VAR_OTHER_UBASE;
4691 
4692 			ASSERT(id < vstate->dtvs_nlocals);
4693 			ASSERT(vstate->dtvs_locals != NULL);
4694 
4695 			svar = vstate->dtvs_locals[id];
4696 			ASSERT(svar != NULL);
4697 			v = &svar->dtsv_var;
4698 
4699 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4700 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4701 				size_t sz = v->dtdv_type.dtdt_size;
4702 
4703 				sz += sizeof (uint64_t);
4704 				ASSERT(svar->dtsv_size == NCPU * sz);
4705 				a += CPU->cpu_id * sz;
4706 
4707 				if (*(uint8_t *)a == UINT8_MAX) {
4708 					/*
4709 					 * If the 0th byte is set to UINT8_MAX
4710 					 * then this is to be treated as a
4711 					 * reference to a NULL variable.
4712 					 */
4713 					regs[rd] = NULL;
4714 				} else {
4715 					regs[rd] = a + sizeof (uint64_t);
4716 				}
4717 
4718 				break;
4719 			}
4720 
4721 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4722 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4723 			regs[rd] = tmp[CPU->cpu_id];
4724 			break;
4725 
4726 		case DIF_OP_STLS:
4727 			id = DIF_INSTR_VAR(instr);
4728 
4729 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4730 			id -= DIF_VAR_OTHER_UBASE;
4731 			ASSERT(id < vstate->dtvs_nlocals);
4732 
4733 			ASSERT(vstate->dtvs_locals != NULL);
4734 			svar = vstate->dtvs_locals[id];
4735 			ASSERT(svar != NULL);
4736 			v = &svar->dtsv_var;
4737 
4738 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4739 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4740 				size_t sz = v->dtdv_type.dtdt_size;
4741 
4742 				sz += sizeof (uint64_t);
4743 				ASSERT(svar->dtsv_size == NCPU * sz);
4744 				a += CPU->cpu_id * sz;
4745 
4746 				if (regs[rd] == NULL) {
4747 					*(uint8_t *)a = UINT8_MAX;
4748 					break;
4749 				} else {
4750 					*(uint8_t *)a = 0;
4751 					a += sizeof (uint64_t);
4752 				}
4753 
4754 				if (!dtrace_vcanload(
4755 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4756 				    mstate, vstate))
4757 					break;
4758 
4759 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4760 				    (void *)a, &v->dtdv_type);
4761 				break;
4762 			}
4763 
4764 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4765 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4766 			tmp[CPU->cpu_id] = regs[rd];
4767 			break;
4768 
4769 		case DIF_OP_LDTS: {
4770 			dtrace_dynvar_t *dvar;
4771 			dtrace_key_t *key;
4772 
4773 			id = DIF_INSTR_VAR(instr);
4774 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4775 			id -= DIF_VAR_OTHER_UBASE;
4776 			v = &vstate->dtvs_tlocals[id];
4777 
4778 			key = &tupregs[DIF_DTR_NREGS];
4779 			key[0].dttk_value = (uint64_t)id;
4780 			key[0].dttk_size = 0;
4781 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4782 			key[1].dttk_size = 0;
4783 
4784 			dvar = dtrace_dynvar(dstate, 2, key,
4785 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
4786 			    mstate, vstate);
4787 
4788 			if (dvar == NULL) {
4789 				regs[rd] = 0;
4790 				break;
4791 			}
4792 
4793 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4794 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4795 			} else {
4796 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4797 			}
4798 
4799 			break;
4800 		}
4801 
4802 		case DIF_OP_STTS: {
4803 			dtrace_dynvar_t *dvar;
4804 			dtrace_key_t *key;
4805 
4806 			id = DIF_INSTR_VAR(instr);
4807 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4808 			id -= DIF_VAR_OTHER_UBASE;
4809 
4810 			key = &tupregs[DIF_DTR_NREGS];
4811 			key[0].dttk_value = (uint64_t)id;
4812 			key[0].dttk_size = 0;
4813 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4814 			key[1].dttk_size = 0;
4815 			v = &vstate->dtvs_tlocals[id];
4816 
4817 			dvar = dtrace_dynvar(dstate, 2, key,
4818 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4819 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4820 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4821 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
4822 
4823 			/*
4824 			 * Given that we're storing to thread-local data,
4825 			 * we need to flush our predicate cache.
4826 			 */
4827 			curthread->t_predcache = NULL;
4828 
4829 			if (dvar == NULL)
4830 				break;
4831 
4832 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4833 				if (!dtrace_vcanload(
4834 				    (void *)(uintptr_t)regs[rd],
4835 				    &v->dtdv_type, mstate, vstate))
4836 					break;
4837 
4838 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4839 				    dvar->dtdv_data, &v->dtdv_type);
4840 			} else {
4841 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4842 			}
4843 
4844 			break;
4845 		}
4846 
4847 		case DIF_OP_SRA:
4848 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
4849 			break;
4850 
4851 		case DIF_OP_CALL:
4852 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
4853 			    regs, tupregs, ttop, mstate, state);
4854 			break;
4855 
4856 		case DIF_OP_PUSHTR:
4857 			if (ttop == DIF_DTR_NREGS) {
4858 				*flags |= CPU_DTRACE_TUPOFLOW;
4859 				break;
4860 			}
4861 
4862 			if (r1 == DIF_TYPE_STRING) {
4863 				/*
4864 				 * If this is a string type and the size is 0,
4865 				 * we'll use the system-wide default string
4866 				 * size.  Note that we are _not_ looking at
4867 				 * the value of the DTRACEOPT_STRSIZE option;
4868 				 * had this been set, we would expect to have
4869 				 * a non-zero size value in the "pushtr".
4870 				 */
4871 				tupregs[ttop].dttk_size =
4872 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
4873 				    regs[r2] ? regs[r2] :
4874 				    dtrace_strsize_default) + 1;
4875 			} else {
4876 				tupregs[ttop].dttk_size = regs[r2];
4877 			}
4878 
4879 			tupregs[ttop++].dttk_value = regs[rd];
4880 			break;
4881 
4882 		case DIF_OP_PUSHTV:
4883 			if (ttop == DIF_DTR_NREGS) {
4884 				*flags |= CPU_DTRACE_TUPOFLOW;
4885 				break;
4886 			}
4887 
4888 			tupregs[ttop].dttk_value = regs[rd];
4889 			tupregs[ttop++].dttk_size = 0;
4890 			break;
4891 
4892 		case DIF_OP_POPTS:
4893 			if (ttop != 0)
4894 				ttop--;
4895 			break;
4896 
4897 		case DIF_OP_FLUSHTS:
4898 			ttop = 0;
4899 			break;
4900 
4901 		case DIF_OP_LDGAA:
4902 		case DIF_OP_LDTAA: {
4903 			dtrace_dynvar_t *dvar;
4904 			dtrace_key_t *key = tupregs;
4905 			uint_t nkeys = ttop;
4906 
4907 			id = DIF_INSTR_VAR(instr);
4908 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4909 			id -= DIF_VAR_OTHER_UBASE;
4910 
4911 			key[nkeys].dttk_value = (uint64_t)id;
4912 			key[nkeys++].dttk_size = 0;
4913 
4914 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
4915 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4916 				key[nkeys++].dttk_size = 0;
4917 				v = &vstate->dtvs_tlocals[id];
4918 			} else {
4919 				v = &vstate->dtvs_globals[id]->dtsv_var;
4920 			}
4921 
4922 			dvar = dtrace_dynvar(dstate, nkeys, key,
4923 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4924 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4925 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
4926 
4927 			if (dvar == NULL) {
4928 				regs[rd] = 0;
4929 				break;
4930 			}
4931 
4932 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4933 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4934 			} else {
4935 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4936 			}
4937 
4938 			break;
4939 		}
4940 
4941 		case DIF_OP_STGAA:
4942 		case DIF_OP_STTAA: {
4943 			dtrace_dynvar_t *dvar;
4944 			dtrace_key_t *key = tupregs;
4945 			uint_t nkeys = ttop;
4946 
4947 			id = DIF_INSTR_VAR(instr);
4948 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4949 			id -= DIF_VAR_OTHER_UBASE;
4950 
4951 			key[nkeys].dttk_value = (uint64_t)id;
4952 			key[nkeys++].dttk_size = 0;
4953 
4954 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
4955 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4956 				key[nkeys++].dttk_size = 0;
4957 				v = &vstate->dtvs_tlocals[id];
4958 			} else {
4959 				v = &vstate->dtvs_globals[id]->dtsv_var;
4960 			}
4961 
4962 			dvar = dtrace_dynvar(dstate, nkeys, key,
4963 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4964 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4965 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4966 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
4967 
4968 			if (dvar == NULL)
4969 				break;
4970 
4971 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4972 				if (!dtrace_vcanload(
4973 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4974 				    mstate, vstate))
4975 					break;
4976 
4977 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4978 				    dvar->dtdv_data, &v->dtdv_type);
4979 			} else {
4980 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4981 			}
4982 
4983 			break;
4984 		}
4985 
4986 		case DIF_OP_ALLOCS: {
4987 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4988 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
4989 
4990 			/*
4991 			 * Rounding up the user allocation size could have
4992 			 * overflowed large, bogus allocations (like -1ULL) to
4993 			 * 0.
4994 			 */
4995 			if (size < regs[r1] ||
4996 			    !DTRACE_INSCRATCH(mstate, size)) {
4997 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4998 				regs[rd] = NULL;
4999 				break;
5000 			}
5001 
5002 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5003 			mstate->dtms_scratch_ptr += size;
5004 			regs[rd] = ptr;
5005 			break;
5006 		}
5007 
5008 		case DIF_OP_COPYS:
5009 			if (!dtrace_canstore(regs[rd], regs[r2],
5010 			    mstate, vstate)) {
5011 				*flags |= CPU_DTRACE_BADADDR;
5012 				*illval = regs[rd];
5013 				break;
5014 			}
5015 
5016 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5017 				break;
5018 
5019 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
5020 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5021 			break;
5022 
5023 		case DIF_OP_STB:
5024 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5025 				*flags |= CPU_DTRACE_BADADDR;
5026 				*illval = regs[rd];
5027 				break;
5028 			}
5029 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5030 			break;
5031 
5032 		case DIF_OP_STH:
5033 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5034 				*flags |= CPU_DTRACE_BADADDR;
5035 				*illval = regs[rd];
5036 				break;
5037 			}
5038 			if (regs[rd] & 1) {
5039 				*flags |= CPU_DTRACE_BADALIGN;
5040 				*illval = regs[rd];
5041 				break;
5042 			}
5043 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5044 			break;
5045 
5046 		case DIF_OP_STW:
5047 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5048 				*flags |= CPU_DTRACE_BADADDR;
5049 				*illval = regs[rd];
5050 				break;
5051 			}
5052 			if (regs[rd] & 3) {
5053 				*flags |= CPU_DTRACE_BADALIGN;
5054 				*illval = regs[rd];
5055 				break;
5056 			}
5057 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5058 			break;
5059 
5060 		case DIF_OP_STX:
5061 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5062 				*flags |= CPU_DTRACE_BADADDR;
5063 				*illval = regs[rd];
5064 				break;
5065 			}
5066 			if (regs[rd] & 7) {
5067 				*flags |= CPU_DTRACE_BADALIGN;
5068 				*illval = regs[rd];
5069 				break;
5070 			}
5071 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5072 			break;
5073 		}
5074 	}
5075 
5076 	if (!(*flags & CPU_DTRACE_FAULT))
5077 		return (rval);
5078 
5079 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5080 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5081 
5082 	return (0);
5083 }
5084 
5085 static void
5086 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5087 {
5088 	dtrace_probe_t *probe = ecb->dte_probe;
5089 	dtrace_provider_t *prov = probe->dtpr_provider;
5090 	char c[DTRACE_FULLNAMELEN + 80], *str;
5091 	char *msg = "dtrace: breakpoint action at probe ";
5092 	char *ecbmsg = " (ecb ";
5093 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5094 	uintptr_t val = (uintptr_t)ecb;
5095 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5096 
5097 	if (dtrace_destructive_disallow)
5098 		return;
5099 
5100 	/*
5101 	 * It's impossible to be taking action on the NULL probe.
5102 	 */
5103 	ASSERT(probe != NULL);
5104 
5105 	/*
5106 	 * This is a poor man's (destitute man's?) sprintf():  we want to
5107 	 * print the provider name, module name, function name and name of
5108 	 * the probe, along with the hex address of the ECB with the breakpoint
5109 	 * action -- all of which we must place in the character buffer by
5110 	 * hand.
5111 	 */
5112 	while (*msg != '\0')
5113 		c[i++] = *msg++;
5114 
5115 	for (str = prov->dtpv_name; *str != '\0'; str++)
5116 		c[i++] = *str;
5117 	c[i++] = ':';
5118 
5119 	for (str = probe->dtpr_mod; *str != '\0'; str++)
5120 		c[i++] = *str;
5121 	c[i++] = ':';
5122 
5123 	for (str = probe->dtpr_func; *str != '\0'; str++)
5124 		c[i++] = *str;
5125 	c[i++] = ':';
5126 
5127 	for (str = probe->dtpr_name; *str != '\0'; str++)
5128 		c[i++] = *str;
5129 
5130 	while (*ecbmsg != '\0')
5131 		c[i++] = *ecbmsg++;
5132 
5133 	while (shift >= 0) {
5134 		mask = (uintptr_t)0xf << shift;
5135 
5136 		if (val >= ((uintptr_t)1 << shift))
5137 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5138 		shift -= 4;
5139 	}
5140 
5141 	c[i++] = ')';
5142 	c[i] = '\0';
5143 
5144 	debug_enter(c);
5145 }
5146 
5147 static void
5148 dtrace_action_panic(dtrace_ecb_t *ecb)
5149 {
5150 	dtrace_probe_t *probe = ecb->dte_probe;
5151 
5152 	/*
5153 	 * It's impossible to be taking action on the NULL probe.
5154 	 */
5155 	ASSERT(probe != NULL);
5156 
5157 	if (dtrace_destructive_disallow)
5158 		return;
5159 
5160 	if (dtrace_panicked != NULL)
5161 		return;
5162 
5163 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5164 		return;
5165 
5166 	/*
5167 	 * We won the right to panic.  (We want to be sure that only one
5168 	 * thread calls panic() from dtrace_probe(), and that panic() is
5169 	 * called exactly once.)
5170 	 */
5171 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5172 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5173 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5174 }
5175 
5176 static void
5177 dtrace_action_raise(uint64_t sig)
5178 {
5179 	if (dtrace_destructive_disallow)
5180 		return;
5181 
5182 	if (sig >= NSIG) {
5183 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5184 		return;
5185 	}
5186 
5187 	/*
5188 	 * raise() has a queue depth of 1 -- we ignore all subsequent
5189 	 * invocations of the raise() action.
5190 	 */
5191 	if (curthread->t_dtrace_sig == 0)
5192 		curthread->t_dtrace_sig = (uint8_t)sig;
5193 
5194 	curthread->t_sig_check = 1;
5195 	aston(curthread);
5196 }
5197 
5198 static void
5199 dtrace_action_stop(void)
5200 {
5201 	if (dtrace_destructive_disallow)
5202 		return;
5203 
5204 	if (!curthread->t_dtrace_stop) {
5205 		curthread->t_dtrace_stop = 1;
5206 		curthread->t_sig_check = 1;
5207 		aston(curthread);
5208 	}
5209 }
5210 
5211 static void
5212 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5213 {
5214 	hrtime_t now;
5215 	volatile uint16_t *flags;
5216 	cpu_t *cpu = CPU;
5217 
5218 	if (dtrace_destructive_disallow)
5219 		return;
5220 
5221 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5222 
5223 	now = dtrace_gethrtime();
5224 
5225 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5226 		/*
5227 		 * We need to advance the mark to the current time.
5228 		 */
5229 		cpu->cpu_dtrace_chillmark = now;
5230 		cpu->cpu_dtrace_chilled = 0;
5231 	}
5232 
5233 	/*
5234 	 * Now check to see if the requested chill time would take us over
5235 	 * the maximum amount of time allowed in the chill interval.  (Or
5236 	 * worse, if the calculation itself induces overflow.)
5237 	 */
5238 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5239 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5240 		*flags |= CPU_DTRACE_ILLOP;
5241 		return;
5242 	}
5243 
5244 	while (dtrace_gethrtime() - now < val)
5245 		continue;
5246 
5247 	/*
5248 	 * Normally, we assure that the value of the variable "timestamp" does
5249 	 * not change within an ECB.  The presence of chill() represents an
5250 	 * exception to this rule, however.
5251 	 */
5252 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5253 	cpu->cpu_dtrace_chilled += val;
5254 }
5255 
5256 static void
5257 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5258     uint64_t *buf, uint64_t arg)
5259 {
5260 	int nframes = DTRACE_USTACK_NFRAMES(arg);
5261 	int strsize = DTRACE_USTACK_STRSIZE(arg);
5262 	uint64_t *pcs = &buf[1], *fps;
5263 	char *str = (char *)&pcs[nframes];
5264 	int size, offs = 0, i, j;
5265 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
5266 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5267 	char *sym;
5268 
5269 	/*
5270 	 * Should be taking a faster path if string space has not been
5271 	 * allocated.
5272 	 */
5273 	ASSERT(strsize != 0);
5274 
5275 	/*
5276 	 * We will first allocate some temporary space for the frame pointers.
5277 	 */
5278 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5279 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5280 	    (nframes * sizeof (uint64_t));
5281 
5282 	if (!DTRACE_INSCRATCH(mstate, size)) {
5283 		/*
5284 		 * Not enough room for our frame pointers -- need to indicate
5285 		 * that we ran out of scratch space.
5286 		 */
5287 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5288 		return;
5289 	}
5290 
5291 	mstate->dtms_scratch_ptr += size;
5292 	saved = mstate->dtms_scratch_ptr;
5293 
5294 	/*
5295 	 * Now get a stack with both program counters and frame pointers.
5296 	 */
5297 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5298 	dtrace_getufpstack(buf, fps, nframes + 1);
5299 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5300 
5301 	/*
5302 	 * If that faulted, we're cooked.
5303 	 */
5304 	if (*flags & CPU_DTRACE_FAULT)
5305 		goto out;
5306 
5307 	/*
5308 	 * Now we want to walk up the stack, calling the USTACK helper.  For
5309 	 * each iteration, we restore the scratch pointer.
5310 	 */
5311 	for (i = 0; i < nframes; i++) {
5312 		mstate->dtms_scratch_ptr = saved;
5313 
5314 		if (offs >= strsize)
5315 			break;
5316 
5317 		sym = (char *)(uintptr_t)dtrace_helper(
5318 		    DTRACE_HELPER_ACTION_USTACK,
5319 		    mstate, state, pcs[i], fps[i]);
5320 
5321 		/*
5322 		 * If we faulted while running the helper, we're going to
5323 		 * clear the fault and null out the corresponding string.
5324 		 */
5325 		if (*flags & CPU_DTRACE_FAULT) {
5326 			*flags &= ~CPU_DTRACE_FAULT;
5327 			str[offs++] = '\0';
5328 			continue;
5329 		}
5330 
5331 		if (sym == NULL) {
5332 			str[offs++] = '\0';
5333 			continue;
5334 		}
5335 
5336 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5337 
5338 		/*
5339 		 * Now copy in the string that the helper returned to us.
5340 		 */
5341 		for (j = 0; offs + j < strsize; j++) {
5342 			if ((str[offs + j] = sym[j]) == '\0')
5343 				break;
5344 		}
5345 
5346 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5347 
5348 		offs += j + 1;
5349 	}
5350 
5351 	if (offs >= strsize) {
5352 		/*
5353 		 * If we didn't have room for all of the strings, we don't
5354 		 * abort processing -- this needn't be a fatal error -- but we
5355 		 * still want to increment a counter (dts_stkstroverflows) to
5356 		 * allow this condition to be warned about.  (If this is from
5357 		 * a jstack() action, it is easily tuned via jstackstrsize.)
5358 		 */
5359 		dtrace_error(&state->dts_stkstroverflows);
5360 	}
5361 
5362 	while (offs < strsize)
5363 		str[offs++] = '\0';
5364 
5365 out:
5366 	mstate->dtms_scratch_ptr = old;
5367 }
5368 
5369 /*
5370  * If you're looking for the epicenter of DTrace, you just found it.  This
5371  * is the function called by the provider to fire a probe -- from which all
5372  * subsequent probe-context DTrace activity emanates.
5373  */
5374 void
5375 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
5376     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
5377 {
5378 	processorid_t cpuid;
5379 	dtrace_icookie_t cookie;
5380 	dtrace_probe_t *probe;
5381 	dtrace_mstate_t mstate;
5382 	dtrace_ecb_t *ecb;
5383 	dtrace_action_t *act;
5384 	intptr_t offs;
5385 	size_t size;
5386 	int vtime, onintr;
5387 	volatile uint16_t *flags;
5388 	hrtime_t now;
5389 
5390 	/*
5391 	 * Kick out immediately if this CPU is still being born (in which case
5392 	 * curthread will be set to -1) or the current thread can't allow
5393 	 * probes in its current context.
5394 	 */
5395 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
5396 		return;
5397 
5398 	cookie = dtrace_interrupt_disable();
5399 	probe = dtrace_probes[id - 1];
5400 	cpuid = CPU->cpu_id;
5401 	onintr = CPU_ON_INTR(CPU);
5402 
5403 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
5404 	    probe->dtpr_predcache == curthread->t_predcache) {
5405 		/*
5406 		 * We have hit in the predicate cache; we know that
5407 		 * this predicate would evaluate to be false.
5408 		 */
5409 		dtrace_interrupt_enable(cookie);
5410 		return;
5411 	}
5412 
5413 	if (panic_quiesce) {
5414 		/*
5415 		 * We don't trace anything if we're panicking.
5416 		 */
5417 		dtrace_interrupt_enable(cookie);
5418 		return;
5419 	}
5420 
5421 	now = dtrace_gethrtime();
5422 	vtime = dtrace_vtime_references != 0;
5423 
5424 	if (vtime && curthread->t_dtrace_start)
5425 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
5426 
5427 	mstate.dtms_difo = NULL;
5428 	mstate.dtms_probe = probe;
5429 	mstate.dtms_strtok = NULL;
5430 	mstate.dtms_arg[0] = arg0;
5431 	mstate.dtms_arg[1] = arg1;
5432 	mstate.dtms_arg[2] = arg2;
5433 	mstate.dtms_arg[3] = arg3;
5434 	mstate.dtms_arg[4] = arg4;
5435 
5436 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
5437 
5438 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
5439 		dtrace_predicate_t *pred = ecb->dte_predicate;
5440 		dtrace_state_t *state = ecb->dte_state;
5441 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
5442 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
5443 		dtrace_vstate_t *vstate = &state->dts_vstate;
5444 		dtrace_provider_t *prov = probe->dtpr_provider;
5445 		int committed = 0;
5446 		caddr_t tomax;
5447 
5448 		/*
5449 		 * A little subtlety with the following (seemingly innocuous)
5450 		 * declaration of the automatic 'val':  by looking at the
5451 		 * code, you might think that it could be declared in the
5452 		 * action processing loop, below.  (That is, it's only used in
5453 		 * the action processing loop.)  However, it must be declared
5454 		 * out of that scope because in the case of DIF expression
5455 		 * arguments to aggregating actions, one iteration of the
5456 		 * action loop will use the last iteration's value.
5457 		 */
5458 #ifdef lint
5459 		uint64_t val = 0;
5460 #else
5461 		uint64_t val;
5462 #endif
5463 
5464 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
5465 		*flags &= ~CPU_DTRACE_ERROR;
5466 
5467 		if (prov == dtrace_provider) {
5468 			/*
5469 			 * If dtrace itself is the provider of this probe,
5470 			 * we're only going to continue processing the ECB if
5471 			 * arg0 (the dtrace_state_t) is equal to the ECB's
5472 			 * creating state.  (This prevents disjoint consumers
5473 			 * from seeing one another's metaprobes.)
5474 			 */
5475 			if (arg0 != (uint64_t)(uintptr_t)state)
5476 				continue;
5477 		}
5478 
5479 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
5480 			/*
5481 			 * We're not currently active.  If our provider isn't
5482 			 * the dtrace pseudo provider, we're not interested.
5483 			 */
5484 			if (prov != dtrace_provider)
5485 				continue;
5486 
5487 			/*
5488 			 * Now we must further check if we are in the BEGIN
5489 			 * probe.  If we are, we will only continue processing
5490 			 * if we're still in WARMUP -- if one BEGIN enabling
5491 			 * has invoked the exit() action, we don't want to
5492 			 * evaluate subsequent BEGIN enablings.
5493 			 */
5494 			if (probe->dtpr_id == dtrace_probeid_begin &&
5495 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
5496 				ASSERT(state->dts_activity ==
5497 				    DTRACE_ACTIVITY_DRAINING);
5498 				continue;
5499 			}
5500 		}
5501 
5502 		if (ecb->dte_cond) {
5503 			/*
5504 			 * If the dte_cond bits indicate that this
5505 			 * consumer is only allowed to see user-mode firings
5506 			 * of this probe, call the provider's dtps_usermode()
5507 			 * entry point to check that the probe was fired
5508 			 * while in a user context. Skip this ECB if that's
5509 			 * not the case.
5510 			 */
5511 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
5512 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
5513 			    probe->dtpr_id, probe->dtpr_arg) == 0)
5514 				continue;
5515 
5516 			/*
5517 			 * This is more subtle than it looks. We have to be
5518 			 * absolutely certain that CRED() isn't going to
5519 			 * change out from under us so it's only legit to
5520 			 * examine that structure if we're in constrained
5521 			 * situations. Currently, the only times we'll this
5522 			 * check is if a non-super-user has enabled the
5523 			 * profile or syscall providers -- providers that
5524 			 * allow visibility of all processes. For the
5525 			 * profile case, the check above will ensure that
5526 			 * we're examining a user context.
5527 			 */
5528 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
5529 				cred_t *cr;
5530 				cred_t *s_cr =
5531 				    ecb->dte_state->dts_cred.dcr_cred;
5532 				proc_t *proc;
5533 
5534 				ASSERT(s_cr != NULL);
5535 
5536 				if ((cr = CRED()) == NULL ||
5537 				    s_cr->cr_uid != cr->cr_uid ||
5538 				    s_cr->cr_uid != cr->cr_ruid ||
5539 				    s_cr->cr_uid != cr->cr_suid ||
5540 				    s_cr->cr_gid != cr->cr_gid ||
5541 				    s_cr->cr_gid != cr->cr_rgid ||
5542 				    s_cr->cr_gid != cr->cr_sgid ||
5543 				    (proc = ttoproc(curthread)) == NULL ||
5544 				    (proc->p_flag & SNOCD))
5545 					continue;
5546 			}
5547 
5548 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
5549 				cred_t *cr;
5550 				cred_t *s_cr =
5551 				    ecb->dte_state->dts_cred.dcr_cred;
5552 
5553 				ASSERT(s_cr != NULL);
5554 
5555 				if ((cr = CRED()) == NULL ||
5556 				    s_cr->cr_zone->zone_id !=
5557 				    cr->cr_zone->zone_id)
5558 					continue;
5559 			}
5560 		}
5561 
5562 		if (now - state->dts_alive > dtrace_deadman_timeout) {
5563 			/*
5564 			 * We seem to be dead.  Unless we (a) have kernel
5565 			 * destructive permissions (b) have expicitly enabled
5566 			 * destructive actions and (c) destructive actions have
5567 			 * not been disabled, we're going to transition into
5568 			 * the KILLED state, from which no further processing
5569 			 * on this state will be performed.
5570 			 */
5571 			if (!dtrace_priv_kernel_destructive(state) ||
5572 			    !state->dts_cred.dcr_destructive ||
5573 			    dtrace_destructive_disallow) {
5574 				void *activity = &state->dts_activity;
5575 				dtrace_activity_t current;
5576 
5577 				do {
5578 					current = state->dts_activity;
5579 				} while (dtrace_cas32(activity, current,
5580 				    DTRACE_ACTIVITY_KILLED) != current);
5581 
5582 				continue;
5583 			}
5584 		}
5585 
5586 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
5587 		    ecb->dte_alignment, state, &mstate)) < 0)
5588 			continue;
5589 
5590 		tomax = buf->dtb_tomax;
5591 		ASSERT(tomax != NULL);
5592 
5593 		if (ecb->dte_size != 0)
5594 			DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
5595 
5596 		mstate.dtms_epid = ecb->dte_epid;
5597 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
5598 
5599 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
5600 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
5601 		else
5602 			mstate.dtms_access = 0;
5603 
5604 		if (pred != NULL) {
5605 			dtrace_difo_t *dp = pred->dtp_difo;
5606 			int rval;
5607 
5608 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
5609 
5610 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
5611 				dtrace_cacheid_t cid = probe->dtpr_predcache;
5612 
5613 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
5614 					/*
5615 					 * Update the predicate cache...
5616 					 */
5617 					ASSERT(cid == pred->dtp_cacheid);
5618 					curthread->t_predcache = cid;
5619 				}
5620 
5621 				continue;
5622 			}
5623 		}
5624 
5625 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
5626 		    act != NULL; act = act->dta_next) {
5627 			size_t valoffs;
5628 			dtrace_difo_t *dp;
5629 			dtrace_recdesc_t *rec = &act->dta_rec;
5630 
5631 			size = rec->dtrd_size;
5632 			valoffs = offs + rec->dtrd_offset;
5633 
5634 			if (DTRACEACT_ISAGG(act->dta_kind)) {
5635 				uint64_t v = 0xbad;
5636 				dtrace_aggregation_t *agg;
5637 
5638 				agg = (dtrace_aggregation_t *)act;
5639 
5640 				if ((dp = act->dta_difo) != NULL)
5641 					v = dtrace_dif_emulate(dp,
5642 					    &mstate, vstate, state);
5643 
5644 				if (*flags & CPU_DTRACE_ERROR)
5645 					continue;
5646 
5647 				/*
5648 				 * Note that we always pass the expression
5649 				 * value from the previous iteration of the
5650 				 * action loop.  This value will only be used
5651 				 * if there is an expression argument to the
5652 				 * aggregating action, denoted by the
5653 				 * dtag_hasarg field.
5654 				 */
5655 				dtrace_aggregate(agg, buf,
5656 				    offs, aggbuf, v, val);
5657 				continue;
5658 			}
5659 
5660 			switch (act->dta_kind) {
5661 			case DTRACEACT_STOP:
5662 				if (dtrace_priv_proc_destructive(state))
5663 					dtrace_action_stop();
5664 				continue;
5665 
5666 			case DTRACEACT_BREAKPOINT:
5667 				if (dtrace_priv_kernel_destructive(state))
5668 					dtrace_action_breakpoint(ecb);
5669 				continue;
5670 
5671 			case DTRACEACT_PANIC:
5672 				if (dtrace_priv_kernel_destructive(state))
5673 					dtrace_action_panic(ecb);
5674 				continue;
5675 
5676 			case DTRACEACT_STACK:
5677 				if (!dtrace_priv_kernel(state))
5678 					continue;
5679 
5680 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
5681 				    size / sizeof (pc_t), probe->dtpr_aframes,
5682 				    DTRACE_ANCHORED(probe) ? NULL :
5683 				    (uint32_t *)arg0);
5684 
5685 				continue;
5686 
5687 			case DTRACEACT_JSTACK:
5688 			case DTRACEACT_USTACK:
5689 				if (!dtrace_priv_proc(state))
5690 					continue;
5691 
5692 				/*
5693 				 * See comment in DIF_VAR_PID.
5694 				 */
5695 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
5696 				    CPU_ON_INTR(CPU)) {
5697 					int depth = DTRACE_USTACK_NFRAMES(
5698 					    rec->dtrd_arg) + 1;
5699 
5700 					dtrace_bzero((void *)(tomax + valoffs),
5701 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
5702 					    + depth * sizeof (uint64_t));
5703 
5704 					continue;
5705 				}
5706 
5707 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
5708 				    curproc->p_dtrace_helpers != NULL) {
5709 					/*
5710 					 * This is the slow path -- we have
5711 					 * allocated string space, and we're
5712 					 * getting the stack of a process that
5713 					 * has helpers.  Call into a separate
5714 					 * routine to perform this processing.
5715 					 */
5716 					dtrace_action_ustack(&mstate, state,
5717 					    (uint64_t *)(tomax + valoffs),
5718 					    rec->dtrd_arg);
5719 					continue;
5720 				}
5721 
5722 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5723 				dtrace_getupcstack((uint64_t *)
5724 				    (tomax + valoffs),
5725 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
5726 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5727 				continue;
5728 
5729 			default:
5730 				break;
5731 			}
5732 
5733 			dp = act->dta_difo;
5734 			ASSERT(dp != NULL);
5735 
5736 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
5737 
5738 			if (*flags & CPU_DTRACE_ERROR)
5739 				continue;
5740 
5741 			switch (act->dta_kind) {
5742 			case DTRACEACT_SPECULATE:
5743 				ASSERT(buf == &state->dts_buffer[cpuid]);
5744 				buf = dtrace_speculation_buffer(state,
5745 				    cpuid, val);
5746 
5747 				if (buf == NULL) {
5748 					*flags |= CPU_DTRACE_DROP;
5749 					continue;
5750 				}
5751 
5752 				offs = dtrace_buffer_reserve(buf,
5753 				    ecb->dte_needed, ecb->dte_alignment,
5754 				    state, NULL);
5755 
5756 				if (offs < 0) {
5757 					*flags |= CPU_DTRACE_DROP;
5758 					continue;
5759 				}
5760 
5761 				tomax = buf->dtb_tomax;
5762 				ASSERT(tomax != NULL);
5763 
5764 				if (ecb->dte_size != 0)
5765 					DTRACE_STORE(uint32_t, tomax, offs,
5766 					    ecb->dte_epid);
5767 				continue;
5768 
5769 			case DTRACEACT_CHILL:
5770 				if (dtrace_priv_kernel_destructive(state))
5771 					dtrace_action_chill(&mstate, val);
5772 				continue;
5773 
5774 			case DTRACEACT_RAISE:
5775 				if (dtrace_priv_proc_destructive(state))
5776 					dtrace_action_raise(val);
5777 				continue;
5778 
5779 			case DTRACEACT_COMMIT:
5780 				ASSERT(!committed);
5781 
5782 				/*
5783 				 * We need to commit our buffer state.
5784 				 */
5785 				if (ecb->dte_size)
5786 					buf->dtb_offset = offs + ecb->dte_size;
5787 				buf = &state->dts_buffer[cpuid];
5788 				dtrace_speculation_commit(state, cpuid, val);
5789 				committed = 1;
5790 				continue;
5791 
5792 			case DTRACEACT_DISCARD:
5793 				dtrace_speculation_discard(state, cpuid, val);
5794 				continue;
5795 
5796 			case DTRACEACT_DIFEXPR:
5797 			case DTRACEACT_LIBACT:
5798 			case DTRACEACT_PRINTF:
5799 			case DTRACEACT_PRINTA:
5800 			case DTRACEACT_SYSTEM:
5801 			case DTRACEACT_FREOPEN:
5802 				break;
5803 
5804 			case DTRACEACT_SYM:
5805 			case DTRACEACT_MOD:
5806 				if (!dtrace_priv_kernel(state))
5807 					continue;
5808 				break;
5809 
5810 			case DTRACEACT_USYM:
5811 			case DTRACEACT_UMOD:
5812 			case DTRACEACT_UADDR: {
5813 				struct pid *pid = curthread->t_procp->p_pidp;
5814 
5815 				if (!dtrace_priv_proc(state))
5816 					continue;
5817 
5818 				DTRACE_STORE(uint64_t, tomax,
5819 				    valoffs, (uint64_t)pid->pid_id);
5820 				DTRACE_STORE(uint64_t, tomax,
5821 				    valoffs + sizeof (uint64_t), val);
5822 
5823 				continue;
5824 			}
5825 
5826 			case DTRACEACT_EXIT: {
5827 				/*
5828 				 * For the exit action, we are going to attempt
5829 				 * to atomically set our activity to be
5830 				 * draining.  If this fails (either because
5831 				 * another CPU has beat us to the exit action,
5832 				 * or because our current activity is something
5833 				 * other than ACTIVE or WARMUP), we will
5834 				 * continue.  This assures that the exit action
5835 				 * can be successfully recorded at most once
5836 				 * when we're in the ACTIVE state.  If we're
5837 				 * encountering the exit() action while in
5838 				 * COOLDOWN, however, we want to honor the new
5839 				 * status code.  (We know that we're the only
5840 				 * thread in COOLDOWN, so there is no race.)
5841 				 */
5842 				void *activity = &state->dts_activity;
5843 				dtrace_activity_t current = state->dts_activity;
5844 
5845 				if (current == DTRACE_ACTIVITY_COOLDOWN)
5846 					break;
5847 
5848 				if (current != DTRACE_ACTIVITY_WARMUP)
5849 					current = DTRACE_ACTIVITY_ACTIVE;
5850 
5851 				if (dtrace_cas32(activity, current,
5852 				    DTRACE_ACTIVITY_DRAINING) != current) {
5853 					*flags |= CPU_DTRACE_DROP;
5854 					continue;
5855 				}
5856 
5857 				break;
5858 			}
5859 
5860 			default:
5861 				ASSERT(0);
5862 			}
5863 
5864 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
5865 				uintptr_t end = valoffs + size;
5866 
5867 				if (!dtrace_vcanload((void *)(uintptr_t)val,
5868 				    &dp->dtdo_rtype, &mstate, vstate))
5869 					continue;
5870 
5871 				/*
5872 				 * If this is a string, we're going to only
5873 				 * load until we find the zero byte -- after
5874 				 * which we'll store zero bytes.
5875 				 */
5876 				if (dp->dtdo_rtype.dtdt_kind ==
5877 				    DIF_TYPE_STRING) {
5878 					char c = '\0' + 1;
5879 					int intuple = act->dta_intuple;
5880 					size_t s;
5881 
5882 					for (s = 0; s < size; s++) {
5883 						if (c != '\0')
5884 							c = dtrace_load8(val++);
5885 
5886 						DTRACE_STORE(uint8_t, tomax,
5887 						    valoffs++, c);
5888 
5889 						if (c == '\0' && intuple)
5890 							break;
5891 					}
5892 
5893 					continue;
5894 				}
5895 
5896 				while (valoffs < end) {
5897 					DTRACE_STORE(uint8_t, tomax, valoffs++,
5898 					    dtrace_load8(val++));
5899 				}
5900 
5901 				continue;
5902 			}
5903 
5904 			switch (size) {
5905 			case 0:
5906 				break;
5907 
5908 			case sizeof (uint8_t):
5909 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
5910 				break;
5911 			case sizeof (uint16_t):
5912 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
5913 				break;
5914 			case sizeof (uint32_t):
5915 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
5916 				break;
5917 			case sizeof (uint64_t):
5918 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
5919 				break;
5920 			default:
5921 				/*
5922 				 * Any other size should have been returned by
5923 				 * reference, not by value.
5924 				 */
5925 				ASSERT(0);
5926 				break;
5927 			}
5928 		}
5929 
5930 		if (*flags & CPU_DTRACE_DROP)
5931 			continue;
5932 
5933 		if (*flags & CPU_DTRACE_FAULT) {
5934 			int ndx;
5935 			dtrace_action_t *err;
5936 
5937 			buf->dtb_errors++;
5938 
5939 			if (probe->dtpr_id == dtrace_probeid_error) {
5940 				/*
5941 				 * There's nothing we can do -- we had an
5942 				 * error on the error probe.  We bump an
5943 				 * error counter to at least indicate that
5944 				 * this condition happened.
5945 				 */
5946 				dtrace_error(&state->dts_dblerrors);
5947 				continue;
5948 			}
5949 
5950 			if (vtime) {
5951 				/*
5952 				 * Before recursing on dtrace_probe(), we
5953 				 * need to explicitly clear out our start
5954 				 * time to prevent it from being accumulated
5955 				 * into t_dtrace_vtime.
5956 				 */
5957 				curthread->t_dtrace_start = 0;
5958 			}
5959 
5960 			/*
5961 			 * Iterate over the actions to figure out which action
5962 			 * we were processing when we experienced the error.
5963 			 * Note that act points _past_ the faulting action; if
5964 			 * act is ecb->dte_action, the fault was in the
5965 			 * predicate, if it's ecb->dte_action->dta_next it's
5966 			 * in action #1, and so on.
5967 			 */
5968 			for (err = ecb->dte_action, ndx = 0;
5969 			    err != act; err = err->dta_next, ndx++)
5970 				continue;
5971 
5972 			dtrace_probe_error(state, ecb->dte_epid, ndx,
5973 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
5974 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
5975 			    cpu_core[cpuid].cpuc_dtrace_illval);
5976 
5977 			continue;
5978 		}
5979 
5980 		if (!committed)
5981 			buf->dtb_offset = offs + ecb->dte_size;
5982 	}
5983 
5984 	if (vtime)
5985 		curthread->t_dtrace_start = dtrace_gethrtime();
5986 
5987 	dtrace_interrupt_enable(cookie);
5988 }
5989 
5990 /*
5991  * DTrace Probe Hashing Functions
5992  *
5993  * The functions in this section (and indeed, the functions in remaining
5994  * sections) are not _called_ from probe context.  (Any exceptions to this are
5995  * marked with a "Note:".)  Rather, they are called from elsewhere in the
5996  * DTrace framework to look-up probes in, add probes to and remove probes from
5997  * the DTrace probe hashes.  (Each probe is hashed by each element of the
5998  * probe tuple -- allowing for fast lookups, regardless of what was
5999  * specified.)
6000  */
6001 static uint_t
6002 dtrace_hash_str(char *p)
6003 {
6004 	unsigned int g;
6005 	uint_t hval = 0;
6006 
6007 	while (*p) {
6008 		hval = (hval << 4) + *p++;
6009 		if ((g = (hval & 0xf0000000)) != 0)
6010 			hval ^= g >> 24;
6011 		hval &= ~g;
6012 	}
6013 	return (hval);
6014 }
6015 
6016 static dtrace_hash_t *
6017 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6018 {
6019 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6020 
6021 	hash->dth_stroffs = stroffs;
6022 	hash->dth_nextoffs = nextoffs;
6023 	hash->dth_prevoffs = prevoffs;
6024 
6025 	hash->dth_size = 1;
6026 	hash->dth_mask = hash->dth_size - 1;
6027 
6028 	hash->dth_tab = kmem_zalloc(hash->dth_size *
6029 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6030 
6031 	return (hash);
6032 }
6033 
6034 static void
6035 dtrace_hash_destroy(dtrace_hash_t *hash)
6036 {
6037 #ifdef DEBUG
6038 	int i;
6039 
6040 	for (i = 0; i < hash->dth_size; i++)
6041 		ASSERT(hash->dth_tab[i] == NULL);
6042 #endif
6043 
6044 	kmem_free(hash->dth_tab,
6045 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
6046 	kmem_free(hash, sizeof (dtrace_hash_t));
6047 }
6048 
6049 static void
6050 dtrace_hash_resize(dtrace_hash_t *hash)
6051 {
6052 	int size = hash->dth_size, i, ndx;
6053 	int new_size = hash->dth_size << 1;
6054 	int new_mask = new_size - 1;
6055 	dtrace_hashbucket_t **new_tab, *bucket, *next;
6056 
6057 	ASSERT((new_size & new_mask) == 0);
6058 
6059 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6060 
6061 	for (i = 0; i < size; i++) {
6062 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6063 			dtrace_probe_t *probe = bucket->dthb_chain;
6064 
6065 			ASSERT(probe != NULL);
6066 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6067 
6068 			next = bucket->dthb_next;
6069 			bucket->dthb_next = new_tab[ndx];
6070 			new_tab[ndx] = bucket;
6071 		}
6072 	}
6073 
6074 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6075 	hash->dth_tab = new_tab;
6076 	hash->dth_size = new_size;
6077 	hash->dth_mask = new_mask;
6078 }
6079 
6080 static void
6081 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6082 {
6083 	int hashval = DTRACE_HASHSTR(hash, new);
6084 	int ndx = hashval & hash->dth_mask;
6085 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6086 	dtrace_probe_t **nextp, **prevp;
6087 
6088 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6089 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6090 			goto add;
6091 	}
6092 
6093 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6094 		dtrace_hash_resize(hash);
6095 		dtrace_hash_add(hash, new);
6096 		return;
6097 	}
6098 
6099 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6100 	bucket->dthb_next = hash->dth_tab[ndx];
6101 	hash->dth_tab[ndx] = bucket;
6102 	hash->dth_nbuckets++;
6103 
6104 add:
6105 	nextp = DTRACE_HASHNEXT(hash, new);
6106 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6107 	*nextp = bucket->dthb_chain;
6108 
6109 	if (bucket->dthb_chain != NULL) {
6110 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6111 		ASSERT(*prevp == NULL);
6112 		*prevp = new;
6113 	}
6114 
6115 	bucket->dthb_chain = new;
6116 	bucket->dthb_len++;
6117 }
6118 
6119 static dtrace_probe_t *
6120 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6121 {
6122 	int hashval = DTRACE_HASHSTR(hash, template);
6123 	int ndx = hashval & hash->dth_mask;
6124 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6125 
6126 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6127 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6128 			return (bucket->dthb_chain);
6129 	}
6130 
6131 	return (NULL);
6132 }
6133 
6134 static int
6135 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6136 {
6137 	int hashval = DTRACE_HASHSTR(hash, template);
6138 	int ndx = hashval & hash->dth_mask;
6139 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6140 
6141 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6142 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6143 			return (bucket->dthb_len);
6144 	}
6145 
6146 	return (NULL);
6147 }
6148 
6149 static void
6150 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6151 {
6152 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6153 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6154 
6155 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6156 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6157 
6158 	/*
6159 	 * Find the bucket that we're removing this probe from.
6160 	 */
6161 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6162 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6163 			break;
6164 	}
6165 
6166 	ASSERT(bucket != NULL);
6167 
6168 	if (*prevp == NULL) {
6169 		if (*nextp == NULL) {
6170 			/*
6171 			 * The removed probe was the only probe on this
6172 			 * bucket; we need to remove the bucket.
6173 			 */
6174 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6175 
6176 			ASSERT(bucket->dthb_chain == probe);
6177 			ASSERT(b != NULL);
6178 
6179 			if (b == bucket) {
6180 				hash->dth_tab[ndx] = bucket->dthb_next;
6181 			} else {
6182 				while (b->dthb_next != bucket)
6183 					b = b->dthb_next;
6184 				b->dthb_next = bucket->dthb_next;
6185 			}
6186 
6187 			ASSERT(hash->dth_nbuckets > 0);
6188 			hash->dth_nbuckets--;
6189 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
6190 			return;
6191 		}
6192 
6193 		bucket->dthb_chain = *nextp;
6194 	} else {
6195 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
6196 	}
6197 
6198 	if (*nextp != NULL)
6199 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
6200 }
6201 
6202 /*
6203  * DTrace Utility Functions
6204  *
6205  * These are random utility functions that are _not_ called from probe context.
6206  */
6207 static int
6208 dtrace_badattr(const dtrace_attribute_t *a)
6209 {
6210 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
6211 	    a->dtat_data > DTRACE_STABILITY_MAX ||
6212 	    a->dtat_class > DTRACE_CLASS_MAX);
6213 }
6214 
6215 /*
6216  * Return a duplicate copy of a string.  If the specified string is NULL,
6217  * this function returns a zero-length string.
6218  */
6219 static char *
6220 dtrace_strdup(const char *str)
6221 {
6222 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
6223 
6224 	if (str != NULL)
6225 		(void) strcpy(new, str);
6226 
6227 	return (new);
6228 }
6229 
6230 #define	DTRACE_ISALPHA(c)	\
6231 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
6232 
6233 static int
6234 dtrace_badname(const char *s)
6235 {
6236 	char c;
6237 
6238 	if (s == NULL || (c = *s++) == '\0')
6239 		return (0);
6240 
6241 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
6242 		return (1);
6243 
6244 	while ((c = *s++) != '\0') {
6245 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
6246 		    c != '-' && c != '_' && c != '.' && c != '`')
6247 			return (1);
6248 	}
6249 
6250 	return (0);
6251 }
6252 
6253 static void
6254 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
6255 {
6256 	uint32_t priv;
6257 
6258 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
6259 		/*
6260 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
6261 		 */
6262 		priv = DTRACE_PRIV_ALL;
6263 	} else {
6264 		*uidp = crgetuid(cr);
6265 		*zoneidp = crgetzoneid(cr);
6266 
6267 		priv = 0;
6268 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
6269 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
6270 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
6271 			priv |= DTRACE_PRIV_USER;
6272 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
6273 			priv |= DTRACE_PRIV_PROC;
6274 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
6275 			priv |= DTRACE_PRIV_OWNER;
6276 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
6277 			priv |= DTRACE_PRIV_ZONEOWNER;
6278 	}
6279 
6280 	*privp = priv;
6281 }
6282 
6283 #ifdef DTRACE_ERRDEBUG
6284 static void
6285 dtrace_errdebug(const char *str)
6286 {
6287 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
6288 	int occupied = 0;
6289 
6290 	mutex_enter(&dtrace_errlock);
6291 	dtrace_errlast = str;
6292 	dtrace_errthread = curthread;
6293 
6294 	while (occupied++ < DTRACE_ERRHASHSZ) {
6295 		if (dtrace_errhash[hval].dter_msg == str) {
6296 			dtrace_errhash[hval].dter_count++;
6297 			goto out;
6298 		}
6299 
6300 		if (dtrace_errhash[hval].dter_msg != NULL) {
6301 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
6302 			continue;
6303 		}
6304 
6305 		dtrace_errhash[hval].dter_msg = str;
6306 		dtrace_errhash[hval].dter_count = 1;
6307 		goto out;
6308 	}
6309 
6310 	panic("dtrace: undersized error hash");
6311 out:
6312 	mutex_exit(&dtrace_errlock);
6313 }
6314 #endif
6315 
6316 /*
6317  * DTrace Matching Functions
6318  *
6319  * These functions are used to match groups of probes, given some elements of
6320  * a probe tuple, or some globbed expressions for elements of a probe tuple.
6321  */
6322 static int
6323 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
6324     zoneid_t zoneid)
6325 {
6326 	if (priv != DTRACE_PRIV_ALL) {
6327 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
6328 		uint32_t match = priv & ppriv;
6329 
6330 		/*
6331 		 * No PRIV_DTRACE_* privileges...
6332 		 */
6333 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
6334 		    DTRACE_PRIV_KERNEL)) == 0)
6335 			return (0);
6336 
6337 		/*
6338 		 * No matching bits, but there were bits to match...
6339 		 */
6340 		if (match == 0 && ppriv != 0)
6341 			return (0);
6342 
6343 		/*
6344 		 * Need to have permissions to the process, but don't...
6345 		 */
6346 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
6347 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
6348 			return (0);
6349 		}
6350 
6351 		/*
6352 		 * Need to be in the same zone unless we possess the
6353 		 * privilege to examine all zones.
6354 		 */
6355 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
6356 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
6357 			return (0);
6358 		}
6359 	}
6360 
6361 	return (1);
6362 }
6363 
6364 /*
6365  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
6366  * consists of input pattern strings and an ops-vector to evaluate them.
6367  * This function returns >0 for match, 0 for no match, and <0 for error.
6368  */
6369 static int
6370 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
6371     uint32_t priv, uid_t uid, zoneid_t zoneid)
6372 {
6373 	dtrace_provider_t *pvp = prp->dtpr_provider;
6374 	int rv;
6375 
6376 	if (pvp->dtpv_defunct)
6377 		return (0);
6378 
6379 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
6380 		return (rv);
6381 
6382 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
6383 		return (rv);
6384 
6385 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
6386 		return (rv);
6387 
6388 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
6389 		return (rv);
6390 
6391 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
6392 		return (0);
6393 
6394 	return (rv);
6395 }
6396 
6397 /*
6398  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
6399  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
6400  * libc's version, the kernel version only applies to 8-bit ASCII strings.
6401  * In addition, all of the recursion cases except for '*' matching have been
6402  * unwound.  For '*', we still implement recursive evaluation, but a depth
6403  * counter is maintained and matching is aborted if we recurse too deep.
6404  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
6405  */
6406 static int
6407 dtrace_match_glob(const char *s, const char *p, int depth)
6408 {
6409 	const char *olds;
6410 	char s1, c;
6411 	int gs;
6412 
6413 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
6414 		return (-1);
6415 
6416 	if (s == NULL)
6417 		s = ""; /* treat NULL as empty string */
6418 
6419 top:
6420 	olds = s;
6421 	s1 = *s++;
6422 
6423 	if (p == NULL)
6424 		return (0);
6425 
6426 	if ((c = *p++) == '\0')
6427 		return (s1 == '\0');
6428 
6429 	switch (c) {
6430 	case '[': {
6431 		int ok = 0, notflag = 0;
6432 		char lc = '\0';
6433 
6434 		if (s1 == '\0')
6435 			return (0);
6436 
6437 		if (*p == '!') {
6438 			notflag = 1;
6439 			p++;
6440 		}
6441 
6442 		if ((c = *p++) == '\0')
6443 			return (0);
6444 
6445 		do {
6446 			if (c == '-' && lc != '\0' && *p != ']') {
6447 				if ((c = *p++) == '\0')
6448 					return (0);
6449 				if (c == '\\' && (c = *p++) == '\0')
6450 					return (0);
6451 
6452 				if (notflag) {
6453 					if (s1 < lc || s1 > c)
6454 						ok++;
6455 					else
6456 						return (0);
6457 				} else if (lc <= s1 && s1 <= c)
6458 					ok++;
6459 
6460 			} else if (c == '\\' && (c = *p++) == '\0')
6461 				return (0);
6462 
6463 			lc = c; /* save left-hand 'c' for next iteration */
6464 
6465 			if (notflag) {
6466 				if (s1 != c)
6467 					ok++;
6468 				else
6469 					return (0);
6470 			} else if (s1 == c)
6471 				ok++;
6472 
6473 			if ((c = *p++) == '\0')
6474 				return (0);
6475 
6476 		} while (c != ']');
6477 
6478 		if (ok)
6479 			goto top;
6480 
6481 		return (0);
6482 	}
6483 
6484 	case '\\':
6485 		if ((c = *p++) == '\0')
6486 			return (0);
6487 		/*FALLTHRU*/
6488 
6489 	default:
6490 		if (c != s1)
6491 			return (0);
6492 		/*FALLTHRU*/
6493 
6494 	case '?':
6495 		if (s1 != '\0')
6496 			goto top;
6497 		return (0);
6498 
6499 	case '*':
6500 		while (*p == '*')
6501 			p++; /* consecutive *'s are identical to a single one */
6502 
6503 		if (*p == '\0')
6504 			return (1);
6505 
6506 		for (s = olds; *s != '\0'; s++) {
6507 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
6508 				return (gs);
6509 		}
6510 
6511 		return (0);
6512 	}
6513 }
6514 
6515 /*ARGSUSED*/
6516 static int
6517 dtrace_match_string(const char *s, const char *p, int depth)
6518 {
6519 	return (s != NULL && strcmp(s, p) == 0);
6520 }
6521 
6522 /*ARGSUSED*/
6523 static int
6524 dtrace_match_nul(const char *s, const char *p, int depth)
6525 {
6526 	return (1); /* always match the empty pattern */
6527 }
6528 
6529 /*ARGSUSED*/
6530 static int
6531 dtrace_match_nonzero(const char *s, const char *p, int depth)
6532 {
6533 	return (s != NULL && s[0] != '\0');
6534 }
6535 
6536 static int
6537 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
6538     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
6539 {
6540 	dtrace_probe_t template, *probe;
6541 	dtrace_hash_t *hash = NULL;
6542 	int len, best = INT_MAX, nmatched = 0;
6543 	dtrace_id_t i;
6544 
6545 	ASSERT(MUTEX_HELD(&dtrace_lock));
6546 
6547 	/*
6548 	 * If the probe ID is specified in the key, just lookup by ID and
6549 	 * invoke the match callback once if a matching probe is found.
6550 	 */
6551 	if (pkp->dtpk_id != DTRACE_IDNONE) {
6552 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
6553 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
6554 			(void) (*matched)(probe, arg);
6555 			nmatched++;
6556 		}
6557 		return (nmatched);
6558 	}
6559 
6560 	template.dtpr_mod = (char *)pkp->dtpk_mod;
6561 	template.dtpr_func = (char *)pkp->dtpk_func;
6562 	template.dtpr_name = (char *)pkp->dtpk_name;
6563 
6564 	/*
6565 	 * We want to find the most distinct of the module name, function
6566 	 * name, and name.  So for each one that is not a glob pattern or
6567 	 * empty string, we perform a lookup in the corresponding hash and
6568 	 * use the hash table with the fewest collisions to do our search.
6569 	 */
6570 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
6571 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
6572 		best = len;
6573 		hash = dtrace_bymod;
6574 	}
6575 
6576 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
6577 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
6578 		best = len;
6579 		hash = dtrace_byfunc;
6580 	}
6581 
6582 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
6583 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
6584 		best = len;
6585 		hash = dtrace_byname;
6586 	}
6587 
6588 	/*
6589 	 * If we did not select a hash table, iterate over every probe and
6590 	 * invoke our callback for each one that matches our input probe key.
6591 	 */
6592 	if (hash == NULL) {
6593 		for (i = 0; i < dtrace_nprobes; i++) {
6594 			if ((probe = dtrace_probes[i]) == NULL ||
6595 			    dtrace_match_probe(probe, pkp, priv, uid,
6596 			    zoneid) <= 0)
6597 				continue;
6598 
6599 			nmatched++;
6600 
6601 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
6602 				break;
6603 		}
6604 
6605 		return (nmatched);
6606 	}
6607 
6608 	/*
6609 	 * If we selected a hash table, iterate over each probe of the same key
6610 	 * name and invoke the callback for every probe that matches the other
6611 	 * attributes of our input probe key.
6612 	 */
6613 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
6614 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
6615 
6616 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
6617 			continue;
6618 
6619 		nmatched++;
6620 
6621 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
6622 			break;
6623 	}
6624 
6625 	return (nmatched);
6626 }
6627 
6628 /*
6629  * Return the function pointer dtrace_probecmp() should use to compare the
6630  * specified pattern with a string.  For NULL or empty patterns, we select
6631  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
6632  * For non-empty non-glob strings, we use dtrace_match_string().
6633  */
6634 static dtrace_probekey_f *
6635 dtrace_probekey_func(const char *p)
6636 {
6637 	char c;
6638 
6639 	if (p == NULL || *p == '\0')
6640 		return (&dtrace_match_nul);
6641 
6642 	while ((c = *p++) != '\0') {
6643 		if (c == '[' || c == '?' || c == '*' || c == '\\')
6644 			return (&dtrace_match_glob);
6645 	}
6646 
6647 	return (&dtrace_match_string);
6648 }
6649 
6650 /*
6651  * Build a probe comparison key for use with dtrace_match_probe() from the
6652  * given probe description.  By convention, a null key only matches anchored
6653  * probes: if each field is the empty string, reset dtpk_fmatch to
6654  * dtrace_match_nonzero().
6655  */
6656 static void
6657 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
6658 {
6659 	pkp->dtpk_prov = pdp->dtpd_provider;
6660 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
6661 
6662 	pkp->dtpk_mod = pdp->dtpd_mod;
6663 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
6664 
6665 	pkp->dtpk_func = pdp->dtpd_func;
6666 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
6667 
6668 	pkp->dtpk_name = pdp->dtpd_name;
6669 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
6670 
6671 	pkp->dtpk_id = pdp->dtpd_id;
6672 
6673 	if (pkp->dtpk_id == DTRACE_IDNONE &&
6674 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
6675 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
6676 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
6677 	    pkp->dtpk_nmatch == &dtrace_match_nul)
6678 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
6679 }
6680 
6681 /*
6682  * DTrace Provider-to-Framework API Functions
6683  *
6684  * These functions implement much of the Provider-to-Framework API, as
6685  * described in <sys/dtrace.h>.  The parts of the API not in this section are
6686  * the functions in the API for probe management (found below), and
6687  * dtrace_probe() itself (found above).
6688  */
6689 
6690 /*
6691  * Register the calling provider with the DTrace framework.  This should
6692  * generally be called by DTrace providers in their attach(9E) entry point.
6693  */
6694 int
6695 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
6696     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
6697 {
6698 	dtrace_provider_t *provider;
6699 
6700 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
6701 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6702 		    "arguments", name ? name : "<NULL>");
6703 		return (EINVAL);
6704 	}
6705 
6706 	if (name[0] == '\0' || dtrace_badname(name)) {
6707 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6708 		    "provider name", name);
6709 		return (EINVAL);
6710 	}
6711 
6712 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
6713 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
6714 	    pops->dtps_destroy == NULL ||
6715 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
6716 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6717 		    "provider ops", name);
6718 		return (EINVAL);
6719 	}
6720 
6721 	if (dtrace_badattr(&pap->dtpa_provider) ||
6722 	    dtrace_badattr(&pap->dtpa_mod) ||
6723 	    dtrace_badattr(&pap->dtpa_func) ||
6724 	    dtrace_badattr(&pap->dtpa_name) ||
6725 	    dtrace_badattr(&pap->dtpa_args)) {
6726 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6727 		    "provider attributes", name);
6728 		return (EINVAL);
6729 	}
6730 
6731 	if (priv & ~DTRACE_PRIV_ALL) {
6732 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6733 		    "privilege attributes", name);
6734 		return (EINVAL);
6735 	}
6736 
6737 	if ((priv & DTRACE_PRIV_KERNEL) &&
6738 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
6739 	    pops->dtps_usermode == NULL) {
6740 		cmn_err(CE_WARN, "failed to register provider '%s': need "
6741 		    "dtps_usermode() op for given privilege attributes", name);
6742 		return (EINVAL);
6743 	}
6744 
6745 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
6746 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
6747 	(void) strcpy(provider->dtpv_name, name);
6748 
6749 	provider->dtpv_attr = *pap;
6750 	provider->dtpv_priv.dtpp_flags = priv;
6751 	if (cr != NULL) {
6752 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
6753 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
6754 	}
6755 	provider->dtpv_pops = *pops;
6756 
6757 	if (pops->dtps_provide == NULL) {
6758 		ASSERT(pops->dtps_provide_module != NULL);
6759 		provider->dtpv_pops.dtps_provide =
6760 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
6761 	}
6762 
6763 	if (pops->dtps_provide_module == NULL) {
6764 		ASSERT(pops->dtps_provide != NULL);
6765 		provider->dtpv_pops.dtps_provide_module =
6766 		    (void (*)(void *, struct modctl *))dtrace_nullop;
6767 	}
6768 
6769 	if (pops->dtps_suspend == NULL) {
6770 		ASSERT(pops->dtps_resume == NULL);
6771 		provider->dtpv_pops.dtps_suspend =
6772 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6773 		provider->dtpv_pops.dtps_resume =
6774 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6775 	}
6776 
6777 	provider->dtpv_arg = arg;
6778 	*idp = (dtrace_provider_id_t)provider;
6779 
6780 	if (pops == &dtrace_provider_ops) {
6781 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6782 		ASSERT(MUTEX_HELD(&dtrace_lock));
6783 		ASSERT(dtrace_anon.dta_enabling == NULL);
6784 
6785 		/*
6786 		 * We make sure that the DTrace provider is at the head of
6787 		 * the provider chain.
6788 		 */
6789 		provider->dtpv_next = dtrace_provider;
6790 		dtrace_provider = provider;
6791 		return (0);
6792 	}
6793 
6794 	mutex_enter(&dtrace_provider_lock);
6795 	mutex_enter(&dtrace_lock);
6796 
6797 	/*
6798 	 * If there is at least one provider registered, we'll add this
6799 	 * provider after the first provider.
6800 	 */
6801 	if (dtrace_provider != NULL) {
6802 		provider->dtpv_next = dtrace_provider->dtpv_next;
6803 		dtrace_provider->dtpv_next = provider;
6804 	} else {
6805 		dtrace_provider = provider;
6806 	}
6807 
6808 	if (dtrace_retained != NULL) {
6809 		dtrace_enabling_provide(provider);
6810 
6811 		/*
6812 		 * Now we need to call dtrace_enabling_matchall() -- which
6813 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
6814 		 * to drop all of our locks before calling into it...
6815 		 */
6816 		mutex_exit(&dtrace_lock);
6817 		mutex_exit(&dtrace_provider_lock);
6818 		dtrace_enabling_matchall();
6819 
6820 		return (0);
6821 	}
6822 
6823 	mutex_exit(&dtrace_lock);
6824 	mutex_exit(&dtrace_provider_lock);
6825 
6826 	return (0);
6827 }
6828 
6829 /*
6830  * Unregister the specified provider from the DTrace framework.  This should
6831  * generally be called by DTrace providers in their detach(9E) entry point.
6832  */
6833 int
6834 dtrace_unregister(dtrace_provider_id_t id)
6835 {
6836 	dtrace_provider_t *old = (dtrace_provider_t *)id;
6837 	dtrace_provider_t *prev = NULL;
6838 	int i, self = 0;
6839 	dtrace_probe_t *probe, *first = NULL;
6840 
6841 	if (old->dtpv_pops.dtps_enable ==
6842 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
6843 		/*
6844 		 * If DTrace itself is the provider, we're called with locks
6845 		 * already held.
6846 		 */
6847 		ASSERT(old == dtrace_provider);
6848 		ASSERT(dtrace_devi != NULL);
6849 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6850 		ASSERT(MUTEX_HELD(&dtrace_lock));
6851 		self = 1;
6852 
6853 		if (dtrace_provider->dtpv_next != NULL) {
6854 			/*
6855 			 * There's another provider here; return failure.
6856 			 */
6857 			return (EBUSY);
6858 		}
6859 	} else {
6860 		mutex_enter(&dtrace_provider_lock);
6861 		mutex_enter(&mod_lock);
6862 		mutex_enter(&dtrace_lock);
6863 	}
6864 
6865 	/*
6866 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
6867 	 * probes, we refuse to let providers slither away, unless this
6868 	 * provider has already been explicitly invalidated.
6869 	 */
6870 	if (!old->dtpv_defunct &&
6871 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
6872 	    dtrace_anon.dta_state->dts_necbs > 0))) {
6873 		if (!self) {
6874 			mutex_exit(&dtrace_lock);
6875 			mutex_exit(&mod_lock);
6876 			mutex_exit(&dtrace_provider_lock);
6877 		}
6878 		return (EBUSY);
6879 	}
6880 
6881 	/*
6882 	 * Attempt to destroy the probes associated with this provider.
6883 	 */
6884 	for (i = 0; i < dtrace_nprobes; i++) {
6885 		if ((probe = dtrace_probes[i]) == NULL)
6886 			continue;
6887 
6888 		if (probe->dtpr_provider != old)
6889 			continue;
6890 
6891 		if (probe->dtpr_ecb == NULL)
6892 			continue;
6893 
6894 		/*
6895 		 * We have at least one ECB; we can't remove this provider.
6896 		 */
6897 		if (!self) {
6898 			mutex_exit(&dtrace_lock);
6899 			mutex_exit(&mod_lock);
6900 			mutex_exit(&dtrace_provider_lock);
6901 		}
6902 		return (EBUSY);
6903 	}
6904 
6905 	/*
6906 	 * All of the probes for this provider are disabled; we can safely
6907 	 * remove all of them from their hash chains and from the probe array.
6908 	 */
6909 	for (i = 0; i < dtrace_nprobes; i++) {
6910 		if ((probe = dtrace_probes[i]) == NULL)
6911 			continue;
6912 
6913 		if (probe->dtpr_provider != old)
6914 			continue;
6915 
6916 		dtrace_probes[i] = NULL;
6917 
6918 		dtrace_hash_remove(dtrace_bymod, probe);
6919 		dtrace_hash_remove(dtrace_byfunc, probe);
6920 		dtrace_hash_remove(dtrace_byname, probe);
6921 
6922 		if (first == NULL) {
6923 			first = probe;
6924 			probe->dtpr_nextmod = NULL;
6925 		} else {
6926 			probe->dtpr_nextmod = first;
6927 			first = probe;
6928 		}
6929 	}
6930 
6931 	/*
6932 	 * The provider's probes have been removed from the hash chains and
6933 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
6934 	 * everyone has cleared out from any probe array processing.
6935 	 */
6936 	dtrace_sync();
6937 
6938 	for (probe = first; probe != NULL; probe = first) {
6939 		first = probe->dtpr_nextmod;
6940 
6941 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
6942 		    probe->dtpr_arg);
6943 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
6944 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
6945 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
6946 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
6947 		kmem_free(probe, sizeof (dtrace_probe_t));
6948 	}
6949 
6950 	if ((prev = dtrace_provider) == old) {
6951 		ASSERT(self || dtrace_devi == NULL);
6952 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
6953 		dtrace_provider = old->dtpv_next;
6954 	} else {
6955 		while (prev != NULL && prev->dtpv_next != old)
6956 			prev = prev->dtpv_next;
6957 
6958 		if (prev == NULL) {
6959 			panic("attempt to unregister non-existent "
6960 			    "dtrace provider %p\n", (void *)id);
6961 		}
6962 
6963 		prev->dtpv_next = old->dtpv_next;
6964 	}
6965 
6966 	if (!self) {
6967 		mutex_exit(&dtrace_lock);
6968 		mutex_exit(&mod_lock);
6969 		mutex_exit(&dtrace_provider_lock);
6970 	}
6971 
6972 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
6973 	kmem_free(old, sizeof (dtrace_provider_t));
6974 
6975 	return (0);
6976 }
6977 
6978 /*
6979  * Invalidate the specified provider.  All subsequent probe lookups for the
6980  * specified provider will fail, but its probes will not be removed.
6981  */
6982 void
6983 dtrace_invalidate(dtrace_provider_id_t id)
6984 {
6985 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
6986 
6987 	ASSERT(pvp->dtpv_pops.dtps_enable !=
6988 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6989 
6990 	mutex_enter(&dtrace_provider_lock);
6991 	mutex_enter(&dtrace_lock);
6992 
6993 	pvp->dtpv_defunct = 1;
6994 
6995 	mutex_exit(&dtrace_lock);
6996 	mutex_exit(&dtrace_provider_lock);
6997 }
6998 
6999 /*
7000  * Indicate whether or not DTrace has attached.
7001  */
7002 int
7003 dtrace_attached(void)
7004 {
7005 	/*
7006 	 * dtrace_provider will be non-NULL iff the DTrace driver has
7007 	 * attached.  (It's non-NULL because DTrace is always itself a
7008 	 * provider.)
7009 	 */
7010 	return (dtrace_provider != NULL);
7011 }
7012 
7013 /*
7014  * Remove all the unenabled probes for the given provider.  This function is
7015  * not unlike dtrace_unregister(), except that it doesn't remove the provider
7016  * -- just as many of its associated probes as it can.
7017  */
7018 int
7019 dtrace_condense(dtrace_provider_id_t id)
7020 {
7021 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
7022 	int i;
7023 	dtrace_probe_t *probe;
7024 
7025 	/*
7026 	 * Make sure this isn't the dtrace provider itself.
7027 	 */
7028 	ASSERT(prov->dtpv_pops.dtps_enable !=
7029 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
7030 
7031 	mutex_enter(&dtrace_provider_lock);
7032 	mutex_enter(&dtrace_lock);
7033 
7034 	/*
7035 	 * Attempt to destroy the probes associated with this provider.
7036 	 */
7037 	for (i = 0; i < dtrace_nprobes; i++) {
7038 		if ((probe = dtrace_probes[i]) == NULL)
7039 			continue;
7040 
7041 		if (probe->dtpr_provider != prov)
7042 			continue;
7043 
7044 		if (probe->dtpr_ecb != NULL)
7045 			continue;
7046 
7047 		dtrace_probes[i] = NULL;
7048 
7049 		dtrace_hash_remove(dtrace_bymod, probe);
7050 		dtrace_hash_remove(dtrace_byfunc, probe);
7051 		dtrace_hash_remove(dtrace_byname, probe);
7052 
7053 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7054 		    probe->dtpr_arg);
7055 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7056 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7057 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7058 		kmem_free(probe, sizeof (dtrace_probe_t));
7059 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7060 	}
7061 
7062 	mutex_exit(&dtrace_lock);
7063 	mutex_exit(&dtrace_provider_lock);
7064 
7065 	return (0);
7066 }
7067 
7068 /*
7069  * DTrace Probe Management Functions
7070  *
7071  * The functions in this section perform the DTrace probe management,
7072  * including functions to create probes, look-up probes, and call into the
7073  * providers to request that probes be provided.  Some of these functions are
7074  * in the Provider-to-Framework API; these functions can be identified by the
7075  * fact that they are not declared "static".
7076  */
7077 
7078 /*
7079  * Create a probe with the specified module name, function name, and name.
7080  */
7081 dtrace_id_t
7082 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7083     const char *func, const char *name, int aframes, void *arg)
7084 {
7085 	dtrace_probe_t *probe, **probes;
7086 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7087 	dtrace_id_t id;
7088 
7089 	if (provider == dtrace_provider) {
7090 		ASSERT(MUTEX_HELD(&dtrace_lock));
7091 	} else {
7092 		mutex_enter(&dtrace_lock);
7093 	}
7094 
7095 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7096 	    VM_BESTFIT | VM_SLEEP);
7097 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
7098 
7099 	probe->dtpr_id = id;
7100 	probe->dtpr_gen = dtrace_probegen++;
7101 	probe->dtpr_mod = dtrace_strdup(mod);
7102 	probe->dtpr_func = dtrace_strdup(func);
7103 	probe->dtpr_name = dtrace_strdup(name);
7104 	probe->dtpr_arg = arg;
7105 	probe->dtpr_aframes = aframes;
7106 	probe->dtpr_provider = provider;
7107 
7108 	dtrace_hash_add(dtrace_bymod, probe);
7109 	dtrace_hash_add(dtrace_byfunc, probe);
7110 	dtrace_hash_add(dtrace_byname, probe);
7111 
7112 	if (id - 1 >= dtrace_nprobes) {
7113 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7114 		size_t nsize = osize << 1;
7115 
7116 		if (nsize == 0) {
7117 			ASSERT(osize == 0);
7118 			ASSERT(dtrace_probes == NULL);
7119 			nsize = sizeof (dtrace_probe_t *);
7120 		}
7121 
7122 		probes = kmem_zalloc(nsize, KM_SLEEP);
7123 
7124 		if (dtrace_probes == NULL) {
7125 			ASSERT(osize == 0);
7126 			dtrace_probes = probes;
7127 			dtrace_nprobes = 1;
7128 		} else {
7129 			dtrace_probe_t **oprobes = dtrace_probes;
7130 
7131 			bcopy(oprobes, probes, osize);
7132 			dtrace_membar_producer();
7133 			dtrace_probes = probes;
7134 
7135 			dtrace_sync();
7136 
7137 			/*
7138 			 * All CPUs are now seeing the new probes array; we can
7139 			 * safely free the old array.
7140 			 */
7141 			kmem_free(oprobes, osize);
7142 			dtrace_nprobes <<= 1;
7143 		}
7144 
7145 		ASSERT(id - 1 < dtrace_nprobes);
7146 	}
7147 
7148 	ASSERT(dtrace_probes[id - 1] == NULL);
7149 	dtrace_probes[id - 1] = probe;
7150 
7151 	if (provider != dtrace_provider)
7152 		mutex_exit(&dtrace_lock);
7153 
7154 	return (id);
7155 }
7156 
7157 static dtrace_probe_t *
7158 dtrace_probe_lookup_id(dtrace_id_t id)
7159 {
7160 	ASSERT(MUTEX_HELD(&dtrace_lock));
7161 
7162 	if (id == 0 || id > dtrace_nprobes)
7163 		return (NULL);
7164 
7165 	return (dtrace_probes[id - 1]);
7166 }
7167 
7168 static int
7169 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
7170 {
7171 	*((dtrace_id_t *)arg) = probe->dtpr_id;
7172 
7173 	return (DTRACE_MATCH_DONE);
7174 }
7175 
7176 /*
7177  * Look up a probe based on provider and one or more of module name, function
7178  * name and probe name.
7179  */
7180 dtrace_id_t
7181 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
7182     const char *func, const char *name)
7183 {
7184 	dtrace_probekey_t pkey;
7185 	dtrace_id_t id;
7186 	int match;
7187 
7188 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
7189 	pkey.dtpk_pmatch = &dtrace_match_string;
7190 	pkey.dtpk_mod = mod;
7191 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
7192 	pkey.dtpk_func = func;
7193 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
7194 	pkey.dtpk_name = name;
7195 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
7196 	pkey.dtpk_id = DTRACE_IDNONE;
7197 
7198 	mutex_enter(&dtrace_lock);
7199 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
7200 	    dtrace_probe_lookup_match, &id);
7201 	mutex_exit(&dtrace_lock);
7202 
7203 	ASSERT(match == 1 || match == 0);
7204 	return (match ? id : 0);
7205 }
7206 
7207 /*
7208  * Returns the probe argument associated with the specified probe.
7209  */
7210 void *
7211 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
7212 {
7213 	dtrace_probe_t *probe;
7214 	void *rval = NULL;
7215 
7216 	mutex_enter(&dtrace_lock);
7217 
7218 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
7219 	    probe->dtpr_provider == (dtrace_provider_t *)id)
7220 		rval = probe->dtpr_arg;
7221 
7222 	mutex_exit(&dtrace_lock);
7223 
7224 	return (rval);
7225 }
7226 
7227 /*
7228  * Copy a probe into a probe description.
7229  */
7230 static void
7231 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
7232 {
7233 	bzero(pdp, sizeof (dtrace_probedesc_t));
7234 	pdp->dtpd_id = prp->dtpr_id;
7235 
7236 	(void) strncpy(pdp->dtpd_provider,
7237 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
7238 
7239 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
7240 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
7241 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
7242 }
7243 
7244 /*
7245  * Called to indicate that a probe -- or probes -- should be provided by a
7246  * specfied provider.  If the specified description is NULL, the provider will
7247  * be told to provide all of its probes.  (This is done whenever a new
7248  * consumer comes along, or whenever a retained enabling is to be matched.) If
7249  * the specified description is non-NULL, the provider is given the
7250  * opportunity to dynamically provide the specified probe, allowing providers
7251  * to support the creation of probes on-the-fly.  (So-called _autocreated_
7252  * probes.)  If the provider is NULL, the operations will be applied to all
7253  * providers; if the provider is non-NULL the operations will only be applied
7254  * to the specified provider.  The dtrace_provider_lock must be held, and the
7255  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
7256  * will need to grab the dtrace_lock when it reenters the framework through
7257  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
7258  */
7259 static void
7260 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
7261 {
7262 	struct modctl *ctl;
7263 	int all = 0;
7264 
7265 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7266 
7267 	if (prv == NULL) {
7268 		all = 1;
7269 		prv = dtrace_provider;
7270 	}
7271 
7272 	do {
7273 		/*
7274 		 * First, call the blanket provide operation.
7275 		 */
7276 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
7277 
7278 		/*
7279 		 * Now call the per-module provide operation.  We will grab
7280 		 * mod_lock to prevent the list from being modified.  Note
7281 		 * that this also prevents the mod_busy bits from changing.
7282 		 * (mod_busy can only be changed with mod_lock held.)
7283 		 */
7284 		mutex_enter(&mod_lock);
7285 
7286 		ctl = &modules;
7287 		do {
7288 			if (ctl->mod_busy || ctl->mod_mp == NULL)
7289 				continue;
7290 
7291 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
7292 
7293 		} while ((ctl = ctl->mod_next) != &modules);
7294 
7295 		mutex_exit(&mod_lock);
7296 	} while (all && (prv = prv->dtpv_next) != NULL);
7297 }
7298 
7299 /*
7300  * Iterate over each probe, and call the Framework-to-Provider API function
7301  * denoted by offs.
7302  */
7303 static void
7304 dtrace_probe_foreach(uintptr_t offs)
7305 {
7306 	dtrace_provider_t *prov;
7307 	void (*func)(void *, dtrace_id_t, void *);
7308 	dtrace_probe_t *probe;
7309 	dtrace_icookie_t cookie;
7310 	int i;
7311 
7312 	/*
7313 	 * We disable interrupts to walk through the probe array.  This is
7314 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
7315 	 * won't see stale data.
7316 	 */
7317 	cookie = dtrace_interrupt_disable();
7318 
7319 	for (i = 0; i < dtrace_nprobes; i++) {
7320 		if ((probe = dtrace_probes[i]) == NULL)
7321 			continue;
7322 
7323 		if (probe->dtpr_ecb == NULL) {
7324 			/*
7325 			 * This probe isn't enabled -- don't call the function.
7326 			 */
7327 			continue;
7328 		}
7329 
7330 		prov = probe->dtpr_provider;
7331 		func = *((void(**)(void *, dtrace_id_t, void *))
7332 		    ((uintptr_t)&prov->dtpv_pops + offs));
7333 
7334 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
7335 	}
7336 
7337 	dtrace_interrupt_enable(cookie);
7338 }
7339 
7340 static int
7341 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
7342 {
7343 	dtrace_probekey_t pkey;
7344 	uint32_t priv;
7345 	uid_t uid;
7346 	zoneid_t zoneid;
7347 
7348 	ASSERT(MUTEX_HELD(&dtrace_lock));
7349 	dtrace_ecb_create_cache = NULL;
7350 
7351 	if (desc == NULL) {
7352 		/*
7353 		 * If we're passed a NULL description, we're being asked to
7354 		 * create an ECB with a NULL probe.
7355 		 */
7356 		(void) dtrace_ecb_create_enable(NULL, enab);
7357 		return (0);
7358 	}
7359 
7360 	dtrace_probekey(desc, &pkey);
7361 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
7362 	    &priv, &uid, &zoneid);
7363 
7364 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
7365 	    enab));
7366 }
7367 
7368 /*
7369  * DTrace Helper Provider Functions
7370  */
7371 static void
7372 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
7373 {
7374 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
7375 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
7376 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
7377 }
7378 
7379 static void
7380 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
7381     const dof_provider_t *dofprov, char *strtab)
7382 {
7383 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
7384 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
7385 	    dofprov->dofpv_provattr);
7386 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
7387 	    dofprov->dofpv_modattr);
7388 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
7389 	    dofprov->dofpv_funcattr);
7390 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
7391 	    dofprov->dofpv_nameattr);
7392 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
7393 	    dofprov->dofpv_argsattr);
7394 }
7395 
7396 static void
7397 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7398 {
7399 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7400 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7401 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
7402 	dof_provider_t *provider;
7403 	dof_probe_t *probe;
7404 	uint32_t *off, *enoff;
7405 	uint8_t *arg;
7406 	char *strtab;
7407 	uint_t i, nprobes;
7408 	dtrace_helper_provdesc_t dhpv;
7409 	dtrace_helper_probedesc_t dhpb;
7410 	dtrace_meta_t *meta = dtrace_meta_pid;
7411 	dtrace_mops_t *mops = &meta->dtm_mops;
7412 	void *parg;
7413 
7414 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7415 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7416 	    provider->dofpv_strtab * dof->dofh_secsize);
7417 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7418 	    provider->dofpv_probes * dof->dofh_secsize);
7419 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7420 	    provider->dofpv_prargs * dof->dofh_secsize);
7421 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7422 	    provider->dofpv_proffs * dof->dofh_secsize);
7423 
7424 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7425 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
7426 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
7427 	enoff = NULL;
7428 
7429 	/*
7430 	 * See dtrace_helper_provider_validate().
7431 	 */
7432 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
7433 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
7434 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7435 		    provider->dofpv_prenoffs * dof->dofh_secsize);
7436 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
7437 	}
7438 
7439 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
7440 
7441 	/*
7442 	 * Create the provider.
7443 	 */
7444 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7445 
7446 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
7447 		return;
7448 
7449 	meta->dtm_count++;
7450 
7451 	/*
7452 	 * Create the probes.
7453 	 */
7454 	for (i = 0; i < nprobes; i++) {
7455 		probe = (dof_probe_t *)(uintptr_t)(daddr +
7456 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
7457 
7458 		dhpb.dthpb_mod = dhp->dofhp_mod;
7459 		dhpb.dthpb_func = strtab + probe->dofpr_func;
7460 		dhpb.dthpb_name = strtab + probe->dofpr_name;
7461 		dhpb.dthpb_base = probe->dofpr_addr;
7462 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
7463 		dhpb.dthpb_noffs = probe->dofpr_noffs;
7464 		if (enoff != NULL) {
7465 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
7466 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
7467 		} else {
7468 			dhpb.dthpb_enoffs = NULL;
7469 			dhpb.dthpb_nenoffs = 0;
7470 		}
7471 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
7472 		dhpb.dthpb_nargc = probe->dofpr_nargc;
7473 		dhpb.dthpb_xargc = probe->dofpr_xargc;
7474 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
7475 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
7476 
7477 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
7478 	}
7479 }
7480 
7481 static void
7482 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
7483 {
7484 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7485 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7486 	int i;
7487 
7488 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7489 
7490 	for (i = 0; i < dof->dofh_secnum; i++) {
7491 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7492 		    dof->dofh_secoff + i * dof->dofh_secsize);
7493 
7494 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7495 			continue;
7496 
7497 		dtrace_helper_provide_one(dhp, sec, pid);
7498 	}
7499 
7500 	/*
7501 	 * We may have just created probes, so we must now rematch against
7502 	 * any retained enablings.  Note that this call will acquire both
7503 	 * cpu_lock and dtrace_lock; the fact that we are holding
7504 	 * dtrace_meta_lock now is what defines the ordering with respect to
7505 	 * these three locks.
7506 	 */
7507 	dtrace_enabling_matchall();
7508 }
7509 
7510 static void
7511 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7512 {
7513 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7514 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7515 	dof_sec_t *str_sec;
7516 	dof_provider_t *provider;
7517 	char *strtab;
7518 	dtrace_helper_provdesc_t dhpv;
7519 	dtrace_meta_t *meta = dtrace_meta_pid;
7520 	dtrace_mops_t *mops = &meta->dtm_mops;
7521 
7522 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7523 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7524 	    provider->dofpv_strtab * dof->dofh_secsize);
7525 
7526 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7527 
7528 	/*
7529 	 * Create the provider.
7530 	 */
7531 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7532 
7533 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
7534 
7535 	meta->dtm_count--;
7536 }
7537 
7538 static void
7539 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
7540 {
7541 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7542 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7543 	int i;
7544 
7545 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7546 
7547 	for (i = 0; i < dof->dofh_secnum; i++) {
7548 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7549 		    dof->dofh_secoff + i * dof->dofh_secsize);
7550 
7551 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7552 			continue;
7553 
7554 		dtrace_helper_provider_remove_one(dhp, sec, pid);
7555 	}
7556 }
7557 
7558 /*
7559  * DTrace Meta Provider-to-Framework API Functions
7560  *
7561  * These functions implement the Meta Provider-to-Framework API, as described
7562  * in <sys/dtrace.h>.
7563  */
7564 int
7565 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
7566     dtrace_meta_provider_id_t *idp)
7567 {
7568 	dtrace_meta_t *meta;
7569 	dtrace_helpers_t *help, *next;
7570 	int i;
7571 
7572 	*idp = DTRACE_METAPROVNONE;
7573 
7574 	/*
7575 	 * We strictly don't need the name, but we hold onto it for
7576 	 * debuggability. All hail error queues!
7577 	 */
7578 	if (name == NULL) {
7579 		cmn_err(CE_WARN, "failed to register meta-provider: "
7580 		    "invalid name");
7581 		return (EINVAL);
7582 	}
7583 
7584 	if (mops == NULL ||
7585 	    mops->dtms_create_probe == NULL ||
7586 	    mops->dtms_provide_pid == NULL ||
7587 	    mops->dtms_remove_pid == NULL) {
7588 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7589 		    "invalid ops", name);
7590 		return (EINVAL);
7591 	}
7592 
7593 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
7594 	meta->dtm_mops = *mops;
7595 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7596 	(void) strcpy(meta->dtm_name, name);
7597 	meta->dtm_arg = arg;
7598 
7599 	mutex_enter(&dtrace_meta_lock);
7600 	mutex_enter(&dtrace_lock);
7601 
7602 	if (dtrace_meta_pid != NULL) {
7603 		mutex_exit(&dtrace_lock);
7604 		mutex_exit(&dtrace_meta_lock);
7605 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7606 		    "user-land meta-provider exists", name);
7607 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
7608 		kmem_free(meta, sizeof (dtrace_meta_t));
7609 		return (EINVAL);
7610 	}
7611 
7612 	dtrace_meta_pid = meta;
7613 	*idp = (dtrace_meta_provider_id_t)meta;
7614 
7615 	/*
7616 	 * If there are providers and probes ready to go, pass them
7617 	 * off to the new meta provider now.
7618 	 */
7619 
7620 	help = dtrace_deferred_pid;
7621 	dtrace_deferred_pid = NULL;
7622 
7623 	mutex_exit(&dtrace_lock);
7624 
7625 	while (help != NULL) {
7626 		for (i = 0; i < help->dthps_nprovs; i++) {
7627 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
7628 			    help->dthps_pid);
7629 		}
7630 
7631 		next = help->dthps_next;
7632 		help->dthps_next = NULL;
7633 		help->dthps_prev = NULL;
7634 		help->dthps_deferred = 0;
7635 		help = next;
7636 	}
7637 
7638 	mutex_exit(&dtrace_meta_lock);
7639 
7640 	return (0);
7641 }
7642 
7643 int
7644 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
7645 {
7646 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
7647 
7648 	mutex_enter(&dtrace_meta_lock);
7649 	mutex_enter(&dtrace_lock);
7650 
7651 	if (old == dtrace_meta_pid) {
7652 		pp = &dtrace_meta_pid;
7653 	} else {
7654 		panic("attempt to unregister non-existent "
7655 		    "dtrace meta-provider %p\n", (void *)old);
7656 	}
7657 
7658 	if (old->dtm_count != 0) {
7659 		mutex_exit(&dtrace_lock);
7660 		mutex_exit(&dtrace_meta_lock);
7661 		return (EBUSY);
7662 	}
7663 
7664 	*pp = NULL;
7665 
7666 	mutex_exit(&dtrace_lock);
7667 	mutex_exit(&dtrace_meta_lock);
7668 
7669 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
7670 	kmem_free(old, sizeof (dtrace_meta_t));
7671 
7672 	return (0);
7673 }
7674 
7675 
7676 /*
7677  * DTrace DIF Object Functions
7678  */
7679 static int
7680 dtrace_difo_err(uint_t pc, const char *format, ...)
7681 {
7682 	if (dtrace_err_verbose) {
7683 		va_list alist;
7684 
7685 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
7686 		va_start(alist, format);
7687 		(void) vuprintf(format, alist);
7688 		va_end(alist);
7689 	}
7690 
7691 #ifdef DTRACE_ERRDEBUG
7692 	dtrace_errdebug(format);
7693 #endif
7694 	return (1);
7695 }
7696 
7697 /*
7698  * Validate a DTrace DIF object by checking the IR instructions.  The following
7699  * rules are currently enforced by dtrace_difo_validate():
7700  *
7701  * 1. Each instruction must have a valid opcode
7702  * 2. Each register, string, variable, or subroutine reference must be valid
7703  * 3. No instruction can modify register %r0 (must be zero)
7704  * 4. All instruction reserved bits must be set to zero
7705  * 5. The last instruction must be a "ret" instruction
7706  * 6. All branch targets must reference a valid instruction _after_ the branch
7707  */
7708 static int
7709 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
7710     cred_t *cr)
7711 {
7712 	int err = 0, i;
7713 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
7714 	int kcheckload;
7715 	uint_t pc;
7716 
7717 	kcheckload = cr == NULL ||
7718 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
7719 
7720 	dp->dtdo_destructive = 0;
7721 
7722 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
7723 		dif_instr_t instr = dp->dtdo_buf[pc];
7724 
7725 		uint_t r1 = DIF_INSTR_R1(instr);
7726 		uint_t r2 = DIF_INSTR_R2(instr);
7727 		uint_t rd = DIF_INSTR_RD(instr);
7728 		uint_t rs = DIF_INSTR_RS(instr);
7729 		uint_t label = DIF_INSTR_LABEL(instr);
7730 		uint_t v = DIF_INSTR_VAR(instr);
7731 		uint_t subr = DIF_INSTR_SUBR(instr);
7732 		uint_t type = DIF_INSTR_TYPE(instr);
7733 		uint_t op = DIF_INSTR_OP(instr);
7734 
7735 		switch (op) {
7736 		case DIF_OP_OR:
7737 		case DIF_OP_XOR:
7738 		case DIF_OP_AND:
7739 		case DIF_OP_SLL:
7740 		case DIF_OP_SRL:
7741 		case DIF_OP_SRA:
7742 		case DIF_OP_SUB:
7743 		case DIF_OP_ADD:
7744 		case DIF_OP_MUL:
7745 		case DIF_OP_SDIV:
7746 		case DIF_OP_UDIV:
7747 		case DIF_OP_SREM:
7748 		case DIF_OP_UREM:
7749 		case DIF_OP_COPYS:
7750 			if (r1 >= nregs)
7751 				err += efunc(pc, "invalid register %u\n", r1);
7752 			if (r2 >= nregs)
7753 				err += efunc(pc, "invalid register %u\n", r2);
7754 			if (rd >= nregs)
7755 				err += efunc(pc, "invalid register %u\n", rd);
7756 			if (rd == 0)
7757 				err += efunc(pc, "cannot write to %r0\n");
7758 			break;
7759 		case DIF_OP_NOT:
7760 		case DIF_OP_MOV:
7761 		case DIF_OP_ALLOCS:
7762 			if (r1 >= nregs)
7763 				err += efunc(pc, "invalid register %u\n", r1);
7764 			if (r2 != 0)
7765 				err += efunc(pc, "non-zero reserved bits\n");
7766 			if (rd >= nregs)
7767 				err += efunc(pc, "invalid register %u\n", rd);
7768 			if (rd == 0)
7769 				err += efunc(pc, "cannot write to %r0\n");
7770 			break;
7771 		case DIF_OP_LDSB:
7772 		case DIF_OP_LDSH:
7773 		case DIF_OP_LDSW:
7774 		case DIF_OP_LDUB:
7775 		case DIF_OP_LDUH:
7776 		case DIF_OP_LDUW:
7777 		case DIF_OP_LDX:
7778 			if (r1 >= nregs)
7779 				err += efunc(pc, "invalid register %u\n", r1);
7780 			if (r2 != 0)
7781 				err += efunc(pc, "non-zero reserved bits\n");
7782 			if (rd >= nregs)
7783 				err += efunc(pc, "invalid register %u\n", rd);
7784 			if (rd == 0)
7785 				err += efunc(pc, "cannot write to %r0\n");
7786 			if (kcheckload)
7787 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
7788 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
7789 			break;
7790 		case DIF_OP_RLDSB:
7791 		case DIF_OP_RLDSH:
7792 		case DIF_OP_RLDSW:
7793 		case DIF_OP_RLDUB:
7794 		case DIF_OP_RLDUH:
7795 		case DIF_OP_RLDUW:
7796 		case DIF_OP_RLDX:
7797 			if (r1 >= nregs)
7798 				err += efunc(pc, "invalid register %u\n", r1);
7799 			if (r2 != 0)
7800 				err += efunc(pc, "non-zero reserved bits\n");
7801 			if (rd >= nregs)
7802 				err += efunc(pc, "invalid register %u\n", rd);
7803 			if (rd == 0)
7804 				err += efunc(pc, "cannot write to %r0\n");
7805 			break;
7806 		case DIF_OP_ULDSB:
7807 		case DIF_OP_ULDSH:
7808 		case DIF_OP_ULDSW:
7809 		case DIF_OP_ULDUB:
7810 		case DIF_OP_ULDUH:
7811 		case DIF_OP_ULDUW:
7812 		case DIF_OP_ULDX:
7813 			if (r1 >= nregs)
7814 				err += efunc(pc, "invalid register %u\n", r1);
7815 			if (r2 != 0)
7816 				err += efunc(pc, "non-zero reserved bits\n");
7817 			if (rd >= nregs)
7818 				err += efunc(pc, "invalid register %u\n", rd);
7819 			if (rd == 0)
7820 				err += efunc(pc, "cannot write to %r0\n");
7821 			break;
7822 		case DIF_OP_STB:
7823 		case DIF_OP_STH:
7824 		case DIF_OP_STW:
7825 		case DIF_OP_STX:
7826 			if (r1 >= nregs)
7827 				err += efunc(pc, "invalid register %u\n", r1);
7828 			if (r2 != 0)
7829 				err += efunc(pc, "non-zero reserved bits\n");
7830 			if (rd >= nregs)
7831 				err += efunc(pc, "invalid register %u\n", rd);
7832 			if (rd == 0)
7833 				err += efunc(pc, "cannot write to 0 address\n");
7834 			break;
7835 		case DIF_OP_CMP:
7836 		case DIF_OP_SCMP:
7837 			if (r1 >= nregs)
7838 				err += efunc(pc, "invalid register %u\n", r1);
7839 			if (r2 >= nregs)
7840 				err += efunc(pc, "invalid register %u\n", r2);
7841 			if (rd != 0)
7842 				err += efunc(pc, "non-zero reserved bits\n");
7843 			break;
7844 		case DIF_OP_TST:
7845 			if (r1 >= nregs)
7846 				err += efunc(pc, "invalid register %u\n", r1);
7847 			if (r2 != 0 || rd != 0)
7848 				err += efunc(pc, "non-zero reserved bits\n");
7849 			break;
7850 		case DIF_OP_BA:
7851 		case DIF_OP_BE:
7852 		case DIF_OP_BNE:
7853 		case DIF_OP_BG:
7854 		case DIF_OP_BGU:
7855 		case DIF_OP_BGE:
7856 		case DIF_OP_BGEU:
7857 		case DIF_OP_BL:
7858 		case DIF_OP_BLU:
7859 		case DIF_OP_BLE:
7860 		case DIF_OP_BLEU:
7861 			if (label >= dp->dtdo_len) {
7862 				err += efunc(pc, "invalid branch target %u\n",
7863 				    label);
7864 			}
7865 			if (label <= pc) {
7866 				err += efunc(pc, "backward branch to %u\n",
7867 				    label);
7868 			}
7869 			break;
7870 		case DIF_OP_RET:
7871 			if (r1 != 0 || r2 != 0)
7872 				err += efunc(pc, "non-zero reserved bits\n");
7873 			if (rd >= nregs)
7874 				err += efunc(pc, "invalid register %u\n", rd);
7875 			break;
7876 		case DIF_OP_NOP:
7877 		case DIF_OP_POPTS:
7878 		case DIF_OP_FLUSHTS:
7879 			if (r1 != 0 || r2 != 0 || rd != 0)
7880 				err += efunc(pc, "non-zero reserved bits\n");
7881 			break;
7882 		case DIF_OP_SETX:
7883 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
7884 				err += efunc(pc, "invalid integer ref %u\n",
7885 				    DIF_INSTR_INTEGER(instr));
7886 			}
7887 			if (rd >= nregs)
7888 				err += efunc(pc, "invalid register %u\n", rd);
7889 			if (rd == 0)
7890 				err += efunc(pc, "cannot write to %r0\n");
7891 			break;
7892 		case DIF_OP_SETS:
7893 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
7894 				err += efunc(pc, "invalid string ref %u\n",
7895 				    DIF_INSTR_STRING(instr));
7896 			}
7897 			if (rd >= nregs)
7898 				err += efunc(pc, "invalid register %u\n", rd);
7899 			if (rd == 0)
7900 				err += efunc(pc, "cannot write to %r0\n");
7901 			break;
7902 		case DIF_OP_LDGA:
7903 		case DIF_OP_LDTA:
7904 			if (r1 > DIF_VAR_ARRAY_MAX)
7905 				err += efunc(pc, "invalid array %u\n", r1);
7906 			if (r2 >= nregs)
7907 				err += efunc(pc, "invalid register %u\n", r2);
7908 			if (rd >= nregs)
7909 				err += efunc(pc, "invalid register %u\n", rd);
7910 			if (rd == 0)
7911 				err += efunc(pc, "cannot write to %r0\n");
7912 			break;
7913 		case DIF_OP_LDGS:
7914 		case DIF_OP_LDTS:
7915 		case DIF_OP_LDLS:
7916 		case DIF_OP_LDGAA:
7917 		case DIF_OP_LDTAA:
7918 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
7919 				err += efunc(pc, "invalid variable %u\n", v);
7920 			if (rd >= nregs)
7921 				err += efunc(pc, "invalid register %u\n", rd);
7922 			if (rd == 0)
7923 				err += efunc(pc, "cannot write to %r0\n");
7924 			break;
7925 		case DIF_OP_STGS:
7926 		case DIF_OP_STTS:
7927 		case DIF_OP_STLS:
7928 		case DIF_OP_STGAA:
7929 		case DIF_OP_STTAA:
7930 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
7931 				err += efunc(pc, "invalid variable %u\n", v);
7932 			if (rs >= nregs)
7933 				err += efunc(pc, "invalid register %u\n", rd);
7934 			break;
7935 		case DIF_OP_CALL:
7936 			if (subr > DIF_SUBR_MAX)
7937 				err += efunc(pc, "invalid subr %u\n", subr);
7938 			if (rd >= nregs)
7939 				err += efunc(pc, "invalid register %u\n", rd);
7940 			if (rd == 0)
7941 				err += efunc(pc, "cannot write to %r0\n");
7942 
7943 			if (subr == DIF_SUBR_COPYOUT ||
7944 			    subr == DIF_SUBR_COPYOUTSTR) {
7945 				dp->dtdo_destructive = 1;
7946 			}
7947 			break;
7948 		case DIF_OP_PUSHTR:
7949 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
7950 				err += efunc(pc, "invalid ref type %u\n", type);
7951 			if (r2 >= nregs)
7952 				err += efunc(pc, "invalid register %u\n", r2);
7953 			if (rs >= nregs)
7954 				err += efunc(pc, "invalid register %u\n", rs);
7955 			break;
7956 		case DIF_OP_PUSHTV:
7957 			if (type != DIF_TYPE_CTF)
7958 				err += efunc(pc, "invalid val type %u\n", type);
7959 			if (r2 >= nregs)
7960 				err += efunc(pc, "invalid register %u\n", r2);
7961 			if (rs >= nregs)
7962 				err += efunc(pc, "invalid register %u\n", rs);
7963 			break;
7964 		default:
7965 			err += efunc(pc, "invalid opcode %u\n",
7966 			    DIF_INSTR_OP(instr));
7967 		}
7968 	}
7969 
7970 	if (dp->dtdo_len != 0 &&
7971 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
7972 		err += efunc(dp->dtdo_len - 1,
7973 		    "expected 'ret' as last DIF instruction\n");
7974 	}
7975 
7976 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
7977 		/*
7978 		 * If we're not returning by reference, the size must be either
7979 		 * 0 or the size of one of the base types.
7980 		 */
7981 		switch (dp->dtdo_rtype.dtdt_size) {
7982 		case 0:
7983 		case sizeof (uint8_t):
7984 		case sizeof (uint16_t):
7985 		case sizeof (uint32_t):
7986 		case sizeof (uint64_t):
7987 			break;
7988 
7989 		default:
7990 			err += efunc(dp->dtdo_len - 1, "bad return size");
7991 		}
7992 	}
7993 
7994 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
7995 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
7996 		dtrace_diftype_t *vt, *et;
7997 		uint_t id, ndx;
7998 
7999 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8000 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
8001 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8002 			err += efunc(i, "unrecognized variable scope %d\n",
8003 			    v->dtdv_scope);
8004 			break;
8005 		}
8006 
8007 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8008 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
8009 			err += efunc(i, "unrecognized variable type %d\n",
8010 			    v->dtdv_kind);
8011 			break;
8012 		}
8013 
8014 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8015 			err += efunc(i, "%d exceeds variable id limit\n", id);
8016 			break;
8017 		}
8018 
8019 		if (id < DIF_VAR_OTHER_UBASE)
8020 			continue;
8021 
8022 		/*
8023 		 * For user-defined variables, we need to check that this
8024 		 * definition is identical to any previous definition that we
8025 		 * encountered.
8026 		 */
8027 		ndx = id - DIF_VAR_OTHER_UBASE;
8028 
8029 		switch (v->dtdv_scope) {
8030 		case DIFV_SCOPE_GLOBAL:
8031 			if (ndx < vstate->dtvs_nglobals) {
8032 				dtrace_statvar_t *svar;
8033 
8034 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8035 					existing = &svar->dtsv_var;
8036 			}
8037 
8038 			break;
8039 
8040 		case DIFV_SCOPE_THREAD:
8041 			if (ndx < vstate->dtvs_ntlocals)
8042 				existing = &vstate->dtvs_tlocals[ndx];
8043 			break;
8044 
8045 		case DIFV_SCOPE_LOCAL:
8046 			if (ndx < vstate->dtvs_nlocals) {
8047 				dtrace_statvar_t *svar;
8048 
8049 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8050 					existing = &svar->dtsv_var;
8051 			}
8052 
8053 			break;
8054 		}
8055 
8056 		vt = &v->dtdv_type;
8057 
8058 		if (vt->dtdt_flags & DIF_TF_BYREF) {
8059 			if (vt->dtdt_size == 0) {
8060 				err += efunc(i, "zero-sized variable\n");
8061 				break;
8062 			}
8063 
8064 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8065 			    vt->dtdt_size > dtrace_global_maxsize) {
8066 				err += efunc(i, "oversized by-ref global\n");
8067 				break;
8068 			}
8069 		}
8070 
8071 		if (existing == NULL || existing->dtdv_id == 0)
8072 			continue;
8073 
8074 		ASSERT(existing->dtdv_id == v->dtdv_id);
8075 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
8076 
8077 		if (existing->dtdv_kind != v->dtdv_kind)
8078 			err += efunc(i, "%d changed variable kind\n", id);
8079 
8080 		et = &existing->dtdv_type;
8081 
8082 		if (vt->dtdt_flags != et->dtdt_flags) {
8083 			err += efunc(i, "%d changed variable type flags\n", id);
8084 			break;
8085 		}
8086 
8087 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8088 			err += efunc(i, "%d changed variable type size\n", id);
8089 			break;
8090 		}
8091 	}
8092 
8093 	return (err);
8094 }
8095 
8096 /*
8097  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
8098  * are much more constrained than normal DIFOs.  Specifically, they may
8099  * not:
8100  *
8101  * 1. Make calls to subroutines other than copyin(), copyinstr() or
8102  *    miscellaneous string routines
8103  * 2. Access DTrace variables other than the args[] array, and the
8104  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8105  * 3. Have thread-local variables.
8106  * 4. Have dynamic variables.
8107  */
8108 static int
8109 dtrace_difo_validate_helper(dtrace_difo_t *dp)
8110 {
8111 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8112 	int err = 0;
8113 	uint_t pc;
8114 
8115 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8116 		dif_instr_t instr = dp->dtdo_buf[pc];
8117 
8118 		uint_t v = DIF_INSTR_VAR(instr);
8119 		uint_t subr = DIF_INSTR_SUBR(instr);
8120 		uint_t op = DIF_INSTR_OP(instr);
8121 
8122 		switch (op) {
8123 		case DIF_OP_OR:
8124 		case DIF_OP_XOR:
8125 		case DIF_OP_AND:
8126 		case DIF_OP_SLL:
8127 		case DIF_OP_SRL:
8128 		case DIF_OP_SRA:
8129 		case DIF_OP_SUB:
8130 		case DIF_OP_ADD:
8131 		case DIF_OP_MUL:
8132 		case DIF_OP_SDIV:
8133 		case DIF_OP_UDIV:
8134 		case DIF_OP_SREM:
8135 		case DIF_OP_UREM:
8136 		case DIF_OP_COPYS:
8137 		case DIF_OP_NOT:
8138 		case DIF_OP_MOV:
8139 		case DIF_OP_RLDSB:
8140 		case DIF_OP_RLDSH:
8141 		case DIF_OP_RLDSW:
8142 		case DIF_OP_RLDUB:
8143 		case DIF_OP_RLDUH:
8144 		case DIF_OP_RLDUW:
8145 		case DIF_OP_RLDX:
8146 		case DIF_OP_ULDSB:
8147 		case DIF_OP_ULDSH:
8148 		case DIF_OP_ULDSW:
8149 		case DIF_OP_ULDUB:
8150 		case DIF_OP_ULDUH:
8151 		case DIF_OP_ULDUW:
8152 		case DIF_OP_ULDX:
8153 		case DIF_OP_STB:
8154 		case DIF_OP_STH:
8155 		case DIF_OP_STW:
8156 		case DIF_OP_STX:
8157 		case DIF_OP_ALLOCS:
8158 		case DIF_OP_CMP:
8159 		case DIF_OP_SCMP:
8160 		case DIF_OP_TST:
8161 		case DIF_OP_BA:
8162 		case DIF_OP_BE:
8163 		case DIF_OP_BNE:
8164 		case DIF_OP_BG:
8165 		case DIF_OP_BGU:
8166 		case DIF_OP_BGE:
8167 		case DIF_OP_BGEU:
8168 		case DIF_OP_BL:
8169 		case DIF_OP_BLU:
8170 		case DIF_OP_BLE:
8171 		case DIF_OP_BLEU:
8172 		case DIF_OP_RET:
8173 		case DIF_OP_NOP:
8174 		case DIF_OP_POPTS:
8175 		case DIF_OP_FLUSHTS:
8176 		case DIF_OP_SETX:
8177 		case DIF_OP_SETS:
8178 		case DIF_OP_LDGA:
8179 		case DIF_OP_LDLS:
8180 		case DIF_OP_STGS:
8181 		case DIF_OP_STLS:
8182 		case DIF_OP_PUSHTR:
8183 		case DIF_OP_PUSHTV:
8184 			break;
8185 
8186 		case DIF_OP_LDGS:
8187 			if (v >= DIF_VAR_OTHER_UBASE)
8188 				break;
8189 
8190 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
8191 				break;
8192 
8193 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
8194 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
8195 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
8196 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
8197 				break;
8198 
8199 			err += efunc(pc, "illegal variable %u\n", v);
8200 			break;
8201 
8202 		case DIF_OP_LDTA:
8203 		case DIF_OP_LDTS:
8204 		case DIF_OP_LDGAA:
8205 		case DIF_OP_LDTAA:
8206 			err += efunc(pc, "illegal dynamic variable load\n");
8207 			break;
8208 
8209 		case DIF_OP_STTS:
8210 		case DIF_OP_STGAA:
8211 		case DIF_OP_STTAA:
8212 			err += efunc(pc, "illegal dynamic variable store\n");
8213 			break;
8214 
8215 		case DIF_OP_CALL:
8216 			if (subr == DIF_SUBR_ALLOCA ||
8217 			    subr == DIF_SUBR_BCOPY ||
8218 			    subr == DIF_SUBR_COPYIN ||
8219 			    subr == DIF_SUBR_COPYINTO ||
8220 			    subr == DIF_SUBR_COPYINSTR ||
8221 			    subr == DIF_SUBR_INDEX ||
8222 			    subr == DIF_SUBR_INET_NTOA ||
8223 			    subr == DIF_SUBR_INET_NTOA6 ||
8224 			    subr == DIF_SUBR_INET_NTOP ||
8225 			    subr == DIF_SUBR_LLTOSTR ||
8226 			    subr == DIF_SUBR_RINDEX ||
8227 			    subr == DIF_SUBR_STRCHR ||
8228 			    subr == DIF_SUBR_STRJOIN ||
8229 			    subr == DIF_SUBR_STRRCHR ||
8230 			    subr == DIF_SUBR_STRSTR ||
8231 			    subr == DIF_SUBR_HTONS ||
8232 			    subr == DIF_SUBR_HTONL ||
8233 			    subr == DIF_SUBR_HTONLL ||
8234 			    subr == DIF_SUBR_NTOHS ||
8235 			    subr == DIF_SUBR_NTOHL ||
8236 			    subr == DIF_SUBR_NTOHLL)
8237 				break;
8238 
8239 			err += efunc(pc, "invalid subr %u\n", subr);
8240 			break;
8241 
8242 		default:
8243 			err += efunc(pc, "invalid opcode %u\n",
8244 			    DIF_INSTR_OP(instr));
8245 		}
8246 	}
8247 
8248 	return (err);
8249 }
8250 
8251 /*
8252  * Returns 1 if the expression in the DIF object can be cached on a per-thread
8253  * basis; 0 if not.
8254  */
8255 static int
8256 dtrace_difo_cacheable(dtrace_difo_t *dp)
8257 {
8258 	int i;
8259 
8260 	if (dp == NULL)
8261 		return (0);
8262 
8263 	for (i = 0; i < dp->dtdo_varlen; i++) {
8264 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8265 
8266 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
8267 			continue;
8268 
8269 		switch (v->dtdv_id) {
8270 		case DIF_VAR_CURTHREAD:
8271 		case DIF_VAR_PID:
8272 		case DIF_VAR_TID:
8273 		case DIF_VAR_EXECNAME:
8274 		case DIF_VAR_ZONENAME:
8275 			break;
8276 
8277 		default:
8278 			return (0);
8279 		}
8280 	}
8281 
8282 	/*
8283 	 * This DIF object may be cacheable.  Now we need to look for any
8284 	 * array loading instructions, any memory loading instructions, or
8285 	 * any stores to thread-local variables.
8286 	 */
8287 	for (i = 0; i < dp->dtdo_len; i++) {
8288 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
8289 
8290 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
8291 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
8292 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
8293 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
8294 			return (0);
8295 	}
8296 
8297 	return (1);
8298 }
8299 
8300 static void
8301 dtrace_difo_hold(dtrace_difo_t *dp)
8302 {
8303 	int i;
8304 
8305 	ASSERT(MUTEX_HELD(&dtrace_lock));
8306 
8307 	dp->dtdo_refcnt++;
8308 	ASSERT(dp->dtdo_refcnt != 0);
8309 
8310 	/*
8311 	 * We need to check this DIF object for references to the variable
8312 	 * DIF_VAR_VTIMESTAMP.
8313 	 */
8314 	for (i = 0; i < dp->dtdo_varlen; i++) {
8315 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8316 
8317 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8318 			continue;
8319 
8320 		if (dtrace_vtime_references++ == 0)
8321 			dtrace_vtime_enable();
8322 	}
8323 }
8324 
8325 /*
8326  * This routine calculates the dynamic variable chunksize for a given DIF
8327  * object.  The calculation is not fool-proof, and can probably be tricked by
8328  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
8329  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
8330  * if a dynamic variable size exceeds the chunksize.
8331  */
8332 static void
8333 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8334 {
8335 	uint64_t sval;
8336 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
8337 	const dif_instr_t *text = dp->dtdo_buf;
8338 	uint_t pc, srd = 0;
8339 	uint_t ttop = 0;
8340 	size_t size, ksize;
8341 	uint_t id, i;
8342 
8343 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8344 		dif_instr_t instr = text[pc];
8345 		uint_t op = DIF_INSTR_OP(instr);
8346 		uint_t rd = DIF_INSTR_RD(instr);
8347 		uint_t r1 = DIF_INSTR_R1(instr);
8348 		uint_t nkeys = 0;
8349 		uchar_t scope;
8350 
8351 		dtrace_key_t *key = tupregs;
8352 
8353 		switch (op) {
8354 		case DIF_OP_SETX:
8355 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
8356 			srd = rd;
8357 			continue;
8358 
8359 		case DIF_OP_STTS:
8360 			key = &tupregs[DIF_DTR_NREGS];
8361 			key[0].dttk_size = 0;
8362 			key[1].dttk_size = 0;
8363 			nkeys = 2;
8364 			scope = DIFV_SCOPE_THREAD;
8365 			break;
8366 
8367 		case DIF_OP_STGAA:
8368 		case DIF_OP_STTAA:
8369 			nkeys = ttop;
8370 
8371 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
8372 				key[nkeys++].dttk_size = 0;
8373 
8374 			key[nkeys++].dttk_size = 0;
8375 
8376 			if (op == DIF_OP_STTAA) {
8377 				scope = DIFV_SCOPE_THREAD;
8378 			} else {
8379 				scope = DIFV_SCOPE_GLOBAL;
8380 			}
8381 
8382 			break;
8383 
8384 		case DIF_OP_PUSHTR:
8385 			if (ttop == DIF_DTR_NREGS)
8386 				return;
8387 
8388 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
8389 				/*
8390 				 * If the register for the size of the "pushtr"
8391 				 * is %r0 (or the value is 0) and the type is
8392 				 * a string, we'll use the system-wide default
8393 				 * string size.
8394 				 */
8395 				tupregs[ttop++].dttk_size =
8396 				    dtrace_strsize_default;
8397 			} else {
8398 				if (srd == 0)
8399 					return;
8400 
8401 				tupregs[ttop++].dttk_size = sval;
8402 			}
8403 
8404 			break;
8405 
8406 		case DIF_OP_PUSHTV:
8407 			if (ttop == DIF_DTR_NREGS)
8408 				return;
8409 
8410 			tupregs[ttop++].dttk_size = 0;
8411 			break;
8412 
8413 		case DIF_OP_FLUSHTS:
8414 			ttop = 0;
8415 			break;
8416 
8417 		case DIF_OP_POPTS:
8418 			if (ttop != 0)
8419 				ttop--;
8420 			break;
8421 		}
8422 
8423 		sval = 0;
8424 		srd = 0;
8425 
8426 		if (nkeys == 0)
8427 			continue;
8428 
8429 		/*
8430 		 * We have a dynamic variable allocation; calculate its size.
8431 		 */
8432 		for (ksize = 0, i = 0; i < nkeys; i++)
8433 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
8434 
8435 		size = sizeof (dtrace_dynvar_t);
8436 		size += sizeof (dtrace_key_t) * (nkeys - 1);
8437 		size += ksize;
8438 
8439 		/*
8440 		 * Now we need to determine the size of the stored data.
8441 		 */
8442 		id = DIF_INSTR_VAR(instr);
8443 
8444 		for (i = 0; i < dp->dtdo_varlen; i++) {
8445 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
8446 
8447 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
8448 				size += v->dtdv_type.dtdt_size;
8449 				break;
8450 			}
8451 		}
8452 
8453 		if (i == dp->dtdo_varlen)
8454 			return;
8455 
8456 		/*
8457 		 * We have the size.  If this is larger than the chunk size
8458 		 * for our dynamic variable state, reset the chunk size.
8459 		 */
8460 		size = P2ROUNDUP(size, sizeof (uint64_t));
8461 
8462 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
8463 			vstate->dtvs_dynvars.dtds_chunksize = size;
8464 	}
8465 }
8466 
8467 static void
8468 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8469 {
8470 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
8471 	uint_t id;
8472 
8473 	ASSERT(MUTEX_HELD(&dtrace_lock));
8474 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
8475 
8476 	for (i = 0; i < dp->dtdo_varlen; i++) {
8477 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8478 		dtrace_statvar_t *svar, ***svarp;
8479 		size_t dsize = 0;
8480 		uint8_t scope = v->dtdv_scope;
8481 		int *np;
8482 
8483 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8484 			continue;
8485 
8486 		id -= DIF_VAR_OTHER_UBASE;
8487 
8488 		switch (scope) {
8489 		case DIFV_SCOPE_THREAD:
8490 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
8491 				dtrace_difv_t *tlocals;
8492 
8493 				if ((ntlocals = (otlocals << 1)) == 0)
8494 					ntlocals = 1;
8495 
8496 				osz = otlocals * sizeof (dtrace_difv_t);
8497 				nsz = ntlocals * sizeof (dtrace_difv_t);
8498 
8499 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
8500 
8501 				if (osz != 0) {
8502 					bcopy(vstate->dtvs_tlocals,
8503 					    tlocals, osz);
8504 					kmem_free(vstate->dtvs_tlocals, osz);
8505 				}
8506 
8507 				vstate->dtvs_tlocals = tlocals;
8508 				vstate->dtvs_ntlocals = ntlocals;
8509 			}
8510 
8511 			vstate->dtvs_tlocals[id] = *v;
8512 			continue;
8513 
8514 		case DIFV_SCOPE_LOCAL:
8515 			np = &vstate->dtvs_nlocals;
8516 			svarp = &vstate->dtvs_locals;
8517 
8518 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8519 				dsize = NCPU * (v->dtdv_type.dtdt_size +
8520 				    sizeof (uint64_t));
8521 			else
8522 				dsize = NCPU * sizeof (uint64_t);
8523 
8524 			break;
8525 
8526 		case DIFV_SCOPE_GLOBAL:
8527 			np = &vstate->dtvs_nglobals;
8528 			svarp = &vstate->dtvs_globals;
8529 
8530 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8531 				dsize = v->dtdv_type.dtdt_size +
8532 				    sizeof (uint64_t);
8533 
8534 			break;
8535 
8536 		default:
8537 			ASSERT(0);
8538 		}
8539 
8540 		while (id >= (oldsvars = *np)) {
8541 			dtrace_statvar_t **statics;
8542 			int newsvars, oldsize, newsize;
8543 
8544 			if ((newsvars = (oldsvars << 1)) == 0)
8545 				newsvars = 1;
8546 
8547 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
8548 			newsize = newsvars * sizeof (dtrace_statvar_t *);
8549 
8550 			statics = kmem_zalloc(newsize, KM_SLEEP);
8551 
8552 			if (oldsize != 0) {
8553 				bcopy(*svarp, statics, oldsize);
8554 				kmem_free(*svarp, oldsize);
8555 			}
8556 
8557 			*svarp = statics;
8558 			*np = newsvars;
8559 		}
8560 
8561 		if ((svar = (*svarp)[id]) == NULL) {
8562 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
8563 			svar->dtsv_var = *v;
8564 
8565 			if ((svar->dtsv_size = dsize) != 0) {
8566 				svar->dtsv_data = (uint64_t)(uintptr_t)
8567 				    kmem_zalloc(dsize, KM_SLEEP);
8568 			}
8569 
8570 			(*svarp)[id] = svar;
8571 		}
8572 
8573 		svar->dtsv_refcnt++;
8574 	}
8575 
8576 	dtrace_difo_chunksize(dp, vstate);
8577 	dtrace_difo_hold(dp);
8578 }
8579 
8580 static dtrace_difo_t *
8581 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8582 {
8583 	dtrace_difo_t *new;
8584 	size_t sz;
8585 
8586 	ASSERT(dp->dtdo_buf != NULL);
8587 	ASSERT(dp->dtdo_refcnt != 0);
8588 
8589 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
8590 
8591 	ASSERT(dp->dtdo_buf != NULL);
8592 	sz = dp->dtdo_len * sizeof (dif_instr_t);
8593 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
8594 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
8595 	new->dtdo_len = dp->dtdo_len;
8596 
8597 	if (dp->dtdo_strtab != NULL) {
8598 		ASSERT(dp->dtdo_strlen != 0);
8599 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
8600 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
8601 		new->dtdo_strlen = dp->dtdo_strlen;
8602 	}
8603 
8604 	if (dp->dtdo_inttab != NULL) {
8605 		ASSERT(dp->dtdo_intlen != 0);
8606 		sz = dp->dtdo_intlen * sizeof (uint64_t);
8607 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
8608 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
8609 		new->dtdo_intlen = dp->dtdo_intlen;
8610 	}
8611 
8612 	if (dp->dtdo_vartab != NULL) {
8613 		ASSERT(dp->dtdo_varlen != 0);
8614 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
8615 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
8616 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
8617 		new->dtdo_varlen = dp->dtdo_varlen;
8618 	}
8619 
8620 	dtrace_difo_init(new, vstate);
8621 	return (new);
8622 }
8623 
8624 static void
8625 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8626 {
8627 	int i;
8628 
8629 	ASSERT(dp->dtdo_refcnt == 0);
8630 
8631 	for (i = 0; i < dp->dtdo_varlen; i++) {
8632 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8633 		dtrace_statvar_t *svar, **svarp;
8634 		uint_t id;
8635 		uint8_t scope = v->dtdv_scope;
8636 		int *np;
8637 
8638 		switch (scope) {
8639 		case DIFV_SCOPE_THREAD:
8640 			continue;
8641 
8642 		case DIFV_SCOPE_LOCAL:
8643 			np = &vstate->dtvs_nlocals;
8644 			svarp = vstate->dtvs_locals;
8645 			break;
8646 
8647 		case DIFV_SCOPE_GLOBAL:
8648 			np = &vstate->dtvs_nglobals;
8649 			svarp = vstate->dtvs_globals;
8650 			break;
8651 
8652 		default:
8653 			ASSERT(0);
8654 		}
8655 
8656 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8657 			continue;
8658 
8659 		id -= DIF_VAR_OTHER_UBASE;
8660 		ASSERT(id < *np);
8661 
8662 		svar = svarp[id];
8663 		ASSERT(svar != NULL);
8664 		ASSERT(svar->dtsv_refcnt > 0);
8665 
8666 		if (--svar->dtsv_refcnt > 0)
8667 			continue;
8668 
8669 		if (svar->dtsv_size != 0) {
8670 			ASSERT(svar->dtsv_data != NULL);
8671 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
8672 			    svar->dtsv_size);
8673 		}
8674 
8675 		kmem_free(svar, sizeof (dtrace_statvar_t));
8676 		svarp[id] = NULL;
8677 	}
8678 
8679 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
8680 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
8681 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
8682 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
8683 
8684 	kmem_free(dp, sizeof (dtrace_difo_t));
8685 }
8686 
8687 static void
8688 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8689 {
8690 	int i;
8691 
8692 	ASSERT(MUTEX_HELD(&dtrace_lock));
8693 	ASSERT(dp->dtdo_refcnt != 0);
8694 
8695 	for (i = 0; i < dp->dtdo_varlen; i++) {
8696 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8697 
8698 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8699 			continue;
8700 
8701 		ASSERT(dtrace_vtime_references > 0);
8702 		if (--dtrace_vtime_references == 0)
8703 			dtrace_vtime_disable();
8704 	}
8705 
8706 	if (--dp->dtdo_refcnt == 0)
8707 		dtrace_difo_destroy(dp, vstate);
8708 }
8709 
8710 /*
8711  * DTrace Format Functions
8712  */
8713 static uint16_t
8714 dtrace_format_add(dtrace_state_t *state, char *str)
8715 {
8716 	char *fmt, **new;
8717 	uint16_t ndx, len = strlen(str) + 1;
8718 
8719 	fmt = kmem_zalloc(len, KM_SLEEP);
8720 	bcopy(str, fmt, len);
8721 
8722 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
8723 		if (state->dts_formats[ndx] == NULL) {
8724 			state->dts_formats[ndx] = fmt;
8725 			return (ndx + 1);
8726 		}
8727 	}
8728 
8729 	if (state->dts_nformats == USHRT_MAX) {
8730 		/*
8731 		 * This is only likely if a denial-of-service attack is being
8732 		 * attempted.  As such, it's okay to fail silently here.
8733 		 */
8734 		kmem_free(fmt, len);
8735 		return (0);
8736 	}
8737 
8738 	/*
8739 	 * For simplicity, we always resize the formats array to be exactly the
8740 	 * number of formats.
8741 	 */
8742 	ndx = state->dts_nformats++;
8743 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
8744 
8745 	if (state->dts_formats != NULL) {
8746 		ASSERT(ndx != 0);
8747 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
8748 		kmem_free(state->dts_formats, ndx * sizeof (char *));
8749 	}
8750 
8751 	state->dts_formats = new;
8752 	state->dts_formats[ndx] = fmt;
8753 
8754 	return (ndx + 1);
8755 }
8756 
8757 static void
8758 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
8759 {
8760 	char *fmt;
8761 
8762 	ASSERT(state->dts_formats != NULL);
8763 	ASSERT(format <= state->dts_nformats);
8764 	ASSERT(state->dts_formats[format - 1] != NULL);
8765 
8766 	fmt = state->dts_formats[format - 1];
8767 	kmem_free(fmt, strlen(fmt) + 1);
8768 	state->dts_formats[format - 1] = NULL;
8769 }
8770 
8771 static void
8772 dtrace_format_destroy(dtrace_state_t *state)
8773 {
8774 	int i;
8775 
8776 	if (state->dts_nformats == 0) {
8777 		ASSERT(state->dts_formats == NULL);
8778 		return;
8779 	}
8780 
8781 	ASSERT(state->dts_formats != NULL);
8782 
8783 	for (i = 0; i < state->dts_nformats; i++) {
8784 		char *fmt = state->dts_formats[i];
8785 
8786 		if (fmt == NULL)
8787 			continue;
8788 
8789 		kmem_free(fmt, strlen(fmt) + 1);
8790 	}
8791 
8792 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
8793 	state->dts_nformats = 0;
8794 	state->dts_formats = NULL;
8795 }
8796 
8797 /*
8798  * DTrace Predicate Functions
8799  */
8800 static dtrace_predicate_t *
8801 dtrace_predicate_create(dtrace_difo_t *dp)
8802 {
8803 	dtrace_predicate_t *pred;
8804 
8805 	ASSERT(MUTEX_HELD(&dtrace_lock));
8806 	ASSERT(dp->dtdo_refcnt != 0);
8807 
8808 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
8809 	pred->dtp_difo = dp;
8810 	pred->dtp_refcnt = 1;
8811 
8812 	if (!dtrace_difo_cacheable(dp))
8813 		return (pred);
8814 
8815 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
8816 		/*
8817 		 * This is only theoretically possible -- we have had 2^32
8818 		 * cacheable predicates on this machine.  We cannot allow any
8819 		 * more predicates to become cacheable:  as unlikely as it is,
8820 		 * there may be a thread caching a (now stale) predicate cache
8821 		 * ID. (N.B.: the temptation is being successfully resisted to
8822 		 * have this cmn_err() "Holy shit -- we executed this code!")
8823 		 */
8824 		return (pred);
8825 	}
8826 
8827 	pred->dtp_cacheid = dtrace_predcache_id++;
8828 
8829 	return (pred);
8830 }
8831 
8832 static void
8833 dtrace_predicate_hold(dtrace_predicate_t *pred)
8834 {
8835 	ASSERT(MUTEX_HELD(&dtrace_lock));
8836 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
8837 	ASSERT(pred->dtp_refcnt > 0);
8838 
8839 	pred->dtp_refcnt++;
8840 }
8841 
8842 static void
8843 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
8844 {
8845 	dtrace_difo_t *dp = pred->dtp_difo;
8846 
8847 	ASSERT(MUTEX_HELD(&dtrace_lock));
8848 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
8849 	ASSERT(pred->dtp_refcnt > 0);
8850 
8851 	if (--pred->dtp_refcnt == 0) {
8852 		dtrace_difo_release(pred->dtp_difo, vstate);
8853 		kmem_free(pred, sizeof (dtrace_predicate_t));
8854 	}
8855 }
8856 
8857 /*
8858  * DTrace Action Description Functions
8859  */
8860 static dtrace_actdesc_t *
8861 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
8862     uint64_t uarg, uint64_t arg)
8863 {
8864 	dtrace_actdesc_t *act;
8865 
8866 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
8867 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
8868 
8869 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
8870 	act->dtad_kind = kind;
8871 	act->dtad_ntuple = ntuple;
8872 	act->dtad_uarg = uarg;
8873 	act->dtad_arg = arg;
8874 	act->dtad_refcnt = 1;
8875 
8876 	return (act);
8877 }
8878 
8879 static void
8880 dtrace_actdesc_hold(dtrace_actdesc_t *act)
8881 {
8882 	ASSERT(act->dtad_refcnt >= 1);
8883 	act->dtad_refcnt++;
8884 }
8885 
8886 static void
8887 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
8888 {
8889 	dtrace_actkind_t kind = act->dtad_kind;
8890 	dtrace_difo_t *dp;
8891 
8892 	ASSERT(act->dtad_refcnt >= 1);
8893 
8894 	if (--act->dtad_refcnt != 0)
8895 		return;
8896 
8897 	if ((dp = act->dtad_difo) != NULL)
8898 		dtrace_difo_release(dp, vstate);
8899 
8900 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
8901 		char *str = (char *)(uintptr_t)act->dtad_arg;
8902 
8903 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
8904 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
8905 
8906 		if (str != NULL)
8907 			kmem_free(str, strlen(str) + 1);
8908 	}
8909 
8910 	kmem_free(act, sizeof (dtrace_actdesc_t));
8911 }
8912 
8913 /*
8914  * DTrace ECB Functions
8915  */
8916 static dtrace_ecb_t *
8917 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
8918 {
8919 	dtrace_ecb_t *ecb;
8920 	dtrace_epid_t epid;
8921 
8922 	ASSERT(MUTEX_HELD(&dtrace_lock));
8923 
8924 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
8925 	ecb->dte_predicate = NULL;
8926 	ecb->dte_probe = probe;
8927 
8928 	/*
8929 	 * The default size is the size of the default action: recording
8930 	 * the epid.
8931 	 */
8932 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
8933 	ecb->dte_alignment = sizeof (dtrace_epid_t);
8934 
8935 	epid = state->dts_epid++;
8936 
8937 	if (epid - 1 >= state->dts_necbs) {
8938 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
8939 		int necbs = state->dts_necbs << 1;
8940 
8941 		ASSERT(epid == state->dts_necbs + 1);
8942 
8943 		if (necbs == 0) {
8944 			ASSERT(oecbs == NULL);
8945 			necbs = 1;
8946 		}
8947 
8948 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
8949 
8950 		if (oecbs != NULL)
8951 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
8952 
8953 		dtrace_membar_producer();
8954 		state->dts_ecbs = ecbs;
8955 
8956 		if (oecbs != NULL) {
8957 			/*
8958 			 * If this state is active, we must dtrace_sync()
8959 			 * before we can free the old dts_ecbs array:  we're
8960 			 * coming in hot, and there may be active ring
8961 			 * buffer processing (which indexes into the dts_ecbs
8962 			 * array) on another CPU.
8963 			 */
8964 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
8965 				dtrace_sync();
8966 
8967 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
8968 		}
8969 
8970 		dtrace_membar_producer();
8971 		state->dts_necbs = necbs;
8972 	}
8973 
8974 	ecb->dte_state = state;
8975 
8976 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
8977 	dtrace_membar_producer();
8978 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
8979 
8980 	return (ecb);
8981 }
8982 
8983 static void
8984 dtrace_ecb_enable(dtrace_ecb_t *ecb)
8985 {
8986 	dtrace_probe_t *probe = ecb->dte_probe;
8987 
8988 	ASSERT(MUTEX_HELD(&cpu_lock));
8989 	ASSERT(MUTEX_HELD(&dtrace_lock));
8990 	ASSERT(ecb->dte_next == NULL);
8991 
8992 	if (probe == NULL) {
8993 		/*
8994 		 * This is the NULL probe -- there's nothing to do.
8995 		 */
8996 		return;
8997 	}
8998 
8999 	if (probe->dtpr_ecb == NULL) {
9000 		dtrace_provider_t *prov = probe->dtpr_provider;
9001 
9002 		/*
9003 		 * We're the first ECB on this probe.
9004 		 */
9005 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9006 
9007 		if (ecb->dte_predicate != NULL)
9008 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9009 
9010 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9011 		    probe->dtpr_id, probe->dtpr_arg);
9012 	} else {
9013 		/*
9014 		 * This probe is already active.  Swing the last pointer to
9015 		 * point to the new ECB, and issue a dtrace_sync() to assure
9016 		 * that all CPUs have seen the change.
9017 		 */
9018 		ASSERT(probe->dtpr_ecb_last != NULL);
9019 		probe->dtpr_ecb_last->dte_next = ecb;
9020 		probe->dtpr_ecb_last = ecb;
9021 		probe->dtpr_predcache = 0;
9022 
9023 		dtrace_sync();
9024 	}
9025 }
9026 
9027 static void
9028 dtrace_ecb_resize(dtrace_ecb_t *ecb)
9029 {
9030 	uint32_t maxalign = sizeof (dtrace_epid_t);
9031 	uint32_t align = sizeof (uint8_t), offs, diff;
9032 	dtrace_action_t *act;
9033 	int wastuple = 0;
9034 	uint32_t aggbase = UINT32_MAX;
9035 	dtrace_state_t *state = ecb->dte_state;
9036 
9037 	/*
9038 	 * If we record anything, we always record the epid.  (And we always
9039 	 * record it first.)
9040 	 */
9041 	offs = sizeof (dtrace_epid_t);
9042 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
9043 
9044 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9045 		dtrace_recdesc_t *rec = &act->dta_rec;
9046 
9047 		if ((align = rec->dtrd_alignment) > maxalign)
9048 			maxalign = align;
9049 
9050 		if (!wastuple && act->dta_intuple) {
9051 			/*
9052 			 * This is the first record in a tuple.  Align the
9053 			 * offset to be at offset 4 in an 8-byte aligned
9054 			 * block.
9055 			 */
9056 			diff = offs + sizeof (dtrace_aggid_t);
9057 
9058 			if (diff = (diff & (sizeof (uint64_t) - 1)))
9059 				offs += sizeof (uint64_t) - diff;
9060 
9061 			aggbase = offs - sizeof (dtrace_aggid_t);
9062 			ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
9063 		}
9064 
9065 		/*LINTED*/
9066 		if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
9067 			/*
9068 			 * The current offset is not properly aligned; align it.
9069 			 */
9070 			offs += align - diff;
9071 		}
9072 
9073 		rec->dtrd_offset = offs;
9074 
9075 		if (offs + rec->dtrd_size > ecb->dte_needed) {
9076 			ecb->dte_needed = offs + rec->dtrd_size;
9077 
9078 			if (ecb->dte_needed > state->dts_needed)
9079 				state->dts_needed = ecb->dte_needed;
9080 		}
9081 
9082 		if (DTRACEACT_ISAGG(act->dta_kind)) {
9083 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9084 			dtrace_action_t *first = agg->dtag_first, *prev;
9085 
9086 			ASSERT(rec->dtrd_size != 0 && first != NULL);
9087 			ASSERT(wastuple);
9088 			ASSERT(aggbase != UINT32_MAX);
9089 
9090 			agg->dtag_base = aggbase;
9091 
9092 			while ((prev = first->dta_prev) != NULL &&
9093 			    DTRACEACT_ISAGG(prev->dta_kind)) {
9094 				agg = (dtrace_aggregation_t *)prev;
9095 				first = agg->dtag_first;
9096 			}
9097 
9098 			if (prev != NULL) {
9099 				offs = prev->dta_rec.dtrd_offset +
9100 				    prev->dta_rec.dtrd_size;
9101 			} else {
9102 				offs = sizeof (dtrace_epid_t);
9103 			}
9104 			wastuple = 0;
9105 		} else {
9106 			if (!act->dta_intuple)
9107 				ecb->dte_size = offs + rec->dtrd_size;
9108 
9109 			offs += rec->dtrd_size;
9110 		}
9111 
9112 		wastuple = act->dta_intuple;
9113 	}
9114 
9115 	if ((act = ecb->dte_action) != NULL &&
9116 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9117 	    ecb->dte_size == sizeof (dtrace_epid_t)) {
9118 		/*
9119 		 * If the size is still sizeof (dtrace_epid_t), then all
9120 		 * actions store no data; set the size to 0.
9121 		 */
9122 		ecb->dte_alignment = maxalign;
9123 		ecb->dte_size = 0;
9124 
9125 		/*
9126 		 * If the needed space is still sizeof (dtrace_epid_t), then
9127 		 * all actions need no additional space; set the needed
9128 		 * size to 0.
9129 		 */
9130 		if (ecb->dte_needed == sizeof (dtrace_epid_t))
9131 			ecb->dte_needed = 0;
9132 
9133 		return;
9134 	}
9135 
9136 	/*
9137 	 * Set our alignment, and make sure that the dte_size and dte_needed
9138 	 * are aligned to the size of an EPID.
9139 	 */
9140 	ecb->dte_alignment = maxalign;
9141 	ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
9142 	    ~(sizeof (dtrace_epid_t) - 1);
9143 	ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
9144 	    ~(sizeof (dtrace_epid_t) - 1);
9145 	ASSERT(ecb->dte_size <= ecb->dte_needed);
9146 }
9147 
9148 static dtrace_action_t *
9149 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9150 {
9151 	dtrace_aggregation_t *agg;
9152 	size_t size = sizeof (uint64_t);
9153 	int ntuple = desc->dtad_ntuple;
9154 	dtrace_action_t *act;
9155 	dtrace_recdesc_t *frec;
9156 	dtrace_aggid_t aggid;
9157 	dtrace_state_t *state = ecb->dte_state;
9158 
9159 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
9160 	agg->dtag_ecb = ecb;
9161 
9162 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
9163 
9164 	switch (desc->dtad_kind) {
9165 	case DTRACEAGG_MIN:
9166 		agg->dtag_initial = UINT64_MAX;
9167 		agg->dtag_aggregate = dtrace_aggregate_min;
9168 		break;
9169 
9170 	case DTRACEAGG_MAX:
9171 		agg->dtag_aggregate = dtrace_aggregate_max;
9172 		break;
9173 
9174 	case DTRACEAGG_COUNT:
9175 		agg->dtag_aggregate = dtrace_aggregate_count;
9176 		break;
9177 
9178 	case DTRACEAGG_QUANTIZE:
9179 		agg->dtag_aggregate = dtrace_aggregate_quantize;
9180 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
9181 		    sizeof (uint64_t);
9182 		break;
9183 
9184 	case DTRACEAGG_LQUANTIZE: {
9185 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
9186 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
9187 
9188 		agg->dtag_initial = desc->dtad_arg;
9189 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
9190 
9191 		if (step == 0 || levels == 0)
9192 			goto err;
9193 
9194 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
9195 		break;
9196 	}
9197 
9198 	case DTRACEAGG_AVG:
9199 		agg->dtag_aggregate = dtrace_aggregate_avg;
9200 		size = sizeof (uint64_t) * 2;
9201 		break;
9202 
9203 	case DTRACEAGG_SUM:
9204 		agg->dtag_aggregate = dtrace_aggregate_sum;
9205 		break;
9206 
9207 	default:
9208 		goto err;
9209 	}
9210 
9211 	agg->dtag_action.dta_rec.dtrd_size = size;
9212 
9213 	if (ntuple == 0)
9214 		goto err;
9215 
9216 	/*
9217 	 * We must make sure that we have enough actions for the n-tuple.
9218 	 */
9219 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
9220 		if (DTRACEACT_ISAGG(act->dta_kind))
9221 			break;
9222 
9223 		if (--ntuple == 0) {
9224 			/*
9225 			 * This is the action with which our n-tuple begins.
9226 			 */
9227 			agg->dtag_first = act;
9228 			goto success;
9229 		}
9230 	}
9231 
9232 	/*
9233 	 * This n-tuple is short by ntuple elements.  Return failure.
9234 	 */
9235 	ASSERT(ntuple != 0);
9236 err:
9237 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9238 	return (NULL);
9239 
9240 success:
9241 	/*
9242 	 * If the last action in the tuple has a size of zero, it's actually
9243 	 * an expression argument for the aggregating action.
9244 	 */
9245 	ASSERT(ecb->dte_action_last != NULL);
9246 	act = ecb->dte_action_last;
9247 
9248 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
9249 		ASSERT(act->dta_difo != NULL);
9250 
9251 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
9252 			agg->dtag_hasarg = 1;
9253 	}
9254 
9255 	/*
9256 	 * We need to allocate an id for this aggregation.
9257 	 */
9258 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
9259 	    VM_BESTFIT | VM_SLEEP);
9260 
9261 	if (aggid - 1 >= state->dts_naggregations) {
9262 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
9263 		dtrace_aggregation_t **aggs;
9264 		int naggs = state->dts_naggregations << 1;
9265 		int onaggs = state->dts_naggregations;
9266 
9267 		ASSERT(aggid == state->dts_naggregations + 1);
9268 
9269 		if (naggs == 0) {
9270 			ASSERT(oaggs == NULL);
9271 			naggs = 1;
9272 		}
9273 
9274 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
9275 
9276 		if (oaggs != NULL) {
9277 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
9278 			kmem_free(oaggs, onaggs * sizeof (*aggs));
9279 		}
9280 
9281 		state->dts_aggregations = aggs;
9282 		state->dts_naggregations = naggs;
9283 	}
9284 
9285 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
9286 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
9287 
9288 	frec = &agg->dtag_first->dta_rec;
9289 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
9290 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
9291 
9292 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
9293 		ASSERT(!act->dta_intuple);
9294 		act->dta_intuple = 1;
9295 	}
9296 
9297 	return (&agg->dtag_action);
9298 }
9299 
9300 static void
9301 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
9302 {
9303 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9304 	dtrace_state_t *state = ecb->dte_state;
9305 	dtrace_aggid_t aggid = agg->dtag_id;
9306 
9307 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
9308 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
9309 
9310 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
9311 	state->dts_aggregations[aggid - 1] = NULL;
9312 
9313 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9314 }
9315 
9316 static int
9317 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9318 {
9319 	dtrace_action_t *action, *last;
9320 	dtrace_difo_t *dp = desc->dtad_difo;
9321 	uint32_t size = 0, align = sizeof (uint8_t), mask;
9322 	uint16_t format = 0;
9323 	dtrace_recdesc_t *rec;
9324 	dtrace_state_t *state = ecb->dte_state;
9325 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
9326 	uint64_t arg = desc->dtad_arg;
9327 
9328 	ASSERT(MUTEX_HELD(&dtrace_lock));
9329 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
9330 
9331 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
9332 		/*
9333 		 * If this is an aggregating action, there must be neither
9334 		 * a speculate nor a commit on the action chain.
9335 		 */
9336 		dtrace_action_t *act;
9337 
9338 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9339 			if (act->dta_kind == DTRACEACT_COMMIT)
9340 				return (EINVAL);
9341 
9342 			if (act->dta_kind == DTRACEACT_SPECULATE)
9343 				return (EINVAL);
9344 		}
9345 
9346 		action = dtrace_ecb_aggregation_create(ecb, desc);
9347 
9348 		if (action == NULL)
9349 			return (EINVAL);
9350 	} else {
9351 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
9352 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
9353 		    dp != NULL && dp->dtdo_destructive)) {
9354 			state->dts_destructive = 1;
9355 		}
9356 
9357 		switch (desc->dtad_kind) {
9358 		case DTRACEACT_PRINTF:
9359 		case DTRACEACT_PRINTA:
9360 		case DTRACEACT_SYSTEM:
9361 		case DTRACEACT_FREOPEN:
9362 			/*
9363 			 * We know that our arg is a string -- turn it into a
9364 			 * format.
9365 			 */
9366 			if (arg == NULL) {
9367 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
9368 				format = 0;
9369 			} else {
9370 				ASSERT(arg != NULL);
9371 				ASSERT(arg > KERNELBASE);
9372 				format = dtrace_format_add(state,
9373 				    (char *)(uintptr_t)arg);
9374 			}
9375 
9376 			/*FALLTHROUGH*/
9377 		case DTRACEACT_LIBACT:
9378 		case DTRACEACT_DIFEXPR:
9379 			if (dp == NULL)
9380 				return (EINVAL);
9381 
9382 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
9383 				break;
9384 
9385 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
9386 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9387 					return (EINVAL);
9388 
9389 				size = opt[DTRACEOPT_STRSIZE];
9390 			}
9391 
9392 			break;
9393 
9394 		case DTRACEACT_STACK:
9395 			if ((nframes = arg) == 0) {
9396 				nframes = opt[DTRACEOPT_STACKFRAMES];
9397 				ASSERT(nframes > 0);
9398 				arg = nframes;
9399 			}
9400 
9401 			size = nframes * sizeof (pc_t);
9402 			break;
9403 
9404 		case DTRACEACT_JSTACK:
9405 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
9406 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
9407 
9408 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
9409 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
9410 
9411 			arg = DTRACE_USTACK_ARG(nframes, strsize);
9412 
9413 			/*FALLTHROUGH*/
9414 		case DTRACEACT_USTACK:
9415 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
9416 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
9417 				strsize = DTRACE_USTACK_STRSIZE(arg);
9418 				nframes = opt[DTRACEOPT_USTACKFRAMES];
9419 				ASSERT(nframes > 0);
9420 				arg = DTRACE_USTACK_ARG(nframes, strsize);
9421 			}
9422 
9423 			/*
9424 			 * Save a slot for the pid.
9425 			 */
9426 			size = (nframes + 1) * sizeof (uint64_t);
9427 			size += DTRACE_USTACK_STRSIZE(arg);
9428 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
9429 
9430 			break;
9431 
9432 		case DTRACEACT_SYM:
9433 		case DTRACEACT_MOD:
9434 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
9435 			    sizeof (uint64_t)) ||
9436 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9437 				return (EINVAL);
9438 			break;
9439 
9440 		case DTRACEACT_USYM:
9441 		case DTRACEACT_UMOD:
9442 		case DTRACEACT_UADDR:
9443 			if (dp == NULL ||
9444 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
9445 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9446 				return (EINVAL);
9447 
9448 			/*
9449 			 * We have a slot for the pid, plus a slot for the
9450 			 * argument.  To keep things simple (aligned with
9451 			 * bitness-neutral sizing), we store each as a 64-bit
9452 			 * quantity.
9453 			 */
9454 			size = 2 * sizeof (uint64_t);
9455 			break;
9456 
9457 		case DTRACEACT_STOP:
9458 		case DTRACEACT_BREAKPOINT:
9459 		case DTRACEACT_PANIC:
9460 			break;
9461 
9462 		case DTRACEACT_CHILL:
9463 		case DTRACEACT_DISCARD:
9464 		case DTRACEACT_RAISE:
9465 			if (dp == NULL)
9466 				return (EINVAL);
9467 			break;
9468 
9469 		case DTRACEACT_EXIT:
9470 			if (dp == NULL ||
9471 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
9472 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9473 				return (EINVAL);
9474 			break;
9475 
9476 		case DTRACEACT_SPECULATE:
9477 			if (ecb->dte_size > sizeof (dtrace_epid_t))
9478 				return (EINVAL);
9479 
9480 			if (dp == NULL)
9481 				return (EINVAL);
9482 
9483 			state->dts_speculates = 1;
9484 			break;
9485 
9486 		case DTRACEACT_COMMIT: {
9487 			dtrace_action_t *act = ecb->dte_action;
9488 
9489 			for (; act != NULL; act = act->dta_next) {
9490 				if (act->dta_kind == DTRACEACT_COMMIT)
9491 					return (EINVAL);
9492 			}
9493 
9494 			if (dp == NULL)
9495 				return (EINVAL);
9496 			break;
9497 		}
9498 
9499 		default:
9500 			return (EINVAL);
9501 		}
9502 
9503 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
9504 			/*
9505 			 * If this is a data-storing action or a speculate,
9506 			 * we must be sure that there isn't a commit on the
9507 			 * action chain.
9508 			 */
9509 			dtrace_action_t *act = ecb->dte_action;
9510 
9511 			for (; act != NULL; act = act->dta_next) {
9512 				if (act->dta_kind == DTRACEACT_COMMIT)
9513 					return (EINVAL);
9514 			}
9515 		}
9516 
9517 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
9518 		action->dta_rec.dtrd_size = size;
9519 	}
9520 
9521 	action->dta_refcnt = 1;
9522 	rec = &action->dta_rec;
9523 	size = rec->dtrd_size;
9524 
9525 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
9526 		if (!(size & mask)) {
9527 			align = mask + 1;
9528 			break;
9529 		}
9530 	}
9531 
9532 	action->dta_kind = desc->dtad_kind;
9533 
9534 	if ((action->dta_difo = dp) != NULL)
9535 		dtrace_difo_hold(dp);
9536 
9537 	rec->dtrd_action = action->dta_kind;
9538 	rec->dtrd_arg = arg;
9539 	rec->dtrd_uarg = desc->dtad_uarg;
9540 	rec->dtrd_alignment = (uint16_t)align;
9541 	rec->dtrd_format = format;
9542 
9543 	if ((last = ecb->dte_action_last) != NULL) {
9544 		ASSERT(ecb->dte_action != NULL);
9545 		action->dta_prev = last;
9546 		last->dta_next = action;
9547 	} else {
9548 		ASSERT(ecb->dte_action == NULL);
9549 		ecb->dte_action = action;
9550 	}
9551 
9552 	ecb->dte_action_last = action;
9553 
9554 	return (0);
9555 }
9556 
9557 static void
9558 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
9559 {
9560 	dtrace_action_t *act = ecb->dte_action, *next;
9561 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
9562 	dtrace_difo_t *dp;
9563 	uint16_t format;
9564 
9565 	if (act != NULL && act->dta_refcnt > 1) {
9566 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
9567 		act->dta_refcnt--;
9568 	} else {
9569 		for (; act != NULL; act = next) {
9570 			next = act->dta_next;
9571 			ASSERT(next != NULL || act == ecb->dte_action_last);
9572 			ASSERT(act->dta_refcnt == 1);
9573 
9574 			if ((format = act->dta_rec.dtrd_format) != 0)
9575 				dtrace_format_remove(ecb->dte_state, format);
9576 
9577 			if ((dp = act->dta_difo) != NULL)
9578 				dtrace_difo_release(dp, vstate);
9579 
9580 			if (DTRACEACT_ISAGG(act->dta_kind)) {
9581 				dtrace_ecb_aggregation_destroy(ecb, act);
9582 			} else {
9583 				kmem_free(act, sizeof (dtrace_action_t));
9584 			}
9585 		}
9586 	}
9587 
9588 	ecb->dte_action = NULL;
9589 	ecb->dte_action_last = NULL;
9590 	ecb->dte_size = sizeof (dtrace_epid_t);
9591 }
9592 
9593 static void
9594 dtrace_ecb_disable(dtrace_ecb_t *ecb)
9595 {
9596 	/*
9597 	 * We disable the ECB by removing it from its probe.
9598 	 */
9599 	dtrace_ecb_t *pecb, *prev = NULL;
9600 	dtrace_probe_t *probe = ecb->dte_probe;
9601 
9602 	ASSERT(MUTEX_HELD(&dtrace_lock));
9603 
9604 	if (probe == NULL) {
9605 		/*
9606 		 * This is the NULL probe; there is nothing to disable.
9607 		 */
9608 		return;
9609 	}
9610 
9611 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
9612 		if (pecb == ecb)
9613 			break;
9614 		prev = pecb;
9615 	}
9616 
9617 	ASSERT(pecb != NULL);
9618 
9619 	if (prev == NULL) {
9620 		probe->dtpr_ecb = ecb->dte_next;
9621 	} else {
9622 		prev->dte_next = ecb->dte_next;
9623 	}
9624 
9625 	if (ecb == probe->dtpr_ecb_last) {
9626 		ASSERT(ecb->dte_next == NULL);
9627 		probe->dtpr_ecb_last = prev;
9628 	}
9629 
9630 	/*
9631 	 * The ECB has been disconnected from the probe; now sync to assure
9632 	 * that all CPUs have seen the change before returning.
9633 	 */
9634 	dtrace_sync();
9635 
9636 	if (probe->dtpr_ecb == NULL) {
9637 		/*
9638 		 * That was the last ECB on the probe; clear the predicate
9639 		 * cache ID for the probe, disable it and sync one more time
9640 		 * to assure that we'll never hit it again.
9641 		 */
9642 		dtrace_provider_t *prov = probe->dtpr_provider;
9643 
9644 		ASSERT(ecb->dte_next == NULL);
9645 		ASSERT(probe->dtpr_ecb_last == NULL);
9646 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
9647 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
9648 		    probe->dtpr_id, probe->dtpr_arg);
9649 		dtrace_sync();
9650 	} else {
9651 		/*
9652 		 * There is at least one ECB remaining on the probe.  If there
9653 		 * is _exactly_ one, set the probe's predicate cache ID to be
9654 		 * the predicate cache ID of the remaining ECB.
9655 		 */
9656 		ASSERT(probe->dtpr_ecb_last != NULL);
9657 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
9658 
9659 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
9660 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
9661 
9662 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
9663 
9664 			if (p != NULL)
9665 				probe->dtpr_predcache = p->dtp_cacheid;
9666 		}
9667 
9668 		ecb->dte_next = NULL;
9669 	}
9670 }
9671 
9672 static void
9673 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
9674 {
9675 	dtrace_state_t *state = ecb->dte_state;
9676 	dtrace_vstate_t *vstate = &state->dts_vstate;
9677 	dtrace_predicate_t *pred;
9678 	dtrace_epid_t epid = ecb->dte_epid;
9679 
9680 	ASSERT(MUTEX_HELD(&dtrace_lock));
9681 	ASSERT(ecb->dte_next == NULL);
9682 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
9683 
9684 	if ((pred = ecb->dte_predicate) != NULL)
9685 		dtrace_predicate_release(pred, vstate);
9686 
9687 	dtrace_ecb_action_remove(ecb);
9688 
9689 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
9690 	state->dts_ecbs[epid - 1] = NULL;
9691 
9692 	kmem_free(ecb, sizeof (dtrace_ecb_t));
9693 }
9694 
9695 static dtrace_ecb_t *
9696 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
9697     dtrace_enabling_t *enab)
9698 {
9699 	dtrace_ecb_t *ecb;
9700 	dtrace_predicate_t *pred;
9701 	dtrace_actdesc_t *act;
9702 	dtrace_provider_t *prov;
9703 	dtrace_ecbdesc_t *desc = enab->dten_current;
9704 
9705 	ASSERT(MUTEX_HELD(&dtrace_lock));
9706 	ASSERT(state != NULL);
9707 
9708 	ecb = dtrace_ecb_add(state, probe);
9709 	ecb->dte_uarg = desc->dted_uarg;
9710 
9711 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
9712 		dtrace_predicate_hold(pred);
9713 		ecb->dte_predicate = pred;
9714 	}
9715 
9716 	if (probe != NULL) {
9717 		/*
9718 		 * If the provider shows more leg than the consumer is old
9719 		 * enough to see, we need to enable the appropriate implicit
9720 		 * predicate bits to prevent the ecb from activating at
9721 		 * revealing times.
9722 		 *
9723 		 * Providers specifying DTRACE_PRIV_USER at register time
9724 		 * are stating that they need the /proc-style privilege
9725 		 * model to be enforced, and this is what DTRACE_COND_OWNER
9726 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
9727 		 */
9728 		prov = probe->dtpr_provider;
9729 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
9730 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9731 			ecb->dte_cond |= DTRACE_COND_OWNER;
9732 
9733 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
9734 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9735 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
9736 
9737 		/*
9738 		 * If the provider shows us kernel innards and the user
9739 		 * is lacking sufficient privilege, enable the
9740 		 * DTRACE_COND_USERMODE implicit predicate.
9741 		 */
9742 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
9743 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
9744 			ecb->dte_cond |= DTRACE_COND_USERMODE;
9745 	}
9746 
9747 	if (dtrace_ecb_create_cache != NULL) {
9748 		/*
9749 		 * If we have a cached ecb, we'll use its action list instead
9750 		 * of creating our own (saving both time and space).
9751 		 */
9752 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
9753 		dtrace_action_t *act = cached->dte_action;
9754 
9755 		if (act != NULL) {
9756 			ASSERT(act->dta_refcnt > 0);
9757 			act->dta_refcnt++;
9758 			ecb->dte_action = act;
9759 			ecb->dte_action_last = cached->dte_action_last;
9760 			ecb->dte_needed = cached->dte_needed;
9761 			ecb->dte_size = cached->dte_size;
9762 			ecb->dte_alignment = cached->dte_alignment;
9763 		}
9764 
9765 		return (ecb);
9766 	}
9767 
9768 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
9769 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
9770 			dtrace_ecb_destroy(ecb);
9771 			return (NULL);
9772 		}
9773 	}
9774 
9775 	dtrace_ecb_resize(ecb);
9776 
9777 	return (dtrace_ecb_create_cache = ecb);
9778 }
9779 
9780 static int
9781 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
9782 {
9783 	dtrace_ecb_t *ecb;
9784 	dtrace_enabling_t *enab = arg;
9785 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
9786 
9787 	ASSERT(state != NULL);
9788 
9789 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
9790 		/*
9791 		 * This probe was created in a generation for which this
9792 		 * enabling has previously created ECBs; we don't want to
9793 		 * enable it again, so just kick out.
9794 		 */
9795 		return (DTRACE_MATCH_NEXT);
9796 	}
9797 
9798 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
9799 		return (DTRACE_MATCH_DONE);
9800 
9801 	dtrace_ecb_enable(ecb);
9802 	return (DTRACE_MATCH_NEXT);
9803 }
9804 
9805 static dtrace_ecb_t *
9806 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
9807 {
9808 	dtrace_ecb_t *ecb;
9809 
9810 	ASSERT(MUTEX_HELD(&dtrace_lock));
9811 
9812 	if (id == 0 || id > state->dts_necbs)
9813 		return (NULL);
9814 
9815 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
9816 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
9817 
9818 	return (state->dts_ecbs[id - 1]);
9819 }
9820 
9821 static dtrace_aggregation_t *
9822 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
9823 {
9824 	dtrace_aggregation_t *agg;
9825 
9826 	ASSERT(MUTEX_HELD(&dtrace_lock));
9827 
9828 	if (id == 0 || id > state->dts_naggregations)
9829 		return (NULL);
9830 
9831 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
9832 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
9833 	    agg->dtag_id == id);
9834 
9835 	return (state->dts_aggregations[id - 1]);
9836 }
9837 
9838 /*
9839  * DTrace Buffer Functions
9840  *
9841  * The following functions manipulate DTrace buffers.  Most of these functions
9842  * are called in the context of establishing or processing consumer state;
9843  * exceptions are explicitly noted.
9844  */
9845 
9846 /*
9847  * Note:  called from cross call context.  This function switches the two
9848  * buffers on a given CPU.  The atomicity of this operation is assured by
9849  * disabling interrupts while the actual switch takes place; the disabling of
9850  * interrupts serializes the execution with any execution of dtrace_probe() on
9851  * the same CPU.
9852  */
9853 static void
9854 dtrace_buffer_switch(dtrace_buffer_t *buf)
9855 {
9856 	caddr_t tomax = buf->dtb_tomax;
9857 	caddr_t xamot = buf->dtb_xamot;
9858 	dtrace_icookie_t cookie;
9859 
9860 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
9861 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
9862 
9863 	cookie = dtrace_interrupt_disable();
9864 	buf->dtb_tomax = xamot;
9865 	buf->dtb_xamot = tomax;
9866 	buf->dtb_xamot_drops = buf->dtb_drops;
9867 	buf->dtb_xamot_offset = buf->dtb_offset;
9868 	buf->dtb_xamot_errors = buf->dtb_errors;
9869 	buf->dtb_xamot_flags = buf->dtb_flags;
9870 	buf->dtb_offset = 0;
9871 	buf->dtb_drops = 0;
9872 	buf->dtb_errors = 0;
9873 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
9874 	dtrace_interrupt_enable(cookie);
9875 }
9876 
9877 /*
9878  * Note:  called from cross call context.  This function activates a buffer
9879  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
9880  * is guaranteed by the disabling of interrupts.
9881  */
9882 static void
9883 dtrace_buffer_activate(dtrace_state_t *state)
9884 {
9885 	dtrace_buffer_t *buf;
9886 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
9887 
9888 	buf = &state->dts_buffer[CPU->cpu_id];
9889 
9890 	if (buf->dtb_tomax != NULL) {
9891 		/*
9892 		 * We might like to assert that the buffer is marked inactive,
9893 		 * but this isn't necessarily true:  the buffer for the CPU
9894 		 * that processes the BEGIN probe has its buffer activated
9895 		 * manually.  In this case, we take the (harmless) action
9896 		 * re-clearing the bit INACTIVE bit.
9897 		 */
9898 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
9899 	}
9900 
9901 	dtrace_interrupt_enable(cookie);
9902 }
9903 
9904 static int
9905 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
9906     processorid_t cpu)
9907 {
9908 	cpu_t *cp;
9909 	dtrace_buffer_t *buf;
9910 
9911 	ASSERT(MUTEX_HELD(&cpu_lock));
9912 	ASSERT(MUTEX_HELD(&dtrace_lock));
9913 
9914 	if (size > dtrace_nonroot_maxsize &&
9915 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
9916 		return (EFBIG);
9917 
9918 	cp = cpu_list;
9919 
9920 	do {
9921 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9922 			continue;
9923 
9924 		buf = &bufs[cp->cpu_id];
9925 
9926 		/*
9927 		 * If there is already a buffer allocated for this CPU, it
9928 		 * is only possible that this is a DR event.  In this case,
9929 		 * the buffer size must match our specified size.
9930 		 */
9931 		if (buf->dtb_tomax != NULL) {
9932 			ASSERT(buf->dtb_size == size);
9933 			continue;
9934 		}
9935 
9936 		ASSERT(buf->dtb_xamot == NULL);
9937 
9938 		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9939 			goto err;
9940 
9941 		buf->dtb_size = size;
9942 		buf->dtb_flags = flags;
9943 		buf->dtb_offset = 0;
9944 		buf->dtb_drops = 0;
9945 
9946 		if (flags & DTRACEBUF_NOSWITCH)
9947 			continue;
9948 
9949 		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9950 			goto err;
9951 	} while ((cp = cp->cpu_next) != cpu_list);
9952 
9953 	return (0);
9954 
9955 err:
9956 	cp = cpu_list;
9957 
9958 	do {
9959 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9960 			continue;
9961 
9962 		buf = &bufs[cp->cpu_id];
9963 
9964 		if (buf->dtb_xamot != NULL) {
9965 			ASSERT(buf->dtb_tomax != NULL);
9966 			ASSERT(buf->dtb_size == size);
9967 			kmem_free(buf->dtb_xamot, size);
9968 		}
9969 
9970 		if (buf->dtb_tomax != NULL) {
9971 			ASSERT(buf->dtb_size == size);
9972 			kmem_free(buf->dtb_tomax, size);
9973 		}
9974 
9975 		buf->dtb_tomax = NULL;
9976 		buf->dtb_xamot = NULL;
9977 		buf->dtb_size = 0;
9978 	} while ((cp = cp->cpu_next) != cpu_list);
9979 
9980 	return (ENOMEM);
9981 }
9982 
9983 /*
9984  * Note:  called from probe context.  This function just increments the drop
9985  * count on a buffer.  It has been made a function to allow for the
9986  * possibility of understanding the source of mysterious drop counts.  (A
9987  * problem for which one may be particularly disappointed that DTrace cannot
9988  * be used to understand DTrace.)
9989  */
9990 static void
9991 dtrace_buffer_drop(dtrace_buffer_t *buf)
9992 {
9993 	buf->dtb_drops++;
9994 }
9995 
9996 /*
9997  * Note:  called from probe context.  This function is called to reserve space
9998  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
9999  * mstate.  Returns the new offset in the buffer, or a negative value if an
10000  * error has occurred.
10001  */
10002 static intptr_t
10003 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
10004     dtrace_state_t *state, dtrace_mstate_t *mstate)
10005 {
10006 	intptr_t offs = buf->dtb_offset, soffs;
10007 	intptr_t woffs;
10008 	caddr_t tomax;
10009 	size_t total;
10010 
10011 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
10012 		return (-1);
10013 
10014 	if ((tomax = buf->dtb_tomax) == NULL) {
10015 		dtrace_buffer_drop(buf);
10016 		return (-1);
10017 	}
10018 
10019 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
10020 		while (offs & (align - 1)) {
10021 			/*
10022 			 * Assert that our alignment is off by a number which
10023 			 * is itself sizeof (uint32_t) aligned.
10024 			 */
10025 			ASSERT(!((align - (offs & (align - 1))) &
10026 			    (sizeof (uint32_t) - 1)));
10027 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10028 			offs += sizeof (uint32_t);
10029 		}
10030 
10031 		if ((soffs = offs + needed) > buf->dtb_size) {
10032 			dtrace_buffer_drop(buf);
10033 			return (-1);
10034 		}
10035 
10036 		if (mstate == NULL)
10037 			return (offs);
10038 
10039 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
10040 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
10041 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10042 
10043 		return (offs);
10044 	}
10045 
10046 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10047 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
10048 		    (buf->dtb_flags & DTRACEBUF_FULL))
10049 			return (-1);
10050 		goto out;
10051 	}
10052 
10053 	total = needed + (offs & (align - 1));
10054 
10055 	/*
10056 	 * For a ring buffer, life is quite a bit more complicated.  Before
10057 	 * we can store any padding, we need to adjust our wrapping offset.
10058 	 * (If we've never before wrapped or we're not about to, no adjustment
10059 	 * is required.)
10060 	 */
10061 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
10062 	    offs + total > buf->dtb_size) {
10063 		woffs = buf->dtb_xamot_offset;
10064 
10065 		if (offs + total > buf->dtb_size) {
10066 			/*
10067 			 * We can't fit in the end of the buffer.  First, a
10068 			 * sanity check that we can fit in the buffer at all.
10069 			 */
10070 			if (total > buf->dtb_size) {
10071 				dtrace_buffer_drop(buf);
10072 				return (-1);
10073 			}
10074 
10075 			/*
10076 			 * We're going to be storing at the top of the buffer,
10077 			 * so now we need to deal with the wrapped offset.  We
10078 			 * only reset our wrapped offset to 0 if it is
10079 			 * currently greater than the current offset.  If it
10080 			 * is less than the current offset, it is because a
10081 			 * previous allocation induced a wrap -- but the
10082 			 * allocation didn't subsequently take the space due
10083 			 * to an error or false predicate evaluation.  In this
10084 			 * case, we'll just leave the wrapped offset alone: if
10085 			 * the wrapped offset hasn't been advanced far enough
10086 			 * for this allocation, it will be adjusted in the
10087 			 * lower loop.
10088 			 */
10089 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
10090 				if (woffs >= offs)
10091 					woffs = 0;
10092 			} else {
10093 				woffs = 0;
10094 			}
10095 
10096 			/*
10097 			 * Now we know that we're going to be storing to the
10098 			 * top of the buffer and that there is room for us
10099 			 * there.  We need to clear the buffer from the current
10100 			 * offset to the end (there may be old gunk there).
10101 			 */
10102 			while (offs < buf->dtb_size)
10103 				tomax[offs++] = 0;
10104 
10105 			/*
10106 			 * We need to set our offset to zero.  And because we
10107 			 * are wrapping, we need to set the bit indicating as
10108 			 * much.  We can also adjust our needed space back
10109 			 * down to the space required by the ECB -- we know
10110 			 * that the top of the buffer is aligned.
10111 			 */
10112 			offs = 0;
10113 			total = needed;
10114 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
10115 		} else {
10116 			/*
10117 			 * There is room for us in the buffer, so we simply
10118 			 * need to check the wrapped offset.
10119 			 */
10120 			if (woffs < offs) {
10121 				/*
10122 				 * The wrapped offset is less than the offset.
10123 				 * This can happen if we allocated buffer space
10124 				 * that induced a wrap, but then we didn't
10125 				 * subsequently take the space due to an error
10126 				 * or false predicate evaluation.  This is
10127 				 * okay; we know that _this_ allocation isn't
10128 				 * going to induce a wrap.  We still can't
10129 				 * reset the wrapped offset to be zero,
10130 				 * however: the space may have been trashed in
10131 				 * the previous failed probe attempt.  But at
10132 				 * least the wrapped offset doesn't need to
10133 				 * be adjusted at all...
10134 				 */
10135 				goto out;
10136 			}
10137 		}
10138 
10139 		while (offs + total > woffs) {
10140 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
10141 			size_t size;
10142 
10143 			if (epid == DTRACE_EPIDNONE) {
10144 				size = sizeof (uint32_t);
10145 			} else {
10146 				ASSERT(epid <= state->dts_necbs);
10147 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
10148 
10149 				size = state->dts_ecbs[epid - 1]->dte_size;
10150 			}
10151 
10152 			ASSERT(woffs + size <= buf->dtb_size);
10153 			ASSERT(size != 0);
10154 
10155 			if (woffs + size == buf->dtb_size) {
10156 				/*
10157 				 * We've reached the end of the buffer; we want
10158 				 * to set the wrapped offset to 0 and break
10159 				 * out.  However, if the offs is 0, then we're
10160 				 * in a strange edge-condition:  the amount of
10161 				 * space that we want to reserve plus the size
10162 				 * of the record that we're overwriting is
10163 				 * greater than the size of the buffer.  This
10164 				 * is problematic because if we reserve the
10165 				 * space but subsequently don't consume it (due
10166 				 * to a failed predicate or error) the wrapped
10167 				 * offset will be 0 -- yet the EPID at offset 0
10168 				 * will not be committed.  This situation is
10169 				 * relatively easy to deal with:  if we're in
10170 				 * this case, the buffer is indistinguishable
10171 				 * from one that hasn't wrapped; we need only
10172 				 * finish the job by clearing the wrapped bit,
10173 				 * explicitly setting the offset to be 0, and
10174 				 * zero'ing out the old data in the buffer.
10175 				 */
10176 				if (offs == 0) {
10177 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
10178 					buf->dtb_offset = 0;
10179 					woffs = total;
10180 
10181 					while (woffs < buf->dtb_size)
10182 						tomax[woffs++] = 0;
10183 				}
10184 
10185 				woffs = 0;
10186 				break;
10187 			}
10188 
10189 			woffs += size;
10190 		}
10191 
10192 		/*
10193 		 * We have a wrapped offset.  It may be that the wrapped offset
10194 		 * has become zero -- that's okay.
10195 		 */
10196 		buf->dtb_xamot_offset = woffs;
10197 	}
10198 
10199 out:
10200 	/*
10201 	 * Now we can plow the buffer with any necessary padding.
10202 	 */
10203 	while (offs & (align - 1)) {
10204 		/*
10205 		 * Assert that our alignment is off by a number which
10206 		 * is itself sizeof (uint32_t) aligned.
10207 		 */
10208 		ASSERT(!((align - (offs & (align - 1))) &
10209 		    (sizeof (uint32_t) - 1)));
10210 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10211 		offs += sizeof (uint32_t);
10212 	}
10213 
10214 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10215 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
10216 			buf->dtb_flags |= DTRACEBUF_FULL;
10217 			return (-1);
10218 		}
10219 	}
10220 
10221 	if (mstate == NULL)
10222 		return (offs);
10223 
10224 	/*
10225 	 * For ring buffers and fill buffers, the scratch space is always
10226 	 * the inactive buffer.
10227 	 */
10228 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
10229 	mstate->dtms_scratch_size = buf->dtb_size;
10230 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10231 
10232 	return (offs);
10233 }
10234 
10235 static void
10236 dtrace_buffer_polish(dtrace_buffer_t *buf)
10237 {
10238 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
10239 	ASSERT(MUTEX_HELD(&dtrace_lock));
10240 
10241 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
10242 		return;
10243 
10244 	/*
10245 	 * We need to polish the ring buffer.  There are three cases:
10246 	 *
10247 	 * - The first (and presumably most common) is that there is no gap
10248 	 *   between the buffer offset and the wrapped offset.  In this case,
10249 	 *   there is nothing in the buffer that isn't valid data; we can
10250 	 *   mark the buffer as polished and return.
10251 	 *
10252 	 * - The second (less common than the first but still more common
10253 	 *   than the third) is that there is a gap between the buffer offset
10254 	 *   and the wrapped offset, and the wrapped offset is larger than the
10255 	 *   buffer offset.  This can happen because of an alignment issue, or
10256 	 *   can happen because of a call to dtrace_buffer_reserve() that
10257 	 *   didn't subsequently consume the buffer space.  In this case,
10258 	 *   we need to zero the data from the buffer offset to the wrapped
10259 	 *   offset.
10260 	 *
10261 	 * - The third (and least common) is that there is a gap between the
10262 	 *   buffer offset and the wrapped offset, but the wrapped offset is
10263 	 *   _less_ than the buffer offset.  This can only happen because a
10264 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
10265 	 *   was not subsequently consumed.  In this case, we need to zero the
10266 	 *   space from the offset to the end of the buffer _and_ from the
10267 	 *   top of the buffer to the wrapped offset.
10268 	 */
10269 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
10270 		bzero(buf->dtb_tomax + buf->dtb_offset,
10271 		    buf->dtb_xamot_offset - buf->dtb_offset);
10272 	}
10273 
10274 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
10275 		bzero(buf->dtb_tomax + buf->dtb_offset,
10276 		    buf->dtb_size - buf->dtb_offset);
10277 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
10278 	}
10279 }
10280 
10281 static void
10282 dtrace_buffer_free(dtrace_buffer_t *bufs)
10283 {
10284 	int i;
10285 
10286 	for (i = 0; i < NCPU; i++) {
10287 		dtrace_buffer_t *buf = &bufs[i];
10288 
10289 		if (buf->dtb_tomax == NULL) {
10290 			ASSERT(buf->dtb_xamot == NULL);
10291 			ASSERT(buf->dtb_size == 0);
10292 			continue;
10293 		}
10294 
10295 		if (buf->dtb_xamot != NULL) {
10296 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10297 			kmem_free(buf->dtb_xamot, buf->dtb_size);
10298 		}
10299 
10300 		kmem_free(buf->dtb_tomax, buf->dtb_size);
10301 		buf->dtb_size = 0;
10302 		buf->dtb_tomax = NULL;
10303 		buf->dtb_xamot = NULL;
10304 	}
10305 }
10306 
10307 /*
10308  * DTrace Enabling Functions
10309  */
10310 static dtrace_enabling_t *
10311 dtrace_enabling_create(dtrace_vstate_t *vstate)
10312 {
10313 	dtrace_enabling_t *enab;
10314 
10315 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
10316 	enab->dten_vstate = vstate;
10317 
10318 	return (enab);
10319 }
10320 
10321 static void
10322 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
10323 {
10324 	dtrace_ecbdesc_t **ndesc;
10325 	size_t osize, nsize;
10326 
10327 	/*
10328 	 * We can't add to enablings after we've enabled them, or after we've
10329 	 * retained them.
10330 	 */
10331 	ASSERT(enab->dten_probegen == 0);
10332 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10333 
10334 	if (enab->dten_ndesc < enab->dten_maxdesc) {
10335 		enab->dten_desc[enab->dten_ndesc++] = ecb;
10336 		return;
10337 	}
10338 
10339 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10340 
10341 	if (enab->dten_maxdesc == 0) {
10342 		enab->dten_maxdesc = 1;
10343 	} else {
10344 		enab->dten_maxdesc <<= 1;
10345 	}
10346 
10347 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
10348 
10349 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10350 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
10351 	bcopy(enab->dten_desc, ndesc, osize);
10352 	kmem_free(enab->dten_desc, osize);
10353 
10354 	enab->dten_desc = ndesc;
10355 	enab->dten_desc[enab->dten_ndesc++] = ecb;
10356 }
10357 
10358 static void
10359 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
10360     dtrace_probedesc_t *pd)
10361 {
10362 	dtrace_ecbdesc_t *new;
10363 	dtrace_predicate_t *pred;
10364 	dtrace_actdesc_t *act;
10365 
10366 	/*
10367 	 * We're going to create a new ECB description that matches the
10368 	 * specified ECB in every way, but has the specified probe description.
10369 	 */
10370 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
10371 
10372 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
10373 		dtrace_predicate_hold(pred);
10374 
10375 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
10376 		dtrace_actdesc_hold(act);
10377 
10378 	new->dted_action = ecb->dted_action;
10379 	new->dted_pred = ecb->dted_pred;
10380 	new->dted_probe = *pd;
10381 	new->dted_uarg = ecb->dted_uarg;
10382 
10383 	dtrace_enabling_add(enab, new);
10384 }
10385 
10386 static void
10387 dtrace_enabling_dump(dtrace_enabling_t *enab)
10388 {
10389 	int i;
10390 
10391 	for (i = 0; i < enab->dten_ndesc; i++) {
10392 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
10393 
10394 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
10395 		    desc->dtpd_provider, desc->dtpd_mod,
10396 		    desc->dtpd_func, desc->dtpd_name);
10397 	}
10398 }
10399 
10400 static void
10401 dtrace_enabling_destroy(dtrace_enabling_t *enab)
10402 {
10403 	int i;
10404 	dtrace_ecbdesc_t *ep;
10405 	dtrace_vstate_t *vstate = enab->dten_vstate;
10406 
10407 	ASSERT(MUTEX_HELD(&dtrace_lock));
10408 
10409 	for (i = 0; i < enab->dten_ndesc; i++) {
10410 		dtrace_actdesc_t *act, *next;
10411 		dtrace_predicate_t *pred;
10412 
10413 		ep = enab->dten_desc[i];
10414 
10415 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
10416 			dtrace_predicate_release(pred, vstate);
10417 
10418 		for (act = ep->dted_action; act != NULL; act = next) {
10419 			next = act->dtad_next;
10420 			dtrace_actdesc_release(act, vstate);
10421 		}
10422 
10423 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
10424 	}
10425 
10426 	kmem_free(enab->dten_desc,
10427 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
10428 
10429 	/*
10430 	 * If this was a retained enabling, decrement the dts_nretained count
10431 	 * and take it off of the dtrace_retained list.
10432 	 */
10433 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
10434 	    dtrace_retained == enab) {
10435 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10436 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
10437 		enab->dten_vstate->dtvs_state->dts_nretained--;
10438 	}
10439 
10440 	if (enab->dten_prev == NULL) {
10441 		if (dtrace_retained == enab) {
10442 			dtrace_retained = enab->dten_next;
10443 
10444 			if (dtrace_retained != NULL)
10445 				dtrace_retained->dten_prev = NULL;
10446 		}
10447 	} else {
10448 		ASSERT(enab != dtrace_retained);
10449 		ASSERT(dtrace_retained != NULL);
10450 		enab->dten_prev->dten_next = enab->dten_next;
10451 	}
10452 
10453 	if (enab->dten_next != NULL) {
10454 		ASSERT(dtrace_retained != NULL);
10455 		enab->dten_next->dten_prev = enab->dten_prev;
10456 	}
10457 
10458 	kmem_free(enab, sizeof (dtrace_enabling_t));
10459 }
10460 
10461 static int
10462 dtrace_enabling_retain(dtrace_enabling_t *enab)
10463 {
10464 	dtrace_state_t *state;
10465 
10466 	ASSERT(MUTEX_HELD(&dtrace_lock));
10467 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10468 	ASSERT(enab->dten_vstate != NULL);
10469 
10470 	state = enab->dten_vstate->dtvs_state;
10471 	ASSERT(state != NULL);
10472 
10473 	/*
10474 	 * We only allow each state to retain dtrace_retain_max enablings.
10475 	 */
10476 	if (state->dts_nretained >= dtrace_retain_max)
10477 		return (ENOSPC);
10478 
10479 	state->dts_nretained++;
10480 
10481 	if (dtrace_retained == NULL) {
10482 		dtrace_retained = enab;
10483 		return (0);
10484 	}
10485 
10486 	enab->dten_next = dtrace_retained;
10487 	dtrace_retained->dten_prev = enab;
10488 	dtrace_retained = enab;
10489 
10490 	return (0);
10491 }
10492 
10493 static int
10494 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
10495     dtrace_probedesc_t *create)
10496 {
10497 	dtrace_enabling_t *new, *enab;
10498 	int found = 0, err = ENOENT;
10499 
10500 	ASSERT(MUTEX_HELD(&dtrace_lock));
10501 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
10502 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
10503 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
10504 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
10505 
10506 	new = dtrace_enabling_create(&state->dts_vstate);
10507 
10508 	/*
10509 	 * Iterate over all retained enablings, looking for enablings that
10510 	 * match the specified state.
10511 	 */
10512 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10513 		int i;
10514 
10515 		/*
10516 		 * dtvs_state can only be NULL for helper enablings -- and
10517 		 * helper enablings can't be retained.
10518 		 */
10519 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10520 
10521 		if (enab->dten_vstate->dtvs_state != state)
10522 			continue;
10523 
10524 		/*
10525 		 * Now iterate over each probe description; we're looking for
10526 		 * an exact match to the specified probe description.
10527 		 */
10528 		for (i = 0; i < enab->dten_ndesc; i++) {
10529 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
10530 			dtrace_probedesc_t *pd = &ep->dted_probe;
10531 
10532 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
10533 				continue;
10534 
10535 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
10536 				continue;
10537 
10538 			if (strcmp(pd->dtpd_func, match->dtpd_func))
10539 				continue;
10540 
10541 			if (strcmp(pd->dtpd_name, match->dtpd_name))
10542 				continue;
10543 
10544 			/*
10545 			 * We have a winning probe!  Add it to our growing
10546 			 * enabling.
10547 			 */
10548 			found = 1;
10549 			dtrace_enabling_addlike(new, ep, create);
10550 		}
10551 	}
10552 
10553 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
10554 		dtrace_enabling_destroy(new);
10555 		return (err);
10556 	}
10557 
10558 	return (0);
10559 }
10560 
10561 static void
10562 dtrace_enabling_retract(dtrace_state_t *state)
10563 {
10564 	dtrace_enabling_t *enab, *next;
10565 
10566 	ASSERT(MUTEX_HELD(&dtrace_lock));
10567 
10568 	/*
10569 	 * Iterate over all retained enablings, destroy the enablings retained
10570 	 * for the specified state.
10571 	 */
10572 	for (enab = dtrace_retained; enab != NULL; enab = next) {
10573 		next = enab->dten_next;
10574 
10575 		/*
10576 		 * dtvs_state can only be NULL for helper enablings -- and
10577 		 * helper enablings can't be retained.
10578 		 */
10579 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10580 
10581 		if (enab->dten_vstate->dtvs_state == state) {
10582 			ASSERT(state->dts_nretained > 0);
10583 			dtrace_enabling_destroy(enab);
10584 		}
10585 	}
10586 
10587 	ASSERT(state->dts_nretained == 0);
10588 }
10589 
10590 static int
10591 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
10592 {
10593 	int i = 0;
10594 	int matched = 0;
10595 
10596 	ASSERT(MUTEX_HELD(&cpu_lock));
10597 	ASSERT(MUTEX_HELD(&dtrace_lock));
10598 
10599 	for (i = 0; i < enab->dten_ndesc; i++) {
10600 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
10601 
10602 		enab->dten_current = ep;
10603 		enab->dten_error = 0;
10604 
10605 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
10606 
10607 		if (enab->dten_error != 0) {
10608 			/*
10609 			 * If we get an error half-way through enabling the
10610 			 * probes, we kick out -- perhaps with some number of
10611 			 * them enabled.  Leaving enabled probes enabled may
10612 			 * be slightly confusing for user-level, but we expect
10613 			 * that no one will attempt to actually drive on in
10614 			 * the face of such errors.  If this is an anonymous
10615 			 * enabling (indicated with a NULL nmatched pointer),
10616 			 * we cmn_err() a message.  We aren't expecting to
10617 			 * get such an error -- such as it can exist at all,
10618 			 * it would be a result of corrupted DOF in the driver
10619 			 * properties.
10620 			 */
10621 			if (nmatched == NULL) {
10622 				cmn_err(CE_WARN, "dtrace_enabling_match() "
10623 				    "error on %p: %d", (void *)ep,
10624 				    enab->dten_error);
10625 			}
10626 
10627 			return (enab->dten_error);
10628 		}
10629 	}
10630 
10631 	enab->dten_probegen = dtrace_probegen;
10632 	if (nmatched != NULL)
10633 		*nmatched = matched;
10634 
10635 	return (0);
10636 }
10637 
10638 static void
10639 dtrace_enabling_matchall(void)
10640 {
10641 	dtrace_enabling_t *enab;
10642 
10643 	mutex_enter(&cpu_lock);
10644 	mutex_enter(&dtrace_lock);
10645 
10646 	/*
10647 	 * Because we can be called after dtrace_detach() has been called, we
10648 	 * cannot assert that there are retained enablings.  We can safely
10649 	 * load from dtrace_retained, however:  the taskq_destroy() at the
10650 	 * end of dtrace_detach() will block pending our completion.
10651 	 */
10652 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next)
10653 		(void) dtrace_enabling_match(enab, NULL);
10654 
10655 	mutex_exit(&dtrace_lock);
10656 	mutex_exit(&cpu_lock);
10657 }
10658 
10659 static int
10660 dtrace_enabling_matchstate(dtrace_state_t *state, int *nmatched)
10661 {
10662 	dtrace_enabling_t *enab;
10663 	int matched, total = 0, err;
10664 
10665 	ASSERT(MUTEX_HELD(&cpu_lock));
10666 	ASSERT(MUTEX_HELD(&dtrace_lock));
10667 
10668 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10669 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10670 
10671 		if (enab->dten_vstate->dtvs_state != state)
10672 			continue;
10673 
10674 		if ((err = dtrace_enabling_match(enab, &matched)) != 0)
10675 			return (err);
10676 
10677 		total += matched;
10678 	}
10679 
10680 	if (nmatched != NULL)
10681 		*nmatched = total;
10682 
10683 	return (0);
10684 }
10685 
10686 /*
10687  * If an enabling is to be enabled without having matched probes (that is, if
10688  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
10689  * enabling must be _primed_ by creating an ECB for every ECB description.
10690  * This must be done to assure that we know the number of speculations, the
10691  * number of aggregations, the minimum buffer size needed, etc. before we
10692  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
10693  * enabling any probes, we create ECBs for every ECB decription, but with a
10694  * NULL probe -- which is exactly what this function does.
10695  */
10696 static void
10697 dtrace_enabling_prime(dtrace_state_t *state)
10698 {
10699 	dtrace_enabling_t *enab;
10700 	int i;
10701 
10702 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10703 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10704 
10705 		if (enab->dten_vstate->dtvs_state != state)
10706 			continue;
10707 
10708 		/*
10709 		 * We don't want to prime an enabling more than once, lest
10710 		 * we allow a malicious user to induce resource exhaustion.
10711 		 * (The ECBs that result from priming an enabling aren't
10712 		 * leaked -- but they also aren't deallocated until the
10713 		 * consumer state is destroyed.)
10714 		 */
10715 		if (enab->dten_primed)
10716 			continue;
10717 
10718 		for (i = 0; i < enab->dten_ndesc; i++) {
10719 			enab->dten_current = enab->dten_desc[i];
10720 			(void) dtrace_probe_enable(NULL, enab);
10721 		}
10722 
10723 		enab->dten_primed = 1;
10724 	}
10725 }
10726 
10727 /*
10728  * Called to indicate that probes should be provided due to retained
10729  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
10730  * must take an initial lap through the enabling calling the dtps_provide()
10731  * entry point explicitly to allow for autocreated probes.
10732  */
10733 static void
10734 dtrace_enabling_provide(dtrace_provider_t *prv)
10735 {
10736 	int i, all = 0;
10737 	dtrace_probedesc_t desc;
10738 
10739 	ASSERT(MUTEX_HELD(&dtrace_lock));
10740 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
10741 
10742 	if (prv == NULL) {
10743 		all = 1;
10744 		prv = dtrace_provider;
10745 	}
10746 
10747 	do {
10748 		dtrace_enabling_t *enab = dtrace_retained;
10749 		void *parg = prv->dtpv_arg;
10750 
10751 		for (; enab != NULL; enab = enab->dten_next) {
10752 			for (i = 0; i < enab->dten_ndesc; i++) {
10753 				desc = enab->dten_desc[i]->dted_probe;
10754 				mutex_exit(&dtrace_lock);
10755 				prv->dtpv_pops.dtps_provide(parg, &desc);
10756 				mutex_enter(&dtrace_lock);
10757 			}
10758 		}
10759 	} while (all && (prv = prv->dtpv_next) != NULL);
10760 
10761 	mutex_exit(&dtrace_lock);
10762 	dtrace_probe_provide(NULL, all ? NULL : prv);
10763 	mutex_enter(&dtrace_lock);
10764 }
10765 
10766 /*
10767  * DTrace DOF Functions
10768  */
10769 /*ARGSUSED*/
10770 static void
10771 dtrace_dof_error(dof_hdr_t *dof, const char *str)
10772 {
10773 	if (dtrace_err_verbose)
10774 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
10775 
10776 #ifdef DTRACE_ERRDEBUG
10777 	dtrace_errdebug(str);
10778 #endif
10779 }
10780 
10781 /*
10782  * Create DOF out of a currently enabled state.  Right now, we only create
10783  * DOF containing the run-time options -- but this could be expanded to create
10784  * complete DOF representing the enabled state.
10785  */
10786 static dof_hdr_t *
10787 dtrace_dof_create(dtrace_state_t *state)
10788 {
10789 	dof_hdr_t *dof;
10790 	dof_sec_t *sec;
10791 	dof_optdesc_t *opt;
10792 	int i, len = sizeof (dof_hdr_t) +
10793 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
10794 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10795 
10796 	ASSERT(MUTEX_HELD(&dtrace_lock));
10797 
10798 	dof = kmem_zalloc(len, KM_SLEEP);
10799 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
10800 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
10801 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
10802 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
10803 
10804 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
10805 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
10806 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
10807 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
10808 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
10809 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
10810 
10811 	dof->dofh_flags = 0;
10812 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
10813 	dof->dofh_secsize = sizeof (dof_sec_t);
10814 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
10815 	dof->dofh_secoff = sizeof (dof_hdr_t);
10816 	dof->dofh_loadsz = len;
10817 	dof->dofh_filesz = len;
10818 	dof->dofh_pad = 0;
10819 
10820 	/*
10821 	 * Fill in the option section header...
10822 	 */
10823 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
10824 	sec->dofs_type = DOF_SECT_OPTDESC;
10825 	sec->dofs_align = sizeof (uint64_t);
10826 	sec->dofs_flags = DOF_SECF_LOAD;
10827 	sec->dofs_entsize = sizeof (dof_optdesc_t);
10828 
10829 	opt = (dof_optdesc_t *)((uintptr_t)sec +
10830 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
10831 
10832 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
10833 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10834 
10835 	for (i = 0; i < DTRACEOPT_MAX; i++) {
10836 		opt[i].dofo_option = i;
10837 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
10838 		opt[i].dofo_value = state->dts_options[i];
10839 	}
10840 
10841 	return (dof);
10842 }
10843 
10844 static dof_hdr_t *
10845 dtrace_dof_copyin(uintptr_t uarg, int *errp)
10846 {
10847 	dof_hdr_t hdr, *dof;
10848 
10849 	ASSERT(!MUTEX_HELD(&dtrace_lock));
10850 
10851 	/*
10852 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
10853 	 */
10854 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
10855 		dtrace_dof_error(NULL, "failed to copyin DOF header");
10856 		*errp = EFAULT;
10857 		return (NULL);
10858 	}
10859 
10860 	/*
10861 	 * Now we'll allocate the entire DOF and copy it in -- provided
10862 	 * that the length isn't outrageous.
10863 	 */
10864 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
10865 		dtrace_dof_error(&hdr, "load size exceeds maximum");
10866 		*errp = E2BIG;
10867 		return (NULL);
10868 	}
10869 
10870 	if (hdr.dofh_loadsz < sizeof (hdr)) {
10871 		dtrace_dof_error(&hdr, "invalid load size");
10872 		*errp = EINVAL;
10873 		return (NULL);
10874 	}
10875 
10876 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
10877 
10878 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
10879 		kmem_free(dof, hdr.dofh_loadsz);
10880 		*errp = EFAULT;
10881 		return (NULL);
10882 	}
10883 
10884 	return (dof);
10885 }
10886 
10887 static dof_hdr_t *
10888 dtrace_dof_property(const char *name)
10889 {
10890 	uchar_t *buf;
10891 	uint64_t loadsz;
10892 	unsigned int len, i;
10893 	dof_hdr_t *dof;
10894 
10895 	/*
10896 	 * Unfortunately, array of values in .conf files are always (and
10897 	 * only) interpreted to be integer arrays.  We must read our DOF
10898 	 * as an integer array, and then squeeze it into a byte array.
10899 	 */
10900 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
10901 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
10902 		return (NULL);
10903 
10904 	for (i = 0; i < len; i++)
10905 		buf[i] = (uchar_t)(((int *)buf)[i]);
10906 
10907 	if (len < sizeof (dof_hdr_t)) {
10908 		ddi_prop_free(buf);
10909 		dtrace_dof_error(NULL, "truncated header");
10910 		return (NULL);
10911 	}
10912 
10913 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
10914 		ddi_prop_free(buf);
10915 		dtrace_dof_error(NULL, "truncated DOF");
10916 		return (NULL);
10917 	}
10918 
10919 	if (loadsz >= dtrace_dof_maxsize) {
10920 		ddi_prop_free(buf);
10921 		dtrace_dof_error(NULL, "oversized DOF");
10922 		return (NULL);
10923 	}
10924 
10925 	dof = kmem_alloc(loadsz, KM_SLEEP);
10926 	bcopy(buf, dof, loadsz);
10927 	ddi_prop_free(buf);
10928 
10929 	return (dof);
10930 }
10931 
10932 static void
10933 dtrace_dof_destroy(dof_hdr_t *dof)
10934 {
10935 	kmem_free(dof, dof->dofh_loadsz);
10936 }
10937 
10938 /*
10939  * Return the dof_sec_t pointer corresponding to a given section index.  If the
10940  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
10941  * a type other than DOF_SECT_NONE is specified, the header is checked against
10942  * this type and NULL is returned if the types do not match.
10943  */
10944 static dof_sec_t *
10945 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
10946 {
10947 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
10948 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
10949 
10950 	if (i >= dof->dofh_secnum) {
10951 		dtrace_dof_error(dof, "referenced section index is invalid");
10952 		return (NULL);
10953 	}
10954 
10955 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
10956 		dtrace_dof_error(dof, "referenced section is not loadable");
10957 		return (NULL);
10958 	}
10959 
10960 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
10961 		dtrace_dof_error(dof, "referenced section is the wrong type");
10962 		return (NULL);
10963 	}
10964 
10965 	return (sec);
10966 }
10967 
10968 static dtrace_probedesc_t *
10969 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
10970 {
10971 	dof_probedesc_t *probe;
10972 	dof_sec_t *strtab;
10973 	uintptr_t daddr = (uintptr_t)dof;
10974 	uintptr_t str;
10975 	size_t size;
10976 
10977 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
10978 		dtrace_dof_error(dof, "invalid probe section");
10979 		return (NULL);
10980 	}
10981 
10982 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
10983 		dtrace_dof_error(dof, "bad alignment in probe description");
10984 		return (NULL);
10985 	}
10986 
10987 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
10988 		dtrace_dof_error(dof, "truncated probe description");
10989 		return (NULL);
10990 	}
10991 
10992 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
10993 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
10994 
10995 	if (strtab == NULL)
10996 		return (NULL);
10997 
10998 	str = daddr + strtab->dofs_offset;
10999 	size = strtab->dofs_size;
11000 
11001 	if (probe->dofp_provider >= strtab->dofs_size) {
11002 		dtrace_dof_error(dof, "corrupt probe provider");
11003 		return (NULL);
11004 	}
11005 
11006 	(void) strncpy(desc->dtpd_provider,
11007 	    (char *)(str + probe->dofp_provider),
11008 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
11009 
11010 	if (probe->dofp_mod >= strtab->dofs_size) {
11011 		dtrace_dof_error(dof, "corrupt probe module");
11012 		return (NULL);
11013 	}
11014 
11015 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
11016 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
11017 
11018 	if (probe->dofp_func >= strtab->dofs_size) {
11019 		dtrace_dof_error(dof, "corrupt probe function");
11020 		return (NULL);
11021 	}
11022 
11023 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
11024 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
11025 
11026 	if (probe->dofp_name >= strtab->dofs_size) {
11027 		dtrace_dof_error(dof, "corrupt probe name");
11028 		return (NULL);
11029 	}
11030 
11031 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
11032 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
11033 
11034 	return (desc);
11035 }
11036 
11037 static dtrace_difo_t *
11038 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11039     cred_t *cr)
11040 {
11041 	dtrace_difo_t *dp;
11042 	size_t ttl = 0;
11043 	dof_difohdr_t *dofd;
11044 	uintptr_t daddr = (uintptr_t)dof;
11045 	size_t max = dtrace_difo_maxsize;
11046 	int i, l, n;
11047 
11048 	static const struct {
11049 		int section;
11050 		int bufoffs;
11051 		int lenoffs;
11052 		int entsize;
11053 		int align;
11054 		const char *msg;
11055 	} difo[] = {
11056 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
11057 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
11058 		sizeof (dif_instr_t), "multiple DIF sections" },
11059 
11060 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
11061 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
11062 		sizeof (uint64_t), "multiple integer tables" },
11063 
11064 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
11065 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
11066 		sizeof (char), "multiple string tables" },
11067 
11068 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
11069 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
11070 		sizeof (uint_t), "multiple variable tables" },
11071 
11072 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
11073 	};
11074 
11075 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
11076 		dtrace_dof_error(dof, "invalid DIFO header section");
11077 		return (NULL);
11078 	}
11079 
11080 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
11081 		dtrace_dof_error(dof, "bad alignment in DIFO header");
11082 		return (NULL);
11083 	}
11084 
11085 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
11086 	    sec->dofs_size % sizeof (dof_secidx_t)) {
11087 		dtrace_dof_error(dof, "bad size in DIFO header");
11088 		return (NULL);
11089 	}
11090 
11091 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11092 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
11093 
11094 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
11095 	dp->dtdo_rtype = dofd->dofd_rtype;
11096 
11097 	for (l = 0; l < n; l++) {
11098 		dof_sec_t *subsec;
11099 		void **bufp;
11100 		uint32_t *lenp;
11101 
11102 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
11103 		    dofd->dofd_links[l])) == NULL)
11104 			goto err; /* invalid section link */
11105 
11106 		if (ttl + subsec->dofs_size > max) {
11107 			dtrace_dof_error(dof, "exceeds maximum size");
11108 			goto err;
11109 		}
11110 
11111 		ttl += subsec->dofs_size;
11112 
11113 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
11114 			if (subsec->dofs_type != difo[i].section)
11115 				continue;
11116 
11117 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
11118 				dtrace_dof_error(dof, "section not loaded");
11119 				goto err;
11120 			}
11121 
11122 			if (subsec->dofs_align != difo[i].align) {
11123 				dtrace_dof_error(dof, "bad alignment");
11124 				goto err;
11125 			}
11126 
11127 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
11128 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
11129 
11130 			if (*bufp != NULL) {
11131 				dtrace_dof_error(dof, difo[i].msg);
11132 				goto err;
11133 			}
11134 
11135 			if (difo[i].entsize != subsec->dofs_entsize) {
11136 				dtrace_dof_error(dof, "entry size mismatch");
11137 				goto err;
11138 			}
11139 
11140 			if (subsec->dofs_entsize != 0 &&
11141 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
11142 				dtrace_dof_error(dof, "corrupt entry size");
11143 				goto err;
11144 			}
11145 
11146 			*lenp = subsec->dofs_size;
11147 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
11148 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
11149 			    *bufp, subsec->dofs_size);
11150 
11151 			if (subsec->dofs_entsize != 0)
11152 				*lenp /= subsec->dofs_entsize;
11153 
11154 			break;
11155 		}
11156 
11157 		/*
11158 		 * If we encounter a loadable DIFO sub-section that is not
11159 		 * known to us, assume this is a broken program and fail.
11160 		 */
11161 		if (difo[i].section == DOF_SECT_NONE &&
11162 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
11163 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
11164 			goto err;
11165 		}
11166 	}
11167 
11168 	if (dp->dtdo_buf == NULL) {
11169 		/*
11170 		 * We can't have a DIF object without DIF text.
11171 		 */
11172 		dtrace_dof_error(dof, "missing DIF text");
11173 		goto err;
11174 	}
11175 
11176 	/*
11177 	 * Before we validate the DIF object, run through the variable table
11178 	 * looking for the strings -- if any of their size are under, we'll set
11179 	 * their size to be the system-wide default string size.  Note that
11180 	 * this should _not_ happen if the "strsize" option has been set --
11181 	 * in this case, the compiler should have set the size to reflect the
11182 	 * setting of the option.
11183 	 */
11184 	for (i = 0; i < dp->dtdo_varlen; i++) {
11185 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
11186 		dtrace_diftype_t *t = &v->dtdv_type;
11187 
11188 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
11189 			continue;
11190 
11191 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
11192 			t->dtdt_size = dtrace_strsize_default;
11193 	}
11194 
11195 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
11196 		goto err;
11197 
11198 	dtrace_difo_init(dp, vstate);
11199 	return (dp);
11200 
11201 err:
11202 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
11203 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
11204 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
11205 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
11206 
11207 	kmem_free(dp, sizeof (dtrace_difo_t));
11208 	return (NULL);
11209 }
11210 
11211 static dtrace_predicate_t *
11212 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11213     cred_t *cr)
11214 {
11215 	dtrace_difo_t *dp;
11216 
11217 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
11218 		return (NULL);
11219 
11220 	return (dtrace_predicate_create(dp));
11221 }
11222 
11223 static dtrace_actdesc_t *
11224 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11225     cred_t *cr)
11226 {
11227 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
11228 	dof_actdesc_t *desc;
11229 	dof_sec_t *difosec;
11230 	size_t offs;
11231 	uintptr_t daddr = (uintptr_t)dof;
11232 	uint64_t arg;
11233 	dtrace_actkind_t kind;
11234 
11235 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
11236 		dtrace_dof_error(dof, "invalid action section");
11237 		return (NULL);
11238 	}
11239 
11240 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
11241 		dtrace_dof_error(dof, "truncated action description");
11242 		return (NULL);
11243 	}
11244 
11245 	if (sec->dofs_align != sizeof (uint64_t)) {
11246 		dtrace_dof_error(dof, "bad alignment in action description");
11247 		return (NULL);
11248 	}
11249 
11250 	if (sec->dofs_size < sec->dofs_entsize) {
11251 		dtrace_dof_error(dof, "section entry size exceeds total size");
11252 		return (NULL);
11253 	}
11254 
11255 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
11256 		dtrace_dof_error(dof, "bad entry size in action description");
11257 		return (NULL);
11258 	}
11259 
11260 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
11261 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
11262 		return (NULL);
11263 	}
11264 
11265 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
11266 		desc = (dof_actdesc_t *)(daddr +
11267 		    (uintptr_t)sec->dofs_offset + offs);
11268 		kind = (dtrace_actkind_t)desc->dofa_kind;
11269 
11270 		if (DTRACEACT_ISPRINTFLIKE(kind) &&
11271 		    (kind != DTRACEACT_PRINTA ||
11272 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
11273 			dof_sec_t *strtab;
11274 			char *str, *fmt;
11275 			uint64_t i;
11276 
11277 			/*
11278 			 * printf()-like actions must have a format string.
11279 			 */
11280 			if ((strtab = dtrace_dof_sect(dof,
11281 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
11282 				goto err;
11283 
11284 			str = (char *)((uintptr_t)dof +
11285 			    (uintptr_t)strtab->dofs_offset);
11286 
11287 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
11288 				if (str[i] == '\0')
11289 					break;
11290 			}
11291 
11292 			if (i >= strtab->dofs_size) {
11293 				dtrace_dof_error(dof, "bogus format string");
11294 				goto err;
11295 			}
11296 
11297 			if (i == desc->dofa_arg) {
11298 				dtrace_dof_error(dof, "empty format string");
11299 				goto err;
11300 			}
11301 
11302 			i -= desc->dofa_arg;
11303 			fmt = kmem_alloc(i + 1, KM_SLEEP);
11304 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
11305 			arg = (uint64_t)(uintptr_t)fmt;
11306 		} else {
11307 			if (kind == DTRACEACT_PRINTA) {
11308 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
11309 				arg = 0;
11310 			} else {
11311 				arg = desc->dofa_arg;
11312 			}
11313 		}
11314 
11315 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
11316 		    desc->dofa_uarg, arg);
11317 
11318 		if (last != NULL) {
11319 			last->dtad_next = act;
11320 		} else {
11321 			first = act;
11322 		}
11323 
11324 		last = act;
11325 
11326 		if (desc->dofa_difo == DOF_SECIDX_NONE)
11327 			continue;
11328 
11329 		if ((difosec = dtrace_dof_sect(dof,
11330 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
11331 			goto err;
11332 
11333 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
11334 
11335 		if (act->dtad_difo == NULL)
11336 			goto err;
11337 	}
11338 
11339 	ASSERT(first != NULL);
11340 	return (first);
11341 
11342 err:
11343 	for (act = first; act != NULL; act = next) {
11344 		next = act->dtad_next;
11345 		dtrace_actdesc_release(act, vstate);
11346 	}
11347 
11348 	return (NULL);
11349 }
11350 
11351 static dtrace_ecbdesc_t *
11352 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11353     cred_t *cr)
11354 {
11355 	dtrace_ecbdesc_t *ep;
11356 	dof_ecbdesc_t *ecb;
11357 	dtrace_probedesc_t *desc;
11358 	dtrace_predicate_t *pred = NULL;
11359 
11360 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
11361 		dtrace_dof_error(dof, "truncated ECB description");
11362 		return (NULL);
11363 	}
11364 
11365 	if (sec->dofs_align != sizeof (uint64_t)) {
11366 		dtrace_dof_error(dof, "bad alignment in ECB description");
11367 		return (NULL);
11368 	}
11369 
11370 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
11371 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
11372 
11373 	if (sec == NULL)
11374 		return (NULL);
11375 
11376 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11377 	ep->dted_uarg = ecb->dofe_uarg;
11378 	desc = &ep->dted_probe;
11379 
11380 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
11381 		goto err;
11382 
11383 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
11384 		if ((sec = dtrace_dof_sect(dof,
11385 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
11386 			goto err;
11387 
11388 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
11389 			goto err;
11390 
11391 		ep->dted_pred.dtpdd_predicate = pred;
11392 	}
11393 
11394 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
11395 		if ((sec = dtrace_dof_sect(dof,
11396 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
11397 			goto err;
11398 
11399 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
11400 
11401 		if (ep->dted_action == NULL)
11402 			goto err;
11403 	}
11404 
11405 	return (ep);
11406 
11407 err:
11408 	if (pred != NULL)
11409 		dtrace_predicate_release(pred, vstate);
11410 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11411 	return (NULL);
11412 }
11413 
11414 /*
11415  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
11416  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
11417  * site of any user SETX relocations to account for load object base address.
11418  * In the future, if we need other relocations, this function can be extended.
11419  */
11420 static int
11421 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
11422 {
11423 	uintptr_t daddr = (uintptr_t)dof;
11424 	dof_relohdr_t *dofr =
11425 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11426 	dof_sec_t *ss, *rs, *ts;
11427 	dof_relodesc_t *r;
11428 	uint_t i, n;
11429 
11430 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
11431 	    sec->dofs_align != sizeof (dof_secidx_t)) {
11432 		dtrace_dof_error(dof, "invalid relocation header");
11433 		return (-1);
11434 	}
11435 
11436 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
11437 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
11438 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
11439 
11440 	if (ss == NULL || rs == NULL || ts == NULL)
11441 		return (-1); /* dtrace_dof_error() has been called already */
11442 
11443 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
11444 	    rs->dofs_align != sizeof (uint64_t)) {
11445 		dtrace_dof_error(dof, "invalid relocation section");
11446 		return (-1);
11447 	}
11448 
11449 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
11450 	n = rs->dofs_size / rs->dofs_entsize;
11451 
11452 	for (i = 0; i < n; i++) {
11453 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
11454 
11455 		switch (r->dofr_type) {
11456 		case DOF_RELO_NONE:
11457 			break;
11458 		case DOF_RELO_SETX:
11459 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
11460 			    sizeof (uint64_t) > ts->dofs_size) {
11461 				dtrace_dof_error(dof, "bad relocation offset");
11462 				return (-1);
11463 			}
11464 
11465 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
11466 				dtrace_dof_error(dof, "misaligned setx relo");
11467 				return (-1);
11468 			}
11469 
11470 			*(uint64_t *)taddr += ubase;
11471 			break;
11472 		default:
11473 			dtrace_dof_error(dof, "invalid relocation type");
11474 			return (-1);
11475 		}
11476 
11477 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
11478 	}
11479 
11480 	return (0);
11481 }
11482 
11483 /*
11484  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
11485  * header:  it should be at the front of a memory region that is at least
11486  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
11487  * size.  It need not be validated in any other way.
11488  */
11489 static int
11490 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
11491     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
11492 {
11493 	uint64_t len = dof->dofh_loadsz, seclen;
11494 	uintptr_t daddr = (uintptr_t)dof;
11495 	dtrace_ecbdesc_t *ep;
11496 	dtrace_enabling_t *enab;
11497 	uint_t i;
11498 
11499 	ASSERT(MUTEX_HELD(&dtrace_lock));
11500 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
11501 
11502 	/*
11503 	 * Check the DOF header identification bytes.  In addition to checking
11504 	 * valid settings, we also verify that unused bits/bytes are zeroed so
11505 	 * we can use them later without fear of regressing existing binaries.
11506 	 */
11507 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
11508 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
11509 		dtrace_dof_error(dof, "DOF magic string mismatch");
11510 		return (-1);
11511 	}
11512 
11513 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
11514 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
11515 		dtrace_dof_error(dof, "DOF has invalid data model");
11516 		return (-1);
11517 	}
11518 
11519 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
11520 		dtrace_dof_error(dof, "DOF encoding mismatch");
11521 		return (-1);
11522 	}
11523 
11524 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
11525 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
11526 		dtrace_dof_error(dof, "DOF version mismatch");
11527 		return (-1);
11528 	}
11529 
11530 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
11531 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
11532 		return (-1);
11533 	}
11534 
11535 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
11536 		dtrace_dof_error(dof, "DOF uses too many integer registers");
11537 		return (-1);
11538 	}
11539 
11540 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
11541 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
11542 		return (-1);
11543 	}
11544 
11545 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
11546 		if (dof->dofh_ident[i] != 0) {
11547 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
11548 			return (-1);
11549 		}
11550 	}
11551 
11552 	if (dof->dofh_flags & ~DOF_FL_VALID) {
11553 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
11554 		return (-1);
11555 	}
11556 
11557 	if (dof->dofh_secsize == 0) {
11558 		dtrace_dof_error(dof, "zero section header size");
11559 		return (-1);
11560 	}
11561 
11562 	/*
11563 	 * Check that the section headers don't exceed the amount of DOF
11564 	 * data.  Note that we cast the section size and number of sections
11565 	 * to uint64_t's to prevent possible overflow in the multiplication.
11566 	 */
11567 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
11568 
11569 	if (dof->dofh_secoff > len || seclen > len ||
11570 	    dof->dofh_secoff + seclen > len) {
11571 		dtrace_dof_error(dof, "truncated section headers");
11572 		return (-1);
11573 	}
11574 
11575 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
11576 		dtrace_dof_error(dof, "misaligned section headers");
11577 		return (-1);
11578 	}
11579 
11580 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
11581 		dtrace_dof_error(dof, "misaligned section size");
11582 		return (-1);
11583 	}
11584 
11585 	/*
11586 	 * Take an initial pass through the section headers to be sure that
11587 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
11588 	 * set, do not permit sections relating to providers, probes, or args.
11589 	 */
11590 	for (i = 0; i < dof->dofh_secnum; i++) {
11591 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11592 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11593 
11594 		if (noprobes) {
11595 			switch (sec->dofs_type) {
11596 			case DOF_SECT_PROVIDER:
11597 			case DOF_SECT_PROBES:
11598 			case DOF_SECT_PRARGS:
11599 			case DOF_SECT_PROFFS:
11600 				dtrace_dof_error(dof, "illegal sections "
11601 				    "for enabling");
11602 				return (-1);
11603 			}
11604 		}
11605 
11606 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
11607 			continue; /* just ignore non-loadable sections */
11608 
11609 		if (sec->dofs_align & (sec->dofs_align - 1)) {
11610 			dtrace_dof_error(dof, "bad section alignment");
11611 			return (-1);
11612 		}
11613 
11614 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
11615 			dtrace_dof_error(dof, "misaligned section");
11616 			return (-1);
11617 		}
11618 
11619 		if (sec->dofs_offset > len || sec->dofs_size > len ||
11620 		    sec->dofs_offset + sec->dofs_size > len) {
11621 			dtrace_dof_error(dof, "corrupt section header");
11622 			return (-1);
11623 		}
11624 
11625 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
11626 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
11627 			dtrace_dof_error(dof, "non-terminating string table");
11628 			return (-1);
11629 		}
11630 	}
11631 
11632 	/*
11633 	 * Take a second pass through the sections and locate and perform any
11634 	 * relocations that are present.  We do this after the first pass to
11635 	 * be sure that all sections have had their headers validated.
11636 	 */
11637 	for (i = 0; i < dof->dofh_secnum; i++) {
11638 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11639 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11640 
11641 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
11642 			continue; /* skip sections that are not loadable */
11643 
11644 		switch (sec->dofs_type) {
11645 		case DOF_SECT_URELHDR:
11646 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
11647 				return (-1);
11648 			break;
11649 		}
11650 	}
11651 
11652 	if ((enab = *enabp) == NULL)
11653 		enab = *enabp = dtrace_enabling_create(vstate);
11654 
11655 	for (i = 0; i < dof->dofh_secnum; i++) {
11656 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11657 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11658 
11659 		if (sec->dofs_type != DOF_SECT_ECBDESC)
11660 			continue;
11661 
11662 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
11663 			dtrace_enabling_destroy(enab);
11664 			*enabp = NULL;
11665 			return (-1);
11666 		}
11667 
11668 		dtrace_enabling_add(enab, ep);
11669 	}
11670 
11671 	return (0);
11672 }
11673 
11674 /*
11675  * Process DOF for any options.  This routine assumes that the DOF has been
11676  * at least processed by dtrace_dof_slurp().
11677  */
11678 static int
11679 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
11680 {
11681 	int i, rval;
11682 	uint32_t entsize;
11683 	size_t offs;
11684 	dof_optdesc_t *desc;
11685 
11686 	for (i = 0; i < dof->dofh_secnum; i++) {
11687 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
11688 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11689 
11690 		if (sec->dofs_type != DOF_SECT_OPTDESC)
11691 			continue;
11692 
11693 		if (sec->dofs_align != sizeof (uint64_t)) {
11694 			dtrace_dof_error(dof, "bad alignment in "
11695 			    "option description");
11696 			return (EINVAL);
11697 		}
11698 
11699 		if ((entsize = sec->dofs_entsize) == 0) {
11700 			dtrace_dof_error(dof, "zeroed option entry size");
11701 			return (EINVAL);
11702 		}
11703 
11704 		if (entsize < sizeof (dof_optdesc_t)) {
11705 			dtrace_dof_error(dof, "bad option entry size");
11706 			return (EINVAL);
11707 		}
11708 
11709 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
11710 			desc = (dof_optdesc_t *)((uintptr_t)dof +
11711 			    (uintptr_t)sec->dofs_offset + offs);
11712 
11713 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
11714 				dtrace_dof_error(dof, "non-zero option string");
11715 				return (EINVAL);
11716 			}
11717 
11718 			if (desc->dofo_value == DTRACEOPT_UNSET) {
11719 				dtrace_dof_error(dof, "unset option");
11720 				return (EINVAL);
11721 			}
11722 
11723 			if ((rval = dtrace_state_option(state,
11724 			    desc->dofo_option, desc->dofo_value)) != 0) {
11725 				dtrace_dof_error(dof, "rejected option");
11726 				return (rval);
11727 			}
11728 		}
11729 	}
11730 
11731 	return (0);
11732 }
11733 
11734 /*
11735  * DTrace Consumer State Functions
11736  */
11737 int
11738 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
11739 {
11740 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
11741 	void *base;
11742 	uintptr_t limit;
11743 	dtrace_dynvar_t *dvar, *next, *start;
11744 	int i;
11745 
11746 	ASSERT(MUTEX_HELD(&dtrace_lock));
11747 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
11748 
11749 	bzero(dstate, sizeof (dtrace_dstate_t));
11750 
11751 	if ((dstate->dtds_chunksize = chunksize) == 0)
11752 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
11753 
11754 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
11755 		size = min;
11756 
11757 	if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11758 		return (ENOMEM);
11759 
11760 	dstate->dtds_size = size;
11761 	dstate->dtds_base = base;
11762 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
11763 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
11764 
11765 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
11766 
11767 	if (hashsize != 1 && (hashsize & 1))
11768 		hashsize--;
11769 
11770 	dstate->dtds_hashsize = hashsize;
11771 	dstate->dtds_hash = dstate->dtds_base;
11772 
11773 	/*
11774 	 * Set all of our hash buckets to point to the single sink, and (if
11775 	 * it hasn't already been set), set the sink's hash value to be the
11776 	 * sink sentinel value.  The sink is needed for dynamic variable
11777 	 * lookups to know that they have iterated over an entire, valid hash
11778 	 * chain.
11779 	 */
11780 	for (i = 0; i < hashsize; i++)
11781 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
11782 
11783 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
11784 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
11785 
11786 	/*
11787 	 * Determine number of active CPUs.  Divide free list evenly among
11788 	 * active CPUs.
11789 	 */
11790 	start = (dtrace_dynvar_t *)
11791 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
11792 	limit = (uintptr_t)base + size;
11793 
11794 	maxper = (limit - (uintptr_t)start) / NCPU;
11795 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
11796 
11797 	for (i = 0; i < NCPU; i++) {
11798 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
11799 
11800 		/*
11801 		 * If we don't even have enough chunks to make it once through
11802 		 * NCPUs, we're just going to allocate everything to the first
11803 		 * CPU.  And if we're on the last CPU, we're going to allocate
11804 		 * whatever is left over.  In either case, we set the limit to
11805 		 * be the limit of the dynamic variable space.
11806 		 */
11807 		if (maxper == 0 || i == NCPU - 1) {
11808 			limit = (uintptr_t)base + size;
11809 			start = NULL;
11810 		} else {
11811 			limit = (uintptr_t)start + maxper;
11812 			start = (dtrace_dynvar_t *)limit;
11813 		}
11814 
11815 		ASSERT(limit <= (uintptr_t)base + size);
11816 
11817 		for (;;) {
11818 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
11819 			    dstate->dtds_chunksize);
11820 
11821 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
11822 				break;
11823 
11824 			dvar->dtdv_next = next;
11825 			dvar = next;
11826 		}
11827 
11828 		if (maxper == 0)
11829 			break;
11830 	}
11831 
11832 	return (0);
11833 }
11834 
11835 void
11836 dtrace_dstate_fini(dtrace_dstate_t *dstate)
11837 {
11838 	ASSERT(MUTEX_HELD(&cpu_lock));
11839 
11840 	if (dstate->dtds_base == NULL)
11841 		return;
11842 
11843 	kmem_free(dstate->dtds_base, dstate->dtds_size);
11844 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
11845 }
11846 
11847 static void
11848 dtrace_vstate_fini(dtrace_vstate_t *vstate)
11849 {
11850 	/*
11851 	 * Logical XOR, where are you?
11852 	 */
11853 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
11854 
11855 	if (vstate->dtvs_nglobals > 0) {
11856 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
11857 		    sizeof (dtrace_statvar_t *));
11858 	}
11859 
11860 	if (vstate->dtvs_ntlocals > 0) {
11861 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
11862 		    sizeof (dtrace_difv_t));
11863 	}
11864 
11865 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
11866 
11867 	if (vstate->dtvs_nlocals > 0) {
11868 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
11869 		    sizeof (dtrace_statvar_t *));
11870 	}
11871 }
11872 
11873 static void
11874 dtrace_state_clean(dtrace_state_t *state)
11875 {
11876 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
11877 		return;
11878 
11879 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
11880 	dtrace_speculation_clean(state);
11881 }
11882 
11883 static void
11884 dtrace_state_deadman(dtrace_state_t *state)
11885 {
11886 	hrtime_t now;
11887 
11888 	dtrace_sync();
11889 
11890 	now = dtrace_gethrtime();
11891 
11892 	if (state != dtrace_anon.dta_state &&
11893 	    now - state->dts_laststatus >= dtrace_deadman_user)
11894 		return;
11895 
11896 	/*
11897 	 * We must be sure that dts_alive never appears to be less than the
11898 	 * value upon entry to dtrace_state_deadman(), and because we lack a
11899 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
11900 	 * store INT64_MAX to it, followed by a memory barrier, followed by
11901 	 * the new value.  This assures that dts_alive never appears to be
11902 	 * less than its true value, regardless of the order in which the
11903 	 * stores to the underlying storage are issued.
11904 	 */
11905 	state->dts_alive = INT64_MAX;
11906 	dtrace_membar_producer();
11907 	state->dts_alive = now;
11908 }
11909 
11910 dtrace_state_t *
11911 dtrace_state_create(dev_t *devp, cred_t *cr)
11912 {
11913 	minor_t minor;
11914 	major_t major;
11915 	char c[30];
11916 	dtrace_state_t *state;
11917 	dtrace_optval_t *opt;
11918 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
11919 
11920 	ASSERT(MUTEX_HELD(&dtrace_lock));
11921 	ASSERT(MUTEX_HELD(&cpu_lock));
11922 
11923 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
11924 	    VM_BESTFIT | VM_SLEEP);
11925 
11926 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
11927 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
11928 		return (NULL);
11929 	}
11930 
11931 	state = ddi_get_soft_state(dtrace_softstate, minor);
11932 	state->dts_epid = DTRACE_EPIDNONE + 1;
11933 
11934 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
11935 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
11936 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
11937 
11938 	if (devp != NULL) {
11939 		major = getemajor(*devp);
11940 	} else {
11941 		major = ddi_driver_major(dtrace_devi);
11942 	}
11943 
11944 	state->dts_dev = makedevice(major, minor);
11945 
11946 	if (devp != NULL)
11947 		*devp = state->dts_dev;
11948 
11949 	/*
11950 	 * We allocate NCPU buffers.  On the one hand, this can be quite
11951 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
11952 	 * other hand, it saves an additional memory reference in the probe
11953 	 * path.
11954 	 */
11955 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
11956 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
11957 	state->dts_cleaner = CYCLIC_NONE;
11958 	state->dts_deadman = CYCLIC_NONE;
11959 	state->dts_vstate.dtvs_state = state;
11960 
11961 	for (i = 0; i < DTRACEOPT_MAX; i++)
11962 		state->dts_options[i] = DTRACEOPT_UNSET;
11963 
11964 	/*
11965 	 * Set the default options.
11966 	 */
11967 	opt = state->dts_options;
11968 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
11969 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
11970 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
11971 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
11972 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
11973 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
11974 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
11975 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
11976 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
11977 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
11978 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
11979 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
11980 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
11981 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
11982 
11983 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
11984 
11985 	/*
11986 	 * Depending on the user credentials, we set flag bits which alter probe
11987 	 * visibility or the amount of destructiveness allowed.  In the case of
11988 	 * actual anonymous tracing, or the possession of all privileges, all of
11989 	 * the normal checks are bypassed.
11990 	 */
11991 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
11992 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
11993 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
11994 	} else {
11995 		/*
11996 		 * Set up the credentials for this instantiation.  We take a
11997 		 * hold on the credential to prevent it from disappearing on
11998 		 * us; this in turn prevents the zone_t referenced by this
11999 		 * credential from disappearing.  This means that we can
12000 		 * examine the credential and the zone from probe context.
12001 		 */
12002 		crhold(cr);
12003 		state->dts_cred.dcr_cred = cr;
12004 
12005 		/*
12006 		 * CRA_PROC means "we have *some* privilege for dtrace" and
12007 		 * unlocks the use of variables like pid, zonename, etc.
12008 		 */
12009 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
12010 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12011 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
12012 		}
12013 
12014 		/*
12015 		 * dtrace_user allows use of syscall and profile providers.
12016 		 * If the user also has proc_owner and/or proc_zone, we
12017 		 * extend the scope to include additional visibility and
12018 		 * destructive power.
12019 		 */
12020 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
12021 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
12022 				state->dts_cred.dcr_visible |=
12023 				    DTRACE_CRV_ALLPROC;
12024 
12025 				state->dts_cred.dcr_action |=
12026 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12027 			}
12028 
12029 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
12030 				state->dts_cred.dcr_visible |=
12031 				    DTRACE_CRV_ALLZONE;
12032 
12033 				state->dts_cred.dcr_action |=
12034 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12035 			}
12036 
12037 			/*
12038 			 * If we have all privs in whatever zone this is,
12039 			 * we can do destructive things to processes which
12040 			 * have altered credentials.
12041 			 */
12042 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12043 			    cr->cr_zone->zone_privset)) {
12044 				state->dts_cred.dcr_action |=
12045 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12046 			}
12047 		}
12048 
12049 		/*
12050 		 * Holding the dtrace_kernel privilege also implies that
12051 		 * the user has the dtrace_user privilege from a visibility
12052 		 * perspective.  But without further privileges, some
12053 		 * destructive actions are not available.
12054 		 */
12055 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
12056 			/*
12057 			 * Make all probes in all zones visible.  However,
12058 			 * this doesn't mean that all actions become available
12059 			 * to all zones.
12060 			 */
12061 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
12062 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
12063 
12064 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
12065 			    DTRACE_CRA_PROC;
12066 			/*
12067 			 * Holding proc_owner means that destructive actions
12068 			 * for *this* zone are allowed.
12069 			 */
12070 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12071 				state->dts_cred.dcr_action |=
12072 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12073 
12074 			/*
12075 			 * Holding proc_zone means that destructive actions
12076 			 * for this user/group ID in all zones is allowed.
12077 			 */
12078 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12079 				state->dts_cred.dcr_action |=
12080 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12081 
12082 			/*
12083 			 * If we have all privs in whatever zone this is,
12084 			 * we can do destructive things to processes which
12085 			 * have altered credentials.
12086 			 */
12087 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12088 			    cr->cr_zone->zone_privset)) {
12089 				state->dts_cred.dcr_action |=
12090 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12091 			}
12092 		}
12093 
12094 		/*
12095 		 * Holding the dtrace_proc privilege gives control over fasttrap
12096 		 * and pid providers.  We need to grant wider destructive
12097 		 * privileges in the event that the user has proc_owner and/or
12098 		 * proc_zone.
12099 		 */
12100 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12101 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12102 				state->dts_cred.dcr_action |=
12103 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12104 
12105 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12106 				state->dts_cred.dcr_action |=
12107 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12108 		}
12109 	}
12110 
12111 	return (state);
12112 }
12113 
12114 static int
12115 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
12116 {
12117 	dtrace_optval_t *opt = state->dts_options, size;
12118 	processorid_t cpu;
12119 	int flags = 0, rval;
12120 
12121 	ASSERT(MUTEX_HELD(&dtrace_lock));
12122 	ASSERT(MUTEX_HELD(&cpu_lock));
12123 	ASSERT(which < DTRACEOPT_MAX);
12124 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
12125 	    (state == dtrace_anon.dta_state &&
12126 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
12127 
12128 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
12129 		return (0);
12130 
12131 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
12132 		cpu = opt[DTRACEOPT_CPU];
12133 
12134 	if (which == DTRACEOPT_SPECSIZE)
12135 		flags |= DTRACEBUF_NOSWITCH;
12136 
12137 	if (which == DTRACEOPT_BUFSIZE) {
12138 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
12139 			flags |= DTRACEBUF_RING;
12140 
12141 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
12142 			flags |= DTRACEBUF_FILL;
12143 
12144 		if (state != dtrace_anon.dta_state ||
12145 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
12146 			flags |= DTRACEBUF_INACTIVE;
12147 	}
12148 
12149 	for (size = opt[which]; size >= sizeof (uint64_t); size >>= 1) {
12150 		/*
12151 		 * The size must be 8-byte aligned.  If the size is not 8-byte
12152 		 * aligned, drop it down by the difference.
12153 		 */
12154 		if (size & (sizeof (uint64_t) - 1))
12155 			size -= size & (sizeof (uint64_t) - 1);
12156 
12157 		if (size < state->dts_reserve) {
12158 			/*
12159 			 * Buffers always must be large enough to accommodate
12160 			 * their prereserved space.  We return E2BIG instead
12161 			 * of ENOMEM in this case to allow for user-level
12162 			 * software to differentiate the cases.
12163 			 */
12164 			return (E2BIG);
12165 		}
12166 
12167 		rval = dtrace_buffer_alloc(buf, size, flags, cpu);
12168 
12169 		if (rval != ENOMEM) {
12170 			opt[which] = size;
12171 			return (rval);
12172 		}
12173 
12174 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12175 			return (rval);
12176 	}
12177 
12178 	return (ENOMEM);
12179 }
12180 
12181 static int
12182 dtrace_state_buffers(dtrace_state_t *state)
12183 {
12184 	dtrace_speculation_t *spec = state->dts_speculations;
12185 	int rval, i;
12186 
12187 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
12188 	    DTRACEOPT_BUFSIZE)) != 0)
12189 		return (rval);
12190 
12191 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
12192 	    DTRACEOPT_AGGSIZE)) != 0)
12193 		return (rval);
12194 
12195 	for (i = 0; i < state->dts_nspeculations; i++) {
12196 		if ((rval = dtrace_state_buffer(state,
12197 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
12198 			return (rval);
12199 	}
12200 
12201 	return (0);
12202 }
12203 
12204 static void
12205 dtrace_state_prereserve(dtrace_state_t *state)
12206 {
12207 	dtrace_ecb_t *ecb;
12208 	dtrace_probe_t *probe;
12209 
12210 	state->dts_reserve = 0;
12211 
12212 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
12213 		return;
12214 
12215 	/*
12216 	 * If our buffer policy is a "fill" buffer policy, we need to set the
12217 	 * prereserved space to be the space required by the END probes.
12218 	 */
12219 	probe = dtrace_probes[dtrace_probeid_end - 1];
12220 	ASSERT(probe != NULL);
12221 
12222 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
12223 		if (ecb->dte_state != state)
12224 			continue;
12225 
12226 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
12227 	}
12228 }
12229 
12230 static int
12231 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
12232 {
12233 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
12234 	dtrace_speculation_t *spec;
12235 	dtrace_buffer_t *buf;
12236 	cyc_handler_t hdlr;
12237 	cyc_time_t when;
12238 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12239 	dtrace_icookie_t cookie;
12240 
12241 	mutex_enter(&cpu_lock);
12242 	mutex_enter(&dtrace_lock);
12243 
12244 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
12245 		rval = EBUSY;
12246 		goto out;
12247 	}
12248 
12249 	/*
12250 	 * Before we can perform any checks, we must prime all of the
12251 	 * retained enablings that correspond to this state.
12252 	 */
12253 	dtrace_enabling_prime(state);
12254 
12255 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
12256 		rval = EACCES;
12257 		goto out;
12258 	}
12259 
12260 	dtrace_state_prereserve(state);
12261 
12262 	/*
12263 	 * Now we want to do is try to allocate our speculations.
12264 	 * We do not automatically resize the number of speculations; if
12265 	 * this fails, we will fail the operation.
12266 	 */
12267 	nspec = opt[DTRACEOPT_NSPEC];
12268 	ASSERT(nspec != DTRACEOPT_UNSET);
12269 
12270 	if (nspec > INT_MAX) {
12271 		rval = ENOMEM;
12272 		goto out;
12273 	}
12274 
12275 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
12276 
12277 	if (spec == NULL) {
12278 		rval = ENOMEM;
12279 		goto out;
12280 	}
12281 
12282 	state->dts_speculations = spec;
12283 	state->dts_nspeculations = (int)nspec;
12284 
12285 	for (i = 0; i < nspec; i++) {
12286 		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
12287 			rval = ENOMEM;
12288 			goto err;
12289 		}
12290 
12291 		spec[i].dtsp_buffer = buf;
12292 	}
12293 
12294 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
12295 		if (dtrace_anon.dta_state == NULL) {
12296 			rval = ENOENT;
12297 			goto out;
12298 		}
12299 
12300 		if (state->dts_necbs != 0) {
12301 			rval = EALREADY;
12302 			goto out;
12303 		}
12304 
12305 		state->dts_anon = dtrace_anon_grab();
12306 		ASSERT(state->dts_anon != NULL);
12307 		state = state->dts_anon;
12308 
12309 		/*
12310 		 * We want "grabanon" to be set in the grabbed state, so we'll
12311 		 * copy that option value from the grabbing state into the
12312 		 * grabbed state.
12313 		 */
12314 		state->dts_options[DTRACEOPT_GRABANON] =
12315 		    opt[DTRACEOPT_GRABANON];
12316 
12317 		*cpu = dtrace_anon.dta_beganon;
12318 
12319 		/*
12320 		 * If the anonymous state is active (as it almost certainly
12321 		 * is if the anonymous enabling ultimately matched anything),
12322 		 * we don't allow any further option processing -- but we
12323 		 * don't return failure.
12324 		 */
12325 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12326 			goto out;
12327 	}
12328 
12329 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
12330 	    opt[DTRACEOPT_AGGSIZE] != 0) {
12331 		if (state->dts_aggregations == NULL) {
12332 			/*
12333 			 * We're not going to create an aggregation buffer
12334 			 * because we don't have any ECBs that contain
12335 			 * aggregations -- set this option to 0.
12336 			 */
12337 			opt[DTRACEOPT_AGGSIZE] = 0;
12338 		} else {
12339 			/*
12340 			 * If we have an aggregation buffer, we must also have
12341 			 * a buffer to use as scratch.
12342 			 */
12343 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
12344 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
12345 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
12346 			}
12347 		}
12348 	}
12349 
12350 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
12351 	    opt[DTRACEOPT_SPECSIZE] != 0) {
12352 		if (!state->dts_speculates) {
12353 			/*
12354 			 * We're not going to create speculation buffers
12355 			 * because we don't have any ECBs that actually
12356 			 * speculate -- set the speculation size to 0.
12357 			 */
12358 			opt[DTRACEOPT_SPECSIZE] = 0;
12359 		}
12360 	}
12361 
12362 	/*
12363 	 * The bare minimum size for any buffer that we're actually going to
12364 	 * do anything to is sizeof (uint64_t).
12365 	 */
12366 	sz = sizeof (uint64_t);
12367 
12368 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
12369 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
12370 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
12371 		/*
12372 		 * A buffer size has been explicitly set to 0 (or to a size
12373 		 * that will be adjusted to 0) and we need the space -- we
12374 		 * need to return failure.  We return ENOSPC to differentiate
12375 		 * it from failing to allocate a buffer due to failure to meet
12376 		 * the reserve (for which we return E2BIG).
12377 		 */
12378 		rval = ENOSPC;
12379 		goto out;
12380 	}
12381 
12382 	if ((rval = dtrace_state_buffers(state)) != 0)
12383 		goto err;
12384 
12385 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
12386 		sz = dtrace_dstate_defsize;
12387 
12388 	do {
12389 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
12390 
12391 		if (rval == 0)
12392 			break;
12393 
12394 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12395 			goto err;
12396 	} while (sz >>= 1);
12397 
12398 	opt[DTRACEOPT_DYNVARSIZE] = sz;
12399 
12400 	if (rval != 0)
12401 		goto err;
12402 
12403 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
12404 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
12405 
12406 	if (opt[DTRACEOPT_CLEANRATE] == 0)
12407 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12408 
12409 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
12410 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
12411 
12412 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
12413 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12414 
12415 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
12416 	hdlr.cyh_arg = state;
12417 	hdlr.cyh_level = CY_LOW_LEVEL;
12418 
12419 	when.cyt_when = 0;
12420 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
12421 
12422 	state->dts_cleaner = cyclic_add(&hdlr, &when);
12423 
12424 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
12425 	hdlr.cyh_arg = state;
12426 	hdlr.cyh_level = CY_LOW_LEVEL;
12427 
12428 	when.cyt_when = 0;
12429 	when.cyt_interval = dtrace_deadman_interval;
12430 
12431 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
12432 	state->dts_deadman = cyclic_add(&hdlr, &when);
12433 
12434 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
12435 
12436 	/*
12437 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
12438 	 * interrupts here both to record the CPU on which we fired the BEGIN
12439 	 * probe (the data from this CPU will be processed first at user
12440 	 * level) and to manually activate the buffer for this CPU.
12441 	 */
12442 	cookie = dtrace_interrupt_disable();
12443 	*cpu = CPU->cpu_id;
12444 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
12445 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12446 
12447 	dtrace_probe(dtrace_probeid_begin,
12448 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
12449 	dtrace_interrupt_enable(cookie);
12450 	/*
12451 	 * We may have had an exit action from a BEGIN probe; only change our
12452 	 * state to ACTIVE if we're still in WARMUP.
12453 	 */
12454 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
12455 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
12456 
12457 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
12458 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
12459 
12460 	/*
12461 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
12462 	 * want each CPU to transition its principal buffer out of the
12463 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
12464 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
12465 	 * atomically transition from processing none of a state's ECBs to
12466 	 * processing all of them.
12467 	 */
12468 	dtrace_xcall(DTRACE_CPUALL,
12469 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
12470 	goto out;
12471 
12472 err:
12473 	dtrace_buffer_free(state->dts_buffer);
12474 	dtrace_buffer_free(state->dts_aggbuffer);
12475 
12476 	if ((nspec = state->dts_nspeculations) == 0) {
12477 		ASSERT(state->dts_speculations == NULL);
12478 		goto out;
12479 	}
12480 
12481 	spec = state->dts_speculations;
12482 	ASSERT(spec != NULL);
12483 
12484 	for (i = 0; i < state->dts_nspeculations; i++) {
12485 		if ((buf = spec[i].dtsp_buffer) == NULL)
12486 			break;
12487 
12488 		dtrace_buffer_free(buf);
12489 		kmem_free(buf, bufsize);
12490 	}
12491 
12492 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
12493 	state->dts_nspeculations = 0;
12494 	state->dts_speculations = NULL;
12495 
12496 out:
12497 	mutex_exit(&dtrace_lock);
12498 	mutex_exit(&cpu_lock);
12499 
12500 	return (rval);
12501 }
12502 
12503 static int
12504 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
12505 {
12506 	dtrace_icookie_t cookie;
12507 
12508 	ASSERT(MUTEX_HELD(&dtrace_lock));
12509 
12510 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
12511 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
12512 		return (EINVAL);
12513 
12514 	/*
12515 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
12516 	 * to be sure that every CPU has seen it.  See below for the details
12517 	 * on why this is done.
12518 	 */
12519 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
12520 	dtrace_sync();
12521 
12522 	/*
12523 	 * By this point, it is impossible for any CPU to be still processing
12524 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
12525 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
12526 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
12527 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
12528 	 * iff we're in the END probe.
12529 	 */
12530 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
12531 	dtrace_sync();
12532 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
12533 
12534 	/*
12535 	 * Finally, we can release the reserve and call the END probe.  We
12536 	 * disable interrupts across calling the END probe to allow us to
12537 	 * return the CPU on which we actually called the END probe.  This
12538 	 * allows user-land to be sure that this CPU's principal buffer is
12539 	 * processed last.
12540 	 */
12541 	state->dts_reserve = 0;
12542 
12543 	cookie = dtrace_interrupt_disable();
12544 	*cpu = CPU->cpu_id;
12545 	dtrace_probe(dtrace_probeid_end,
12546 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
12547 	dtrace_interrupt_enable(cookie);
12548 
12549 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
12550 	dtrace_sync();
12551 
12552 	return (0);
12553 }
12554 
12555 static int
12556 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
12557     dtrace_optval_t val)
12558 {
12559 	ASSERT(MUTEX_HELD(&dtrace_lock));
12560 
12561 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12562 		return (EBUSY);
12563 
12564 	if (option >= DTRACEOPT_MAX)
12565 		return (EINVAL);
12566 
12567 	if (option != DTRACEOPT_CPU && val < 0)
12568 		return (EINVAL);
12569 
12570 	switch (option) {
12571 	case DTRACEOPT_DESTRUCTIVE:
12572 		if (dtrace_destructive_disallow)
12573 			return (EACCES);
12574 
12575 		state->dts_cred.dcr_destructive = 1;
12576 		break;
12577 
12578 	case DTRACEOPT_BUFSIZE:
12579 	case DTRACEOPT_DYNVARSIZE:
12580 	case DTRACEOPT_AGGSIZE:
12581 	case DTRACEOPT_SPECSIZE:
12582 	case DTRACEOPT_STRSIZE:
12583 		if (val < 0)
12584 			return (EINVAL);
12585 
12586 		if (val >= LONG_MAX) {
12587 			/*
12588 			 * If this is an otherwise negative value, set it to
12589 			 * the highest multiple of 128m less than LONG_MAX.
12590 			 * Technically, we're adjusting the size without
12591 			 * regard to the buffer resizing policy, but in fact,
12592 			 * this has no effect -- if we set the buffer size to
12593 			 * ~LONG_MAX and the buffer policy is ultimately set to
12594 			 * be "manual", the buffer allocation is guaranteed to
12595 			 * fail, if only because the allocation requires two
12596 			 * buffers.  (We set the the size to the highest
12597 			 * multiple of 128m because it ensures that the size
12598 			 * will remain a multiple of a megabyte when
12599 			 * repeatedly halved -- all the way down to 15m.)
12600 			 */
12601 			val = LONG_MAX - (1 << 27) + 1;
12602 		}
12603 	}
12604 
12605 	state->dts_options[option] = val;
12606 
12607 	return (0);
12608 }
12609 
12610 static void
12611 dtrace_state_destroy(dtrace_state_t *state)
12612 {
12613 	dtrace_ecb_t *ecb;
12614 	dtrace_vstate_t *vstate = &state->dts_vstate;
12615 	minor_t minor = getminor(state->dts_dev);
12616 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12617 	dtrace_speculation_t *spec = state->dts_speculations;
12618 	int nspec = state->dts_nspeculations;
12619 	uint32_t match;
12620 
12621 	ASSERT(MUTEX_HELD(&dtrace_lock));
12622 	ASSERT(MUTEX_HELD(&cpu_lock));
12623 
12624 	/*
12625 	 * First, retract any retained enablings for this state.
12626 	 */
12627 	dtrace_enabling_retract(state);
12628 	ASSERT(state->dts_nretained == 0);
12629 
12630 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
12631 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
12632 		/*
12633 		 * We have managed to come into dtrace_state_destroy() on a
12634 		 * hot enabling -- almost certainly because of a disorderly
12635 		 * shutdown of a consumer.  (That is, a consumer that is
12636 		 * exiting without having called dtrace_stop().) In this case,
12637 		 * we're going to set our activity to be KILLED, and then
12638 		 * issue a sync to be sure that everyone is out of probe
12639 		 * context before we start blowing away ECBs.
12640 		 */
12641 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
12642 		dtrace_sync();
12643 	}
12644 
12645 	/*
12646 	 * Release the credential hold we took in dtrace_state_create().
12647 	 */
12648 	if (state->dts_cred.dcr_cred != NULL)
12649 		crfree(state->dts_cred.dcr_cred);
12650 
12651 	/*
12652 	 * Now we can safely disable and destroy any enabled probes.  Because
12653 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
12654 	 * (especially if they're all enabled), we take two passes through the
12655 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
12656 	 * in the second we disable whatever is left over.
12657 	 */
12658 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
12659 		for (i = 0; i < state->dts_necbs; i++) {
12660 			if ((ecb = state->dts_ecbs[i]) == NULL)
12661 				continue;
12662 
12663 			if (match && ecb->dte_probe != NULL) {
12664 				dtrace_probe_t *probe = ecb->dte_probe;
12665 				dtrace_provider_t *prov = probe->dtpr_provider;
12666 
12667 				if (!(prov->dtpv_priv.dtpp_flags & match))
12668 					continue;
12669 			}
12670 
12671 			dtrace_ecb_disable(ecb);
12672 			dtrace_ecb_destroy(ecb);
12673 		}
12674 
12675 		if (!match)
12676 			break;
12677 	}
12678 
12679 	/*
12680 	 * Before we free the buffers, perform one more sync to assure that
12681 	 * every CPU is out of probe context.
12682 	 */
12683 	dtrace_sync();
12684 
12685 	dtrace_buffer_free(state->dts_buffer);
12686 	dtrace_buffer_free(state->dts_aggbuffer);
12687 
12688 	for (i = 0; i < nspec; i++)
12689 		dtrace_buffer_free(spec[i].dtsp_buffer);
12690 
12691 	if (state->dts_cleaner != CYCLIC_NONE)
12692 		cyclic_remove(state->dts_cleaner);
12693 
12694 	if (state->dts_deadman != CYCLIC_NONE)
12695 		cyclic_remove(state->dts_deadman);
12696 
12697 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
12698 	dtrace_vstate_fini(vstate);
12699 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
12700 
12701 	if (state->dts_aggregations != NULL) {
12702 #ifdef DEBUG
12703 		for (i = 0; i < state->dts_naggregations; i++)
12704 			ASSERT(state->dts_aggregations[i] == NULL);
12705 #endif
12706 		ASSERT(state->dts_naggregations > 0);
12707 		kmem_free(state->dts_aggregations,
12708 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
12709 	}
12710 
12711 	kmem_free(state->dts_buffer, bufsize);
12712 	kmem_free(state->dts_aggbuffer, bufsize);
12713 
12714 	for (i = 0; i < nspec; i++)
12715 		kmem_free(spec[i].dtsp_buffer, bufsize);
12716 
12717 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
12718 
12719 	dtrace_format_destroy(state);
12720 
12721 	vmem_destroy(state->dts_aggid_arena);
12722 	ddi_soft_state_free(dtrace_softstate, minor);
12723 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12724 }
12725 
12726 /*
12727  * DTrace Anonymous Enabling Functions
12728  */
12729 static dtrace_state_t *
12730 dtrace_anon_grab(void)
12731 {
12732 	dtrace_state_t *state;
12733 
12734 	ASSERT(MUTEX_HELD(&dtrace_lock));
12735 
12736 	if ((state = dtrace_anon.dta_state) == NULL) {
12737 		ASSERT(dtrace_anon.dta_enabling == NULL);
12738 		return (NULL);
12739 	}
12740 
12741 	ASSERT(dtrace_anon.dta_enabling != NULL);
12742 	ASSERT(dtrace_retained != NULL);
12743 
12744 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
12745 	dtrace_anon.dta_enabling = NULL;
12746 	dtrace_anon.dta_state = NULL;
12747 
12748 	return (state);
12749 }
12750 
12751 static void
12752 dtrace_anon_property(void)
12753 {
12754 	int i, rv;
12755 	dtrace_state_t *state;
12756 	dof_hdr_t *dof;
12757 	char c[32];		/* enough for "dof-data-" + digits */
12758 
12759 	ASSERT(MUTEX_HELD(&dtrace_lock));
12760 	ASSERT(MUTEX_HELD(&cpu_lock));
12761 
12762 	for (i = 0; ; i++) {
12763 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
12764 
12765 		dtrace_err_verbose = 1;
12766 
12767 		if ((dof = dtrace_dof_property(c)) == NULL) {
12768 			dtrace_err_verbose = 0;
12769 			break;
12770 		}
12771 
12772 		/*
12773 		 * We want to create anonymous state, so we need to transition
12774 		 * the kernel debugger to indicate that DTrace is active.  If
12775 		 * this fails (e.g. because the debugger has modified text in
12776 		 * some way), we won't continue with the processing.
12777 		 */
12778 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
12779 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
12780 			    "enabling ignored.");
12781 			dtrace_dof_destroy(dof);
12782 			break;
12783 		}
12784 
12785 		/*
12786 		 * If we haven't allocated an anonymous state, we'll do so now.
12787 		 */
12788 		if ((state = dtrace_anon.dta_state) == NULL) {
12789 			state = dtrace_state_create(NULL, NULL);
12790 			dtrace_anon.dta_state = state;
12791 
12792 			if (state == NULL) {
12793 				/*
12794 				 * This basically shouldn't happen:  the only
12795 				 * failure mode from dtrace_state_create() is a
12796 				 * failure of ddi_soft_state_zalloc() that
12797 				 * itself should never happen.  Still, the
12798 				 * interface allows for a failure mode, and
12799 				 * we want to fail as gracefully as possible:
12800 				 * we'll emit an error message and cease
12801 				 * processing anonymous state in this case.
12802 				 */
12803 				cmn_err(CE_WARN, "failed to create "
12804 				    "anonymous state");
12805 				dtrace_dof_destroy(dof);
12806 				break;
12807 			}
12808 		}
12809 
12810 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
12811 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
12812 
12813 		if (rv == 0)
12814 			rv = dtrace_dof_options(dof, state);
12815 
12816 		dtrace_err_verbose = 0;
12817 		dtrace_dof_destroy(dof);
12818 
12819 		if (rv != 0) {
12820 			/*
12821 			 * This is malformed DOF; chuck any anonymous state
12822 			 * that we created.
12823 			 */
12824 			ASSERT(dtrace_anon.dta_enabling == NULL);
12825 			dtrace_state_destroy(state);
12826 			dtrace_anon.dta_state = NULL;
12827 			break;
12828 		}
12829 
12830 		ASSERT(dtrace_anon.dta_enabling != NULL);
12831 	}
12832 
12833 	if (dtrace_anon.dta_enabling != NULL) {
12834 		int rval;
12835 
12836 		/*
12837 		 * dtrace_enabling_retain() can only fail because we are
12838 		 * trying to retain more enablings than are allowed -- but
12839 		 * we only have one anonymous enabling, and we are guaranteed
12840 		 * to be allowed at least one retained enabling; we assert
12841 		 * that dtrace_enabling_retain() returns success.
12842 		 */
12843 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
12844 		ASSERT(rval == 0);
12845 
12846 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
12847 	}
12848 }
12849 
12850 /*
12851  * DTrace Helper Functions
12852  */
12853 static void
12854 dtrace_helper_trace(dtrace_helper_action_t *helper,
12855     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
12856 {
12857 	uint32_t size, next, nnext, i;
12858 	dtrace_helptrace_t *ent;
12859 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12860 
12861 	if (!dtrace_helptrace_enabled)
12862 		return;
12863 
12864 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
12865 
12866 	/*
12867 	 * What would a tracing framework be without its own tracing
12868 	 * framework?  (Well, a hell of a lot simpler, for starters...)
12869 	 */
12870 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
12871 	    sizeof (uint64_t) - sizeof (uint64_t);
12872 
12873 	/*
12874 	 * Iterate until we can allocate a slot in the trace buffer.
12875 	 */
12876 	do {
12877 		next = dtrace_helptrace_next;
12878 
12879 		if (next + size < dtrace_helptrace_bufsize) {
12880 			nnext = next + size;
12881 		} else {
12882 			nnext = size;
12883 		}
12884 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
12885 
12886 	/*
12887 	 * We have our slot; fill it in.
12888 	 */
12889 	if (nnext == size)
12890 		next = 0;
12891 
12892 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
12893 	ent->dtht_helper = helper;
12894 	ent->dtht_where = where;
12895 	ent->dtht_nlocals = vstate->dtvs_nlocals;
12896 
12897 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
12898 	    mstate->dtms_fltoffs : -1;
12899 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
12900 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
12901 
12902 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
12903 		dtrace_statvar_t *svar;
12904 
12905 		if ((svar = vstate->dtvs_locals[i]) == NULL)
12906 			continue;
12907 
12908 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
12909 		ent->dtht_locals[i] =
12910 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
12911 	}
12912 }
12913 
12914 static uint64_t
12915 dtrace_helper(int which, dtrace_mstate_t *mstate,
12916     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
12917 {
12918 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12919 	uint64_t sarg0 = mstate->dtms_arg[0];
12920 	uint64_t sarg1 = mstate->dtms_arg[1];
12921 	uint64_t rval;
12922 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
12923 	dtrace_helper_action_t *helper;
12924 	dtrace_vstate_t *vstate;
12925 	dtrace_difo_t *pred;
12926 	int i, trace = dtrace_helptrace_enabled;
12927 
12928 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
12929 
12930 	if (helpers == NULL)
12931 		return (0);
12932 
12933 	if ((helper = helpers->dthps_actions[which]) == NULL)
12934 		return (0);
12935 
12936 	vstate = &helpers->dthps_vstate;
12937 	mstate->dtms_arg[0] = arg0;
12938 	mstate->dtms_arg[1] = arg1;
12939 
12940 	/*
12941 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
12942 	 * we'll call the corresponding actions.  Note that the below calls
12943 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
12944 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
12945 	 * the stored DIF offset with its own (which is the desired behavior).
12946 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
12947 	 * from machine state; this is okay, too.
12948 	 */
12949 	for (; helper != NULL; helper = helper->dtha_next) {
12950 		if ((pred = helper->dtha_predicate) != NULL) {
12951 			if (trace)
12952 				dtrace_helper_trace(helper, mstate, vstate, 0);
12953 
12954 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
12955 				goto next;
12956 
12957 			if (*flags & CPU_DTRACE_FAULT)
12958 				goto err;
12959 		}
12960 
12961 		for (i = 0; i < helper->dtha_nactions; i++) {
12962 			if (trace)
12963 				dtrace_helper_trace(helper,
12964 				    mstate, vstate, i + 1);
12965 
12966 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
12967 			    mstate, vstate, state);
12968 
12969 			if (*flags & CPU_DTRACE_FAULT)
12970 				goto err;
12971 		}
12972 
12973 next:
12974 		if (trace)
12975 			dtrace_helper_trace(helper, mstate, vstate,
12976 			    DTRACE_HELPTRACE_NEXT);
12977 	}
12978 
12979 	if (trace)
12980 		dtrace_helper_trace(helper, mstate, vstate,
12981 		    DTRACE_HELPTRACE_DONE);
12982 
12983 	/*
12984 	 * Restore the arg0 that we saved upon entry.
12985 	 */
12986 	mstate->dtms_arg[0] = sarg0;
12987 	mstate->dtms_arg[1] = sarg1;
12988 
12989 	return (rval);
12990 
12991 err:
12992 	if (trace)
12993 		dtrace_helper_trace(helper, mstate, vstate,
12994 		    DTRACE_HELPTRACE_ERR);
12995 
12996 	/*
12997 	 * Restore the arg0 that we saved upon entry.
12998 	 */
12999 	mstate->dtms_arg[0] = sarg0;
13000 	mstate->dtms_arg[1] = sarg1;
13001 
13002 	return (NULL);
13003 }
13004 
13005 static void
13006 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
13007     dtrace_vstate_t *vstate)
13008 {
13009 	int i;
13010 
13011 	if (helper->dtha_predicate != NULL)
13012 		dtrace_difo_release(helper->dtha_predicate, vstate);
13013 
13014 	for (i = 0; i < helper->dtha_nactions; i++) {
13015 		ASSERT(helper->dtha_actions[i] != NULL);
13016 		dtrace_difo_release(helper->dtha_actions[i], vstate);
13017 	}
13018 
13019 	kmem_free(helper->dtha_actions,
13020 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
13021 	kmem_free(helper, sizeof (dtrace_helper_action_t));
13022 }
13023 
13024 static int
13025 dtrace_helper_destroygen(int gen)
13026 {
13027 	proc_t *p = curproc;
13028 	dtrace_helpers_t *help = p->p_dtrace_helpers;
13029 	dtrace_vstate_t *vstate;
13030 	int i;
13031 
13032 	ASSERT(MUTEX_HELD(&dtrace_lock));
13033 
13034 	if (help == NULL || gen > help->dthps_generation)
13035 		return (EINVAL);
13036 
13037 	vstate = &help->dthps_vstate;
13038 
13039 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13040 		dtrace_helper_action_t *last = NULL, *h, *next;
13041 
13042 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13043 			next = h->dtha_next;
13044 
13045 			if (h->dtha_generation == gen) {
13046 				if (last != NULL) {
13047 					last->dtha_next = next;
13048 				} else {
13049 					help->dthps_actions[i] = next;
13050 				}
13051 
13052 				dtrace_helper_action_destroy(h, vstate);
13053 			} else {
13054 				last = h;
13055 			}
13056 		}
13057 	}
13058 
13059 	/*
13060 	 * Interate until we've cleared out all helper providers with the
13061 	 * given generation number.
13062 	 */
13063 	for (;;) {
13064 		dtrace_helper_provider_t *prov;
13065 
13066 		/*
13067 		 * Look for a helper provider with the right generation. We
13068 		 * have to start back at the beginning of the list each time
13069 		 * because we drop dtrace_lock. It's unlikely that we'll make
13070 		 * more than two passes.
13071 		 */
13072 		for (i = 0; i < help->dthps_nprovs; i++) {
13073 			prov = help->dthps_provs[i];
13074 
13075 			if (prov->dthp_generation == gen)
13076 				break;
13077 		}
13078 
13079 		/*
13080 		 * If there were no matches, we're done.
13081 		 */
13082 		if (i == help->dthps_nprovs)
13083 			break;
13084 
13085 		/*
13086 		 * Move the last helper provider into this slot.
13087 		 */
13088 		help->dthps_nprovs--;
13089 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
13090 		help->dthps_provs[help->dthps_nprovs] = NULL;
13091 
13092 		mutex_exit(&dtrace_lock);
13093 
13094 		/*
13095 		 * If we have a meta provider, remove this helper provider.
13096 		 */
13097 		mutex_enter(&dtrace_meta_lock);
13098 		if (dtrace_meta_pid != NULL) {
13099 			ASSERT(dtrace_deferred_pid == NULL);
13100 			dtrace_helper_provider_remove(&prov->dthp_prov,
13101 			    p->p_pid);
13102 		}
13103 		mutex_exit(&dtrace_meta_lock);
13104 
13105 		dtrace_helper_provider_destroy(prov);
13106 
13107 		mutex_enter(&dtrace_lock);
13108 	}
13109 
13110 	return (0);
13111 }
13112 
13113 static int
13114 dtrace_helper_validate(dtrace_helper_action_t *helper)
13115 {
13116 	int err = 0, i;
13117 	dtrace_difo_t *dp;
13118 
13119 	if ((dp = helper->dtha_predicate) != NULL)
13120 		err += dtrace_difo_validate_helper(dp);
13121 
13122 	for (i = 0; i < helper->dtha_nactions; i++)
13123 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
13124 
13125 	return (err == 0);
13126 }
13127 
13128 static int
13129 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
13130 {
13131 	dtrace_helpers_t *help;
13132 	dtrace_helper_action_t *helper, *last;
13133 	dtrace_actdesc_t *act;
13134 	dtrace_vstate_t *vstate;
13135 	dtrace_predicate_t *pred;
13136 	int count = 0, nactions = 0, i;
13137 
13138 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
13139 		return (EINVAL);
13140 
13141 	help = curproc->p_dtrace_helpers;
13142 	last = help->dthps_actions[which];
13143 	vstate = &help->dthps_vstate;
13144 
13145 	for (count = 0; last != NULL; last = last->dtha_next) {
13146 		count++;
13147 		if (last->dtha_next == NULL)
13148 			break;
13149 	}
13150 
13151 	/*
13152 	 * If we already have dtrace_helper_actions_max helper actions for this
13153 	 * helper action type, we'll refuse to add a new one.
13154 	 */
13155 	if (count >= dtrace_helper_actions_max)
13156 		return (ENOSPC);
13157 
13158 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
13159 	helper->dtha_generation = help->dthps_generation;
13160 
13161 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
13162 		ASSERT(pred->dtp_difo != NULL);
13163 		dtrace_difo_hold(pred->dtp_difo);
13164 		helper->dtha_predicate = pred->dtp_difo;
13165 	}
13166 
13167 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
13168 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
13169 			goto err;
13170 
13171 		if (act->dtad_difo == NULL)
13172 			goto err;
13173 
13174 		nactions++;
13175 	}
13176 
13177 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
13178 	    (helper->dtha_nactions = nactions), KM_SLEEP);
13179 
13180 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
13181 		dtrace_difo_hold(act->dtad_difo);
13182 		helper->dtha_actions[i++] = act->dtad_difo;
13183 	}
13184 
13185 	if (!dtrace_helper_validate(helper))
13186 		goto err;
13187 
13188 	if (last == NULL) {
13189 		help->dthps_actions[which] = helper;
13190 	} else {
13191 		last->dtha_next = helper;
13192 	}
13193 
13194 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
13195 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
13196 		dtrace_helptrace_next = 0;
13197 	}
13198 
13199 	return (0);
13200 err:
13201 	dtrace_helper_action_destroy(helper, vstate);
13202 	return (EINVAL);
13203 }
13204 
13205 static void
13206 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
13207     dof_helper_t *dofhp)
13208 {
13209 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
13210 
13211 	mutex_enter(&dtrace_meta_lock);
13212 	mutex_enter(&dtrace_lock);
13213 
13214 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
13215 		/*
13216 		 * If the dtrace module is loaded but not attached, or if
13217 		 * there aren't isn't a meta provider registered to deal with
13218 		 * these provider descriptions, we need to postpone creating
13219 		 * the actual providers until later.
13220 		 */
13221 
13222 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
13223 		    dtrace_deferred_pid != help) {
13224 			help->dthps_deferred = 1;
13225 			help->dthps_pid = p->p_pid;
13226 			help->dthps_next = dtrace_deferred_pid;
13227 			help->dthps_prev = NULL;
13228 			if (dtrace_deferred_pid != NULL)
13229 				dtrace_deferred_pid->dthps_prev = help;
13230 			dtrace_deferred_pid = help;
13231 		}
13232 
13233 		mutex_exit(&dtrace_lock);
13234 
13235 	} else if (dofhp != NULL) {
13236 		/*
13237 		 * If the dtrace module is loaded and we have a particular
13238 		 * helper provider description, pass that off to the
13239 		 * meta provider.
13240 		 */
13241 
13242 		mutex_exit(&dtrace_lock);
13243 
13244 		dtrace_helper_provide(dofhp, p->p_pid);
13245 
13246 	} else {
13247 		/*
13248 		 * Otherwise, just pass all the helper provider descriptions
13249 		 * off to the meta provider.
13250 		 */
13251 
13252 		int i;
13253 		mutex_exit(&dtrace_lock);
13254 
13255 		for (i = 0; i < help->dthps_nprovs; i++) {
13256 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
13257 			    p->p_pid);
13258 		}
13259 	}
13260 
13261 	mutex_exit(&dtrace_meta_lock);
13262 }
13263 
13264 static int
13265 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
13266 {
13267 	dtrace_helpers_t *help;
13268 	dtrace_helper_provider_t *hprov, **tmp_provs;
13269 	uint_t tmp_maxprovs, i;
13270 
13271 	ASSERT(MUTEX_HELD(&dtrace_lock));
13272 
13273 	help = curproc->p_dtrace_helpers;
13274 	ASSERT(help != NULL);
13275 
13276 	/*
13277 	 * If we already have dtrace_helper_providers_max helper providers,
13278 	 * we're refuse to add a new one.
13279 	 */
13280 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
13281 		return (ENOSPC);
13282 
13283 	/*
13284 	 * Check to make sure this isn't a duplicate.
13285 	 */
13286 	for (i = 0; i < help->dthps_nprovs; i++) {
13287 		if (dofhp->dofhp_addr ==
13288 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
13289 			return (EALREADY);
13290 	}
13291 
13292 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
13293 	hprov->dthp_prov = *dofhp;
13294 	hprov->dthp_ref = 1;
13295 	hprov->dthp_generation = gen;
13296 
13297 	/*
13298 	 * Allocate a bigger table for helper providers if it's already full.
13299 	 */
13300 	if (help->dthps_maxprovs == help->dthps_nprovs) {
13301 		tmp_maxprovs = help->dthps_maxprovs;
13302 		tmp_provs = help->dthps_provs;
13303 
13304 		if (help->dthps_maxprovs == 0)
13305 			help->dthps_maxprovs = 2;
13306 		else
13307 			help->dthps_maxprovs *= 2;
13308 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
13309 			help->dthps_maxprovs = dtrace_helper_providers_max;
13310 
13311 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
13312 
13313 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
13314 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13315 
13316 		if (tmp_provs != NULL) {
13317 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
13318 			    sizeof (dtrace_helper_provider_t *));
13319 			kmem_free(tmp_provs, tmp_maxprovs *
13320 			    sizeof (dtrace_helper_provider_t *));
13321 		}
13322 	}
13323 
13324 	help->dthps_provs[help->dthps_nprovs] = hprov;
13325 	help->dthps_nprovs++;
13326 
13327 	return (0);
13328 }
13329 
13330 static void
13331 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
13332 {
13333 	mutex_enter(&dtrace_lock);
13334 
13335 	if (--hprov->dthp_ref == 0) {
13336 		dof_hdr_t *dof;
13337 		mutex_exit(&dtrace_lock);
13338 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
13339 		dtrace_dof_destroy(dof);
13340 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
13341 	} else {
13342 		mutex_exit(&dtrace_lock);
13343 	}
13344 }
13345 
13346 static int
13347 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
13348 {
13349 	uintptr_t daddr = (uintptr_t)dof;
13350 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
13351 	dof_provider_t *provider;
13352 	dof_probe_t *probe;
13353 	uint8_t *arg;
13354 	char *strtab, *typestr;
13355 	dof_stridx_t typeidx;
13356 	size_t typesz;
13357 	uint_t nprobes, j, k;
13358 
13359 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
13360 
13361 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
13362 		dtrace_dof_error(dof, "misaligned section offset");
13363 		return (-1);
13364 	}
13365 
13366 	/*
13367 	 * The section needs to be large enough to contain the DOF provider
13368 	 * structure appropriate for the given version.
13369 	 */
13370 	if (sec->dofs_size <
13371 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
13372 	    offsetof(dof_provider_t, dofpv_prenoffs) :
13373 	    sizeof (dof_provider_t))) {
13374 		dtrace_dof_error(dof, "provider section too small");
13375 		return (-1);
13376 	}
13377 
13378 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
13379 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
13380 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
13381 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
13382 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
13383 
13384 	if (str_sec == NULL || prb_sec == NULL ||
13385 	    arg_sec == NULL || off_sec == NULL)
13386 		return (-1);
13387 
13388 	enoff_sec = NULL;
13389 
13390 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13391 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
13392 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
13393 	    provider->dofpv_prenoffs)) == NULL)
13394 		return (-1);
13395 
13396 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
13397 
13398 	if (provider->dofpv_name >= str_sec->dofs_size ||
13399 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
13400 		dtrace_dof_error(dof, "invalid provider name");
13401 		return (-1);
13402 	}
13403 
13404 	if (prb_sec->dofs_entsize == 0 ||
13405 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
13406 		dtrace_dof_error(dof, "invalid entry size");
13407 		return (-1);
13408 	}
13409 
13410 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
13411 		dtrace_dof_error(dof, "misaligned entry size");
13412 		return (-1);
13413 	}
13414 
13415 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
13416 		dtrace_dof_error(dof, "invalid entry size");
13417 		return (-1);
13418 	}
13419 
13420 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
13421 		dtrace_dof_error(dof, "misaligned section offset");
13422 		return (-1);
13423 	}
13424 
13425 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
13426 		dtrace_dof_error(dof, "invalid entry size");
13427 		return (-1);
13428 	}
13429 
13430 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
13431 
13432 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
13433 
13434 	/*
13435 	 * Take a pass through the probes to check for errors.
13436 	 */
13437 	for (j = 0; j < nprobes; j++) {
13438 		probe = (dof_probe_t *)(uintptr_t)(daddr +
13439 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
13440 
13441 		if (probe->dofpr_func >= str_sec->dofs_size) {
13442 			dtrace_dof_error(dof, "invalid function name");
13443 			return (-1);
13444 		}
13445 
13446 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
13447 			dtrace_dof_error(dof, "function name too long");
13448 			return (-1);
13449 		}
13450 
13451 		if (probe->dofpr_name >= str_sec->dofs_size ||
13452 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
13453 			dtrace_dof_error(dof, "invalid probe name");
13454 			return (-1);
13455 		}
13456 
13457 		/*
13458 		 * The offset count must not wrap the index, and the offsets
13459 		 * must also not overflow the section's data.
13460 		 */
13461 		if (probe->dofpr_offidx + probe->dofpr_noffs <
13462 		    probe->dofpr_offidx ||
13463 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
13464 		    off_sec->dofs_entsize > off_sec->dofs_size) {
13465 			dtrace_dof_error(dof, "invalid probe offset");
13466 			return (-1);
13467 		}
13468 
13469 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
13470 			/*
13471 			 * If there's no is-enabled offset section, make sure
13472 			 * there aren't any is-enabled offsets. Otherwise
13473 			 * perform the same checks as for probe offsets
13474 			 * (immediately above).
13475 			 */
13476 			if (enoff_sec == NULL) {
13477 				if (probe->dofpr_enoffidx != 0 ||
13478 				    probe->dofpr_nenoffs != 0) {
13479 					dtrace_dof_error(dof, "is-enabled "
13480 					    "offsets with null section");
13481 					return (-1);
13482 				}
13483 			} else if (probe->dofpr_enoffidx +
13484 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
13485 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
13486 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
13487 				dtrace_dof_error(dof, "invalid is-enabled "
13488 				    "offset");
13489 				return (-1);
13490 			}
13491 
13492 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
13493 				dtrace_dof_error(dof, "zero probe and "
13494 				    "is-enabled offsets");
13495 				return (-1);
13496 			}
13497 		} else if (probe->dofpr_noffs == 0) {
13498 			dtrace_dof_error(dof, "zero probe offsets");
13499 			return (-1);
13500 		}
13501 
13502 		if (probe->dofpr_argidx + probe->dofpr_xargc <
13503 		    probe->dofpr_argidx ||
13504 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
13505 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
13506 			dtrace_dof_error(dof, "invalid args");
13507 			return (-1);
13508 		}
13509 
13510 		typeidx = probe->dofpr_nargv;
13511 		typestr = strtab + probe->dofpr_nargv;
13512 		for (k = 0; k < probe->dofpr_nargc; k++) {
13513 			if (typeidx >= str_sec->dofs_size) {
13514 				dtrace_dof_error(dof, "bad "
13515 				    "native argument type");
13516 				return (-1);
13517 			}
13518 
13519 			typesz = strlen(typestr) + 1;
13520 			if (typesz > DTRACE_ARGTYPELEN) {
13521 				dtrace_dof_error(dof, "native "
13522 				    "argument type too long");
13523 				return (-1);
13524 			}
13525 			typeidx += typesz;
13526 			typestr += typesz;
13527 		}
13528 
13529 		typeidx = probe->dofpr_xargv;
13530 		typestr = strtab + probe->dofpr_xargv;
13531 		for (k = 0; k < probe->dofpr_xargc; k++) {
13532 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
13533 				dtrace_dof_error(dof, "bad "
13534 				    "native argument index");
13535 				return (-1);
13536 			}
13537 
13538 			if (typeidx >= str_sec->dofs_size) {
13539 				dtrace_dof_error(dof, "bad "
13540 				    "translated argument type");
13541 				return (-1);
13542 			}
13543 
13544 			typesz = strlen(typestr) + 1;
13545 			if (typesz > DTRACE_ARGTYPELEN) {
13546 				dtrace_dof_error(dof, "translated argument "
13547 				    "type too long");
13548 				return (-1);
13549 			}
13550 
13551 			typeidx += typesz;
13552 			typestr += typesz;
13553 		}
13554 	}
13555 
13556 	return (0);
13557 }
13558 
13559 static int
13560 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
13561 {
13562 	dtrace_helpers_t *help;
13563 	dtrace_vstate_t *vstate;
13564 	dtrace_enabling_t *enab = NULL;
13565 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
13566 	uintptr_t daddr = (uintptr_t)dof;
13567 
13568 	ASSERT(MUTEX_HELD(&dtrace_lock));
13569 
13570 	if ((help = curproc->p_dtrace_helpers) == NULL)
13571 		help = dtrace_helpers_create(curproc);
13572 
13573 	vstate = &help->dthps_vstate;
13574 
13575 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
13576 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
13577 		dtrace_dof_destroy(dof);
13578 		return (rv);
13579 	}
13580 
13581 	/*
13582 	 * Look for helper providers and validate their descriptions.
13583 	 */
13584 	if (dhp != NULL) {
13585 		for (i = 0; i < dof->dofh_secnum; i++) {
13586 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
13587 			    dof->dofh_secoff + i * dof->dofh_secsize);
13588 
13589 			if (sec->dofs_type != DOF_SECT_PROVIDER)
13590 				continue;
13591 
13592 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
13593 				dtrace_enabling_destroy(enab);
13594 				dtrace_dof_destroy(dof);
13595 				return (-1);
13596 			}
13597 
13598 			nprovs++;
13599 		}
13600 	}
13601 
13602 	/*
13603 	 * Now we need to walk through the ECB descriptions in the enabling.
13604 	 */
13605 	for (i = 0; i < enab->dten_ndesc; i++) {
13606 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
13607 		dtrace_probedesc_t *desc = &ep->dted_probe;
13608 
13609 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
13610 			continue;
13611 
13612 		if (strcmp(desc->dtpd_mod, "helper") != 0)
13613 			continue;
13614 
13615 		if (strcmp(desc->dtpd_func, "ustack") != 0)
13616 			continue;
13617 
13618 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
13619 		    ep)) != 0) {
13620 			/*
13621 			 * Adding this helper action failed -- we are now going
13622 			 * to rip out the entire generation and return failure.
13623 			 */
13624 			(void) dtrace_helper_destroygen(help->dthps_generation);
13625 			dtrace_enabling_destroy(enab);
13626 			dtrace_dof_destroy(dof);
13627 			return (-1);
13628 		}
13629 
13630 		nhelpers++;
13631 	}
13632 
13633 	if (nhelpers < enab->dten_ndesc)
13634 		dtrace_dof_error(dof, "unmatched helpers");
13635 
13636 	gen = help->dthps_generation++;
13637 	dtrace_enabling_destroy(enab);
13638 
13639 	if (dhp != NULL && nprovs > 0) {
13640 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
13641 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
13642 			mutex_exit(&dtrace_lock);
13643 			dtrace_helper_provider_register(curproc, help, dhp);
13644 			mutex_enter(&dtrace_lock);
13645 
13646 			destroy = 0;
13647 		}
13648 	}
13649 
13650 	if (destroy)
13651 		dtrace_dof_destroy(dof);
13652 
13653 	return (gen);
13654 }
13655 
13656 static dtrace_helpers_t *
13657 dtrace_helpers_create(proc_t *p)
13658 {
13659 	dtrace_helpers_t *help;
13660 
13661 	ASSERT(MUTEX_HELD(&dtrace_lock));
13662 	ASSERT(p->p_dtrace_helpers == NULL);
13663 
13664 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
13665 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
13666 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
13667 
13668 	p->p_dtrace_helpers = help;
13669 	dtrace_helpers++;
13670 
13671 	return (help);
13672 }
13673 
13674 static void
13675 dtrace_helpers_destroy(void)
13676 {
13677 	dtrace_helpers_t *help;
13678 	dtrace_vstate_t *vstate;
13679 	proc_t *p = curproc;
13680 	int i;
13681 
13682 	mutex_enter(&dtrace_lock);
13683 
13684 	ASSERT(p->p_dtrace_helpers != NULL);
13685 	ASSERT(dtrace_helpers > 0);
13686 
13687 	help = p->p_dtrace_helpers;
13688 	vstate = &help->dthps_vstate;
13689 
13690 	/*
13691 	 * We're now going to lose the help from this process.
13692 	 */
13693 	p->p_dtrace_helpers = NULL;
13694 	dtrace_sync();
13695 
13696 	/*
13697 	 * Destory the helper actions.
13698 	 */
13699 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13700 		dtrace_helper_action_t *h, *next;
13701 
13702 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13703 			next = h->dtha_next;
13704 			dtrace_helper_action_destroy(h, vstate);
13705 			h = next;
13706 		}
13707 	}
13708 
13709 	mutex_exit(&dtrace_lock);
13710 
13711 	/*
13712 	 * Destroy the helper providers.
13713 	 */
13714 	if (help->dthps_maxprovs > 0) {
13715 		mutex_enter(&dtrace_meta_lock);
13716 		if (dtrace_meta_pid != NULL) {
13717 			ASSERT(dtrace_deferred_pid == NULL);
13718 
13719 			for (i = 0; i < help->dthps_nprovs; i++) {
13720 				dtrace_helper_provider_remove(
13721 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
13722 			}
13723 		} else {
13724 			mutex_enter(&dtrace_lock);
13725 			ASSERT(help->dthps_deferred == 0 ||
13726 			    help->dthps_next != NULL ||
13727 			    help->dthps_prev != NULL ||
13728 			    help == dtrace_deferred_pid);
13729 
13730 			/*
13731 			 * Remove the helper from the deferred list.
13732 			 */
13733 			if (help->dthps_next != NULL)
13734 				help->dthps_next->dthps_prev = help->dthps_prev;
13735 			if (help->dthps_prev != NULL)
13736 				help->dthps_prev->dthps_next = help->dthps_next;
13737 			if (dtrace_deferred_pid == help) {
13738 				dtrace_deferred_pid = help->dthps_next;
13739 				ASSERT(help->dthps_prev == NULL);
13740 			}
13741 
13742 			mutex_exit(&dtrace_lock);
13743 		}
13744 
13745 		mutex_exit(&dtrace_meta_lock);
13746 
13747 		for (i = 0; i < help->dthps_nprovs; i++) {
13748 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
13749 		}
13750 
13751 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
13752 		    sizeof (dtrace_helper_provider_t *));
13753 	}
13754 
13755 	mutex_enter(&dtrace_lock);
13756 
13757 	dtrace_vstate_fini(&help->dthps_vstate);
13758 	kmem_free(help->dthps_actions,
13759 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
13760 	kmem_free(help, sizeof (dtrace_helpers_t));
13761 
13762 	--dtrace_helpers;
13763 	mutex_exit(&dtrace_lock);
13764 }
13765 
13766 static void
13767 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
13768 {
13769 	dtrace_helpers_t *help, *newhelp;
13770 	dtrace_helper_action_t *helper, *new, *last;
13771 	dtrace_difo_t *dp;
13772 	dtrace_vstate_t *vstate;
13773 	int i, j, sz, hasprovs = 0;
13774 
13775 	mutex_enter(&dtrace_lock);
13776 	ASSERT(from->p_dtrace_helpers != NULL);
13777 	ASSERT(dtrace_helpers > 0);
13778 
13779 	help = from->p_dtrace_helpers;
13780 	newhelp = dtrace_helpers_create(to);
13781 	ASSERT(to->p_dtrace_helpers != NULL);
13782 
13783 	newhelp->dthps_generation = help->dthps_generation;
13784 	vstate = &newhelp->dthps_vstate;
13785 
13786 	/*
13787 	 * Duplicate the helper actions.
13788 	 */
13789 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13790 		if ((helper = help->dthps_actions[i]) == NULL)
13791 			continue;
13792 
13793 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
13794 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
13795 			    KM_SLEEP);
13796 			new->dtha_generation = helper->dtha_generation;
13797 
13798 			if ((dp = helper->dtha_predicate) != NULL) {
13799 				dp = dtrace_difo_duplicate(dp, vstate);
13800 				new->dtha_predicate = dp;
13801 			}
13802 
13803 			new->dtha_nactions = helper->dtha_nactions;
13804 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
13805 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
13806 
13807 			for (j = 0; j < new->dtha_nactions; j++) {
13808 				dtrace_difo_t *dp = helper->dtha_actions[j];
13809 
13810 				ASSERT(dp != NULL);
13811 				dp = dtrace_difo_duplicate(dp, vstate);
13812 				new->dtha_actions[j] = dp;
13813 			}
13814 
13815 			if (last != NULL) {
13816 				last->dtha_next = new;
13817 			} else {
13818 				newhelp->dthps_actions[i] = new;
13819 			}
13820 
13821 			last = new;
13822 		}
13823 	}
13824 
13825 	/*
13826 	 * Duplicate the helper providers and register them with the
13827 	 * DTrace framework.
13828 	 */
13829 	if (help->dthps_nprovs > 0) {
13830 		newhelp->dthps_nprovs = help->dthps_nprovs;
13831 		newhelp->dthps_maxprovs = help->dthps_nprovs;
13832 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
13833 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13834 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
13835 			newhelp->dthps_provs[i] = help->dthps_provs[i];
13836 			newhelp->dthps_provs[i]->dthp_ref++;
13837 		}
13838 
13839 		hasprovs = 1;
13840 	}
13841 
13842 	mutex_exit(&dtrace_lock);
13843 
13844 	if (hasprovs)
13845 		dtrace_helper_provider_register(to, newhelp, NULL);
13846 }
13847 
13848 /*
13849  * DTrace Hook Functions
13850  */
13851 static void
13852 dtrace_module_loaded(struct modctl *ctl)
13853 {
13854 	dtrace_provider_t *prv;
13855 
13856 	mutex_enter(&dtrace_provider_lock);
13857 	mutex_enter(&mod_lock);
13858 
13859 	ASSERT(ctl->mod_busy);
13860 
13861 	/*
13862 	 * We're going to call each providers per-module provide operation
13863 	 * specifying only this module.
13864 	 */
13865 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
13866 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
13867 
13868 	mutex_exit(&mod_lock);
13869 	mutex_exit(&dtrace_provider_lock);
13870 
13871 	/*
13872 	 * If we have any retained enablings, we need to match against them.
13873 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
13874 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
13875 	 * module.  (In particular, this happens when loading scheduling
13876 	 * classes.)  So if we have any retained enablings, we need to dispatch
13877 	 * our task queue to do the match for us.
13878 	 */
13879 	mutex_enter(&dtrace_lock);
13880 
13881 	if (dtrace_retained == NULL) {
13882 		mutex_exit(&dtrace_lock);
13883 		return;
13884 	}
13885 
13886 	(void) taskq_dispatch(dtrace_taskq,
13887 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
13888 
13889 	mutex_exit(&dtrace_lock);
13890 
13891 	/*
13892 	 * And now, for a little heuristic sleaze:  in general, we want to
13893 	 * match modules as soon as they load.  However, we cannot guarantee
13894 	 * this, because it would lead us to the lock ordering violation
13895 	 * outlined above.  The common case, of course, is that cpu_lock is
13896 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
13897 	 * long enough for the task queue to do its work.  If it's not, it's
13898 	 * not a serious problem -- it just means that the module that we
13899 	 * just loaded may not be immediately instrumentable.
13900 	 */
13901 	delay(1);
13902 }
13903 
13904 static void
13905 dtrace_module_unloaded(struct modctl *ctl)
13906 {
13907 	dtrace_probe_t template, *probe, *first, *next;
13908 	dtrace_provider_t *prov;
13909 
13910 	template.dtpr_mod = ctl->mod_modname;
13911 
13912 	mutex_enter(&dtrace_provider_lock);
13913 	mutex_enter(&mod_lock);
13914 	mutex_enter(&dtrace_lock);
13915 
13916 	if (dtrace_bymod == NULL) {
13917 		/*
13918 		 * The DTrace module is loaded (obviously) but not attached;
13919 		 * we don't have any work to do.
13920 		 */
13921 		mutex_exit(&dtrace_provider_lock);
13922 		mutex_exit(&mod_lock);
13923 		mutex_exit(&dtrace_lock);
13924 		return;
13925 	}
13926 
13927 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
13928 	    probe != NULL; probe = probe->dtpr_nextmod) {
13929 		if (probe->dtpr_ecb != NULL) {
13930 			mutex_exit(&dtrace_provider_lock);
13931 			mutex_exit(&mod_lock);
13932 			mutex_exit(&dtrace_lock);
13933 
13934 			/*
13935 			 * This shouldn't _actually_ be possible -- we're
13936 			 * unloading a module that has an enabled probe in it.
13937 			 * (It's normally up to the provider to make sure that
13938 			 * this can't happen.)  However, because dtps_enable()
13939 			 * doesn't have a failure mode, there can be an
13940 			 * enable/unload race.  Upshot:  we don't want to
13941 			 * assert, but we're not going to disable the
13942 			 * probe, either.
13943 			 */
13944 			if (dtrace_err_verbose) {
13945 				cmn_err(CE_WARN, "unloaded module '%s' had "
13946 				    "enabled probes", ctl->mod_modname);
13947 			}
13948 
13949 			return;
13950 		}
13951 	}
13952 
13953 	probe = first;
13954 
13955 	for (first = NULL; probe != NULL; probe = next) {
13956 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
13957 
13958 		dtrace_probes[probe->dtpr_id - 1] = NULL;
13959 
13960 		next = probe->dtpr_nextmod;
13961 		dtrace_hash_remove(dtrace_bymod, probe);
13962 		dtrace_hash_remove(dtrace_byfunc, probe);
13963 		dtrace_hash_remove(dtrace_byname, probe);
13964 
13965 		if (first == NULL) {
13966 			first = probe;
13967 			probe->dtpr_nextmod = NULL;
13968 		} else {
13969 			probe->dtpr_nextmod = first;
13970 			first = probe;
13971 		}
13972 	}
13973 
13974 	/*
13975 	 * We've removed all of the module's probes from the hash chains and
13976 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
13977 	 * everyone has cleared out from any probe array processing.
13978 	 */
13979 	dtrace_sync();
13980 
13981 	for (probe = first; probe != NULL; probe = first) {
13982 		first = probe->dtpr_nextmod;
13983 		prov = probe->dtpr_provider;
13984 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
13985 		    probe->dtpr_arg);
13986 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
13987 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
13988 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
13989 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
13990 		kmem_free(probe, sizeof (dtrace_probe_t));
13991 	}
13992 
13993 	mutex_exit(&dtrace_lock);
13994 	mutex_exit(&mod_lock);
13995 	mutex_exit(&dtrace_provider_lock);
13996 }
13997 
13998 void
13999 dtrace_suspend(void)
14000 {
14001 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
14002 }
14003 
14004 void
14005 dtrace_resume(void)
14006 {
14007 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
14008 }
14009 
14010 static int
14011 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
14012 {
14013 	ASSERT(MUTEX_HELD(&cpu_lock));
14014 	mutex_enter(&dtrace_lock);
14015 
14016 	switch (what) {
14017 	case CPU_CONFIG: {
14018 		dtrace_state_t *state;
14019 		dtrace_optval_t *opt, rs, c;
14020 
14021 		/*
14022 		 * For now, we only allocate a new buffer for anonymous state.
14023 		 */
14024 		if ((state = dtrace_anon.dta_state) == NULL)
14025 			break;
14026 
14027 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14028 			break;
14029 
14030 		opt = state->dts_options;
14031 		c = opt[DTRACEOPT_CPU];
14032 
14033 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
14034 			break;
14035 
14036 		/*
14037 		 * Regardless of what the actual policy is, we're going to
14038 		 * temporarily set our resize policy to be manual.  We're
14039 		 * also going to temporarily set our CPU option to denote
14040 		 * the newly configured CPU.
14041 		 */
14042 		rs = opt[DTRACEOPT_BUFRESIZE];
14043 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
14044 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
14045 
14046 		(void) dtrace_state_buffers(state);
14047 
14048 		opt[DTRACEOPT_BUFRESIZE] = rs;
14049 		opt[DTRACEOPT_CPU] = c;
14050 
14051 		break;
14052 	}
14053 
14054 	case CPU_UNCONFIG:
14055 		/*
14056 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
14057 		 * buffer will be freed when the consumer exits.)
14058 		 */
14059 		break;
14060 
14061 	default:
14062 		break;
14063 	}
14064 
14065 	mutex_exit(&dtrace_lock);
14066 	return (0);
14067 }
14068 
14069 static void
14070 dtrace_cpu_setup_initial(processorid_t cpu)
14071 {
14072 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
14073 }
14074 
14075 static void
14076 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
14077 {
14078 	if (dtrace_toxranges >= dtrace_toxranges_max) {
14079 		int osize, nsize;
14080 		dtrace_toxrange_t *range;
14081 
14082 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14083 
14084 		if (osize == 0) {
14085 			ASSERT(dtrace_toxrange == NULL);
14086 			ASSERT(dtrace_toxranges_max == 0);
14087 			dtrace_toxranges_max = 1;
14088 		} else {
14089 			dtrace_toxranges_max <<= 1;
14090 		}
14091 
14092 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14093 		range = kmem_zalloc(nsize, KM_SLEEP);
14094 
14095 		if (dtrace_toxrange != NULL) {
14096 			ASSERT(osize != 0);
14097 			bcopy(dtrace_toxrange, range, osize);
14098 			kmem_free(dtrace_toxrange, osize);
14099 		}
14100 
14101 		dtrace_toxrange = range;
14102 	}
14103 
14104 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
14105 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
14106 
14107 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
14108 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
14109 	dtrace_toxranges++;
14110 }
14111 
14112 /*
14113  * DTrace Driver Cookbook Functions
14114  */
14115 /*ARGSUSED*/
14116 static int
14117 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
14118 {
14119 	dtrace_provider_id_t id;
14120 	dtrace_state_t *state = NULL;
14121 	dtrace_enabling_t *enab;
14122 
14123 	mutex_enter(&cpu_lock);
14124 	mutex_enter(&dtrace_provider_lock);
14125 	mutex_enter(&dtrace_lock);
14126 
14127 	if (ddi_soft_state_init(&dtrace_softstate,
14128 	    sizeof (dtrace_state_t), 0) != 0) {
14129 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
14130 		mutex_exit(&cpu_lock);
14131 		mutex_exit(&dtrace_provider_lock);
14132 		mutex_exit(&dtrace_lock);
14133 		return (DDI_FAILURE);
14134 	}
14135 
14136 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
14137 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
14138 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
14139 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
14140 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
14141 		ddi_remove_minor_node(devi, NULL);
14142 		ddi_soft_state_fini(&dtrace_softstate);
14143 		mutex_exit(&cpu_lock);
14144 		mutex_exit(&dtrace_provider_lock);
14145 		mutex_exit(&dtrace_lock);
14146 		return (DDI_FAILURE);
14147 	}
14148 
14149 	ddi_report_dev(devi);
14150 	dtrace_devi = devi;
14151 
14152 	dtrace_modload = dtrace_module_loaded;
14153 	dtrace_modunload = dtrace_module_unloaded;
14154 	dtrace_cpu_init = dtrace_cpu_setup_initial;
14155 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
14156 	dtrace_helpers_fork = dtrace_helpers_duplicate;
14157 	dtrace_cpustart_init = dtrace_suspend;
14158 	dtrace_cpustart_fini = dtrace_resume;
14159 	dtrace_debugger_init = dtrace_suspend;
14160 	dtrace_debugger_fini = dtrace_resume;
14161 
14162 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
14163 
14164 	ASSERT(MUTEX_HELD(&cpu_lock));
14165 
14166 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
14167 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14168 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
14169 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
14170 	    VM_SLEEP | VMC_IDENTIFIER);
14171 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
14172 	    1, INT_MAX, 0);
14173 
14174 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
14175 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
14176 	    NULL, NULL, NULL, NULL, NULL, 0);
14177 
14178 	ASSERT(MUTEX_HELD(&cpu_lock));
14179 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
14180 	    offsetof(dtrace_probe_t, dtpr_nextmod),
14181 	    offsetof(dtrace_probe_t, dtpr_prevmod));
14182 
14183 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
14184 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
14185 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
14186 
14187 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
14188 	    offsetof(dtrace_probe_t, dtpr_nextname),
14189 	    offsetof(dtrace_probe_t, dtpr_prevname));
14190 
14191 	if (dtrace_retain_max < 1) {
14192 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
14193 		    "setting to 1", dtrace_retain_max);
14194 		dtrace_retain_max = 1;
14195 	}
14196 
14197 	/*
14198 	 * Now discover our toxic ranges.
14199 	 */
14200 	dtrace_toxic_ranges(dtrace_toxrange_add);
14201 
14202 	/*
14203 	 * Before we register ourselves as a provider to our own framework,
14204 	 * we would like to assert that dtrace_provider is NULL -- but that's
14205 	 * not true if we were loaded as a dependency of a DTrace provider.
14206 	 * Once we've registered, we can assert that dtrace_provider is our
14207 	 * pseudo provider.
14208 	 */
14209 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
14210 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
14211 
14212 	ASSERT(dtrace_provider != NULL);
14213 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
14214 
14215 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
14216 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
14217 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
14218 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
14219 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
14220 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
14221 
14222 	dtrace_anon_property();
14223 	mutex_exit(&cpu_lock);
14224 
14225 	/*
14226 	 * If DTrace helper tracing is enabled, we need to allocate the
14227 	 * trace buffer and initialize the values.
14228 	 */
14229 	if (dtrace_helptrace_enabled) {
14230 		ASSERT(dtrace_helptrace_buffer == NULL);
14231 		dtrace_helptrace_buffer =
14232 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
14233 		dtrace_helptrace_next = 0;
14234 	}
14235 
14236 	/*
14237 	 * If there are already providers, we must ask them to provide their
14238 	 * probes, and then match any anonymous enabling against them.  Note
14239 	 * that there should be no other retained enablings at this time:
14240 	 * the only retained enablings at this time should be the anonymous
14241 	 * enabling.
14242 	 */
14243 	if (dtrace_anon.dta_enabling != NULL) {
14244 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
14245 
14246 		dtrace_enabling_provide(NULL);
14247 		state = dtrace_anon.dta_state;
14248 
14249 		/*
14250 		 * We couldn't hold cpu_lock across the above call to
14251 		 * dtrace_enabling_provide(), but we must hold it to actually
14252 		 * enable the probes.  We have to drop all of our locks, pick
14253 		 * up cpu_lock, and regain our locks before matching the
14254 		 * retained anonymous enabling.
14255 		 */
14256 		mutex_exit(&dtrace_lock);
14257 		mutex_exit(&dtrace_provider_lock);
14258 
14259 		mutex_enter(&cpu_lock);
14260 		mutex_enter(&dtrace_provider_lock);
14261 		mutex_enter(&dtrace_lock);
14262 
14263 		if ((enab = dtrace_anon.dta_enabling) != NULL)
14264 			(void) dtrace_enabling_match(enab, NULL);
14265 
14266 		mutex_exit(&cpu_lock);
14267 	}
14268 
14269 	mutex_exit(&dtrace_lock);
14270 	mutex_exit(&dtrace_provider_lock);
14271 
14272 	if (state != NULL) {
14273 		/*
14274 		 * If we created any anonymous state, set it going now.
14275 		 */
14276 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
14277 	}
14278 
14279 	return (DDI_SUCCESS);
14280 }
14281 
14282 /*ARGSUSED*/
14283 static int
14284 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
14285 {
14286 	dtrace_state_t *state;
14287 	uint32_t priv;
14288 	uid_t uid;
14289 	zoneid_t zoneid;
14290 
14291 	if (getminor(*devp) == DTRACEMNRN_HELPER)
14292 		return (0);
14293 
14294 	/*
14295 	 * If this wasn't an open with the "helper" minor, then it must be
14296 	 * the "dtrace" minor.
14297 	 */
14298 	ASSERT(getminor(*devp) == DTRACEMNRN_DTRACE);
14299 
14300 	/*
14301 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
14302 	 * caller lacks sufficient permission to do anything with DTrace.
14303 	 */
14304 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
14305 	if (priv == DTRACE_PRIV_NONE)
14306 		return (EACCES);
14307 
14308 	/*
14309 	 * Ask all providers to provide all their probes.
14310 	 */
14311 	mutex_enter(&dtrace_provider_lock);
14312 	dtrace_probe_provide(NULL, NULL);
14313 	mutex_exit(&dtrace_provider_lock);
14314 
14315 	mutex_enter(&cpu_lock);
14316 	mutex_enter(&dtrace_lock);
14317 	dtrace_opens++;
14318 	dtrace_membar_producer();
14319 
14320 	/*
14321 	 * If the kernel debugger is active (that is, if the kernel debugger
14322 	 * modified text in some way), we won't allow the open.
14323 	 */
14324 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14325 		dtrace_opens--;
14326 		mutex_exit(&cpu_lock);
14327 		mutex_exit(&dtrace_lock);
14328 		return (EBUSY);
14329 	}
14330 
14331 	state = dtrace_state_create(devp, cred_p);
14332 	mutex_exit(&cpu_lock);
14333 
14334 	if (state == NULL) {
14335 		if (--dtrace_opens == 0)
14336 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14337 		mutex_exit(&dtrace_lock);
14338 		return (EAGAIN);
14339 	}
14340 
14341 	mutex_exit(&dtrace_lock);
14342 
14343 	return (0);
14344 }
14345 
14346 /*ARGSUSED*/
14347 static int
14348 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
14349 {
14350 	minor_t minor = getminor(dev);
14351 	dtrace_state_t *state;
14352 
14353 	if (minor == DTRACEMNRN_HELPER)
14354 		return (0);
14355 
14356 	state = ddi_get_soft_state(dtrace_softstate, minor);
14357 
14358 	mutex_enter(&cpu_lock);
14359 	mutex_enter(&dtrace_lock);
14360 
14361 	if (state->dts_anon) {
14362 		/*
14363 		 * There is anonymous state. Destroy that first.
14364 		 */
14365 		ASSERT(dtrace_anon.dta_state == NULL);
14366 		dtrace_state_destroy(state->dts_anon);
14367 	}
14368 
14369 	dtrace_state_destroy(state);
14370 	ASSERT(dtrace_opens > 0);
14371 	if (--dtrace_opens == 0)
14372 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14373 
14374 	mutex_exit(&dtrace_lock);
14375 	mutex_exit(&cpu_lock);
14376 
14377 	return (0);
14378 }
14379 
14380 /*ARGSUSED*/
14381 static int
14382 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
14383 {
14384 	int rval;
14385 	dof_helper_t help, *dhp = NULL;
14386 
14387 	switch (cmd) {
14388 	case DTRACEHIOC_ADDDOF:
14389 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
14390 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
14391 			return (EFAULT);
14392 		}
14393 
14394 		dhp = &help;
14395 		arg = (intptr_t)help.dofhp_dof;
14396 		/*FALLTHROUGH*/
14397 
14398 	case DTRACEHIOC_ADD: {
14399 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
14400 
14401 		if (dof == NULL)
14402 			return (rval);
14403 
14404 		mutex_enter(&dtrace_lock);
14405 
14406 		/*
14407 		 * dtrace_helper_slurp() takes responsibility for the dof --
14408 		 * it may free it now or it may save it and free it later.
14409 		 */
14410 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
14411 			*rv = rval;
14412 			rval = 0;
14413 		} else {
14414 			rval = EINVAL;
14415 		}
14416 
14417 		mutex_exit(&dtrace_lock);
14418 		return (rval);
14419 	}
14420 
14421 	case DTRACEHIOC_REMOVE: {
14422 		mutex_enter(&dtrace_lock);
14423 		rval = dtrace_helper_destroygen(arg);
14424 		mutex_exit(&dtrace_lock);
14425 
14426 		return (rval);
14427 	}
14428 
14429 	default:
14430 		break;
14431 	}
14432 
14433 	return (ENOTTY);
14434 }
14435 
14436 /*ARGSUSED*/
14437 static int
14438 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
14439 {
14440 	minor_t minor = getminor(dev);
14441 	dtrace_state_t *state;
14442 	int rval;
14443 
14444 	if (minor == DTRACEMNRN_HELPER)
14445 		return (dtrace_ioctl_helper(cmd, arg, rv));
14446 
14447 	state = ddi_get_soft_state(dtrace_softstate, minor);
14448 
14449 	if (state->dts_anon) {
14450 		ASSERT(dtrace_anon.dta_state == NULL);
14451 		state = state->dts_anon;
14452 	}
14453 
14454 	switch (cmd) {
14455 	case DTRACEIOC_PROVIDER: {
14456 		dtrace_providerdesc_t pvd;
14457 		dtrace_provider_t *pvp;
14458 
14459 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
14460 			return (EFAULT);
14461 
14462 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
14463 		mutex_enter(&dtrace_provider_lock);
14464 
14465 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
14466 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
14467 				break;
14468 		}
14469 
14470 		mutex_exit(&dtrace_provider_lock);
14471 
14472 		if (pvp == NULL)
14473 			return (ESRCH);
14474 
14475 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
14476 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
14477 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
14478 			return (EFAULT);
14479 
14480 		return (0);
14481 	}
14482 
14483 	case DTRACEIOC_EPROBE: {
14484 		dtrace_eprobedesc_t epdesc;
14485 		dtrace_ecb_t *ecb;
14486 		dtrace_action_t *act;
14487 		void *buf;
14488 		size_t size;
14489 		uintptr_t dest;
14490 		int nrecs;
14491 
14492 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
14493 			return (EFAULT);
14494 
14495 		mutex_enter(&dtrace_lock);
14496 
14497 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
14498 			mutex_exit(&dtrace_lock);
14499 			return (EINVAL);
14500 		}
14501 
14502 		if (ecb->dte_probe == NULL) {
14503 			mutex_exit(&dtrace_lock);
14504 			return (EINVAL);
14505 		}
14506 
14507 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
14508 		epdesc.dtepd_uarg = ecb->dte_uarg;
14509 		epdesc.dtepd_size = ecb->dte_size;
14510 
14511 		nrecs = epdesc.dtepd_nrecs;
14512 		epdesc.dtepd_nrecs = 0;
14513 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
14514 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
14515 				continue;
14516 
14517 			epdesc.dtepd_nrecs++;
14518 		}
14519 
14520 		/*
14521 		 * Now that we have the size, we need to allocate a temporary
14522 		 * buffer in which to store the complete description.  We need
14523 		 * the temporary buffer to be able to drop dtrace_lock()
14524 		 * across the copyout(), below.
14525 		 */
14526 		size = sizeof (dtrace_eprobedesc_t) +
14527 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
14528 
14529 		buf = kmem_alloc(size, KM_SLEEP);
14530 		dest = (uintptr_t)buf;
14531 
14532 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
14533 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
14534 
14535 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
14536 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
14537 				continue;
14538 
14539 			if (nrecs-- == 0)
14540 				break;
14541 
14542 			bcopy(&act->dta_rec, (void *)dest,
14543 			    sizeof (dtrace_recdesc_t));
14544 			dest += sizeof (dtrace_recdesc_t);
14545 		}
14546 
14547 		mutex_exit(&dtrace_lock);
14548 
14549 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
14550 			kmem_free(buf, size);
14551 			return (EFAULT);
14552 		}
14553 
14554 		kmem_free(buf, size);
14555 		return (0);
14556 	}
14557 
14558 	case DTRACEIOC_AGGDESC: {
14559 		dtrace_aggdesc_t aggdesc;
14560 		dtrace_action_t *act;
14561 		dtrace_aggregation_t *agg;
14562 		int nrecs;
14563 		uint32_t offs;
14564 		dtrace_recdesc_t *lrec;
14565 		void *buf;
14566 		size_t size;
14567 		uintptr_t dest;
14568 
14569 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
14570 			return (EFAULT);
14571 
14572 		mutex_enter(&dtrace_lock);
14573 
14574 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
14575 			mutex_exit(&dtrace_lock);
14576 			return (EINVAL);
14577 		}
14578 
14579 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
14580 
14581 		nrecs = aggdesc.dtagd_nrecs;
14582 		aggdesc.dtagd_nrecs = 0;
14583 
14584 		offs = agg->dtag_base;
14585 		lrec = &agg->dtag_action.dta_rec;
14586 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
14587 
14588 		for (act = agg->dtag_first; ; act = act->dta_next) {
14589 			ASSERT(act->dta_intuple ||
14590 			    DTRACEACT_ISAGG(act->dta_kind));
14591 
14592 			/*
14593 			 * If this action has a record size of zero, it
14594 			 * denotes an argument to the aggregating action.
14595 			 * Because the presence of this record doesn't (or
14596 			 * shouldn't) affect the way the data is interpreted,
14597 			 * we don't copy it out to save user-level the
14598 			 * confusion of dealing with a zero-length record.
14599 			 */
14600 			if (act->dta_rec.dtrd_size == 0) {
14601 				ASSERT(agg->dtag_hasarg);
14602 				continue;
14603 			}
14604 
14605 			aggdesc.dtagd_nrecs++;
14606 
14607 			if (act == &agg->dtag_action)
14608 				break;
14609 		}
14610 
14611 		/*
14612 		 * Now that we have the size, we need to allocate a temporary
14613 		 * buffer in which to store the complete description.  We need
14614 		 * the temporary buffer to be able to drop dtrace_lock()
14615 		 * across the copyout(), below.
14616 		 */
14617 		size = sizeof (dtrace_aggdesc_t) +
14618 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
14619 
14620 		buf = kmem_alloc(size, KM_SLEEP);
14621 		dest = (uintptr_t)buf;
14622 
14623 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
14624 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
14625 
14626 		for (act = agg->dtag_first; ; act = act->dta_next) {
14627 			dtrace_recdesc_t rec = act->dta_rec;
14628 
14629 			/*
14630 			 * See the comment in the above loop for why we pass
14631 			 * over zero-length records.
14632 			 */
14633 			if (rec.dtrd_size == 0) {
14634 				ASSERT(agg->dtag_hasarg);
14635 				continue;
14636 			}
14637 
14638 			if (nrecs-- == 0)
14639 				break;
14640 
14641 			rec.dtrd_offset -= offs;
14642 			bcopy(&rec, (void *)dest, sizeof (rec));
14643 			dest += sizeof (dtrace_recdesc_t);
14644 
14645 			if (act == &agg->dtag_action)
14646 				break;
14647 		}
14648 
14649 		mutex_exit(&dtrace_lock);
14650 
14651 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
14652 			kmem_free(buf, size);
14653 			return (EFAULT);
14654 		}
14655 
14656 		kmem_free(buf, size);
14657 		return (0);
14658 	}
14659 
14660 	case DTRACEIOC_ENABLE: {
14661 		dof_hdr_t *dof;
14662 		dtrace_enabling_t *enab = NULL;
14663 		dtrace_vstate_t *vstate;
14664 		int err = 0;
14665 
14666 		*rv = 0;
14667 
14668 		/*
14669 		 * If a NULL argument has been passed, we take this as our
14670 		 * cue to reevaluate our enablings.
14671 		 */
14672 		if (arg == NULL) {
14673 			mutex_enter(&cpu_lock);
14674 			mutex_enter(&dtrace_lock);
14675 			err = dtrace_enabling_matchstate(state, rv);
14676 			mutex_exit(&dtrace_lock);
14677 			mutex_exit(&cpu_lock);
14678 
14679 			return (err);
14680 		}
14681 
14682 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
14683 			return (rval);
14684 
14685 		mutex_enter(&cpu_lock);
14686 		mutex_enter(&dtrace_lock);
14687 		vstate = &state->dts_vstate;
14688 
14689 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14690 			mutex_exit(&dtrace_lock);
14691 			mutex_exit(&cpu_lock);
14692 			dtrace_dof_destroy(dof);
14693 			return (EBUSY);
14694 		}
14695 
14696 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
14697 			mutex_exit(&dtrace_lock);
14698 			mutex_exit(&cpu_lock);
14699 			dtrace_dof_destroy(dof);
14700 			return (EINVAL);
14701 		}
14702 
14703 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
14704 			dtrace_enabling_destroy(enab);
14705 			mutex_exit(&dtrace_lock);
14706 			mutex_exit(&cpu_lock);
14707 			dtrace_dof_destroy(dof);
14708 			return (rval);
14709 		}
14710 
14711 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
14712 			err = dtrace_enabling_retain(enab);
14713 		} else {
14714 			dtrace_enabling_destroy(enab);
14715 		}
14716 
14717 		mutex_exit(&cpu_lock);
14718 		mutex_exit(&dtrace_lock);
14719 		dtrace_dof_destroy(dof);
14720 
14721 		return (err);
14722 	}
14723 
14724 	case DTRACEIOC_REPLICATE: {
14725 		dtrace_repldesc_t desc;
14726 		dtrace_probedesc_t *match = &desc.dtrpd_match;
14727 		dtrace_probedesc_t *create = &desc.dtrpd_create;
14728 		int err;
14729 
14730 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14731 			return (EFAULT);
14732 
14733 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14734 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14735 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14736 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14737 
14738 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14739 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14740 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14741 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14742 
14743 		mutex_enter(&dtrace_lock);
14744 		err = dtrace_enabling_replicate(state, match, create);
14745 		mutex_exit(&dtrace_lock);
14746 
14747 		return (err);
14748 	}
14749 
14750 	case DTRACEIOC_PROBEMATCH:
14751 	case DTRACEIOC_PROBES: {
14752 		dtrace_probe_t *probe = NULL;
14753 		dtrace_probedesc_t desc;
14754 		dtrace_probekey_t pkey;
14755 		dtrace_id_t i;
14756 		int m = 0;
14757 		uint32_t priv;
14758 		uid_t uid;
14759 		zoneid_t zoneid;
14760 
14761 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14762 			return (EFAULT);
14763 
14764 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14765 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14766 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14767 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14768 
14769 		/*
14770 		 * Before we attempt to match this probe, we want to give
14771 		 * all providers the opportunity to provide it.
14772 		 */
14773 		if (desc.dtpd_id == DTRACE_IDNONE) {
14774 			mutex_enter(&dtrace_provider_lock);
14775 			dtrace_probe_provide(&desc, NULL);
14776 			mutex_exit(&dtrace_provider_lock);
14777 			desc.dtpd_id++;
14778 		}
14779 
14780 		if (cmd == DTRACEIOC_PROBEMATCH)  {
14781 			dtrace_probekey(&desc, &pkey);
14782 			pkey.dtpk_id = DTRACE_IDNONE;
14783 		}
14784 
14785 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
14786 
14787 		mutex_enter(&dtrace_lock);
14788 
14789 		if (cmd == DTRACEIOC_PROBEMATCH) {
14790 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14791 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14792 				    (m = dtrace_match_probe(probe, &pkey,
14793 				    priv, uid, zoneid)) != 0)
14794 					break;
14795 			}
14796 
14797 			if (m < 0) {
14798 				mutex_exit(&dtrace_lock);
14799 				return (EINVAL);
14800 			}
14801 
14802 		} else {
14803 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14804 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14805 				    dtrace_match_priv(probe, priv, uid, zoneid))
14806 					break;
14807 			}
14808 		}
14809 
14810 		if (probe == NULL) {
14811 			mutex_exit(&dtrace_lock);
14812 			return (ESRCH);
14813 		}
14814 
14815 		dtrace_probe_description(probe, &desc);
14816 		mutex_exit(&dtrace_lock);
14817 
14818 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14819 			return (EFAULT);
14820 
14821 		return (0);
14822 	}
14823 
14824 	case DTRACEIOC_PROBEARG: {
14825 		dtrace_argdesc_t desc;
14826 		dtrace_probe_t *probe;
14827 		dtrace_provider_t *prov;
14828 
14829 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14830 			return (EFAULT);
14831 
14832 		if (desc.dtargd_id == DTRACE_IDNONE)
14833 			return (EINVAL);
14834 
14835 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
14836 			return (EINVAL);
14837 
14838 		mutex_enter(&dtrace_provider_lock);
14839 		mutex_enter(&mod_lock);
14840 		mutex_enter(&dtrace_lock);
14841 
14842 		if (desc.dtargd_id > dtrace_nprobes) {
14843 			mutex_exit(&dtrace_lock);
14844 			mutex_exit(&mod_lock);
14845 			mutex_exit(&dtrace_provider_lock);
14846 			return (EINVAL);
14847 		}
14848 
14849 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
14850 			mutex_exit(&dtrace_lock);
14851 			mutex_exit(&mod_lock);
14852 			mutex_exit(&dtrace_provider_lock);
14853 			return (EINVAL);
14854 		}
14855 
14856 		mutex_exit(&dtrace_lock);
14857 
14858 		prov = probe->dtpr_provider;
14859 
14860 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
14861 			/*
14862 			 * There isn't any typed information for this probe.
14863 			 * Set the argument number to DTRACE_ARGNONE.
14864 			 */
14865 			desc.dtargd_ndx = DTRACE_ARGNONE;
14866 		} else {
14867 			desc.dtargd_native[0] = '\0';
14868 			desc.dtargd_xlate[0] = '\0';
14869 			desc.dtargd_mapping = desc.dtargd_ndx;
14870 
14871 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
14872 			    probe->dtpr_id, probe->dtpr_arg, &desc);
14873 		}
14874 
14875 		mutex_exit(&mod_lock);
14876 		mutex_exit(&dtrace_provider_lock);
14877 
14878 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14879 			return (EFAULT);
14880 
14881 		return (0);
14882 	}
14883 
14884 	case DTRACEIOC_GO: {
14885 		processorid_t cpuid;
14886 		rval = dtrace_state_go(state, &cpuid);
14887 
14888 		if (rval != 0)
14889 			return (rval);
14890 
14891 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14892 			return (EFAULT);
14893 
14894 		return (0);
14895 	}
14896 
14897 	case DTRACEIOC_STOP: {
14898 		processorid_t cpuid;
14899 
14900 		mutex_enter(&dtrace_lock);
14901 		rval = dtrace_state_stop(state, &cpuid);
14902 		mutex_exit(&dtrace_lock);
14903 
14904 		if (rval != 0)
14905 			return (rval);
14906 
14907 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14908 			return (EFAULT);
14909 
14910 		return (0);
14911 	}
14912 
14913 	case DTRACEIOC_DOFGET: {
14914 		dof_hdr_t hdr, *dof;
14915 		uint64_t len;
14916 
14917 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
14918 			return (EFAULT);
14919 
14920 		mutex_enter(&dtrace_lock);
14921 		dof = dtrace_dof_create(state);
14922 		mutex_exit(&dtrace_lock);
14923 
14924 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
14925 		rval = copyout(dof, (void *)arg, len);
14926 		dtrace_dof_destroy(dof);
14927 
14928 		return (rval == 0 ? 0 : EFAULT);
14929 	}
14930 
14931 	case DTRACEIOC_AGGSNAP:
14932 	case DTRACEIOC_BUFSNAP: {
14933 		dtrace_bufdesc_t desc;
14934 		caddr_t cached;
14935 		dtrace_buffer_t *buf;
14936 
14937 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14938 			return (EFAULT);
14939 
14940 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
14941 			return (EINVAL);
14942 
14943 		mutex_enter(&dtrace_lock);
14944 
14945 		if (cmd == DTRACEIOC_BUFSNAP) {
14946 			buf = &state->dts_buffer[desc.dtbd_cpu];
14947 		} else {
14948 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
14949 		}
14950 
14951 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
14952 			size_t sz = buf->dtb_offset;
14953 
14954 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
14955 				mutex_exit(&dtrace_lock);
14956 				return (EBUSY);
14957 			}
14958 
14959 			/*
14960 			 * If this buffer has already been consumed, we're
14961 			 * going to indicate that there's nothing left here
14962 			 * to consume.
14963 			 */
14964 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
14965 				mutex_exit(&dtrace_lock);
14966 
14967 				desc.dtbd_size = 0;
14968 				desc.dtbd_drops = 0;
14969 				desc.dtbd_errors = 0;
14970 				desc.dtbd_oldest = 0;
14971 				sz = sizeof (desc);
14972 
14973 				if (copyout(&desc, (void *)arg, sz) != 0)
14974 					return (EFAULT);
14975 
14976 				return (0);
14977 			}
14978 
14979 			/*
14980 			 * If this is a ring buffer that has wrapped, we want
14981 			 * to copy the whole thing out.
14982 			 */
14983 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
14984 				dtrace_buffer_polish(buf);
14985 				sz = buf->dtb_size;
14986 			}
14987 
14988 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
14989 				mutex_exit(&dtrace_lock);
14990 				return (EFAULT);
14991 			}
14992 
14993 			desc.dtbd_size = sz;
14994 			desc.dtbd_drops = buf->dtb_drops;
14995 			desc.dtbd_errors = buf->dtb_errors;
14996 			desc.dtbd_oldest = buf->dtb_xamot_offset;
14997 
14998 			mutex_exit(&dtrace_lock);
14999 
15000 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15001 				return (EFAULT);
15002 
15003 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
15004 
15005 			return (0);
15006 		}
15007 
15008 		if (buf->dtb_tomax == NULL) {
15009 			ASSERT(buf->dtb_xamot == NULL);
15010 			mutex_exit(&dtrace_lock);
15011 			return (ENOENT);
15012 		}
15013 
15014 		cached = buf->dtb_tomax;
15015 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
15016 
15017 		dtrace_xcall(desc.dtbd_cpu,
15018 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
15019 
15020 		state->dts_errors += buf->dtb_xamot_errors;
15021 
15022 		/*
15023 		 * If the buffers did not actually switch, then the cross call
15024 		 * did not take place -- presumably because the given CPU is
15025 		 * not in the ready set.  If this is the case, we'll return
15026 		 * ENOENT.
15027 		 */
15028 		if (buf->dtb_tomax == cached) {
15029 			ASSERT(buf->dtb_xamot != cached);
15030 			mutex_exit(&dtrace_lock);
15031 			return (ENOENT);
15032 		}
15033 
15034 		ASSERT(cached == buf->dtb_xamot);
15035 
15036 		/*
15037 		 * We have our snapshot; now copy it out.
15038 		 */
15039 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
15040 		    buf->dtb_xamot_offset) != 0) {
15041 			mutex_exit(&dtrace_lock);
15042 			return (EFAULT);
15043 		}
15044 
15045 		desc.dtbd_size = buf->dtb_xamot_offset;
15046 		desc.dtbd_drops = buf->dtb_xamot_drops;
15047 		desc.dtbd_errors = buf->dtb_xamot_errors;
15048 		desc.dtbd_oldest = 0;
15049 
15050 		mutex_exit(&dtrace_lock);
15051 
15052 		/*
15053 		 * Finally, copy out the buffer description.
15054 		 */
15055 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15056 			return (EFAULT);
15057 
15058 		return (0);
15059 	}
15060 
15061 	case DTRACEIOC_CONF: {
15062 		dtrace_conf_t conf;
15063 
15064 		bzero(&conf, sizeof (conf));
15065 		conf.dtc_difversion = DIF_VERSION;
15066 		conf.dtc_difintregs = DIF_DIR_NREGS;
15067 		conf.dtc_diftupregs = DIF_DTR_NREGS;
15068 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
15069 
15070 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
15071 			return (EFAULT);
15072 
15073 		return (0);
15074 	}
15075 
15076 	case DTRACEIOC_STATUS: {
15077 		dtrace_status_t stat;
15078 		dtrace_dstate_t *dstate;
15079 		int i, j;
15080 		uint64_t nerrs;
15081 
15082 		/*
15083 		 * See the comment in dtrace_state_deadman() for the reason
15084 		 * for setting dts_laststatus to INT64_MAX before setting
15085 		 * it to the correct value.
15086 		 */
15087 		state->dts_laststatus = INT64_MAX;
15088 		dtrace_membar_producer();
15089 		state->dts_laststatus = dtrace_gethrtime();
15090 
15091 		bzero(&stat, sizeof (stat));
15092 
15093 		mutex_enter(&dtrace_lock);
15094 
15095 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
15096 			mutex_exit(&dtrace_lock);
15097 			return (ENOENT);
15098 		}
15099 
15100 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
15101 			stat.dtst_exiting = 1;
15102 
15103 		nerrs = state->dts_errors;
15104 		dstate = &state->dts_vstate.dtvs_dynvars;
15105 
15106 		for (i = 0; i < NCPU; i++) {
15107 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
15108 
15109 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
15110 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
15111 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
15112 
15113 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
15114 				stat.dtst_filled++;
15115 
15116 			nerrs += state->dts_buffer[i].dtb_errors;
15117 
15118 			for (j = 0; j < state->dts_nspeculations; j++) {
15119 				dtrace_speculation_t *spec;
15120 				dtrace_buffer_t *buf;
15121 
15122 				spec = &state->dts_speculations[j];
15123 				buf = &spec->dtsp_buffer[i];
15124 				stat.dtst_specdrops += buf->dtb_xamot_drops;
15125 			}
15126 		}
15127 
15128 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
15129 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
15130 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
15131 		stat.dtst_dblerrors = state->dts_dblerrors;
15132 		stat.dtst_killed =
15133 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
15134 		stat.dtst_errors = nerrs;
15135 
15136 		mutex_exit(&dtrace_lock);
15137 
15138 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
15139 			return (EFAULT);
15140 
15141 		return (0);
15142 	}
15143 
15144 	case DTRACEIOC_FORMAT: {
15145 		dtrace_fmtdesc_t fmt;
15146 		char *str;
15147 		int len;
15148 
15149 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
15150 			return (EFAULT);
15151 
15152 		mutex_enter(&dtrace_lock);
15153 
15154 		if (fmt.dtfd_format == 0 ||
15155 		    fmt.dtfd_format > state->dts_nformats) {
15156 			mutex_exit(&dtrace_lock);
15157 			return (EINVAL);
15158 		}
15159 
15160 		/*
15161 		 * Format strings are allocated contiguously and they are
15162 		 * never freed; if a format index is less than the number
15163 		 * of formats, we can assert that the format map is non-NULL
15164 		 * and that the format for the specified index is non-NULL.
15165 		 */
15166 		ASSERT(state->dts_formats != NULL);
15167 		str = state->dts_formats[fmt.dtfd_format - 1];
15168 		ASSERT(str != NULL);
15169 
15170 		len = strlen(str) + 1;
15171 
15172 		if (len > fmt.dtfd_length) {
15173 			fmt.dtfd_length = len;
15174 
15175 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
15176 				mutex_exit(&dtrace_lock);
15177 				return (EINVAL);
15178 			}
15179 		} else {
15180 			if (copyout(str, fmt.dtfd_string, len) != 0) {
15181 				mutex_exit(&dtrace_lock);
15182 				return (EINVAL);
15183 			}
15184 		}
15185 
15186 		mutex_exit(&dtrace_lock);
15187 		return (0);
15188 	}
15189 
15190 	default:
15191 		break;
15192 	}
15193 
15194 	return (ENOTTY);
15195 }
15196 
15197 /*ARGSUSED*/
15198 static int
15199 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
15200 {
15201 	dtrace_state_t *state;
15202 
15203 	switch (cmd) {
15204 	case DDI_DETACH:
15205 		break;
15206 
15207 	case DDI_SUSPEND:
15208 		return (DDI_SUCCESS);
15209 
15210 	default:
15211 		return (DDI_FAILURE);
15212 	}
15213 
15214 	mutex_enter(&cpu_lock);
15215 	mutex_enter(&dtrace_provider_lock);
15216 	mutex_enter(&dtrace_lock);
15217 
15218 	ASSERT(dtrace_opens == 0);
15219 
15220 	if (dtrace_helpers > 0) {
15221 		mutex_exit(&dtrace_provider_lock);
15222 		mutex_exit(&dtrace_lock);
15223 		mutex_exit(&cpu_lock);
15224 		return (DDI_FAILURE);
15225 	}
15226 
15227 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
15228 		mutex_exit(&dtrace_provider_lock);
15229 		mutex_exit(&dtrace_lock);
15230 		mutex_exit(&cpu_lock);
15231 		return (DDI_FAILURE);
15232 	}
15233 
15234 	dtrace_provider = NULL;
15235 
15236 	if ((state = dtrace_anon_grab()) != NULL) {
15237 		/*
15238 		 * If there were ECBs on this state, the provider should
15239 		 * have not been allowed to detach; assert that there is
15240 		 * none.
15241 		 */
15242 		ASSERT(state->dts_necbs == 0);
15243 		dtrace_state_destroy(state);
15244 
15245 		/*
15246 		 * If we're being detached with anonymous state, we need to
15247 		 * indicate to the kernel debugger that DTrace is now inactive.
15248 		 */
15249 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15250 	}
15251 
15252 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
15253 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15254 	dtrace_cpu_init = NULL;
15255 	dtrace_helpers_cleanup = NULL;
15256 	dtrace_helpers_fork = NULL;
15257 	dtrace_cpustart_init = NULL;
15258 	dtrace_cpustart_fini = NULL;
15259 	dtrace_debugger_init = NULL;
15260 	dtrace_debugger_fini = NULL;
15261 	dtrace_modload = NULL;
15262 	dtrace_modunload = NULL;
15263 
15264 	mutex_exit(&cpu_lock);
15265 
15266 	if (dtrace_helptrace_enabled) {
15267 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
15268 		dtrace_helptrace_buffer = NULL;
15269 	}
15270 
15271 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
15272 	dtrace_probes = NULL;
15273 	dtrace_nprobes = 0;
15274 
15275 	dtrace_hash_destroy(dtrace_bymod);
15276 	dtrace_hash_destroy(dtrace_byfunc);
15277 	dtrace_hash_destroy(dtrace_byname);
15278 	dtrace_bymod = NULL;
15279 	dtrace_byfunc = NULL;
15280 	dtrace_byname = NULL;
15281 
15282 	kmem_cache_destroy(dtrace_state_cache);
15283 	vmem_destroy(dtrace_minor);
15284 	vmem_destroy(dtrace_arena);
15285 
15286 	if (dtrace_toxrange != NULL) {
15287 		kmem_free(dtrace_toxrange,
15288 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
15289 		dtrace_toxrange = NULL;
15290 		dtrace_toxranges = 0;
15291 		dtrace_toxranges_max = 0;
15292 	}
15293 
15294 	ddi_remove_minor_node(dtrace_devi, NULL);
15295 	dtrace_devi = NULL;
15296 
15297 	ddi_soft_state_fini(&dtrace_softstate);
15298 
15299 	ASSERT(dtrace_vtime_references == 0);
15300 	ASSERT(dtrace_opens == 0);
15301 	ASSERT(dtrace_retained == NULL);
15302 
15303 	mutex_exit(&dtrace_lock);
15304 	mutex_exit(&dtrace_provider_lock);
15305 
15306 	/*
15307 	 * We don't destroy the task queue until after we have dropped our
15308 	 * locks (taskq_destroy() may block on running tasks).  To prevent
15309 	 * attempting to do work after we have effectively detached but before
15310 	 * the task queue has been destroyed, all tasks dispatched via the
15311 	 * task queue must check that DTrace is still attached before
15312 	 * performing any operation.
15313 	 */
15314 	taskq_destroy(dtrace_taskq);
15315 	dtrace_taskq = NULL;
15316 
15317 	return (DDI_SUCCESS);
15318 }
15319 
15320 /*ARGSUSED*/
15321 static int
15322 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
15323 {
15324 	int error;
15325 
15326 	switch (infocmd) {
15327 	case DDI_INFO_DEVT2DEVINFO:
15328 		*result = (void *)dtrace_devi;
15329 		error = DDI_SUCCESS;
15330 		break;
15331 	case DDI_INFO_DEVT2INSTANCE:
15332 		*result = (void *)0;
15333 		error = DDI_SUCCESS;
15334 		break;
15335 	default:
15336 		error = DDI_FAILURE;
15337 	}
15338 	return (error);
15339 }
15340 
15341 static struct cb_ops dtrace_cb_ops = {
15342 	dtrace_open,		/* open */
15343 	dtrace_close,		/* close */
15344 	nulldev,		/* strategy */
15345 	nulldev,		/* print */
15346 	nodev,			/* dump */
15347 	nodev,			/* read */
15348 	nodev,			/* write */
15349 	dtrace_ioctl,		/* ioctl */
15350 	nodev,			/* devmap */
15351 	nodev,			/* mmap */
15352 	nodev,			/* segmap */
15353 	nochpoll,		/* poll */
15354 	ddi_prop_op,		/* cb_prop_op */
15355 	0,			/* streamtab  */
15356 	D_NEW | D_MP		/* Driver compatibility flag */
15357 };
15358 
15359 static struct dev_ops dtrace_ops = {
15360 	DEVO_REV,		/* devo_rev */
15361 	0,			/* refcnt */
15362 	dtrace_info,		/* get_dev_info */
15363 	nulldev,		/* identify */
15364 	nulldev,		/* probe */
15365 	dtrace_attach,		/* attach */
15366 	dtrace_detach,		/* detach */
15367 	nodev,			/* reset */
15368 	&dtrace_cb_ops,		/* driver operations */
15369 	NULL,			/* bus operations */
15370 	nodev			/* dev power */
15371 };
15372 
15373 static struct modldrv modldrv = {
15374 	&mod_driverops,		/* module type (this is a pseudo driver) */
15375 	"Dynamic Tracing",	/* name of module */
15376 	&dtrace_ops,		/* driver ops */
15377 };
15378 
15379 static struct modlinkage modlinkage = {
15380 	MODREV_1,
15381 	(void *)&modldrv,
15382 	NULL
15383 };
15384 
15385 int
15386 _init(void)
15387 {
15388 	return (mod_install(&modlinkage));
15389 }
15390 
15391 int
15392 _info(struct modinfo *modinfop)
15393 {
15394 	return (mod_info(&modlinkage, modinfop));
15395 }
15396 
15397 int
15398 _fini(void)
15399 {
15400 	return (mod_remove(&modlinkage));
15401 }
15402