xref: /titanic_54/usr/src/uts/common/dtrace/dtrace.c (revision 1ea5f93d6265bec480d4d5f9640ddffbfcd03df1)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, Joyent, Inc. All rights reserved.
25  */
26 
27 /*
28  * DTrace - Dynamic Tracing for Solaris
29  *
30  * This is the implementation of the Solaris Dynamic Tracing framework
31  * (DTrace).  The user-visible interface to DTrace is described at length in
32  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
33  * library, the in-kernel DTrace framework, and the DTrace providers are
34  * described in the block comments in the <sys/dtrace.h> header file.  The
35  * internal architecture of DTrace is described in the block comments in the
36  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
37  * implementation very much assume mastery of all of these sources; if one has
38  * an unanswered question about the implementation, one should consult them
39  * first.
40  *
41  * The functions here are ordered roughly as follows:
42  *
43  *   - Probe context functions
44  *   - Probe hashing functions
45  *   - Non-probe context utility functions
46  *   - Matching functions
47  *   - Provider-to-Framework API functions
48  *   - Probe management functions
49  *   - DIF object functions
50  *   - Format functions
51  *   - Predicate functions
52  *   - ECB functions
53  *   - Buffer functions
54  *   - Enabling functions
55  *   - DOF functions
56  *   - Anonymous enabling functions
57  *   - Consumer state functions
58  *   - Helper functions
59  *   - Hook functions
60  *   - Driver cookbook functions
61  *
62  * Each group of functions begins with a block comment labelled the "DTrace
63  * [Group] Functions", allowing one to find each block by searching forward
64  * on capital-f functions.
65  */
66 #include <sys/errno.h>
67 #include <sys/stat.h>
68 #include <sys/modctl.h>
69 #include <sys/conf.h>
70 #include <sys/systm.h>
71 #include <sys/ddi.h>
72 #include <sys/sunddi.h>
73 #include <sys/cpuvar.h>
74 #include <sys/kmem.h>
75 #include <sys/strsubr.h>
76 #include <sys/sysmacros.h>
77 #include <sys/dtrace_impl.h>
78 #include <sys/atomic.h>
79 #include <sys/cmn_err.h>
80 #include <sys/mutex_impl.h>
81 #include <sys/rwlock_impl.h>
82 #include <sys/ctf_api.h>
83 #include <sys/panic.h>
84 #include <sys/priv_impl.h>
85 #include <sys/policy.h>
86 #include <sys/cred_impl.h>
87 #include <sys/procfs_isa.h>
88 #include <sys/taskq.h>
89 #include <sys/mkdev.h>
90 #include <sys/kdi.h>
91 #include <sys/zone.h>
92 #include <sys/socket.h>
93 #include <netinet/in.h>
94 
95 /*
96  * DTrace Tunable Variables
97  *
98  * The following variables may be tuned by adding a line to /etc/system that
99  * includes both the name of the DTrace module ("dtrace") and the name of the
100  * variable.  For example:
101  *
102  *   set dtrace:dtrace_destructive_disallow = 1
103  *
104  * In general, the only variables that one should be tuning this way are those
105  * that affect system-wide DTrace behavior, and for which the default behavior
106  * is undesirable.  Most of these variables are tunable on a per-consumer
107  * basis using DTrace options, and need not be tuned on a system-wide basis.
108  * When tuning these variables, avoid pathological values; while some attempt
109  * is made to verify the integrity of these variables, they are not considered
110  * part of the supported interface to DTrace, and they are therefore not
111  * checked comprehensively.  Further, these variables should not be tuned
112  * dynamically via "mdb -kw" or other means; they should only be tuned via
113  * /etc/system.
114  */
115 int		dtrace_destructive_disallow = 0;
116 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
117 size_t		dtrace_difo_maxsize = (256 * 1024);
118 dtrace_optval_t	dtrace_dof_maxsize = (256 * 1024);
119 size_t		dtrace_global_maxsize = (16 * 1024);
120 size_t		dtrace_actions_max = (16 * 1024);
121 size_t		dtrace_retain_max = 1024;
122 dtrace_optval_t	dtrace_helper_actions_max = 32;
123 dtrace_optval_t	dtrace_helper_providers_max = 32;
124 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
125 size_t		dtrace_strsize_default = 256;
126 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
127 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
128 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
129 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
130 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
131 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
132 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
133 dtrace_optval_t	dtrace_nspec_default = 1;
134 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
135 dtrace_optval_t dtrace_stackframes_default = 20;
136 dtrace_optval_t dtrace_ustackframes_default = 20;
137 dtrace_optval_t dtrace_jstackframes_default = 50;
138 dtrace_optval_t dtrace_jstackstrsize_default = 512;
139 int		dtrace_msgdsize_max = 128;
140 hrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
141 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
142 int		dtrace_devdepth_max = 32;
143 int		dtrace_err_verbose;
144 hrtime_t	dtrace_deadman_interval = NANOSEC;
145 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
146 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
147 hrtime_t	dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
148 
149 /*
150  * DTrace External Variables
151  *
152  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
153  * available to DTrace consumers via the backtick (`) syntax.  One of these,
154  * dtrace_zero, is made deliberately so:  it is provided as a source of
155  * well-known, zero-filled memory.  While this variable is not documented,
156  * it is used by some translators as an implementation detail.
157  */
158 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
159 
160 /*
161  * DTrace Internal Variables
162  */
163 static dev_info_t	*dtrace_devi;		/* device info */
164 static vmem_t		*dtrace_arena;		/* probe ID arena */
165 static vmem_t		*dtrace_minor;		/* minor number arena */
166 static taskq_t		*dtrace_taskq;		/* task queue */
167 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
168 static int		dtrace_nprobes;		/* number of probes */
169 static dtrace_provider_t *dtrace_provider;	/* provider list */
170 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
171 static int		dtrace_opens;		/* number of opens */
172 static int		dtrace_helpers;		/* number of helpers */
173 static void		*dtrace_softstate;	/* softstate pointer */
174 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
175 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
176 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
177 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
178 static int		dtrace_toxranges;	/* number of toxic ranges */
179 static int		dtrace_toxranges_max;	/* size of toxic range array */
180 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
181 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
182 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
183 static kthread_t	*dtrace_panicked;	/* panicking thread */
184 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
185 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
186 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
187 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
188 static dtrace_genid_t	dtrace_retained_gen;	/* current retained enab gen */
189 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
190 static int		dtrace_dynvar_failclean; /* dynvars failed to clean */
191 
192 /*
193  * DTrace Locking
194  * DTrace is protected by three (relatively coarse-grained) locks:
195  *
196  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
197  *     including enabling state, probes, ECBs, consumer state, helper state,
198  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
199  *     probe context is lock-free -- synchronization is handled via the
200  *     dtrace_sync() cross call mechanism.
201  *
202  * (2) dtrace_provider_lock is required when manipulating provider state, or
203  *     when provider state must be held constant.
204  *
205  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
206  *     when meta provider state must be held constant.
207  *
208  * The lock ordering between these three locks is dtrace_meta_lock before
209  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
210  * several places where dtrace_provider_lock is held by the framework as it
211  * calls into the providers -- which then call back into the framework,
212  * grabbing dtrace_lock.)
213  *
214  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
215  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
216  * role as a coarse-grained lock; it is acquired before both of these locks.
217  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
218  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
219  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
220  * acquired _between_ dtrace_provider_lock and dtrace_lock.
221  */
222 static kmutex_t		dtrace_lock;		/* probe state lock */
223 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
224 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
225 
226 /*
227  * DTrace Provider Variables
228  *
229  * These are the variables relating to DTrace as a provider (that is, the
230  * provider of the BEGIN, END, and ERROR probes).
231  */
232 static dtrace_pattr_t	dtrace_provider_attr = {
233 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
234 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
235 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
236 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
237 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
238 };
239 
240 static void
241 dtrace_nullop(void)
242 {}
243 
244 static int
245 dtrace_enable_nullop(void)
246 {
247 	return (0);
248 }
249 
250 static dtrace_pops_t	dtrace_provider_ops = {
251 	(void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
252 	(void (*)(void *, struct modctl *))dtrace_nullop,
253 	(int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
254 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
255 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
256 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
257 	NULL,
258 	NULL,
259 	NULL,
260 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
261 };
262 
263 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
264 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
265 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
266 
267 /*
268  * DTrace Helper Tracing Variables
269  */
270 uint32_t dtrace_helptrace_next = 0;
271 uint32_t dtrace_helptrace_nlocals;
272 char	*dtrace_helptrace_buffer;
273 int	dtrace_helptrace_bufsize = 512 * 1024;
274 
275 #ifdef DEBUG
276 int	dtrace_helptrace_enabled = 1;
277 #else
278 int	dtrace_helptrace_enabled = 0;
279 #endif
280 
281 /*
282  * DTrace Error Hashing
283  *
284  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
285  * table.  This is very useful for checking coverage of tests that are
286  * expected to induce DIF or DOF processing errors, and may be useful for
287  * debugging problems in the DIF code generator or in DOF generation .  The
288  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
289  */
290 #ifdef DEBUG
291 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
292 static const char *dtrace_errlast;
293 static kthread_t *dtrace_errthread;
294 static kmutex_t dtrace_errlock;
295 #endif
296 
297 /*
298  * DTrace Macros and Constants
299  *
300  * These are various macros that are useful in various spots in the
301  * implementation, along with a few random constants that have no meaning
302  * outside of the implementation.  There is no real structure to this cpp
303  * mishmash -- but is there ever?
304  */
305 #define	DTRACE_HASHSTR(hash, probe)	\
306 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
307 
308 #define	DTRACE_HASHNEXT(hash, probe)	\
309 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
310 
311 #define	DTRACE_HASHPREV(hash, probe)	\
312 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
313 
314 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
315 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
316 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
317 
318 #define	DTRACE_AGGHASHSIZE_SLEW		17
319 
320 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
321 
322 /*
323  * The key for a thread-local variable consists of the lower 61 bits of the
324  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
325  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
326  * equal to a variable identifier.  This is necessary (but not sufficient) to
327  * assure that global associative arrays never collide with thread-local
328  * variables.  To guarantee that they cannot collide, we must also define the
329  * order for keying dynamic variables.  That order is:
330  *
331  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
332  *
333  * Because the variable-key and the tls-key are in orthogonal spaces, there is
334  * no way for a global variable key signature to match a thread-local key
335  * signature.
336  */
337 #define	DTRACE_TLS_THRKEY(where) { \
338 	uint_t intr = 0; \
339 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
340 	for (; actv; actv >>= 1) \
341 		intr++; \
342 	ASSERT(intr < (1 << 3)); \
343 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
344 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
345 }
346 
347 #define	DT_BSWAP_8(x)	((x) & 0xff)
348 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
349 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
350 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
351 
352 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
353 
354 #define	DTRACE_STORE(type, tomax, offset, what) \
355 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
356 
357 #ifndef __i386
358 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
359 	if (addr & (size - 1)) {					\
360 		*flags |= CPU_DTRACE_BADALIGN;				\
361 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
362 		return (0);						\
363 	}
364 #else
365 #define	DTRACE_ALIGNCHECK(addr, size, flags)
366 #endif
367 
368 /*
369  * Test whether a range of memory starting at testaddr of size testsz falls
370  * within the range of memory described by addr, sz.  We take care to avoid
371  * problems with overflow and underflow of the unsigned quantities, and
372  * disallow all negative sizes.  Ranges of size 0 are allowed.
373  */
374 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
375 	((testaddr) - (baseaddr) < (basesz) && \
376 	(testaddr) + (testsz) - (baseaddr) <= (basesz) && \
377 	(testaddr) + (testsz) >= (testaddr))
378 
379 /*
380  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
381  * alloc_sz on the righthand side of the comparison in order to avoid overflow
382  * or underflow in the comparison with it.  This is simpler than the INRANGE
383  * check above, because we know that the dtms_scratch_ptr is valid in the
384  * range.  Allocations of size zero are allowed.
385  */
386 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
387 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
388 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
389 
390 #define	DTRACE_LOADFUNC(bits)						\
391 /*CSTYLED*/								\
392 uint##bits##_t								\
393 dtrace_load##bits(uintptr_t addr)					\
394 {									\
395 	size_t size = bits / NBBY;					\
396 	/*CSTYLED*/							\
397 	uint##bits##_t rval;						\
398 	int i;								\
399 	volatile uint16_t *flags = (volatile uint16_t *)		\
400 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
401 									\
402 	DTRACE_ALIGNCHECK(addr, size, flags);				\
403 									\
404 	for (i = 0; i < dtrace_toxranges; i++) {			\
405 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
406 			continue;					\
407 									\
408 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
409 			continue;					\
410 									\
411 		/*							\
412 		 * This address falls within a toxic region; return 0.	\
413 		 */							\
414 		*flags |= CPU_DTRACE_BADADDR;				\
415 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
416 		return (0);						\
417 	}								\
418 									\
419 	*flags |= CPU_DTRACE_NOFAULT;					\
420 	/*CSTYLED*/							\
421 	rval = *((volatile uint##bits##_t *)addr);			\
422 	*flags &= ~CPU_DTRACE_NOFAULT;					\
423 									\
424 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
425 }
426 
427 #ifdef _LP64
428 #define	dtrace_loadptr	dtrace_load64
429 #else
430 #define	dtrace_loadptr	dtrace_load32
431 #endif
432 
433 #define	DTRACE_DYNHASH_FREE	0
434 #define	DTRACE_DYNHASH_SINK	1
435 #define	DTRACE_DYNHASH_VALID	2
436 
437 #define	DTRACE_MATCH_FAIL	-1
438 #define	DTRACE_MATCH_NEXT	0
439 #define	DTRACE_MATCH_DONE	1
440 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
441 #define	DTRACE_STATE_ALIGN	64
442 
443 #define	DTRACE_FLAGS2FLT(flags)						\
444 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
445 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
446 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
447 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
448 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
449 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
450 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
451 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
452 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
453 	DTRACEFLT_UNKNOWN)
454 
455 #define	DTRACEACT_ISSTRING(act)						\
456 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
457 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
458 
459 static size_t dtrace_strlen(const char *, size_t);
460 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
461 static void dtrace_enabling_provide(dtrace_provider_t *);
462 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
463 static void dtrace_enabling_matchall(void);
464 static void dtrace_enabling_reap(void);
465 static dtrace_state_t *dtrace_anon_grab(void);
466 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
467     dtrace_state_t *, uint64_t, uint64_t);
468 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
469 static void dtrace_buffer_drop(dtrace_buffer_t *);
470 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
471 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
472     dtrace_state_t *, dtrace_mstate_t *);
473 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
474     dtrace_optval_t);
475 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
476 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
477 
478 /*
479  * DTrace Probe Context Functions
480  *
481  * These functions are called from probe context.  Because probe context is
482  * any context in which C may be called, arbitrarily locks may be held,
483  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
484  * As a result, functions called from probe context may only call other DTrace
485  * support functions -- they may not interact at all with the system at large.
486  * (Note that the ASSERT macro is made probe-context safe by redefining it in
487  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
488  * loads are to be performed from probe context, they _must_ be in terms of
489  * the safe dtrace_load*() variants.
490  *
491  * Some functions in this block are not actually called from probe context;
492  * for these functions, there will be a comment above the function reading
493  * "Note:  not called from probe context."
494  */
495 void
496 dtrace_panic(const char *format, ...)
497 {
498 	va_list alist;
499 
500 	va_start(alist, format);
501 	dtrace_vpanic(format, alist);
502 	va_end(alist);
503 }
504 
505 int
506 dtrace_assfail(const char *a, const char *f, int l)
507 {
508 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
509 
510 	/*
511 	 * We just need something here that even the most clever compiler
512 	 * cannot optimize away.
513 	 */
514 	return (a[(uintptr_t)f]);
515 }
516 
517 /*
518  * Atomically increment a specified error counter from probe context.
519  */
520 static void
521 dtrace_error(uint32_t *counter)
522 {
523 	/*
524 	 * Most counters stored to in probe context are per-CPU counters.
525 	 * However, there are some error conditions that are sufficiently
526 	 * arcane that they don't merit per-CPU storage.  If these counters
527 	 * are incremented concurrently on different CPUs, scalability will be
528 	 * adversely affected -- but we don't expect them to be white-hot in a
529 	 * correctly constructed enabling...
530 	 */
531 	uint32_t oval, nval;
532 
533 	do {
534 		oval = *counter;
535 
536 		if ((nval = oval + 1) == 0) {
537 			/*
538 			 * If the counter would wrap, set it to 1 -- assuring
539 			 * that the counter is never zero when we have seen
540 			 * errors.  (The counter must be 32-bits because we
541 			 * aren't guaranteed a 64-bit compare&swap operation.)
542 			 * To save this code both the infamy of being fingered
543 			 * by a priggish news story and the indignity of being
544 			 * the target of a neo-puritan witch trial, we're
545 			 * carefully avoiding any colorful description of the
546 			 * likelihood of this condition -- but suffice it to
547 			 * say that it is only slightly more likely than the
548 			 * overflow of predicate cache IDs, as discussed in
549 			 * dtrace_predicate_create().
550 			 */
551 			nval = 1;
552 		}
553 	} while (dtrace_cas32(counter, oval, nval) != oval);
554 }
555 
556 /*
557  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
558  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
559  */
560 DTRACE_LOADFUNC(8)
561 DTRACE_LOADFUNC(16)
562 DTRACE_LOADFUNC(32)
563 DTRACE_LOADFUNC(64)
564 
565 static int
566 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
567 {
568 	if (dest < mstate->dtms_scratch_base)
569 		return (0);
570 
571 	if (dest + size < dest)
572 		return (0);
573 
574 	if (dest + size > mstate->dtms_scratch_ptr)
575 		return (0);
576 
577 	return (1);
578 }
579 
580 static int
581 dtrace_canstore_statvar(uint64_t addr, size_t sz,
582     dtrace_statvar_t **svars, int nsvars)
583 {
584 	int i;
585 
586 	for (i = 0; i < nsvars; i++) {
587 		dtrace_statvar_t *svar = svars[i];
588 
589 		if (svar == NULL || svar->dtsv_size == 0)
590 			continue;
591 
592 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
593 			return (1);
594 	}
595 
596 	return (0);
597 }
598 
599 /*
600  * Check to see if the address is within a memory region to which a store may
601  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
602  * region.  The caller of dtrace_canstore() is responsible for performing any
603  * alignment checks that are needed before stores are actually executed.
604  */
605 static int
606 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
607     dtrace_vstate_t *vstate)
608 {
609 	/*
610 	 * First, check to see if the address is in scratch space...
611 	 */
612 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
613 	    mstate->dtms_scratch_size))
614 		return (1);
615 
616 	/*
617 	 * Now check to see if it's a dynamic variable.  This check will pick
618 	 * up both thread-local variables and any global dynamically-allocated
619 	 * variables.
620 	 */
621 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
622 	    vstate->dtvs_dynvars.dtds_size)) {
623 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
624 		uintptr_t base = (uintptr_t)dstate->dtds_base +
625 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
626 		uintptr_t chunkoffs;
627 
628 		/*
629 		 * Before we assume that we can store here, we need to make
630 		 * sure that it isn't in our metadata -- storing to our
631 		 * dynamic variable metadata would corrupt our state.  For
632 		 * the range to not include any dynamic variable metadata,
633 		 * it must:
634 		 *
635 		 *	(1) Start above the hash table that is at the base of
636 		 *	the dynamic variable space
637 		 *
638 		 *	(2) Have a starting chunk offset that is beyond the
639 		 *	dtrace_dynvar_t that is at the base of every chunk
640 		 *
641 		 *	(3) Not span a chunk boundary
642 		 *
643 		 */
644 		if (addr < base)
645 			return (0);
646 
647 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
648 
649 		if (chunkoffs < sizeof (dtrace_dynvar_t))
650 			return (0);
651 
652 		if (chunkoffs + sz > dstate->dtds_chunksize)
653 			return (0);
654 
655 		return (1);
656 	}
657 
658 	/*
659 	 * Finally, check the static local and global variables.  These checks
660 	 * take the longest, so we perform them last.
661 	 */
662 	if (dtrace_canstore_statvar(addr, sz,
663 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
664 		return (1);
665 
666 	if (dtrace_canstore_statvar(addr, sz,
667 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
668 		return (1);
669 
670 	return (0);
671 }
672 
673 
674 /*
675  * Convenience routine to check to see if the address is within a memory
676  * region in which a load may be issued given the user's privilege level;
677  * if not, it sets the appropriate error flags and loads 'addr' into the
678  * illegal value slot.
679  *
680  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
681  * appropriate memory access protection.
682  */
683 static int
684 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
685     dtrace_vstate_t *vstate)
686 {
687 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
688 
689 	/*
690 	 * If we hold the privilege to read from kernel memory, then
691 	 * everything is readable.
692 	 */
693 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
694 		return (1);
695 
696 	/*
697 	 * You can obviously read that which you can store.
698 	 */
699 	if (dtrace_canstore(addr, sz, mstate, vstate))
700 		return (1);
701 
702 	/*
703 	 * We're allowed to read from our own string table.
704 	 */
705 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
706 	    mstate->dtms_difo->dtdo_strlen))
707 		return (1);
708 
709 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
710 	*illval = addr;
711 	return (0);
712 }
713 
714 /*
715  * Convenience routine to check to see if a given string is within a memory
716  * region in which a load may be issued given the user's privilege level;
717  * this exists so that we don't need to issue unnecessary dtrace_strlen()
718  * calls in the event that the user has all privileges.
719  */
720 static int
721 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
722     dtrace_vstate_t *vstate)
723 {
724 	size_t strsz;
725 
726 	/*
727 	 * If we hold the privilege to read from kernel memory, then
728 	 * everything is readable.
729 	 */
730 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
731 		return (1);
732 
733 	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
734 	if (dtrace_canload(addr, strsz, mstate, vstate))
735 		return (1);
736 
737 	return (0);
738 }
739 
740 /*
741  * Convenience routine to check to see if a given variable is within a memory
742  * region in which a load may be issued given the user's privilege level.
743  */
744 static int
745 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
746     dtrace_vstate_t *vstate)
747 {
748 	size_t sz;
749 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
750 
751 	/*
752 	 * If we hold the privilege to read from kernel memory, then
753 	 * everything is readable.
754 	 */
755 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
756 		return (1);
757 
758 	if (type->dtdt_kind == DIF_TYPE_STRING)
759 		sz = dtrace_strlen(src,
760 		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
761 	else
762 		sz = type->dtdt_size;
763 
764 	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
765 }
766 
767 /*
768  * Compare two strings using safe loads.
769  */
770 static int
771 dtrace_strncmp(char *s1, char *s2, size_t limit)
772 {
773 	uint8_t c1, c2;
774 	volatile uint16_t *flags;
775 
776 	if (s1 == s2 || limit == 0)
777 		return (0);
778 
779 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
780 
781 	do {
782 		if (s1 == NULL) {
783 			c1 = '\0';
784 		} else {
785 			c1 = dtrace_load8((uintptr_t)s1++);
786 		}
787 
788 		if (s2 == NULL) {
789 			c2 = '\0';
790 		} else {
791 			c2 = dtrace_load8((uintptr_t)s2++);
792 		}
793 
794 		if (c1 != c2)
795 			return (c1 - c2);
796 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
797 
798 	return (0);
799 }
800 
801 /*
802  * Compute strlen(s) for a string using safe memory accesses.  The additional
803  * len parameter is used to specify a maximum length to ensure completion.
804  */
805 static size_t
806 dtrace_strlen(const char *s, size_t lim)
807 {
808 	uint_t len;
809 
810 	for (len = 0; len != lim; len++) {
811 		if (dtrace_load8((uintptr_t)s++) == '\0')
812 			break;
813 	}
814 
815 	return (len);
816 }
817 
818 /*
819  * Check if an address falls within a toxic region.
820  */
821 static int
822 dtrace_istoxic(uintptr_t kaddr, size_t size)
823 {
824 	uintptr_t taddr, tsize;
825 	int i;
826 
827 	for (i = 0; i < dtrace_toxranges; i++) {
828 		taddr = dtrace_toxrange[i].dtt_base;
829 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
830 
831 		if (kaddr - taddr < tsize) {
832 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
833 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
834 			return (1);
835 		}
836 
837 		if (taddr - kaddr < size) {
838 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
839 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
840 			return (1);
841 		}
842 	}
843 
844 	return (0);
845 }
846 
847 /*
848  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
849  * memory specified by the DIF program.  The dst is assumed to be safe memory
850  * that we can store to directly because it is managed by DTrace.  As with
851  * standard bcopy, overlapping copies are handled properly.
852  */
853 static void
854 dtrace_bcopy(const void *src, void *dst, size_t len)
855 {
856 	if (len != 0) {
857 		uint8_t *s1 = dst;
858 		const uint8_t *s2 = src;
859 
860 		if (s1 <= s2) {
861 			do {
862 				*s1++ = dtrace_load8((uintptr_t)s2++);
863 			} while (--len != 0);
864 		} else {
865 			s2 += len;
866 			s1 += len;
867 
868 			do {
869 				*--s1 = dtrace_load8((uintptr_t)--s2);
870 			} while (--len != 0);
871 		}
872 	}
873 }
874 
875 /*
876  * Copy src to dst using safe memory accesses, up to either the specified
877  * length, or the point that a nul byte is encountered.  The src is assumed to
878  * be unsafe memory specified by the DIF program.  The dst is assumed to be
879  * safe memory that we can store to directly because it is managed by DTrace.
880  * Unlike dtrace_bcopy(), overlapping regions are not handled.
881  */
882 static void
883 dtrace_strcpy(const void *src, void *dst, size_t len)
884 {
885 	if (len != 0) {
886 		uint8_t *s1 = dst, c;
887 		const uint8_t *s2 = src;
888 
889 		do {
890 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
891 		} while (--len != 0 && c != '\0');
892 	}
893 }
894 
895 /*
896  * Copy src to dst, deriving the size and type from the specified (BYREF)
897  * variable type.  The src is assumed to be unsafe memory specified by the DIF
898  * program.  The dst is assumed to be DTrace variable memory that is of the
899  * specified type; we assume that we can store to directly.
900  */
901 static void
902 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
903 {
904 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
905 
906 	if (type->dtdt_kind == DIF_TYPE_STRING) {
907 		dtrace_strcpy(src, dst, type->dtdt_size);
908 	} else {
909 		dtrace_bcopy(src, dst, type->dtdt_size);
910 	}
911 }
912 
913 /*
914  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
915  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
916  * safe memory that we can access directly because it is managed by DTrace.
917  */
918 static int
919 dtrace_bcmp(const void *s1, const void *s2, size_t len)
920 {
921 	volatile uint16_t *flags;
922 
923 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
924 
925 	if (s1 == s2)
926 		return (0);
927 
928 	if (s1 == NULL || s2 == NULL)
929 		return (1);
930 
931 	if (s1 != s2 && len != 0) {
932 		const uint8_t *ps1 = s1;
933 		const uint8_t *ps2 = s2;
934 
935 		do {
936 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
937 				return (1);
938 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
939 	}
940 	return (0);
941 }
942 
943 /*
944  * Zero the specified region using a simple byte-by-byte loop.  Note that this
945  * is for safe DTrace-managed memory only.
946  */
947 static void
948 dtrace_bzero(void *dst, size_t len)
949 {
950 	uchar_t *cp;
951 
952 	for (cp = dst; len != 0; len--)
953 		*cp++ = 0;
954 }
955 
956 static void
957 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
958 {
959 	uint64_t result[2];
960 
961 	result[0] = addend1[0] + addend2[0];
962 	result[1] = addend1[1] + addend2[1] +
963 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
964 
965 	sum[0] = result[0];
966 	sum[1] = result[1];
967 }
968 
969 /*
970  * Shift the 128-bit value in a by b. If b is positive, shift left.
971  * If b is negative, shift right.
972  */
973 static void
974 dtrace_shift_128(uint64_t *a, int b)
975 {
976 	uint64_t mask;
977 
978 	if (b == 0)
979 		return;
980 
981 	if (b < 0) {
982 		b = -b;
983 		if (b >= 64) {
984 			a[0] = a[1] >> (b - 64);
985 			a[1] = 0;
986 		} else {
987 			a[0] >>= b;
988 			mask = 1LL << (64 - b);
989 			mask -= 1;
990 			a[0] |= ((a[1] & mask) << (64 - b));
991 			a[1] >>= b;
992 		}
993 	} else {
994 		if (b >= 64) {
995 			a[1] = a[0] << (b - 64);
996 			a[0] = 0;
997 		} else {
998 			a[1] <<= b;
999 			mask = a[0] >> (64 - b);
1000 			a[1] |= mask;
1001 			a[0] <<= b;
1002 		}
1003 	}
1004 }
1005 
1006 /*
1007  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1008  * use native multiplication on those, and then re-combine into the
1009  * resulting 128-bit value.
1010  *
1011  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1012  *     hi1 * hi2 << 64 +
1013  *     hi1 * lo2 << 32 +
1014  *     hi2 * lo1 << 32 +
1015  *     lo1 * lo2
1016  */
1017 static void
1018 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1019 {
1020 	uint64_t hi1, hi2, lo1, lo2;
1021 	uint64_t tmp[2];
1022 
1023 	hi1 = factor1 >> 32;
1024 	hi2 = factor2 >> 32;
1025 
1026 	lo1 = factor1 & DT_MASK_LO;
1027 	lo2 = factor2 & DT_MASK_LO;
1028 
1029 	product[0] = lo1 * lo2;
1030 	product[1] = hi1 * hi2;
1031 
1032 	tmp[0] = hi1 * lo2;
1033 	tmp[1] = 0;
1034 	dtrace_shift_128(tmp, 32);
1035 	dtrace_add_128(product, tmp, product);
1036 
1037 	tmp[0] = hi2 * lo1;
1038 	tmp[1] = 0;
1039 	dtrace_shift_128(tmp, 32);
1040 	dtrace_add_128(product, tmp, product);
1041 }
1042 
1043 /*
1044  * This privilege check should be used by actions and subroutines to
1045  * verify that the user credentials of the process that enabled the
1046  * invoking ECB match the target credentials
1047  */
1048 static int
1049 dtrace_priv_proc_common_user(dtrace_state_t *state)
1050 {
1051 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1052 
1053 	/*
1054 	 * We should always have a non-NULL state cred here, since if cred
1055 	 * is null (anonymous tracing), we fast-path bypass this routine.
1056 	 */
1057 	ASSERT(s_cr != NULL);
1058 
1059 	if ((cr = CRED()) != NULL &&
1060 	    s_cr->cr_uid == cr->cr_uid &&
1061 	    s_cr->cr_uid == cr->cr_ruid &&
1062 	    s_cr->cr_uid == cr->cr_suid &&
1063 	    s_cr->cr_gid == cr->cr_gid &&
1064 	    s_cr->cr_gid == cr->cr_rgid &&
1065 	    s_cr->cr_gid == cr->cr_sgid)
1066 		return (1);
1067 
1068 	return (0);
1069 }
1070 
1071 /*
1072  * This privilege check should be used by actions and subroutines to
1073  * verify that the zone of the process that enabled the invoking ECB
1074  * matches the target credentials
1075  */
1076 static int
1077 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1078 {
1079 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1080 
1081 	/*
1082 	 * We should always have a non-NULL state cred here, since if cred
1083 	 * is null (anonymous tracing), we fast-path bypass this routine.
1084 	 */
1085 	ASSERT(s_cr != NULL);
1086 
1087 	if ((cr = CRED()) != NULL &&
1088 	    s_cr->cr_zone == cr->cr_zone)
1089 		return (1);
1090 
1091 	return (0);
1092 }
1093 
1094 /*
1095  * This privilege check should be used by actions and subroutines to
1096  * verify that the process has not setuid or changed credentials.
1097  */
1098 static int
1099 dtrace_priv_proc_common_nocd()
1100 {
1101 	proc_t *proc;
1102 
1103 	if ((proc = ttoproc(curthread)) != NULL &&
1104 	    !(proc->p_flag & SNOCD))
1105 		return (1);
1106 
1107 	return (0);
1108 }
1109 
1110 static int
1111 dtrace_priv_proc_destructive(dtrace_state_t *state, dtrace_mstate_t *mstate)
1112 {
1113 	int action = state->dts_cred.dcr_action;
1114 
1115 	if (!(mstate->dtms_access & DTRACE_ACCESS_PROC))
1116 		goto bad;
1117 
1118 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1119 	    dtrace_priv_proc_common_zone(state) == 0)
1120 		goto bad;
1121 
1122 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1123 	    dtrace_priv_proc_common_user(state) == 0)
1124 		goto bad;
1125 
1126 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1127 	    dtrace_priv_proc_common_nocd() == 0)
1128 		goto bad;
1129 
1130 	return (1);
1131 
1132 bad:
1133 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1134 
1135 	return (0);
1136 }
1137 
1138 static int
1139 dtrace_priv_proc_control(dtrace_state_t *state, dtrace_mstate_t *mstate)
1140 {
1141 	if (mstate->dtms_access & DTRACE_ACCESS_PROC) {
1142 		if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1143 			return (1);
1144 
1145 		if (dtrace_priv_proc_common_zone(state) &&
1146 		    dtrace_priv_proc_common_user(state) &&
1147 		    dtrace_priv_proc_common_nocd())
1148 			return (1);
1149 	}
1150 
1151 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1152 
1153 	return (0);
1154 }
1155 
1156 static int
1157 dtrace_priv_proc(dtrace_state_t *state, dtrace_mstate_t *mstate)
1158 {
1159 	if ((mstate->dtms_access & DTRACE_ACCESS_PROC) &&
1160 	    (state->dts_cred.dcr_action & DTRACE_CRA_PROC))
1161 		return (1);
1162 
1163 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1164 
1165 	return (0);
1166 }
1167 
1168 static int
1169 dtrace_priv_kernel(dtrace_state_t *state)
1170 {
1171 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1172 		return (1);
1173 
1174 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1175 
1176 	return (0);
1177 }
1178 
1179 static int
1180 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1181 {
1182 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1183 		return (1);
1184 
1185 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1186 
1187 	return (0);
1188 }
1189 
1190 /*
1191  * Determine if the dte_cond of the specified ECB allows for processing of
1192  * the current probe to continue.  Note that this routine may allow continued
1193  * processing, but with access(es) stripped from the mstate's dtms_access
1194  * field.
1195  */
1196 static int
1197 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1198     dtrace_ecb_t *ecb)
1199 {
1200 	dtrace_probe_t *probe = ecb->dte_probe;
1201 	dtrace_provider_t *prov = probe->dtpr_provider;
1202 	dtrace_pops_t *pops = &prov->dtpv_pops;
1203 	int mode = DTRACE_MODE_NOPRIV_DROP;
1204 
1205 	ASSERT(ecb->dte_cond);
1206 
1207 	if (pops->dtps_mode != NULL) {
1208 		mode = pops->dtps_mode(prov->dtpv_arg,
1209 		    probe->dtpr_id, probe->dtpr_arg);
1210 
1211 		ASSERT((mode & DTRACE_MODE_USER) ||
1212 		    (mode & DTRACE_MODE_KERNEL));
1213 		ASSERT((mode & DTRACE_MODE_NOPRIV_RESTRICT) ||
1214 		    (mode & DTRACE_MODE_NOPRIV_DROP));
1215 	}
1216 
1217 	/*
1218 	 * If the dte_cond bits indicate that this consumer is only allowed to
1219 	 * see user-mode firings of this probe, call the provider's dtps_mode()
1220 	 * entry point to check that the probe was fired while in a user
1221 	 * context.  If that's not the case, use the policy specified by the
1222 	 * provider to determine if we drop the probe or merely restrict
1223 	 * operation.
1224 	 */
1225 	if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1226 		ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1227 
1228 		if (!(mode & DTRACE_MODE_USER)) {
1229 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1230 				return (0);
1231 
1232 			mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1233 		}
1234 	}
1235 
1236 	/*
1237 	 * This is more subtle than it looks. We have to be absolutely certain
1238 	 * that CRED() isn't going to change out from under us so it's only
1239 	 * legit to examine that structure if we're in constrained situations.
1240 	 * Currently, the only times we'll this check is if a non-super-user
1241 	 * has enabled the profile or syscall providers -- providers that
1242 	 * allow visibility of all processes. For the profile case, the check
1243 	 * above will ensure that we're examining a user context.
1244 	 */
1245 	if (ecb->dte_cond & DTRACE_COND_OWNER) {
1246 		cred_t *cr;
1247 		cred_t *s_cr = state->dts_cred.dcr_cred;
1248 		proc_t *proc;
1249 
1250 		ASSERT(s_cr != NULL);
1251 
1252 		if ((cr = CRED()) == NULL ||
1253 		    s_cr->cr_uid != cr->cr_uid ||
1254 		    s_cr->cr_uid != cr->cr_ruid ||
1255 		    s_cr->cr_uid != cr->cr_suid ||
1256 		    s_cr->cr_gid != cr->cr_gid ||
1257 		    s_cr->cr_gid != cr->cr_rgid ||
1258 		    s_cr->cr_gid != cr->cr_sgid ||
1259 		    (proc = ttoproc(curthread)) == NULL ||
1260 		    (proc->p_flag & SNOCD)) {
1261 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1262 				return (0);
1263 
1264 			mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1265 		}
1266 	}
1267 
1268 	/*
1269 	 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1270 	 * in our zone, check to see if our mode policy is to restrict rather
1271 	 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1272 	 * and DTRACE_ACCESS_ARGS
1273 	 */
1274 	if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1275 		cred_t *cr;
1276 		cred_t *s_cr = state->dts_cred.dcr_cred;
1277 
1278 		ASSERT(s_cr != NULL);
1279 
1280 		if ((cr = CRED()) == NULL ||
1281 		    s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1282 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1283 				return (0);
1284 
1285 			mstate->dtms_access &=
1286 			    ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1287 		}
1288 	}
1289 
1290 	return (1);
1291 }
1292 
1293 /*
1294  * Note:  not called from probe context.  This function is called
1295  * asynchronously (and at a regular interval) from outside of probe context to
1296  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1297  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1298  */
1299 void
1300 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1301 {
1302 	dtrace_dynvar_t *dirty;
1303 	dtrace_dstate_percpu_t *dcpu;
1304 	dtrace_dynvar_t **rinsep;
1305 	int i, j, work = 0;
1306 
1307 	for (i = 0; i < NCPU; i++) {
1308 		dcpu = &dstate->dtds_percpu[i];
1309 		rinsep = &dcpu->dtdsc_rinsing;
1310 
1311 		/*
1312 		 * If the dirty list is NULL, there is no dirty work to do.
1313 		 */
1314 		if (dcpu->dtdsc_dirty == NULL)
1315 			continue;
1316 
1317 		if (dcpu->dtdsc_rinsing != NULL) {
1318 			/*
1319 			 * If the rinsing list is non-NULL, then it is because
1320 			 * this CPU was selected to accept another CPU's
1321 			 * dirty list -- and since that time, dirty buffers
1322 			 * have accumulated.  This is a highly unlikely
1323 			 * condition, but we choose to ignore the dirty
1324 			 * buffers -- they'll be picked up a future cleanse.
1325 			 */
1326 			continue;
1327 		}
1328 
1329 		if (dcpu->dtdsc_clean != NULL) {
1330 			/*
1331 			 * If the clean list is non-NULL, then we're in a
1332 			 * situation where a CPU has done deallocations (we
1333 			 * have a non-NULL dirty list) but no allocations (we
1334 			 * also have a non-NULL clean list).  We can't simply
1335 			 * move the dirty list into the clean list on this
1336 			 * CPU, yet we also don't want to allow this condition
1337 			 * to persist, lest a short clean list prevent a
1338 			 * massive dirty list from being cleaned (which in
1339 			 * turn could lead to otherwise avoidable dynamic
1340 			 * drops).  To deal with this, we look for some CPU
1341 			 * with a NULL clean list, NULL dirty list, and NULL
1342 			 * rinsing list -- and then we borrow this CPU to
1343 			 * rinse our dirty list.
1344 			 */
1345 			for (j = 0; j < NCPU; j++) {
1346 				dtrace_dstate_percpu_t *rinser;
1347 
1348 				rinser = &dstate->dtds_percpu[j];
1349 
1350 				if (rinser->dtdsc_rinsing != NULL)
1351 					continue;
1352 
1353 				if (rinser->dtdsc_dirty != NULL)
1354 					continue;
1355 
1356 				if (rinser->dtdsc_clean != NULL)
1357 					continue;
1358 
1359 				rinsep = &rinser->dtdsc_rinsing;
1360 				break;
1361 			}
1362 
1363 			if (j == NCPU) {
1364 				/*
1365 				 * We were unable to find another CPU that
1366 				 * could accept this dirty list -- we are
1367 				 * therefore unable to clean it now.
1368 				 */
1369 				dtrace_dynvar_failclean++;
1370 				continue;
1371 			}
1372 		}
1373 
1374 		work = 1;
1375 
1376 		/*
1377 		 * Atomically move the dirty list aside.
1378 		 */
1379 		do {
1380 			dirty = dcpu->dtdsc_dirty;
1381 
1382 			/*
1383 			 * Before we zap the dirty list, set the rinsing list.
1384 			 * (This allows for a potential assertion in
1385 			 * dtrace_dynvar():  if a free dynamic variable appears
1386 			 * on a hash chain, either the dirty list or the
1387 			 * rinsing list for some CPU must be non-NULL.)
1388 			 */
1389 			*rinsep = dirty;
1390 			dtrace_membar_producer();
1391 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1392 		    dirty, NULL) != dirty);
1393 	}
1394 
1395 	if (!work) {
1396 		/*
1397 		 * We have no work to do; we can simply return.
1398 		 */
1399 		return;
1400 	}
1401 
1402 	dtrace_sync();
1403 
1404 	for (i = 0; i < NCPU; i++) {
1405 		dcpu = &dstate->dtds_percpu[i];
1406 
1407 		if (dcpu->dtdsc_rinsing == NULL)
1408 			continue;
1409 
1410 		/*
1411 		 * We are now guaranteed that no hash chain contains a pointer
1412 		 * into this dirty list; we can make it clean.
1413 		 */
1414 		ASSERT(dcpu->dtdsc_clean == NULL);
1415 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1416 		dcpu->dtdsc_rinsing = NULL;
1417 	}
1418 
1419 	/*
1420 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1421 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1422 	 * This prevents a race whereby a CPU incorrectly decides that
1423 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1424 	 * after dtrace_dynvar_clean() has completed.
1425 	 */
1426 	dtrace_sync();
1427 
1428 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1429 }
1430 
1431 /*
1432  * Depending on the value of the op parameter, this function looks-up,
1433  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1434  * allocation is requested, this function will return a pointer to a
1435  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1436  * variable can be allocated.  If NULL is returned, the appropriate counter
1437  * will be incremented.
1438  */
1439 dtrace_dynvar_t *
1440 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1441     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1442     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1443 {
1444 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1445 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1446 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1447 	processorid_t me = CPU->cpu_id, cpu = me;
1448 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1449 	size_t bucket, ksize;
1450 	size_t chunksize = dstate->dtds_chunksize;
1451 	uintptr_t kdata, lock, nstate;
1452 	uint_t i;
1453 
1454 	ASSERT(nkeys != 0);
1455 
1456 	/*
1457 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1458 	 * algorithm.  For the by-value portions, we perform the algorithm in
1459 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1460 	 * bit, and seems to have only a minute effect on distribution.  For
1461 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1462 	 * over each referenced byte.  It's painful to do this, but it's much
1463 	 * better than pathological hash distribution.  The efficacy of the
1464 	 * hashing algorithm (and a comparison with other algorithms) may be
1465 	 * found by running the ::dtrace_dynstat MDB dcmd.
1466 	 */
1467 	for (i = 0; i < nkeys; i++) {
1468 		if (key[i].dttk_size == 0) {
1469 			uint64_t val = key[i].dttk_value;
1470 
1471 			hashval += (val >> 48) & 0xffff;
1472 			hashval += (hashval << 10);
1473 			hashval ^= (hashval >> 6);
1474 
1475 			hashval += (val >> 32) & 0xffff;
1476 			hashval += (hashval << 10);
1477 			hashval ^= (hashval >> 6);
1478 
1479 			hashval += (val >> 16) & 0xffff;
1480 			hashval += (hashval << 10);
1481 			hashval ^= (hashval >> 6);
1482 
1483 			hashval += val & 0xffff;
1484 			hashval += (hashval << 10);
1485 			hashval ^= (hashval >> 6);
1486 		} else {
1487 			/*
1488 			 * This is incredibly painful, but it beats the hell
1489 			 * out of the alternative.
1490 			 */
1491 			uint64_t j, size = key[i].dttk_size;
1492 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1493 
1494 			if (!dtrace_canload(base, size, mstate, vstate))
1495 				break;
1496 
1497 			for (j = 0; j < size; j++) {
1498 				hashval += dtrace_load8(base + j);
1499 				hashval += (hashval << 10);
1500 				hashval ^= (hashval >> 6);
1501 			}
1502 		}
1503 	}
1504 
1505 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1506 		return (NULL);
1507 
1508 	hashval += (hashval << 3);
1509 	hashval ^= (hashval >> 11);
1510 	hashval += (hashval << 15);
1511 
1512 	/*
1513 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1514 	 * comes out to be one of our two sentinel hash values.  If this
1515 	 * actually happens, we set the hashval to be a value known to be a
1516 	 * non-sentinel value.
1517 	 */
1518 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1519 		hashval = DTRACE_DYNHASH_VALID;
1520 
1521 	/*
1522 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1523 	 * important here, tricks can be pulled to reduce it.  (However, it's
1524 	 * critical that hash collisions be kept to an absolute minimum;
1525 	 * they're much more painful than a divide.)  It's better to have a
1526 	 * solution that generates few collisions and still keeps things
1527 	 * relatively simple.
1528 	 */
1529 	bucket = hashval % dstate->dtds_hashsize;
1530 
1531 	if (op == DTRACE_DYNVAR_DEALLOC) {
1532 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1533 
1534 		for (;;) {
1535 			while ((lock = *lockp) & 1)
1536 				continue;
1537 
1538 			if (dtrace_casptr((void *)lockp,
1539 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1540 				break;
1541 		}
1542 
1543 		dtrace_membar_producer();
1544 	}
1545 
1546 top:
1547 	prev = NULL;
1548 	lock = hash[bucket].dtdh_lock;
1549 
1550 	dtrace_membar_consumer();
1551 
1552 	start = hash[bucket].dtdh_chain;
1553 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1554 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1555 	    op != DTRACE_DYNVAR_DEALLOC));
1556 
1557 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1558 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1559 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1560 
1561 		if (dvar->dtdv_hashval != hashval) {
1562 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1563 				/*
1564 				 * We've reached the sink, and therefore the
1565 				 * end of the hash chain; we can kick out of
1566 				 * the loop knowing that we have seen a valid
1567 				 * snapshot of state.
1568 				 */
1569 				ASSERT(dvar->dtdv_next == NULL);
1570 				ASSERT(dvar == &dtrace_dynhash_sink);
1571 				break;
1572 			}
1573 
1574 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1575 				/*
1576 				 * We've gone off the rails:  somewhere along
1577 				 * the line, one of the members of this hash
1578 				 * chain was deleted.  Note that we could also
1579 				 * detect this by simply letting this loop run
1580 				 * to completion, as we would eventually hit
1581 				 * the end of the dirty list.  However, we
1582 				 * want to avoid running the length of the
1583 				 * dirty list unnecessarily (it might be quite
1584 				 * long), so we catch this as early as
1585 				 * possible by detecting the hash marker.  In
1586 				 * this case, we simply set dvar to NULL and
1587 				 * break; the conditional after the loop will
1588 				 * send us back to top.
1589 				 */
1590 				dvar = NULL;
1591 				break;
1592 			}
1593 
1594 			goto next;
1595 		}
1596 
1597 		if (dtuple->dtt_nkeys != nkeys)
1598 			goto next;
1599 
1600 		for (i = 0; i < nkeys; i++, dkey++) {
1601 			if (dkey->dttk_size != key[i].dttk_size)
1602 				goto next; /* size or type mismatch */
1603 
1604 			if (dkey->dttk_size != 0) {
1605 				if (dtrace_bcmp(
1606 				    (void *)(uintptr_t)key[i].dttk_value,
1607 				    (void *)(uintptr_t)dkey->dttk_value,
1608 				    dkey->dttk_size))
1609 					goto next;
1610 			} else {
1611 				if (dkey->dttk_value != key[i].dttk_value)
1612 					goto next;
1613 			}
1614 		}
1615 
1616 		if (op != DTRACE_DYNVAR_DEALLOC)
1617 			return (dvar);
1618 
1619 		ASSERT(dvar->dtdv_next == NULL ||
1620 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1621 
1622 		if (prev != NULL) {
1623 			ASSERT(hash[bucket].dtdh_chain != dvar);
1624 			ASSERT(start != dvar);
1625 			ASSERT(prev->dtdv_next == dvar);
1626 			prev->dtdv_next = dvar->dtdv_next;
1627 		} else {
1628 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1629 			    start, dvar->dtdv_next) != start) {
1630 				/*
1631 				 * We have failed to atomically swing the
1632 				 * hash table head pointer, presumably because
1633 				 * of a conflicting allocation on another CPU.
1634 				 * We need to reread the hash chain and try
1635 				 * again.
1636 				 */
1637 				goto top;
1638 			}
1639 		}
1640 
1641 		dtrace_membar_producer();
1642 
1643 		/*
1644 		 * Now set the hash value to indicate that it's free.
1645 		 */
1646 		ASSERT(hash[bucket].dtdh_chain != dvar);
1647 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1648 
1649 		dtrace_membar_producer();
1650 
1651 		/*
1652 		 * Set the next pointer to point at the dirty list, and
1653 		 * atomically swing the dirty pointer to the newly freed dvar.
1654 		 */
1655 		do {
1656 			next = dcpu->dtdsc_dirty;
1657 			dvar->dtdv_next = next;
1658 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1659 
1660 		/*
1661 		 * Finally, unlock this hash bucket.
1662 		 */
1663 		ASSERT(hash[bucket].dtdh_lock == lock);
1664 		ASSERT(lock & 1);
1665 		hash[bucket].dtdh_lock++;
1666 
1667 		return (NULL);
1668 next:
1669 		prev = dvar;
1670 		continue;
1671 	}
1672 
1673 	if (dvar == NULL) {
1674 		/*
1675 		 * If dvar is NULL, it is because we went off the rails:
1676 		 * one of the elements that we traversed in the hash chain
1677 		 * was deleted while we were traversing it.  In this case,
1678 		 * we assert that we aren't doing a dealloc (deallocs lock
1679 		 * the hash bucket to prevent themselves from racing with
1680 		 * one another), and retry the hash chain traversal.
1681 		 */
1682 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1683 		goto top;
1684 	}
1685 
1686 	if (op != DTRACE_DYNVAR_ALLOC) {
1687 		/*
1688 		 * If we are not to allocate a new variable, we want to
1689 		 * return NULL now.  Before we return, check that the value
1690 		 * of the lock word hasn't changed.  If it has, we may have
1691 		 * seen an inconsistent snapshot.
1692 		 */
1693 		if (op == DTRACE_DYNVAR_NOALLOC) {
1694 			if (hash[bucket].dtdh_lock != lock)
1695 				goto top;
1696 		} else {
1697 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1698 			ASSERT(hash[bucket].dtdh_lock == lock);
1699 			ASSERT(lock & 1);
1700 			hash[bucket].dtdh_lock++;
1701 		}
1702 
1703 		return (NULL);
1704 	}
1705 
1706 	/*
1707 	 * We need to allocate a new dynamic variable.  The size we need is the
1708 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1709 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1710 	 * the size of any referred-to data (dsize).  We then round the final
1711 	 * size up to the chunksize for allocation.
1712 	 */
1713 	for (ksize = 0, i = 0; i < nkeys; i++)
1714 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1715 
1716 	/*
1717 	 * This should be pretty much impossible, but could happen if, say,
1718 	 * strange DIF specified the tuple.  Ideally, this should be an
1719 	 * assertion and not an error condition -- but that requires that the
1720 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1721 	 * bullet-proof.  (That is, it must not be able to be fooled by
1722 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1723 	 * solving this would presumably not amount to solving the Halting
1724 	 * Problem -- but it still seems awfully hard.
1725 	 */
1726 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1727 	    ksize + dsize > chunksize) {
1728 		dcpu->dtdsc_drops++;
1729 		return (NULL);
1730 	}
1731 
1732 	nstate = DTRACE_DSTATE_EMPTY;
1733 
1734 	do {
1735 retry:
1736 		free = dcpu->dtdsc_free;
1737 
1738 		if (free == NULL) {
1739 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1740 			void *rval;
1741 
1742 			if (clean == NULL) {
1743 				/*
1744 				 * We're out of dynamic variable space on
1745 				 * this CPU.  Unless we have tried all CPUs,
1746 				 * we'll try to allocate from a different
1747 				 * CPU.
1748 				 */
1749 				switch (dstate->dtds_state) {
1750 				case DTRACE_DSTATE_CLEAN: {
1751 					void *sp = &dstate->dtds_state;
1752 
1753 					if (++cpu >= NCPU)
1754 						cpu = 0;
1755 
1756 					if (dcpu->dtdsc_dirty != NULL &&
1757 					    nstate == DTRACE_DSTATE_EMPTY)
1758 						nstate = DTRACE_DSTATE_DIRTY;
1759 
1760 					if (dcpu->dtdsc_rinsing != NULL)
1761 						nstate = DTRACE_DSTATE_RINSING;
1762 
1763 					dcpu = &dstate->dtds_percpu[cpu];
1764 
1765 					if (cpu != me)
1766 						goto retry;
1767 
1768 					(void) dtrace_cas32(sp,
1769 					    DTRACE_DSTATE_CLEAN, nstate);
1770 
1771 					/*
1772 					 * To increment the correct bean
1773 					 * counter, take another lap.
1774 					 */
1775 					goto retry;
1776 				}
1777 
1778 				case DTRACE_DSTATE_DIRTY:
1779 					dcpu->dtdsc_dirty_drops++;
1780 					break;
1781 
1782 				case DTRACE_DSTATE_RINSING:
1783 					dcpu->dtdsc_rinsing_drops++;
1784 					break;
1785 
1786 				case DTRACE_DSTATE_EMPTY:
1787 					dcpu->dtdsc_drops++;
1788 					break;
1789 				}
1790 
1791 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1792 				return (NULL);
1793 			}
1794 
1795 			/*
1796 			 * The clean list appears to be non-empty.  We want to
1797 			 * move the clean list to the free list; we start by
1798 			 * moving the clean pointer aside.
1799 			 */
1800 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1801 			    clean, NULL) != clean) {
1802 				/*
1803 				 * We are in one of two situations:
1804 				 *
1805 				 *  (a)	The clean list was switched to the
1806 				 *	free list by another CPU.
1807 				 *
1808 				 *  (b)	The clean list was added to by the
1809 				 *	cleansing cyclic.
1810 				 *
1811 				 * In either of these situations, we can
1812 				 * just reattempt the free list allocation.
1813 				 */
1814 				goto retry;
1815 			}
1816 
1817 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1818 
1819 			/*
1820 			 * Now we'll move the clean list to our free list.
1821 			 * It's impossible for this to fail:  the only way
1822 			 * the free list can be updated is through this
1823 			 * code path, and only one CPU can own the clean list.
1824 			 * Thus, it would only be possible for this to fail if
1825 			 * this code were racing with dtrace_dynvar_clean().
1826 			 * (That is, if dtrace_dynvar_clean() updated the clean
1827 			 * list, and we ended up racing to update the free
1828 			 * list.)  This race is prevented by the dtrace_sync()
1829 			 * in dtrace_dynvar_clean() -- which flushes the
1830 			 * owners of the clean lists out before resetting
1831 			 * the clean lists.
1832 			 */
1833 			dcpu = &dstate->dtds_percpu[me];
1834 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1835 			ASSERT(rval == NULL);
1836 			goto retry;
1837 		}
1838 
1839 		dvar = free;
1840 		new_free = dvar->dtdv_next;
1841 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1842 
1843 	/*
1844 	 * We have now allocated a new chunk.  We copy the tuple keys into the
1845 	 * tuple array and copy any referenced key data into the data space
1846 	 * following the tuple array.  As we do this, we relocate dttk_value
1847 	 * in the final tuple to point to the key data address in the chunk.
1848 	 */
1849 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1850 	dvar->dtdv_data = (void *)(kdata + ksize);
1851 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
1852 
1853 	for (i = 0; i < nkeys; i++) {
1854 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1855 		size_t kesize = key[i].dttk_size;
1856 
1857 		if (kesize != 0) {
1858 			dtrace_bcopy(
1859 			    (const void *)(uintptr_t)key[i].dttk_value,
1860 			    (void *)kdata, kesize);
1861 			dkey->dttk_value = kdata;
1862 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1863 		} else {
1864 			dkey->dttk_value = key[i].dttk_value;
1865 		}
1866 
1867 		dkey->dttk_size = kesize;
1868 	}
1869 
1870 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1871 	dvar->dtdv_hashval = hashval;
1872 	dvar->dtdv_next = start;
1873 
1874 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1875 		return (dvar);
1876 
1877 	/*
1878 	 * The cas has failed.  Either another CPU is adding an element to
1879 	 * this hash chain, or another CPU is deleting an element from this
1880 	 * hash chain.  The simplest way to deal with both of these cases
1881 	 * (though not necessarily the most efficient) is to free our
1882 	 * allocated block and tail-call ourselves.  Note that the free is
1883 	 * to the dirty list and _not_ to the free list.  This is to prevent
1884 	 * races with allocators, above.
1885 	 */
1886 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1887 
1888 	dtrace_membar_producer();
1889 
1890 	do {
1891 		free = dcpu->dtdsc_dirty;
1892 		dvar->dtdv_next = free;
1893 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1894 
1895 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1896 }
1897 
1898 /*ARGSUSED*/
1899 static void
1900 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1901 {
1902 	if ((int64_t)nval < (int64_t)*oval)
1903 		*oval = nval;
1904 }
1905 
1906 /*ARGSUSED*/
1907 static void
1908 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1909 {
1910 	if ((int64_t)nval > (int64_t)*oval)
1911 		*oval = nval;
1912 }
1913 
1914 static void
1915 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1916 {
1917 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1918 	int64_t val = (int64_t)nval;
1919 
1920 	if (val < 0) {
1921 		for (i = 0; i < zero; i++) {
1922 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1923 				quanta[i] += incr;
1924 				return;
1925 			}
1926 		}
1927 	} else {
1928 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1929 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1930 				quanta[i - 1] += incr;
1931 				return;
1932 			}
1933 		}
1934 
1935 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1936 		return;
1937 	}
1938 
1939 	ASSERT(0);
1940 }
1941 
1942 static void
1943 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1944 {
1945 	uint64_t arg = *lquanta++;
1946 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1947 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1948 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1949 	int32_t val = (int32_t)nval, level;
1950 
1951 	ASSERT(step != 0);
1952 	ASSERT(levels != 0);
1953 
1954 	if (val < base) {
1955 		/*
1956 		 * This is an underflow.
1957 		 */
1958 		lquanta[0] += incr;
1959 		return;
1960 	}
1961 
1962 	level = (val - base) / step;
1963 
1964 	if (level < levels) {
1965 		lquanta[level + 1] += incr;
1966 		return;
1967 	}
1968 
1969 	/*
1970 	 * This is an overflow.
1971 	 */
1972 	lquanta[levels + 1] += incr;
1973 }
1974 
1975 static int
1976 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
1977     uint16_t high, uint16_t nsteps, int64_t value)
1978 {
1979 	int64_t this = 1, last, next;
1980 	int base = 1, order;
1981 
1982 	ASSERT(factor <= nsteps);
1983 	ASSERT(nsteps % factor == 0);
1984 
1985 	for (order = 0; order < low; order++)
1986 		this *= factor;
1987 
1988 	/*
1989 	 * If our value is less than our factor taken to the power of the
1990 	 * low order of magnitude, it goes into the zeroth bucket.
1991 	 */
1992 	if (value < (last = this))
1993 		return (0);
1994 
1995 	for (this *= factor; order <= high; order++) {
1996 		int nbuckets = this > nsteps ? nsteps : this;
1997 
1998 		if ((next = this * factor) < this) {
1999 			/*
2000 			 * We should not generally get log/linear quantizations
2001 			 * with a high magnitude that allows 64-bits to
2002 			 * overflow, but we nonetheless protect against this
2003 			 * by explicitly checking for overflow, and clamping
2004 			 * our value accordingly.
2005 			 */
2006 			value = this - 1;
2007 		}
2008 
2009 		if (value < this) {
2010 			/*
2011 			 * If our value lies within this order of magnitude,
2012 			 * determine its position by taking the offset within
2013 			 * the order of magnitude, dividing by the bucket
2014 			 * width, and adding to our (accumulated) base.
2015 			 */
2016 			return (base + (value - last) / (this / nbuckets));
2017 		}
2018 
2019 		base += nbuckets - (nbuckets / factor);
2020 		last = this;
2021 		this = next;
2022 	}
2023 
2024 	/*
2025 	 * Our value is greater than or equal to our factor taken to the
2026 	 * power of one plus the high magnitude -- return the top bucket.
2027 	 */
2028 	return (base);
2029 }
2030 
2031 static void
2032 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2033 {
2034 	uint64_t arg = *llquanta++;
2035 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2036 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2037 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2038 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2039 
2040 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
2041 	    low, high, nsteps, nval)] += incr;
2042 }
2043 
2044 /*ARGSUSED*/
2045 static void
2046 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2047 {
2048 	data[0]++;
2049 	data[1] += nval;
2050 }
2051 
2052 /*ARGSUSED*/
2053 static void
2054 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2055 {
2056 	int64_t snval = (int64_t)nval;
2057 	uint64_t tmp[2];
2058 
2059 	data[0]++;
2060 	data[1] += nval;
2061 
2062 	/*
2063 	 * What we want to say here is:
2064 	 *
2065 	 * data[2] += nval * nval;
2066 	 *
2067 	 * But given that nval is 64-bit, we could easily overflow, so
2068 	 * we do this as 128-bit arithmetic.
2069 	 */
2070 	if (snval < 0)
2071 		snval = -snval;
2072 
2073 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2074 	dtrace_add_128(data + 2, tmp, data + 2);
2075 }
2076 
2077 /*ARGSUSED*/
2078 static void
2079 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2080 {
2081 	*oval = *oval + 1;
2082 }
2083 
2084 /*ARGSUSED*/
2085 static void
2086 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2087 {
2088 	*oval += nval;
2089 }
2090 
2091 /*
2092  * Aggregate given the tuple in the principal data buffer, and the aggregating
2093  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2094  * buffer is specified as the buf parameter.  This routine does not return
2095  * failure; if there is no space in the aggregation buffer, the data will be
2096  * dropped, and a corresponding counter incremented.
2097  */
2098 static void
2099 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2100     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2101 {
2102 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2103 	uint32_t i, ndx, size, fsize;
2104 	uint32_t align = sizeof (uint64_t) - 1;
2105 	dtrace_aggbuffer_t *agb;
2106 	dtrace_aggkey_t *key;
2107 	uint32_t hashval = 0, limit, isstr;
2108 	caddr_t tomax, data, kdata;
2109 	dtrace_actkind_t action;
2110 	dtrace_action_t *act;
2111 	uintptr_t offs;
2112 
2113 	if (buf == NULL)
2114 		return;
2115 
2116 	if (!agg->dtag_hasarg) {
2117 		/*
2118 		 * Currently, only quantize() and lquantize() take additional
2119 		 * arguments, and they have the same semantics:  an increment
2120 		 * value that defaults to 1 when not present.  If additional
2121 		 * aggregating actions take arguments, the setting of the
2122 		 * default argument value will presumably have to become more
2123 		 * sophisticated...
2124 		 */
2125 		arg = 1;
2126 	}
2127 
2128 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2129 	size = rec->dtrd_offset - agg->dtag_base;
2130 	fsize = size + rec->dtrd_size;
2131 
2132 	ASSERT(dbuf->dtb_tomax != NULL);
2133 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2134 
2135 	if ((tomax = buf->dtb_tomax) == NULL) {
2136 		dtrace_buffer_drop(buf);
2137 		return;
2138 	}
2139 
2140 	/*
2141 	 * The metastructure is always at the bottom of the buffer.
2142 	 */
2143 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2144 	    sizeof (dtrace_aggbuffer_t));
2145 
2146 	if (buf->dtb_offset == 0) {
2147 		/*
2148 		 * We just kludge up approximately 1/8th of the size to be
2149 		 * buckets.  If this guess ends up being routinely
2150 		 * off-the-mark, we may need to dynamically readjust this
2151 		 * based on past performance.
2152 		 */
2153 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2154 
2155 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2156 		    (uintptr_t)tomax || hashsize == 0) {
2157 			/*
2158 			 * We've been given a ludicrously small buffer;
2159 			 * increment our drop count and leave.
2160 			 */
2161 			dtrace_buffer_drop(buf);
2162 			return;
2163 		}
2164 
2165 		/*
2166 		 * And now, a pathetic attempt to try to get a an odd (or
2167 		 * perchance, a prime) hash size for better hash distribution.
2168 		 */
2169 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2170 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2171 
2172 		agb->dtagb_hashsize = hashsize;
2173 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2174 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2175 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2176 
2177 		for (i = 0; i < agb->dtagb_hashsize; i++)
2178 			agb->dtagb_hash[i] = NULL;
2179 	}
2180 
2181 	ASSERT(agg->dtag_first != NULL);
2182 	ASSERT(agg->dtag_first->dta_intuple);
2183 
2184 	/*
2185 	 * Calculate the hash value based on the key.  Note that we _don't_
2186 	 * include the aggid in the hashing (but we will store it as part of
2187 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2188 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2189 	 * gets good distribution in practice.  The efficacy of the hashing
2190 	 * algorithm (and a comparison with other algorithms) may be found by
2191 	 * running the ::dtrace_aggstat MDB dcmd.
2192 	 */
2193 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2194 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2195 		limit = i + act->dta_rec.dtrd_size;
2196 		ASSERT(limit <= size);
2197 		isstr = DTRACEACT_ISSTRING(act);
2198 
2199 		for (; i < limit; i++) {
2200 			hashval += data[i];
2201 			hashval += (hashval << 10);
2202 			hashval ^= (hashval >> 6);
2203 
2204 			if (isstr && data[i] == '\0')
2205 				break;
2206 		}
2207 	}
2208 
2209 	hashval += (hashval << 3);
2210 	hashval ^= (hashval >> 11);
2211 	hashval += (hashval << 15);
2212 
2213 	/*
2214 	 * Yes, the divide here is expensive -- but it's generally the least
2215 	 * of the performance issues given the amount of data that we iterate
2216 	 * over to compute hash values, compare data, etc.
2217 	 */
2218 	ndx = hashval % agb->dtagb_hashsize;
2219 
2220 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2221 		ASSERT((caddr_t)key >= tomax);
2222 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2223 
2224 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2225 			continue;
2226 
2227 		kdata = key->dtak_data;
2228 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2229 
2230 		for (act = agg->dtag_first; act->dta_intuple;
2231 		    act = act->dta_next) {
2232 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2233 			limit = i + act->dta_rec.dtrd_size;
2234 			ASSERT(limit <= size);
2235 			isstr = DTRACEACT_ISSTRING(act);
2236 
2237 			for (; i < limit; i++) {
2238 				if (kdata[i] != data[i])
2239 					goto next;
2240 
2241 				if (isstr && data[i] == '\0')
2242 					break;
2243 			}
2244 		}
2245 
2246 		if (action != key->dtak_action) {
2247 			/*
2248 			 * We are aggregating on the same value in the same
2249 			 * aggregation with two different aggregating actions.
2250 			 * (This should have been picked up in the compiler,
2251 			 * so we may be dealing with errant or devious DIF.)
2252 			 * This is an error condition; we indicate as much,
2253 			 * and return.
2254 			 */
2255 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2256 			return;
2257 		}
2258 
2259 		/*
2260 		 * This is a hit:  we need to apply the aggregator to
2261 		 * the value at this key.
2262 		 */
2263 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2264 		return;
2265 next:
2266 		continue;
2267 	}
2268 
2269 	/*
2270 	 * We didn't find it.  We need to allocate some zero-filled space,
2271 	 * link it into the hash table appropriately, and apply the aggregator
2272 	 * to the (zero-filled) value.
2273 	 */
2274 	offs = buf->dtb_offset;
2275 	while (offs & (align - 1))
2276 		offs += sizeof (uint32_t);
2277 
2278 	/*
2279 	 * If we don't have enough room to both allocate a new key _and_
2280 	 * its associated data, increment the drop count and return.
2281 	 */
2282 	if ((uintptr_t)tomax + offs + fsize >
2283 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2284 		dtrace_buffer_drop(buf);
2285 		return;
2286 	}
2287 
2288 	/*CONSTCOND*/
2289 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2290 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2291 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2292 
2293 	key->dtak_data = kdata = tomax + offs;
2294 	buf->dtb_offset = offs + fsize;
2295 
2296 	/*
2297 	 * Now copy the data across.
2298 	 */
2299 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2300 
2301 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2302 		kdata[i] = data[i];
2303 
2304 	/*
2305 	 * Because strings are not zeroed out by default, we need to iterate
2306 	 * looking for actions that store strings, and we need to explicitly
2307 	 * pad these strings out with zeroes.
2308 	 */
2309 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2310 		int nul;
2311 
2312 		if (!DTRACEACT_ISSTRING(act))
2313 			continue;
2314 
2315 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2316 		limit = i + act->dta_rec.dtrd_size;
2317 		ASSERT(limit <= size);
2318 
2319 		for (nul = 0; i < limit; i++) {
2320 			if (nul) {
2321 				kdata[i] = '\0';
2322 				continue;
2323 			}
2324 
2325 			if (data[i] != '\0')
2326 				continue;
2327 
2328 			nul = 1;
2329 		}
2330 	}
2331 
2332 	for (i = size; i < fsize; i++)
2333 		kdata[i] = 0;
2334 
2335 	key->dtak_hashval = hashval;
2336 	key->dtak_size = size;
2337 	key->dtak_action = action;
2338 	key->dtak_next = agb->dtagb_hash[ndx];
2339 	agb->dtagb_hash[ndx] = key;
2340 
2341 	/*
2342 	 * Finally, apply the aggregator.
2343 	 */
2344 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2345 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2346 }
2347 
2348 /*
2349  * Given consumer state, this routine finds a speculation in the INACTIVE
2350  * state and transitions it into the ACTIVE state.  If there is no speculation
2351  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2352  * incremented -- it is up to the caller to take appropriate action.
2353  */
2354 static int
2355 dtrace_speculation(dtrace_state_t *state)
2356 {
2357 	int i = 0;
2358 	dtrace_speculation_state_t current;
2359 	uint32_t *stat = &state->dts_speculations_unavail, count;
2360 
2361 	while (i < state->dts_nspeculations) {
2362 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2363 
2364 		current = spec->dtsp_state;
2365 
2366 		if (current != DTRACESPEC_INACTIVE) {
2367 			if (current == DTRACESPEC_COMMITTINGMANY ||
2368 			    current == DTRACESPEC_COMMITTING ||
2369 			    current == DTRACESPEC_DISCARDING)
2370 				stat = &state->dts_speculations_busy;
2371 			i++;
2372 			continue;
2373 		}
2374 
2375 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2376 		    current, DTRACESPEC_ACTIVE) == current)
2377 			return (i + 1);
2378 	}
2379 
2380 	/*
2381 	 * We couldn't find a speculation.  If we found as much as a single
2382 	 * busy speculation buffer, we'll attribute this failure as "busy"
2383 	 * instead of "unavail".
2384 	 */
2385 	do {
2386 		count = *stat;
2387 	} while (dtrace_cas32(stat, count, count + 1) != count);
2388 
2389 	return (0);
2390 }
2391 
2392 /*
2393  * This routine commits an active speculation.  If the specified speculation
2394  * is not in a valid state to perform a commit(), this routine will silently do
2395  * nothing.  The state of the specified speculation is transitioned according
2396  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2397  */
2398 static void
2399 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2400     dtrace_specid_t which)
2401 {
2402 	dtrace_speculation_t *spec;
2403 	dtrace_buffer_t *src, *dest;
2404 	uintptr_t daddr, saddr, dlimit;
2405 	dtrace_speculation_state_t current, new;
2406 	intptr_t offs;
2407 
2408 	if (which == 0)
2409 		return;
2410 
2411 	if (which > state->dts_nspeculations) {
2412 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2413 		return;
2414 	}
2415 
2416 	spec = &state->dts_speculations[which - 1];
2417 	src = &spec->dtsp_buffer[cpu];
2418 	dest = &state->dts_buffer[cpu];
2419 
2420 	do {
2421 		current = spec->dtsp_state;
2422 
2423 		if (current == DTRACESPEC_COMMITTINGMANY)
2424 			break;
2425 
2426 		switch (current) {
2427 		case DTRACESPEC_INACTIVE:
2428 		case DTRACESPEC_DISCARDING:
2429 			return;
2430 
2431 		case DTRACESPEC_COMMITTING:
2432 			/*
2433 			 * This is only possible if we are (a) commit()'ing
2434 			 * without having done a prior speculate() on this CPU
2435 			 * and (b) racing with another commit() on a different
2436 			 * CPU.  There's nothing to do -- we just assert that
2437 			 * our offset is 0.
2438 			 */
2439 			ASSERT(src->dtb_offset == 0);
2440 			return;
2441 
2442 		case DTRACESPEC_ACTIVE:
2443 			new = DTRACESPEC_COMMITTING;
2444 			break;
2445 
2446 		case DTRACESPEC_ACTIVEONE:
2447 			/*
2448 			 * This speculation is active on one CPU.  If our
2449 			 * buffer offset is non-zero, we know that the one CPU
2450 			 * must be us.  Otherwise, we are committing on a
2451 			 * different CPU from the speculate(), and we must
2452 			 * rely on being asynchronously cleaned.
2453 			 */
2454 			if (src->dtb_offset != 0) {
2455 				new = DTRACESPEC_COMMITTING;
2456 				break;
2457 			}
2458 			/*FALLTHROUGH*/
2459 
2460 		case DTRACESPEC_ACTIVEMANY:
2461 			new = DTRACESPEC_COMMITTINGMANY;
2462 			break;
2463 
2464 		default:
2465 			ASSERT(0);
2466 		}
2467 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2468 	    current, new) != current);
2469 
2470 	/*
2471 	 * We have set the state to indicate that we are committing this
2472 	 * speculation.  Now reserve the necessary space in the destination
2473 	 * buffer.
2474 	 */
2475 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2476 	    sizeof (uint64_t), state, NULL)) < 0) {
2477 		dtrace_buffer_drop(dest);
2478 		goto out;
2479 	}
2480 
2481 	/*
2482 	 * We have the space; copy the buffer across.  (Note that this is a
2483 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2484 	 * a serious performance issue, a high-performance DTrace-specific
2485 	 * bcopy() should obviously be invented.)
2486 	 */
2487 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2488 	dlimit = daddr + src->dtb_offset;
2489 	saddr = (uintptr_t)src->dtb_tomax;
2490 
2491 	/*
2492 	 * First, the aligned portion.
2493 	 */
2494 	while (dlimit - daddr >= sizeof (uint64_t)) {
2495 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2496 
2497 		daddr += sizeof (uint64_t);
2498 		saddr += sizeof (uint64_t);
2499 	}
2500 
2501 	/*
2502 	 * Now any left-over bit...
2503 	 */
2504 	while (dlimit - daddr)
2505 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2506 
2507 	/*
2508 	 * Finally, commit the reserved space in the destination buffer.
2509 	 */
2510 	dest->dtb_offset = offs + src->dtb_offset;
2511 
2512 out:
2513 	/*
2514 	 * If we're lucky enough to be the only active CPU on this speculation
2515 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2516 	 */
2517 	if (current == DTRACESPEC_ACTIVE ||
2518 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2519 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2520 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2521 
2522 		ASSERT(rval == DTRACESPEC_COMMITTING);
2523 	}
2524 
2525 	src->dtb_offset = 0;
2526 	src->dtb_xamot_drops += src->dtb_drops;
2527 	src->dtb_drops = 0;
2528 }
2529 
2530 /*
2531  * This routine discards an active speculation.  If the specified speculation
2532  * is not in a valid state to perform a discard(), this routine will silently
2533  * do nothing.  The state of the specified speculation is transitioned
2534  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2535  */
2536 static void
2537 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2538     dtrace_specid_t which)
2539 {
2540 	dtrace_speculation_t *spec;
2541 	dtrace_speculation_state_t current, new;
2542 	dtrace_buffer_t *buf;
2543 
2544 	if (which == 0)
2545 		return;
2546 
2547 	if (which > state->dts_nspeculations) {
2548 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2549 		return;
2550 	}
2551 
2552 	spec = &state->dts_speculations[which - 1];
2553 	buf = &spec->dtsp_buffer[cpu];
2554 
2555 	do {
2556 		current = spec->dtsp_state;
2557 
2558 		switch (current) {
2559 		case DTRACESPEC_INACTIVE:
2560 		case DTRACESPEC_COMMITTINGMANY:
2561 		case DTRACESPEC_COMMITTING:
2562 		case DTRACESPEC_DISCARDING:
2563 			return;
2564 
2565 		case DTRACESPEC_ACTIVE:
2566 		case DTRACESPEC_ACTIVEMANY:
2567 			new = DTRACESPEC_DISCARDING;
2568 			break;
2569 
2570 		case DTRACESPEC_ACTIVEONE:
2571 			if (buf->dtb_offset != 0) {
2572 				new = DTRACESPEC_INACTIVE;
2573 			} else {
2574 				new = DTRACESPEC_DISCARDING;
2575 			}
2576 			break;
2577 
2578 		default:
2579 			ASSERT(0);
2580 		}
2581 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2582 	    current, new) != current);
2583 
2584 	buf->dtb_offset = 0;
2585 	buf->dtb_drops = 0;
2586 }
2587 
2588 /*
2589  * Note:  not called from probe context.  This function is called
2590  * asynchronously from cross call context to clean any speculations that are
2591  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2592  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2593  * speculation.
2594  */
2595 static void
2596 dtrace_speculation_clean_here(dtrace_state_t *state)
2597 {
2598 	dtrace_icookie_t cookie;
2599 	processorid_t cpu = CPU->cpu_id;
2600 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2601 	dtrace_specid_t i;
2602 
2603 	cookie = dtrace_interrupt_disable();
2604 
2605 	if (dest->dtb_tomax == NULL) {
2606 		dtrace_interrupt_enable(cookie);
2607 		return;
2608 	}
2609 
2610 	for (i = 0; i < state->dts_nspeculations; i++) {
2611 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2612 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2613 
2614 		if (src->dtb_tomax == NULL)
2615 			continue;
2616 
2617 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2618 			src->dtb_offset = 0;
2619 			continue;
2620 		}
2621 
2622 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2623 			continue;
2624 
2625 		if (src->dtb_offset == 0)
2626 			continue;
2627 
2628 		dtrace_speculation_commit(state, cpu, i + 1);
2629 	}
2630 
2631 	dtrace_interrupt_enable(cookie);
2632 }
2633 
2634 /*
2635  * Note:  not called from probe context.  This function is called
2636  * asynchronously (and at a regular interval) to clean any speculations that
2637  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2638  * is work to be done, it cross calls all CPUs to perform that work;
2639  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2640  * INACTIVE state until they have been cleaned by all CPUs.
2641  */
2642 static void
2643 dtrace_speculation_clean(dtrace_state_t *state)
2644 {
2645 	int work = 0, rv;
2646 	dtrace_specid_t i;
2647 
2648 	for (i = 0; i < state->dts_nspeculations; i++) {
2649 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2650 
2651 		ASSERT(!spec->dtsp_cleaning);
2652 
2653 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2654 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2655 			continue;
2656 
2657 		work++;
2658 		spec->dtsp_cleaning = 1;
2659 	}
2660 
2661 	if (!work)
2662 		return;
2663 
2664 	dtrace_xcall(DTRACE_CPUALL,
2665 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2666 
2667 	/*
2668 	 * We now know that all CPUs have committed or discarded their
2669 	 * speculation buffers, as appropriate.  We can now set the state
2670 	 * to inactive.
2671 	 */
2672 	for (i = 0; i < state->dts_nspeculations; i++) {
2673 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2674 		dtrace_speculation_state_t current, new;
2675 
2676 		if (!spec->dtsp_cleaning)
2677 			continue;
2678 
2679 		current = spec->dtsp_state;
2680 		ASSERT(current == DTRACESPEC_DISCARDING ||
2681 		    current == DTRACESPEC_COMMITTINGMANY);
2682 
2683 		new = DTRACESPEC_INACTIVE;
2684 
2685 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2686 		ASSERT(rv == current);
2687 		spec->dtsp_cleaning = 0;
2688 	}
2689 }
2690 
2691 /*
2692  * Called as part of a speculate() to get the speculative buffer associated
2693  * with a given speculation.  Returns NULL if the specified speculation is not
2694  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2695  * the active CPU is not the specified CPU -- the speculation will be
2696  * atomically transitioned into the ACTIVEMANY state.
2697  */
2698 static dtrace_buffer_t *
2699 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2700     dtrace_specid_t which)
2701 {
2702 	dtrace_speculation_t *spec;
2703 	dtrace_speculation_state_t current, new;
2704 	dtrace_buffer_t *buf;
2705 
2706 	if (which == 0)
2707 		return (NULL);
2708 
2709 	if (which > state->dts_nspeculations) {
2710 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2711 		return (NULL);
2712 	}
2713 
2714 	spec = &state->dts_speculations[which - 1];
2715 	buf = &spec->dtsp_buffer[cpuid];
2716 
2717 	do {
2718 		current = spec->dtsp_state;
2719 
2720 		switch (current) {
2721 		case DTRACESPEC_INACTIVE:
2722 		case DTRACESPEC_COMMITTINGMANY:
2723 		case DTRACESPEC_DISCARDING:
2724 			return (NULL);
2725 
2726 		case DTRACESPEC_COMMITTING:
2727 			ASSERT(buf->dtb_offset == 0);
2728 			return (NULL);
2729 
2730 		case DTRACESPEC_ACTIVEONE:
2731 			/*
2732 			 * This speculation is currently active on one CPU.
2733 			 * Check the offset in the buffer; if it's non-zero,
2734 			 * that CPU must be us (and we leave the state alone).
2735 			 * If it's zero, assume that we're starting on a new
2736 			 * CPU -- and change the state to indicate that the
2737 			 * speculation is active on more than one CPU.
2738 			 */
2739 			if (buf->dtb_offset != 0)
2740 				return (buf);
2741 
2742 			new = DTRACESPEC_ACTIVEMANY;
2743 			break;
2744 
2745 		case DTRACESPEC_ACTIVEMANY:
2746 			return (buf);
2747 
2748 		case DTRACESPEC_ACTIVE:
2749 			new = DTRACESPEC_ACTIVEONE;
2750 			break;
2751 
2752 		default:
2753 			ASSERT(0);
2754 		}
2755 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2756 	    current, new) != current);
2757 
2758 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2759 	return (buf);
2760 }
2761 
2762 /*
2763  * Return a string.  In the event that the user lacks the privilege to access
2764  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2765  * don't fail access checking.
2766  *
2767  * dtrace_dif_variable() uses this routine as a helper for various
2768  * builtin values such as 'execname' and 'probefunc.'
2769  */
2770 uintptr_t
2771 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2772     dtrace_mstate_t *mstate)
2773 {
2774 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2775 	uintptr_t ret;
2776 	size_t strsz;
2777 
2778 	/*
2779 	 * The easy case: this probe is allowed to read all of memory, so
2780 	 * we can just return this as a vanilla pointer.
2781 	 */
2782 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2783 		return (addr);
2784 
2785 	/*
2786 	 * This is the tougher case: we copy the string in question from
2787 	 * kernel memory into scratch memory and return it that way: this
2788 	 * ensures that we won't trip up when access checking tests the
2789 	 * BYREF return value.
2790 	 */
2791 	strsz = dtrace_strlen((char *)addr, size) + 1;
2792 
2793 	if (mstate->dtms_scratch_ptr + strsz >
2794 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2795 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2796 		return (NULL);
2797 	}
2798 
2799 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2800 	    strsz);
2801 	ret = mstate->dtms_scratch_ptr;
2802 	mstate->dtms_scratch_ptr += strsz;
2803 	return (ret);
2804 }
2805 
2806 /*
2807  * This function implements the DIF emulator's variable lookups.  The emulator
2808  * passes a reserved variable identifier and optional built-in array index.
2809  */
2810 static uint64_t
2811 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2812     uint64_t ndx)
2813 {
2814 	/*
2815 	 * If we're accessing one of the uncached arguments, we'll turn this
2816 	 * into a reference in the args array.
2817 	 */
2818 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2819 		ndx = v - DIF_VAR_ARG0;
2820 		v = DIF_VAR_ARGS;
2821 	}
2822 
2823 	switch (v) {
2824 	case DIF_VAR_ARGS:
2825 		if (!(mstate->dtms_access & DTRACE_ACCESS_ARGS)) {
2826 			cpu_core[CPU->cpu_id].cpuc_dtrace_flags |=
2827 			    CPU_DTRACE_KPRIV;
2828 			return (0);
2829 		}
2830 
2831 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2832 		if (ndx >= sizeof (mstate->dtms_arg) /
2833 		    sizeof (mstate->dtms_arg[0])) {
2834 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2835 			dtrace_provider_t *pv;
2836 			uint64_t val;
2837 
2838 			pv = mstate->dtms_probe->dtpr_provider;
2839 			if (pv->dtpv_pops.dtps_getargval != NULL)
2840 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2841 				    mstate->dtms_probe->dtpr_id,
2842 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
2843 			else
2844 				val = dtrace_getarg(ndx, aframes);
2845 
2846 			/*
2847 			 * This is regrettably required to keep the compiler
2848 			 * from tail-optimizing the call to dtrace_getarg().
2849 			 * The condition always evaluates to true, but the
2850 			 * compiler has no way of figuring that out a priori.
2851 			 * (None of this would be necessary if the compiler
2852 			 * could be relied upon to _always_ tail-optimize
2853 			 * the call to dtrace_getarg() -- but it can't.)
2854 			 */
2855 			if (mstate->dtms_probe != NULL)
2856 				return (val);
2857 
2858 			ASSERT(0);
2859 		}
2860 
2861 		return (mstate->dtms_arg[ndx]);
2862 
2863 	case DIF_VAR_UREGS: {
2864 		klwp_t *lwp;
2865 
2866 		if (!dtrace_priv_proc(state, mstate))
2867 			return (0);
2868 
2869 		if ((lwp = curthread->t_lwp) == NULL) {
2870 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2871 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
2872 			return (0);
2873 		}
2874 
2875 		return (dtrace_getreg(lwp->lwp_regs, ndx));
2876 	}
2877 
2878 	case DIF_VAR_VMREGS: {
2879 		uint64_t rval;
2880 
2881 		if (!dtrace_priv_kernel(state))
2882 			return (0);
2883 
2884 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2885 
2886 		rval = dtrace_getvmreg(ndx,
2887 		    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags);
2888 
2889 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2890 
2891 		return (rval);
2892 	}
2893 
2894 	case DIF_VAR_CURTHREAD:
2895 		if (!dtrace_priv_kernel(state))
2896 			return (0);
2897 		return ((uint64_t)(uintptr_t)curthread);
2898 
2899 	case DIF_VAR_TIMESTAMP:
2900 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2901 			mstate->dtms_timestamp = dtrace_gethrtime();
2902 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2903 		}
2904 		return (mstate->dtms_timestamp);
2905 
2906 	case DIF_VAR_VTIMESTAMP:
2907 		ASSERT(dtrace_vtime_references != 0);
2908 		return (curthread->t_dtrace_vtime);
2909 
2910 	case DIF_VAR_WALLTIMESTAMP:
2911 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2912 			mstate->dtms_walltimestamp = dtrace_gethrestime();
2913 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2914 		}
2915 		return (mstate->dtms_walltimestamp);
2916 
2917 	case DIF_VAR_IPL:
2918 		if (!dtrace_priv_kernel(state))
2919 			return (0);
2920 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2921 			mstate->dtms_ipl = dtrace_getipl();
2922 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
2923 		}
2924 		return (mstate->dtms_ipl);
2925 
2926 	case DIF_VAR_EPID:
2927 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2928 		return (mstate->dtms_epid);
2929 
2930 	case DIF_VAR_ID:
2931 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2932 		return (mstate->dtms_probe->dtpr_id);
2933 
2934 	case DIF_VAR_STACKDEPTH:
2935 		if (!dtrace_priv_kernel(state))
2936 			return (0);
2937 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2938 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2939 
2940 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2941 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2942 		}
2943 		return (mstate->dtms_stackdepth);
2944 
2945 	case DIF_VAR_USTACKDEPTH:
2946 		if (!dtrace_priv_proc(state, mstate))
2947 			return (0);
2948 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2949 			/*
2950 			 * See comment in DIF_VAR_PID.
2951 			 */
2952 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2953 			    CPU_ON_INTR(CPU)) {
2954 				mstate->dtms_ustackdepth = 0;
2955 			} else {
2956 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2957 				mstate->dtms_ustackdepth =
2958 				    dtrace_getustackdepth();
2959 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2960 			}
2961 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2962 		}
2963 		return (mstate->dtms_ustackdepth);
2964 
2965 	case DIF_VAR_CALLER:
2966 		if (!dtrace_priv_kernel(state))
2967 			return (0);
2968 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2969 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2970 
2971 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2972 				/*
2973 				 * If this is an unanchored probe, we are
2974 				 * required to go through the slow path:
2975 				 * dtrace_caller() only guarantees correct
2976 				 * results for anchored probes.
2977 				 */
2978 				pc_t caller[2];
2979 
2980 				dtrace_getpcstack(caller, 2, aframes,
2981 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2982 				mstate->dtms_caller = caller[1];
2983 			} else if ((mstate->dtms_caller =
2984 			    dtrace_caller(aframes)) == -1) {
2985 				/*
2986 				 * We have failed to do this the quick way;
2987 				 * we must resort to the slower approach of
2988 				 * calling dtrace_getpcstack().
2989 				 */
2990 				pc_t caller;
2991 
2992 				dtrace_getpcstack(&caller, 1, aframes, NULL);
2993 				mstate->dtms_caller = caller;
2994 			}
2995 
2996 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
2997 		}
2998 		return (mstate->dtms_caller);
2999 
3000 	case DIF_VAR_UCALLER:
3001 		if (!dtrace_priv_proc(state, mstate))
3002 			return (0);
3003 
3004 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3005 			uint64_t ustack[3];
3006 
3007 			/*
3008 			 * dtrace_getupcstack() fills in the first uint64_t
3009 			 * with the current PID.  The second uint64_t will
3010 			 * be the program counter at user-level.  The third
3011 			 * uint64_t will contain the caller, which is what
3012 			 * we're after.
3013 			 */
3014 			ustack[2] = NULL;
3015 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3016 			dtrace_getupcstack(ustack, 3);
3017 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3018 			mstate->dtms_ucaller = ustack[2];
3019 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3020 		}
3021 
3022 		return (mstate->dtms_ucaller);
3023 
3024 	case DIF_VAR_PROBEPROV:
3025 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3026 		return (dtrace_dif_varstr(
3027 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3028 		    state, mstate));
3029 
3030 	case DIF_VAR_PROBEMOD:
3031 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3032 		return (dtrace_dif_varstr(
3033 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3034 		    state, mstate));
3035 
3036 	case DIF_VAR_PROBEFUNC:
3037 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3038 		return (dtrace_dif_varstr(
3039 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3040 		    state, mstate));
3041 
3042 	case DIF_VAR_PROBENAME:
3043 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3044 		return (dtrace_dif_varstr(
3045 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3046 		    state, mstate));
3047 
3048 	case DIF_VAR_PID:
3049 		if (!dtrace_priv_proc(state, mstate))
3050 			return (0);
3051 
3052 		/*
3053 		 * Note that we are assuming that an unanchored probe is
3054 		 * always due to a high-level interrupt.  (And we're assuming
3055 		 * that there is only a single high level interrupt.)
3056 		 */
3057 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3058 			return (pid0.pid_id);
3059 
3060 		/*
3061 		 * It is always safe to dereference one's own t_procp pointer:
3062 		 * it always points to a valid, allocated proc structure.
3063 		 * Further, it is always safe to dereference the p_pidp member
3064 		 * of one's own proc structure.  (These are truisms becuase
3065 		 * threads and processes don't clean up their own state --
3066 		 * they leave that task to whomever reaps them.)
3067 		 */
3068 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3069 
3070 	case DIF_VAR_PPID:
3071 		if (!dtrace_priv_proc(state, mstate))
3072 			return (0);
3073 
3074 		/*
3075 		 * See comment in DIF_VAR_PID.
3076 		 */
3077 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3078 			return (pid0.pid_id);
3079 
3080 		/*
3081 		 * It is always safe to dereference one's own t_procp pointer:
3082 		 * it always points to a valid, allocated proc structure.
3083 		 * (This is true because threads don't clean up their own
3084 		 * state -- they leave that task to whomever reaps them.)
3085 		 */
3086 		return ((uint64_t)curthread->t_procp->p_ppid);
3087 
3088 	case DIF_VAR_TID:
3089 		/*
3090 		 * See comment in DIF_VAR_PID.
3091 		 */
3092 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3093 			return (0);
3094 
3095 		return ((uint64_t)curthread->t_tid);
3096 
3097 	case DIF_VAR_EXECNAME:
3098 		if (!dtrace_priv_proc(state, mstate))
3099 			return (0);
3100 
3101 		/*
3102 		 * See comment in DIF_VAR_PID.
3103 		 */
3104 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3105 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3106 
3107 		/*
3108 		 * It is always safe to dereference one's own t_procp pointer:
3109 		 * it always points to a valid, allocated proc structure.
3110 		 * (This is true because threads don't clean up their own
3111 		 * state -- they leave that task to whomever reaps them.)
3112 		 */
3113 		return (dtrace_dif_varstr(
3114 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3115 		    state, mstate));
3116 
3117 	case DIF_VAR_ZONENAME:
3118 		if (!dtrace_priv_proc(state, mstate))
3119 			return (0);
3120 
3121 		/*
3122 		 * See comment in DIF_VAR_PID.
3123 		 */
3124 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3125 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3126 
3127 		/*
3128 		 * It is always safe to dereference one's own t_procp pointer:
3129 		 * it always points to a valid, allocated proc structure.
3130 		 * (This is true because threads don't clean up their own
3131 		 * state -- they leave that task to whomever reaps them.)
3132 		 */
3133 		return (dtrace_dif_varstr(
3134 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3135 		    state, mstate));
3136 
3137 	case DIF_VAR_UID:
3138 		if (!dtrace_priv_proc(state, mstate))
3139 			return (0);
3140 
3141 		/*
3142 		 * See comment in DIF_VAR_PID.
3143 		 */
3144 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3145 			return ((uint64_t)p0.p_cred->cr_uid);
3146 
3147 		/*
3148 		 * It is always safe to dereference one's own t_procp pointer:
3149 		 * it always points to a valid, allocated proc structure.
3150 		 * (This is true because threads don't clean up their own
3151 		 * state -- they leave that task to whomever reaps them.)
3152 		 *
3153 		 * Additionally, it is safe to dereference one's own process
3154 		 * credential, since this is never NULL after process birth.
3155 		 */
3156 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3157 
3158 	case DIF_VAR_GID:
3159 		if (!dtrace_priv_proc(state, mstate))
3160 			return (0);
3161 
3162 		/*
3163 		 * See comment in DIF_VAR_PID.
3164 		 */
3165 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3166 			return ((uint64_t)p0.p_cred->cr_gid);
3167 
3168 		/*
3169 		 * It is always safe to dereference one's own t_procp pointer:
3170 		 * it always points to a valid, allocated proc structure.
3171 		 * (This is true because threads don't clean up their own
3172 		 * state -- they leave that task to whomever reaps them.)
3173 		 *
3174 		 * Additionally, it is safe to dereference one's own process
3175 		 * credential, since this is never NULL after process birth.
3176 		 */
3177 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3178 
3179 	case DIF_VAR_ERRNO: {
3180 		klwp_t *lwp;
3181 		if (!dtrace_priv_proc(state, mstate))
3182 			return (0);
3183 
3184 		/*
3185 		 * See comment in DIF_VAR_PID.
3186 		 */
3187 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3188 			return (0);
3189 
3190 		/*
3191 		 * It is always safe to dereference one's own t_lwp pointer in
3192 		 * the event that this pointer is non-NULL.  (This is true
3193 		 * because threads and lwps don't clean up their own state --
3194 		 * they leave that task to whomever reaps them.)
3195 		 */
3196 		if ((lwp = curthread->t_lwp) == NULL)
3197 			return (0);
3198 
3199 		return ((uint64_t)lwp->lwp_errno);
3200 	}
3201 	default:
3202 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3203 		return (0);
3204 	}
3205 }
3206 
3207 /*
3208  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
3209  * Notice that we don't bother validating the proper number of arguments or
3210  * their types in the tuple stack.  This isn't needed because all argument
3211  * interpretation is safe because of our load safety -- the worst that can
3212  * happen is that a bogus program can obtain bogus results.
3213  */
3214 static void
3215 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
3216     dtrace_key_t *tupregs, int nargs,
3217     dtrace_mstate_t *mstate, dtrace_state_t *state)
3218 {
3219 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3220 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3221 	dtrace_vstate_t *vstate = &state->dts_vstate;
3222 
3223 	union {
3224 		mutex_impl_t mi;
3225 		uint64_t mx;
3226 	} m;
3227 
3228 	union {
3229 		krwlock_t ri;
3230 		uintptr_t rw;
3231 	} r;
3232 
3233 	switch (subr) {
3234 	case DIF_SUBR_RAND:
3235 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
3236 		break;
3237 
3238 	case DIF_SUBR_MUTEX_OWNED:
3239 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3240 		    mstate, vstate)) {
3241 			regs[rd] = NULL;
3242 			break;
3243 		}
3244 
3245 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3246 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
3247 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
3248 		else
3249 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
3250 		break;
3251 
3252 	case DIF_SUBR_MUTEX_OWNER:
3253 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3254 		    mstate, vstate)) {
3255 			regs[rd] = NULL;
3256 			break;
3257 		}
3258 
3259 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3260 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3261 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3262 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3263 		else
3264 			regs[rd] = 0;
3265 		break;
3266 
3267 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3268 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3269 		    mstate, vstate)) {
3270 			regs[rd] = NULL;
3271 			break;
3272 		}
3273 
3274 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3275 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3276 		break;
3277 
3278 	case DIF_SUBR_MUTEX_TYPE_SPIN:
3279 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3280 		    mstate, vstate)) {
3281 			regs[rd] = NULL;
3282 			break;
3283 		}
3284 
3285 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3286 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3287 		break;
3288 
3289 	case DIF_SUBR_RW_READ_HELD: {
3290 		uintptr_t tmp;
3291 
3292 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3293 		    mstate, vstate)) {
3294 			regs[rd] = NULL;
3295 			break;
3296 		}
3297 
3298 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3299 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3300 		break;
3301 	}
3302 
3303 	case DIF_SUBR_RW_WRITE_HELD:
3304 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3305 		    mstate, vstate)) {
3306 			regs[rd] = NULL;
3307 			break;
3308 		}
3309 
3310 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3311 		regs[rd] = _RW_WRITE_HELD(&r.ri);
3312 		break;
3313 
3314 	case DIF_SUBR_RW_ISWRITER:
3315 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3316 		    mstate, vstate)) {
3317 			regs[rd] = NULL;
3318 			break;
3319 		}
3320 
3321 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3322 		regs[rd] = _RW_ISWRITER(&r.ri);
3323 		break;
3324 
3325 	case DIF_SUBR_BCOPY: {
3326 		/*
3327 		 * We need to be sure that the destination is in the scratch
3328 		 * region -- no other region is allowed.
3329 		 */
3330 		uintptr_t src = tupregs[0].dttk_value;
3331 		uintptr_t dest = tupregs[1].dttk_value;
3332 		size_t size = tupregs[2].dttk_value;
3333 
3334 		if (!dtrace_inscratch(dest, size, mstate)) {
3335 			*flags |= CPU_DTRACE_BADADDR;
3336 			*illval = regs[rd];
3337 			break;
3338 		}
3339 
3340 		if (!dtrace_canload(src, size, mstate, vstate)) {
3341 			regs[rd] = NULL;
3342 			break;
3343 		}
3344 
3345 		dtrace_bcopy((void *)src, (void *)dest, size);
3346 		break;
3347 	}
3348 
3349 	case DIF_SUBR_ALLOCA:
3350 	case DIF_SUBR_COPYIN: {
3351 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3352 		uint64_t size =
3353 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3354 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3355 
3356 		/*
3357 		 * This action doesn't require any credential checks since
3358 		 * probes will not activate in user contexts to which the
3359 		 * enabling user does not have permissions.
3360 		 */
3361 
3362 		/*
3363 		 * Rounding up the user allocation size could have overflowed
3364 		 * a large, bogus allocation (like -1ULL) to 0.
3365 		 */
3366 		if (scratch_size < size ||
3367 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
3368 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3369 			regs[rd] = NULL;
3370 			break;
3371 		}
3372 
3373 		if (subr == DIF_SUBR_COPYIN) {
3374 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3375 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3376 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3377 		}
3378 
3379 		mstate->dtms_scratch_ptr += scratch_size;
3380 		regs[rd] = dest;
3381 		break;
3382 	}
3383 
3384 	case DIF_SUBR_COPYINTO: {
3385 		uint64_t size = tupregs[1].dttk_value;
3386 		uintptr_t dest = tupregs[2].dttk_value;
3387 
3388 		/*
3389 		 * This action doesn't require any credential checks since
3390 		 * probes will not activate in user contexts to which the
3391 		 * enabling user does not have permissions.
3392 		 */
3393 		if (!dtrace_inscratch(dest, size, mstate)) {
3394 			*flags |= CPU_DTRACE_BADADDR;
3395 			*illval = regs[rd];
3396 			break;
3397 		}
3398 
3399 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3400 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3401 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3402 		break;
3403 	}
3404 
3405 	case DIF_SUBR_COPYINSTR: {
3406 		uintptr_t dest = mstate->dtms_scratch_ptr;
3407 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3408 
3409 		if (nargs > 1 && tupregs[1].dttk_value < size)
3410 			size = tupregs[1].dttk_value + 1;
3411 
3412 		/*
3413 		 * This action doesn't require any credential checks since
3414 		 * probes will not activate in user contexts to which the
3415 		 * enabling user does not have permissions.
3416 		 */
3417 		if (!DTRACE_INSCRATCH(mstate, size)) {
3418 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3419 			regs[rd] = NULL;
3420 			break;
3421 		}
3422 
3423 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3424 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3425 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3426 
3427 		((char *)dest)[size - 1] = '\0';
3428 		mstate->dtms_scratch_ptr += size;
3429 		regs[rd] = dest;
3430 		break;
3431 	}
3432 
3433 	case DIF_SUBR_MSGSIZE:
3434 	case DIF_SUBR_MSGDSIZE: {
3435 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
3436 		uintptr_t wptr, rptr;
3437 		size_t count = 0;
3438 		int cont = 0;
3439 
3440 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3441 
3442 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3443 			    vstate)) {
3444 				regs[rd] = NULL;
3445 				break;
3446 			}
3447 
3448 			wptr = dtrace_loadptr(baddr +
3449 			    offsetof(mblk_t, b_wptr));
3450 
3451 			rptr = dtrace_loadptr(baddr +
3452 			    offsetof(mblk_t, b_rptr));
3453 
3454 			if (wptr < rptr) {
3455 				*flags |= CPU_DTRACE_BADADDR;
3456 				*illval = tupregs[0].dttk_value;
3457 				break;
3458 			}
3459 
3460 			daddr = dtrace_loadptr(baddr +
3461 			    offsetof(mblk_t, b_datap));
3462 
3463 			baddr = dtrace_loadptr(baddr +
3464 			    offsetof(mblk_t, b_cont));
3465 
3466 			/*
3467 			 * We want to prevent against denial-of-service here,
3468 			 * so we're only going to search the list for
3469 			 * dtrace_msgdsize_max mblks.
3470 			 */
3471 			if (cont++ > dtrace_msgdsize_max) {
3472 				*flags |= CPU_DTRACE_ILLOP;
3473 				break;
3474 			}
3475 
3476 			if (subr == DIF_SUBR_MSGDSIZE) {
3477 				if (dtrace_load8(daddr +
3478 				    offsetof(dblk_t, db_type)) != M_DATA)
3479 					continue;
3480 			}
3481 
3482 			count += wptr - rptr;
3483 		}
3484 
3485 		if (!(*flags & CPU_DTRACE_FAULT))
3486 			regs[rd] = count;
3487 
3488 		break;
3489 	}
3490 
3491 	case DIF_SUBR_PROGENYOF: {
3492 		pid_t pid = tupregs[0].dttk_value;
3493 		proc_t *p;
3494 		int rval = 0;
3495 
3496 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3497 
3498 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3499 			if (p->p_pidp->pid_id == pid) {
3500 				rval = 1;
3501 				break;
3502 			}
3503 		}
3504 
3505 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3506 
3507 		regs[rd] = rval;
3508 		break;
3509 	}
3510 
3511 	case DIF_SUBR_SPECULATION:
3512 		regs[rd] = dtrace_speculation(state);
3513 		break;
3514 
3515 	case DIF_SUBR_COPYOUT: {
3516 		uintptr_t kaddr = tupregs[0].dttk_value;
3517 		uintptr_t uaddr = tupregs[1].dttk_value;
3518 		uint64_t size = tupregs[2].dttk_value;
3519 
3520 		if (!dtrace_destructive_disallow &&
3521 		    dtrace_priv_proc_control(state, mstate) &&
3522 		    !dtrace_istoxic(kaddr, size)) {
3523 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3524 			dtrace_copyout(kaddr, uaddr, size, flags);
3525 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3526 		}
3527 		break;
3528 	}
3529 
3530 	case DIF_SUBR_COPYOUTSTR: {
3531 		uintptr_t kaddr = tupregs[0].dttk_value;
3532 		uintptr_t uaddr = tupregs[1].dttk_value;
3533 		uint64_t size = tupregs[2].dttk_value;
3534 
3535 		if (!dtrace_destructive_disallow &&
3536 		    dtrace_priv_proc_control(state, mstate) &&
3537 		    !dtrace_istoxic(kaddr, size)) {
3538 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3539 			dtrace_copyoutstr(kaddr, uaddr, size, flags);
3540 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3541 		}
3542 		break;
3543 	}
3544 
3545 	case DIF_SUBR_STRLEN: {
3546 		size_t sz;
3547 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3548 		sz = dtrace_strlen((char *)addr,
3549 		    state->dts_options[DTRACEOPT_STRSIZE]);
3550 
3551 		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3552 			regs[rd] = NULL;
3553 			break;
3554 		}
3555 
3556 		regs[rd] = sz;
3557 
3558 		break;
3559 	}
3560 
3561 	case DIF_SUBR_STRCHR:
3562 	case DIF_SUBR_STRRCHR: {
3563 		/*
3564 		 * We're going to iterate over the string looking for the
3565 		 * specified character.  We will iterate until we have reached
3566 		 * the string length or we have found the character.  If this
3567 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3568 		 * of the specified character instead of the first.
3569 		 */
3570 		uintptr_t saddr = tupregs[0].dttk_value;
3571 		uintptr_t addr = tupregs[0].dttk_value;
3572 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3573 		char c, target = (char)tupregs[1].dttk_value;
3574 
3575 		for (regs[rd] = NULL; addr < limit; addr++) {
3576 			if ((c = dtrace_load8(addr)) == target) {
3577 				regs[rd] = addr;
3578 
3579 				if (subr == DIF_SUBR_STRCHR)
3580 					break;
3581 			}
3582 
3583 			if (c == '\0')
3584 				break;
3585 		}
3586 
3587 		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3588 			regs[rd] = NULL;
3589 			break;
3590 		}
3591 
3592 		break;
3593 	}
3594 
3595 	case DIF_SUBR_STRSTR:
3596 	case DIF_SUBR_INDEX:
3597 	case DIF_SUBR_RINDEX: {
3598 		/*
3599 		 * We're going to iterate over the string looking for the
3600 		 * specified string.  We will iterate until we have reached
3601 		 * the string length or we have found the string.  (Yes, this
3602 		 * is done in the most naive way possible -- but considering
3603 		 * that the string we're searching for is likely to be
3604 		 * relatively short, the complexity of Rabin-Karp or similar
3605 		 * hardly seems merited.)
3606 		 */
3607 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3608 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3609 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3610 		size_t len = dtrace_strlen(addr, size);
3611 		size_t sublen = dtrace_strlen(substr, size);
3612 		char *limit = addr + len, *orig = addr;
3613 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3614 		int inc = 1;
3615 
3616 		regs[rd] = notfound;
3617 
3618 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3619 			regs[rd] = NULL;
3620 			break;
3621 		}
3622 
3623 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3624 		    vstate)) {
3625 			regs[rd] = NULL;
3626 			break;
3627 		}
3628 
3629 		/*
3630 		 * strstr() and index()/rindex() have similar semantics if
3631 		 * both strings are the empty string: strstr() returns a
3632 		 * pointer to the (empty) string, and index() and rindex()
3633 		 * both return index 0 (regardless of any position argument).
3634 		 */
3635 		if (sublen == 0 && len == 0) {
3636 			if (subr == DIF_SUBR_STRSTR)
3637 				regs[rd] = (uintptr_t)addr;
3638 			else
3639 				regs[rd] = 0;
3640 			break;
3641 		}
3642 
3643 		if (subr != DIF_SUBR_STRSTR) {
3644 			if (subr == DIF_SUBR_RINDEX) {
3645 				limit = orig - 1;
3646 				addr += len;
3647 				inc = -1;
3648 			}
3649 
3650 			/*
3651 			 * Both index() and rindex() take an optional position
3652 			 * argument that denotes the starting position.
3653 			 */
3654 			if (nargs == 3) {
3655 				int64_t pos = (int64_t)tupregs[2].dttk_value;
3656 
3657 				/*
3658 				 * If the position argument to index() is
3659 				 * negative, Perl implicitly clamps it at
3660 				 * zero.  This semantic is a little surprising
3661 				 * given the special meaning of negative
3662 				 * positions to similar Perl functions like
3663 				 * substr(), but it appears to reflect a
3664 				 * notion that index() can start from a
3665 				 * negative index and increment its way up to
3666 				 * the string.  Given this notion, Perl's
3667 				 * rindex() is at least self-consistent in
3668 				 * that it implicitly clamps positions greater
3669 				 * than the string length to be the string
3670 				 * length.  Where Perl completely loses
3671 				 * coherence, however, is when the specified
3672 				 * substring is the empty string ("").  In
3673 				 * this case, even if the position is
3674 				 * negative, rindex() returns 0 -- and even if
3675 				 * the position is greater than the length,
3676 				 * index() returns the string length.  These
3677 				 * semantics violate the notion that index()
3678 				 * should never return a value less than the
3679 				 * specified position and that rindex() should
3680 				 * never return a value greater than the
3681 				 * specified position.  (One assumes that
3682 				 * these semantics are artifacts of Perl's
3683 				 * implementation and not the results of
3684 				 * deliberate design -- it beggars belief that
3685 				 * even Larry Wall could desire such oddness.)
3686 				 * While in the abstract one would wish for
3687 				 * consistent position semantics across
3688 				 * substr(), index() and rindex() -- or at the
3689 				 * very least self-consistent position
3690 				 * semantics for index() and rindex() -- we
3691 				 * instead opt to keep with the extant Perl
3692 				 * semantics, in all their broken glory.  (Do
3693 				 * we have more desire to maintain Perl's
3694 				 * semantics than Perl does?  Probably.)
3695 				 */
3696 				if (subr == DIF_SUBR_RINDEX) {
3697 					if (pos < 0) {
3698 						if (sublen == 0)
3699 							regs[rd] = 0;
3700 						break;
3701 					}
3702 
3703 					if (pos > len)
3704 						pos = len;
3705 				} else {
3706 					if (pos < 0)
3707 						pos = 0;
3708 
3709 					if (pos >= len) {
3710 						if (sublen == 0)
3711 							regs[rd] = len;
3712 						break;
3713 					}
3714 				}
3715 
3716 				addr = orig + pos;
3717 			}
3718 		}
3719 
3720 		for (regs[rd] = notfound; addr != limit; addr += inc) {
3721 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
3722 				if (subr != DIF_SUBR_STRSTR) {
3723 					/*
3724 					 * As D index() and rindex() are
3725 					 * modeled on Perl (and not on awk),
3726 					 * we return a zero-based (and not a
3727 					 * one-based) index.  (For you Perl
3728 					 * weenies: no, we're not going to add
3729 					 * $[ -- and shouldn't you be at a con
3730 					 * or something?)
3731 					 */
3732 					regs[rd] = (uintptr_t)(addr - orig);
3733 					break;
3734 				}
3735 
3736 				ASSERT(subr == DIF_SUBR_STRSTR);
3737 				regs[rd] = (uintptr_t)addr;
3738 				break;
3739 			}
3740 		}
3741 
3742 		break;
3743 	}
3744 
3745 	case DIF_SUBR_STRTOK: {
3746 		uintptr_t addr = tupregs[0].dttk_value;
3747 		uintptr_t tokaddr = tupregs[1].dttk_value;
3748 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3749 		uintptr_t limit, toklimit = tokaddr + size;
3750 		uint8_t c, tokmap[32];	 /* 256 / 8 */
3751 		char *dest = (char *)mstate->dtms_scratch_ptr;
3752 		int i;
3753 
3754 		/*
3755 		 * Check both the token buffer and (later) the input buffer,
3756 		 * since both could be non-scratch addresses.
3757 		 */
3758 		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3759 			regs[rd] = NULL;
3760 			break;
3761 		}
3762 
3763 		if (!DTRACE_INSCRATCH(mstate, size)) {
3764 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3765 			regs[rd] = NULL;
3766 			break;
3767 		}
3768 
3769 		if (addr == NULL) {
3770 			/*
3771 			 * If the address specified is NULL, we use our saved
3772 			 * strtok pointer from the mstate.  Note that this
3773 			 * means that the saved strtok pointer is _only_
3774 			 * valid within multiple enablings of the same probe --
3775 			 * it behaves like an implicit clause-local variable.
3776 			 */
3777 			addr = mstate->dtms_strtok;
3778 		} else {
3779 			/*
3780 			 * If the user-specified address is non-NULL we must
3781 			 * access check it.  This is the only time we have
3782 			 * a chance to do so, since this address may reside
3783 			 * in the string table of this clause-- future calls
3784 			 * (when we fetch addr from mstate->dtms_strtok)
3785 			 * would fail this access check.
3786 			 */
3787 			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3788 				regs[rd] = NULL;
3789 				break;
3790 			}
3791 		}
3792 
3793 		/*
3794 		 * First, zero the token map, and then process the token
3795 		 * string -- setting a bit in the map for every character
3796 		 * found in the token string.
3797 		 */
3798 		for (i = 0; i < sizeof (tokmap); i++)
3799 			tokmap[i] = 0;
3800 
3801 		for (; tokaddr < toklimit; tokaddr++) {
3802 			if ((c = dtrace_load8(tokaddr)) == '\0')
3803 				break;
3804 
3805 			ASSERT((c >> 3) < sizeof (tokmap));
3806 			tokmap[c >> 3] |= (1 << (c & 0x7));
3807 		}
3808 
3809 		for (limit = addr + size; addr < limit; addr++) {
3810 			/*
3811 			 * We're looking for a character that is _not_ contained
3812 			 * in the token string.
3813 			 */
3814 			if ((c = dtrace_load8(addr)) == '\0')
3815 				break;
3816 
3817 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3818 				break;
3819 		}
3820 
3821 		if (c == '\0') {
3822 			/*
3823 			 * We reached the end of the string without finding
3824 			 * any character that was not in the token string.
3825 			 * We return NULL in this case, and we set the saved
3826 			 * address to NULL as well.
3827 			 */
3828 			regs[rd] = NULL;
3829 			mstate->dtms_strtok = NULL;
3830 			break;
3831 		}
3832 
3833 		/*
3834 		 * From here on, we're copying into the destination string.
3835 		 */
3836 		for (i = 0; addr < limit && i < size - 1; addr++) {
3837 			if ((c = dtrace_load8(addr)) == '\0')
3838 				break;
3839 
3840 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
3841 				break;
3842 
3843 			ASSERT(i < size);
3844 			dest[i++] = c;
3845 		}
3846 
3847 		ASSERT(i < size);
3848 		dest[i] = '\0';
3849 		regs[rd] = (uintptr_t)dest;
3850 		mstate->dtms_scratch_ptr += size;
3851 		mstate->dtms_strtok = addr;
3852 		break;
3853 	}
3854 
3855 	case DIF_SUBR_SUBSTR: {
3856 		uintptr_t s = tupregs[0].dttk_value;
3857 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3858 		char *d = (char *)mstate->dtms_scratch_ptr;
3859 		int64_t index = (int64_t)tupregs[1].dttk_value;
3860 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
3861 		size_t len = dtrace_strlen((char *)s, size);
3862 		int64_t i;
3863 
3864 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
3865 			regs[rd] = NULL;
3866 			break;
3867 		}
3868 
3869 		if (!DTRACE_INSCRATCH(mstate, size)) {
3870 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3871 			regs[rd] = NULL;
3872 			break;
3873 		}
3874 
3875 		if (nargs <= 2)
3876 			remaining = (int64_t)size;
3877 
3878 		if (index < 0) {
3879 			index += len;
3880 
3881 			if (index < 0 && index + remaining > 0) {
3882 				remaining += index;
3883 				index = 0;
3884 			}
3885 		}
3886 
3887 		if (index >= len || index < 0) {
3888 			remaining = 0;
3889 		} else if (remaining < 0) {
3890 			remaining += len - index;
3891 		} else if (index + remaining > size) {
3892 			remaining = size - index;
3893 		}
3894 
3895 		for (i = 0; i < remaining; i++) {
3896 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
3897 				break;
3898 		}
3899 
3900 		d[i] = '\0';
3901 
3902 		mstate->dtms_scratch_ptr += size;
3903 		regs[rd] = (uintptr_t)d;
3904 		break;
3905 	}
3906 
3907 	case DIF_SUBR_GETMAJOR:
3908 #ifdef _LP64
3909 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
3910 #else
3911 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
3912 #endif
3913 		break;
3914 
3915 	case DIF_SUBR_GETMINOR:
3916 #ifdef _LP64
3917 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
3918 #else
3919 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
3920 #endif
3921 		break;
3922 
3923 	case DIF_SUBR_DDI_PATHNAME: {
3924 		/*
3925 		 * This one is a galactic mess.  We are going to roughly
3926 		 * emulate ddi_pathname(), but it's made more complicated
3927 		 * by the fact that we (a) want to include the minor name and
3928 		 * (b) must proceed iteratively instead of recursively.
3929 		 */
3930 		uintptr_t dest = mstate->dtms_scratch_ptr;
3931 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3932 		char *start = (char *)dest, *end = start + size - 1;
3933 		uintptr_t daddr = tupregs[0].dttk_value;
3934 		int64_t minor = (int64_t)tupregs[1].dttk_value;
3935 		char *s;
3936 		int i, len, depth = 0;
3937 
3938 		/*
3939 		 * Due to all the pointer jumping we do and context we must
3940 		 * rely upon, we just mandate that the user must have kernel
3941 		 * read privileges to use this routine.
3942 		 */
3943 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
3944 			*flags |= CPU_DTRACE_KPRIV;
3945 			*illval = daddr;
3946 			regs[rd] = NULL;
3947 		}
3948 
3949 		if (!DTRACE_INSCRATCH(mstate, size)) {
3950 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3951 			regs[rd] = NULL;
3952 			break;
3953 		}
3954 
3955 		*end = '\0';
3956 
3957 		/*
3958 		 * We want to have a name for the minor.  In order to do this,
3959 		 * we need to walk the minor list from the devinfo.  We want
3960 		 * to be sure that we don't infinitely walk a circular list,
3961 		 * so we check for circularity by sending a scout pointer
3962 		 * ahead two elements for every element that we iterate over;
3963 		 * if the list is circular, these will ultimately point to the
3964 		 * same element.  You may recognize this little trick as the
3965 		 * answer to a stupid interview question -- one that always
3966 		 * seems to be asked by those who had to have it laboriously
3967 		 * explained to them, and who can't even concisely describe
3968 		 * the conditions under which one would be forced to resort to
3969 		 * this technique.  Needless to say, those conditions are
3970 		 * found here -- and probably only here.  Is this the only use
3971 		 * of this infamous trick in shipping, production code?  If it
3972 		 * isn't, it probably should be...
3973 		 */
3974 		if (minor != -1) {
3975 			uintptr_t maddr = dtrace_loadptr(daddr +
3976 			    offsetof(struct dev_info, devi_minor));
3977 
3978 			uintptr_t next = offsetof(struct ddi_minor_data, next);
3979 			uintptr_t name = offsetof(struct ddi_minor_data,
3980 			    d_minor) + offsetof(struct ddi_minor, name);
3981 			uintptr_t dev = offsetof(struct ddi_minor_data,
3982 			    d_minor) + offsetof(struct ddi_minor, dev);
3983 			uintptr_t scout;
3984 
3985 			if (maddr != NULL)
3986 				scout = dtrace_loadptr(maddr + next);
3987 
3988 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3989 				uint64_t m;
3990 #ifdef _LP64
3991 				m = dtrace_load64(maddr + dev) & MAXMIN64;
3992 #else
3993 				m = dtrace_load32(maddr + dev) & MAXMIN;
3994 #endif
3995 				if (m != minor) {
3996 					maddr = dtrace_loadptr(maddr + next);
3997 
3998 					if (scout == NULL)
3999 						continue;
4000 
4001 					scout = dtrace_loadptr(scout + next);
4002 
4003 					if (scout == NULL)
4004 						continue;
4005 
4006 					scout = dtrace_loadptr(scout + next);
4007 
4008 					if (scout == NULL)
4009 						continue;
4010 
4011 					if (scout == maddr) {
4012 						*flags |= CPU_DTRACE_ILLOP;
4013 						break;
4014 					}
4015 
4016 					continue;
4017 				}
4018 
4019 				/*
4020 				 * We have the minor data.  Now we need to
4021 				 * copy the minor's name into the end of the
4022 				 * pathname.
4023 				 */
4024 				s = (char *)dtrace_loadptr(maddr + name);
4025 				len = dtrace_strlen(s, size);
4026 
4027 				if (*flags & CPU_DTRACE_FAULT)
4028 					break;
4029 
4030 				if (len != 0) {
4031 					if ((end -= (len + 1)) < start)
4032 						break;
4033 
4034 					*end = ':';
4035 				}
4036 
4037 				for (i = 1; i <= len; i++)
4038 					end[i] = dtrace_load8((uintptr_t)s++);
4039 				break;
4040 			}
4041 		}
4042 
4043 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4044 			ddi_node_state_t devi_state;
4045 
4046 			devi_state = dtrace_load32(daddr +
4047 			    offsetof(struct dev_info, devi_node_state));
4048 
4049 			if (*flags & CPU_DTRACE_FAULT)
4050 				break;
4051 
4052 			if (devi_state >= DS_INITIALIZED) {
4053 				s = (char *)dtrace_loadptr(daddr +
4054 				    offsetof(struct dev_info, devi_addr));
4055 				len = dtrace_strlen(s, size);
4056 
4057 				if (*flags & CPU_DTRACE_FAULT)
4058 					break;
4059 
4060 				if (len != 0) {
4061 					if ((end -= (len + 1)) < start)
4062 						break;
4063 
4064 					*end = '@';
4065 				}
4066 
4067 				for (i = 1; i <= len; i++)
4068 					end[i] = dtrace_load8((uintptr_t)s++);
4069 			}
4070 
4071 			/*
4072 			 * Now for the node name...
4073 			 */
4074 			s = (char *)dtrace_loadptr(daddr +
4075 			    offsetof(struct dev_info, devi_node_name));
4076 
4077 			daddr = dtrace_loadptr(daddr +
4078 			    offsetof(struct dev_info, devi_parent));
4079 
4080 			/*
4081 			 * If our parent is NULL (that is, if we're the root
4082 			 * node), we're going to use the special path
4083 			 * "devices".
4084 			 */
4085 			if (daddr == NULL)
4086 				s = "devices";
4087 
4088 			len = dtrace_strlen(s, size);
4089 			if (*flags & CPU_DTRACE_FAULT)
4090 				break;
4091 
4092 			if ((end -= (len + 1)) < start)
4093 				break;
4094 
4095 			for (i = 1; i <= len; i++)
4096 				end[i] = dtrace_load8((uintptr_t)s++);
4097 			*end = '/';
4098 
4099 			if (depth++ > dtrace_devdepth_max) {
4100 				*flags |= CPU_DTRACE_ILLOP;
4101 				break;
4102 			}
4103 		}
4104 
4105 		if (end < start)
4106 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4107 
4108 		if (daddr == NULL) {
4109 			regs[rd] = (uintptr_t)end;
4110 			mstate->dtms_scratch_ptr += size;
4111 		}
4112 
4113 		break;
4114 	}
4115 
4116 	case DIF_SUBR_STRJOIN: {
4117 		char *d = (char *)mstate->dtms_scratch_ptr;
4118 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4119 		uintptr_t s1 = tupregs[0].dttk_value;
4120 		uintptr_t s2 = tupregs[1].dttk_value;
4121 		int i = 0;
4122 
4123 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4124 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
4125 			regs[rd] = NULL;
4126 			break;
4127 		}
4128 
4129 		if (!DTRACE_INSCRATCH(mstate, size)) {
4130 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4131 			regs[rd] = NULL;
4132 			break;
4133 		}
4134 
4135 		for (;;) {
4136 			if (i >= size) {
4137 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4138 				regs[rd] = NULL;
4139 				break;
4140 			}
4141 
4142 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4143 				i--;
4144 				break;
4145 			}
4146 		}
4147 
4148 		for (;;) {
4149 			if (i >= size) {
4150 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4151 				regs[rd] = NULL;
4152 				break;
4153 			}
4154 
4155 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
4156 				break;
4157 		}
4158 
4159 		if (i < size) {
4160 			mstate->dtms_scratch_ptr += i;
4161 			regs[rd] = (uintptr_t)d;
4162 		}
4163 
4164 		break;
4165 	}
4166 
4167 	case DIF_SUBR_LLTOSTR: {
4168 		int64_t i = (int64_t)tupregs[0].dttk_value;
4169 		int64_t val = i < 0 ? i * -1 : i;
4170 		uint64_t size = 22;	/* enough room for 2^64 in decimal */
4171 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4172 
4173 		if (!DTRACE_INSCRATCH(mstate, size)) {
4174 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4175 			regs[rd] = NULL;
4176 			break;
4177 		}
4178 
4179 		for (*end-- = '\0'; val; val /= 10)
4180 			*end-- = '0' + (val % 10);
4181 
4182 		if (i == 0)
4183 			*end-- = '0';
4184 
4185 		if (i < 0)
4186 			*end-- = '-';
4187 
4188 		regs[rd] = (uintptr_t)end + 1;
4189 		mstate->dtms_scratch_ptr += size;
4190 		break;
4191 	}
4192 
4193 	case DIF_SUBR_HTONS:
4194 	case DIF_SUBR_NTOHS:
4195 #ifdef _BIG_ENDIAN
4196 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
4197 #else
4198 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4199 #endif
4200 		break;
4201 
4202 
4203 	case DIF_SUBR_HTONL:
4204 	case DIF_SUBR_NTOHL:
4205 #ifdef _BIG_ENDIAN
4206 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
4207 #else
4208 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4209 #endif
4210 		break;
4211 
4212 
4213 	case DIF_SUBR_HTONLL:
4214 	case DIF_SUBR_NTOHLL:
4215 #ifdef _BIG_ENDIAN
4216 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
4217 #else
4218 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4219 #endif
4220 		break;
4221 
4222 
4223 	case DIF_SUBR_DIRNAME:
4224 	case DIF_SUBR_BASENAME: {
4225 		char *dest = (char *)mstate->dtms_scratch_ptr;
4226 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4227 		uintptr_t src = tupregs[0].dttk_value;
4228 		int i, j, len = dtrace_strlen((char *)src, size);
4229 		int lastbase = -1, firstbase = -1, lastdir = -1;
4230 		int start, end;
4231 
4232 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4233 			regs[rd] = NULL;
4234 			break;
4235 		}
4236 
4237 		if (!DTRACE_INSCRATCH(mstate, size)) {
4238 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4239 			regs[rd] = NULL;
4240 			break;
4241 		}
4242 
4243 		/*
4244 		 * The basename and dirname for a zero-length string is
4245 		 * defined to be "."
4246 		 */
4247 		if (len == 0) {
4248 			len = 1;
4249 			src = (uintptr_t)".";
4250 		}
4251 
4252 		/*
4253 		 * Start from the back of the string, moving back toward the
4254 		 * front until we see a character that isn't a slash.  That
4255 		 * character is the last character in the basename.
4256 		 */
4257 		for (i = len - 1; i >= 0; i--) {
4258 			if (dtrace_load8(src + i) != '/')
4259 				break;
4260 		}
4261 
4262 		if (i >= 0)
4263 			lastbase = i;
4264 
4265 		/*
4266 		 * Starting from the last character in the basename, move
4267 		 * towards the front until we find a slash.  The character
4268 		 * that we processed immediately before that is the first
4269 		 * character in the basename.
4270 		 */
4271 		for (; i >= 0; i--) {
4272 			if (dtrace_load8(src + i) == '/')
4273 				break;
4274 		}
4275 
4276 		if (i >= 0)
4277 			firstbase = i + 1;
4278 
4279 		/*
4280 		 * Now keep going until we find a non-slash character.  That
4281 		 * character is the last character in the dirname.
4282 		 */
4283 		for (; i >= 0; i--) {
4284 			if (dtrace_load8(src + i) != '/')
4285 				break;
4286 		}
4287 
4288 		if (i >= 0)
4289 			lastdir = i;
4290 
4291 		ASSERT(!(lastbase == -1 && firstbase != -1));
4292 		ASSERT(!(firstbase == -1 && lastdir != -1));
4293 
4294 		if (lastbase == -1) {
4295 			/*
4296 			 * We didn't find a non-slash character.  We know that
4297 			 * the length is non-zero, so the whole string must be
4298 			 * slashes.  In either the dirname or the basename
4299 			 * case, we return '/'.
4300 			 */
4301 			ASSERT(firstbase == -1);
4302 			firstbase = lastbase = lastdir = 0;
4303 		}
4304 
4305 		if (firstbase == -1) {
4306 			/*
4307 			 * The entire string consists only of a basename
4308 			 * component.  If we're looking for dirname, we need
4309 			 * to change our string to be just "."; if we're
4310 			 * looking for a basename, we'll just set the first
4311 			 * character of the basename to be 0.
4312 			 */
4313 			if (subr == DIF_SUBR_DIRNAME) {
4314 				ASSERT(lastdir == -1);
4315 				src = (uintptr_t)".";
4316 				lastdir = 0;
4317 			} else {
4318 				firstbase = 0;
4319 			}
4320 		}
4321 
4322 		if (subr == DIF_SUBR_DIRNAME) {
4323 			if (lastdir == -1) {
4324 				/*
4325 				 * We know that we have a slash in the name --
4326 				 * or lastdir would be set to 0, above.  And
4327 				 * because lastdir is -1, we know that this
4328 				 * slash must be the first character.  (That
4329 				 * is, the full string must be of the form
4330 				 * "/basename".)  In this case, the last
4331 				 * character of the directory name is 0.
4332 				 */
4333 				lastdir = 0;
4334 			}
4335 
4336 			start = 0;
4337 			end = lastdir;
4338 		} else {
4339 			ASSERT(subr == DIF_SUBR_BASENAME);
4340 			ASSERT(firstbase != -1 && lastbase != -1);
4341 			start = firstbase;
4342 			end = lastbase;
4343 		}
4344 
4345 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
4346 			dest[j] = dtrace_load8(src + i);
4347 
4348 		dest[j] = '\0';
4349 		regs[rd] = (uintptr_t)dest;
4350 		mstate->dtms_scratch_ptr += size;
4351 		break;
4352 	}
4353 
4354 	case DIF_SUBR_CLEANPATH: {
4355 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4356 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4357 		uintptr_t src = tupregs[0].dttk_value;
4358 		int i = 0, j = 0;
4359 
4360 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
4361 			regs[rd] = NULL;
4362 			break;
4363 		}
4364 
4365 		if (!DTRACE_INSCRATCH(mstate, size)) {
4366 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4367 			regs[rd] = NULL;
4368 			break;
4369 		}
4370 
4371 		/*
4372 		 * Move forward, loading each character.
4373 		 */
4374 		do {
4375 			c = dtrace_load8(src + i++);
4376 next:
4377 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
4378 				break;
4379 
4380 			if (c != '/') {
4381 				dest[j++] = c;
4382 				continue;
4383 			}
4384 
4385 			c = dtrace_load8(src + i++);
4386 
4387 			if (c == '/') {
4388 				/*
4389 				 * We have two slashes -- we can just advance
4390 				 * to the next character.
4391 				 */
4392 				goto next;
4393 			}
4394 
4395 			if (c != '.') {
4396 				/*
4397 				 * This is not "." and it's not ".." -- we can
4398 				 * just store the "/" and this character and
4399 				 * drive on.
4400 				 */
4401 				dest[j++] = '/';
4402 				dest[j++] = c;
4403 				continue;
4404 			}
4405 
4406 			c = dtrace_load8(src + i++);
4407 
4408 			if (c == '/') {
4409 				/*
4410 				 * This is a "/./" component.  We're not going
4411 				 * to store anything in the destination buffer;
4412 				 * we're just going to go to the next component.
4413 				 */
4414 				goto next;
4415 			}
4416 
4417 			if (c != '.') {
4418 				/*
4419 				 * This is not ".." -- we can just store the
4420 				 * "/." and this character and continue
4421 				 * processing.
4422 				 */
4423 				dest[j++] = '/';
4424 				dest[j++] = '.';
4425 				dest[j++] = c;
4426 				continue;
4427 			}
4428 
4429 			c = dtrace_load8(src + i++);
4430 
4431 			if (c != '/' && c != '\0') {
4432 				/*
4433 				 * This is not ".." -- it's "..[mumble]".
4434 				 * We'll store the "/.." and this character
4435 				 * and continue processing.
4436 				 */
4437 				dest[j++] = '/';
4438 				dest[j++] = '.';
4439 				dest[j++] = '.';
4440 				dest[j++] = c;
4441 				continue;
4442 			}
4443 
4444 			/*
4445 			 * This is "/../" or "/..\0".  We need to back up
4446 			 * our destination pointer until we find a "/".
4447 			 */
4448 			i--;
4449 			while (j != 0 && dest[--j] != '/')
4450 				continue;
4451 
4452 			if (c == '\0')
4453 				dest[++j] = '/';
4454 		} while (c != '\0');
4455 
4456 		dest[j] = '\0';
4457 		regs[rd] = (uintptr_t)dest;
4458 		mstate->dtms_scratch_ptr += size;
4459 		break;
4460 	}
4461 
4462 	case DIF_SUBR_INET_NTOA:
4463 	case DIF_SUBR_INET_NTOA6:
4464 	case DIF_SUBR_INET_NTOP: {
4465 		size_t size;
4466 		int af, argi, i;
4467 		char *base, *end;
4468 
4469 		if (subr == DIF_SUBR_INET_NTOP) {
4470 			af = (int)tupregs[0].dttk_value;
4471 			argi = 1;
4472 		} else {
4473 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4474 			argi = 0;
4475 		}
4476 
4477 		if (af == AF_INET) {
4478 			ipaddr_t ip4;
4479 			uint8_t *ptr8, val;
4480 
4481 			/*
4482 			 * Safely load the IPv4 address.
4483 			 */
4484 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
4485 
4486 			/*
4487 			 * Check an IPv4 string will fit in scratch.
4488 			 */
4489 			size = INET_ADDRSTRLEN;
4490 			if (!DTRACE_INSCRATCH(mstate, size)) {
4491 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4492 				regs[rd] = NULL;
4493 				break;
4494 			}
4495 			base = (char *)mstate->dtms_scratch_ptr;
4496 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4497 
4498 			/*
4499 			 * Stringify as a dotted decimal quad.
4500 			 */
4501 			*end-- = '\0';
4502 			ptr8 = (uint8_t *)&ip4;
4503 			for (i = 3; i >= 0; i--) {
4504 				val = ptr8[i];
4505 
4506 				if (val == 0) {
4507 					*end-- = '0';
4508 				} else {
4509 					for (; val; val /= 10) {
4510 						*end-- = '0' + (val % 10);
4511 					}
4512 				}
4513 
4514 				if (i > 0)
4515 					*end-- = '.';
4516 			}
4517 			ASSERT(end + 1 >= base);
4518 
4519 		} else if (af == AF_INET6) {
4520 			struct in6_addr ip6;
4521 			int firstzero, tryzero, numzero, v6end;
4522 			uint16_t val;
4523 			const char digits[] = "0123456789abcdef";
4524 
4525 			/*
4526 			 * Stringify using RFC 1884 convention 2 - 16 bit
4527 			 * hexadecimal values with a zero-run compression.
4528 			 * Lower case hexadecimal digits are used.
4529 			 * 	eg, fe80::214:4fff:fe0b:76c8.
4530 			 * The IPv4 embedded form is returned for inet_ntop,
4531 			 * just the IPv4 string is returned for inet_ntoa6.
4532 			 */
4533 
4534 			/*
4535 			 * Safely load the IPv6 address.
4536 			 */
4537 			dtrace_bcopy(
4538 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
4539 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4540 
4541 			/*
4542 			 * Check an IPv6 string will fit in scratch.
4543 			 */
4544 			size = INET6_ADDRSTRLEN;
4545 			if (!DTRACE_INSCRATCH(mstate, size)) {
4546 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4547 				regs[rd] = NULL;
4548 				break;
4549 			}
4550 			base = (char *)mstate->dtms_scratch_ptr;
4551 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4552 			*end-- = '\0';
4553 
4554 			/*
4555 			 * Find the longest run of 16 bit zero values
4556 			 * for the single allowed zero compression - "::".
4557 			 */
4558 			firstzero = -1;
4559 			tryzero = -1;
4560 			numzero = 1;
4561 			for (i = 0; i < sizeof (struct in6_addr); i++) {
4562 				if (ip6._S6_un._S6_u8[i] == 0 &&
4563 				    tryzero == -1 && i % 2 == 0) {
4564 					tryzero = i;
4565 					continue;
4566 				}
4567 
4568 				if (tryzero != -1 &&
4569 				    (ip6._S6_un._S6_u8[i] != 0 ||
4570 				    i == sizeof (struct in6_addr) - 1)) {
4571 
4572 					if (i - tryzero <= numzero) {
4573 						tryzero = -1;
4574 						continue;
4575 					}
4576 
4577 					firstzero = tryzero;
4578 					numzero = i - i % 2 - tryzero;
4579 					tryzero = -1;
4580 
4581 					if (ip6._S6_un._S6_u8[i] == 0 &&
4582 					    i == sizeof (struct in6_addr) - 1)
4583 						numzero += 2;
4584 				}
4585 			}
4586 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4587 
4588 			/*
4589 			 * Check for an IPv4 embedded address.
4590 			 */
4591 			v6end = sizeof (struct in6_addr) - 2;
4592 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4593 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
4594 				for (i = sizeof (struct in6_addr) - 1;
4595 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
4596 					ASSERT(end >= base);
4597 
4598 					val = ip6._S6_un._S6_u8[i];
4599 
4600 					if (val == 0) {
4601 						*end-- = '0';
4602 					} else {
4603 						for (; val; val /= 10) {
4604 							*end-- = '0' + val % 10;
4605 						}
4606 					}
4607 
4608 					if (i > DTRACE_V4MAPPED_OFFSET)
4609 						*end-- = '.';
4610 				}
4611 
4612 				if (subr == DIF_SUBR_INET_NTOA6)
4613 					goto inetout;
4614 
4615 				/*
4616 				 * Set v6end to skip the IPv4 address that
4617 				 * we have already stringified.
4618 				 */
4619 				v6end = 10;
4620 			}
4621 
4622 			/*
4623 			 * Build the IPv6 string by working through the
4624 			 * address in reverse.
4625 			 */
4626 			for (i = v6end; i >= 0; i -= 2) {
4627 				ASSERT(end >= base);
4628 
4629 				if (i == firstzero + numzero - 2) {
4630 					*end-- = ':';
4631 					*end-- = ':';
4632 					i -= numzero - 2;
4633 					continue;
4634 				}
4635 
4636 				if (i < 14 && i != firstzero - 2)
4637 					*end-- = ':';
4638 
4639 				val = (ip6._S6_un._S6_u8[i] << 8) +
4640 				    ip6._S6_un._S6_u8[i + 1];
4641 
4642 				if (val == 0) {
4643 					*end-- = '0';
4644 				} else {
4645 					for (; val; val /= 16) {
4646 						*end-- = digits[val % 16];
4647 					}
4648 				}
4649 			}
4650 			ASSERT(end + 1 >= base);
4651 
4652 		} else {
4653 			/*
4654 			 * The user didn't use AH_INET or AH_INET6.
4655 			 */
4656 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4657 			regs[rd] = NULL;
4658 			break;
4659 		}
4660 
4661 inetout:	regs[rd] = (uintptr_t)end + 1;
4662 		mstate->dtms_scratch_ptr += size;
4663 		break;
4664 	}
4665 
4666 	}
4667 }
4668 
4669 /*
4670  * Emulate the execution of DTrace IR instructions specified by the given
4671  * DIF object.  This function is deliberately void of assertions as all of
4672  * the necessary checks are handled by a call to dtrace_difo_validate().
4673  */
4674 static uint64_t
4675 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4676     dtrace_vstate_t *vstate, dtrace_state_t *state)
4677 {
4678 	const dif_instr_t *text = difo->dtdo_buf;
4679 	const uint_t textlen = difo->dtdo_len;
4680 	const char *strtab = difo->dtdo_strtab;
4681 	const uint64_t *inttab = difo->dtdo_inttab;
4682 
4683 	uint64_t rval = 0;
4684 	dtrace_statvar_t *svar;
4685 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4686 	dtrace_difv_t *v;
4687 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4688 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4689 
4690 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4691 	uint64_t regs[DIF_DIR_NREGS];
4692 	uint64_t *tmp;
4693 
4694 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4695 	int64_t cc_r;
4696 	uint_t pc = 0, id, opc;
4697 	uint8_t ttop = 0;
4698 	dif_instr_t instr;
4699 	uint_t r1, r2, rd;
4700 
4701 	/*
4702 	 * We stash the current DIF object into the machine state: we need it
4703 	 * for subsequent access checking.
4704 	 */
4705 	mstate->dtms_difo = difo;
4706 
4707 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
4708 
4709 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4710 		opc = pc;
4711 
4712 		instr = text[pc++];
4713 		r1 = DIF_INSTR_R1(instr);
4714 		r2 = DIF_INSTR_R2(instr);
4715 		rd = DIF_INSTR_RD(instr);
4716 
4717 		switch (DIF_INSTR_OP(instr)) {
4718 		case DIF_OP_OR:
4719 			regs[rd] = regs[r1] | regs[r2];
4720 			break;
4721 		case DIF_OP_XOR:
4722 			regs[rd] = regs[r1] ^ regs[r2];
4723 			break;
4724 		case DIF_OP_AND:
4725 			regs[rd] = regs[r1] & regs[r2];
4726 			break;
4727 		case DIF_OP_SLL:
4728 			regs[rd] = regs[r1] << regs[r2];
4729 			break;
4730 		case DIF_OP_SRL:
4731 			regs[rd] = regs[r1] >> regs[r2];
4732 			break;
4733 		case DIF_OP_SUB:
4734 			regs[rd] = regs[r1] - regs[r2];
4735 			break;
4736 		case DIF_OP_ADD:
4737 			regs[rd] = regs[r1] + regs[r2];
4738 			break;
4739 		case DIF_OP_MUL:
4740 			regs[rd] = regs[r1] * regs[r2];
4741 			break;
4742 		case DIF_OP_SDIV:
4743 			if (regs[r2] == 0) {
4744 				regs[rd] = 0;
4745 				*flags |= CPU_DTRACE_DIVZERO;
4746 			} else {
4747 				regs[rd] = (int64_t)regs[r1] /
4748 				    (int64_t)regs[r2];
4749 			}
4750 			break;
4751 
4752 		case DIF_OP_UDIV:
4753 			if (regs[r2] == 0) {
4754 				regs[rd] = 0;
4755 				*flags |= CPU_DTRACE_DIVZERO;
4756 			} else {
4757 				regs[rd] = regs[r1] / regs[r2];
4758 			}
4759 			break;
4760 
4761 		case DIF_OP_SREM:
4762 			if (regs[r2] == 0) {
4763 				regs[rd] = 0;
4764 				*flags |= CPU_DTRACE_DIVZERO;
4765 			} else {
4766 				regs[rd] = (int64_t)regs[r1] %
4767 				    (int64_t)regs[r2];
4768 			}
4769 			break;
4770 
4771 		case DIF_OP_UREM:
4772 			if (regs[r2] == 0) {
4773 				regs[rd] = 0;
4774 				*flags |= CPU_DTRACE_DIVZERO;
4775 			} else {
4776 				regs[rd] = regs[r1] % regs[r2];
4777 			}
4778 			break;
4779 
4780 		case DIF_OP_NOT:
4781 			regs[rd] = ~regs[r1];
4782 			break;
4783 		case DIF_OP_MOV:
4784 			regs[rd] = regs[r1];
4785 			break;
4786 		case DIF_OP_CMP:
4787 			cc_r = regs[r1] - regs[r2];
4788 			cc_n = cc_r < 0;
4789 			cc_z = cc_r == 0;
4790 			cc_v = 0;
4791 			cc_c = regs[r1] < regs[r2];
4792 			break;
4793 		case DIF_OP_TST:
4794 			cc_n = cc_v = cc_c = 0;
4795 			cc_z = regs[r1] == 0;
4796 			break;
4797 		case DIF_OP_BA:
4798 			pc = DIF_INSTR_LABEL(instr);
4799 			break;
4800 		case DIF_OP_BE:
4801 			if (cc_z)
4802 				pc = DIF_INSTR_LABEL(instr);
4803 			break;
4804 		case DIF_OP_BNE:
4805 			if (cc_z == 0)
4806 				pc = DIF_INSTR_LABEL(instr);
4807 			break;
4808 		case DIF_OP_BG:
4809 			if ((cc_z | (cc_n ^ cc_v)) == 0)
4810 				pc = DIF_INSTR_LABEL(instr);
4811 			break;
4812 		case DIF_OP_BGU:
4813 			if ((cc_c | cc_z) == 0)
4814 				pc = DIF_INSTR_LABEL(instr);
4815 			break;
4816 		case DIF_OP_BGE:
4817 			if ((cc_n ^ cc_v) == 0)
4818 				pc = DIF_INSTR_LABEL(instr);
4819 			break;
4820 		case DIF_OP_BGEU:
4821 			if (cc_c == 0)
4822 				pc = DIF_INSTR_LABEL(instr);
4823 			break;
4824 		case DIF_OP_BL:
4825 			if (cc_n ^ cc_v)
4826 				pc = DIF_INSTR_LABEL(instr);
4827 			break;
4828 		case DIF_OP_BLU:
4829 			if (cc_c)
4830 				pc = DIF_INSTR_LABEL(instr);
4831 			break;
4832 		case DIF_OP_BLE:
4833 			if (cc_z | (cc_n ^ cc_v))
4834 				pc = DIF_INSTR_LABEL(instr);
4835 			break;
4836 		case DIF_OP_BLEU:
4837 			if (cc_c | cc_z)
4838 				pc = DIF_INSTR_LABEL(instr);
4839 			break;
4840 		case DIF_OP_RLDSB:
4841 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4842 				*flags |= CPU_DTRACE_KPRIV;
4843 				*illval = regs[r1];
4844 				break;
4845 			}
4846 			/*FALLTHROUGH*/
4847 		case DIF_OP_LDSB:
4848 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
4849 			break;
4850 		case DIF_OP_RLDSH:
4851 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4852 				*flags |= CPU_DTRACE_KPRIV;
4853 				*illval = regs[r1];
4854 				break;
4855 			}
4856 			/*FALLTHROUGH*/
4857 		case DIF_OP_LDSH:
4858 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
4859 			break;
4860 		case DIF_OP_RLDSW:
4861 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4862 				*flags |= CPU_DTRACE_KPRIV;
4863 				*illval = regs[r1];
4864 				break;
4865 			}
4866 			/*FALLTHROUGH*/
4867 		case DIF_OP_LDSW:
4868 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
4869 			break;
4870 		case DIF_OP_RLDUB:
4871 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4872 				*flags |= CPU_DTRACE_KPRIV;
4873 				*illval = regs[r1];
4874 				break;
4875 			}
4876 			/*FALLTHROUGH*/
4877 		case DIF_OP_LDUB:
4878 			regs[rd] = dtrace_load8(regs[r1]);
4879 			break;
4880 		case DIF_OP_RLDUH:
4881 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4882 				*flags |= CPU_DTRACE_KPRIV;
4883 				*illval = regs[r1];
4884 				break;
4885 			}
4886 			/*FALLTHROUGH*/
4887 		case DIF_OP_LDUH:
4888 			regs[rd] = dtrace_load16(regs[r1]);
4889 			break;
4890 		case DIF_OP_RLDUW:
4891 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4892 				*flags |= CPU_DTRACE_KPRIV;
4893 				*illval = regs[r1];
4894 				break;
4895 			}
4896 			/*FALLTHROUGH*/
4897 		case DIF_OP_LDUW:
4898 			regs[rd] = dtrace_load32(regs[r1]);
4899 			break;
4900 		case DIF_OP_RLDX:
4901 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
4902 				*flags |= CPU_DTRACE_KPRIV;
4903 				*illval = regs[r1];
4904 				break;
4905 			}
4906 			/*FALLTHROUGH*/
4907 		case DIF_OP_LDX:
4908 			regs[rd] = dtrace_load64(regs[r1]);
4909 			break;
4910 		case DIF_OP_ULDSB:
4911 			regs[rd] = (int8_t)
4912 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4913 			break;
4914 		case DIF_OP_ULDSH:
4915 			regs[rd] = (int16_t)
4916 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4917 			break;
4918 		case DIF_OP_ULDSW:
4919 			regs[rd] = (int32_t)
4920 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4921 			break;
4922 		case DIF_OP_ULDUB:
4923 			regs[rd] =
4924 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4925 			break;
4926 		case DIF_OP_ULDUH:
4927 			regs[rd] =
4928 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4929 			break;
4930 		case DIF_OP_ULDUW:
4931 			regs[rd] =
4932 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4933 			break;
4934 		case DIF_OP_ULDX:
4935 			regs[rd] =
4936 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
4937 			break;
4938 		case DIF_OP_RET:
4939 			rval = regs[rd];
4940 			pc = textlen;
4941 			break;
4942 		case DIF_OP_NOP:
4943 			break;
4944 		case DIF_OP_SETX:
4945 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
4946 			break;
4947 		case DIF_OP_SETS:
4948 			regs[rd] = (uint64_t)(uintptr_t)
4949 			    (strtab + DIF_INSTR_STRING(instr));
4950 			break;
4951 		case DIF_OP_SCMP: {
4952 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
4953 			uintptr_t s1 = regs[r1];
4954 			uintptr_t s2 = regs[r2];
4955 
4956 			if (s1 != NULL &&
4957 			    !dtrace_strcanload(s1, sz, mstate, vstate))
4958 				break;
4959 			if (s2 != NULL &&
4960 			    !dtrace_strcanload(s2, sz, mstate, vstate))
4961 				break;
4962 
4963 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
4964 
4965 			cc_n = cc_r < 0;
4966 			cc_z = cc_r == 0;
4967 			cc_v = cc_c = 0;
4968 			break;
4969 		}
4970 		case DIF_OP_LDGA:
4971 			regs[rd] = dtrace_dif_variable(mstate, state,
4972 			    r1, regs[r2]);
4973 			break;
4974 		case DIF_OP_LDGS:
4975 			id = DIF_INSTR_VAR(instr);
4976 
4977 			if (id >= DIF_VAR_OTHER_UBASE) {
4978 				uintptr_t a;
4979 
4980 				id -= DIF_VAR_OTHER_UBASE;
4981 				svar = vstate->dtvs_globals[id];
4982 				ASSERT(svar != NULL);
4983 				v = &svar->dtsv_var;
4984 
4985 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
4986 					regs[rd] = svar->dtsv_data;
4987 					break;
4988 				}
4989 
4990 				a = (uintptr_t)svar->dtsv_data;
4991 
4992 				if (*(uint8_t *)a == UINT8_MAX) {
4993 					/*
4994 					 * If the 0th byte is set to UINT8_MAX
4995 					 * then this is to be treated as a
4996 					 * reference to a NULL variable.
4997 					 */
4998 					regs[rd] = NULL;
4999 				} else {
5000 					regs[rd] = a + sizeof (uint64_t);
5001 				}
5002 
5003 				break;
5004 			}
5005 
5006 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5007 			break;
5008 
5009 		case DIF_OP_STGS:
5010 			id = DIF_INSTR_VAR(instr);
5011 
5012 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5013 			id -= DIF_VAR_OTHER_UBASE;
5014 
5015 			svar = vstate->dtvs_globals[id];
5016 			ASSERT(svar != NULL);
5017 			v = &svar->dtsv_var;
5018 
5019 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5020 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5021 
5022 				ASSERT(a != NULL);
5023 				ASSERT(svar->dtsv_size != 0);
5024 
5025 				if (regs[rd] == NULL) {
5026 					*(uint8_t *)a = UINT8_MAX;
5027 					break;
5028 				} else {
5029 					*(uint8_t *)a = 0;
5030 					a += sizeof (uint64_t);
5031 				}
5032 				if (!dtrace_vcanload(
5033 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5034 				    mstate, vstate))
5035 					break;
5036 
5037 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5038 				    (void *)a, &v->dtdv_type);
5039 				break;
5040 			}
5041 
5042 			svar->dtsv_data = regs[rd];
5043 			break;
5044 
5045 		case DIF_OP_LDTA:
5046 			/*
5047 			 * There are no DTrace built-in thread-local arrays at
5048 			 * present.  This opcode is saved for future work.
5049 			 */
5050 			*flags |= CPU_DTRACE_ILLOP;
5051 			regs[rd] = 0;
5052 			break;
5053 
5054 		case DIF_OP_LDLS:
5055 			id = DIF_INSTR_VAR(instr);
5056 
5057 			if (id < DIF_VAR_OTHER_UBASE) {
5058 				/*
5059 				 * For now, this has no meaning.
5060 				 */
5061 				regs[rd] = 0;
5062 				break;
5063 			}
5064 
5065 			id -= DIF_VAR_OTHER_UBASE;
5066 
5067 			ASSERT(id < vstate->dtvs_nlocals);
5068 			ASSERT(vstate->dtvs_locals != NULL);
5069 
5070 			svar = vstate->dtvs_locals[id];
5071 			ASSERT(svar != NULL);
5072 			v = &svar->dtsv_var;
5073 
5074 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5075 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5076 				size_t sz = v->dtdv_type.dtdt_size;
5077 
5078 				sz += sizeof (uint64_t);
5079 				ASSERT(svar->dtsv_size == NCPU * sz);
5080 				a += CPU->cpu_id * sz;
5081 
5082 				if (*(uint8_t *)a == UINT8_MAX) {
5083 					/*
5084 					 * If the 0th byte is set to UINT8_MAX
5085 					 * then this is to be treated as a
5086 					 * reference to a NULL variable.
5087 					 */
5088 					regs[rd] = NULL;
5089 				} else {
5090 					regs[rd] = a + sizeof (uint64_t);
5091 				}
5092 
5093 				break;
5094 			}
5095 
5096 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5097 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5098 			regs[rd] = tmp[CPU->cpu_id];
5099 			break;
5100 
5101 		case DIF_OP_STLS:
5102 			id = DIF_INSTR_VAR(instr);
5103 
5104 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5105 			id -= DIF_VAR_OTHER_UBASE;
5106 			ASSERT(id < vstate->dtvs_nlocals);
5107 
5108 			ASSERT(vstate->dtvs_locals != NULL);
5109 			svar = vstate->dtvs_locals[id];
5110 			ASSERT(svar != NULL);
5111 			v = &svar->dtsv_var;
5112 
5113 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5114 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5115 				size_t sz = v->dtdv_type.dtdt_size;
5116 
5117 				sz += sizeof (uint64_t);
5118 				ASSERT(svar->dtsv_size == NCPU * sz);
5119 				a += CPU->cpu_id * sz;
5120 
5121 				if (regs[rd] == NULL) {
5122 					*(uint8_t *)a = UINT8_MAX;
5123 					break;
5124 				} else {
5125 					*(uint8_t *)a = 0;
5126 					a += sizeof (uint64_t);
5127 				}
5128 
5129 				if (!dtrace_vcanload(
5130 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5131 				    mstate, vstate))
5132 					break;
5133 
5134 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5135 				    (void *)a, &v->dtdv_type);
5136 				break;
5137 			}
5138 
5139 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5140 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5141 			tmp[CPU->cpu_id] = regs[rd];
5142 			break;
5143 
5144 		case DIF_OP_LDTS: {
5145 			dtrace_dynvar_t *dvar;
5146 			dtrace_key_t *key;
5147 
5148 			id = DIF_INSTR_VAR(instr);
5149 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5150 			id -= DIF_VAR_OTHER_UBASE;
5151 			v = &vstate->dtvs_tlocals[id];
5152 
5153 			key = &tupregs[DIF_DTR_NREGS];
5154 			key[0].dttk_value = (uint64_t)id;
5155 			key[0].dttk_size = 0;
5156 			DTRACE_TLS_THRKEY(key[1].dttk_value);
5157 			key[1].dttk_size = 0;
5158 
5159 			dvar = dtrace_dynvar(dstate, 2, key,
5160 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5161 			    mstate, vstate);
5162 
5163 			if (dvar == NULL) {
5164 				regs[rd] = 0;
5165 				break;
5166 			}
5167 
5168 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5169 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5170 			} else {
5171 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
5172 			}
5173 
5174 			break;
5175 		}
5176 
5177 		case DIF_OP_STTS: {
5178 			dtrace_dynvar_t *dvar;
5179 			dtrace_key_t *key;
5180 
5181 			id = DIF_INSTR_VAR(instr);
5182 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5183 			id -= DIF_VAR_OTHER_UBASE;
5184 
5185 			key = &tupregs[DIF_DTR_NREGS];
5186 			key[0].dttk_value = (uint64_t)id;
5187 			key[0].dttk_size = 0;
5188 			DTRACE_TLS_THRKEY(key[1].dttk_value);
5189 			key[1].dttk_size = 0;
5190 			v = &vstate->dtvs_tlocals[id];
5191 
5192 			dvar = dtrace_dynvar(dstate, 2, key,
5193 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5194 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5195 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
5196 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5197 
5198 			/*
5199 			 * Given that we're storing to thread-local data,
5200 			 * we need to flush our predicate cache.
5201 			 */
5202 			curthread->t_predcache = NULL;
5203 
5204 			if (dvar == NULL)
5205 				break;
5206 
5207 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5208 				if (!dtrace_vcanload(
5209 				    (void *)(uintptr_t)regs[rd],
5210 				    &v->dtdv_type, mstate, vstate))
5211 					break;
5212 
5213 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5214 				    dvar->dtdv_data, &v->dtdv_type);
5215 			} else {
5216 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
5217 			}
5218 
5219 			break;
5220 		}
5221 
5222 		case DIF_OP_SRA:
5223 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
5224 			break;
5225 
5226 		case DIF_OP_CALL:
5227 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5228 			    regs, tupregs, ttop, mstate, state);
5229 			break;
5230 
5231 		case DIF_OP_PUSHTR:
5232 			if (ttop == DIF_DTR_NREGS) {
5233 				*flags |= CPU_DTRACE_TUPOFLOW;
5234 				break;
5235 			}
5236 
5237 			if (r1 == DIF_TYPE_STRING) {
5238 				/*
5239 				 * If this is a string type and the size is 0,
5240 				 * we'll use the system-wide default string
5241 				 * size.  Note that we are _not_ looking at
5242 				 * the value of the DTRACEOPT_STRSIZE option;
5243 				 * had this been set, we would expect to have
5244 				 * a non-zero size value in the "pushtr".
5245 				 */
5246 				tupregs[ttop].dttk_size =
5247 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
5248 				    regs[r2] ? regs[r2] :
5249 				    dtrace_strsize_default) + 1;
5250 			} else {
5251 				tupregs[ttop].dttk_size = regs[r2];
5252 			}
5253 
5254 			tupregs[ttop++].dttk_value = regs[rd];
5255 			break;
5256 
5257 		case DIF_OP_PUSHTV:
5258 			if (ttop == DIF_DTR_NREGS) {
5259 				*flags |= CPU_DTRACE_TUPOFLOW;
5260 				break;
5261 			}
5262 
5263 			tupregs[ttop].dttk_value = regs[rd];
5264 			tupregs[ttop++].dttk_size = 0;
5265 			break;
5266 
5267 		case DIF_OP_POPTS:
5268 			if (ttop != 0)
5269 				ttop--;
5270 			break;
5271 
5272 		case DIF_OP_FLUSHTS:
5273 			ttop = 0;
5274 			break;
5275 
5276 		case DIF_OP_LDGAA:
5277 		case DIF_OP_LDTAA: {
5278 			dtrace_dynvar_t *dvar;
5279 			dtrace_key_t *key = tupregs;
5280 			uint_t nkeys = ttop;
5281 
5282 			id = DIF_INSTR_VAR(instr);
5283 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5284 			id -= DIF_VAR_OTHER_UBASE;
5285 
5286 			key[nkeys].dttk_value = (uint64_t)id;
5287 			key[nkeys++].dttk_size = 0;
5288 
5289 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5290 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5291 				key[nkeys++].dttk_size = 0;
5292 				v = &vstate->dtvs_tlocals[id];
5293 			} else {
5294 				v = &vstate->dtvs_globals[id]->dtsv_var;
5295 			}
5296 
5297 			dvar = dtrace_dynvar(dstate, nkeys, key,
5298 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5299 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5300 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5301 
5302 			if (dvar == NULL) {
5303 				regs[rd] = 0;
5304 				break;
5305 			}
5306 
5307 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5308 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5309 			} else {
5310 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
5311 			}
5312 
5313 			break;
5314 		}
5315 
5316 		case DIF_OP_STGAA:
5317 		case DIF_OP_STTAA: {
5318 			dtrace_dynvar_t *dvar;
5319 			dtrace_key_t *key = tupregs;
5320 			uint_t nkeys = ttop;
5321 
5322 			id = DIF_INSTR_VAR(instr);
5323 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5324 			id -= DIF_VAR_OTHER_UBASE;
5325 
5326 			key[nkeys].dttk_value = (uint64_t)id;
5327 			key[nkeys++].dttk_size = 0;
5328 
5329 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5330 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5331 				key[nkeys++].dttk_size = 0;
5332 				v = &vstate->dtvs_tlocals[id];
5333 			} else {
5334 				v = &vstate->dtvs_globals[id]->dtsv_var;
5335 			}
5336 
5337 			dvar = dtrace_dynvar(dstate, nkeys, key,
5338 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5339 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5340 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
5341 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5342 
5343 			if (dvar == NULL)
5344 				break;
5345 
5346 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5347 				if (!dtrace_vcanload(
5348 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5349 				    mstate, vstate))
5350 					break;
5351 
5352 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5353 				    dvar->dtdv_data, &v->dtdv_type);
5354 			} else {
5355 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
5356 			}
5357 
5358 			break;
5359 		}
5360 
5361 		case DIF_OP_ALLOCS: {
5362 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5363 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5364 
5365 			/*
5366 			 * Rounding up the user allocation size could have
5367 			 * overflowed large, bogus allocations (like -1ULL) to
5368 			 * 0.
5369 			 */
5370 			if (size < regs[r1] ||
5371 			    !DTRACE_INSCRATCH(mstate, size)) {
5372 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5373 				regs[rd] = NULL;
5374 				break;
5375 			}
5376 
5377 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5378 			mstate->dtms_scratch_ptr += size;
5379 			regs[rd] = ptr;
5380 			break;
5381 		}
5382 
5383 		case DIF_OP_COPYS:
5384 			if (!dtrace_canstore(regs[rd], regs[r2],
5385 			    mstate, vstate)) {
5386 				*flags |= CPU_DTRACE_BADADDR;
5387 				*illval = regs[rd];
5388 				break;
5389 			}
5390 
5391 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5392 				break;
5393 
5394 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
5395 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5396 			break;
5397 
5398 		case DIF_OP_STB:
5399 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5400 				*flags |= CPU_DTRACE_BADADDR;
5401 				*illval = regs[rd];
5402 				break;
5403 			}
5404 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5405 			break;
5406 
5407 		case DIF_OP_STH:
5408 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5409 				*flags |= CPU_DTRACE_BADADDR;
5410 				*illval = regs[rd];
5411 				break;
5412 			}
5413 			if (regs[rd] & 1) {
5414 				*flags |= CPU_DTRACE_BADALIGN;
5415 				*illval = regs[rd];
5416 				break;
5417 			}
5418 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5419 			break;
5420 
5421 		case DIF_OP_STW:
5422 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5423 				*flags |= CPU_DTRACE_BADADDR;
5424 				*illval = regs[rd];
5425 				break;
5426 			}
5427 			if (regs[rd] & 3) {
5428 				*flags |= CPU_DTRACE_BADALIGN;
5429 				*illval = regs[rd];
5430 				break;
5431 			}
5432 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5433 			break;
5434 
5435 		case DIF_OP_STX:
5436 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5437 				*flags |= CPU_DTRACE_BADADDR;
5438 				*illval = regs[rd];
5439 				break;
5440 			}
5441 			if (regs[rd] & 7) {
5442 				*flags |= CPU_DTRACE_BADALIGN;
5443 				*illval = regs[rd];
5444 				break;
5445 			}
5446 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5447 			break;
5448 		}
5449 	}
5450 
5451 	if (!(*flags & CPU_DTRACE_FAULT))
5452 		return (rval);
5453 
5454 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5455 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5456 
5457 	return (0);
5458 }
5459 
5460 static void
5461 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5462 {
5463 	dtrace_probe_t *probe = ecb->dte_probe;
5464 	dtrace_provider_t *prov = probe->dtpr_provider;
5465 	char c[DTRACE_FULLNAMELEN + 80], *str;
5466 	char *msg = "dtrace: breakpoint action at probe ";
5467 	char *ecbmsg = " (ecb ";
5468 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5469 	uintptr_t val = (uintptr_t)ecb;
5470 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5471 
5472 	if (dtrace_destructive_disallow)
5473 		return;
5474 
5475 	/*
5476 	 * It's impossible to be taking action on the NULL probe.
5477 	 */
5478 	ASSERT(probe != NULL);
5479 
5480 	/*
5481 	 * This is a poor man's (destitute man's?) sprintf():  we want to
5482 	 * print the provider name, module name, function name and name of
5483 	 * the probe, along with the hex address of the ECB with the breakpoint
5484 	 * action -- all of which we must place in the character buffer by
5485 	 * hand.
5486 	 */
5487 	while (*msg != '\0')
5488 		c[i++] = *msg++;
5489 
5490 	for (str = prov->dtpv_name; *str != '\0'; str++)
5491 		c[i++] = *str;
5492 	c[i++] = ':';
5493 
5494 	for (str = probe->dtpr_mod; *str != '\0'; str++)
5495 		c[i++] = *str;
5496 	c[i++] = ':';
5497 
5498 	for (str = probe->dtpr_func; *str != '\0'; str++)
5499 		c[i++] = *str;
5500 	c[i++] = ':';
5501 
5502 	for (str = probe->dtpr_name; *str != '\0'; str++)
5503 		c[i++] = *str;
5504 
5505 	while (*ecbmsg != '\0')
5506 		c[i++] = *ecbmsg++;
5507 
5508 	while (shift >= 0) {
5509 		mask = (uintptr_t)0xf << shift;
5510 
5511 		if (val >= ((uintptr_t)1 << shift))
5512 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5513 		shift -= 4;
5514 	}
5515 
5516 	c[i++] = ')';
5517 	c[i] = '\0';
5518 
5519 	debug_enter(c);
5520 }
5521 
5522 static void
5523 dtrace_action_panic(dtrace_ecb_t *ecb)
5524 {
5525 	dtrace_probe_t *probe = ecb->dte_probe;
5526 
5527 	/*
5528 	 * It's impossible to be taking action on the NULL probe.
5529 	 */
5530 	ASSERT(probe != NULL);
5531 
5532 	if (dtrace_destructive_disallow)
5533 		return;
5534 
5535 	if (dtrace_panicked != NULL)
5536 		return;
5537 
5538 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5539 		return;
5540 
5541 	/*
5542 	 * We won the right to panic.  (We want to be sure that only one
5543 	 * thread calls panic() from dtrace_probe(), and that panic() is
5544 	 * called exactly once.)
5545 	 */
5546 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5547 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5548 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5549 }
5550 
5551 static void
5552 dtrace_action_raise(uint64_t sig)
5553 {
5554 	if (dtrace_destructive_disallow)
5555 		return;
5556 
5557 	if (sig >= NSIG) {
5558 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5559 		return;
5560 	}
5561 
5562 	/*
5563 	 * raise() has a queue depth of 1 -- we ignore all subsequent
5564 	 * invocations of the raise() action.
5565 	 */
5566 	if (curthread->t_dtrace_sig == 0)
5567 		curthread->t_dtrace_sig = (uint8_t)sig;
5568 
5569 	curthread->t_sig_check = 1;
5570 	aston(curthread);
5571 }
5572 
5573 static void
5574 dtrace_action_stop(void)
5575 {
5576 	if (dtrace_destructive_disallow)
5577 		return;
5578 
5579 	if (!curthread->t_dtrace_stop) {
5580 		curthread->t_dtrace_stop = 1;
5581 		curthread->t_sig_check = 1;
5582 		aston(curthread);
5583 	}
5584 }
5585 
5586 static void
5587 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5588 {
5589 	hrtime_t now;
5590 	volatile uint16_t *flags;
5591 	cpu_t *cpu = CPU;
5592 
5593 	if (dtrace_destructive_disallow)
5594 		return;
5595 
5596 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5597 
5598 	now = dtrace_gethrtime();
5599 
5600 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5601 		/*
5602 		 * We need to advance the mark to the current time.
5603 		 */
5604 		cpu->cpu_dtrace_chillmark = now;
5605 		cpu->cpu_dtrace_chilled = 0;
5606 	}
5607 
5608 	/*
5609 	 * Now check to see if the requested chill time would take us over
5610 	 * the maximum amount of time allowed in the chill interval.  (Or
5611 	 * worse, if the calculation itself induces overflow.)
5612 	 */
5613 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5614 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5615 		*flags |= CPU_DTRACE_ILLOP;
5616 		return;
5617 	}
5618 
5619 	while (dtrace_gethrtime() - now < val)
5620 		continue;
5621 
5622 	/*
5623 	 * Normally, we assure that the value of the variable "timestamp" does
5624 	 * not change within an ECB.  The presence of chill() represents an
5625 	 * exception to this rule, however.
5626 	 */
5627 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5628 	cpu->cpu_dtrace_chilled += val;
5629 }
5630 
5631 static void
5632 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5633     uint64_t *buf, uint64_t arg)
5634 {
5635 	int nframes = DTRACE_USTACK_NFRAMES(arg);
5636 	int strsize = DTRACE_USTACK_STRSIZE(arg);
5637 	uint64_t *pcs = &buf[1], *fps;
5638 	char *str = (char *)&pcs[nframes];
5639 	int size, offs = 0, i, j;
5640 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
5641 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5642 	char *sym;
5643 
5644 	/*
5645 	 * Should be taking a faster path if string space has not been
5646 	 * allocated.
5647 	 */
5648 	ASSERT(strsize != 0);
5649 
5650 	/*
5651 	 * We will first allocate some temporary space for the frame pointers.
5652 	 */
5653 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5654 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5655 	    (nframes * sizeof (uint64_t));
5656 
5657 	if (!DTRACE_INSCRATCH(mstate, size)) {
5658 		/*
5659 		 * Not enough room for our frame pointers -- need to indicate
5660 		 * that we ran out of scratch space.
5661 		 */
5662 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5663 		return;
5664 	}
5665 
5666 	mstate->dtms_scratch_ptr += size;
5667 	saved = mstate->dtms_scratch_ptr;
5668 
5669 	/*
5670 	 * Now get a stack with both program counters and frame pointers.
5671 	 */
5672 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5673 	dtrace_getufpstack(buf, fps, nframes + 1);
5674 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5675 
5676 	/*
5677 	 * If that faulted, we're cooked.
5678 	 */
5679 	if (*flags & CPU_DTRACE_FAULT)
5680 		goto out;
5681 
5682 	/*
5683 	 * Now we want to walk up the stack, calling the USTACK helper.  For
5684 	 * each iteration, we restore the scratch pointer.
5685 	 */
5686 	for (i = 0; i < nframes; i++) {
5687 		mstate->dtms_scratch_ptr = saved;
5688 
5689 		if (offs >= strsize)
5690 			break;
5691 
5692 		sym = (char *)(uintptr_t)dtrace_helper(
5693 		    DTRACE_HELPER_ACTION_USTACK,
5694 		    mstate, state, pcs[i], fps[i]);
5695 
5696 		/*
5697 		 * If we faulted while running the helper, we're going to
5698 		 * clear the fault and null out the corresponding string.
5699 		 */
5700 		if (*flags & CPU_DTRACE_FAULT) {
5701 			*flags &= ~CPU_DTRACE_FAULT;
5702 			str[offs++] = '\0';
5703 			continue;
5704 		}
5705 
5706 		if (sym == NULL) {
5707 			str[offs++] = '\0';
5708 			continue;
5709 		}
5710 
5711 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5712 
5713 		/*
5714 		 * Now copy in the string that the helper returned to us.
5715 		 */
5716 		for (j = 0; offs + j < strsize; j++) {
5717 			if ((str[offs + j] = sym[j]) == '\0')
5718 				break;
5719 		}
5720 
5721 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5722 
5723 		offs += j + 1;
5724 	}
5725 
5726 	if (offs >= strsize) {
5727 		/*
5728 		 * If we didn't have room for all of the strings, we don't
5729 		 * abort processing -- this needn't be a fatal error -- but we
5730 		 * still want to increment a counter (dts_stkstroverflows) to
5731 		 * allow this condition to be warned about.  (If this is from
5732 		 * a jstack() action, it is easily tuned via jstackstrsize.)
5733 		 */
5734 		dtrace_error(&state->dts_stkstroverflows);
5735 	}
5736 
5737 	while (offs < strsize)
5738 		str[offs++] = '\0';
5739 
5740 out:
5741 	mstate->dtms_scratch_ptr = old;
5742 }
5743 
5744 /*
5745  * If you're looking for the epicenter of DTrace, you just found it.  This
5746  * is the function called by the provider to fire a probe -- from which all
5747  * subsequent probe-context DTrace activity emanates.
5748  */
5749 void
5750 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
5751     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
5752 {
5753 	processorid_t cpuid;
5754 	dtrace_icookie_t cookie;
5755 	dtrace_probe_t *probe;
5756 	dtrace_mstate_t mstate;
5757 	dtrace_ecb_t *ecb;
5758 	dtrace_action_t *act;
5759 	intptr_t offs;
5760 	size_t size;
5761 	int vtime, onintr;
5762 	volatile uint16_t *flags;
5763 	hrtime_t now;
5764 
5765 	/*
5766 	 * Kick out immediately if this CPU is still being born (in which case
5767 	 * curthread will be set to -1) or the current thread can't allow
5768 	 * probes in its current context.
5769 	 */
5770 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
5771 		return;
5772 
5773 	cookie = dtrace_interrupt_disable();
5774 	probe = dtrace_probes[id - 1];
5775 	cpuid = CPU->cpu_id;
5776 	onintr = CPU_ON_INTR(CPU);
5777 
5778 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
5779 	    probe->dtpr_predcache == curthread->t_predcache) {
5780 		/*
5781 		 * We have hit in the predicate cache; we know that
5782 		 * this predicate would evaluate to be false.
5783 		 */
5784 		dtrace_interrupt_enable(cookie);
5785 		return;
5786 	}
5787 
5788 	if (panic_quiesce) {
5789 		/*
5790 		 * We don't trace anything if we're panicking.
5791 		 */
5792 		dtrace_interrupt_enable(cookie);
5793 		return;
5794 	}
5795 
5796 	now = dtrace_gethrtime();
5797 	vtime = dtrace_vtime_references != 0;
5798 
5799 	if (vtime && curthread->t_dtrace_start)
5800 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
5801 
5802 	mstate.dtms_difo = NULL;
5803 	mstate.dtms_probe = probe;
5804 	mstate.dtms_strtok = NULL;
5805 	mstate.dtms_arg[0] = arg0;
5806 	mstate.dtms_arg[1] = arg1;
5807 	mstate.dtms_arg[2] = arg2;
5808 	mstate.dtms_arg[3] = arg3;
5809 	mstate.dtms_arg[4] = arg4;
5810 
5811 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
5812 
5813 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
5814 		dtrace_predicate_t *pred = ecb->dte_predicate;
5815 		dtrace_state_t *state = ecb->dte_state;
5816 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
5817 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
5818 		dtrace_vstate_t *vstate = &state->dts_vstate;
5819 		dtrace_provider_t *prov = probe->dtpr_provider;
5820 		uint64_t tracememsize = 0;
5821 		int committed = 0;
5822 		caddr_t tomax;
5823 
5824 		/*
5825 		 * A little subtlety with the following (seemingly innocuous)
5826 		 * declaration of the automatic 'val':  by looking at the
5827 		 * code, you might think that it could be declared in the
5828 		 * action processing loop, below.  (That is, it's only used in
5829 		 * the action processing loop.)  However, it must be declared
5830 		 * out of that scope because in the case of DIF expression
5831 		 * arguments to aggregating actions, one iteration of the
5832 		 * action loop will use the last iteration's value.
5833 		 */
5834 #ifdef lint
5835 		uint64_t val = 0;
5836 #else
5837 		uint64_t val;
5838 #endif
5839 
5840 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
5841 		mstate.dtms_access = DTRACE_ACCESS_ARGS | DTRACE_ACCESS_PROC;
5842 		*flags &= ~CPU_DTRACE_ERROR;
5843 
5844 		if (prov == dtrace_provider) {
5845 			/*
5846 			 * If dtrace itself is the provider of this probe,
5847 			 * we're only going to continue processing the ECB if
5848 			 * arg0 (the dtrace_state_t) is equal to the ECB's
5849 			 * creating state.  (This prevents disjoint consumers
5850 			 * from seeing one another's metaprobes.)
5851 			 */
5852 			if (arg0 != (uint64_t)(uintptr_t)state)
5853 				continue;
5854 		}
5855 
5856 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
5857 			/*
5858 			 * We're not currently active.  If our provider isn't
5859 			 * the dtrace pseudo provider, we're not interested.
5860 			 */
5861 			if (prov != dtrace_provider)
5862 				continue;
5863 
5864 			/*
5865 			 * Now we must further check if we are in the BEGIN
5866 			 * probe.  If we are, we will only continue processing
5867 			 * if we're still in WARMUP -- if one BEGIN enabling
5868 			 * has invoked the exit() action, we don't want to
5869 			 * evaluate subsequent BEGIN enablings.
5870 			 */
5871 			if (probe->dtpr_id == dtrace_probeid_begin &&
5872 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
5873 				ASSERT(state->dts_activity ==
5874 				    DTRACE_ACTIVITY_DRAINING);
5875 				continue;
5876 			}
5877 		}
5878 
5879 		if (ecb->dte_cond && !dtrace_priv_probe(state, &mstate, ecb))
5880 			continue;
5881 
5882 		if (now - state->dts_alive > dtrace_deadman_timeout) {
5883 			/*
5884 			 * We seem to be dead.  Unless we (a) have kernel
5885 			 * destructive permissions (b) have expicitly enabled
5886 			 * destructive actions and (c) destructive actions have
5887 			 * not been disabled, we're going to transition into
5888 			 * the KILLED state, from which no further processing
5889 			 * on this state will be performed.
5890 			 */
5891 			if (!dtrace_priv_kernel_destructive(state) ||
5892 			    !state->dts_cred.dcr_destructive ||
5893 			    dtrace_destructive_disallow) {
5894 				void *activity = &state->dts_activity;
5895 				dtrace_activity_t current;
5896 
5897 				do {
5898 					current = state->dts_activity;
5899 				} while (dtrace_cas32(activity, current,
5900 				    DTRACE_ACTIVITY_KILLED) != current);
5901 
5902 				continue;
5903 			}
5904 		}
5905 
5906 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
5907 		    ecb->dte_alignment, state, &mstate)) < 0)
5908 			continue;
5909 
5910 		tomax = buf->dtb_tomax;
5911 		ASSERT(tomax != NULL);
5912 
5913 		if (ecb->dte_size != 0)
5914 			DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
5915 
5916 		mstate.dtms_epid = ecb->dte_epid;
5917 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
5918 
5919 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
5920 			mstate.dtms_access |= DTRACE_ACCESS_KERNEL;
5921 
5922 		if (pred != NULL) {
5923 			dtrace_difo_t *dp = pred->dtp_difo;
5924 			int rval;
5925 
5926 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
5927 
5928 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
5929 				dtrace_cacheid_t cid = probe->dtpr_predcache;
5930 
5931 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
5932 					/*
5933 					 * Update the predicate cache...
5934 					 */
5935 					ASSERT(cid == pred->dtp_cacheid);
5936 					curthread->t_predcache = cid;
5937 				}
5938 
5939 				continue;
5940 			}
5941 		}
5942 
5943 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
5944 		    act != NULL; act = act->dta_next) {
5945 			size_t valoffs;
5946 			dtrace_difo_t *dp;
5947 			dtrace_recdesc_t *rec = &act->dta_rec;
5948 
5949 			size = rec->dtrd_size;
5950 			valoffs = offs + rec->dtrd_offset;
5951 
5952 			if (DTRACEACT_ISAGG(act->dta_kind)) {
5953 				uint64_t v = 0xbad;
5954 				dtrace_aggregation_t *agg;
5955 
5956 				agg = (dtrace_aggregation_t *)act;
5957 
5958 				if ((dp = act->dta_difo) != NULL)
5959 					v = dtrace_dif_emulate(dp,
5960 					    &mstate, vstate, state);
5961 
5962 				if (*flags & CPU_DTRACE_ERROR)
5963 					continue;
5964 
5965 				/*
5966 				 * Note that we always pass the expression
5967 				 * value from the previous iteration of the
5968 				 * action loop.  This value will only be used
5969 				 * if there is an expression argument to the
5970 				 * aggregating action, denoted by the
5971 				 * dtag_hasarg field.
5972 				 */
5973 				dtrace_aggregate(agg, buf,
5974 				    offs, aggbuf, v, val);
5975 				continue;
5976 			}
5977 
5978 			switch (act->dta_kind) {
5979 			case DTRACEACT_STOP:
5980 				if (dtrace_priv_proc_destructive(state,
5981 				    &mstate))
5982 					dtrace_action_stop();
5983 				continue;
5984 
5985 			case DTRACEACT_BREAKPOINT:
5986 				if (dtrace_priv_kernel_destructive(state))
5987 					dtrace_action_breakpoint(ecb);
5988 				continue;
5989 
5990 			case DTRACEACT_PANIC:
5991 				if (dtrace_priv_kernel_destructive(state))
5992 					dtrace_action_panic(ecb);
5993 				continue;
5994 
5995 			case DTRACEACT_STACK:
5996 				if (!dtrace_priv_kernel(state))
5997 					continue;
5998 
5999 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
6000 				    size / sizeof (pc_t), probe->dtpr_aframes,
6001 				    DTRACE_ANCHORED(probe) ? NULL :
6002 				    (uint32_t *)arg0);
6003 
6004 				continue;
6005 
6006 			case DTRACEACT_JSTACK:
6007 			case DTRACEACT_USTACK:
6008 				if (!dtrace_priv_proc(state, &mstate))
6009 					continue;
6010 
6011 				/*
6012 				 * See comment in DIF_VAR_PID.
6013 				 */
6014 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6015 				    CPU_ON_INTR(CPU)) {
6016 					int depth = DTRACE_USTACK_NFRAMES(
6017 					    rec->dtrd_arg) + 1;
6018 
6019 					dtrace_bzero((void *)(tomax + valoffs),
6020 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6021 					    + depth * sizeof (uint64_t));
6022 
6023 					continue;
6024 				}
6025 
6026 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6027 				    curproc->p_dtrace_helpers != NULL) {
6028 					/*
6029 					 * This is the slow path -- we have
6030 					 * allocated string space, and we're
6031 					 * getting the stack of a process that
6032 					 * has helpers.  Call into a separate
6033 					 * routine to perform this processing.
6034 					 */
6035 					dtrace_action_ustack(&mstate, state,
6036 					    (uint64_t *)(tomax + valoffs),
6037 					    rec->dtrd_arg);
6038 					continue;
6039 				}
6040 
6041 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6042 				dtrace_getupcstack((uint64_t *)
6043 				    (tomax + valoffs),
6044 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6045 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6046 				continue;
6047 
6048 			default:
6049 				break;
6050 			}
6051 
6052 			dp = act->dta_difo;
6053 			ASSERT(dp != NULL);
6054 
6055 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6056 
6057 			if (*flags & CPU_DTRACE_ERROR)
6058 				continue;
6059 
6060 			switch (act->dta_kind) {
6061 			case DTRACEACT_SPECULATE:
6062 				ASSERT(buf == &state->dts_buffer[cpuid]);
6063 				buf = dtrace_speculation_buffer(state,
6064 				    cpuid, val);
6065 
6066 				if (buf == NULL) {
6067 					*flags |= CPU_DTRACE_DROP;
6068 					continue;
6069 				}
6070 
6071 				offs = dtrace_buffer_reserve(buf,
6072 				    ecb->dte_needed, ecb->dte_alignment,
6073 				    state, NULL);
6074 
6075 				if (offs < 0) {
6076 					*flags |= CPU_DTRACE_DROP;
6077 					continue;
6078 				}
6079 
6080 				tomax = buf->dtb_tomax;
6081 				ASSERT(tomax != NULL);
6082 
6083 				if (ecb->dte_size != 0)
6084 					DTRACE_STORE(uint32_t, tomax, offs,
6085 					    ecb->dte_epid);
6086 				continue;
6087 
6088 			case DTRACEACT_CHILL:
6089 				if (dtrace_priv_kernel_destructive(state))
6090 					dtrace_action_chill(&mstate, val);
6091 				continue;
6092 
6093 			case DTRACEACT_RAISE:
6094 				if (dtrace_priv_proc_destructive(state,
6095 				    &mstate))
6096 					dtrace_action_raise(val);
6097 				continue;
6098 
6099 			case DTRACEACT_COMMIT:
6100 				ASSERT(!committed);
6101 
6102 				/*
6103 				 * We need to commit our buffer state.
6104 				 */
6105 				if (ecb->dte_size)
6106 					buf->dtb_offset = offs + ecb->dte_size;
6107 				buf = &state->dts_buffer[cpuid];
6108 				dtrace_speculation_commit(state, cpuid, val);
6109 				committed = 1;
6110 				continue;
6111 
6112 			case DTRACEACT_DISCARD:
6113 				dtrace_speculation_discard(state, cpuid, val);
6114 				continue;
6115 
6116 			case DTRACEACT_DIFEXPR:
6117 			case DTRACEACT_LIBACT:
6118 			case DTRACEACT_PRINTF:
6119 			case DTRACEACT_PRINTA:
6120 			case DTRACEACT_SYSTEM:
6121 			case DTRACEACT_FREOPEN:
6122 			case DTRACEACT_TRACEMEM:
6123 				break;
6124 
6125 			case DTRACEACT_TRACEMEM_DYNSIZE:
6126 				tracememsize = val;
6127 				break;
6128 
6129 			case DTRACEACT_SYM:
6130 			case DTRACEACT_MOD:
6131 				if (!dtrace_priv_kernel(state))
6132 					continue;
6133 				break;
6134 
6135 			case DTRACEACT_USYM:
6136 			case DTRACEACT_UMOD:
6137 			case DTRACEACT_UADDR: {
6138 				struct pid *pid = curthread->t_procp->p_pidp;
6139 
6140 				if (!dtrace_priv_proc(state, &mstate))
6141 					continue;
6142 
6143 				DTRACE_STORE(uint64_t, tomax,
6144 				    valoffs, (uint64_t)pid->pid_id);
6145 				DTRACE_STORE(uint64_t, tomax,
6146 				    valoffs + sizeof (uint64_t), val);
6147 
6148 				continue;
6149 			}
6150 
6151 			case DTRACEACT_EXIT: {
6152 				/*
6153 				 * For the exit action, we are going to attempt
6154 				 * to atomically set our activity to be
6155 				 * draining.  If this fails (either because
6156 				 * another CPU has beat us to the exit action,
6157 				 * or because our current activity is something
6158 				 * other than ACTIVE or WARMUP), we will
6159 				 * continue.  This assures that the exit action
6160 				 * can be successfully recorded at most once
6161 				 * when we're in the ACTIVE state.  If we're
6162 				 * encountering the exit() action while in
6163 				 * COOLDOWN, however, we want to honor the new
6164 				 * status code.  (We know that we're the only
6165 				 * thread in COOLDOWN, so there is no race.)
6166 				 */
6167 				void *activity = &state->dts_activity;
6168 				dtrace_activity_t current = state->dts_activity;
6169 
6170 				if (current == DTRACE_ACTIVITY_COOLDOWN)
6171 					break;
6172 
6173 				if (current != DTRACE_ACTIVITY_WARMUP)
6174 					current = DTRACE_ACTIVITY_ACTIVE;
6175 
6176 				if (dtrace_cas32(activity, current,
6177 				    DTRACE_ACTIVITY_DRAINING) != current) {
6178 					*flags |= CPU_DTRACE_DROP;
6179 					continue;
6180 				}
6181 
6182 				break;
6183 			}
6184 
6185 			default:
6186 				ASSERT(0);
6187 			}
6188 
6189 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6190 				uintptr_t end = valoffs + size;
6191 
6192 				if (tracememsize != 0 &&
6193 				    valoffs + tracememsize < end) {
6194 					end = valoffs + tracememsize;
6195 					tracememsize = 0;
6196 				}
6197 
6198 				if (!dtrace_vcanload((void *)(uintptr_t)val,
6199 				    &dp->dtdo_rtype, &mstate, vstate))
6200 					continue;
6201 
6202 				/*
6203 				 * If this is a string, we're going to only
6204 				 * load until we find the zero byte -- after
6205 				 * which we'll store zero bytes.
6206 				 */
6207 				if (dp->dtdo_rtype.dtdt_kind ==
6208 				    DIF_TYPE_STRING) {
6209 					char c = '\0' + 1;
6210 					int intuple = act->dta_intuple;
6211 					size_t s;
6212 
6213 					for (s = 0; s < size; s++) {
6214 						if (c != '\0')
6215 							c = dtrace_load8(val++);
6216 
6217 						DTRACE_STORE(uint8_t, tomax,
6218 						    valoffs++, c);
6219 
6220 						if (c == '\0' && intuple)
6221 							break;
6222 					}
6223 
6224 					continue;
6225 				}
6226 
6227 				while (valoffs < end) {
6228 					DTRACE_STORE(uint8_t, tomax, valoffs++,
6229 					    dtrace_load8(val++));
6230 				}
6231 
6232 				continue;
6233 			}
6234 
6235 			switch (size) {
6236 			case 0:
6237 				break;
6238 
6239 			case sizeof (uint8_t):
6240 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
6241 				break;
6242 			case sizeof (uint16_t):
6243 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
6244 				break;
6245 			case sizeof (uint32_t):
6246 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
6247 				break;
6248 			case sizeof (uint64_t):
6249 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
6250 				break;
6251 			default:
6252 				/*
6253 				 * Any other size should have been returned by
6254 				 * reference, not by value.
6255 				 */
6256 				ASSERT(0);
6257 				break;
6258 			}
6259 		}
6260 
6261 		if (*flags & CPU_DTRACE_DROP)
6262 			continue;
6263 
6264 		if (*flags & CPU_DTRACE_FAULT) {
6265 			int ndx;
6266 			dtrace_action_t *err;
6267 
6268 			buf->dtb_errors++;
6269 
6270 			if (probe->dtpr_id == dtrace_probeid_error) {
6271 				/*
6272 				 * There's nothing we can do -- we had an
6273 				 * error on the error probe.  We bump an
6274 				 * error counter to at least indicate that
6275 				 * this condition happened.
6276 				 */
6277 				dtrace_error(&state->dts_dblerrors);
6278 				continue;
6279 			}
6280 
6281 			if (vtime) {
6282 				/*
6283 				 * Before recursing on dtrace_probe(), we
6284 				 * need to explicitly clear out our start
6285 				 * time to prevent it from being accumulated
6286 				 * into t_dtrace_vtime.
6287 				 */
6288 				curthread->t_dtrace_start = 0;
6289 			}
6290 
6291 			/*
6292 			 * Iterate over the actions to figure out which action
6293 			 * we were processing when we experienced the error.
6294 			 * Note that act points _past_ the faulting action; if
6295 			 * act is ecb->dte_action, the fault was in the
6296 			 * predicate, if it's ecb->dte_action->dta_next it's
6297 			 * in action #1, and so on.
6298 			 */
6299 			for (err = ecb->dte_action, ndx = 0;
6300 			    err != act; err = err->dta_next, ndx++)
6301 				continue;
6302 
6303 			dtrace_probe_error(state, ecb->dte_epid, ndx,
6304 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6305 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6306 			    cpu_core[cpuid].cpuc_dtrace_illval);
6307 
6308 			continue;
6309 		}
6310 
6311 		if (!committed)
6312 			buf->dtb_offset = offs + ecb->dte_size;
6313 	}
6314 
6315 	if (vtime)
6316 		curthread->t_dtrace_start = dtrace_gethrtime();
6317 
6318 	dtrace_interrupt_enable(cookie);
6319 }
6320 
6321 /*
6322  * DTrace Probe Hashing Functions
6323  *
6324  * The functions in this section (and indeed, the functions in remaining
6325  * sections) are not _called_ from probe context.  (Any exceptions to this are
6326  * marked with a "Note:".)  Rather, they are called from elsewhere in the
6327  * DTrace framework to look-up probes in, add probes to and remove probes from
6328  * the DTrace probe hashes.  (Each probe is hashed by each element of the
6329  * probe tuple -- allowing for fast lookups, regardless of what was
6330  * specified.)
6331  */
6332 static uint_t
6333 dtrace_hash_str(char *p)
6334 {
6335 	unsigned int g;
6336 	uint_t hval = 0;
6337 
6338 	while (*p) {
6339 		hval = (hval << 4) + *p++;
6340 		if ((g = (hval & 0xf0000000)) != 0)
6341 			hval ^= g >> 24;
6342 		hval &= ~g;
6343 	}
6344 	return (hval);
6345 }
6346 
6347 static dtrace_hash_t *
6348 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6349 {
6350 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6351 
6352 	hash->dth_stroffs = stroffs;
6353 	hash->dth_nextoffs = nextoffs;
6354 	hash->dth_prevoffs = prevoffs;
6355 
6356 	hash->dth_size = 1;
6357 	hash->dth_mask = hash->dth_size - 1;
6358 
6359 	hash->dth_tab = kmem_zalloc(hash->dth_size *
6360 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6361 
6362 	return (hash);
6363 }
6364 
6365 static void
6366 dtrace_hash_destroy(dtrace_hash_t *hash)
6367 {
6368 #ifdef DEBUG
6369 	int i;
6370 
6371 	for (i = 0; i < hash->dth_size; i++)
6372 		ASSERT(hash->dth_tab[i] == NULL);
6373 #endif
6374 
6375 	kmem_free(hash->dth_tab,
6376 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
6377 	kmem_free(hash, sizeof (dtrace_hash_t));
6378 }
6379 
6380 static void
6381 dtrace_hash_resize(dtrace_hash_t *hash)
6382 {
6383 	int size = hash->dth_size, i, ndx;
6384 	int new_size = hash->dth_size << 1;
6385 	int new_mask = new_size - 1;
6386 	dtrace_hashbucket_t **new_tab, *bucket, *next;
6387 
6388 	ASSERT((new_size & new_mask) == 0);
6389 
6390 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6391 
6392 	for (i = 0; i < size; i++) {
6393 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6394 			dtrace_probe_t *probe = bucket->dthb_chain;
6395 
6396 			ASSERT(probe != NULL);
6397 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6398 
6399 			next = bucket->dthb_next;
6400 			bucket->dthb_next = new_tab[ndx];
6401 			new_tab[ndx] = bucket;
6402 		}
6403 	}
6404 
6405 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6406 	hash->dth_tab = new_tab;
6407 	hash->dth_size = new_size;
6408 	hash->dth_mask = new_mask;
6409 }
6410 
6411 static void
6412 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6413 {
6414 	int hashval = DTRACE_HASHSTR(hash, new);
6415 	int ndx = hashval & hash->dth_mask;
6416 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6417 	dtrace_probe_t **nextp, **prevp;
6418 
6419 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6420 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6421 			goto add;
6422 	}
6423 
6424 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6425 		dtrace_hash_resize(hash);
6426 		dtrace_hash_add(hash, new);
6427 		return;
6428 	}
6429 
6430 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6431 	bucket->dthb_next = hash->dth_tab[ndx];
6432 	hash->dth_tab[ndx] = bucket;
6433 	hash->dth_nbuckets++;
6434 
6435 add:
6436 	nextp = DTRACE_HASHNEXT(hash, new);
6437 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6438 	*nextp = bucket->dthb_chain;
6439 
6440 	if (bucket->dthb_chain != NULL) {
6441 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6442 		ASSERT(*prevp == NULL);
6443 		*prevp = new;
6444 	}
6445 
6446 	bucket->dthb_chain = new;
6447 	bucket->dthb_len++;
6448 }
6449 
6450 static dtrace_probe_t *
6451 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6452 {
6453 	int hashval = DTRACE_HASHSTR(hash, template);
6454 	int ndx = hashval & hash->dth_mask;
6455 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6456 
6457 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6458 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6459 			return (bucket->dthb_chain);
6460 	}
6461 
6462 	return (NULL);
6463 }
6464 
6465 static int
6466 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6467 {
6468 	int hashval = DTRACE_HASHSTR(hash, template);
6469 	int ndx = hashval & hash->dth_mask;
6470 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6471 
6472 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6473 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6474 			return (bucket->dthb_len);
6475 	}
6476 
6477 	return (NULL);
6478 }
6479 
6480 static void
6481 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6482 {
6483 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6484 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6485 
6486 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6487 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6488 
6489 	/*
6490 	 * Find the bucket that we're removing this probe from.
6491 	 */
6492 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6493 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6494 			break;
6495 	}
6496 
6497 	ASSERT(bucket != NULL);
6498 
6499 	if (*prevp == NULL) {
6500 		if (*nextp == NULL) {
6501 			/*
6502 			 * The removed probe was the only probe on this
6503 			 * bucket; we need to remove the bucket.
6504 			 */
6505 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6506 
6507 			ASSERT(bucket->dthb_chain == probe);
6508 			ASSERT(b != NULL);
6509 
6510 			if (b == bucket) {
6511 				hash->dth_tab[ndx] = bucket->dthb_next;
6512 			} else {
6513 				while (b->dthb_next != bucket)
6514 					b = b->dthb_next;
6515 				b->dthb_next = bucket->dthb_next;
6516 			}
6517 
6518 			ASSERT(hash->dth_nbuckets > 0);
6519 			hash->dth_nbuckets--;
6520 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
6521 			return;
6522 		}
6523 
6524 		bucket->dthb_chain = *nextp;
6525 	} else {
6526 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
6527 	}
6528 
6529 	if (*nextp != NULL)
6530 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
6531 }
6532 
6533 /*
6534  * DTrace Utility Functions
6535  *
6536  * These are random utility functions that are _not_ called from probe context.
6537  */
6538 static int
6539 dtrace_badattr(const dtrace_attribute_t *a)
6540 {
6541 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
6542 	    a->dtat_data > DTRACE_STABILITY_MAX ||
6543 	    a->dtat_class > DTRACE_CLASS_MAX);
6544 }
6545 
6546 /*
6547  * Return a duplicate copy of a string.  If the specified string is NULL,
6548  * this function returns a zero-length string.
6549  */
6550 static char *
6551 dtrace_strdup(const char *str)
6552 {
6553 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
6554 
6555 	if (str != NULL)
6556 		(void) strcpy(new, str);
6557 
6558 	return (new);
6559 }
6560 
6561 #define	DTRACE_ISALPHA(c)	\
6562 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
6563 
6564 static int
6565 dtrace_badname(const char *s)
6566 {
6567 	char c;
6568 
6569 	if (s == NULL || (c = *s++) == '\0')
6570 		return (0);
6571 
6572 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
6573 		return (1);
6574 
6575 	while ((c = *s++) != '\0') {
6576 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
6577 		    c != '-' && c != '_' && c != '.' && c != '`')
6578 			return (1);
6579 	}
6580 
6581 	return (0);
6582 }
6583 
6584 static void
6585 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
6586 {
6587 	uint32_t priv;
6588 
6589 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
6590 		/*
6591 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
6592 		 */
6593 		priv = DTRACE_PRIV_ALL;
6594 	} else {
6595 		*uidp = crgetuid(cr);
6596 		*zoneidp = crgetzoneid(cr);
6597 
6598 		priv = 0;
6599 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
6600 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
6601 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
6602 			priv |= DTRACE_PRIV_USER;
6603 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
6604 			priv |= DTRACE_PRIV_PROC;
6605 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
6606 			priv |= DTRACE_PRIV_OWNER;
6607 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
6608 			priv |= DTRACE_PRIV_ZONEOWNER;
6609 	}
6610 
6611 	*privp = priv;
6612 }
6613 
6614 #ifdef DTRACE_ERRDEBUG
6615 static void
6616 dtrace_errdebug(const char *str)
6617 {
6618 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
6619 	int occupied = 0;
6620 
6621 	mutex_enter(&dtrace_errlock);
6622 	dtrace_errlast = str;
6623 	dtrace_errthread = curthread;
6624 
6625 	while (occupied++ < DTRACE_ERRHASHSZ) {
6626 		if (dtrace_errhash[hval].dter_msg == str) {
6627 			dtrace_errhash[hval].dter_count++;
6628 			goto out;
6629 		}
6630 
6631 		if (dtrace_errhash[hval].dter_msg != NULL) {
6632 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
6633 			continue;
6634 		}
6635 
6636 		dtrace_errhash[hval].dter_msg = str;
6637 		dtrace_errhash[hval].dter_count = 1;
6638 		goto out;
6639 	}
6640 
6641 	panic("dtrace: undersized error hash");
6642 out:
6643 	mutex_exit(&dtrace_errlock);
6644 }
6645 #endif
6646 
6647 /*
6648  * DTrace Matching Functions
6649  *
6650  * These functions are used to match groups of probes, given some elements of
6651  * a probe tuple, or some globbed expressions for elements of a probe tuple.
6652  */
6653 static int
6654 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
6655     zoneid_t zoneid)
6656 {
6657 	if (priv != DTRACE_PRIV_ALL) {
6658 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
6659 		uint32_t match = priv & ppriv;
6660 
6661 		/*
6662 		 * No PRIV_DTRACE_* privileges...
6663 		 */
6664 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
6665 		    DTRACE_PRIV_KERNEL)) == 0)
6666 			return (0);
6667 
6668 		/*
6669 		 * No matching bits, but there were bits to match...
6670 		 */
6671 		if (match == 0 && ppriv != 0)
6672 			return (0);
6673 
6674 		/*
6675 		 * Need to have permissions to the process, but don't...
6676 		 */
6677 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
6678 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
6679 			return (0);
6680 		}
6681 
6682 		/*
6683 		 * Need to be in the same zone unless we possess the
6684 		 * privilege to examine all zones.
6685 		 */
6686 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
6687 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
6688 			return (0);
6689 		}
6690 	}
6691 
6692 	return (1);
6693 }
6694 
6695 /*
6696  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
6697  * consists of input pattern strings and an ops-vector to evaluate them.
6698  * This function returns >0 for match, 0 for no match, and <0 for error.
6699  */
6700 static int
6701 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
6702     uint32_t priv, uid_t uid, zoneid_t zoneid)
6703 {
6704 	dtrace_provider_t *pvp = prp->dtpr_provider;
6705 	int rv;
6706 
6707 	if (pvp->dtpv_defunct)
6708 		return (0);
6709 
6710 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
6711 		return (rv);
6712 
6713 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
6714 		return (rv);
6715 
6716 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
6717 		return (rv);
6718 
6719 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
6720 		return (rv);
6721 
6722 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
6723 		return (0);
6724 
6725 	return (rv);
6726 }
6727 
6728 /*
6729  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
6730  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
6731  * libc's version, the kernel version only applies to 8-bit ASCII strings.
6732  * In addition, all of the recursion cases except for '*' matching have been
6733  * unwound.  For '*', we still implement recursive evaluation, but a depth
6734  * counter is maintained and matching is aborted if we recurse too deep.
6735  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
6736  */
6737 static int
6738 dtrace_match_glob(const char *s, const char *p, int depth)
6739 {
6740 	const char *olds;
6741 	char s1, c;
6742 	int gs;
6743 
6744 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
6745 		return (-1);
6746 
6747 	if (s == NULL)
6748 		s = ""; /* treat NULL as empty string */
6749 
6750 top:
6751 	olds = s;
6752 	s1 = *s++;
6753 
6754 	if (p == NULL)
6755 		return (0);
6756 
6757 	if ((c = *p++) == '\0')
6758 		return (s1 == '\0');
6759 
6760 	switch (c) {
6761 	case '[': {
6762 		int ok = 0, notflag = 0;
6763 		char lc = '\0';
6764 
6765 		if (s1 == '\0')
6766 			return (0);
6767 
6768 		if (*p == '!') {
6769 			notflag = 1;
6770 			p++;
6771 		}
6772 
6773 		if ((c = *p++) == '\0')
6774 			return (0);
6775 
6776 		do {
6777 			if (c == '-' && lc != '\0' && *p != ']') {
6778 				if ((c = *p++) == '\0')
6779 					return (0);
6780 				if (c == '\\' && (c = *p++) == '\0')
6781 					return (0);
6782 
6783 				if (notflag) {
6784 					if (s1 < lc || s1 > c)
6785 						ok++;
6786 					else
6787 						return (0);
6788 				} else if (lc <= s1 && s1 <= c)
6789 					ok++;
6790 
6791 			} else if (c == '\\' && (c = *p++) == '\0')
6792 				return (0);
6793 
6794 			lc = c; /* save left-hand 'c' for next iteration */
6795 
6796 			if (notflag) {
6797 				if (s1 != c)
6798 					ok++;
6799 				else
6800 					return (0);
6801 			} else if (s1 == c)
6802 				ok++;
6803 
6804 			if ((c = *p++) == '\0')
6805 				return (0);
6806 
6807 		} while (c != ']');
6808 
6809 		if (ok)
6810 			goto top;
6811 
6812 		return (0);
6813 	}
6814 
6815 	case '\\':
6816 		if ((c = *p++) == '\0')
6817 			return (0);
6818 		/*FALLTHRU*/
6819 
6820 	default:
6821 		if (c != s1)
6822 			return (0);
6823 		/*FALLTHRU*/
6824 
6825 	case '?':
6826 		if (s1 != '\0')
6827 			goto top;
6828 		return (0);
6829 
6830 	case '*':
6831 		while (*p == '*')
6832 			p++; /* consecutive *'s are identical to a single one */
6833 
6834 		if (*p == '\0')
6835 			return (1);
6836 
6837 		for (s = olds; *s != '\0'; s++) {
6838 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
6839 				return (gs);
6840 		}
6841 
6842 		return (0);
6843 	}
6844 }
6845 
6846 /*ARGSUSED*/
6847 static int
6848 dtrace_match_string(const char *s, const char *p, int depth)
6849 {
6850 	return (s != NULL && strcmp(s, p) == 0);
6851 }
6852 
6853 /*ARGSUSED*/
6854 static int
6855 dtrace_match_nul(const char *s, const char *p, int depth)
6856 {
6857 	return (1); /* always match the empty pattern */
6858 }
6859 
6860 /*ARGSUSED*/
6861 static int
6862 dtrace_match_nonzero(const char *s, const char *p, int depth)
6863 {
6864 	return (s != NULL && s[0] != '\0');
6865 }
6866 
6867 static int
6868 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
6869     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
6870 {
6871 	dtrace_probe_t template, *probe;
6872 	dtrace_hash_t *hash = NULL;
6873 	int len, rc, best = INT_MAX, nmatched = 0;
6874 	dtrace_id_t i;
6875 
6876 	ASSERT(MUTEX_HELD(&dtrace_lock));
6877 
6878 	/*
6879 	 * If the probe ID is specified in the key, just lookup by ID and
6880 	 * invoke the match callback once if a matching probe is found.
6881 	 */
6882 	if (pkp->dtpk_id != DTRACE_IDNONE) {
6883 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
6884 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
6885 			if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
6886 				return (DTRACE_MATCH_FAIL);
6887 			nmatched++;
6888 		}
6889 		return (nmatched);
6890 	}
6891 
6892 	template.dtpr_mod = (char *)pkp->dtpk_mod;
6893 	template.dtpr_func = (char *)pkp->dtpk_func;
6894 	template.dtpr_name = (char *)pkp->dtpk_name;
6895 
6896 	/*
6897 	 * We want to find the most distinct of the module name, function
6898 	 * name, and name.  So for each one that is not a glob pattern or
6899 	 * empty string, we perform a lookup in the corresponding hash and
6900 	 * use the hash table with the fewest collisions to do our search.
6901 	 */
6902 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
6903 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
6904 		best = len;
6905 		hash = dtrace_bymod;
6906 	}
6907 
6908 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
6909 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
6910 		best = len;
6911 		hash = dtrace_byfunc;
6912 	}
6913 
6914 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
6915 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
6916 		best = len;
6917 		hash = dtrace_byname;
6918 	}
6919 
6920 	/*
6921 	 * If we did not select a hash table, iterate over every probe and
6922 	 * invoke our callback for each one that matches our input probe key.
6923 	 */
6924 	if (hash == NULL) {
6925 		for (i = 0; i < dtrace_nprobes; i++) {
6926 			if ((probe = dtrace_probes[i]) == NULL ||
6927 			    dtrace_match_probe(probe, pkp, priv, uid,
6928 			    zoneid) <= 0)
6929 				continue;
6930 
6931 			nmatched++;
6932 
6933 			if ((rc = (*matched)(probe, arg)) !=
6934 			    DTRACE_MATCH_NEXT) {
6935 				if (rc == DTRACE_MATCH_FAIL)
6936 					return (DTRACE_MATCH_FAIL);
6937 				break;
6938 			}
6939 		}
6940 
6941 		return (nmatched);
6942 	}
6943 
6944 	/*
6945 	 * If we selected a hash table, iterate over each probe of the same key
6946 	 * name and invoke the callback for every probe that matches the other
6947 	 * attributes of our input probe key.
6948 	 */
6949 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
6950 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
6951 
6952 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
6953 			continue;
6954 
6955 		nmatched++;
6956 
6957 		if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
6958 			if (rc == DTRACE_MATCH_FAIL)
6959 				return (DTRACE_MATCH_FAIL);
6960 			break;
6961 		}
6962 	}
6963 
6964 	return (nmatched);
6965 }
6966 
6967 /*
6968  * Return the function pointer dtrace_probecmp() should use to compare the
6969  * specified pattern with a string.  For NULL or empty patterns, we select
6970  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
6971  * For non-empty non-glob strings, we use dtrace_match_string().
6972  */
6973 static dtrace_probekey_f *
6974 dtrace_probekey_func(const char *p)
6975 {
6976 	char c;
6977 
6978 	if (p == NULL || *p == '\0')
6979 		return (&dtrace_match_nul);
6980 
6981 	while ((c = *p++) != '\0') {
6982 		if (c == '[' || c == '?' || c == '*' || c == '\\')
6983 			return (&dtrace_match_glob);
6984 	}
6985 
6986 	return (&dtrace_match_string);
6987 }
6988 
6989 /*
6990  * Build a probe comparison key for use with dtrace_match_probe() from the
6991  * given probe description.  By convention, a null key only matches anchored
6992  * probes: if each field is the empty string, reset dtpk_fmatch to
6993  * dtrace_match_nonzero().
6994  */
6995 static void
6996 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
6997 {
6998 	pkp->dtpk_prov = pdp->dtpd_provider;
6999 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7000 
7001 	pkp->dtpk_mod = pdp->dtpd_mod;
7002 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7003 
7004 	pkp->dtpk_func = pdp->dtpd_func;
7005 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7006 
7007 	pkp->dtpk_name = pdp->dtpd_name;
7008 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7009 
7010 	pkp->dtpk_id = pdp->dtpd_id;
7011 
7012 	if (pkp->dtpk_id == DTRACE_IDNONE &&
7013 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
7014 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
7015 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
7016 	    pkp->dtpk_nmatch == &dtrace_match_nul)
7017 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
7018 }
7019 
7020 /*
7021  * DTrace Provider-to-Framework API Functions
7022  *
7023  * These functions implement much of the Provider-to-Framework API, as
7024  * described in <sys/dtrace.h>.  The parts of the API not in this section are
7025  * the functions in the API for probe management (found below), and
7026  * dtrace_probe() itself (found above).
7027  */
7028 
7029 /*
7030  * Register the calling provider with the DTrace framework.  This should
7031  * generally be called by DTrace providers in their attach(9E) entry point.
7032  */
7033 int
7034 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7035     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7036 {
7037 	dtrace_provider_t *provider;
7038 
7039 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7040 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7041 		    "arguments", name ? name : "<NULL>");
7042 		return (EINVAL);
7043 	}
7044 
7045 	if (name[0] == '\0' || dtrace_badname(name)) {
7046 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7047 		    "provider name", name);
7048 		return (EINVAL);
7049 	}
7050 
7051 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7052 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7053 	    pops->dtps_destroy == NULL ||
7054 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7055 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7056 		    "provider ops", name);
7057 		return (EINVAL);
7058 	}
7059 
7060 	if (dtrace_badattr(&pap->dtpa_provider) ||
7061 	    dtrace_badattr(&pap->dtpa_mod) ||
7062 	    dtrace_badattr(&pap->dtpa_func) ||
7063 	    dtrace_badattr(&pap->dtpa_name) ||
7064 	    dtrace_badattr(&pap->dtpa_args)) {
7065 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7066 		    "provider attributes", name);
7067 		return (EINVAL);
7068 	}
7069 
7070 	if (priv & ~DTRACE_PRIV_ALL) {
7071 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7072 		    "privilege attributes", name);
7073 		return (EINVAL);
7074 	}
7075 
7076 	if ((priv & DTRACE_PRIV_KERNEL) &&
7077 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7078 	    pops->dtps_mode == NULL) {
7079 		cmn_err(CE_WARN, "failed to register provider '%s': need "
7080 		    "dtps_mode() op for given privilege attributes", name);
7081 		return (EINVAL);
7082 	}
7083 
7084 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7085 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7086 	(void) strcpy(provider->dtpv_name, name);
7087 
7088 	provider->dtpv_attr = *pap;
7089 	provider->dtpv_priv.dtpp_flags = priv;
7090 	if (cr != NULL) {
7091 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7092 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7093 	}
7094 	provider->dtpv_pops = *pops;
7095 
7096 	if (pops->dtps_provide == NULL) {
7097 		ASSERT(pops->dtps_provide_module != NULL);
7098 		provider->dtpv_pops.dtps_provide =
7099 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
7100 	}
7101 
7102 	if (pops->dtps_provide_module == NULL) {
7103 		ASSERT(pops->dtps_provide != NULL);
7104 		provider->dtpv_pops.dtps_provide_module =
7105 		    (void (*)(void *, struct modctl *))dtrace_nullop;
7106 	}
7107 
7108 	if (pops->dtps_suspend == NULL) {
7109 		ASSERT(pops->dtps_resume == NULL);
7110 		provider->dtpv_pops.dtps_suspend =
7111 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7112 		provider->dtpv_pops.dtps_resume =
7113 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7114 	}
7115 
7116 	provider->dtpv_arg = arg;
7117 	*idp = (dtrace_provider_id_t)provider;
7118 
7119 	if (pops == &dtrace_provider_ops) {
7120 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7121 		ASSERT(MUTEX_HELD(&dtrace_lock));
7122 		ASSERT(dtrace_anon.dta_enabling == NULL);
7123 
7124 		/*
7125 		 * We make sure that the DTrace provider is at the head of
7126 		 * the provider chain.
7127 		 */
7128 		provider->dtpv_next = dtrace_provider;
7129 		dtrace_provider = provider;
7130 		return (0);
7131 	}
7132 
7133 	mutex_enter(&dtrace_provider_lock);
7134 	mutex_enter(&dtrace_lock);
7135 
7136 	/*
7137 	 * If there is at least one provider registered, we'll add this
7138 	 * provider after the first provider.
7139 	 */
7140 	if (dtrace_provider != NULL) {
7141 		provider->dtpv_next = dtrace_provider->dtpv_next;
7142 		dtrace_provider->dtpv_next = provider;
7143 	} else {
7144 		dtrace_provider = provider;
7145 	}
7146 
7147 	if (dtrace_retained != NULL) {
7148 		dtrace_enabling_provide(provider);
7149 
7150 		/*
7151 		 * Now we need to call dtrace_enabling_matchall() -- which
7152 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
7153 		 * to drop all of our locks before calling into it...
7154 		 */
7155 		mutex_exit(&dtrace_lock);
7156 		mutex_exit(&dtrace_provider_lock);
7157 		dtrace_enabling_matchall();
7158 
7159 		return (0);
7160 	}
7161 
7162 	mutex_exit(&dtrace_lock);
7163 	mutex_exit(&dtrace_provider_lock);
7164 
7165 	return (0);
7166 }
7167 
7168 /*
7169  * Unregister the specified provider from the DTrace framework.  This should
7170  * generally be called by DTrace providers in their detach(9E) entry point.
7171  */
7172 int
7173 dtrace_unregister(dtrace_provider_id_t id)
7174 {
7175 	dtrace_provider_t *old = (dtrace_provider_t *)id;
7176 	dtrace_provider_t *prev = NULL;
7177 	int i, self = 0, noreap = 0;
7178 	dtrace_probe_t *probe, *first = NULL;
7179 
7180 	if (old->dtpv_pops.dtps_enable ==
7181 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
7182 		/*
7183 		 * If DTrace itself is the provider, we're called with locks
7184 		 * already held.
7185 		 */
7186 		ASSERT(old == dtrace_provider);
7187 		ASSERT(dtrace_devi != NULL);
7188 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7189 		ASSERT(MUTEX_HELD(&dtrace_lock));
7190 		self = 1;
7191 
7192 		if (dtrace_provider->dtpv_next != NULL) {
7193 			/*
7194 			 * There's another provider here; return failure.
7195 			 */
7196 			return (EBUSY);
7197 		}
7198 	} else {
7199 		mutex_enter(&dtrace_provider_lock);
7200 		mutex_enter(&mod_lock);
7201 		mutex_enter(&dtrace_lock);
7202 	}
7203 
7204 	/*
7205 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7206 	 * probes, we refuse to let providers slither away, unless this
7207 	 * provider has already been explicitly invalidated.
7208 	 */
7209 	if (!old->dtpv_defunct &&
7210 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7211 	    dtrace_anon.dta_state->dts_necbs > 0))) {
7212 		if (!self) {
7213 			mutex_exit(&dtrace_lock);
7214 			mutex_exit(&mod_lock);
7215 			mutex_exit(&dtrace_provider_lock);
7216 		}
7217 		return (EBUSY);
7218 	}
7219 
7220 	/*
7221 	 * Attempt to destroy the probes associated with this provider.
7222 	 */
7223 	for (i = 0; i < dtrace_nprobes; i++) {
7224 		if ((probe = dtrace_probes[i]) == NULL)
7225 			continue;
7226 
7227 		if (probe->dtpr_provider != old)
7228 			continue;
7229 
7230 		if (probe->dtpr_ecb == NULL)
7231 			continue;
7232 
7233 		/*
7234 		 * If we are trying to unregister a defunct provider, and the
7235 		 * provider was made defunct within the interval dictated by
7236 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
7237 		 * attempt to reap our enablings.  To denote that the provider
7238 		 * should reattempt to unregister itself at some point in the
7239 		 * future, we will return a differentiable error code (EAGAIN
7240 		 * instead of EBUSY) in this case.
7241 		 */
7242 		if (dtrace_gethrtime() - old->dtpv_defunct >
7243 		    dtrace_unregister_defunct_reap)
7244 			noreap = 1;
7245 
7246 		if (!self) {
7247 			mutex_exit(&dtrace_lock);
7248 			mutex_exit(&mod_lock);
7249 			mutex_exit(&dtrace_provider_lock);
7250 		}
7251 
7252 		if (noreap)
7253 			return (EBUSY);
7254 
7255 		(void) taskq_dispatch(dtrace_taskq,
7256 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
7257 
7258 		return (EAGAIN);
7259 	}
7260 
7261 	/*
7262 	 * All of the probes for this provider are disabled; we can safely
7263 	 * remove all of them from their hash chains and from the probe array.
7264 	 */
7265 	for (i = 0; i < dtrace_nprobes; i++) {
7266 		if ((probe = dtrace_probes[i]) == NULL)
7267 			continue;
7268 
7269 		if (probe->dtpr_provider != old)
7270 			continue;
7271 
7272 		dtrace_probes[i] = NULL;
7273 
7274 		dtrace_hash_remove(dtrace_bymod, probe);
7275 		dtrace_hash_remove(dtrace_byfunc, probe);
7276 		dtrace_hash_remove(dtrace_byname, probe);
7277 
7278 		if (first == NULL) {
7279 			first = probe;
7280 			probe->dtpr_nextmod = NULL;
7281 		} else {
7282 			probe->dtpr_nextmod = first;
7283 			first = probe;
7284 		}
7285 	}
7286 
7287 	/*
7288 	 * The provider's probes have been removed from the hash chains and
7289 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
7290 	 * everyone has cleared out from any probe array processing.
7291 	 */
7292 	dtrace_sync();
7293 
7294 	for (probe = first; probe != NULL; probe = first) {
7295 		first = probe->dtpr_nextmod;
7296 
7297 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7298 		    probe->dtpr_arg);
7299 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7300 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7301 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7302 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7303 		kmem_free(probe, sizeof (dtrace_probe_t));
7304 	}
7305 
7306 	if ((prev = dtrace_provider) == old) {
7307 		ASSERT(self || dtrace_devi == NULL);
7308 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7309 		dtrace_provider = old->dtpv_next;
7310 	} else {
7311 		while (prev != NULL && prev->dtpv_next != old)
7312 			prev = prev->dtpv_next;
7313 
7314 		if (prev == NULL) {
7315 			panic("attempt to unregister non-existent "
7316 			    "dtrace provider %p\n", (void *)id);
7317 		}
7318 
7319 		prev->dtpv_next = old->dtpv_next;
7320 	}
7321 
7322 	if (!self) {
7323 		mutex_exit(&dtrace_lock);
7324 		mutex_exit(&mod_lock);
7325 		mutex_exit(&dtrace_provider_lock);
7326 	}
7327 
7328 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7329 	kmem_free(old, sizeof (dtrace_provider_t));
7330 
7331 	return (0);
7332 }
7333 
7334 /*
7335  * Invalidate the specified provider.  All subsequent probe lookups for the
7336  * specified provider will fail, but its probes will not be removed.
7337  */
7338 void
7339 dtrace_invalidate(dtrace_provider_id_t id)
7340 {
7341 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7342 
7343 	ASSERT(pvp->dtpv_pops.dtps_enable !=
7344 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7345 
7346 	mutex_enter(&dtrace_provider_lock);
7347 	mutex_enter(&dtrace_lock);
7348 
7349 	pvp->dtpv_defunct = dtrace_gethrtime();
7350 
7351 	mutex_exit(&dtrace_lock);
7352 	mutex_exit(&dtrace_provider_lock);
7353 }
7354 
7355 /*
7356  * Indicate whether or not DTrace has attached.
7357  */
7358 int
7359 dtrace_attached(void)
7360 {
7361 	/*
7362 	 * dtrace_provider will be non-NULL iff the DTrace driver has
7363 	 * attached.  (It's non-NULL because DTrace is always itself a
7364 	 * provider.)
7365 	 */
7366 	return (dtrace_provider != NULL);
7367 }
7368 
7369 /*
7370  * Remove all the unenabled probes for the given provider.  This function is
7371  * not unlike dtrace_unregister(), except that it doesn't remove the provider
7372  * -- just as many of its associated probes as it can.
7373  */
7374 int
7375 dtrace_condense(dtrace_provider_id_t id)
7376 {
7377 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
7378 	int i;
7379 	dtrace_probe_t *probe;
7380 
7381 	/*
7382 	 * Make sure this isn't the dtrace provider itself.
7383 	 */
7384 	ASSERT(prov->dtpv_pops.dtps_enable !=
7385 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7386 
7387 	mutex_enter(&dtrace_provider_lock);
7388 	mutex_enter(&dtrace_lock);
7389 
7390 	/*
7391 	 * Attempt to destroy the probes associated with this provider.
7392 	 */
7393 	for (i = 0; i < dtrace_nprobes; i++) {
7394 		if ((probe = dtrace_probes[i]) == NULL)
7395 			continue;
7396 
7397 		if (probe->dtpr_provider != prov)
7398 			continue;
7399 
7400 		if (probe->dtpr_ecb != NULL)
7401 			continue;
7402 
7403 		dtrace_probes[i] = NULL;
7404 
7405 		dtrace_hash_remove(dtrace_bymod, probe);
7406 		dtrace_hash_remove(dtrace_byfunc, probe);
7407 		dtrace_hash_remove(dtrace_byname, probe);
7408 
7409 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7410 		    probe->dtpr_arg);
7411 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7412 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7413 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7414 		kmem_free(probe, sizeof (dtrace_probe_t));
7415 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7416 	}
7417 
7418 	mutex_exit(&dtrace_lock);
7419 	mutex_exit(&dtrace_provider_lock);
7420 
7421 	return (0);
7422 }
7423 
7424 /*
7425  * DTrace Probe Management Functions
7426  *
7427  * The functions in this section perform the DTrace probe management,
7428  * including functions to create probes, look-up probes, and call into the
7429  * providers to request that probes be provided.  Some of these functions are
7430  * in the Provider-to-Framework API; these functions can be identified by the
7431  * fact that they are not declared "static".
7432  */
7433 
7434 /*
7435  * Create a probe with the specified module name, function name, and name.
7436  */
7437 dtrace_id_t
7438 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7439     const char *func, const char *name, int aframes, void *arg)
7440 {
7441 	dtrace_probe_t *probe, **probes;
7442 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7443 	dtrace_id_t id;
7444 
7445 	if (provider == dtrace_provider) {
7446 		ASSERT(MUTEX_HELD(&dtrace_lock));
7447 	} else {
7448 		mutex_enter(&dtrace_lock);
7449 	}
7450 
7451 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7452 	    VM_BESTFIT | VM_SLEEP);
7453 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
7454 
7455 	probe->dtpr_id = id;
7456 	probe->dtpr_gen = dtrace_probegen++;
7457 	probe->dtpr_mod = dtrace_strdup(mod);
7458 	probe->dtpr_func = dtrace_strdup(func);
7459 	probe->dtpr_name = dtrace_strdup(name);
7460 	probe->dtpr_arg = arg;
7461 	probe->dtpr_aframes = aframes;
7462 	probe->dtpr_provider = provider;
7463 
7464 	dtrace_hash_add(dtrace_bymod, probe);
7465 	dtrace_hash_add(dtrace_byfunc, probe);
7466 	dtrace_hash_add(dtrace_byname, probe);
7467 
7468 	if (id - 1 >= dtrace_nprobes) {
7469 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7470 		size_t nsize = osize << 1;
7471 
7472 		if (nsize == 0) {
7473 			ASSERT(osize == 0);
7474 			ASSERT(dtrace_probes == NULL);
7475 			nsize = sizeof (dtrace_probe_t *);
7476 		}
7477 
7478 		probes = kmem_zalloc(nsize, KM_SLEEP);
7479 
7480 		if (dtrace_probes == NULL) {
7481 			ASSERT(osize == 0);
7482 			dtrace_probes = probes;
7483 			dtrace_nprobes = 1;
7484 		} else {
7485 			dtrace_probe_t **oprobes = dtrace_probes;
7486 
7487 			bcopy(oprobes, probes, osize);
7488 			dtrace_membar_producer();
7489 			dtrace_probes = probes;
7490 
7491 			dtrace_sync();
7492 
7493 			/*
7494 			 * All CPUs are now seeing the new probes array; we can
7495 			 * safely free the old array.
7496 			 */
7497 			kmem_free(oprobes, osize);
7498 			dtrace_nprobes <<= 1;
7499 		}
7500 
7501 		ASSERT(id - 1 < dtrace_nprobes);
7502 	}
7503 
7504 	ASSERT(dtrace_probes[id - 1] == NULL);
7505 	dtrace_probes[id - 1] = probe;
7506 
7507 	if (provider != dtrace_provider)
7508 		mutex_exit(&dtrace_lock);
7509 
7510 	return (id);
7511 }
7512 
7513 static dtrace_probe_t *
7514 dtrace_probe_lookup_id(dtrace_id_t id)
7515 {
7516 	ASSERT(MUTEX_HELD(&dtrace_lock));
7517 
7518 	if (id == 0 || id > dtrace_nprobes)
7519 		return (NULL);
7520 
7521 	return (dtrace_probes[id - 1]);
7522 }
7523 
7524 static int
7525 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
7526 {
7527 	*((dtrace_id_t *)arg) = probe->dtpr_id;
7528 
7529 	return (DTRACE_MATCH_DONE);
7530 }
7531 
7532 /*
7533  * Look up a probe based on provider and one or more of module name, function
7534  * name and probe name.
7535  */
7536 dtrace_id_t
7537 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
7538     const char *func, const char *name)
7539 {
7540 	dtrace_probekey_t pkey;
7541 	dtrace_id_t id;
7542 	int match;
7543 
7544 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
7545 	pkey.dtpk_pmatch = &dtrace_match_string;
7546 	pkey.dtpk_mod = mod;
7547 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
7548 	pkey.dtpk_func = func;
7549 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
7550 	pkey.dtpk_name = name;
7551 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
7552 	pkey.dtpk_id = DTRACE_IDNONE;
7553 
7554 	mutex_enter(&dtrace_lock);
7555 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
7556 	    dtrace_probe_lookup_match, &id);
7557 	mutex_exit(&dtrace_lock);
7558 
7559 	ASSERT(match == 1 || match == 0);
7560 	return (match ? id : 0);
7561 }
7562 
7563 /*
7564  * Returns the probe argument associated with the specified probe.
7565  */
7566 void *
7567 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
7568 {
7569 	dtrace_probe_t *probe;
7570 	void *rval = NULL;
7571 
7572 	mutex_enter(&dtrace_lock);
7573 
7574 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
7575 	    probe->dtpr_provider == (dtrace_provider_t *)id)
7576 		rval = probe->dtpr_arg;
7577 
7578 	mutex_exit(&dtrace_lock);
7579 
7580 	return (rval);
7581 }
7582 
7583 /*
7584  * Copy a probe into a probe description.
7585  */
7586 static void
7587 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
7588 {
7589 	bzero(pdp, sizeof (dtrace_probedesc_t));
7590 	pdp->dtpd_id = prp->dtpr_id;
7591 
7592 	(void) strncpy(pdp->dtpd_provider,
7593 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
7594 
7595 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
7596 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
7597 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
7598 }
7599 
7600 /*
7601  * Called to indicate that a probe -- or probes -- should be provided by a
7602  * specfied provider.  If the specified description is NULL, the provider will
7603  * be told to provide all of its probes.  (This is done whenever a new
7604  * consumer comes along, or whenever a retained enabling is to be matched.) If
7605  * the specified description is non-NULL, the provider is given the
7606  * opportunity to dynamically provide the specified probe, allowing providers
7607  * to support the creation of probes on-the-fly.  (So-called _autocreated_
7608  * probes.)  If the provider is NULL, the operations will be applied to all
7609  * providers; if the provider is non-NULL the operations will only be applied
7610  * to the specified provider.  The dtrace_provider_lock must be held, and the
7611  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
7612  * will need to grab the dtrace_lock when it reenters the framework through
7613  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
7614  */
7615 static void
7616 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
7617 {
7618 	struct modctl *ctl;
7619 	int all = 0;
7620 
7621 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7622 
7623 	if (prv == NULL) {
7624 		all = 1;
7625 		prv = dtrace_provider;
7626 	}
7627 
7628 	do {
7629 		/*
7630 		 * First, call the blanket provide operation.
7631 		 */
7632 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
7633 
7634 		/*
7635 		 * Now call the per-module provide operation.  We will grab
7636 		 * mod_lock to prevent the list from being modified.  Note
7637 		 * that this also prevents the mod_busy bits from changing.
7638 		 * (mod_busy can only be changed with mod_lock held.)
7639 		 */
7640 		mutex_enter(&mod_lock);
7641 
7642 		ctl = &modules;
7643 		do {
7644 			if (ctl->mod_busy || ctl->mod_mp == NULL)
7645 				continue;
7646 
7647 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
7648 
7649 		} while ((ctl = ctl->mod_next) != &modules);
7650 
7651 		mutex_exit(&mod_lock);
7652 	} while (all && (prv = prv->dtpv_next) != NULL);
7653 }
7654 
7655 /*
7656  * Iterate over each probe, and call the Framework-to-Provider API function
7657  * denoted by offs.
7658  */
7659 static void
7660 dtrace_probe_foreach(uintptr_t offs)
7661 {
7662 	dtrace_provider_t *prov;
7663 	void (*func)(void *, dtrace_id_t, void *);
7664 	dtrace_probe_t *probe;
7665 	dtrace_icookie_t cookie;
7666 	int i;
7667 
7668 	/*
7669 	 * We disable interrupts to walk through the probe array.  This is
7670 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
7671 	 * won't see stale data.
7672 	 */
7673 	cookie = dtrace_interrupt_disable();
7674 
7675 	for (i = 0; i < dtrace_nprobes; i++) {
7676 		if ((probe = dtrace_probes[i]) == NULL)
7677 			continue;
7678 
7679 		if (probe->dtpr_ecb == NULL) {
7680 			/*
7681 			 * This probe isn't enabled -- don't call the function.
7682 			 */
7683 			continue;
7684 		}
7685 
7686 		prov = probe->dtpr_provider;
7687 		func = *((void(**)(void *, dtrace_id_t, void *))
7688 		    ((uintptr_t)&prov->dtpv_pops + offs));
7689 
7690 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
7691 	}
7692 
7693 	dtrace_interrupt_enable(cookie);
7694 }
7695 
7696 static int
7697 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
7698 {
7699 	dtrace_probekey_t pkey;
7700 	uint32_t priv;
7701 	uid_t uid;
7702 	zoneid_t zoneid;
7703 
7704 	ASSERT(MUTEX_HELD(&dtrace_lock));
7705 	dtrace_ecb_create_cache = NULL;
7706 
7707 	if (desc == NULL) {
7708 		/*
7709 		 * If we're passed a NULL description, we're being asked to
7710 		 * create an ECB with a NULL probe.
7711 		 */
7712 		(void) dtrace_ecb_create_enable(NULL, enab);
7713 		return (0);
7714 	}
7715 
7716 	dtrace_probekey(desc, &pkey);
7717 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
7718 	    &priv, &uid, &zoneid);
7719 
7720 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
7721 	    enab));
7722 }
7723 
7724 /*
7725  * DTrace Helper Provider Functions
7726  */
7727 static void
7728 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
7729 {
7730 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
7731 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
7732 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
7733 }
7734 
7735 static void
7736 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
7737     const dof_provider_t *dofprov, char *strtab)
7738 {
7739 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
7740 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
7741 	    dofprov->dofpv_provattr);
7742 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
7743 	    dofprov->dofpv_modattr);
7744 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
7745 	    dofprov->dofpv_funcattr);
7746 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
7747 	    dofprov->dofpv_nameattr);
7748 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
7749 	    dofprov->dofpv_argsattr);
7750 }
7751 
7752 static void
7753 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7754 {
7755 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7756 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7757 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
7758 	dof_provider_t *provider;
7759 	dof_probe_t *probe;
7760 	uint32_t *off, *enoff;
7761 	uint8_t *arg;
7762 	char *strtab;
7763 	uint_t i, nprobes;
7764 	dtrace_helper_provdesc_t dhpv;
7765 	dtrace_helper_probedesc_t dhpb;
7766 	dtrace_meta_t *meta = dtrace_meta_pid;
7767 	dtrace_mops_t *mops = &meta->dtm_mops;
7768 	void *parg;
7769 
7770 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7771 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7772 	    provider->dofpv_strtab * dof->dofh_secsize);
7773 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7774 	    provider->dofpv_probes * dof->dofh_secsize);
7775 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7776 	    provider->dofpv_prargs * dof->dofh_secsize);
7777 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7778 	    provider->dofpv_proffs * dof->dofh_secsize);
7779 
7780 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7781 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
7782 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
7783 	enoff = NULL;
7784 
7785 	/*
7786 	 * See dtrace_helper_provider_validate().
7787 	 */
7788 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
7789 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
7790 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7791 		    provider->dofpv_prenoffs * dof->dofh_secsize);
7792 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
7793 	}
7794 
7795 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
7796 
7797 	/*
7798 	 * Create the provider.
7799 	 */
7800 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7801 
7802 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
7803 		return;
7804 
7805 	meta->dtm_count++;
7806 
7807 	/*
7808 	 * Create the probes.
7809 	 */
7810 	for (i = 0; i < nprobes; i++) {
7811 		probe = (dof_probe_t *)(uintptr_t)(daddr +
7812 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
7813 
7814 		dhpb.dthpb_mod = dhp->dofhp_mod;
7815 		dhpb.dthpb_func = strtab + probe->dofpr_func;
7816 		dhpb.dthpb_name = strtab + probe->dofpr_name;
7817 		dhpb.dthpb_base = probe->dofpr_addr;
7818 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
7819 		dhpb.dthpb_noffs = probe->dofpr_noffs;
7820 		if (enoff != NULL) {
7821 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
7822 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
7823 		} else {
7824 			dhpb.dthpb_enoffs = NULL;
7825 			dhpb.dthpb_nenoffs = 0;
7826 		}
7827 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
7828 		dhpb.dthpb_nargc = probe->dofpr_nargc;
7829 		dhpb.dthpb_xargc = probe->dofpr_xargc;
7830 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
7831 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
7832 
7833 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
7834 	}
7835 }
7836 
7837 static void
7838 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
7839 {
7840 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7841 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7842 	int i;
7843 
7844 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7845 
7846 	for (i = 0; i < dof->dofh_secnum; i++) {
7847 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7848 		    dof->dofh_secoff + i * dof->dofh_secsize);
7849 
7850 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7851 			continue;
7852 
7853 		dtrace_helper_provide_one(dhp, sec, pid);
7854 	}
7855 
7856 	/*
7857 	 * We may have just created probes, so we must now rematch against
7858 	 * any retained enablings.  Note that this call will acquire both
7859 	 * cpu_lock and dtrace_lock; the fact that we are holding
7860 	 * dtrace_meta_lock now is what defines the ordering with respect to
7861 	 * these three locks.
7862 	 */
7863 	dtrace_enabling_matchall();
7864 }
7865 
7866 static void
7867 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7868 {
7869 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7870 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7871 	dof_sec_t *str_sec;
7872 	dof_provider_t *provider;
7873 	char *strtab;
7874 	dtrace_helper_provdesc_t dhpv;
7875 	dtrace_meta_t *meta = dtrace_meta_pid;
7876 	dtrace_mops_t *mops = &meta->dtm_mops;
7877 
7878 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7879 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7880 	    provider->dofpv_strtab * dof->dofh_secsize);
7881 
7882 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7883 
7884 	/*
7885 	 * Create the provider.
7886 	 */
7887 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7888 
7889 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
7890 
7891 	meta->dtm_count--;
7892 }
7893 
7894 static void
7895 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
7896 {
7897 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7898 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7899 	int i;
7900 
7901 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7902 
7903 	for (i = 0; i < dof->dofh_secnum; i++) {
7904 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7905 		    dof->dofh_secoff + i * dof->dofh_secsize);
7906 
7907 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7908 			continue;
7909 
7910 		dtrace_helper_provider_remove_one(dhp, sec, pid);
7911 	}
7912 }
7913 
7914 /*
7915  * DTrace Meta Provider-to-Framework API Functions
7916  *
7917  * These functions implement the Meta Provider-to-Framework API, as described
7918  * in <sys/dtrace.h>.
7919  */
7920 int
7921 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
7922     dtrace_meta_provider_id_t *idp)
7923 {
7924 	dtrace_meta_t *meta;
7925 	dtrace_helpers_t *help, *next;
7926 	int i;
7927 
7928 	*idp = DTRACE_METAPROVNONE;
7929 
7930 	/*
7931 	 * We strictly don't need the name, but we hold onto it for
7932 	 * debuggability. All hail error queues!
7933 	 */
7934 	if (name == NULL) {
7935 		cmn_err(CE_WARN, "failed to register meta-provider: "
7936 		    "invalid name");
7937 		return (EINVAL);
7938 	}
7939 
7940 	if (mops == NULL ||
7941 	    mops->dtms_create_probe == NULL ||
7942 	    mops->dtms_provide_pid == NULL ||
7943 	    mops->dtms_remove_pid == NULL) {
7944 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7945 		    "invalid ops", name);
7946 		return (EINVAL);
7947 	}
7948 
7949 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
7950 	meta->dtm_mops = *mops;
7951 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7952 	(void) strcpy(meta->dtm_name, name);
7953 	meta->dtm_arg = arg;
7954 
7955 	mutex_enter(&dtrace_meta_lock);
7956 	mutex_enter(&dtrace_lock);
7957 
7958 	if (dtrace_meta_pid != NULL) {
7959 		mutex_exit(&dtrace_lock);
7960 		mutex_exit(&dtrace_meta_lock);
7961 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7962 		    "user-land meta-provider exists", name);
7963 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
7964 		kmem_free(meta, sizeof (dtrace_meta_t));
7965 		return (EINVAL);
7966 	}
7967 
7968 	dtrace_meta_pid = meta;
7969 	*idp = (dtrace_meta_provider_id_t)meta;
7970 
7971 	/*
7972 	 * If there are providers and probes ready to go, pass them
7973 	 * off to the new meta provider now.
7974 	 */
7975 
7976 	help = dtrace_deferred_pid;
7977 	dtrace_deferred_pid = NULL;
7978 
7979 	mutex_exit(&dtrace_lock);
7980 
7981 	while (help != NULL) {
7982 		for (i = 0; i < help->dthps_nprovs; i++) {
7983 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
7984 			    help->dthps_pid);
7985 		}
7986 
7987 		next = help->dthps_next;
7988 		help->dthps_next = NULL;
7989 		help->dthps_prev = NULL;
7990 		help->dthps_deferred = 0;
7991 		help = next;
7992 	}
7993 
7994 	mutex_exit(&dtrace_meta_lock);
7995 
7996 	return (0);
7997 }
7998 
7999 int
8000 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8001 {
8002 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8003 
8004 	mutex_enter(&dtrace_meta_lock);
8005 	mutex_enter(&dtrace_lock);
8006 
8007 	if (old == dtrace_meta_pid) {
8008 		pp = &dtrace_meta_pid;
8009 	} else {
8010 		panic("attempt to unregister non-existent "
8011 		    "dtrace meta-provider %p\n", (void *)old);
8012 	}
8013 
8014 	if (old->dtm_count != 0) {
8015 		mutex_exit(&dtrace_lock);
8016 		mutex_exit(&dtrace_meta_lock);
8017 		return (EBUSY);
8018 	}
8019 
8020 	*pp = NULL;
8021 
8022 	mutex_exit(&dtrace_lock);
8023 	mutex_exit(&dtrace_meta_lock);
8024 
8025 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8026 	kmem_free(old, sizeof (dtrace_meta_t));
8027 
8028 	return (0);
8029 }
8030 
8031 
8032 /*
8033  * DTrace DIF Object Functions
8034  */
8035 static int
8036 dtrace_difo_err(uint_t pc, const char *format, ...)
8037 {
8038 	if (dtrace_err_verbose) {
8039 		va_list alist;
8040 
8041 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
8042 		va_start(alist, format);
8043 		(void) vuprintf(format, alist);
8044 		va_end(alist);
8045 	}
8046 
8047 #ifdef DTRACE_ERRDEBUG
8048 	dtrace_errdebug(format);
8049 #endif
8050 	return (1);
8051 }
8052 
8053 /*
8054  * Validate a DTrace DIF object by checking the IR instructions.  The following
8055  * rules are currently enforced by dtrace_difo_validate():
8056  *
8057  * 1. Each instruction must have a valid opcode
8058  * 2. Each register, string, variable, or subroutine reference must be valid
8059  * 3. No instruction can modify register %r0 (must be zero)
8060  * 4. All instruction reserved bits must be set to zero
8061  * 5. The last instruction must be a "ret" instruction
8062  * 6. All branch targets must reference a valid instruction _after_ the branch
8063  */
8064 static int
8065 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8066     cred_t *cr)
8067 {
8068 	int err = 0, i;
8069 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8070 	int kcheckload;
8071 	uint_t pc;
8072 
8073 	kcheckload = cr == NULL ||
8074 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8075 
8076 	dp->dtdo_destructive = 0;
8077 
8078 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8079 		dif_instr_t instr = dp->dtdo_buf[pc];
8080 
8081 		uint_t r1 = DIF_INSTR_R1(instr);
8082 		uint_t r2 = DIF_INSTR_R2(instr);
8083 		uint_t rd = DIF_INSTR_RD(instr);
8084 		uint_t rs = DIF_INSTR_RS(instr);
8085 		uint_t label = DIF_INSTR_LABEL(instr);
8086 		uint_t v = DIF_INSTR_VAR(instr);
8087 		uint_t subr = DIF_INSTR_SUBR(instr);
8088 		uint_t type = DIF_INSTR_TYPE(instr);
8089 		uint_t op = DIF_INSTR_OP(instr);
8090 
8091 		switch (op) {
8092 		case DIF_OP_OR:
8093 		case DIF_OP_XOR:
8094 		case DIF_OP_AND:
8095 		case DIF_OP_SLL:
8096 		case DIF_OP_SRL:
8097 		case DIF_OP_SRA:
8098 		case DIF_OP_SUB:
8099 		case DIF_OP_ADD:
8100 		case DIF_OP_MUL:
8101 		case DIF_OP_SDIV:
8102 		case DIF_OP_UDIV:
8103 		case DIF_OP_SREM:
8104 		case DIF_OP_UREM:
8105 		case DIF_OP_COPYS:
8106 			if (r1 >= nregs)
8107 				err += efunc(pc, "invalid register %u\n", r1);
8108 			if (r2 >= nregs)
8109 				err += efunc(pc, "invalid register %u\n", r2);
8110 			if (rd >= nregs)
8111 				err += efunc(pc, "invalid register %u\n", rd);
8112 			if (rd == 0)
8113 				err += efunc(pc, "cannot write to %r0\n");
8114 			break;
8115 		case DIF_OP_NOT:
8116 		case DIF_OP_MOV:
8117 		case DIF_OP_ALLOCS:
8118 			if (r1 >= nregs)
8119 				err += efunc(pc, "invalid register %u\n", r1);
8120 			if (r2 != 0)
8121 				err += efunc(pc, "non-zero reserved bits\n");
8122 			if (rd >= nregs)
8123 				err += efunc(pc, "invalid register %u\n", rd);
8124 			if (rd == 0)
8125 				err += efunc(pc, "cannot write to %r0\n");
8126 			break;
8127 		case DIF_OP_LDSB:
8128 		case DIF_OP_LDSH:
8129 		case DIF_OP_LDSW:
8130 		case DIF_OP_LDUB:
8131 		case DIF_OP_LDUH:
8132 		case DIF_OP_LDUW:
8133 		case DIF_OP_LDX:
8134 			if (r1 >= nregs)
8135 				err += efunc(pc, "invalid register %u\n", r1);
8136 			if (r2 != 0)
8137 				err += efunc(pc, "non-zero reserved bits\n");
8138 			if (rd >= nregs)
8139 				err += efunc(pc, "invalid register %u\n", rd);
8140 			if (rd == 0)
8141 				err += efunc(pc, "cannot write to %r0\n");
8142 			if (kcheckload)
8143 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8144 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8145 			break;
8146 		case DIF_OP_RLDSB:
8147 		case DIF_OP_RLDSH:
8148 		case DIF_OP_RLDSW:
8149 		case DIF_OP_RLDUB:
8150 		case DIF_OP_RLDUH:
8151 		case DIF_OP_RLDUW:
8152 		case DIF_OP_RLDX:
8153 			if (r1 >= nregs)
8154 				err += efunc(pc, "invalid register %u\n", r1);
8155 			if (r2 != 0)
8156 				err += efunc(pc, "non-zero reserved bits\n");
8157 			if (rd >= nregs)
8158 				err += efunc(pc, "invalid register %u\n", rd);
8159 			if (rd == 0)
8160 				err += efunc(pc, "cannot write to %r0\n");
8161 			break;
8162 		case DIF_OP_ULDSB:
8163 		case DIF_OP_ULDSH:
8164 		case DIF_OP_ULDSW:
8165 		case DIF_OP_ULDUB:
8166 		case DIF_OP_ULDUH:
8167 		case DIF_OP_ULDUW:
8168 		case DIF_OP_ULDX:
8169 			if (r1 >= nregs)
8170 				err += efunc(pc, "invalid register %u\n", r1);
8171 			if (r2 != 0)
8172 				err += efunc(pc, "non-zero reserved bits\n");
8173 			if (rd >= nregs)
8174 				err += efunc(pc, "invalid register %u\n", rd);
8175 			if (rd == 0)
8176 				err += efunc(pc, "cannot write to %r0\n");
8177 			break;
8178 		case DIF_OP_STB:
8179 		case DIF_OP_STH:
8180 		case DIF_OP_STW:
8181 		case DIF_OP_STX:
8182 			if (r1 >= nregs)
8183 				err += efunc(pc, "invalid register %u\n", r1);
8184 			if (r2 != 0)
8185 				err += efunc(pc, "non-zero reserved bits\n");
8186 			if (rd >= nregs)
8187 				err += efunc(pc, "invalid register %u\n", rd);
8188 			if (rd == 0)
8189 				err += efunc(pc, "cannot write to 0 address\n");
8190 			break;
8191 		case DIF_OP_CMP:
8192 		case DIF_OP_SCMP:
8193 			if (r1 >= nregs)
8194 				err += efunc(pc, "invalid register %u\n", r1);
8195 			if (r2 >= nregs)
8196 				err += efunc(pc, "invalid register %u\n", r2);
8197 			if (rd != 0)
8198 				err += efunc(pc, "non-zero reserved bits\n");
8199 			break;
8200 		case DIF_OP_TST:
8201 			if (r1 >= nregs)
8202 				err += efunc(pc, "invalid register %u\n", r1);
8203 			if (r2 != 0 || rd != 0)
8204 				err += efunc(pc, "non-zero reserved bits\n");
8205 			break;
8206 		case DIF_OP_BA:
8207 		case DIF_OP_BE:
8208 		case DIF_OP_BNE:
8209 		case DIF_OP_BG:
8210 		case DIF_OP_BGU:
8211 		case DIF_OP_BGE:
8212 		case DIF_OP_BGEU:
8213 		case DIF_OP_BL:
8214 		case DIF_OP_BLU:
8215 		case DIF_OP_BLE:
8216 		case DIF_OP_BLEU:
8217 			if (label >= dp->dtdo_len) {
8218 				err += efunc(pc, "invalid branch target %u\n",
8219 				    label);
8220 			}
8221 			if (label <= pc) {
8222 				err += efunc(pc, "backward branch to %u\n",
8223 				    label);
8224 			}
8225 			break;
8226 		case DIF_OP_RET:
8227 			if (r1 != 0 || r2 != 0)
8228 				err += efunc(pc, "non-zero reserved bits\n");
8229 			if (rd >= nregs)
8230 				err += efunc(pc, "invalid register %u\n", rd);
8231 			break;
8232 		case DIF_OP_NOP:
8233 		case DIF_OP_POPTS:
8234 		case DIF_OP_FLUSHTS:
8235 			if (r1 != 0 || r2 != 0 || rd != 0)
8236 				err += efunc(pc, "non-zero reserved bits\n");
8237 			break;
8238 		case DIF_OP_SETX:
8239 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8240 				err += efunc(pc, "invalid integer ref %u\n",
8241 				    DIF_INSTR_INTEGER(instr));
8242 			}
8243 			if (rd >= nregs)
8244 				err += efunc(pc, "invalid register %u\n", rd);
8245 			if (rd == 0)
8246 				err += efunc(pc, "cannot write to %r0\n");
8247 			break;
8248 		case DIF_OP_SETS:
8249 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8250 				err += efunc(pc, "invalid string ref %u\n",
8251 				    DIF_INSTR_STRING(instr));
8252 			}
8253 			if (rd >= nregs)
8254 				err += efunc(pc, "invalid register %u\n", rd);
8255 			if (rd == 0)
8256 				err += efunc(pc, "cannot write to %r0\n");
8257 			break;
8258 		case DIF_OP_LDGA:
8259 		case DIF_OP_LDTA:
8260 			if (r1 > DIF_VAR_ARRAY_MAX)
8261 				err += efunc(pc, "invalid array %u\n", r1);
8262 			if (r2 >= nregs)
8263 				err += efunc(pc, "invalid register %u\n", r2);
8264 			if (rd >= nregs)
8265 				err += efunc(pc, "invalid register %u\n", rd);
8266 			if (rd == 0)
8267 				err += efunc(pc, "cannot write to %r0\n");
8268 			break;
8269 		case DIF_OP_LDGS:
8270 		case DIF_OP_LDTS:
8271 		case DIF_OP_LDLS:
8272 		case DIF_OP_LDGAA:
8273 		case DIF_OP_LDTAA:
8274 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8275 				err += efunc(pc, "invalid variable %u\n", v);
8276 			if (rd >= nregs)
8277 				err += efunc(pc, "invalid register %u\n", rd);
8278 			if (rd == 0)
8279 				err += efunc(pc, "cannot write to %r0\n");
8280 			break;
8281 		case DIF_OP_STGS:
8282 		case DIF_OP_STTS:
8283 		case DIF_OP_STLS:
8284 		case DIF_OP_STGAA:
8285 		case DIF_OP_STTAA:
8286 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8287 				err += efunc(pc, "invalid variable %u\n", v);
8288 			if (rs >= nregs)
8289 				err += efunc(pc, "invalid register %u\n", rd);
8290 			break;
8291 		case DIF_OP_CALL:
8292 			if (subr > DIF_SUBR_MAX)
8293 				err += efunc(pc, "invalid subr %u\n", subr);
8294 			if (rd >= nregs)
8295 				err += efunc(pc, "invalid register %u\n", rd);
8296 			if (rd == 0)
8297 				err += efunc(pc, "cannot write to %r0\n");
8298 
8299 			if (subr == DIF_SUBR_COPYOUT ||
8300 			    subr == DIF_SUBR_COPYOUTSTR) {
8301 				dp->dtdo_destructive = 1;
8302 			}
8303 			break;
8304 		case DIF_OP_PUSHTR:
8305 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8306 				err += efunc(pc, "invalid ref type %u\n", type);
8307 			if (r2 >= nregs)
8308 				err += efunc(pc, "invalid register %u\n", r2);
8309 			if (rs >= nregs)
8310 				err += efunc(pc, "invalid register %u\n", rs);
8311 			break;
8312 		case DIF_OP_PUSHTV:
8313 			if (type != DIF_TYPE_CTF)
8314 				err += efunc(pc, "invalid val type %u\n", type);
8315 			if (r2 >= nregs)
8316 				err += efunc(pc, "invalid register %u\n", r2);
8317 			if (rs >= nregs)
8318 				err += efunc(pc, "invalid register %u\n", rs);
8319 			break;
8320 		default:
8321 			err += efunc(pc, "invalid opcode %u\n",
8322 			    DIF_INSTR_OP(instr));
8323 		}
8324 	}
8325 
8326 	if (dp->dtdo_len != 0 &&
8327 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8328 		err += efunc(dp->dtdo_len - 1,
8329 		    "expected 'ret' as last DIF instruction\n");
8330 	}
8331 
8332 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
8333 		/*
8334 		 * If we're not returning by reference, the size must be either
8335 		 * 0 or the size of one of the base types.
8336 		 */
8337 		switch (dp->dtdo_rtype.dtdt_size) {
8338 		case 0:
8339 		case sizeof (uint8_t):
8340 		case sizeof (uint16_t):
8341 		case sizeof (uint32_t):
8342 		case sizeof (uint64_t):
8343 			break;
8344 
8345 		default:
8346 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
8347 		}
8348 	}
8349 
8350 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8351 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8352 		dtrace_diftype_t *vt, *et;
8353 		uint_t id, ndx;
8354 
8355 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8356 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
8357 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8358 			err += efunc(i, "unrecognized variable scope %d\n",
8359 			    v->dtdv_scope);
8360 			break;
8361 		}
8362 
8363 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8364 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
8365 			err += efunc(i, "unrecognized variable type %d\n",
8366 			    v->dtdv_kind);
8367 			break;
8368 		}
8369 
8370 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8371 			err += efunc(i, "%d exceeds variable id limit\n", id);
8372 			break;
8373 		}
8374 
8375 		if (id < DIF_VAR_OTHER_UBASE)
8376 			continue;
8377 
8378 		/*
8379 		 * For user-defined variables, we need to check that this
8380 		 * definition is identical to any previous definition that we
8381 		 * encountered.
8382 		 */
8383 		ndx = id - DIF_VAR_OTHER_UBASE;
8384 
8385 		switch (v->dtdv_scope) {
8386 		case DIFV_SCOPE_GLOBAL:
8387 			if (ndx < vstate->dtvs_nglobals) {
8388 				dtrace_statvar_t *svar;
8389 
8390 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8391 					existing = &svar->dtsv_var;
8392 			}
8393 
8394 			break;
8395 
8396 		case DIFV_SCOPE_THREAD:
8397 			if (ndx < vstate->dtvs_ntlocals)
8398 				existing = &vstate->dtvs_tlocals[ndx];
8399 			break;
8400 
8401 		case DIFV_SCOPE_LOCAL:
8402 			if (ndx < vstate->dtvs_nlocals) {
8403 				dtrace_statvar_t *svar;
8404 
8405 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8406 					existing = &svar->dtsv_var;
8407 			}
8408 
8409 			break;
8410 		}
8411 
8412 		vt = &v->dtdv_type;
8413 
8414 		if (vt->dtdt_flags & DIF_TF_BYREF) {
8415 			if (vt->dtdt_size == 0) {
8416 				err += efunc(i, "zero-sized variable\n");
8417 				break;
8418 			}
8419 
8420 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8421 			    vt->dtdt_size > dtrace_global_maxsize) {
8422 				err += efunc(i, "oversized by-ref global\n");
8423 				break;
8424 			}
8425 		}
8426 
8427 		if (existing == NULL || existing->dtdv_id == 0)
8428 			continue;
8429 
8430 		ASSERT(existing->dtdv_id == v->dtdv_id);
8431 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
8432 
8433 		if (existing->dtdv_kind != v->dtdv_kind)
8434 			err += efunc(i, "%d changed variable kind\n", id);
8435 
8436 		et = &existing->dtdv_type;
8437 
8438 		if (vt->dtdt_flags != et->dtdt_flags) {
8439 			err += efunc(i, "%d changed variable type flags\n", id);
8440 			break;
8441 		}
8442 
8443 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8444 			err += efunc(i, "%d changed variable type size\n", id);
8445 			break;
8446 		}
8447 	}
8448 
8449 	return (err);
8450 }
8451 
8452 /*
8453  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
8454  * are much more constrained than normal DIFOs.  Specifically, they may
8455  * not:
8456  *
8457  * 1. Make calls to subroutines other than copyin(), copyinstr() or
8458  *    miscellaneous string routines
8459  * 2. Access DTrace variables other than the args[] array, and the
8460  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8461  * 3. Have thread-local variables.
8462  * 4. Have dynamic variables.
8463  */
8464 static int
8465 dtrace_difo_validate_helper(dtrace_difo_t *dp)
8466 {
8467 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8468 	int err = 0;
8469 	uint_t pc;
8470 
8471 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8472 		dif_instr_t instr = dp->dtdo_buf[pc];
8473 
8474 		uint_t v = DIF_INSTR_VAR(instr);
8475 		uint_t subr = DIF_INSTR_SUBR(instr);
8476 		uint_t op = DIF_INSTR_OP(instr);
8477 
8478 		switch (op) {
8479 		case DIF_OP_OR:
8480 		case DIF_OP_XOR:
8481 		case DIF_OP_AND:
8482 		case DIF_OP_SLL:
8483 		case DIF_OP_SRL:
8484 		case DIF_OP_SRA:
8485 		case DIF_OP_SUB:
8486 		case DIF_OP_ADD:
8487 		case DIF_OP_MUL:
8488 		case DIF_OP_SDIV:
8489 		case DIF_OP_UDIV:
8490 		case DIF_OP_SREM:
8491 		case DIF_OP_UREM:
8492 		case DIF_OP_COPYS:
8493 		case DIF_OP_NOT:
8494 		case DIF_OP_MOV:
8495 		case DIF_OP_RLDSB:
8496 		case DIF_OP_RLDSH:
8497 		case DIF_OP_RLDSW:
8498 		case DIF_OP_RLDUB:
8499 		case DIF_OP_RLDUH:
8500 		case DIF_OP_RLDUW:
8501 		case DIF_OP_RLDX:
8502 		case DIF_OP_ULDSB:
8503 		case DIF_OP_ULDSH:
8504 		case DIF_OP_ULDSW:
8505 		case DIF_OP_ULDUB:
8506 		case DIF_OP_ULDUH:
8507 		case DIF_OP_ULDUW:
8508 		case DIF_OP_ULDX:
8509 		case DIF_OP_STB:
8510 		case DIF_OP_STH:
8511 		case DIF_OP_STW:
8512 		case DIF_OP_STX:
8513 		case DIF_OP_ALLOCS:
8514 		case DIF_OP_CMP:
8515 		case DIF_OP_SCMP:
8516 		case DIF_OP_TST:
8517 		case DIF_OP_BA:
8518 		case DIF_OP_BE:
8519 		case DIF_OP_BNE:
8520 		case DIF_OP_BG:
8521 		case DIF_OP_BGU:
8522 		case DIF_OP_BGE:
8523 		case DIF_OP_BGEU:
8524 		case DIF_OP_BL:
8525 		case DIF_OP_BLU:
8526 		case DIF_OP_BLE:
8527 		case DIF_OP_BLEU:
8528 		case DIF_OP_RET:
8529 		case DIF_OP_NOP:
8530 		case DIF_OP_POPTS:
8531 		case DIF_OP_FLUSHTS:
8532 		case DIF_OP_SETX:
8533 		case DIF_OP_SETS:
8534 		case DIF_OP_LDGA:
8535 		case DIF_OP_LDLS:
8536 		case DIF_OP_STGS:
8537 		case DIF_OP_STLS:
8538 		case DIF_OP_PUSHTR:
8539 		case DIF_OP_PUSHTV:
8540 			break;
8541 
8542 		case DIF_OP_LDGS:
8543 			if (v >= DIF_VAR_OTHER_UBASE)
8544 				break;
8545 
8546 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
8547 				break;
8548 
8549 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
8550 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
8551 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
8552 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
8553 				break;
8554 
8555 			err += efunc(pc, "illegal variable %u\n", v);
8556 			break;
8557 
8558 		case DIF_OP_LDTA:
8559 		case DIF_OP_LDTS:
8560 		case DIF_OP_LDGAA:
8561 		case DIF_OP_LDTAA:
8562 			err += efunc(pc, "illegal dynamic variable load\n");
8563 			break;
8564 
8565 		case DIF_OP_STTS:
8566 		case DIF_OP_STGAA:
8567 		case DIF_OP_STTAA:
8568 			err += efunc(pc, "illegal dynamic variable store\n");
8569 			break;
8570 
8571 		case DIF_OP_CALL:
8572 			if (subr == DIF_SUBR_ALLOCA ||
8573 			    subr == DIF_SUBR_BCOPY ||
8574 			    subr == DIF_SUBR_COPYIN ||
8575 			    subr == DIF_SUBR_COPYINTO ||
8576 			    subr == DIF_SUBR_COPYINSTR ||
8577 			    subr == DIF_SUBR_INDEX ||
8578 			    subr == DIF_SUBR_INET_NTOA ||
8579 			    subr == DIF_SUBR_INET_NTOA6 ||
8580 			    subr == DIF_SUBR_INET_NTOP ||
8581 			    subr == DIF_SUBR_LLTOSTR ||
8582 			    subr == DIF_SUBR_RINDEX ||
8583 			    subr == DIF_SUBR_STRCHR ||
8584 			    subr == DIF_SUBR_STRJOIN ||
8585 			    subr == DIF_SUBR_STRRCHR ||
8586 			    subr == DIF_SUBR_STRSTR ||
8587 			    subr == DIF_SUBR_HTONS ||
8588 			    subr == DIF_SUBR_HTONL ||
8589 			    subr == DIF_SUBR_HTONLL ||
8590 			    subr == DIF_SUBR_NTOHS ||
8591 			    subr == DIF_SUBR_NTOHL ||
8592 			    subr == DIF_SUBR_NTOHLL)
8593 				break;
8594 
8595 			err += efunc(pc, "invalid subr %u\n", subr);
8596 			break;
8597 
8598 		default:
8599 			err += efunc(pc, "invalid opcode %u\n",
8600 			    DIF_INSTR_OP(instr));
8601 		}
8602 	}
8603 
8604 	return (err);
8605 }
8606 
8607 /*
8608  * Returns 1 if the expression in the DIF object can be cached on a per-thread
8609  * basis; 0 if not.
8610  */
8611 static int
8612 dtrace_difo_cacheable(dtrace_difo_t *dp)
8613 {
8614 	int i;
8615 
8616 	if (dp == NULL)
8617 		return (0);
8618 
8619 	for (i = 0; i < dp->dtdo_varlen; i++) {
8620 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8621 
8622 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
8623 			continue;
8624 
8625 		switch (v->dtdv_id) {
8626 		case DIF_VAR_CURTHREAD:
8627 		case DIF_VAR_PID:
8628 		case DIF_VAR_TID:
8629 		case DIF_VAR_EXECNAME:
8630 		case DIF_VAR_ZONENAME:
8631 			break;
8632 
8633 		default:
8634 			return (0);
8635 		}
8636 	}
8637 
8638 	/*
8639 	 * This DIF object may be cacheable.  Now we need to look for any
8640 	 * array loading instructions, any memory loading instructions, or
8641 	 * any stores to thread-local variables.
8642 	 */
8643 	for (i = 0; i < dp->dtdo_len; i++) {
8644 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
8645 
8646 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
8647 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
8648 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
8649 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
8650 			return (0);
8651 	}
8652 
8653 	return (1);
8654 }
8655 
8656 static void
8657 dtrace_difo_hold(dtrace_difo_t *dp)
8658 {
8659 	int i;
8660 
8661 	ASSERT(MUTEX_HELD(&dtrace_lock));
8662 
8663 	dp->dtdo_refcnt++;
8664 	ASSERT(dp->dtdo_refcnt != 0);
8665 
8666 	/*
8667 	 * We need to check this DIF object for references to the variable
8668 	 * DIF_VAR_VTIMESTAMP.
8669 	 */
8670 	for (i = 0; i < dp->dtdo_varlen; i++) {
8671 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8672 
8673 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8674 			continue;
8675 
8676 		if (dtrace_vtime_references++ == 0)
8677 			dtrace_vtime_enable();
8678 	}
8679 }
8680 
8681 /*
8682  * This routine calculates the dynamic variable chunksize for a given DIF
8683  * object.  The calculation is not fool-proof, and can probably be tricked by
8684  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
8685  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
8686  * if a dynamic variable size exceeds the chunksize.
8687  */
8688 static void
8689 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8690 {
8691 	uint64_t sval;
8692 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
8693 	const dif_instr_t *text = dp->dtdo_buf;
8694 	uint_t pc, srd = 0;
8695 	uint_t ttop = 0;
8696 	size_t size, ksize;
8697 	uint_t id, i;
8698 
8699 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8700 		dif_instr_t instr = text[pc];
8701 		uint_t op = DIF_INSTR_OP(instr);
8702 		uint_t rd = DIF_INSTR_RD(instr);
8703 		uint_t r1 = DIF_INSTR_R1(instr);
8704 		uint_t nkeys = 0;
8705 		uchar_t scope;
8706 
8707 		dtrace_key_t *key = tupregs;
8708 
8709 		switch (op) {
8710 		case DIF_OP_SETX:
8711 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
8712 			srd = rd;
8713 			continue;
8714 
8715 		case DIF_OP_STTS:
8716 			key = &tupregs[DIF_DTR_NREGS];
8717 			key[0].dttk_size = 0;
8718 			key[1].dttk_size = 0;
8719 			nkeys = 2;
8720 			scope = DIFV_SCOPE_THREAD;
8721 			break;
8722 
8723 		case DIF_OP_STGAA:
8724 		case DIF_OP_STTAA:
8725 			nkeys = ttop;
8726 
8727 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
8728 				key[nkeys++].dttk_size = 0;
8729 
8730 			key[nkeys++].dttk_size = 0;
8731 
8732 			if (op == DIF_OP_STTAA) {
8733 				scope = DIFV_SCOPE_THREAD;
8734 			} else {
8735 				scope = DIFV_SCOPE_GLOBAL;
8736 			}
8737 
8738 			break;
8739 
8740 		case DIF_OP_PUSHTR:
8741 			if (ttop == DIF_DTR_NREGS)
8742 				return;
8743 
8744 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
8745 				/*
8746 				 * If the register for the size of the "pushtr"
8747 				 * is %r0 (or the value is 0) and the type is
8748 				 * a string, we'll use the system-wide default
8749 				 * string size.
8750 				 */
8751 				tupregs[ttop++].dttk_size =
8752 				    dtrace_strsize_default;
8753 			} else {
8754 				if (srd == 0)
8755 					return;
8756 
8757 				tupregs[ttop++].dttk_size = sval;
8758 			}
8759 
8760 			break;
8761 
8762 		case DIF_OP_PUSHTV:
8763 			if (ttop == DIF_DTR_NREGS)
8764 				return;
8765 
8766 			tupregs[ttop++].dttk_size = 0;
8767 			break;
8768 
8769 		case DIF_OP_FLUSHTS:
8770 			ttop = 0;
8771 			break;
8772 
8773 		case DIF_OP_POPTS:
8774 			if (ttop != 0)
8775 				ttop--;
8776 			break;
8777 		}
8778 
8779 		sval = 0;
8780 		srd = 0;
8781 
8782 		if (nkeys == 0)
8783 			continue;
8784 
8785 		/*
8786 		 * We have a dynamic variable allocation; calculate its size.
8787 		 */
8788 		for (ksize = 0, i = 0; i < nkeys; i++)
8789 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
8790 
8791 		size = sizeof (dtrace_dynvar_t);
8792 		size += sizeof (dtrace_key_t) * (nkeys - 1);
8793 		size += ksize;
8794 
8795 		/*
8796 		 * Now we need to determine the size of the stored data.
8797 		 */
8798 		id = DIF_INSTR_VAR(instr);
8799 
8800 		for (i = 0; i < dp->dtdo_varlen; i++) {
8801 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
8802 
8803 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
8804 				size += v->dtdv_type.dtdt_size;
8805 				break;
8806 			}
8807 		}
8808 
8809 		if (i == dp->dtdo_varlen)
8810 			return;
8811 
8812 		/*
8813 		 * We have the size.  If this is larger than the chunk size
8814 		 * for our dynamic variable state, reset the chunk size.
8815 		 */
8816 		size = P2ROUNDUP(size, sizeof (uint64_t));
8817 
8818 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
8819 			vstate->dtvs_dynvars.dtds_chunksize = size;
8820 	}
8821 }
8822 
8823 static void
8824 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8825 {
8826 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
8827 	uint_t id;
8828 
8829 	ASSERT(MUTEX_HELD(&dtrace_lock));
8830 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
8831 
8832 	for (i = 0; i < dp->dtdo_varlen; i++) {
8833 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8834 		dtrace_statvar_t *svar, ***svarp;
8835 		size_t dsize = 0;
8836 		uint8_t scope = v->dtdv_scope;
8837 		int *np;
8838 
8839 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8840 			continue;
8841 
8842 		id -= DIF_VAR_OTHER_UBASE;
8843 
8844 		switch (scope) {
8845 		case DIFV_SCOPE_THREAD:
8846 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
8847 				dtrace_difv_t *tlocals;
8848 
8849 				if ((ntlocals = (otlocals << 1)) == 0)
8850 					ntlocals = 1;
8851 
8852 				osz = otlocals * sizeof (dtrace_difv_t);
8853 				nsz = ntlocals * sizeof (dtrace_difv_t);
8854 
8855 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
8856 
8857 				if (osz != 0) {
8858 					bcopy(vstate->dtvs_tlocals,
8859 					    tlocals, osz);
8860 					kmem_free(vstate->dtvs_tlocals, osz);
8861 				}
8862 
8863 				vstate->dtvs_tlocals = tlocals;
8864 				vstate->dtvs_ntlocals = ntlocals;
8865 			}
8866 
8867 			vstate->dtvs_tlocals[id] = *v;
8868 			continue;
8869 
8870 		case DIFV_SCOPE_LOCAL:
8871 			np = &vstate->dtvs_nlocals;
8872 			svarp = &vstate->dtvs_locals;
8873 
8874 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8875 				dsize = NCPU * (v->dtdv_type.dtdt_size +
8876 				    sizeof (uint64_t));
8877 			else
8878 				dsize = NCPU * sizeof (uint64_t);
8879 
8880 			break;
8881 
8882 		case DIFV_SCOPE_GLOBAL:
8883 			np = &vstate->dtvs_nglobals;
8884 			svarp = &vstate->dtvs_globals;
8885 
8886 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8887 				dsize = v->dtdv_type.dtdt_size +
8888 				    sizeof (uint64_t);
8889 
8890 			break;
8891 
8892 		default:
8893 			ASSERT(0);
8894 		}
8895 
8896 		while (id >= (oldsvars = *np)) {
8897 			dtrace_statvar_t **statics;
8898 			int newsvars, oldsize, newsize;
8899 
8900 			if ((newsvars = (oldsvars << 1)) == 0)
8901 				newsvars = 1;
8902 
8903 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
8904 			newsize = newsvars * sizeof (dtrace_statvar_t *);
8905 
8906 			statics = kmem_zalloc(newsize, KM_SLEEP);
8907 
8908 			if (oldsize != 0) {
8909 				bcopy(*svarp, statics, oldsize);
8910 				kmem_free(*svarp, oldsize);
8911 			}
8912 
8913 			*svarp = statics;
8914 			*np = newsvars;
8915 		}
8916 
8917 		if ((svar = (*svarp)[id]) == NULL) {
8918 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
8919 			svar->dtsv_var = *v;
8920 
8921 			if ((svar->dtsv_size = dsize) != 0) {
8922 				svar->dtsv_data = (uint64_t)(uintptr_t)
8923 				    kmem_zalloc(dsize, KM_SLEEP);
8924 			}
8925 
8926 			(*svarp)[id] = svar;
8927 		}
8928 
8929 		svar->dtsv_refcnt++;
8930 	}
8931 
8932 	dtrace_difo_chunksize(dp, vstate);
8933 	dtrace_difo_hold(dp);
8934 }
8935 
8936 static dtrace_difo_t *
8937 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8938 {
8939 	dtrace_difo_t *new;
8940 	size_t sz;
8941 
8942 	ASSERT(dp->dtdo_buf != NULL);
8943 	ASSERT(dp->dtdo_refcnt != 0);
8944 
8945 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
8946 
8947 	ASSERT(dp->dtdo_buf != NULL);
8948 	sz = dp->dtdo_len * sizeof (dif_instr_t);
8949 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
8950 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
8951 	new->dtdo_len = dp->dtdo_len;
8952 
8953 	if (dp->dtdo_strtab != NULL) {
8954 		ASSERT(dp->dtdo_strlen != 0);
8955 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
8956 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
8957 		new->dtdo_strlen = dp->dtdo_strlen;
8958 	}
8959 
8960 	if (dp->dtdo_inttab != NULL) {
8961 		ASSERT(dp->dtdo_intlen != 0);
8962 		sz = dp->dtdo_intlen * sizeof (uint64_t);
8963 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
8964 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
8965 		new->dtdo_intlen = dp->dtdo_intlen;
8966 	}
8967 
8968 	if (dp->dtdo_vartab != NULL) {
8969 		ASSERT(dp->dtdo_varlen != 0);
8970 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
8971 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
8972 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
8973 		new->dtdo_varlen = dp->dtdo_varlen;
8974 	}
8975 
8976 	dtrace_difo_init(new, vstate);
8977 	return (new);
8978 }
8979 
8980 static void
8981 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8982 {
8983 	int i;
8984 
8985 	ASSERT(dp->dtdo_refcnt == 0);
8986 
8987 	for (i = 0; i < dp->dtdo_varlen; i++) {
8988 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8989 		dtrace_statvar_t *svar, **svarp;
8990 		uint_t id;
8991 		uint8_t scope = v->dtdv_scope;
8992 		int *np;
8993 
8994 		switch (scope) {
8995 		case DIFV_SCOPE_THREAD:
8996 			continue;
8997 
8998 		case DIFV_SCOPE_LOCAL:
8999 			np = &vstate->dtvs_nlocals;
9000 			svarp = vstate->dtvs_locals;
9001 			break;
9002 
9003 		case DIFV_SCOPE_GLOBAL:
9004 			np = &vstate->dtvs_nglobals;
9005 			svarp = vstate->dtvs_globals;
9006 			break;
9007 
9008 		default:
9009 			ASSERT(0);
9010 		}
9011 
9012 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9013 			continue;
9014 
9015 		id -= DIF_VAR_OTHER_UBASE;
9016 		ASSERT(id < *np);
9017 
9018 		svar = svarp[id];
9019 		ASSERT(svar != NULL);
9020 		ASSERT(svar->dtsv_refcnt > 0);
9021 
9022 		if (--svar->dtsv_refcnt > 0)
9023 			continue;
9024 
9025 		if (svar->dtsv_size != 0) {
9026 			ASSERT(svar->dtsv_data != NULL);
9027 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
9028 			    svar->dtsv_size);
9029 		}
9030 
9031 		kmem_free(svar, sizeof (dtrace_statvar_t));
9032 		svarp[id] = NULL;
9033 	}
9034 
9035 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9036 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9037 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9038 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9039 
9040 	kmem_free(dp, sizeof (dtrace_difo_t));
9041 }
9042 
9043 static void
9044 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9045 {
9046 	int i;
9047 
9048 	ASSERT(MUTEX_HELD(&dtrace_lock));
9049 	ASSERT(dp->dtdo_refcnt != 0);
9050 
9051 	for (i = 0; i < dp->dtdo_varlen; i++) {
9052 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9053 
9054 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9055 			continue;
9056 
9057 		ASSERT(dtrace_vtime_references > 0);
9058 		if (--dtrace_vtime_references == 0)
9059 			dtrace_vtime_disable();
9060 	}
9061 
9062 	if (--dp->dtdo_refcnt == 0)
9063 		dtrace_difo_destroy(dp, vstate);
9064 }
9065 
9066 /*
9067  * DTrace Format Functions
9068  */
9069 static uint16_t
9070 dtrace_format_add(dtrace_state_t *state, char *str)
9071 {
9072 	char *fmt, **new;
9073 	uint16_t ndx, len = strlen(str) + 1;
9074 
9075 	fmt = kmem_zalloc(len, KM_SLEEP);
9076 	bcopy(str, fmt, len);
9077 
9078 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9079 		if (state->dts_formats[ndx] == NULL) {
9080 			state->dts_formats[ndx] = fmt;
9081 			return (ndx + 1);
9082 		}
9083 	}
9084 
9085 	if (state->dts_nformats == USHRT_MAX) {
9086 		/*
9087 		 * This is only likely if a denial-of-service attack is being
9088 		 * attempted.  As such, it's okay to fail silently here.
9089 		 */
9090 		kmem_free(fmt, len);
9091 		return (0);
9092 	}
9093 
9094 	/*
9095 	 * For simplicity, we always resize the formats array to be exactly the
9096 	 * number of formats.
9097 	 */
9098 	ndx = state->dts_nformats++;
9099 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9100 
9101 	if (state->dts_formats != NULL) {
9102 		ASSERT(ndx != 0);
9103 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
9104 		kmem_free(state->dts_formats, ndx * sizeof (char *));
9105 	}
9106 
9107 	state->dts_formats = new;
9108 	state->dts_formats[ndx] = fmt;
9109 
9110 	return (ndx + 1);
9111 }
9112 
9113 static void
9114 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9115 {
9116 	char *fmt;
9117 
9118 	ASSERT(state->dts_formats != NULL);
9119 	ASSERT(format <= state->dts_nformats);
9120 	ASSERT(state->dts_formats[format - 1] != NULL);
9121 
9122 	fmt = state->dts_formats[format - 1];
9123 	kmem_free(fmt, strlen(fmt) + 1);
9124 	state->dts_formats[format - 1] = NULL;
9125 }
9126 
9127 static void
9128 dtrace_format_destroy(dtrace_state_t *state)
9129 {
9130 	int i;
9131 
9132 	if (state->dts_nformats == 0) {
9133 		ASSERT(state->dts_formats == NULL);
9134 		return;
9135 	}
9136 
9137 	ASSERT(state->dts_formats != NULL);
9138 
9139 	for (i = 0; i < state->dts_nformats; i++) {
9140 		char *fmt = state->dts_formats[i];
9141 
9142 		if (fmt == NULL)
9143 			continue;
9144 
9145 		kmem_free(fmt, strlen(fmt) + 1);
9146 	}
9147 
9148 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9149 	state->dts_nformats = 0;
9150 	state->dts_formats = NULL;
9151 }
9152 
9153 /*
9154  * DTrace Predicate Functions
9155  */
9156 static dtrace_predicate_t *
9157 dtrace_predicate_create(dtrace_difo_t *dp)
9158 {
9159 	dtrace_predicate_t *pred;
9160 
9161 	ASSERT(MUTEX_HELD(&dtrace_lock));
9162 	ASSERT(dp->dtdo_refcnt != 0);
9163 
9164 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9165 	pred->dtp_difo = dp;
9166 	pred->dtp_refcnt = 1;
9167 
9168 	if (!dtrace_difo_cacheable(dp))
9169 		return (pred);
9170 
9171 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9172 		/*
9173 		 * This is only theoretically possible -- we have had 2^32
9174 		 * cacheable predicates on this machine.  We cannot allow any
9175 		 * more predicates to become cacheable:  as unlikely as it is,
9176 		 * there may be a thread caching a (now stale) predicate cache
9177 		 * ID. (N.B.: the temptation is being successfully resisted to
9178 		 * have this cmn_err() "Holy shit -- we executed this code!")
9179 		 */
9180 		return (pred);
9181 	}
9182 
9183 	pred->dtp_cacheid = dtrace_predcache_id++;
9184 
9185 	return (pred);
9186 }
9187 
9188 static void
9189 dtrace_predicate_hold(dtrace_predicate_t *pred)
9190 {
9191 	ASSERT(MUTEX_HELD(&dtrace_lock));
9192 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9193 	ASSERT(pred->dtp_refcnt > 0);
9194 
9195 	pred->dtp_refcnt++;
9196 }
9197 
9198 static void
9199 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9200 {
9201 	dtrace_difo_t *dp = pred->dtp_difo;
9202 
9203 	ASSERT(MUTEX_HELD(&dtrace_lock));
9204 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9205 	ASSERT(pred->dtp_refcnt > 0);
9206 
9207 	if (--pred->dtp_refcnt == 0) {
9208 		dtrace_difo_release(pred->dtp_difo, vstate);
9209 		kmem_free(pred, sizeof (dtrace_predicate_t));
9210 	}
9211 }
9212 
9213 /*
9214  * DTrace Action Description Functions
9215  */
9216 static dtrace_actdesc_t *
9217 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9218     uint64_t uarg, uint64_t arg)
9219 {
9220 	dtrace_actdesc_t *act;
9221 
9222 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
9223 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
9224 
9225 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9226 	act->dtad_kind = kind;
9227 	act->dtad_ntuple = ntuple;
9228 	act->dtad_uarg = uarg;
9229 	act->dtad_arg = arg;
9230 	act->dtad_refcnt = 1;
9231 
9232 	return (act);
9233 }
9234 
9235 static void
9236 dtrace_actdesc_hold(dtrace_actdesc_t *act)
9237 {
9238 	ASSERT(act->dtad_refcnt >= 1);
9239 	act->dtad_refcnt++;
9240 }
9241 
9242 static void
9243 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9244 {
9245 	dtrace_actkind_t kind = act->dtad_kind;
9246 	dtrace_difo_t *dp;
9247 
9248 	ASSERT(act->dtad_refcnt >= 1);
9249 
9250 	if (--act->dtad_refcnt != 0)
9251 		return;
9252 
9253 	if ((dp = act->dtad_difo) != NULL)
9254 		dtrace_difo_release(dp, vstate);
9255 
9256 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
9257 		char *str = (char *)(uintptr_t)act->dtad_arg;
9258 
9259 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
9260 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9261 
9262 		if (str != NULL)
9263 			kmem_free(str, strlen(str) + 1);
9264 	}
9265 
9266 	kmem_free(act, sizeof (dtrace_actdesc_t));
9267 }
9268 
9269 /*
9270  * DTrace ECB Functions
9271  */
9272 static dtrace_ecb_t *
9273 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9274 {
9275 	dtrace_ecb_t *ecb;
9276 	dtrace_epid_t epid;
9277 
9278 	ASSERT(MUTEX_HELD(&dtrace_lock));
9279 
9280 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9281 	ecb->dte_predicate = NULL;
9282 	ecb->dte_probe = probe;
9283 
9284 	/*
9285 	 * The default size is the size of the default action: recording
9286 	 * the epid.
9287 	 */
9288 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
9289 	ecb->dte_alignment = sizeof (dtrace_epid_t);
9290 
9291 	epid = state->dts_epid++;
9292 
9293 	if (epid - 1 >= state->dts_necbs) {
9294 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9295 		int necbs = state->dts_necbs << 1;
9296 
9297 		ASSERT(epid == state->dts_necbs + 1);
9298 
9299 		if (necbs == 0) {
9300 			ASSERT(oecbs == NULL);
9301 			necbs = 1;
9302 		}
9303 
9304 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9305 
9306 		if (oecbs != NULL)
9307 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9308 
9309 		dtrace_membar_producer();
9310 		state->dts_ecbs = ecbs;
9311 
9312 		if (oecbs != NULL) {
9313 			/*
9314 			 * If this state is active, we must dtrace_sync()
9315 			 * before we can free the old dts_ecbs array:  we're
9316 			 * coming in hot, and there may be active ring
9317 			 * buffer processing (which indexes into the dts_ecbs
9318 			 * array) on another CPU.
9319 			 */
9320 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9321 				dtrace_sync();
9322 
9323 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9324 		}
9325 
9326 		dtrace_membar_producer();
9327 		state->dts_necbs = necbs;
9328 	}
9329 
9330 	ecb->dte_state = state;
9331 
9332 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
9333 	dtrace_membar_producer();
9334 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
9335 
9336 	return (ecb);
9337 }
9338 
9339 static int
9340 dtrace_ecb_enable(dtrace_ecb_t *ecb)
9341 {
9342 	dtrace_probe_t *probe = ecb->dte_probe;
9343 
9344 	ASSERT(MUTEX_HELD(&cpu_lock));
9345 	ASSERT(MUTEX_HELD(&dtrace_lock));
9346 	ASSERT(ecb->dte_next == NULL);
9347 
9348 	if (probe == NULL) {
9349 		/*
9350 		 * This is the NULL probe -- there's nothing to do.
9351 		 */
9352 		return (0);
9353 	}
9354 
9355 	if (probe->dtpr_ecb == NULL) {
9356 		dtrace_provider_t *prov = probe->dtpr_provider;
9357 
9358 		/*
9359 		 * We're the first ECB on this probe.
9360 		 */
9361 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9362 
9363 		if (ecb->dte_predicate != NULL)
9364 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9365 
9366 		return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9367 		    probe->dtpr_id, probe->dtpr_arg));
9368 	} else {
9369 		/*
9370 		 * This probe is already active.  Swing the last pointer to
9371 		 * point to the new ECB, and issue a dtrace_sync() to assure
9372 		 * that all CPUs have seen the change.
9373 		 */
9374 		ASSERT(probe->dtpr_ecb_last != NULL);
9375 		probe->dtpr_ecb_last->dte_next = ecb;
9376 		probe->dtpr_ecb_last = ecb;
9377 		probe->dtpr_predcache = 0;
9378 
9379 		dtrace_sync();
9380 		return (0);
9381 	}
9382 }
9383 
9384 static void
9385 dtrace_ecb_resize(dtrace_ecb_t *ecb)
9386 {
9387 	uint32_t maxalign = sizeof (dtrace_epid_t);
9388 	uint32_t align = sizeof (uint8_t), offs, diff;
9389 	dtrace_action_t *act;
9390 	int wastuple = 0;
9391 	uint32_t aggbase = UINT32_MAX;
9392 	dtrace_state_t *state = ecb->dte_state;
9393 
9394 	/*
9395 	 * If we record anything, we always record the epid.  (And we always
9396 	 * record it first.)
9397 	 */
9398 	offs = sizeof (dtrace_epid_t);
9399 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
9400 
9401 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9402 		dtrace_recdesc_t *rec = &act->dta_rec;
9403 
9404 		if ((align = rec->dtrd_alignment) > maxalign)
9405 			maxalign = align;
9406 
9407 		if (!wastuple && act->dta_intuple) {
9408 			/*
9409 			 * This is the first record in a tuple.  Align the
9410 			 * offset to be at offset 4 in an 8-byte aligned
9411 			 * block.
9412 			 */
9413 			diff = offs + sizeof (dtrace_aggid_t);
9414 
9415 			if (diff = (diff & (sizeof (uint64_t) - 1)))
9416 				offs += sizeof (uint64_t) - diff;
9417 
9418 			aggbase = offs - sizeof (dtrace_aggid_t);
9419 			ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
9420 		}
9421 
9422 		/*LINTED*/
9423 		if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
9424 			/*
9425 			 * The current offset is not properly aligned; align it.
9426 			 */
9427 			offs += align - diff;
9428 		}
9429 
9430 		rec->dtrd_offset = offs;
9431 
9432 		if (offs + rec->dtrd_size > ecb->dte_needed) {
9433 			ecb->dte_needed = offs + rec->dtrd_size;
9434 
9435 			if (ecb->dte_needed > state->dts_needed)
9436 				state->dts_needed = ecb->dte_needed;
9437 		}
9438 
9439 		if (DTRACEACT_ISAGG(act->dta_kind)) {
9440 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9441 			dtrace_action_t *first = agg->dtag_first, *prev;
9442 
9443 			ASSERT(rec->dtrd_size != 0 && first != NULL);
9444 			ASSERT(wastuple);
9445 			ASSERT(aggbase != UINT32_MAX);
9446 
9447 			agg->dtag_base = aggbase;
9448 
9449 			while ((prev = first->dta_prev) != NULL &&
9450 			    DTRACEACT_ISAGG(prev->dta_kind)) {
9451 				agg = (dtrace_aggregation_t *)prev;
9452 				first = agg->dtag_first;
9453 			}
9454 
9455 			if (prev != NULL) {
9456 				offs = prev->dta_rec.dtrd_offset +
9457 				    prev->dta_rec.dtrd_size;
9458 			} else {
9459 				offs = sizeof (dtrace_epid_t);
9460 			}
9461 			wastuple = 0;
9462 		} else {
9463 			if (!act->dta_intuple)
9464 				ecb->dte_size = offs + rec->dtrd_size;
9465 
9466 			offs += rec->dtrd_size;
9467 		}
9468 
9469 		wastuple = act->dta_intuple;
9470 	}
9471 
9472 	if ((act = ecb->dte_action) != NULL &&
9473 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9474 	    ecb->dte_size == sizeof (dtrace_epid_t)) {
9475 		/*
9476 		 * If the size is still sizeof (dtrace_epid_t), then all
9477 		 * actions store no data; set the size to 0.
9478 		 */
9479 		ecb->dte_alignment = maxalign;
9480 		ecb->dte_size = 0;
9481 
9482 		/*
9483 		 * If the needed space is still sizeof (dtrace_epid_t), then
9484 		 * all actions need no additional space; set the needed
9485 		 * size to 0.
9486 		 */
9487 		if (ecb->dte_needed == sizeof (dtrace_epid_t))
9488 			ecb->dte_needed = 0;
9489 
9490 		return;
9491 	}
9492 
9493 	/*
9494 	 * Set our alignment, and make sure that the dte_size and dte_needed
9495 	 * are aligned to the size of an EPID.
9496 	 */
9497 	ecb->dte_alignment = maxalign;
9498 	ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
9499 	    ~(sizeof (dtrace_epid_t) - 1);
9500 	ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
9501 	    ~(sizeof (dtrace_epid_t) - 1);
9502 	ASSERT(ecb->dte_size <= ecb->dte_needed);
9503 }
9504 
9505 static dtrace_action_t *
9506 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9507 {
9508 	dtrace_aggregation_t *agg;
9509 	size_t size = sizeof (uint64_t);
9510 	int ntuple = desc->dtad_ntuple;
9511 	dtrace_action_t *act;
9512 	dtrace_recdesc_t *frec;
9513 	dtrace_aggid_t aggid;
9514 	dtrace_state_t *state = ecb->dte_state;
9515 
9516 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
9517 	agg->dtag_ecb = ecb;
9518 
9519 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
9520 
9521 	switch (desc->dtad_kind) {
9522 	case DTRACEAGG_MIN:
9523 		agg->dtag_initial = INT64_MAX;
9524 		agg->dtag_aggregate = dtrace_aggregate_min;
9525 		break;
9526 
9527 	case DTRACEAGG_MAX:
9528 		agg->dtag_initial = INT64_MIN;
9529 		agg->dtag_aggregate = dtrace_aggregate_max;
9530 		break;
9531 
9532 	case DTRACEAGG_COUNT:
9533 		agg->dtag_aggregate = dtrace_aggregate_count;
9534 		break;
9535 
9536 	case DTRACEAGG_QUANTIZE:
9537 		agg->dtag_aggregate = dtrace_aggregate_quantize;
9538 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
9539 		    sizeof (uint64_t);
9540 		break;
9541 
9542 	case DTRACEAGG_LQUANTIZE: {
9543 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
9544 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
9545 
9546 		agg->dtag_initial = desc->dtad_arg;
9547 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
9548 
9549 		if (step == 0 || levels == 0)
9550 			goto err;
9551 
9552 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
9553 		break;
9554 	}
9555 
9556 	case DTRACEAGG_LLQUANTIZE: {
9557 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
9558 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
9559 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
9560 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
9561 		int64_t v;
9562 
9563 		agg->dtag_initial = desc->dtad_arg;
9564 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
9565 
9566 		if (factor < 2 || low >= high || nsteps < factor)
9567 			goto err;
9568 
9569 		/*
9570 		 * Now check that the number of steps evenly divides a power
9571 		 * of the factor.  (This assures both integer bucket size and
9572 		 * linearity within each magnitude.)
9573 		 */
9574 		for (v = factor; v < nsteps; v *= factor)
9575 			continue;
9576 
9577 		if ((v % nsteps) || (nsteps % factor))
9578 			goto err;
9579 
9580 		size = (dtrace_aggregate_llquantize_bucket(factor,
9581 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
9582 		break;
9583 	}
9584 
9585 	case DTRACEAGG_AVG:
9586 		agg->dtag_aggregate = dtrace_aggregate_avg;
9587 		size = sizeof (uint64_t) * 2;
9588 		break;
9589 
9590 	case DTRACEAGG_STDDEV:
9591 		agg->dtag_aggregate = dtrace_aggregate_stddev;
9592 		size = sizeof (uint64_t) * 4;
9593 		break;
9594 
9595 	case DTRACEAGG_SUM:
9596 		agg->dtag_aggregate = dtrace_aggregate_sum;
9597 		break;
9598 
9599 	default:
9600 		goto err;
9601 	}
9602 
9603 	agg->dtag_action.dta_rec.dtrd_size = size;
9604 
9605 	if (ntuple == 0)
9606 		goto err;
9607 
9608 	/*
9609 	 * We must make sure that we have enough actions for the n-tuple.
9610 	 */
9611 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
9612 		if (DTRACEACT_ISAGG(act->dta_kind))
9613 			break;
9614 
9615 		if (--ntuple == 0) {
9616 			/*
9617 			 * This is the action with which our n-tuple begins.
9618 			 */
9619 			agg->dtag_first = act;
9620 			goto success;
9621 		}
9622 	}
9623 
9624 	/*
9625 	 * This n-tuple is short by ntuple elements.  Return failure.
9626 	 */
9627 	ASSERT(ntuple != 0);
9628 err:
9629 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9630 	return (NULL);
9631 
9632 success:
9633 	/*
9634 	 * If the last action in the tuple has a size of zero, it's actually
9635 	 * an expression argument for the aggregating action.
9636 	 */
9637 	ASSERT(ecb->dte_action_last != NULL);
9638 	act = ecb->dte_action_last;
9639 
9640 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
9641 		ASSERT(act->dta_difo != NULL);
9642 
9643 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
9644 			agg->dtag_hasarg = 1;
9645 	}
9646 
9647 	/*
9648 	 * We need to allocate an id for this aggregation.
9649 	 */
9650 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
9651 	    VM_BESTFIT | VM_SLEEP);
9652 
9653 	if (aggid - 1 >= state->dts_naggregations) {
9654 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
9655 		dtrace_aggregation_t **aggs;
9656 		int naggs = state->dts_naggregations << 1;
9657 		int onaggs = state->dts_naggregations;
9658 
9659 		ASSERT(aggid == state->dts_naggregations + 1);
9660 
9661 		if (naggs == 0) {
9662 			ASSERT(oaggs == NULL);
9663 			naggs = 1;
9664 		}
9665 
9666 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
9667 
9668 		if (oaggs != NULL) {
9669 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
9670 			kmem_free(oaggs, onaggs * sizeof (*aggs));
9671 		}
9672 
9673 		state->dts_aggregations = aggs;
9674 		state->dts_naggregations = naggs;
9675 	}
9676 
9677 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
9678 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
9679 
9680 	frec = &agg->dtag_first->dta_rec;
9681 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
9682 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
9683 
9684 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
9685 		ASSERT(!act->dta_intuple);
9686 		act->dta_intuple = 1;
9687 	}
9688 
9689 	return (&agg->dtag_action);
9690 }
9691 
9692 static void
9693 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
9694 {
9695 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9696 	dtrace_state_t *state = ecb->dte_state;
9697 	dtrace_aggid_t aggid = agg->dtag_id;
9698 
9699 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
9700 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
9701 
9702 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
9703 	state->dts_aggregations[aggid - 1] = NULL;
9704 
9705 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9706 }
9707 
9708 static int
9709 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9710 {
9711 	dtrace_action_t *action, *last;
9712 	dtrace_difo_t *dp = desc->dtad_difo;
9713 	uint32_t size = 0, align = sizeof (uint8_t), mask;
9714 	uint16_t format = 0;
9715 	dtrace_recdesc_t *rec;
9716 	dtrace_state_t *state = ecb->dte_state;
9717 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
9718 	uint64_t arg = desc->dtad_arg;
9719 
9720 	ASSERT(MUTEX_HELD(&dtrace_lock));
9721 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
9722 
9723 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
9724 		/*
9725 		 * If this is an aggregating action, there must be neither
9726 		 * a speculate nor a commit on the action chain.
9727 		 */
9728 		dtrace_action_t *act;
9729 
9730 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9731 			if (act->dta_kind == DTRACEACT_COMMIT)
9732 				return (EINVAL);
9733 
9734 			if (act->dta_kind == DTRACEACT_SPECULATE)
9735 				return (EINVAL);
9736 		}
9737 
9738 		action = dtrace_ecb_aggregation_create(ecb, desc);
9739 
9740 		if (action == NULL)
9741 			return (EINVAL);
9742 	} else {
9743 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
9744 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
9745 		    dp != NULL && dp->dtdo_destructive)) {
9746 			state->dts_destructive = 1;
9747 		}
9748 
9749 		switch (desc->dtad_kind) {
9750 		case DTRACEACT_PRINTF:
9751 		case DTRACEACT_PRINTA:
9752 		case DTRACEACT_SYSTEM:
9753 		case DTRACEACT_FREOPEN:
9754 			/*
9755 			 * We know that our arg is a string -- turn it into a
9756 			 * format.
9757 			 */
9758 			if (arg == NULL) {
9759 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
9760 				format = 0;
9761 			} else {
9762 				ASSERT(arg != NULL);
9763 				ASSERT(arg > KERNELBASE);
9764 				format = dtrace_format_add(state,
9765 				    (char *)(uintptr_t)arg);
9766 			}
9767 
9768 			/*FALLTHROUGH*/
9769 		case DTRACEACT_LIBACT:
9770 		case DTRACEACT_DIFEXPR:
9771 		case DTRACEACT_TRACEMEM:
9772 		case DTRACEACT_TRACEMEM_DYNSIZE:
9773 			if (dp == NULL)
9774 				return (EINVAL);
9775 
9776 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
9777 				break;
9778 
9779 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
9780 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9781 					return (EINVAL);
9782 
9783 				size = opt[DTRACEOPT_STRSIZE];
9784 			}
9785 
9786 			break;
9787 
9788 		case DTRACEACT_STACK:
9789 			if ((nframes = arg) == 0) {
9790 				nframes = opt[DTRACEOPT_STACKFRAMES];
9791 				ASSERT(nframes > 0);
9792 				arg = nframes;
9793 			}
9794 
9795 			size = nframes * sizeof (pc_t);
9796 			break;
9797 
9798 		case DTRACEACT_JSTACK:
9799 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
9800 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
9801 
9802 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
9803 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
9804 
9805 			arg = DTRACE_USTACK_ARG(nframes, strsize);
9806 
9807 			/*FALLTHROUGH*/
9808 		case DTRACEACT_USTACK:
9809 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
9810 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
9811 				strsize = DTRACE_USTACK_STRSIZE(arg);
9812 				nframes = opt[DTRACEOPT_USTACKFRAMES];
9813 				ASSERT(nframes > 0);
9814 				arg = DTRACE_USTACK_ARG(nframes, strsize);
9815 			}
9816 
9817 			/*
9818 			 * Save a slot for the pid.
9819 			 */
9820 			size = (nframes + 1) * sizeof (uint64_t);
9821 			size += DTRACE_USTACK_STRSIZE(arg);
9822 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
9823 
9824 			break;
9825 
9826 		case DTRACEACT_SYM:
9827 		case DTRACEACT_MOD:
9828 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
9829 			    sizeof (uint64_t)) ||
9830 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9831 				return (EINVAL);
9832 			break;
9833 
9834 		case DTRACEACT_USYM:
9835 		case DTRACEACT_UMOD:
9836 		case DTRACEACT_UADDR:
9837 			if (dp == NULL ||
9838 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
9839 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9840 				return (EINVAL);
9841 
9842 			/*
9843 			 * We have a slot for the pid, plus a slot for the
9844 			 * argument.  To keep things simple (aligned with
9845 			 * bitness-neutral sizing), we store each as a 64-bit
9846 			 * quantity.
9847 			 */
9848 			size = 2 * sizeof (uint64_t);
9849 			break;
9850 
9851 		case DTRACEACT_STOP:
9852 		case DTRACEACT_BREAKPOINT:
9853 		case DTRACEACT_PANIC:
9854 			break;
9855 
9856 		case DTRACEACT_CHILL:
9857 		case DTRACEACT_DISCARD:
9858 		case DTRACEACT_RAISE:
9859 			if (dp == NULL)
9860 				return (EINVAL);
9861 			break;
9862 
9863 		case DTRACEACT_EXIT:
9864 			if (dp == NULL ||
9865 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
9866 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9867 				return (EINVAL);
9868 			break;
9869 
9870 		case DTRACEACT_SPECULATE:
9871 			if (ecb->dte_size > sizeof (dtrace_epid_t))
9872 				return (EINVAL);
9873 
9874 			if (dp == NULL)
9875 				return (EINVAL);
9876 
9877 			state->dts_speculates = 1;
9878 			break;
9879 
9880 		case DTRACEACT_COMMIT: {
9881 			dtrace_action_t *act = ecb->dte_action;
9882 
9883 			for (; act != NULL; act = act->dta_next) {
9884 				if (act->dta_kind == DTRACEACT_COMMIT)
9885 					return (EINVAL);
9886 			}
9887 
9888 			if (dp == NULL)
9889 				return (EINVAL);
9890 			break;
9891 		}
9892 
9893 		default:
9894 			return (EINVAL);
9895 		}
9896 
9897 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
9898 			/*
9899 			 * If this is a data-storing action or a speculate,
9900 			 * we must be sure that there isn't a commit on the
9901 			 * action chain.
9902 			 */
9903 			dtrace_action_t *act = ecb->dte_action;
9904 
9905 			for (; act != NULL; act = act->dta_next) {
9906 				if (act->dta_kind == DTRACEACT_COMMIT)
9907 					return (EINVAL);
9908 			}
9909 		}
9910 
9911 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
9912 		action->dta_rec.dtrd_size = size;
9913 	}
9914 
9915 	action->dta_refcnt = 1;
9916 	rec = &action->dta_rec;
9917 	size = rec->dtrd_size;
9918 
9919 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
9920 		if (!(size & mask)) {
9921 			align = mask + 1;
9922 			break;
9923 		}
9924 	}
9925 
9926 	action->dta_kind = desc->dtad_kind;
9927 
9928 	if ((action->dta_difo = dp) != NULL)
9929 		dtrace_difo_hold(dp);
9930 
9931 	rec->dtrd_action = action->dta_kind;
9932 	rec->dtrd_arg = arg;
9933 	rec->dtrd_uarg = desc->dtad_uarg;
9934 	rec->dtrd_alignment = (uint16_t)align;
9935 	rec->dtrd_format = format;
9936 
9937 	if ((last = ecb->dte_action_last) != NULL) {
9938 		ASSERT(ecb->dte_action != NULL);
9939 		action->dta_prev = last;
9940 		last->dta_next = action;
9941 	} else {
9942 		ASSERT(ecb->dte_action == NULL);
9943 		ecb->dte_action = action;
9944 	}
9945 
9946 	ecb->dte_action_last = action;
9947 
9948 	return (0);
9949 }
9950 
9951 static void
9952 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
9953 {
9954 	dtrace_action_t *act = ecb->dte_action, *next;
9955 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
9956 	dtrace_difo_t *dp;
9957 	uint16_t format;
9958 
9959 	if (act != NULL && act->dta_refcnt > 1) {
9960 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
9961 		act->dta_refcnt--;
9962 	} else {
9963 		for (; act != NULL; act = next) {
9964 			next = act->dta_next;
9965 			ASSERT(next != NULL || act == ecb->dte_action_last);
9966 			ASSERT(act->dta_refcnt == 1);
9967 
9968 			if ((format = act->dta_rec.dtrd_format) != 0)
9969 				dtrace_format_remove(ecb->dte_state, format);
9970 
9971 			if ((dp = act->dta_difo) != NULL)
9972 				dtrace_difo_release(dp, vstate);
9973 
9974 			if (DTRACEACT_ISAGG(act->dta_kind)) {
9975 				dtrace_ecb_aggregation_destroy(ecb, act);
9976 			} else {
9977 				kmem_free(act, sizeof (dtrace_action_t));
9978 			}
9979 		}
9980 	}
9981 
9982 	ecb->dte_action = NULL;
9983 	ecb->dte_action_last = NULL;
9984 	ecb->dte_size = sizeof (dtrace_epid_t);
9985 }
9986 
9987 static void
9988 dtrace_ecb_disable(dtrace_ecb_t *ecb)
9989 {
9990 	/*
9991 	 * We disable the ECB by removing it from its probe.
9992 	 */
9993 	dtrace_ecb_t *pecb, *prev = NULL;
9994 	dtrace_probe_t *probe = ecb->dte_probe;
9995 
9996 	ASSERT(MUTEX_HELD(&dtrace_lock));
9997 
9998 	if (probe == NULL) {
9999 		/*
10000 		 * This is the NULL probe; there is nothing to disable.
10001 		 */
10002 		return;
10003 	}
10004 
10005 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10006 		if (pecb == ecb)
10007 			break;
10008 		prev = pecb;
10009 	}
10010 
10011 	ASSERT(pecb != NULL);
10012 
10013 	if (prev == NULL) {
10014 		probe->dtpr_ecb = ecb->dte_next;
10015 	} else {
10016 		prev->dte_next = ecb->dte_next;
10017 	}
10018 
10019 	if (ecb == probe->dtpr_ecb_last) {
10020 		ASSERT(ecb->dte_next == NULL);
10021 		probe->dtpr_ecb_last = prev;
10022 	}
10023 
10024 	/*
10025 	 * The ECB has been disconnected from the probe; now sync to assure
10026 	 * that all CPUs have seen the change before returning.
10027 	 */
10028 	dtrace_sync();
10029 
10030 	if (probe->dtpr_ecb == NULL) {
10031 		/*
10032 		 * That was the last ECB on the probe; clear the predicate
10033 		 * cache ID for the probe, disable it and sync one more time
10034 		 * to assure that we'll never hit it again.
10035 		 */
10036 		dtrace_provider_t *prov = probe->dtpr_provider;
10037 
10038 		ASSERT(ecb->dte_next == NULL);
10039 		ASSERT(probe->dtpr_ecb_last == NULL);
10040 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10041 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10042 		    probe->dtpr_id, probe->dtpr_arg);
10043 		dtrace_sync();
10044 	} else {
10045 		/*
10046 		 * There is at least one ECB remaining on the probe.  If there
10047 		 * is _exactly_ one, set the probe's predicate cache ID to be
10048 		 * the predicate cache ID of the remaining ECB.
10049 		 */
10050 		ASSERT(probe->dtpr_ecb_last != NULL);
10051 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10052 
10053 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10054 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10055 
10056 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
10057 
10058 			if (p != NULL)
10059 				probe->dtpr_predcache = p->dtp_cacheid;
10060 		}
10061 
10062 		ecb->dte_next = NULL;
10063 	}
10064 }
10065 
10066 static void
10067 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10068 {
10069 	dtrace_state_t *state = ecb->dte_state;
10070 	dtrace_vstate_t *vstate = &state->dts_vstate;
10071 	dtrace_predicate_t *pred;
10072 	dtrace_epid_t epid = ecb->dte_epid;
10073 
10074 	ASSERT(MUTEX_HELD(&dtrace_lock));
10075 	ASSERT(ecb->dte_next == NULL);
10076 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10077 
10078 	if ((pred = ecb->dte_predicate) != NULL)
10079 		dtrace_predicate_release(pred, vstate);
10080 
10081 	dtrace_ecb_action_remove(ecb);
10082 
10083 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
10084 	state->dts_ecbs[epid - 1] = NULL;
10085 
10086 	kmem_free(ecb, sizeof (dtrace_ecb_t));
10087 }
10088 
10089 static dtrace_ecb_t *
10090 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10091     dtrace_enabling_t *enab)
10092 {
10093 	dtrace_ecb_t *ecb;
10094 	dtrace_predicate_t *pred;
10095 	dtrace_actdesc_t *act;
10096 	dtrace_provider_t *prov;
10097 	dtrace_ecbdesc_t *desc = enab->dten_current;
10098 
10099 	ASSERT(MUTEX_HELD(&dtrace_lock));
10100 	ASSERT(state != NULL);
10101 
10102 	ecb = dtrace_ecb_add(state, probe);
10103 	ecb->dte_uarg = desc->dted_uarg;
10104 
10105 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10106 		dtrace_predicate_hold(pred);
10107 		ecb->dte_predicate = pred;
10108 	}
10109 
10110 	if (probe != NULL) {
10111 		/*
10112 		 * If the provider shows more leg than the consumer is old
10113 		 * enough to see, we need to enable the appropriate implicit
10114 		 * predicate bits to prevent the ecb from activating at
10115 		 * revealing times.
10116 		 *
10117 		 * Providers specifying DTRACE_PRIV_USER at register time
10118 		 * are stating that they need the /proc-style privilege
10119 		 * model to be enforced, and this is what DTRACE_COND_OWNER
10120 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10121 		 */
10122 		prov = probe->dtpr_provider;
10123 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10124 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10125 			ecb->dte_cond |= DTRACE_COND_OWNER;
10126 
10127 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10128 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10129 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10130 
10131 		/*
10132 		 * If the provider shows us kernel innards and the user
10133 		 * is lacking sufficient privilege, enable the
10134 		 * DTRACE_COND_USERMODE implicit predicate.
10135 		 */
10136 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10137 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10138 			ecb->dte_cond |= DTRACE_COND_USERMODE;
10139 	}
10140 
10141 	if (dtrace_ecb_create_cache != NULL) {
10142 		/*
10143 		 * If we have a cached ecb, we'll use its action list instead
10144 		 * of creating our own (saving both time and space).
10145 		 */
10146 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10147 		dtrace_action_t *act = cached->dte_action;
10148 
10149 		if (act != NULL) {
10150 			ASSERT(act->dta_refcnt > 0);
10151 			act->dta_refcnt++;
10152 			ecb->dte_action = act;
10153 			ecb->dte_action_last = cached->dte_action_last;
10154 			ecb->dte_needed = cached->dte_needed;
10155 			ecb->dte_size = cached->dte_size;
10156 			ecb->dte_alignment = cached->dte_alignment;
10157 		}
10158 
10159 		return (ecb);
10160 	}
10161 
10162 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10163 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10164 			dtrace_ecb_destroy(ecb);
10165 			return (NULL);
10166 		}
10167 	}
10168 
10169 	dtrace_ecb_resize(ecb);
10170 
10171 	return (dtrace_ecb_create_cache = ecb);
10172 }
10173 
10174 static int
10175 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10176 {
10177 	dtrace_ecb_t *ecb;
10178 	dtrace_enabling_t *enab = arg;
10179 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10180 
10181 	ASSERT(state != NULL);
10182 
10183 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10184 		/*
10185 		 * This probe was created in a generation for which this
10186 		 * enabling has previously created ECBs; we don't want to
10187 		 * enable it again, so just kick out.
10188 		 */
10189 		return (DTRACE_MATCH_NEXT);
10190 	}
10191 
10192 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10193 		return (DTRACE_MATCH_DONE);
10194 
10195 	if (dtrace_ecb_enable(ecb) < 0)
10196 		return (DTRACE_MATCH_FAIL);
10197 
10198 	return (DTRACE_MATCH_NEXT);
10199 }
10200 
10201 static dtrace_ecb_t *
10202 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10203 {
10204 	dtrace_ecb_t *ecb;
10205 
10206 	ASSERT(MUTEX_HELD(&dtrace_lock));
10207 
10208 	if (id == 0 || id > state->dts_necbs)
10209 		return (NULL);
10210 
10211 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10212 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10213 
10214 	return (state->dts_ecbs[id - 1]);
10215 }
10216 
10217 static dtrace_aggregation_t *
10218 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10219 {
10220 	dtrace_aggregation_t *agg;
10221 
10222 	ASSERT(MUTEX_HELD(&dtrace_lock));
10223 
10224 	if (id == 0 || id > state->dts_naggregations)
10225 		return (NULL);
10226 
10227 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10228 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10229 	    agg->dtag_id == id);
10230 
10231 	return (state->dts_aggregations[id - 1]);
10232 }
10233 
10234 /*
10235  * DTrace Buffer Functions
10236  *
10237  * The following functions manipulate DTrace buffers.  Most of these functions
10238  * are called in the context of establishing or processing consumer state;
10239  * exceptions are explicitly noted.
10240  */
10241 
10242 /*
10243  * Note:  called from cross call context.  This function switches the two
10244  * buffers on a given CPU.  The atomicity of this operation is assured by
10245  * disabling interrupts while the actual switch takes place; the disabling of
10246  * interrupts serializes the execution with any execution of dtrace_probe() on
10247  * the same CPU.
10248  */
10249 static void
10250 dtrace_buffer_switch(dtrace_buffer_t *buf)
10251 {
10252 	caddr_t tomax = buf->dtb_tomax;
10253 	caddr_t xamot = buf->dtb_xamot;
10254 	dtrace_icookie_t cookie;
10255 	hrtime_t now = dtrace_gethrtime();
10256 
10257 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10258 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10259 
10260 	cookie = dtrace_interrupt_disable();
10261 	buf->dtb_tomax = xamot;
10262 	buf->dtb_xamot = tomax;
10263 	buf->dtb_xamot_drops = buf->dtb_drops;
10264 	buf->dtb_xamot_offset = buf->dtb_offset;
10265 	buf->dtb_xamot_errors = buf->dtb_errors;
10266 	buf->dtb_xamot_flags = buf->dtb_flags;
10267 	buf->dtb_offset = 0;
10268 	buf->dtb_drops = 0;
10269 	buf->dtb_errors = 0;
10270 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10271 	buf->dtb_interval = now - buf->dtb_switched;
10272 	buf->dtb_switched = now;
10273 	dtrace_interrupt_enable(cookie);
10274 }
10275 
10276 /*
10277  * Note:  called from cross call context.  This function activates a buffer
10278  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
10279  * is guaranteed by the disabling of interrupts.
10280  */
10281 static void
10282 dtrace_buffer_activate(dtrace_state_t *state)
10283 {
10284 	dtrace_buffer_t *buf;
10285 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
10286 
10287 	buf = &state->dts_buffer[CPU->cpu_id];
10288 
10289 	if (buf->dtb_tomax != NULL) {
10290 		/*
10291 		 * We might like to assert that the buffer is marked inactive,
10292 		 * but this isn't necessarily true:  the buffer for the CPU
10293 		 * that processes the BEGIN probe has its buffer activated
10294 		 * manually.  In this case, we take the (harmless) action
10295 		 * re-clearing the bit INACTIVE bit.
10296 		 */
10297 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10298 	}
10299 
10300 	dtrace_interrupt_enable(cookie);
10301 }
10302 
10303 static int
10304 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
10305     processorid_t cpu, int *factor)
10306 {
10307 	cpu_t *cp;
10308 	dtrace_buffer_t *buf;
10309 	int allocated = 0, desired = 0;
10310 
10311 	ASSERT(MUTEX_HELD(&cpu_lock));
10312 	ASSERT(MUTEX_HELD(&dtrace_lock));
10313 
10314 	*factor = 1;
10315 
10316 	if (size > dtrace_nonroot_maxsize &&
10317 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
10318 		return (EFBIG);
10319 
10320 	cp = cpu_list;
10321 
10322 	do {
10323 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10324 			continue;
10325 
10326 		buf = &bufs[cp->cpu_id];
10327 
10328 		/*
10329 		 * If there is already a buffer allocated for this CPU, it
10330 		 * is only possible that this is a DR event.  In this case,
10331 		 * the buffer size must match our specified size.
10332 		 */
10333 		if (buf->dtb_tomax != NULL) {
10334 			ASSERT(buf->dtb_size == size);
10335 			continue;
10336 		}
10337 
10338 		ASSERT(buf->dtb_xamot == NULL);
10339 
10340 		if ((buf->dtb_tomax = kmem_zalloc(size,
10341 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10342 			goto err;
10343 
10344 		buf->dtb_size = size;
10345 		buf->dtb_flags = flags;
10346 		buf->dtb_offset = 0;
10347 		buf->dtb_drops = 0;
10348 
10349 		if (flags & DTRACEBUF_NOSWITCH)
10350 			continue;
10351 
10352 		if ((buf->dtb_xamot = kmem_zalloc(size,
10353 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10354 			goto err;
10355 	} while ((cp = cp->cpu_next) != cpu_list);
10356 
10357 	return (0);
10358 
10359 err:
10360 	cp = cpu_list;
10361 
10362 	do {
10363 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10364 			continue;
10365 
10366 		buf = &bufs[cp->cpu_id];
10367 		desired += 2;
10368 
10369 		if (buf->dtb_xamot != NULL) {
10370 			ASSERT(buf->dtb_tomax != NULL);
10371 			ASSERT(buf->dtb_size == size);
10372 			kmem_free(buf->dtb_xamot, size);
10373 			allocated++;
10374 		}
10375 
10376 		if (buf->dtb_tomax != NULL) {
10377 			ASSERT(buf->dtb_size == size);
10378 			kmem_free(buf->dtb_tomax, size);
10379 			allocated++;
10380 		}
10381 
10382 		buf->dtb_tomax = NULL;
10383 		buf->dtb_xamot = NULL;
10384 		buf->dtb_size = 0;
10385 	} while ((cp = cp->cpu_next) != cpu_list);
10386 
10387 	*factor = desired / (allocated > 0 ? allocated : 1);
10388 
10389 	return (ENOMEM);
10390 }
10391 
10392 /*
10393  * Note:  called from probe context.  This function just increments the drop
10394  * count on a buffer.  It has been made a function to allow for the
10395  * possibility of understanding the source of mysterious drop counts.  (A
10396  * problem for which one may be particularly disappointed that DTrace cannot
10397  * be used to understand DTrace.)
10398  */
10399 static void
10400 dtrace_buffer_drop(dtrace_buffer_t *buf)
10401 {
10402 	buf->dtb_drops++;
10403 }
10404 
10405 /*
10406  * Note:  called from probe context.  This function is called to reserve space
10407  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
10408  * mstate.  Returns the new offset in the buffer, or a negative value if an
10409  * error has occurred.
10410  */
10411 static intptr_t
10412 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
10413     dtrace_state_t *state, dtrace_mstate_t *mstate)
10414 {
10415 	intptr_t offs = buf->dtb_offset, soffs;
10416 	intptr_t woffs;
10417 	caddr_t tomax;
10418 	size_t total;
10419 
10420 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
10421 		return (-1);
10422 
10423 	if ((tomax = buf->dtb_tomax) == NULL) {
10424 		dtrace_buffer_drop(buf);
10425 		return (-1);
10426 	}
10427 
10428 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
10429 		while (offs & (align - 1)) {
10430 			/*
10431 			 * Assert that our alignment is off by a number which
10432 			 * is itself sizeof (uint32_t) aligned.
10433 			 */
10434 			ASSERT(!((align - (offs & (align - 1))) &
10435 			    (sizeof (uint32_t) - 1)));
10436 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10437 			offs += sizeof (uint32_t);
10438 		}
10439 
10440 		if ((soffs = offs + needed) > buf->dtb_size) {
10441 			dtrace_buffer_drop(buf);
10442 			return (-1);
10443 		}
10444 
10445 		if (mstate == NULL)
10446 			return (offs);
10447 
10448 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
10449 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
10450 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10451 
10452 		return (offs);
10453 	}
10454 
10455 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10456 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
10457 		    (buf->dtb_flags & DTRACEBUF_FULL))
10458 			return (-1);
10459 		goto out;
10460 	}
10461 
10462 	total = needed + (offs & (align - 1));
10463 
10464 	/*
10465 	 * For a ring buffer, life is quite a bit more complicated.  Before
10466 	 * we can store any padding, we need to adjust our wrapping offset.
10467 	 * (If we've never before wrapped or we're not about to, no adjustment
10468 	 * is required.)
10469 	 */
10470 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
10471 	    offs + total > buf->dtb_size) {
10472 		woffs = buf->dtb_xamot_offset;
10473 
10474 		if (offs + total > buf->dtb_size) {
10475 			/*
10476 			 * We can't fit in the end of the buffer.  First, a
10477 			 * sanity check that we can fit in the buffer at all.
10478 			 */
10479 			if (total > buf->dtb_size) {
10480 				dtrace_buffer_drop(buf);
10481 				return (-1);
10482 			}
10483 
10484 			/*
10485 			 * We're going to be storing at the top of the buffer,
10486 			 * so now we need to deal with the wrapped offset.  We
10487 			 * only reset our wrapped offset to 0 if it is
10488 			 * currently greater than the current offset.  If it
10489 			 * is less than the current offset, it is because a
10490 			 * previous allocation induced a wrap -- but the
10491 			 * allocation didn't subsequently take the space due
10492 			 * to an error or false predicate evaluation.  In this
10493 			 * case, we'll just leave the wrapped offset alone: if
10494 			 * the wrapped offset hasn't been advanced far enough
10495 			 * for this allocation, it will be adjusted in the
10496 			 * lower loop.
10497 			 */
10498 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
10499 				if (woffs >= offs)
10500 					woffs = 0;
10501 			} else {
10502 				woffs = 0;
10503 			}
10504 
10505 			/*
10506 			 * Now we know that we're going to be storing to the
10507 			 * top of the buffer and that there is room for us
10508 			 * there.  We need to clear the buffer from the current
10509 			 * offset to the end (there may be old gunk there).
10510 			 */
10511 			while (offs < buf->dtb_size)
10512 				tomax[offs++] = 0;
10513 
10514 			/*
10515 			 * We need to set our offset to zero.  And because we
10516 			 * are wrapping, we need to set the bit indicating as
10517 			 * much.  We can also adjust our needed space back
10518 			 * down to the space required by the ECB -- we know
10519 			 * that the top of the buffer is aligned.
10520 			 */
10521 			offs = 0;
10522 			total = needed;
10523 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
10524 		} else {
10525 			/*
10526 			 * There is room for us in the buffer, so we simply
10527 			 * need to check the wrapped offset.
10528 			 */
10529 			if (woffs < offs) {
10530 				/*
10531 				 * The wrapped offset is less than the offset.
10532 				 * This can happen if we allocated buffer space
10533 				 * that induced a wrap, but then we didn't
10534 				 * subsequently take the space due to an error
10535 				 * or false predicate evaluation.  This is
10536 				 * okay; we know that _this_ allocation isn't
10537 				 * going to induce a wrap.  We still can't
10538 				 * reset the wrapped offset to be zero,
10539 				 * however: the space may have been trashed in
10540 				 * the previous failed probe attempt.  But at
10541 				 * least the wrapped offset doesn't need to
10542 				 * be adjusted at all...
10543 				 */
10544 				goto out;
10545 			}
10546 		}
10547 
10548 		while (offs + total > woffs) {
10549 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
10550 			size_t size;
10551 
10552 			if (epid == DTRACE_EPIDNONE) {
10553 				size = sizeof (uint32_t);
10554 			} else {
10555 				ASSERT(epid <= state->dts_necbs);
10556 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
10557 
10558 				size = state->dts_ecbs[epid - 1]->dte_size;
10559 			}
10560 
10561 			ASSERT(woffs + size <= buf->dtb_size);
10562 			ASSERT(size != 0);
10563 
10564 			if (woffs + size == buf->dtb_size) {
10565 				/*
10566 				 * We've reached the end of the buffer; we want
10567 				 * to set the wrapped offset to 0 and break
10568 				 * out.  However, if the offs is 0, then we're
10569 				 * in a strange edge-condition:  the amount of
10570 				 * space that we want to reserve plus the size
10571 				 * of the record that we're overwriting is
10572 				 * greater than the size of the buffer.  This
10573 				 * is problematic because if we reserve the
10574 				 * space but subsequently don't consume it (due
10575 				 * to a failed predicate or error) the wrapped
10576 				 * offset will be 0 -- yet the EPID at offset 0
10577 				 * will not be committed.  This situation is
10578 				 * relatively easy to deal with:  if we're in
10579 				 * this case, the buffer is indistinguishable
10580 				 * from one that hasn't wrapped; we need only
10581 				 * finish the job by clearing the wrapped bit,
10582 				 * explicitly setting the offset to be 0, and
10583 				 * zero'ing out the old data in the buffer.
10584 				 */
10585 				if (offs == 0) {
10586 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
10587 					buf->dtb_offset = 0;
10588 					woffs = total;
10589 
10590 					while (woffs < buf->dtb_size)
10591 						tomax[woffs++] = 0;
10592 				}
10593 
10594 				woffs = 0;
10595 				break;
10596 			}
10597 
10598 			woffs += size;
10599 		}
10600 
10601 		/*
10602 		 * We have a wrapped offset.  It may be that the wrapped offset
10603 		 * has become zero -- that's okay.
10604 		 */
10605 		buf->dtb_xamot_offset = woffs;
10606 	}
10607 
10608 out:
10609 	/*
10610 	 * Now we can plow the buffer with any necessary padding.
10611 	 */
10612 	while (offs & (align - 1)) {
10613 		/*
10614 		 * Assert that our alignment is off by a number which
10615 		 * is itself sizeof (uint32_t) aligned.
10616 		 */
10617 		ASSERT(!((align - (offs & (align - 1))) &
10618 		    (sizeof (uint32_t) - 1)));
10619 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10620 		offs += sizeof (uint32_t);
10621 	}
10622 
10623 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10624 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
10625 			buf->dtb_flags |= DTRACEBUF_FULL;
10626 			return (-1);
10627 		}
10628 	}
10629 
10630 	if (mstate == NULL)
10631 		return (offs);
10632 
10633 	/*
10634 	 * For ring buffers and fill buffers, the scratch space is always
10635 	 * the inactive buffer.
10636 	 */
10637 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
10638 	mstate->dtms_scratch_size = buf->dtb_size;
10639 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10640 
10641 	return (offs);
10642 }
10643 
10644 static void
10645 dtrace_buffer_polish(dtrace_buffer_t *buf)
10646 {
10647 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
10648 	ASSERT(MUTEX_HELD(&dtrace_lock));
10649 
10650 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
10651 		return;
10652 
10653 	/*
10654 	 * We need to polish the ring buffer.  There are three cases:
10655 	 *
10656 	 * - The first (and presumably most common) is that there is no gap
10657 	 *   between the buffer offset and the wrapped offset.  In this case,
10658 	 *   there is nothing in the buffer that isn't valid data; we can
10659 	 *   mark the buffer as polished and return.
10660 	 *
10661 	 * - The second (less common than the first but still more common
10662 	 *   than the third) is that there is a gap between the buffer offset
10663 	 *   and the wrapped offset, and the wrapped offset is larger than the
10664 	 *   buffer offset.  This can happen because of an alignment issue, or
10665 	 *   can happen because of a call to dtrace_buffer_reserve() that
10666 	 *   didn't subsequently consume the buffer space.  In this case,
10667 	 *   we need to zero the data from the buffer offset to the wrapped
10668 	 *   offset.
10669 	 *
10670 	 * - The third (and least common) is that there is a gap between the
10671 	 *   buffer offset and the wrapped offset, but the wrapped offset is
10672 	 *   _less_ than the buffer offset.  This can only happen because a
10673 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
10674 	 *   was not subsequently consumed.  In this case, we need to zero the
10675 	 *   space from the offset to the end of the buffer _and_ from the
10676 	 *   top of the buffer to the wrapped offset.
10677 	 */
10678 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
10679 		bzero(buf->dtb_tomax + buf->dtb_offset,
10680 		    buf->dtb_xamot_offset - buf->dtb_offset);
10681 	}
10682 
10683 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
10684 		bzero(buf->dtb_tomax + buf->dtb_offset,
10685 		    buf->dtb_size - buf->dtb_offset);
10686 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
10687 	}
10688 }
10689 
10690 /*
10691  * This routine determines if data generated at the specified time has likely
10692  * been entirely consumed at user-level.  This routine is called to determine
10693  * if an ECB on a defunct probe (but for an active enabling) can be safely
10694  * disabled and destroyed.
10695  */
10696 static int
10697 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
10698 {
10699 	int i;
10700 
10701 	for (i = 0; i < NCPU; i++) {
10702 		dtrace_buffer_t *buf = &bufs[i];
10703 
10704 		if (buf->dtb_size == 0)
10705 			continue;
10706 
10707 		if (buf->dtb_flags & DTRACEBUF_RING)
10708 			return (0);
10709 
10710 		if (!buf->dtb_switched && buf->dtb_offset != 0)
10711 			return (0);
10712 
10713 		if (buf->dtb_switched - buf->dtb_interval < when)
10714 			return (0);
10715 	}
10716 
10717 	return (1);
10718 }
10719 
10720 static void
10721 dtrace_buffer_free(dtrace_buffer_t *bufs)
10722 {
10723 	int i;
10724 
10725 	for (i = 0; i < NCPU; i++) {
10726 		dtrace_buffer_t *buf = &bufs[i];
10727 
10728 		if (buf->dtb_tomax == NULL) {
10729 			ASSERT(buf->dtb_xamot == NULL);
10730 			ASSERT(buf->dtb_size == 0);
10731 			continue;
10732 		}
10733 
10734 		if (buf->dtb_xamot != NULL) {
10735 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10736 			kmem_free(buf->dtb_xamot, buf->dtb_size);
10737 		}
10738 
10739 		kmem_free(buf->dtb_tomax, buf->dtb_size);
10740 		buf->dtb_size = 0;
10741 		buf->dtb_tomax = NULL;
10742 		buf->dtb_xamot = NULL;
10743 	}
10744 }
10745 
10746 /*
10747  * DTrace Enabling Functions
10748  */
10749 static dtrace_enabling_t *
10750 dtrace_enabling_create(dtrace_vstate_t *vstate)
10751 {
10752 	dtrace_enabling_t *enab;
10753 
10754 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
10755 	enab->dten_vstate = vstate;
10756 
10757 	return (enab);
10758 }
10759 
10760 static void
10761 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
10762 {
10763 	dtrace_ecbdesc_t **ndesc;
10764 	size_t osize, nsize;
10765 
10766 	/*
10767 	 * We can't add to enablings after we've enabled them, or after we've
10768 	 * retained them.
10769 	 */
10770 	ASSERT(enab->dten_probegen == 0);
10771 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10772 
10773 	if (enab->dten_ndesc < enab->dten_maxdesc) {
10774 		enab->dten_desc[enab->dten_ndesc++] = ecb;
10775 		return;
10776 	}
10777 
10778 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10779 
10780 	if (enab->dten_maxdesc == 0) {
10781 		enab->dten_maxdesc = 1;
10782 	} else {
10783 		enab->dten_maxdesc <<= 1;
10784 	}
10785 
10786 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
10787 
10788 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10789 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
10790 	bcopy(enab->dten_desc, ndesc, osize);
10791 	kmem_free(enab->dten_desc, osize);
10792 
10793 	enab->dten_desc = ndesc;
10794 	enab->dten_desc[enab->dten_ndesc++] = ecb;
10795 }
10796 
10797 static void
10798 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
10799     dtrace_probedesc_t *pd)
10800 {
10801 	dtrace_ecbdesc_t *new;
10802 	dtrace_predicate_t *pred;
10803 	dtrace_actdesc_t *act;
10804 
10805 	/*
10806 	 * We're going to create a new ECB description that matches the
10807 	 * specified ECB in every way, but has the specified probe description.
10808 	 */
10809 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
10810 
10811 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
10812 		dtrace_predicate_hold(pred);
10813 
10814 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
10815 		dtrace_actdesc_hold(act);
10816 
10817 	new->dted_action = ecb->dted_action;
10818 	new->dted_pred = ecb->dted_pred;
10819 	new->dted_probe = *pd;
10820 	new->dted_uarg = ecb->dted_uarg;
10821 
10822 	dtrace_enabling_add(enab, new);
10823 }
10824 
10825 static void
10826 dtrace_enabling_dump(dtrace_enabling_t *enab)
10827 {
10828 	int i;
10829 
10830 	for (i = 0; i < enab->dten_ndesc; i++) {
10831 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
10832 
10833 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
10834 		    desc->dtpd_provider, desc->dtpd_mod,
10835 		    desc->dtpd_func, desc->dtpd_name);
10836 	}
10837 }
10838 
10839 static void
10840 dtrace_enabling_destroy(dtrace_enabling_t *enab)
10841 {
10842 	int i;
10843 	dtrace_ecbdesc_t *ep;
10844 	dtrace_vstate_t *vstate = enab->dten_vstate;
10845 
10846 	ASSERT(MUTEX_HELD(&dtrace_lock));
10847 
10848 	for (i = 0; i < enab->dten_ndesc; i++) {
10849 		dtrace_actdesc_t *act, *next;
10850 		dtrace_predicate_t *pred;
10851 
10852 		ep = enab->dten_desc[i];
10853 
10854 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
10855 			dtrace_predicate_release(pred, vstate);
10856 
10857 		for (act = ep->dted_action; act != NULL; act = next) {
10858 			next = act->dtad_next;
10859 			dtrace_actdesc_release(act, vstate);
10860 		}
10861 
10862 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
10863 	}
10864 
10865 	kmem_free(enab->dten_desc,
10866 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
10867 
10868 	/*
10869 	 * If this was a retained enabling, decrement the dts_nretained count
10870 	 * and take it off of the dtrace_retained list.
10871 	 */
10872 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
10873 	    dtrace_retained == enab) {
10874 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10875 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
10876 		enab->dten_vstate->dtvs_state->dts_nretained--;
10877 		dtrace_retained_gen++;
10878 	}
10879 
10880 	if (enab->dten_prev == NULL) {
10881 		if (dtrace_retained == enab) {
10882 			dtrace_retained = enab->dten_next;
10883 
10884 			if (dtrace_retained != NULL)
10885 				dtrace_retained->dten_prev = NULL;
10886 		}
10887 	} else {
10888 		ASSERT(enab != dtrace_retained);
10889 		ASSERT(dtrace_retained != NULL);
10890 		enab->dten_prev->dten_next = enab->dten_next;
10891 	}
10892 
10893 	if (enab->dten_next != NULL) {
10894 		ASSERT(dtrace_retained != NULL);
10895 		enab->dten_next->dten_prev = enab->dten_prev;
10896 	}
10897 
10898 	kmem_free(enab, sizeof (dtrace_enabling_t));
10899 }
10900 
10901 static int
10902 dtrace_enabling_retain(dtrace_enabling_t *enab)
10903 {
10904 	dtrace_state_t *state;
10905 
10906 	ASSERT(MUTEX_HELD(&dtrace_lock));
10907 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10908 	ASSERT(enab->dten_vstate != NULL);
10909 
10910 	state = enab->dten_vstate->dtvs_state;
10911 	ASSERT(state != NULL);
10912 
10913 	/*
10914 	 * We only allow each state to retain dtrace_retain_max enablings.
10915 	 */
10916 	if (state->dts_nretained >= dtrace_retain_max)
10917 		return (ENOSPC);
10918 
10919 	state->dts_nretained++;
10920 	dtrace_retained_gen++;
10921 
10922 	if (dtrace_retained == NULL) {
10923 		dtrace_retained = enab;
10924 		return (0);
10925 	}
10926 
10927 	enab->dten_next = dtrace_retained;
10928 	dtrace_retained->dten_prev = enab;
10929 	dtrace_retained = enab;
10930 
10931 	return (0);
10932 }
10933 
10934 static int
10935 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
10936     dtrace_probedesc_t *create)
10937 {
10938 	dtrace_enabling_t *new, *enab;
10939 	int found = 0, err = ENOENT;
10940 
10941 	ASSERT(MUTEX_HELD(&dtrace_lock));
10942 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
10943 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
10944 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
10945 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
10946 
10947 	new = dtrace_enabling_create(&state->dts_vstate);
10948 
10949 	/*
10950 	 * Iterate over all retained enablings, looking for enablings that
10951 	 * match the specified state.
10952 	 */
10953 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10954 		int i;
10955 
10956 		/*
10957 		 * dtvs_state can only be NULL for helper enablings -- and
10958 		 * helper enablings can't be retained.
10959 		 */
10960 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10961 
10962 		if (enab->dten_vstate->dtvs_state != state)
10963 			continue;
10964 
10965 		/*
10966 		 * Now iterate over each probe description; we're looking for
10967 		 * an exact match to the specified probe description.
10968 		 */
10969 		for (i = 0; i < enab->dten_ndesc; i++) {
10970 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
10971 			dtrace_probedesc_t *pd = &ep->dted_probe;
10972 
10973 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
10974 				continue;
10975 
10976 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
10977 				continue;
10978 
10979 			if (strcmp(pd->dtpd_func, match->dtpd_func))
10980 				continue;
10981 
10982 			if (strcmp(pd->dtpd_name, match->dtpd_name))
10983 				continue;
10984 
10985 			/*
10986 			 * We have a winning probe!  Add it to our growing
10987 			 * enabling.
10988 			 */
10989 			found = 1;
10990 			dtrace_enabling_addlike(new, ep, create);
10991 		}
10992 	}
10993 
10994 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
10995 		dtrace_enabling_destroy(new);
10996 		return (err);
10997 	}
10998 
10999 	return (0);
11000 }
11001 
11002 static void
11003 dtrace_enabling_retract(dtrace_state_t *state)
11004 {
11005 	dtrace_enabling_t *enab, *next;
11006 
11007 	ASSERT(MUTEX_HELD(&dtrace_lock));
11008 
11009 	/*
11010 	 * Iterate over all retained enablings, destroy the enablings retained
11011 	 * for the specified state.
11012 	 */
11013 	for (enab = dtrace_retained; enab != NULL; enab = next) {
11014 		next = enab->dten_next;
11015 
11016 		/*
11017 		 * dtvs_state can only be NULL for helper enablings -- and
11018 		 * helper enablings can't be retained.
11019 		 */
11020 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11021 
11022 		if (enab->dten_vstate->dtvs_state == state) {
11023 			ASSERT(state->dts_nretained > 0);
11024 			dtrace_enabling_destroy(enab);
11025 		}
11026 	}
11027 
11028 	ASSERT(state->dts_nretained == 0);
11029 }
11030 
11031 static int
11032 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11033 {
11034 	int i = 0;
11035 	int total_matched = 0, matched = 0;
11036 
11037 	ASSERT(MUTEX_HELD(&cpu_lock));
11038 	ASSERT(MUTEX_HELD(&dtrace_lock));
11039 
11040 	for (i = 0; i < enab->dten_ndesc; i++) {
11041 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11042 
11043 		enab->dten_current = ep;
11044 		enab->dten_error = 0;
11045 
11046 		/*
11047 		 * If a provider failed to enable a probe then get out and
11048 		 * let the consumer know we failed.
11049 		 */
11050 		if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
11051 			return (EBUSY);
11052 
11053 		total_matched += matched;
11054 
11055 		if (enab->dten_error != 0) {
11056 			/*
11057 			 * If we get an error half-way through enabling the
11058 			 * probes, we kick out -- perhaps with some number of
11059 			 * them enabled.  Leaving enabled probes enabled may
11060 			 * be slightly confusing for user-level, but we expect
11061 			 * that no one will attempt to actually drive on in
11062 			 * the face of such errors.  If this is an anonymous
11063 			 * enabling (indicated with a NULL nmatched pointer),
11064 			 * we cmn_err() a message.  We aren't expecting to
11065 			 * get such an error -- such as it can exist at all,
11066 			 * it would be a result of corrupted DOF in the driver
11067 			 * properties.
11068 			 */
11069 			if (nmatched == NULL) {
11070 				cmn_err(CE_WARN, "dtrace_enabling_match() "
11071 				    "error on %p: %d", (void *)ep,
11072 				    enab->dten_error);
11073 			}
11074 
11075 			return (enab->dten_error);
11076 		}
11077 	}
11078 
11079 	enab->dten_probegen = dtrace_probegen;
11080 	if (nmatched != NULL)
11081 		*nmatched = total_matched;
11082 
11083 	return (0);
11084 }
11085 
11086 static void
11087 dtrace_enabling_matchall(void)
11088 {
11089 	dtrace_enabling_t *enab;
11090 
11091 	mutex_enter(&cpu_lock);
11092 	mutex_enter(&dtrace_lock);
11093 
11094 	/*
11095 	 * Iterate over all retained enablings to see if any probes match
11096 	 * against them.  We only perform this operation on enablings for which
11097 	 * we have sufficient permissions by virtue of being in the global zone
11098 	 * or in the same zone as the DTrace client.  Because we can be called
11099 	 * after dtrace_detach() has been called, we cannot assert that there
11100 	 * are retained enablings.  We can safely load from dtrace_retained,
11101 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
11102 	 * block pending our completion.
11103 	 */
11104 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11105 		dtrace_cred_t *dcr = &enab->dten_vstate->dtvs_state->dts_cred;
11106 		cred_t *cr = dcr->dcr_cred;
11107 		zoneid_t zone = cr != NULL ? crgetzoneid(cr) : 0;
11108 
11109 		if ((dcr->dcr_visible & DTRACE_CRV_ALLZONE) || (cr != NULL &&
11110 		    (zone == GLOBAL_ZONEID || getzoneid() == zone)))
11111 			(void) dtrace_enabling_match(enab, NULL);
11112 	}
11113 
11114 	mutex_exit(&dtrace_lock);
11115 	mutex_exit(&cpu_lock);
11116 }
11117 
11118 /*
11119  * If an enabling is to be enabled without having matched probes (that is, if
11120  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11121  * enabling must be _primed_ by creating an ECB for every ECB description.
11122  * This must be done to assure that we know the number of speculations, the
11123  * number of aggregations, the minimum buffer size needed, etc. before we
11124  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
11125  * enabling any probes, we create ECBs for every ECB decription, but with a
11126  * NULL probe -- which is exactly what this function does.
11127  */
11128 static void
11129 dtrace_enabling_prime(dtrace_state_t *state)
11130 {
11131 	dtrace_enabling_t *enab;
11132 	int i;
11133 
11134 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11135 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11136 
11137 		if (enab->dten_vstate->dtvs_state != state)
11138 			continue;
11139 
11140 		/*
11141 		 * We don't want to prime an enabling more than once, lest
11142 		 * we allow a malicious user to induce resource exhaustion.
11143 		 * (The ECBs that result from priming an enabling aren't
11144 		 * leaked -- but they also aren't deallocated until the
11145 		 * consumer state is destroyed.)
11146 		 */
11147 		if (enab->dten_primed)
11148 			continue;
11149 
11150 		for (i = 0; i < enab->dten_ndesc; i++) {
11151 			enab->dten_current = enab->dten_desc[i];
11152 			(void) dtrace_probe_enable(NULL, enab);
11153 		}
11154 
11155 		enab->dten_primed = 1;
11156 	}
11157 }
11158 
11159 /*
11160  * Called to indicate that probes should be provided due to retained
11161  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
11162  * must take an initial lap through the enabling calling the dtps_provide()
11163  * entry point explicitly to allow for autocreated probes.
11164  */
11165 static void
11166 dtrace_enabling_provide(dtrace_provider_t *prv)
11167 {
11168 	int i, all = 0;
11169 	dtrace_probedesc_t desc;
11170 	dtrace_genid_t gen;
11171 
11172 	ASSERT(MUTEX_HELD(&dtrace_lock));
11173 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
11174 
11175 	if (prv == NULL) {
11176 		all = 1;
11177 		prv = dtrace_provider;
11178 	}
11179 
11180 	do {
11181 		dtrace_enabling_t *enab;
11182 		void *parg = prv->dtpv_arg;
11183 
11184 retry:
11185 		gen = dtrace_retained_gen;
11186 		for (enab = dtrace_retained; enab != NULL;
11187 		    enab = enab->dten_next) {
11188 			for (i = 0; i < enab->dten_ndesc; i++) {
11189 				desc = enab->dten_desc[i]->dted_probe;
11190 				mutex_exit(&dtrace_lock);
11191 				prv->dtpv_pops.dtps_provide(parg, &desc);
11192 				mutex_enter(&dtrace_lock);
11193 				/*
11194 				 * Process the retained enablings again if
11195 				 * they have changed while we weren't holding
11196 				 * dtrace_lock.
11197 				 */
11198 				if (gen != dtrace_retained_gen)
11199 					goto retry;
11200 			}
11201 		}
11202 	} while (all && (prv = prv->dtpv_next) != NULL);
11203 
11204 	mutex_exit(&dtrace_lock);
11205 	dtrace_probe_provide(NULL, all ? NULL : prv);
11206 	mutex_enter(&dtrace_lock);
11207 }
11208 
11209 /*
11210  * Called to reap ECBs that are attached to probes from defunct providers.
11211  */
11212 static void
11213 dtrace_enabling_reap(void)
11214 {
11215 	dtrace_provider_t *prov;
11216 	dtrace_probe_t *probe;
11217 	dtrace_ecb_t *ecb;
11218 	hrtime_t when;
11219 	int i;
11220 
11221 	mutex_enter(&cpu_lock);
11222 	mutex_enter(&dtrace_lock);
11223 
11224 	for (i = 0; i < dtrace_nprobes; i++) {
11225 		if ((probe = dtrace_probes[i]) == NULL)
11226 			continue;
11227 
11228 		if (probe->dtpr_ecb == NULL)
11229 			continue;
11230 
11231 		prov = probe->dtpr_provider;
11232 
11233 		if ((when = prov->dtpv_defunct) == 0)
11234 			continue;
11235 
11236 		/*
11237 		 * We have ECBs on a defunct provider:  we want to reap these
11238 		 * ECBs to allow the provider to unregister.  The destruction
11239 		 * of these ECBs must be done carefully:  if we destroy the ECB
11240 		 * and the consumer later wishes to consume an EPID that
11241 		 * corresponds to the destroyed ECB (and if the EPID metadata
11242 		 * has not been previously consumed), the consumer will abort
11243 		 * processing on the unknown EPID.  To reduce (but not, sadly,
11244 		 * eliminate) the possibility of this, we will only destroy an
11245 		 * ECB for a defunct provider if, for the state that
11246 		 * corresponds to the ECB:
11247 		 *
11248 		 *  (a)	There is no speculative tracing (which can effectively
11249 		 *	cache an EPID for an arbitrary amount of time).
11250 		 *
11251 		 *  (b)	The principal buffers have been switched twice since the
11252 		 *	provider became defunct.
11253 		 *
11254 		 *  (c)	The aggregation buffers are of zero size or have been
11255 		 *	switched twice since the provider became defunct.
11256 		 *
11257 		 * We use dts_speculates to determine (a) and call a function
11258 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
11259 		 * that as soon as we've been unable to destroy one of the ECBs
11260 		 * associated with the probe, we quit trying -- reaping is only
11261 		 * fruitful in as much as we can destroy all ECBs associated
11262 		 * with the defunct provider's probes.
11263 		 */
11264 		while ((ecb = probe->dtpr_ecb) != NULL) {
11265 			dtrace_state_t *state = ecb->dte_state;
11266 			dtrace_buffer_t *buf = state->dts_buffer;
11267 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
11268 
11269 			if (state->dts_speculates)
11270 				break;
11271 
11272 			if (!dtrace_buffer_consumed(buf, when))
11273 				break;
11274 
11275 			if (!dtrace_buffer_consumed(aggbuf, when))
11276 				break;
11277 
11278 			dtrace_ecb_disable(ecb);
11279 			ASSERT(probe->dtpr_ecb != ecb);
11280 			dtrace_ecb_destroy(ecb);
11281 		}
11282 	}
11283 
11284 	mutex_exit(&dtrace_lock);
11285 	mutex_exit(&cpu_lock);
11286 }
11287 
11288 /*
11289  * DTrace DOF Functions
11290  */
11291 /*ARGSUSED*/
11292 static void
11293 dtrace_dof_error(dof_hdr_t *dof, const char *str)
11294 {
11295 	if (dtrace_err_verbose)
11296 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
11297 
11298 #ifdef DTRACE_ERRDEBUG
11299 	dtrace_errdebug(str);
11300 #endif
11301 }
11302 
11303 /*
11304  * Create DOF out of a currently enabled state.  Right now, we only create
11305  * DOF containing the run-time options -- but this could be expanded to create
11306  * complete DOF representing the enabled state.
11307  */
11308 static dof_hdr_t *
11309 dtrace_dof_create(dtrace_state_t *state)
11310 {
11311 	dof_hdr_t *dof;
11312 	dof_sec_t *sec;
11313 	dof_optdesc_t *opt;
11314 	int i, len = sizeof (dof_hdr_t) +
11315 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
11316 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11317 
11318 	ASSERT(MUTEX_HELD(&dtrace_lock));
11319 
11320 	dof = kmem_zalloc(len, KM_SLEEP);
11321 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
11322 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
11323 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
11324 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
11325 
11326 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
11327 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
11328 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
11329 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
11330 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
11331 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
11332 
11333 	dof->dofh_flags = 0;
11334 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
11335 	dof->dofh_secsize = sizeof (dof_sec_t);
11336 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
11337 	dof->dofh_secoff = sizeof (dof_hdr_t);
11338 	dof->dofh_loadsz = len;
11339 	dof->dofh_filesz = len;
11340 	dof->dofh_pad = 0;
11341 
11342 	/*
11343 	 * Fill in the option section header...
11344 	 */
11345 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
11346 	sec->dofs_type = DOF_SECT_OPTDESC;
11347 	sec->dofs_align = sizeof (uint64_t);
11348 	sec->dofs_flags = DOF_SECF_LOAD;
11349 	sec->dofs_entsize = sizeof (dof_optdesc_t);
11350 
11351 	opt = (dof_optdesc_t *)((uintptr_t)sec +
11352 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
11353 
11354 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
11355 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11356 
11357 	for (i = 0; i < DTRACEOPT_MAX; i++) {
11358 		opt[i].dofo_option = i;
11359 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
11360 		opt[i].dofo_value = state->dts_options[i];
11361 	}
11362 
11363 	return (dof);
11364 }
11365 
11366 static dof_hdr_t *
11367 dtrace_dof_copyin(uintptr_t uarg, int *errp)
11368 {
11369 	dof_hdr_t hdr, *dof;
11370 
11371 	ASSERT(!MUTEX_HELD(&dtrace_lock));
11372 
11373 	/*
11374 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
11375 	 */
11376 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
11377 		dtrace_dof_error(NULL, "failed to copyin DOF header");
11378 		*errp = EFAULT;
11379 		return (NULL);
11380 	}
11381 
11382 	/*
11383 	 * Now we'll allocate the entire DOF and copy it in -- provided
11384 	 * that the length isn't outrageous.
11385 	 */
11386 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
11387 		dtrace_dof_error(&hdr, "load size exceeds maximum");
11388 		*errp = E2BIG;
11389 		return (NULL);
11390 	}
11391 
11392 	if (hdr.dofh_loadsz < sizeof (hdr)) {
11393 		dtrace_dof_error(&hdr, "invalid load size");
11394 		*errp = EINVAL;
11395 		return (NULL);
11396 	}
11397 
11398 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
11399 
11400 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
11401 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
11402 		kmem_free(dof, hdr.dofh_loadsz);
11403 		*errp = EFAULT;
11404 		return (NULL);
11405 	}
11406 
11407 	return (dof);
11408 }
11409 
11410 static dof_hdr_t *
11411 dtrace_dof_property(const char *name)
11412 {
11413 	uchar_t *buf;
11414 	uint64_t loadsz;
11415 	unsigned int len, i;
11416 	dof_hdr_t *dof;
11417 
11418 	/*
11419 	 * Unfortunately, array of values in .conf files are always (and
11420 	 * only) interpreted to be integer arrays.  We must read our DOF
11421 	 * as an integer array, and then squeeze it into a byte array.
11422 	 */
11423 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
11424 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
11425 		return (NULL);
11426 
11427 	for (i = 0; i < len; i++)
11428 		buf[i] = (uchar_t)(((int *)buf)[i]);
11429 
11430 	if (len < sizeof (dof_hdr_t)) {
11431 		ddi_prop_free(buf);
11432 		dtrace_dof_error(NULL, "truncated header");
11433 		return (NULL);
11434 	}
11435 
11436 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
11437 		ddi_prop_free(buf);
11438 		dtrace_dof_error(NULL, "truncated DOF");
11439 		return (NULL);
11440 	}
11441 
11442 	if (loadsz >= dtrace_dof_maxsize) {
11443 		ddi_prop_free(buf);
11444 		dtrace_dof_error(NULL, "oversized DOF");
11445 		return (NULL);
11446 	}
11447 
11448 	dof = kmem_alloc(loadsz, KM_SLEEP);
11449 	bcopy(buf, dof, loadsz);
11450 	ddi_prop_free(buf);
11451 
11452 	return (dof);
11453 }
11454 
11455 static void
11456 dtrace_dof_destroy(dof_hdr_t *dof)
11457 {
11458 	kmem_free(dof, dof->dofh_loadsz);
11459 }
11460 
11461 /*
11462  * Return the dof_sec_t pointer corresponding to a given section index.  If the
11463  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
11464  * a type other than DOF_SECT_NONE is specified, the header is checked against
11465  * this type and NULL is returned if the types do not match.
11466  */
11467 static dof_sec_t *
11468 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
11469 {
11470 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
11471 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
11472 
11473 	if (i >= dof->dofh_secnum) {
11474 		dtrace_dof_error(dof, "referenced section index is invalid");
11475 		return (NULL);
11476 	}
11477 
11478 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
11479 		dtrace_dof_error(dof, "referenced section is not loadable");
11480 		return (NULL);
11481 	}
11482 
11483 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
11484 		dtrace_dof_error(dof, "referenced section is the wrong type");
11485 		return (NULL);
11486 	}
11487 
11488 	return (sec);
11489 }
11490 
11491 static dtrace_probedesc_t *
11492 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
11493 {
11494 	dof_probedesc_t *probe;
11495 	dof_sec_t *strtab;
11496 	uintptr_t daddr = (uintptr_t)dof;
11497 	uintptr_t str;
11498 	size_t size;
11499 
11500 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
11501 		dtrace_dof_error(dof, "invalid probe section");
11502 		return (NULL);
11503 	}
11504 
11505 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
11506 		dtrace_dof_error(dof, "bad alignment in probe description");
11507 		return (NULL);
11508 	}
11509 
11510 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
11511 		dtrace_dof_error(dof, "truncated probe description");
11512 		return (NULL);
11513 	}
11514 
11515 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
11516 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
11517 
11518 	if (strtab == NULL)
11519 		return (NULL);
11520 
11521 	str = daddr + strtab->dofs_offset;
11522 	size = strtab->dofs_size;
11523 
11524 	if (probe->dofp_provider >= strtab->dofs_size) {
11525 		dtrace_dof_error(dof, "corrupt probe provider");
11526 		return (NULL);
11527 	}
11528 
11529 	(void) strncpy(desc->dtpd_provider,
11530 	    (char *)(str + probe->dofp_provider),
11531 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
11532 
11533 	if (probe->dofp_mod >= strtab->dofs_size) {
11534 		dtrace_dof_error(dof, "corrupt probe module");
11535 		return (NULL);
11536 	}
11537 
11538 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
11539 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
11540 
11541 	if (probe->dofp_func >= strtab->dofs_size) {
11542 		dtrace_dof_error(dof, "corrupt probe function");
11543 		return (NULL);
11544 	}
11545 
11546 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
11547 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
11548 
11549 	if (probe->dofp_name >= strtab->dofs_size) {
11550 		dtrace_dof_error(dof, "corrupt probe name");
11551 		return (NULL);
11552 	}
11553 
11554 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
11555 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
11556 
11557 	return (desc);
11558 }
11559 
11560 static dtrace_difo_t *
11561 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11562     cred_t *cr)
11563 {
11564 	dtrace_difo_t *dp;
11565 	size_t ttl = 0;
11566 	dof_difohdr_t *dofd;
11567 	uintptr_t daddr = (uintptr_t)dof;
11568 	size_t max = dtrace_difo_maxsize;
11569 	int i, l, n;
11570 
11571 	static const struct {
11572 		int section;
11573 		int bufoffs;
11574 		int lenoffs;
11575 		int entsize;
11576 		int align;
11577 		const char *msg;
11578 	} difo[] = {
11579 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
11580 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
11581 		sizeof (dif_instr_t), "multiple DIF sections" },
11582 
11583 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
11584 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
11585 		sizeof (uint64_t), "multiple integer tables" },
11586 
11587 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
11588 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
11589 		sizeof (char), "multiple string tables" },
11590 
11591 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
11592 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
11593 		sizeof (uint_t), "multiple variable tables" },
11594 
11595 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
11596 	};
11597 
11598 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
11599 		dtrace_dof_error(dof, "invalid DIFO header section");
11600 		return (NULL);
11601 	}
11602 
11603 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
11604 		dtrace_dof_error(dof, "bad alignment in DIFO header");
11605 		return (NULL);
11606 	}
11607 
11608 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
11609 	    sec->dofs_size % sizeof (dof_secidx_t)) {
11610 		dtrace_dof_error(dof, "bad size in DIFO header");
11611 		return (NULL);
11612 	}
11613 
11614 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11615 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
11616 
11617 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
11618 	dp->dtdo_rtype = dofd->dofd_rtype;
11619 
11620 	for (l = 0; l < n; l++) {
11621 		dof_sec_t *subsec;
11622 		void **bufp;
11623 		uint32_t *lenp;
11624 
11625 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
11626 		    dofd->dofd_links[l])) == NULL)
11627 			goto err; /* invalid section link */
11628 
11629 		if (ttl + subsec->dofs_size > max) {
11630 			dtrace_dof_error(dof, "exceeds maximum size");
11631 			goto err;
11632 		}
11633 
11634 		ttl += subsec->dofs_size;
11635 
11636 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
11637 			if (subsec->dofs_type != difo[i].section)
11638 				continue;
11639 
11640 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
11641 				dtrace_dof_error(dof, "section not loaded");
11642 				goto err;
11643 			}
11644 
11645 			if (subsec->dofs_align != difo[i].align) {
11646 				dtrace_dof_error(dof, "bad alignment");
11647 				goto err;
11648 			}
11649 
11650 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
11651 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
11652 
11653 			if (*bufp != NULL) {
11654 				dtrace_dof_error(dof, difo[i].msg);
11655 				goto err;
11656 			}
11657 
11658 			if (difo[i].entsize != subsec->dofs_entsize) {
11659 				dtrace_dof_error(dof, "entry size mismatch");
11660 				goto err;
11661 			}
11662 
11663 			if (subsec->dofs_entsize != 0 &&
11664 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
11665 				dtrace_dof_error(dof, "corrupt entry size");
11666 				goto err;
11667 			}
11668 
11669 			*lenp = subsec->dofs_size;
11670 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
11671 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
11672 			    *bufp, subsec->dofs_size);
11673 
11674 			if (subsec->dofs_entsize != 0)
11675 				*lenp /= subsec->dofs_entsize;
11676 
11677 			break;
11678 		}
11679 
11680 		/*
11681 		 * If we encounter a loadable DIFO sub-section that is not
11682 		 * known to us, assume this is a broken program and fail.
11683 		 */
11684 		if (difo[i].section == DOF_SECT_NONE &&
11685 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
11686 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
11687 			goto err;
11688 		}
11689 	}
11690 
11691 	if (dp->dtdo_buf == NULL) {
11692 		/*
11693 		 * We can't have a DIF object without DIF text.
11694 		 */
11695 		dtrace_dof_error(dof, "missing DIF text");
11696 		goto err;
11697 	}
11698 
11699 	/*
11700 	 * Before we validate the DIF object, run through the variable table
11701 	 * looking for the strings -- if any of their size are under, we'll set
11702 	 * their size to be the system-wide default string size.  Note that
11703 	 * this should _not_ happen if the "strsize" option has been set --
11704 	 * in this case, the compiler should have set the size to reflect the
11705 	 * setting of the option.
11706 	 */
11707 	for (i = 0; i < dp->dtdo_varlen; i++) {
11708 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
11709 		dtrace_diftype_t *t = &v->dtdv_type;
11710 
11711 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
11712 			continue;
11713 
11714 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
11715 			t->dtdt_size = dtrace_strsize_default;
11716 	}
11717 
11718 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
11719 		goto err;
11720 
11721 	dtrace_difo_init(dp, vstate);
11722 	return (dp);
11723 
11724 err:
11725 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
11726 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
11727 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
11728 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
11729 
11730 	kmem_free(dp, sizeof (dtrace_difo_t));
11731 	return (NULL);
11732 }
11733 
11734 static dtrace_predicate_t *
11735 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11736     cred_t *cr)
11737 {
11738 	dtrace_difo_t *dp;
11739 
11740 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
11741 		return (NULL);
11742 
11743 	return (dtrace_predicate_create(dp));
11744 }
11745 
11746 static dtrace_actdesc_t *
11747 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11748     cred_t *cr)
11749 {
11750 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
11751 	dof_actdesc_t *desc;
11752 	dof_sec_t *difosec;
11753 	size_t offs;
11754 	uintptr_t daddr = (uintptr_t)dof;
11755 	uint64_t arg;
11756 	dtrace_actkind_t kind;
11757 
11758 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
11759 		dtrace_dof_error(dof, "invalid action section");
11760 		return (NULL);
11761 	}
11762 
11763 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
11764 		dtrace_dof_error(dof, "truncated action description");
11765 		return (NULL);
11766 	}
11767 
11768 	if (sec->dofs_align != sizeof (uint64_t)) {
11769 		dtrace_dof_error(dof, "bad alignment in action description");
11770 		return (NULL);
11771 	}
11772 
11773 	if (sec->dofs_size < sec->dofs_entsize) {
11774 		dtrace_dof_error(dof, "section entry size exceeds total size");
11775 		return (NULL);
11776 	}
11777 
11778 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
11779 		dtrace_dof_error(dof, "bad entry size in action description");
11780 		return (NULL);
11781 	}
11782 
11783 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
11784 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
11785 		return (NULL);
11786 	}
11787 
11788 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
11789 		desc = (dof_actdesc_t *)(daddr +
11790 		    (uintptr_t)sec->dofs_offset + offs);
11791 		kind = (dtrace_actkind_t)desc->dofa_kind;
11792 
11793 		if (DTRACEACT_ISPRINTFLIKE(kind) &&
11794 		    (kind != DTRACEACT_PRINTA ||
11795 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
11796 			dof_sec_t *strtab;
11797 			char *str, *fmt;
11798 			uint64_t i;
11799 
11800 			/*
11801 			 * printf()-like actions must have a format string.
11802 			 */
11803 			if ((strtab = dtrace_dof_sect(dof,
11804 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
11805 				goto err;
11806 
11807 			str = (char *)((uintptr_t)dof +
11808 			    (uintptr_t)strtab->dofs_offset);
11809 
11810 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
11811 				if (str[i] == '\0')
11812 					break;
11813 			}
11814 
11815 			if (i >= strtab->dofs_size) {
11816 				dtrace_dof_error(dof, "bogus format string");
11817 				goto err;
11818 			}
11819 
11820 			if (i == desc->dofa_arg) {
11821 				dtrace_dof_error(dof, "empty format string");
11822 				goto err;
11823 			}
11824 
11825 			i -= desc->dofa_arg;
11826 			fmt = kmem_alloc(i + 1, KM_SLEEP);
11827 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
11828 			arg = (uint64_t)(uintptr_t)fmt;
11829 		} else {
11830 			if (kind == DTRACEACT_PRINTA) {
11831 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
11832 				arg = 0;
11833 			} else {
11834 				arg = desc->dofa_arg;
11835 			}
11836 		}
11837 
11838 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
11839 		    desc->dofa_uarg, arg);
11840 
11841 		if (last != NULL) {
11842 			last->dtad_next = act;
11843 		} else {
11844 			first = act;
11845 		}
11846 
11847 		last = act;
11848 
11849 		if (desc->dofa_difo == DOF_SECIDX_NONE)
11850 			continue;
11851 
11852 		if ((difosec = dtrace_dof_sect(dof,
11853 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
11854 			goto err;
11855 
11856 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
11857 
11858 		if (act->dtad_difo == NULL)
11859 			goto err;
11860 	}
11861 
11862 	ASSERT(first != NULL);
11863 	return (first);
11864 
11865 err:
11866 	for (act = first; act != NULL; act = next) {
11867 		next = act->dtad_next;
11868 		dtrace_actdesc_release(act, vstate);
11869 	}
11870 
11871 	return (NULL);
11872 }
11873 
11874 static dtrace_ecbdesc_t *
11875 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11876     cred_t *cr)
11877 {
11878 	dtrace_ecbdesc_t *ep;
11879 	dof_ecbdesc_t *ecb;
11880 	dtrace_probedesc_t *desc;
11881 	dtrace_predicate_t *pred = NULL;
11882 
11883 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
11884 		dtrace_dof_error(dof, "truncated ECB description");
11885 		return (NULL);
11886 	}
11887 
11888 	if (sec->dofs_align != sizeof (uint64_t)) {
11889 		dtrace_dof_error(dof, "bad alignment in ECB description");
11890 		return (NULL);
11891 	}
11892 
11893 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
11894 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
11895 
11896 	if (sec == NULL)
11897 		return (NULL);
11898 
11899 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11900 	ep->dted_uarg = ecb->dofe_uarg;
11901 	desc = &ep->dted_probe;
11902 
11903 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
11904 		goto err;
11905 
11906 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
11907 		if ((sec = dtrace_dof_sect(dof,
11908 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
11909 			goto err;
11910 
11911 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
11912 			goto err;
11913 
11914 		ep->dted_pred.dtpdd_predicate = pred;
11915 	}
11916 
11917 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
11918 		if ((sec = dtrace_dof_sect(dof,
11919 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
11920 			goto err;
11921 
11922 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
11923 
11924 		if (ep->dted_action == NULL)
11925 			goto err;
11926 	}
11927 
11928 	return (ep);
11929 
11930 err:
11931 	if (pred != NULL)
11932 		dtrace_predicate_release(pred, vstate);
11933 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11934 	return (NULL);
11935 }
11936 
11937 /*
11938  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
11939  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
11940  * site of any user SETX relocations to account for load object base address.
11941  * In the future, if we need other relocations, this function can be extended.
11942  */
11943 static int
11944 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
11945 {
11946 	uintptr_t daddr = (uintptr_t)dof;
11947 	dof_relohdr_t *dofr =
11948 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11949 	dof_sec_t *ss, *rs, *ts;
11950 	dof_relodesc_t *r;
11951 	uint_t i, n;
11952 
11953 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
11954 	    sec->dofs_align != sizeof (dof_secidx_t)) {
11955 		dtrace_dof_error(dof, "invalid relocation header");
11956 		return (-1);
11957 	}
11958 
11959 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
11960 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
11961 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
11962 
11963 	if (ss == NULL || rs == NULL || ts == NULL)
11964 		return (-1); /* dtrace_dof_error() has been called already */
11965 
11966 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
11967 	    rs->dofs_align != sizeof (uint64_t)) {
11968 		dtrace_dof_error(dof, "invalid relocation section");
11969 		return (-1);
11970 	}
11971 
11972 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
11973 	n = rs->dofs_size / rs->dofs_entsize;
11974 
11975 	for (i = 0; i < n; i++) {
11976 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
11977 
11978 		switch (r->dofr_type) {
11979 		case DOF_RELO_NONE:
11980 			break;
11981 		case DOF_RELO_SETX:
11982 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
11983 			    sizeof (uint64_t) > ts->dofs_size) {
11984 				dtrace_dof_error(dof, "bad relocation offset");
11985 				return (-1);
11986 			}
11987 
11988 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
11989 				dtrace_dof_error(dof, "misaligned setx relo");
11990 				return (-1);
11991 			}
11992 
11993 			*(uint64_t *)taddr += ubase;
11994 			break;
11995 		default:
11996 			dtrace_dof_error(dof, "invalid relocation type");
11997 			return (-1);
11998 		}
11999 
12000 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12001 	}
12002 
12003 	return (0);
12004 }
12005 
12006 /*
12007  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12008  * header:  it should be at the front of a memory region that is at least
12009  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12010  * size.  It need not be validated in any other way.
12011  */
12012 static int
12013 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12014     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12015 {
12016 	uint64_t len = dof->dofh_loadsz, seclen;
12017 	uintptr_t daddr = (uintptr_t)dof;
12018 	dtrace_ecbdesc_t *ep;
12019 	dtrace_enabling_t *enab;
12020 	uint_t i;
12021 
12022 	ASSERT(MUTEX_HELD(&dtrace_lock));
12023 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12024 
12025 	/*
12026 	 * Check the DOF header identification bytes.  In addition to checking
12027 	 * valid settings, we also verify that unused bits/bytes are zeroed so
12028 	 * we can use them later without fear of regressing existing binaries.
12029 	 */
12030 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12031 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12032 		dtrace_dof_error(dof, "DOF magic string mismatch");
12033 		return (-1);
12034 	}
12035 
12036 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12037 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12038 		dtrace_dof_error(dof, "DOF has invalid data model");
12039 		return (-1);
12040 	}
12041 
12042 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12043 		dtrace_dof_error(dof, "DOF encoding mismatch");
12044 		return (-1);
12045 	}
12046 
12047 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12048 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12049 		dtrace_dof_error(dof, "DOF version mismatch");
12050 		return (-1);
12051 	}
12052 
12053 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12054 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12055 		return (-1);
12056 	}
12057 
12058 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12059 		dtrace_dof_error(dof, "DOF uses too many integer registers");
12060 		return (-1);
12061 	}
12062 
12063 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12064 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
12065 		return (-1);
12066 	}
12067 
12068 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12069 		if (dof->dofh_ident[i] != 0) {
12070 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
12071 			return (-1);
12072 		}
12073 	}
12074 
12075 	if (dof->dofh_flags & ~DOF_FL_VALID) {
12076 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
12077 		return (-1);
12078 	}
12079 
12080 	if (dof->dofh_secsize == 0) {
12081 		dtrace_dof_error(dof, "zero section header size");
12082 		return (-1);
12083 	}
12084 
12085 	/*
12086 	 * Check that the section headers don't exceed the amount of DOF
12087 	 * data.  Note that we cast the section size and number of sections
12088 	 * to uint64_t's to prevent possible overflow in the multiplication.
12089 	 */
12090 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12091 
12092 	if (dof->dofh_secoff > len || seclen > len ||
12093 	    dof->dofh_secoff + seclen > len) {
12094 		dtrace_dof_error(dof, "truncated section headers");
12095 		return (-1);
12096 	}
12097 
12098 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12099 		dtrace_dof_error(dof, "misaligned section headers");
12100 		return (-1);
12101 	}
12102 
12103 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12104 		dtrace_dof_error(dof, "misaligned section size");
12105 		return (-1);
12106 	}
12107 
12108 	/*
12109 	 * Take an initial pass through the section headers to be sure that
12110 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
12111 	 * set, do not permit sections relating to providers, probes, or args.
12112 	 */
12113 	for (i = 0; i < dof->dofh_secnum; i++) {
12114 		dof_sec_t *sec = (dof_sec_t *)(daddr +
12115 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12116 
12117 		if (noprobes) {
12118 			switch (sec->dofs_type) {
12119 			case DOF_SECT_PROVIDER:
12120 			case DOF_SECT_PROBES:
12121 			case DOF_SECT_PRARGS:
12122 			case DOF_SECT_PROFFS:
12123 				dtrace_dof_error(dof, "illegal sections "
12124 				    "for enabling");
12125 				return (-1);
12126 			}
12127 		}
12128 
12129 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
12130 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
12131 			dtrace_dof_error(dof, "loadable section with load "
12132 			    "flag unset");
12133 			return (-1);
12134 		}
12135 
12136 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
12137 			continue; /* just ignore non-loadable sections */
12138 
12139 		if (sec->dofs_align & (sec->dofs_align - 1)) {
12140 			dtrace_dof_error(dof, "bad section alignment");
12141 			return (-1);
12142 		}
12143 
12144 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
12145 			dtrace_dof_error(dof, "misaligned section");
12146 			return (-1);
12147 		}
12148 
12149 		if (sec->dofs_offset > len || sec->dofs_size > len ||
12150 		    sec->dofs_offset + sec->dofs_size > len) {
12151 			dtrace_dof_error(dof, "corrupt section header");
12152 			return (-1);
12153 		}
12154 
12155 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12156 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12157 			dtrace_dof_error(dof, "non-terminating string table");
12158 			return (-1);
12159 		}
12160 	}
12161 
12162 	/*
12163 	 * Take a second pass through the sections and locate and perform any
12164 	 * relocations that are present.  We do this after the first pass to
12165 	 * be sure that all sections have had their headers validated.
12166 	 */
12167 	for (i = 0; i < dof->dofh_secnum; i++) {
12168 		dof_sec_t *sec = (dof_sec_t *)(daddr +
12169 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12170 
12171 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
12172 			continue; /* skip sections that are not loadable */
12173 
12174 		switch (sec->dofs_type) {
12175 		case DOF_SECT_URELHDR:
12176 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
12177 				return (-1);
12178 			break;
12179 		}
12180 	}
12181 
12182 	if ((enab = *enabp) == NULL)
12183 		enab = *enabp = dtrace_enabling_create(vstate);
12184 
12185 	for (i = 0; i < dof->dofh_secnum; i++) {
12186 		dof_sec_t *sec = (dof_sec_t *)(daddr +
12187 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12188 
12189 		if (sec->dofs_type != DOF_SECT_ECBDESC)
12190 			continue;
12191 
12192 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
12193 			dtrace_enabling_destroy(enab);
12194 			*enabp = NULL;
12195 			return (-1);
12196 		}
12197 
12198 		dtrace_enabling_add(enab, ep);
12199 	}
12200 
12201 	return (0);
12202 }
12203 
12204 /*
12205  * Process DOF for any options.  This routine assumes that the DOF has been
12206  * at least processed by dtrace_dof_slurp().
12207  */
12208 static int
12209 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12210 {
12211 	int i, rval;
12212 	uint32_t entsize;
12213 	size_t offs;
12214 	dof_optdesc_t *desc;
12215 
12216 	for (i = 0; i < dof->dofh_secnum; i++) {
12217 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12218 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12219 
12220 		if (sec->dofs_type != DOF_SECT_OPTDESC)
12221 			continue;
12222 
12223 		if (sec->dofs_align != sizeof (uint64_t)) {
12224 			dtrace_dof_error(dof, "bad alignment in "
12225 			    "option description");
12226 			return (EINVAL);
12227 		}
12228 
12229 		if ((entsize = sec->dofs_entsize) == 0) {
12230 			dtrace_dof_error(dof, "zeroed option entry size");
12231 			return (EINVAL);
12232 		}
12233 
12234 		if (entsize < sizeof (dof_optdesc_t)) {
12235 			dtrace_dof_error(dof, "bad option entry size");
12236 			return (EINVAL);
12237 		}
12238 
12239 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12240 			desc = (dof_optdesc_t *)((uintptr_t)dof +
12241 			    (uintptr_t)sec->dofs_offset + offs);
12242 
12243 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12244 				dtrace_dof_error(dof, "non-zero option string");
12245 				return (EINVAL);
12246 			}
12247 
12248 			if (desc->dofo_value == DTRACEOPT_UNSET) {
12249 				dtrace_dof_error(dof, "unset option");
12250 				return (EINVAL);
12251 			}
12252 
12253 			if ((rval = dtrace_state_option(state,
12254 			    desc->dofo_option, desc->dofo_value)) != 0) {
12255 				dtrace_dof_error(dof, "rejected option");
12256 				return (rval);
12257 			}
12258 		}
12259 	}
12260 
12261 	return (0);
12262 }
12263 
12264 /*
12265  * DTrace Consumer State Functions
12266  */
12267 int
12268 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12269 {
12270 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
12271 	void *base;
12272 	uintptr_t limit;
12273 	dtrace_dynvar_t *dvar, *next, *start;
12274 	int i;
12275 
12276 	ASSERT(MUTEX_HELD(&dtrace_lock));
12277 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12278 
12279 	bzero(dstate, sizeof (dtrace_dstate_t));
12280 
12281 	if ((dstate->dtds_chunksize = chunksize) == 0)
12282 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12283 
12284 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12285 		size = min;
12286 
12287 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12288 		return (ENOMEM);
12289 
12290 	dstate->dtds_size = size;
12291 	dstate->dtds_base = base;
12292 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
12293 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
12294 
12295 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12296 
12297 	if (hashsize != 1 && (hashsize & 1))
12298 		hashsize--;
12299 
12300 	dstate->dtds_hashsize = hashsize;
12301 	dstate->dtds_hash = dstate->dtds_base;
12302 
12303 	/*
12304 	 * Set all of our hash buckets to point to the single sink, and (if
12305 	 * it hasn't already been set), set the sink's hash value to be the
12306 	 * sink sentinel value.  The sink is needed for dynamic variable
12307 	 * lookups to know that they have iterated over an entire, valid hash
12308 	 * chain.
12309 	 */
12310 	for (i = 0; i < hashsize; i++)
12311 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
12312 
12313 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
12314 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
12315 
12316 	/*
12317 	 * Determine number of active CPUs.  Divide free list evenly among
12318 	 * active CPUs.
12319 	 */
12320 	start = (dtrace_dynvar_t *)
12321 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
12322 	limit = (uintptr_t)base + size;
12323 
12324 	maxper = (limit - (uintptr_t)start) / NCPU;
12325 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
12326 
12327 	for (i = 0; i < NCPU; i++) {
12328 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
12329 
12330 		/*
12331 		 * If we don't even have enough chunks to make it once through
12332 		 * NCPUs, we're just going to allocate everything to the first
12333 		 * CPU.  And if we're on the last CPU, we're going to allocate
12334 		 * whatever is left over.  In either case, we set the limit to
12335 		 * be the limit of the dynamic variable space.
12336 		 */
12337 		if (maxper == 0 || i == NCPU - 1) {
12338 			limit = (uintptr_t)base + size;
12339 			start = NULL;
12340 		} else {
12341 			limit = (uintptr_t)start + maxper;
12342 			start = (dtrace_dynvar_t *)limit;
12343 		}
12344 
12345 		ASSERT(limit <= (uintptr_t)base + size);
12346 
12347 		for (;;) {
12348 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
12349 			    dstate->dtds_chunksize);
12350 
12351 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
12352 				break;
12353 
12354 			dvar->dtdv_next = next;
12355 			dvar = next;
12356 		}
12357 
12358 		if (maxper == 0)
12359 			break;
12360 	}
12361 
12362 	return (0);
12363 }
12364 
12365 void
12366 dtrace_dstate_fini(dtrace_dstate_t *dstate)
12367 {
12368 	ASSERT(MUTEX_HELD(&cpu_lock));
12369 
12370 	if (dstate->dtds_base == NULL)
12371 		return;
12372 
12373 	kmem_free(dstate->dtds_base, dstate->dtds_size);
12374 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
12375 }
12376 
12377 static void
12378 dtrace_vstate_fini(dtrace_vstate_t *vstate)
12379 {
12380 	/*
12381 	 * Logical XOR, where are you?
12382 	 */
12383 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
12384 
12385 	if (vstate->dtvs_nglobals > 0) {
12386 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
12387 		    sizeof (dtrace_statvar_t *));
12388 	}
12389 
12390 	if (vstate->dtvs_ntlocals > 0) {
12391 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
12392 		    sizeof (dtrace_difv_t));
12393 	}
12394 
12395 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
12396 
12397 	if (vstate->dtvs_nlocals > 0) {
12398 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
12399 		    sizeof (dtrace_statvar_t *));
12400 	}
12401 }
12402 
12403 static void
12404 dtrace_state_clean(dtrace_state_t *state)
12405 {
12406 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
12407 		return;
12408 
12409 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
12410 	dtrace_speculation_clean(state);
12411 }
12412 
12413 static void
12414 dtrace_state_deadman(dtrace_state_t *state)
12415 {
12416 	hrtime_t now;
12417 
12418 	dtrace_sync();
12419 
12420 	now = dtrace_gethrtime();
12421 
12422 	if (state != dtrace_anon.dta_state &&
12423 	    now - state->dts_laststatus >= dtrace_deadman_user)
12424 		return;
12425 
12426 	/*
12427 	 * We must be sure that dts_alive never appears to be less than the
12428 	 * value upon entry to dtrace_state_deadman(), and because we lack a
12429 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
12430 	 * store INT64_MAX to it, followed by a memory barrier, followed by
12431 	 * the new value.  This assures that dts_alive never appears to be
12432 	 * less than its true value, regardless of the order in which the
12433 	 * stores to the underlying storage are issued.
12434 	 */
12435 	state->dts_alive = INT64_MAX;
12436 	dtrace_membar_producer();
12437 	state->dts_alive = now;
12438 }
12439 
12440 dtrace_state_t *
12441 dtrace_state_create(dev_t *devp, cred_t *cr)
12442 {
12443 	minor_t minor;
12444 	major_t major;
12445 	char c[30];
12446 	dtrace_state_t *state;
12447 	dtrace_optval_t *opt;
12448 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
12449 
12450 	ASSERT(MUTEX_HELD(&dtrace_lock));
12451 	ASSERT(MUTEX_HELD(&cpu_lock));
12452 
12453 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
12454 	    VM_BESTFIT | VM_SLEEP);
12455 
12456 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
12457 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12458 		return (NULL);
12459 	}
12460 
12461 	state = ddi_get_soft_state(dtrace_softstate, minor);
12462 	state->dts_epid = DTRACE_EPIDNONE + 1;
12463 
12464 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
12465 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
12466 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
12467 
12468 	if (devp != NULL) {
12469 		major = getemajor(*devp);
12470 	} else {
12471 		major = ddi_driver_major(dtrace_devi);
12472 	}
12473 
12474 	state->dts_dev = makedevice(major, minor);
12475 
12476 	if (devp != NULL)
12477 		*devp = state->dts_dev;
12478 
12479 	/*
12480 	 * We allocate NCPU buffers.  On the one hand, this can be quite
12481 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
12482 	 * other hand, it saves an additional memory reference in the probe
12483 	 * path.
12484 	 */
12485 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
12486 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
12487 	state->dts_cleaner = CYCLIC_NONE;
12488 	state->dts_deadman = CYCLIC_NONE;
12489 	state->dts_vstate.dtvs_state = state;
12490 
12491 	for (i = 0; i < DTRACEOPT_MAX; i++)
12492 		state->dts_options[i] = DTRACEOPT_UNSET;
12493 
12494 	/*
12495 	 * Set the default options.
12496 	 */
12497 	opt = state->dts_options;
12498 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
12499 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
12500 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
12501 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
12502 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
12503 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
12504 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
12505 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
12506 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
12507 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
12508 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
12509 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
12510 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
12511 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
12512 
12513 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
12514 
12515 	/*
12516 	 * Depending on the user credentials, we set flag bits which alter probe
12517 	 * visibility or the amount of destructiveness allowed.  In the case of
12518 	 * actual anonymous tracing, or the possession of all privileges, all of
12519 	 * the normal checks are bypassed.
12520 	 */
12521 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
12522 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
12523 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
12524 	} else {
12525 		/*
12526 		 * Set up the credentials for this instantiation.  We take a
12527 		 * hold on the credential to prevent it from disappearing on
12528 		 * us; this in turn prevents the zone_t referenced by this
12529 		 * credential from disappearing.  This means that we can
12530 		 * examine the credential and the zone from probe context.
12531 		 */
12532 		crhold(cr);
12533 		state->dts_cred.dcr_cred = cr;
12534 
12535 		/*
12536 		 * CRA_PROC means "we have *some* privilege for dtrace" and
12537 		 * unlocks the use of variables like pid, zonename, etc.
12538 		 */
12539 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
12540 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12541 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
12542 		}
12543 
12544 		/*
12545 		 * dtrace_user allows use of syscall and profile providers.
12546 		 * If the user also has proc_owner and/or proc_zone, we
12547 		 * extend the scope to include additional visibility and
12548 		 * destructive power.
12549 		 */
12550 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
12551 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
12552 				state->dts_cred.dcr_visible |=
12553 				    DTRACE_CRV_ALLPROC;
12554 
12555 				state->dts_cred.dcr_action |=
12556 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12557 			}
12558 
12559 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
12560 				state->dts_cred.dcr_visible |=
12561 				    DTRACE_CRV_ALLZONE;
12562 
12563 				state->dts_cred.dcr_action |=
12564 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12565 			}
12566 
12567 			/*
12568 			 * If we have all privs in whatever zone this is,
12569 			 * we can do destructive things to processes which
12570 			 * have altered credentials.
12571 			 */
12572 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12573 			    cr->cr_zone->zone_privset)) {
12574 				state->dts_cred.dcr_action |=
12575 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12576 			}
12577 		}
12578 
12579 		/*
12580 		 * Holding the dtrace_kernel privilege also implies that
12581 		 * the user has the dtrace_user privilege from a visibility
12582 		 * perspective.  But without further privileges, some
12583 		 * destructive actions are not available.
12584 		 */
12585 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
12586 			/*
12587 			 * Make all probes in all zones visible.  However,
12588 			 * this doesn't mean that all actions become available
12589 			 * to all zones.
12590 			 */
12591 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
12592 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
12593 
12594 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
12595 			    DTRACE_CRA_PROC;
12596 			/*
12597 			 * Holding proc_owner means that destructive actions
12598 			 * for *this* zone are allowed.
12599 			 */
12600 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12601 				state->dts_cred.dcr_action |=
12602 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12603 
12604 			/*
12605 			 * Holding proc_zone means that destructive actions
12606 			 * for this user/group ID in all zones is allowed.
12607 			 */
12608 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12609 				state->dts_cred.dcr_action |=
12610 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12611 
12612 			/*
12613 			 * If we have all privs in whatever zone this is,
12614 			 * we can do destructive things to processes which
12615 			 * have altered credentials.
12616 			 */
12617 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12618 			    cr->cr_zone->zone_privset)) {
12619 				state->dts_cred.dcr_action |=
12620 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12621 			}
12622 		}
12623 
12624 		/*
12625 		 * Holding the dtrace_proc privilege gives control over fasttrap
12626 		 * and pid providers.  We need to grant wider destructive
12627 		 * privileges in the event that the user has proc_owner and/or
12628 		 * proc_zone.
12629 		 */
12630 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12631 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12632 				state->dts_cred.dcr_action |=
12633 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12634 
12635 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12636 				state->dts_cred.dcr_action |=
12637 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12638 		}
12639 	}
12640 
12641 	return (state);
12642 }
12643 
12644 static int
12645 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
12646 {
12647 	dtrace_optval_t *opt = state->dts_options, size;
12648 	processorid_t cpu;
12649 	int flags = 0, rval, factor, divisor = 1;
12650 
12651 	ASSERT(MUTEX_HELD(&dtrace_lock));
12652 	ASSERT(MUTEX_HELD(&cpu_lock));
12653 	ASSERT(which < DTRACEOPT_MAX);
12654 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
12655 	    (state == dtrace_anon.dta_state &&
12656 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
12657 
12658 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
12659 		return (0);
12660 
12661 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
12662 		cpu = opt[DTRACEOPT_CPU];
12663 
12664 	if (which == DTRACEOPT_SPECSIZE)
12665 		flags |= DTRACEBUF_NOSWITCH;
12666 
12667 	if (which == DTRACEOPT_BUFSIZE) {
12668 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
12669 			flags |= DTRACEBUF_RING;
12670 
12671 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
12672 			flags |= DTRACEBUF_FILL;
12673 
12674 		if (state != dtrace_anon.dta_state ||
12675 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
12676 			flags |= DTRACEBUF_INACTIVE;
12677 	}
12678 
12679 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
12680 		/*
12681 		 * The size must be 8-byte aligned.  If the size is not 8-byte
12682 		 * aligned, drop it down by the difference.
12683 		 */
12684 		if (size & (sizeof (uint64_t) - 1))
12685 			size -= size & (sizeof (uint64_t) - 1);
12686 
12687 		if (size < state->dts_reserve) {
12688 			/*
12689 			 * Buffers always must be large enough to accommodate
12690 			 * their prereserved space.  We return E2BIG instead
12691 			 * of ENOMEM in this case to allow for user-level
12692 			 * software to differentiate the cases.
12693 			 */
12694 			return (E2BIG);
12695 		}
12696 
12697 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
12698 
12699 		if (rval != ENOMEM) {
12700 			opt[which] = size;
12701 			return (rval);
12702 		}
12703 
12704 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12705 			return (rval);
12706 
12707 		for (divisor = 2; divisor < factor; divisor <<= 1)
12708 			continue;
12709 	}
12710 
12711 	return (ENOMEM);
12712 }
12713 
12714 static int
12715 dtrace_state_buffers(dtrace_state_t *state)
12716 {
12717 	dtrace_speculation_t *spec = state->dts_speculations;
12718 	int rval, i;
12719 
12720 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
12721 	    DTRACEOPT_BUFSIZE)) != 0)
12722 		return (rval);
12723 
12724 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
12725 	    DTRACEOPT_AGGSIZE)) != 0)
12726 		return (rval);
12727 
12728 	for (i = 0; i < state->dts_nspeculations; i++) {
12729 		if ((rval = dtrace_state_buffer(state,
12730 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
12731 			return (rval);
12732 	}
12733 
12734 	return (0);
12735 }
12736 
12737 static void
12738 dtrace_state_prereserve(dtrace_state_t *state)
12739 {
12740 	dtrace_ecb_t *ecb;
12741 	dtrace_probe_t *probe;
12742 
12743 	state->dts_reserve = 0;
12744 
12745 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
12746 		return;
12747 
12748 	/*
12749 	 * If our buffer policy is a "fill" buffer policy, we need to set the
12750 	 * prereserved space to be the space required by the END probes.
12751 	 */
12752 	probe = dtrace_probes[dtrace_probeid_end - 1];
12753 	ASSERT(probe != NULL);
12754 
12755 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
12756 		if (ecb->dte_state != state)
12757 			continue;
12758 
12759 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
12760 	}
12761 }
12762 
12763 static int
12764 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
12765 {
12766 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
12767 	dtrace_speculation_t *spec;
12768 	dtrace_buffer_t *buf;
12769 	cyc_handler_t hdlr;
12770 	cyc_time_t when;
12771 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12772 	dtrace_icookie_t cookie;
12773 
12774 	mutex_enter(&cpu_lock);
12775 	mutex_enter(&dtrace_lock);
12776 
12777 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
12778 		rval = EBUSY;
12779 		goto out;
12780 	}
12781 
12782 	/*
12783 	 * Before we can perform any checks, we must prime all of the
12784 	 * retained enablings that correspond to this state.
12785 	 */
12786 	dtrace_enabling_prime(state);
12787 
12788 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
12789 		rval = EACCES;
12790 		goto out;
12791 	}
12792 
12793 	dtrace_state_prereserve(state);
12794 
12795 	/*
12796 	 * Now we want to do is try to allocate our speculations.
12797 	 * We do not automatically resize the number of speculations; if
12798 	 * this fails, we will fail the operation.
12799 	 */
12800 	nspec = opt[DTRACEOPT_NSPEC];
12801 	ASSERT(nspec != DTRACEOPT_UNSET);
12802 
12803 	if (nspec > INT_MAX) {
12804 		rval = ENOMEM;
12805 		goto out;
12806 	}
12807 
12808 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
12809 	    KM_NOSLEEP | KM_NORMALPRI);
12810 
12811 	if (spec == NULL) {
12812 		rval = ENOMEM;
12813 		goto out;
12814 	}
12815 
12816 	state->dts_speculations = spec;
12817 	state->dts_nspeculations = (int)nspec;
12818 
12819 	for (i = 0; i < nspec; i++) {
12820 		if ((buf = kmem_zalloc(bufsize,
12821 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
12822 			rval = ENOMEM;
12823 			goto err;
12824 		}
12825 
12826 		spec[i].dtsp_buffer = buf;
12827 	}
12828 
12829 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
12830 		if (dtrace_anon.dta_state == NULL) {
12831 			rval = ENOENT;
12832 			goto out;
12833 		}
12834 
12835 		if (state->dts_necbs != 0) {
12836 			rval = EALREADY;
12837 			goto out;
12838 		}
12839 
12840 		state->dts_anon = dtrace_anon_grab();
12841 		ASSERT(state->dts_anon != NULL);
12842 		state = state->dts_anon;
12843 
12844 		/*
12845 		 * We want "grabanon" to be set in the grabbed state, so we'll
12846 		 * copy that option value from the grabbing state into the
12847 		 * grabbed state.
12848 		 */
12849 		state->dts_options[DTRACEOPT_GRABANON] =
12850 		    opt[DTRACEOPT_GRABANON];
12851 
12852 		*cpu = dtrace_anon.dta_beganon;
12853 
12854 		/*
12855 		 * If the anonymous state is active (as it almost certainly
12856 		 * is if the anonymous enabling ultimately matched anything),
12857 		 * we don't allow any further option processing -- but we
12858 		 * don't return failure.
12859 		 */
12860 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12861 			goto out;
12862 	}
12863 
12864 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
12865 	    opt[DTRACEOPT_AGGSIZE] != 0) {
12866 		if (state->dts_aggregations == NULL) {
12867 			/*
12868 			 * We're not going to create an aggregation buffer
12869 			 * because we don't have any ECBs that contain
12870 			 * aggregations -- set this option to 0.
12871 			 */
12872 			opt[DTRACEOPT_AGGSIZE] = 0;
12873 		} else {
12874 			/*
12875 			 * If we have an aggregation buffer, we must also have
12876 			 * a buffer to use as scratch.
12877 			 */
12878 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
12879 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
12880 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
12881 			}
12882 		}
12883 	}
12884 
12885 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
12886 	    opt[DTRACEOPT_SPECSIZE] != 0) {
12887 		if (!state->dts_speculates) {
12888 			/*
12889 			 * We're not going to create speculation buffers
12890 			 * because we don't have any ECBs that actually
12891 			 * speculate -- set the speculation size to 0.
12892 			 */
12893 			opt[DTRACEOPT_SPECSIZE] = 0;
12894 		}
12895 	}
12896 
12897 	/*
12898 	 * The bare minimum size for any buffer that we're actually going to
12899 	 * do anything to is sizeof (uint64_t).
12900 	 */
12901 	sz = sizeof (uint64_t);
12902 
12903 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
12904 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
12905 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
12906 		/*
12907 		 * A buffer size has been explicitly set to 0 (or to a size
12908 		 * that will be adjusted to 0) and we need the space -- we
12909 		 * need to return failure.  We return ENOSPC to differentiate
12910 		 * it from failing to allocate a buffer due to failure to meet
12911 		 * the reserve (for which we return E2BIG).
12912 		 */
12913 		rval = ENOSPC;
12914 		goto out;
12915 	}
12916 
12917 	if ((rval = dtrace_state_buffers(state)) != 0)
12918 		goto err;
12919 
12920 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
12921 		sz = dtrace_dstate_defsize;
12922 
12923 	do {
12924 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
12925 
12926 		if (rval == 0)
12927 			break;
12928 
12929 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12930 			goto err;
12931 	} while (sz >>= 1);
12932 
12933 	opt[DTRACEOPT_DYNVARSIZE] = sz;
12934 
12935 	if (rval != 0)
12936 		goto err;
12937 
12938 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
12939 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
12940 
12941 	if (opt[DTRACEOPT_CLEANRATE] == 0)
12942 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12943 
12944 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
12945 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
12946 
12947 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
12948 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12949 
12950 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
12951 	hdlr.cyh_arg = state;
12952 	hdlr.cyh_level = CY_LOW_LEVEL;
12953 
12954 	when.cyt_when = 0;
12955 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
12956 
12957 	state->dts_cleaner = cyclic_add(&hdlr, &when);
12958 
12959 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
12960 	hdlr.cyh_arg = state;
12961 	hdlr.cyh_level = CY_LOW_LEVEL;
12962 
12963 	when.cyt_when = 0;
12964 	when.cyt_interval = dtrace_deadman_interval;
12965 
12966 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
12967 	state->dts_deadman = cyclic_add(&hdlr, &when);
12968 
12969 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
12970 
12971 	/*
12972 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
12973 	 * interrupts here both to record the CPU on which we fired the BEGIN
12974 	 * probe (the data from this CPU will be processed first at user
12975 	 * level) and to manually activate the buffer for this CPU.
12976 	 */
12977 	cookie = dtrace_interrupt_disable();
12978 	*cpu = CPU->cpu_id;
12979 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
12980 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12981 
12982 	dtrace_probe(dtrace_probeid_begin,
12983 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
12984 	dtrace_interrupt_enable(cookie);
12985 	/*
12986 	 * We may have had an exit action from a BEGIN probe; only change our
12987 	 * state to ACTIVE if we're still in WARMUP.
12988 	 */
12989 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
12990 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
12991 
12992 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
12993 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
12994 
12995 	/*
12996 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
12997 	 * want each CPU to transition its principal buffer out of the
12998 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
12999 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13000 	 * atomically transition from processing none of a state's ECBs to
13001 	 * processing all of them.
13002 	 */
13003 	dtrace_xcall(DTRACE_CPUALL,
13004 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
13005 	goto out;
13006 
13007 err:
13008 	dtrace_buffer_free(state->dts_buffer);
13009 	dtrace_buffer_free(state->dts_aggbuffer);
13010 
13011 	if ((nspec = state->dts_nspeculations) == 0) {
13012 		ASSERT(state->dts_speculations == NULL);
13013 		goto out;
13014 	}
13015 
13016 	spec = state->dts_speculations;
13017 	ASSERT(spec != NULL);
13018 
13019 	for (i = 0; i < state->dts_nspeculations; i++) {
13020 		if ((buf = spec[i].dtsp_buffer) == NULL)
13021 			break;
13022 
13023 		dtrace_buffer_free(buf);
13024 		kmem_free(buf, bufsize);
13025 	}
13026 
13027 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13028 	state->dts_nspeculations = 0;
13029 	state->dts_speculations = NULL;
13030 
13031 out:
13032 	mutex_exit(&dtrace_lock);
13033 	mutex_exit(&cpu_lock);
13034 
13035 	return (rval);
13036 }
13037 
13038 static int
13039 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13040 {
13041 	dtrace_icookie_t cookie;
13042 
13043 	ASSERT(MUTEX_HELD(&dtrace_lock));
13044 
13045 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13046 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13047 		return (EINVAL);
13048 
13049 	/*
13050 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13051 	 * to be sure that every CPU has seen it.  See below for the details
13052 	 * on why this is done.
13053 	 */
13054 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13055 	dtrace_sync();
13056 
13057 	/*
13058 	 * By this point, it is impossible for any CPU to be still processing
13059 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
13060 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13061 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
13062 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13063 	 * iff we're in the END probe.
13064 	 */
13065 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13066 	dtrace_sync();
13067 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13068 
13069 	/*
13070 	 * Finally, we can release the reserve and call the END probe.  We
13071 	 * disable interrupts across calling the END probe to allow us to
13072 	 * return the CPU on which we actually called the END probe.  This
13073 	 * allows user-land to be sure that this CPU's principal buffer is
13074 	 * processed last.
13075 	 */
13076 	state->dts_reserve = 0;
13077 
13078 	cookie = dtrace_interrupt_disable();
13079 	*cpu = CPU->cpu_id;
13080 	dtrace_probe(dtrace_probeid_end,
13081 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13082 	dtrace_interrupt_enable(cookie);
13083 
13084 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13085 	dtrace_sync();
13086 
13087 	return (0);
13088 }
13089 
13090 static int
13091 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13092     dtrace_optval_t val)
13093 {
13094 	ASSERT(MUTEX_HELD(&dtrace_lock));
13095 
13096 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13097 		return (EBUSY);
13098 
13099 	if (option >= DTRACEOPT_MAX)
13100 		return (EINVAL);
13101 
13102 	if (option != DTRACEOPT_CPU && val < 0)
13103 		return (EINVAL);
13104 
13105 	switch (option) {
13106 	case DTRACEOPT_DESTRUCTIVE:
13107 		if (dtrace_destructive_disallow)
13108 			return (EACCES);
13109 
13110 		state->dts_cred.dcr_destructive = 1;
13111 		break;
13112 
13113 	case DTRACEOPT_BUFSIZE:
13114 	case DTRACEOPT_DYNVARSIZE:
13115 	case DTRACEOPT_AGGSIZE:
13116 	case DTRACEOPT_SPECSIZE:
13117 	case DTRACEOPT_STRSIZE:
13118 		if (val < 0)
13119 			return (EINVAL);
13120 
13121 		if (val >= LONG_MAX) {
13122 			/*
13123 			 * If this is an otherwise negative value, set it to
13124 			 * the highest multiple of 128m less than LONG_MAX.
13125 			 * Technically, we're adjusting the size without
13126 			 * regard to the buffer resizing policy, but in fact,
13127 			 * this has no effect -- if we set the buffer size to
13128 			 * ~LONG_MAX and the buffer policy is ultimately set to
13129 			 * be "manual", the buffer allocation is guaranteed to
13130 			 * fail, if only because the allocation requires two
13131 			 * buffers.  (We set the the size to the highest
13132 			 * multiple of 128m because it ensures that the size
13133 			 * will remain a multiple of a megabyte when
13134 			 * repeatedly halved -- all the way down to 15m.)
13135 			 */
13136 			val = LONG_MAX - (1 << 27) + 1;
13137 		}
13138 	}
13139 
13140 	state->dts_options[option] = val;
13141 
13142 	return (0);
13143 }
13144 
13145 static void
13146 dtrace_state_destroy(dtrace_state_t *state)
13147 {
13148 	dtrace_ecb_t *ecb;
13149 	dtrace_vstate_t *vstate = &state->dts_vstate;
13150 	minor_t minor = getminor(state->dts_dev);
13151 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13152 	dtrace_speculation_t *spec = state->dts_speculations;
13153 	int nspec = state->dts_nspeculations;
13154 	uint32_t match;
13155 
13156 	ASSERT(MUTEX_HELD(&dtrace_lock));
13157 	ASSERT(MUTEX_HELD(&cpu_lock));
13158 
13159 	/*
13160 	 * First, retract any retained enablings for this state.
13161 	 */
13162 	dtrace_enabling_retract(state);
13163 	ASSERT(state->dts_nretained == 0);
13164 
13165 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13166 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13167 		/*
13168 		 * We have managed to come into dtrace_state_destroy() on a
13169 		 * hot enabling -- almost certainly because of a disorderly
13170 		 * shutdown of a consumer.  (That is, a consumer that is
13171 		 * exiting without having called dtrace_stop().) In this case,
13172 		 * we're going to set our activity to be KILLED, and then
13173 		 * issue a sync to be sure that everyone is out of probe
13174 		 * context before we start blowing away ECBs.
13175 		 */
13176 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
13177 		dtrace_sync();
13178 	}
13179 
13180 	/*
13181 	 * Release the credential hold we took in dtrace_state_create().
13182 	 */
13183 	if (state->dts_cred.dcr_cred != NULL)
13184 		crfree(state->dts_cred.dcr_cred);
13185 
13186 	/*
13187 	 * Now we can safely disable and destroy any enabled probes.  Because
13188 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13189 	 * (especially if they're all enabled), we take two passes through the
13190 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13191 	 * in the second we disable whatever is left over.
13192 	 */
13193 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13194 		for (i = 0; i < state->dts_necbs; i++) {
13195 			if ((ecb = state->dts_ecbs[i]) == NULL)
13196 				continue;
13197 
13198 			if (match && ecb->dte_probe != NULL) {
13199 				dtrace_probe_t *probe = ecb->dte_probe;
13200 				dtrace_provider_t *prov = probe->dtpr_provider;
13201 
13202 				if (!(prov->dtpv_priv.dtpp_flags & match))
13203 					continue;
13204 			}
13205 
13206 			dtrace_ecb_disable(ecb);
13207 			dtrace_ecb_destroy(ecb);
13208 		}
13209 
13210 		if (!match)
13211 			break;
13212 	}
13213 
13214 	/*
13215 	 * Before we free the buffers, perform one more sync to assure that
13216 	 * every CPU is out of probe context.
13217 	 */
13218 	dtrace_sync();
13219 
13220 	dtrace_buffer_free(state->dts_buffer);
13221 	dtrace_buffer_free(state->dts_aggbuffer);
13222 
13223 	for (i = 0; i < nspec; i++)
13224 		dtrace_buffer_free(spec[i].dtsp_buffer);
13225 
13226 	if (state->dts_cleaner != CYCLIC_NONE)
13227 		cyclic_remove(state->dts_cleaner);
13228 
13229 	if (state->dts_deadman != CYCLIC_NONE)
13230 		cyclic_remove(state->dts_deadman);
13231 
13232 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
13233 	dtrace_vstate_fini(vstate);
13234 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
13235 
13236 	if (state->dts_aggregations != NULL) {
13237 #ifdef DEBUG
13238 		for (i = 0; i < state->dts_naggregations; i++)
13239 			ASSERT(state->dts_aggregations[i] == NULL);
13240 #endif
13241 		ASSERT(state->dts_naggregations > 0);
13242 		kmem_free(state->dts_aggregations,
13243 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
13244 	}
13245 
13246 	kmem_free(state->dts_buffer, bufsize);
13247 	kmem_free(state->dts_aggbuffer, bufsize);
13248 
13249 	for (i = 0; i < nspec; i++)
13250 		kmem_free(spec[i].dtsp_buffer, bufsize);
13251 
13252 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13253 
13254 	dtrace_format_destroy(state);
13255 
13256 	vmem_destroy(state->dts_aggid_arena);
13257 	ddi_soft_state_free(dtrace_softstate, minor);
13258 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13259 }
13260 
13261 /*
13262  * DTrace Anonymous Enabling Functions
13263  */
13264 static dtrace_state_t *
13265 dtrace_anon_grab(void)
13266 {
13267 	dtrace_state_t *state;
13268 
13269 	ASSERT(MUTEX_HELD(&dtrace_lock));
13270 
13271 	if ((state = dtrace_anon.dta_state) == NULL) {
13272 		ASSERT(dtrace_anon.dta_enabling == NULL);
13273 		return (NULL);
13274 	}
13275 
13276 	ASSERT(dtrace_anon.dta_enabling != NULL);
13277 	ASSERT(dtrace_retained != NULL);
13278 
13279 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
13280 	dtrace_anon.dta_enabling = NULL;
13281 	dtrace_anon.dta_state = NULL;
13282 
13283 	return (state);
13284 }
13285 
13286 static void
13287 dtrace_anon_property(void)
13288 {
13289 	int i, rv;
13290 	dtrace_state_t *state;
13291 	dof_hdr_t *dof;
13292 	char c[32];		/* enough for "dof-data-" + digits */
13293 
13294 	ASSERT(MUTEX_HELD(&dtrace_lock));
13295 	ASSERT(MUTEX_HELD(&cpu_lock));
13296 
13297 	for (i = 0; ; i++) {
13298 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
13299 
13300 		dtrace_err_verbose = 1;
13301 
13302 		if ((dof = dtrace_dof_property(c)) == NULL) {
13303 			dtrace_err_verbose = 0;
13304 			break;
13305 		}
13306 
13307 		/*
13308 		 * We want to create anonymous state, so we need to transition
13309 		 * the kernel debugger to indicate that DTrace is active.  If
13310 		 * this fails (e.g. because the debugger has modified text in
13311 		 * some way), we won't continue with the processing.
13312 		 */
13313 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
13314 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
13315 			    "enabling ignored.");
13316 			dtrace_dof_destroy(dof);
13317 			break;
13318 		}
13319 
13320 		/*
13321 		 * If we haven't allocated an anonymous state, we'll do so now.
13322 		 */
13323 		if ((state = dtrace_anon.dta_state) == NULL) {
13324 			state = dtrace_state_create(NULL, NULL);
13325 			dtrace_anon.dta_state = state;
13326 
13327 			if (state == NULL) {
13328 				/*
13329 				 * This basically shouldn't happen:  the only
13330 				 * failure mode from dtrace_state_create() is a
13331 				 * failure of ddi_soft_state_zalloc() that
13332 				 * itself should never happen.  Still, the
13333 				 * interface allows for a failure mode, and
13334 				 * we want to fail as gracefully as possible:
13335 				 * we'll emit an error message and cease
13336 				 * processing anonymous state in this case.
13337 				 */
13338 				cmn_err(CE_WARN, "failed to create "
13339 				    "anonymous state");
13340 				dtrace_dof_destroy(dof);
13341 				break;
13342 			}
13343 		}
13344 
13345 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
13346 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
13347 
13348 		if (rv == 0)
13349 			rv = dtrace_dof_options(dof, state);
13350 
13351 		dtrace_err_verbose = 0;
13352 		dtrace_dof_destroy(dof);
13353 
13354 		if (rv != 0) {
13355 			/*
13356 			 * This is malformed DOF; chuck any anonymous state
13357 			 * that we created.
13358 			 */
13359 			ASSERT(dtrace_anon.dta_enabling == NULL);
13360 			dtrace_state_destroy(state);
13361 			dtrace_anon.dta_state = NULL;
13362 			break;
13363 		}
13364 
13365 		ASSERT(dtrace_anon.dta_enabling != NULL);
13366 	}
13367 
13368 	if (dtrace_anon.dta_enabling != NULL) {
13369 		int rval;
13370 
13371 		/*
13372 		 * dtrace_enabling_retain() can only fail because we are
13373 		 * trying to retain more enablings than are allowed -- but
13374 		 * we only have one anonymous enabling, and we are guaranteed
13375 		 * to be allowed at least one retained enabling; we assert
13376 		 * that dtrace_enabling_retain() returns success.
13377 		 */
13378 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
13379 		ASSERT(rval == 0);
13380 
13381 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
13382 	}
13383 }
13384 
13385 /*
13386  * DTrace Helper Functions
13387  */
13388 static void
13389 dtrace_helper_trace(dtrace_helper_action_t *helper,
13390     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
13391 {
13392 	uint32_t size, next, nnext, i;
13393 	dtrace_helptrace_t *ent;
13394 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13395 
13396 	if (!dtrace_helptrace_enabled)
13397 		return;
13398 
13399 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
13400 
13401 	/*
13402 	 * What would a tracing framework be without its own tracing
13403 	 * framework?  (Well, a hell of a lot simpler, for starters...)
13404 	 */
13405 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
13406 	    sizeof (uint64_t) - sizeof (uint64_t);
13407 
13408 	/*
13409 	 * Iterate until we can allocate a slot in the trace buffer.
13410 	 */
13411 	do {
13412 		next = dtrace_helptrace_next;
13413 
13414 		if (next + size < dtrace_helptrace_bufsize) {
13415 			nnext = next + size;
13416 		} else {
13417 			nnext = size;
13418 		}
13419 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
13420 
13421 	/*
13422 	 * We have our slot; fill it in.
13423 	 */
13424 	if (nnext == size)
13425 		next = 0;
13426 
13427 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
13428 	ent->dtht_helper = helper;
13429 	ent->dtht_where = where;
13430 	ent->dtht_nlocals = vstate->dtvs_nlocals;
13431 
13432 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
13433 	    mstate->dtms_fltoffs : -1;
13434 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
13435 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
13436 
13437 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
13438 		dtrace_statvar_t *svar;
13439 
13440 		if ((svar = vstate->dtvs_locals[i]) == NULL)
13441 			continue;
13442 
13443 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
13444 		ent->dtht_locals[i] =
13445 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
13446 	}
13447 }
13448 
13449 static uint64_t
13450 dtrace_helper(int which, dtrace_mstate_t *mstate,
13451     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
13452 {
13453 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13454 	uint64_t sarg0 = mstate->dtms_arg[0];
13455 	uint64_t sarg1 = mstate->dtms_arg[1];
13456 	uint64_t rval;
13457 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
13458 	dtrace_helper_action_t *helper;
13459 	dtrace_vstate_t *vstate;
13460 	dtrace_difo_t *pred;
13461 	int i, trace = dtrace_helptrace_enabled;
13462 
13463 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
13464 
13465 	if (helpers == NULL)
13466 		return (0);
13467 
13468 	if ((helper = helpers->dthps_actions[which]) == NULL)
13469 		return (0);
13470 
13471 	vstate = &helpers->dthps_vstate;
13472 	mstate->dtms_arg[0] = arg0;
13473 	mstate->dtms_arg[1] = arg1;
13474 
13475 	/*
13476 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
13477 	 * we'll call the corresponding actions.  Note that the below calls
13478 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
13479 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
13480 	 * the stored DIF offset with its own (which is the desired behavior).
13481 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
13482 	 * from machine state; this is okay, too.
13483 	 */
13484 	for (; helper != NULL; helper = helper->dtha_next) {
13485 		if ((pred = helper->dtha_predicate) != NULL) {
13486 			if (trace)
13487 				dtrace_helper_trace(helper, mstate, vstate, 0);
13488 
13489 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
13490 				goto next;
13491 
13492 			if (*flags & CPU_DTRACE_FAULT)
13493 				goto err;
13494 		}
13495 
13496 		for (i = 0; i < helper->dtha_nactions; i++) {
13497 			if (trace)
13498 				dtrace_helper_trace(helper,
13499 				    mstate, vstate, i + 1);
13500 
13501 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
13502 			    mstate, vstate, state);
13503 
13504 			if (*flags & CPU_DTRACE_FAULT)
13505 				goto err;
13506 		}
13507 
13508 next:
13509 		if (trace)
13510 			dtrace_helper_trace(helper, mstate, vstate,
13511 			    DTRACE_HELPTRACE_NEXT);
13512 	}
13513 
13514 	if (trace)
13515 		dtrace_helper_trace(helper, mstate, vstate,
13516 		    DTRACE_HELPTRACE_DONE);
13517 
13518 	/*
13519 	 * Restore the arg0 that we saved upon entry.
13520 	 */
13521 	mstate->dtms_arg[0] = sarg0;
13522 	mstate->dtms_arg[1] = sarg1;
13523 
13524 	return (rval);
13525 
13526 err:
13527 	if (trace)
13528 		dtrace_helper_trace(helper, mstate, vstate,
13529 		    DTRACE_HELPTRACE_ERR);
13530 
13531 	/*
13532 	 * Restore the arg0 that we saved upon entry.
13533 	 */
13534 	mstate->dtms_arg[0] = sarg0;
13535 	mstate->dtms_arg[1] = sarg1;
13536 
13537 	return (NULL);
13538 }
13539 
13540 static void
13541 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
13542     dtrace_vstate_t *vstate)
13543 {
13544 	int i;
13545 
13546 	if (helper->dtha_predicate != NULL)
13547 		dtrace_difo_release(helper->dtha_predicate, vstate);
13548 
13549 	for (i = 0; i < helper->dtha_nactions; i++) {
13550 		ASSERT(helper->dtha_actions[i] != NULL);
13551 		dtrace_difo_release(helper->dtha_actions[i], vstate);
13552 	}
13553 
13554 	kmem_free(helper->dtha_actions,
13555 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
13556 	kmem_free(helper, sizeof (dtrace_helper_action_t));
13557 }
13558 
13559 static int
13560 dtrace_helper_destroygen(int gen)
13561 {
13562 	proc_t *p = curproc;
13563 	dtrace_helpers_t *help = p->p_dtrace_helpers;
13564 	dtrace_vstate_t *vstate;
13565 	int i;
13566 
13567 	ASSERT(MUTEX_HELD(&dtrace_lock));
13568 
13569 	if (help == NULL || gen > help->dthps_generation)
13570 		return (EINVAL);
13571 
13572 	vstate = &help->dthps_vstate;
13573 
13574 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13575 		dtrace_helper_action_t *last = NULL, *h, *next;
13576 
13577 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13578 			next = h->dtha_next;
13579 
13580 			if (h->dtha_generation == gen) {
13581 				if (last != NULL) {
13582 					last->dtha_next = next;
13583 				} else {
13584 					help->dthps_actions[i] = next;
13585 				}
13586 
13587 				dtrace_helper_action_destroy(h, vstate);
13588 			} else {
13589 				last = h;
13590 			}
13591 		}
13592 	}
13593 
13594 	/*
13595 	 * Interate until we've cleared out all helper providers with the
13596 	 * given generation number.
13597 	 */
13598 	for (;;) {
13599 		dtrace_helper_provider_t *prov;
13600 
13601 		/*
13602 		 * Look for a helper provider with the right generation. We
13603 		 * have to start back at the beginning of the list each time
13604 		 * because we drop dtrace_lock. It's unlikely that we'll make
13605 		 * more than two passes.
13606 		 */
13607 		for (i = 0; i < help->dthps_nprovs; i++) {
13608 			prov = help->dthps_provs[i];
13609 
13610 			if (prov->dthp_generation == gen)
13611 				break;
13612 		}
13613 
13614 		/*
13615 		 * If there were no matches, we're done.
13616 		 */
13617 		if (i == help->dthps_nprovs)
13618 			break;
13619 
13620 		/*
13621 		 * Move the last helper provider into this slot.
13622 		 */
13623 		help->dthps_nprovs--;
13624 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
13625 		help->dthps_provs[help->dthps_nprovs] = NULL;
13626 
13627 		mutex_exit(&dtrace_lock);
13628 
13629 		/*
13630 		 * If we have a meta provider, remove this helper provider.
13631 		 */
13632 		mutex_enter(&dtrace_meta_lock);
13633 		if (dtrace_meta_pid != NULL) {
13634 			ASSERT(dtrace_deferred_pid == NULL);
13635 			dtrace_helper_provider_remove(&prov->dthp_prov,
13636 			    p->p_pid);
13637 		}
13638 		mutex_exit(&dtrace_meta_lock);
13639 
13640 		dtrace_helper_provider_destroy(prov);
13641 
13642 		mutex_enter(&dtrace_lock);
13643 	}
13644 
13645 	return (0);
13646 }
13647 
13648 static int
13649 dtrace_helper_validate(dtrace_helper_action_t *helper)
13650 {
13651 	int err = 0, i;
13652 	dtrace_difo_t *dp;
13653 
13654 	if ((dp = helper->dtha_predicate) != NULL)
13655 		err += dtrace_difo_validate_helper(dp);
13656 
13657 	for (i = 0; i < helper->dtha_nactions; i++)
13658 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
13659 
13660 	return (err == 0);
13661 }
13662 
13663 static int
13664 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
13665 {
13666 	dtrace_helpers_t *help;
13667 	dtrace_helper_action_t *helper, *last;
13668 	dtrace_actdesc_t *act;
13669 	dtrace_vstate_t *vstate;
13670 	dtrace_predicate_t *pred;
13671 	int count = 0, nactions = 0, i;
13672 
13673 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
13674 		return (EINVAL);
13675 
13676 	help = curproc->p_dtrace_helpers;
13677 	last = help->dthps_actions[which];
13678 	vstate = &help->dthps_vstate;
13679 
13680 	for (count = 0; last != NULL; last = last->dtha_next) {
13681 		count++;
13682 		if (last->dtha_next == NULL)
13683 			break;
13684 	}
13685 
13686 	/*
13687 	 * If we already have dtrace_helper_actions_max helper actions for this
13688 	 * helper action type, we'll refuse to add a new one.
13689 	 */
13690 	if (count >= dtrace_helper_actions_max)
13691 		return (ENOSPC);
13692 
13693 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
13694 	helper->dtha_generation = help->dthps_generation;
13695 
13696 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
13697 		ASSERT(pred->dtp_difo != NULL);
13698 		dtrace_difo_hold(pred->dtp_difo);
13699 		helper->dtha_predicate = pred->dtp_difo;
13700 	}
13701 
13702 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
13703 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
13704 			goto err;
13705 
13706 		if (act->dtad_difo == NULL)
13707 			goto err;
13708 
13709 		nactions++;
13710 	}
13711 
13712 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
13713 	    (helper->dtha_nactions = nactions), KM_SLEEP);
13714 
13715 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
13716 		dtrace_difo_hold(act->dtad_difo);
13717 		helper->dtha_actions[i++] = act->dtad_difo;
13718 	}
13719 
13720 	if (!dtrace_helper_validate(helper))
13721 		goto err;
13722 
13723 	if (last == NULL) {
13724 		help->dthps_actions[which] = helper;
13725 	} else {
13726 		last->dtha_next = helper;
13727 	}
13728 
13729 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
13730 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
13731 		dtrace_helptrace_next = 0;
13732 	}
13733 
13734 	return (0);
13735 err:
13736 	dtrace_helper_action_destroy(helper, vstate);
13737 	return (EINVAL);
13738 }
13739 
13740 static void
13741 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
13742     dof_helper_t *dofhp)
13743 {
13744 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
13745 
13746 	mutex_enter(&dtrace_meta_lock);
13747 	mutex_enter(&dtrace_lock);
13748 
13749 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
13750 		/*
13751 		 * If the dtrace module is loaded but not attached, or if
13752 		 * there aren't isn't a meta provider registered to deal with
13753 		 * these provider descriptions, we need to postpone creating
13754 		 * the actual providers until later.
13755 		 */
13756 
13757 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
13758 		    dtrace_deferred_pid != help) {
13759 			help->dthps_deferred = 1;
13760 			help->dthps_pid = p->p_pid;
13761 			help->dthps_next = dtrace_deferred_pid;
13762 			help->dthps_prev = NULL;
13763 			if (dtrace_deferred_pid != NULL)
13764 				dtrace_deferred_pid->dthps_prev = help;
13765 			dtrace_deferred_pid = help;
13766 		}
13767 
13768 		mutex_exit(&dtrace_lock);
13769 
13770 	} else if (dofhp != NULL) {
13771 		/*
13772 		 * If the dtrace module is loaded and we have a particular
13773 		 * helper provider description, pass that off to the
13774 		 * meta provider.
13775 		 */
13776 
13777 		mutex_exit(&dtrace_lock);
13778 
13779 		dtrace_helper_provide(dofhp, p->p_pid);
13780 
13781 	} else {
13782 		/*
13783 		 * Otherwise, just pass all the helper provider descriptions
13784 		 * off to the meta provider.
13785 		 */
13786 
13787 		int i;
13788 		mutex_exit(&dtrace_lock);
13789 
13790 		for (i = 0; i < help->dthps_nprovs; i++) {
13791 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
13792 			    p->p_pid);
13793 		}
13794 	}
13795 
13796 	mutex_exit(&dtrace_meta_lock);
13797 }
13798 
13799 static int
13800 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
13801 {
13802 	dtrace_helpers_t *help;
13803 	dtrace_helper_provider_t *hprov, **tmp_provs;
13804 	uint_t tmp_maxprovs, i;
13805 
13806 	ASSERT(MUTEX_HELD(&dtrace_lock));
13807 
13808 	help = curproc->p_dtrace_helpers;
13809 	ASSERT(help != NULL);
13810 
13811 	/*
13812 	 * If we already have dtrace_helper_providers_max helper providers,
13813 	 * we're refuse to add a new one.
13814 	 */
13815 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
13816 		return (ENOSPC);
13817 
13818 	/*
13819 	 * Check to make sure this isn't a duplicate.
13820 	 */
13821 	for (i = 0; i < help->dthps_nprovs; i++) {
13822 		if (dofhp->dofhp_addr ==
13823 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
13824 			return (EALREADY);
13825 	}
13826 
13827 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
13828 	hprov->dthp_prov = *dofhp;
13829 	hprov->dthp_ref = 1;
13830 	hprov->dthp_generation = gen;
13831 
13832 	/*
13833 	 * Allocate a bigger table for helper providers if it's already full.
13834 	 */
13835 	if (help->dthps_maxprovs == help->dthps_nprovs) {
13836 		tmp_maxprovs = help->dthps_maxprovs;
13837 		tmp_provs = help->dthps_provs;
13838 
13839 		if (help->dthps_maxprovs == 0)
13840 			help->dthps_maxprovs = 2;
13841 		else
13842 			help->dthps_maxprovs *= 2;
13843 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
13844 			help->dthps_maxprovs = dtrace_helper_providers_max;
13845 
13846 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
13847 
13848 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
13849 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13850 
13851 		if (tmp_provs != NULL) {
13852 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
13853 			    sizeof (dtrace_helper_provider_t *));
13854 			kmem_free(tmp_provs, tmp_maxprovs *
13855 			    sizeof (dtrace_helper_provider_t *));
13856 		}
13857 	}
13858 
13859 	help->dthps_provs[help->dthps_nprovs] = hprov;
13860 	help->dthps_nprovs++;
13861 
13862 	return (0);
13863 }
13864 
13865 static void
13866 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
13867 {
13868 	mutex_enter(&dtrace_lock);
13869 
13870 	if (--hprov->dthp_ref == 0) {
13871 		dof_hdr_t *dof;
13872 		mutex_exit(&dtrace_lock);
13873 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
13874 		dtrace_dof_destroy(dof);
13875 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
13876 	} else {
13877 		mutex_exit(&dtrace_lock);
13878 	}
13879 }
13880 
13881 static int
13882 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
13883 {
13884 	uintptr_t daddr = (uintptr_t)dof;
13885 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
13886 	dof_provider_t *provider;
13887 	dof_probe_t *probe;
13888 	uint8_t *arg;
13889 	char *strtab, *typestr;
13890 	dof_stridx_t typeidx;
13891 	size_t typesz;
13892 	uint_t nprobes, j, k;
13893 
13894 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
13895 
13896 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
13897 		dtrace_dof_error(dof, "misaligned section offset");
13898 		return (-1);
13899 	}
13900 
13901 	/*
13902 	 * The section needs to be large enough to contain the DOF provider
13903 	 * structure appropriate for the given version.
13904 	 */
13905 	if (sec->dofs_size <
13906 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
13907 	    offsetof(dof_provider_t, dofpv_prenoffs) :
13908 	    sizeof (dof_provider_t))) {
13909 		dtrace_dof_error(dof, "provider section too small");
13910 		return (-1);
13911 	}
13912 
13913 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
13914 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
13915 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
13916 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
13917 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
13918 
13919 	if (str_sec == NULL || prb_sec == NULL ||
13920 	    arg_sec == NULL || off_sec == NULL)
13921 		return (-1);
13922 
13923 	enoff_sec = NULL;
13924 
13925 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13926 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
13927 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
13928 	    provider->dofpv_prenoffs)) == NULL)
13929 		return (-1);
13930 
13931 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
13932 
13933 	if (provider->dofpv_name >= str_sec->dofs_size ||
13934 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
13935 		dtrace_dof_error(dof, "invalid provider name");
13936 		return (-1);
13937 	}
13938 
13939 	if (prb_sec->dofs_entsize == 0 ||
13940 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
13941 		dtrace_dof_error(dof, "invalid entry size");
13942 		return (-1);
13943 	}
13944 
13945 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
13946 		dtrace_dof_error(dof, "misaligned entry size");
13947 		return (-1);
13948 	}
13949 
13950 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
13951 		dtrace_dof_error(dof, "invalid entry size");
13952 		return (-1);
13953 	}
13954 
13955 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
13956 		dtrace_dof_error(dof, "misaligned section offset");
13957 		return (-1);
13958 	}
13959 
13960 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
13961 		dtrace_dof_error(dof, "invalid entry size");
13962 		return (-1);
13963 	}
13964 
13965 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
13966 
13967 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
13968 
13969 	/*
13970 	 * Take a pass through the probes to check for errors.
13971 	 */
13972 	for (j = 0; j < nprobes; j++) {
13973 		probe = (dof_probe_t *)(uintptr_t)(daddr +
13974 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
13975 
13976 		if (probe->dofpr_func >= str_sec->dofs_size) {
13977 			dtrace_dof_error(dof, "invalid function name");
13978 			return (-1);
13979 		}
13980 
13981 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
13982 			dtrace_dof_error(dof, "function name too long");
13983 			return (-1);
13984 		}
13985 
13986 		if (probe->dofpr_name >= str_sec->dofs_size ||
13987 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
13988 			dtrace_dof_error(dof, "invalid probe name");
13989 			return (-1);
13990 		}
13991 
13992 		/*
13993 		 * The offset count must not wrap the index, and the offsets
13994 		 * must also not overflow the section's data.
13995 		 */
13996 		if (probe->dofpr_offidx + probe->dofpr_noffs <
13997 		    probe->dofpr_offidx ||
13998 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
13999 		    off_sec->dofs_entsize > off_sec->dofs_size) {
14000 			dtrace_dof_error(dof, "invalid probe offset");
14001 			return (-1);
14002 		}
14003 
14004 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14005 			/*
14006 			 * If there's no is-enabled offset section, make sure
14007 			 * there aren't any is-enabled offsets. Otherwise
14008 			 * perform the same checks as for probe offsets
14009 			 * (immediately above).
14010 			 */
14011 			if (enoff_sec == NULL) {
14012 				if (probe->dofpr_enoffidx != 0 ||
14013 				    probe->dofpr_nenoffs != 0) {
14014 					dtrace_dof_error(dof, "is-enabled "
14015 					    "offsets with null section");
14016 					return (-1);
14017 				}
14018 			} else if (probe->dofpr_enoffidx +
14019 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14020 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14021 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14022 				dtrace_dof_error(dof, "invalid is-enabled "
14023 				    "offset");
14024 				return (-1);
14025 			}
14026 
14027 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14028 				dtrace_dof_error(dof, "zero probe and "
14029 				    "is-enabled offsets");
14030 				return (-1);
14031 			}
14032 		} else if (probe->dofpr_noffs == 0) {
14033 			dtrace_dof_error(dof, "zero probe offsets");
14034 			return (-1);
14035 		}
14036 
14037 		if (probe->dofpr_argidx + probe->dofpr_xargc <
14038 		    probe->dofpr_argidx ||
14039 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
14040 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
14041 			dtrace_dof_error(dof, "invalid args");
14042 			return (-1);
14043 		}
14044 
14045 		typeidx = probe->dofpr_nargv;
14046 		typestr = strtab + probe->dofpr_nargv;
14047 		for (k = 0; k < probe->dofpr_nargc; k++) {
14048 			if (typeidx >= str_sec->dofs_size) {
14049 				dtrace_dof_error(dof, "bad "
14050 				    "native argument type");
14051 				return (-1);
14052 			}
14053 
14054 			typesz = strlen(typestr) + 1;
14055 			if (typesz > DTRACE_ARGTYPELEN) {
14056 				dtrace_dof_error(dof, "native "
14057 				    "argument type too long");
14058 				return (-1);
14059 			}
14060 			typeidx += typesz;
14061 			typestr += typesz;
14062 		}
14063 
14064 		typeidx = probe->dofpr_xargv;
14065 		typestr = strtab + probe->dofpr_xargv;
14066 		for (k = 0; k < probe->dofpr_xargc; k++) {
14067 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14068 				dtrace_dof_error(dof, "bad "
14069 				    "native argument index");
14070 				return (-1);
14071 			}
14072 
14073 			if (typeidx >= str_sec->dofs_size) {
14074 				dtrace_dof_error(dof, "bad "
14075 				    "translated argument type");
14076 				return (-1);
14077 			}
14078 
14079 			typesz = strlen(typestr) + 1;
14080 			if (typesz > DTRACE_ARGTYPELEN) {
14081 				dtrace_dof_error(dof, "translated argument "
14082 				    "type too long");
14083 				return (-1);
14084 			}
14085 
14086 			typeidx += typesz;
14087 			typestr += typesz;
14088 		}
14089 	}
14090 
14091 	return (0);
14092 }
14093 
14094 static int
14095 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
14096 {
14097 	dtrace_helpers_t *help;
14098 	dtrace_vstate_t *vstate;
14099 	dtrace_enabling_t *enab = NULL;
14100 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14101 	uintptr_t daddr = (uintptr_t)dof;
14102 
14103 	ASSERT(MUTEX_HELD(&dtrace_lock));
14104 
14105 	if ((help = curproc->p_dtrace_helpers) == NULL)
14106 		help = dtrace_helpers_create(curproc);
14107 
14108 	vstate = &help->dthps_vstate;
14109 
14110 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14111 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14112 		dtrace_dof_destroy(dof);
14113 		return (rv);
14114 	}
14115 
14116 	/*
14117 	 * Look for helper providers and validate their descriptions.
14118 	 */
14119 	if (dhp != NULL) {
14120 		for (i = 0; i < dof->dofh_secnum; i++) {
14121 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14122 			    dof->dofh_secoff + i * dof->dofh_secsize);
14123 
14124 			if (sec->dofs_type != DOF_SECT_PROVIDER)
14125 				continue;
14126 
14127 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
14128 				dtrace_enabling_destroy(enab);
14129 				dtrace_dof_destroy(dof);
14130 				return (-1);
14131 			}
14132 
14133 			nprovs++;
14134 		}
14135 	}
14136 
14137 	/*
14138 	 * Now we need to walk through the ECB descriptions in the enabling.
14139 	 */
14140 	for (i = 0; i < enab->dten_ndesc; i++) {
14141 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14142 		dtrace_probedesc_t *desc = &ep->dted_probe;
14143 
14144 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
14145 			continue;
14146 
14147 		if (strcmp(desc->dtpd_mod, "helper") != 0)
14148 			continue;
14149 
14150 		if (strcmp(desc->dtpd_func, "ustack") != 0)
14151 			continue;
14152 
14153 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
14154 		    ep)) != 0) {
14155 			/*
14156 			 * Adding this helper action failed -- we are now going
14157 			 * to rip out the entire generation and return failure.
14158 			 */
14159 			(void) dtrace_helper_destroygen(help->dthps_generation);
14160 			dtrace_enabling_destroy(enab);
14161 			dtrace_dof_destroy(dof);
14162 			return (-1);
14163 		}
14164 
14165 		nhelpers++;
14166 	}
14167 
14168 	if (nhelpers < enab->dten_ndesc)
14169 		dtrace_dof_error(dof, "unmatched helpers");
14170 
14171 	gen = help->dthps_generation++;
14172 	dtrace_enabling_destroy(enab);
14173 
14174 	if (dhp != NULL && nprovs > 0) {
14175 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14176 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
14177 			mutex_exit(&dtrace_lock);
14178 			dtrace_helper_provider_register(curproc, help, dhp);
14179 			mutex_enter(&dtrace_lock);
14180 
14181 			destroy = 0;
14182 		}
14183 	}
14184 
14185 	if (destroy)
14186 		dtrace_dof_destroy(dof);
14187 
14188 	return (gen);
14189 }
14190 
14191 static dtrace_helpers_t *
14192 dtrace_helpers_create(proc_t *p)
14193 {
14194 	dtrace_helpers_t *help;
14195 
14196 	ASSERT(MUTEX_HELD(&dtrace_lock));
14197 	ASSERT(p->p_dtrace_helpers == NULL);
14198 
14199 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
14200 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
14201 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
14202 
14203 	p->p_dtrace_helpers = help;
14204 	dtrace_helpers++;
14205 
14206 	return (help);
14207 }
14208 
14209 static void
14210 dtrace_helpers_destroy(void)
14211 {
14212 	dtrace_helpers_t *help;
14213 	dtrace_vstate_t *vstate;
14214 	proc_t *p = curproc;
14215 	int i;
14216 
14217 	mutex_enter(&dtrace_lock);
14218 
14219 	ASSERT(p->p_dtrace_helpers != NULL);
14220 	ASSERT(dtrace_helpers > 0);
14221 
14222 	help = p->p_dtrace_helpers;
14223 	vstate = &help->dthps_vstate;
14224 
14225 	/*
14226 	 * We're now going to lose the help from this process.
14227 	 */
14228 	p->p_dtrace_helpers = NULL;
14229 	dtrace_sync();
14230 
14231 	/*
14232 	 * Destory the helper actions.
14233 	 */
14234 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14235 		dtrace_helper_action_t *h, *next;
14236 
14237 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
14238 			next = h->dtha_next;
14239 			dtrace_helper_action_destroy(h, vstate);
14240 			h = next;
14241 		}
14242 	}
14243 
14244 	mutex_exit(&dtrace_lock);
14245 
14246 	/*
14247 	 * Destroy the helper providers.
14248 	 */
14249 	if (help->dthps_maxprovs > 0) {
14250 		mutex_enter(&dtrace_meta_lock);
14251 		if (dtrace_meta_pid != NULL) {
14252 			ASSERT(dtrace_deferred_pid == NULL);
14253 
14254 			for (i = 0; i < help->dthps_nprovs; i++) {
14255 				dtrace_helper_provider_remove(
14256 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
14257 			}
14258 		} else {
14259 			mutex_enter(&dtrace_lock);
14260 			ASSERT(help->dthps_deferred == 0 ||
14261 			    help->dthps_next != NULL ||
14262 			    help->dthps_prev != NULL ||
14263 			    help == dtrace_deferred_pid);
14264 
14265 			/*
14266 			 * Remove the helper from the deferred list.
14267 			 */
14268 			if (help->dthps_next != NULL)
14269 				help->dthps_next->dthps_prev = help->dthps_prev;
14270 			if (help->dthps_prev != NULL)
14271 				help->dthps_prev->dthps_next = help->dthps_next;
14272 			if (dtrace_deferred_pid == help) {
14273 				dtrace_deferred_pid = help->dthps_next;
14274 				ASSERT(help->dthps_prev == NULL);
14275 			}
14276 
14277 			mutex_exit(&dtrace_lock);
14278 		}
14279 
14280 		mutex_exit(&dtrace_meta_lock);
14281 
14282 		for (i = 0; i < help->dthps_nprovs; i++) {
14283 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
14284 		}
14285 
14286 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
14287 		    sizeof (dtrace_helper_provider_t *));
14288 	}
14289 
14290 	mutex_enter(&dtrace_lock);
14291 
14292 	dtrace_vstate_fini(&help->dthps_vstate);
14293 	kmem_free(help->dthps_actions,
14294 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
14295 	kmem_free(help, sizeof (dtrace_helpers_t));
14296 
14297 	--dtrace_helpers;
14298 	mutex_exit(&dtrace_lock);
14299 }
14300 
14301 static void
14302 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
14303 {
14304 	dtrace_helpers_t *help, *newhelp;
14305 	dtrace_helper_action_t *helper, *new, *last;
14306 	dtrace_difo_t *dp;
14307 	dtrace_vstate_t *vstate;
14308 	int i, j, sz, hasprovs = 0;
14309 
14310 	mutex_enter(&dtrace_lock);
14311 	ASSERT(from->p_dtrace_helpers != NULL);
14312 	ASSERT(dtrace_helpers > 0);
14313 
14314 	help = from->p_dtrace_helpers;
14315 	newhelp = dtrace_helpers_create(to);
14316 	ASSERT(to->p_dtrace_helpers != NULL);
14317 
14318 	newhelp->dthps_generation = help->dthps_generation;
14319 	vstate = &newhelp->dthps_vstate;
14320 
14321 	/*
14322 	 * Duplicate the helper actions.
14323 	 */
14324 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14325 		if ((helper = help->dthps_actions[i]) == NULL)
14326 			continue;
14327 
14328 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
14329 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
14330 			    KM_SLEEP);
14331 			new->dtha_generation = helper->dtha_generation;
14332 
14333 			if ((dp = helper->dtha_predicate) != NULL) {
14334 				dp = dtrace_difo_duplicate(dp, vstate);
14335 				new->dtha_predicate = dp;
14336 			}
14337 
14338 			new->dtha_nactions = helper->dtha_nactions;
14339 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
14340 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
14341 
14342 			for (j = 0; j < new->dtha_nactions; j++) {
14343 				dtrace_difo_t *dp = helper->dtha_actions[j];
14344 
14345 				ASSERT(dp != NULL);
14346 				dp = dtrace_difo_duplicate(dp, vstate);
14347 				new->dtha_actions[j] = dp;
14348 			}
14349 
14350 			if (last != NULL) {
14351 				last->dtha_next = new;
14352 			} else {
14353 				newhelp->dthps_actions[i] = new;
14354 			}
14355 
14356 			last = new;
14357 		}
14358 	}
14359 
14360 	/*
14361 	 * Duplicate the helper providers and register them with the
14362 	 * DTrace framework.
14363 	 */
14364 	if (help->dthps_nprovs > 0) {
14365 		newhelp->dthps_nprovs = help->dthps_nprovs;
14366 		newhelp->dthps_maxprovs = help->dthps_nprovs;
14367 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
14368 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14369 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
14370 			newhelp->dthps_provs[i] = help->dthps_provs[i];
14371 			newhelp->dthps_provs[i]->dthp_ref++;
14372 		}
14373 
14374 		hasprovs = 1;
14375 	}
14376 
14377 	mutex_exit(&dtrace_lock);
14378 
14379 	if (hasprovs)
14380 		dtrace_helper_provider_register(to, newhelp, NULL);
14381 }
14382 
14383 /*
14384  * DTrace Hook Functions
14385  */
14386 static void
14387 dtrace_module_loaded(struct modctl *ctl)
14388 {
14389 	dtrace_provider_t *prv;
14390 
14391 	mutex_enter(&dtrace_provider_lock);
14392 	mutex_enter(&mod_lock);
14393 
14394 	ASSERT(ctl->mod_busy);
14395 
14396 	/*
14397 	 * We're going to call each providers per-module provide operation
14398 	 * specifying only this module.
14399 	 */
14400 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
14401 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
14402 
14403 	mutex_exit(&mod_lock);
14404 	mutex_exit(&dtrace_provider_lock);
14405 
14406 	/*
14407 	 * If we have any retained enablings, we need to match against them.
14408 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
14409 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
14410 	 * module.  (In particular, this happens when loading scheduling
14411 	 * classes.)  So if we have any retained enablings, we need to dispatch
14412 	 * our task queue to do the match for us.
14413 	 */
14414 	mutex_enter(&dtrace_lock);
14415 
14416 	if (dtrace_retained == NULL) {
14417 		mutex_exit(&dtrace_lock);
14418 		return;
14419 	}
14420 
14421 	(void) taskq_dispatch(dtrace_taskq,
14422 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
14423 
14424 	mutex_exit(&dtrace_lock);
14425 
14426 	/*
14427 	 * And now, for a little heuristic sleaze:  in general, we want to
14428 	 * match modules as soon as they load.  However, we cannot guarantee
14429 	 * this, because it would lead us to the lock ordering violation
14430 	 * outlined above.  The common case, of course, is that cpu_lock is
14431 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
14432 	 * long enough for the task queue to do its work.  If it's not, it's
14433 	 * not a serious problem -- it just means that the module that we
14434 	 * just loaded may not be immediately instrumentable.
14435 	 */
14436 	delay(1);
14437 }
14438 
14439 static void
14440 dtrace_module_unloaded(struct modctl *ctl)
14441 {
14442 	dtrace_probe_t template, *probe, *first, *next;
14443 	dtrace_provider_t *prov;
14444 
14445 	template.dtpr_mod = ctl->mod_modname;
14446 
14447 	mutex_enter(&dtrace_provider_lock);
14448 	mutex_enter(&mod_lock);
14449 	mutex_enter(&dtrace_lock);
14450 
14451 	if (dtrace_bymod == NULL) {
14452 		/*
14453 		 * The DTrace module is loaded (obviously) but not attached;
14454 		 * we don't have any work to do.
14455 		 */
14456 		mutex_exit(&dtrace_provider_lock);
14457 		mutex_exit(&mod_lock);
14458 		mutex_exit(&dtrace_lock);
14459 		return;
14460 	}
14461 
14462 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
14463 	    probe != NULL; probe = probe->dtpr_nextmod) {
14464 		if (probe->dtpr_ecb != NULL) {
14465 			mutex_exit(&dtrace_provider_lock);
14466 			mutex_exit(&mod_lock);
14467 			mutex_exit(&dtrace_lock);
14468 
14469 			/*
14470 			 * This shouldn't _actually_ be possible -- we're
14471 			 * unloading a module that has an enabled probe in it.
14472 			 * (It's normally up to the provider to make sure that
14473 			 * this can't happen.)  However, because dtps_enable()
14474 			 * doesn't have a failure mode, there can be an
14475 			 * enable/unload race.  Upshot:  we don't want to
14476 			 * assert, but we're not going to disable the
14477 			 * probe, either.
14478 			 */
14479 			if (dtrace_err_verbose) {
14480 				cmn_err(CE_WARN, "unloaded module '%s' had "
14481 				    "enabled probes", ctl->mod_modname);
14482 			}
14483 
14484 			return;
14485 		}
14486 	}
14487 
14488 	probe = first;
14489 
14490 	for (first = NULL; probe != NULL; probe = next) {
14491 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
14492 
14493 		dtrace_probes[probe->dtpr_id - 1] = NULL;
14494 
14495 		next = probe->dtpr_nextmod;
14496 		dtrace_hash_remove(dtrace_bymod, probe);
14497 		dtrace_hash_remove(dtrace_byfunc, probe);
14498 		dtrace_hash_remove(dtrace_byname, probe);
14499 
14500 		if (first == NULL) {
14501 			first = probe;
14502 			probe->dtpr_nextmod = NULL;
14503 		} else {
14504 			probe->dtpr_nextmod = first;
14505 			first = probe;
14506 		}
14507 	}
14508 
14509 	/*
14510 	 * We've removed all of the module's probes from the hash chains and
14511 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
14512 	 * everyone has cleared out from any probe array processing.
14513 	 */
14514 	dtrace_sync();
14515 
14516 	for (probe = first; probe != NULL; probe = first) {
14517 		first = probe->dtpr_nextmod;
14518 		prov = probe->dtpr_provider;
14519 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
14520 		    probe->dtpr_arg);
14521 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
14522 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
14523 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
14524 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
14525 		kmem_free(probe, sizeof (dtrace_probe_t));
14526 	}
14527 
14528 	mutex_exit(&dtrace_lock);
14529 	mutex_exit(&mod_lock);
14530 	mutex_exit(&dtrace_provider_lock);
14531 }
14532 
14533 void
14534 dtrace_suspend(void)
14535 {
14536 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
14537 }
14538 
14539 void
14540 dtrace_resume(void)
14541 {
14542 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
14543 }
14544 
14545 static int
14546 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
14547 {
14548 	ASSERT(MUTEX_HELD(&cpu_lock));
14549 	mutex_enter(&dtrace_lock);
14550 
14551 	switch (what) {
14552 	case CPU_CONFIG: {
14553 		dtrace_state_t *state;
14554 		dtrace_optval_t *opt, rs, c;
14555 
14556 		/*
14557 		 * For now, we only allocate a new buffer for anonymous state.
14558 		 */
14559 		if ((state = dtrace_anon.dta_state) == NULL)
14560 			break;
14561 
14562 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14563 			break;
14564 
14565 		opt = state->dts_options;
14566 		c = opt[DTRACEOPT_CPU];
14567 
14568 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
14569 			break;
14570 
14571 		/*
14572 		 * Regardless of what the actual policy is, we're going to
14573 		 * temporarily set our resize policy to be manual.  We're
14574 		 * also going to temporarily set our CPU option to denote
14575 		 * the newly configured CPU.
14576 		 */
14577 		rs = opt[DTRACEOPT_BUFRESIZE];
14578 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
14579 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
14580 
14581 		(void) dtrace_state_buffers(state);
14582 
14583 		opt[DTRACEOPT_BUFRESIZE] = rs;
14584 		opt[DTRACEOPT_CPU] = c;
14585 
14586 		break;
14587 	}
14588 
14589 	case CPU_UNCONFIG:
14590 		/*
14591 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
14592 		 * buffer will be freed when the consumer exits.)
14593 		 */
14594 		break;
14595 
14596 	default:
14597 		break;
14598 	}
14599 
14600 	mutex_exit(&dtrace_lock);
14601 	return (0);
14602 }
14603 
14604 static void
14605 dtrace_cpu_setup_initial(processorid_t cpu)
14606 {
14607 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
14608 }
14609 
14610 static void
14611 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
14612 {
14613 	if (dtrace_toxranges >= dtrace_toxranges_max) {
14614 		int osize, nsize;
14615 		dtrace_toxrange_t *range;
14616 
14617 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14618 
14619 		if (osize == 0) {
14620 			ASSERT(dtrace_toxrange == NULL);
14621 			ASSERT(dtrace_toxranges_max == 0);
14622 			dtrace_toxranges_max = 1;
14623 		} else {
14624 			dtrace_toxranges_max <<= 1;
14625 		}
14626 
14627 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14628 		range = kmem_zalloc(nsize, KM_SLEEP);
14629 
14630 		if (dtrace_toxrange != NULL) {
14631 			ASSERT(osize != 0);
14632 			bcopy(dtrace_toxrange, range, osize);
14633 			kmem_free(dtrace_toxrange, osize);
14634 		}
14635 
14636 		dtrace_toxrange = range;
14637 	}
14638 
14639 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
14640 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
14641 
14642 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
14643 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
14644 	dtrace_toxranges++;
14645 }
14646 
14647 /*
14648  * DTrace Driver Cookbook Functions
14649  */
14650 /*ARGSUSED*/
14651 static int
14652 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
14653 {
14654 	dtrace_provider_id_t id;
14655 	dtrace_state_t *state = NULL;
14656 	dtrace_enabling_t *enab;
14657 
14658 	mutex_enter(&cpu_lock);
14659 	mutex_enter(&dtrace_provider_lock);
14660 	mutex_enter(&dtrace_lock);
14661 
14662 	if (ddi_soft_state_init(&dtrace_softstate,
14663 	    sizeof (dtrace_state_t), 0) != 0) {
14664 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
14665 		mutex_exit(&cpu_lock);
14666 		mutex_exit(&dtrace_provider_lock);
14667 		mutex_exit(&dtrace_lock);
14668 		return (DDI_FAILURE);
14669 	}
14670 
14671 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
14672 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
14673 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
14674 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
14675 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
14676 		ddi_remove_minor_node(devi, NULL);
14677 		ddi_soft_state_fini(&dtrace_softstate);
14678 		mutex_exit(&cpu_lock);
14679 		mutex_exit(&dtrace_provider_lock);
14680 		mutex_exit(&dtrace_lock);
14681 		return (DDI_FAILURE);
14682 	}
14683 
14684 	ddi_report_dev(devi);
14685 	dtrace_devi = devi;
14686 
14687 	dtrace_modload = dtrace_module_loaded;
14688 	dtrace_modunload = dtrace_module_unloaded;
14689 	dtrace_cpu_init = dtrace_cpu_setup_initial;
14690 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
14691 	dtrace_helpers_fork = dtrace_helpers_duplicate;
14692 	dtrace_cpustart_init = dtrace_suspend;
14693 	dtrace_cpustart_fini = dtrace_resume;
14694 	dtrace_debugger_init = dtrace_suspend;
14695 	dtrace_debugger_fini = dtrace_resume;
14696 
14697 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
14698 
14699 	ASSERT(MUTEX_HELD(&cpu_lock));
14700 
14701 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
14702 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14703 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
14704 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
14705 	    VM_SLEEP | VMC_IDENTIFIER);
14706 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
14707 	    1, INT_MAX, 0);
14708 
14709 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
14710 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
14711 	    NULL, NULL, NULL, NULL, NULL, 0);
14712 
14713 	ASSERT(MUTEX_HELD(&cpu_lock));
14714 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
14715 	    offsetof(dtrace_probe_t, dtpr_nextmod),
14716 	    offsetof(dtrace_probe_t, dtpr_prevmod));
14717 
14718 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
14719 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
14720 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
14721 
14722 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
14723 	    offsetof(dtrace_probe_t, dtpr_nextname),
14724 	    offsetof(dtrace_probe_t, dtpr_prevname));
14725 
14726 	if (dtrace_retain_max < 1) {
14727 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
14728 		    "setting to 1", dtrace_retain_max);
14729 		dtrace_retain_max = 1;
14730 	}
14731 
14732 	/*
14733 	 * Now discover our toxic ranges.
14734 	 */
14735 	dtrace_toxic_ranges(dtrace_toxrange_add);
14736 
14737 	/*
14738 	 * Before we register ourselves as a provider to our own framework,
14739 	 * we would like to assert that dtrace_provider is NULL -- but that's
14740 	 * not true if we were loaded as a dependency of a DTrace provider.
14741 	 * Once we've registered, we can assert that dtrace_provider is our
14742 	 * pseudo provider.
14743 	 */
14744 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
14745 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
14746 
14747 	ASSERT(dtrace_provider != NULL);
14748 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
14749 
14750 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
14751 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
14752 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
14753 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
14754 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
14755 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
14756 
14757 	dtrace_anon_property();
14758 	mutex_exit(&cpu_lock);
14759 
14760 	/*
14761 	 * If DTrace helper tracing is enabled, we need to allocate the
14762 	 * trace buffer and initialize the values.
14763 	 */
14764 	if (dtrace_helptrace_enabled) {
14765 		ASSERT(dtrace_helptrace_buffer == NULL);
14766 		dtrace_helptrace_buffer =
14767 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
14768 		dtrace_helptrace_next = 0;
14769 	}
14770 
14771 	/*
14772 	 * If there are already providers, we must ask them to provide their
14773 	 * probes, and then match any anonymous enabling against them.  Note
14774 	 * that there should be no other retained enablings at this time:
14775 	 * the only retained enablings at this time should be the anonymous
14776 	 * enabling.
14777 	 */
14778 	if (dtrace_anon.dta_enabling != NULL) {
14779 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
14780 
14781 		dtrace_enabling_provide(NULL);
14782 		state = dtrace_anon.dta_state;
14783 
14784 		/*
14785 		 * We couldn't hold cpu_lock across the above call to
14786 		 * dtrace_enabling_provide(), but we must hold it to actually
14787 		 * enable the probes.  We have to drop all of our locks, pick
14788 		 * up cpu_lock, and regain our locks before matching the
14789 		 * retained anonymous enabling.
14790 		 */
14791 		mutex_exit(&dtrace_lock);
14792 		mutex_exit(&dtrace_provider_lock);
14793 
14794 		mutex_enter(&cpu_lock);
14795 		mutex_enter(&dtrace_provider_lock);
14796 		mutex_enter(&dtrace_lock);
14797 
14798 		if ((enab = dtrace_anon.dta_enabling) != NULL)
14799 			(void) dtrace_enabling_match(enab, NULL);
14800 
14801 		mutex_exit(&cpu_lock);
14802 	}
14803 
14804 	mutex_exit(&dtrace_lock);
14805 	mutex_exit(&dtrace_provider_lock);
14806 
14807 	if (state != NULL) {
14808 		/*
14809 		 * If we created any anonymous state, set it going now.
14810 		 */
14811 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
14812 	}
14813 
14814 	return (DDI_SUCCESS);
14815 }
14816 
14817 /*ARGSUSED*/
14818 static int
14819 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
14820 {
14821 	dtrace_state_t *state;
14822 	uint32_t priv;
14823 	uid_t uid;
14824 	zoneid_t zoneid;
14825 
14826 	if (getminor(*devp) == DTRACEMNRN_HELPER)
14827 		return (0);
14828 
14829 	/*
14830 	 * If this wasn't an open with the "helper" minor, then it must be
14831 	 * the "dtrace" minor.
14832 	 */
14833 	if (getminor(*devp) != DTRACEMNRN_DTRACE)
14834 		return (ENXIO);
14835 
14836 	/*
14837 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
14838 	 * caller lacks sufficient permission to do anything with DTrace.
14839 	 */
14840 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
14841 	if (priv == DTRACE_PRIV_NONE)
14842 		return (EACCES);
14843 
14844 	/*
14845 	 * Ask all providers to provide all their probes.
14846 	 */
14847 	mutex_enter(&dtrace_provider_lock);
14848 	dtrace_probe_provide(NULL, NULL);
14849 	mutex_exit(&dtrace_provider_lock);
14850 
14851 	mutex_enter(&cpu_lock);
14852 	mutex_enter(&dtrace_lock);
14853 	dtrace_opens++;
14854 	dtrace_membar_producer();
14855 
14856 	/*
14857 	 * If the kernel debugger is active (that is, if the kernel debugger
14858 	 * modified text in some way), we won't allow the open.
14859 	 */
14860 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14861 		dtrace_opens--;
14862 		mutex_exit(&cpu_lock);
14863 		mutex_exit(&dtrace_lock);
14864 		return (EBUSY);
14865 	}
14866 
14867 	state = dtrace_state_create(devp, cred_p);
14868 	mutex_exit(&cpu_lock);
14869 
14870 	if (state == NULL) {
14871 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
14872 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14873 		mutex_exit(&dtrace_lock);
14874 		return (EAGAIN);
14875 	}
14876 
14877 	mutex_exit(&dtrace_lock);
14878 
14879 	return (0);
14880 }
14881 
14882 /*ARGSUSED*/
14883 static int
14884 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
14885 {
14886 	minor_t minor = getminor(dev);
14887 	dtrace_state_t *state;
14888 
14889 	if (minor == DTRACEMNRN_HELPER)
14890 		return (0);
14891 
14892 	state = ddi_get_soft_state(dtrace_softstate, minor);
14893 
14894 	mutex_enter(&cpu_lock);
14895 	mutex_enter(&dtrace_lock);
14896 
14897 	if (state->dts_anon) {
14898 		/*
14899 		 * There is anonymous state. Destroy that first.
14900 		 */
14901 		ASSERT(dtrace_anon.dta_state == NULL);
14902 		dtrace_state_destroy(state->dts_anon);
14903 	}
14904 
14905 	dtrace_state_destroy(state);
14906 	ASSERT(dtrace_opens > 0);
14907 
14908 	/*
14909 	 * Only relinquish control of the kernel debugger interface when there
14910 	 * are no consumers and no anonymous enablings.
14911 	 */
14912 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
14913 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14914 
14915 	mutex_exit(&dtrace_lock);
14916 	mutex_exit(&cpu_lock);
14917 
14918 	return (0);
14919 }
14920 
14921 /*ARGSUSED*/
14922 static int
14923 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
14924 {
14925 	int rval;
14926 	dof_helper_t help, *dhp = NULL;
14927 
14928 	switch (cmd) {
14929 	case DTRACEHIOC_ADDDOF:
14930 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
14931 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
14932 			return (EFAULT);
14933 		}
14934 
14935 		dhp = &help;
14936 		arg = (intptr_t)help.dofhp_dof;
14937 		/*FALLTHROUGH*/
14938 
14939 	case DTRACEHIOC_ADD: {
14940 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
14941 
14942 		if (dof == NULL)
14943 			return (rval);
14944 
14945 		mutex_enter(&dtrace_lock);
14946 
14947 		/*
14948 		 * dtrace_helper_slurp() takes responsibility for the dof --
14949 		 * it may free it now or it may save it and free it later.
14950 		 */
14951 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
14952 			*rv = rval;
14953 			rval = 0;
14954 		} else {
14955 			rval = EINVAL;
14956 		}
14957 
14958 		mutex_exit(&dtrace_lock);
14959 		return (rval);
14960 	}
14961 
14962 	case DTRACEHIOC_REMOVE: {
14963 		mutex_enter(&dtrace_lock);
14964 		rval = dtrace_helper_destroygen(arg);
14965 		mutex_exit(&dtrace_lock);
14966 
14967 		return (rval);
14968 	}
14969 
14970 	default:
14971 		break;
14972 	}
14973 
14974 	return (ENOTTY);
14975 }
14976 
14977 /*ARGSUSED*/
14978 static int
14979 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
14980 {
14981 	minor_t minor = getminor(dev);
14982 	dtrace_state_t *state;
14983 	int rval;
14984 
14985 	if (minor == DTRACEMNRN_HELPER)
14986 		return (dtrace_ioctl_helper(cmd, arg, rv));
14987 
14988 	state = ddi_get_soft_state(dtrace_softstate, minor);
14989 
14990 	if (state->dts_anon) {
14991 		ASSERT(dtrace_anon.dta_state == NULL);
14992 		state = state->dts_anon;
14993 	}
14994 
14995 	switch (cmd) {
14996 	case DTRACEIOC_PROVIDER: {
14997 		dtrace_providerdesc_t pvd;
14998 		dtrace_provider_t *pvp;
14999 
15000 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
15001 			return (EFAULT);
15002 
15003 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
15004 		mutex_enter(&dtrace_provider_lock);
15005 
15006 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
15007 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
15008 				break;
15009 		}
15010 
15011 		mutex_exit(&dtrace_provider_lock);
15012 
15013 		if (pvp == NULL)
15014 			return (ESRCH);
15015 
15016 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
15017 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
15018 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
15019 			return (EFAULT);
15020 
15021 		return (0);
15022 	}
15023 
15024 	case DTRACEIOC_EPROBE: {
15025 		dtrace_eprobedesc_t epdesc;
15026 		dtrace_ecb_t *ecb;
15027 		dtrace_action_t *act;
15028 		void *buf;
15029 		size_t size;
15030 		uintptr_t dest;
15031 		int nrecs;
15032 
15033 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
15034 			return (EFAULT);
15035 
15036 		mutex_enter(&dtrace_lock);
15037 
15038 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
15039 			mutex_exit(&dtrace_lock);
15040 			return (EINVAL);
15041 		}
15042 
15043 		if (ecb->dte_probe == NULL) {
15044 			mutex_exit(&dtrace_lock);
15045 			return (EINVAL);
15046 		}
15047 
15048 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
15049 		epdesc.dtepd_uarg = ecb->dte_uarg;
15050 		epdesc.dtepd_size = ecb->dte_size;
15051 
15052 		nrecs = epdesc.dtepd_nrecs;
15053 		epdesc.dtepd_nrecs = 0;
15054 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15055 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15056 				continue;
15057 
15058 			epdesc.dtepd_nrecs++;
15059 		}
15060 
15061 		/*
15062 		 * Now that we have the size, we need to allocate a temporary
15063 		 * buffer in which to store the complete description.  We need
15064 		 * the temporary buffer to be able to drop dtrace_lock()
15065 		 * across the copyout(), below.
15066 		 */
15067 		size = sizeof (dtrace_eprobedesc_t) +
15068 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
15069 
15070 		buf = kmem_alloc(size, KM_SLEEP);
15071 		dest = (uintptr_t)buf;
15072 
15073 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
15074 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
15075 
15076 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15077 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15078 				continue;
15079 
15080 			if (nrecs-- == 0)
15081 				break;
15082 
15083 			bcopy(&act->dta_rec, (void *)dest,
15084 			    sizeof (dtrace_recdesc_t));
15085 			dest += sizeof (dtrace_recdesc_t);
15086 		}
15087 
15088 		mutex_exit(&dtrace_lock);
15089 
15090 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
15091 			kmem_free(buf, size);
15092 			return (EFAULT);
15093 		}
15094 
15095 		kmem_free(buf, size);
15096 		return (0);
15097 	}
15098 
15099 	case DTRACEIOC_AGGDESC: {
15100 		dtrace_aggdesc_t aggdesc;
15101 		dtrace_action_t *act;
15102 		dtrace_aggregation_t *agg;
15103 		int nrecs;
15104 		uint32_t offs;
15105 		dtrace_recdesc_t *lrec;
15106 		void *buf;
15107 		size_t size;
15108 		uintptr_t dest;
15109 
15110 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
15111 			return (EFAULT);
15112 
15113 		mutex_enter(&dtrace_lock);
15114 
15115 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
15116 			mutex_exit(&dtrace_lock);
15117 			return (EINVAL);
15118 		}
15119 
15120 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
15121 
15122 		nrecs = aggdesc.dtagd_nrecs;
15123 		aggdesc.dtagd_nrecs = 0;
15124 
15125 		offs = agg->dtag_base;
15126 		lrec = &agg->dtag_action.dta_rec;
15127 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
15128 
15129 		for (act = agg->dtag_first; ; act = act->dta_next) {
15130 			ASSERT(act->dta_intuple ||
15131 			    DTRACEACT_ISAGG(act->dta_kind));
15132 
15133 			/*
15134 			 * If this action has a record size of zero, it
15135 			 * denotes an argument to the aggregating action.
15136 			 * Because the presence of this record doesn't (or
15137 			 * shouldn't) affect the way the data is interpreted,
15138 			 * we don't copy it out to save user-level the
15139 			 * confusion of dealing with a zero-length record.
15140 			 */
15141 			if (act->dta_rec.dtrd_size == 0) {
15142 				ASSERT(agg->dtag_hasarg);
15143 				continue;
15144 			}
15145 
15146 			aggdesc.dtagd_nrecs++;
15147 
15148 			if (act == &agg->dtag_action)
15149 				break;
15150 		}
15151 
15152 		/*
15153 		 * Now that we have the size, we need to allocate a temporary
15154 		 * buffer in which to store the complete description.  We need
15155 		 * the temporary buffer to be able to drop dtrace_lock()
15156 		 * across the copyout(), below.
15157 		 */
15158 		size = sizeof (dtrace_aggdesc_t) +
15159 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
15160 
15161 		buf = kmem_alloc(size, KM_SLEEP);
15162 		dest = (uintptr_t)buf;
15163 
15164 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
15165 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
15166 
15167 		for (act = agg->dtag_first; ; act = act->dta_next) {
15168 			dtrace_recdesc_t rec = act->dta_rec;
15169 
15170 			/*
15171 			 * See the comment in the above loop for why we pass
15172 			 * over zero-length records.
15173 			 */
15174 			if (rec.dtrd_size == 0) {
15175 				ASSERT(agg->dtag_hasarg);
15176 				continue;
15177 			}
15178 
15179 			if (nrecs-- == 0)
15180 				break;
15181 
15182 			rec.dtrd_offset -= offs;
15183 			bcopy(&rec, (void *)dest, sizeof (rec));
15184 			dest += sizeof (dtrace_recdesc_t);
15185 
15186 			if (act == &agg->dtag_action)
15187 				break;
15188 		}
15189 
15190 		mutex_exit(&dtrace_lock);
15191 
15192 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
15193 			kmem_free(buf, size);
15194 			return (EFAULT);
15195 		}
15196 
15197 		kmem_free(buf, size);
15198 		return (0);
15199 	}
15200 
15201 	case DTRACEIOC_ENABLE: {
15202 		dof_hdr_t *dof;
15203 		dtrace_enabling_t *enab = NULL;
15204 		dtrace_vstate_t *vstate;
15205 		int err = 0;
15206 
15207 		*rv = 0;
15208 
15209 		/*
15210 		 * If a NULL argument has been passed, we take this as our
15211 		 * cue to reevaluate our enablings.
15212 		 */
15213 		if (arg == NULL) {
15214 			dtrace_enabling_matchall();
15215 
15216 			return (0);
15217 		}
15218 
15219 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
15220 			return (rval);
15221 
15222 		mutex_enter(&cpu_lock);
15223 		mutex_enter(&dtrace_lock);
15224 		vstate = &state->dts_vstate;
15225 
15226 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
15227 			mutex_exit(&dtrace_lock);
15228 			mutex_exit(&cpu_lock);
15229 			dtrace_dof_destroy(dof);
15230 			return (EBUSY);
15231 		}
15232 
15233 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
15234 			mutex_exit(&dtrace_lock);
15235 			mutex_exit(&cpu_lock);
15236 			dtrace_dof_destroy(dof);
15237 			return (EINVAL);
15238 		}
15239 
15240 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
15241 			dtrace_enabling_destroy(enab);
15242 			mutex_exit(&dtrace_lock);
15243 			mutex_exit(&cpu_lock);
15244 			dtrace_dof_destroy(dof);
15245 			return (rval);
15246 		}
15247 
15248 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
15249 			err = dtrace_enabling_retain(enab);
15250 		} else {
15251 			dtrace_enabling_destroy(enab);
15252 		}
15253 
15254 		mutex_exit(&cpu_lock);
15255 		mutex_exit(&dtrace_lock);
15256 		dtrace_dof_destroy(dof);
15257 
15258 		return (err);
15259 	}
15260 
15261 	case DTRACEIOC_REPLICATE: {
15262 		dtrace_repldesc_t desc;
15263 		dtrace_probedesc_t *match = &desc.dtrpd_match;
15264 		dtrace_probedesc_t *create = &desc.dtrpd_create;
15265 		int err;
15266 
15267 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15268 			return (EFAULT);
15269 
15270 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15271 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15272 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15273 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15274 
15275 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15276 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15277 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15278 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15279 
15280 		mutex_enter(&dtrace_lock);
15281 		err = dtrace_enabling_replicate(state, match, create);
15282 		mutex_exit(&dtrace_lock);
15283 
15284 		return (err);
15285 	}
15286 
15287 	case DTRACEIOC_PROBEMATCH:
15288 	case DTRACEIOC_PROBES: {
15289 		dtrace_probe_t *probe = NULL;
15290 		dtrace_probedesc_t desc;
15291 		dtrace_probekey_t pkey;
15292 		dtrace_id_t i;
15293 		int m = 0;
15294 		uint32_t priv;
15295 		uid_t uid;
15296 		zoneid_t zoneid;
15297 
15298 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15299 			return (EFAULT);
15300 
15301 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15302 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15303 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15304 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15305 
15306 		/*
15307 		 * Before we attempt to match this probe, we want to give
15308 		 * all providers the opportunity to provide it.
15309 		 */
15310 		if (desc.dtpd_id == DTRACE_IDNONE) {
15311 			mutex_enter(&dtrace_provider_lock);
15312 			dtrace_probe_provide(&desc, NULL);
15313 			mutex_exit(&dtrace_provider_lock);
15314 			desc.dtpd_id++;
15315 		}
15316 
15317 		if (cmd == DTRACEIOC_PROBEMATCH)  {
15318 			dtrace_probekey(&desc, &pkey);
15319 			pkey.dtpk_id = DTRACE_IDNONE;
15320 		}
15321 
15322 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
15323 
15324 		mutex_enter(&dtrace_lock);
15325 
15326 		if (cmd == DTRACEIOC_PROBEMATCH) {
15327 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
15328 				if ((probe = dtrace_probes[i - 1]) != NULL &&
15329 				    (m = dtrace_match_probe(probe, &pkey,
15330 				    priv, uid, zoneid)) != 0)
15331 					break;
15332 			}
15333 
15334 			if (m < 0) {
15335 				mutex_exit(&dtrace_lock);
15336 				return (EINVAL);
15337 			}
15338 
15339 		} else {
15340 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
15341 				if ((probe = dtrace_probes[i - 1]) != NULL &&
15342 				    dtrace_match_priv(probe, priv, uid, zoneid))
15343 					break;
15344 			}
15345 		}
15346 
15347 		if (probe == NULL) {
15348 			mutex_exit(&dtrace_lock);
15349 			return (ESRCH);
15350 		}
15351 
15352 		dtrace_probe_description(probe, &desc);
15353 		mutex_exit(&dtrace_lock);
15354 
15355 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15356 			return (EFAULT);
15357 
15358 		return (0);
15359 	}
15360 
15361 	case DTRACEIOC_PROBEARG: {
15362 		dtrace_argdesc_t desc;
15363 		dtrace_probe_t *probe;
15364 		dtrace_provider_t *prov;
15365 
15366 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15367 			return (EFAULT);
15368 
15369 		if (desc.dtargd_id == DTRACE_IDNONE)
15370 			return (EINVAL);
15371 
15372 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
15373 			return (EINVAL);
15374 
15375 		mutex_enter(&dtrace_provider_lock);
15376 		mutex_enter(&mod_lock);
15377 		mutex_enter(&dtrace_lock);
15378 
15379 		if (desc.dtargd_id > dtrace_nprobes) {
15380 			mutex_exit(&dtrace_lock);
15381 			mutex_exit(&mod_lock);
15382 			mutex_exit(&dtrace_provider_lock);
15383 			return (EINVAL);
15384 		}
15385 
15386 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
15387 			mutex_exit(&dtrace_lock);
15388 			mutex_exit(&mod_lock);
15389 			mutex_exit(&dtrace_provider_lock);
15390 			return (EINVAL);
15391 		}
15392 
15393 		mutex_exit(&dtrace_lock);
15394 
15395 		prov = probe->dtpr_provider;
15396 
15397 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
15398 			/*
15399 			 * There isn't any typed information for this probe.
15400 			 * Set the argument number to DTRACE_ARGNONE.
15401 			 */
15402 			desc.dtargd_ndx = DTRACE_ARGNONE;
15403 		} else {
15404 			desc.dtargd_native[0] = '\0';
15405 			desc.dtargd_xlate[0] = '\0';
15406 			desc.dtargd_mapping = desc.dtargd_ndx;
15407 
15408 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
15409 			    probe->dtpr_id, probe->dtpr_arg, &desc);
15410 		}
15411 
15412 		mutex_exit(&mod_lock);
15413 		mutex_exit(&dtrace_provider_lock);
15414 
15415 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15416 			return (EFAULT);
15417 
15418 		return (0);
15419 	}
15420 
15421 	case DTRACEIOC_GO: {
15422 		processorid_t cpuid;
15423 		rval = dtrace_state_go(state, &cpuid);
15424 
15425 		if (rval != 0)
15426 			return (rval);
15427 
15428 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
15429 			return (EFAULT);
15430 
15431 		return (0);
15432 	}
15433 
15434 	case DTRACEIOC_STOP: {
15435 		processorid_t cpuid;
15436 
15437 		mutex_enter(&dtrace_lock);
15438 		rval = dtrace_state_stop(state, &cpuid);
15439 		mutex_exit(&dtrace_lock);
15440 
15441 		if (rval != 0)
15442 			return (rval);
15443 
15444 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
15445 			return (EFAULT);
15446 
15447 		return (0);
15448 	}
15449 
15450 	case DTRACEIOC_DOFGET: {
15451 		dof_hdr_t hdr, *dof;
15452 		uint64_t len;
15453 
15454 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
15455 			return (EFAULT);
15456 
15457 		mutex_enter(&dtrace_lock);
15458 		dof = dtrace_dof_create(state);
15459 		mutex_exit(&dtrace_lock);
15460 
15461 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
15462 		rval = copyout(dof, (void *)arg, len);
15463 		dtrace_dof_destroy(dof);
15464 
15465 		return (rval == 0 ? 0 : EFAULT);
15466 	}
15467 
15468 	case DTRACEIOC_AGGSNAP:
15469 	case DTRACEIOC_BUFSNAP: {
15470 		dtrace_bufdesc_t desc;
15471 		caddr_t cached;
15472 		dtrace_buffer_t *buf;
15473 
15474 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15475 			return (EFAULT);
15476 
15477 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
15478 			return (EINVAL);
15479 
15480 		mutex_enter(&dtrace_lock);
15481 
15482 		if (cmd == DTRACEIOC_BUFSNAP) {
15483 			buf = &state->dts_buffer[desc.dtbd_cpu];
15484 		} else {
15485 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
15486 		}
15487 
15488 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
15489 			size_t sz = buf->dtb_offset;
15490 
15491 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
15492 				mutex_exit(&dtrace_lock);
15493 				return (EBUSY);
15494 			}
15495 
15496 			/*
15497 			 * If this buffer has already been consumed, we're
15498 			 * going to indicate that there's nothing left here
15499 			 * to consume.
15500 			 */
15501 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
15502 				mutex_exit(&dtrace_lock);
15503 
15504 				desc.dtbd_size = 0;
15505 				desc.dtbd_drops = 0;
15506 				desc.dtbd_errors = 0;
15507 				desc.dtbd_oldest = 0;
15508 				sz = sizeof (desc);
15509 
15510 				if (copyout(&desc, (void *)arg, sz) != 0)
15511 					return (EFAULT);
15512 
15513 				return (0);
15514 			}
15515 
15516 			/*
15517 			 * If this is a ring buffer that has wrapped, we want
15518 			 * to copy the whole thing out.
15519 			 */
15520 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
15521 				dtrace_buffer_polish(buf);
15522 				sz = buf->dtb_size;
15523 			}
15524 
15525 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
15526 				mutex_exit(&dtrace_lock);
15527 				return (EFAULT);
15528 			}
15529 
15530 			desc.dtbd_size = sz;
15531 			desc.dtbd_drops = buf->dtb_drops;
15532 			desc.dtbd_errors = buf->dtb_errors;
15533 			desc.dtbd_oldest = buf->dtb_xamot_offset;
15534 
15535 			mutex_exit(&dtrace_lock);
15536 
15537 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15538 				return (EFAULT);
15539 
15540 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
15541 
15542 			return (0);
15543 		}
15544 
15545 		if (buf->dtb_tomax == NULL) {
15546 			ASSERT(buf->dtb_xamot == NULL);
15547 			mutex_exit(&dtrace_lock);
15548 			return (ENOENT);
15549 		}
15550 
15551 		cached = buf->dtb_tomax;
15552 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
15553 
15554 		dtrace_xcall(desc.dtbd_cpu,
15555 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
15556 
15557 		state->dts_errors += buf->dtb_xamot_errors;
15558 
15559 		/*
15560 		 * If the buffers did not actually switch, then the cross call
15561 		 * did not take place -- presumably because the given CPU is
15562 		 * not in the ready set.  If this is the case, we'll return
15563 		 * ENOENT.
15564 		 */
15565 		if (buf->dtb_tomax == cached) {
15566 			ASSERT(buf->dtb_xamot != cached);
15567 			mutex_exit(&dtrace_lock);
15568 			return (ENOENT);
15569 		}
15570 
15571 		ASSERT(cached == buf->dtb_xamot);
15572 
15573 		/*
15574 		 * We have our snapshot; now copy it out.
15575 		 */
15576 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
15577 		    buf->dtb_xamot_offset) != 0) {
15578 			mutex_exit(&dtrace_lock);
15579 			return (EFAULT);
15580 		}
15581 
15582 		desc.dtbd_size = buf->dtb_xamot_offset;
15583 		desc.dtbd_drops = buf->dtb_xamot_drops;
15584 		desc.dtbd_errors = buf->dtb_xamot_errors;
15585 		desc.dtbd_oldest = 0;
15586 
15587 		mutex_exit(&dtrace_lock);
15588 
15589 		/*
15590 		 * Finally, copy out the buffer description.
15591 		 */
15592 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15593 			return (EFAULT);
15594 
15595 		return (0);
15596 	}
15597 
15598 	case DTRACEIOC_CONF: {
15599 		dtrace_conf_t conf;
15600 
15601 		bzero(&conf, sizeof (conf));
15602 		conf.dtc_difversion = DIF_VERSION;
15603 		conf.dtc_difintregs = DIF_DIR_NREGS;
15604 		conf.dtc_diftupregs = DIF_DTR_NREGS;
15605 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
15606 
15607 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
15608 			return (EFAULT);
15609 
15610 		return (0);
15611 	}
15612 
15613 	case DTRACEIOC_STATUS: {
15614 		dtrace_status_t stat;
15615 		dtrace_dstate_t *dstate;
15616 		int i, j;
15617 		uint64_t nerrs;
15618 
15619 		/*
15620 		 * See the comment in dtrace_state_deadman() for the reason
15621 		 * for setting dts_laststatus to INT64_MAX before setting
15622 		 * it to the correct value.
15623 		 */
15624 		state->dts_laststatus = INT64_MAX;
15625 		dtrace_membar_producer();
15626 		state->dts_laststatus = dtrace_gethrtime();
15627 
15628 		bzero(&stat, sizeof (stat));
15629 
15630 		mutex_enter(&dtrace_lock);
15631 
15632 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
15633 			mutex_exit(&dtrace_lock);
15634 			return (ENOENT);
15635 		}
15636 
15637 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
15638 			stat.dtst_exiting = 1;
15639 
15640 		nerrs = state->dts_errors;
15641 		dstate = &state->dts_vstate.dtvs_dynvars;
15642 
15643 		for (i = 0; i < NCPU; i++) {
15644 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
15645 
15646 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
15647 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
15648 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
15649 
15650 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
15651 				stat.dtst_filled++;
15652 
15653 			nerrs += state->dts_buffer[i].dtb_errors;
15654 
15655 			for (j = 0; j < state->dts_nspeculations; j++) {
15656 				dtrace_speculation_t *spec;
15657 				dtrace_buffer_t *buf;
15658 
15659 				spec = &state->dts_speculations[j];
15660 				buf = &spec->dtsp_buffer[i];
15661 				stat.dtst_specdrops += buf->dtb_xamot_drops;
15662 			}
15663 		}
15664 
15665 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
15666 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
15667 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
15668 		stat.dtst_dblerrors = state->dts_dblerrors;
15669 		stat.dtst_killed =
15670 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
15671 		stat.dtst_errors = nerrs;
15672 
15673 		mutex_exit(&dtrace_lock);
15674 
15675 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
15676 			return (EFAULT);
15677 
15678 		return (0);
15679 	}
15680 
15681 	case DTRACEIOC_FORMAT: {
15682 		dtrace_fmtdesc_t fmt;
15683 		char *str;
15684 		int len;
15685 
15686 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
15687 			return (EFAULT);
15688 
15689 		mutex_enter(&dtrace_lock);
15690 
15691 		if (fmt.dtfd_format == 0 ||
15692 		    fmt.dtfd_format > state->dts_nformats) {
15693 			mutex_exit(&dtrace_lock);
15694 			return (EINVAL);
15695 		}
15696 
15697 		/*
15698 		 * Format strings are allocated contiguously and they are
15699 		 * never freed; if a format index is less than the number
15700 		 * of formats, we can assert that the format map is non-NULL
15701 		 * and that the format for the specified index is non-NULL.
15702 		 */
15703 		ASSERT(state->dts_formats != NULL);
15704 		str = state->dts_formats[fmt.dtfd_format - 1];
15705 		ASSERT(str != NULL);
15706 
15707 		len = strlen(str) + 1;
15708 
15709 		if (len > fmt.dtfd_length) {
15710 			fmt.dtfd_length = len;
15711 
15712 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
15713 				mutex_exit(&dtrace_lock);
15714 				return (EINVAL);
15715 			}
15716 		} else {
15717 			if (copyout(str, fmt.dtfd_string, len) != 0) {
15718 				mutex_exit(&dtrace_lock);
15719 				return (EINVAL);
15720 			}
15721 		}
15722 
15723 		mutex_exit(&dtrace_lock);
15724 		return (0);
15725 	}
15726 
15727 	default:
15728 		break;
15729 	}
15730 
15731 	return (ENOTTY);
15732 }
15733 
15734 /*ARGSUSED*/
15735 static int
15736 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
15737 {
15738 	dtrace_state_t *state;
15739 
15740 	switch (cmd) {
15741 	case DDI_DETACH:
15742 		break;
15743 
15744 	case DDI_SUSPEND:
15745 		return (DDI_SUCCESS);
15746 
15747 	default:
15748 		return (DDI_FAILURE);
15749 	}
15750 
15751 	mutex_enter(&cpu_lock);
15752 	mutex_enter(&dtrace_provider_lock);
15753 	mutex_enter(&dtrace_lock);
15754 
15755 	ASSERT(dtrace_opens == 0);
15756 
15757 	if (dtrace_helpers > 0) {
15758 		mutex_exit(&dtrace_provider_lock);
15759 		mutex_exit(&dtrace_lock);
15760 		mutex_exit(&cpu_lock);
15761 		return (DDI_FAILURE);
15762 	}
15763 
15764 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
15765 		mutex_exit(&dtrace_provider_lock);
15766 		mutex_exit(&dtrace_lock);
15767 		mutex_exit(&cpu_lock);
15768 		return (DDI_FAILURE);
15769 	}
15770 
15771 	dtrace_provider = NULL;
15772 
15773 	if ((state = dtrace_anon_grab()) != NULL) {
15774 		/*
15775 		 * If there were ECBs on this state, the provider should
15776 		 * have not been allowed to detach; assert that there is
15777 		 * none.
15778 		 */
15779 		ASSERT(state->dts_necbs == 0);
15780 		dtrace_state_destroy(state);
15781 
15782 		/*
15783 		 * If we're being detached with anonymous state, we need to
15784 		 * indicate to the kernel debugger that DTrace is now inactive.
15785 		 */
15786 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15787 	}
15788 
15789 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
15790 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15791 	dtrace_cpu_init = NULL;
15792 	dtrace_helpers_cleanup = NULL;
15793 	dtrace_helpers_fork = NULL;
15794 	dtrace_cpustart_init = NULL;
15795 	dtrace_cpustart_fini = NULL;
15796 	dtrace_debugger_init = NULL;
15797 	dtrace_debugger_fini = NULL;
15798 	dtrace_modload = NULL;
15799 	dtrace_modunload = NULL;
15800 
15801 	mutex_exit(&cpu_lock);
15802 
15803 	if (dtrace_helptrace_enabled) {
15804 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
15805 		dtrace_helptrace_buffer = NULL;
15806 	}
15807 
15808 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
15809 	dtrace_probes = NULL;
15810 	dtrace_nprobes = 0;
15811 
15812 	dtrace_hash_destroy(dtrace_bymod);
15813 	dtrace_hash_destroy(dtrace_byfunc);
15814 	dtrace_hash_destroy(dtrace_byname);
15815 	dtrace_bymod = NULL;
15816 	dtrace_byfunc = NULL;
15817 	dtrace_byname = NULL;
15818 
15819 	kmem_cache_destroy(dtrace_state_cache);
15820 	vmem_destroy(dtrace_minor);
15821 	vmem_destroy(dtrace_arena);
15822 
15823 	if (dtrace_toxrange != NULL) {
15824 		kmem_free(dtrace_toxrange,
15825 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
15826 		dtrace_toxrange = NULL;
15827 		dtrace_toxranges = 0;
15828 		dtrace_toxranges_max = 0;
15829 	}
15830 
15831 	ddi_remove_minor_node(dtrace_devi, NULL);
15832 	dtrace_devi = NULL;
15833 
15834 	ddi_soft_state_fini(&dtrace_softstate);
15835 
15836 	ASSERT(dtrace_vtime_references == 0);
15837 	ASSERT(dtrace_opens == 0);
15838 	ASSERT(dtrace_retained == NULL);
15839 
15840 	mutex_exit(&dtrace_lock);
15841 	mutex_exit(&dtrace_provider_lock);
15842 
15843 	/*
15844 	 * We don't destroy the task queue until after we have dropped our
15845 	 * locks (taskq_destroy() may block on running tasks).  To prevent
15846 	 * attempting to do work after we have effectively detached but before
15847 	 * the task queue has been destroyed, all tasks dispatched via the
15848 	 * task queue must check that DTrace is still attached before
15849 	 * performing any operation.
15850 	 */
15851 	taskq_destroy(dtrace_taskq);
15852 	dtrace_taskq = NULL;
15853 
15854 	return (DDI_SUCCESS);
15855 }
15856 
15857 /*ARGSUSED*/
15858 static int
15859 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
15860 {
15861 	int error;
15862 
15863 	switch (infocmd) {
15864 	case DDI_INFO_DEVT2DEVINFO:
15865 		*result = (void *)dtrace_devi;
15866 		error = DDI_SUCCESS;
15867 		break;
15868 	case DDI_INFO_DEVT2INSTANCE:
15869 		*result = (void *)0;
15870 		error = DDI_SUCCESS;
15871 		break;
15872 	default:
15873 		error = DDI_FAILURE;
15874 	}
15875 	return (error);
15876 }
15877 
15878 static struct cb_ops dtrace_cb_ops = {
15879 	dtrace_open,		/* open */
15880 	dtrace_close,		/* close */
15881 	nulldev,		/* strategy */
15882 	nulldev,		/* print */
15883 	nodev,			/* dump */
15884 	nodev,			/* read */
15885 	nodev,			/* write */
15886 	dtrace_ioctl,		/* ioctl */
15887 	nodev,			/* devmap */
15888 	nodev,			/* mmap */
15889 	nodev,			/* segmap */
15890 	nochpoll,		/* poll */
15891 	ddi_prop_op,		/* cb_prop_op */
15892 	0,			/* streamtab  */
15893 	D_NEW | D_MP		/* Driver compatibility flag */
15894 };
15895 
15896 static struct dev_ops dtrace_ops = {
15897 	DEVO_REV,		/* devo_rev */
15898 	0,			/* refcnt */
15899 	dtrace_info,		/* get_dev_info */
15900 	nulldev,		/* identify */
15901 	nulldev,		/* probe */
15902 	dtrace_attach,		/* attach */
15903 	dtrace_detach,		/* detach */
15904 	nodev,			/* reset */
15905 	&dtrace_cb_ops,		/* driver operations */
15906 	NULL,			/* bus operations */
15907 	nodev,			/* dev power */
15908 	ddi_quiesce_not_needed,		/* quiesce */
15909 };
15910 
15911 static struct modldrv modldrv = {
15912 	&mod_driverops,		/* module type (this is a pseudo driver) */
15913 	"Dynamic Tracing",	/* name of module */
15914 	&dtrace_ops,		/* driver ops */
15915 };
15916 
15917 static struct modlinkage modlinkage = {
15918 	MODREV_1,
15919 	(void *)&modldrv,
15920 	NULL
15921 };
15922 
15923 int
15924 _init(void)
15925 {
15926 	return (mod_install(&modlinkage));
15927 }
15928 
15929 int
15930 _info(struct modinfo *modinfop)
15931 {
15932 	return (mod_info(&modlinkage, modinfop));
15933 }
15934 
15935 int
15936 _fini(void)
15937 {
15938 	return (mod_remove(&modlinkage));
15939 }
15940