xref: /titanic_41/usr/src/uts/common/dtrace/dtrace.c (revision 2917a9c9c3eee6fcaedb239f5f68da01f4ed0da9)
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 		return (1);
612 
613 	/*
614 	 * Finally, check the static local and global variables.  These checks
615 	 * take the longest, so we perform them last.
616 	 */
617 	if (dtrace_canstore_statvar(addr, sz,
618 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
619 		return (1);
620 
621 	if (dtrace_canstore_statvar(addr, sz,
622 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
623 		return (1);
624 
625 	return (0);
626 }
627 
628 
629 /*
630  * Convenience routine to check to see if the address is within a memory
631  * region in which a load may be issued given the user's privilege level;
632  * if not, it sets the appropriate error flags and loads 'addr' into the
633  * illegal value slot.
634  *
635  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
636  * appropriate memory access protection.
637  */
638 static int
639 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
640     dtrace_vstate_t *vstate)
641 {
642 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
643 
644 	/*
645 	 * If we hold the privilege to read from kernel memory, then
646 	 * everything is readable.
647 	 */
648 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
649 		return (1);
650 
651 	/*
652 	 * You can obviously read that which you can store.
653 	 */
654 	if (dtrace_canstore(addr, sz, mstate, vstate))
655 		return (1);
656 
657 	/*
658 	 * We're allowed to read from our own string table.
659 	 */
660 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
661 	    mstate->dtms_difo->dtdo_strlen))
662 		return (1);
663 
664 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
665 	*illval = addr;
666 	return (0);
667 }
668 
669 /*
670  * Convenience routine to check to see if a given string is within a memory
671  * region in which a load may be issued given the user's privilege level;
672  * this exists so that we don't need to issue unnecessary dtrace_strlen()
673  * calls in the event that the user has all privileges.
674  */
675 static int
676 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
677     dtrace_vstate_t *vstate)
678 {
679 	size_t strsz;
680 
681 	/*
682 	 * If we hold the privilege to read from kernel memory, then
683 	 * everything is readable.
684 	 */
685 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
686 		return (1);
687 
688 	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
689 	if (dtrace_canload(addr, strsz, mstate, vstate))
690 		return (1);
691 
692 	return (0);
693 }
694 
695 /*
696  * Convenience routine to check to see if a given variable is within a memory
697  * region in which a load may be issued given the user's privilege level.
698  */
699 static int
700 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
701     dtrace_vstate_t *vstate)
702 {
703 	size_t sz;
704 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
705 
706 	/*
707 	 * If we hold the privilege to read from kernel memory, then
708 	 * everything is readable.
709 	 */
710 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
711 		return (1);
712 
713 	if (type->dtdt_kind == DIF_TYPE_STRING)
714 		sz = dtrace_strlen(src,
715 		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
716 	else
717 		sz = type->dtdt_size;
718 
719 	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
720 }
721 
722 /*
723  * Compare two strings using safe loads.
724  */
725 static int
726 dtrace_strncmp(char *s1, char *s2, size_t limit)
727 {
728 	uint8_t c1, c2;
729 	volatile uint16_t *flags;
730 
731 	if (s1 == s2 || limit == 0)
732 		return (0);
733 
734 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
735 
736 	do {
737 		if (s1 == NULL) {
738 			c1 = '\0';
739 		} else {
740 			c1 = dtrace_load8((uintptr_t)s1++);
741 		}
742 
743 		if (s2 == NULL) {
744 			c2 = '\0';
745 		} else {
746 			c2 = dtrace_load8((uintptr_t)s2++);
747 		}
748 
749 		if (c1 != c2)
750 			return (c1 - c2);
751 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
752 
753 	return (0);
754 }
755 
756 /*
757  * Compute strlen(s) for a string using safe memory accesses.  The additional
758  * len parameter is used to specify a maximum length to ensure completion.
759  */
760 static size_t
761 dtrace_strlen(const char *s, size_t lim)
762 {
763 	uint_t len;
764 
765 	for (len = 0; len != lim; len++) {
766 		if (dtrace_load8((uintptr_t)s++) == '\0')
767 			break;
768 	}
769 
770 	return (len);
771 }
772 
773 /*
774  * Check if an address falls within a toxic region.
775  */
776 static int
777 dtrace_istoxic(uintptr_t kaddr, size_t size)
778 {
779 	uintptr_t taddr, tsize;
780 	int i;
781 
782 	for (i = 0; i < dtrace_toxranges; i++) {
783 		taddr = dtrace_toxrange[i].dtt_base;
784 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
785 
786 		if (kaddr - taddr < tsize) {
787 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
788 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
789 			return (1);
790 		}
791 
792 		if (taddr - kaddr < size) {
793 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
794 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
795 			return (1);
796 		}
797 	}
798 
799 	return (0);
800 }
801 
802 /*
803  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
804  * memory specified by the DIF program.  The dst is assumed to be safe memory
805  * that we can store to directly because it is managed by DTrace.  As with
806  * standard bcopy, overlapping copies are handled properly.
807  */
808 static void
809 dtrace_bcopy(const void *src, void *dst, size_t len)
810 {
811 	if (len != 0) {
812 		uint8_t *s1 = dst;
813 		const uint8_t *s2 = src;
814 
815 		if (s1 <= s2) {
816 			do {
817 				*s1++ = dtrace_load8((uintptr_t)s2++);
818 			} while (--len != 0);
819 		} else {
820 			s2 += len;
821 			s1 += len;
822 
823 			do {
824 				*--s1 = dtrace_load8((uintptr_t)--s2);
825 			} while (--len != 0);
826 		}
827 	}
828 }
829 
830 /*
831  * Copy src to dst using safe memory accesses, up to either the specified
832  * length, or the point that a nul byte is encountered.  The src is assumed to
833  * be unsafe memory specified by the DIF program.  The dst is assumed to be
834  * safe memory that we can store to directly because it is managed by DTrace.
835  * Unlike dtrace_bcopy(), overlapping regions are not handled.
836  */
837 static void
838 dtrace_strcpy(const void *src, void *dst, size_t len)
839 {
840 	if (len != 0) {
841 		uint8_t *s1 = dst, c;
842 		const uint8_t *s2 = src;
843 
844 		do {
845 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
846 		} while (--len != 0 && c != '\0');
847 	}
848 }
849 
850 /*
851  * Copy src to dst, deriving the size and type from the specified (BYREF)
852  * variable type.  The src is assumed to be unsafe memory specified by the DIF
853  * program.  The dst is assumed to be DTrace variable memory that is of the
854  * specified type; we assume that we can store to directly.
855  */
856 static void
857 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
858 {
859 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
860 
861 	if (type->dtdt_kind == DIF_TYPE_STRING) {
862 		dtrace_strcpy(src, dst, type->dtdt_size);
863 	} else {
864 		dtrace_bcopy(src, dst, type->dtdt_size);
865 	}
866 }
867 
868 /*
869  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
870  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
871  * safe memory that we can access directly because it is managed by DTrace.
872  */
873 static int
874 dtrace_bcmp(const void *s1, const void *s2, size_t len)
875 {
876 	volatile uint16_t *flags;
877 
878 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
879 
880 	if (s1 == s2)
881 		return (0);
882 
883 	if (s1 == NULL || s2 == NULL)
884 		return (1);
885 
886 	if (s1 != s2 && len != 0) {
887 		const uint8_t *ps1 = s1;
888 		const uint8_t *ps2 = s2;
889 
890 		do {
891 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
892 				return (1);
893 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
894 	}
895 	return (0);
896 }
897 
898 /*
899  * Zero the specified region using a simple byte-by-byte loop.  Note that this
900  * is for safe DTrace-managed memory only.
901  */
902 static void
903 dtrace_bzero(void *dst, size_t len)
904 {
905 	uchar_t *cp;
906 
907 	for (cp = dst; len != 0; len--)
908 		*cp++ = 0;
909 }
910 
911 /*
912  * This privilege check should be used by actions and subroutines to
913  * verify that the user credentials of the process that enabled the
914  * invoking ECB match the target credentials
915  */
916 static int
917 dtrace_priv_proc_common_user(dtrace_state_t *state)
918 {
919 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
920 
921 	/*
922 	 * We should always have a non-NULL state cred here, since if cred
923 	 * is null (anonymous tracing), we fast-path bypass this routine.
924 	 */
925 	ASSERT(s_cr != NULL);
926 
927 	if ((cr = CRED()) != NULL &&
928 	    s_cr->cr_uid == cr->cr_uid &&
929 	    s_cr->cr_uid == cr->cr_ruid &&
930 	    s_cr->cr_uid == cr->cr_suid &&
931 	    s_cr->cr_gid == cr->cr_gid &&
932 	    s_cr->cr_gid == cr->cr_rgid &&
933 	    s_cr->cr_gid == cr->cr_sgid)
934 		return (1);
935 
936 	return (0);
937 }
938 
939 /*
940  * This privilege check should be used by actions and subroutines to
941  * verify that the zone of the process that enabled the invoking ECB
942  * matches the target credentials
943  */
944 static int
945 dtrace_priv_proc_common_zone(dtrace_state_t *state)
946 {
947 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
948 
949 	/*
950 	 * We should always have a non-NULL state cred here, since if cred
951 	 * is null (anonymous tracing), we fast-path bypass this routine.
952 	 */
953 	ASSERT(s_cr != NULL);
954 
955 	if ((cr = CRED()) != NULL &&
956 	    s_cr->cr_zone == cr->cr_zone)
957 		return (1);
958 
959 	return (0);
960 }
961 
962 /*
963  * This privilege check should be used by actions and subroutines to
964  * verify that the process has not setuid or changed credentials.
965  */
966 static int
967 dtrace_priv_proc_common_nocd()
968 {
969 	proc_t *proc;
970 
971 	if ((proc = ttoproc(curthread)) != NULL &&
972 	    !(proc->p_flag & SNOCD))
973 		return (1);
974 
975 	return (0);
976 }
977 
978 static int
979 dtrace_priv_proc_destructive(dtrace_state_t *state)
980 {
981 	int action = state->dts_cred.dcr_action;
982 
983 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
984 	    dtrace_priv_proc_common_zone(state) == 0)
985 		goto bad;
986 
987 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
988 	    dtrace_priv_proc_common_user(state) == 0)
989 		goto bad;
990 
991 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
992 	    dtrace_priv_proc_common_nocd() == 0)
993 		goto bad;
994 
995 	return (1);
996 
997 bad:
998 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
999 
1000 	return (0);
1001 }
1002 
1003 static int
1004 dtrace_priv_proc_control(dtrace_state_t *state)
1005 {
1006 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1007 		return (1);
1008 
1009 	if (dtrace_priv_proc_common_zone(state) &&
1010 	    dtrace_priv_proc_common_user(state) &&
1011 	    dtrace_priv_proc_common_nocd())
1012 		return (1);
1013 
1014 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1015 
1016 	return (0);
1017 }
1018 
1019 static int
1020 dtrace_priv_proc(dtrace_state_t *state)
1021 {
1022 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1023 		return (1);
1024 
1025 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1026 
1027 	return (0);
1028 }
1029 
1030 static int
1031 dtrace_priv_kernel(dtrace_state_t *state)
1032 {
1033 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1034 		return (1);
1035 
1036 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1037 
1038 	return (0);
1039 }
1040 
1041 static int
1042 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1043 {
1044 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1045 		return (1);
1046 
1047 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1048 
1049 	return (0);
1050 }
1051 
1052 /*
1053  * Note:  not called from probe context.  This function is called
1054  * asynchronously (and at a regular interval) from outside of probe context to
1055  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1056  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1057  */
1058 void
1059 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1060 {
1061 	dtrace_dynvar_t *dirty;
1062 	dtrace_dstate_percpu_t *dcpu;
1063 	int i, work = 0;
1064 
1065 	for (i = 0; i < NCPU; i++) {
1066 		dcpu = &dstate->dtds_percpu[i];
1067 
1068 		ASSERT(dcpu->dtdsc_rinsing == NULL);
1069 
1070 		/*
1071 		 * If the dirty list is NULL, there is no dirty work to do.
1072 		 */
1073 		if (dcpu->dtdsc_dirty == NULL)
1074 			continue;
1075 
1076 		/*
1077 		 * If the clean list is non-NULL, then we're not going to do
1078 		 * any work for this CPU -- it means that there has not been
1079 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1080 		 * since the last time we cleaned house.
1081 		 */
1082 		if (dcpu->dtdsc_clean != NULL)
1083 			continue;
1084 
1085 		work = 1;
1086 
1087 		/*
1088 		 * Atomically move the dirty list aside.
1089 		 */
1090 		do {
1091 			dirty = dcpu->dtdsc_dirty;
1092 
1093 			/*
1094 			 * Before we zap the dirty list, set the rinsing list.
1095 			 * (This allows for a potential assertion in
1096 			 * dtrace_dynvar():  if a free dynamic variable appears
1097 			 * on a hash chain, either the dirty list or the
1098 			 * rinsing list for some CPU must be non-NULL.)
1099 			 */
1100 			dcpu->dtdsc_rinsing = dirty;
1101 			dtrace_membar_producer();
1102 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1103 		    dirty, NULL) != dirty);
1104 	}
1105 
1106 	if (!work) {
1107 		/*
1108 		 * We have no work to do; we can simply return.
1109 		 */
1110 		return;
1111 	}
1112 
1113 	dtrace_sync();
1114 
1115 	for (i = 0; i < NCPU; i++) {
1116 		dcpu = &dstate->dtds_percpu[i];
1117 
1118 		if (dcpu->dtdsc_rinsing == NULL)
1119 			continue;
1120 
1121 		/*
1122 		 * We are now guaranteed that no hash chain contains a pointer
1123 		 * into this dirty list; we can make it clean.
1124 		 */
1125 		ASSERT(dcpu->dtdsc_clean == NULL);
1126 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1127 		dcpu->dtdsc_rinsing = NULL;
1128 	}
1129 
1130 	/*
1131 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1132 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1133 	 * This prevents a race whereby a CPU incorrectly decides that
1134 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1135 	 * after dtrace_dynvar_clean() has completed.
1136 	 */
1137 	dtrace_sync();
1138 
1139 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1140 }
1141 
1142 /*
1143  * Depending on the value of the op parameter, this function looks-up,
1144  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1145  * allocation is requested, this function will return a pointer to a
1146  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1147  * variable can be allocated.  If NULL is returned, the appropriate counter
1148  * will be incremented.
1149  */
1150 dtrace_dynvar_t *
1151 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1152     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1153     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1154 {
1155 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1156 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1157 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1158 	processorid_t me = CPU->cpu_id, cpu = me;
1159 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1160 	size_t bucket, ksize;
1161 	size_t chunksize = dstate->dtds_chunksize;
1162 	uintptr_t kdata, lock, nstate;
1163 	uint_t i;
1164 
1165 	ASSERT(nkeys != 0);
1166 
1167 	/*
1168 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1169 	 * algorithm.  For the by-value portions, we perform the algorithm in
1170 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1171 	 * bit, and seems to have only a minute effect on distribution.  For
1172 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1173 	 * over each referenced byte.  It's painful to do this, but it's much
1174 	 * better than pathological hash distribution.  The efficacy of the
1175 	 * hashing algorithm (and a comparison with other algorithms) may be
1176 	 * found by running the ::dtrace_dynstat MDB dcmd.
1177 	 */
1178 	for (i = 0; i < nkeys; i++) {
1179 		if (key[i].dttk_size == 0) {
1180 			uint64_t val = key[i].dttk_value;
1181 
1182 			hashval += (val >> 48) & 0xffff;
1183 			hashval += (hashval << 10);
1184 			hashval ^= (hashval >> 6);
1185 
1186 			hashval += (val >> 32) & 0xffff;
1187 			hashval += (hashval << 10);
1188 			hashval ^= (hashval >> 6);
1189 
1190 			hashval += (val >> 16) & 0xffff;
1191 			hashval += (hashval << 10);
1192 			hashval ^= (hashval >> 6);
1193 
1194 			hashval += val & 0xffff;
1195 			hashval += (hashval << 10);
1196 			hashval ^= (hashval >> 6);
1197 		} else {
1198 			/*
1199 			 * This is incredibly painful, but it beats the hell
1200 			 * out of the alternative.
1201 			 */
1202 			uint64_t j, size = key[i].dttk_size;
1203 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1204 
1205 			if (!dtrace_canload(base, size, mstate, vstate))
1206 				break;
1207 
1208 			for (j = 0; j < size; j++) {
1209 				hashval += dtrace_load8(base + j);
1210 				hashval += (hashval << 10);
1211 				hashval ^= (hashval >> 6);
1212 			}
1213 		}
1214 	}
1215 
1216 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1217 		return (NULL);
1218 
1219 	hashval += (hashval << 3);
1220 	hashval ^= (hashval >> 11);
1221 	hashval += (hashval << 15);
1222 
1223 	/*
1224 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1225 	 * comes out to be one of our two sentinel hash values.  If this
1226 	 * actually happens, we set the hashval to be a value known to be a
1227 	 * non-sentinel value.
1228 	 */
1229 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1230 		hashval = DTRACE_DYNHASH_VALID;
1231 
1232 	/*
1233 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1234 	 * important here, tricks can be pulled to reduce it.  (However, it's
1235 	 * critical that hash collisions be kept to an absolute minimum;
1236 	 * they're much more painful than a divide.)  It's better to have a
1237 	 * solution that generates few collisions and still keeps things
1238 	 * relatively simple.
1239 	 */
1240 	bucket = hashval % dstate->dtds_hashsize;
1241 
1242 	if (op == DTRACE_DYNVAR_DEALLOC) {
1243 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1244 
1245 		for (;;) {
1246 			while ((lock = *lockp) & 1)
1247 				continue;
1248 
1249 			if (dtrace_casptr((void *)lockp,
1250 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1251 				break;
1252 		}
1253 
1254 		dtrace_membar_producer();
1255 	}
1256 
1257 top:
1258 	prev = NULL;
1259 	lock = hash[bucket].dtdh_lock;
1260 
1261 	dtrace_membar_consumer();
1262 
1263 	start = hash[bucket].dtdh_chain;
1264 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1265 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1266 	    op != DTRACE_DYNVAR_DEALLOC));
1267 
1268 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1269 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1270 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1271 
1272 		if (dvar->dtdv_hashval != hashval) {
1273 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1274 				/*
1275 				 * We've reached the sink, and therefore the
1276 				 * end of the hash chain; we can kick out of
1277 				 * the loop knowing that we have seen a valid
1278 				 * snapshot of state.
1279 				 */
1280 				ASSERT(dvar->dtdv_next == NULL);
1281 				ASSERT(dvar == &dtrace_dynhash_sink);
1282 				break;
1283 			}
1284 
1285 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1286 				/*
1287 				 * We've gone off the rails:  somewhere along
1288 				 * the line, one of the members of this hash
1289 				 * chain was deleted.  Note that we could also
1290 				 * detect this by simply letting this loop run
1291 				 * to completion, as we would eventually hit
1292 				 * the end of the dirty list.  However, we
1293 				 * want to avoid running the length of the
1294 				 * dirty list unnecessarily (it might be quite
1295 				 * long), so we catch this as early as
1296 				 * possible by detecting the hash marker.  In
1297 				 * this case, we simply set dvar to NULL and
1298 				 * break; the conditional after the loop will
1299 				 * send us back to top.
1300 				 */
1301 				dvar = NULL;
1302 				break;
1303 			}
1304 
1305 			goto next;
1306 		}
1307 
1308 		if (dtuple->dtt_nkeys != nkeys)
1309 			goto next;
1310 
1311 		for (i = 0; i < nkeys; i++, dkey++) {
1312 			if (dkey->dttk_size != key[i].dttk_size)
1313 				goto next; /* size or type mismatch */
1314 
1315 			if (dkey->dttk_size != 0) {
1316 				if (dtrace_bcmp(
1317 				    (void *)(uintptr_t)key[i].dttk_value,
1318 				    (void *)(uintptr_t)dkey->dttk_value,
1319 				    dkey->dttk_size))
1320 					goto next;
1321 			} else {
1322 				if (dkey->dttk_value != key[i].dttk_value)
1323 					goto next;
1324 			}
1325 		}
1326 
1327 		if (op != DTRACE_DYNVAR_DEALLOC)
1328 			return (dvar);
1329 
1330 		ASSERT(dvar->dtdv_next == NULL ||
1331 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1332 
1333 		if (prev != NULL) {
1334 			ASSERT(hash[bucket].dtdh_chain != dvar);
1335 			ASSERT(start != dvar);
1336 			ASSERT(prev->dtdv_next == dvar);
1337 			prev->dtdv_next = dvar->dtdv_next;
1338 		} else {
1339 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1340 			    start, dvar->dtdv_next) != start) {
1341 				/*
1342 				 * We have failed to atomically swing the
1343 				 * hash table head pointer, presumably because
1344 				 * of a conflicting allocation on another CPU.
1345 				 * We need to reread the hash chain and try
1346 				 * again.
1347 				 */
1348 				goto top;
1349 			}
1350 		}
1351 
1352 		dtrace_membar_producer();
1353 
1354 		/*
1355 		 * Now set the hash value to indicate that it's free.
1356 		 */
1357 		ASSERT(hash[bucket].dtdh_chain != dvar);
1358 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1359 
1360 		dtrace_membar_producer();
1361 
1362 		/*
1363 		 * Set the next pointer to point at the dirty list, and
1364 		 * atomically swing the dirty pointer to the newly freed dvar.
1365 		 */
1366 		do {
1367 			next = dcpu->dtdsc_dirty;
1368 			dvar->dtdv_next = next;
1369 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1370 
1371 		/*
1372 		 * Finally, unlock this hash bucket.
1373 		 */
1374 		ASSERT(hash[bucket].dtdh_lock == lock);
1375 		ASSERT(lock & 1);
1376 		hash[bucket].dtdh_lock++;
1377 
1378 		return (NULL);
1379 next:
1380 		prev = dvar;
1381 		continue;
1382 	}
1383 
1384 	if (dvar == NULL) {
1385 		/*
1386 		 * If dvar is NULL, it is because we went off the rails:
1387 		 * one of the elements that we traversed in the hash chain
1388 		 * was deleted while we were traversing it.  In this case,
1389 		 * we assert that we aren't doing a dealloc (deallocs lock
1390 		 * the hash bucket to prevent themselves from racing with
1391 		 * one another), and retry the hash chain traversal.
1392 		 */
1393 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1394 		goto top;
1395 	}
1396 
1397 	if (op != DTRACE_DYNVAR_ALLOC) {
1398 		/*
1399 		 * If we are not to allocate a new variable, we want to
1400 		 * return NULL now.  Before we return, check that the value
1401 		 * of the lock word hasn't changed.  If it has, we may have
1402 		 * seen an inconsistent snapshot.
1403 		 */
1404 		if (op == DTRACE_DYNVAR_NOALLOC) {
1405 			if (hash[bucket].dtdh_lock != lock)
1406 				goto top;
1407 		} else {
1408 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1409 			ASSERT(hash[bucket].dtdh_lock == lock);
1410 			ASSERT(lock & 1);
1411 			hash[bucket].dtdh_lock++;
1412 		}
1413 
1414 		return (NULL);
1415 	}
1416 
1417 	/*
1418 	 * We need to allocate a new dynamic variable.  The size we need is the
1419 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1420 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1421 	 * the size of any referred-to data (dsize).  We then round the final
1422 	 * size up to the chunksize for allocation.
1423 	 */
1424 	for (ksize = 0, i = 0; i < nkeys; i++)
1425 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1426 
1427 	/*
1428 	 * This should be pretty much impossible, but could happen if, say,
1429 	 * strange DIF specified the tuple.  Ideally, this should be an
1430 	 * assertion and not an error condition -- but that requires that the
1431 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1432 	 * bullet-proof.  (That is, it must not be able to be fooled by
1433 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1434 	 * solving this would presumably not amount to solving the Halting
1435 	 * Problem -- but it still seems awfully hard.
1436 	 */
1437 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1438 	    ksize + dsize > chunksize) {
1439 		dcpu->dtdsc_drops++;
1440 		return (NULL);
1441 	}
1442 
1443 	nstate = DTRACE_DSTATE_EMPTY;
1444 
1445 	do {
1446 retry:
1447 		free = dcpu->dtdsc_free;
1448 
1449 		if (free == NULL) {
1450 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1451 			void *rval;
1452 
1453 			if (clean == NULL) {
1454 				/*
1455 				 * We're out of dynamic variable space on
1456 				 * this CPU.  Unless we have tried all CPUs,
1457 				 * we'll try to allocate from a different
1458 				 * CPU.
1459 				 */
1460 				switch (dstate->dtds_state) {
1461 				case DTRACE_DSTATE_CLEAN: {
1462 					void *sp = &dstate->dtds_state;
1463 
1464 					if (++cpu >= NCPU)
1465 						cpu = 0;
1466 
1467 					if (dcpu->dtdsc_dirty != NULL &&
1468 					    nstate == DTRACE_DSTATE_EMPTY)
1469 						nstate = DTRACE_DSTATE_DIRTY;
1470 
1471 					if (dcpu->dtdsc_rinsing != NULL)
1472 						nstate = DTRACE_DSTATE_RINSING;
1473 
1474 					dcpu = &dstate->dtds_percpu[cpu];
1475 
1476 					if (cpu != me)
1477 						goto retry;
1478 
1479 					(void) dtrace_cas32(sp,
1480 					    DTRACE_DSTATE_CLEAN, nstate);
1481 
1482 					/*
1483 					 * To increment the correct bean
1484 					 * counter, take another lap.
1485 					 */
1486 					goto retry;
1487 				}
1488 
1489 				case DTRACE_DSTATE_DIRTY:
1490 					dcpu->dtdsc_dirty_drops++;
1491 					break;
1492 
1493 				case DTRACE_DSTATE_RINSING:
1494 					dcpu->dtdsc_rinsing_drops++;
1495 					break;
1496 
1497 				case DTRACE_DSTATE_EMPTY:
1498 					dcpu->dtdsc_drops++;
1499 					break;
1500 				}
1501 
1502 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1503 				return (NULL);
1504 			}
1505 
1506 			/*
1507 			 * The clean list appears to be non-empty.  We want to
1508 			 * move the clean list to the free list; we start by
1509 			 * moving the clean pointer aside.
1510 			 */
1511 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1512 			    clean, NULL) != clean) {
1513 				/*
1514 				 * We are in one of two situations:
1515 				 *
1516 				 *  (a)	The clean list was switched to the
1517 				 *	free list by another CPU.
1518 				 *
1519 				 *  (b)	The clean list was added to by the
1520 				 *	cleansing cyclic.
1521 				 *
1522 				 * In either of these situations, we can
1523 				 * just reattempt the free list allocation.
1524 				 */
1525 				goto retry;
1526 			}
1527 
1528 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1529 
1530 			/*
1531 			 * Now we'll move the clean list to the free list.
1532 			 * It's impossible for this to fail:  the only way
1533 			 * the free list can be updated is through this
1534 			 * code path, and only one CPU can own the clean list.
1535 			 * Thus, it would only be possible for this to fail if
1536 			 * this code were racing with dtrace_dynvar_clean().
1537 			 * (That is, if dtrace_dynvar_clean() updated the clean
1538 			 * list, and we ended up racing to update the free
1539 			 * list.)  This race is prevented by the dtrace_sync()
1540 			 * in dtrace_dynvar_clean() -- which flushes the
1541 			 * owners of the clean lists out before resetting
1542 			 * the clean lists.
1543 			 */
1544 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1545 			ASSERT(rval == NULL);
1546 			goto retry;
1547 		}
1548 
1549 		dvar = free;
1550 		new_free = dvar->dtdv_next;
1551 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1552 
1553 	/*
1554 	 * We have now allocated a new chunk.  We copy the tuple keys into the
1555 	 * tuple array and copy any referenced key data into the data space
1556 	 * following the tuple array.  As we do this, we relocate dttk_value
1557 	 * in the final tuple to point to the key data address in the chunk.
1558 	 */
1559 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1560 	dvar->dtdv_data = (void *)(kdata + ksize);
1561 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
1562 
1563 	for (i = 0; i < nkeys; i++) {
1564 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1565 		size_t kesize = key[i].dttk_size;
1566 
1567 		if (kesize != 0) {
1568 			dtrace_bcopy(
1569 			    (const void *)(uintptr_t)key[i].dttk_value,
1570 			    (void *)kdata, kesize);
1571 			dkey->dttk_value = kdata;
1572 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1573 		} else {
1574 			dkey->dttk_value = key[i].dttk_value;
1575 		}
1576 
1577 		dkey->dttk_size = kesize;
1578 	}
1579 
1580 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1581 	dvar->dtdv_hashval = hashval;
1582 	dvar->dtdv_next = start;
1583 
1584 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1585 		return (dvar);
1586 
1587 	/*
1588 	 * The cas has failed.  Either another CPU is adding an element to
1589 	 * this hash chain, or another CPU is deleting an element from this
1590 	 * hash chain.  The simplest way to deal with both of these cases
1591 	 * (though not necessarily the most efficient) is to free our
1592 	 * allocated block and tail-call ourselves.  Note that the free is
1593 	 * to the dirty list and _not_ to the free list.  This is to prevent
1594 	 * races with allocators, above.
1595 	 */
1596 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1597 
1598 	dtrace_membar_producer();
1599 
1600 	do {
1601 		free = dcpu->dtdsc_dirty;
1602 		dvar->dtdv_next = free;
1603 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1604 
1605 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1606 }
1607 
1608 /*ARGSUSED*/
1609 static void
1610 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1611 {
1612 	if (nval < *oval)
1613 		*oval = nval;
1614 }
1615 
1616 /*ARGSUSED*/
1617 static void
1618 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1619 {
1620 	if (nval > *oval)
1621 		*oval = nval;
1622 }
1623 
1624 static void
1625 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1626 {
1627 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1628 	int64_t val = (int64_t)nval;
1629 
1630 	if (val < 0) {
1631 		for (i = 0; i < zero; i++) {
1632 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1633 				quanta[i] += incr;
1634 				return;
1635 			}
1636 		}
1637 	} else {
1638 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1639 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1640 				quanta[i - 1] += incr;
1641 				return;
1642 			}
1643 		}
1644 
1645 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1646 		return;
1647 	}
1648 
1649 	ASSERT(0);
1650 }
1651 
1652 static void
1653 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1654 {
1655 	uint64_t arg = *lquanta++;
1656 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1657 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1658 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1659 	int32_t val = (int32_t)nval, level;
1660 
1661 	ASSERT(step != 0);
1662 	ASSERT(levels != 0);
1663 
1664 	if (val < base) {
1665 		/*
1666 		 * This is an underflow.
1667 		 */
1668 		lquanta[0] += incr;
1669 		return;
1670 	}
1671 
1672 	level = (val - base) / step;
1673 
1674 	if (level < levels) {
1675 		lquanta[level + 1] += incr;
1676 		return;
1677 	}
1678 
1679 	/*
1680 	 * This is an overflow.
1681 	 */
1682 	lquanta[levels + 1] += incr;
1683 }
1684 
1685 /*ARGSUSED*/
1686 static void
1687 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
1688 {
1689 	data[0]++;
1690 	data[1] += nval;
1691 }
1692 
1693 /*ARGSUSED*/
1694 static void
1695 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
1696 {
1697 	*oval = *oval + 1;
1698 }
1699 
1700 /*ARGSUSED*/
1701 static void
1702 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
1703 {
1704 	*oval += nval;
1705 }
1706 
1707 /*
1708  * Aggregate given the tuple in the principal data buffer, and the aggregating
1709  * action denoted by the specified dtrace_aggregation_t.  The aggregation
1710  * buffer is specified as the buf parameter.  This routine does not return
1711  * failure; if there is no space in the aggregation buffer, the data will be
1712  * dropped, and a corresponding counter incremented.
1713  */
1714 static void
1715 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
1716     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
1717 {
1718 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
1719 	uint32_t i, ndx, size, fsize;
1720 	uint32_t align = sizeof (uint64_t) - 1;
1721 	dtrace_aggbuffer_t *agb;
1722 	dtrace_aggkey_t *key;
1723 	uint32_t hashval = 0, limit, isstr;
1724 	caddr_t tomax, data, kdata;
1725 	dtrace_actkind_t action;
1726 	dtrace_action_t *act;
1727 	uintptr_t offs;
1728 
1729 	if (buf == NULL)
1730 		return;
1731 
1732 	if (!agg->dtag_hasarg) {
1733 		/*
1734 		 * Currently, only quantize() and lquantize() take additional
1735 		 * arguments, and they have the same semantics:  an increment
1736 		 * value that defaults to 1 when not present.  If additional
1737 		 * aggregating actions take arguments, the setting of the
1738 		 * default argument value will presumably have to become more
1739 		 * sophisticated...
1740 		 */
1741 		arg = 1;
1742 	}
1743 
1744 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
1745 	size = rec->dtrd_offset - agg->dtag_base;
1746 	fsize = size + rec->dtrd_size;
1747 
1748 	ASSERT(dbuf->dtb_tomax != NULL);
1749 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
1750 
1751 	if ((tomax = buf->dtb_tomax) == NULL) {
1752 		dtrace_buffer_drop(buf);
1753 		return;
1754 	}
1755 
1756 	/*
1757 	 * The metastructure is always at the bottom of the buffer.
1758 	 */
1759 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
1760 	    sizeof (dtrace_aggbuffer_t));
1761 
1762 	if (buf->dtb_offset == 0) {
1763 		/*
1764 		 * We just kludge up approximately 1/8th of the size to be
1765 		 * buckets.  If this guess ends up being routinely
1766 		 * off-the-mark, we may need to dynamically readjust this
1767 		 * based on past performance.
1768 		 */
1769 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
1770 
1771 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
1772 		    (uintptr_t)tomax || hashsize == 0) {
1773 			/*
1774 			 * We've been given a ludicrously small buffer;
1775 			 * increment our drop count and leave.
1776 			 */
1777 			dtrace_buffer_drop(buf);
1778 			return;
1779 		}
1780 
1781 		/*
1782 		 * And now, a pathetic attempt to try to get a an odd (or
1783 		 * perchance, a prime) hash size for better hash distribution.
1784 		 */
1785 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
1786 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
1787 
1788 		agb->dtagb_hashsize = hashsize;
1789 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
1790 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
1791 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
1792 
1793 		for (i = 0; i < agb->dtagb_hashsize; i++)
1794 			agb->dtagb_hash[i] = NULL;
1795 	}
1796 
1797 	ASSERT(agg->dtag_first != NULL);
1798 	ASSERT(agg->dtag_first->dta_intuple);
1799 
1800 	/*
1801 	 * Calculate the hash value based on the key.  Note that we _don't_
1802 	 * include the aggid in the hashing (but we will store it as part of
1803 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
1804 	 * algorithm: a simple, quick algorithm that has no known funnels, and
1805 	 * gets good distribution in practice.  The efficacy of the hashing
1806 	 * algorithm (and a comparison with other algorithms) may be found by
1807 	 * running the ::dtrace_aggstat MDB dcmd.
1808 	 */
1809 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1810 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1811 		limit = i + act->dta_rec.dtrd_size;
1812 		ASSERT(limit <= size);
1813 		isstr = DTRACEACT_ISSTRING(act);
1814 
1815 		for (; i < limit; i++) {
1816 			hashval += data[i];
1817 			hashval += (hashval << 10);
1818 			hashval ^= (hashval >> 6);
1819 
1820 			if (isstr && data[i] == '\0')
1821 				break;
1822 		}
1823 	}
1824 
1825 	hashval += (hashval << 3);
1826 	hashval ^= (hashval >> 11);
1827 	hashval += (hashval << 15);
1828 
1829 	/*
1830 	 * Yes, the divide here is expensive -- but it's generally the least
1831 	 * of the performance issues given the amount of data that we iterate
1832 	 * over to compute hash values, compare data, etc.
1833 	 */
1834 	ndx = hashval % agb->dtagb_hashsize;
1835 
1836 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
1837 		ASSERT((caddr_t)key >= tomax);
1838 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
1839 
1840 		if (hashval != key->dtak_hashval || key->dtak_size != size)
1841 			continue;
1842 
1843 		kdata = key->dtak_data;
1844 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
1845 
1846 		for (act = agg->dtag_first; act->dta_intuple;
1847 		    act = act->dta_next) {
1848 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
1849 			limit = i + act->dta_rec.dtrd_size;
1850 			ASSERT(limit <= size);
1851 			isstr = DTRACEACT_ISSTRING(act);
1852 
1853 			for (; i < limit; i++) {
1854 				if (kdata[i] != data[i])
1855 					goto next;
1856 
1857 				if (isstr && data[i] == '\0')
1858 					break;
1859 			}
1860 		}
1861 
1862 		if (action != key->dtak_action) {
1863 			/*
1864 			 * We are aggregating on the same value in the same
1865 			 * aggregation with two different aggregating actions.
1866 			 * (This should have been picked up in the compiler,
1867 			 * so we may be dealing with errant or devious DIF.)
1868 			 * This is an error condition; we indicate as much,
1869 			 * and return.
1870 			 */
1871 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
1872 			return;
1873 		}
1874 
1875 		/*
1876 		 * This is a hit:  we need to apply the aggregator to
1877 		 * the value at this key.
1878 		 */
1879 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
1880 		return;
1881 next:
1882 		continue;
1883 	}
1884 
1885 	/*
1886 	 * We didn't find it.  We need to allocate some zero-filled space,
1887 	 * link it into the hash table appropriately, and apply the aggregator
1888 	 * to the (zero-filled) value.
1889 	 */
1890 	offs = buf->dtb_offset;
1891 	while (offs & (align - 1))
1892 		offs += sizeof (uint32_t);
1893 
1894 	/*
1895 	 * If we don't have enough room to both allocate a new key _and_
1896 	 * its associated data, increment the drop count and return.
1897 	 */
1898 	if ((uintptr_t)tomax + offs + fsize >
1899 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
1900 		dtrace_buffer_drop(buf);
1901 		return;
1902 	}
1903 
1904 	/*CONSTCOND*/
1905 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
1906 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
1907 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
1908 
1909 	key->dtak_data = kdata = tomax + offs;
1910 	buf->dtb_offset = offs + fsize;
1911 
1912 	/*
1913 	 * Now copy the data across.
1914 	 */
1915 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
1916 
1917 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
1918 		kdata[i] = data[i];
1919 
1920 	/*
1921 	 * Because strings are not zeroed out by default, we need to iterate
1922 	 * looking for actions that store strings, and we need to explicitly
1923 	 * pad these strings out with zeroes.
1924 	 */
1925 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1926 		int nul;
1927 
1928 		if (!DTRACEACT_ISSTRING(act))
1929 			continue;
1930 
1931 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1932 		limit = i + act->dta_rec.dtrd_size;
1933 		ASSERT(limit <= size);
1934 
1935 		for (nul = 0; i < limit; i++) {
1936 			if (nul) {
1937 				kdata[i] = '\0';
1938 				continue;
1939 			}
1940 
1941 			if (data[i] != '\0')
1942 				continue;
1943 
1944 			nul = 1;
1945 		}
1946 	}
1947 
1948 	for (i = size; i < fsize; i++)
1949 		kdata[i] = 0;
1950 
1951 	key->dtak_hashval = hashval;
1952 	key->dtak_size = size;
1953 	key->dtak_action = action;
1954 	key->dtak_next = agb->dtagb_hash[ndx];
1955 	agb->dtagb_hash[ndx] = key;
1956 
1957 	/*
1958 	 * Finally, apply the aggregator.
1959 	 */
1960 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
1961 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
1962 }
1963 
1964 /*
1965  * Given consumer state, this routine finds a speculation in the INACTIVE
1966  * state and transitions it into the ACTIVE state.  If there is no speculation
1967  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
1968  * incremented -- it is up to the caller to take appropriate action.
1969  */
1970 static int
1971 dtrace_speculation(dtrace_state_t *state)
1972 {
1973 	int i = 0;
1974 	dtrace_speculation_state_t current;
1975 	uint32_t *stat = &state->dts_speculations_unavail, count;
1976 
1977 	while (i < state->dts_nspeculations) {
1978 		dtrace_speculation_t *spec = &state->dts_speculations[i];
1979 
1980 		current = spec->dtsp_state;
1981 
1982 		if (current != DTRACESPEC_INACTIVE) {
1983 			if (current == DTRACESPEC_COMMITTINGMANY ||
1984 			    current == DTRACESPEC_COMMITTING ||
1985 			    current == DTRACESPEC_DISCARDING)
1986 				stat = &state->dts_speculations_busy;
1987 			i++;
1988 			continue;
1989 		}
1990 
1991 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
1992 		    current, DTRACESPEC_ACTIVE) == current)
1993 			return (i + 1);
1994 	}
1995 
1996 	/*
1997 	 * We couldn't find a speculation.  If we found as much as a single
1998 	 * busy speculation buffer, we'll attribute this failure as "busy"
1999 	 * instead of "unavail".
2000 	 */
2001 	do {
2002 		count = *stat;
2003 	} while (dtrace_cas32(stat, count, count + 1) != count);
2004 
2005 	return (0);
2006 }
2007 
2008 /*
2009  * This routine commits an active speculation.  If the specified speculation
2010  * is not in a valid state to perform a commit(), this routine will silently do
2011  * nothing.  The state of the specified speculation is transitioned according
2012  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2013  */
2014 static void
2015 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2016     dtrace_specid_t which)
2017 {
2018 	dtrace_speculation_t *spec;
2019 	dtrace_buffer_t *src, *dest;
2020 	uintptr_t daddr, saddr, dlimit;
2021 	dtrace_speculation_state_t current, new;
2022 	intptr_t offs;
2023 
2024 	if (which == 0)
2025 		return;
2026 
2027 	if (which > state->dts_nspeculations) {
2028 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2029 		return;
2030 	}
2031 
2032 	spec = &state->dts_speculations[which - 1];
2033 	src = &spec->dtsp_buffer[cpu];
2034 	dest = &state->dts_buffer[cpu];
2035 
2036 	do {
2037 		current = spec->dtsp_state;
2038 
2039 		if (current == DTRACESPEC_COMMITTINGMANY)
2040 			break;
2041 
2042 		switch (current) {
2043 		case DTRACESPEC_INACTIVE:
2044 		case DTRACESPEC_DISCARDING:
2045 			return;
2046 
2047 		case DTRACESPEC_COMMITTING:
2048 			/*
2049 			 * This is only possible if we are (a) commit()'ing
2050 			 * without having done a prior speculate() on this CPU
2051 			 * and (b) racing with another commit() on a different
2052 			 * CPU.  There's nothing to do -- we just assert that
2053 			 * our offset is 0.
2054 			 */
2055 			ASSERT(src->dtb_offset == 0);
2056 			return;
2057 
2058 		case DTRACESPEC_ACTIVE:
2059 			new = DTRACESPEC_COMMITTING;
2060 			break;
2061 
2062 		case DTRACESPEC_ACTIVEONE:
2063 			/*
2064 			 * This speculation is active on one CPU.  If our
2065 			 * buffer offset is non-zero, we know that the one CPU
2066 			 * must be us.  Otherwise, we are committing on a
2067 			 * different CPU from the speculate(), and we must
2068 			 * rely on being asynchronously cleaned.
2069 			 */
2070 			if (src->dtb_offset != 0) {
2071 				new = DTRACESPEC_COMMITTING;
2072 				break;
2073 			}
2074 			/*FALLTHROUGH*/
2075 
2076 		case DTRACESPEC_ACTIVEMANY:
2077 			new = DTRACESPEC_COMMITTINGMANY;
2078 			break;
2079 
2080 		default:
2081 			ASSERT(0);
2082 		}
2083 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2084 	    current, new) != current);
2085 
2086 	/*
2087 	 * We have set the state to indicate that we are committing this
2088 	 * speculation.  Now reserve the necessary space in the destination
2089 	 * buffer.
2090 	 */
2091 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2092 	    sizeof (uint64_t), state, NULL)) < 0) {
2093 		dtrace_buffer_drop(dest);
2094 		goto out;
2095 	}
2096 
2097 	/*
2098 	 * We have the space; copy the buffer across.  (Note that this is a
2099 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2100 	 * a serious performance issue, a high-performance DTrace-specific
2101 	 * bcopy() should obviously be invented.)
2102 	 */
2103 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2104 	dlimit = daddr + src->dtb_offset;
2105 	saddr = (uintptr_t)src->dtb_tomax;
2106 
2107 	/*
2108 	 * First, the aligned portion.
2109 	 */
2110 	while (dlimit - daddr >= sizeof (uint64_t)) {
2111 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2112 
2113 		daddr += sizeof (uint64_t);
2114 		saddr += sizeof (uint64_t);
2115 	}
2116 
2117 	/*
2118 	 * Now any left-over bit...
2119 	 */
2120 	while (dlimit - daddr)
2121 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2122 
2123 	/*
2124 	 * Finally, commit the reserved space in the destination buffer.
2125 	 */
2126 	dest->dtb_offset = offs + src->dtb_offset;
2127 
2128 out:
2129 	/*
2130 	 * If we're lucky enough to be the only active CPU on this speculation
2131 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2132 	 */
2133 	if (current == DTRACESPEC_ACTIVE ||
2134 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2135 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2136 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2137 
2138 		ASSERT(rval == DTRACESPEC_COMMITTING);
2139 	}
2140 
2141 	src->dtb_offset = 0;
2142 	src->dtb_xamot_drops += src->dtb_drops;
2143 	src->dtb_drops = 0;
2144 }
2145 
2146 /*
2147  * This routine discards an active speculation.  If the specified speculation
2148  * is not in a valid state to perform a discard(), this routine will silently
2149  * do nothing.  The state of the specified speculation is transitioned
2150  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2151  */
2152 static void
2153 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2154     dtrace_specid_t which)
2155 {
2156 	dtrace_speculation_t *spec;
2157 	dtrace_speculation_state_t current, new;
2158 	dtrace_buffer_t *buf;
2159 
2160 	if (which == 0)
2161 		return;
2162 
2163 	if (which > state->dts_nspeculations) {
2164 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2165 		return;
2166 	}
2167 
2168 	spec = &state->dts_speculations[which - 1];
2169 	buf = &spec->dtsp_buffer[cpu];
2170 
2171 	do {
2172 		current = spec->dtsp_state;
2173 
2174 		switch (current) {
2175 		case DTRACESPEC_INACTIVE:
2176 		case DTRACESPEC_COMMITTINGMANY:
2177 		case DTRACESPEC_COMMITTING:
2178 		case DTRACESPEC_DISCARDING:
2179 			return;
2180 
2181 		case DTRACESPEC_ACTIVE:
2182 		case DTRACESPEC_ACTIVEMANY:
2183 			new = DTRACESPEC_DISCARDING;
2184 			break;
2185 
2186 		case DTRACESPEC_ACTIVEONE:
2187 			if (buf->dtb_offset != 0) {
2188 				new = DTRACESPEC_INACTIVE;
2189 			} else {
2190 				new = DTRACESPEC_DISCARDING;
2191 			}
2192 			break;
2193 
2194 		default:
2195 			ASSERT(0);
2196 		}
2197 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2198 	    current, new) != current);
2199 
2200 	buf->dtb_offset = 0;
2201 	buf->dtb_drops = 0;
2202 }
2203 
2204 /*
2205  * Note:  not called from probe context.  This function is called
2206  * asynchronously from cross call context to clean any speculations that are
2207  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2208  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2209  * speculation.
2210  */
2211 static void
2212 dtrace_speculation_clean_here(dtrace_state_t *state)
2213 {
2214 	dtrace_icookie_t cookie;
2215 	processorid_t cpu = CPU->cpu_id;
2216 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2217 	dtrace_specid_t i;
2218 
2219 	cookie = dtrace_interrupt_disable();
2220 
2221 	if (dest->dtb_tomax == NULL) {
2222 		dtrace_interrupt_enable(cookie);
2223 		return;
2224 	}
2225 
2226 	for (i = 0; i < state->dts_nspeculations; i++) {
2227 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2228 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2229 
2230 		if (src->dtb_tomax == NULL)
2231 			continue;
2232 
2233 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2234 			src->dtb_offset = 0;
2235 			continue;
2236 		}
2237 
2238 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2239 			continue;
2240 
2241 		if (src->dtb_offset == 0)
2242 			continue;
2243 
2244 		dtrace_speculation_commit(state, cpu, i + 1);
2245 	}
2246 
2247 	dtrace_interrupt_enable(cookie);
2248 }
2249 
2250 /*
2251  * Note:  not called from probe context.  This function is called
2252  * asynchronously (and at a regular interval) to clean any speculations that
2253  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2254  * is work to be done, it cross calls all CPUs to perform that work;
2255  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2256  * INACTIVE state until they have been cleaned by all CPUs.
2257  */
2258 static void
2259 dtrace_speculation_clean(dtrace_state_t *state)
2260 {
2261 	int work = 0, rv;
2262 	dtrace_specid_t i;
2263 
2264 	for (i = 0; i < state->dts_nspeculations; i++) {
2265 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2266 
2267 		ASSERT(!spec->dtsp_cleaning);
2268 
2269 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2270 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2271 			continue;
2272 
2273 		work++;
2274 		spec->dtsp_cleaning = 1;
2275 	}
2276 
2277 	if (!work)
2278 		return;
2279 
2280 	dtrace_xcall(DTRACE_CPUALL,
2281 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2282 
2283 	/*
2284 	 * We now know that all CPUs have committed or discarded their
2285 	 * speculation buffers, as appropriate.  We can now set the state
2286 	 * to inactive.
2287 	 */
2288 	for (i = 0; i < state->dts_nspeculations; i++) {
2289 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2290 		dtrace_speculation_state_t current, new;
2291 
2292 		if (!spec->dtsp_cleaning)
2293 			continue;
2294 
2295 		current = spec->dtsp_state;
2296 		ASSERT(current == DTRACESPEC_DISCARDING ||
2297 		    current == DTRACESPEC_COMMITTINGMANY);
2298 
2299 		new = DTRACESPEC_INACTIVE;
2300 
2301 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2302 		ASSERT(rv == current);
2303 		spec->dtsp_cleaning = 0;
2304 	}
2305 }
2306 
2307 /*
2308  * Called as part of a speculate() to get the speculative buffer associated
2309  * with a given speculation.  Returns NULL if the specified speculation is not
2310  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2311  * the active CPU is not the specified CPU -- the speculation will be
2312  * atomically transitioned into the ACTIVEMANY state.
2313  */
2314 static dtrace_buffer_t *
2315 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2316     dtrace_specid_t which)
2317 {
2318 	dtrace_speculation_t *spec;
2319 	dtrace_speculation_state_t current, new;
2320 	dtrace_buffer_t *buf;
2321 
2322 	if (which == 0)
2323 		return (NULL);
2324 
2325 	if (which > state->dts_nspeculations) {
2326 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2327 		return (NULL);
2328 	}
2329 
2330 	spec = &state->dts_speculations[which - 1];
2331 	buf = &spec->dtsp_buffer[cpuid];
2332 
2333 	do {
2334 		current = spec->dtsp_state;
2335 
2336 		switch (current) {
2337 		case DTRACESPEC_INACTIVE:
2338 		case DTRACESPEC_COMMITTINGMANY:
2339 		case DTRACESPEC_DISCARDING:
2340 			return (NULL);
2341 
2342 		case DTRACESPEC_COMMITTING:
2343 			ASSERT(buf->dtb_offset == 0);
2344 			return (NULL);
2345 
2346 		case DTRACESPEC_ACTIVEONE:
2347 			/*
2348 			 * This speculation is currently active on one CPU.
2349 			 * Check the offset in the buffer; if it's non-zero,
2350 			 * that CPU must be us (and we leave the state alone).
2351 			 * If it's zero, assume that we're starting on a new
2352 			 * CPU -- and change the state to indicate that the
2353 			 * speculation is active on more than one CPU.
2354 			 */
2355 			if (buf->dtb_offset != 0)
2356 				return (buf);
2357 
2358 			new = DTRACESPEC_ACTIVEMANY;
2359 			break;
2360 
2361 		case DTRACESPEC_ACTIVEMANY:
2362 			return (buf);
2363 
2364 		case DTRACESPEC_ACTIVE:
2365 			new = DTRACESPEC_ACTIVEONE;
2366 			break;
2367 
2368 		default:
2369 			ASSERT(0);
2370 		}
2371 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2372 	    current, new) != current);
2373 
2374 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2375 	return (buf);
2376 }
2377 
2378 /*
2379  * Return a string.  In the event that the user lacks the privilege to access
2380  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2381  * don't fail access checking.
2382  *
2383  * dtrace_dif_variable() uses this routine as a helper for various
2384  * builtin values such as 'execname' and 'probefunc.'
2385  */
2386 uintptr_t
2387 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2388     dtrace_mstate_t *mstate)
2389 {
2390 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2391 	uintptr_t ret;
2392 	size_t strsz;
2393 
2394 	/*
2395 	 * The easy case: this probe is allowed to read all of memory, so
2396 	 * we can just return this as a vanilla pointer.
2397 	 */
2398 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2399 		return (addr);
2400 
2401 	/*
2402 	 * This is the tougher case: we copy the string in question from
2403 	 * kernel memory into scratch memory and return it that way: this
2404 	 * ensures that we won't trip up when access checking tests the
2405 	 * BYREF return value.
2406 	 */
2407 	strsz = dtrace_strlen((char *)addr, size) + 1;
2408 
2409 	if (mstate->dtms_scratch_ptr + strsz >
2410 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2411 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2412 		return (NULL);
2413 	}
2414 
2415 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2416 	    strsz);
2417 	ret = mstate->dtms_scratch_ptr;
2418 	mstate->dtms_scratch_ptr += strsz;
2419 	return (ret);
2420 }
2421 
2422 /*
2423  * This function implements the DIF emulator's variable lookups.  The emulator
2424  * passes a reserved variable identifier and optional built-in array index.
2425  */
2426 static uint64_t
2427 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2428     uint64_t ndx)
2429 {
2430 	/*
2431 	 * If we're accessing one of the uncached arguments, we'll turn this
2432 	 * into a reference in the args array.
2433 	 */
2434 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2435 		ndx = v - DIF_VAR_ARG0;
2436 		v = DIF_VAR_ARGS;
2437 	}
2438 
2439 	switch (v) {
2440 	case DIF_VAR_ARGS:
2441 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2442 		if (ndx >= sizeof (mstate->dtms_arg) /
2443 		    sizeof (mstate->dtms_arg[0])) {
2444 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2445 			dtrace_provider_t *pv;
2446 			uint64_t val;
2447 
2448 			pv = mstate->dtms_probe->dtpr_provider;
2449 			if (pv->dtpv_pops.dtps_getargval != NULL)
2450 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2451 				    mstate->dtms_probe->dtpr_id,
2452 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
2453 			else
2454 				val = dtrace_getarg(ndx, aframes);
2455 
2456 			/*
2457 			 * This is regrettably required to keep the compiler
2458 			 * from tail-optimizing the call to dtrace_getarg().
2459 			 * The condition always evaluates to true, but the
2460 			 * compiler has no way of figuring that out a priori.
2461 			 * (None of this would be necessary if the compiler
2462 			 * could be relied upon to _always_ tail-optimize
2463 			 * the call to dtrace_getarg() -- but it can't.)
2464 			 */
2465 			if (mstate->dtms_probe != NULL)
2466 				return (val);
2467 
2468 			ASSERT(0);
2469 		}
2470 
2471 		return (mstate->dtms_arg[ndx]);
2472 
2473 	case DIF_VAR_UREGS: {
2474 		klwp_t *lwp;
2475 
2476 		if (!dtrace_priv_proc(state))
2477 			return (0);
2478 
2479 		if ((lwp = curthread->t_lwp) == NULL) {
2480 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2481 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
2482 			return (0);
2483 		}
2484 
2485 		return (dtrace_getreg(lwp->lwp_regs, ndx));
2486 	}
2487 
2488 	case DIF_VAR_CURTHREAD:
2489 		if (!dtrace_priv_kernel(state))
2490 			return (0);
2491 		return ((uint64_t)(uintptr_t)curthread);
2492 
2493 	case DIF_VAR_TIMESTAMP:
2494 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2495 			mstate->dtms_timestamp = dtrace_gethrtime();
2496 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2497 		}
2498 		return (mstate->dtms_timestamp);
2499 
2500 	case DIF_VAR_VTIMESTAMP:
2501 		ASSERT(dtrace_vtime_references != 0);
2502 		return (curthread->t_dtrace_vtime);
2503 
2504 	case DIF_VAR_WALLTIMESTAMP:
2505 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2506 			mstate->dtms_walltimestamp = dtrace_gethrestime();
2507 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2508 		}
2509 		return (mstate->dtms_walltimestamp);
2510 
2511 	case DIF_VAR_IPL:
2512 		if (!dtrace_priv_kernel(state))
2513 			return (0);
2514 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2515 			mstate->dtms_ipl = dtrace_getipl();
2516 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
2517 		}
2518 		return (mstate->dtms_ipl);
2519 
2520 	case DIF_VAR_EPID:
2521 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2522 		return (mstate->dtms_epid);
2523 
2524 	case DIF_VAR_ID:
2525 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2526 		return (mstate->dtms_probe->dtpr_id);
2527 
2528 	case DIF_VAR_STACKDEPTH:
2529 		if (!dtrace_priv_kernel(state))
2530 			return (0);
2531 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2532 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2533 
2534 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2535 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2536 		}
2537 		return (mstate->dtms_stackdepth);
2538 
2539 	case DIF_VAR_USTACKDEPTH:
2540 		if (!dtrace_priv_proc(state))
2541 			return (0);
2542 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2543 			/*
2544 			 * See comment in DIF_VAR_PID.
2545 			 */
2546 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2547 			    CPU_ON_INTR(CPU)) {
2548 				mstate->dtms_ustackdepth = 0;
2549 			} else {
2550 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2551 				mstate->dtms_ustackdepth =
2552 				    dtrace_getustackdepth();
2553 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2554 			}
2555 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2556 		}
2557 		return (mstate->dtms_ustackdepth);
2558 
2559 	case DIF_VAR_CALLER:
2560 		if (!dtrace_priv_kernel(state))
2561 			return (0);
2562 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2563 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2564 
2565 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2566 				/*
2567 				 * If this is an unanchored probe, we are
2568 				 * required to go through the slow path:
2569 				 * dtrace_caller() only guarantees correct
2570 				 * results for anchored probes.
2571 				 */
2572 				pc_t caller[2];
2573 
2574 				dtrace_getpcstack(caller, 2, aframes,
2575 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2576 				mstate->dtms_caller = caller[1];
2577 			} else if ((mstate->dtms_caller =
2578 			    dtrace_caller(aframes)) == -1) {
2579 				/*
2580 				 * We have failed to do this the quick way;
2581 				 * we must resort to the slower approach of
2582 				 * calling dtrace_getpcstack().
2583 				 */
2584 				pc_t caller;
2585 
2586 				dtrace_getpcstack(&caller, 1, aframes, NULL);
2587 				mstate->dtms_caller = caller;
2588 			}
2589 
2590 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
2591 		}
2592 		return (mstate->dtms_caller);
2593 
2594 	case DIF_VAR_UCALLER:
2595 		if (!dtrace_priv_proc(state))
2596 			return (0);
2597 
2598 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
2599 			uint64_t ustack[3];
2600 
2601 			/*
2602 			 * dtrace_getupcstack() fills in the first uint64_t
2603 			 * with the current PID.  The second uint64_t will
2604 			 * be the program counter at user-level.  The third
2605 			 * uint64_t will contain the caller, which is what
2606 			 * we're after.
2607 			 */
2608 			ustack[2] = NULL;
2609 			dtrace_getupcstack(ustack, 3);
2610 			mstate->dtms_ucaller = ustack[2];
2611 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
2612 		}
2613 
2614 		return (mstate->dtms_ucaller);
2615 
2616 	case DIF_VAR_PROBEPROV:
2617 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2618 		return (dtrace_dif_varstr(
2619 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
2620 		    state, mstate));
2621 
2622 	case DIF_VAR_PROBEMOD:
2623 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2624 		return (dtrace_dif_varstr(
2625 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
2626 		    state, mstate));
2627 
2628 	case DIF_VAR_PROBEFUNC:
2629 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2630 		return (dtrace_dif_varstr(
2631 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
2632 		    state, mstate));
2633 
2634 	case DIF_VAR_PROBENAME:
2635 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2636 		return (dtrace_dif_varstr(
2637 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
2638 		    state, mstate));
2639 
2640 	case DIF_VAR_PID:
2641 		if (!dtrace_priv_proc(state))
2642 			return (0);
2643 
2644 		/*
2645 		 * Note that we are assuming that an unanchored probe is
2646 		 * always due to a high-level interrupt.  (And we're assuming
2647 		 * that there is only a single high level interrupt.)
2648 		 */
2649 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2650 			return (pid0.pid_id);
2651 
2652 		/*
2653 		 * It is always safe to dereference one's own t_procp pointer:
2654 		 * it always points to a valid, allocated proc structure.
2655 		 * Further, it is always safe to dereference the p_pidp member
2656 		 * of one's own proc structure.  (These are truisms becuase
2657 		 * threads and processes don't clean up their own state --
2658 		 * they leave that task to whomever reaps them.)
2659 		 */
2660 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
2661 
2662 	case DIF_VAR_PPID:
2663 		if (!dtrace_priv_proc(state))
2664 			return (0);
2665 
2666 		/*
2667 		 * See comment in DIF_VAR_PID.
2668 		 */
2669 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2670 			return (pid0.pid_id);
2671 
2672 		/*
2673 		 * It is always safe to dereference one's own t_procp pointer:
2674 		 * it always points to a valid, allocated proc structure.
2675 		 * (This is true because threads don't clean up their own
2676 		 * state -- they leave that task to whomever reaps them.)
2677 		 */
2678 		return ((uint64_t)curthread->t_procp->p_ppid);
2679 
2680 	case DIF_VAR_TID:
2681 		/*
2682 		 * See comment in DIF_VAR_PID.
2683 		 */
2684 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2685 			return (0);
2686 
2687 		return ((uint64_t)curthread->t_tid);
2688 
2689 	case DIF_VAR_EXECNAME:
2690 		if (!dtrace_priv_proc(state))
2691 			return (0);
2692 
2693 		/*
2694 		 * See comment in DIF_VAR_PID.
2695 		 */
2696 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2697 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
2698 
2699 		/*
2700 		 * It is always safe to dereference one's own t_procp pointer:
2701 		 * it always points to a valid, allocated proc structure.
2702 		 * (This is true because threads don't clean up their own
2703 		 * state -- they leave that task to whomever reaps them.)
2704 		 */
2705 		return (dtrace_dif_varstr(
2706 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
2707 		    state, mstate));
2708 
2709 	case DIF_VAR_ZONENAME:
2710 		if (!dtrace_priv_proc(state))
2711 			return (0);
2712 
2713 		/*
2714 		 * See comment in DIF_VAR_PID.
2715 		 */
2716 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2717 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
2718 
2719 		/*
2720 		 * It is always safe to dereference one's own t_procp pointer:
2721 		 * it always points to a valid, allocated proc structure.
2722 		 * (This is true because threads don't clean up their own
2723 		 * state -- they leave that task to whomever reaps them.)
2724 		 */
2725 		return (dtrace_dif_varstr(
2726 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
2727 		    state, mstate));
2728 
2729 	case DIF_VAR_UID:
2730 		if (!dtrace_priv_proc(state))
2731 			return (0);
2732 
2733 		/*
2734 		 * See comment in DIF_VAR_PID.
2735 		 */
2736 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2737 			return ((uint64_t)p0.p_cred->cr_uid);
2738 
2739 		/*
2740 		 * It is always safe to dereference one's own t_procp pointer:
2741 		 * it always points to a valid, allocated proc structure.
2742 		 * (This is true because threads don't clean up their own
2743 		 * state -- they leave that task to whomever reaps them.)
2744 		 *
2745 		 * Additionally, it is safe to dereference one's own process
2746 		 * credential, since this is never NULL after process birth.
2747 		 */
2748 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
2749 
2750 	case DIF_VAR_GID:
2751 		if (!dtrace_priv_proc(state))
2752 			return (0);
2753 
2754 		/*
2755 		 * See comment in DIF_VAR_PID.
2756 		 */
2757 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2758 			return ((uint64_t)p0.p_cred->cr_gid);
2759 
2760 		/*
2761 		 * It is always safe to dereference one's own t_procp pointer:
2762 		 * it always points to a valid, allocated proc structure.
2763 		 * (This is true because threads don't clean up their own
2764 		 * state -- they leave that task to whomever reaps them.)
2765 		 *
2766 		 * Additionally, it is safe to dereference one's own process
2767 		 * credential, since this is never NULL after process birth.
2768 		 */
2769 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
2770 
2771 	case DIF_VAR_ERRNO: {
2772 		klwp_t *lwp;
2773 		if (!dtrace_priv_proc(state))
2774 			return (0);
2775 
2776 		/*
2777 		 * See comment in DIF_VAR_PID.
2778 		 */
2779 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2780 			return (0);
2781 
2782 		/*
2783 		 * It is always safe to dereference one's own t_lwp pointer in
2784 		 * the event that this pointer is non-NULL.  (This is true
2785 		 * because threads and lwps don't clean up their own state --
2786 		 * they leave that task to whomever reaps them.)
2787 		 */
2788 		if ((lwp = curthread->t_lwp) == NULL)
2789 			return (0);
2790 
2791 		return ((uint64_t)lwp->lwp_errno);
2792 	}
2793 	default:
2794 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2795 		return (0);
2796 	}
2797 }
2798 
2799 /*
2800  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
2801  * Notice that we don't bother validating the proper number of arguments or
2802  * their types in the tuple stack.  This isn't needed because all argument
2803  * interpretation is safe because of our load safety -- the worst that can
2804  * happen is that a bogus program can obtain bogus results.
2805  */
2806 static void
2807 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
2808     dtrace_key_t *tupregs, int nargs,
2809     dtrace_mstate_t *mstate, dtrace_state_t *state)
2810 {
2811 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
2812 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
2813 	dtrace_vstate_t *vstate = &state->dts_vstate;
2814 
2815 	union {
2816 		mutex_impl_t mi;
2817 		uint64_t mx;
2818 	} m;
2819 
2820 	union {
2821 		krwlock_t ri;
2822 		uintptr_t rw;
2823 	} r;
2824 
2825 	switch (subr) {
2826 	case DIF_SUBR_RAND:
2827 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
2828 		break;
2829 
2830 	case DIF_SUBR_MUTEX_OWNED:
2831 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2832 		    mstate, vstate)) {
2833 			regs[rd] = NULL;
2834 			break;
2835 		}
2836 
2837 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2838 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
2839 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
2840 		else
2841 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
2842 		break;
2843 
2844 	case DIF_SUBR_MUTEX_OWNER:
2845 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2846 		    mstate, vstate)) {
2847 			regs[rd] = NULL;
2848 			break;
2849 		}
2850 
2851 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2852 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
2853 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
2854 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
2855 		else
2856 			regs[rd] = 0;
2857 		break;
2858 
2859 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
2860 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2861 		    mstate, vstate)) {
2862 			regs[rd] = NULL;
2863 			break;
2864 		}
2865 
2866 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2867 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
2868 		break;
2869 
2870 	case DIF_SUBR_MUTEX_TYPE_SPIN:
2871 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2872 		    mstate, vstate)) {
2873 			regs[rd] = NULL;
2874 			break;
2875 		}
2876 
2877 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2878 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
2879 		break;
2880 
2881 	case DIF_SUBR_RW_READ_HELD: {
2882 		uintptr_t tmp;
2883 
2884 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
2885 		    mstate, vstate)) {
2886 			regs[rd] = NULL;
2887 			break;
2888 		}
2889 
2890 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2891 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
2892 		break;
2893 	}
2894 
2895 	case DIF_SUBR_RW_WRITE_HELD:
2896 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
2897 		    mstate, vstate)) {
2898 			regs[rd] = NULL;
2899 			break;
2900 		}
2901 
2902 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2903 		regs[rd] = _RW_WRITE_HELD(&r.ri);
2904 		break;
2905 
2906 	case DIF_SUBR_RW_ISWRITER:
2907 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
2908 		    mstate, vstate)) {
2909 			regs[rd] = NULL;
2910 			break;
2911 		}
2912 
2913 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2914 		regs[rd] = _RW_ISWRITER(&r.ri);
2915 		break;
2916 
2917 	case DIF_SUBR_BCOPY: {
2918 		/*
2919 		 * We need to be sure that the destination is in the scratch
2920 		 * region -- no other region is allowed.
2921 		 */
2922 		uintptr_t src = tupregs[0].dttk_value;
2923 		uintptr_t dest = tupregs[1].dttk_value;
2924 		size_t size = tupregs[2].dttk_value;
2925 
2926 		if (!dtrace_inscratch(dest, size, mstate)) {
2927 			*flags |= CPU_DTRACE_BADADDR;
2928 			*illval = regs[rd];
2929 			break;
2930 		}
2931 
2932 		if (!dtrace_canload(src, size, mstate, vstate)) {
2933 			regs[rd] = NULL;
2934 			break;
2935 		}
2936 
2937 		dtrace_bcopy((void *)src, (void *)dest, size);
2938 		break;
2939 	}
2940 
2941 	case DIF_SUBR_ALLOCA:
2942 	case DIF_SUBR_COPYIN: {
2943 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
2944 		uint64_t size =
2945 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
2946 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
2947 
2948 		/*
2949 		 * This action doesn't require any credential checks since
2950 		 * probes will not activate in user contexts to which the
2951 		 * enabling user does not have permissions.
2952 		 */
2953 
2954 		/*
2955 		 * Rounding up the user allocation size could have overflowed
2956 		 * a large, bogus allocation (like -1ULL) to 0.
2957 		 */
2958 		if (scratch_size < size ||
2959 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
2960 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2961 			regs[rd] = NULL;
2962 			break;
2963 		}
2964 
2965 		if (subr == DIF_SUBR_COPYIN) {
2966 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2967 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
2968 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2969 		}
2970 
2971 		mstate->dtms_scratch_ptr += scratch_size;
2972 		regs[rd] = dest;
2973 		break;
2974 	}
2975 
2976 	case DIF_SUBR_COPYINTO: {
2977 		uint64_t size = tupregs[1].dttk_value;
2978 		uintptr_t dest = tupregs[2].dttk_value;
2979 
2980 		/*
2981 		 * This action doesn't require any credential checks since
2982 		 * probes will not activate in user contexts to which the
2983 		 * enabling user does not have permissions.
2984 		 */
2985 		if (!dtrace_inscratch(dest, size, mstate)) {
2986 			*flags |= CPU_DTRACE_BADADDR;
2987 			*illval = regs[rd];
2988 			break;
2989 		}
2990 
2991 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2992 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
2993 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2994 		break;
2995 	}
2996 
2997 	case DIF_SUBR_COPYINSTR: {
2998 		uintptr_t dest = mstate->dtms_scratch_ptr;
2999 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3000 
3001 		if (nargs > 1 && tupregs[1].dttk_value < size)
3002 			size = tupregs[1].dttk_value + 1;
3003 
3004 		/*
3005 		 * This action doesn't require any credential checks since
3006 		 * probes will not activate in user contexts to which the
3007 		 * enabling user does not have permissions.
3008 		 */
3009 		if (!DTRACE_INSCRATCH(mstate, size)) {
3010 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3011 			regs[rd] = NULL;
3012 			break;
3013 		}
3014 
3015 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3016 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3017 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3018 
3019 		((char *)dest)[size - 1] = '\0';
3020 		mstate->dtms_scratch_ptr += size;
3021 		regs[rd] = dest;
3022 		break;
3023 	}
3024 
3025 	case DIF_SUBR_MSGSIZE:
3026 	case DIF_SUBR_MSGDSIZE: {
3027 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
3028 		uintptr_t wptr, rptr;
3029 		size_t count = 0;
3030 		int cont = 0;
3031 
3032 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3033 
3034 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3035 			    vstate)) {
3036 				regs[rd] = NULL;
3037 				break;
3038 			}
3039 
3040 			wptr = dtrace_loadptr(baddr +
3041 			    offsetof(mblk_t, b_wptr));
3042 
3043 			rptr = dtrace_loadptr(baddr +
3044 			    offsetof(mblk_t, b_rptr));
3045 
3046 			if (wptr < rptr) {
3047 				*flags |= CPU_DTRACE_BADADDR;
3048 				*illval = tupregs[0].dttk_value;
3049 				break;
3050 			}
3051 
3052 			daddr = dtrace_loadptr(baddr +
3053 			    offsetof(mblk_t, b_datap));
3054 
3055 			baddr = dtrace_loadptr(baddr +
3056 			    offsetof(mblk_t, b_cont));
3057 
3058 			/*
3059 			 * We want to prevent against denial-of-service here,
3060 			 * so we're only going to search the list for
3061 			 * dtrace_msgdsize_max mblks.
3062 			 */
3063 			if (cont++ > dtrace_msgdsize_max) {
3064 				*flags |= CPU_DTRACE_ILLOP;
3065 				break;
3066 			}
3067 
3068 			if (subr == DIF_SUBR_MSGDSIZE) {
3069 				if (dtrace_load8(daddr +
3070 				    offsetof(dblk_t, db_type)) != M_DATA)
3071 					continue;
3072 			}
3073 
3074 			count += wptr - rptr;
3075 		}
3076 
3077 		if (!(*flags & CPU_DTRACE_FAULT))
3078 			regs[rd] = count;
3079 
3080 		break;
3081 	}
3082 
3083 	case DIF_SUBR_PROGENYOF: {
3084 		pid_t pid = tupregs[0].dttk_value;
3085 		proc_t *p;
3086 		int rval = 0;
3087 
3088 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3089 
3090 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3091 			if (p->p_pidp->pid_id == pid) {
3092 				rval = 1;
3093 				break;
3094 			}
3095 		}
3096 
3097 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3098 
3099 		regs[rd] = rval;
3100 		break;
3101 	}
3102 
3103 	case DIF_SUBR_SPECULATION:
3104 		regs[rd] = dtrace_speculation(state);
3105 		break;
3106 
3107 	case DIF_SUBR_COPYOUT: {
3108 		uintptr_t kaddr = tupregs[0].dttk_value;
3109 		uintptr_t uaddr = tupregs[1].dttk_value;
3110 		uint64_t size = tupregs[2].dttk_value;
3111 
3112 		if (!dtrace_destructive_disallow &&
3113 		    dtrace_priv_proc_control(state) &&
3114 		    !dtrace_istoxic(kaddr, size)) {
3115 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3116 			dtrace_copyout(kaddr, uaddr, size, flags);
3117 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3118 		}
3119 		break;
3120 	}
3121 
3122 	case DIF_SUBR_COPYOUTSTR: {
3123 		uintptr_t kaddr = tupregs[0].dttk_value;
3124 		uintptr_t uaddr = tupregs[1].dttk_value;
3125 		uint64_t size = tupregs[2].dttk_value;
3126 
3127 		if (!dtrace_destructive_disallow &&
3128 		    dtrace_priv_proc_control(state) &&
3129 		    !dtrace_istoxic(kaddr, size)) {
3130 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3131 			dtrace_copyoutstr(kaddr, uaddr, size, flags);
3132 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3133 		}
3134 		break;
3135 	}
3136 
3137 	case DIF_SUBR_STRLEN: {
3138 		size_t sz;
3139 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3140 		sz = dtrace_strlen((char *)addr,
3141 		    state->dts_options[DTRACEOPT_STRSIZE]);
3142 
3143 		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3144 			regs[rd] = NULL;
3145 			break;
3146 		}
3147 
3148 		regs[rd] = sz;
3149 
3150 		break;
3151 	}
3152 
3153 	case DIF_SUBR_STRCHR:
3154 	case DIF_SUBR_STRRCHR: {
3155 		/*
3156 		 * We're going to iterate over the string looking for the
3157 		 * specified character.  We will iterate until we have reached
3158 		 * the string length or we have found the character.  If this
3159 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3160 		 * of the specified character instead of the first.
3161 		 */
3162 		uintptr_t saddr = tupregs[0].dttk_value;
3163 		uintptr_t addr = tupregs[0].dttk_value;
3164 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3165 		char c, target = (char)tupregs[1].dttk_value;
3166 
3167 		for (regs[rd] = NULL; addr < limit; addr++) {
3168 			if ((c = dtrace_load8(addr)) == target) {
3169 				regs[rd] = addr;
3170 
3171 				if (subr == DIF_SUBR_STRCHR)
3172 					break;
3173 			}
3174 
3175 			if (c == '\0')
3176 				break;
3177 		}
3178 
3179 		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3180 			regs[rd] = NULL;
3181 			break;
3182 		}
3183 
3184 		break;
3185 	}
3186 
3187 	case DIF_SUBR_STRSTR:
3188 	case DIF_SUBR_INDEX:
3189 	case DIF_SUBR_RINDEX: {
3190 		/*
3191 		 * We're going to iterate over the string looking for the
3192 		 * specified string.  We will iterate until we have reached
3193 		 * the string length or we have found the string.  (Yes, this
3194 		 * is done in the most naive way possible -- but considering
3195 		 * that the string we're searching for is likely to be
3196 		 * relatively short, the complexity of Rabin-Karp or similar
3197 		 * hardly seems merited.)
3198 		 */
3199 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3200 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3201 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3202 		size_t len = dtrace_strlen(addr, size);
3203 		size_t sublen = dtrace_strlen(substr, size);
3204 		char *limit = addr + len, *orig = addr;
3205 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3206 		int inc = 1;
3207 
3208 		regs[rd] = notfound;
3209 
3210 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3211 			regs[rd] = NULL;
3212 			break;
3213 		}
3214 
3215 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3216 		    vstate)) {
3217 			regs[rd] = NULL;
3218 			break;
3219 		}
3220 
3221 		/*
3222 		 * strstr() and index()/rindex() have similar semantics if
3223 		 * both strings are the empty string: strstr() returns a
3224 		 * pointer to the (empty) string, and index() and rindex()
3225 		 * both return index 0 (regardless of any position argument).
3226 		 */
3227 		if (sublen == 0 && len == 0) {
3228 			if (subr == DIF_SUBR_STRSTR)
3229 				regs[rd] = (uintptr_t)addr;
3230 			else
3231 				regs[rd] = 0;
3232 			break;
3233 		}
3234 
3235 		if (subr != DIF_SUBR_STRSTR) {
3236 			if (subr == DIF_SUBR_RINDEX) {
3237 				limit = orig - 1;
3238 				addr += len;
3239 				inc = -1;
3240 			}
3241 
3242 			/*
3243 			 * Both index() and rindex() take an optional position
3244 			 * argument that denotes the starting position.
3245 			 */
3246 			if (nargs == 3) {
3247 				int64_t pos = (int64_t)tupregs[2].dttk_value;
3248 
3249 				/*
3250 				 * If the position argument to index() is
3251 				 * negative, Perl implicitly clamps it at
3252 				 * zero.  This semantic is a little surprising
3253 				 * given the special meaning of negative
3254 				 * positions to similar Perl functions like
3255 				 * substr(), but it appears to reflect a
3256 				 * notion that index() can start from a
3257 				 * negative index and increment its way up to
3258 				 * the string.  Given this notion, Perl's
3259 				 * rindex() is at least self-consistent in
3260 				 * that it implicitly clamps positions greater
3261 				 * than the string length to be the string
3262 				 * length.  Where Perl completely loses
3263 				 * coherence, however, is when the specified
3264 				 * substring is the empty string ("").  In
3265 				 * this case, even if the position is
3266 				 * negative, rindex() returns 0 -- and even if
3267 				 * the position is greater than the length,
3268 				 * index() returns the string length.  These
3269 				 * semantics violate the notion that index()
3270 				 * should never return a value less than the
3271 				 * specified position and that rindex() should
3272 				 * never return a value greater than the
3273 				 * specified position.  (One assumes that
3274 				 * these semantics are artifacts of Perl's
3275 				 * implementation and not the results of
3276 				 * deliberate design -- it beggars belief that
3277 				 * even Larry Wall could desire such oddness.)
3278 				 * While in the abstract one would wish for
3279 				 * consistent position semantics across
3280 				 * substr(), index() and rindex() -- or at the
3281 				 * very least self-consistent position
3282 				 * semantics for index() and rindex() -- we
3283 				 * instead opt to keep with the extant Perl
3284 				 * semantics, in all their broken glory.  (Do
3285 				 * we have more desire to maintain Perl's
3286 				 * semantics than Perl does?  Probably.)
3287 				 */
3288 				if (subr == DIF_SUBR_RINDEX) {
3289 					if (pos < 0) {
3290 						if (sublen == 0)
3291 							regs[rd] = 0;
3292 						break;
3293 					}
3294 
3295 					if (pos > len)
3296 						pos = len;
3297 				} else {
3298 					if (pos < 0)
3299 						pos = 0;
3300 
3301 					if (pos >= len) {
3302 						if (sublen == 0)
3303 							regs[rd] = len;
3304 						break;
3305 					}
3306 				}
3307 
3308 				addr = orig + pos;
3309 			}
3310 		}
3311 
3312 		for (regs[rd] = notfound; addr != limit; addr += inc) {
3313 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
3314 				if (subr != DIF_SUBR_STRSTR) {
3315 					/*
3316 					 * As D index() and rindex() are
3317 					 * modeled on Perl (and not on awk),
3318 					 * we return a zero-based (and not a
3319 					 * one-based) index.  (For you Perl
3320 					 * weenies: no, we're not going to add
3321 					 * $[ -- and shouldn't you be at a con
3322 					 * or something?)
3323 					 */
3324 					regs[rd] = (uintptr_t)(addr - orig);
3325 					break;
3326 				}
3327 
3328 				ASSERT(subr == DIF_SUBR_STRSTR);
3329 				regs[rd] = (uintptr_t)addr;
3330 				break;
3331 			}
3332 		}
3333 
3334 		break;
3335 	}
3336 
3337 	case DIF_SUBR_STRTOK: {
3338 		uintptr_t addr = tupregs[0].dttk_value;
3339 		uintptr_t tokaddr = tupregs[1].dttk_value;
3340 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3341 		uintptr_t limit, toklimit = tokaddr + size;
3342 		uint8_t c, tokmap[32];	 /* 256 / 8 */
3343 		char *dest = (char *)mstate->dtms_scratch_ptr;
3344 		int i;
3345 
3346 		/*
3347 		 * Check both the token buffer and (later) the input buffer,
3348 		 * since both could be non-scratch addresses.
3349 		 */
3350 		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3351 			regs[rd] = NULL;
3352 			break;
3353 		}
3354 
3355 		if (!DTRACE_INSCRATCH(mstate, size)) {
3356 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3357 			regs[rd] = NULL;
3358 			break;
3359 		}
3360 
3361 		if (addr == NULL) {
3362 			/*
3363 			 * If the address specified is NULL, we use our saved
3364 			 * strtok pointer from the mstate.  Note that this
3365 			 * means that the saved strtok pointer is _only_
3366 			 * valid within multiple enablings of the same probe --
3367 			 * it behaves like an implicit clause-local variable.
3368 			 */
3369 			addr = mstate->dtms_strtok;
3370 		} else {
3371 			/*
3372 			 * If the user-specified address is non-NULL we must
3373 			 * access check it.  This is the only time we have
3374 			 * a chance to do so, since this address may reside
3375 			 * in the string table of this clause-- future calls
3376 			 * (when we fetch addr from mstate->dtms_strtok)
3377 			 * would fail this access check.
3378 			 */
3379 			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3380 				regs[rd] = NULL;
3381 				break;
3382 			}
3383 		}
3384 
3385 		/*
3386 		 * First, zero the token map, and then process the token
3387 		 * string -- setting a bit in the map for every character
3388 		 * found in the token string.
3389 		 */
3390 		for (i = 0; i < sizeof (tokmap); i++)
3391 			tokmap[i] = 0;
3392 
3393 		for (; tokaddr < toklimit; tokaddr++) {
3394 			if ((c = dtrace_load8(tokaddr)) == '\0')
3395 				break;
3396 
3397 			ASSERT((c >> 3) < sizeof (tokmap));
3398 			tokmap[c >> 3] |= (1 << (c & 0x7));
3399 		}
3400 
3401 		for (limit = addr + size; addr < limit; addr++) {
3402 			/*
3403 			 * We're looking for a character that is _not_ contained
3404 			 * in the token string.
3405 			 */
3406 			if ((c = dtrace_load8(addr)) == '\0')
3407 				break;
3408 
3409 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3410 				break;
3411 		}
3412 
3413 		if (c == '\0') {
3414 			/*
3415 			 * We reached the end of the string without finding
3416 			 * any character that was not in the token string.
3417 			 * We return NULL in this case, and we set the saved
3418 			 * address to NULL as well.
3419 			 */
3420 			regs[rd] = NULL;
3421 			mstate->dtms_strtok = NULL;
3422 			break;
3423 		}
3424 
3425 		/*
3426 		 * From here on, we're copying into the destination string.
3427 		 */
3428 		for (i = 0; addr < limit && i < size - 1; addr++) {
3429 			if ((c = dtrace_load8(addr)) == '\0')
3430 				break;
3431 
3432 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
3433 				break;
3434 
3435 			ASSERT(i < size);
3436 			dest[i++] = c;
3437 		}
3438 
3439 		ASSERT(i < size);
3440 		dest[i] = '\0';
3441 		regs[rd] = (uintptr_t)dest;
3442 		mstate->dtms_scratch_ptr += size;
3443 		mstate->dtms_strtok = addr;
3444 		break;
3445 	}
3446 
3447 	case DIF_SUBR_SUBSTR: {
3448 		uintptr_t s = tupregs[0].dttk_value;
3449 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3450 		char *d = (char *)mstate->dtms_scratch_ptr;
3451 		int64_t index = (int64_t)tupregs[1].dttk_value;
3452 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
3453 		size_t len = dtrace_strlen((char *)s, size);
3454 		int64_t i = 0;
3455 
3456 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
3457 			regs[rd] = NULL;
3458 			break;
3459 		}
3460 
3461 		if (nargs <= 2)
3462 			remaining = (int64_t)size;
3463 
3464 		if (!DTRACE_INSCRATCH(mstate, size)) {
3465 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3466 			regs[rd] = NULL;
3467 			break;
3468 		}
3469 
3470 		if (index < 0) {
3471 			index += len;
3472 
3473 			if (index < 0 && index + remaining > 0) {
3474 				remaining += index;
3475 				index = 0;
3476 			}
3477 		}
3478 
3479 		if (index >= len || index < 0)
3480 			index = len;
3481 
3482 		for (d[0] = '\0'; remaining > 0; remaining--) {
3483 			if ((d[i++] = dtrace_load8(s++ + index)) == '\0')
3484 				break;
3485 
3486 			if (i == size) {
3487 				d[i - 1] = '\0';
3488 				break;
3489 			}
3490 		}
3491 
3492 		mstate->dtms_scratch_ptr += size;
3493 		regs[rd] = (uintptr_t)d;
3494 		break;
3495 	}
3496 
3497 	case DIF_SUBR_GETMAJOR:
3498 #ifdef _LP64
3499 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
3500 #else
3501 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
3502 #endif
3503 		break;
3504 
3505 	case DIF_SUBR_GETMINOR:
3506 #ifdef _LP64
3507 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
3508 #else
3509 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
3510 #endif
3511 		break;
3512 
3513 	case DIF_SUBR_DDI_PATHNAME: {
3514 		/*
3515 		 * This one is a galactic mess.  We are going to roughly
3516 		 * emulate ddi_pathname(), but it's made more complicated
3517 		 * by the fact that we (a) want to include the minor name and
3518 		 * (b) must proceed iteratively instead of recursively.
3519 		 */
3520 		uintptr_t dest = mstate->dtms_scratch_ptr;
3521 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3522 		char *start = (char *)dest, *end = start + size - 1;
3523 		uintptr_t daddr = tupregs[0].dttk_value;
3524 		int64_t minor = (int64_t)tupregs[1].dttk_value;
3525 		char *s;
3526 		int i, len, depth = 0;
3527 
3528 		/*
3529 		 * Due to all the pointer jumping we do and context we must
3530 		 * rely upon, we just mandate that the user must have kernel
3531 		 * read privileges to use this routine.
3532 		 */
3533 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
3534 			*flags |= CPU_DTRACE_KPRIV;
3535 			*illval = daddr;
3536 			regs[rd] = NULL;
3537 		}
3538 
3539 		if (!DTRACE_INSCRATCH(mstate, size)) {
3540 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3541 			regs[rd] = NULL;
3542 			break;
3543 		}
3544 
3545 		*end = '\0';
3546 
3547 		/*
3548 		 * We want to have a name for the minor.  In order to do this,
3549 		 * we need to walk the minor list from the devinfo.  We want
3550 		 * to be sure that we don't infinitely walk a circular list,
3551 		 * so we check for circularity by sending a scout pointer
3552 		 * ahead two elements for every element that we iterate over;
3553 		 * if the list is circular, these will ultimately point to the
3554 		 * same element.  You may recognize this little trick as the
3555 		 * answer to a stupid interview question -- one that always
3556 		 * seems to be asked by those who had to have it laboriously
3557 		 * explained to them, and who can't even concisely describe
3558 		 * the conditions under which one would be forced to resort to
3559 		 * this technique.  Needless to say, those conditions are
3560 		 * found here -- and probably only here.  Is this is the only
3561 		 * use of this infamous trick in shipping, production code?
3562 		 * If it isn't, it probably should be...
3563 		 */
3564 		if (minor != -1) {
3565 			uintptr_t maddr = dtrace_loadptr(daddr +
3566 			    offsetof(struct dev_info, devi_minor));
3567 
3568 			uintptr_t next = offsetof(struct ddi_minor_data, next);
3569 			uintptr_t name = offsetof(struct ddi_minor_data,
3570 			    d_minor) + offsetof(struct ddi_minor, name);
3571 			uintptr_t dev = offsetof(struct ddi_minor_data,
3572 			    d_minor) + offsetof(struct ddi_minor, dev);
3573 			uintptr_t scout;
3574 
3575 			if (maddr != NULL)
3576 				scout = dtrace_loadptr(maddr + next);
3577 
3578 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3579 				uint64_t m;
3580 #ifdef _LP64
3581 				m = dtrace_load64(maddr + dev) & MAXMIN64;
3582 #else
3583 				m = dtrace_load32(maddr + dev) & MAXMIN;
3584 #endif
3585 				if (m != minor) {
3586 					maddr = dtrace_loadptr(maddr + next);
3587 
3588 					if (scout == NULL)
3589 						continue;
3590 
3591 					scout = dtrace_loadptr(scout + next);
3592 
3593 					if (scout == NULL)
3594 						continue;
3595 
3596 					scout = dtrace_loadptr(scout + next);
3597 
3598 					if (scout == NULL)
3599 						continue;
3600 
3601 					if (scout == maddr) {
3602 						*flags |= CPU_DTRACE_ILLOP;
3603 						break;
3604 					}
3605 
3606 					continue;
3607 				}
3608 
3609 				/*
3610 				 * We have the minor data.  Now we need to
3611 				 * copy the minor's name into the end of the
3612 				 * pathname.
3613 				 */
3614 				s = (char *)dtrace_loadptr(maddr + name);
3615 				len = dtrace_strlen(s, size);
3616 
3617 				if (*flags & CPU_DTRACE_FAULT)
3618 					break;
3619 
3620 				if (len != 0) {
3621 					if ((end -= (len + 1)) < start)
3622 						break;
3623 
3624 					*end = ':';
3625 				}
3626 
3627 				for (i = 1; i <= len; i++)
3628 					end[i] = dtrace_load8((uintptr_t)s++);
3629 				break;
3630 			}
3631 		}
3632 
3633 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3634 			ddi_node_state_t devi_state;
3635 
3636 			devi_state = dtrace_load32(daddr +
3637 			    offsetof(struct dev_info, devi_node_state));
3638 
3639 			if (*flags & CPU_DTRACE_FAULT)
3640 				break;
3641 
3642 			if (devi_state >= DS_INITIALIZED) {
3643 				s = (char *)dtrace_loadptr(daddr +
3644 				    offsetof(struct dev_info, devi_addr));
3645 				len = dtrace_strlen(s, size);
3646 
3647 				if (*flags & CPU_DTRACE_FAULT)
3648 					break;
3649 
3650 				if (len != 0) {
3651 					if ((end -= (len + 1)) < start)
3652 						break;
3653 
3654 					*end = '@';
3655 				}
3656 
3657 				for (i = 1; i <= len; i++)
3658 					end[i] = dtrace_load8((uintptr_t)s++);
3659 			}
3660 
3661 			/*
3662 			 * Now for the node name...
3663 			 */
3664 			s = (char *)dtrace_loadptr(daddr +
3665 			    offsetof(struct dev_info, devi_node_name));
3666 
3667 			daddr = dtrace_loadptr(daddr +
3668 			    offsetof(struct dev_info, devi_parent));
3669 
3670 			/*
3671 			 * If our parent is NULL (that is, if we're the root
3672 			 * node), we're going to use the special path
3673 			 * "devices".
3674 			 */
3675 			if (daddr == NULL)
3676 				s = "devices";
3677 
3678 			len = dtrace_strlen(s, size);
3679 			if (*flags & CPU_DTRACE_FAULT)
3680 				break;
3681 
3682 			if ((end -= (len + 1)) < start)
3683 				break;
3684 
3685 			for (i = 1; i <= len; i++)
3686 				end[i] = dtrace_load8((uintptr_t)s++);
3687 			*end = '/';
3688 
3689 			if (depth++ > dtrace_devdepth_max) {
3690 				*flags |= CPU_DTRACE_ILLOP;
3691 				break;
3692 			}
3693 		}
3694 
3695 		if (end < start)
3696 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3697 
3698 		if (daddr == NULL) {
3699 			regs[rd] = (uintptr_t)end;
3700 			mstate->dtms_scratch_ptr += size;
3701 		}
3702 
3703 		break;
3704 	}
3705 
3706 	case DIF_SUBR_STRJOIN: {
3707 		char *d = (char *)mstate->dtms_scratch_ptr;
3708 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3709 		uintptr_t s1 = tupregs[0].dttk_value;
3710 		uintptr_t s2 = tupregs[1].dttk_value;
3711 		int i = 0;
3712 
3713 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
3714 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
3715 			regs[rd] = NULL;
3716 			break;
3717 		}
3718 
3719 		if (!DTRACE_INSCRATCH(mstate, size)) {
3720 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3721 			regs[rd] = NULL;
3722 			break;
3723 		}
3724 
3725 		for (;;) {
3726 			if (i >= size) {
3727 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3728 				regs[rd] = NULL;
3729 				break;
3730 			}
3731 
3732 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
3733 				i--;
3734 				break;
3735 			}
3736 		}
3737 
3738 		for (;;) {
3739 			if (i >= size) {
3740 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3741 				regs[rd] = NULL;
3742 				break;
3743 			}
3744 
3745 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
3746 				break;
3747 		}
3748 
3749 		if (i < size) {
3750 			mstate->dtms_scratch_ptr += i;
3751 			regs[rd] = (uintptr_t)d;
3752 		}
3753 
3754 		break;
3755 	}
3756 
3757 	case DIF_SUBR_LLTOSTR: {
3758 		int64_t i = (int64_t)tupregs[0].dttk_value;
3759 		int64_t val = i < 0 ? i * -1 : i;
3760 		uint64_t size = 22;	/* enough room for 2^64 in decimal */
3761 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
3762 
3763 		if (!DTRACE_INSCRATCH(mstate, size)) {
3764 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3765 			regs[rd] = NULL;
3766 			break;
3767 		}
3768 
3769 		for (*end-- = '\0'; val; val /= 10)
3770 			*end-- = '0' + (val % 10);
3771 
3772 		if (i == 0)
3773 			*end-- = '0';
3774 
3775 		if (i < 0)
3776 			*end-- = '-';
3777 
3778 		regs[rd] = (uintptr_t)end + 1;
3779 		mstate->dtms_scratch_ptr += size;
3780 		break;
3781 	}
3782 
3783 	case DIF_SUBR_HTONS:
3784 	case DIF_SUBR_NTOHS:
3785 #ifdef _BIG_ENDIAN
3786 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
3787 #else
3788 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
3789 #endif
3790 		break;
3791 
3792 
3793 	case DIF_SUBR_HTONL:
3794 	case DIF_SUBR_NTOHL:
3795 #ifdef _BIG_ENDIAN
3796 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
3797 #else
3798 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
3799 #endif
3800 		break;
3801 
3802 
3803 	case DIF_SUBR_HTONLL:
3804 	case DIF_SUBR_NTOHLL:
3805 #ifdef _BIG_ENDIAN
3806 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
3807 #else
3808 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
3809 #endif
3810 		break;
3811 
3812 
3813 	case DIF_SUBR_DIRNAME:
3814 	case DIF_SUBR_BASENAME: {
3815 		char *dest = (char *)mstate->dtms_scratch_ptr;
3816 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3817 		uintptr_t src = tupregs[0].dttk_value;
3818 		int i, j, len = dtrace_strlen((char *)src, size);
3819 		int lastbase = -1, firstbase = -1, lastdir = -1;
3820 		int start, end;
3821 
3822 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
3823 			regs[rd] = NULL;
3824 			break;
3825 		}
3826 
3827 		if (!DTRACE_INSCRATCH(mstate, size)) {
3828 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3829 			regs[rd] = NULL;
3830 			break;
3831 		}
3832 
3833 		/*
3834 		 * The basename and dirname for a zero-length string is
3835 		 * defined to be "."
3836 		 */
3837 		if (len == 0) {
3838 			len = 1;
3839 			src = (uintptr_t)".";
3840 		}
3841 
3842 		/*
3843 		 * Start from the back of the string, moving back toward the
3844 		 * front until we see a character that isn't a slash.  That
3845 		 * character is the last character in the basename.
3846 		 */
3847 		for (i = len - 1; i >= 0; i--) {
3848 			if (dtrace_load8(src + i) != '/')
3849 				break;
3850 		}
3851 
3852 		if (i >= 0)
3853 			lastbase = i;
3854 
3855 		/*
3856 		 * Starting from the last character in the basename, move
3857 		 * towards the front until we find a slash.  The character
3858 		 * that we processed immediately before that is the first
3859 		 * character in the basename.
3860 		 */
3861 		for (; i >= 0; i--) {
3862 			if (dtrace_load8(src + i) == '/')
3863 				break;
3864 		}
3865 
3866 		if (i >= 0)
3867 			firstbase = i + 1;
3868 
3869 		/*
3870 		 * Now keep going until we find a non-slash character.  That
3871 		 * character is the last character in the dirname.
3872 		 */
3873 		for (; i >= 0; i--) {
3874 			if (dtrace_load8(src + i) != '/')
3875 				break;
3876 		}
3877 
3878 		if (i >= 0)
3879 			lastdir = i;
3880 
3881 		ASSERT(!(lastbase == -1 && firstbase != -1));
3882 		ASSERT(!(firstbase == -1 && lastdir != -1));
3883 
3884 		if (lastbase == -1) {
3885 			/*
3886 			 * We didn't find a non-slash character.  We know that
3887 			 * the length is non-zero, so the whole string must be
3888 			 * slashes.  In either the dirname or the basename
3889 			 * case, we return '/'.
3890 			 */
3891 			ASSERT(firstbase == -1);
3892 			firstbase = lastbase = lastdir = 0;
3893 		}
3894 
3895 		if (firstbase == -1) {
3896 			/*
3897 			 * The entire string consists only of a basename
3898 			 * component.  If we're looking for dirname, we need
3899 			 * to change our string to be just "."; if we're
3900 			 * looking for a basename, we'll just set the first
3901 			 * character of the basename to be 0.
3902 			 */
3903 			if (subr == DIF_SUBR_DIRNAME) {
3904 				ASSERT(lastdir == -1);
3905 				src = (uintptr_t)".";
3906 				lastdir = 0;
3907 			} else {
3908 				firstbase = 0;
3909 			}
3910 		}
3911 
3912 		if (subr == DIF_SUBR_DIRNAME) {
3913 			if (lastdir == -1) {
3914 				/*
3915 				 * We know that we have a slash in the name --
3916 				 * or lastdir would be set to 0, above.  And
3917 				 * because lastdir is -1, we know that this
3918 				 * slash must be the first character.  (That
3919 				 * is, the full string must be of the form
3920 				 * "/basename".)  In this case, the last
3921 				 * character of the directory name is 0.
3922 				 */
3923 				lastdir = 0;
3924 			}
3925 
3926 			start = 0;
3927 			end = lastdir;
3928 		} else {
3929 			ASSERT(subr == DIF_SUBR_BASENAME);
3930 			ASSERT(firstbase != -1 && lastbase != -1);
3931 			start = firstbase;
3932 			end = lastbase;
3933 		}
3934 
3935 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
3936 			dest[j] = dtrace_load8(src + i);
3937 
3938 		dest[j] = '\0';
3939 		regs[rd] = (uintptr_t)dest;
3940 		mstate->dtms_scratch_ptr += size;
3941 		break;
3942 	}
3943 
3944 	case DIF_SUBR_CLEANPATH: {
3945 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
3946 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3947 		uintptr_t src = tupregs[0].dttk_value;
3948 		int i = 0, j = 0;
3949 
3950 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
3951 			regs[rd] = NULL;
3952 			break;
3953 		}
3954 
3955 		if (!DTRACE_INSCRATCH(mstate, size)) {
3956 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3957 			regs[rd] = NULL;
3958 			break;
3959 		}
3960 
3961 		/*
3962 		 * Move forward, loading each character.
3963 		 */
3964 		do {
3965 			c = dtrace_load8(src + i++);
3966 next:
3967 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
3968 				break;
3969 
3970 			if (c != '/') {
3971 				dest[j++] = c;
3972 				continue;
3973 			}
3974 
3975 			c = dtrace_load8(src + i++);
3976 
3977 			if (c == '/') {
3978 				/*
3979 				 * We have two slashes -- we can just advance
3980 				 * to the next character.
3981 				 */
3982 				goto next;
3983 			}
3984 
3985 			if (c != '.') {
3986 				/*
3987 				 * This is not "." and it's not ".." -- we can
3988 				 * just store the "/" and this character and
3989 				 * drive on.
3990 				 */
3991 				dest[j++] = '/';
3992 				dest[j++] = c;
3993 				continue;
3994 			}
3995 
3996 			c = dtrace_load8(src + i++);
3997 
3998 			if (c == '/') {
3999 				/*
4000 				 * This is a "/./" component.  We're not going
4001 				 * to store anything in the destination buffer;
4002 				 * we're just going to go to the next component.
4003 				 */
4004 				goto next;
4005 			}
4006 
4007 			if (c != '.') {
4008 				/*
4009 				 * This is not ".." -- we can just store the
4010 				 * "/." and this character and continue
4011 				 * processing.
4012 				 */
4013 				dest[j++] = '/';
4014 				dest[j++] = '.';
4015 				dest[j++] = c;
4016 				continue;
4017 			}
4018 
4019 			c = dtrace_load8(src + i++);
4020 
4021 			if (c != '/' && c != '\0') {
4022 				/*
4023 				 * This is not ".." -- it's "..[mumble]".
4024 				 * We'll store the "/.." and this character
4025 				 * and continue processing.
4026 				 */
4027 				dest[j++] = '/';
4028 				dest[j++] = '.';
4029 				dest[j++] = '.';
4030 				dest[j++] = c;
4031 				continue;
4032 			}
4033 
4034 			/*
4035 			 * This is "/../" or "/..\0".  We need to back up
4036 			 * our destination pointer until we find a "/".
4037 			 */
4038 			i--;
4039 			while (j != 0 && dest[--j] != '/')
4040 				continue;
4041 
4042 			if (c == '\0')
4043 				dest[++j] = '/';
4044 		} while (c != '\0');
4045 
4046 		dest[j] = '\0';
4047 		regs[rd] = (uintptr_t)dest;
4048 		mstate->dtms_scratch_ptr += size;
4049 		break;
4050 	}
4051 
4052 	case DIF_SUBR_INET_NTOA:
4053 	case DIF_SUBR_INET_NTOA6:
4054 	case DIF_SUBR_INET_NTOP: {
4055 		size_t size;
4056 		int af, argi, i;
4057 		char *base, *end;
4058 
4059 		if (subr == DIF_SUBR_INET_NTOP) {
4060 			af = (int)tupregs[0].dttk_value;
4061 			argi = 1;
4062 		} else {
4063 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4064 			argi = 0;
4065 		}
4066 
4067 		if (af == AF_INET) {
4068 			ipaddr_t ip4;
4069 			uint8_t *ptr8, val;
4070 
4071 			/*
4072 			 * Safely load the IPv4 address.
4073 			 */
4074 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
4075 
4076 			/*
4077 			 * Check an IPv4 string will fit in scratch.
4078 			 */
4079 			size = INET_ADDRSTRLEN;
4080 			if (!DTRACE_INSCRATCH(mstate, size)) {
4081 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4082 				regs[rd] = NULL;
4083 				break;
4084 			}
4085 			base = (char *)mstate->dtms_scratch_ptr;
4086 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4087 
4088 			/*
4089 			 * Stringify as a dotted decimal quad.
4090 			 */
4091 			*end-- = '\0';
4092 			ptr8 = (uint8_t *)&ip4;
4093 			for (i = 3; i >= 0; i--) {
4094 				val = ptr8[i];
4095 
4096 				if (val == 0) {
4097 					*end-- = '0';
4098 				} else {
4099 					for (; val; val /= 10) {
4100 						*end-- = '0' + (val % 10);
4101 					}
4102 				}
4103 
4104 				if (i > 0)
4105 					*end-- = '.';
4106 			}
4107 			ASSERT(end + 1 >= base);
4108 
4109 		} else if (af == AF_INET6) {
4110 			struct in6_addr ip6;
4111 			int firstzero, tryzero, numzero, v6end;
4112 			uint16_t val;
4113 			const char digits[] = "0123456789abcdef";
4114 
4115 			/*
4116 			 * Stringify using RFC 1884 convention 2 - 16 bit
4117 			 * hexadecimal values with a zero-run compression.
4118 			 * Lower case hexadecimal digits are used.
4119 			 * 	eg, fe80::214:4fff:fe0b:76c8.
4120 			 * The IPv4 embedded form is returned for inet_ntop,
4121 			 * just the IPv4 string is returned for inet_ntoa6.
4122 			 */
4123 
4124 			/*
4125 			 * Safely load the IPv6 address.
4126 			 */
4127 			dtrace_bcopy(
4128 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
4129 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4130 
4131 			/*
4132 			 * Check an IPv6 string will fit in scratch.
4133 			 */
4134 			size = INET6_ADDRSTRLEN;
4135 			if (!DTRACE_INSCRATCH(mstate, size)) {
4136 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4137 				regs[rd] = NULL;
4138 				break;
4139 			}
4140 			base = (char *)mstate->dtms_scratch_ptr;
4141 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4142 			*end-- = '\0';
4143 
4144 			/*
4145 			 * Find the longest run of 16 bit zero values
4146 			 * for the single allowed zero compression - "::".
4147 			 */
4148 			firstzero = -1;
4149 			tryzero = -1;
4150 			numzero = 1;
4151 			for (i = 0; i < sizeof (struct in6_addr); i++) {
4152 				if (ip6._S6_un._S6_u8[i] == 0 &&
4153 				    tryzero == -1 && i % 2 == 0) {
4154 					tryzero = i;
4155 					continue;
4156 				}
4157 
4158 				if (tryzero != -1 &&
4159 				    (ip6._S6_un._S6_u8[i] != 0 ||
4160 				    i == sizeof (struct in6_addr) - 1)) {
4161 
4162 					if (i - tryzero <= numzero) {
4163 						tryzero = -1;
4164 						continue;
4165 					}
4166 
4167 					firstzero = tryzero;
4168 					numzero = i - i % 2 - tryzero;
4169 					tryzero = -1;
4170 
4171 					if (ip6._S6_un._S6_u8[i] == 0 &&
4172 					    i == sizeof (struct in6_addr) - 1)
4173 						numzero += 2;
4174 				}
4175 			}
4176 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4177 
4178 			/*
4179 			 * Check for an IPv4 embedded address.
4180 			 */
4181 			v6end = sizeof (struct in6_addr) - 2;
4182 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4183 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
4184 				for (i = sizeof (struct in6_addr) - 1;
4185 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
4186 					ASSERT(end >= base);
4187 
4188 					val = ip6._S6_un._S6_u8[i];
4189 
4190 					if (val == 0) {
4191 						*end-- = '0';
4192 					} else {
4193 						for (; val; val /= 10) {
4194 							*end-- = '0' + val % 10;
4195 						}
4196 					}
4197 
4198 					if (i > DTRACE_V4MAPPED_OFFSET)
4199 						*end-- = '.';
4200 				}
4201 
4202 				if (subr == DIF_SUBR_INET_NTOA6)
4203 					goto inetout;
4204 
4205 				/*
4206 				 * Set v6end to skip the IPv4 address that
4207 				 * we have already stringified.
4208 				 */
4209 				v6end = 10;
4210 			}
4211 
4212 			/*
4213 			 * Build the IPv6 string by working through the
4214 			 * address in reverse.
4215 			 */
4216 			for (i = v6end; i >= 0; i -= 2) {
4217 				ASSERT(end >= base);
4218 
4219 				if (i == firstzero + numzero - 2) {
4220 					*end-- = ':';
4221 					*end-- = ':';
4222 					i -= numzero - 2;
4223 					continue;
4224 				}
4225 
4226 				if (i < 14 && i != firstzero - 2)
4227 					*end-- = ':';
4228 
4229 				val = (ip6._S6_un._S6_u8[i] << 8) +
4230 				    ip6._S6_un._S6_u8[i + 1];
4231 
4232 				if (val == 0) {
4233 					*end-- = '0';
4234 				} else {
4235 					for (; val; val /= 16) {
4236 						*end-- = digits[val % 16];
4237 					}
4238 				}
4239 			}
4240 			ASSERT(end + 1 >= base);
4241 
4242 		} else {
4243 			/*
4244 			 * The user didn't use AH_INET or AH_INET6.
4245 			 */
4246 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4247 			regs[rd] = NULL;
4248 			break;
4249 		}
4250 
4251 inetout:	regs[rd] = (uintptr_t)end + 1;
4252 		mstate->dtms_scratch_ptr += size;
4253 		break;
4254 	}
4255 
4256 	}
4257 }
4258 
4259 /*
4260  * Emulate the execution of DTrace IR instructions specified by the given
4261  * DIF object.  This function is deliberately void of assertions as all of
4262  * the necessary checks are handled by a call to dtrace_difo_validate().
4263  */
4264 static uint64_t
4265 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4266     dtrace_vstate_t *vstate, dtrace_state_t *state)
4267 {
4268 	const dif_instr_t *text = difo->dtdo_buf;
4269 	const uint_t textlen = difo->dtdo_len;
4270 	const char *strtab = difo->dtdo_strtab;
4271 	const uint64_t *inttab = difo->dtdo_inttab;
4272 
4273 	uint64_t rval = 0;
4274 	dtrace_statvar_t *svar;
4275 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4276 	dtrace_difv_t *v;
4277 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4278 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4279 
4280 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4281 	uint64_t regs[DIF_DIR_NREGS];
4282 	uint64_t *tmp;
4283 
4284 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4285 	int64_t cc_r;
4286 	uint_t pc = 0, id, opc;
4287 	uint8_t ttop = 0;
4288 	dif_instr_t instr;
4289 	uint_t r1, r2, rd;
4290 
4291 	/*
4292 	 * We stash the current DIF object into the machine state: we need it
4293 	 * for subsequent access checking.
4294 	 */
4295 	mstate->dtms_difo = difo;
4296 
4297 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
4298 
4299 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4300 		opc = pc;
4301 
4302 		instr = text[pc++];
4303 		r1 = DIF_INSTR_R1(instr);
4304 		r2 = DIF_INSTR_R2(instr);
4305 		rd = DIF_INSTR_RD(instr);
4306 
4307 		switch (DIF_INSTR_OP(instr)) {
4308 		case DIF_OP_OR:
4309 			regs[rd] = regs[r1] | regs[r2];
4310 			break;
4311 		case DIF_OP_XOR:
4312 			regs[rd] = regs[r1] ^ regs[r2];
4313 			break;
4314 		case DIF_OP_AND:
4315 			regs[rd] = regs[r1] & regs[r2];
4316 			break;
4317 		case DIF_OP_SLL:
4318 			regs[rd] = regs[r1] << regs[r2];
4319 			break;
4320 		case DIF_OP_SRL:
4321 			regs[rd] = regs[r1] >> regs[r2];
4322 			break;
4323 		case DIF_OP_SUB:
4324 			regs[rd] = regs[r1] - regs[r2];
4325 			break;
4326 		case DIF_OP_ADD:
4327 			regs[rd] = regs[r1] + regs[r2];
4328 			break;
4329 		case DIF_OP_MUL:
4330 			regs[rd] = regs[r1] * regs[r2];
4331 			break;
4332 		case DIF_OP_SDIV:
4333 			if (regs[r2] == 0) {
4334 				regs[rd] = 0;
4335 				*flags |= CPU_DTRACE_DIVZERO;
4336 			} else {
4337 				regs[rd] = (int64_t)regs[r1] /
4338 				    (int64_t)regs[r2];
4339 			}
4340 			break;
4341 
4342 		case DIF_OP_UDIV:
4343 			if (regs[r2] == 0) {
4344 				regs[rd] = 0;
4345 				*flags |= CPU_DTRACE_DIVZERO;
4346 			} else {
4347 				regs[rd] = regs[r1] / regs[r2];
4348 			}
4349 			break;
4350 
4351 		case DIF_OP_SREM:
4352 			if (regs[r2] == 0) {
4353 				regs[rd] = 0;
4354 				*flags |= CPU_DTRACE_DIVZERO;
4355 			} else {
4356 				regs[rd] = (int64_t)regs[r1] %
4357 				    (int64_t)regs[r2];
4358 			}
4359 			break;
4360 
4361 		case DIF_OP_UREM:
4362 			if (regs[r2] == 0) {
4363 				regs[rd] = 0;
4364 				*flags |= CPU_DTRACE_DIVZERO;
4365 			} else {
4366 				regs[rd] = regs[r1] % regs[r2];
4367 			}
4368 			break;
4369 
4370 		case DIF_OP_NOT:
4371 			regs[rd] = ~regs[r1];
4372 			break;
4373 		case DIF_OP_MOV:
4374 			regs[rd] = regs[r1];
4375 			break;
4376 		case DIF_OP_CMP:
4377 			cc_r = regs[r1] - regs[r2];
4378 			cc_n = cc_r < 0;
4379 			cc_z = cc_r == 0;
4380 			cc_v = 0;
4381 			cc_c = regs[r1] < regs[r2];
4382 			break;
4383 		case DIF_OP_TST:
4384 			cc_n = cc_v = cc_c = 0;
4385 			cc_z = regs[r1] == 0;
4386 			break;
4387 		case DIF_OP_BA:
4388 			pc = DIF_INSTR_LABEL(instr);
4389 			break;
4390 		case DIF_OP_BE:
4391 			if (cc_z)
4392 				pc = DIF_INSTR_LABEL(instr);
4393 			break;
4394 		case DIF_OP_BNE:
4395 			if (cc_z == 0)
4396 				pc = DIF_INSTR_LABEL(instr);
4397 			break;
4398 		case DIF_OP_BG:
4399 			if ((cc_z | (cc_n ^ cc_v)) == 0)
4400 				pc = DIF_INSTR_LABEL(instr);
4401 			break;
4402 		case DIF_OP_BGU:
4403 			if ((cc_c | cc_z) == 0)
4404 				pc = DIF_INSTR_LABEL(instr);
4405 			break;
4406 		case DIF_OP_BGE:
4407 			if ((cc_n ^ cc_v) == 0)
4408 				pc = DIF_INSTR_LABEL(instr);
4409 			break;
4410 		case DIF_OP_BGEU:
4411 			if (cc_c == 0)
4412 				pc = DIF_INSTR_LABEL(instr);
4413 			break;
4414 		case DIF_OP_BL:
4415 			if (cc_n ^ cc_v)
4416 				pc = DIF_INSTR_LABEL(instr);
4417 			break;
4418 		case DIF_OP_BLU:
4419 			if (cc_c)
4420 				pc = DIF_INSTR_LABEL(instr);
4421 			break;
4422 		case DIF_OP_BLE:
4423 			if (cc_z | (cc_n ^ cc_v))
4424 				pc = DIF_INSTR_LABEL(instr);
4425 			break;
4426 		case DIF_OP_BLEU:
4427 			if (cc_c | cc_z)
4428 				pc = DIF_INSTR_LABEL(instr);
4429 			break;
4430 		case DIF_OP_RLDSB:
4431 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4432 				*flags |= CPU_DTRACE_KPRIV;
4433 				*illval = regs[r1];
4434 				break;
4435 			}
4436 			/*FALLTHROUGH*/
4437 		case DIF_OP_LDSB:
4438 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
4439 			break;
4440 		case DIF_OP_RLDSH:
4441 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4442 				*flags |= CPU_DTRACE_KPRIV;
4443 				*illval = regs[r1];
4444 				break;
4445 			}
4446 			/*FALLTHROUGH*/
4447 		case DIF_OP_LDSH:
4448 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
4449 			break;
4450 		case DIF_OP_RLDSW:
4451 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4452 				*flags |= CPU_DTRACE_KPRIV;
4453 				*illval = regs[r1];
4454 				break;
4455 			}
4456 			/*FALLTHROUGH*/
4457 		case DIF_OP_LDSW:
4458 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
4459 			break;
4460 		case DIF_OP_RLDUB:
4461 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4462 				*flags |= CPU_DTRACE_KPRIV;
4463 				*illval = regs[r1];
4464 				break;
4465 			}
4466 			/*FALLTHROUGH*/
4467 		case DIF_OP_LDUB:
4468 			regs[rd] = dtrace_load8(regs[r1]);
4469 			break;
4470 		case DIF_OP_RLDUH:
4471 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4472 				*flags |= CPU_DTRACE_KPRIV;
4473 				*illval = regs[r1];
4474 				break;
4475 			}
4476 			/*FALLTHROUGH*/
4477 		case DIF_OP_LDUH:
4478 			regs[rd] = dtrace_load16(regs[r1]);
4479 			break;
4480 		case DIF_OP_RLDUW:
4481 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4482 				*flags |= CPU_DTRACE_KPRIV;
4483 				*illval = regs[r1];
4484 				break;
4485 			}
4486 			/*FALLTHROUGH*/
4487 		case DIF_OP_LDUW:
4488 			regs[rd] = dtrace_load32(regs[r1]);
4489 			break;
4490 		case DIF_OP_RLDX:
4491 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
4492 				*flags |= CPU_DTRACE_KPRIV;
4493 				*illval = regs[r1];
4494 				break;
4495 			}
4496 			/*FALLTHROUGH*/
4497 		case DIF_OP_LDX:
4498 			regs[rd] = dtrace_load64(regs[r1]);
4499 			break;
4500 		case DIF_OP_ULDSB:
4501 			regs[rd] = (int8_t)
4502 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4503 			break;
4504 		case DIF_OP_ULDSH:
4505 			regs[rd] = (int16_t)
4506 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4507 			break;
4508 		case DIF_OP_ULDSW:
4509 			regs[rd] = (int32_t)
4510 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4511 			break;
4512 		case DIF_OP_ULDUB:
4513 			regs[rd] =
4514 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4515 			break;
4516 		case DIF_OP_ULDUH:
4517 			regs[rd] =
4518 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4519 			break;
4520 		case DIF_OP_ULDUW:
4521 			regs[rd] =
4522 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4523 			break;
4524 		case DIF_OP_ULDX:
4525 			regs[rd] =
4526 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
4527 			break;
4528 		case DIF_OP_RET:
4529 			rval = regs[rd];
4530 			break;
4531 		case DIF_OP_NOP:
4532 			break;
4533 		case DIF_OP_SETX:
4534 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
4535 			break;
4536 		case DIF_OP_SETS:
4537 			regs[rd] = (uint64_t)(uintptr_t)
4538 			    (strtab + DIF_INSTR_STRING(instr));
4539 			break;
4540 		case DIF_OP_SCMP: {
4541 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
4542 			uintptr_t s1 = regs[r1];
4543 			uintptr_t s2 = regs[r2];
4544 
4545 			if (s1 != NULL &&
4546 			    !dtrace_strcanload(s1, sz, mstate, vstate))
4547 				break;
4548 			if (s2 != NULL &&
4549 			    !dtrace_strcanload(s2, sz, mstate, vstate))
4550 				break;
4551 
4552 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
4553 
4554 			cc_n = cc_r < 0;
4555 			cc_z = cc_r == 0;
4556 			cc_v = cc_c = 0;
4557 			break;
4558 		}
4559 		case DIF_OP_LDGA:
4560 			regs[rd] = dtrace_dif_variable(mstate, state,
4561 			    r1, regs[r2]);
4562 			break;
4563 		case DIF_OP_LDGS:
4564 			id = DIF_INSTR_VAR(instr);
4565 
4566 			if (id >= DIF_VAR_OTHER_UBASE) {
4567 				uintptr_t a;
4568 
4569 				id -= DIF_VAR_OTHER_UBASE;
4570 				svar = vstate->dtvs_globals[id];
4571 				ASSERT(svar != NULL);
4572 				v = &svar->dtsv_var;
4573 
4574 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
4575 					regs[rd] = svar->dtsv_data;
4576 					break;
4577 				}
4578 
4579 				a = (uintptr_t)svar->dtsv_data;
4580 
4581 				if (*(uint8_t *)a == UINT8_MAX) {
4582 					/*
4583 					 * If the 0th byte is set to UINT8_MAX
4584 					 * then this is to be treated as a
4585 					 * reference to a NULL variable.
4586 					 */
4587 					regs[rd] = NULL;
4588 				} else {
4589 					regs[rd] = a + sizeof (uint64_t);
4590 				}
4591 
4592 				break;
4593 			}
4594 
4595 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
4596 			break;
4597 
4598 		case DIF_OP_STGS:
4599 			id = DIF_INSTR_VAR(instr);
4600 
4601 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4602 			id -= DIF_VAR_OTHER_UBASE;
4603 
4604 			svar = vstate->dtvs_globals[id];
4605 			ASSERT(svar != NULL);
4606 			v = &svar->dtsv_var;
4607 
4608 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4609 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4610 
4611 				ASSERT(a != NULL);
4612 				ASSERT(svar->dtsv_size != 0);
4613 
4614 				if (regs[rd] == NULL) {
4615 					*(uint8_t *)a = UINT8_MAX;
4616 					break;
4617 				} else {
4618 					*(uint8_t *)a = 0;
4619 					a += sizeof (uint64_t);
4620 				}
4621 				if (!dtrace_vcanload(
4622 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4623 				    mstate, vstate))
4624 					break;
4625 
4626 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4627 				    (void *)a, &v->dtdv_type);
4628 				break;
4629 			}
4630 
4631 			svar->dtsv_data = regs[rd];
4632 			break;
4633 
4634 		case DIF_OP_LDTA:
4635 			/*
4636 			 * There are no DTrace built-in thread-local arrays at
4637 			 * present.  This opcode is saved for future work.
4638 			 */
4639 			*flags |= CPU_DTRACE_ILLOP;
4640 			regs[rd] = 0;
4641 			break;
4642 
4643 		case DIF_OP_LDLS:
4644 			id = DIF_INSTR_VAR(instr);
4645 
4646 			if (id < DIF_VAR_OTHER_UBASE) {
4647 				/*
4648 				 * For now, this has no meaning.
4649 				 */
4650 				regs[rd] = 0;
4651 				break;
4652 			}
4653 
4654 			id -= DIF_VAR_OTHER_UBASE;
4655 
4656 			ASSERT(id < vstate->dtvs_nlocals);
4657 			ASSERT(vstate->dtvs_locals != NULL);
4658 
4659 			svar = vstate->dtvs_locals[id];
4660 			ASSERT(svar != NULL);
4661 			v = &svar->dtsv_var;
4662 
4663 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4664 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4665 				size_t sz = v->dtdv_type.dtdt_size;
4666 
4667 				sz += sizeof (uint64_t);
4668 				ASSERT(svar->dtsv_size == NCPU * sz);
4669 				a += CPU->cpu_id * sz;
4670 
4671 				if (*(uint8_t *)a == UINT8_MAX) {
4672 					/*
4673 					 * If the 0th byte is set to UINT8_MAX
4674 					 * then this is to be treated as a
4675 					 * reference to a NULL variable.
4676 					 */
4677 					regs[rd] = NULL;
4678 				} else {
4679 					regs[rd] = a + sizeof (uint64_t);
4680 				}
4681 
4682 				break;
4683 			}
4684 
4685 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4686 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4687 			regs[rd] = tmp[CPU->cpu_id];
4688 			break;
4689 
4690 		case DIF_OP_STLS:
4691 			id = DIF_INSTR_VAR(instr);
4692 
4693 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4694 			id -= DIF_VAR_OTHER_UBASE;
4695 			ASSERT(id < vstate->dtvs_nlocals);
4696 
4697 			ASSERT(vstate->dtvs_locals != NULL);
4698 			svar = vstate->dtvs_locals[id];
4699 			ASSERT(svar != NULL);
4700 			v = &svar->dtsv_var;
4701 
4702 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4703 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4704 				size_t sz = v->dtdv_type.dtdt_size;
4705 
4706 				sz += sizeof (uint64_t);
4707 				ASSERT(svar->dtsv_size == NCPU * sz);
4708 				a += CPU->cpu_id * sz;
4709 
4710 				if (regs[rd] == NULL) {
4711 					*(uint8_t *)a = UINT8_MAX;
4712 					break;
4713 				} else {
4714 					*(uint8_t *)a = 0;
4715 					a += sizeof (uint64_t);
4716 				}
4717 
4718 				if (!dtrace_vcanload(
4719 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4720 				    mstate, vstate))
4721 					break;
4722 
4723 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4724 				    (void *)a, &v->dtdv_type);
4725 				break;
4726 			}
4727 
4728 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4729 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4730 			tmp[CPU->cpu_id] = regs[rd];
4731 			break;
4732 
4733 		case DIF_OP_LDTS: {
4734 			dtrace_dynvar_t *dvar;
4735 			dtrace_key_t *key;
4736 
4737 			id = DIF_INSTR_VAR(instr);
4738 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4739 			id -= DIF_VAR_OTHER_UBASE;
4740 			v = &vstate->dtvs_tlocals[id];
4741 
4742 			key = &tupregs[DIF_DTR_NREGS];
4743 			key[0].dttk_value = (uint64_t)id;
4744 			key[0].dttk_size = 0;
4745 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4746 			key[1].dttk_size = 0;
4747 
4748 			dvar = dtrace_dynvar(dstate, 2, key,
4749 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
4750 			    mstate, vstate);
4751 
4752 			if (dvar == NULL) {
4753 				regs[rd] = 0;
4754 				break;
4755 			}
4756 
4757 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4758 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4759 			} else {
4760 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4761 			}
4762 
4763 			break;
4764 		}
4765 
4766 		case DIF_OP_STTS: {
4767 			dtrace_dynvar_t *dvar;
4768 			dtrace_key_t *key;
4769 
4770 			id = DIF_INSTR_VAR(instr);
4771 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4772 			id -= DIF_VAR_OTHER_UBASE;
4773 
4774 			key = &tupregs[DIF_DTR_NREGS];
4775 			key[0].dttk_value = (uint64_t)id;
4776 			key[0].dttk_size = 0;
4777 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4778 			key[1].dttk_size = 0;
4779 			v = &vstate->dtvs_tlocals[id];
4780 
4781 			dvar = dtrace_dynvar(dstate, 2, key,
4782 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4783 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4784 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4785 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
4786 
4787 			/*
4788 			 * Given that we're storing to thread-local data,
4789 			 * we need to flush our predicate cache.
4790 			 */
4791 			curthread->t_predcache = NULL;
4792 
4793 			if (dvar == NULL)
4794 				break;
4795 
4796 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4797 				if (!dtrace_vcanload(
4798 				    (void *)(uintptr_t)regs[rd],
4799 				    &v->dtdv_type, mstate, vstate))
4800 					break;
4801 
4802 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4803 				    dvar->dtdv_data, &v->dtdv_type);
4804 			} else {
4805 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4806 			}
4807 
4808 			break;
4809 		}
4810 
4811 		case DIF_OP_SRA:
4812 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
4813 			break;
4814 
4815 		case DIF_OP_CALL:
4816 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
4817 			    regs, tupregs, ttop, mstate, state);
4818 			break;
4819 
4820 		case DIF_OP_PUSHTR:
4821 			if (ttop == DIF_DTR_NREGS) {
4822 				*flags |= CPU_DTRACE_TUPOFLOW;
4823 				break;
4824 			}
4825 
4826 			if (r1 == DIF_TYPE_STRING) {
4827 				/*
4828 				 * If this is a string type and the size is 0,
4829 				 * we'll use the system-wide default string
4830 				 * size.  Note that we are _not_ looking at
4831 				 * the value of the DTRACEOPT_STRSIZE option;
4832 				 * had this been set, we would expect to have
4833 				 * a non-zero size value in the "pushtr".
4834 				 */
4835 				tupregs[ttop].dttk_size =
4836 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
4837 				    regs[r2] ? regs[r2] :
4838 				    dtrace_strsize_default) + 1;
4839 			} else {
4840 				tupregs[ttop].dttk_size = regs[r2];
4841 			}
4842 
4843 			tupregs[ttop++].dttk_value = regs[rd];
4844 			break;
4845 
4846 		case DIF_OP_PUSHTV:
4847 			if (ttop == DIF_DTR_NREGS) {
4848 				*flags |= CPU_DTRACE_TUPOFLOW;
4849 				break;
4850 			}
4851 
4852 			tupregs[ttop].dttk_value = regs[rd];
4853 			tupregs[ttop++].dttk_size = 0;
4854 			break;
4855 
4856 		case DIF_OP_POPTS:
4857 			if (ttop != 0)
4858 				ttop--;
4859 			break;
4860 
4861 		case DIF_OP_FLUSHTS:
4862 			ttop = 0;
4863 			break;
4864 
4865 		case DIF_OP_LDGAA:
4866 		case DIF_OP_LDTAA: {
4867 			dtrace_dynvar_t *dvar;
4868 			dtrace_key_t *key = tupregs;
4869 			uint_t nkeys = ttop;
4870 
4871 			id = DIF_INSTR_VAR(instr);
4872 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4873 			id -= DIF_VAR_OTHER_UBASE;
4874 
4875 			key[nkeys].dttk_value = (uint64_t)id;
4876 			key[nkeys++].dttk_size = 0;
4877 
4878 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
4879 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4880 				key[nkeys++].dttk_size = 0;
4881 				v = &vstate->dtvs_tlocals[id];
4882 			} else {
4883 				v = &vstate->dtvs_globals[id]->dtsv_var;
4884 			}
4885 
4886 			dvar = dtrace_dynvar(dstate, nkeys, key,
4887 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4888 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4889 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
4890 
4891 			if (dvar == NULL) {
4892 				regs[rd] = 0;
4893 				break;
4894 			}
4895 
4896 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4897 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4898 			} else {
4899 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4900 			}
4901 
4902 			break;
4903 		}
4904 
4905 		case DIF_OP_STGAA:
4906 		case DIF_OP_STTAA: {
4907 			dtrace_dynvar_t *dvar;
4908 			dtrace_key_t *key = tupregs;
4909 			uint_t nkeys = ttop;
4910 
4911 			id = DIF_INSTR_VAR(instr);
4912 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4913 			id -= DIF_VAR_OTHER_UBASE;
4914 
4915 			key[nkeys].dttk_value = (uint64_t)id;
4916 			key[nkeys++].dttk_size = 0;
4917 
4918 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
4919 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4920 				key[nkeys++].dttk_size = 0;
4921 				v = &vstate->dtvs_tlocals[id];
4922 			} else {
4923 				v = &vstate->dtvs_globals[id]->dtsv_var;
4924 			}
4925 
4926 			dvar = dtrace_dynvar(dstate, nkeys, key,
4927 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4928 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4929 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4930 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
4931 
4932 			if (dvar == NULL)
4933 				break;
4934 
4935 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4936 				if (!dtrace_vcanload(
4937 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4938 				    mstate, vstate))
4939 					break;
4940 
4941 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4942 				    dvar->dtdv_data, &v->dtdv_type);
4943 			} else {
4944 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4945 			}
4946 
4947 			break;
4948 		}
4949 
4950 		case DIF_OP_ALLOCS: {
4951 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4952 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
4953 
4954 			/*
4955 			 * Rounding up the user allocation size could have
4956 			 * overflowed large, bogus allocations (like -1ULL) to
4957 			 * 0.
4958 			 */
4959 			if (size < regs[r1] ||
4960 			    !DTRACE_INSCRATCH(mstate, size)) {
4961 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4962 				regs[rd] = NULL;
4963 				break;
4964 			}
4965 
4966 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
4967 			mstate->dtms_scratch_ptr += size;
4968 			regs[rd] = ptr;
4969 			break;
4970 		}
4971 
4972 		case DIF_OP_COPYS:
4973 			if (!dtrace_canstore(regs[rd], regs[r2],
4974 			    mstate, vstate)) {
4975 				*flags |= CPU_DTRACE_BADADDR;
4976 				*illval = regs[rd];
4977 				break;
4978 			}
4979 
4980 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
4981 				break;
4982 
4983 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
4984 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
4985 			break;
4986 
4987 		case DIF_OP_STB:
4988 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
4989 				*flags |= CPU_DTRACE_BADADDR;
4990 				*illval = regs[rd];
4991 				break;
4992 			}
4993 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
4994 			break;
4995 
4996 		case DIF_OP_STH:
4997 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
4998 				*flags |= CPU_DTRACE_BADADDR;
4999 				*illval = regs[rd];
5000 				break;
5001 			}
5002 			if (regs[rd] & 1) {
5003 				*flags |= CPU_DTRACE_BADALIGN;
5004 				*illval = regs[rd];
5005 				break;
5006 			}
5007 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5008 			break;
5009 
5010 		case DIF_OP_STW:
5011 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5012 				*flags |= CPU_DTRACE_BADADDR;
5013 				*illval = regs[rd];
5014 				break;
5015 			}
5016 			if (regs[rd] & 3) {
5017 				*flags |= CPU_DTRACE_BADALIGN;
5018 				*illval = regs[rd];
5019 				break;
5020 			}
5021 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5022 			break;
5023 
5024 		case DIF_OP_STX:
5025 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5026 				*flags |= CPU_DTRACE_BADADDR;
5027 				*illval = regs[rd];
5028 				break;
5029 			}
5030 			if (regs[rd] & 7) {
5031 				*flags |= CPU_DTRACE_BADALIGN;
5032 				*illval = regs[rd];
5033 				break;
5034 			}
5035 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5036 			break;
5037 		}
5038 	}
5039 
5040 	if (!(*flags & CPU_DTRACE_FAULT))
5041 		return (rval);
5042 
5043 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5044 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5045 
5046 	return (0);
5047 }
5048 
5049 static void
5050 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5051 {
5052 	dtrace_probe_t *probe = ecb->dte_probe;
5053 	dtrace_provider_t *prov = probe->dtpr_provider;
5054 	char c[DTRACE_FULLNAMELEN + 80], *str;
5055 	char *msg = "dtrace: breakpoint action at probe ";
5056 	char *ecbmsg = " (ecb ";
5057 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5058 	uintptr_t val = (uintptr_t)ecb;
5059 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5060 
5061 	if (dtrace_destructive_disallow)
5062 		return;
5063 
5064 	/*
5065 	 * It's impossible to be taking action on the NULL probe.
5066 	 */
5067 	ASSERT(probe != NULL);
5068 
5069 	/*
5070 	 * This is a poor man's (destitute man's?) sprintf():  we want to
5071 	 * print the provider name, module name, function name and name of
5072 	 * the probe, along with the hex address of the ECB with the breakpoint
5073 	 * action -- all of which we must place in the character buffer by
5074 	 * hand.
5075 	 */
5076 	while (*msg != '\0')
5077 		c[i++] = *msg++;
5078 
5079 	for (str = prov->dtpv_name; *str != '\0'; str++)
5080 		c[i++] = *str;
5081 	c[i++] = ':';
5082 
5083 	for (str = probe->dtpr_mod; *str != '\0'; str++)
5084 		c[i++] = *str;
5085 	c[i++] = ':';
5086 
5087 	for (str = probe->dtpr_func; *str != '\0'; str++)
5088 		c[i++] = *str;
5089 	c[i++] = ':';
5090 
5091 	for (str = probe->dtpr_name; *str != '\0'; str++)
5092 		c[i++] = *str;
5093 
5094 	while (*ecbmsg != '\0')
5095 		c[i++] = *ecbmsg++;
5096 
5097 	while (shift >= 0) {
5098 		mask = (uintptr_t)0xf << shift;
5099 
5100 		if (val >= ((uintptr_t)1 << shift))
5101 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5102 		shift -= 4;
5103 	}
5104 
5105 	c[i++] = ')';
5106 	c[i] = '\0';
5107 
5108 	debug_enter(c);
5109 }
5110 
5111 static void
5112 dtrace_action_panic(dtrace_ecb_t *ecb)
5113 {
5114 	dtrace_probe_t *probe = ecb->dte_probe;
5115 
5116 	/*
5117 	 * It's impossible to be taking action on the NULL probe.
5118 	 */
5119 	ASSERT(probe != NULL);
5120 
5121 	if (dtrace_destructive_disallow)
5122 		return;
5123 
5124 	if (dtrace_panicked != NULL)
5125 		return;
5126 
5127 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5128 		return;
5129 
5130 	/*
5131 	 * We won the right to panic.  (We want to be sure that only one
5132 	 * thread calls panic() from dtrace_probe(), and that panic() is
5133 	 * called exactly once.)
5134 	 */
5135 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5136 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5137 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5138 }
5139 
5140 static void
5141 dtrace_action_raise(uint64_t sig)
5142 {
5143 	if (dtrace_destructive_disallow)
5144 		return;
5145 
5146 	if (sig >= NSIG) {
5147 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5148 		return;
5149 	}
5150 
5151 	/*
5152 	 * raise() has a queue depth of 1 -- we ignore all subsequent
5153 	 * invocations of the raise() action.
5154 	 */
5155 	if (curthread->t_dtrace_sig == 0)
5156 		curthread->t_dtrace_sig = (uint8_t)sig;
5157 
5158 	curthread->t_sig_check = 1;
5159 	aston(curthread);
5160 }
5161 
5162 static void
5163 dtrace_action_stop(void)
5164 {
5165 	if (dtrace_destructive_disallow)
5166 		return;
5167 
5168 	if (!curthread->t_dtrace_stop) {
5169 		curthread->t_dtrace_stop = 1;
5170 		curthread->t_sig_check = 1;
5171 		aston(curthread);
5172 	}
5173 }
5174 
5175 static void
5176 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5177 {
5178 	hrtime_t now;
5179 	volatile uint16_t *flags;
5180 	cpu_t *cpu = CPU;
5181 
5182 	if (dtrace_destructive_disallow)
5183 		return;
5184 
5185 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5186 
5187 	now = dtrace_gethrtime();
5188 
5189 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5190 		/*
5191 		 * We need to advance the mark to the current time.
5192 		 */
5193 		cpu->cpu_dtrace_chillmark = now;
5194 		cpu->cpu_dtrace_chilled = 0;
5195 	}
5196 
5197 	/*
5198 	 * Now check to see if the requested chill time would take us over
5199 	 * the maximum amount of time allowed in the chill interval.  (Or
5200 	 * worse, if the calculation itself induces overflow.)
5201 	 */
5202 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5203 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5204 		*flags |= CPU_DTRACE_ILLOP;
5205 		return;
5206 	}
5207 
5208 	while (dtrace_gethrtime() - now < val)
5209 		continue;
5210 
5211 	/*
5212 	 * Normally, we assure that the value of the variable "timestamp" does
5213 	 * not change within an ECB.  The presence of chill() represents an
5214 	 * exception to this rule, however.
5215 	 */
5216 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5217 	cpu->cpu_dtrace_chilled += val;
5218 }
5219 
5220 static void
5221 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5222     uint64_t *buf, uint64_t arg)
5223 {
5224 	int nframes = DTRACE_USTACK_NFRAMES(arg);
5225 	int strsize = DTRACE_USTACK_STRSIZE(arg);
5226 	uint64_t *pcs = &buf[1], *fps;
5227 	char *str = (char *)&pcs[nframes];
5228 	int size, offs = 0, i, j;
5229 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
5230 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5231 	char *sym;
5232 
5233 	/*
5234 	 * Should be taking a faster path if string space has not been
5235 	 * allocated.
5236 	 */
5237 	ASSERT(strsize != 0);
5238 
5239 	/*
5240 	 * We will first allocate some temporary space for the frame pointers.
5241 	 */
5242 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5243 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5244 	    (nframes * sizeof (uint64_t));
5245 
5246 	if (!DTRACE_INSCRATCH(mstate, size)) {
5247 		/*
5248 		 * Not enough room for our frame pointers -- need to indicate
5249 		 * that we ran out of scratch space.
5250 		 */
5251 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5252 		return;
5253 	}
5254 
5255 	mstate->dtms_scratch_ptr += size;
5256 	saved = mstate->dtms_scratch_ptr;
5257 
5258 	/*
5259 	 * Now get a stack with both program counters and frame pointers.
5260 	 */
5261 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5262 	dtrace_getufpstack(buf, fps, nframes + 1);
5263 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5264 
5265 	/*
5266 	 * If that faulted, we're cooked.
5267 	 */
5268 	if (*flags & CPU_DTRACE_FAULT)
5269 		goto out;
5270 
5271 	/*
5272 	 * Now we want to walk up the stack, calling the USTACK helper.  For
5273 	 * each iteration, we restore the scratch pointer.
5274 	 */
5275 	for (i = 0; i < nframes; i++) {
5276 		mstate->dtms_scratch_ptr = saved;
5277 
5278 		if (offs >= strsize)
5279 			break;
5280 
5281 		sym = (char *)(uintptr_t)dtrace_helper(
5282 		    DTRACE_HELPER_ACTION_USTACK,
5283 		    mstate, state, pcs[i], fps[i]);
5284 
5285 		/*
5286 		 * If we faulted while running the helper, we're going to
5287 		 * clear the fault and null out the corresponding string.
5288 		 */
5289 		if (*flags & CPU_DTRACE_FAULT) {
5290 			*flags &= ~CPU_DTRACE_FAULT;
5291 			str[offs++] = '\0';
5292 			continue;
5293 		}
5294 
5295 		if (sym == NULL) {
5296 			str[offs++] = '\0';
5297 			continue;
5298 		}
5299 
5300 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5301 
5302 		/*
5303 		 * Now copy in the string that the helper returned to us.
5304 		 */
5305 		for (j = 0; offs + j < strsize; j++) {
5306 			if ((str[offs + j] = sym[j]) == '\0')
5307 				break;
5308 		}
5309 
5310 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5311 
5312 		offs += j + 1;
5313 	}
5314 
5315 	if (offs >= strsize) {
5316 		/*
5317 		 * If we didn't have room for all of the strings, we don't
5318 		 * abort processing -- this needn't be a fatal error -- but we
5319 		 * still want to increment a counter (dts_stkstroverflows) to
5320 		 * allow this condition to be warned about.  (If this is from
5321 		 * a jstack() action, it is easily tuned via jstackstrsize.)
5322 		 */
5323 		dtrace_error(&state->dts_stkstroverflows);
5324 	}
5325 
5326 	while (offs < strsize)
5327 		str[offs++] = '\0';
5328 
5329 out:
5330 	mstate->dtms_scratch_ptr = old;
5331 }
5332 
5333 /*
5334  * If you're looking for the epicenter of DTrace, you just found it.  This
5335  * is the function called by the provider to fire a probe -- from which all
5336  * subsequent probe-context DTrace activity emanates.
5337  */
5338 void
5339 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
5340     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
5341 {
5342 	processorid_t cpuid;
5343 	dtrace_icookie_t cookie;
5344 	dtrace_probe_t *probe;
5345 	dtrace_mstate_t mstate;
5346 	dtrace_ecb_t *ecb;
5347 	dtrace_action_t *act;
5348 	intptr_t offs;
5349 	size_t size;
5350 	int vtime, onintr;
5351 	volatile uint16_t *flags;
5352 	hrtime_t now;
5353 
5354 	/*
5355 	 * Kick out immediately if this CPU is still being born (in which case
5356 	 * curthread will be set to -1)
5357 	 */
5358 	if ((uintptr_t)curthread & 1)
5359 		return;
5360 
5361 	cookie = dtrace_interrupt_disable();
5362 	probe = dtrace_probes[id - 1];
5363 	cpuid = CPU->cpu_id;
5364 	onintr = CPU_ON_INTR(CPU);
5365 
5366 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
5367 	    probe->dtpr_predcache == curthread->t_predcache) {
5368 		/*
5369 		 * We have hit in the predicate cache; we know that
5370 		 * this predicate would evaluate to be false.
5371 		 */
5372 		dtrace_interrupt_enable(cookie);
5373 		return;
5374 	}
5375 
5376 	if (panic_quiesce) {
5377 		/*
5378 		 * We don't trace anything if we're panicking.
5379 		 */
5380 		dtrace_interrupt_enable(cookie);
5381 		return;
5382 	}
5383 
5384 	now = dtrace_gethrtime();
5385 	vtime = dtrace_vtime_references != 0;
5386 
5387 	if (vtime && curthread->t_dtrace_start)
5388 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
5389 
5390 	mstate.dtms_difo = NULL;
5391 	mstate.dtms_probe = probe;
5392 	mstate.dtms_strtok = NULL;
5393 	mstate.dtms_arg[0] = arg0;
5394 	mstate.dtms_arg[1] = arg1;
5395 	mstate.dtms_arg[2] = arg2;
5396 	mstate.dtms_arg[3] = arg3;
5397 	mstate.dtms_arg[4] = arg4;
5398 
5399 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
5400 
5401 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
5402 		dtrace_predicate_t *pred = ecb->dte_predicate;
5403 		dtrace_state_t *state = ecb->dte_state;
5404 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
5405 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
5406 		dtrace_vstate_t *vstate = &state->dts_vstate;
5407 		dtrace_provider_t *prov = probe->dtpr_provider;
5408 		int committed = 0;
5409 		caddr_t tomax;
5410 
5411 		/*
5412 		 * A little subtlety with the following (seemingly innocuous)
5413 		 * declaration of the automatic 'val':  by looking at the
5414 		 * code, you might think that it could be declared in the
5415 		 * action processing loop, below.  (That is, it's only used in
5416 		 * the action processing loop.)  However, it must be declared
5417 		 * out of that scope because in the case of DIF expression
5418 		 * arguments to aggregating actions, one iteration of the
5419 		 * action loop will use the last iteration's value.
5420 		 */
5421 #ifdef lint
5422 		uint64_t val = 0;
5423 #else
5424 		uint64_t val;
5425 #endif
5426 
5427 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
5428 		*flags &= ~CPU_DTRACE_ERROR;
5429 
5430 		if (prov == dtrace_provider) {
5431 			/*
5432 			 * If dtrace itself is the provider of this probe,
5433 			 * we're only going to continue processing the ECB if
5434 			 * arg0 (the dtrace_state_t) is equal to the ECB's
5435 			 * creating state.  (This prevents disjoint consumers
5436 			 * from seeing one another's metaprobes.)
5437 			 */
5438 			if (arg0 != (uint64_t)(uintptr_t)state)
5439 				continue;
5440 		}
5441 
5442 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
5443 			/*
5444 			 * We're not currently active.  If our provider isn't
5445 			 * the dtrace pseudo provider, we're not interested.
5446 			 */
5447 			if (prov != dtrace_provider)
5448 				continue;
5449 
5450 			/*
5451 			 * Now we must further check if we are in the BEGIN
5452 			 * probe.  If we are, we will only continue processing
5453 			 * if we're still in WARMUP -- if one BEGIN enabling
5454 			 * has invoked the exit() action, we don't want to
5455 			 * evaluate subsequent BEGIN enablings.
5456 			 */
5457 			if (probe->dtpr_id == dtrace_probeid_begin &&
5458 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
5459 				ASSERT(state->dts_activity ==
5460 				    DTRACE_ACTIVITY_DRAINING);
5461 				continue;
5462 			}
5463 		}
5464 
5465 		if (ecb->dte_cond) {
5466 			/*
5467 			 * If the dte_cond bits indicate that this
5468 			 * consumer is only allowed to see user-mode firings
5469 			 * of this probe, call the provider's dtps_usermode()
5470 			 * entry point to check that the probe was fired
5471 			 * while in a user context. Skip this ECB if that's
5472 			 * not the case.
5473 			 */
5474 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
5475 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
5476 			    probe->dtpr_id, probe->dtpr_arg) == 0)
5477 				continue;
5478 
5479 			/*
5480 			 * This is more subtle than it looks. We have to be
5481 			 * absolutely certain that CRED() isn't going to
5482 			 * change out from under us so it's only legit to
5483 			 * examine that structure if we're in constrained
5484 			 * situations. Currently, the only times we'll this
5485 			 * check is if a non-super-user has enabled the
5486 			 * profile or syscall providers -- providers that
5487 			 * allow visibility of all processes. For the
5488 			 * profile case, the check above will ensure that
5489 			 * we're examining a user context.
5490 			 */
5491 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
5492 				cred_t *cr;
5493 				cred_t *s_cr =
5494 				    ecb->dte_state->dts_cred.dcr_cred;
5495 				proc_t *proc;
5496 
5497 				ASSERT(s_cr != NULL);
5498 
5499 				if ((cr = CRED()) == NULL ||
5500 				    s_cr->cr_uid != cr->cr_uid ||
5501 				    s_cr->cr_uid != cr->cr_ruid ||
5502 				    s_cr->cr_uid != cr->cr_suid ||
5503 				    s_cr->cr_gid != cr->cr_gid ||
5504 				    s_cr->cr_gid != cr->cr_rgid ||
5505 				    s_cr->cr_gid != cr->cr_sgid ||
5506 				    (proc = ttoproc(curthread)) == NULL ||
5507 				    (proc->p_flag & SNOCD))
5508 					continue;
5509 			}
5510 
5511 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
5512 				cred_t *cr;
5513 				cred_t *s_cr =
5514 				    ecb->dte_state->dts_cred.dcr_cred;
5515 
5516 				ASSERT(s_cr != NULL);
5517 
5518 				if ((cr = CRED()) == NULL ||
5519 				    s_cr->cr_zone->zone_id !=
5520 				    cr->cr_zone->zone_id)
5521 					continue;
5522 			}
5523 		}
5524 
5525 		if (now - state->dts_alive > dtrace_deadman_timeout) {
5526 			/*
5527 			 * We seem to be dead.  Unless we (a) have kernel
5528 			 * destructive permissions (b) have expicitly enabled
5529 			 * destructive actions and (c) destructive actions have
5530 			 * not been disabled, we're going to transition into
5531 			 * the KILLED state, from which no further processing
5532 			 * on this state will be performed.
5533 			 */
5534 			if (!dtrace_priv_kernel_destructive(state) ||
5535 			    !state->dts_cred.dcr_destructive ||
5536 			    dtrace_destructive_disallow) {
5537 				void *activity = &state->dts_activity;
5538 				dtrace_activity_t current;
5539 
5540 				do {
5541 					current = state->dts_activity;
5542 				} while (dtrace_cas32(activity, current,
5543 				    DTRACE_ACTIVITY_KILLED) != current);
5544 
5545 				continue;
5546 			}
5547 		}
5548 
5549 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
5550 		    ecb->dte_alignment, state, &mstate)) < 0)
5551 			continue;
5552 
5553 		tomax = buf->dtb_tomax;
5554 		ASSERT(tomax != NULL);
5555 
5556 		if (ecb->dte_size != 0)
5557 			DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
5558 
5559 		mstate.dtms_epid = ecb->dte_epid;
5560 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
5561 
5562 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
5563 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
5564 		else
5565 			mstate.dtms_access = 0;
5566 
5567 		if (pred != NULL) {
5568 			dtrace_difo_t *dp = pred->dtp_difo;
5569 			int rval;
5570 
5571 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
5572 
5573 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
5574 				dtrace_cacheid_t cid = probe->dtpr_predcache;
5575 
5576 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
5577 					/*
5578 					 * Update the predicate cache...
5579 					 */
5580 					ASSERT(cid == pred->dtp_cacheid);
5581 					curthread->t_predcache = cid;
5582 				}
5583 
5584 				continue;
5585 			}
5586 		}
5587 
5588 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
5589 		    act != NULL; act = act->dta_next) {
5590 			size_t valoffs;
5591 			dtrace_difo_t *dp;
5592 			dtrace_recdesc_t *rec = &act->dta_rec;
5593 
5594 			size = rec->dtrd_size;
5595 			valoffs = offs + rec->dtrd_offset;
5596 
5597 			if (DTRACEACT_ISAGG(act->dta_kind)) {
5598 				uint64_t v = 0xbad;
5599 				dtrace_aggregation_t *agg;
5600 
5601 				agg = (dtrace_aggregation_t *)act;
5602 
5603 				if ((dp = act->dta_difo) != NULL)
5604 					v = dtrace_dif_emulate(dp,
5605 					    &mstate, vstate, state);
5606 
5607 				if (*flags & CPU_DTRACE_ERROR)
5608 					continue;
5609 
5610 				/*
5611 				 * Note that we always pass the expression
5612 				 * value from the previous iteration of the
5613 				 * action loop.  This value will only be used
5614 				 * if there is an expression argument to the
5615 				 * aggregating action, denoted by the
5616 				 * dtag_hasarg field.
5617 				 */
5618 				dtrace_aggregate(agg, buf,
5619 				    offs, aggbuf, v, val);
5620 				continue;
5621 			}
5622 
5623 			switch (act->dta_kind) {
5624 			case DTRACEACT_STOP:
5625 				if (dtrace_priv_proc_destructive(state))
5626 					dtrace_action_stop();
5627 				continue;
5628 
5629 			case DTRACEACT_BREAKPOINT:
5630 				if (dtrace_priv_kernel_destructive(state))
5631 					dtrace_action_breakpoint(ecb);
5632 				continue;
5633 
5634 			case DTRACEACT_PANIC:
5635 				if (dtrace_priv_kernel_destructive(state))
5636 					dtrace_action_panic(ecb);
5637 				continue;
5638 
5639 			case DTRACEACT_STACK:
5640 				if (!dtrace_priv_kernel(state))
5641 					continue;
5642 
5643 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
5644 				    size / sizeof (pc_t), probe->dtpr_aframes,
5645 				    DTRACE_ANCHORED(probe) ? NULL :
5646 				    (uint32_t *)arg0);
5647 
5648 				continue;
5649 
5650 			case DTRACEACT_JSTACK:
5651 			case DTRACEACT_USTACK:
5652 				if (!dtrace_priv_proc(state))
5653 					continue;
5654 
5655 				/*
5656 				 * See comment in DIF_VAR_PID.
5657 				 */
5658 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
5659 				    CPU_ON_INTR(CPU)) {
5660 					int depth = DTRACE_USTACK_NFRAMES(
5661 					    rec->dtrd_arg) + 1;
5662 
5663 					dtrace_bzero((void *)(tomax + valoffs),
5664 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
5665 					    + depth * sizeof (uint64_t));
5666 
5667 					continue;
5668 				}
5669 
5670 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
5671 				    curproc->p_dtrace_helpers != NULL) {
5672 					/*
5673 					 * This is the slow path -- we have
5674 					 * allocated string space, and we're
5675 					 * getting the stack of a process that
5676 					 * has helpers.  Call into a separate
5677 					 * routine to perform this processing.
5678 					 */
5679 					dtrace_action_ustack(&mstate, state,
5680 					    (uint64_t *)(tomax + valoffs),
5681 					    rec->dtrd_arg);
5682 					continue;
5683 				}
5684 
5685 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5686 				dtrace_getupcstack((uint64_t *)
5687 				    (tomax + valoffs),
5688 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
5689 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5690 				continue;
5691 
5692 			default:
5693 				break;
5694 			}
5695 
5696 			dp = act->dta_difo;
5697 			ASSERT(dp != NULL);
5698 
5699 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
5700 
5701 			if (*flags & CPU_DTRACE_ERROR)
5702 				continue;
5703 
5704 			switch (act->dta_kind) {
5705 			case DTRACEACT_SPECULATE:
5706 				ASSERT(buf == &state->dts_buffer[cpuid]);
5707 				buf = dtrace_speculation_buffer(state,
5708 				    cpuid, val);
5709 
5710 				if (buf == NULL) {
5711 					*flags |= CPU_DTRACE_DROP;
5712 					continue;
5713 				}
5714 
5715 				offs = dtrace_buffer_reserve(buf,
5716 				    ecb->dte_needed, ecb->dte_alignment,
5717 				    state, NULL);
5718 
5719 				if (offs < 0) {
5720 					*flags |= CPU_DTRACE_DROP;
5721 					continue;
5722 				}
5723 
5724 				tomax = buf->dtb_tomax;
5725 				ASSERT(tomax != NULL);
5726 
5727 				if (ecb->dte_size != 0)
5728 					DTRACE_STORE(uint32_t, tomax, offs,
5729 					    ecb->dte_epid);
5730 				continue;
5731 
5732 			case DTRACEACT_CHILL:
5733 				if (dtrace_priv_kernel_destructive(state))
5734 					dtrace_action_chill(&mstate, val);
5735 				continue;
5736 
5737 			case DTRACEACT_RAISE:
5738 				if (dtrace_priv_proc_destructive(state))
5739 					dtrace_action_raise(val);
5740 				continue;
5741 
5742 			case DTRACEACT_COMMIT:
5743 				ASSERT(!committed);
5744 
5745 				/*
5746 				 * We need to commit our buffer state.
5747 				 */
5748 				if (ecb->dte_size)
5749 					buf->dtb_offset = offs + ecb->dte_size;
5750 				buf = &state->dts_buffer[cpuid];
5751 				dtrace_speculation_commit(state, cpuid, val);
5752 				committed = 1;
5753 				continue;
5754 
5755 			case DTRACEACT_DISCARD:
5756 				dtrace_speculation_discard(state, cpuid, val);
5757 				continue;
5758 
5759 			case DTRACEACT_DIFEXPR:
5760 			case DTRACEACT_LIBACT:
5761 			case DTRACEACT_PRINTF:
5762 			case DTRACEACT_PRINTA:
5763 			case DTRACEACT_SYSTEM:
5764 			case DTRACEACT_FREOPEN:
5765 				break;
5766 
5767 			case DTRACEACT_SYM:
5768 			case DTRACEACT_MOD:
5769 				if (!dtrace_priv_kernel(state))
5770 					continue;
5771 				break;
5772 
5773 			case DTRACEACT_USYM:
5774 			case DTRACEACT_UMOD:
5775 			case DTRACEACT_UADDR: {
5776 				struct pid *pid = curthread->t_procp->p_pidp;
5777 
5778 				if (!dtrace_priv_proc(state))
5779 					continue;
5780 
5781 				DTRACE_STORE(uint64_t, tomax,
5782 				    valoffs, (uint64_t)pid->pid_id);
5783 				DTRACE_STORE(uint64_t, tomax,
5784 				    valoffs + sizeof (uint64_t), val);
5785 
5786 				continue;
5787 			}
5788 
5789 			case DTRACEACT_EXIT: {
5790 				/*
5791 				 * For the exit action, we are going to attempt
5792 				 * to atomically set our activity to be
5793 				 * draining.  If this fails (either because
5794 				 * another CPU has beat us to the exit action,
5795 				 * or because our current activity is something
5796 				 * other than ACTIVE or WARMUP), we will
5797 				 * continue.  This assures that the exit action
5798 				 * can be successfully recorded at most once
5799 				 * when we're in the ACTIVE state.  If we're
5800 				 * encountering the exit() action while in
5801 				 * COOLDOWN, however, we want to honor the new
5802 				 * status code.  (We know that we're the only
5803 				 * thread in COOLDOWN, so there is no race.)
5804 				 */
5805 				void *activity = &state->dts_activity;
5806 				dtrace_activity_t current = state->dts_activity;
5807 
5808 				if (current == DTRACE_ACTIVITY_COOLDOWN)
5809 					break;
5810 
5811 				if (current != DTRACE_ACTIVITY_WARMUP)
5812 					current = DTRACE_ACTIVITY_ACTIVE;
5813 
5814 				if (dtrace_cas32(activity, current,
5815 				    DTRACE_ACTIVITY_DRAINING) != current) {
5816 					*flags |= CPU_DTRACE_DROP;
5817 					continue;
5818 				}
5819 
5820 				break;
5821 			}
5822 
5823 			default:
5824 				ASSERT(0);
5825 			}
5826 
5827 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
5828 				uintptr_t end = valoffs + size;
5829 
5830 				if (!dtrace_vcanload((void *)(uintptr_t)val,
5831 				    &dp->dtdo_rtype, &mstate, vstate))
5832 					continue;
5833 
5834 				/*
5835 				 * If this is a string, we're going to only
5836 				 * load until we find the zero byte -- after
5837 				 * which we'll store zero bytes.
5838 				 */
5839 				if (dp->dtdo_rtype.dtdt_kind ==
5840 				    DIF_TYPE_STRING) {
5841 					char c = '\0' + 1;
5842 					int intuple = act->dta_intuple;
5843 					size_t s;
5844 
5845 					for (s = 0; s < size; s++) {
5846 						if (c != '\0')
5847 							c = dtrace_load8(val++);
5848 
5849 						DTRACE_STORE(uint8_t, tomax,
5850 						    valoffs++, c);
5851 
5852 						if (c == '\0' && intuple)
5853 							break;
5854 					}
5855 
5856 					continue;
5857 				}
5858 
5859 				while (valoffs < end) {
5860 					DTRACE_STORE(uint8_t, tomax, valoffs++,
5861 					    dtrace_load8(val++));
5862 				}
5863 
5864 				continue;
5865 			}
5866 
5867 			switch (size) {
5868 			case 0:
5869 				break;
5870 
5871 			case sizeof (uint8_t):
5872 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
5873 				break;
5874 			case sizeof (uint16_t):
5875 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
5876 				break;
5877 			case sizeof (uint32_t):
5878 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
5879 				break;
5880 			case sizeof (uint64_t):
5881 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
5882 				break;
5883 			default:
5884 				/*
5885 				 * Any other size should have been returned by
5886 				 * reference, not by value.
5887 				 */
5888 				ASSERT(0);
5889 				break;
5890 			}
5891 		}
5892 
5893 		if (*flags & CPU_DTRACE_DROP)
5894 			continue;
5895 
5896 		if (*flags & CPU_DTRACE_FAULT) {
5897 			int ndx;
5898 			dtrace_action_t *err;
5899 
5900 			buf->dtb_errors++;
5901 
5902 			if (probe->dtpr_id == dtrace_probeid_error) {
5903 				/*
5904 				 * There's nothing we can do -- we had an
5905 				 * error on the error probe.  We bump an
5906 				 * error counter to at least indicate that
5907 				 * this condition happened.
5908 				 */
5909 				dtrace_error(&state->dts_dblerrors);
5910 				continue;
5911 			}
5912 
5913 			if (vtime) {
5914 				/*
5915 				 * Before recursing on dtrace_probe(), we
5916 				 * need to explicitly clear out our start
5917 				 * time to prevent it from being accumulated
5918 				 * into t_dtrace_vtime.
5919 				 */
5920 				curthread->t_dtrace_start = 0;
5921 			}
5922 
5923 			/*
5924 			 * Iterate over the actions to figure out which action
5925 			 * we were processing when we experienced the error.
5926 			 * Note that act points _past_ the faulting action; if
5927 			 * act is ecb->dte_action, the fault was in the
5928 			 * predicate, if it's ecb->dte_action->dta_next it's
5929 			 * in action #1, and so on.
5930 			 */
5931 			for (err = ecb->dte_action, ndx = 0;
5932 			    err != act; err = err->dta_next, ndx++)
5933 				continue;
5934 
5935 			dtrace_probe_error(state, ecb->dte_epid, ndx,
5936 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
5937 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
5938 			    cpu_core[cpuid].cpuc_dtrace_illval);
5939 
5940 			continue;
5941 		}
5942 
5943 		if (!committed)
5944 			buf->dtb_offset = offs + ecb->dte_size;
5945 	}
5946 
5947 	if (vtime)
5948 		curthread->t_dtrace_start = dtrace_gethrtime();
5949 
5950 	dtrace_interrupt_enable(cookie);
5951 }
5952 
5953 /*
5954  * DTrace Probe Hashing Functions
5955  *
5956  * The functions in this section (and indeed, the functions in remaining
5957  * sections) are not _called_ from probe context.  (Any exceptions to this are
5958  * marked with a "Note:".)  Rather, they are called from elsewhere in the
5959  * DTrace framework to look-up probes in, add probes to and remove probes from
5960  * the DTrace probe hashes.  (Each probe is hashed by each element of the
5961  * probe tuple -- allowing for fast lookups, regardless of what was
5962  * specified.)
5963  */
5964 static uint_t
5965 dtrace_hash_str(char *p)
5966 {
5967 	unsigned int g;
5968 	uint_t hval = 0;
5969 
5970 	while (*p) {
5971 		hval = (hval << 4) + *p++;
5972 		if ((g = (hval & 0xf0000000)) != 0)
5973 			hval ^= g >> 24;
5974 		hval &= ~g;
5975 	}
5976 	return (hval);
5977 }
5978 
5979 static dtrace_hash_t *
5980 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
5981 {
5982 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
5983 
5984 	hash->dth_stroffs = stroffs;
5985 	hash->dth_nextoffs = nextoffs;
5986 	hash->dth_prevoffs = prevoffs;
5987 
5988 	hash->dth_size = 1;
5989 	hash->dth_mask = hash->dth_size - 1;
5990 
5991 	hash->dth_tab = kmem_zalloc(hash->dth_size *
5992 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
5993 
5994 	return (hash);
5995 }
5996 
5997 static void
5998 dtrace_hash_destroy(dtrace_hash_t *hash)
5999 {
6000 #ifdef DEBUG
6001 	int i;
6002 
6003 	for (i = 0; i < hash->dth_size; i++)
6004 		ASSERT(hash->dth_tab[i] == NULL);
6005 #endif
6006 
6007 	kmem_free(hash->dth_tab,
6008 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
6009 	kmem_free(hash, sizeof (dtrace_hash_t));
6010 }
6011 
6012 static void
6013 dtrace_hash_resize(dtrace_hash_t *hash)
6014 {
6015 	int size = hash->dth_size, i, ndx;
6016 	int new_size = hash->dth_size << 1;
6017 	int new_mask = new_size - 1;
6018 	dtrace_hashbucket_t **new_tab, *bucket, *next;
6019 
6020 	ASSERT((new_size & new_mask) == 0);
6021 
6022 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6023 
6024 	for (i = 0; i < size; i++) {
6025 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6026 			dtrace_probe_t *probe = bucket->dthb_chain;
6027 
6028 			ASSERT(probe != NULL);
6029 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6030 
6031 			next = bucket->dthb_next;
6032 			bucket->dthb_next = new_tab[ndx];
6033 			new_tab[ndx] = bucket;
6034 		}
6035 	}
6036 
6037 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6038 	hash->dth_tab = new_tab;
6039 	hash->dth_size = new_size;
6040 	hash->dth_mask = new_mask;
6041 }
6042 
6043 static void
6044 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6045 {
6046 	int hashval = DTRACE_HASHSTR(hash, new);
6047 	int ndx = hashval & hash->dth_mask;
6048 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6049 	dtrace_probe_t **nextp, **prevp;
6050 
6051 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6052 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6053 			goto add;
6054 	}
6055 
6056 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6057 		dtrace_hash_resize(hash);
6058 		dtrace_hash_add(hash, new);
6059 		return;
6060 	}
6061 
6062 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6063 	bucket->dthb_next = hash->dth_tab[ndx];
6064 	hash->dth_tab[ndx] = bucket;
6065 	hash->dth_nbuckets++;
6066 
6067 add:
6068 	nextp = DTRACE_HASHNEXT(hash, new);
6069 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6070 	*nextp = bucket->dthb_chain;
6071 
6072 	if (bucket->dthb_chain != NULL) {
6073 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6074 		ASSERT(*prevp == NULL);
6075 		*prevp = new;
6076 	}
6077 
6078 	bucket->dthb_chain = new;
6079 	bucket->dthb_len++;
6080 }
6081 
6082 static dtrace_probe_t *
6083 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6084 {
6085 	int hashval = DTRACE_HASHSTR(hash, template);
6086 	int ndx = hashval & hash->dth_mask;
6087 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6088 
6089 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6090 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6091 			return (bucket->dthb_chain);
6092 	}
6093 
6094 	return (NULL);
6095 }
6096 
6097 static int
6098 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6099 {
6100 	int hashval = DTRACE_HASHSTR(hash, template);
6101 	int ndx = hashval & hash->dth_mask;
6102 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6103 
6104 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6105 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6106 			return (bucket->dthb_len);
6107 	}
6108 
6109 	return (NULL);
6110 }
6111 
6112 static void
6113 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6114 {
6115 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6116 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6117 
6118 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6119 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6120 
6121 	/*
6122 	 * Find the bucket that we're removing this probe from.
6123 	 */
6124 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6125 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6126 			break;
6127 	}
6128 
6129 	ASSERT(bucket != NULL);
6130 
6131 	if (*prevp == NULL) {
6132 		if (*nextp == NULL) {
6133 			/*
6134 			 * The removed probe was the only probe on this
6135 			 * bucket; we need to remove the bucket.
6136 			 */
6137 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6138 
6139 			ASSERT(bucket->dthb_chain == probe);
6140 			ASSERT(b != NULL);
6141 
6142 			if (b == bucket) {
6143 				hash->dth_tab[ndx] = bucket->dthb_next;
6144 			} else {
6145 				while (b->dthb_next != bucket)
6146 					b = b->dthb_next;
6147 				b->dthb_next = bucket->dthb_next;
6148 			}
6149 
6150 			ASSERT(hash->dth_nbuckets > 0);
6151 			hash->dth_nbuckets--;
6152 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
6153 			return;
6154 		}
6155 
6156 		bucket->dthb_chain = *nextp;
6157 	} else {
6158 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
6159 	}
6160 
6161 	if (*nextp != NULL)
6162 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
6163 }
6164 
6165 /*
6166  * DTrace Utility Functions
6167  *
6168  * These are random utility functions that are _not_ called from probe context.
6169  */
6170 static int
6171 dtrace_badattr(const dtrace_attribute_t *a)
6172 {
6173 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
6174 	    a->dtat_data > DTRACE_STABILITY_MAX ||
6175 	    a->dtat_class > DTRACE_CLASS_MAX);
6176 }
6177 
6178 /*
6179  * Return a duplicate copy of a string.  If the specified string is NULL,
6180  * this function returns a zero-length string.
6181  */
6182 static char *
6183 dtrace_strdup(const char *str)
6184 {
6185 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
6186 
6187 	if (str != NULL)
6188 		(void) strcpy(new, str);
6189 
6190 	return (new);
6191 }
6192 
6193 #define	DTRACE_ISALPHA(c)	\
6194 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
6195 
6196 static int
6197 dtrace_badname(const char *s)
6198 {
6199 	char c;
6200 
6201 	if (s == NULL || (c = *s++) == '\0')
6202 		return (0);
6203 
6204 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
6205 		return (1);
6206 
6207 	while ((c = *s++) != '\0') {
6208 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
6209 		    c != '-' && c != '_' && c != '.' && c != '`')
6210 			return (1);
6211 	}
6212 
6213 	return (0);
6214 }
6215 
6216 static void
6217 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
6218 {
6219 	uint32_t priv;
6220 
6221 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
6222 		/*
6223 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
6224 		 */
6225 		priv = DTRACE_PRIV_ALL;
6226 	} else {
6227 		*uidp = crgetuid(cr);
6228 		*zoneidp = crgetzoneid(cr);
6229 
6230 		priv = 0;
6231 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
6232 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
6233 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
6234 			priv |= DTRACE_PRIV_USER;
6235 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
6236 			priv |= DTRACE_PRIV_PROC;
6237 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
6238 			priv |= DTRACE_PRIV_OWNER;
6239 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
6240 			priv |= DTRACE_PRIV_ZONEOWNER;
6241 	}
6242 
6243 	*privp = priv;
6244 }
6245 
6246 #ifdef DTRACE_ERRDEBUG
6247 static void
6248 dtrace_errdebug(const char *str)
6249 {
6250 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
6251 	int occupied = 0;
6252 
6253 	mutex_enter(&dtrace_errlock);
6254 	dtrace_errlast = str;
6255 	dtrace_errthread = curthread;
6256 
6257 	while (occupied++ < DTRACE_ERRHASHSZ) {
6258 		if (dtrace_errhash[hval].dter_msg == str) {
6259 			dtrace_errhash[hval].dter_count++;
6260 			goto out;
6261 		}
6262 
6263 		if (dtrace_errhash[hval].dter_msg != NULL) {
6264 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
6265 			continue;
6266 		}
6267 
6268 		dtrace_errhash[hval].dter_msg = str;
6269 		dtrace_errhash[hval].dter_count = 1;
6270 		goto out;
6271 	}
6272 
6273 	panic("dtrace: undersized error hash");
6274 out:
6275 	mutex_exit(&dtrace_errlock);
6276 }
6277 #endif
6278 
6279 /*
6280  * DTrace Matching Functions
6281  *
6282  * These functions are used to match groups of probes, given some elements of
6283  * a probe tuple, or some globbed expressions for elements of a probe tuple.
6284  */
6285 static int
6286 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
6287     zoneid_t zoneid)
6288 {
6289 	if (priv != DTRACE_PRIV_ALL) {
6290 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
6291 		uint32_t match = priv & ppriv;
6292 
6293 		/*
6294 		 * No PRIV_DTRACE_* privileges...
6295 		 */
6296 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
6297 		    DTRACE_PRIV_KERNEL)) == 0)
6298 			return (0);
6299 
6300 		/*
6301 		 * No matching bits, but there were bits to match...
6302 		 */
6303 		if (match == 0 && ppriv != 0)
6304 			return (0);
6305 
6306 		/*
6307 		 * Need to have permissions to the process, but don't...
6308 		 */
6309 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
6310 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
6311 			return (0);
6312 		}
6313 
6314 		/*
6315 		 * Need to be in the same zone unless we possess the
6316 		 * privilege to examine all zones.
6317 		 */
6318 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
6319 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
6320 			return (0);
6321 		}
6322 	}
6323 
6324 	return (1);
6325 }
6326 
6327 /*
6328  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
6329  * consists of input pattern strings and an ops-vector to evaluate them.
6330  * This function returns >0 for match, 0 for no match, and <0 for error.
6331  */
6332 static int
6333 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
6334     uint32_t priv, uid_t uid, zoneid_t zoneid)
6335 {
6336 	dtrace_provider_t *pvp = prp->dtpr_provider;
6337 	int rv;
6338 
6339 	if (pvp->dtpv_defunct)
6340 		return (0);
6341 
6342 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
6343 		return (rv);
6344 
6345 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
6346 		return (rv);
6347 
6348 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
6349 		return (rv);
6350 
6351 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
6352 		return (rv);
6353 
6354 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
6355 		return (0);
6356 
6357 	return (rv);
6358 }
6359 
6360 /*
6361  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
6362  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
6363  * libc's version, the kernel version only applies to 8-bit ASCII strings.
6364  * In addition, all of the recursion cases except for '*' matching have been
6365  * unwound.  For '*', we still implement recursive evaluation, but a depth
6366  * counter is maintained and matching is aborted if we recurse too deep.
6367  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
6368  */
6369 static int
6370 dtrace_match_glob(const char *s, const char *p, int depth)
6371 {
6372 	const char *olds;
6373 	char s1, c;
6374 	int gs;
6375 
6376 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
6377 		return (-1);
6378 
6379 	if (s == NULL)
6380 		s = ""; /* treat NULL as empty string */
6381 
6382 top:
6383 	olds = s;
6384 	s1 = *s++;
6385 
6386 	if (p == NULL)
6387 		return (0);
6388 
6389 	if ((c = *p++) == '\0')
6390 		return (s1 == '\0');
6391 
6392 	switch (c) {
6393 	case '[': {
6394 		int ok = 0, notflag = 0;
6395 		char lc = '\0';
6396 
6397 		if (s1 == '\0')
6398 			return (0);
6399 
6400 		if (*p == '!') {
6401 			notflag = 1;
6402 			p++;
6403 		}
6404 
6405 		if ((c = *p++) == '\0')
6406 			return (0);
6407 
6408 		do {
6409 			if (c == '-' && lc != '\0' && *p != ']') {
6410 				if ((c = *p++) == '\0')
6411 					return (0);
6412 				if (c == '\\' && (c = *p++) == '\0')
6413 					return (0);
6414 
6415 				if (notflag) {
6416 					if (s1 < lc || s1 > c)
6417 						ok++;
6418 					else
6419 						return (0);
6420 				} else if (lc <= s1 && s1 <= c)
6421 					ok++;
6422 
6423 			} else if (c == '\\' && (c = *p++) == '\0')
6424 				return (0);
6425 
6426 			lc = c; /* save left-hand 'c' for next iteration */
6427 
6428 			if (notflag) {
6429 				if (s1 != c)
6430 					ok++;
6431 				else
6432 					return (0);
6433 			} else if (s1 == c)
6434 				ok++;
6435 
6436 			if ((c = *p++) == '\0')
6437 				return (0);
6438 
6439 		} while (c != ']');
6440 
6441 		if (ok)
6442 			goto top;
6443 
6444 		return (0);
6445 	}
6446 
6447 	case '\\':
6448 		if ((c = *p++) == '\0')
6449 			return (0);
6450 		/*FALLTHRU*/
6451 
6452 	default:
6453 		if (c != s1)
6454 			return (0);
6455 		/*FALLTHRU*/
6456 
6457 	case '?':
6458 		if (s1 != '\0')
6459 			goto top;
6460 		return (0);
6461 
6462 	case '*':
6463 		while (*p == '*')
6464 			p++; /* consecutive *'s are identical to a single one */
6465 
6466 		if (*p == '\0')
6467 			return (1);
6468 
6469 		for (s = olds; *s != '\0'; s++) {
6470 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
6471 				return (gs);
6472 		}
6473 
6474 		return (0);
6475 	}
6476 }
6477 
6478 /*ARGSUSED*/
6479 static int
6480 dtrace_match_string(const char *s, const char *p, int depth)
6481 {
6482 	return (s != NULL && strcmp(s, p) == 0);
6483 }
6484 
6485 /*ARGSUSED*/
6486 static int
6487 dtrace_match_nul(const char *s, const char *p, int depth)
6488 {
6489 	return (1); /* always match the empty pattern */
6490 }
6491 
6492 /*ARGSUSED*/
6493 static int
6494 dtrace_match_nonzero(const char *s, const char *p, int depth)
6495 {
6496 	return (s != NULL && s[0] != '\0');
6497 }
6498 
6499 static int
6500 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
6501     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
6502 {
6503 	dtrace_probe_t template, *probe;
6504 	dtrace_hash_t *hash = NULL;
6505 	int len, best = INT_MAX, nmatched = 0;
6506 	dtrace_id_t i;
6507 
6508 	ASSERT(MUTEX_HELD(&dtrace_lock));
6509 
6510 	/*
6511 	 * If the probe ID is specified in the key, just lookup by ID and
6512 	 * invoke the match callback once if a matching probe is found.
6513 	 */
6514 	if (pkp->dtpk_id != DTRACE_IDNONE) {
6515 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
6516 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
6517 			(void) (*matched)(probe, arg);
6518 			nmatched++;
6519 		}
6520 		return (nmatched);
6521 	}
6522 
6523 	template.dtpr_mod = (char *)pkp->dtpk_mod;
6524 	template.dtpr_func = (char *)pkp->dtpk_func;
6525 	template.dtpr_name = (char *)pkp->dtpk_name;
6526 
6527 	/*
6528 	 * We want to find the most distinct of the module name, function
6529 	 * name, and name.  So for each one that is not a glob pattern or
6530 	 * empty string, we perform a lookup in the corresponding hash and
6531 	 * use the hash table with the fewest collisions to do our search.
6532 	 */
6533 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
6534 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
6535 		best = len;
6536 		hash = dtrace_bymod;
6537 	}
6538 
6539 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
6540 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
6541 		best = len;
6542 		hash = dtrace_byfunc;
6543 	}
6544 
6545 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
6546 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
6547 		best = len;
6548 		hash = dtrace_byname;
6549 	}
6550 
6551 	/*
6552 	 * If we did not select a hash table, iterate over every probe and
6553 	 * invoke our callback for each one that matches our input probe key.
6554 	 */
6555 	if (hash == NULL) {
6556 		for (i = 0; i < dtrace_nprobes; i++) {
6557 			if ((probe = dtrace_probes[i]) == NULL ||
6558 			    dtrace_match_probe(probe, pkp, priv, uid,
6559 			    zoneid) <= 0)
6560 				continue;
6561 
6562 			nmatched++;
6563 
6564 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
6565 				break;
6566 		}
6567 
6568 		return (nmatched);
6569 	}
6570 
6571 	/*
6572 	 * If we selected a hash table, iterate over each probe of the same key
6573 	 * name and invoke the callback for every probe that matches the other
6574 	 * attributes of our input probe key.
6575 	 */
6576 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
6577 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
6578 
6579 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
6580 			continue;
6581 
6582 		nmatched++;
6583 
6584 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
6585 			break;
6586 	}
6587 
6588 	return (nmatched);
6589 }
6590 
6591 /*
6592  * Return the function pointer dtrace_probecmp() should use to compare the
6593  * specified pattern with a string.  For NULL or empty patterns, we select
6594  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
6595  * For non-empty non-glob strings, we use dtrace_match_string().
6596  */
6597 static dtrace_probekey_f *
6598 dtrace_probekey_func(const char *p)
6599 {
6600 	char c;
6601 
6602 	if (p == NULL || *p == '\0')
6603 		return (&dtrace_match_nul);
6604 
6605 	while ((c = *p++) != '\0') {
6606 		if (c == '[' || c == '?' || c == '*' || c == '\\')
6607 			return (&dtrace_match_glob);
6608 	}
6609 
6610 	return (&dtrace_match_string);
6611 }
6612 
6613 /*
6614  * Build a probe comparison key for use with dtrace_match_probe() from the
6615  * given probe description.  By convention, a null key only matches anchored
6616  * probes: if each field is the empty string, reset dtpk_fmatch to
6617  * dtrace_match_nonzero().
6618  */
6619 static void
6620 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
6621 {
6622 	pkp->dtpk_prov = pdp->dtpd_provider;
6623 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
6624 
6625 	pkp->dtpk_mod = pdp->dtpd_mod;
6626 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
6627 
6628 	pkp->dtpk_func = pdp->dtpd_func;
6629 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
6630 
6631 	pkp->dtpk_name = pdp->dtpd_name;
6632 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
6633 
6634 	pkp->dtpk_id = pdp->dtpd_id;
6635 
6636 	if (pkp->dtpk_id == DTRACE_IDNONE &&
6637 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
6638 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
6639 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
6640 	    pkp->dtpk_nmatch == &dtrace_match_nul)
6641 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
6642 }
6643 
6644 /*
6645  * DTrace Provider-to-Framework API Functions
6646  *
6647  * These functions implement much of the Provider-to-Framework API, as
6648  * described in <sys/dtrace.h>.  The parts of the API not in this section are
6649  * the functions in the API for probe management (found below), and
6650  * dtrace_probe() itself (found above).
6651  */
6652 
6653 /*
6654  * Register the calling provider with the DTrace framework.  This should
6655  * generally be called by DTrace providers in their attach(9E) entry point.
6656  */
6657 int
6658 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
6659     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
6660 {
6661 	dtrace_provider_t *provider;
6662 
6663 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
6664 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6665 		    "arguments", name ? name : "<NULL>");
6666 		return (EINVAL);
6667 	}
6668 
6669 	if (name[0] == '\0' || dtrace_badname(name)) {
6670 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6671 		    "provider name", name);
6672 		return (EINVAL);
6673 	}
6674 
6675 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
6676 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
6677 	    pops->dtps_destroy == NULL ||
6678 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
6679 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6680 		    "provider ops", name);
6681 		return (EINVAL);
6682 	}
6683 
6684 	if (dtrace_badattr(&pap->dtpa_provider) ||
6685 	    dtrace_badattr(&pap->dtpa_mod) ||
6686 	    dtrace_badattr(&pap->dtpa_func) ||
6687 	    dtrace_badattr(&pap->dtpa_name) ||
6688 	    dtrace_badattr(&pap->dtpa_args)) {
6689 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6690 		    "provider attributes", name);
6691 		return (EINVAL);
6692 	}
6693 
6694 	if (priv & ~DTRACE_PRIV_ALL) {
6695 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6696 		    "privilege attributes", name);
6697 		return (EINVAL);
6698 	}
6699 
6700 	if ((priv & DTRACE_PRIV_KERNEL) &&
6701 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
6702 	    pops->dtps_usermode == NULL) {
6703 		cmn_err(CE_WARN, "failed to register provider '%s': need "
6704 		    "dtps_usermode() op for given privilege attributes", name);
6705 		return (EINVAL);
6706 	}
6707 
6708 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
6709 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
6710 	(void) strcpy(provider->dtpv_name, name);
6711 
6712 	provider->dtpv_attr = *pap;
6713 	provider->dtpv_priv.dtpp_flags = priv;
6714 	if (cr != NULL) {
6715 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
6716 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
6717 	}
6718 	provider->dtpv_pops = *pops;
6719 
6720 	if (pops->dtps_provide == NULL) {
6721 		ASSERT(pops->dtps_provide_module != NULL);
6722 		provider->dtpv_pops.dtps_provide =
6723 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
6724 	}
6725 
6726 	if (pops->dtps_provide_module == NULL) {
6727 		ASSERT(pops->dtps_provide != NULL);
6728 		provider->dtpv_pops.dtps_provide_module =
6729 		    (void (*)(void *, struct modctl *))dtrace_nullop;
6730 	}
6731 
6732 	if (pops->dtps_suspend == NULL) {
6733 		ASSERT(pops->dtps_resume == NULL);
6734 		provider->dtpv_pops.dtps_suspend =
6735 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6736 		provider->dtpv_pops.dtps_resume =
6737 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6738 	}
6739 
6740 	provider->dtpv_arg = arg;
6741 	*idp = (dtrace_provider_id_t)provider;
6742 
6743 	if (pops == &dtrace_provider_ops) {
6744 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6745 		ASSERT(MUTEX_HELD(&dtrace_lock));
6746 		ASSERT(dtrace_anon.dta_enabling == NULL);
6747 
6748 		/*
6749 		 * We make sure that the DTrace provider is at the head of
6750 		 * the provider chain.
6751 		 */
6752 		provider->dtpv_next = dtrace_provider;
6753 		dtrace_provider = provider;
6754 		return (0);
6755 	}
6756 
6757 	mutex_enter(&dtrace_provider_lock);
6758 	mutex_enter(&dtrace_lock);
6759 
6760 	/*
6761 	 * If there is at least one provider registered, we'll add this
6762 	 * provider after the first provider.
6763 	 */
6764 	if (dtrace_provider != NULL) {
6765 		provider->dtpv_next = dtrace_provider->dtpv_next;
6766 		dtrace_provider->dtpv_next = provider;
6767 	} else {
6768 		dtrace_provider = provider;
6769 	}
6770 
6771 	if (dtrace_retained != NULL) {
6772 		dtrace_enabling_provide(provider);
6773 
6774 		/*
6775 		 * Now we need to call dtrace_enabling_matchall() -- which
6776 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
6777 		 * to drop all of our locks before calling into it...
6778 		 */
6779 		mutex_exit(&dtrace_lock);
6780 		mutex_exit(&dtrace_provider_lock);
6781 		dtrace_enabling_matchall();
6782 
6783 		return (0);
6784 	}
6785 
6786 	mutex_exit(&dtrace_lock);
6787 	mutex_exit(&dtrace_provider_lock);
6788 
6789 	return (0);
6790 }
6791 
6792 /*
6793  * Unregister the specified provider from the DTrace framework.  This should
6794  * generally be called by DTrace providers in their detach(9E) entry point.
6795  */
6796 int
6797 dtrace_unregister(dtrace_provider_id_t id)
6798 {
6799 	dtrace_provider_t *old = (dtrace_provider_t *)id;
6800 	dtrace_provider_t *prev = NULL;
6801 	int i, self = 0;
6802 	dtrace_probe_t *probe, *first = NULL;
6803 
6804 	if (old->dtpv_pops.dtps_enable ==
6805 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
6806 		/*
6807 		 * If DTrace itself is the provider, we're called with locks
6808 		 * already held.
6809 		 */
6810 		ASSERT(old == dtrace_provider);
6811 		ASSERT(dtrace_devi != NULL);
6812 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6813 		ASSERT(MUTEX_HELD(&dtrace_lock));
6814 		self = 1;
6815 
6816 		if (dtrace_provider->dtpv_next != NULL) {
6817 			/*
6818 			 * There's another provider here; return failure.
6819 			 */
6820 			return (EBUSY);
6821 		}
6822 	} else {
6823 		mutex_enter(&dtrace_provider_lock);
6824 		mutex_enter(&mod_lock);
6825 		mutex_enter(&dtrace_lock);
6826 	}
6827 
6828 	/*
6829 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
6830 	 * probes, we refuse to let providers slither away, unless this
6831 	 * provider has already been explicitly invalidated.
6832 	 */
6833 	if (!old->dtpv_defunct &&
6834 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
6835 	    dtrace_anon.dta_state->dts_necbs > 0))) {
6836 		if (!self) {
6837 			mutex_exit(&dtrace_lock);
6838 			mutex_exit(&mod_lock);
6839 			mutex_exit(&dtrace_provider_lock);
6840 		}
6841 		return (EBUSY);
6842 	}
6843 
6844 	/*
6845 	 * Attempt to destroy the probes associated with this provider.
6846 	 */
6847 	for (i = 0; i < dtrace_nprobes; i++) {
6848 		if ((probe = dtrace_probes[i]) == NULL)
6849 			continue;
6850 
6851 		if (probe->dtpr_provider != old)
6852 			continue;
6853 
6854 		if (probe->dtpr_ecb == NULL)
6855 			continue;
6856 
6857 		/*
6858 		 * We have at least one ECB; we can't remove this provider.
6859 		 */
6860 		if (!self) {
6861 			mutex_exit(&dtrace_lock);
6862 			mutex_exit(&mod_lock);
6863 			mutex_exit(&dtrace_provider_lock);
6864 		}
6865 		return (EBUSY);
6866 	}
6867 
6868 	/*
6869 	 * All of the probes for this provider are disabled; we can safely
6870 	 * remove all of them from their hash chains and from the probe array.
6871 	 */
6872 	for (i = 0; i < dtrace_nprobes; i++) {
6873 		if ((probe = dtrace_probes[i]) == NULL)
6874 			continue;
6875 
6876 		if (probe->dtpr_provider != old)
6877 			continue;
6878 
6879 		dtrace_probes[i] = NULL;
6880 
6881 		dtrace_hash_remove(dtrace_bymod, probe);
6882 		dtrace_hash_remove(dtrace_byfunc, probe);
6883 		dtrace_hash_remove(dtrace_byname, probe);
6884 
6885 		if (first == NULL) {
6886 			first = probe;
6887 			probe->dtpr_nextmod = NULL;
6888 		} else {
6889 			probe->dtpr_nextmod = first;
6890 			first = probe;
6891 		}
6892 	}
6893 
6894 	/*
6895 	 * The provider's probes have been removed from the hash chains and
6896 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
6897 	 * everyone has cleared out from any probe array processing.
6898 	 */
6899 	dtrace_sync();
6900 
6901 	for (probe = first; probe != NULL; probe = first) {
6902 		first = probe->dtpr_nextmod;
6903 
6904 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
6905 		    probe->dtpr_arg);
6906 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
6907 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
6908 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
6909 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
6910 		kmem_free(probe, sizeof (dtrace_probe_t));
6911 	}
6912 
6913 	if ((prev = dtrace_provider) == old) {
6914 		ASSERT(self || dtrace_devi == NULL);
6915 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
6916 		dtrace_provider = old->dtpv_next;
6917 	} else {
6918 		while (prev != NULL && prev->dtpv_next != old)
6919 			prev = prev->dtpv_next;
6920 
6921 		if (prev == NULL) {
6922 			panic("attempt to unregister non-existent "
6923 			    "dtrace provider %p\n", (void *)id);
6924 		}
6925 
6926 		prev->dtpv_next = old->dtpv_next;
6927 	}
6928 
6929 	if (!self) {
6930 		mutex_exit(&dtrace_lock);
6931 		mutex_exit(&mod_lock);
6932 		mutex_exit(&dtrace_provider_lock);
6933 	}
6934 
6935 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
6936 	kmem_free(old, sizeof (dtrace_provider_t));
6937 
6938 	return (0);
6939 }
6940 
6941 /*
6942  * Invalidate the specified provider.  All subsequent probe lookups for the
6943  * specified provider will fail, but its probes will not be removed.
6944  */
6945 void
6946 dtrace_invalidate(dtrace_provider_id_t id)
6947 {
6948 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
6949 
6950 	ASSERT(pvp->dtpv_pops.dtps_enable !=
6951 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6952 
6953 	mutex_enter(&dtrace_provider_lock);
6954 	mutex_enter(&dtrace_lock);
6955 
6956 	pvp->dtpv_defunct = 1;
6957 
6958 	mutex_exit(&dtrace_lock);
6959 	mutex_exit(&dtrace_provider_lock);
6960 }
6961 
6962 /*
6963  * Indicate whether or not DTrace has attached.
6964  */
6965 int
6966 dtrace_attached(void)
6967 {
6968 	/*
6969 	 * dtrace_provider will be non-NULL iff the DTrace driver has
6970 	 * attached.  (It's non-NULL because DTrace is always itself a
6971 	 * provider.)
6972 	 */
6973 	return (dtrace_provider != NULL);
6974 }
6975 
6976 /*
6977  * Remove all the unenabled probes for the given provider.  This function is
6978  * not unlike dtrace_unregister(), except that it doesn't remove the provider
6979  * -- just as many of its associated probes as it can.
6980  */
6981 int
6982 dtrace_condense(dtrace_provider_id_t id)
6983 {
6984 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
6985 	int i;
6986 	dtrace_probe_t *probe;
6987 
6988 	/*
6989 	 * Make sure this isn't the dtrace provider itself.
6990 	 */
6991 	ASSERT(prov->dtpv_pops.dtps_enable !=
6992 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6993 
6994 	mutex_enter(&dtrace_provider_lock);
6995 	mutex_enter(&dtrace_lock);
6996 
6997 	/*
6998 	 * Attempt to destroy the probes associated with this provider.
6999 	 */
7000 	for (i = 0; i < dtrace_nprobes; i++) {
7001 		if ((probe = dtrace_probes[i]) == NULL)
7002 			continue;
7003 
7004 		if (probe->dtpr_provider != prov)
7005 			continue;
7006 
7007 		if (probe->dtpr_ecb != NULL)
7008 			continue;
7009 
7010 		dtrace_probes[i] = NULL;
7011 
7012 		dtrace_hash_remove(dtrace_bymod, probe);
7013 		dtrace_hash_remove(dtrace_byfunc, probe);
7014 		dtrace_hash_remove(dtrace_byname, probe);
7015 
7016 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7017 		    probe->dtpr_arg);
7018 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7019 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7020 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7021 		kmem_free(probe, sizeof (dtrace_probe_t));
7022 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7023 	}
7024 
7025 	mutex_exit(&dtrace_lock);
7026 	mutex_exit(&dtrace_provider_lock);
7027 
7028 	return (0);
7029 }
7030 
7031 /*
7032  * DTrace Probe Management Functions
7033  *
7034  * The functions in this section perform the DTrace probe management,
7035  * including functions to create probes, look-up probes, and call into the
7036  * providers to request that probes be provided.  Some of these functions are
7037  * in the Provider-to-Framework API; these functions can be identified by the
7038  * fact that they are not declared "static".
7039  */
7040 
7041 /*
7042  * Create a probe with the specified module name, function name, and name.
7043  */
7044 dtrace_id_t
7045 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7046     const char *func, const char *name, int aframes, void *arg)
7047 {
7048 	dtrace_probe_t *probe, **probes;
7049 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7050 	dtrace_id_t id;
7051 
7052 	if (provider == dtrace_provider) {
7053 		ASSERT(MUTEX_HELD(&dtrace_lock));
7054 	} else {
7055 		mutex_enter(&dtrace_lock);
7056 	}
7057 
7058 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7059 	    VM_BESTFIT | VM_SLEEP);
7060 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
7061 
7062 	probe->dtpr_id = id;
7063 	probe->dtpr_gen = dtrace_probegen++;
7064 	probe->dtpr_mod = dtrace_strdup(mod);
7065 	probe->dtpr_func = dtrace_strdup(func);
7066 	probe->dtpr_name = dtrace_strdup(name);
7067 	probe->dtpr_arg = arg;
7068 	probe->dtpr_aframes = aframes;
7069 	probe->dtpr_provider = provider;
7070 
7071 	dtrace_hash_add(dtrace_bymod, probe);
7072 	dtrace_hash_add(dtrace_byfunc, probe);
7073 	dtrace_hash_add(dtrace_byname, probe);
7074 
7075 	if (id - 1 >= dtrace_nprobes) {
7076 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7077 		size_t nsize = osize << 1;
7078 
7079 		if (nsize == 0) {
7080 			ASSERT(osize == 0);
7081 			ASSERT(dtrace_probes == NULL);
7082 			nsize = sizeof (dtrace_probe_t *);
7083 		}
7084 
7085 		probes = kmem_zalloc(nsize, KM_SLEEP);
7086 
7087 		if (dtrace_probes == NULL) {
7088 			ASSERT(osize == 0);
7089 			dtrace_probes = probes;
7090 			dtrace_nprobes = 1;
7091 		} else {
7092 			dtrace_probe_t **oprobes = dtrace_probes;
7093 
7094 			bcopy(oprobes, probes, osize);
7095 			dtrace_membar_producer();
7096 			dtrace_probes = probes;
7097 
7098 			dtrace_sync();
7099 
7100 			/*
7101 			 * All CPUs are now seeing the new probes array; we can
7102 			 * safely free the old array.
7103 			 */
7104 			kmem_free(oprobes, osize);
7105 			dtrace_nprobes <<= 1;
7106 		}
7107 
7108 		ASSERT(id - 1 < dtrace_nprobes);
7109 	}
7110 
7111 	ASSERT(dtrace_probes[id - 1] == NULL);
7112 	dtrace_probes[id - 1] = probe;
7113 
7114 	if (provider != dtrace_provider)
7115 		mutex_exit(&dtrace_lock);
7116 
7117 	return (id);
7118 }
7119 
7120 static dtrace_probe_t *
7121 dtrace_probe_lookup_id(dtrace_id_t id)
7122 {
7123 	ASSERT(MUTEX_HELD(&dtrace_lock));
7124 
7125 	if (id == 0 || id > dtrace_nprobes)
7126 		return (NULL);
7127 
7128 	return (dtrace_probes[id - 1]);
7129 }
7130 
7131 static int
7132 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
7133 {
7134 	*((dtrace_id_t *)arg) = probe->dtpr_id;
7135 
7136 	return (DTRACE_MATCH_DONE);
7137 }
7138 
7139 /*
7140  * Look up a probe based on provider and one or more of module name, function
7141  * name and probe name.
7142  */
7143 dtrace_id_t
7144 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
7145     const char *func, const char *name)
7146 {
7147 	dtrace_probekey_t pkey;
7148 	dtrace_id_t id;
7149 	int match;
7150 
7151 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
7152 	pkey.dtpk_pmatch = &dtrace_match_string;
7153 	pkey.dtpk_mod = mod;
7154 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
7155 	pkey.dtpk_func = func;
7156 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
7157 	pkey.dtpk_name = name;
7158 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
7159 	pkey.dtpk_id = DTRACE_IDNONE;
7160 
7161 	mutex_enter(&dtrace_lock);
7162 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
7163 	    dtrace_probe_lookup_match, &id);
7164 	mutex_exit(&dtrace_lock);
7165 
7166 	ASSERT(match == 1 || match == 0);
7167 	return (match ? id : 0);
7168 }
7169 
7170 /*
7171  * Returns the probe argument associated with the specified probe.
7172  */
7173 void *
7174 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
7175 {
7176 	dtrace_probe_t *probe;
7177 	void *rval = NULL;
7178 
7179 	mutex_enter(&dtrace_lock);
7180 
7181 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
7182 	    probe->dtpr_provider == (dtrace_provider_t *)id)
7183 		rval = probe->dtpr_arg;
7184 
7185 	mutex_exit(&dtrace_lock);
7186 
7187 	return (rval);
7188 }
7189 
7190 /*
7191  * Copy a probe into a probe description.
7192  */
7193 static void
7194 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
7195 {
7196 	bzero(pdp, sizeof (dtrace_probedesc_t));
7197 	pdp->dtpd_id = prp->dtpr_id;
7198 
7199 	(void) strncpy(pdp->dtpd_provider,
7200 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
7201 
7202 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
7203 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
7204 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
7205 }
7206 
7207 /*
7208  * Called to indicate that a probe -- or probes -- should be provided by a
7209  * specfied provider.  If the specified description is NULL, the provider will
7210  * be told to provide all of its probes.  (This is done whenever a new
7211  * consumer comes along, or whenever a retained enabling is to be matched.) If
7212  * the specified description is non-NULL, the provider is given the
7213  * opportunity to dynamically provide the specified probe, allowing providers
7214  * to support the creation of probes on-the-fly.  (So-called _autocreated_
7215  * probes.)  If the provider is NULL, the operations will be applied to all
7216  * providers; if the provider is non-NULL the operations will only be applied
7217  * to the specified provider.  The dtrace_provider_lock must be held, and the
7218  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
7219  * will need to grab the dtrace_lock when it reenters the framework through
7220  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
7221  */
7222 static void
7223 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
7224 {
7225 	struct modctl *ctl;
7226 	int all = 0;
7227 
7228 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7229 
7230 	if (prv == NULL) {
7231 		all = 1;
7232 		prv = dtrace_provider;
7233 	}
7234 
7235 	do {
7236 		/*
7237 		 * First, call the blanket provide operation.
7238 		 */
7239 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
7240 
7241 		/*
7242 		 * Now call the per-module provide operation.  We will grab
7243 		 * mod_lock to prevent the list from being modified.  Note
7244 		 * that this also prevents the mod_busy bits from changing.
7245 		 * (mod_busy can only be changed with mod_lock held.)
7246 		 */
7247 		mutex_enter(&mod_lock);
7248 
7249 		ctl = &modules;
7250 		do {
7251 			if (ctl->mod_busy || ctl->mod_mp == NULL)
7252 				continue;
7253 
7254 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
7255 
7256 		} while ((ctl = ctl->mod_next) != &modules);
7257 
7258 		mutex_exit(&mod_lock);
7259 	} while (all && (prv = prv->dtpv_next) != NULL);
7260 }
7261 
7262 /*
7263  * Iterate over each probe, and call the Framework-to-Provider API function
7264  * denoted by offs.
7265  */
7266 static void
7267 dtrace_probe_foreach(uintptr_t offs)
7268 {
7269 	dtrace_provider_t *prov;
7270 	void (*func)(void *, dtrace_id_t, void *);
7271 	dtrace_probe_t *probe;
7272 	dtrace_icookie_t cookie;
7273 	int i;
7274 
7275 	/*
7276 	 * We disable interrupts to walk through the probe array.  This is
7277 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
7278 	 * won't see stale data.
7279 	 */
7280 	cookie = dtrace_interrupt_disable();
7281 
7282 	for (i = 0; i < dtrace_nprobes; i++) {
7283 		if ((probe = dtrace_probes[i]) == NULL)
7284 			continue;
7285 
7286 		if (probe->dtpr_ecb == NULL) {
7287 			/*
7288 			 * This probe isn't enabled -- don't call the function.
7289 			 */
7290 			continue;
7291 		}
7292 
7293 		prov = probe->dtpr_provider;
7294 		func = *((void(**)(void *, dtrace_id_t, void *))
7295 		    ((uintptr_t)&prov->dtpv_pops + offs));
7296 
7297 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
7298 	}
7299 
7300 	dtrace_interrupt_enable(cookie);
7301 }
7302 
7303 static int
7304 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
7305 {
7306 	dtrace_probekey_t pkey;
7307 	uint32_t priv;
7308 	uid_t uid;
7309 	zoneid_t zoneid;
7310 
7311 	ASSERT(MUTEX_HELD(&dtrace_lock));
7312 	dtrace_ecb_create_cache = NULL;
7313 
7314 	if (desc == NULL) {
7315 		/*
7316 		 * If we're passed a NULL description, we're being asked to
7317 		 * create an ECB with a NULL probe.
7318 		 */
7319 		(void) dtrace_ecb_create_enable(NULL, enab);
7320 		return (0);
7321 	}
7322 
7323 	dtrace_probekey(desc, &pkey);
7324 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
7325 	    &priv, &uid, &zoneid);
7326 
7327 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
7328 	    enab));
7329 }
7330 
7331 /*
7332  * DTrace Helper Provider Functions
7333  */
7334 static void
7335 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
7336 {
7337 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
7338 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
7339 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
7340 }
7341 
7342 static void
7343 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
7344     const dof_provider_t *dofprov, char *strtab)
7345 {
7346 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
7347 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
7348 	    dofprov->dofpv_provattr);
7349 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
7350 	    dofprov->dofpv_modattr);
7351 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
7352 	    dofprov->dofpv_funcattr);
7353 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
7354 	    dofprov->dofpv_nameattr);
7355 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
7356 	    dofprov->dofpv_argsattr);
7357 }
7358 
7359 static void
7360 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7361 {
7362 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7363 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7364 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
7365 	dof_provider_t *provider;
7366 	dof_probe_t *probe;
7367 	uint32_t *off, *enoff;
7368 	uint8_t *arg;
7369 	char *strtab;
7370 	uint_t i, nprobes;
7371 	dtrace_helper_provdesc_t dhpv;
7372 	dtrace_helper_probedesc_t dhpb;
7373 	dtrace_meta_t *meta = dtrace_meta_pid;
7374 	dtrace_mops_t *mops = &meta->dtm_mops;
7375 	void *parg;
7376 
7377 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7378 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7379 	    provider->dofpv_strtab * dof->dofh_secsize);
7380 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7381 	    provider->dofpv_probes * dof->dofh_secsize);
7382 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7383 	    provider->dofpv_prargs * dof->dofh_secsize);
7384 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7385 	    provider->dofpv_proffs * dof->dofh_secsize);
7386 
7387 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7388 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
7389 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
7390 	enoff = NULL;
7391 
7392 	/*
7393 	 * See dtrace_helper_provider_validate().
7394 	 */
7395 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
7396 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
7397 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7398 		    provider->dofpv_prenoffs * dof->dofh_secsize);
7399 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
7400 	}
7401 
7402 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
7403 
7404 	/*
7405 	 * Create the provider.
7406 	 */
7407 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7408 
7409 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
7410 		return;
7411 
7412 	meta->dtm_count++;
7413 
7414 	/*
7415 	 * Create the probes.
7416 	 */
7417 	for (i = 0; i < nprobes; i++) {
7418 		probe = (dof_probe_t *)(uintptr_t)(daddr +
7419 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
7420 
7421 		dhpb.dthpb_mod = dhp->dofhp_mod;
7422 		dhpb.dthpb_func = strtab + probe->dofpr_func;
7423 		dhpb.dthpb_name = strtab + probe->dofpr_name;
7424 		dhpb.dthpb_base = probe->dofpr_addr;
7425 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
7426 		dhpb.dthpb_noffs = probe->dofpr_noffs;
7427 		if (enoff != NULL) {
7428 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
7429 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
7430 		} else {
7431 			dhpb.dthpb_enoffs = NULL;
7432 			dhpb.dthpb_nenoffs = 0;
7433 		}
7434 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
7435 		dhpb.dthpb_nargc = probe->dofpr_nargc;
7436 		dhpb.dthpb_xargc = probe->dofpr_xargc;
7437 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
7438 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
7439 
7440 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
7441 	}
7442 }
7443 
7444 static void
7445 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
7446 {
7447 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7448 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7449 	int i;
7450 
7451 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7452 
7453 	for (i = 0; i < dof->dofh_secnum; i++) {
7454 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7455 		    dof->dofh_secoff + i * dof->dofh_secsize);
7456 
7457 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7458 			continue;
7459 
7460 		dtrace_helper_provide_one(dhp, sec, pid);
7461 	}
7462 
7463 	/*
7464 	 * We may have just created probes, so we must now rematch against
7465 	 * any retained enablings.  Note that this call will acquire both
7466 	 * cpu_lock and dtrace_lock; the fact that we are holding
7467 	 * dtrace_meta_lock now is what defines the ordering with respect to
7468 	 * these three locks.
7469 	 */
7470 	dtrace_enabling_matchall();
7471 }
7472 
7473 static void
7474 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7475 {
7476 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7477 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7478 	dof_sec_t *str_sec;
7479 	dof_provider_t *provider;
7480 	char *strtab;
7481 	dtrace_helper_provdesc_t dhpv;
7482 	dtrace_meta_t *meta = dtrace_meta_pid;
7483 	dtrace_mops_t *mops = &meta->dtm_mops;
7484 
7485 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7486 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7487 	    provider->dofpv_strtab * dof->dofh_secsize);
7488 
7489 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7490 
7491 	/*
7492 	 * Create the provider.
7493 	 */
7494 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7495 
7496 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
7497 
7498 	meta->dtm_count--;
7499 }
7500 
7501 static void
7502 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
7503 {
7504 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7505 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7506 	int i;
7507 
7508 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7509 
7510 	for (i = 0; i < dof->dofh_secnum; i++) {
7511 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7512 		    dof->dofh_secoff + i * dof->dofh_secsize);
7513 
7514 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7515 			continue;
7516 
7517 		dtrace_helper_provider_remove_one(dhp, sec, pid);
7518 	}
7519 }
7520 
7521 /*
7522  * DTrace Meta Provider-to-Framework API Functions
7523  *
7524  * These functions implement the Meta Provider-to-Framework API, as described
7525  * in <sys/dtrace.h>.
7526  */
7527 int
7528 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
7529     dtrace_meta_provider_id_t *idp)
7530 {
7531 	dtrace_meta_t *meta;
7532 	dtrace_helpers_t *help, *next;
7533 	int i;
7534 
7535 	*idp = DTRACE_METAPROVNONE;
7536 
7537 	/*
7538 	 * We strictly don't need the name, but we hold onto it for
7539 	 * debuggability. All hail error queues!
7540 	 */
7541 	if (name == NULL) {
7542 		cmn_err(CE_WARN, "failed to register meta-provider: "
7543 		    "invalid name");
7544 		return (EINVAL);
7545 	}
7546 
7547 	if (mops == NULL ||
7548 	    mops->dtms_create_probe == NULL ||
7549 	    mops->dtms_provide_pid == NULL ||
7550 	    mops->dtms_remove_pid == NULL) {
7551 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7552 		    "invalid ops", name);
7553 		return (EINVAL);
7554 	}
7555 
7556 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
7557 	meta->dtm_mops = *mops;
7558 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7559 	(void) strcpy(meta->dtm_name, name);
7560 	meta->dtm_arg = arg;
7561 
7562 	mutex_enter(&dtrace_meta_lock);
7563 	mutex_enter(&dtrace_lock);
7564 
7565 	if (dtrace_meta_pid != NULL) {
7566 		mutex_exit(&dtrace_lock);
7567 		mutex_exit(&dtrace_meta_lock);
7568 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7569 		    "user-land meta-provider exists", name);
7570 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
7571 		kmem_free(meta, sizeof (dtrace_meta_t));
7572 		return (EINVAL);
7573 	}
7574 
7575 	dtrace_meta_pid = meta;
7576 	*idp = (dtrace_meta_provider_id_t)meta;
7577 
7578 	/*
7579 	 * If there are providers and probes ready to go, pass them
7580 	 * off to the new meta provider now.
7581 	 */
7582 
7583 	help = dtrace_deferred_pid;
7584 	dtrace_deferred_pid = NULL;
7585 
7586 	mutex_exit(&dtrace_lock);
7587 
7588 	while (help != NULL) {
7589 		for (i = 0; i < help->dthps_nprovs; i++) {
7590 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
7591 			    help->dthps_pid);
7592 		}
7593 
7594 		next = help->dthps_next;
7595 		help->dthps_next = NULL;
7596 		help->dthps_prev = NULL;
7597 		help->dthps_deferred = 0;
7598 		help = next;
7599 	}
7600 
7601 	mutex_exit(&dtrace_meta_lock);
7602 
7603 	return (0);
7604 }
7605 
7606 int
7607 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
7608 {
7609 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
7610 
7611 	mutex_enter(&dtrace_meta_lock);
7612 	mutex_enter(&dtrace_lock);
7613 
7614 	if (old == dtrace_meta_pid) {
7615 		pp = &dtrace_meta_pid;
7616 	} else {
7617 		panic("attempt to unregister non-existent "
7618 		    "dtrace meta-provider %p\n", (void *)old);
7619 	}
7620 
7621 	if (old->dtm_count != 0) {
7622 		mutex_exit(&dtrace_lock);
7623 		mutex_exit(&dtrace_meta_lock);
7624 		return (EBUSY);
7625 	}
7626 
7627 	*pp = NULL;
7628 
7629 	mutex_exit(&dtrace_lock);
7630 	mutex_exit(&dtrace_meta_lock);
7631 
7632 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
7633 	kmem_free(old, sizeof (dtrace_meta_t));
7634 
7635 	return (0);
7636 }
7637 
7638 
7639 /*
7640  * DTrace DIF Object Functions
7641  */
7642 static int
7643 dtrace_difo_err(uint_t pc, const char *format, ...)
7644 {
7645 	if (dtrace_err_verbose) {
7646 		va_list alist;
7647 
7648 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
7649 		va_start(alist, format);
7650 		(void) vuprintf(format, alist);
7651 		va_end(alist);
7652 	}
7653 
7654 #ifdef DTRACE_ERRDEBUG
7655 	dtrace_errdebug(format);
7656 #endif
7657 	return (1);
7658 }
7659 
7660 /*
7661  * Validate a DTrace DIF object by checking the IR instructions.  The following
7662  * rules are currently enforced by dtrace_difo_validate():
7663  *
7664  * 1. Each instruction must have a valid opcode
7665  * 2. Each register, string, variable, or subroutine reference must be valid
7666  * 3. No instruction can modify register %r0 (must be zero)
7667  * 4. All instruction reserved bits must be set to zero
7668  * 5. The last instruction must be a "ret" instruction
7669  * 6. All branch targets must reference a valid instruction _after_ the branch
7670  */
7671 static int
7672 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
7673     cred_t *cr)
7674 {
7675 	int err = 0, i;
7676 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
7677 	int kcheckload;
7678 	uint_t pc;
7679 
7680 	kcheckload = cr == NULL ||
7681 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
7682 
7683 	dp->dtdo_destructive = 0;
7684 
7685 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
7686 		dif_instr_t instr = dp->dtdo_buf[pc];
7687 
7688 		uint_t r1 = DIF_INSTR_R1(instr);
7689 		uint_t r2 = DIF_INSTR_R2(instr);
7690 		uint_t rd = DIF_INSTR_RD(instr);
7691 		uint_t rs = DIF_INSTR_RS(instr);
7692 		uint_t label = DIF_INSTR_LABEL(instr);
7693 		uint_t v = DIF_INSTR_VAR(instr);
7694 		uint_t subr = DIF_INSTR_SUBR(instr);
7695 		uint_t type = DIF_INSTR_TYPE(instr);
7696 		uint_t op = DIF_INSTR_OP(instr);
7697 
7698 		switch (op) {
7699 		case DIF_OP_OR:
7700 		case DIF_OP_XOR:
7701 		case DIF_OP_AND:
7702 		case DIF_OP_SLL:
7703 		case DIF_OP_SRL:
7704 		case DIF_OP_SRA:
7705 		case DIF_OP_SUB:
7706 		case DIF_OP_ADD:
7707 		case DIF_OP_MUL:
7708 		case DIF_OP_SDIV:
7709 		case DIF_OP_UDIV:
7710 		case DIF_OP_SREM:
7711 		case DIF_OP_UREM:
7712 		case DIF_OP_COPYS:
7713 			if (r1 >= nregs)
7714 				err += efunc(pc, "invalid register %u\n", r1);
7715 			if (r2 >= nregs)
7716 				err += efunc(pc, "invalid register %u\n", r2);
7717 			if (rd >= nregs)
7718 				err += efunc(pc, "invalid register %u\n", rd);
7719 			if (rd == 0)
7720 				err += efunc(pc, "cannot write to %r0\n");
7721 			break;
7722 		case DIF_OP_NOT:
7723 		case DIF_OP_MOV:
7724 		case DIF_OP_ALLOCS:
7725 			if (r1 >= nregs)
7726 				err += efunc(pc, "invalid register %u\n", r1);
7727 			if (r2 != 0)
7728 				err += efunc(pc, "non-zero reserved bits\n");
7729 			if (rd >= nregs)
7730 				err += efunc(pc, "invalid register %u\n", rd);
7731 			if (rd == 0)
7732 				err += efunc(pc, "cannot write to %r0\n");
7733 			break;
7734 		case DIF_OP_LDSB:
7735 		case DIF_OP_LDSH:
7736 		case DIF_OP_LDSW:
7737 		case DIF_OP_LDUB:
7738 		case DIF_OP_LDUH:
7739 		case DIF_OP_LDUW:
7740 		case DIF_OP_LDX:
7741 			if (r1 >= nregs)
7742 				err += efunc(pc, "invalid register %u\n", r1);
7743 			if (r2 != 0)
7744 				err += efunc(pc, "non-zero reserved bits\n");
7745 			if (rd >= nregs)
7746 				err += efunc(pc, "invalid register %u\n", rd);
7747 			if (rd == 0)
7748 				err += efunc(pc, "cannot write to %r0\n");
7749 			if (kcheckload)
7750 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
7751 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
7752 			break;
7753 		case DIF_OP_RLDSB:
7754 		case DIF_OP_RLDSH:
7755 		case DIF_OP_RLDSW:
7756 		case DIF_OP_RLDUB:
7757 		case DIF_OP_RLDUH:
7758 		case DIF_OP_RLDUW:
7759 		case DIF_OP_RLDX:
7760 			if (r1 >= nregs)
7761 				err += efunc(pc, "invalid register %u\n", r1);
7762 			if (r2 != 0)
7763 				err += efunc(pc, "non-zero reserved bits\n");
7764 			if (rd >= nregs)
7765 				err += efunc(pc, "invalid register %u\n", rd);
7766 			if (rd == 0)
7767 				err += efunc(pc, "cannot write to %r0\n");
7768 			break;
7769 		case DIF_OP_ULDSB:
7770 		case DIF_OP_ULDSH:
7771 		case DIF_OP_ULDSW:
7772 		case DIF_OP_ULDUB:
7773 		case DIF_OP_ULDUH:
7774 		case DIF_OP_ULDUW:
7775 		case DIF_OP_ULDX:
7776 			if (r1 >= nregs)
7777 				err += efunc(pc, "invalid register %u\n", r1);
7778 			if (r2 != 0)
7779 				err += efunc(pc, "non-zero reserved bits\n");
7780 			if (rd >= nregs)
7781 				err += efunc(pc, "invalid register %u\n", rd);
7782 			if (rd == 0)
7783 				err += efunc(pc, "cannot write to %r0\n");
7784 			break;
7785 		case DIF_OP_STB:
7786 		case DIF_OP_STH:
7787 		case DIF_OP_STW:
7788 		case DIF_OP_STX:
7789 			if (r1 >= nregs)
7790 				err += efunc(pc, "invalid register %u\n", r1);
7791 			if (r2 != 0)
7792 				err += efunc(pc, "non-zero reserved bits\n");
7793 			if (rd >= nregs)
7794 				err += efunc(pc, "invalid register %u\n", rd);
7795 			if (rd == 0)
7796 				err += efunc(pc, "cannot write to 0 address\n");
7797 			break;
7798 		case DIF_OP_CMP:
7799 		case DIF_OP_SCMP:
7800 			if (r1 >= nregs)
7801 				err += efunc(pc, "invalid register %u\n", r1);
7802 			if (r2 >= nregs)
7803 				err += efunc(pc, "invalid register %u\n", r2);
7804 			if (rd != 0)
7805 				err += efunc(pc, "non-zero reserved bits\n");
7806 			break;
7807 		case DIF_OP_TST:
7808 			if (r1 >= nregs)
7809 				err += efunc(pc, "invalid register %u\n", r1);
7810 			if (r2 != 0 || rd != 0)
7811 				err += efunc(pc, "non-zero reserved bits\n");
7812 			break;
7813 		case DIF_OP_BA:
7814 		case DIF_OP_BE:
7815 		case DIF_OP_BNE:
7816 		case DIF_OP_BG:
7817 		case DIF_OP_BGU:
7818 		case DIF_OP_BGE:
7819 		case DIF_OP_BGEU:
7820 		case DIF_OP_BL:
7821 		case DIF_OP_BLU:
7822 		case DIF_OP_BLE:
7823 		case DIF_OP_BLEU:
7824 			if (label >= dp->dtdo_len) {
7825 				err += efunc(pc, "invalid branch target %u\n",
7826 				    label);
7827 			}
7828 			if (label <= pc) {
7829 				err += efunc(pc, "backward branch to %u\n",
7830 				    label);
7831 			}
7832 			break;
7833 		case DIF_OP_RET:
7834 			if (r1 != 0 || r2 != 0)
7835 				err += efunc(pc, "non-zero reserved bits\n");
7836 			if (rd >= nregs)
7837 				err += efunc(pc, "invalid register %u\n", rd);
7838 			break;
7839 		case DIF_OP_NOP:
7840 		case DIF_OP_POPTS:
7841 		case DIF_OP_FLUSHTS:
7842 			if (r1 != 0 || r2 != 0 || rd != 0)
7843 				err += efunc(pc, "non-zero reserved bits\n");
7844 			break;
7845 		case DIF_OP_SETX:
7846 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
7847 				err += efunc(pc, "invalid integer ref %u\n",
7848 				    DIF_INSTR_INTEGER(instr));
7849 			}
7850 			if (rd >= nregs)
7851 				err += efunc(pc, "invalid register %u\n", rd);
7852 			if (rd == 0)
7853 				err += efunc(pc, "cannot write to %r0\n");
7854 			break;
7855 		case DIF_OP_SETS:
7856 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
7857 				err += efunc(pc, "invalid string ref %u\n",
7858 				    DIF_INSTR_STRING(instr));
7859 			}
7860 			if (rd >= nregs)
7861 				err += efunc(pc, "invalid register %u\n", rd);
7862 			if (rd == 0)
7863 				err += efunc(pc, "cannot write to %r0\n");
7864 			break;
7865 		case DIF_OP_LDGA:
7866 		case DIF_OP_LDTA:
7867 			if (r1 > DIF_VAR_ARRAY_MAX)
7868 				err += efunc(pc, "invalid array %u\n", r1);
7869 			if (r2 >= nregs)
7870 				err += efunc(pc, "invalid register %u\n", r2);
7871 			if (rd >= nregs)
7872 				err += efunc(pc, "invalid register %u\n", rd);
7873 			if (rd == 0)
7874 				err += efunc(pc, "cannot write to %r0\n");
7875 			break;
7876 		case DIF_OP_LDGS:
7877 		case DIF_OP_LDTS:
7878 		case DIF_OP_LDLS:
7879 		case DIF_OP_LDGAA:
7880 		case DIF_OP_LDTAA:
7881 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
7882 				err += efunc(pc, "invalid variable %u\n", v);
7883 			if (rd >= nregs)
7884 				err += efunc(pc, "invalid register %u\n", rd);
7885 			if (rd == 0)
7886 				err += efunc(pc, "cannot write to %r0\n");
7887 			break;
7888 		case DIF_OP_STGS:
7889 		case DIF_OP_STTS:
7890 		case DIF_OP_STLS:
7891 		case DIF_OP_STGAA:
7892 		case DIF_OP_STTAA:
7893 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
7894 				err += efunc(pc, "invalid variable %u\n", v);
7895 			if (rs >= nregs)
7896 				err += efunc(pc, "invalid register %u\n", rd);
7897 			break;
7898 		case DIF_OP_CALL:
7899 			if (subr > DIF_SUBR_MAX)
7900 				err += efunc(pc, "invalid subr %u\n", subr);
7901 			if (rd >= nregs)
7902 				err += efunc(pc, "invalid register %u\n", rd);
7903 			if (rd == 0)
7904 				err += efunc(pc, "cannot write to %r0\n");
7905 
7906 			if (subr == DIF_SUBR_COPYOUT ||
7907 			    subr == DIF_SUBR_COPYOUTSTR) {
7908 				dp->dtdo_destructive = 1;
7909 			}
7910 			break;
7911 		case DIF_OP_PUSHTR:
7912 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
7913 				err += efunc(pc, "invalid ref type %u\n", type);
7914 			if (r2 >= nregs)
7915 				err += efunc(pc, "invalid register %u\n", r2);
7916 			if (rs >= nregs)
7917 				err += efunc(pc, "invalid register %u\n", rs);
7918 			break;
7919 		case DIF_OP_PUSHTV:
7920 			if (type != DIF_TYPE_CTF)
7921 				err += efunc(pc, "invalid val type %u\n", type);
7922 			if (r2 >= nregs)
7923 				err += efunc(pc, "invalid register %u\n", r2);
7924 			if (rs >= nregs)
7925 				err += efunc(pc, "invalid register %u\n", rs);
7926 			break;
7927 		default:
7928 			err += efunc(pc, "invalid opcode %u\n",
7929 			    DIF_INSTR_OP(instr));
7930 		}
7931 	}
7932 
7933 	if (dp->dtdo_len != 0 &&
7934 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
7935 		err += efunc(dp->dtdo_len - 1,
7936 		    "expected 'ret' as last DIF instruction\n");
7937 	}
7938 
7939 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
7940 		/*
7941 		 * If we're not returning by reference, the size must be either
7942 		 * 0 or the size of one of the base types.
7943 		 */
7944 		switch (dp->dtdo_rtype.dtdt_size) {
7945 		case 0:
7946 		case sizeof (uint8_t):
7947 		case sizeof (uint16_t):
7948 		case sizeof (uint32_t):
7949 		case sizeof (uint64_t):
7950 			break;
7951 
7952 		default:
7953 			err += efunc(dp->dtdo_len - 1, "bad return size");
7954 		}
7955 	}
7956 
7957 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
7958 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
7959 		dtrace_diftype_t *vt, *et;
7960 		uint_t id, ndx;
7961 
7962 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
7963 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
7964 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
7965 			err += efunc(i, "unrecognized variable scope %d\n",
7966 			    v->dtdv_scope);
7967 			break;
7968 		}
7969 
7970 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
7971 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
7972 			err += efunc(i, "unrecognized variable type %d\n",
7973 			    v->dtdv_kind);
7974 			break;
7975 		}
7976 
7977 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
7978 			err += efunc(i, "%d exceeds variable id limit\n", id);
7979 			break;
7980 		}
7981 
7982 		if (id < DIF_VAR_OTHER_UBASE)
7983 			continue;
7984 
7985 		/*
7986 		 * For user-defined variables, we need to check that this
7987 		 * definition is identical to any previous definition that we
7988 		 * encountered.
7989 		 */
7990 		ndx = id - DIF_VAR_OTHER_UBASE;
7991 
7992 		switch (v->dtdv_scope) {
7993 		case DIFV_SCOPE_GLOBAL:
7994 			if (ndx < vstate->dtvs_nglobals) {
7995 				dtrace_statvar_t *svar;
7996 
7997 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
7998 					existing = &svar->dtsv_var;
7999 			}
8000 
8001 			break;
8002 
8003 		case DIFV_SCOPE_THREAD:
8004 			if (ndx < vstate->dtvs_ntlocals)
8005 				existing = &vstate->dtvs_tlocals[ndx];
8006 			break;
8007 
8008 		case DIFV_SCOPE_LOCAL:
8009 			if (ndx < vstate->dtvs_nlocals) {
8010 				dtrace_statvar_t *svar;
8011 
8012 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8013 					existing = &svar->dtsv_var;
8014 			}
8015 
8016 			break;
8017 		}
8018 
8019 		vt = &v->dtdv_type;
8020 
8021 		if (vt->dtdt_flags & DIF_TF_BYREF) {
8022 			if (vt->dtdt_size == 0) {
8023 				err += efunc(i, "zero-sized variable\n");
8024 				break;
8025 			}
8026 
8027 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8028 			    vt->dtdt_size > dtrace_global_maxsize) {
8029 				err += efunc(i, "oversized by-ref global\n");
8030 				break;
8031 			}
8032 		}
8033 
8034 		if (existing == NULL || existing->dtdv_id == 0)
8035 			continue;
8036 
8037 		ASSERT(existing->dtdv_id == v->dtdv_id);
8038 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
8039 
8040 		if (existing->dtdv_kind != v->dtdv_kind)
8041 			err += efunc(i, "%d changed variable kind\n", id);
8042 
8043 		et = &existing->dtdv_type;
8044 
8045 		if (vt->dtdt_flags != et->dtdt_flags) {
8046 			err += efunc(i, "%d changed variable type flags\n", id);
8047 			break;
8048 		}
8049 
8050 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8051 			err += efunc(i, "%d changed variable type size\n", id);
8052 			break;
8053 		}
8054 	}
8055 
8056 	return (err);
8057 }
8058 
8059 /*
8060  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
8061  * are much more constrained than normal DIFOs.  Specifically, they may
8062  * not:
8063  *
8064  * 1. Make calls to subroutines other than copyin(), copyinstr() or
8065  *    miscellaneous string routines
8066  * 2. Access DTrace variables other than the args[] array, and the
8067  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8068  * 3. Have thread-local variables.
8069  * 4. Have dynamic variables.
8070  */
8071 static int
8072 dtrace_difo_validate_helper(dtrace_difo_t *dp)
8073 {
8074 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8075 	int err = 0;
8076 	uint_t pc;
8077 
8078 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8079 		dif_instr_t instr = dp->dtdo_buf[pc];
8080 
8081 		uint_t v = DIF_INSTR_VAR(instr);
8082 		uint_t subr = DIF_INSTR_SUBR(instr);
8083 		uint_t op = DIF_INSTR_OP(instr);
8084 
8085 		switch (op) {
8086 		case DIF_OP_OR:
8087 		case DIF_OP_XOR:
8088 		case DIF_OP_AND:
8089 		case DIF_OP_SLL:
8090 		case DIF_OP_SRL:
8091 		case DIF_OP_SRA:
8092 		case DIF_OP_SUB:
8093 		case DIF_OP_ADD:
8094 		case DIF_OP_MUL:
8095 		case DIF_OP_SDIV:
8096 		case DIF_OP_UDIV:
8097 		case DIF_OP_SREM:
8098 		case DIF_OP_UREM:
8099 		case DIF_OP_COPYS:
8100 		case DIF_OP_NOT:
8101 		case DIF_OP_MOV:
8102 		case DIF_OP_RLDSB:
8103 		case DIF_OP_RLDSH:
8104 		case DIF_OP_RLDSW:
8105 		case DIF_OP_RLDUB:
8106 		case DIF_OP_RLDUH:
8107 		case DIF_OP_RLDUW:
8108 		case DIF_OP_RLDX:
8109 		case DIF_OP_ULDSB:
8110 		case DIF_OP_ULDSH:
8111 		case DIF_OP_ULDSW:
8112 		case DIF_OP_ULDUB:
8113 		case DIF_OP_ULDUH:
8114 		case DIF_OP_ULDUW:
8115 		case DIF_OP_ULDX:
8116 		case DIF_OP_STB:
8117 		case DIF_OP_STH:
8118 		case DIF_OP_STW:
8119 		case DIF_OP_STX:
8120 		case DIF_OP_ALLOCS:
8121 		case DIF_OP_CMP:
8122 		case DIF_OP_SCMP:
8123 		case DIF_OP_TST:
8124 		case DIF_OP_BA:
8125 		case DIF_OP_BE:
8126 		case DIF_OP_BNE:
8127 		case DIF_OP_BG:
8128 		case DIF_OP_BGU:
8129 		case DIF_OP_BGE:
8130 		case DIF_OP_BGEU:
8131 		case DIF_OP_BL:
8132 		case DIF_OP_BLU:
8133 		case DIF_OP_BLE:
8134 		case DIF_OP_BLEU:
8135 		case DIF_OP_RET:
8136 		case DIF_OP_NOP:
8137 		case DIF_OP_POPTS:
8138 		case DIF_OP_FLUSHTS:
8139 		case DIF_OP_SETX:
8140 		case DIF_OP_SETS:
8141 		case DIF_OP_LDGA:
8142 		case DIF_OP_LDLS:
8143 		case DIF_OP_STGS:
8144 		case DIF_OP_STLS:
8145 		case DIF_OP_PUSHTR:
8146 		case DIF_OP_PUSHTV:
8147 			break;
8148 
8149 		case DIF_OP_LDGS:
8150 			if (v >= DIF_VAR_OTHER_UBASE)
8151 				break;
8152 
8153 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
8154 				break;
8155 
8156 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
8157 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
8158 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
8159 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
8160 				break;
8161 
8162 			err += efunc(pc, "illegal variable %u\n", v);
8163 			break;
8164 
8165 		case DIF_OP_LDTA:
8166 		case DIF_OP_LDTS:
8167 		case DIF_OP_LDGAA:
8168 		case DIF_OP_LDTAA:
8169 			err += efunc(pc, "illegal dynamic variable load\n");
8170 			break;
8171 
8172 		case DIF_OP_STTS:
8173 		case DIF_OP_STGAA:
8174 		case DIF_OP_STTAA:
8175 			err += efunc(pc, "illegal dynamic variable store\n");
8176 			break;
8177 
8178 		case DIF_OP_CALL:
8179 			if (subr == DIF_SUBR_ALLOCA ||
8180 			    subr == DIF_SUBR_BCOPY ||
8181 			    subr == DIF_SUBR_COPYIN ||
8182 			    subr == DIF_SUBR_COPYINTO ||
8183 			    subr == DIF_SUBR_COPYINSTR ||
8184 			    subr == DIF_SUBR_INDEX ||
8185 			    subr == DIF_SUBR_INET_NTOA ||
8186 			    subr == DIF_SUBR_INET_NTOA6 ||
8187 			    subr == DIF_SUBR_INET_NTOP ||
8188 			    subr == DIF_SUBR_LLTOSTR ||
8189 			    subr == DIF_SUBR_RINDEX ||
8190 			    subr == DIF_SUBR_STRCHR ||
8191 			    subr == DIF_SUBR_STRJOIN ||
8192 			    subr == DIF_SUBR_STRRCHR ||
8193 			    subr == DIF_SUBR_STRSTR ||
8194 			    subr == DIF_SUBR_HTONS ||
8195 			    subr == DIF_SUBR_HTONL ||
8196 			    subr == DIF_SUBR_HTONLL ||
8197 			    subr == DIF_SUBR_NTOHS ||
8198 			    subr == DIF_SUBR_NTOHL ||
8199 			    subr == DIF_SUBR_NTOHLL)
8200 				break;
8201 
8202 			err += efunc(pc, "invalid subr %u\n", subr);
8203 			break;
8204 
8205 		default:
8206 			err += efunc(pc, "invalid opcode %u\n",
8207 			    DIF_INSTR_OP(instr));
8208 		}
8209 	}
8210 
8211 	return (err);
8212 }
8213 
8214 /*
8215  * Returns 1 if the expression in the DIF object can be cached on a per-thread
8216  * basis; 0 if not.
8217  */
8218 static int
8219 dtrace_difo_cacheable(dtrace_difo_t *dp)
8220 {
8221 	int i;
8222 
8223 	if (dp == NULL)
8224 		return (0);
8225 
8226 	for (i = 0; i < dp->dtdo_varlen; i++) {
8227 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8228 
8229 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
8230 			continue;
8231 
8232 		switch (v->dtdv_id) {
8233 		case DIF_VAR_CURTHREAD:
8234 		case DIF_VAR_PID:
8235 		case DIF_VAR_TID:
8236 		case DIF_VAR_EXECNAME:
8237 		case DIF_VAR_ZONENAME:
8238 			break;
8239 
8240 		default:
8241 			return (0);
8242 		}
8243 	}
8244 
8245 	/*
8246 	 * This DIF object may be cacheable.  Now we need to look for any
8247 	 * array loading instructions, any memory loading instructions, or
8248 	 * any stores to thread-local variables.
8249 	 */
8250 	for (i = 0; i < dp->dtdo_len; i++) {
8251 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
8252 
8253 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
8254 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
8255 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
8256 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
8257 			return (0);
8258 	}
8259 
8260 	return (1);
8261 }
8262 
8263 static void
8264 dtrace_difo_hold(dtrace_difo_t *dp)
8265 {
8266 	int i;
8267 
8268 	ASSERT(MUTEX_HELD(&dtrace_lock));
8269 
8270 	dp->dtdo_refcnt++;
8271 	ASSERT(dp->dtdo_refcnt != 0);
8272 
8273 	/*
8274 	 * We need to check this DIF object for references to the variable
8275 	 * DIF_VAR_VTIMESTAMP.
8276 	 */
8277 	for (i = 0; i < dp->dtdo_varlen; i++) {
8278 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8279 
8280 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8281 			continue;
8282 
8283 		if (dtrace_vtime_references++ == 0)
8284 			dtrace_vtime_enable();
8285 	}
8286 }
8287 
8288 /*
8289  * This routine calculates the dynamic variable chunksize for a given DIF
8290  * object.  The calculation is not fool-proof, and can probably be tricked by
8291  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
8292  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
8293  * if a dynamic variable size exceeds the chunksize.
8294  */
8295 static void
8296 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8297 {
8298 	uint64_t sval;
8299 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
8300 	const dif_instr_t *text = dp->dtdo_buf;
8301 	uint_t pc, srd = 0;
8302 	uint_t ttop = 0;
8303 	size_t size, ksize;
8304 	uint_t id, i;
8305 
8306 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8307 		dif_instr_t instr = text[pc];
8308 		uint_t op = DIF_INSTR_OP(instr);
8309 		uint_t rd = DIF_INSTR_RD(instr);
8310 		uint_t r1 = DIF_INSTR_R1(instr);
8311 		uint_t nkeys = 0;
8312 		uchar_t scope;
8313 
8314 		dtrace_key_t *key = tupregs;
8315 
8316 		switch (op) {
8317 		case DIF_OP_SETX:
8318 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
8319 			srd = rd;
8320 			continue;
8321 
8322 		case DIF_OP_STTS:
8323 			key = &tupregs[DIF_DTR_NREGS];
8324 			key[0].dttk_size = 0;
8325 			key[1].dttk_size = 0;
8326 			nkeys = 2;
8327 			scope = DIFV_SCOPE_THREAD;
8328 			break;
8329 
8330 		case DIF_OP_STGAA:
8331 		case DIF_OP_STTAA:
8332 			nkeys = ttop;
8333 
8334 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
8335 				key[nkeys++].dttk_size = 0;
8336 
8337 			key[nkeys++].dttk_size = 0;
8338 
8339 			if (op == DIF_OP_STTAA) {
8340 				scope = DIFV_SCOPE_THREAD;
8341 			} else {
8342 				scope = DIFV_SCOPE_GLOBAL;
8343 			}
8344 
8345 			break;
8346 
8347 		case DIF_OP_PUSHTR:
8348 			if (ttop == DIF_DTR_NREGS)
8349 				return;
8350 
8351 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
8352 				/*
8353 				 * If the register for the size of the "pushtr"
8354 				 * is %r0 (or the value is 0) and the type is
8355 				 * a string, we'll use the system-wide default
8356 				 * string size.
8357 				 */
8358 				tupregs[ttop++].dttk_size =
8359 				    dtrace_strsize_default;
8360 			} else {
8361 				if (srd == 0)
8362 					return;
8363 
8364 				tupregs[ttop++].dttk_size = sval;
8365 			}
8366 
8367 			break;
8368 
8369 		case DIF_OP_PUSHTV:
8370 			if (ttop == DIF_DTR_NREGS)
8371 				return;
8372 
8373 			tupregs[ttop++].dttk_size = 0;
8374 			break;
8375 
8376 		case DIF_OP_FLUSHTS:
8377 			ttop = 0;
8378 			break;
8379 
8380 		case DIF_OP_POPTS:
8381 			if (ttop != 0)
8382 				ttop--;
8383 			break;
8384 		}
8385 
8386 		sval = 0;
8387 		srd = 0;
8388 
8389 		if (nkeys == 0)
8390 			continue;
8391 
8392 		/*
8393 		 * We have a dynamic variable allocation; calculate its size.
8394 		 */
8395 		for (ksize = 0, i = 0; i < nkeys; i++)
8396 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
8397 
8398 		size = sizeof (dtrace_dynvar_t);
8399 		size += sizeof (dtrace_key_t) * (nkeys - 1);
8400 		size += ksize;
8401 
8402 		/*
8403 		 * Now we need to determine the size of the stored data.
8404 		 */
8405 		id = DIF_INSTR_VAR(instr);
8406 
8407 		for (i = 0; i < dp->dtdo_varlen; i++) {
8408 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
8409 
8410 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
8411 				size += v->dtdv_type.dtdt_size;
8412 				break;
8413 			}
8414 		}
8415 
8416 		if (i == dp->dtdo_varlen)
8417 			return;
8418 
8419 		/*
8420 		 * We have the size.  If this is larger than the chunk size
8421 		 * for our dynamic variable state, reset the chunk size.
8422 		 */
8423 		size = P2ROUNDUP(size, sizeof (uint64_t));
8424 
8425 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
8426 			vstate->dtvs_dynvars.dtds_chunksize = size;
8427 	}
8428 }
8429 
8430 static void
8431 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8432 {
8433 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
8434 	uint_t id;
8435 
8436 	ASSERT(MUTEX_HELD(&dtrace_lock));
8437 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
8438 
8439 	for (i = 0; i < dp->dtdo_varlen; i++) {
8440 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8441 		dtrace_statvar_t *svar, ***svarp;
8442 		size_t dsize = 0;
8443 		uint8_t scope = v->dtdv_scope;
8444 		int *np;
8445 
8446 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8447 			continue;
8448 
8449 		id -= DIF_VAR_OTHER_UBASE;
8450 
8451 		switch (scope) {
8452 		case DIFV_SCOPE_THREAD:
8453 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
8454 				dtrace_difv_t *tlocals;
8455 
8456 				if ((ntlocals = (otlocals << 1)) == 0)
8457 					ntlocals = 1;
8458 
8459 				osz = otlocals * sizeof (dtrace_difv_t);
8460 				nsz = ntlocals * sizeof (dtrace_difv_t);
8461 
8462 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
8463 
8464 				if (osz != 0) {
8465 					bcopy(vstate->dtvs_tlocals,
8466 					    tlocals, osz);
8467 					kmem_free(vstate->dtvs_tlocals, osz);
8468 				}
8469 
8470 				vstate->dtvs_tlocals = tlocals;
8471 				vstate->dtvs_ntlocals = ntlocals;
8472 			}
8473 
8474 			vstate->dtvs_tlocals[id] = *v;
8475 			continue;
8476 
8477 		case DIFV_SCOPE_LOCAL:
8478 			np = &vstate->dtvs_nlocals;
8479 			svarp = &vstate->dtvs_locals;
8480 
8481 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8482 				dsize = NCPU * (v->dtdv_type.dtdt_size +
8483 				    sizeof (uint64_t));
8484 			else
8485 				dsize = NCPU * sizeof (uint64_t);
8486 
8487 			break;
8488 
8489 		case DIFV_SCOPE_GLOBAL:
8490 			np = &vstate->dtvs_nglobals;
8491 			svarp = &vstate->dtvs_globals;
8492 
8493 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8494 				dsize = v->dtdv_type.dtdt_size +
8495 				    sizeof (uint64_t);
8496 
8497 			break;
8498 
8499 		default:
8500 			ASSERT(0);
8501 		}
8502 
8503 		while (id >= (oldsvars = *np)) {
8504 			dtrace_statvar_t **statics;
8505 			int newsvars, oldsize, newsize;
8506 
8507 			if ((newsvars = (oldsvars << 1)) == 0)
8508 				newsvars = 1;
8509 
8510 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
8511 			newsize = newsvars * sizeof (dtrace_statvar_t *);
8512 
8513 			statics = kmem_zalloc(newsize, KM_SLEEP);
8514 
8515 			if (oldsize != 0) {
8516 				bcopy(*svarp, statics, oldsize);
8517 				kmem_free(*svarp, oldsize);
8518 			}
8519 
8520 			*svarp = statics;
8521 			*np = newsvars;
8522 		}
8523 
8524 		if ((svar = (*svarp)[id]) == NULL) {
8525 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
8526 			svar->dtsv_var = *v;
8527 
8528 			if ((svar->dtsv_size = dsize) != 0) {
8529 				svar->dtsv_data = (uint64_t)(uintptr_t)
8530 				    kmem_zalloc(dsize, KM_SLEEP);
8531 			}
8532 
8533 			(*svarp)[id] = svar;
8534 		}
8535 
8536 		svar->dtsv_refcnt++;
8537 	}
8538 
8539 	dtrace_difo_chunksize(dp, vstate);
8540 	dtrace_difo_hold(dp);
8541 }
8542 
8543 static dtrace_difo_t *
8544 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8545 {
8546 	dtrace_difo_t *new;
8547 	size_t sz;
8548 
8549 	ASSERT(dp->dtdo_buf != NULL);
8550 	ASSERT(dp->dtdo_refcnt != 0);
8551 
8552 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
8553 
8554 	ASSERT(dp->dtdo_buf != NULL);
8555 	sz = dp->dtdo_len * sizeof (dif_instr_t);
8556 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
8557 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
8558 	new->dtdo_len = dp->dtdo_len;
8559 
8560 	if (dp->dtdo_strtab != NULL) {
8561 		ASSERT(dp->dtdo_strlen != 0);
8562 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
8563 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
8564 		new->dtdo_strlen = dp->dtdo_strlen;
8565 	}
8566 
8567 	if (dp->dtdo_inttab != NULL) {
8568 		ASSERT(dp->dtdo_intlen != 0);
8569 		sz = dp->dtdo_intlen * sizeof (uint64_t);
8570 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
8571 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
8572 		new->dtdo_intlen = dp->dtdo_intlen;
8573 	}
8574 
8575 	if (dp->dtdo_vartab != NULL) {
8576 		ASSERT(dp->dtdo_varlen != 0);
8577 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
8578 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
8579 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
8580 		new->dtdo_varlen = dp->dtdo_varlen;
8581 	}
8582 
8583 	dtrace_difo_init(new, vstate);
8584 	return (new);
8585 }
8586 
8587 static void
8588 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8589 {
8590 	int i;
8591 
8592 	ASSERT(dp->dtdo_refcnt == 0);
8593 
8594 	for (i = 0; i < dp->dtdo_varlen; i++) {
8595 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8596 		dtrace_statvar_t *svar, **svarp;
8597 		uint_t id;
8598 		uint8_t scope = v->dtdv_scope;
8599 		int *np;
8600 
8601 		switch (scope) {
8602 		case DIFV_SCOPE_THREAD:
8603 			continue;
8604 
8605 		case DIFV_SCOPE_LOCAL:
8606 			np = &vstate->dtvs_nlocals;
8607 			svarp = vstate->dtvs_locals;
8608 			break;
8609 
8610 		case DIFV_SCOPE_GLOBAL:
8611 			np = &vstate->dtvs_nglobals;
8612 			svarp = vstate->dtvs_globals;
8613 			break;
8614 
8615 		default:
8616 			ASSERT(0);
8617 		}
8618 
8619 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8620 			continue;
8621 
8622 		id -= DIF_VAR_OTHER_UBASE;
8623 		ASSERT(id < *np);
8624 
8625 		svar = svarp[id];
8626 		ASSERT(svar != NULL);
8627 		ASSERT(svar->dtsv_refcnt > 0);
8628 
8629 		if (--svar->dtsv_refcnt > 0)
8630 			continue;
8631 
8632 		if (svar->dtsv_size != 0) {
8633 			ASSERT(svar->dtsv_data != NULL);
8634 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
8635 			    svar->dtsv_size);
8636 		}
8637 
8638 		kmem_free(svar, sizeof (dtrace_statvar_t));
8639 		svarp[id] = NULL;
8640 	}
8641 
8642 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
8643 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
8644 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
8645 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
8646 
8647 	kmem_free(dp, sizeof (dtrace_difo_t));
8648 }
8649 
8650 static void
8651 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8652 {
8653 	int i;
8654 
8655 	ASSERT(MUTEX_HELD(&dtrace_lock));
8656 	ASSERT(dp->dtdo_refcnt != 0);
8657 
8658 	for (i = 0; i < dp->dtdo_varlen; i++) {
8659 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8660 
8661 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8662 			continue;
8663 
8664 		ASSERT(dtrace_vtime_references > 0);
8665 		if (--dtrace_vtime_references == 0)
8666 			dtrace_vtime_disable();
8667 	}
8668 
8669 	if (--dp->dtdo_refcnt == 0)
8670 		dtrace_difo_destroy(dp, vstate);
8671 }
8672 
8673 /*
8674  * DTrace Format Functions
8675  */
8676 static uint16_t
8677 dtrace_format_add(dtrace_state_t *state, char *str)
8678 {
8679 	char *fmt, **new;
8680 	uint16_t ndx, len = strlen(str) + 1;
8681 
8682 	fmt = kmem_zalloc(len, KM_SLEEP);
8683 	bcopy(str, fmt, len);
8684 
8685 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
8686 		if (state->dts_formats[ndx] == NULL) {
8687 			state->dts_formats[ndx] = fmt;
8688 			return (ndx + 1);
8689 		}
8690 	}
8691 
8692 	if (state->dts_nformats == USHRT_MAX) {
8693 		/*
8694 		 * This is only likely if a denial-of-service attack is being
8695 		 * attempted.  As such, it's okay to fail silently here.
8696 		 */
8697 		kmem_free(fmt, len);
8698 		return (0);
8699 	}
8700 
8701 	/*
8702 	 * For simplicity, we always resize the formats array to be exactly the
8703 	 * number of formats.
8704 	 */
8705 	ndx = state->dts_nformats++;
8706 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
8707 
8708 	if (state->dts_formats != NULL) {
8709 		ASSERT(ndx != 0);
8710 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
8711 		kmem_free(state->dts_formats, ndx * sizeof (char *));
8712 	}
8713 
8714 	state->dts_formats = new;
8715 	state->dts_formats[ndx] = fmt;
8716 
8717 	return (ndx + 1);
8718 }
8719 
8720 static void
8721 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
8722 {
8723 	char *fmt;
8724 
8725 	ASSERT(state->dts_formats != NULL);
8726 	ASSERT(format <= state->dts_nformats);
8727 	ASSERT(state->dts_formats[format - 1] != NULL);
8728 
8729 	fmt = state->dts_formats[format - 1];
8730 	kmem_free(fmt, strlen(fmt) + 1);
8731 	state->dts_formats[format - 1] = NULL;
8732 }
8733 
8734 static void
8735 dtrace_format_destroy(dtrace_state_t *state)
8736 {
8737 	int i;
8738 
8739 	if (state->dts_nformats == 0) {
8740 		ASSERT(state->dts_formats == NULL);
8741 		return;
8742 	}
8743 
8744 	ASSERT(state->dts_formats != NULL);
8745 
8746 	for (i = 0; i < state->dts_nformats; i++) {
8747 		char *fmt = state->dts_formats[i];
8748 
8749 		if (fmt == NULL)
8750 			continue;
8751 
8752 		kmem_free(fmt, strlen(fmt) + 1);
8753 	}
8754 
8755 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
8756 	state->dts_nformats = 0;
8757 	state->dts_formats = NULL;
8758 }
8759 
8760 /*
8761  * DTrace Predicate Functions
8762  */
8763 static dtrace_predicate_t *
8764 dtrace_predicate_create(dtrace_difo_t *dp)
8765 {
8766 	dtrace_predicate_t *pred;
8767 
8768 	ASSERT(MUTEX_HELD(&dtrace_lock));
8769 	ASSERT(dp->dtdo_refcnt != 0);
8770 
8771 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
8772 	pred->dtp_difo = dp;
8773 	pred->dtp_refcnt = 1;
8774 
8775 	if (!dtrace_difo_cacheable(dp))
8776 		return (pred);
8777 
8778 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
8779 		/*
8780 		 * This is only theoretically possible -- we have had 2^32
8781 		 * cacheable predicates on this machine.  We cannot allow any
8782 		 * more predicates to become cacheable:  as unlikely as it is,
8783 		 * there may be a thread caching a (now stale) predicate cache
8784 		 * ID. (N.B.: the temptation is being successfully resisted to
8785 		 * have this cmn_err() "Holy shit -- we executed this code!")
8786 		 */
8787 		return (pred);
8788 	}
8789 
8790 	pred->dtp_cacheid = dtrace_predcache_id++;
8791 
8792 	return (pred);
8793 }
8794 
8795 static void
8796 dtrace_predicate_hold(dtrace_predicate_t *pred)
8797 {
8798 	ASSERT(MUTEX_HELD(&dtrace_lock));
8799 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
8800 	ASSERT(pred->dtp_refcnt > 0);
8801 
8802 	pred->dtp_refcnt++;
8803 }
8804 
8805 static void
8806 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
8807 {
8808 	dtrace_difo_t *dp = pred->dtp_difo;
8809 
8810 	ASSERT(MUTEX_HELD(&dtrace_lock));
8811 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
8812 	ASSERT(pred->dtp_refcnt > 0);
8813 
8814 	if (--pred->dtp_refcnt == 0) {
8815 		dtrace_difo_release(pred->dtp_difo, vstate);
8816 		kmem_free(pred, sizeof (dtrace_predicate_t));
8817 	}
8818 }
8819 
8820 /*
8821  * DTrace Action Description Functions
8822  */
8823 static dtrace_actdesc_t *
8824 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
8825     uint64_t uarg, uint64_t arg)
8826 {
8827 	dtrace_actdesc_t *act;
8828 
8829 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
8830 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
8831 
8832 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
8833 	act->dtad_kind = kind;
8834 	act->dtad_ntuple = ntuple;
8835 	act->dtad_uarg = uarg;
8836 	act->dtad_arg = arg;
8837 	act->dtad_refcnt = 1;
8838 
8839 	return (act);
8840 }
8841 
8842 static void
8843 dtrace_actdesc_hold(dtrace_actdesc_t *act)
8844 {
8845 	ASSERT(act->dtad_refcnt >= 1);
8846 	act->dtad_refcnt++;
8847 }
8848 
8849 static void
8850 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
8851 {
8852 	dtrace_actkind_t kind = act->dtad_kind;
8853 	dtrace_difo_t *dp;
8854 
8855 	ASSERT(act->dtad_refcnt >= 1);
8856 
8857 	if (--act->dtad_refcnt != 0)
8858 		return;
8859 
8860 	if ((dp = act->dtad_difo) != NULL)
8861 		dtrace_difo_release(dp, vstate);
8862 
8863 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
8864 		char *str = (char *)(uintptr_t)act->dtad_arg;
8865 
8866 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
8867 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
8868 
8869 		if (str != NULL)
8870 			kmem_free(str, strlen(str) + 1);
8871 	}
8872 
8873 	kmem_free(act, sizeof (dtrace_actdesc_t));
8874 }
8875 
8876 /*
8877  * DTrace ECB Functions
8878  */
8879 static dtrace_ecb_t *
8880 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
8881 {
8882 	dtrace_ecb_t *ecb;
8883 	dtrace_epid_t epid;
8884 
8885 	ASSERT(MUTEX_HELD(&dtrace_lock));
8886 
8887 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
8888 	ecb->dte_predicate = NULL;
8889 	ecb->dte_probe = probe;
8890 
8891 	/*
8892 	 * The default size is the size of the default action: recording
8893 	 * the epid.
8894 	 */
8895 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
8896 	ecb->dte_alignment = sizeof (dtrace_epid_t);
8897 
8898 	epid = state->dts_epid++;
8899 
8900 	if (epid - 1 >= state->dts_necbs) {
8901 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
8902 		int necbs = state->dts_necbs << 1;
8903 
8904 		ASSERT(epid == state->dts_necbs + 1);
8905 
8906 		if (necbs == 0) {
8907 			ASSERT(oecbs == NULL);
8908 			necbs = 1;
8909 		}
8910 
8911 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
8912 
8913 		if (oecbs != NULL)
8914 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
8915 
8916 		dtrace_membar_producer();
8917 		state->dts_ecbs = ecbs;
8918 
8919 		if (oecbs != NULL) {
8920 			/*
8921 			 * If this state is active, we must dtrace_sync()
8922 			 * before we can free the old dts_ecbs array:  we're
8923 			 * coming in hot, and there may be active ring
8924 			 * buffer processing (which indexes into the dts_ecbs
8925 			 * array) on another CPU.
8926 			 */
8927 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
8928 				dtrace_sync();
8929 
8930 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
8931 		}
8932 
8933 		dtrace_membar_producer();
8934 		state->dts_necbs = necbs;
8935 	}
8936 
8937 	ecb->dte_state = state;
8938 
8939 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
8940 	dtrace_membar_producer();
8941 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
8942 
8943 	return (ecb);
8944 }
8945 
8946 static void
8947 dtrace_ecb_enable(dtrace_ecb_t *ecb)
8948 {
8949 	dtrace_probe_t *probe = ecb->dte_probe;
8950 
8951 	ASSERT(MUTEX_HELD(&cpu_lock));
8952 	ASSERT(MUTEX_HELD(&dtrace_lock));
8953 	ASSERT(ecb->dte_next == NULL);
8954 
8955 	if (probe == NULL) {
8956 		/*
8957 		 * This is the NULL probe -- there's nothing to do.
8958 		 */
8959 		return;
8960 	}
8961 
8962 	if (probe->dtpr_ecb == NULL) {
8963 		dtrace_provider_t *prov = probe->dtpr_provider;
8964 
8965 		/*
8966 		 * We're the first ECB on this probe.
8967 		 */
8968 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
8969 
8970 		if (ecb->dte_predicate != NULL)
8971 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
8972 
8973 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
8974 		    probe->dtpr_id, probe->dtpr_arg);
8975 	} else {
8976 		/*
8977 		 * This probe is already active.  Swing the last pointer to
8978 		 * point to the new ECB, and issue a dtrace_sync() to assure
8979 		 * that all CPUs have seen the change.
8980 		 */
8981 		ASSERT(probe->dtpr_ecb_last != NULL);
8982 		probe->dtpr_ecb_last->dte_next = ecb;
8983 		probe->dtpr_ecb_last = ecb;
8984 		probe->dtpr_predcache = 0;
8985 
8986 		dtrace_sync();
8987 	}
8988 }
8989 
8990 static void
8991 dtrace_ecb_resize(dtrace_ecb_t *ecb)
8992 {
8993 	uint32_t maxalign = sizeof (dtrace_epid_t);
8994 	uint32_t align = sizeof (uint8_t), offs, diff;
8995 	dtrace_action_t *act;
8996 	int wastuple = 0;
8997 	uint32_t aggbase = UINT32_MAX;
8998 	dtrace_state_t *state = ecb->dte_state;
8999 
9000 	/*
9001 	 * If we record anything, we always record the epid.  (And we always
9002 	 * record it first.)
9003 	 */
9004 	offs = sizeof (dtrace_epid_t);
9005 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
9006 
9007 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9008 		dtrace_recdesc_t *rec = &act->dta_rec;
9009 
9010 		if ((align = rec->dtrd_alignment) > maxalign)
9011 			maxalign = align;
9012 
9013 		if (!wastuple && act->dta_intuple) {
9014 			/*
9015 			 * This is the first record in a tuple.  Align the
9016 			 * offset to be at offset 4 in an 8-byte aligned
9017 			 * block.
9018 			 */
9019 			diff = offs + sizeof (dtrace_aggid_t);
9020 
9021 			if (diff = (diff & (sizeof (uint64_t) - 1)))
9022 				offs += sizeof (uint64_t) - diff;
9023 
9024 			aggbase = offs - sizeof (dtrace_aggid_t);
9025 			ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
9026 		}
9027 
9028 		/*LINTED*/
9029 		if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
9030 			/*
9031 			 * The current offset is not properly aligned; align it.
9032 			 */
9033 			offs += align - diff;
9034 		}
9035 
9036 		rec->dtrd_offset = offs;
9037 
9038 		if (offs + rec->dtrd_size > ecb->dte_needed) {
9039 			ecb->dte_needed = offs + rec->dtrd_size;
9040 
9041 			if (ecb->dte_needed > state->dts_needed)
9042 				state->dts_needed = ecb->dte_needed;
9043 		}
9044 
9045 		if (DTRACEACT_ISAGG(act->dta_kind)) {
9046 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9047 			dtrace_action_t *first = agg->dtag_first, *prev;
9048 
9049 			ASSERT(rec->dtrd_size != 0 && first != NULL);
9050 			ASSERT(wastuple);
9051 			ASSERT(aggbase != UINT32_MAX);
9052 
9053 			agg->dtag_base = aggbase;
9054 
9055 			while ((prev = first->dta_prev) != NULL &&
9056 			    DTRACEACT_ISAGG(prev->dta_kind)) {
9057 				agg = (dtrace_aggregation_t *)prev;
9058 				first = agg->dtag_first;
9059 			}
9060 
9061 			if (prev != NULL) {
9062 				offs = prev->dta_rec.dtrd_offset +
9063 				    prev->dta_rec.dtrd_size;
9064 			} else {
9065 				offs = sizeof (dtrace_epid_t);
9066 			}
9067 			wastuple = 0;
9068 		} else {
9069 			if (!act->dta_intuple)
9070 				ecb->dte_size = offs + rec->dtrd_size;
9071 
9072 			offs += rec->dtrd_size;
9073 		}
9074 
9075 		wastuple = act->dta_intuple;
9076 	}
9077 
9078 	if ((act = ecb->dte_action) != NULL &&
9079 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9080 	    ecb->dte_size == sizeof (dtrace_epid_t)) {
9081 		/*
9082 		 * If the size is still sizeof (dtrace_epid_t), then all
9083 		 * actions store no data; set the size to 0.
9084 		 */
9085 		ecb->dte_alignment = maxalign;
9086 		ecb->dte_size = 0;
9087 
9088 		/*
9089 		 * If the needed space is still sizeof (dtrace_epid_t), then
9090 		 * all actions need no additional space; set the needed
9091 		 * size to 0.
9092 		 */
9093 		if (ecb->dte_needed == sizeof (dtrace_epid_t))
9094 			ecb->dte_needed = 0;
9095 
9096 		return;
9097 	}
9098 
9099 	/*
9100 	 * Set our alignment, and make sure that the dte_size and dte_needed
9101 	 * are aligned to the size of an EPID.
9102 	 */
9103 	ecb->dte_alignment = maxalign;
9104 	ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
9105 	    ~(sizeof (dtrace_epid_t) - 1);
9106 	ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
9107 	    ~(sizeof (dtrace_epid_t) - 1);
9108 	ASSERT(ecb->dte_size <= ecb->dte_needed);
9109 }
9110 
9111 static dtrace_action_t *
9112 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9113 {
9114 	dtrace_aggregation_t *agg;
9115 	size_t size = sizeof (uint64_t);
9116 	int ntuple = desc->dtad_ntuple;
9117 	dtrace_action_t *act;
9118 	dtrace_recdesc_t *frec;
9119 	dtrace_aggid_t aggid;
9120 	dtrace_state_t *state = ecb->dte_state;
9121 
9122 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
9123 	agg->dtag_ecb = ecb;
9124 
9125 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
9126 
9127 	switch (desc->dtad_kind) {
9128 	case DTRACEAGG_MIN:
9129 		agg->dtag_initial = UINT64_MAX;
9130 		agg->dtag_aggregate = dtrace_aggregate_min;
9131 		break;
9132 
9133 	case DTRACEAGG_MAX:
9134 		agg->dtag_aggregate = dtrace_aggregate_max;
9135 		break;
9136 
9137 	case DTRACEAGG_COUNT:
9138 		agg->dtag_aggregate = dtrace_aggregate_count;
9139 		break;
9140 
9141 	case DTRACEAGG_QUANTIZE:
9142 		agg->dtag_aggregate = dtrace_aggregate_quantize;
9143 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
9144 		    sizeof (uint64_t);
9145 		break;
9146 
9147 	case DTRACEAGG_LQUANTIZE: {
9148 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
9149 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
9150 
9151 		agg->dtag_initial = desc->dtad_arg;
9152 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
9153 
9154 		if (step == 0 || levels == 0)
9155 			goto err;
9156 
9157 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
9158 		break;
9159 	}
9160 
9161 	case DTRACEAGG_AVG:
9162 		agg->dtag_aggregate = dtrace_aggregate_avg;
9163 		size = sizeof (uint64_t) * 2;
9164 		break;
9165 
9166 	case DTRACEAGG_SUM:
9167 		agg->dtag_aggregate = dtrace_aggregate_sum;
9168 		break;
9169 
9170 	default:
9171 		goto err;
9172 	}
9173 
9174 	agg->dtag_action.dta_rec.dtrd_size = size;
9175 
9176 	if (ntuple == 0)
9177 		goto err;
9178 
9179 	/*
9180 	 * We must make sure that we have enough actions for the n-tuple.
9181 	 */
9182 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
9183 		if (DTRACEACT_ISAGG(act->dta_kind))
9184 			break;
9185 
9186 		if (--ntuple == 0) {
9187 			/*
9188 			 * This is the action with which our n-tuple begins.
9189 			 */
9190 			agg->dtag_first = act;
9191 			goto success;
9192 		}
9193 	}
9194 
9195 	/*
9196 	 * This n-tuple is short by ntuple elements.  Return failure.
9197 	 */
9198 	ASSERT(ntuple != 0);
9199 err:
9200 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9201 	return (NULL);
9202 
9203 success:
9204 	/*
9205 	 * If the last action in the tuple has a size of zero, it's actually
9206 	 * an expression argument for the aggregating action.
9207 	 */
9208 	ASSERT(ecb->dte_action_last != NULL);
9209 	act = ecb->dte_action_last;
9210 
9211 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
9212 		ASSERT(act->dta_difo != NULL);
9213 
9214 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
9215 			agg->dtag_hasarg = 1;
9216 	}
9217 
9218 	/*
9219 	 * We need to allocate an id for this aggregation.
9220 	 */
9221 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
9222 	    VM_BESTFIT | VM_SLEEP);
9223 
9224 	if (aggid - 1 >= state->dts_naggregations) {
9225 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
9226 		dtrace_aggregation_t **aggs;
9227 		int naggs = state->dts_naggregations << 1;
9228 		int onaggs = state->dts_naggregations;
9229 
9230 		ASSERT(aggid == state->dts_naggregations + 1);
9231 
9232 		if (naggs == 0) {
9233 			ASSERT(oaggs == NULL);
9234 			naggs = 1;
9235 		}
9236 
9237 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
9238 
9239 		if (oaggs != NULL) {
9240 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
9241 			kmem_free(oaggs, onaggs * sizeof (*aggs));
9242 		}
9243 
9244 		state->dts_aggregations = aggs;
9245 		state->dts_naggregations = naggs;
9246 	}
9247 
9248 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
9249 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
9250 
9251 	frec = &agg->dtag_first->dta_rec;
9252 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
9253 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
9254 
9255 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
9256 		ASSERT(!act->dta_intuple);
9257 		act->dta_intuple = 1;
9258 	}
9259 
9260 	return (&agg->dtag_action);
9261 }
9262 
9263 static void
9264 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
9265 {
9266 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9267 	dtrace_state_t *state = ecb->dte_state;
9268 	dtrace_aggid_t aggid = agg->dtag_id;
9269 
9270 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
9271 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
9272 
9273 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
9274 	state->dts_aggregations[aggid - 1] = NULL;
9275 
9276 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9277 }
9278 
9279 static int
9280 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9281 {
9282 	dtrace_action_t *action, *last;
9283 	dtrace_difo_t *dp = desc->dtad_difo;
9284 	uint32_t size = 0, align = sizeof (uint8_t), mask;
9285 	uint16_t format = 0;
9286 	dtrace_recdesc_t *rec;
9287 	dtrace_state_t *state = ecb->dte_state;
9288 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
9289 	uint64_t arg = desc->dtad_arg;
9290 
9291 	ASSERT(MUTEX_HELD(&dtrace_lock));
9292 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
9293 
9294 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
9295 		/*
9296 		 * If this is an aggregating action, there must be neither
9297 		 * a speculate nor a commit on the action chain.
9298 		 */
9299 		dtrace_action_t *act;
9300 
9301 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9302 			if (act->dta_kind == DTRACEACT_COMMIT)
9303 				return (EINVAL);
9304 
9305 			if (act->dta_kind == DTRACEACT_SPECULATE)
9306 				return (EINVAL);
9307 		}
9308 
9309 		action = dtrace_ecb_aggregation_create(ecb, desc);
9310 
9311 		if (action == NULL)
9312 			return (EINVAL);
9313 	} else {
9314 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
9315 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
9316 		    dp != NULL && dp->dtdo_destructive)) {
9317 			state->dts_destructive = 1;
9318 		}
9319 
9320 		switch (desc->dtad_kind) {
9321 		case DTRACEACT_PRINTF:
9322 		case DTRACEACT_PRINTA:
9323 		case DTRACEACT_SYSTEM:
9324 		case DTRACEACT_FREOPEN:
9325 			/*
9326 			 * We know that our arg is a string -- turn it into a
9327 			 * format.
9328 			 */
9329 			if (arg == NULL) {
9330 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
9331 				format = 0;
9332 			} else {
9333 				ASSERT(arg != NULL);
9334 				ASSERT(arg > KERNELBASE);
9335 				format = dtrace_format_add(state,
9336 				    (char *)(uintptr_t)arg);
9337 			}
9338 
9339 			/*FALLTHROUGH*/
9340 		case DTRACEACT_LIBACT:
9341 		case DTRACEACT_DIFEXPR:
9342 			if (dp == NULL)
9343 				return (EINVAL);
9344 
9345 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
9346 				break;
9347 
9348 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
9349 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9350 					return (EINVAL);
9351 
9352 				size = opt[DTRACEOPT_STRSIZE];
9353 			}
9354 
9355 			break;
9356 
9357 		case DTRACEACT_STACK:
9358 			if ((nframes = arg) == 0) {
9359 				nframes = opt[DTRACEOPT_STACKFRAMES];
9360 				ASSERT(nframes > 0);
9361 				arg = nframes;
9362 			}
9363 
9364 			size = nframes * sizeof (pc_t);
9365 			break;
9366 
9367 		case DTRACEACT_JSTACK:
9368 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
9369 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
9370 
9371 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
9372 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
9373 
9374 			arg = DTRACE_USTACK_ARG(nframes, strsize);
9375 
9376 			/*FALLTHROUGH*/
9377 		case DTRACEACT_USTACK:
9378 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
9379 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
9380 				strsize = DTRACE_USTACK_STRSIZE(arg);
9381 				nframes = opt[DTRACEOPT_USTACKFRAMES];
9382 				ASSERT(nframes > 0);
9383 				arg = DTRACE_USTACK_ARG(nframes, strsize);
9384 			}
9385 
9386 			/*
9387 			 * Save a slot for the pid.
9388 			 */
9389 			size = (nframes + 1) * sizeof (uint64_t);
9390 			size += DTRACE_USTACK_STRSIZE(arg);
9391 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
9392 
9393 			break;
9394 
9395 		case DTRACEACT_SYM:
9396 		case DTRACEACT_MOD:
9397 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
9398 			    sizeof (uint64_t)) ||
9399 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9400 				return (EINVAL);
9401 			break;
9402 
9403 		case DTRACEACT_USYM:
9404 		case DTRACEACT_UMOD:
9405 		case DTRACEACT_UADDR:
9406 			if (dp == NULL ||
9407 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
9408 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9409 				return (EINVAL);
9410 
9411 			/*
9412 			 * We have a slot for the pid, plus a slot for the
9413 			 * argument.  To keep things simple (aligned with
9414 			 * bitness-neutral sizing), we store each as a 64-bit
9415 			 * quantity.
9416 			 */
9417 			size = 2 * sizeof (uint64_t);
9418 			break;
9419 
9420 		case DTRACEACT_STOP:
9421 		case DTRACEACT_BREAKPOINT:
9422 		case DTRACEACT_PANIC:
9423 			break;
9424 
9425 		case DTRACEACT_CHILL:
9426 		case DTRACEACT_DISCARD:
9427 		case DTRACEACT_RAISE:
9428 			if (dp == NULL)
9429 				return (EINVAL);
9430 			break;
9431 
9432 		case DTRACEACT_EXIT:
9433 			if (dp == NULL ||
9434 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
9435 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9436 				return (EINVAL);
9437 			break;
9438 
9439 		case DTRACEACT_SPECULATE:
9440 			if (ecb->dte_size > sizeof (dtrace_epid_t))
9441 				return (EINVAL);
9442 
9443 			if (dp == NULL)
9444 				return (EINVAL);
9445 
9446 			state->dts_speculates = 1;
9447 			break;
9448 
9449 		case DTRACEACT_COMMIT: {
9450 			dtrace_action_t *act = ecb->dte_action;
9451 
9452 			for (; act != NULL; act = act->dta_next) {
9453 				if (act->dta_kind == DTRACEACT_COMMIT)
9454 					return (EINVAL);
9455 			}
9456 
9457 			if (dp == NULL)
9458 				return (EINVAL);
9459 			break;
9460 		}
9461 
9462 		default:
9463 			return (EINVAL);
9464 		}
9465 
9466 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
9467 			/*
9468 			 * If this is a data-storing action or a speculate,
9469 			 * we must be sure that there isn't a commit on the
9470 			 * action chain.
9471 			 */
9472 			dtrace_action_t *act = ecb->dte_action;
9473 
9474 			for (; act != NULL; act = act->dta_next) {
9475 				if (act->dta_kind == DTRACEACT_COMMIT)
9476 					return (EINVAL);
9477 			}
9478 		}
9479 
9480 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
9481 		action->dta_rec.dtrd_size = size;
9482 	}
9483 
9484 	action->dta_refcnt = 1;
9485 	rec = &action->dta_rec;
9486 	size = rec->dtrd_size;
9487 
9488 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
9489 		if (!(size & mask)) {
9490 			align = mask + 1;
9491 			break;
9492 		}
9493 	}
9494 
9495 	action->dta_kind = desc->dtad_kind;
9496 
9497 	if ((action->dta_difo = dp) != NULL)
9498 		dtrace_difo_hold(dp);
9499 
9500 	rec->dtrd_action = action->dta_kind;
9501 	rec->dtrd_arg = arg;
9502 	rec->dtrd_uarg = desc->dtad_uarg;
9503 	rec->dtrd_alignment = (uint16_t)align;
9504 	rec->dtrd_format = format;
9505 
9506 	if ((last = ecb->dte_action_last) != NULL) {
9507 		ASSERT(ecb->dte_action != NULL);
9508 		action->dta_prev = last;
9509 		last->dta_next = action;
9510 	} else {
9511 		ASSERT(ecb->dte_action == NULL);
9512 		ecb->dte_action = action;
9513 	}
9514 
9515 	ecb->dte_action_last = action;
9516 
9517 	return (0);
9518 }
9519 
9520 static void
9521 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
9522 {
9523 	dtrace_action_t *act = ecb->dte_action, *next;
9524 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
9525 	dtrace_difo_t *dp;
9526 	uint16_t format;
9527 
9528 	if (act != NULL && act->dta_refcnt > 1) {
9529 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
9530 		act->dta_refcnt--;
9531 	} else {
9532 		for (; act != NULL; act = next) {
9533 			next = act->dta_next;
9534 			ASSERT(next != NULL || act == ecb->dte_action_last);
9535 			ASSERT(act->dta_refcnt == 1);
9536 
9537 			if ((format = act->dta_rec.dtrd_format) != 0)
9538 				dtrace_format_remove(ecb->dte_state, format);
9539 
9540 			if ((dp = act->dta_difo) != NULL)
9541 				dtrace_difo_release(dp, vstate);
9542 
9543 			if (DTRACEACT_ISAGG(act->dta_kind)) {
9544 				dtrace_ecb_aggregation_destroy(ecb, act);
9545 			} else {
9546 				kmem_free(act, sizeof (dtrace_action_t));
9547 			}
9548 		}
9549 	}
9550 
9551 	ecb->dte_action = NULL;
9552 	ecb->dte_action_last = NULL;
9553 	ecb->dte_size = sizeof (dtrace_epid_t);
9554 }
9555 
9556 static void
9557 dtrace_ecb_disable(dtrace_ecb_t *ecb)
9558 {
9559 	/*
9560 	 * We disable the ECB by removing it from its probe.
9561 	 */
9562 	dtrace_ecb_t *pecb, *prev = NULL;
9563 	dtrace_probe_t *probe = ecb->dte_probe;
9564 
9565 	ASSERT(MUTEX_HELD(&dtrace_lock));
9566 
9567 	if (probe == NULL) {
9568 		/*
9569 		 * This is the NULL probe; there is nothing to disable.
9570 		 */
9571 		return;
9572 	}
9573 
9574 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
9575 		if (pecb == ecb)
9576 			break;
9577 		prev = pecb;
9578 	}
9579 
9580 	ASSERT(pecb != NULL);
9581 
9582 	if (prev == NULL) {
9583 		probe->dtpr_ecb = ecb->dte_next;
9584 	} else {
9585 		prev->dte_next = ecb->dte_next;
9586 	}
9587 
9588 	if (ecb == probe->dtpr_ecb_last) {
9589 		ASSERT(ecb->dte_next == NULL);
9590 		probe->dtpr_ecb_last = prev;
9591 	}
9592 
9593 	/*
9594 	 * The ECB has been disconnected from the probe; now sync to assure
9595 	 * that all CPUs have seen the change before returning.
9596 	 */
9597 	dtrace_sync();
9598 
9599 	if (probe->dtpr_ecb == NULL) {
9600 		/*
9601 		 * That was the last ECB on the probe; clear the predicate
9602 		 * cache ID for the probe, disable it and sync one more time
9603 		 * to assure that we'll never hit it again.
9604 		 */
9605 		dtrace_provider_t *prov = probe->dtpr_provider;
9606 
9607 		ASSERT(ecb->dte_next == NULL);
9608 		ASSERT(probe->dtpr_ecb_last == NULL);
9609 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
9610 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
9611 		    probe->dtpr_id, probe->dtpr_arg);
9612 		dtrace_sync();
9613 	} else {
9614 		/*
9615 		 * There is at least one ECB remaining on the probe.  If there
9616 		 * is _exactly_ one, set the probe's predicate cache ID to be
9617 		 * the predicate cache ID of the remaining ECB.
9618 		 */
9619 		ASSERT(probe->dtpr_ecb_last != NULL);
9620 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
9621 
9622 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
9623 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
9624 
9625 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
9626 
9627 			if (p != NULL)
9628 				probe->dtpr_predcache = p->dtp_cacheid;
9629 		}
9630 
9631 		ecb->dte_next = NULL;
9632 	}
9633 }
9634 
9635 static void
9636 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
9637 {
9638 	dtrace_state_t *state = ecb->dte_state;
9639 	dtrace_vstate_t *vstate = &state->dts_vstate;
9640 	dtrace_predicate_t *pred;
9641 	dtrace_epid_t epid = ecb->dte_epid;
9642 
9643 	ASSERT(MUTEX_HELD(&dtrace_lock));
9644 	ASSERT(ecb->dte_next == NULL);
9645 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
9646 
9647 	if ((pred = ecb->dte_predicate) != NULL)
9648 		dtrace_predicate_release(pred, vstate);
9649 
9650 	dtrace_ecb_action_remove(ecb);
9651 
9652 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
9653 	state->dts_ecbs[epid - 1] = NULL;
9654 
9655 	kmem_free(ecb, sizeof (dtrace_ecb_t));
9656 }
9657 
9658 static dtrace_ecb_t *
9659 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
9660     dtrace_enabling_t *enab)
9661 {
9662 	dtrace_ecb_t *ecb;
9663 	dtrace_predicate_t *pred;
9664 	dtrace_actdesc_t *act;
9665 	dtrace_provider_t *prov;
9666 	dtrace_ecbdesc_t *desc = enab->dten_current;
9667 
9668 	ASSERT(MUTEX_HELD(&dtrace_lock));
9669 	ASSERT(state != NULL);
9670 
9671 	ecb = dtrace_ecb_add(state, probe);
9672 	ecb->dte_uarg = desc->dted_uarg;
9673 
9674 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
9675 		dtrace_predicate_hold(pred);
9676 		ecb->dte_predicate = pred;
9677 	}
9678 
9679 	if (probe != NULL) {
9680 		/*
9681 		 * If the provider shows more leg than the consumer is old
9682 		 * enough to see, we need to enable the appropriate implicit
9683 		 * predicate bits to prevent the ecb from activating at
9684 		 * revealing times.
9685 		 *
9686 		 * Providers specifying DTRACE_PRIV_USER at register time
9687 		 * are stating that they need the /proc-style privilege
9688 		 * model to be enforced, and this is what DTRACE_COND_OWNER
9689 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
9690 		 */
9691 		prov = probe->dtpr_provider;
9692 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
9693 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9694 			ecb->dte_cond |= DTRACE_COND_OWNER;
9695 
9696 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
9697 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9698 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
9699 
9700 		/*
9701 		 * If the provider shows us kernel innards and the user
9702 		 * is lacking sufficient privilege, enable the
9703 		 * DTRACE_COND_USERMODE implicit predicate.
9704 		 */
9705 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
9706 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
9707 			ecb->dte_cond |= DTRACE_COND_USERMODE;
9708 	}
9709 
9710 	if (dtrace_ecb_create_cache != NULL) {
9711 		/*
9712 		 * If we have a cached ecb, we'll use its action list instead
9713 		 * of creating our own (saving both time and space).
9714 		 */
9715 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
9716 		dtrace_action_t *act = cached->dte_action;
9717 
9718 		if (act != NULL) {
9719 			ASSERT(act->dta_refcnt > 0);
9720 			act->dta_refcnt++;
9721 			ecb->dte_action = act;
9722 			ecb->dte_action_last = cached->dte_action_last;
9723 			ecb->dte_needed = cached->dte_needed;
9724 			ecb->dte_size = cached->dte_size;
9725 			ecb->dte_alignment = cached->dte_alignment;
9726 		}
9727 
9728 		return (ecb);
9729 	}
9730 
9731 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
9732 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
9733 			dtrace_ecb_destroy(ecb);
9734 			return (NULL);
9735 		}
9736 	}
9737 
9738 	dtrace_ecb_resize(ecb);
9739 
9740 	return (dtrace_ecb_create_cache = ecb);
9741 }
9742 
9743 static int
9744 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
9745 {
9746 	dtrace_ecb_t *ecb;
9747 	dtrace_enabling_t *enab = arg;
9748 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
9749 
9750 	ASSERT(state != NULL);
9751 
9752 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
9753 		/*
9754 		 * This probe was created in a generation for which this
9755 		 * enabling has previously created ECBs; we don't want to
9756 		 * enable it again, so just kick out.
9757 		 */
9758 		return (DTRACE_MATCH_NEXT);
9759 	}
9760 
9761 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
9762 		return (DTRACE_MATCH_DONE);
9763 
9764 	dtrace_ecb_enable(ecb);
9765 	return (DTRACE_MATCH_NEXT);
9766 }
9767 
9768 static dtrace_ecb_t *
9769 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
9770 {
9771 	dtrace_ecb_t *ecb;
9772 
9773 	ASSERT(MUTEX_HELD(&dtrace_lock));
9774 
9775 	if (id == 0 || id > state->dts_necbs)
9776 		return (NULL);
9777 
9778 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
9779 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
9780 
9781 	return (state->dts_ecbs[id - 1]);
9782 }
9783 
9784 static dtrace_aggregation_t *
9785 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
9786 {
9787 	dtrace_aggregation_t *agg;
9788 
9789 	ASSERT(MUTEX_HELD(&dtrace_lock));
9790 
9791 	if (id == 0 || id > state->dts_naggregations)
9792 		return (NULL);
9793 
9794 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
9795 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
9796 	    agg->dtag_id == id);
9797 
9798 	return (state->dts_aggregations[id - 1]);
9799 }
9800 
9801 /*
9802  * DTrace Buffer Functions
9803  *
9804  * The following functions manipulate DTrace buffers.  Most of these functions
9805  * are called in the context of establishing or processing consumer state;
9806  * exceptions are explicitly noted.
9807  */
9808 
9809 /*
9810  * Note:  called from cross call context.  This function switches the two
9811  * buffers on a given CPU.  The atomicity of this operation is assured by
9812  * disabling interrupts while the actual switch takes place; the disabling of
9813  * interrupts serializes the execution with any execution of dtrace_probe() on
9814  * the same CPU.
9815  */
9816 static void
9817 dtrace_buffer_switch(dtrace_buffer_t *buf)
9818 {
9819 	caddr_t tomax = buf->dtb_tomax;
9820 	caddr_t xamot = buf->dtb_xamot;
9821 	dtrace_icookie_t cookie;
9822 
9823 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
9824 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
9825 
9826 	cookie = dtrace_interrupt_disable();
9827 	buf->dtb_tomax = xamot;
9828 	buf->dtb_xamot = tomax;
9829 	buf->dtb_xamot_drops = buf->dtb_drops;
9830 	buf->dtb_xamot_offset = buf->dtb_offset;
9831 	buf->dtb_xamot_errors = buf->dtb_errors;
9832 	buf->dtb_xamot_flags = buf->dtb_flags;
9833 	buf->dtb_offset = 0;
9834 	buf->dtb_drops = 0;
9835 	buf->dtb_errors = 0;
9836 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
9837 	dtrace_interrupt_enable(cookie);
9838 }
9839 
9840 /*
9841  * Note:  called from cross call context.  This function activates a buffer
9842  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
9843  * is guaranteed by the disabling of interrupts.
9844  */
9845 static void
9846 dtrace_buffer_activate(dtrace_state_t *state)
9847 {
9848 	dtrace_buffer_t *buf;
9849 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
9850 
9851 	buf = &state->dts_buffer[CPU->cpu_id];
9852 
9853 	if (buf->dtb_tomax != NULL) {
9854 		/*
9855 		 * We might like to assert that the buffer is marked inactive,
9856 		 * but this isn't necessarily true:  the buffer for the CPU
9857 		 * that processes the BEGIN probe has its buffer activated
9858 		 * manually.  In this case, we take the (harmless) action
9859 		 * re-clearing the bit INACTIVE bit.
9860 		 */
9861 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
9862 	}
9863 
9864 	dtrace_interrupt_enable(cookie);
9865 }
9866 
9867 static int
9868 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
9869     processorid_t cpu)
9870 {
9871 	cpu_t *cp;
9872 	dtrace_buffer_t *buf;
9873 
9874 	ASSERT(MUTEX_HELD(&cpu_lock));
9875 	ASSERT(MUTEX_HELD(&dtrace_lock));
9876 
9877 	if (size > dtrace_nonroot_maxsize &&
9878 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
9879 		return (EFBIG);
9880 
9881 	cp = cpu_list;
9882 
9883 	do {
9884 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9885 			continue;
9886 
9887 		buf = &bufs[cp->cpu_id];
9888 
9889 		/*
9890 		 * If there is already a buffer allocated for this CPU, it
9891 		 * is only possible that this is a DR event.  In this case,
9892 		 * the buffer size must match our specified size.
9893 		 */
9894 		if (buf->dtb_tomax != NULL) {
9895 			ASSERT(buf->dtb_size == size);
9896 			continue;
9897 		}
9898 
9899 		ASSERT(buf->dtb_xamot == NULL);
9900 
9901 		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9902 			goto err;
9903 
9904 		buf->dtb_size = size;
9905 		buf->dtb_flags = flags;
9906 		buf->dtb_offset = 0;
9907 		buf->dtb_drops = 0;
9908 
9909 		if (flags & DTRACEBUF_NOSWITCH)
9910 			continue;
9911 
9912 		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9913 			goto err;
9914 	} while ((cp = cp->cpu_next) != cpu_list);
9915 
9916 	return (0);
9917 
9918 err:
9919 	cp = cpu_list;
9920 
9921 	do {
9922 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9923 			continue;
9924 
9925 		buf = &bufs[cp->cpu_id];
9926 
9927 		if (buf->dtb_xamot != NULL) {
9928 			ASSERT(buf->dtb_tomax != NULL);
9929 			ASSERT(buf->dtb_size == size);
9930 			kmem_free(buf->dtb_xamot, size);
9931 		}
9932 
9933 		if (buf->dtb_tomax != NULL) {
9934 			ASSERT(buf->dtb_size == size);
9935 			kmem_free(buf->dtb_tomax, size);
9936 		}
9937 
9938 		buf->dtb_tomax = NULL;
9939 		buf->dtb_xamot = NULL;
9940 		buf->dtb_size = 0;
9941 	} while ((cp = cp->cpu_next) != cpu_list);
9942 
9943 	return (ENOMEM);
9944 }
9945 
9946 /*
9947  * Note:  called from probe context.  This function just increments the drop
9948  * count on a buffer.  It has been made a function to allow for the
9949  * possibility of understanding the source of mysterious drop counts.  (A
9950  * problem for which one may be particularly disappointed that DTrace cannot
9951  * be used to understand DTrace.)
9952  */
9953 static void
9954 dtrace_buffer_drop(dtrace_buffer_t *buf)
9955 {
9956 	buf->dtb_drops++;
9957 }
9958 
9959 /*
9960  * Note:  called from probe context.  This function is called to reserve space
9961  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
9962  * mstate.  Returns the new offset in the buffer, or a negative value if an
9963  * error has occurred.
9964  */
9965 static intptr_t
9966 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
9967     dtrace_state_t *state, dtrace_mstate_t *mstate)
9968 {
9969 	intptr_t offs = buf->dtb_offset, soffs;
9970 	intptr_t woffs;
9971 	caddr_t tomax;
9972 	size_t total;
9973 
9974 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
9975 		return (-1);
9976 
9977 	if ((tomax = buf->dtb_tomax) == NULL) {
9978 		dtrace_buffer_drop(buf);
9979 		return (-1);
9980 	}
9981 
9982 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
9983 		while (offs & (align - 1)) {
9984 			/*
9985 			 * Assert that our alignment is off by a number which
9986 			 * is itself sizeof (uint32_t) aligned.
9987 			 */
9988 			ASSERT(!((align - (offs & (align - 1))) &
9989 			    (sizeof (uint32_t) - 1)));
9990 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
9991 			offs += sizeof (uint32_t);
9992 		}
9993 
9994 		if ((soffs = offs + needed) > buf->dtb_size) {
9995 			dtrace_buffer_drop(buf);
9996 			return (-1);
9997 		}
9998 
9999 		if (mstate == NULL)
10000 			return (offs);
10001 
10002 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
10003 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
10004 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10005 
10006 		return (offs);
10007 	}
10008 
10009 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10010 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
10011 		    (buf->dtb_flags & DTRACEBUF_FULL))
10012 			return (-1);
10013 		goto out;
10014 	}
10015 
10016 	total = needed + (offs & (align - 1));
10017 
10018 	/*
10019 	 * For a ring buffer, life is quite a bit more complicated.  Before
10020 	 * we can store any padding, we need to adjust our wrapping offset.
10021 	 * (If we've never before wrapped or we're not about to, no adjustment
10022 	 * is required.)
10023 	 */
10024 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
10025 	    offs + total > buf->dtb_size) {
10026 		woffs = buf->dtb_xamot_offset;
10027 
10028 		if (offs + total > buf->dtb_size) {
10029 			/*
10030 			 * We can't fit in the end of the buffer.  First, a
10031 			 * sanity check that we can fit in the buffer at all.
10032 			 */
10033 			if (total > buf->dtb_size) {
10034 				dtrace_buffer_drop(buf);
10035 				return (-1);
10036 			}
10037 
10038 			/*
10039 			 * We're going to be storing at the top of the buffer,
10040 			 * so now we need to deal with the wrapped offset.  We
10041 			 * only reset our wrapped offset to 0 if it is
10042 			 * currently greater than the current offset.  If it
10043 			 * is less than the current offset, it is because a
10044 			 * previous allocation induced a wrap -- but the
10045 			 * allocation didn't subsequently take the space due
10046 			 * to an error or false predicate evaluation.  In this
10047 			 * case, we'll just leave the wrapped offset alone: if
10048 			 * the wrapped offset hasn't been advanced far enough
10049 			 * for this allocation, it will be adjusted in the
10050 			 * lower loop.
10051 			 */
10052 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
10053 				if (woffs >= offs)
10054 					woffs = 0;
10055 			} else {
10056 				woffs = 0;
10057 			}
10058 
10059 			/*
10060 			 * Now we know that we're going to be storing to the
10061 			 * top of the buffer and that there is room for us
10062 			 * there.  We need to clear the buffer from the current
10063 			 * offset to the end (there may be old gunk there).
10064 			 */
10065 			while (offs < buf->dtb_size)
10066 				tomax[offs++] = 0;
10067 
10068 			/*
10069 			 * We need to set our offset to zero.  And because we
10070 			 * are wrapping, we need to set the bit indicating as
10071 			 * much.  We can also adjust our needed space back
10072 			 * down to the space required by the ECB -- we know
10073 			 * that the top of the buffer is aligned.
10074 			 */
10075 			offs = 0;
10076 			total = needed;
10077 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
10078 		} else {
10079 			/*
10080 			 * There is room for us in the buffer, so we simply
10081 			 * need to check the wrapped offset.
10082 			 */
10083 			if (woffs < offs) {
10084 				/*
10085 				 * The wrapped offset is less than the offset.
10086 				 * This can happen if we allocated buffer space
10087 				 * that induced a wrap, but then we didn't
10088 				 * subsequently take the space due to an error
10089 				 * or false predicate evaluation.  This is
10090 				 * okay; we know that _this_ allocation isn't
10091 				 * going to induce a wrap.  We still can't
10092 				 * reset the wrapped offset to be zero,
10093 				 * however: the space may have been trashed in
10094 				 * the previous failed probe attempt.  But at
10095 				 * least the wrapped offset doesn't need to
10096 				 * be adjusted at all...
10097 				 */
10098 				goto out;
10099 			}
10100 		}
10101 
10102 		while (offs + total > woffs) {
10103 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
10104 			size_t size;
10105 
10106 			if (epid == DTRACE_EPIDNONE) {
10107 				size = sizeof (uint32_t);
10108 			} else {
10109 				ASSERT(epid <= state->dts_necbs);
10110 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
10111 
10112 				size = state->dts_ecbs[epid - 1]->dte_size;
10113 			}
10114 
10115 			ASSERT(woffs + size <= buf->dtb_size);
10116 			ASSERT(size != 0);
10117 
10118 			if (woffs + size == buf->dtb_size) {
10119 				/*
10120 				 * We've reached the end of the buffer; we want
10121 				 * to set the wrapped offset to 0 and break
10122 				 * out.  However, if the offs is 0, then we're
10123 				 * in a strange edge-condition:  the amount of
10124 				 * space that we want to reserve plus the size
10125 				 * of the record that we're overwriting is
10126 				 * greater than the size of the buffer.  This
10127 				 * is problematic because if we reserve the
10128 				 * space but subsequently don't consume it (due
10129 				 * to a failed predicate or error) the wrapped
10130 				 * offset will be 0 -- yet the EPID at offset 0
10131 				 * will not be committed.  This situation is
10132 				 * relatively easy to deal with:  if we're in
10133 				 * this case, the buffer is indistinguishable
10134 				 * from one that hasn't wrapped; we need only
10135 				 * finish the job by clearing the wrapped bit,
10136 				 * explicitly setting the offset to be 0, and
10137 				 * zero'ing out the old data in the buffer.
10138 				 */
10139 				if (offs == 0) {
10140 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
10141 					buf->dtb_offset = 0;
10142 					woffs = total;
10143 
10144 					while (woffs < buf->dtb_size)
10145 						tomax[woffs++] = 0;
10146 				}
10147 
10148 				woffs = 0;
10149 				break;
10150 			}
10151 
10152 			woffs += size;
10153 		}
10154 
10155 		/*
10156 		 * We have a wrapped offset.  It may be that the wrapped offset
10157 		 * has become zero -- that's okay.
10158 		 */
10159 		buf->dtb_xamot_offset = woffs;
10160 	}
10161 
10162 out:
10163 	/*
10164 	 * Now we can plow the buffer with any necessary padding.
10165 	 */
10166 	while (offs & (align - 1)) {
10167 		/*
10168 		 * Assert that our alignment is off by a number which
10169 		 * is itself sizeof (uint32_t) aligned.
10170 		 */
10171 		ASSERT(!((align - (offs & (align - 1))) &
10172 		    (sizeof (uint32_t) - 1)));
10173 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10174 		offs += sizeof (uint32_t);
10175 	}
10176 
10177 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10178 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
10179 			buf->dtb_flags |= DTRACEBUF_FULL;
10180 			return (-1);
10181 		}
10182 	}
10183 
10184 	if (mstate == NULL)
10185 		return (offs);
10186 
10187 	/*
10188 	 * For ring buffers and fill buffers, the scratch space is always
10189 	 * the inactive buffer.
10190 	 */
10191 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
10192 	mstate->dtms_scratch_size = buf->dtb_size;
10193 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10194 
10195 	return (offs);
10196 }
10197 
10198 static void
10199 dtrace_buffer_polish(dtrace_buffer_t *buf)
10200 {
10201 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
10202 	ASSERT(MUTEX_HELD(&dtrace_lock));
10203 
10204 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
10205 		return;
10206 
10207 	/*
10208 	 * We need to polish the ring buffer.  There are three cases:
10209 	 *
10210 	 * - The first (and presumably most common) is that there is no gap
10211 	 *   between the buffer offset and the wrapped offset.  In this case,
10212 	 *   there is nothing in the buffer that isn't valid data; we can
10213 	 *   mark the buffer as polished and return.
10214 	 *
10215 	 * - The second (less common than the first but still more common
10216 	 *   than the third) is that there is a gap between the buffer offset
10217 	 *   and the wrapped offset, and the wrapped offset is larger than the
10218 	 *   buffer offset.  This can happen because of an alignment issue, or
10219 	 *   can happen because of a call to dtrace_buffer_reserve() that
10220 	 *   didn't subsequently consume the buffer space.  In this case,
10221 	 *   we need to zero the data from the buffer offset to the wrapped
10222 	 *   offset.
10223 	 *
10224 	 * - The third (and least common) is that there is a gap between the
10225 	 *   buffer offset and the wrapped offset, but the wrapped offset is
10226 	 *   _less_ than the buffer offset.  This can only happen because a
10227 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
10228 	 *   was not subsequently consumed.  In this case, we need to zero the
10229 	 *   space from the offset to the end of the buffer _and_ from the
10230 	 *   top of the buffer to the wrapped offset.
10231 	 */
10232 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
10233 		bzero(buf->dtb_tomax + buf->dtb_offset,
10234 		    buf->dtb_xamot_offset - buf->dtb_offset);
10235 	}
10236 
10237 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
10238 		bzero(buf->dtb_tomax + buf->dtb_offset,
10239 		    buf->dtb_size - buf->dtb_offset);
10240 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
10241 	}
10242 }
10243 
10244 static void
10245 dtrace_buffer_free(dtrace_buffer_t *bufs)
10246 {
10247 	int i;
10248 
10249 	for (i = 0; i < NCPU; i++) {
10250 		dtrace_buffer_t *buf = &bufs[i];
10251 
10252 		if (buf->dtb_tomax == NULL) {
10253 			ASSERT(buf->dtb_xamot == NULL);
10254 			ASSERT(buf->dtb_size == 0);
10255 			continue;
10256 		}
10257 
10258 		if (buf->dtb_xamot != NULL) {
10259 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10260 			kmem_free(buf->dtb_xamot, buf->dtb_size);
10261 		}
10262 
10263 		kmem_free(buf->dtb_tomax, buf->dtb_size);
10264 		buf->dtb_size = 0;
10265 		buf->dtb_tomax = NULL;
10266 		buf->dtb_xamot = NULL;
10267 	}
10268 }
10269 
10270 /*
10271  * DTrace Enabling Functions
10272  */
10273 static dtrace_enabling_t *
10274 dtrace_enabling_create(dtrace_vstate_t *vstate)
10275 {
10276 	dtrace_enabling_t *enab;
10277 
10278 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
10279 	enab->dten_vstate = vstate;
10280 
10281 	return (enab);
10282 }
10283 
10284 static void
10285 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
10286 {
10287 	dtrace_ecbdesc_t **ndesc;
10288 	size_t osize, nsize;
10289 
10290 	/*
10291 	 * We can't add to enablings after we've enabled them, or after we've
10292 	 * retained them.
10293 	 */
10294 	ASSERT(enab->dten_probegen == 0);
10295 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10296 
10297 	if (enab->dten_ndesc < enab->dten_maxdesc) {
10298 		enab->dten_desc[enab->dten_ndesc++] = ecb;
10299 		return;
10300 	}
10301 
10302 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10303 
10304 	if (enab->dten_maxdesc == 0) {
10305 		enab->dten_maxdesc = 1;
10306 	} else {
10307 		enab->dten_maxdesc <<= 1;
10308 	}
10309 
10310 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
10311 
10312 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10313 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
10314 	bcopy(enab->dten_desc, ndesc, osize);
10315 	kmem_free(enab->dten_desc, osize);
10316 
10317 	enab->dten_desc = ndesc;
10318 	enab->dten_desc[enab->dten_ndesc++] = ecb;
10319 }
10320 
10321 static void
10322 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
10323     dtrace_probedesc_t *pd)
10324 {
10325 	dtrace_ecbdesc_t *new;
10326 	dtrace_predicate_t *pred;
10327 	dtrace_actdesc_t *act;
10328 
10329 	/*
10330 	 * We're going to create a new ECB description that matches the
10331 	 * specified ECB in every way, but has the specified probe description.
10332 	 */
10333 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
10334 
10335 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
10336 		dtrace_predicate_hold(pred);
10337 
10338 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
10339 		dtrace_actdesc_hold(act);
10340 
10341 	new->dted_action = ecb->dted_action;
10342 	new->dted_pred = ecb->dted_pred;
10343 	new->dted_probe = *pd;
10344 	new->dted_uarg = ecb->dted_uarg;
10345 
10346 	dtrace_enabling_add(enab, new);
10347 }
10348 
10349 static void
10350 dtrace_enabling_dump(dtrace_enabling_t *enab)
10351 {
10352 	int i;
10353 
10354 	for (i = 0; i < enab->dten_ndesc; i++) {
10355 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
10356 
10357 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
10358 		    desc->dtpd_provider, desc->dtpd_mod,
10359 		    desc->dtpd_func, desc->dtpd_name);
10360 	}
10361 }
10362 
10363 static void
10364 dtrace_enabling_destroy(dtrace_enabling_t *enab)
10365 {
10366 	int i;
10367 	dtrace_ecbdesc_t *ep;
10368 	dtrace_vstate_t *vstate = enab->dten_vstate;
10369 
10370 	ASSERT(MUTEX_HELD(&dtrace_lock));
10371 
10372 	for (i = 0; i < enab->dten_ndesc; i++) {
10373 		dtrace_actdesc_t *act, *next;
10374 		dtrace_predicate_t *pred;
10375 
10376 		ep = enab->dten_desc[i];
10377 
10378 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
10379 			dtrace_predicate_release(pred, vstate);
10380 
10381 		for (act = ep->dted_action; act != NULL; act = next) {
10382 			next = act->dtad_next;
10383 			dtrace_actdesc_release(act, vstate);
10384 		}
10385 
10386 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
10387 	}
10388 
10389 	kmem_free(enab->dten_desc,
10390 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
10391 
10392 	/*
10393 	 * If this was a retained enabling, decrement the dts_nretained count
10394 	 * and take it off of the dtrace_retained list.
10395 	 */
10396 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
10397 	    dtrace_retained == enab) {
10398 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10399 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
10400 		enab->dten_vstate->dtvs_state->dts_nretained--;
10401 	}
10402 
10403 	if (enab->dten_prev == NULL) {
10404 		if (dtrace_retained == enab) {
10405 			dtrace_retained = enab->dten_next;
10406 
10407 			if (dtrace_retained != NULL)
10408 				dtrace_retained->dten_prev = NULL;
10409 		}
10410 	} else {
10411 		ASSERT(enab != dtrace_retained);
10412 		ASSERT(dtrace_retained != NULL);
10413 		enab->dten_prev->dten_next = enab->dten_next;
10414 	}
10415 
10416 	if (enab->dten_next != NULL) {
10417 		ASSERT(dtrace_retained != NULL);
10418 		enab->dten_next->dten_prev = enab->dten_prev;
10419 	}
10420 
10421 	kmem_free(enab, sizeof (dtrace_enabling_t));
10422 }
10423 
10424 static int
10425 dtrace_enabling_retain(dtrace_enabling_t *enab)
10426 {
10427 	dtrace_state_t *state;
10428 
10429 	ASSERT(MUTEX_HELD(&dtrace_lock));
10430 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10431 	ASSERT(enab->dten_vstate != NULL);
10432 
10433 	state = enab->dten_vstate->dtvs_state;
10434 	ASSERT(state != NULL);
10435 
10436 	/*
10437 	 * We only allow each state to retain dtrace_retain_max enablings.
10438 	 */
10439 	if (state->dts_nretained >= dtrace_retain_max)
10440 		return (ENOSPC);
10441 
10442 	state->dts_nretained++;
10443 
10444 	if (dtrace_retained == NULL) {
10445 		dtrace_retained = enab;
10446 		return (0);
10447 	}
10448 
10449 	enab->dten_next = dtrace_retained;
10450 	dtrace_retained->dten_prev = enab;
10451 	dtrace_retained = enab;
10452 
10453 	return (0);
10454 }
10455 
10456 static int
10457 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
10458     dtrace_probedesc_t *create)
10459 {
10460 	dtrace_enabling_t *new, *enab;
10461 	int found = 0, err = ENOENT;
10462 
10463 	ASSERT(MUTEX_HELD(&dtrace_lock));
10464 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
10465 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
10466 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
10467 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
10468 
10469 	new = dtrace_enabling_create(&state->dts_vstate);
10470 
10471 	/*
10472 	 * Iterate over all retained enablings, looking for enablings that
10473 	 * match the specified state.
10474 	 */
10475 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10476 		int i;
10477 
10478 		/*
10479 		 * dtvs_state can only be NULL for helper enablings -- and
10480 		 * helper enablings can't be retained.
10481 		 */
10482 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10483 
10484 		if (enab->dten_vstate->dtvs_state != state)
10485 			continue;
10486 
10487 		/*
10488 		 * Now iterate over each probe description; we're looking for
10489 		 * an exact match to the specified probe description.
10490 		 */
10491 		for (i = 0; i < enab->dten_ndesc; i++) {
10492 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
10493 			dtrace_probedesc_t *pd = &ep->dted_probe;
10494 
10495 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
10496 				continue;
10497 
10498 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
10499 				continue;
10500 
10501 			if (strcmp(pd->dtpd_func, match->dtpd_func))
10502 				continue;
10503 
10504 			if (strcmp(pd->dtpd_name, match->dtpd_name))
10505 				continue;
10506 
10507 			/*
10508 			 * We have a winning probe!  Add it to our growing
10509 			 * enabling.
10510 			 */
10511 			found = 1;
10512 			dtrace_enabling_addlike(new, ep, create);
10513 		}
10514 	}
10515 
10516 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
10517 		dtrace_enabling_destroy(new);
10518 		return (err);
10519 	}
10520 
10521 	return (0);
10522 }
10523 
10524 static void
10525 dtrace_enabling_retract(dtrace_state_t *state)
10526 {
10527 	dtrace_enabling_t *enab, *next;
10528 
10529 	ASSERT(MUTEX_HELD(&dtrace_lock));
10530 
10531 	/*
10532 	 * Iterate over all retained enablings, destroy the enablings retained
10533 	 * for the specified state.
10534 	 */
10535 	for (enab = dtrace_retained; enab != NULL; enab = next) {
10536 		next = enab->dten_next;
10537 
10538 		/*
10539 		 * dtvs_state can only be NULL for helper enablings -- and
10540 		 * helper enablings can't be retained.
10541 		 */
10542 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10543 
10544 		if (enab->dten_vstate->dtvs_state == state) {
10545 			ASSERT(state->dts_nretained > 0);
10546 			dtrace_enabling_destroy(enab);
10547 		}
10548 	}
10549 
10550 	ASSERT(state->dts_nretained == 0);
10551 }
10552 
10553 static int
10554 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
10555 {
10556 	int i = 0;
10557 	int matched = 0;
10558 
10559 	ASSERT(MUTEX_HELD(&cpu_lock));
10560 	ASSERT(MUTEX_HELD(&dtrace_lock));
10561 
10562 	for (i = 0; i < enab->dten_ndesc; i++) {
10563 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
10564 
10565 		enab->dten_current = ep;
10566 		enab->dten_error = 0;
10567 
10568 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
10569 
10570 		if (enab->dten_error != 0) {
10571 			/*
10572 			 * If we get an error half-way through enabling the
10573 			 * probes, we kick out -- perhaps with some number of
10574 			 * them enabled.  Leaving enabled probes enabled may
10575 			 * be slightly confusing for user-level, but we expect
10576 			 * that no one will attempt to actually drive on in
10577 			 * the face of such errors.  If this is an anonymous
10578 			 * enabling (indicated with a NULL nmatched pointer),
10579 			 * we cmn_err() a message.  We aren't expecting to
10580 			 * get such an error -- such as it can exist at all,
10581 			 * it would be a result of corrupted DOF in the driver
10582 			 * properties.
10583 			 */
10584 			if (nmatched == NULL) {
10585 				cmn_err(CE_WARN, "dtrace_enabling_match() "
10586 				    "error on %p: %d", (void *)ep,
10587 				    enab->dten_error);
10588 			}
10589 
10590 			return (enab->dten_error);
10591 		}
10592 	}
10593 
10594 	enab->dten_probegen = dtrace_probegen;
10595 	if (nmatched != NULL)
10596 		*nmatched = matched;
10597 
10598 	return (0);
10599 }
10600 
10601 static void
10602 dtrace_enabling_matchall(void)
10603 {
10604 	dtrace_enabling_t *enab;
10605 
10606 	mutex_enter(&cpu_lock);
10607 	mutex_enter(&dtrace_lock);
10608 
10609 	/*
10610 	 * Because we can be called after dtrace_detach() has been called, we
10611 	 * cannot assert that there are retained enablings.  We can safely
10612 	 * load from dtrace_retained, however:  the taskq_destroy() at the
10613 	 * end of dtrace_detach() will block pending our completion.
10614 	 */
10615 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next)
10616 		(void) dtrace_enabling_match(enab, NULL);
10617 
10618 	mutex_exit(&dtrace_lock);
10619 	mutex_exit(&cpu_lock);
10620 }
10621 
10622 static int
10623 dtrace_enabling_matchstate(dtrace_state_t *state, int *nmatched)
10624 {
10625 	dtrace_enabling_t *enab;
10626 	int matched, total = 0, err;
10627 
10628 	ASSERT(MUTEX_HELD(&cpu_lock));
10629 	ASSERT(MUTEX_HELD(&dtrace_lock));
10630 
10631 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10632 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10633 
10634 		if (enab->dten_vstate->dtvs_state != state)
10635 			continue;
10636 
10637 		if ((err = dtrace_enabling_match(enab, &matched)) != 0)
10638 			return (err);
10639 
10640 		total += matched;
10641 	}
10642 
10643 	if (nmatched != NULL)
10644 		*nmatched = total;
10645 
10646 	return (0);
10647 }
10648 
10649 /*
10650  * If an enabling is to be enabled without having matched probes (that is, if
10651  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
10652  * enabling must be _primed_ by creating an ECB for every ECB description.
10653  * This must be done to assure that we know the number of speculations, the
10654  * number of aggregations, the minimum buffer size needed, etc. before we
10655  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
10656  * enabling any probes, we create ECBs for every ECB decription, but with a
10657  * NULL probe -- which is exactly what this function does.
10658  */
10659 static void
10660 dtrace_enabling_prime(dtrace_state_t *state)
10661 {
10662 	dtrace_enabling_t *enab;
10663 	int i;
10664 
10665 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10666 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10667 
10668 		if (enab->dten_vstate->dtvs_state != state)
10669 			continue;
10670 
10671 		/*
10672 		 * We don't want to prime an enabling more than once, lest
10673 		 * we allow a malicious user to induce resource exhaustion.
10674 		 * (The ECBs that result from priming an enabling aren't
10675 		 * leaked -- but they also aren't deallocated until the
10676 		 * consumer state is destroyed.)
10677 		 */
10678 		if (enab->dten_primed)
10679 			continue;
10680 
10681 		for (i = 0; i < enab->dten_ndesc; i++) {
10682 			enab->dten_current = enab->dten_desc[i];
10683 			(void) dtrace_probe_enable(NULL, enab);
10684 		}
10685 
10686 		enab->dten_primed = 1;
10687 	}
10688 }
10689 
10690 /*
10691  * Called to indicate that probes should be provided due to retained
10692  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
10693  * must take an initial lap through the enabling calling the dtps_provide()
10694  * entry point explicitly to allow for autocreated probes.
10695  */
10696 static void
10697 dtrace_enabling_provide(dtrace_provider_t *prv)
10698 {
10699 	int i, all = 0;
10700 	dtrace_probedesc_t desc;
10701 
10702 	ASSERT(MUTEX_HELD(&dtrace_lock));
10703 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
10704 
10705 	if (prv == NULL) {
10706 		all = 1;
10707 		prv = dtrace_provider;
10708 	}
10709 
10710 	do {
10711 		dtrace_enabling_t *enab = dtrace_retained;
10712 		void *parg = prv->dtpv_arg;
10713 
10714 		for (; enab != NULL; enab = enab->dten_next) {
10715 			for (i = 0; i < enab->dten_ndesc; i++) {
10716 				desc = enab->dten_desc[i]->dted_probe;
10717 				mutex_exit(&dtrace_lock);
10718 				prv->dtpv_pops.dtps_provide(parg, &desc);
10719 				mutex_enter(&dtrace_lock);
10720 			}
10721 		}
10722 	} while (all && (prv = prv->dtpv_next) != NULL);
10723 
10724 	mutex_exit(&dtrace_lock);
10725 	dtrace_probe_provide(NULL, all ? NULL : prv);
10726 	mutex_enter(&dtrace_lock);
10727 }
10728 
10729 /*
10730  * DTrace DOF Functions
10731  */
10732 /*ARGSUSED*/
10733 static void
10734 dtrace_dof_error(dof_hdr_t *dof, const char *str)
10735 {
10736 	if (dtrace_err_verbose)
10737 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
10738 
10739 #ifdef DTRACE_ERRDEBUG
10740 	dtrace_errdebug(str);
10741 #endif
10742 }
10743 
10744 /*
10745  * Create DOF out of a currently enabled state.  Right now, we only create
10746  * DOF containing the run-time options -- but this could be expanded to create
10747  * complete DOF representing the enabled state.
10748  */
10749 static dof_hdr_t *
10750 dtrace_dof_create(dtrace_state_t *state)
10751 {
10752 	dof_hdr_t *dof;
10753 	dof_sec_t *sec;
10754 	dof_optdesc_t *opt;
10755 	int i, len = sizeof (dof_hdr_t) +
10756 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
10757 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10758 
10759 	ASSERT(MUTEX_HELD(&dtrace_lock));
10760 
10761 	dof = kmem_zalloc(len, KM_SLEEP);
10762 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
10763 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
10764 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
10765 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
10766 
10767 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
10768 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
10769 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
10770 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
10771 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
10772 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
10773 
10774 	dof->dofh_flags = 0;
10775 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
10776 	dof->dofh_secsize = sizeof (dof_sec_t);
10777 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
10778 	dof->dofh_secoff = sizeof (dof_hdr_t);
10779 	dof->dofh_loadsz = len;
10780 	dof->dofh_filesz = len;
10781 	dof->dofh_pad = 0;
10782 
10783 	/*
10784 	 * Fill in the option section header...
10785 	 */
10786 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
10787 	sec->dofs_type = DOF_SECT_OPTDESC;
10788 	sec->dofs_align = sizeof (uint64_t);
10789 	sec->dofs_flags = DOF_SECF_LOAD;
10790 	sec->dofs_entsize = sizeof (dof_optdesc_t);
10791 
10792 	opt = (dof_optdesc_t *)((uintptr_t)sec +
10793 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
10794 
10795 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
10796 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10797 
10798 	for (i = 0; i < DTRACEOPT_MAX; i++) {
10799 		opt[i].dofo_option = i;
10800 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
10801 		opt[i].dofo_value = state->dts_options[i];
10802 	}
10803 
10804 	return (dof);
10805 }
10806 
10807 static dof_hdr_t *
10808 dtrace_dof_copyin(uintptr_t uarg, int *errp)
10809 {
10810 	dof_hdr_t hdr, *dof;
10811 
10812 	ASSERT(!MUTEX_HELD(&dtrace_lock));
10813 
10814 	/*
10815 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
10816 	 */
10817 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
10818 		dtrace_dof_error(NULL, "failed to copyin DOF header");
10819 		*errp = EFAULT;
10820 		return (NULL);
10821 	}
10822 
10823 	/*
10824 	 * Now we'll allocate the entire DOF and copy it in -- provided
10825 	 * that the length isn't outrageous.
10826 	 */
10827 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
10828 		dtrace_dof_error(&hdr, "load size exceeds maximum");
10829 		*errp = E2BIG;
10830 		return (NULL);
10831 	}
10832 
10833 	if (hdr.dofh_loadsz < sizeof (hdr)) {
10834 		dtrace_dof_error(&hdr, "invalid load size");
10835 		*errp = EINVAL;
10836 		return (NULL);
10837 	}
10838 
10839 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
10840 
10841 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
10842 		kmem_free(dof, hdr.dofh_loadsz);
10843 		*errp = EFAULT;
10844 		return (NULL);
10845 	}
10846 
10847 	return (dof);
10848 }
10849 
10850 static dof_hdr_t *
10851 dtrace_dof_property(const char *name)
10852 {
10853 	uchar_t *buf;
10854 	uint64_t loadsz;
10855 	unsigned int len, i;
10856 	dof_hdr_t *dof;
10857 
10858 	/*
10859 	 * Unfortunately, array of values in .conf files are always (and
10860 	 * only) interpreted to be integer arrays.  We must read our DOF
10861 	 * as an integer array, and then squeeze it into a byte array.
10862 	 */
10863 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
10864 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
10865 		return (NULL);
10866 
10867 	for (i = 0; i < len; i++)
10868 		buf[i] = (uchar_t)(((int *)buf)[i]);
10869 
10870 	if (len < sizeof (dof_hdr_t)) {
10871 		ddi_prop_free(buf);
10872 		dtrace_dof_error(NULL, "truncated header");
10873 		return (NULL);
10874 	}
10875 
10876 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
10877 		ddi_prop_free(buf);
10878 		dtrace_dof_error(NULL, "truncated DOF");
10879 		return (NULL);
10880 	}
10881 
10882 	if (loadsz >= dtrace_dof_maxsize) {
10883 		ddi_prop_free(buf);
10884 		dtrace_dof_error(NULL, "oversized DOF");
10885 		return (NULL);
10886 	}
10887 
10888 	dof = kmem_alloc(loadsz, KM_SLEEP);
10889 	bcopy(buf, dof, loadsz);
10890 	ddi_prop_free(buf);
10891 
10892 	return (dof);
10893 }
10894 
10895 static void
10896 dtrace_dof_destroy(dof_hdr_t *dof)
10897 {
10898 	kmem_free(dof, dof->dofh_loadsz);
10899 }
10900 
10901 /*
10902  * Return the dof_sec_t pointer corresponding to a given section index.  If the
10903  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
10904  * a type other than DOF_SECT_NONE is specified, the header is checked against
10905  * this type and NULL is returned if the types do not match.
10906  */
10907 static dof_sec_t *
10908 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
10909 {
10910 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
10911 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
10912 
10913 	if (i >= dof->dofh_secnum) {
10914 		dtrace_dof_error(dof, "referenced section index is invalid");
10915 		return (NULL);
10916 	}
10917 
10918 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
10919 		dtrace_dof_error(dof, "referenced section is not loadable");
10920 		return (NULL);
10921 	}
10922 
10923 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
10924 		dtrace_dof_error(dof, "referenced section is the wrong type");
10925 		return (NULL);
10926 	}
10927 
10928 	return (sec);
10929 }
10930 
10931 static dtrace_probedesc_t *
10932 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
10933 {
10934 	dof_probedesc_t *probe;
10935 	dof_sec_t *strtab;
10936 	uintptr_t daddr = (uintptr_t)dof;
10937 	uintptr_t str;
10938 	size_t size;
10939 
10940 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
10941 		dtrace_dof_error(dof, "invalid probe section");
10942 		return (NULL);
10943 	}
10944 
10945 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
10946 		dtrace_dof_error(dof, "bad alignment in probe description");
10947 		return (NULL);
10948 	}
10949 
10950 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
10951 		dtrace_dof_error(dof, "truncated probe description");
10952 		return (NULL);
10953 	}
10954 
10955 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
10956 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
10957 
10958 	if (strtab == NULL)
10959 		return (NULL);
10960 
10961 	str = daddr + strtab->dofs_offset;
10962 	size = strtab->dofs_size;
10963 
10964 	if (probe->dofp_provider >= strtab->dofs_size) {
10965 		dtrace_dof_error(dof, "corrupt probe provider");
10966 		return (NULL);
10967 	}
10968 
10969 	(void) strncpy(desc->dtpd_provider,
10970 	    (char *)(str + probe->dofp_provider),
10971 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
10972 
10973 	if (probe->dofp_mod >= strtab->dofs_size) {
10974 		dtrace_dof_error(dof, "corrupt probe module");
10975 		return (NULL);
10976 	}
10977 
10978 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
10979 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
10980 
10981 	if (probe->dofp_func >= strtab->dofs_size) {
10982 		dtrace_dof_error(dof, "corrupt probe function");
10983 		return (NULL);
10984 	}
10985 
10986 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
10987 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
10988 
10989 	if (probe->dofp_name >= strtab->dofs_size) {
10990 		dtrace_dof_error(dof, "corrupt probe name");
10991 		return (NULL);
10992 	}
10993 
10994 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
10995 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
10996 
10997 	return (desc);
10998 }
10999 
11000 static dtrace_difo_t *
11001 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11002     cred_t *cr)
11003 {
11004 	dtrace_difo_t *dp;
11005 	size_t ttl = 0;
11006 	dof_difohdr_t *dofd;
11007 	uintptr_t daddr = (uintptr_t)dof;
11008 	size_t max = dtrace_difo_maxsize;
11009 	int i, l, n;
11010 
11011 	static const struct {
11012 		int section;
11013 		int bufoffs;
11014 		int lenoffs;
11015 		int entsize;
11016 		int align;
11017 		const char *msg;
11018 	} difo[] = {
11019 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
11020 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
11021 		sizeof (dif_instr_t), "multiple DIF sections" },
11022 
11023 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
11024 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
11025 		sizeof (uint64_t), "multiple integer tables" },
11026 
11027 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
11028 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
11029 		sizeof (char), "multiple string tables" },
11030 
11031 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
11032 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
11033 		sizeof (uint_t), "multiple variable tables" },
11034 
11035 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
11036 	};
11037 
11038 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
11039 		dtrace_dof_error(dof, "invalid DIFO header section");
11040 		return (NULL);
11041 	}
11042 
11043 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
11044 		dtrace_dof_error(dof, "bad alignment in DIFO header");
11045 		return (NULL);
11046 	}
11047 
11048 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
11049 	    sec->dofs_size % sizeof (dof_secidx_t)) {
11050 		dtrace_dof_error(dof, "bad size in DIFO header");
11051 		return (NULL);
11052 	}
11053 
11054 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11055 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
11056 
11057 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
11058 	dp->dtdo_rtype = dofd->dofd_rtype;
11059 
11060 	for (l = 0; l < n; l++) {
11061 		dof_sec_t *subsec;
11062 		void **bufp;
11063 		uint32_t *lenp;
11064 
11065 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
11066 		    dofd->dofd_links[l])) == NULL)
11067 			goto err; /* invalid section link */
11068 
11069 		if (ttl + subsec->dofs_size > max) {
11070 			dtrace_dof_error(dof, "exceeds maximum size");
11071 			goto err;
11072 		}
11073 
11074 		ttl += subsec->dofs_size;
11075 
11076 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
11077 			if (subsec->dofs_type != difo[i].section)
11078 				continue;
11079 
11080 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
11081 				dtrace_dof_error(dof, "section not loaded");
11082 				goto err;
11083 			}
11084 
11085 			if (subsec->dofs_align != difo[i].align) {
11086 				dtrace_dof_error(dof, "bad alignment");
11087 				goto err;
11088 			}
11089 
11090 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
11091 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
11092 
11093 			if (*bufp != NULL) {
11094 				dtrace_dof_error(dof, difo[i].msg);
11095 				goto err;
11096 			}
11097 
11098 			if (difo[i].entsize != subsec->dofs_entsize) {
11099 				dtrace_dof_error(dof, "entry size mismatch");
11100 				goto err;
11101 			}
11102 
11103 			if (subsec->dofs_entsize != 0 &&
11104 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
11105 				dtrace_dof_error(dof, "corrupt entry size");
11106 				goto err;
11107 			}
11108 
11109 			*lenp = subsec->dofs_size;
11110 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
11111 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
11112 			    *bufp, subsec->dofs_size);
11113 
11114 			if (subsec->dofs_entsize != 0)
11115 				*lenp /= subsec->dofs_entsize;
11116 
11117 			break;
11118 		}
11119 
11120 		/*
11121 		 * If we encounter a loadable DIFO sub-section that is not
11122 		 * known to us, assume this is a broken program and fail.
11123 		 */
11124 		if (difo[i].section == DOF_SECT_NONE &&
11125 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
11126 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
11127 			goto err;
11128 		}
11129 	}
11130 
11131 	if (dp->dtdo_buf == NULL) {
11132 		/*
11133 		 * We can't have a DIF object without DIF text.
11134 		 */
11135 		dtrace_dof_error(dof, "missing DIF text");
11136 		goto err;
11137 	}
11138 
11139 	/*
11140 	 * Before we validate the DIF object, run through the variable table
11141 	 * looking for the strings -- if any of their size are under, we'll set
11142 	 * their size to be the system-wide default string size.  Note that
11143 	 * this should _not_ happen if the "strsize" option has been set --
11144 	 * in this case, the compiler should have set the size to reflect the
11145 	 * setting of the option.
11146 	 */
11147 	for (i = 0; i < dp->dtdo_varlen; i++) {
11148 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
11149 		dtrace_diftype_t *t = &v->dtdv_type;
11150 
11151 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
11152 			continue;
11153 
11154 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
11155 			t->dtdt_size = dtrace_strsize_default;
11156 	}
11157 
11158 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
11159 		goto err;
11160 
11161 	dtrace_difo_init(dp, vstate);
11162 	return (dp);
11163 
11164 err:
11165 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
11166 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
11167 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
11168 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
11169 
11170 	kmem_free(dp, sizeof (dtrace_difo_t));
11171 	return (NULL);
11172 }
11173 
11174 static dtrace_predicate_t *
11175 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11176     cred_t *cr)
11177 {
11178 	dtrace_difo_t *dp;
11179 
11180 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
11181 		return (NULL);
11182 
11183 	return (dtrace_predicate_create(dp));
11184 }
11185 
11186 static dtrace_actdesc_t *
11187 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11188     cred_t *cr)
11189 {
11190 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
11191 	dof_actdesc_t *desc;
11192 	dof_sec_t *difosec;
11193 	size_t offs;
11194 	uintptr_t daddr = (uintptr_t)dof;
11195 	uint64_t arg;
11196 	dtrace_actkind_t kind;
11197 
11198 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
11199 		dtrace_dof_error(dof, "invalid action section");
11200 		return (NULL);
11201 	}
11202 
11203 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
11204 		dtrace_dof_error(dof, "truncated action description");
11205 		return (NULL);
11206 	}
11207 
11208 	if (sec->dofs_align != sizeof (uint64_t)) {
11209 		dtrace_dof_error(dof, "bad alignment in action description");
11210 		return (NULL);
11211 	}
11212 
11213 	if (sec->dofs_size < sec->dofs_entsize) {
11214 		dtrace_dof_error(dof, "section entry size exceeds total size");
11215 		return (NULL);
11216 	}
11217 
11218 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
11219 		dtrace_dof_error(dof, "bad entry size in action description");
11220 		return (NULL);
11221 	}
11222 
11223 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
11224 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
11225 		return (NULL);
11226 	}
11227 
11228 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
11229 		desc = (dof_actdesc_t *)(daddr +
11230 		    (uintptr_t)sec->dofs_offset + offs);
11231 		kind = (dtrace_actkind_t)desc->dofa_kind;
11232 
11233 		if (DTRACEACT_ISPRINTFLIKE(kind) &&
11234 		    (kind != DTRACEACT_PRINTA ||
11235 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
11236 			dof_sec_t *strtab;
11237 			char *str, *fmt;
11238 			uint64_t i;
11239 
11240 			/*
11241 			 * printf()-like actions must have a format string.
11242 			 */
11243 			if ((strtab = dtrace_dof_sect(dof,
11244 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
11245 				goto err;
11246 
11247 			str = (char *)((uintptr_t)dof +
11248 			    (uintptr_t)strtab->dofs_offset);
11249 
11250 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
11251 				if (str[i] == '\0')
11252 					break;
11253 			}
11254 
11255 			if (i >= strtab->dofs_size) {
11256 				dtrace_dof_error(dof, "bogus format string");
11257 				goto err;
11258 			}
11259 
11260 			if (i == desc->dofa_arg) {
11261 				dtrace_dof_error(dof, "empty format string");
11262 				goto err;
11263 			}
11264 
11265 			i -= desc->dofa_arg;
11266 			fmt = kmem_alloc(i + 1, KM_SLEEP);
11267 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
11268 			arg = (uint64_t)(uintptr_t)fmt;
11269 		} else {
11270 			if (kind == DTRACEACT_PRINTA) {
11271 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
11272 				arg = 0;
11273 			} else {
11274 				arg = desc->dofa_arg;
11275 			}
11276 		}
11277 
11278 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
11279 		    desc->dofa_uarg, arg);
11280 
11281 		if (last != NULL) {
11282 			last->dtad_next = act;
11283 		} else {
11284 			first = act;
11285 		}
11286 
11287 		last = act;
11288 
11289 		if (desc->dofa_difo == DOF_SECIDX_NONE)
11290 			continue;
11291 
11292 		if ((difosec = dtrace_dof_sect(dof,
11293 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
11294 			goto err;
11295 
11296 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
11297 
11298 		if (act->dtad_difo == NULL)
11299 			goto err;
11300 	}
11301 
11302 	ASSERT(first != NULL);
11303 	return (first);
11304 
11305 err:
11306 	for (act = first; act != NULL; act = next) {
11307 		next = act->dtad_next;
11308 		dtrace_actdesc_release(act, vstate);
11309 	}
11310 
11311 	return (NULL);
11312 }
11313 
11314 static dtrace_ecbdesc_t *
11315 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11316     cred_t *cr)
11317 {
11318 	dtrace_ecbdesc_t *ep;
11319 	dof_ecbdesc_t *ecb;
11320 	dtrace_probedesc_t *desc;
11321 	dtrace_predicate_t *pred = NULL;
11322 
11323 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
11324 		dtrace_dof_error(dof, "truncated ECB description");
11325 		return (NULL);
11326 	}
11327 
11328 	if (sec->dofs_align != sizeof (uint64_t)) {
11329 		dtrace_dof_error(dof, "bad alignment in ECB description");
11330 		return (NULL);
11331 	}
11332 
11333 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
11334 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
11335 
11336 	if (sec == NULL)
11337 		return (NULL);
11338 
11339 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11340 	ep->dted_uarg = ecb->dofe_uarg;
11341 	desc = &ep->dted_probe;
11342 
11343 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
11344 		goto err;
11345 
11346 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
11347 		if ((sec = dtrace_dof_sect(dof,
11348 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
11349 			goto err;
11350 
11351 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
11352 			goto err;
11353 
11354 		ep->dted_pred.dtpdd_predicate = pred;
11355 	}
11356 
11357 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
11358 		if ((sec = dtrace_dof_sect(dof,
11359 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
11360 			goto err;
11361 
11362 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
11363 
11364 		if (ep->dted_action == NULL)
11365 			goto err;
11366 	}
11367 
11368 	return (ep);
11369 
11370 err:
11371 	if (pred != NULL)
11372 		dtrace_predicate_release(pred, vstate);
11373 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11374 	return (NULL);
11375 }
11376 
11377 /*
11378  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
11379  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
11380  * site of any user SETX relocations to account for load object base address.
11381  * In the future, if we need other relocations, this function can be extended.
11382  */
11383 static int
11384 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
11385 {
11386 	uintptr_t daddr = (uintptr_t)dof;
11387 	dof_relohdr_t *dofr =
11388 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11389 	dof_sec_t *ss, *rs, *ts;
11390 	dof_relodesc_t *r;
11391 	uint_t i, n;
11392 
11393 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
11394 	    sec->dofs_align != sizeof (dof_secidx_t)) {
11395 		dtrace_dof_error(dof, "invalid relocation header");
11396 		return (-1);
11397 	}
11398 
11399 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
11400 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
11401 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
11402 
11403 	if (ss == NULL || rs == NULL || ts == NULL)
11404 		return (-1); /* dtrace_dof_error() has been called already */
11405 
11406 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
11407 	    rs->dofs_align != sizeof (uint64_t)) {
11408 		dtrace_dof_error(dof, "invalid relocation section");
11409 		return (-1);
11410 	}
11411 
11412 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
11413 	n = rs->dofs_size / rs->dofs_entsize;
11414 
11415 	for (i = 0; i < n; i++) {
11416 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
11417 
11418 		switch (r->dofr_type) {
11419 		case DOF_RELO_NONE:
11420 			break;
11421 		case DOF_RELO_SETX:
11422 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
11423 			    sizeof (uint64_t) > ts->dofs_size) {
11424 				dtrace_dof_error(dof, "bad relocation offset");
11425 				return (-1);
11426 			}
11427 
11428 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
11429 				dtrace_dof_error(dof, "misaligned setx relo");
11430 				return (-1);
11431 			}
11432 
11433 			*(uint64_t *)taddr += ubase;
11434 			break;
11435 		default:
11436 			dtrace_dof_error(dof, "invalid relocation type");
11437 			return (-1);
11438 		}
11439 
11440 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
11441 	}
11442 
11443 	return (0);
11444 }
11445 
11446 /*
11447  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
11448  * header:  it should be at the front of a memory region that is at least
11449  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
11450  * size.  It need not be validated in any other way.
11451  */
11452 static int
11453 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
11454     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
11455 {
11456 	uint64_t len = dof->dofh_loadsz, seclen;
11457 	uintptr_t daddr = (uintptr_t)dof;
11458 	dtrace_ecbdesc_t *ep;
11459 	dtrace_enabling_t *enab;
11460 	uint_t i;
11461 
11462 	ASSERT(MUTEX_HELD(&dtrace_lock));
11463 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
11464 
11465 	/*
11466 	 * Check the DOF header identification bytes.  In addition to checking
11467 	 * valid settings, we also verify that unused bits/bytes are zeroed so
11468 	 * we can use them later without fear of regressing existing binaries.
11469 	 */
11470 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
11471 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
11472 		dtrace_dof_error(dof, "DOF magic string mismatch");
11473 		return (-1);
11474 	}
11475 
11476 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
11477 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
11478 		dtrace_dof_error(dof, "DOF has invalid data model");
11479 		return (-1);
11480 	}
11481 
11482 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
11483 		dtrace_dof_error(dof, "DOF encoding mismatch");
11484 		return (-1);
11485 	}
11486 
11487 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
11488 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
11489 		dtrace_dof_error(dof, "DOF version mismatch");
11490 		return (-1);
11491 	}
11492 
11493 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
11494 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
11495 		return (-1);
11496 	}
11497 
11498 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
11499 		dtrace_dof_error(dof, "DOF uses too many integer registers");
11500 		return (-1);
11501 	}
11502 
11503 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
11504 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
11505 		return (-1);
11506 	}
11507 
11508 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
11509 		if (dof->dofh_ident[i] != 0) {
11510 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
11511 			return (-1);
11512 		}
11513 	}
11514 
11515 	if (dof->dofh_flags & ~DOF_FL_VALID) {
11516 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
11517 		return (-1);
11518 	}
11519 
11520 	if (dof->dofh_secsize == 0) {
11521 		dtrace_dof_error(dof, "zero section header size");
11522 		return (-1);
11523 	}
11524 
11525 	/*
11526 	 * Check that the section headers don't exceed the amount of DOF
11527 	 * data.  Note that we cast the section size and number of sections
11528 	 * to uint64_t's to prevent possible overflow in the multiplication.
11529 	 */
11530 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
11531 
11532 	if (dof->dofh_secoff > len || seclen > len ||
11533 	    dof->dofh_secoff + seclen > len) {
11534 		dtrace_dof_error(dof, "truncated section headers");
11535 		return (-1);
11536 	}
11537 
11538 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
11539 		dtrace_dof_error(dof, "misaligned section headers");
11540 		return (-1);
11541 	}
11542 
11543 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
11544 		dtrace_dof_error(dof, "misaligned section size");
11545 		return (-1);
11546 	}
11547 
11548 	/*
11549 	 * Take an initial pass through the section headers to be sure that
11550 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
11551 	 * set, do not permit sections relating to providers, probes, or args.
11552 	 */
11553 	for (i = 0; i < dof->dofh_secnum; i++) {
11554 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11555 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11556 
11557 		if (noprobes) {
11558 			switch (sec->dofs_type) {
11559 			case DOF_SECT_PROVIDER:
11560 			case DOF_SECT_PROBES:
11561 			case DOF_SECT_PRARGS:
11562 			case DOF_SECT_PROFFS:
11563 				dtrace_dof_error(dof, "illegal sections "
11564 				    "for enabling");
11565 				return (-1);
11566 			}
11567 		}
11568 
11569 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
11570 			continue; /* just ignore non-loadable sections */
11571 
11572 		if (sec->dofs_align & (sec->dofs_align - 1)) {
11573 			dtrace_dof_error(dof, "bad section alignment");
11574 			return (-1);
11575 		}
11576 
11577 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
11578 			dtrace_dof_error(dof, "misaligned section");
11579 			return (-1);
11580 		}
11581 
11582 		if (sec->dofs_offset > len || sec->dofs_size > len ||
11583 		    sec->dofs_offset + sec->dofs_size > len) {
11584 			dtrace_dof_error(dof, "corrupt section header");
11585 			return (-1);
11586 		}
11587 
11588 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
11589 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
11590 			dtrace_dof_error(dof, "non-terminating string table");
11591 			return (-1);
11592 		}
11593 	}
11594 
11595 	/*
11596 	 * Take a second pass through the sections and locate and perform any
11597 	 * relocations that are present.  We do this after the first pass to
11598 	 * be sure that all sections have had their headers validated.
11599 	 */
11600 	for (i = 0; i < dof->dofh_secnum; i++) {
11601 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11602 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11603 
11604 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
11605 			continue; /* skip sections that are not loadable */
11606 
11607 		switch (sec->dofs_type) {
11608 		case DOF_SECT_URELHDR:
11609 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
11610 				return (-1);
11611 			break;
11612 		}
11613 	}
11614 
11615 	if ((enab = *enabp) == NULL)
11616 		enab = *enabp = dtrace_enabling_create(vstate);
11617 
11618 	for (i = 0; i < dof->dofh_secnum; i++) {
11619 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11620 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11621 
11622 		if (sec->dofs_type != DOF_SECT_ECBDESC)
11623 			continue;
11624 
11625 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
11626 			dtrace_enabling_destroy(enab);
11627 			*enabp = NULL;
11628 			return (-1);
11629 		}
11630 
11631 		dtrace_enabling_add(enab, ep);
11632 	}
11633 
11634 	return (0);
11635 }
11636 
11637 /*
11638  * Process DOF for any options.  This routine assumes that the DOF has been
11639  * at least processed by dtrace_dof_slurp().
11640  */
11641 static int
11642 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
11643 {
11644 	int i, rval;
11645 	uint32_t entsize;
11646 	size_t offs;
11647 	dof_optdesc_t *desc;
11648 
11649 	for (i = 0; i < dof->dofh_secnum; i++) {
11650 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
11651 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11652 
11653 		if (sec->dofs_type != DOF_SECT_OPTDESC)
11654 			continue;
11655 
11656 		if (sec->dofs_align != sizeof (uint64_t)) {
11657 			dtrace_dof_error(dof, "bad alignment in "
11658 			    "option description");
11659 			return (EINVAL);
11660 		}
11661 
11662 		if ((entsize = sec->dofs_entsize) == 0) {
11663 			dtrace_dof_error(dof, "zeroed option entry size");
11664 			return (EINVAL);
11665 		}
11666 
11667 		if (entsize < sizeof (dof_optdesc_t)) {
11668 			dtrace_dof_error(dof, "bad option entry size");
11669 			return (EINVAL);
11670 		}
11671 
11672 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
11673 			desc = (dof_optdesc_t *)((uintptr_t)dof +
11674 			    (uintptr_t)sec->dofs_offset + offs);
11675 
11676 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
11677 				dtrace_dof_error(dof, "non-zero option string");
11678 				return (EINVAL);
11679 			}
11680 
11681 			if (desc->dofo_value == DTRACEOPT_UNSET) {
11682 				dtrace_dof_error(dof, "unset option");
11683 				return (EINVAL);
11684 			}
11685 
11686 			if ((rval = dtrace_state_option(state,
11687 			    desc->dofo_option, desc->dofo_value)) != 0) {
11688 				dtrace_dof_error(dof, "rejected option");
11689 				return (rval);
11690 			}
11691 		}
11692 	}
11693 
11694 	return (0);
11695 }
11696 
11697 /*
11698  * DTrace Consumer State Functions
11699  */
11700 int
11701 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
11702 {
11703 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
11704 	void *base;
11705 	uintptr_t limit;
11706 	dtrace_dynvar_t *dvar, *next, *start;
11707 	int i;
11708 
11709 	ASSERT(MUTEX_HELD(&dtrace_lock));
11710 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
11711 
11712 	bzero(dstate, sizeof (dtrace_dstate_t));
11713 
11714 	if ((dstate->dtds_chunksize = chunksize) == 0)
11715 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
11716 
11717 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
11718 		size = min;
11719 
11720 	if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11721 		return (ENOMEM);
11722 
11723 	dstate->dtds_size = size;
11724 	dstate->dtds_base = base;
11725 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
11726 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
11727 
11728 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
11729 
11730 	if (hashsize != 1 && (hashsize & 1))
11731 		hashsize--;
11732 
11733 	dstate->dtds_hashsize = hashsize;
11734 	dstate->dtds_hash = dstate->dtds_base;
11735 
11736 	/*
11737 	 * Set all of our hash buckets to point to the single sink, and (if
11738 	 * it hasn't already been set), set the sink's hash value to be the
11739 	 * sink sentinel value.  The sink is needed for dynamic variable
11740 	 * lookups to know that they have iterated over an entire, valid hash
11741 	 * chain.
11742 	 */
11743 	for (i = 0; i < hashsize; i++)
11744 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
11745 
11746 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
11747 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
11748 
11749 	/*
11750 	 * Determine number of active CPUs.  Divide free list evenly among
11751 	 * active CPUs.
11752 	 */
11753 	start = (dtrace_dynvar_t *)
11754 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
11755 	limit = (uintptr_t)base + size;
11756 
11757 	maxper = (limit - (uintptr_t)start) / NCPU;
11758 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
11759 
11760 	for (i = 0; i < NCPU; i++) {
11761 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
11762 
11763 		/*
11764 		 * If we don't even have enough chunks to make it once through
11765 		 * NCPUs, we're just going to allocate everything to the first
11766 		 * CPU.  And if we're on the last CPU, we're going to allocate
11767 		 * whatever is left over.  In either case, we set the limit to
11768 		 * be the limit of the dynamic variable space.
11769 		 */
11770 		if (maxper == 0 || i == NCPU - 1) {
11771 			limit = (uintptr_t)base + size;
11772 			start = NULL;
11773 		} else {
11774 			limit = (uintptr_t)start + maxper;
11775 			start = (dtrace_dynvar_t *)limit;
11776 		}
11777 
11778 		ASSERT(limit <= (uintptr_t)base + size);
11779 
11780 		for (;;) {
11781 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
11782 			    dstate->dtds_chunksize);
11783 
11784 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
11785 				break;
11786 
11787 			dvar->dtdv_next = next;
11788 			dvar = next;
11789 		}
11790 
11791 		if (maxper == 0)
11792 			break;
11793 	}
11794 
11795 	return (0);
11796 }
11797 
11798 void
11799 dtrace_dstate_fini(dtrace_dstate_t *dstate)
11800 {
11801 	ASSERT(MUTEX_HELD(&cpu_lock));
11802 
11803 	if (dstate->dtds_base == NULL)
11804 		return;
11805 
11806 	kmem_free(dstate->dtds_base, dstate->dtds_size);
11807 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
11808 }
11809 
11810 static void
11811 dtrace_vstate_fini(dtrace_vstate_t *vstate)
11812 {
11813 	/*
11814 	 * Logical XOR, where are you?
11815 	 */
11816 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
11817 
11818 	if (vstate->dtvs_nglobals > 0) {
11819 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
11820 		    sizeof (dtrace_statvar_t *));
11821 	}
11822 
11823 	if (vstate->dtvs_ntlocals > 0) {
11824 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
11825 		    sizeof (dtrace_difv_t));
11826 	}
11827 
11828 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
11829 
11830 	if (vstate->dtvs_nlocals > 0) {
11831 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
11832 		    sizeof (dtrace_statvar_t *));
11833 	}
11834 }
11835 
11836 static void
11837 dtrace_state_clean(dtrace_state_t *state)
11838 {
11839 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
11840 		return;
11841 
11842 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
11843 	dtrace_speculation_clean(state);
11844 }
11845 
11846 static void
11847 dtrace_state_deadman(dtrace_state_t *state)
11848 {
11849 	hrtime_t now;
11850 
11851 	dtrace_sync();
11852 
11853 	now = dtrace_gethrtime();
11854 
11855 	if (state != dtrace_anon.dta_state &&
11856 	    now - state->dts_laststatus >= dtrace_deadman_user)
11857 		return;
11858 
11859 	/*
11860 	 * We must be sure that dts_alive never appears to be less than the
11861 	 * value upon entry to dtrace_state_deadman(), and because we lack a
11862 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
11863 	 * store INT64_MAX to it, followed by a memory barrier, followed by
11864 	 * the new value.  This assures that dts_alive never appears to be
11865 	 * less than its true value, regardless of the order in which the
11866 	 * stores to the underlying storage are issued.
11867 	 */
11868 	state->dts_alive = INT64_MAX;
11869 	dtrace_membar_producer();
11870 	state->dts_alive = now;
11871 }
11872 
11873 dtrace_state_t *
11874 dtrace_state_create(dev_t *devp, cred_t *cr)
11875 {
11876 	minor_t minor;
11877 	major_t major;
11878 	char c[30];
11879 	dtrace_state_t *state;
11880 	dtrace_optval_t *opt;
11881 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
11882 
11883 	ASSERT(MUTEX_HELD(&dtrace_lock));
11884 	ASSERT(MUTEX_HELD(&cpu_lock));
11885 
11886 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
11887 	    VM_BESTFIT | VM_SLEEP);
11888 
11889 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
11890 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
11891 		return (NULL);
11892 	}
11893 
11894 	state = ddi_get_soft_state(dtrace_softstate, minor);
11895 	state->dts_epid = DTRACE_EPIDNONE + 1;
11896 
11897 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
11898 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
11899 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
11900 
11901 	if (devp != NULL) {
11902 		major = getemajor(*devp);
11903 	} else {
11904 		major = ddi_driver_major(dtrace_devi);
11905 	}
11906 
11907 	state->dts_dev = makedevice(major, minor);
11908 
11909 	if (devp != NULL)
11910 		*devp = state->dts_dev;
11911 
11912 	/*
11913 	 * We allocate NCPU buffers.  On the one hand, this can be quite
11914 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
11915 	 * other hand, it saves an additional memory reference in the probe
11916 	 * path.
11917 	 */
11918 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
11919 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
11920 	state->dts_cleaner = CYCLIC_NONE;
11921 	state->dts_deadman = CYCLIC_NONE;
11922 	state->dts_vstate.dtvs_state = state;
11923 
11924 	for (i = 0; i < DTRACEOPT_MAX; i++)
11925 		state->dts_options[i] = DTRACEOPT_UNSET;
11926 
11927 	/*
11928 	 * Set the default options.
11929 	 */
11930 	opt = state->dts_options;
11931 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
11932 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
11933 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
11934 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
11935 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
11936 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
11937 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
11938 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
11939 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
11940 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
11941 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
11942 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
11943 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
11944 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
11945 
11946 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
11947 
11948 	/*
11949 	 * Depending on the user credentials, we set flag bits which alter probe
11950 	 * visibility or the amount of destructiveness allowed.  In the case of
11951 	 * actual anonymous tracing, or the possession of all privileges, all of
11952 	 * the normal checks are bypassed.
11953 	 */
11954 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
11955 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
11956 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
11957 	} else {
11958 		/*
11959 		 * Set up the credentials for this instantiation.  We take a
11960 		 * hold on the credential to prevent it from disappearing on
11961 		 * us; this in turn prevents the zone_t referenced by this
11962 		 * credential from disappearing.  This means that we can
11963 		 * examine the credential and the zone from probe context.
11964 		 */
11965 		crhold(cr);
11966 		state->dts_cred.dcr_cred = cr;
11967 
11968 		/*
11969 		 * CRA_PROC means "we have *some* privilege for dtrace" and
11970 		 * unlocks the use of variables like pid, zonename, etc.
11971 		 */
11972 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
11973 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
11974 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
11975 		}
11976 
11977 		/*
11978 		 * dtrace_user allows use of syscall and profile providers.
11979 		 * If the user also has proc_owner and/or proc_zone, we
11980 		 * extend the scope to include additional visibility and
11981 		 * destructive power.
11982 		 */
11983 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
11984 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
11985 				state->dts_cred.dcr_visible |=
11986 				    DTRACE_CRV_ALLPROC;
11987 
11988 				state->dts_cred.dcr_action |=
11989 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
11990 			}
11991 
11992 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
11993 				state->dts_cred.dcr_visible |=
11994 				    DTRACE_CRV_ALLZONE;
11995 
11996 				state->dts_cred.dcr_action |=
11997 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
11998 			}
11999 
12000 			/*
12001 			 * If we have all privs in whatever zone this is,
12002 			 * we can do destructive things to processes which
12003 			 * have altered credentials.
12004 			 */
12005 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12006 			    cr->cr_zone->zone_privset)) {
12007 				state->dts_cred.dcr_action |=
12008 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12009 			}
12010 		}
12011 
12012 		/*
12013 		 * Holding the dtrace_kernel privilege also implies that
12014 		 * the user has the dtrace_user privilege from a visibility
12015 		 * perspective.  But without further privileges, some
12016 		 * destructive actions are not available.
12017 		 */
12018 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
12019 			/*
12020 			 * Make all probes in all zones visible.  However,
12021 			 * this doesn't mean that all actions become available
12022 			 * to all zones.
12023 			 */
12024 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
12025 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
12026 
12027 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
12028 			    DTRACE_CRA_PROC;
12029 			/*
12030 			 * Holding proc_owner means that destructive actions
12031 			 * for *this* zone are allowed.
12032 			 */
12033 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12034 				state->dts_cred.dcr_action |=
12035 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12036 
12037 			/*
12038 			 * Holding proc_zone means that destructive actions
12039 			 * for this user/group ID in all zones is allowed.
12040 			 */
12041 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12042 				state->dts_cred.dcr_action |=
12043 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12044 
12045 			/*
12046 			 * If we have all privs in whatever zone this is,
12047 			 * we can do destructive things to processes which
12048 			 * have altered credentials.
12049 			 */
12050 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12051 			    cr->cr_zone->zone_privset)) {
12052 				state->dts_cred.dcr_action |=
12053 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12054 			}
12055 		}
12056 
12057 		/*
12058 		 * Holding the dtrace_proc privilege gives control over fasttrap
12059 		 * and pid providers.  We need to grant wider destructive
12060 		 * privileges in the event that the user has proc_owner and/or
12061 		 * proc_zone.
12062 		 */
12063 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12064 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12065 				state->dts_cred.dcr_action |=
12066 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12067 
12068 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12069 				state->dts_cred.dcr_action |=
12070 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12071 		}
12072 	}
12073 
12074 	return (state);
12075 }
12076 
12077 static int
12078 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
12079 {
12080 	dtrace_optval_t *opt = state->dts_options, size;
12081 	processorid_t cpu;
12082 	int flags = 0, rval;
12083 
12084 	ASSERT(MUTEX_HELD(&dtrace_lock));
12085 	ASSERT(MUTEX_HELD(&cpu_lock));
12086 	ASSERT(which < DTRACEOPT_MAX);
12087 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
12088 	    (state == dtrace_anon.dta_state &&
12089 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
12090 
12091 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
12092 		return (0);
12093 
12094 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
12095 		cpu = opt[DTRACEOPT_CPU];
12096 
12097 	if (which == DTRACEOPT_SPECSIZE)
12098 		flags |= DTRACEBUF_NOSWITCH;
12099 
12100 	if (which == DTRACEOPT_BUFSIZE) {
12101 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
12102 			flags |= DTRACEBUF_RING;
12103 
12104 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
12105 			flags |= DTRACEBUF_FILL;
12106 
12107 		if (state != dtrace_anon.dta_state ||
12108 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
12109 			flags |= DTRACEBUF_INACTIVE;
12110 	}
12111 
12112 	for (size = opt[which]; size >= sizeof (uint64_t); size >>= 1) {
12113 		/*
12114 		 * The size must be 8-byte aligned.  If the size is not 8-byte
12115 		 * aligned, drop it down by the difference.
12116 		 */
12117 		if (size & (sizeof (uint64_t) - 1))
12118 			size -= size & (sizeof (uint64_t) - 1);
12119 
12120 		if (size < state->dts_reserve) {
12121 			/*
12122 			 * Buffers always must be large enough to accommodate
12123 			 * their prereserved space.  We return E2BIG instead
12124 			 * of ENOMEM in this case to allow for user-level
12125 			 * software to differentiate the cases.
12126 			 */
12127 			return (E2BIG);
12128 		}
12129 
12130 		rval = dtrace_buffer_alloc(buf, size, flags, cpu);
12131 
12132 		if (rval != ENOMEM) {
12133 			opt[which] = size;
12134 			return (rval);
12135 		}
12136 
12137 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12138 			return (rval);
12139 	}
12140 
12141 	return (ENOMEM);
12142 }
12143 
12144 static int
12145 dtrace_state_buffers(dtrace_state_t *state)
12146 {
12147 	dtrace_speculation_t *spec = state->dts_speculations;
12148 	int rval, i;
12149 
12150 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
12151 	    DTRACEOPT_BUFSIZE)) != 0)
12152 		return (rval);
12153 
12154 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
12155 	    DTRACEOPT_AGGSIZE)) != 0)
12156 		return (rval);
12157 
12158 	for (i = 0; i < state->dts_nspeculations; i++) {
12159 		if ((rval = dtrace_state_buffer(state,
12160 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
12161 			return (rval);
12162 	}
12163 
12164 	return (0);
12165 }
12166 
12167 static void
12168 dtrace_state_prereserve(dtrace_state_t *state)
12169 {
12170 	dtrace_ecb_t *ecb;
12171 	dtrace_probe_t *probe;
12172 
12173 	state->dts_reserve = 0;
12174 
12175 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
12176 		return;
12177 
12178 	/*
12179 	 * If our buffer policy is a "fill" buffer policy, we need to set the
12180 	 * prereserved space to be the space required by the END probes.
12181 	 */
12182 	probe = dtrace_probes[dtrace_probeid_end - 1];
12183 	ASSERT(probe != NULL);
12184 
12185 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
12186 		if (ecb->dte_state != state)
12187 			continue;
12188 
12189 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
12190 	}
12191 }
12192 
12193 static int
12194 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
12195 {
12196 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
12197 	dtrace_speculation_t *spec;
12198 	dtrace_buffer_t *buf;
12199 	cyc_handler_t hdlr;
12200 	cyc_time_t when;
12201 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12202 	dtrace_icookie_t cookie;
12203 
12204 	mutex_enter(&cpu_lock);
12205 	mutex_enter(&dtrace_lock);
12206 
12207 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
12208 		rval = EBUSY;
12209 		goto out;
12210 	}
12211 
12212 	/*
12213 	 * Before we can perform any checks, we must prime all of the
12214 	 * retained enablings that correspond to this state.
12215 	 */
12216 	dtrace_enabling_prime(state);
12217 
12218 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
12219 		rval = EACCES;
12220 		goto out;
12221 	}
12222 
12223 	dtrace_state_prereserve(state);
12224 
12225 	/*
12226 	 * Now we want to do is try to allocate our speculations.
12227 	 * We do not automatically resize the number of speculations; if
12228 	 * this fails, we will fail the operation.
12229 	 */
12230 	nspec = opt[DTRACEOPT_NSPEC];
12231 	ASSERT(nspec != DTRACEOPT_UNSET);
12232 
12233 	if (nspec > INT_MAX) {
12234 		rval = ENOMEM;
12235 		goto out;
12236 	}
12237 
12238 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
12239 
12240 	if (spec == NULL) {
12241 		rval = ENOMEM;
12242 		goto out;
12243 	}
12244 
12245 	state->dts_speculations = spec;
12246 	state->dts_nspeculations = (int)nspec;
12247 
12248 	for (i = 0; i < nspec; i++) {
12249 		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
12250 			rval = ENOMEM;
12251 			goto err;
12252 		}
12253 
12254 		spec[i].dtsp_buffer = buf;
12255 	}
12256 
12257 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
12258 		if (dtrace_anon.dta_state == NULL) {
12259 			rval = ENOENT;
12260 			goto out;
12261 		}
12262 
12263 		if (state->dts_necbs != 0) {
12264 			rval = EALREADY;
12265 			goto out;
12266 		}
12267 
12268 		state->dts_anon = dtrace_anon_grab();
12269 		ASSERT(state->dts_anon != NULL);
12270 		state = state->dts_anon;
12271 
12272 		/*
12273 		 * We want "grabanon" to be set in the grabbed state, so we'll
12274 		 * copy that option value from the grabbing state into the
12275 		 * grabbed state.
12276 		 */
12277 		state->dts_options[DTRACEOPT_GRABANON] =
12278 		    opt[DTRACEOPT_GRABANON];
12279 
12280 		*cpu = dtrace_anon.dta_beganon;
12281 
12282 		/*
12283 		 * If the anonymous state is active (as it almost certainly
12284 		 * is if the anonymous enabling ultimately matched anything),
12285 		 * we don't allow any further option processing -- but we
12286 		 * don't return failure.
12287 		 */
12288 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12289 			goto out;
12290 	}
12291 
12292 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
12293 	    opt[DTRACEOPT_AGGSIZE] != 0) {
12294 		if (state->dts_aggregations == NULL) {
12295 			/*
12296 			 * We're not going to create an aggregation buffer
12297 			 * because we don't have any ECBs that contain
12298 			 * aggregations -- set this option to 0.
12299 			 */
12300 			opt[DTRACEOPT_AGGSIZE] = 0;
12301 		} else {
12302 			/*
12303 			 * If we have an aggregation buffer, we must also have
12304 			 * a buffer to use as scratch.
12305 			 */
12306 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
12307 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
12308 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
12309 			}
12310 		}
12311 	}
12312 
12313 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
12314 	    opt[DTRACEOPT_SPECSIZE] != 0) {
12315 		if (!state->dts_speculates) {
12316 			/*
12317 			 * We're not going to create speculation buffers
12318 			 * because we don't have any ECBs that actually
12319 			 * speculate -- set the speculation size to 0.
12320 			 */
12321 			opt[DTRACEOPT_SPECSIZE] = 0;
12322 		}
12323 	}
12324 
12325 	/*
12326 	 * The bare minimum size for any buffer that we're actually going to
12327 	 * do anything to is sizeof (uint64_t).
12328 	 */
12329 	sz = sizeof (uint64_t);
12330 
12331 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
12332 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
12333 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
12334 		/*
12335 		 * A buffer size has been explicitly set to 0 (or to a size
12336 		 * that will be adjusted to 0) and we need the space -- we
12337 		 * need to return failure.  We return ENOSPC to differentiate
12338 		 * it from failing to allocate a buffer due to failure to meet
12339 		 * the reserve (for which we return E2BIG).
12340 		 */
12341 		rval = ENOSPC;
12342 		goto out;
12343 	}
12344 
12345 	if ((rval = dtrace_state_buffers(state)) != 0)
12346 		goto err;
12347 
12348 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
12349 		sz = dtrace_dstate_defsize;
12350 
12351 	do {
12352 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
12353 
12354 		if (rval == 0)
12355 			break;
12356 
12357 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12358 			goto err;
12359 	} while (sz >>= 1);
12360 
12361 	opt[DTRACEOPT_DYNVARSIZE] = sz;
12362 
12363 	if (rval != 0)
12364 		goto err;
12365 
12366 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
12367 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
12368 
12369 	if (opt[DTRACEOPT_CLEANRATE] == 0)
12370 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12371 
12372 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
12373 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
12374 
12375 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
12376 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12377 
12378 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
12379 	hdlr.cyh_arg = state;
12380 	hdlr.cyh_level = CY_LOW_LEVEL;
12381 
12382 	when.cyt_when = 0;
12383 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
12384 
12385 	state->dts_cleaner = cyclic_add(&hdlr, &when);
12386 
12387 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
12388 	hdlr.cyh_arg = state;
12389 	hdlr.cyh_level = CY_LOW_LEVEL;
12390 
12391 	when.cyt_when = 0;
12392 	when.cyt_interval = dtrace_deadman_interval;
12393 
12394 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
12395 	state->dts_deadman = cyclic_add(&hdlr, &when);
12396 
12397 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
12398 
12399 	/*
12400 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
12401 	 * interrupts here both to record the CPU on which we fired the BEGIN
12402 	 * probe (the data from this CPU will be processed first at user
12403 	 * level) and to manually activate the buffer for this CPU.
12404 	 */
12405 	cookie = dtrace_interrupt_disable();
12406 	*cpu = CPU->cpu_id;
12407 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
12408 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12409 
12410 	dtrace_probe(dtrace_probeid_begin,
12411 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
12412 	dtrace_interrupt_enable(cookie);
12413 	/*
12414 	 * We may have had an exit action from a BEGIN probe; only change our
12415 	 * state to ACTIVE if we're still in WARMUP.
12416 	 */
12417 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
12418 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
12419 
12420 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
12421 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
12422 
12423 	/*
12424 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
12425 	 * want each CPU to transition its principal buffer out of the
12426 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
12427 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
12428 	 * atomically transition from processing none of a state's ECBs to
12429 	 * processing all of them.
12430 	 */
12431 	dtrace_xcall(DTRACE_CPUALL,
12432 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
12433 	goto out;
12434 
12435 err:
12436 	dtrace_buffer_free(state->dts_buffer);
12437 	dtrace_buffer_free(state->dts_aggbuffer);
12438 
12439 	if ((nspec = state->dts_nspeculations) == 0) {
12440 		ASSERT(state->dts_speculations == NULL);
12441 		goto out;
12442 	}
12443 
12444 	spec = state->dts_speculations;
12445 	ASSERT(spec != NULL);
12446 
12447 	for (i = 0; i < state->dts_nspeculations; i++) {
12448 		if ((buf = spec[i].dtsp_buffer) == NULL)
12449 			break;
12450 
12451 		dtrace_buffer_free(buf);
12452 		kmem_free(buf, bufsize);
12453 	}
12454 
12455 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
12456 	state->dts_nspeculations = 0;
12457 	state->dts_speculations = NULL;
12458 
12459 out:
12460 	mutex_exit(&dtrace_lock);
12461 	mutex_exit(&cpu_lock);
12462 
12463 	return (rval);
12464 }
12465 
12466 static int
12467 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
12468 {
12469 	dtrace_icookie_t cookie;
12470 
12471 	ASSERT(MUTEX_HELD(&dtrace_lock));
12472 
12473 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
12474 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
12475 		return (EINVAL);
12476 
12477 	/*
12478 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
12479 	 * to be sure that every CPU has seen it.  See below for the details
12480 	 * on why this is done.
12481 	 */
12482 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
12483 	dtrace_sync();
12484 
12485 	/*
12486 	 * By this point, it is impossible for any CPU to be still processing
12487 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
12488 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
12489 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
12490 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
12491 	 * iff we're in the END probe.
12492 	 */
12493 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
12494 	dtrace_sync();
12495 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
12496 
12497 	/*
12498 	 * Finally, we can release the reserve and call the END probe.  We
12499 	 * disable interrupts across calling the END probe to allow us to
12500 	 * return the CPU on which we actually called the END probe.  This
12501 	 * allows user-land to be sure that this CPU's principal buffer is
12502 	 * processed last.
12503 	 */
12504 	state->dts_reserve = 0;
12505 
12506 	cookie = dtrace_interrupt_disable();
12507 	*cpu = CPU->cpu_id;
12508 	dtrace_probe(dtrace_probeid_end,
12509 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
12510 	dtrace_interrupt_enable(cookie);
12511 
12512 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
12513 	dtrace_sync();
12514 
12515 	return (0);
12516 }
12517 
12518 static int
12519 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
12520     dtrace_optval_t val)
12521 {
12522 	ASSERT(MUTEX_HELD(&dtrace_lock));
12523 
12524 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12525 		return (EBUSY);
12526 
12527 	if (option >= DTRACEOPT_MAX)
12528 		return (EINVAL);
12529 
12530 	if (option != DTRACEOPT_CPU && val < 0)
12531 		return (EINVAL);
12532 
12533 	switch (option) {
12534 	case DTRACEOPT_DESTRUCTIVE:
12535 		if (dtrace_destructive_disallow)
12536 			return (EACCES);
12537 
12538 		state->dts_cred.dcr_destructive = 1;
12539 		break;
12540 
12541 	case DTRACEOPT_BUFSIZE:
12542 	case DTRACEOPT_DYNVARSIZE:
12543 	case DTRACEOPT_AGGSIZE:
12544 	case DTRACEOPT_SPECSIZE:
12545 	case DTRACEOPT_STRSIZE:
12546 		if (val < 0)
12547 			return (EINVAL);
12548 
12549 		if (val >= LONG_MAX) {
12550 			/*
12551 			 * If this is an otherwise negative value, set it to
12552 			 * the highest multiple of 128m less than LONG_MAX.
12553 			 * Technically, we're adjusting the size without
12554 			 * regard to the buffer resizing policy, but in fact,
12555 			 * this has no effect -- if we set the buffer size to
12556 			 * ~LONG_MAX and the buffer policy is ultimately set to
12557 			 * be "manual", the buffer allocation is guaranteed to
12558 			 * fail, if only because the allocation requires two
12559 			 * buffers.  (We set the the size to the highest
12560 			 * multiple of 128m because it ensures that the size
12561 			 * will remain a multiple of a megabyte when
12562 			 * repeatedly halved -- all the way down to 15m.)
12563 			 */
12564 			val = LONG_MAX - (1 << 27) + 1;
12565 		}
12566 	}
12567 
12568 	state->dts_options[option] = val;
12569 
12570 	return (0);
12571 }
12572 
12573 static void
12574 dtrace_state_destroy(dtrace_state_t *state)
12575 {
12576 	dtrace_ecb_t *ecb;
12577 	dtrace_vstate_t *vstate = &state->dts_vstate;
12578 	minor_t minor = getminor(state->dts_dev);
12579 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12580 	dtrace_speculation_t *spec = state->dts_speculations;
12581 	int nspec = state->dts_nspeculations;
12582 	uint32_t match;
12583 
12584 	ASSERT(MUTEX_HELD(&dtrace_lock));
12585 	ASSERT(MUTEX_HELD(&cpu_lock));
12586 
12587 	/*
12588 	 * First, retract any retained enablings for this state.
12589 	 */
12590 	dtrace_enabling_retract(state);
12591 	ASSERT(state->dts_nretained == 0);
12592 
12593 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
12594 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
12595 		/*
12596 		 * We have managed to come into dtrace_state_destroy() on a
12597 		 * hot enabling -- almost certainly because of a disorderly
12598 		 * shutdown of a consumer.  (That is, a consumer that is
12599 		 * exiting without having called dtrace_stop().) In this case,
12600 		 * we're going to set our activity to be KILLED, and then
12601 		 * issue a sync to be sure that everyone is out of probe
12602 		 * context before we start blowing away ECBs.
12603 		 */
12604 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
12605 		dtrace_sync();
12606 	}
12607 
12608 	/*
12609 	 * Release the credential hold we took in dtrace_state_create().
12610 	 */
12611 	if (state->dts_cred.dcr_cred != NULL)
12612 		crfree(state->dts_cred.dcr_cred);
12613 
12614 	/*
12615 	 * Now we can safely disable and destroy any enabled probes.  Because
12616 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
12617 	 * (especially if they're all enabled), we take two passes through the
12618 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
12619 	 * in the second we disable whatever is left over.
12620 	 */
12621 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
12622 		for (i = 0; i < state->dts_necbs; i++) {
12623 			if ((ecb = state->dts_ecbs[i]) == NULL)
12624 				continue;
12625 
12626 			if (match && ecb->dte_probe != NULL) {
12627 				dtrace_probe_t *probe = ecb->dte_probe;
12628 				dtrace_provider_t *prov = probe->dtpr_provider;
12629 
12630 				if (!(prov->dtpv_priv.dtpp_flags & match))
12631 					continue;
12632 			}
12633 
12634 			dtrace_ecb_disable(ecb);
12635 			dtrace_ecb_destroy(ecb);
12636 		}
12637 
12638 		if (!match)
12639 			break;
12640 	}
12641 
12642 	/*
12643 	 * Before we free the buffers, perform one more sync to assure that
12644 	 * every CPU is out of probe context.
12645 	 */
12646 	dtrace_sync();
12647 
12648 	dtrace_buffer_free(state->dts_buffer);
12649 	dtrace_buffer_free(state->dts_aggbuffer);
12650 
12651 	for (i = 0; i < nspec; i++)
12652 		dtrace_buffer_free(spec[i].dtsp_buffer);
12653 
12654 	if (state->dts_cleaner != CYCLIC_NONE)
12655 		cyclic_remove(state->dts_cleaner);
12656 
12657 	if (state->dts_deadman != CYCLIC_NONE)
12658 		cyclic_remove(state->dts_deadman);
12659 
12660 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
12661 	dtrace_vstate_fini(vstate);
12662 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
12663 
12664 	if (state->dts_aggregations != NULL) {
12665 #ifdef DEBUG
12666 		for (i = 0; i < state->dts_naggregations; i++)
12667 			ASSERT(state->dts_aggregations[i] == NULL);
12668 #endif
12669 		ASSERT(state->dts_naggregations > 0);
12670 		kmem_free(state->dts_aggregations,
12671 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
12672 	}
12673 
12674 	kmem_free(state->dts_buffer, bufsize);
12675 	kmem_free(state->dts_aggbuffer, bufsize);
12676 
12677 	for (i = 0; i < nspec; i++)
12678 		kmem_free(spec[i].dtsp_buffer, bufsize);
12679 
12680 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
12681 
12682 	dtrace_format_destroy(state);
12683 
12684 	vmem_destroy(state->dts_aggid_arena);
12685 	ddi_soft_state_free(dtrace_softstate, minor);
12686 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12687 }
12688 
12689 /*
12690  * DTrace Anonymous Enabling Functions
12691  */
12692 static dtrace_state_t *
12693 dtrace_anon_grab(void)
12694 {
12695 	dtrace_state_t *state;
12696 
12697 	ASSERT(MUTEX_HELD(&dtrace_lock));
12698 
12699 	if ((state = dtrace_anon.dta_state) == NULL) {
12700 		ASSERT(dtrace_anon.dta_enabling == NULL);
12701 		return (NULL);
12702 	}
12703 
12704 	ASSERT(dtrace_anon.dta_enabling != NULL);
12705 	ASSERT(dtrace_retained != NULL);
12706 
12707 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
12708 	dtrace_anon.dta_enabling = NULL;
12709 	dtrace_anon.dta_state = NULL;
12710 
12711 	return (state);
12712 }
12713 
12714 static void
12715 dtrace_anon_property(void)
12716 {
12717 	int i, rv;
12718 	dtrace_state_t *state;
12719 	dof_hdr_t *dof;
12720 	char c[32];		/* enough for "dof-data-" + digits */
12721 
12722 	ASSERT(MUTEX_HELD(&dtrace_lock));
12723 	ASSERT(MUTEX_HELD(&cpu_lock));
12724 
12725 	for (i = 0; ; i++) {
12726 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
12727 
12728 		dtrace_err_verbose = 1;
12729 
12730 		if ((dof = dtrace_dof_property(c)) == NULL) {
12731 			dtrace_err_verbose = 0;
12732 			break;
12733 		}
12734 
12735 		/*
12736 		 * We want to create anonymous state, so we need to transition
12737 		 * the kernel debugger to indicate that DTrace is active.  If
12738 		 * this fails (e.g. because the debugger has modified text in
12739 		 * some way), we won't continue with the processing.
12740 		 */
12741 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
12742 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
12743 			    "enabling ignored.");
12744 			dtrace_dof_destroy(dof);
12745 			break;
12746 		}
12747 
12748 		/*
12749 		 * If we haven't allocated an anonymous state, we'll do so now.
12750 		 */
12751 		if ((state = dtrace_anon.dta_state) == NULL) {
12752 			state = dtrace_state_create(NULL, NULL);
12753 			dtrace_anon.dta_state = state;
12754 
12755 			if (state == NULL) {
12756 				/*
12757 				 * This basically shouldn't happen:  the only
12758 				 * failure mode from dtrace_state_create() is a
12759 				 * failure of ddi_soft_state_zalloc() that
12760 				 * itself should never happen.  Still, the
12761 				 * interface allows for a failure mode, and
12762 				 * we want to fail as gracefully as possible:
12763 				 * we'll emit an error message and cease
12764 				 * processing anonymous state in this case.
12765 				 */
12766 				cmn_err(CE_WARN, "failed to create "
12767 				    "anonymous state");
12768 				dtrace_dof_destroy(dof);
12769 				break;
12770 			}
12771 		}
12772 
12773 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
12774 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
12775 
12776 		if (rv == 0)
12777 			rv = dtrace_dof_options(dof, state);
12778 
12779 		dtrace_err_verbose = 0;
12780 		dtrace_dof_destroy(dof);
12781 
12782 		if (rv != 0) {
12783 			/*
12784 			 * This is malformed DOF; chuck any anonymous state
12785 			 * that we created.
12786 			 */
12787 			ASSERT(dtrace_anon.dta_enabling == NULL);
12788 			dtrace_state_destroy(state);
12789 			dtrace_anon.dta_state = NULL;
12790 			break;
12791 		}
12792 
12793 		ASSERT(dtrace_anon.dta_enabling != NULL);
12794 	}
12795 
12796 	if (dtrace_anon.dta_enabling != NULL) {
12797 		int rval;
12798 
12799 		/*
12800 		 * dtrace_enabling_retain() can only fail because we are
12801 		 * trying to retain more enablings than are allowed -- but
12802 		 * we only have one anonymous enabling, and we are guaranteed
12803 		 * to be allowed at least one retained enabling; we assert
12804 		 * that dtrace_enabling_retain() returns success.
12805 		 */
12806 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
12807 		ASSERT(rval == 0);
12808 
12809 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
12810 	}
12811 }
12812 
12813 /*
12814  * DTrace Helper Functions
12815  */
12816 static void
12817 dtrace_helper_trace(dtrace_helper_action_t *helper,
12818     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
12819 {
12820 	uint32_t size, next, nnext, i;
12821 	dtrace_helptrace_t *ent;
12822 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12823 
12824 	if (!dtrace_helptrace_enabled)
12825 		return;
12826 
12827 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
12828 
12829 	/*
12830 	 * What would a tracing framework be without its own tracing
12831 	 * framework?  (Well, a hell of a lot simpler, for starters...)
12832 	 */
12833 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
12834 	    sizeof (uint64_t) - sizeof (uint64_t);
12835 
12836 	/*
12837 	 * Iterate until we can allocate a slot in the trace buffer.
12838 	 */
12839 	do {
12840 		next = dtrace_helptrace_next;
12841 
12842 		if (next + size < dtrace_helptrace_bufsize) {
12843 			nnext = next + size;
12844 		} else {
12845 			nnext = size;
12846 		}
12847 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
12848 
12849 	/*
12850 	 * We have our slot; fill it in.
12851 	 */
12852 	if (nnext == size)
12853 		next = 0;
12854 
12855 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
12856 	ent->dtht_helper = helper;
12857 	ent->dtht_where = where;
12858 	ent->dtht_nlocals = vstate->dtvs_nlocals;
12859 
12860 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
12861 	    mstate->dtms_fltoffs : -1;
12862 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
12863 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
12864 
12865 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
12866 		dtrace_statvar_t *svar;
12867 
12868 		if ((svar = vstate->dtvs_locals[i]) == NULL)
12869 			continue;
12870 
12871 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
12872 		ent->dtht_locals[i] =
12873 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
12874 	}
12875 }
12876 
12877 static uint64_t
12878 dtrace_helper(int which, dtrace_mstate_t *mstate,
12879     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
12880 {
12881 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12882 	uint64_t sarg0 = mstate->dtms_arg[0];
12883 	uint64_t sarg1 = mstate->dtms_arg[1];
12884 	uint64_t rval;
12885 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
12886 	dtrace_helper_action_t *helper;
12887 	dtrace_vstate_t *vstate;
12888 	dtrace_difo_t *pred;
12889 	int i, trace = dtrace_helptrace_enabled;
12890 
12891 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
12892 
12893 	if (helpers == NULL)
12894 		return (0);
12895 
12896 	if ((helper = helpers->dthps_actions[which]) == NULL)
12897 		return (0);
12898 
12899 	vstate = &helpers->dthps_vstate;
12900 	mstate->dtms_arg[0] = arg0;
12901 	mstate->dtms_arg[1] = arg1;
12902 
12903 	/*
12904 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
12905 	 * we'll call the corresponding actions.  Note that the below calls
12906 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
12907 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
12908 	 * the stored DIF offset with its own (which is the desired behavior).
12909 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
12910 	 * from machine state; this is okay, too.
12911 	 */
12912 	for (; helper != NULL; helper = helper->dtha_next) {
12913 		if ((pred = helper->dtha_predicate) != NULL) {
12914 			if (trace)
12915 				dtrace_helper_trace(helper, mstate, vstate, 0);
12916 
12917 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
12918 				goto next;
12919 
12920 			if (*flags & CPU_DTRACE_FAULT)
12921 				goto err;
12922 		}
12923 
12924 		for (i = 0; i < helper->dtha_nactions; i++) {
12925 			if (trace)
12926 				dtrace_helper_trace(helper,
12927 				    mstate, vstate, i + 1);
12928 
12929 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
12930 			    mstate, vstate, state);
12931 
12932 			if (*flags & CPU_DTRACE_FAULT)
12933 				goto err;
12934 		}
12935 
12936 next:
12937 		if (trace)
12938 			dtrace_helper_trace(helper, mstate, vstate,
12939 			    DTRACE_HELPTRACE_NEXT);
12940 	}
12941 
12942 	if (trace)
12943 		dtrace_helper_trace(helper, mstate, vstate,
12944 		    DTRACE_HELPTRACE_DONE);
12945 
12946 	/*
12947 	 * Restore the arg0 that we saved upon entry.
12948 	 */
12949 	mstate->dtms_arg[0] = sarg0;
12950 	mstate->dtms_arg[1] = sarg1;
12951 
12952 	return (rval);
12953 
12954 err:
12955 	if (trace)
12956 		dtrace_helper_trace(helper, mstate, vstate,
12957 		    DTRACE_HELPTRACE_ERR);
12958 
12959 	/*
12960 	 * Restore the arg0 that we saved upon entry.
12961 	 */
12962 	mstate->dtms_arg[0] = sarg0;
12963 	mstate->dtms_arg[1] = sarg1;
12964 
12965 	return (NULL);
12966 }
12967 
12968 static void
12969 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
12970     dtrace_vstate_t *vstate)
12971 {
12972 	int i;
12973 
12974 	if (helper->dtha_predicate != NULL)
12975 		dtrace_difo_release(helper->dtha_predicate, vstate);
12976 
12977 	for (i = 0; i < helper->dtha_nactions; i++) {
12978 		ASSERT(helper->dtha_actions[i] != NULL);
12979 		dtrace_difo_release(helper->dtha_actions[i], vstate);
12980 	}
12981 
12982 	kmem_free(helper->dtha_actions,
12983 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
12984 	kmem_free(helper, sizeof (dtrace_helper_action_t));
12985 }
12986 
12987 static int
12988 dtrace_helper_destroygen(int gen)
12989 {
12990 	proc_t *p = curproc;
12991 	dtrace_helpers_t *help = p->p_dtrace_helpers;
12992 	dtrace_vstate_t *vstate;
12993 	int i;
12994 
12995 	ASSERT(MUTEX_HELD(&dtrace_lock));
12996 
12997 	if (help == NULL || gen > help->dthps_generation)
12998 		return (EINVAL);
12999 
13000 	vstate = &help->dthps_vstate;
13001 
13002 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13003 		dtrace_helper_action_t *last = NULL, *h, *next;
13004 
13005 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13006 			next = h->dtha_next;
13007 
13008 			if (h->dtha_generation == gen) {
13009 				if (last != NULL) {
13010 					last->dtha_next = next;
13011 				} else {
13012 					help->dthps_actions[i] = next;
13013 				}
13014 
13015 				dtrace_helper_action_destroy(h, vstate);
13016 			} else {
13017 				last = h;
13018 			}
13019 		}
13020 	}
13021 
13022 	/*
13023 	 * Interate until we've cleared out all helper providers with the
13024 	 * given generation number.
13025 	 */
13026 	for (;;) {
13027 		dtrace_helper_provider_t *prov;
13028 
13029 		/*
13030 		 * Look for a helper provider with the right generation. We
13031 		 * have to start back at the beginning of the list each time
13032 		 * because we drop dtrace_lock. It's unlikely that we'll make
13033 		 * more than two passes.
13034 		 */
13035 		for (i = 0; i < help->dthps_nprovs; i++) {
13036 			prov = help->dthps_provs[i];
13037 
13038 			if (prov->dthp_generation == gen)
13039 				break;
13040 		}
13041 
13042 		/*
13043 		 * If there were no matches, we're done.
13044 		 */
13045 		if (i == help->dthps_nprovs)
13046 			break;
13047 
13048 		/*
13049 		 * Move the last helper provider into this slot.
13050 		 */
13051 		help->dthps_nprovs--;
13052 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
13053 		help->dthps_provs[help->dthps_nprovs] = NULL;
13054 
13055 		mutex_exit(&dtrace_lock);
13056 
13057 		/*
13058 		 * If we have a meta provider, remove this helper provider.
13059 		 */
13060 		mutex_enter(&dtrace_meta_lock);
13061 		if (dtrace_meta_pid != NULL) {
13062 			ASSERT(dtrace_deferred_pid == NULL);
13063 			dtrace_helper_provider_remove(&prov->dthp_prov,
13064 			    p->p_pid);
13065 		}
13066 		mutex_exit(&dtrace_meta_lock);
13067 
13068 		dtrace_helper_provider_destroy(prov);
13069 
13070 		mutex_enter(&dtrace_lock);
13071 	}
13072 
13073 	return (0);
13074 }
13075 
13076 static int
13077 dtrace_helper_validate(dtrace_helper_action_t *helper)
13078 {
13079 	int err = 0, i;
13080 	dtrace_difo_t *dp;
13081 
13082 	if ((dp = helper->dtha_predicate) != NULL)
13083 		err += dtrace_difo_validate_helper(dp);
13084 
13085 	for (i = 0; i < helper->dtha_nactions; i++)
13086 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
13087 
13088 	return (err == 0);
13089 }
13090 
13091 static int
13092 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
13093 {
13094 	dtrace_helpers_t *help;
13095 	dtrace_helper_action_t *helper, *last;
13096 	dtrace_actdesc_t *act;
13097 	dtrace_vstate_t *vstate;
13098 	dtrace_predicate_t *pred;
13099 	int count = 0, nactions = 0, i;
13100 
13101 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
13102 		return (EINVAL);
13103 
13104 	help = curproc->p_dtrace_helpers;
13105 	last = help->dthps_actions[which];
13106 	vstate = &help->dthps_vstate;
13107 
13108 	for (count = 0; last != NULL; last = last->dtha_next) {
13109 		count++;
13110 		if (last->dtha_next == NULL)
13111 			break;
13112 	}
13113 
13114 	/*
13115 	 * If we already have dtrace_helper_actions_max helper actions for this
13116 	 * helper action type, we'll refuse to add a new one.
13117 	 */
13118 	if (count >= dtrace_helper_actions_max)
13119 		return (ENOSPC);
13120 
13121 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
13122 	helper->dtha_generation = help->dthps_generation;
13123 
13124 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
13125 		ASSERT(pred->dtp_difo != NULL);
13126 		dtrace_difo_hold(pred->dtp_difo);
13127 		helper->dtha_predicate = pred->dtp_difo;
13128 	}
13129 
13130 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
13131 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
13132 			goto err;
13133 
13134 		if (act->dtad_difo == NULL)
13135 			goto err;
13136 
13137 		nactions++;
13138 	}
13139 
13140 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
13141 	    (helper->dtha_nactions = nactions), KM_SLEEP);
13142 
13143 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
13144 		dtrace_difo_hold(act->dtad_difo);
13145 		helper->dtha_actions[i++] = act->dtad_difo;
13146 	}
13147 
13148 	if (!dtrace_helper_validate(helper))
13149 		goto err;
13150 
13151 	if (last == NULL) {
13152 		help->dthps_actions[which] = helper;
13153 	} else {
13154 		last->dtha_next = helper;
13155 	}
13156 
13157 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
13158 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
13159 		dtrace_helptrace_next = 0;
13160 	}
13161 
13162 	return (0);
13163 err:
13164 	dtrace_helper_action_destroy(helper, vstate);
13165 	return (EINVAL);
13166 }
13167 
13168 static void
13169 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
13170     dof_helper_t *dofhp)
13171 {
13172 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
13173 
13174 	mutex_enter(&dtrace_meta_lock);
13175 	mutex_enter(&dtrace_lock);
13176 
13177 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
13178 		/*
13179 		 * If the dtrace module is loaded but not attached, or if
13180 		 * there aren't isn't a meta provider registered to deal with
13181 		 * these provider descriptions, we need to postpone creating
13182 		 * the actual providers until later.
13183 		 */
13184 
13185 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
13186 		    dtrace_deferred_pid != help) {
13187 			help->dthps_deferred = 1;
13188 			help->dthps_pid = p->p_pid;
13189 			help->dthps_next = dtrace_deferred_pid;
13190 			help->dthps_prev = NULL;
13191 			if (dtrace_deferred_pid != NULL)
13192 				dtrace_deferred_pid->dthps_prev = help;
13193 			dtrace_deferred_pid = help;
13194 		}
13195 
13196 		mutex_exit(&dtrace_lock);
13197 
13198 	} else if (dofhp != NULL) {
13199 		/*
13200 		 * If the dtrace module is loaded and we have a particular
13201 		 * helper provider description, pass that off to the
13202 		 * meta provider.
13203 		 */
13204 
13205 		mutex_exit(&dtrace_lock);
13206 
13207 		dtrace_helper_provide(dofhp, p->p_pid);
13208 
13209 	} else {
13210 		/*
13211 		 * Otherwise, just pass all the helper provider descriptions
13212 		 * off to the meta provider.
13213 		 */
13214 
13215 		int i;
13216 		mutex_exit(&dtrace_lock);
13217 
13218 		for (i = 0; i < help->dthps_nprovs; i++) {
13219 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
13220 			    p->p_pid);
13221 		}
13222 	}
13223 
13224 	mutex_exit(&dtrace_meta_lock);
13225 }
13226 
13227 static int
13228 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
13229 {
13230 	dtrace_helpers_t *help;
13231 	dtrace_helper_provider_t *hprov, **tmp_provs;
13232 	uint_t tmp_maxprovs, i;
13233 
13234 	ASSERT(MUTEX_HELD(&dtrace_lock));
13235 
13236 	help = curproc->p_dtrace_helpers;
13237 	ASSERT(help != NULL);
13238 
13239 	/*
13240 	 * If we already have dtrace_helper_providers_max helper providers,
13241 	 * we're refuse to add a new one.
13242 	 */
13243 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
13244 		return (ENOSPC);
13245 
13246 	/*
13247 	 * Check to make sure this isn't a duplicate.
13248 	 */
13249 	for (i = 0; i < help->dthps_nprovs; i++) {
13250 		if (dofhp->dofhp_addr ==
13251 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
13252 			return (EALREADY);
13253 	}
13254 
13255 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
13256 	hprov->dthp_prov = *dofhp;
13257 	hprov->dthp_ref = 1;
13258 	hprov->dthp_generation = gen;
13259 
13260 	/*
13261 	 * Allocate a bigger table for helper providers if it's already full.
13262 	 */
13263 	if (help->dthps_maxprovs == help->dthps_nprovs) {
13264 		tmp_maxprovs = help->dthps_maxprovs;
13265 		tmp_provs = help->dthps_provs;
13266 
13267 		if (help->dthps_maxprovs == 0)
13268 			help->dthps_maxprovs = 2;
13269 		else
13270 			help->dthps_maxprovs *= 2;
13271 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
13272 			help->dthps_maxprovs = dtrace_helper_providers_max;
13273 
13274 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
13275 
13276 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
13277 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13278 
13279 		if (tmp_provs != NULL) {
13280 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
13281 			    sizeof (dtrace_helper_provider_t *));
13282 			kmem_free(tmp_provs, tmp_maxprovs *
13283 			    sizeof (dtrace_helper_provider_t *));
13284 		}
13285 	}
13286 
13287 	help->dthps_provs[help->dthps_nprovs] = hprov;
13288 	help->dthps_nprovs++;
13289 
13290 	return (0);
13291 }
13292 
13293 static void
13294 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
13295 {
13296 	mutex_enter(&dtrace_lock);
13297 
13298 	if (--hprov->dthp_ref == 0) {
13299 		dof_hdr_t *dof;
13300 		mutex_exit(&dtrace_lock);
13301 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
13302 		dtrace_dof_destroy(dof);
13303 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
13304 	} else {
13305 		mutex_exit(&dtrace_lock);
13306 	}
13307 }
13308 
13309 static int
13310 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
13311 {
13312 	uintptr_t daddr = (uintptr_t)dof;
13313 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
13314 	dof_provider_t *provider;
13315 	dof_probe_t *probe;
13316 	uint8_t *arg;
13317 	char *strtab, *typestr;
13318 	dof_stridx_t typeidx;
13319 	size_t typesz;
13320 	uint_t nprobes, j, k;
13321 
13322 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
13323 
13324 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
13325 		dtrace_dof_error(dof, "misaligned section offset");
13326 		return (-1);
13327 	}
13328 
13329 	/*
13330 	 * The section needs to be large enough to contain the DOF provider
13331 	 * structure appropriate for the given version.
13332 	 */
13333 	if (sec->dofs_size <
13334 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
13335 	    offsetof(dof_provider_t, dofpv_prenoffs) :
13336 	    sizeof (dof_provider_t))) {
13337 		dtrace_dof_error(dof, "provider section too small");
13338 		return (-1);
13339 	}
13340 
13341 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
13342 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
13343 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
13344 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
13345 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
13346 
13347 	if (str_sec == NULL || prb_sec == NULL ||
13348 	    arg_sec == NULL || off_sec == NULL)
13349 		return (-1);
13350 
13351 	enoff_sec = NULL;
13352 
13353 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13354 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
13355 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
13356 	    provider->dofpv_prenoffs)) == NULL)
13357 		return (-1);
13358 
13359 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
13360 
13361 	if (provider->dofpv_name >= str_sec->dofs_size ||
13362 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
13363 		dtrace_dof_error(dof, "invalid provider name");
13364 		return (-1);
13365 	}
13366 
13367 	if (prb_sec->dofs_entsize == 0 ||
13368 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
13369 		dtrace_dof_error(dof, "invalid entry size");
13370 		return (-1);
13371 	}
13372 
13373 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
13374 		dtrace_dof_error(dof, "misaligned entry size");
13375 		return (-1);
13376 	}
13377 
13378 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
13379 		dtrace_dof_error(dof, "invalid entry size");
13380 		return (-1);
13381 	}
13382 
13383 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
13384 		dtrace_dof_error(dof, "misaligned section offset");
13385 		return (-1);
13386 	}
13387 
13388 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
13389 		dtrace_dof_error(dof, "invalid entry size");
13390 		return (-1);
13391 	}
13392 
13393 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
13394 
13395 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
13396 
13397 	/*
13398 	 * Take a pass through the probes to check for errors.
13399 	 */
13400 	for (j = 0; j < nprobes; j++) {
13401 		probe = (dof_probe_t *)(uintptr_t)(daddr +
13402 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
13403 
13404 		if (probe->dofpr_func >= str_sec->dofs_size) {
13405 			dtrace_dof_error(dof, "invalid function name");
13406 			return (-1);
13407 		}
13408 
13409 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
13410 			dtrace_dof_error(dof, "function name too long");
13411 			return (-1);
13412 		}
13413 
13414 		if (probe->dofpr_name >= str_sec->dofs_size ||
13415 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
13416 			dtrace_dof_error(dof, "invalid probe name");
13417 			return (-1);
13418 		}
13419 
13420 		/*
13421 		 * The offset count must not wrap the index, and the offsets
13422 		 * must also not overflow the section's data.
13423 		 */
13424 		if (probe->dofpr_offidx + probe->dofpr_noffs <
13425 		    probe->dofpr_offidx ||
13426 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
13427 		    off_sec->dofs_entsize > off_sec->dofs_size) {
13428 			dtrace_dof_error(dof, "invalid probe offset");
13429 			return (-1);
13430 		}
13431 
13432 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
13433 			/*
13434 			 * If there's no is-enabled offset section, make sure
13435 			 * there aren't any is-enabled offsets. Otherwise
13436 			 * perform the same checks as for probe offsets
13437 			 * (immediately above).
13438 			 */
13439 			if (enoff_sec == NULL) {
13440 				if (probe->dofpr_enoffidx != 0 ||
13441 				    probe->dofpr_nenoffs != 0) {
13442 					dtrace_dof_error(dof, "is-enabled "
13443 					    "offsets with null section");
13444 					return (-1);
13445 				}
13446 			} else if (probe->dofpr_enoffidx +
13447 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
13448 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
13449 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
13450 				dtrace_dof_error(dof, "invalid is-enabled "
13451 				    "offset");
13452 				return (-1);
13453 			}
13454 
13455 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
13456 				dtrace_dof_error(dof, "zero probe and "
13457 				    "is-enabled offsets");
13458 				return (-1);
13459 			}
13460 		} else if (probe->dofpr_noffs == 0) {
13461 			dtrace_dof_error(dof, "zero probe offsets");
13462 			return (-1);
13463 		}
13464 
13465 		if (probe->dofpr_argidx + probe->dofpr_xargc <
13466 		    probe->dofpr_argidx ||
13467 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
13468 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
13469 			dtrace_dof_error(dof, "invalid args");
13470 			return (-1);
13471 		}
13472 
13473 		typeidx = probe->dofpr_nargv;
13474 		typestr = strtab + probe->dofpr_nargv;
13475 		for (k = 0; k < probe->dofpr_nargc; k++) {
13476 			if (typeidx >= str_sec->dofs_size) {
13477 				dtrace_dof_error(dof, "bad "
13478 				    "native argument type");
13479 				return (-1);
13480 			}
13481 
13482 			typesz = strlen(typestr) + 1;
13483 			if (typesz > DTRACE_ARGTYPELEN) {
13484 				dtrace_dof_error(dof, "native "
13485 				    "argument type too long");
13486 				return (-1);
13487 			}
13488 			typeidx += typesz;
13489 			typestr += typesz;
13490 		}
13491 
13492 		typeidx = probe->dofpr_xargv;
13493 		typestr = strtab + probe->dofpr_xargv;
13494 		for (k = 0; k < probe->dofpr_xargc; k++) {
13495 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
13496 				dtrace_dof_error(dof, "bad "
13497 				    "native argument index");
13498 				return (-1);
13499 			}
13500 
13501 			if (typeidx >= str_sec->dofs_size) {
13502 				dtrace_dof_error(dof, "bad "
13503 				    "translated argument type");
13504 				return (-1);
13505 			}
13506 
13507 			typesz = strlen(typestr) + 1;
13508 			if (typesz > DTRACE_ARGTYPELEN) {
13509 				dtrace_dof_error(dof, "translated argument "
13510 				    "type too long");
13511 				return (-1);
13512 			}
13513 
13514 			typeidx += typesz;
13515 			typestr += typesz;
13516 		}
13517 	}
13518 
13519 	return (0);
13520 }
13521 
13522 static int
13523 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
13524 {
13525 	dtrace_helpers_t *help;
13526 	dtrace_vstate_t *vstate;
13527 	dtrace_enabling_t *enab = NULL;
13528 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
13529 	uintptr_t daddr = (uintptr_t)dof;
13530 
13531 	ASSERT(MUTEX_HELD(&dtrace_lock));
13532 
13533 	if ((help = curproc->p_dtrace_helpers) == NULL)
13534 		help = dtrace_helpers_create(curproc);
13535 
13536 	vstate = &help->dthps_vstate;
13537 
13538 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
13539 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
13540 		dtrace_dof_destroy(dof);
13541 		return (rv);
13542 	}
13543 
13544 	/*
13545 	 * Look for helper providers and validate their descriptions.
13546 	 */
13547 	if (dhp != NULL) {
13548 		for (i = 0; i < dof->dofh_secnum; i++) {
13549 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
13550 			    dof->dofh_secoff + i * dof->dofh_secsize);
13551 
13552 			if (sec->dofs_type != DOF_SECT_PROVIDER)
13553 				continue;
13554 
13555 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
13556 				dtrace_enabling_destroy(enab);
13557 				dtrace_dof_destroy(dof);
13558 				return (-1);
13559 			}
13560 
13561 			nprovs++;
13562 		}
13563 	}
13564 
13565 	/*
13566 	 * Now we need to walk through the ECB descriptions in the enabling.
13567 	 */
13568 	for (i = 0; i < enab->dten_ndesc; i++) {
13569 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
13570 		dtrace_probedesc_t *desc = &ep->dted_probe;
13571 
13572 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
13573 			continue;
13574 
13575 		if (strcmp(desc->dtpd_mod, "helper") != 0)
13576 			continue;
13577 
13578 		if (strcmp(desc->dtpd_func, "ustack") != 0)
13579 			continue;
13580 
13581 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
13582 		    ep)) != 0) {
13583 			/*
13584 			 * Adding this helper action failed -- we are now going
13585 			 * to rip out the entire generation and return failure.
13586 			 */
13587 			(void) dtrace_helper_destroygen(help->dthps_generation);
13588 			dtrace_enabling_destroy(enab);
13589 			dtrace_dof_destroy(dof);
13590 			return (-1);
13591 		}
13592 
13593 		nhelpers++;
13594 	}
13595 
13596 	if (nhelpers < enab->dten_ndesc)
13597 		dtrace_dof_error(dof, "unmatched helpers");
13598 
13599 	gen = help->dthps_generation++;
13600 	dtrace_enabling_destroy(enab);
13601 
13602 	if (dhp != NULL && nprovs > 0) {
13603 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
13604 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
13605 			mutex_exit(&dtrace_lock);
13606 			dtrace_helper_provider_register(curproc, help, dhp);
13607 			mutex_enter(&dtrace_lock);
13608 
13609 			destroy = 0;
13610 		}
13611 	}
13612 
13613 	if (destroy)
13614 		dtrace_dof_destroy(dof);
13615 
13616 	return (gen);
13617 }
13618 
13619 static dtrace_helpers_t *
13620 dtrace_helpers_create(proc_t *p)
13621 {
13622 	dtrace_helpers_t *help;
13623 
13624 	ASSERT(MUTEX_HELD(&dtrace_lock));
13625 	ASSERT(p->p_dtrace_helpers == NULL);
13626 
13627 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
13628 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
13629 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
13630 
13631 	p->p_dtrace_helpers = help;
13632 	dtrace_helpers++;
13633 
13634 	return (help);
13635 }
13636 
13637 static void
13638 dtrace_helpers_destroy(void)
13639 {
13640 	dtrace_helpers_t *help;
13641 	dtrace_vstate_t *vstate;
13642 	proc_t *p = curproc;
13643 	int i;
13644 
13645 	mutex_enter(&dtrace_lock);
13646 
13647 	ASSERT(p->p_dtrace_helpers != NULL);
13648 	ASSERT(dtrace_helpers > 0);
13649 
13650 	help = p->p_dtrace_helpers;
13651 	vstate = &help->dthps_vstate;
13652 
13653 	/*
13654 	 * We're now going to lose the help from this process.
13655 	 */
13656 	p->p_dtrace_helpers = NULL;
13657 	dtrace_sync();
13658 
13659 	/*
13660 	 * Destory the helper actions.
13661 	 */
13662 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13663 		dtrace_helper_action_t *h, *next;
13664 
13665 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13666 			next = h->dtha_next;
13667 			dtrace_helper_action_destroy(h, vstate);
13668 			h = next;
13669 		}
13670 	}
13671 
13672 	mutex_exit(&dtrace_lock);
13673 
13674 	/*
13675 	 * Destroy the helper providers.
13676 	 */
13677 	if (help->dthps_maxprovs > 0) {
13678 		mutex_enter(&dtrace_meta_lock);
13679 		if (dtrace_meta_pid != NULL) {
13680 			ASSERT(dtrace_deferred_pid == NULL);
13681 
13682 			for (i = 0; i < help->dthps_nprovs; i++) {
13683 				dtrace_helper_provider_remove(
13684 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
13685 			}
13686 		} else {
13687 			mutex_enter(&dtrace_lock);
13688 			ASSERT(help->dthps_deferred == 0 ||
13689 			    help->dthps_next != NULL ||
13690 			    help->dthps_prev != NULL ||
13691 			    help == dtrace_deferred_pid);
13692 
13693 			/*
13694 			 * Remove the helper from the deferred list.
13695 			 */
13696 			if (help->dthps_next != NULL)
13697 				help->dthps_next->dthps_prev = help->dthps_prev;
13698 			if (help->dthps_prev != NULL)
13699 				help->dthps_prev->dthps_next = help->dthps_next;
13700 			if (dtrace_deferred_pid == help) {
13701 				dtrace_deferred_pid = help->dthps_next;
13702 				ASSERT(help->dthps_prev == NULL);
13703 			}
13704 
13705 			mutex_exit(&dtrace_lock);
13706 		}
13707 
13708 		mutex_exit(&dtrace_meta_lock);
13709 
13710 		for (i = 0; i < help->dthps_nprovs; i++) {
13711 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
13712 		}
13713 
13714 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
13715 		    sizeof (dtrace_helper_provider_t *));
13716 	}
13717 
13718 	mutex_enter(&dtrace_lock);
13719 
13720 	dtrace_vstate_fini(&help->dthps_vstate);
13721 	kmem_free(help->dthps_actions,
13722 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
13723 	kmem_free(help, sizeof (dtrace_helpers_t));
13724 
13725 	--dtrace_helpers;
13726 	mutex_exit(&dtrace_lock);
13727 }
13728 
13729 static void
13730 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
13731 {
13732 	dtrace_helpers_t *help, *newhelp;
13733 	dtrace_helper_action_t *helper, *new, *last;
13734 	dtrace_difo_t *dp;
13735 	dtrace_vstate_t *vstate;
13736 	int i, j, sz, hasprovs = 0;
13737 
13738 	mutex_enter(&dtrace_lock);
13739 	ASSERT(from->p_dtrace_helpers != NULL);
13740 	ASSERT(dtrace_helpers > 0);
13741 
13742 	help = from->p_dtrace_helpers;
13743 	newhelp = dtrace_helpers_create(to);
13744 	ASSERT(to->p_dtrace_helpers != NULL);
13745 
13746 	newhelp->dthps_generation = help->dthps_generation;
13747 	vstate = &newhelp->dthps_vstate;
13748 
13749 	/*
13750 	 * Duplicate the helper actions.
13751 	 */
13752 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13753 		if ((helper = help->dthps_actions[i]) == NULL)
13754 			continue;
13755 
13756 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
13757 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
13758 			    KM_SLEEP);
13759 			new->dtha_generation = helper->dtha_generation;
13760 
13761 			if ((dp = helper->dtha_predicate) != NULL) {
13762 				dp = dtrace_difo_duplicate(dp, vstate);
13763 				new->dtha_predicate = dp;
13764 			}
13765 
13766 			new->dtha_nactions = helper->dtha_nactions;
13767 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
13768 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
13769 
13770 			for (j = 0; j < new->dtha_nactions; j++) {
13771 				dtrace_difo_t *dp = helper->dtha_actions[j];
13772 
13773 				ASSERT(dp != NULL);
13774 				dp = dtrace_difo_duplicate(dp, vstate);
13775 				new->dtha_actions[j] = dp;
13776 			}
13777 
13778 			if (last != NULL) {
13779 				last->dtha_next = new;
13780 			} else {
13781 				newhelp->dthps_actions[i] = new;
13782 			}
13783 
13784 			last = new;
13785 		}
13786 	}
13787 
13788 	/*
13789 	 * Duplicate the helper providers and register them with the
13790 	 * DTrace framework.
13791 	 */
13792 	if (help->dthps_nprovs > 0) {
13793 		newhelp->dthps_nprovs = help->dthps_nprovs;
13794 		newhelp->dthps_maxprovs = help->dthps_nprovs;
13795 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
13796 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13797 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
13798 			newhelp->dthps_provs[i] = help->dthps_provs[i];
13799 			newhelp->dthps_provs[i]->dthp_ref++;
13800 		}
13801 
13802 		hasprovs = 1;
13803 	}
13804 
13805 	mutex_exit(&dtrace_lock);
13806 
13807 	if (hasprovs)
13808 		dtrace_helper_provider_register(to, newhelp, NULL);
13809 }
13810 
13811 /*
13812  * DTrace Hook Functions
13813  */
13814 static void
13815 dtrace_module_loaded(struct modctl *ctl)
13816 {
13817 	dtrace_provider_t *prv;
13818 
13819 	mutex_enter(&dtrace_provider_lock);
13820 	mutex_enter(&mod_lock);
13821 
13822 	ASSERT(ctl->mod_busy);
13823 
13824 	/*
13825 	 * We're going to call each providers per-module provide operation
13826 	 * specifying only this module.
13827 	 */
13828 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
13829 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
13830 
13831 	mutex_exit(&mod_lock);
13832 	mutex_exit(&dtrace_provider_lock);
13833 
13834 	/*
13835 	 * If we have any retained enablings, we need to match against them.
13836 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
13837 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
13838 	 * module.  (In particular, this happens when loading scheduling
13839 	 * classes.)  So if we have any retained enablings, we need to dispatch
13840 	 * our task queue to do the match for us.
13841 	 */
13842 	mutex_enter(&dtrace_lock);
13843 
13844 	if (dtrace_retained == NULL) {
13845 		mutex_exit(&dtrace_lock);
13846 		return;
13847 	}
13848 
13849 	(void) taskq_dispatch(dtrace_taskq,
13850 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
13851 
13852 	mutex_exit(&dtrace_lock);
13853 
13854 	/*
13855 	 * And now, for a little heuristic sleaze:  in general, we want to
13856 	 * match modules as soon as they load.  However, we cannot guarantee
13857 	 * this, because it would lead us to the lock ordering violation
13858 	 * outlined above.  The common case, of course, is that cpu_lock is
13859 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
13860 	 * long enough for the task queue to do its work.  If it's not, it's
13861 	 * not a serious problem -- it just means that the module that we
13862 	 * just loaded may not be immediately instrumentable.
13863 	 */
13864 	delay(1);
13865 }
13866 
13867 static void
13868 dtrace_module_unloaded(struct modctl *ctl)
13869 {
13870 	dtrace_probe_t template, *probe, *first, *next;
13871 	dtrace_provider_t *prov;
13872 
13873 	template.dtpr_mod = ctl->mod_modname;
13874 
13875 	mutex_enter(&dtrace_provider_lock);
13876 	mutex_enter(&mod_lock);
13877 	mutex_enter(&dtrace_lock);
13878 
13879 	if (dtrace_bymod == NULL) {
13880 		/*
13881 		 * The DTrace module is loaded (obviously) but not attached;
13882 		 * we don't have any work to do.
13883 		 */
13884 		mutex_exit(&dtrace_provider_lock);
13885 		mutex_exit(&mod_lock);
13886 		mutex_exit(&dtrace_lock);
13887 		return;
13888 	}
13889 
13890 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
13891 	    probe != NULL; probe = probe->dtpr_nextmod) {
13892 		if (probe->dtpr_ecb != NULL) {
13893 			mutex_exit(&dtrace_provider_lock);
13894 			mutex_exit(&mod_lock);
13895 			mutex_exit(&dtrace_lock);
13896 
13897 			/*
13898 			 * This shouldn't _actually_ be possible -- we're
13899 			 * unloading a module that has an enabled probe in it.
13900 			 * (It's normally up to the provider to make sure that
13901 			 * this can't happen.)  However, because dtps_enable()
13902 			 * doesn't have a failure mode, there can be an
13903 			 * enable/unload race.  Upshot:  we don't want to
13904 			 * assert, but we're not going to disable the
13905 			 * probe, either.
13906 			 */
13907 			if (dtrace_err_verbose) {
13908 				cmn_err(CE_WARN, "unloaded module '%s' had "
13909 				    "enabled probes", ctl->mod_modname);
13910 			}
13911 
13912 			return;
13913 		}
13914 	}
13915 
13916 	probe = first;
13917 
13918 	for (first = NULL; probe != NULL; probe = next) {
13919 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
13920 
13921 		dtrace_probes[probe->dtpr_id - 1] = NULL;
13922 
13923 		next = probe->dtpr_nextmod;
13924 		dtrace_hash_remove(dtrace_bymod, probe);
13925 		dtrace_hash_remove(dtrace_byfunc, probe);
13926 		dtrace_hash_remove(dtrace_byname, probe);
13927 
13928 		if (first == NULL) {
13929 			first = probe;
13930 			probe->dtpr_nextmod = NULL;
13931 		} else {
13932 			probe->dtpr_nextmod = first;
13933 			first = probe;
13934 		}
13935 	}
13936 
13937 	/*
13938 	 * We've removed all of the module's probes from the hash chains and
13939 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
13940 	 * everyone has cleared out from any probe array processing.
13941 	 */
13942 	dtrace_sync();
13943 
13944 	for (probe = first; probe != NULL; probe = first) {
13945 		first = probe->dtpr_nextmod;
13946 		prov = probe->dtpr_provider;
13947 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
13948 		    probe->dtpr_arg);
13949 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
13950 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
13951 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
13952 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
13953 		kmem_free(probe, sizeof (dtrace_probe_t));
13954 	}
13955 
13956 	mutex_exit(&dtrace_lock);
13957 	mutex_exit(&mod_lock);
13958 	mutex_exit(&dtrace_provider_lock);
13959 }
13960 
13961 void
13962 dtrace_suspend(void)
13963 {
13964 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
13965 }
13966 
13967 void
13968 dtrace_resume(void)
13969 {
13970 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
13971 }
13972 
13973 static int
13974 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
13975 {
13976 	ASSERT(MUTEX_HELD(&cpu_lock));
13977 	mutex_enter(&dtrace_lock);
13978 
13979 	switch (what) {
13980 	case CPU_CONFIG: {
13981 		dtrace_state_t *state;
13982 		dtrace_optval_t *opt, rs, c;
13983 
13984 		/*
13985 		 * For now, we only allocate a new buffer for anonymous state.
13986 		 */
13987 		if ((state = dtrace_anon.dta_state) == NULL)
13988 			break;
13989 
13990 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13991 			break;
13992 
13993 		opt = state->dts_options;
13994 		c = opt[DTRACEOPT_CPU];
13995 
13996 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
13997 			break;
13998 
13999 		/*
14000 		 * Regardless of what the actual policy is, we're going to
14001 		 * temporarily set our resize policy to be manual.  We're
14002 		 * also going to temporarily set our CPU option to denote
14003 		 * the newly configured CPU.
14004 		 */
14005 		rs = opt[DTRACEOPT_BUFRESIZE];
14006 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
14007 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
14008 
14009 		(void) dtrace_state_buffers(state);
14010 
14011 		opt[DTRACEOPT_BUFRESIZE] = rs;
14012 		opt[DTRACEOPT_CPU] = c;
14013 
14014 		break;
14015 	}
14016 
14017 	case CPU_UNCONFIG:
14018 		/*
14019 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
14020 		 * buffer will be freed when the consumer exits.)
14021 		 */
14022 		break;
14023 
14024 	default:
14025 		break;
14026 	}
14027 
14028 	mutex_exit(&dtrace_lock);
14029 	return (0);
14030 }
14031 
14032 static void
14033 dtrace_cpu_setup_initial(processorid_t cpu)
14034 {
14035 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
14036 }
14037 
14038 static void
14039 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
14040 {
14041 	if (dtrace_toxranges >= dtrace_toxranges_max) {
14042 		int osize, nsize;
14043 		dtrace_toxrange_t *range;
14044 
14045 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14046 
14047 		if (osize == 0) {
14048 			ASSERT(dtrace_toxrange == NULL);
14049 			ASSERT(dtrace_toxranges_max == 0);
14050 			dtrace_toxranges_max = 1;
14051 		} else {
14052 			dtrace_toxranges_max <<= 1;
14053 		}
14054 
14055 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14056 		range = kmem_zalloc(nsize, KM_SLEEP);
14057 
14058 		if (dtrace_toxrange != NULL) {
14059 			ASSERT(osize != 0);
14060 			bcopy(dtrace_toxrange, range, osize);
14061 			kmem_free(dtrace_toxrange, osize);
14062 		}
14063 
14064 		dtrace_toxrange = range;
14065 	}
14066 
14067 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
14068 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
14069 
14070 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
14071 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
14072 	dtrace_toxranges++;
14073 }
14074 
14075 /*
14076  * DTrace Driver Cookbook Functions
14077  */
14078 /*ARGSUSED*/
14079 static int
14080 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
14081 {
14082 	dtrace_provider_id_t id;
14083 	dtrace_state_t *state = NULL;
14084 	dtrace_enabling_t *enab;
14085 
14086 	mutex_enter(&cpu_lock);
14087 	mutex_enter(&dtrace_provider_lock);
14088 	mutex_enter(&dtrace_lock);
14089 
14090 	if (ddi_soft_state_init(&dtrace_softstate,
14091 	    sizeof (dtrace_state_t), 0) != 0) {
14092 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
14093 		mutex_exit(&cpu_lock);
14094 		mutex_exit(&dtrace_provider_lock);
14095 		mutex_exit(&dtrace_lock);
14096 		return (DDI_FAILURE);
14097 	}
14098 
14099 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
14100 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
14101 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
14102 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
14103 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
14104 		ddi_remove_minor_node(devi, NULL);
14105 		ddi_soft_state_fini(&dtrace_softstate);
14106 		mutex_exit(&cpu_lock);
14107 		mutex_exit(&dtrace_provider_lock);
14108 		mutex_exit(&dtrace_lock);
14109 		return (DDI_FAILURE);
14110 	}
14111 
14112 	ddi_report_dev(devi);
14113 	dtrace_devi = devi;
14114 
14115 	dtrace_modload = dtrace_module_loaded;
14116 	dtrace_modunload = dtrace_module_unloaded;
14117 	dtrace_cpu_init = dtrace_cpu_setup_initial;
14118 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
14119 	dtrace_helpers_fork = dtrace_helpers_duplicate;
14120 	dtrace_cpustart_init = dtrace_suspend;
14121 	dtrace_cpustart_fini = dtrace_resume;
14122 	dtrace_debugger_init = dtrace_suspend;
14123 	dtrace_debugger_fini = dtrace_resume;
14124 	dtrace_kreloc_init = dtrace_suspend;
14125 	dtrace_kreloc_fini = dtrace_resume;
14126 
14127 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
14128 
14129 	ASSERT(MUTEX_HELD(&cpu_lock));
14130 
14131 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
14132 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14133 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
14134 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
14135 	    VM_SLEEP | VMC_IDENTIFIER);
14136 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
14137 	    1, INT_MAX, 0);
14138 
14139 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
14140 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
14141 	    NULL, NULL, NULL, NULL, NULL, 0);
14142 
14143 	ASSERT(MUTEX_HELD(&cpu_lock));
14144 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
14145 	    offsetof(dtrace_probe_t, dtpr_nextmod),
14146 	    offsetof(dtrace_probe_t, dtpr_prevmod));
14147 
14148 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
14149 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
14150 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
14151 
14152 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
14153 	    offsetof(dtrace_probe_t, dtpr_nextname),
14154 	    offsetof(dtrace_probe_t, dtpr_prevname));
14155 
14156 	if (dtrace_retain_max < 1) {
14157 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
14158 		    "setting to 1", dtrace_retain_max);
14159 		dtrace_retain_max = 1;
14160 	}
14161 
14162 	/*
14163 	 * Now discover our toxic ranges.
14164 	 */
14165 	dtrace_toxic_ranges(dtrace_toxrange_add);
14166 
14167 	/*
14168 	 * Before we register ourselves as a provider to our own framework,
14169 	 * we would like to assert that dtrace_provider is NULL -- but that's
14170 	 * not true if we were loaded as a dependency of a DTrace provider.
14171 	 * Once we've registered, we can assert that dtrace_provider is our
14172 	 * pseudo provider.
14173 	 */
14174 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
14175 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
14176 
14177 	ASSERT(dtrace_provider != NULL);
14178 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
14179 
14180 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
14181 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
14182 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
14183 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
14184 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
14185 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
14186 
14187 	dtrace_anon_property();
14188 	mutex_exit(&cpu_lock);
14189 
14190 	/*
14191 	 * If DTrace helper tracing is enabled, we need to allocate the
14192 	 * trace buffer and initialize the values.
14193 	 */
14194 	if (dtrace_helptrace_enabled) {
14195 		ASSERT(dtrace_helptrace_buffer == NULL);
14196 		dtrace_helptrace_buffer =
14197 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
14198 		dtrace_helptrace_next = 0;
14199 	}
14200 
14201 	/*
14202 	 * If there are already providers, we must ask them to provide their
14203 	 * probes, and then match any anonymous enabling against them.  Note
14204 	 * that there should be no other retained enablings at this time:
14205 	 * the only retained enablings at this time should be the anonymous
14206 	 * enabling.
14207 	 */
14208 	if (dtrace_anon.dta_enabling != NULL) {
14209 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
14210 
14211 		dtrace_enabling_provide(NULL);
14212 		state = dtrace_anon.dta_state;
14213 
14214 		/*
14215 		 * We couldn't hold cpu_lock across the above call to
14216 		 * dtrace_enabling_provide(), but we must hold it to actually
14217 		 * enable the probes.  We have to drop all of our locks, pick
14218 		 * up cpu_lock, and regain our locks before matching the
14219 		 * retained anonymous enabling.
14220 		 */
14221 		mutex_exit(&dtrace_lock);
14222 		mutex_exit(&dtrace_provider_lock);
14223 
14224 		mutex_enter(&cpu_lock);
14225 		mutex_enter(&dtrace_provider_lock);
14226 		mutex_enter(&dtrace_lock);
14227 
14228 		if ((enab = dtrace_anon.dta_enabling) != NULL)
14229 			(void) dtrace_enabling_match(enab, NULL);
14230 
14231 		mutex_exit(&cpu_lock);
14232 	}
14233 
14234 	mutex_exit(&dtrace_lock);
14235 	mutex_exit(&dtrace_provider_lock);
14236 
14237 	if (state != NULL) {
14238 		/*
14239 		 * If we created any anonymous state, set it going now.
14240 		 */
14241 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
14242 	}
14243 
14244 	return (DDI_SUCCESS);
14245 }
14246 
14247 /*ARGSUSED*/
14248 static int
14249 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
14250 {
14251 	dtrace_state_t *state;
14252 	uint32_t priv;
14253 	uid_t uid;
14254 	zoneid_t zoneid;
14255 
14256 	if (getminor(*devp) == DTRACEMNRN_HELPER)
14257 		return (0);
14258 
14259 	/*
14260 	 * If this wasn't an open with the "helper" minor, then it must be
14261 	 * the "dtrace" minor.
14262 	 */
14263 	ASSERT(getminor(*devp) == DTRACEMNRN_DTRACE);
14264 
14265 	/*
14266 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
14267 	 * caller lacks sufficient permission to do anything with DTrace.
14268 	 */
14269 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
14270 	if (priv == DTRACE_PRIV_NONE)
14271 		return (EACCES);
14272 
14273 	/*
14274 	 * Ask all providers to provide all their probes.
14275 	 */
14276 	mutex_enter(&dtrace_provider_lock);
14277 	dtrace_probe_provide(NULL, NULL);
14278 	mutex_exit(&dtrace_provider_lock);
14279 
14280 	mutex_enter(&cpu_lock);
14281 	mutex_enter(&dtrace_lock);
14282 	dtrace_opens++;
14283 	dtrace_membar_producer();
14284 
14285 	/*
14286 	 * If the kernel debugger is active (that is, if the kernel debugger
14287 	 * modified text in some way), we won't allow the open.
14288 	 */
14289 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14290 		dtrace_opens--;
14291 		mutex_exit(&cpu_lock);
14292 		mutex_exit(&dtrace_lock);
14293 		return (EBUSY);
14294 	}
14295 
14296 	state = dtrace_state_create(devp, cred_p);
14297 	mutex_exit(&cpu_lock);
14298 
14299 	if (state == NULL) {
14300 		if (--dtrace_opens == 0)
14301 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14302 		mutex_exit(&dtrace_lock);
14303 		return (EAGAIN);
14304 	}
14305 
14306 	mutex_exit(&dtrace_lock);
14307 
14308 	return (0);
14309 }
14310 
14311 /*ARGSUSED*/
14312 static int
14313 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
14314 {
14315 	minor_t minor = getminor(dev);
14316 	dtrace_state_t *state;
14317 
14318 	if (minor == DTRACEMNRN_HELPER)
14319 		return (0);
14320 
14321 	state = ddi_get_soft_state(dtrace_softstate, minor);
14322 
14323 	mutex_enter(&cpu_lock);
14324 	mutex_enter(&dtrace_lock);
14325 
14326 	if (state->dts_anon) {
14327 		/*
14328 		 * There is anonymous state. Destroy that first.
14329 		 */
14330 		ASSERT(dtrace_anon.dta_state == NULL);
14331 		dtrace_state_destroy(state->dts_anon);
14332 	}
14333 
14334 	dtrace_state_destroy(state);
14335 	ASSERT(dtrace_opens > 0);
14336 	if (--dtrace_opens == 0)
14337 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14338 
14339 	mutex_exit(&dtrace_lock);
14340 	mutex_exit(&cpu_lock);
14341 
14342 	return (0);
14343 }
14344 
14345 /*ARGSUSED*/
14346 static int
14347 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
14348 {
14349 	int rval;
14350 	dof_helper_t help, *dhp = NULL;
14351 
14352 	switch (cmd) {
14353 	case DTRACEHIOC_ADDDOF:
14354 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
14355 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
14356 			return (EFAULT);
14357 		}
14358 
14359 		dhp = &help;
14360 		arg = (intptr_t)help.dofhp_dof;
14361 		/*FALLTHROUGH*/
14362 
14363 	case DTRACEHIOC_ADD: {
14364 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
14365 
14366 		if (dof == NULL)
14367 			return (rval);
14368 
14369 		mutex_enter(&dtrace_lock);
14370 
14371 		/*
14372 		 * dtrace_helper_slurp() takes responsibility for the dof --
14373 		 * it may free it now or it may save it and free it later.
14374 		 */
14375 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
14376 			*rv = rval;
14377 			rval = 0;
14378 		} else {
14379 			rval = EINVAL;
14380 		}
14381 
14382 		mutex_exit(&dtrace_lock);
14383 		return (rval);
14384 	}
14385 
14386 	case DTRACEHIOC_REMOVE: {
14387 		mutex_enter(&dtrace_lock);
14388 		rval = dtrace_helper_destroygen(arg);
14389 		mutex_exit(&dtrace_lock);
14390 
14391 		return (rval);
14392 	}
14393 
14394 	default:
14395 		break;
14396 	}
14397 
14398 	return (ENOTTY);
14399 }
14400 
14401 /*ARGSUSED*/
14402 static int
14403 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
14404 {
14405 	minor_t minor = getminor(dev);
14406 	dtrace_state_t *state;
14407 	int rval;
14408 
14409 	if (minor == DTRACEMNRN_HELPER)
14410 		return (dtrace_ioctl_helper(cmd, arg, rv));
14411 
14412 	state = ddi_get_soft_state(dtrace_softstate, minor);
14413 
14414 	if (state->dts_anon) {
14415 		ASSERT(dtrace_anon.dta_state == NULL);
14416 		state = state->dts_anon;
14417 	}
14418 
14419 	switch (cmd) {
14420 	case DTRACEIOC_PROVIDER: {
14421 		dtrace_providerdesc_t pvd;
14422 		dtrace_provider_t *pvp;
14423 
14424 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
14425 			return (EFAULT);
14426 
14427 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
14428 		mutex_enter(&dtrace_provider_lock);
14429 
14430 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
14431 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
14432 				break;
14433 		}
14434 
14435 		mutex_exit(&dtrace_provider_lock);
14436 
14437 		if (pvp == NULL)
14438 			return (ESRCH);
14439 
14440 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
14441 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
14442 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
14443 			return (EFAULT);
14444 
14445 		return (0);
14446 	}
14447 
14448 	case DTRACEIOC_EPROBE: {
14449 		dtrace_eprobedesc_t epdesc;
14450 		dtrace_ecb_t *ecb;
14451 		dtrace_action_t *act;
14452 		void *buf;
14453 		size_t size;
14454 		uintptr_t dest;
14455 		int nrecs;
14456 
14457 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
14458 			return (EFAULT);
14459 
14460 		mutex_enter(&dtrace_lock);
14461 
14462 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
14463 			mutex_exit(&dtrace_lock);
14464 			return (EINVAL);
14465 		}
14466 
14467 		if (ecb->dte_probe == NULL) {
14468 			mutex_exit(&dtrace_lock);
14469 			return (EINVAL);
14470 		}
14471 
14472 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
14473 		epdesc.dtepd_uarg = ecb->dte_uarg;
14474 		epdesc.dtepd_size = ecb->dte_size;
14475 
14476 		nrecs = epdesc.dtepd_nrecs;
14477 		epdesc.dtepd_nrecs = 0;
14478 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
14479 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
14480 				continue;
14481 
14482 			epdesc.dtepd_nrecs++;
14483 		}
14484 
14485 		/*
14486 		 * Now that we have the size, we need to allocate a temporary
14487 		 * buffer in which to store the complete description.  We need
14488 		 * the temporary buffer to be able to drop dtrace_lock()
14489 		 * across the copyout(), below.
14490 		 */
14491 		size = sizeof (dtrace_eprobedesc_t) +
14492 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
14493 
14494 		buf = kmem_alloc(size, KM_SLEEP);
14495 		dest = (uintptr_t)buf;
14496 
14497 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
14498 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
14499 
14500 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
14501 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
14502 				continue;
14503 
14504 			if (nrecs-- == 0)
14505 				break;
14506 
14507 			bcopy(&act->dta_rec, (void *)dest,
14508 			    sizeof (dtrace_recdesc_t));
14509 			dest += sizeof (dtrace_recdesc_t);
14510 		}
14511 
14512 		mutex_exit(&dtrace_lock);
14513 
14514 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
14515 			kmem_free(buf, size);
14516 			return (EFAULT);
14517 		}
14518 
14519 		kmem_free(buf, size);
14520 		return (0);
14521 	}
14522 
14523 	case DTRACEIOC_AGGDESC: {
14524 		dtrace_aggdesc_t aggdesc;
14525 		dtrace_action_t *act;
14526 		dtrace_aggregation_t *agg;
14527 		int nrecs;
14528 		uint32_t offs;
14529 		dtrace_recdesc_t *lrec;
14530 		void *buf;
14531 		size_t size;
14532 		uintptr_t dest;
14533 
14534 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
14535 			return (EFAULT);
14536 
14537 		mutex_enter(&dtrace_lock);
14538 
14539 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
14540 			mutex_exit(&dtrace_lock);
14541 			return (EINVAL);
14542 		}
14543 
14544 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
14545 
14546 		nrecs = aggdesc.dtagd_nrecs;
14547 		aggdesc.dtagd_nrecs = 0;
14548 
14549 		offs = agg->dtag_base;
14550 		lrec = &agg->dtag_action.dta_rec;
14551 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
14552 
14553 		for (act = agg->dtag_first; ; act = act->dta_next) {
14554 			ASSERT(act->dta_intuple ||
14555 			    DTRACEACT_ISAGG(act->dta_kind));
14556 
14557 			/*
14558 			 * If this action has a record size of zero, it
14559 			 * denotes an argument to the aggregating action.
14560 			 * Because the presence of this record doesn't (or
14561 			 * shouldn't) affect the way the data is interpreted,
14562 			 * we don't copy it out to save user-level the
14563 			 * confusion of dealing with a zero-length record.
14564 			 */
14565 			if (act->dta_rec.dtrd_size == 0) {
14566 				ASSERT(agg->dtag_hasarg);
14567 				continue;
14568 			}
14569 
14570 			aggdesc.dtagd_nrecs++;
14571 
14572 			if (act == &agg->dtag_action)
14573 				break;
14574 		}
14575 
14576 		/*
14577 		 * Now that we have the size, we need to allocate a temporary
14578 		 * buffer in which to store the complete description.  We need
14579 		 * the temporary buffer to be able to drop dtrace_lock()
14580 		 * across the copyout(), below.
14581 		 */
14582 		size = sizeof (dtrace_aggdesc_t) +
14583 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
14584 
14585 		buf = kmem_alloc(size, KM_SLEEP);
14586 		dest = (uintptr_t)buf;
14587 
14588 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
14589 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
14590 
14591 		for (act = agg->dtag_first; ; act = act->dta_next) {
14592 			dtrace_recdesc_t rec = act->dta_rec;
14593 
14594 			/*
14595 			 * See the comment in the above loop for why we pass
14596 			 * over zero-length records.
14597 			 */
14598 			if (rec.dtrd_size == 0) {
14599 				ASSERT(agg->dtag_hasarg);
14600 				continue;
14601 			}
14602 
14603 			if (nrecs-- == 0)
14604 				break;
14605 
14606 			rec.dtrd_offset -= offs;
14607 			bcopy(&rec, (void *)dest, sizeof (rec));
14608 			dest += sizeof (dtrace_recdesc_t);
14609 
14610 			if (act == &agg->dtag_action)
14611 				break;
14612 		}
14613 
14614 		mutex_exit(&dtrace_lock);
14615 
14616 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
14617 			kmem_free(buf, size);
14618 			return (EFAULT);
14619 		}
14620 
14621 		kmem_free(buf, size);
14622 		return (0);
14623 	}
14624 
14625 	case DTRACEIOC_ENABLE: {
14626 		dof_hdr_t *dof;
14627 		dtrace_enabling_t *enab = NULL;
14628 		dtrace_vstate_t *vstate;
14629 		int err = 0;
14630 
14631 		*rv = 0;
14632 
14633 		/*
14634 		 * If a NULL argument has been passed, we take this as our
14635 		 * cue to reevaluate our enablings.
14636 		 */
14637 		if (arg == NULL) {
14638 			mutex_enter(&cpu_lock);
14639 			mutex_enter(&dtrace_lock);
14640 			err = dtrace_enabling_matchstate(state, rv);
14641 			mutex_exit(&dtrace_lock);
14642 			mutex_exit(&cpu_lock);
14643 
14644 			return (err);
14645 		}
14646 
14647 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
14648 			return (rval);
14649 
14650 		mutex_enter(&cpu_lock);
14651 		mutex_enter(&dtrace_lock);
14652 		vstate = &state->dts_vstate;
14653 
14654 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14655 			mutex_exit(&dtrace_lock);
14656 			mutex_exit(&cpu_lock);
14657 			dtrace_dof_destroy(dof);
14658 			return (EBUSY);
14659 		}
14660 
14661 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
14662 			mutex_exit(&dtrace_lock);
14663 			mutex_exit(&cpu_lock);
14664 			dtrace_dof_destroy(dof);
14665 			return (EINVAL);
14666 		}
14667 
14668 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
14669 			dtrace_enabling_destroy(enab);
14670 			mutex_exit(&dtrace_lock);
14671 			mutex_exit(&cpu_lock);
14672 			dtrace_dof_destroy(dof);
14673 			return (rval);
14674 		}
14675 
14676 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
14677 			err = dtrace_enabling_retain(enab);
14678 		} else {
14679 			dtrace_enabling_destroy(enab);
14680 		}
14681 
14682 		mutex_exit(&cpu_lock);
14683 		mutex_exit(&dtrace_lock);
14684 		dtrace_dof_destroy(dof);
14685 
14686 		return (err);
14687 	}
14688 
14689 	case DTRACEIOC_REPLICATE: {
14690 		dtrace_repldesc_t desc;
14691 		dtrace_probedesc_t *match = &desc.dtrpd_match;
14692 		dtrace_probedesc_t *create = &desc.dtrpd_create;
14693 		int err;
14694 
14695 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14696 			return (EFAULT);
14697 
14698 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14699 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14700 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14701 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14702 
14703 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14704 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14705 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14706 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14707 
14708 		mutex_enter(&dtrace_lock);
14709 		err = dtrace_enabling_replicate(state, match, create);
14710 		mutex_exit(&dtrace_lock);
14711 
14712 		return (err);
14713 	}
14714 
14715 	case DTRACEIOC_PROBEMATCH:
14716 	case DTRACEIOC_PROBES: {
14717 		dtrace_probe_t *probe = NULL;
14718 		dtrace_probedesc_t desc;
14719 		dtrace_probekey_t pkey;
14720 		dtrace_id_t i;
14721 		int m = 0;
14722 		uint32_t priv;
14723 		uid_t uid;
14724 		zoneid_t zoneid;
14725 
14726 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14727 			return (EFAULT);
14728 
14729 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14730 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14731 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14732 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14733 
14734 		/*
14735 		 * Before we attempt to match this probe, we want to give
14736 		 * all providers the opportunity to provide it.
14737 		 */
14738 		if (desc.dtpd_id == DTRACE_IDNONE) {
14739 			mutex_enter(&dtrace_provider_lock);
14740 			dtrace_probe_provide(&desc, NULL);
14741 			mutex_exit(&dtrace_provider_lock);
14742 			desc.dtpd_id++;
14743 		}
14744 
14745 		if (cmd == DTRACEIOC_PROBEMATCH)  {
14746 			dtrace_probekey(&desc, &pkey);
14747 			pkey.dtpk_id = DTRACE_IDNONE;
14748 		}
14749 
14750 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
14751 
14752 		mutex_enter(&dtrace_lock);
14753 
14754 		if (cmd == DTRACEIOC_PROBEMATCH) {
14755 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14756 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14757 				    (m = dtrace_match_probe(probe, &pkey,
14758 				    priv, uid, zoneid)) != 0)
14759 					break;
14760 			}
14761 
14762 			if (m < 0) {
14763 				mutex_exit(&dtrace_lock);
14764 				return (EINVAL);
14765 			}
14766 
14767 		} else {
14768 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14769 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14770 				    dtrace_match_priv(probe, priv, uid, zoneid))
14771 					break;
14772 			}
14773 		}
14774 
14775 		if (probe == NULL) {
14776 			mutex_exit(&dtrace_lock);
14777 			return (ESRCH);
14778 		}
14779 
14780 		dtrace_probe_description(probe, &desc);
14781 		mutex_exit(&dtrace_lock);
14782 
14783 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14784 			return (EFAULT);
14785 
14786 		return (0);
14787 	}
14788 
14789 	case DTRACEIOC_PROBEARG: {
14790 		dtrace_argdesc_t desc;
14791 		dtrace_probe_t *probe;
14792 		dtrace_provider_t *prov;
14793 
14794 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14795 			return (EFAULT);
14796 
14797 		if (desc.dtargd_id == DTRACE_IDNONE)
14798 			return (EINVAL);
14799 
14800 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
14801 			return (EINVAL);
14802 
14803 		mutex_enter(&dtrace_provider_lock);
14804 		mutex_enter(&mod_lock);
14805 		mutex_enter(&dtrace_lock);
14806 
14807 		if (desc.dtargd_id > dtrace_nprobes) {
14808 			mutex_exit(&dtrace_lock);
14809 			mutex_exit(&mod_lock);
14810 			mutex_exit(&dtrace_provider_lock);
14811 			return (EINVAL);
14812 		}
14813 
14814 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
14815 			mutex_exit(&dtrace_lock);
14816 			mutex_exit(&mod_lock);
14817 			mutex_exit(&dtrace_provider_lock);
14818 			return (EINVAL);
14819 		}
14820 
14821 		mutex_exit(&dtrace_lock);
14822 
14823 		prov = probe->dtpr_provider;
14824 
14825 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
14826 			/*
14827 			 * There isn't any typed information for this probe.
14828 			 * Set the argument number to DTRACE_ARGNONE.
14829 			 */
14830 			desc.dtargd_ndx = DTRACE_ARGNONE;
14831 		} else {
14832 			desc.dtargd_native[0] = '\0';
14833 			desc.dtargd_xlate[0] = '\0';
14834 			desc.dtargd_mapping = desc.dtargd_ndx;
14835 
14836 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
14837 			    probe->dtpr_id, probe->dtpr_arg, &desc);
14838 		}
14839 
14840 		mutex_exit(&mod_lock);
14841 		mutex_exit(&dtrace_provider_lock);
14842 
14843 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14844 			return (EFAULT);
14845 
14846 		return (0);
14847 	}
14848 
14849 	case DTRACEIOC_GO: {
14850 		processorid_t cpuid;
14851 		rval = dtrace_state_go(state, &cpuid);
14852 
14853 		if (rval != 0)
14854 			return (rval);
14855 
14856 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14857 			return (EFAULT);
14858 
14859 		return (0);
14860 	}
14861 
14862 	case DTRACEIOC_STOP: {
14863 		processorid_t cpuid;
14864 
14865 		mutex_enter(&dtrace_lock);
14866 		rval = dtrace_state_stop(state, &cpuid);
14867 		mutex_exit(&dtrace_lock);
14868 
14869 		if (rval != 0)
14870 			return (rval);
14871 
14872 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14873 			return (EFAULT);
14874 
14875 		return (0);
14876 	}
14877 
14878 	case DTRACEIOC_DOFGET: {
14879 		dof_hdr_t hdr, *dof;
14880 		uint64_t len;
14881 
14882 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
14883 			return (EFAULT);
14884 
14885 		mutex_enter(&dtrace_lock);
14886 		dof = dtrace_dof_create(state);
14887 		mutex_exit(&dtrace_lock);
14888 
14889 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
14890 		rval = copyout(dof, (void *)arg, len);
14891 		dtrace_dof_destroy(dof);
14892 
14893 		return (rval == 0 ? 0 : EFAULT);
14894 	}
14895 
14896 	case DTRACEIOC_AGGSNAP:
14897 	case DTRACEIOC_BUFSNAP: {
14898 		dtrace_bufdesc_t desc;
14899 		caddr_t cached;
14900 		dtrace_buffer_t *buf;
14901 
14902 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14903 			return (EFAULT);
14904 
14905 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
14906 			return (EINVAL);
14907 
14908 		mutex_enter(&dtrace_lock);
14909 
14910 		if (cmd == DTRACEIOC_BUFSNAP) {
14911 			buf = &state->dts_buffer[desc.dtbd_cpu];
14912 		} else {
14913 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
14914 		}
14915 
14916 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
14917 			size_t sz = buf->dtb_offset;
14918 
14919 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
14920 				mutex_exit(&dtrace_lock);
14921 				return (EBUSY);
14922 			}
14923 
14924 			/*
14925 			 * If this buffer has already been consumed, we're
14926 			 * going to indicate that there's nothing left here
14927 			 * to consume.
14928 			 */
14929 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
14930 				mutex_exit(&dtrace_lock);
14931 
14932 				desc.dtbd_size = 0;
14933 				desc.dtbd_drops = 0;
14934 				desc.dtbd_errors = 0;
14935 				desc.dtbd_oldest = 0;
14936 				sz = sizeof (desc);
14937 
14938 				if (copyout(&desc, (void *)arg, sz) != 0)
14939 					return (EFAULT);
14940 
14941 				return (0);
14942 			}
14943 
14944 			/*
14945 			 * If this is a ring buffer that has wrapped, we want
14946 			 * to copy the whole thing out.
14947 			 */
14948 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
14949 				dtrace_buffer_polish(buf);
14950 				sz = buf->dtb_size;
14951 			}
14952 
14953 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
14954 				mutex_exit(&dtrace_lock);
14955 				return (EFAULT);
14956 			}
14957 
14958 			desc.dtbd_size = sz;
14959 			desc.dtbd_drops = buf->dtb_drops;
14960 			desc.dtbd_errors = buf->dtb_errors;
14961 			desc.dtbd_oldest = buf->dtb_xamot_offset;
14962 
14963 			mutex_exit(&dtrace_lock);
14964 
14965 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14966 				return (EFAULT);
14967 
14968 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
14969 
14970 			return (0);
14971 		}
14972 
14973 		if (buf->dtb_tomax == NULL) {
14974 			ASSERT(buf->dtb_xamot == NULL);
14975 			mutex_exit(&dtrace_lock);
14976 			return (ENOENT);
14977 		}
14978 
14979 		cached = buf->dtb_tomax;
14980 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
14981 
14982 		dtrace_xcall(desc.dtbd_cpu,
14983 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
14984 
14985 		state->dts_errors += buf->dtb_xamot_errors;
14986 
14987 		/*
14988 		 * If the buffers did not actually switch, then the cross call
14989 		 * did not take place -- presumably because the given CPU is
14990 		 * not in the ready set.  If this is the case, we'll return
14991 		 * ENOENT.
14992 		 */
14993 		if (buf->dtb_tomax == cached) {
14994 			ASSERT(buf->dtb_xamot != cached);
14995 			mutex_exit(&dtrace_lock);
14996 			return (ENOENT);
14997 		}
14998 
14999 		ASSERT(cached == buf->dtb_xamot);
15000 
15001 		/*
15002 		 * We have our snapshot; now copy it out.
15003 		 */
15004 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
15005 		    buf->dtb_xamot_offset) != 0) {
15006 			mutex_exit(&dtrace_lock);
15007 			return (EFAULT);
15008 		}
15009 
15010 		desc.dtbd_size = buf->dtb_xamot_offset;
15011 		desc.dtbd_drops = buf->dtb_xamot_drops;
15012 		desc.dtbd_errors = buf->dtb_xamot_errors;
15013 		desc.dtbd_oldest = 0;
15014 
15015 		mutex_exit(&dtrace_lock);
15016 
15017 		/*
15018 		 * Finally, copy out the buffer description.
15019 		 */
15020 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15021 			return (EFAULT);
15022 
15023 		return (0);
15024 	}
15025 
15026 	case DTRACEIOC_CONF: {
15027 		dtrace_conf_t conf;
15028 
15029 		bzero(&conf, sizeof (conf));
15030 		conf.dtc_difversion = DIF_VERSION;
15031 		conf.dtc_difintregs = DIF_DIR_NREGS;
15032 		conf.dtc_diftupregs = DIF_DTR_NREGS;
15033 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
15034 
15035 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
15036 			return (EFAULT);
15037 
15038 		return (0);
15039 	}
15040 
15041 	case DTRACEIOC_STATUS: {
15042 		dtrace_status_t stat;
15043 		dtrace_dstate_t *dstate;
15044 		int i, j;
15045 		uint64_t nerrs;
15046 
15047 		/*
15048 		 * See the comment in dtrace_state_deadman() for the reason
15049 		 * for setting dts_laststatus to INT64_MAX before setting
15050 		 * it to the correct value.
15051 		 */
15052 		state->dts_laststatus = INT64_MAX;
15053 		dtrace_membar_producer();
15054 		state->dts_laststatus = dtrace_gethrtime();
15055 
15056 		bzero(&stat, sizeof (stat));
15057 
15058 		mutex_enter(&dtrace_lock);
15059 
15060 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
15061 			mutex_exit(&dtrace_lock);
15062 			return (ENOENT);
15063 		}
15064 
15065 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
15066 			stat.dtst_exiting = 1;
15067 
15068 		nerrs = state->dts_errors;
15069 		dstate = &state->dts_vstate.dtvs_dynvars;
15070 
15071 		for (i = 0; i < NCPU; i++) {
15072 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
15073 
15074 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
15075 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
15076 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
15077 
15078 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
15079 				stat.dtst_filled++;
15080 
15081 			nerrs += state->dts_buffer[i].dtb_errors;
15082 
15083 			for (j = 0; j < state->dts_nspeculations; j++) {
15084 				dtrace_speculation_t *spec;
15085 				dtrace_buffer_t *buf;
15086 
15087 				spec = &state->dts_speculations[j];
15088 				buf = &spec->dtsp_buffer[i];
15089 				stat.dtst_specdrops += buf->dtb_xamot_drops;
15090 			}
15091 		}
15092 
15093 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
15094 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
15095 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
15096 		stat.dtst_dblerrors = state->dts_dblerrors;
15097 		stat.dtst_killed =
15098 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
15099 		stat.dtst_errors = nerrs;
15100 
15101 		mutex_exit(&dtrace_lock);
15102 
15103 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
15104 			return (EFAULT);
15105 
15106 		return (0);
15107 	}
15108 
15109 	case DTRACEIOC_FORMAT: {
15110 		dtrace_fmtdesc_t fmt;
15111 		char *str;
15112 		int len;
15113 
15114 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
15115 			return (EFAULT);
15116 
15117 		mutex_enter(&dtrace_lock);
15118 
15119 		if (fmt.dtfd_format == 0 ||
15120 		    fmt.dtfd_format > state->dts_nformats) {
15121 			mutex_exit(&dtrace_lock);
15122 			return (EINVAL);
15123 		}
15124 
15125 		/*
15126 		 * Format strings are allocated contiguously and they are
15127 		 * never freed; if a format index is less than the number
15128 		 * of formats, we can assert that the format map is non-NULL
15129 		 * and that the format for the specified index is non-NULL.
15130 		 */
15131 		ASSERT(state->dts_formats != NULL);
15132 		str = state->dts_formats[fmt.dtfd_format - 1];
15133 		ASSERT(str != NULL);
15134 
15135 		len = strlen(str) + 1;
15136 
15137 		if (len > fmt.dtfd_length) {
15138 			fmt.dtfd_length = len;
15139 
15140 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
15141 				mutex_exit(&dtrace_lock);
15142 				return (EINVAL);
15143 			}
15144 		} else {
15145 			if (copyout(str, fmt.dtfd_string, len) != 0) {
15146 				mutex_exit(&dtrace_lock);
15147 				return (EINVAL);
15148 			}
15149 		}
15150 
15151 		mutex_exit(&dtrace_lock);
15152 		return (0);
15153 	}
15154 
15155 	default:
15156 		break;
15157 	}
15158 
15159 	return (ENOTTY);
15160 }
15161 
15162 /*ARGSUSED*/
15163 static int
15164 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
15165 {
15166 	dtrace_state_t *state;
15167 
15168 	switch (cmd) {
15169 	case DDI_DETACH:
15170 		break;
15171 
15172 	case DDI_SUSPEND:
15173 		return (DDI_SUCCESS);
15174 
15175 	default:
15176 		return (DDI_FAILURE);
15177 	}
15178 
15179 	mutex_enter(&cpu_lock);
15180 	mutex_enter(&dtrace_provider_lock);
15181 	mutex_enter(&dtrace_lock);
15182 
15183 	ASSERT(dtrace_opens == 0);
15184 
15185 	if (dtrace_helpers > 0) {
15186 		mutex_exit(&dtrace_provider_lock);
15187 		mutex_exit(&dtrace_lock);
15188 		mutex_exit(&cpu_lock);
15189 		return (DDI_FAILURE);
15190 	}
15191 
15192 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
15193 		mutex_exit(&dtrace_provider_lock);
15194 		mutex_exit(&dtrace_lock);
15195 		mutex_exit(&cpu_lock);
15196 		return (DDI_FAILURE);
15197 	}
15198 
15199 	dtrace_provider = NULL;
15200 
15201 	if ((state = dtrace_anon_grab()) != NULL) {
15202 		/*
15203 		 * If there were ECBs on this state, the provider should
15204 		 * have not been allowed to detach; assert that there is
15205 		 * none.
15206 		 */
15207 		ASSERT(state->dts_necbs == 0);
15208 		dtrace_state_destroy(state);
15209 
15210 		/*
15211 		 * If we're being detached with anonymous state, we need to
15212 		 * indicate to the kernel debugger that DTrace is now inactive.
15213 		 */
15214 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15215 	}
15216 
15217 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
15218 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15219 	dtrace_cpu_init = NULL;
15220 	dtrace_helpers_cleanup = NULL;
15221 	dtrace_helpers_fork = NULL;
15222 	dtrace_cpustart_init = NULL;
15223 	dtrace_cpustart_fini = NULL;
15224 	dtrace_debugger_init = NULL;
15225 	dtrace_debugger_fini = NULL;
15226 	dtrace_kreloc_init = NULL;
15227 	dtrace_kreloc_fini = NULL;
15228 	dtrace_modload = NULL;
15229 	dtrace_modunload = NULL;
15230 
15231 	mutex_exit(&cpu_lock);
15232 
15233 	if (dtrace_helptrace_enabled) {
15234 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
15235 		dtrace_helptrace_buffer = NULL;
15236 	}
15237 
15238 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
15239 	dtrace_probes = NULL;
15240 	dtrace_nprobes = 0;
15241 
15242 	dtrace_hash_destroy(dtrace_bymod);
15243 	dtrace_hash_destroy(dtrace_byfunc);
15244 	dtrace_hash_destroy(dtrace_byname);
15245 	dtrace_bymod = NULL;
15246 	dtrace_byfunc = NULL;
15247 	dtrace_byname = NULL;
15248 
15249 	kmem_cache_destroy(dtrace_state_cache);
15250 	vmem_destroy(dtrace_minor);
15251 	vmem_destroy(dtrace_arena);
15252 
15253 	if (dtrace_toxrange != NULL) {
15254 		kmem_free(dtrace_toxrange,
15255 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
15256 		dtrace_toxrange = NULL;
15257 		dtrace_toxranges = 0;
15258 		dtrace_toxranges_max = 0;
15259 	}
15260 
15261 	ddi_remove_minor_node(dtrace_devi, NULL);
15262 	dtrace_devi = NULL;
15263 
15264 	ddi_soft_state_fini(&dtrace_softstate);
15265 
15266 	ASSERT(dtrace_vtime_references == 0);
15267 	ASSERT(dtrace_opens == 0);
15268 	ASSERT(dtrace_retained == NULL);
15269 
15270 	mutex_exit(&dtrace_lock);
15271 	mutex_exit(&dtrace_provider_lock);
15272 
15273 	/*
15274 	 * We don't destroy the task queue until after we have dropped our
15275 	 * locks (taskq_destroy() may block on running tasks).  To prevent
15276 	 * attempting to do work after we have effectively detached but before
15277 	 * the task queue has been destroyed, all tasks dispatched via the
15278 	 * task queue must check that DTrace is still attached before
15279 	 * performing any operation.
15280 	 */
15281 	taskq_destroy(dtrace_taskq);
15282 	dtrace_taskq = NULL;
15283 
15284 	return (DDI_SUCCESS);
15285 }
15286 
15287 /*ARGSUSED*/
15288 static int
15289 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
15290 {
15291 	int error;
15292 
15293 	switch (infocmd) {
15294 	case DDI_INFO_DEVT2DEVINFO:
15295 		*result = (void *)dtrace_devi;
15296 		error = DDI_SUCCESS;
15297 		break;
15298 	case DDI_INFO_DEVT2INSTANCE:
15299 		*result = (void *)0;
15300 		error = DDI_SUCCESS;
15301 		break;
15302 	default:
15303 		error = DDI_FAILURE;
15304 	}
15305 	return (error);
15306 }
15307 
15308 static struct cb_ops dtrace_cb_ops = {
15309 	dtrace_open,		/* open */
15310 	dtrace_close,		/* close */
15311 	nulldev,		/* strategy */
15312 	nulldev,		/* print */
15313 	nodev,			/* dump */
15314 	nodev,			/* read */
15315 	nodev,			/* write */
15316 	dtrace_ioctl,		/* ioctl */
15317 	nodev,			/* devmap */
15318 	nodev,			/* mmap */
15319 	nodev,			/* segmap */
15320 	nochpoll,		/* poll */
15321 	ddi_prop_op,		/* cb_prop_op */
15322 	0,			/* streamtab  */
15323 	D_NEW | D_MP		/* Driver compatibility flag */
15324 };
15325 
15326 static struct dev_ops dtrace_ops = {
15327 	DEVO_REV,		/* devo_rev */
15328 	0,			/* refcnt */
15329 	dtrace_info,		/* get_dev_info */
15330 	nulldev,		/* identify */
15331 	nulldev,		/* probe */
15332 	dtrace_attach,		/* attach */
15333 	dtrace_detach,		/* detach */
15334 	nodev,			/* reset */
15335 	&dtrace_cb_ops,		/* driver operations */
15336 	NULL,			/* bus operations */
15337 	nodev			/* dev power */
15338 };
15339 
15340 static struct modldrv modldrv = {
15341 	&mod_driverops,		/* module type (this is a pseudo driver) */
15342 	"Dynamic Tracing",	/* name of module */
15343 	&dtrace_ops,		/* driver ops */
15344 };
15345 
15346 static struct modlinkage modlinkage = {
15347 	MODREV_1,
15348 	(void *)&modldrv,
15349 	NULL
15350 };
15351 
15352 int
15353 _init(void)
15354 {
15355 	return (mod_install(&modlinkage));
15356 }
15357 
15358 int
15359 _info(struct modinfo *modinfop)
15360 {
15361 	return (mod_info(&modlinkage, modinfop));
15362 }
15363 
15364 int
15365 _fini(void)
15366 {
15367 	return (mod_remove(&modlinkage));
15368 }
15369