xref: /illumos-gate/usr/src/uts/common/dtrace/dtrace.c (revision 09a48d4ca0ddda4ad26cc885769745870d989baf)
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 = 1024;
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_TOUPPER:
3908 	case DIF_SUBR_TOLOWER: {
3909 		uintptr_t s = tupregs[0].dttk_value;
3910 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3911 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
3912 		size_t len = dtrace_strlen((char *)s, size);
3913 		char lower, upper, convert;
3914 		int64_t i;
3915 
3916 		if (subr == DIF_SUBR_TOUPPER) {
3917 			lower = 'a';
3918 			upper = 'z';
3919 			convert = 'A';
3920 		} else {
3921 			lower = 'A';
3922 			upper = 'Z';
3923 			convert = 'a';
3924 		}
3925 
3926 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
3927 			regs[rd] = NULL;
3928 			break;
3929 		}
3930 
3931 		if (!DTRACE_INSCRATCH(mstate, size)) {
3932 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3933 			regs[rd] = NULL;
3934 			break;
3935 		}
3936 
3937 		for (i = 0; i < size - 1; i++) {
3938 			if ((c = dtrace_load8(s + i)) == '\0')
3939 				break;
3940 
3941 			if (c >= lower && c <= upper)
3942 				c = convert + (c - lower);
3943 
3944 			dest[i] = c;
3945 		}
3946 
3947 		ASSERT(i < size);
3948 		dest[i] = '\0';
3949 		regs[rd] = (uintptr_t)dest;
3950 		mstate->dtms_scratch_ptr += size;
3951 		break;
3952 	}
3953 
3954 case DIF_SUBR_GETMAJOR:
3955 #ifdef _LP64
3956 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
3957 #else
3958 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
3959 #endif
3960 		break;
3961 
3962 	case DIF_SUBR_GETMINOR:
3963 #ifdef _LP64
3964 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
3965 #else
3966 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
3967 #endif
3968 		break;
3969 
3970 	case DIF_SUBR_DDI_PATHNAME: {
3971 		/*
3972 		 * This one is a galactic mess.  We are going to roughly
3973 		 * emulate ddi_pathname(), but it's made more complicated
3974 		 * by the fact that we (a) want to include the minor name and
3975 		 * (b) must proceed iteratively instead of recursively.
3976 		 */
3977 		uintptr_t dest = mstate->dtms_scratch_ptr;
3978 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3979 		char *start = (char *)dest, *end = start + size - 1;
3980 		uintptr_t daddr = tupregs[0].dttk_value;
3981 		int64_t minor = (int64_t)tupregs[1].dttk_value;
3982 		char *s;
3983 		int i, len, depth = 0;
3984 
3985 		/*
3986 		 * Due to all the pointer jumping we do and context we must
3987 		 * rely upon, we just mandate that the user must have kernel
3988 		 * read privileges to use this routine.
3989 		 */
3990 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
3991 			*flags |= CPU_DTRACE_KPRIV;
3992 			*illval = daddr;
3993 			regs[rd] = NULL;
3994 		}
3995 
3996 		if (!DTRACE_INSCRATCH(mstate, size)) {
3997 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3998 			regs[rd] = NULL;
3999 			break;
4000 		}
4001 
4002 		*end = '\0';
4003 
4004 		/*
4005 		 * We want to have a name for the minor.  In order to do this,
4006 		 * we need to walk the minor list from the devinfo.  We want
4007 		 * to be sure that we don't infinitely walk a circular list,
4008 		 * so we check for circularity by sending a scout pointer
4009 		 * ahead two elements for every element that we iterate over;
4010 		 * if the list is circular, these will ultimately point to the
4011 		 * same element.  You may recognize this little trick as the
4012 		 * answer to a stupid interview question -- one that always
4013 		 * seems to be asked by those who had to have it laboriously
4014 		 * explained to them, and who can't even concisely describe
4015 		 * the conditions under which one would be forced to resort to
4016 		 * this technique.  Needless to say, those conditions are
4017 		 * found here -- and probably only here.  Is this the only use
4018 		 * of this infamous trick in shipping, production code?  If it
4019 		 * isn't, it probably should be...
4020 		 */
4021 		if (minor != -1) {
4022 			uintptr_t maddr = dtrace_loadptr(daddr +
4023 			    offsetof(struct dev_info, devi_minor));
4024 
4025 			uintptr_t next = offsetof(struct ddi_minor_data, next);
4026 			uintptr_t name = offsetof(struct ddi_minor_data,
4027 			    d_minor) + offsetof(struct ddi_minor, name);
4028 			uintptr_t dev = offsetof(struct ddi_minor_data,
4029 			    d_minor) + offsetof(struct ddi_minor, dev);
4030 			uintptr_t scout;
4031 
4032 			if (maddr != NULL)
4033 				scout = dtrace_loadptr(maddr + next);
4034 
4035 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4036 				uint64_t m;
4037 #ifdef _LP64
4038 				m = dtrace_load64(maddr + dev) & MAXMIN64;
4039 #else
4040 				m = dtrace_load32(maddr + dev) & MAXMIN;
4041 #endif
4042 				if (m != minor) {
4043 					maddr = dtrace_loadptr(maddr + next);
4044 
4045 					if (scout == NULL)
4046 						continue;
4047 
4048 					scout = dtrace_loadptr(scout + next);
4049 
4050 					if (scout == NULL)
4051 						continue;
4052 
4053 					scout = dtrace_loadptr(scout + next);
4054 
4055 					if (scout == NULL)
4056 						continue;
4057 
4058 					if (scout == maddr) {
4059 						*flags |= CPU_DTRACE_ILLOP;
4060 						break;
4061 					}
4062 
4063 					continue;
4064 				}
4065 
4066 				/*
4067 				 * We have the minor data.  Now we need to
4068 				 * copy the minor's name into the end of the
4069 				 * pathname.
4070 				 */
4071 				s = (char *)dtrace_loadptr(maddr + name);
4072 				len = dtrace_strlen(s, size);
4073 
4074 				if (*flags & CPU_DTRACE_FAULT)
4075 					break;
4076 
4077 				if (len != 0) {
4078 					if ((end -= (len + 1)) < start)
4079 						break;
4080 
4081 					*end = ':';
4082 				}
4083 
4084 				for (i = 1; i <= len; i++)
4085 					end[i] = dtrace_load8((uintptr_t)s++);
4086 				break;
4087 			}
4088 		}
4089 
4090 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
4091 			ddi_node_state_t devi_state;
4092 
4093 			devi_state = dtrace_load32(daddr +
4094 			    offsetof(struct dev_info, devi_node_state));
4095 
4096 			if (*flags & CPU_DTRACE_FAULT)
4097 				break;
4098 
4099 			if (devi_state >= DS_INITIALIZED) {
4100 				s = (char *)dtrace_loadptr(daddr +
4101 				    offsetof(struct dev_info, devi_addr));
4102 				len = dtrace_strlen(s, size);
4103 
4104 				if (*flags & CPU_DTRACE_FAULT)
4105 					break;
4106 
4107 				if (len != 0) {
4108 					if ((end -= (len + 1)) < start)
4109 						break;
4110 
4111 					*end = '@';
4112 				}
4113 
4114 				for (i = 1; i <= len; i++)
4115 					end[i] = dtrace_load8((uintptr_t)s++);
4116 			}
4117 
4118 			/*
4119 			 * Now for the node name...
4120 			 */
4121 			s = (char *)dtrace_loadptr(daddr +
4122 			    offsetof(struct dev_info, devi_node_name));
4123 
4124 			daddr = dtrace_loadptr(daddr +
4125 			    offsetof(struct dev_info, devi_parent));
4126 
4127 			/*
4128 			 * If our parent is NULL (that is, if we're the root
4129 			 * node), we're going to use the special path
4130 			 * "devices".
4131 			 */
4132 			if (daddr == NULL)
4133 				s = "devices";
4134 
4135 			len = dtrace_strlen(s, size);
4136 			if (*flags & CPU_DTRACE_FAULT)
4137 				break;
4138 
4139 			if ((end -= (len + 1)) < start)
4140 				break;
4141 
4142 			for (i = 1; i <= len; i++)
4143 				end[i] = dtrace_load8((uintptr_t)s++);
4144 			*end = '/';
4145 
4146 			if (depth++ > dtrace_devdepth_max) {
4147 				*flags |= CPU_DTRACE_ILLOP;
4148 				break;
4149 			}
4150 		}
4151 
4152 		if (end < start)
4153 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4154 
4155 		if (daddr == NULL) {
4156 			regs[rd] = (uintptr_t)end;
4157 			mstate->dtms_scratch_ptr += size;
4158 		}
4159 
4160 		break;
4161 	}
4162 
4163 	case DIF_SUBR_STRJOIN: {
4164 		char *d = (char *)mstate->dtms_scratch_ptr;
4165 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4166 		uintptr_t s1 = tupregs[0].dttk_value;
4167 		uintptr_t s2 = tupregs[1].dttk_value;
4168 		int i = 0;
4169 
4170 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
4171 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
4172 			regs[rd] = NULL;
4173 			break;
4174 		}
4175 
4176 		if (!DTRACE_INSCRATCH(mstate, size)) {
4177 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4178 			regs[rd] = NULL;
4179 			break;
4180 		}
4181 
4182 		for (;;) {
4183 			if (i >= size) {
4184 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4185 				regs[rd] = NULL;
4186 				break;
4187 			}
4188 
4189 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
4190 				i--;
4191 				break;
4192 			}
4193 		}
4194 
4195 		for (;;) {
4196 			if (i >= size) {
4197 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4198 				regs[rd] = NULL;
4199 				break;
4200 			}
4201 
4202 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
4203 				break;
4204 		}
4205 
4206 		if (i < size) {
4207 			mstate->dtms_scratch_ptr += i;
4208 			regs[rd] = (uintptr_t)d;
4209 		}
4210 
4211 		break;
4212 	}
4213 
4214 	case DIF_SUBR_LLTOSTR: {
4215 		int64_t i = (int64_t)tupregs[0].dttk_value;
4216 		uint64_t val, digit;
4217 		uint64_t size = 65;	/* enough room for 2^64 in binary */
4218 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
4219 		int base = 10;
4220 
4221 		if (nargs > 1) {
4222 			if ((base = tupregs[1].dttk_value) <= 1 ||
4223 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
4224 				*flags |= CPU_DTRACE_ILLOP;
4225 				break;
4226 			}
4227 		}
4228 
4229 		val = (base == 10 && i < 0) ? i * -1 : i;
4230 
4231 		if (!DTRACE_INSCRATCH(mstate, size)) {
4232 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4233 			regs[rd] = NULL;
4234 			break;
4235 		}
4236 
4237 		for (*end-- = '\0'; val; val /= base) {
4238 			if ((digit = val % base) <= '9' - '0') {
4239 				*end-- = '0' + digit;
4240 			} else {
4241 				*end-- = 'a' + (digit - ('9' - '0') - 1);
4242 			}
4243 		}
4244 
4245 		if (i == 0 && base == 16)
4246 			*end-- = '0';
4247 
4248 		if (base == 16)
4249 			*end-- = 'x';
4250 
4251 		if (i == 0 || base == 8 || base == 16)
4252 			*end-- = '0';
4253 
4254 		if (i < 0 && base == 10)
4255 			*end-- = '-';
4256 
4257 		regs[rd] = (uintptr_t)end + 1;
4258 		mstate->dtms_scratch_ptr += size;
4259 		break;
4260 	}
4261 
4262 	case DIF_SUBR_HTONS:
4263 	case DIF_SUBR_NTOHS:
4264 #ifdef _BIG_ENDIAN
4265 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
4266 #else
4267 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
4268 #endif
4269 		break;
4270 
4271 
4272 	case DIF_SUBR_HTONL:
4273 	case DIF_SUBR_NTOHL:
4274 #ifdef _BIG_ENDIAN
4275 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
4276 #else
4277 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
4278 #endif
4279 		break;
4280 
4281 
4282 	case DIF_SUBR_HTONLL:
4283 	case DIF_SUBR_NTOHLL:
4284 #ifdef _BIG_ENDIAN
4285 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
4286 #else
4287 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
4288 #endif
4289 		break;
4290 
4291 
4292 	case DIF_SUBR_DIRNAME:
4293 	case DIF_SUBR_BASENAME: {
4294 		char *dest = (char *)mstate->dtms_scratch_ptr;
4295 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4296 		uintptr_t src = tupregs[0].dttk_value;
4297 		int i, j, len = dtrace_strlen((char *)src, size);
4298 		int lastbase = -1, firstbase = -1, lastdir = -1;
4299 		int start, end;
4300 
4301 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
4302 			regs[rd] = NULL;
4303 			break;
4304 		}
4305 
4306 		if (!DTRACE_INSCRATCH(mstate, size)) {
4307 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4308 			regs[rd] = NULL;
4309 			break;
4310 		}
4311 
4312 		/*
4313 		 * The basename and dirname for a zero-length string is
4314 		 * defined to be "."
4315 		 */
4316 		if (len == 0) {
4317 			len = 1;
4318 			src = (uintptr_t)".";
4319 		}
4320 
4321 		/*
4322 		 * Start from the back of the string, moving back toward the
4323 		 * front until we see a character that isn't a slash.  That
4324 		 * character is the last character in the basename.
4325 		 */
4326 		for (i = len - 1; i >= 0; i--) {
4327 			if (dtrace_load8(src + i) != '/')
4328 				break;
4329 		}
4330 
4331 		if (i >= 0)
4332 			lastbase = i;
4333 
4334 		/*
4335 		 * Starting from the last character in the basename, move
4336 		 * towards the front until we find a slash.  The character
4337 		 * that we processed immediately before that is the first
4338 		 * character in the basename.
4339 		 */
4340 		for (; i >= 0; i--) {
4341 			if (dtrace_load8(src + i) == '/')
4342 				break;
4343 		}
4344 
4345 		if (i >= 0)
4346 			firstbase = i + 1;
4347 
4348 		/*
4349 		 * Now keep going until we find a non-slash character.  That
4350 		 * character is the last character in the dirname.
4351 		 */
4352 		for (; i >= 0; i--) {
4353 			if (dtrace_load8(src + i) != '/')
4354 				break;
4355 		}
4356 
4357 		if (i >= 0)
4358 			lastdir = i;
4359 
4360 		ASSERT(!(lastbase == -1 && firstbase != -1));
4361 		ASSERT(!(firstbase == -1 && lastdir != -1));
4362 
4363 		if (lastbase == -1) {
4364 			/*
4365 			 * We didn't find a non-slash character.  We know that
4366 			 * the length is non-zero, so the whole string must be
4367 			 * slashes.  In either the dirname or the basename
4368 			 * case, we return '/'.
4369 			 */
4370 			ASSERT(firstbase == -1);
4371 			firstbase = lastbase = lastdir = 0;
4372 		}
4373 
4374 		if (firstbase == -1) {
4375 			/*
4376 			 * The entire string consists only of a basename
4377 			 * component.  If we're looking for dirname, we need
4378 			 * to change our string to be just "."; if we're
4379 			 * looking for a basename, we'll just set the first
4380 			 * character of the basename to be 0.
4381 			 */
4382 			if (subr == DIF_SUBR_DIRNAME) {
4383 				ASSERT(lastdir == -1);
4384 				src = (uintptr_t)".";
4385 				lastdir = 0;
4386 			} else {
4387 				firstbase = 0;
4388 			}
4389 		}
4390 
4391 		if (subr == DIF_SUBR_DIRNAME) {
4392 			if (lastdir == -1) {
4393 				/*
4394 				 * We know that we have a slash in the name --
4395 				 * or lastdir would be set to 0, above.  And
4396 				 * because lastdir is -1, we know that this
4397 				 * slash must be the first character.  (That
4398 				 * is, the full string must be of the form
4399 				 * "/basename".)  In this case, the last
4400 				 * character of the directory name is 0.
4401 				 */
4402 				lastdir = 0;
4403 			}
4404 
4405 			start = 0;
4406 			end = lastdir;
4407 		} else {
4408 			ASSERT(subr == DIF_SUBR_BASENAME);
4409 			ASSERT(firstbase != -1 && lastbase != -1);
4410 			start = firstbase;
4411 			end = lastbase;
4412 		}
4413 
4414 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
4415 			dest[j] = dtrace_load8(src + i);
4416 
4417 		dest[j] = '\0';
4418 		regs[rd] = (uintptr_t)dest;
4419 		mstate->dtms_scratch_ptr += size;
4420 		break;
4421 	}
4422 
4423 	case DIF_SUBR_CLEANPATH: {
4424 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4425 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4426 		uintptr_t src = tupregs[0].dttk_value;
4427 		int i = 0, j = 0;
4428 
4429 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
4430 			regs[rd] = NULL;
4431 			break;
4432 		}
4433 
4434 		if (!DTRACE_INSCRATCH(mstate, size)) {
4435 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4436 			regs[rd] = NULL;
4437 			break;
4438 		}
4439 
4440 		/*
4441 		 * Move forward, loading each character.
4442 		 */
4443 		do {
4444 			c = dtrace_load8(src + i++);
4445 next:
4446 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
4447 				break;
4448 
4449 			if (c != '/') {
4450 				dest[j++] = c;
4451 				continue;
4452 			}
4453 
4454 			c = dtrace_load8(src + i++);
4455 
4456 			if (c == '/') {
4457 				/*
4458 				 * We have two slashes -- we can just advance
4459 				 * to the next character.
4460 				 */
4461 				goto next;
4462 			}
4463 
4464 			if (c != '.') {
4465 				/*
4466 				 * This is not "." and it's not ".." -- we can
4467 				 * just store the "/" and this character and
4468 				 * drive on.
4469 				 */
4470 				dest[j++] = '/';
4471 				dest[j++] = c;
4472 				continue;
4473 			}
4474 
4475 			c = dtrace_load8(src + i++);
4476 
4477 			if (c == '/') {
4478 				/*
4479 				 * This is a "/./" component.  We're not going
4480 				 * to store anything in the destination buffer;
4481 				 * we're just going to go to the next component.
4482 				 */
4483 				goto next;
4484 			}
4485 
4486 			if (c != '.') {
4487 				/*
4488 				 * This is not ".." -- we can just store the
4489 				 * "/." and this character and continue
4490 				 * processing.
4491 				 */
4492 				dest[j++] = '/';
4493 				dest[j++] = '.';
4494 				dest[j++] = c;
4495 				continue;
4496 			}
4497 
4498 			c = dtrace_load8(src + i++);
4499 
4500 			if (c != '/' && c != '\0') {
4501 				/*
4502 				 * This is not ".." -- it's "..[mumble]".
4503 				 * We'll store the "/.." and this character
4504 				 * and continue processing.
4505 				 */
4506 				dest[j++] = '/';
4507 				dest[j++] = '.';
4508 				dest[j++] = '.';
4509 				dest[j++] = c;
4510 				continue;
4511 			}
4512 
4513 			/*
4514 			 * This is "/../" or "/..\0".  We need to back up
4515 			 * our destination pointer until we find a "/".
4516 			 */
4517 			i--;
4518 			while (j != 0 && dest[--j] != '/')
4519 				continue;
4520 
4521 			if (c == '\0')
4522 				dest[++j] = '/';
4523 		} while (c != '\0');
4524 
4525 		dest[j] = '\0';
4526 		regs[rd] = (uintptr_t)dest;
4527 		mstate->dtms_scratch_ptr += size;
4528 		break;
4529 	}
4530 
4531 	case DIF_SUBR_INET_NTOA:
4532 	case DIF_SUBR_INET_NTOA6:
4533 	case DIF_SUBR_INET_NTOP: {
4534 		size_t size;
4535 		int af, argi, i;
4536 		char *base, *end;
4537 
4538 		if (subr == DIF_SUBR_INET_NTOP) {
4539 			af = (int)tupregs[0].dttk_value;
4540 			argi = 1;
4541 		} else {
4542 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4543 			argi = 0;
4544 		}
4545 
4546 		if (af == AF_INET) {
4547 			ipaddr_t ip4;
4548 			uint8_t *ptr8, val;
4549 
4550 			/*
4551 			 * Safely load the IPv4 address.
4552 			 */
4553 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
4554 
4555 			/*
4556 			 * Check an IPv4 string will fit in scratch.
4557 			 */
4558 			size = INET_ADDRSTRLEN;
4559 			if (!DTRACE_INSCRATCH(mstate, size)) {
4560 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4561 				regs[rd] = NULL;
4562 				break;
4563 			}
4564 			base = (char *)mstate->dtms_scratch_ptr;
4565 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4566 
4567 			/*
4568 			 * Stringify as a dotted decimal quad.
4569 			 */
4570 			*end-- = '\0';
4571 			ptr8 = (uint8_t *)&ip4;
4572 			for (i = 3; i >= 0; i--) {
4573 				val = ptr8[i];
4574 
4575 				if (val == 0) {
4576 					*end-- = '0';
4577 				} else {
4578 					for (; val; val /= 10) {
4579 						*end-- = '0' + (val % 10);
4580 					}
4581 				}
4582 
4583 				if (i > 0)
4584 					*end-- = '.';
4585 			}
4586 			ASSERT(end + 1 >= base);
4587 
4588 		} else if (af == AF_INET6) {
4589 			struct in6_addr ip6;
4590 			int firstzero, tryzero, numzero, v6end;
4591 			uint16_t val;
4592 			const char digits[] = "0123456789abcdef";
4593 
4594 			/*
4595 			 * Stringify using RFC 1884 convention 2 - 16 bit
4596 			 * hexadecimal values with a zero-run compression.
4597 			 * Lower case hexadecimal digits are used.
4598 			 * 	eg, fe80::214:4fff:fe0b:76c8.
4599 			 * The IPv4 embedded form is returned for inet_ntop,
4600 			 * just the IPv4 string is returned for inet_ntoa6.
4601 			 */
4602 
4603 			/*
4604 			 * Safely load the IPv6 address.
4605 			 */
4606 			dtrace_bcopy(
4607 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
4608 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4609 
4610 			/*
4611 			 * Check an IPv6 string will fit in scratch.
4612 			 */
4613 			size = INET6_ADDRSTRLEN;
4614 			if (!DTRACE_INSCRATCH(mstate, size)) {
4615 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4616 				regs[rd] = NULL;
4617 				break;
4618 			}
4619 			base = (char *)mstate->dtms_scratch_ptr;
4620 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4621 			*end-- = '\0';
4622 
4623 			/*
4624 			 * Find the longest run of 16 bit zero values
4625 			 * for the single allowed zero compression - "::".
4626 			 */
4627 			firstzero = -1;
4628 			tryzero = -1;
4629 			numzero = 1;
4630 			for (i = 0; i < sizeof (struct in6_addr); i++) {
4631 				if (ip6._S6_un._S6_u8[i] == 0 &&
4632 				    tryzero == -1 && i % 2 == 0) {
4633 					tryzero = i;
4634 					continue;
4635 				}
4636 
4637 				if (tryzero != -1 &&
4638 				    (ip6._S6_un._S6_u8[i] != 0 ||
4639 				    i == sizeof (struct in6_addr) - 1)) {
4640 
4641 					if (i - tryzero <= numzero) {
4642 						tryzero = -1;
4643 						continue;
4644 					}
4645 
4646 					firstzero = tryzero;
4647 					numzero = i - i % 2 - tryzero;
4648 					tryzero = -1;
4649 
4650 					if (ip6._S6_un._S6_u8[i] == 0 &&
4651 					    i == sizeof (struct in6_addr) - 1)
4652 						numzero += 2;
4653 				}
4654 			}
4655 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4656 
4657 			/*
4658 			 * Check for an IPv4 embedded address.
4659 			 */
4660 			v6end = sizeof (struct in6_addr) - 2;
4661 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4662 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
4663 				for (i = sizeof (struct in6_addr) - 1;
4664 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
4665 					ASSERT(end >= base);
4666 
4667 					val = ip6._S6_un._S6_u8[i];
4668 
4669 					if (val == 0) {
4670 						*end-- = '0';
4671 					} else {
4672 						for (; val; val /= 10) {
4673 							*end-- = '0' + val % 10;
4674 						}
4675 					}
4676 
4677 					if (i > DTRACE_V4MAPPED_OFFSET)
4678 						*end-- = '.';
4679 				}
4680 
4681 				if (subr == DIF_SUBR_INET_NTOA6)
4682 					goto inetout;
4683 
4684 				/*
4685 				 * Set v6end to skip the IPv4 address that
4686 				 * we have already stringified.
4687 				 */
4688 				v6end = 10;
4689 			}
4690 
4691 			/*
4692 			 * Build the IPv6 string by working through the
4693 			 * address in reverse.
4694 			 */
4695 			for (i = v6end; i >= 0; i -= 2) {
4696 				ASSERT(end >= base);
4697 
4698 				if (i == firstzero + numzero - 2) {
4699 					*end-- = ':';
4700 					*end-- = ':';
4701 					i -= numzero - 2;
4702 					continue;
4703 				}
4704 
4705 				if (i < 14 && i != firstzero - 2)
4706 					*end-- = ':';
4707 
4708 				val = (ip6._S6_un._S6_u8[i] << 8) +
4709 				    ip6._S6_un._S6_u8[i + 1];
4710 
4711 				if (val == 0) {
4712 					*end-- = '0';
4713 				} else {
4714 					for (; val; val /= 16) {
4715 						*end-- = digits[val % 16];
4716 					}
4717 				}
4718 			}
4719 			ASSERT(end + 1 >= base);
4720 
4721 		} else {
4722 			/*
4723 			 * The user didn't use AH_INET or AH_INET6.
4724 			 */
4725 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4726 			regs[rd] = NULL;
4727 			break;
4728 		}
4729 
4730 inetout:	regs[rd] = (uintptr_t)end + 1;
4731 		mstate->dtms_scratch_ptr += size;
4732 		break;
4733 	}
4734 
4735 	}
4736 }
4737 
4738 /*
4739  * Emulate the execution of DTrace IR instructions specified by the given
4740  * DIF object.  This function is deliberately void of assertions as all of
4741  * the necessary checks are handled by a call to dtrace_difo_validate().
4742  */
4743 static uint64_t
4744 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4745     dtrace_vstate_t *vstate, dtrace_state_t *state)
4746 {
4747 	const dif_instr_t *text = difo->dtdo_buf;
4748 	const uint_t textlen = difo->dtdo_len;
4749 	const char *strtab = difo->dtdo_strtab;
4750 	const uint64_t *inttab = difo->dtdo_inttab;
4751 
4752 	uint64_t rval = 0;
4753 	dtrace_statvar_t *svar;
4754 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4755 	dtrace_difv_t *v;
4756 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4757 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4758 
4759 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4760 	uint64_t regs[DIF_DIR_NREGS];
4761 	uint64_t *tmp;
4762 
4763 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4764 	int64_t cc_r;
4765 	uint_t pc = 0, id, opc;
4766 	uint8_t ttop = 0;
4767 	dif_instr_t instr;
4768 	uint_t r1, r2, rd;
4769 
4770 	/*
4771 	 * We stash the current DIF object into the machine state: we need it
4772 	 * for subsequent access checking.
4773 	 */
4774 	mstate->dtms_difo = difo;
4775 
4776 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
4777 
4778 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4779 		opc = pc;
4780 
4781 		instr = text[pc++];
4782 		r1 = DIF_INSTR_R1(instr);
4783 		r2 = DIF_INSTR_R2(instr);
4784 		rd = DIF_INSTR_RD(instr);
4785 
4786 		switch (DIF_INSTR_OP(instr)) {
4787 		case DIF_OP_OR:
4788 			regs[rd] = regs[r1] | regs[r2];
4789 			break;
4790 		case DIF_OP_XOR:
4791 			regs[rd] = regs[r1] ^ regs[r2];
4792 			break;
4793 		case DIF_OP_AND:
4794 			regs[rd] = regs[r1] & regs[r2];
4795 			break;
4796 		case DIF_OP_SLL:
4797 			regs[rd] = regs[r1] << regs[r2];
4798 			break;
4799 		case DIF_OP_SRL:
4800 			regs[rd] = regs[r1] >> regs[r2];
4801 			break;
4802 		case DIF_OP_SUB:
4803 			regs[rd] = regs[r1] - regs[r2];
4804 			break;
4805 		case DIF_OP_ADD:
4806 			regs[rd] = regs[r1] + regs[r2];
4807 			break;
4808 		case DIF_OP_MUL:
4809 			regs[rd] = regs[r1] * regs[r2];
4810 			break;
4811 		case DIF_OP_SDIV:
4812 			if (regs[r2] == 0) {
4813 				regs[rd] = 0;
4814 				*flags |= CPU_DTRACE_DIVZERO;
4815 			} else {
4816 				regs[rd] = (int64_t)regs[r1] /
4817 				    (int64_t)regs[r2];
4818 			}
4819 			break;
4820 
4821 		case DIF_OP_UDIV:
4822 			if (regs[r2] == 0) {
4823 				regs[rd] = 0;
4824 				*flags |= CPU_DTRACE_DIVZERO;
4825 			} else {
4826 				regs[rd] = regs[r1] / regs[r2];
4827 			}
4828 			break;
4829 
4830 		case DIF_OP_SREM:
4831 			if (regs[r2] == 0) {
4832 				regs[rd] = 0;
4833 				*flags |= CPU_DTRACE_DIVZERO;
4834 			} else {
4835 				regs[rd] = (int64_t)regs[r1] %
4836 				    (int64_t)regs[r2];
4837 			}
4838 			break;
4839 
4840 		case DIF_OP_UREM:
4841 			if (regs[r2] == 0) {
4842 				regs[rd] = 0;
4843 				*flags |= CPU_DTRACE_DIVZERO;
4844 			} else {
4845 				regs[rd] = regs[r1] % regs[r2];
4846 			}
4847 			break;
4848 
4849 		case DIF_OP_NOT:
4850 			regs[rd] = ~regs[r1];
4851 			break;
4852 		case DIF_OP_MOV:
4853 			regs[rd] = regs[r1];
4854 			break;
4855 		case DIF_OP_CMP:
4856 			cc_r = regs[r1] - regs[r2];
4857 			cc_n = cc_r < 0;
4858 			cc_z = cc_r == 0;
4859 			cc_v = 0;
4860 			cc_c = regs[r1] < regs[r2];
4861 			break;
4862 		case DIF_OP_TST:
4863 			cc_n = cc_v = cc_c = 0;
4864 			cc_z = regs[r1] == 0;
4865 			break;
4866 		case DIF_OP_BA:
4867 			pc = DIF_INSTR_LABEL(instr);
4868 			break;
4869 		case DIF_OP_BE:
4870 			if (cc_z)
4871 				pc = DIF_INSTR_LABEL(instr);
4872 			break;
4873 		case DIF_OP_BNE:
4874 			if (cc_z == 0)
4875 				pc = DIF_INSTR_LABEL(instr);
4876 			break;
4877 		case DIF_OP_BG:
4878 			if ((cc_z | (cc_n ^ cc_v)) == 0)
4879 				pc = DIF_INSTR_LABEL(instr);
4880 			break;
4881 		case DIF_OP_BGU:
4882 			if ((cc_c | cc_z) == 0)
4883 				pc = DIF_INSTR_LABEL(instr);
4884 			break;
4885 		case DIF_OP_BGE:
4886 			if ((cc_n ^ cc_v) == 0)
4887 				pc = DIF_INSTR_LABEL(instr);
4888 			break;
4889 		case DIF_OP_BGEU:
4890 			if (cc_c == 0)
4891 				pc = DIF_INSTR_LABEL(instr);
4892 			break;
4893 		case DIF_OP_BL:
4894 			if (cc_n ^ cc_v)
4895 				pc = DIF_INSTR_LABEL(instr);
4896 			break;
4897 		case DIF_OP_BLU:
4898 			if (cc_c)
4899 				pc = DIF_INSTR_LABEL(instr);
4900 			break;
4901 		case DIF_OP_BLE:
4902 			if (cc_z | (cc_n ^ cc_v))
4903 				pc = DIF_INSTR_LABEL(instr);
4904 			break;
4905 		case DIF_OP_BLEU:
4906 			if (cc_c | cc_z)
4907 				pc = DIF_INSTR_LABEL(instr);
4908 			break;
4909 		case DIF_OP_RLDSB:
4910 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4911 				*flags |= CPU_DTRACE_KPRIV;
4912 				*illval = regs[r1];
4913 				break;
4914 			}
4915 			/*FALLTHROUGH*/
4916 		case DIF_OP_LDSB:
4917 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
4918 			break;
4919 		case DIF_OP_RLDSH:
4920 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4921 				*flags |= CPU_DTRACE_KPRIV;
4922 				*illval = regs[r1];
4923 				break;
4924 			}
4925 			/*FALLTHROUGH*/
4926 		case DIF_OP_LDSH:
4927 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
4928 			break;
4929 		case DIF_OP_RLDSW:
4930 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4931 				*flags |= CPU_DTRACE_KPRIV;
4932 				*illval = regs[r1];
4933 				break;
4934 			}
4935 			/*FALLTHROUGH*/
4936 		case DIF_OP_LDSW:
4937 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
4938 			break;
4939 		case DIF_OP_RLDUB:
4940 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4941 				*flags |= CPU_DTRACE_KPRIV;
4942 				*illval = regs[r1];
4943 				break;
4944 			}
4945 			/*FALLTHROUGH*/
4946 		case DIF_OP_LDUB:
4947 			regs[rd] = dtrace_load8(regs[r1]);
4948 			break;
4949 		case DIF_OP_RLDUH:
4950 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4951 				*flags |= CPU_DTRACE_KPRIV;
4952 				*illval = regs[r1];
4953 				break;
4954 			}
4955 			/*FALLTHROUGH*/
4956 		case DIF_OP_LDUH:
4957 			regs[rd] = dtrace_load16(regs[r1]);
4958 			break;
4959 		case DIF_OP_RLDUW:
4960 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4961 				*flags |= CPU_DTRACE_KPRIV;
4962 				*illval = regs[r1];
4963 				break;
4964 			}
4965 			/*FALLTHROUGH*/
4966 		case DIF_OP_LDUW:
4967 			regs[rd] = dtrace_load32(regs[r1]);
4968 			break;
4969 		case DIF_OP_RLDX:
4970 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
4971 				*flags |= CPU_DTRACE_KPRIV;
4972 				*illval = regs[r1];
4973 				break;
4974 			}
4975 			/*FALLTHROUGH*/
4976 		case DIF_OP_LDX:
4977 			regs[rd] = dtrace_load64(regs[r1]);
4978 			break;
4979 		case DIF_OP_ULDSB:
4980 			regs[rd] = (int8_t)
4981 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4982 			break;
4983 		case DIF_OP_ULDSH:
4984 			regs[rd] = (int16_t)
4985 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4986 			break;
4987 		case DIF_OP_ULDSW:
4988 			regs[rd] = (int32_t)
4989 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4990 			break;
4991 		case DIF_OP_ULDUB:
4992 			regs[rd] =
4993 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4994 			break;
4995 		case DIF_OP_ULDUH:
4996 			regs[rd] =
4997 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4998 			break;
4999 		case DIF_OP_ULDUW:
5000 			regs[rd] =
5001 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5002 			break;
5003 		case DIF_OP_ULDX:
5004 			regs[rd] =
5005 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5006 			break;
5007 		case DIF_OP_RET:
5008 			rval = regs[rd];
5009 			pc = textlen;
5010 			break;
5011 		case DIF_OP_NOP:
5012 			break;
5013 		case DIF_OP_SETX:
5014 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
5015 			break;
5016 		case DIF_OP_SETS:
5017 			regs[rd] = (uint64_t)(uintptr_t)
5018 			    (strtab + DIF_INSTR_STRING(instr));
5019 			break;
5020 		case DIF_OP_SCMP: {
5021 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
5022 			uintptr_t s1 = regs[r1];
5023 			uintptr_t s2 = regs[r2];
5024 
5025 			if (s1 != NULL &&
5026 			    !dtrace_strcanload(s1, sz, mstate, vstate))
5027 				break;
5028 			if (s2 != NULL &&
5029 			    !dtrace_strcanload(s2, sz, mstate, vstate))
5030 				break;
5031 
5032 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
5033 
5034 			cc_n = cc_r < 0;
5035 			cc_z = cc_r == 0;
5036 			cc_v = cc_c = 0;
5037 			break;
5038 		}
5039 		case DIF_OP_LDGA:
5040 			regs[rd] = dtrace_dif_variable(mstate, state,
5041 			    r1, regs[r2]);
5042 			break;
5043 		case DIF_OP_LDGS:
5044 			id = DIF_INSTR_VAR(instr);
5045 
5046 			if (id >= DIF_VAR_OTHER_UBASE) {
5047 				uintptr_t a;
5048 
5049 				id -= DIF_VAR_OTHER_UBASE;
5050 				svar = vstate->dtvs_globals[id];
5051 				ASSERT(svar != NULL);
5052 				v = &svar->dtsv_var;
5053 
5054 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
5055 					regs[rd] = svar->dtsv_data;
5056 					break;
5057 				}
5058 
5059 				a = (uintptr_t)svar->dtsv_data;
5060 
5061 				if (*(uint8_t *)a == UINT8_MAX) {
5062 					/*
5063 					 * If the 0th byte is set to UINT8_MAX
5064 					 * then this is to be treated as a
5065 					 * reference to a NULL variable.
5066 					 */
5067 					regs[rd] = NULL;
5068 				} else {
5069 					regs[rd] = a + sizeof (uint64_t);
5070 				}
5071 
5072 				break;
5073 			}
5074 
5075 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
5076 			break;
5077 
5078 		case DIF_OP_STGS:
5079 			id = DIF_INSTR_VAR(instr);
5080 
5081 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5082 			id -= DIF_VAR_OTHER_UBASE;
5083 
5084 			svar = vstate->dtvs_globals[id];
5085 			ASSERT(svar != NULL);
5086 			v = &svar->dtsv_var;
5087 
5088 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5089 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5090 
5091 				ASSERT(a != NULL);
5092 				ASSERT(svar->dtsv_size != 0);
5093 
5094 				if (regs[rd] == NULL) {
5095 					*(uint8_t *)a = UINT8_MAX;
5096 					break;
5097 				} else {
5098 					*(uint8_t *)a = 0;
5099 					a += sizeof (uint64_t);
5100 				}
5101 				if (!dtrace_vcanload(
5102 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5103 				    mstate, vstate))
5104 					break;
5105 
5106 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5107 				    (void *)a, &v->dtdv_type);
5108 				break;
5109 			}
5110 
5111 			svar->dtsv_data = regs[rd];
5112 			break;
5113 
5114 		case DIF_OP_LDTA:
5115 			/*
5116 			 * There are no DTrace built-in thread-local arrays at
5117 			 * present.  This opcode is saved for future work.
5118 			 */
5119 			*flags |= CPU_DTRACE_ILLOP;
5120 			regs[rd] = 0;
5121 			break;
5122 
5123 		case DIF_OP_LDLS:
5124 			id = DIF_INSTR_VAR(instr);
5125 
5126 			if (id < DIF_VAR_OTHER_UBASE) {
5127 				/*
5128 				 * For now, this has no meaning.
5129 				 */
5130 				regs[rd] = 0;
5131 				break;
5132 			}
5133 
5134 			id -= DIF_VAR_OTHER_UBASE;
5135 
5136 			ASSERT(id < vstate->dtvs_nlocals);
5137 			ASSERT(vstate->dtvs_locals != NULL);
5138 
5139 			svar = vstate->dtvs_locals[id];
5140 			ASSERT(svar != NULL);
5141 			v = &svar->dtsv_var;
5142 
5143 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5144 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5145 				size_t sz = v->dtdv_type.dtdt_size;
5146 
5147 				sz += sizeof (uint64_t);
5148 				ASSERT(svar->dtsv_size == NCPU * sz);
5149 				a += CPU->cpu_id * sz;
5150 
5151 				if (*(uint8_t *)a == UINT8_MAX) {
5152 					/*
5153 					 * If the 0th byte is set to UINT8_MAX
5154 					 * then this is to be treated as a
5155 					 * reference to a NULL variable.
5156 					 */
5157 					regs[rd] = NULL;
5158 				} else {
5159 					regs[rd] = a + sizeof (uint64_t);
5160 				}
5161 
5162 				break;
5163 			}
5164 
5165 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5166 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5167 			regs[rd] = tmp[CPU->cpu_id];
5168 			break;
5169 
5170 		case DIF_OP_STLS:
5171 			id = DIF_INSTR_VAR(instr);
5172 
5173 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5174 			id -= DIF_VAR_OTHER_UBASE;
5175 			ASSERT(id < vstate->dtvs_nlocals);
5176 
5177 			ASSERT(vstate->dtvs_locals != NULL);
5178 			svar = vstate->dtvs_locals[id];
5179 			ASSERT(svar != NULL);
5180 			v = &svar->dtsv_var;
5181 
5182 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5183 				uintptr_t a = (uintptr_t)svar->dtsv_data;
5184 				size_t sz = v->dtdv_type.dtdt_size;
5185 
5186 				sz += sizeof (uint64_t);
5187 				ASSERT(svar->dtsv_size == NCPU * sz);
5188 				a += CPU->cpu_id * sz;
5189 
5190 				if (regs[rd] == NULL) {
5191 					*(uint8_t *)a = UINT8_MAX;
5192 					break;
5193 				} else {
5194 					*(uint8_t *)a = 0;
5195 					a += sizeof (uint64_t);
5196 				}
5197 
5198 				if (!dtrace_vcanload(
5199 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5200 				    mstate, vstate))
5201 					break;
5202 
5203 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5204 				    (void *)a, &v->dtdv_type);
5205 				break;
5206 			}
5207 
5208 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
5209 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
5210 			tmp[CPU->cpu_id] = regs[rd];
5211 			break;
5212 
5213 		case DIF_OP_LDTS: {
5214 			dtrace_dynvar_t *dvar;
5215 			dtrace_key_t *key;
5216 
5217 			id = DIF_INSTR_VAR(instr);
5218 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5219 			id -= DIF_VAR_OTHER_UBASE;
5220 			v = &vstate->dtvs_tlocals[id];
5221 
5222 			key = &tupregs[DIF_DTR_NREGS];
5223 			key[0].dttk_value = (uint64_t)id;
5224 			key[0].dttk_size = 0;
5225 			DTRACE_TLS_THRKEY(key[1].dttk_value);
5226 			key[1].dttk_size = 0;
5227 
5228 			dvar = dtrace_dynvar(dstate, 2, key,
5229 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
5230 			    mstate, vstate);
5231 
5232 			if (dvar == NULL) {
5233 				regs[rd] = 0;
5234 				break;
5235 			}
5236 
5237 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5238 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5239 			} else {
5240 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
5241 			}
5242 
5243 			break;
5244 		}
5245 
5246 		case DIF_OP_STTS: {
5247 			dtrace_dynvar_t *dvar;
5248 			dtrace_key_t *key;
5249 
5250 			id = DIF_INSTR_VAR(instr);
5251 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5252 			id -= DIF_VAR_OTHER_UBASE;
5253 
5254 			key = &tupregs[DIF_DTR_NREGS];
5255 			key[0].dttk_value = (uint64_t)id;
5256 			key[0].dttk_size = 0;
5257 			DTRACE_TLS_THRKEY(key[1].dttk_value);
5258 			key[1].dttk_size = 0;
5259 			v = &vstate->dtvs_tlocals[id];
5260 
5261 			dvar = dtrace_dynvar(dstate, 2, key,
5262 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5263 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5264 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
5265 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5266 
5267 			/*
5268 			 * Given that we're storing to thread-local data,
5269 			 * we need to flush our predicate cache.
5270 			 */
5271 			curthread->t_predcache = NULL;
5272 
5273 			if (dvar == NULL)
5274 				break;
5275 
5276 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5277 				if (!dtrace_vcanload(
5278 				    (void *)(uintptr_t)regs[rd],
5279 				    &v->dtdv_type, mstate, vstate))
5280 					break;
5281 
5282 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5283 				    dvar->dtdv_data, &v->dtdv_type);
5284 			} else {
5285 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
5286 			}
5287 
5288 			break;
5289 		}
5290 
5291 		case DIF_OP_SRA:
5292 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
5293 			break;
5294 
5295 		case DIF_OP_CALL:
5296 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
5297 			    regs, tupregs, ttop, mstate, state);
5298 			break;
5299 
5300 		case DIF_OP_PUSHTR:
5301 			if (ttop == DIF_DTR_NREGS) {
5302 				*flags |= CPU_DTRACE_TUPOFLOW;
5303 				break;
5304 			}
5305 
5306 			if (r1 == DIF_TYPE_STRING) {
5307 				/*
5308 				 * If this is a string type and the size is 0,
5309 				 * we'll use the system-wide default string
5310 				 * size.  Note that we are _not_ looking at
5311 				 * the value of the DTRACEOPT_STRSIZE option;
5312 				 * had this been set, we would expect to have
5313 				 * a non-zero size value in the "pushtr".
5314 				 */
5315 				tupregs[ttop].dttk_size =
5316 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
5317 				    regs[r2] ? regs[r2] :
5318 				    dtrace_strsize_default) + 1;
5319 			} else {
5320 				tupregs[ttop].dttk_size = regs[r2];
5321 			}
5322 
5323 			tupregs[ttop++].dttk_value = regs[rd];
5324 			break;
5325 
5326 		case DIF_OP_PUSHTV:
5327 			if (ttop == DIF_DTR_NREGS) {
5328 				*flags |= CPU_DTRACE_TUPOFLOW;
5329 				break;
5330 			}
5331 
5332 			tupregs[ttop].dttk_value = regs[rd];
5333 			tupregs[ttop++].dttk_size = 0;
5334 			break;
5335 
5336 		case DIF_OP_POPTS:
5337 			if (ttop != 0)
5338 				ttop--;
5339 			break;
5340 
5341 		case DIF_OP_FLUSHTS:
5342 			ttop = 0;
5343 			break;
5344 
5345 		case DIF_OP_LDGAA:
5346 		case DIF_OP_LDTAA: {
5347 			dtrace_dynvar_t *dvar;
5348 			dtrace_key_t *key = tupregs;
5349 			uint_t nkeys = ttop;
5350 
5351 			id = DIF_INSTR_VAR(instr);
5352 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5353 			id -= DIF_VAR_OTHER_UBASE;
5354 
5355 			key[nkeys].dttk_value = (uint64_t)id;
5356 			key[nkeys++].dttk_size = 0;
5357 
5358 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5359 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5360 				key[nkeys++].dttk_size = 0;
5361 				v = &vstate->dtvs_tlocals[id];
5362 			} else {
5363 				v = &vstate->dtvs_globals[id]->dtsv_var;
5364 			}
5365 
5366 			dvar = dtrace_dynvar(dstate, nkeys, key,
5367 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5368 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5369 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5370 
5371 			if (dvar == NULL) {
5372 				regs[rd] = 0;
5373 				break;
5374 			}
5375 
5376 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5377 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5378 			} else {
5379 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
5380 			}
5381 
5382 			break;
5383 		}
5384 
5385 		case DIF_OP_STGAA:
5386 		case DIF_OP_STTAA: {
5387 			dtrace_dynvar_t *dvar;
5388 			dtrace_key_t *key = tupregs;
5389 			uint_t nkeys = ttop;
5390 
5391 			id = DIF_INSTR_VAR(instr);
5392 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5393 			id -= DIF_VAR_OTHER_UBASE;
5394 
5395 			key[nkeys].dttk_value = (uint64_t)id;
5396 			key[nkeys++].dttk_size = 0;
5397 
5398 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5399 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5400 				key[nkeys++].dttk_size = 0;
5401 				v = &vstate->dtvs_tlocals[id];
5402 			} else {
5403 				v = &vstate->dtvs_globals[id]->dtsv_var;
5404 			}
5405 
5406 			dvar = dtrace_dynvar(dstate, nkeys, key,
5407 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5408 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5409 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
5410 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5411 
5412 			if (dvar == NULL)
5413 				break;
5414 
5415 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5416 				if (!dtrace_vcanload(
5417 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5418 				    mstate, vstate))
5419 					break;
5420 
5421 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5422 				    dvar->dtdv_data, &v->dtdv_type);
5423 			} else {
5424 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
5425 			}
5426 
5427 			break;
5428 		}
5429 
5430 		case DIF_OP_ALLOCS: {
5431 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5432 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5433 
5434 			/*
5435 			 * Rounding up the user allocation size could have
5436 			 * overflowed large, bogus allocations (like -1ULL) to
5437 			 * 0.
5438 			 */
5439 			if (size < regs[r1] ||
5440 			    !DTRACE_INSCRATCH(mstate, size)) {
5441 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5442 				regs[rd] = NULL;
5443 				break;
5444 			}
5445 
5446 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5447 			mstate->dtms_scratch_ptr += size;
5448 			regs[rd] = ptr;
5449 			break;
5450 		}
5451 
5452 		case DIF_OP_COPYS:
5453 			if (!dtrace_canstore(regs[rd], regs[r2],
5454 			    mstate, vstate)) {
5455 				*flags |= CPU_DTRACE_BADADDR;
5456 				*illval = regs[rd];
5457 				break;
5458 			}
5459 
5460 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5461 				break;
5462 
5463 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
5464 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5465 			break;
5466 
5467 		case DIF_OP_STB:
5468 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5469 				*flags |= CPU_DTRACE_BADADDR;
5470 				*illval = regs[rd];
5471 				break;
5472 			}
5473 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5474 			break;
5475 
5476 		case DIF_OP_STH:
5477 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5478 				*flags |= CPU_DTRACE_BADADDR;
5479 				*illval = regs[rd];
5480 				break;
5481 			}
5482 			if (regs[rd] & 1) {
5483 				*flags |= CPU_DTRACE_BADALIGN;
5484 				*illval = regs[rd];
5485 				break;
5486 			}
5487 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5488 			break;
5489 
5490 		case DIF_OP_STW:
5491 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5492 				*flags |= CPU_DTRACE_BADADDR;
5493 				*illval = regs[rd];
5494 				break;
5495 			}
5496 			if (regs[rd] & 3) {
5497 				*flags |= CPU_DTRACE_BADALIGN;
5498 				*illval = regs[rd];
5499 				break;
5500 			}
5501 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5502 			break;
5503 
5504 		case DIF_OP_STX:
5505 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5506 				*flags |= CPU_DTRACE_BADADDR;
5507 				*illval = regs[rd];
5508 				break;
5509 			}
5510 			if (regs[rd] & 7) {
5511 				*flags |= CPU_DTRACE_BADALIGN;
5512 				*illval = regs[rd];
5513 				break;
5514 			}
5515 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5516 			break;
5517 		}
5518 	}
5519 
5520 	if (!(*flags & CPU_DTRACE_FAULT))
5521 		return (rval);
5522 
5523 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5524 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5525 
5526 	return (0);
5527 }
5528 
5529 static void
5530 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5531 {
5532 	dtrace_probe_t *probe = ecb->dte_probe;
5533 	dtrace_provider_t *prov = probe->dtpr_provider;
5534 	char c[DTRACE_FULLNAMELEN + 80], *str;
5535 	char *msg = "dtrace: breakpoint action at probe ";
5536 	char *ecbmsg = " (ecb ";
5537 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5538 	uintptr_t val = (uintptr_t)ecb;
5539 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5540 
5541 	if (dtrace_destructive_disallow)
5542 		return;
5543 
5544 	/*
5545 	 * It's impossible to be taking action on the NULL probe.
5546 	 */
5547 	ASSERT(probe != NULL);
5548 
5549 	/*
5550 	 * This is a poor man's (destitute man's?) sprintf():  we want to
5551 	 * print the provider name, module name, function name and name of
5552 	 * the probe, along with the hex address of the ECB with the breakpoint
5553 	 * action -- all of which we must place in the character buffer by
5554 	 * hand.
5555 	 */
5556 	while (*msg != '\0')
5557 		c[i++] = *msg++;
5558 
5559 	for (str = prov->dtpv_name; *str != '\0'; str++)
5560 		c[i++] = *str;
5561 	c[i++] = ':';
5562 
5563 	for (str = probe->dtpr_mod; *str != '\0'; str++)
5564 		c[i++] = *str;
5565 	c[i++] = ':';
5566 
5567 	for (str = probe->dtpr_func; *str != '\0'; str++)
5568 		c[i++] = *str;
5569 	c[i++] = ':';
5570 
5571 	for (str = probe->dtpr_name; *str != '\0'; str++)
5572 		c[i++] = *str;
5573 
5574 	while (*ecbmsg != '\0')
5575 		c[i++] = *ecbmsg++;
5576 
5577 	while (shift >= 0) {
5578 		mask = (uintptr_t)0xf << shift;
5579 
5580 		if (val >= ((uintptr_t)1 << shift))
5581 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5582 		shift -= 4;
5583 	}
5584 
5585 	c[i++] = ')';
5586 	c[i] = '\0';
5587 
5588 	debug_enter(c);
5589 }
5590 
5591 static void
5592 dtrace_action_panic(dtrace_ecb_t *ecb)
5593 {
5594 	dtrace_probe_t *probe = ecb->dte_probe;
5595 
5596 	/*
5597 	 * It's impossible to be taking action on the NULL probe.
5598 	 */
5599 	ASSERT(probe != NULL);
5600 
5601 	if (dtrace_destructive_disallow)
5602 		return;
5603 
5604 	if (dtrace_panicked != NULL)
5605 		return;
5606 
5607 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5608 		return;
5609 
5610 	/*
5611 	 * We won the right to panic.  (We want to be sure that only one
5612 	 * thread calls panic() from dtrace_probe(), and that panic() is
5613 	 * called exactly once.)
5614 	 */
5615 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5616 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5617 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5618 }
5619 
5620 static void
5621 dtrace_action_raise(uint64_t sig)
5622 {
5623 	if (dtrace_destructive_disallow)
5624 		return;
5625 
5626 	if (sig >= NSIG) {
5627 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5628 		return;
5629 	}
5630 
5631 	/*
5632 	 * raise() has a queue depth of 1 -- we ignore all subsequent
5633 	 * invocations of the raise() action.
5634 	 */
5635 	if (curthread->t_dtrace_sig == 0)
5636 		curthread->t_dtrace_sig = (uint8_t)sig;
5637 
5638 	curthread->t_sig_check = 1;
5639 	aston(curthread);
5640 }
5641 
5642 static void
5643 dtrace_action_stop(void)
5644 {
5645 	if (dtrace_destructive_disallow)
5646 		return;
5647 
5648 	if (!curthread->t_dtrace_stop) {
5649 		curthread->t_dtrace_stop = 1;
5650 		curthread->t_sig_check = 1;
5651 		aston(curthread);
5652 	}
5653 }
5654 
5655 static void
5656 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5657 {
5658 	hrtime_t now;
5659 	volatile uint16_t *flags;
5660 	cpu_t *cpu = CPU;
5661 
5662 	if (dtrace_destructive_disallow)
5663 		return;
5664 
5665 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5666 
5667 	now = dtrace_gethrtime();
5668 
5669 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5670 		/*
5671 		 * We need to advance the mark to the current time.
5672 		 */
5673 		cpu->cpu_dtrace_chillmark = now;
5674 		cpu->cpu_dtrace_chilled = 0;
5675 	}
5676 
5677 	/*
5678 	 * Now check to see if the requested chill time would take us over
5679 	 * the maximum amount of time allowed in the chill interval.  (Or
5680 	 * worse, if the calculation itself induces overflow.)
5681 	 */
5682 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5683 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5684 		*flags |= CPU_DTRACE_ILLOP;
5685 		return;
5686 	}
5687 
5688 	while (dtrace_gethrtime() - now < val)
5689 		continue;
5690 
5691 	/*
5692 	 * Normally, we assure that the value of the variable "timestamp" does
5693 	 * not change within an ECB.  The presence of chill() represents an
5694 	 * exception to this rule, however.
5695 	 */
5696 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5697 	cpu->cpu_dtrace_chilled += val;
5698 }
5699 
5700 static void
5701 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5702     uint64_t *buf, uint64_t arg)
5703 {
5704 	int nframes = DTRACE_USTACK_NFRAMES(arg);
5705 	int strsize = DTRACE_USTACK_STRSIZE(arg);
5706 	uint64_t *pcs = &buf[1], *fps;
5707 	char *str = (char *)&pcs[nframes];
5708 	int size, offs = 0, i, j;
5709 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
5710 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5711 	char *sym;
5712 
5713 	/*
5714 	 * Should be taking a faster path if string space has not been
5715 	 * allocated.
5716 	 */
5717 	ASSERT(strsize != 0);
5718 
5719 	/*
5720 	 * We will first allocate some temporary space for the frame pointers.
5721 	 */
5722 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5723 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5724 	    (nframes * sizeof (uint64_t));
5725 
5726 	if (!DTRACE_INSCRATCH(mstate, size)) {
5727 		/*
5728 		 * Not enough room for our frame pointers -- need to indicate
5729 		 * that we ran out of scratch space.
5730 		 */
5731 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5732 		return;
5733 	}
5734 
5735 	mstate->dtms_scratch_ptr += size;
5736 	saved = mstate->dtms_scratch_ptr;
5737 
5738 	/*
5739 	 * Now get a stack with both program counters and frame pointers.
5740 	 */
5741 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5742 	dtrace_getufpstack(buf, fps, nframes + 1);
5743 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5744 
5745 	/*
5746 	 * If that faulted, we're cooked.
5747 	 */
5748 	if (*flags & CPU_DTRACE_FAULT)
5749 		goto out;
5750 
5751 	/*
5752 	 * Now we want to walk up the stack, calling the USTACK helper.  For
5753 	 * each iteration, we restore the scratch pointer.
5754 	 */
5755 	for (i = 0; i < nframes; i++) {
5756 		mstate->dtms_scratch_ptr = saved;
5757 
5758 		if (offs >= strsize)
5759 			break;
5760 
5761 		sym = (char *)(uintptr_t)dtrace_helper(
5762 		    DTRACE_HELPER_ACTION_USTACK,
5763 		    mstate, state, pcs[i], fps[i]);
5764 
5765 		/*
5766 		 * If we faulted while running the helper, we're going to
5767 		 * clear the fault and null out the corresponding string.
5768 		 */
5769 		if (*flags & CPU_DTRACE_FAULT) {
5770 			*flags &= ~CPU_DTRACE_FAULT;
5771 			str[offs++] = '\0';
5772 			continue;
5773 		}
5774 
5775 		if (sym == NULL) {
5776 			str[offs++] = '\0';
5777 			continue;
5778 		}
5779 
5780 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5781 
5782 		/*
5783 		 * Now copy in the string that the helper returned to us.
5784 		 */
5785 		for (j = 0; offs + j < strsize; j++) {
5786 			if ((str[offs + j] = sym[j]) == '\0')
5787 				break;
5788 		}
5789 
5790 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5791 
5792 		offs += j + 1;
5793 	}
5794 
5795 	if (offs >= strsize) {
5796 		/*
5797 		 * If we didn't have room for all of the strings, we don't
5798 		 * abort processing -- this needn't be a fatal error -- but we
5799 		 * still want to increment a counter (dts_stkstroverflows) to
5800 		 * allow this condition to be warned about.  (If this is from
5801 		 * a jstack() action, it is easily tuned via jstackstrsize.)
5802 		 */
5803 		dtrace_error(&state->dts_stkstroverflows);
5804 	}
5805 
5806 	while (offs < strsize)
5807 		str[offs++] = '\0';
5808 
5809 out:
5810 	mstate->dtms_scratch_ptr = old;
5811 }
5812 
5813 /*
5814  * If you're looking for the epicenter of DTrace, you just found it.  This
5815  * is the function called by the provider to fire a probe -- from which all
5816  * subsequent probe-context DTrace activity emanates.
5817  */
5818 void
5819 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
5820     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
5821 {
5822 	processorid_t cpuid;
5823 	dtrace_icookie_t cookie;
5824 	dtrace_probe_t *probe;
5825 	dtrace_mstate_t mstate;
5826 	dtrace_ecb_t *ecb;
5827 	dtrace_action_t *act;
5828 	intptr_t offs;
5829 	size_t size;
5830 	int vtime, onintr;
5831 	volatile uint16_t *flags;
5832 	hrtime_t now;
5833 
5834 	/*
5835 	 * Kick out immediately if this CPU is still being born (in which case
5836 	 * curthread will be set to -1) or the current thread can't allow
5837 	 * probes in its current context.
5838 	 */
5839 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
5840 		return;
5841 
5842 	cookie = dtrace_interrupt_disable();
5843 	probe = dtrace_probes[id - 1];
5844 	cpuid = CPU->cpu_id;
5845 	onintr = CPU_ON_INTR(CPU);
5846 
5847 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
5848 	    probe->dtpr_predcache == curthread->t_predcache) {
5849 		/*
5850 		 * We have hit in the predicate cache; we know that
5851 		 * this predicate would evaluate to be false.
5852 		 */
5853 		dtrace_interrupt_enable(cookie);
5854 		return;
5855 	}
5856 
5857 	if (panic_quiesce) {
5858 		/*
5859 		 * We don't trace anything if we're panicking.
5860 		 */
5861 		dtrace_interrupt_enable(cookie);
5862 		return;
5863 	}
5864 
5865 	now = dtrace_gethrtime();
5866 	vtime = dtrace_vtime_references != 0;
5867 
5868 	if (vtime && curthread->t_dtrace_start)
5869 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
5870 
5871 	mstate.dtms_difo = NULL;
5872 	mstate.dtms_probe = probe;
5873 	mstate.dtms_strtok = NULL;
5874 	mstate.dtms_arg[0] = arg0;
5875 	mstate.dtms_arg[1] = arg1;
5876 	mstate.dtms_arg[2] = arg2;
5877 	mstate.dtms_arg[3] = arg3;
5878 	mstate.dtms_arg[4] = arg4;
5879 
5880 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
5881 
5882 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
5883 		dtrace_predicate_t *pred = ecb->dte_predicate;
5884 		dtrace_state_t *state = ecb->dte_state;
5885 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
5886 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
5887 		dtrace_vstate_t *vstate = &state->dts_vstate;
5888 		dtrace_provider_t *prov = probe->dtpr_provider;
5889 		uint64_t tracememsize = 0;
5890 		int committed = 0;
5891 		caddr_t tomax;
5892 
5893 		/*
5894 		 * A little subtlety with the following (seemingly innocuous)
5895 		 * declaration of the automatic 'val':  by looking at the
5896 		 * code, you might think that it could be declared in the
5897 		 * action processing loop, below.  (That is, it's only used in
5898 		 * the action processing loop.)  However, it must be declared
5899 		 * out of that scope because in the case of DIF expression
5900 		 * arguments to aggregating actions, one iteration of the
5901 		 * action loop will use the last iteration's value.
5902 		 */
5903 #ifdef lint
5904 		uint64_t val = 0;
5905 #else
5906 		uint64_t val;
5907 #endif
5908 
5909 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
5910 		mstate.dtms_access = DTRACE_ACCESS_ARGS | DTRACE_ACCESS_PROC;
5911 		*flags &= ~CPU_DTRACE_ERROR;
5912 
5913 		if (prov == dtrace_provider) {
5914 			/*
5915 			 * If dtrace itself is the provider of this probe,
5916 			 * we're only going to continue processing the ECB if
5917 			 * arg0 (the dtrace_state_t) is equal to the ECB's
5918 			 * creating state.  (This prevents disjoint consumers
5919 			 * from seeing one another's metaprobes.)
5920 			 */
5921 			if (arg0 != (uint64_t)(uintptr_t)state)
5922 				continue;
5923 		}
5924 
5925 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
5926 			/*
5927 			 * We're not currently active.  If our provider isn't
5928 			 * the dtrace pseudo provider, we're not interested.
5929 			 */
5930 			if (prov != dtrace_provider)
5931 				continue;
5932 
5933 			/*
5934 			 * Now we must further check if we are in the BEGIN
5935 			 * probe.  If we are, we will only continue processing
5936 			 * if we're still in WARMUP -- if one BEGIN enabling
5937 			 * has invoked the exit() action, we don't want to
5938 			 * evaluate subsequent BEGIN enablings.
5939 			 */
5940 			if (probe->dtpr_id == dtrace_probeid_begin &&
5941 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
5942 				ASSERT(state->dts_activity ==
5943 				    DTRACE_ACTIVITY_DRAINING);
5944 				continue;
5945 			}
5946 		}
5947 
5948 		if (ecb->dte_cond && !dtrace_priv_probe(state, &mstate, ecb))
5949 			continue;
5950 
5951 		if (now - state->dts_alive > dtrace_deadman_timeout) {
5952 			/*
5953 			 * We seem to be dead.  Unless we (a) have kernel
5954 			 * destructive permissions (b) have expicitly enabled
5955 			 * destructive actions and (c) destructive actions have
5956 			 * not been disabled, we're going to transition into
5957 			 * the KILLED state, from which no further processing
5958 			 * on this state will be performed.
5959 			 */
5960 			if (!dtrace_priv_kernel_destructive(state) ||
5961 			    !state->dts_cred.dcr_destructive ||
5962 			    dtrace_destructive_disallow) {
5963 				void *activity = &state->dts_activity;
5964 				dtrace_activity_t current;
5965 
5966 				do {
5967 					current = state->dts_activity;
5968 				} while (dtrace_cas32(activity, current,
5969 				    DTRACE_ACTIVITY_KILLED) != current);
5970 
5971 				continue;
5972 			}
5973 		}
5974 
5975 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
5976 		    ecb->dte_alignment, state, &mstate)) < 0)
5977 			continue;
5978 
5979 		tomax = buf->dtb_tomax;
5980 		ASSERT(tomax != NULL);
5981 
5982 		if (ecb->dte_size != 0)
5983 			DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
5984 
5985 		mstate.dtms_epid = ecb->dte_epid;
5986 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
5987 
5988 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
5989 			mstate.dtms_access |= DTRACE_ACCESS_KERNEL;
5990 
5991 		if (pred != NULL) {
5992 			dtrace_difo_t *dp = pred->dtp_difo;
5993 			int rval;
5994 
5995 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
5996 
5997 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
5998 				dtrace_cacheid_t cid = probe->dtpr_predcache;
5999 
6000 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
6001 					/*
6002 					 * Update the predicate cache...
6003 					 */
6004 					ASSERT(cid == pred->dtp_cacheid);
6005 					curthread->t_predcache = cid;
6006 				}
6007 
6008 				continue;
6009 			}
6010 		}
6011 
6012 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
6013 		    act != NULL; act = act->dta_next) {
6014 			size_t valoffs;
6015 			dtrace_difo_t *dp;
6016 			dtrace_recdesc_t *rec = &act->dta_rec;
6017 
6018 			size = rec->dtrd_size;
6019 			valoffs = offs + rec->dtrd_offset;
6020 
6021 			if (DTRACEACT_ISAGG(act->dta_kind)) {
6022 				uint64_t v = 0xbad;
6023 				dtrace_aggregation_t *agg;
6024 
6025 				agg = (dtrace_aggregation_t *)act;
6026 
6027 				if ((dp = act->dta_difo) != NULL)
6028 					v = dtrace_dif_emulate(dp,
6029 					    &mstate, vstate, state);
6030 
6031 				if (*flags & CPU_DTRACE_ERROR)
6032 					continue;
6033 
6034 				/*
6035 				 * Note that we always pass the expression
6036 				 * value from the previous iteration of the
6037 				 * action loop.  This value will only be used
6038 				 * if there is an expression argument to the
6039 				 * aggregating action, denoted by the
6040 				 * dtag_hasarg field.
6041 				 */
6042 				dtrace_aggregate(agg, buf,
6043 				    offs, aggbuf, v, val);
6044 				continue;
6045 			}
6046 
6047 			switch (act->dta_kind) {
6048 			case DTRACEACT_STOP:
6049 				if (dtrace_priv_proc_destructive(state,
6050 				    &mstate))
6051 					dtrace_action_stop();
6052 				continue;
6053 
6054 			case DTRACEACT_BREAKPOINT:
6055 				if (dtrace_priv_kernel_destructive(state))
6056 					dtrace_action_breakpoint(ecb);
6057 				continue;
6058 
6059 			case DTRACEACT_PANIC:
6060 				if (dtrace_priv_kernel_destructive(state))
6061 					dtrace_action_panic(ecb);
6062 				continue;
6063 
6064 			case DTRACEACT_STACK:
6065 				if (!dtrace_priv_kernel(state))
6066 					continue;
6067 
6068 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
6069 				    size / sizeof (pc_t), probe->dtpr_aframes,
6070 				    DTRACE_ANCHORED(probe) ? NULL :
6071 				    (uint32_t *)arg0);
6072 
6073 				continue;
6074 
6075 			case DTRACEACT_JSTACK:
6076 			case DTRACEACT_USTACK:
6077 				if (!dtrace_priv_proc(state, &mstate))
6078 					continue;
6079 
6080 				/*
6081 				 * See comment in DIF_VAR_PID.
6082 				 */
6083 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
6084 				    CPU_ON_INTR(CPU)) {
6085 					int depth = DTRACE_USTACK_NFRAMES(
6086 					    rec->dtrd_arg) + 1;
6087 
6088 					dtrace_bzero((void *)(tomax + valoffs),
6089 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
6090 					    + depth * sizeof (uint64_t));
6091 
6092 					continue;
6093 				}
6094 
6095 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
6096 				    curproc->p_dtrace_helpers != NULL) {
6097 					/*
6098 					 * This is the slow path -- we have
6099 					 * allocated string space, and we're
6100 					 * getting the stack of a process that
6101 					 * has helpers.  Call into a separate
6102 					 * routine to perform this processing.
6103 					 */
6104 					dtrace_action_ustack(&mstate, state,
6105 					    (uint64_t *)(tomax + valoffs),
6106 					    rec->dtrd_arg);
6107 					continue;
6108 				}
6109 
6110 				/*
6111 				 * Clear the string space, since there's no
6112 				 * helper to do it for us.
6113 				 */
6114 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0) {
6115 					int depth = DTRACE_USTACK_NFRAMES(
6116 					    rec->dtrd_arg);
6117 					size_t strsize = DTRACE_USTACK_STRSIZE(
6118 					    rec->dtrd_arg);
6119 					uint64_t *buf = (uint64_t *)(tomax +
6120 					    valoffs);
6121 					void *strspace = &buf[depth + 1];
6122 
6123 					dtrace_bzero(strspace,
6124 					    MIN(depth, strsize));
6125 				}
6126 
6127 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6128 				dtrace_getupcstack((uint64_t *)
6129 				    (tomax + valoffs),
6130 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
6131 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6132 				continue;
6133 
6134 			default:
6135 				break;
6136 			}
6137 
6138 			dp = act->dta_difo;
6139 			ASSERT(dp != NULL);
6140 
6141 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
6142 
6143 			if (*flags & CPU_DTRACE_ERROR)
6144 				continue;
6145 
6146 			switch (act->dta_kind) {
6147 			case DTRACEACT_SPECULATE:
6148 				ASSERT(buf == &state->dts_buffer[cpuid]);
6149 				buf = dtrace_speculation_buffer(state,
6150 				    cpuid, val);
6151 
6152 				if (buf == NULL) {
6153 					*flags |= CPU_DTRACE_DROP;
6154 					continue;
6155 				}
6156 
6157 				offs = dtrace_buffer_reserve(buf,
6158 				    ecb->dte_needed, ecb->dte_alignment,
6159 				    state, NULL);
6160 
6161 				if (offs < 0) {
6162 					*flags |= CPU_DTRACE_DROP;
6163 					continue;
6164 				}
6165 
6166 				tomax = buf->dtb_tomax;
6167 				ASSERT(tomax != NULL);
6168 
6169 				if (ecb->dte_size != 0)
6170 					DTRACE_STORE(uint32_t, tomax, offs,
6171 					    ecb->dte_epid);
6172 				continue;
6173 
6174 			case DTRACEACT_CHILL:
6175 				if (dtrace_priv_kernel_destructive(state))
6176 					dtrace_action_chill(&mstate, val);
6177 				continue;
6178 
6179 			case DTRACEACT_RAISE:
6180 				if (dtrace_priv_proc_destructive(state,
6181 				    &mstate))
6182 					dtrace_action_raise(val);
6183 				continue;
6184 
6185 			case DTRACEACT_COMMIT:
6186 				ASSERT(!committed);
6187 
6188 				/*
6189 				 * We need to commit our buffer state.
6190 				 */
6191 				if (ecb->dte_size)
6192 					buf->dtb_offset = offs + ecb->dte_size;
6193 				buf = &state->dts_buffer[cpuid];
6194 				dtrace_speculation_commit(state, cpuid, val);
6195 				committed = 1;
6196 				continue;
6197 
6198 			case DTRACEACT_DISCARD:
6199 				dtrace_speculation_discard(state, cpuid, val);
6200 				continue;
6201 
6202 			case DTRACEACT_DIFEXPR:
6203 			case DTRACEACT_LIBACT:
6204 			case DTRACEACT_PRINTF:
6205 			case DTRACEACT_PRINTA:
6206 			case DTRACEACT_SYSTEM:
6207 			case DTRACEACT_FREOPEN:
6208 			case DTRACEACT_TRACEMEM:
6209 				break;
6210 
6211 			case DTRACEACT_TRACEMEM_DYNSIZE:
6212 				tracememsize = val;
6213 				break;
6214 
6215 			case DTRACEACT_SYM:
6216 			case DTRACEACT_MOD:
6217 				if (!dtrace_priv_kernel(state))
6218 					continue;
6219 				break;
6220 
6221 			case DTRACEACT_USYM:
6222 			case DTRACEACT_UMOD:
6223 			case DTRACEACT_UADDR: {
6224 				struct pid *pid = curthread->t_procp->p_pidp;
6225 
6226 				if (!dtrace_priv_proc(state, &mstate))
6227 					continue;
6228 
6229 				DTRACE_STORE(uint64_t, tomax,
6230 				    valoffs, (uint64_t)pid->pid_id);
6231 				DTRACE_STORE(uint64_t, tomax,
6232 				    valoffs + sizeof (uint64_t), val);
6233 
6234 				continue;
6235 			}
6236 
6237 			case DTRACEACT_EXIT: {
6238 				/*
6239 				 * For the exit action, we are going to attempt
6240 				 * to atomically set our activity to be
6241 				 * draining.  If this fails (either because
6242 				 * another CPU has beat us to the exit action,
6243 				 * or because our current activity is something
6244 				 * other than ACTIVE or WARMUP), we will
6245 				 * continue.  This assures that the exit action
6246 				 * can be successfully recorded at most once
6247 				 * when we're in the ACTIVE state.  If we're
6248 				 * encountering the exit() action while in
6249 				 * COOLDOWN, however, we want to honor the new
6250 				 * status code.  (We know that we're the only
6251 				 * thread in COOLDOWN, so there is no race.)
6252 				 */
6253 				void *activity = &state->dts_activity;
6254 				dtrace_activity_t current = state->dts_activity;
6255 
6256 				if (current == DTRACE_ACTIVITY_COOLDOWN)
6257 					break;
6258 
6259 				if (current != DTRACE_ACTIVITY_WARMUP)
6260 					current = DTRACE_ACTIVITY_ACTIVE;
6261 
6262 				if (dtrace_cas32(activity, current,
6263 				    DTRACE_ACTIVITY_DRAINING) != current) {
6264 					*flags |= CPU_DTRACE_DROP;
6265 					continue;
6266 				}
6267 
6268 				break;
6269 			}
6270 
6271 			default:
6272 				ASSERT(0);
6273 			}
6274 
6275 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
6276 				uintptr_t end = valoffs + size;
6277 
6278 				if (tracememsize != 0 &&
6279 				    valoffs + tracememsize < end) {
6280 					end = valoffs + tracememsize;
6281 					tracememsize = 0;
6282 				}
6283 
6284 				if (!dtrace_vcanload((void *)(uintptr_t)val,
6285 				    &dp->dtdo_rtype, &mstate, vstate))
6286 					continue;
6287 
6288 				/*
6289 				 * If this is a string, we're going to only
6290 				 * load until we find the zero byte -- after
6291 				 * which we'll store zero bytes.
6292 				 */
6293 				if (dp->dtdo_rtype.dtdt_kind ==
6294 				    DIF_TYPE_STRING) {
6295 					char c = '\0' + 1;
6296 					int intuple = act->dta_intuple;
6297 					size_t s;
6298 
6299 					for (s = 0; s < size; s++) {
6300 						if (c != '\0')
6301 							c = dtrace_load8(val++);
6302 
6303 						DTRACE_STORE(uint8_t, tomax,
6304 						    valoffs++, c);
6305 
6306 						if (c == '\0' && intuple)
6307 							break;
6308 					}
6309 
6310 					continue;
6311 				}
6312 
6313 				while (valoffs < end) {
6314 					DTRACE_STORE(uint8_t, tomax, valoffs++,
6315 					    dtrace_load8(val++));
6316 				}
6317 
6318 				continue;
6319 			}
6320 
6321 			switch (size) {
6322 			case 0:
6323 				break;
6324 
6325 			case sizeof (uint8_t):
6326 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
6327 				break;
6328 			case sizeof (uint16_t):
6329 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
6330 				break;
6331 			case sizeof (uint32_t):
6332 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
6333 				break;
6334 			case sizeof (uint64_t):
6335 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
6336 				break;
6337 			default:
6338 				/*
6339 				 * Any other size should have been returned by
6340 				 * reference, not by value.
6341 				 */
6342 				ASSERT(0);
6343 				break;
6344 			}
6345 		}
6346 
6347 		if (*flags & CPU_DTRACE_DROP)
6348 			continue;
6349 
6350 		if (*flags & CPU_DTRACE_FAULT) {
6351 			int ndx;
6352 			dtrace_action_t *err;
6353 
6354 			buf->dtb_errors++;
6355 
6356 			if (probe->dtpr_id == dtrace_probeid_error) {
6357 				/*
6358 				 * There's nothing we can do -- we had an
6359 				 * error on the error probe.  We bump an
6360 				 * error counter to at least indicate that
6361 				 * this condition happened.
6362 				 */
6363 				dtrace_error(&state->dts_dblerrors);
6364 				continue;
6365 			}
6366 
6367 			if (vtime) {
6368 				/*
6369 				 * Before recursing on dtrace_probe(), we
6370 				 * need to explicitly clear out our start
6371 				 * time to prevent it from being accumulated
6372 				 * into t_dtrace_vtime.
6373 				 */
6374 				curthread->t_dtrace_start = 0;
6375 			}
6376 
6377 			/*
6378 			 * Iterate over the actions to figure out which action
6379 			 * we were processing when we experienced the error.
6380 			 * Note that act points _past_ the faulting action; if
6381 			 * act is ecb->dte_action, the fault was in the
6382 			 * predicate, if it's ecb->dte_action->dta_next it's
6383 			 * in action #1, and so on.
6384 			 */
6385 			for (err = ecb->dte_action, ndx = 0;
6386 			    err != act; err = err->dta_next, ndx++)
6387 				continue;
6388 
6389 			dtrace_probe_error(state, ecb->dte_epid, ndx,
6390 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6391 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6392 			    cpu_core[cpuid].cpuc_dtrace_illval);
6393 
6394 			continue;
6395 		}
6396 
6397 		if (!committed)
6398 			buf->dtb_offset = offs + ecb->dte_size;
6399 	}
6400 
6401 	if (vtime)
6402 		curthread->t_dtrace_start = dtrace_gethrtime();
6403 
6404 	dtrace_interrupt_enable(cookie);
6405 }
6406 
6407 /*
6408  * DTrace Probe Hashing Functions
6409  *
6410  * The functions in this section (and indeed, the functions in remaining
6411  * sections) are not _called_ from probe context.  (Any exceptions to this are
6412  * marked with a "Note:".)  Rather, they are called from elsewhere in the
6413  * DTrace framework to look-up probes in, add probes to and remove probes from
6414  * the DTrace probe hashes.  (Each probe is hashed by each element of the
6415  * probe tuple -- allowing for fast lookups, regardless of what was
6416  * specified.)
6417  */
6418 static uint_t
6419 dtrace_hash_str(char *p)
6420 {
6421 	unsigned int g;
6422 	uint_t hval = 0;
6423 
6424 	while (*p) {
6425 		hval = (hval << 4) + *p++;
6426 		if ((g = (hval & 0xf0000000)) != 0)
6427 			hval ^= g >> 24;
6428 		hval &= ~g;
6429 	}
6430 	return (hval);
6431 }
6432 
6433 static dtrace_hash_t *
6434 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6435 {
6436 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6437 
6438 	hash->dth_stroffs = stroffs;
6439 	hash->dth_nextoffs = nextoffs;
6440 	hash->dth_prevoffs = prevoffs;
6441 
6442 	hash->dth_size = 1;
6443 	hash->dth_mask = hash->dth_size - 1;
6444 
6445 	hash->dth_tab = kmem_zalloc(hash->dth_size *
6446 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6447 
6448 	return (hash);
6449 }
6450 
6451 static void
6452 dtrace_hash_destroy(dtrace_hash_t *hash)
6453 {
6454 #ifdef DEBUG
6455 	int i;
6456 
6457 	for (i = 0; i < hash->dth_size; i++)
6458 		ASSERT(hash->dth_tab[i] == NULL);
6459 #endif
6460 
6461 	kmem_free(hash->dth_tab,
6462 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
6463 	kmem_free(hash, sizeof (dtrace_hash_t));
6464 }
6465 
6466 static void
6467 dtrace_hash_resize(dtrace_hash_t *hash)
6468 {
6469 	int size = hash->dth_size, i, ndx;
6470 	int new_size = hash->dth_size << 1;
6471 	int new_mask = new_size - 1;
6472 	dtrace_hashbucket_t **new_tab, *bucket, *next;
6473 
6474 	ASSERT((new_size & new_mask) == 0);
6475 
6476 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6477 
6478 	for (i = 0; i < size; i++) {
6479 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6480 			dtrace_probe_t *probe = bucket->dthb_chain;
6481 
6482 			ASSERT(probe != NULL);
6483 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6484 
6485 			next = bucket->dthb_next;
6486 			bucket->dthb_next = new_tab[ndx];
6487 			new_tab[ndx] = bucket;
6488 		}
6489 	}
6490 
6491 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6492 	hash->dth_tab = new_tab;
6493 	hash->dth_size = new_size;
6494 	hash->dth_mask = new_mask;
6495 }
6496 
6497 static void
6498 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6499 {
6500 	int hashval = DTRACE_HASHSTR(hash, new);
6501 	int ndx = hashval & hash->dth_mask;
6502 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6503 	dtrace_probe_t **nextp, **prevp;
6504 
6505 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6506 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6507 			goto add;
6508 	}
6509 
6510 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6511 		dtrace_hash_resize(hash);
6512 		dtrace_hash_add(hash, new);
6513 		return;
6514 	}
6515 
6516 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6517 	bucket->dthb_next = hash->dth_tab[ndx];
6518 	hash->dth_tab[ndx] = bucket;
6519 	hash->dth_nbuckets++;
6520 
6521 add:
6522 	nextp = DTRACE_HASHNEXT(hash, new);
6523 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6524 	*nextp = bucket->dthb_chain;
6525 
6526 	if (bucket->dthb_chain != NULL) {
6527 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6528 		ASSERT(*prevp == NULL);
6529 		*prevp = new;
6530 	}
6531 
6532 	bucket->dthb_chain = new;
6533 	bucket->dthb_len++;
6534 }
6535 
6536 static dtrace_probe_t *
6537 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6538 {
6539 	int hashval = DTRACE_HASHSTR(hash, template);
6540 	int ndx = hashval & hash->dth_mask;
6541 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6542 
6543 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6544 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6545 			return (bucket->dthb_chain);
6546 	}
6547 
6548 	return (NULL);
6549 }
6550 
6551 static int
6552 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6553 {
6554 	int hashval = DTRACE_HASHSTR(hash, template);
6555 	int ndx = hashval & hash->dth_mask;
6556 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6557 
6558 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6559 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6560 			return (bucket->dthb_len);
6561 	}
6562 
6563 	return (NULL);
6564 }
6565 
6566 static void
6567 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6568 {
6569 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6570 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6571 
6572 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6573 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6574 
6575 	/*
6576 	 * Find the bucket that we're removing this probe from.
6577 	 */
6578 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6579 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6580 			break;
6581 	}
6582 
6583 	ASSERT(bucket != NULL);
6584 
6585 	if (*prevp == NULL) {
6586 		if (*nextp == NULL) {
6587 			/*
6588 			 * The removed probe was the only probe on this
6589 			 * bucket; we need to remove the bucket.
6590 			 */
6591 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6592 
6593 			ASSERT(bucket->dthb_chain == probe);
6594 			ASSERT(b != NULL);
6595 
6596 			if (b == bucket) {
6597 				hash->dth_tab[ndx] = bucket->dthb_next;
6598 			} else {
6599 				while (b->dthb_next != bucket)
6600 					b = b->dthb_next;
6601 				b->dthb_next = bucket->dthb_next;
6602 			}
6603 
6604 			ASSERT(hash->dth_nbuckets > 0);
6605 			hash->dth_nbuckets--;
6606 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
6607 			return;
6608 		}
6609 
6610 		bucket->dthb_chain = *nextp;
6611 	} else {
6612 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
6613 	}
6614 
6615 	if (*nextp != NULL)
6616 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
6617 }
6618 
6619 /*
6620  * DTrace Utility Functions
6621  *
6622  * These are random utility functions that are _not_ called from probe context.
6623  */
6624 static int
6625 dtrace_badattr(const dtrace_attribute_t *a)
6626 {
6627 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
6628 	    a->dtat_data > DTRACE_STABILITY_MAX ||
6629 	    a->dtat_class > DTRACE_CLASS_MAX);
6630 }
6631 
6632 /*
6633  * Return a duplicate copy of a string.  If the specified string is NULL,
6634  * this function returns a zero-length string.
6635  */
6636 static char *
6637 dtrace_strdup(const char *str)
6638 {
6639 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
6640 
6641 	if (str != NULL)
6642 		(void) strcpy(new, str);
6643 
6644 	return (new);
6645 }
6646 
6647 #define	DTRACE_ISALPHA(c)	\
6648 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
6649 
6650 static int
6651 dtrace_badname(const char *s)
6652 {
6653 	char c;
6654 
6655 	if (s == NULL || (c = *s++) == '\0')
6656 		return (0);
6657 
6658 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
6659 		return (1);
6660 
6661 	while ((c = *s++) != '\0') {
6662 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
6663 		    c != '-' && c != '_' && c != '.' && c != '`')
6664 			return (1);
6665 	}
6666 
6667 	return (0);
6668 }
6669 
6670 static void
6671 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
6672 {
6673 	uint32_t priv;
6674 
6675 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
6676 		/*
6677 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
6678 		 */
6679 		priv = DTRACE_PRIV_ALL;
6680 	} else {
6681 		*uidp = crgetuid(cr);
6682 		*zoneidp = crgetzoneid(cr);
6683 
6684 		priv = 0;
6685 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
6686 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
6687 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
6688 			priv |= DTRACE_PRIV_USER;
6689 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
6690 			priv |= DTRACE_PRIV_PROC;
6691 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
6692 			priv |= DTRACE_PRIV_OWNER;
6693 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
6694 			priv |= DTRACE_PRIV_ZONEOWNER;
6695 	}
6696 
6697 	*privp = priv;
6698 }
6699 
6700 #ifdef DTRACE_ERRDEBUG
6701 static void
6702 dtrace_errdebug(const char *str)
6703 {
6704 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
6705 	int occupied = 0;
6706 
6707 	mutex_enter(&dtrace_errlock);
6708 	dtrace_errlast = str;
6709 	dtrace_errthread = curthread;
6710 
6711 	while (occupied++ < DTRACE_ERRHASHSZ) {
6712 		if (dtrace_errhash[hval].dter_msg == str) {
6713 			dtrace_errhash[hval].dter_count++;
6714 			goto out;
6715 		}
6716 
6717 		if (dtrace_errhash[hval].dter_msg != NULL) {
6718 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
6719 			continue;
6720 		}
6721 
6722 		dtrace_errhash[hval].dter_msg = str;
6723 		dtrace_errhash[hval].dter_count = 1;
6724 		goto out;
6725 	}
6726 
6727 	panic("dtrace: undersized error hash");
6728 out:
6729 	mutex_exit(&dtrace_errlock);
6730 }
6731 #endif
6732 
6733 /*
6734  * DTrace Matching Functions
6735  *
6736  * These functions are used to match groups of probes, given some elements of
6737  * a probe tuple, or some globbed expressions for elements of a probe tuple.
6738  */
6739 static int
6740 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
6741     zoneid_t zoneid)
6742 {
6743 	if (priv != DTRACE_PRIV_ALL) {
6744 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
6745 		uint32_t match = priv & ppriv;
6746 
6747 		/*
6748 		 * No PRIV_DTRACE_* privileges...
6749 		 */
6750 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
6751 		    DTRACE_PRIV_KERNEL)) == 0)
6752 			return (0);
6753 
6754 		/*
6755 		 * No matching bits, but there were bits to match...
6756 		 */
6757 		if (match == 0 && ppriv != 0)
6758 			return (0);
6759 
6760 		/*
6761 		 * Need to have permissions to the process, but don't...
6762 		 */
6763 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
6764 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
6765 			return (0);
6766 		}
6767 
6768 		/*
6769 		 * Need to be in the same zone unless we possess the
6770 		 * privilege to examine all zones.
6771 		 */
6772 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
6773 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
6774 			return (0);
6775 		}
6776 	}
6777 
6778 	return (1);
6779 }
6780 
6781 /*
6782  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
6783  * consists of input pattern strings and an ops-vector to evaluate them.
6784  * This function returns >0 for match, 0 for no match, and <0 for error.
6785  */
6786 static int
6787 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
6788     uint32_t priv, uid_t uid, zoneid_t zoneid)
6789 {
6790 	dtrace_provider_t *pvp = prp->dtpr_provider;
6791 	int rv;
6792 
6793 	if (pvp->dtpv_defunct)
6794 		return (0);
6795 
6796 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
6797 		return (rv);
6798 
6799 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
6800 		return (rv);
6801 
6802 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
6803 		return (rv);
6804 
6805 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
6806 		return (rv);
6807 
6808 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
6809 		return (0);
6810 
6811 	return (rv);
6812 }
6813 
6814 /*
6815  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
6816  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
6817  * libc's version, the kernel version only applies to 8-bit ASCII strings.
6818  * In addition, all of the recursion cases except for '*' matching have been
6819  * unwound.  For '*', we still implement recursive evaluation, but a depth
6820  * counter is maintained and matching is aborted if we recurse too deep.
6821  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
6822  */
6823 static int
6824 dtrace_match_glob(const char *s, const char *p, int depth)
6825 {
6826 	const char *olds;
6827 	char s1, c;
6828 	int gs;
6829 
6830 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
6831 		return (-1);
6832 
6833 	if (s == NULL)
6834 		s = ""; /* treat NULL as empty string */
6835 
6836 top:
6837 	olds = s;
6838 	s1 = *s++;
6839 
6840 	if (p == NULL)
6841 		return (0);
6842 
6843 	if ((c = *p++) == '\0')
6844 		return (s1 == '\0');
6845 
6846 	switch (c) {
6847 	case '[': {
6848 		int ok = 0, notflag = 0;
6849 		char lc = '\0';
6850 
6851 		if (s1 == '\0')
6852 			return (0);
6853 
6854 		if (*p == '!') {
6855 			notflag = 1;
6856 			p++;
6857 		}
6858 
6859 		if ((c = *p++) == '\0')
6860 			return (0);
6861 
6862 		do {
6863 			if (c == '-' && lc != '\0' && *p != ']') {
6864 				if ((c = *p++) == '\0')
6865 					return (0);
6866 				if (c == '\\' && (c = *p++) == '\0')
6867 					return (0);
6868 
6869 				if (notflag) {
6870 					if (s1 < lc || s1 > c)
6871 						ok++;
6872 					else
6873 						return (0);
6874 				} else if (lc <= s1 && s1 <= c)
6875 					ok++;
6876 
6877 			} else if (c == '\\' && (c = *p++) == '\0')
6878 				return (0);
6879 
6880 			lc = c; /* save left-hand 'c' for next iteration */
6881 
6882 			if (notflag) {
6883 				if (s1 != c)
6884 					ok++;
6885 				else
6886 					return (0);
6887 			} else if (s1 == c)
6888 				ok++;
6889 
6890 			if ((c = *p++) == '\0')
6891 				return (0);
6892 
6893 		} while (c != ']');
6894 
6895 		if (ok)
6896 			goto top;
6897 
6898 		return (0);
6899 	}
6900 
6901 	case '\\':
6902 		if ((c = *p++) == '\0')
6903 			return (0);
6904 		/*FALLTHRU*/
6905 
6906 	default:
6907 		if (c != s1)
6908 			return (0);
6909 		/*FALLTHRU*/
6910 
6911 	case '?':
6912 		if (s1 != '\0')
6913 			goto top;
6914 		return (0);
6915 
6916 	case '*':
6917 		while (*p == '*')
6918 			p++; /* consecutive *'s are identical to a single one */
6919 
6920 		if (*p == '\0')
6921 			return (1);
6922 
6923 		for (s = olds; *s != '\0'; s++) {
6924 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
6925 				return (gs);
6926 		}
6927 
6928 		return (0);
6929 	}
6930 }
6931 
6932 /*ARGSUSED*/
6933 static int
6934 dtrace_match_string(const char *s, const char *p, int depth)
6935 {
6936 	return (s != NULL && strcmp(s, p) == 0);
6937 }
6938 
6939 /*ARGSUSED*/
6940 static int
6941 dtrace_match_nul(const char *s, const char *p, int depth)
6942 {
6943 	return (1); /* always match the empty pattern */
6944 }
6945 
6946 /*ARGSUSED*/
6947 static int
6948 dtrace_match_nonzero(const char *s, const char *p, int depth)
6949 {
6950 	return (s != NULL && s[0] != '\0');
6951 }
6952 
6953 static int
6954 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
6955     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
6956 {
6957 	dtrace_probe_t template, *probe;
6958 	dtrace_hash_t *hash = NULL;
6959 	int len, rc, best = INT_MAX, nmatched = 0;
6960 	dtrace_id_t i;
6961 
6962 	ASSERT(MUTEX_HELD(&dtrace_lock));
6963 
6964 	/*
6965 	 * If the probe ID is specified in the key, just lookup by ID and
6966 	 * invoke the match callback once if a matching probe is found.
6967 	 */
6968 	if (pkp->dtpk_id != DTRACE_IDNONE) {
6969 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
6970 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
6971 			if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
6972 				return (DTRACE_MATCH_FAIL);
6973 			nmatched++;
6974 		}
6975 		return (nmatched);
6976 	}
6977 
6978 	template.dtpr_mod = (char *)pkp->dtpk_mod;
6979 	template.dtpr_func = (char *)pkp->dtpk_func;
6980 	template.dtpr_name = (char *)pkp->dtpk_name;
6981 
6982 	/*
6983 	 * We want to find the most distinct of the module name, function
6984 	 * name, and name.  So for each one that is not a glob pattern or
6985 	 * empty string, we perform a lookup in the corresponding hash and
6986 	 * use the hash table with the fewest collisions to do our search.
6987 	 */
6988 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
6989 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
6990 		best = len;
6991 		hash = dtrace_bymod;
6992 	}
6993 
6994 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
6995 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
6996 		best = len;
6997 		hash = dtrace_byfunc;
6998 	}
6999 
7000 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
7001 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
7002 		best = len;
7003 		hash = dtrace_byname;
7004 	}
7005 
7006 	/*
7007 	 * If we did not select a hash table, iterate over every probe and
7008 	 * invoke our callback for each one that matches our input probe key.
7009 	 */
7010 	if (hash == NULL) {
7011 		for (i = 0; i < dtrace_nprobes; i++) {
7012 			if ((probe = dtrace_probes[i]) == NULL ||
7013 			    dtrace_match_probe(probe, pkp, priv, uid,
7014 			    zoneid) <= 0)
7015 				continue;
7016 
7017 			nmatched++;
7018 
7019 			if ((rc = (*matched)(probe, arg)) !=
7020 			    DTRACE_MATCH_NEXT) {
7021 				if (rc == DTRACE_MATCH_FAIL)
7022 					return (DTRACE_MATCH_FAIL);
7023 				break;
7024 			}
7025 		}
7026 
7027 		return (nmatched);
7028 	}
7029 
7030 	/*
7031 	 * If we selected a hash table, iterate over each probe of the same key
7032 	 * name and invoke the callback for every probe that matches the other
7033 	 * attributes of our input probe key.
7034 	 */
7035 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
7036 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
7037 
7038 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
7039 			continue;
7040 
7041 		nmatched++;
7042 
7043 		if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
7044 			if (rc == DTRACE_MATCH_FAIL)
7045 				return (DTRACE_MATCH_FAIL);
7046 			break;
7047 		}
7048 	}
7049 
7050 	return (nmatched);
7051 }
7052 
7053 /*
7054  * Return the function pointer dtrace_probecmp() should use to compare the
7055  * specified pattern with a string.  For NULL or empty patterns, we select
7056  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
7057  * For non-empty non-glob strings, we use dtrace_match_string().
7058  */
7059 static dtrace_probekey_f *
7060 dtrace_probekey_func(const char *p)
7061 {
7062 	char c;
7063 
7064 	if (p == NULL || *p == '\0')
7065 		return (&dtrace_match_nul);
7066 
7067 	while ((c = *p++) != '\0') {
7068 		if (c == '[' || c == '?' || c == '*' || c == '\\')
7069 			return (&dtrace_match_glob);
7070 	}
7071 
7072 	return (&dtrace_match_string);
7073 }
7074 
7075 /*
7076  * Build a probe comparison key for use with dtrace_match_probe() from the
7077  * given probe description.  By convention, a null key only matches anchored
7078  * probes: if each field is the empty string, reset dtpk_fmatch to
7079  * dtrace_match_nonzero().
7080  */
7081 static void
7082 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
7083 {
7084 	pkp->dtpk_prov = pdp->dtpd_provider;
7085 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
7086 
7087 	pkp->dtpk_mod = pdp->dtpd_mod;
7088 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
7089 
7090 	pkp->dtpk_func = pdp->dtpd_func;
7091 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
7092 
7093 	pkp->dtpk_name = pdp->dtpd_name;
7094 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
7095 
7096 	pkp->dtpk_id = pdp->dtpd_id;
7097 
7098 	if (pkp->dtpk_id == DTRACE_IDNONE &&
7099 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
7100 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
7101 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
7102 	    pkp->dtpk_nmatch == &dtrace_match_nul)
7103 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
7104 }
7105 
7106 /*
7107  * DTrace Provider-to-Framework API Functions
7108  *
7109  * These functions implement much of the Provider-to-Framework API, as
7110  * described in <sys/dtrace.h>.  The parts of the API not in this section are
7111  * the functions in the API for probe management (found below), and
7112  * dtrace_probe() itself (found above).
7113  */
7114 
7115 /*
7116  * Register the calling provider with the DTrace framework.  This should
7117  * generally be called by DTrace providers in their attach(9E) entry point.
7118  */
7119 int
7120 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
7121     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
7122 {
7123 	dtrace_provider_t *provider;
7124 
7125 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
7126 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7127 		    "arguments", name ? name : "<NULL>");
7128 		return (EINVAL);
7129 	}
7130 
7131 	if (name[0] == '\0' || dtrace_badname(name)) {
7132 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7133 		    "provider name", name);
7134 		return (EINVAL);
7135 	}
7136 
7137 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
7138 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
7139 	    pops->dtps_destroy == NULL ||
7140 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
7141 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7142 		    "provider ops", name);
7143 		return (EINVAL);
7144 	}
7145 
7146 	if (dtrace_badattr(&pap->dtpa_provider) ||
7147 	    dtrace_badattr(&pap->dtpa_mod) ||
7148 	    dtrace_badattr(&pap->dtpa_func) ||
7149 	    dtrace_badattr(&pap->dtpa_name) ||
7150 	    dtrace_badattr(&pap->dtpa_args)) {
7151 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7152 		    "provider attributes", name);
7153 		return (EINVAL);
7154 	}
7155 
7156 	if (priv & ~DTRACE_PRIV_ALL) {
7157 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
7158 		    "privilege attributes", name);
7159 		return (EINVAL);
7160 	}
7161 
7162 	if ((priv & DTRACE_PRIV_KERNEL) &&
7163 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
7164 	    pops->dtps_mode == NULL) {
7165 		cmn_err(CE_WARN, "failed to register provider '%s': need "
7166 		    "dtps_mode() op for given privilege attributes", name);
7167 		return (EINVAL);
7168 	}
7169 
7170 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
7171 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7172 	(void) strcpy(provider->dtpv_name, name);
7173 
7174 	provider->dtpv_attr = *pap;
7175 	provider->dtpv_priv.dtpp_flags = priv;
7176 	if (cr != NULL) {
7177 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
7178 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
7179 	}
7180 	provider->dtpv_pops = *pops;
7181 
7182 	if (pops->dtps_provide == NULL) {
7183 		ASSERT(pops->dtps_provide_module != NULL);
7184 		provider->dtpv_pops.dtps_provide =
7185 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
7186 	}
7187 
7188 	if (pops->dtps_provide_module == NULL) {
7189 		ASSERT(pops->dtps_provide != NULL);
7190 		provider->dtpv_pops.dtps_provide_module =
7191 		    (void (*)(void *, struct modctl *))dtrace_nullop;
7192 	}
7193 
7194 	if (pops->dtps_suspend == NULL) {
7195 		ASSERT(pops->dtps_resume == NULL);
7196 		provider->dtpv_pops.dtps_suspend =
7197 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7198 		provider->dtpv_pops.dtps_resume =
7199 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
7200 	}
7201 
7202 	provider->dtpv_arg = arg;
7203 	*idp = (dtrace_provider_id_t)provider;
7204 
7205 	if (pops == &dtrace_provider_ops) {
7206 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7207 		ASSERT(MUTEX_HELD(&dtrace_lock));
7208 		ASSERT(dtrace_anon.dta_enabling == NULL);
7209 
7210 		/*
7211 		 * We make sure that the DTrace provider is at the head of
7212 		 * the provider chain.
7213 		 */
7214 		provider->dtpv_next = dtrace_provider;
7215 		dtrace_provider = provider;
7216 		return (0);
7217 	}
7218 
7219 	mutex_enter(&dtrace_provider_lock);
7220 	mutex_enter(&dtrace_lock);
7221 
7222 	/*
7223 	 * If there is at least one provider registered, we'll add this
7224 	 * provider after the first provider.
7225 	 */
7226 	if (dtrace_provider != NULL) {
7227 		provider->dtpv_next = dtrace_provider->dtpv_next;
7228 		dtrace_provider->dtpv_next = provider;
7229 	} else {
7230 		dtrace_provider = provider;
7231 	}
7232 
7233 	if (dtrace_retained != NULL) {
7234 		dtrace_enabling_provide(provider);
7235 
7236 		/*
7237 		 * Now we need to call dtrace_enabling_matchall() -- which
7238 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
7239 		 * to drop all of our locks before calling into it...
7240 		 */
7241 		mutex_exit(&dtrace_lock);
7242 		mutex_exit(&dtrace_provider_lock);
7243 		dtrace_enabling_matchall();
7244 
7245 		return (0);
7246 	}
7247 
7248 	mutex_exit(&dtrace_lock);
7249 	mutex_exit(&dtrace_provider_lock);
7250 
7251 	return (0);
7252 }
7253 
7254 /*
7255  * Unregister the specified provider from the DTrace framework.  This should
7256  * generally be called by DTrace providers in their detach(9E) entry point.
7257  */
7258 int
7259 dtrace_unregister(dtrace_provider_id_t id)
7260 {
7261 	dtrace_provider_t *old = (dtrace_provider_t *)id;
7262 	dtrace_provider_t *prev = NULL;
7263 	int i, self = 0, noreap = 0;
7264 	dtrace_probe_t *probe, *first = NULL;
7265 
7266 	if (old->dtpv_pops.dtps_enable ==
7267 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
7268 		/*
7269 		 * If DTrace itself is the provider, we're called with locks
7270 		 * already held.
7271 		 */
7272 		ASSERT(old == dtrace_provider);
7273 		ASSERT(dtrace_devi != NULL);
7274 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7275 		ASSERT(MUTEX_HELD(&dtrace_lock));
7276 		self = 1;
7277 
7278 		if (dtrace_provider->dtpv_next != NULL) {
7279 			/*
7280 			 * There's another provider here; return failure.
7281 			 */
7282 			return (EBUSY);
7283 		}
7284 	} else {
7285 		mutex_enter(&dtrace_provider_lock);
7286 		mutex_enter(&mod_lock);
7287 		mutex_enter(&dtrace_lock);
7288 	}
7289 
7290 	/*
7291 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
7292 	 * probes, we refuse to let providers slither away, unless this
7293 	 * provider has already been explicitly invalidated.
7294 	 */
7295 	if (!old->dtpv_defunct &&
7296 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7297 	    dtrace_anon.dta_state->dts_necbs > 0))) {
7298 		if (!self) {
7299 			mutex_exit(&dtrace_lock);
7300 			mutex_exit(&mod_lock);
7301 			mutex_exit(&dtrace_provider_lock);
7302 		}
7303 		return (EBUSY);
7304 	}
7305 
7306 	/*
7307 	 * Attempt to destroy the probes associated with this provider.
7308 	 */
7309 	for (i = 0; i < dtrace_nprobes; i++) {
7310 		if ((probe = dtrace_probes[i]) == NULL)
7311 			continue;
7312 
7313 		if (probe->dtpr_provider != old)
7314 			continue;
7315 
7316 		if (probe->dtpr_ecb == NULL)
7317 			continue;
7318 
7319 		/*
7320 		 * If we are trying to unregister a defunct provider, and the
7321 		 * provider was made defunct within the interval dictated by
7322 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
7323 		 * attempt to reap our enablings.  To denote that the provider
7324 		 * should reattempt to unregister itself at some point in the
7325 		 * future, we will return a differentiable error code (EAGAIN
7326 		 * instead of EBUSY) in this case.
7327 		 */
7328 		if (dtrace_gethrtime() - old->dtpv_defunct >
7329 		    dtrace_unregister_defunct_reap)
7330 			noreap = 1;
7331 
7332 		if (!self) {
7333 			mutex_exit(&dtrace_lock);
7334 			mutex_exit(&mod_lock);
7335 			mutex_exit(&dtrace_provider_lock);
7336 		}
7337 
7338 		if (noreap)
7339 			return (EBUSY);
7340 
7341 		(void) taskq_dispatch(dtrace_taskq,
7342 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
7343 
7344 		return (EAGAIN);
7345 	}
7346 
7347 	/*
7348 	 * All of the probes for this provider are disabled; we can safely
7349 	 * remove all of them from their hash chains and from the probe array.
7350 	 */
7351 	for (i = 0; i < dtrace_nprobes; i++) {
7352 		if ((probe = dtrace_probes[i]) == NULL)
7353 			continue;
7354 
7355 		if (probe->dtpr_provider != old)
7356 			continue;
7357 
7358 		dtrace_probes[i] = NULL;
7359 
7360 		dtrace_hash_remove(dtrace_bymod, probe);
7361 		dtrace_hash_remove(dtrace_byfunc, probe);
7362 		dtrace_hash_remove(dtrace_byname, probe);
7363 
7364 		if (first == NULL) {
7365 			first = probe;
7366 			probe->dtpr_nextmod = NULL;
7367 		} else {
7368 			probe->dtpr_nextmod = first;
7369 			first = probe;
7370 		}
7371 	}
7372 
7373 	/*
7374 	 * The provider's probes have been removed from the hash chains and
7375 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
7376 	 * everyone has cleared out from any probe array processing.
7377 	 */
7378 	dtrace_sync();
7379 
7380 	for (probe = first; probe != NULL; probe = first) {
7381 		first = probe->dtpr_nextmod;
7382 
7383 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7384 		    probe->dtpr_arg);
7385 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7386 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7387 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7388 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7389 		kmem_free(probe, sizeof (dtrace_probe_t));
7390 	}
7391 
7392 	if ((prev = dtrace_provider) == old) {
7393 		ASSERT(self || dtrace_devi == NULL);
7394 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7395 		dtrace_provider = old->dtpv_next;
7396 	} else {
7397 		while (prev != NULL && prev->dtpv_next != old)
7398 			prev = prev->dtpv_next;
7399 
7400 		if (prev == NULL) {
7401 			panic("attempt to unregister non-existent "
7402 			    "dtrace provider %p\n", (void *)id);
7403 		}
7404 
7405 		prev->dtpv_next = old->dtpv_next;
7406 	}
7407 
7408 	if (!self) {
7409 		mutex_exit(&dtrace_lock);
7410 		mutex_exit(&mod_lock);
7411 		mutex_exit(&dtrace_provider_lock);
7412 	}
7413 
7414 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7415 	kmem_free(old, sizeof (dtrace_provider_t));
7416 
7417 	return (0);
7418 }
7419 
7420 /*
7421  * Invalidate the specified provider.  All subsequent probe lookups for the
7422  * specified provider will fail, but its probes will not be removed.
7423  */
7424 void
7425 dtrace_invalidate(dtrace_provider_id_t id)
7426 {
7427 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7428 
7429 	ASSERT(pvp->dtpv_pops.dtps_enable !=
7430 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7431 
7432 	mutex_enter(&dtrace_provider_lock);
7433 	mutex_enter(&dtrace_lock);
7434 
7435 	pvp->dtpv_defunct = dtrace_gethrtime();
7436 
7437 	mutex_exit(&dtrace_lock);
7438 	mutex_exit(&dtrace_provider_lock);
7439 }
7440 
7441 /*
7442  * Indicate whether or not DTrace has attached.
7443  */
7444 int
7445 dtrace_attached(void)
7446 {
7447 	/*
7448 	 * dtrace_provider will be non-NULL iff the DTrace driver has
7449 	 * attached.  (It's non-NULL because DTrace is always itself a
7450 	 * provider.)
7451 	 */
7452 	return (dtrace_provider != NULL);
7453 }
7454 
7455 /*
7456  * Remove all the unenabled probes for the given provider.  This function is
7457  * not unlike dtrace_unregister(), except that it doesn't remove the provider
7458  * -- just as many of its associated probes as it can.
7459  */
7460 int
7461 dtrace_condense(dtrace_provider_id_t id)
7462 {
7463 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
7464 	int i;
7465 	dtrace_probe_t *probe;
7466 
7467 	/*
7468 	 * Make sure this isn't the dtrace provider itself.
7469 	 */
7470 	ASSERT(prov->dtpv_pops.dtps_enable !=
7471 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7472 
7473 	mutex_enter(&dtrace_provider_lock);
7474 	mutex_enter(&dtrace_lock);
7475 
7476 	/*
7477 	 * Attempt to destroy the probes associated with this provider.
7478 	 */
7479 	for (i = 0; i < dtrace_nprobes; i++) {
7480 		if ((probe = dtrace_probes[i]) == NULL)
7481 			continue;
7482 
7483 		if (probe->dtpr_provider != prov)
7484 			continue;
7485 
7486 		if (probe->dtpr_ecb != NULL)
7487 			continue;
7488 
7489 		dtrace_probes[i] = NULL;
7490 
7491 		dtrace_hash_remove(dtrace_bymod, probe);
7492 		dtrace_hash_remove(dtrace_byfunc, probe);
7493 		dtrace_hash_remove(dtrace_byname, probe);
7494 
7495 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7496 		    probe->dtpr_arg);
7497 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7498 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7499 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7500 		kmem_free(probe, sizeof (dtrace_probe_t));
7501 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7502 	}
7503 
7504 	mutex_exit(&dtrace_lock);
7505 	mutex_exit(&dtrace_provider_lock);
7506 
7507 	return (0);
7508 }
7509 
7510 /*
7511  * DTrace Probe Management Functions
7512  *
7513  * The functions in this section perform the DTrace probe management,
7514  * including functions to create probes, look-up probes, and call into the
7515  * providers to request that probes be provided.  Some of these functions are
7516  * in the Provider-to-Framework API; these functions can be identified by the
7517  * fact that they are not declared "static".
7518  */
7519 
7520 /*
7521  * Create a probe with the specified module name, function name, and name.
7522  */
7523 dtrace_id_t
7524 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7525     const char *func, const char *name, int aframes, void *arg)
7526 {
7527 	dtrace_probe_t *probe, **probes;
7528 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7529 	dtrace_id_t id;
7530 
7531 	if (provider == dtrace_provider) {
7532 		ASSERT(MUTEX_HELD(&dtrace_lock));
7533 	} else {
7534 		mutex_enter(&dtrace_lock);
7535 	}
7536 
7537 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7538 	    VM_BESTFIT | VM_SLEEP);
7539 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
7540 
7541 	probe->dtpr_id = id;
7542 	probe->dtpr_gen = dtrace_probegen++;
7543 	probe->dtpr_mod = dtrace_strdup(mod);
7544 	probe->dtpr_func = dtrace_strdup(func);
7545 	probe->dtpr_name = dtrace_strdup(name);
7546 	probe->dtpr_arg = arg;
7547 	probe->dtpr_aframes = aframes;
7548 	probe->dtpr_provider = provider;
7549 
7550 	dtrace_hash_add(dtrace_bymod, probe);
7551 	dtrace_hash_add(dtrace_byfunc, probe);
7552 	dtrace_hash_add(dtrace_byname, probe);
7553 
7554 	if (id - 1 >= dtrace_nprobes) {
7555 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7556 		size_t nsize = osize << 1;
7557 
7558 		if (nsize == 0) {
7559 			ASSERT(osize == 0);
7560 			ASSERT(dtrace_probes == NULL);
7561 			nsize = sizeof (dtrace_probe_t *);
7562 		}
7563 
7564 		probes = kmem_zalloc(nsize, KM_SLEEP);
7565 
7566 		if (dtrace_probes == NULL) {
7567 			ASSERT(osize == 0);
7568 			dtrace_probes = probes;
7569 			dtrace_nprobes = 1;
7570 		} else {
7571 			dtrace_probe_t **oprobes = dtrace_probes;
7572 
7573 			bcopy(oprobes, probes, osize);
7574 			dtrace_membar_producer();
7575 			dtrace_probes = probes;
7576 
7577 			dtrace_sync();
7578 
7579 			/*
7580 			 * All CPUs are now seeing the new probes array; we can
7581 			 * safely free the old array.
7582 			 */
7583 			kmem_free(oprobes, osize);
7584 			dtrace_nprobes <<= 1;
7585 		}
7586 
7587 		ASSERT(id - 1 < dtrace_nprobes);
7588 	}
7589 
7590 	ASSERT(dtrace_probes[id - 1] == NULL);
7591 	dtrace_probes[id - 1] = probe;
7592 
7593 	if (provider != dtrace_provider)
7594 		mutex_exit(&dtrace_lock);
7595 
7596 	return (id);
7597 }
7598 
7599 static dtrace_probe_t *
7600 dtrace_probe_lookup_id(dtrace_id_t id)
7601 {
7602 	ASSERT(MUTEX_HELD(&dtrace_lock));
7603 
7604 	if (id == 0 || id > dtrace_nprobes)
7605 		return (NULL);
7606 
7607 	return (dtrace_probes[id - 1]);
7608 }
7609 
7610 static int
7611 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
7612 {
7613 	*((dtrace_id_t *)arg) = probe->dtpr_id;
7614 
7615 	return (DTRACE_MATCH_DONE);
7616 }
7617 
7618 /*
7619  * Look up a probe based on provider and one or more of module name, function
7620  * name and probe name.
7621  */
7622 dtrace_id_t
7623 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
7624     const char *func, const char *name)
7625 {
7626 	dtrace_probekey_t pkey;
7627 	dtrace_id_t id;
7628 	int match;
7629 
7630 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
7631 	pkey.dtpk_pmatch = &dtrace_match_string;
7632 	pkey.dtpk_mod = mod;
7633 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
7634 	pkey.dtpk_func = func;
7635 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
7636 	pkey.dtpk_name = name;
7637 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
7638 	pkey.dtpk_id = DTRACE_IDNONE;
7639 
7640 	mutex_enter(&dtrace_lock);
7641 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
7642 	    dtrace_probe_lookup_match, &id);
7643 	mutex_exit(&dtrace_lock);
7644 
7645 	ASSERT(match == 1 || match == 0);
7646 	return (match ? id : 0);
7647 }
7648 
7649 /*
7650  * Returns the probe argument associated with the specified probe.
7651  */
7652 void *
7653 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
7654 {
7655 	dtrace_probe_t *probe;
7656 	void *rval = NULL;
7657 
7658 	mutex_enter(&dtrace_lock);
7659 
7660 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
7661 	    probe->dtpr_provider == (dtrace_provider_t *)id)
7662 		rval = probe->dtpr_arg;
7663 
7664 	mutex_exit(&dtrace_lock);
7665 
7666 	return (rval);
7667 }
7668 
7669 /*
7670  * Copy a probe into a probe description.
7671  */
7672 static void
7673 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
7674 {
7675 	bzero(pdp, sizeof (dtrace_probedesc_t));
7676 	pdp->dtpd_id = prp->dtpr_id;
7677 
7678 	(void) strncpy(pdp->dtpd_provider,
7679 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
7680 
7681 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
7682 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
7683 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
7684 }
7685 
7686 /*
7687  * Called to indicate that a probe -- or probes -- should be provided by a
7688  * specfied provider.  If the specified description is NULL, the provider will
7689  * be told to provide all of its probes.  (This is done whenever a new
7690  * consumer comes along, or whenever a retained enabling is to be matched.) If
7691  * the specified description is non-NULL, the provider is given the
7692  * opportunity to dynamically provide the specified probe, allowing providers
7693  * to support the creation of probes on-the-fly.  (So-called _autocreated_
7694  * probes.)  If the provider is NULL, the operations will be applied to all
7695  * providers; if the provider is non-NULL the operations will only be applied
7696  * to the specified provider.  The dtrace_provider_lock must be held, and the
7697  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
7698  * will need to grab the dtrace_lock when it reenters the framework through
7699  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
7700  */
7701 static void
7702 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
7703 {
7704 	struct modctl *ctl;
7705 	int all = 0;
7706 
7707 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7708 
7709 	if (prv == NULL) {
7710 		all = 1;
7711 		prv = dtrace_provider;
7712 	}
7713 
7714 	do {
7715 		/*
7716 		 * First, call the blanket provide operation.
7717 		 */
7718 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
7719 
7720 		/*
7721 		 * Now call the per-module provide operation.  We will grab
7722 		 * mod_lock to prevent the list from being modified.  Note
7723 		 * that this also prevents the mod_busy bits from changing.
7724 		 * (mod_busy can only be changed with mod_lock held.)
7725 		 */
7726 		mutex_enter(&mod_lock);
7727 
7728 		ctl = &modules;
7729 		do {
7730 			if (ctl->mod_busy || ctl->mod_mp == NULL)
7731 				continue;
7732 
7733 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
7734 
7735 		} while ((ctl = ctl->mod_next) != &modules);
7736 
7737 		mutex_exit(&mod_lock);
7738 	} while (all && (prv = prv->dtpv_next) != NULL);
7739 }
7740 
7741 /*
7742  * Iterate over each probe, and call the Framework-to-Provider API function
7743  * denoted by offs.
7744  */
7745 static void
7746 dtrace_probe_foreach(uintptr_t offs)
7747 {
7748 	dtrace_provider_t *prov;
7749 	void (*func)(void *, dtrace_id_t, void *);
7750 	dtrace_probe_t *probe;
7751 	dtrace_icookie_t cookie;
7752 	int i;
7753 
7754 	/*
7755 	 * We disable interrupts to walk through the probe array.  This is
7756 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
7757 	 * won't see stale data.
7758 	 */
7759 	cookie = dtrace_interrupt_disable();
7760 
7761 	for (i = 0; i < dtrace_nprobes; i++) {
7762 		if ((probe = dtrace_probes[i]) == NULL)
7763 			continue;
7764 
7765 		if (probe->dtpr_ecb == NULL) {
7766 			/*
7767 			 * This probe isn't enabled -- don't call the function.
7768 			 */
7769 			continue;
7770 		}
7771 
7772 		prov = probe->dtpr_provider;
7773 		func = *((void(**)(void *, dtrace_id_t, void *))
7774 		    ((uintptr_t)&prov->dtpv_pops + offs));
7775 
7776 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
7777 	}
7778 
7779 	dtrace_interrupt_enable(cookie);
7780 }
7781 
7782 static int
7783 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
7784 {
7785 	dtrace_probekey_t pkey;
7786 	uint32_t priv;
7787 	uid_t uid;
7788 	zoneid_t zoneid;
7789 
7790 	ASSERT(MUTEX_HELD(&dtrace_lock));
7791 	dtrace_ecb_create_cache = NULL;
7792 
7793 	if (desc == NULL) {
7794 		/*
7795 		 * If we're passed a NULL description, we're being asked to
7796 		 * create an ECB with a NULL probe.
7797 		 */
7798 		(void) dtrace_ecb_create_enable(NULL, enab);
7799 		return (0);
7800 	}
7801 
7802 	dtrace_probekey(desc, &pkey);
7803 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
7804 	    &priv, &uid, &zoneid);
7805 
7806 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
7807 	    enab));
7808 }
7809 
7810 /*
7811  * DTrace Helper Provider Functions
7812  */
7813 static void
7814 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
7815 {
7816 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
7817 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
7818 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
7819 }
7820 
7821 static void
7822 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
7823     const dof_provider_t *dofprov, char *strtab)
7824 {
7825 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
7826 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
7827 	    dofprov->dofpv_provattr);
7828 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
7829 	    dofprov->dofpv_modattr);
7830 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
7831 	    dofprov->dofpv_funcattr);
7832 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
7833 	    dofprov->dofpv_nameattr);
7834 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
7835 	    dofprov->dofpv_argsattr);
7836 }
7837 
7838 static void
7839 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7840 {
7841 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7842 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7843 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
7844 	dof_provider_t *provider;
7845 	dof_probe_t *probe;
7846 	uint32_t *off, *enoff;
7847 	uint8_t *arg;
7848 	char *strtab;
7849 	uint_t i, nprobes;
7850 	dtrace_helper_provdesc_t dhpv;
7851 	dtrace_helper_probedesc_t dhpb;
7852 	dtrace_meta_t *meta = dtrace_meta_pid;
7853 	dtrace_mops_t *mops = &meta->dtm_mops;
7854 	void *parg;
7855 
7856 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7857 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7858 	    provider->dofpv_strtab * dof->dofh_secsize);
7859 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7860 	    provider->dofpv_probes * dof->dofh_secsize);
7861 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7862 	    provider->dofpv_prargs * dof->dofh_secsize);
7863 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7864 	    provider->dofpv_proffs * dof->dofh_secsize);
7865 
7866 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7867 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
7868 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
7869 	enoff = NULL;
7870 
7871 	/*
7872 	 * See dtrace_helper_provider_validate().
7873 	 */
7874 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
7875 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
7876 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7877 		    provider->dofpv_prenoffs * dof->dofh_secsize);
7878 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
7879 	}
7880 
7881 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
7882 
7883 	/*
7884 	 * Create the provider.
7885 	 */
7886 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7887 
7888 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
7889 		return;
7890 
7891 	meta->dtm_count++;
7892 
7893 	/*
7894 	 * Create the probes.
7895 	 */
7896 	for (i = 0; i < nprobes; i++) {
7897 		probe = (dof_probe_t *)(uintptr_t)(daddr +
7898 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
7899 
7900 		dhpb.dthpb_mod = dhp->dofhp_mod;
7901 		dhpb.dthpb_func = strtab + probe->dofpr_func;
7902 		dhpb.dthpb_name = strtab + probe->dofpr_name;
7903 		dhpb.dthpb_base = probe->dofpr_addr;
7904 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
7905 		dhpb.dthpb_noffs = probe->dofpr_noffs;
7906 		if (enoff != NULL) {
7907 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
7908 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
7909 		} else {
7910 			dhpb.dthpb_enoffs = NULL;
7911 			dhpb.dthpb_nenoffs = 0;
7912 		}
7913 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
7914 		dhpb.dthpb_nargc = probe->dofpr_nargc;
7915 		dhpb.dthpb_xargc = probe->dofpr_xargc;
7916 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
7917 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
7918 
7919 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
7920 	}
7921 }
7922 
7923 static void
7924 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
7925 {
7926 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7927 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7928 	int i;
7929 
7930 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7931 
7932 	for (i = 0; i < dof->dofh_secnum; i++) {
7933 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7934 		    dof->dofh_secoff + i * dof->dofh_secsize);
7935 
7936 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7937 			continue;
7938 
7939 		dtrace_helper_provide_one(dhp, sec, pid);
7940 	}
7941 
7942 	/*
7943 	 * We may have just created probes, so we must now rematch against
7944 	 * any retained enablings.  Note that this call will acquire both
7945 	 * cpu_lock and dtrace_lock; the fact that we are holding
7946 	 * dtrace_meta_lock now is what defines the ordering with respect to
7947 	 * these three locks.
7948 	 */
7949 	dtrace_enabling_matchall();
7950 }
7951 
7952 static void
7953 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7954 {
7955 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7956 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7957 	dof_sec_t *str_sec;
7958 	dof_provider_t *provider;
7959 	char *strtab;
7960 	dtrace_helper_provdesc_t dhpv;
7961 	dtrace_meta_t *meta = dtrace_meta_pid;
7962 	dtrace_mops_t *mops = &meta->dtm_mops;
7963 
7964 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7965 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7966 	    provider->dofpv_strtab * dof->dofh_secsize);
7967 
7968 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7969 
7970 	/*
7971 	 * Create the provider.
7972 	 */
7973 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7974 
7975 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
7976 
7977 	meta->dtm_count--;
7978 }
7979 
7980 static void
7981 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
7982 {
7983 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7984 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7985 	int i;
7986 
7987 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7988 
7989 	for (i = 0; i < dof->dofh_secnum; i++) {
7990 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7991 		    dof->dofh_secoff + i * dof->dofh_secsize);
7992 
7993 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7994 			continue;
7995 
7996 		dtrace_helper_provider_remove_one(dhp, sec, pid);
7997 	}
7998 }
7999 
8000 /*
8001  * DTrace Meta Provider-to-Framework API Functions
8002  *
8003  * These functions implement the Meta Provider-to-Framework API, as described
8004  * in <sys/dtrace.h>.
8005  */
8006 int
8007 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
8008     dtrace_meta_provider_id_t *idp)
8009 {
8010 	dtrace_meta_t *meta;
8011 	dtrace_helpers_t *help, *next;
8012 	int i;
8013 
8014 	*idp = DTRACE_METAPROVNONE;
8015 
8016 	/*
8017 	 * We strictly don't need the name, but we hold onto it for
8018 	 * debuggability. All hail error queues!
8019 	 */
8020 	if (name == NULL) {
8021 		cmn_err(CE_WARN, "failed to register meta-provider: "
8022 		    "invalid name");
8023 		return (EINVAL);
8024 	}
8025 
8026 	if (mops == NULL ||
8027 	    mops->dtms_create_probe == NULL ||
8028 	    mops->dtms_provide_pid == NULL ||
8029 	    mops->dtms_remove_pid == NULL) {
8030 		cmn_err(CE_WARN, "failed to register meta-register %s: "
8031 		    "invalid ops", name);
8032 		return (EINVAL);
8033 	}
8034 
8035 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
8036 	meta->dtm_mops = *mops;
8037 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8038 	(void) strcpy(meta->dtm_name, name);
8039 	meta->dtm_arg = arg;
8040 
8041 	mutex_enter(&dtrace_meta_lock);
8042 	mutex_enter(&dtrace_lock);
8043 
8044 	if (dtrace_meta_pid != NULL) {
8045 		mutex_exit(&dtrace_lock);
8046 		mutex_exit(&dtrace_meta_lock);
8047 		cmn_err(CE_WARN, "failed to register meta-register %s: "
8048 		    "user-land meta-provider exists", name);
8049 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
8050 		kmem_free(meta, sizeof (dtrace_meta_t));
8051 		return (EINVAL);
8052 	}
8053 
8054 	dtrace_meta_pid = meta;
8055 	*idp = (dtrace_meta_provider_id_t)meta;
8056 
8057 	/*
8058 	 * If there are providers and probes ready to go, pass them
8059 	 * off to the new meta provider now.
8060 	 */
8061 
8062 	help = dtrace_deferred_pid;
8063 	dtrace_deferred_pid = NULL;
8064 
8065 	mutex_exit(&dtrace_lock);
8066 
8067 	while (help != NULL) {
8068 		for (i = 0; i < help->dthps_nprovs; i++) {
8069 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
8070 			    help->dthps_pid);
8071 		}
8072 
8073 		next = help->dthps_next;
8074 		help->dthps_next = NULL;
8075 		help->dthps_prev = NULL;
8076 		help->dthps_deferred = 0;
8077 		help = next;
8078 	}
8079 
8080 	mutex_exit(&dtrace_meta_lock);
8081 
8082 	return (0);
8083 }
8084 
8085 int
8086 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
8087 {
8088 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
8089 
8090 	mutex_enter(&dtrace_meta_lock);
8091 	mutex_enter(&dtrace_lock);
8092 
8093 	if (old == dtrace_meta_pid) {
8094 		pp = &dtrace_meta_pid;
8095 	} else {
8096 		panic("attempt to unregister non-existent "
8097 		    "dtrace meta-provider %p\n", (void *)old);
8098 	}
8099 
8100 	if (old->dtm_count != 0) {
8101 		mutex_exit(&dtrace_lock);
8102 		mutex_exit(&dtrace_meta_lock);
8103 		return (EBUSY);
8104 	}
8105 
8106 	*pp = NULL;
8107 
8108 	mutex_exit(&dtrace_lock);
8109 	mutex_exit(&dtrace_meta_lock);
8110 
8111 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
8112 	kmem_free(old, sizeof (dtrace_meta_t));
8113 
8114 	return (0);
8115 }
8116 
8117 
8118 /*
8119  * DTrace DIF Object Functions
8120  */
8121 static int
8122 dtrace_difo_err(uint_t pc, const char *format, ...)
8123 {
8124 	if (dtrace_err_verbose) {
8125 		va_list alist;
8126 
8127 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
8128 		va_start(alist, format);
8129 		(void) vuprintf(format, alist);
8130 		va_end(alist);
8131 	}
8132 
8133 #ifdef DTRACE_ERRDEBUG
8134 	dtrace_errdebug(format);
8135 #endif
8136 	return (1);
8137 }
8138 
8139 /*
8140  * Validate a DTrace DIF object by checking the IR instructions.  The following
8141  * rules are currently enforced by dtrace_difo_validate():
8142  *
8143  * 1. Each instruction must have a valid opcode
8144  * 2. Each register, string, variable, or subroutine reference must be valid
8145  * 3. No instruction can modify register %r0 (must be zero)
8146  * 4. All instruction reserved bits must be set to zero
8147  * 5. The last instruction must be a "ret" instruction
8148  * 6. All branch targets must reference a valid instruction _after_ the branch
8149  */
8150 static int
8151 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
8152     cred_t *cr)
8153 {
8154 	int err = 0, i;
8155 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8156 	int kcheckload;
8157 	uint_t pc;
8158 
8159 	kcheckload = cr == NULL ||
8160 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
8161 
8162 	dp->dtdo_destructive = 0;
8163 
8164 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
8165 		dif_instr_t instr = dp->dtdo_buf[pc];
8166 
8167 		uint_t r1 = DIF_INSTR_R1(instr);
8168 		uint_t r2 = DIF_INSTR_R2(instr);
8169 		uint_t rd = DIF_INSTR_RD(instr);
8170 		uint_t rs = DIF_INSTR_RS(instr);
8171 		uint_t label = DIF_INSTR_LABEL(instr);
8172 		uint_t v = DIF_INSTR_VAR(instr);
8173 		uint_t subr = DIF_INSTR_SUBR(instr);
8174 		uint_t type = DIF_INSTR_TYPE(instr);
8175 		uint_t op = DIF_INSTR_OP(instr);
8176 
8177 		switch (op) {
8178 		case DIF_OP_OR:
8179 		case DIF_OP_XOR:
8180 		case DIF_OP_AND:
8181 		case DIF_OP_SLL:
8182 		case DIF_OP_SRL:
8183 		case DIF_OP_SRA:
8184 		case DIF_OP_SUB:
8185 		case DIF_OP_ADD:
8186 		case DIF_OP_MUL:
8187 		case DIF_OP_SDIV:
8188 		case DIF_OP_UDIV:
8189 		case DIF_OP_SREM:
8190 		case DIF_OP_UREM:
8191 		case DIF_OP_COPYS:
8192 			if (r1 >= nregs)
8193 				err += efunc(pc, "invalid register %u\n", r1);
8194 			if (r2 >= nregs)
8195 				err += efunc(pc, "invalid register %u\n", r2);
8196 			if (rd >= nregs)
8197 				err += efunc(pc, "invalid register %u\n", rd);
8198 			if (rd == 0)
8199 				err += efunc(pc, "cannot write to %r0\n");
8200 			break;
8201 		case DIF_OP_NOT:
8202 		case DIF_OP_MOV:
8203 		case DIF_OP_ALLOCS:
8204 			if (r1 >= nregs)
8205 				err += efunc(pc, "invalid register %u\n", r1);
8206 			if (r2 != 0)
8207 				err += efunc(pc, "non-zero reserved bits\n");
8208 			if (rd >= nregs)
8209 				err += efunc(pc, "invalid register %u\n", rd);
8210 			if (rd == 0)
8211 				err += efunc(pc, "cannot write to %r0\n");
8212 			break;
8213 		case DIF_OP_LDSB:
8214 		case DIF_OP_LDSH:
8215 		case DIF_OP_LDSW:
8216 		case DIF_OP_LDUB:
8217 		case DIF_OP_LDUH:
8218 		case DIF_OP_LDUW:
8219 		case DIF_OP_LDX:
8220 			if (r1 >= nregs)
8221 				err += efunc(pc, "invalid register %u\n", r1);
8222 			if (r2 != 0)
8223 				err += efunc(pc, "non-zero reserved bits\n");
8224 			if (rd >= nregs)
8225 				err += efunc(pc, "invalid register %u\n", rd);
8226 			if (rd == 0)
8227 				err += efunc(pc, "cannot write to %r0\n");
8228 			if (kcheckload)
8229 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
8230 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
8231 			break;
8232 		case DIF_OP_RLDSB:
8233 		case DIF_OP_RLDSH:
8234 		case DIF_OP_RLDSW:
8235 		case DIF_OP_RLDUB:
8236 		case DIF_OP_RLDUH:
8237 		case DIF_OP_RLDUW:
8238 		case DIF_OP_RLDX:
8239 			if (r1 >= nregs)
8240 				err += efunc(pc, "invalid register %u\n", r1);
8241 			if (r2 != 0)
8242 				err += efunc(pc, "non-zero reserved bits\n");
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_ULDSB:
8249 		case DIF_OP_ULDSH:
8250 		case DIF_OP_ULDSW:
8251 		case DIF_OP_ULDUB:
8252 		case DIF_OP_ULDUH:
8253 		case DIF_OP_ULDUW:
8254 		case DIF_OP_ULDX:
8255 			if (r1 >= nregs)
8256 				err += efunc(pc, "invalid register %u\n", r1);
8257 			if (r2 != 0)
8258 				err += efunc(pc, "non-zero reserved bits\n");
8259 			if (rd >= nregs)
8260 				err += efunc(pc, "invalid register %u\n", rd);
8261 			if (rd == 0)
8262 				err += efunc(pc, "cannot write to %r0\n");
8263 			break;
8264 		case DIF_OP_STB:
8265 		case DIF_OP_STH:
8266 		case DIF_OP_STW:
8267 		case DIF_OP_STX:
8268 			if (r1 >= nregs)
8269 				err += efunc(pc, "invalid register %u\n", r1);
8270 			if (r2 != 0)
8271 				err += efunc(pc, "non-zero reserved bits\n");
8272 			if (rd >= nregs)
8273 				err += efunc(pc, "invalid register %u\n", rd);
8274 			if (rd == 0)
8275 				err += efunc(pc, "cannot write to 0 address\n");
8276 			break;
8277 		case DIF_OP_CMP:
8278 		case DIF_OP_SCMP:
8279 			if (r1 >= nregs)
8280 				err += efunc(pc, "invalid register %u\n", r1);
8281 			if (r2 >= nregs)
8282 				err += efunc(pc, "invalid register %u\n", r2);
8283 			if (rd != 0)
8284 				err += efunc(pc, "non-zero reserved bits\n");
8285 			break;
8286 		case DIF_OP_TST:
8287 			if (r1 >= nregs)
8288 				err += efunc(pc, "invalid register %u\n", r1);
8289 			if (r2 != 0 || rd != 0)
8290 				err += efunc(pc, "non-zero reserved bits\n");
8291 			break;
8292 		case DIF_OP_BA:
8293 		case DIF_OP_BE:
8294 		case DIF_OP_BNE:
8295 		case DIF_OP_BG:
8296 		case DIF_OP_BGU:
8297 		case DIF_OP_BGE:
8298 		case DIF_OP_BGEU:
8299 		case DIF_OP_BL:
8300 		case DIF_OP_BLU:
8301 		case DIF_OP_BLE:
8302 		case DIF_OP_BLEU:
8303 			if (label >= dp->dtdo_len) {
8304 				err += efunc(pc, "invalid branch target %u\n",
8305 				    label);
8306 			}
8307 			if (label <= pc) {
8308 				err += efunc(pc, "backward branch to %u\n",
8309 				    label);
8310 			}
8311 			break;
8312 		case DIF_OP_RET:
8313 			if (r1 != 0 || r2 != 0)
8314 				err += efunc(pc, "non-zero reserved bits\n");
8315 			if (rd >= nregs)
8316 				err += efunc(pc, "invalid register %u\n", rd);
8317 			break;
8318 		case DIF_OP_NOP:
8319 		case DIF_OP_POPTS:
8320 		case DIF_OP_FLUSHTS:
8321 			if (r1 != 0 || r2 != 0 || rd != 0)
8322 				err += efunc(pc, "non-zero reserved bits\n");
8323 			break;
8324 		case DIF_OP_SETX:
8325 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8326 				err += efunc(pc, "invalid integer ref %u\n",
8327 				    DIF_INSTR_INTEGER(instr));
8328 			}
8329 			if (rd >= nregs)
8330 				err += efunc(pc, "invalid register %u\n", rd);
8331 			if (rd == 0)
8332 				err += efunc(pc, "cannot write to %r0\n");
8333 			break;
8334 		case DIF_OP_SETS:
8335 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8336 				err += efunc(pc, "invalid string ref %u\n",
8337 				    DIF_INSTR_STRING(instr));
8338 			}
8339 			if (rd >= nregs)
8340 				err += efunc(pc, "invalid register %u\n", rd);
8341 			if (rd == 0)
8342 				err += efunc(pc, "cannot write to %r0\n");
8343 			break;
8344 		case DIF_OP_LDGA:
8345 		case DIF_OP_LDTA:
8346 			if (r1 > DIF_VAR_ARRAY_MAX)
8347 				err += efunc(pc, "invalid array %u\n", r1);
8348 			if (r2 >= nregs)
8349 				err += efunc(pc, "invalid register %u\n", r2);
8350 			if (rd >= nregs)
8351 				err += efunc(pc, "invalid register %u\n", rd);
8352 			if (rd == 0)
8353 				err += efunc(pc, "cannot write to %r0\n");
8354 			break;
8355 		case DIF_OP_LDGS:
8356 		case DIF_OP_LDTS:
8357 		case DIF_OP_LDLS:
8358 		case DIF_OP_LDGAA:
8359 		case DIF_OP_LDTAA:
8360 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8361 				err += efunc(pc, "invalid variable %u\n", v);
8362 			if (rd >= nregs)
8363 				err += efunc(pc, "invalid register %u\n", rd);
8364 			if (rd == 0)
8365 				err += efunc(pc, "cannot write to %r0\n");
8366 			break;
8367 		case DIF_OP_STGS:
8368 		case DIF_OP_STTS:
8369 		case DIF_OP_STLS:
8370 		case DIF_OP_STGAA:
8371 		case DIF_OP_STTAA:
8372 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8373 				err += efunc(pc, "invalid variable %u\n", v);
8374 			if (rs >= nregs)
8375 				err += efunc(pc, "invalid register %u\n", rd);
8376 			break;
8377 		case DIF_OP_CALL:
8378 			if (subr > DIF_SUBR_MAX)
8379 				err += efunc(pc, "invalid subr %u\n", subr);
8380 			if (rd >= nregs)
8381 				err += efunc(pc, "invalid register %u\n", rd);
8382 			if (rd == 0)
8383 				err += efunc(pc, "cannot write to %r0\n");
8384 
8385 			if (subr == DIF_SUBR_COPYOUT ||
8386 			    subr == DIF_SUBR_COPYOUTSTR) {
8387 				dp->dtdo_destructive = 1;
8388 			}
8389 			break;
8390 		case DIF_OP_PUSHTR:
8391 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8392 				err += efunc(pc, "invalid ref type %u\n", type);
8393 			if (r2 >= nregs)
8394 				err += efunc(pc, "invalid register %u\n", r2);
8395 			if (rs >= nregs)
8396 				err += efunc(pc, "invalid register %u\n", rs);
8397 			break;
8398 		case DIF_OP_PUSHTV:
8399 			if (type != DIF_TYPE_CTF)
8400 				err += efunc(pc, "invalid val type %u\n", type);
8401 			if (r2 >= nregs)
8402 				err += efunc(pc, "invalid register %u\n", r2);
8403 			if (rs >= nregs)
8404 				err += efunc(pc, "invalid register %u\n", rs);
8405 			break;
8406 		default:
8407 			err += efunc(pc, "invalid opcode %u\n",
8408 			    DIF_INSTR_OP(instr));
8409 		}
8410 	}
8411 
8412 	if (dp->dtdo_len != 0 &&
8413 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8414 		err += efunc(dp->dtdo_len - 1,
8415 		    "expected 'ret' as last DIF instruction\n");
8416 	}
8417 
8418 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
8419 		/*
8420 		 * If we're not returning by reference, the size must be either
8421 		 * 0 or the size of one of the base types.
8422 		 */
8423 		switch (dp->dtdo_rtype.dtdt_size) {
8424 		case 0:
8425 		case sizeof (uint8_t):
8426 		case sizeof (uint16_t):
8427 		case sizeof (uint32_t):
8428 		case sizeof (uint64_t):
8429 			break;
8430 
8431 		default:
8432 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
8433 		}
8434 	}
8435 
8436 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8437 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8438 		dtrace_diftype_t *vt, *et;
8439 		uint_t id, ndx;
8440 
8441 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8442 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
8443 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8444 			err += efunc(i, "unrecognized variable scope %d\n",
8445 			    v->dtdv_scope);
8446 			break;
8447 		}
8448 
8449 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8450 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
8451 			err += efunc(i, "unrecognized variable type %d\n",
8452 			    v->dtdv_kind);
8453 			break;
8454 		}
8455 
8456 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8457 			err += efunc(i, "%d exceeds variable id limit\n", id);
8458 			break;
8459 		}
8460 
8461 		if (id < DIF_VAR_OTHER_UBASE)
8462 			continue;
8463 
8464 		/*
8465 		 * For user-defined variables, we need to check that this
8466 		 * definition is identical to any previous definition that we
8467 		 * encountered.
8468 		 */
8469 		ndx = id - DIF_VAR_OTHER_UBASE;
8470 
8471 		switch (v->dtdv_scope) {
8472 		case DIFV_SCOPE_GLOBAL:
8473 			if (ndx < vstate->dtvs_nglobals) {
8474 				dtrace_statvar_t *svar;
8475 
8476 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8477 					existing = &svar->dtsv_var;
8478 			}
8479 
8480 			break;
8481 
8482 		case DIFV_SCOPE_THREAD:
8483 			if (ndx < vstate->dtvs_ntlocals)
8484 				existing = &vstate->dtvs_tlocals[ndx];
8485 			break;
8486 
8487 		case DIFV_SCOPE_LOCAL:
8488 			if (ndx < vstate->dtvs_nlocals) {
8489 				dtrace_statvar_t *svar;
8490 
8491 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8492 					existing = &svar->dtsv_var;
8493 			}
8494 
8495 			break;
8496 		}
8497 
8498 		vt = &v->dtdv_type;
8499 
8500 		if (vt->dtdt_flags & DIF_TF_BYREF) {
8501 			if (vt->dtdt_size == 0) {
8502 				err += efunc(i, "zero-sized variable\n");
8503 				break;
8504 			}
8505 
8506 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8507 			    vt->dtdt_size > dtrace_global_maxsize) {
8508 				err += efunc(i, "oversized by-ref global\n");
8509 				break;
8510 			}
8511 		}
8512 
8513 		if (existing == NULL || existing->dtdv_id == 0)
8514 			continue;
8515 
8516 		ASSERT(existing->dtdv_id == v->dtdv_id);
8517 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
8518 
8519 		if (existing->dtdv_kind != v->dtdv_kind)
8520 			err += efunc(i, "%d changed variable kind\n", id);
8521 
8522 		et = &existing->dtdv_type;
8523 
8524 		if (vt->dtdt_flags != et->dtdt_flags) {
8525 			err += efunc(i, "%d changed variable type flags\n", id);
8526 			break;
8527 		}
8528 
8529 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8530 			err += efunc(i, "%d changed variable type size\n", id);
8531 			break;
8532 		}
8533 	}
8534 
8535 	return (err);
8536 }
8537 
8538 /*
8539  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
8540  * are much more constrained than normal DIFOs.  Specifically, they may
8541  * not:
8542  *
8543  * 1. Make calls to subroutines other than copyin(), copyinstr() or
8544  *    miscellaneous string routines
8545  * 2. Access DTrace variables other than the args[] array, and the
8546  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8547  * 3. Have thread-local variables.
8548  * 4. Have dynamic variables.
8549  */
8550 static int
8551 dtrace_difo_validate_helper(dtrace_difo_t *dp)
8552 {
8553 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8554 	int err = 0;
8555 	uint_t pc;
8556 
8557 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8558 		dif_instr_t instr = dp->dtdo_buf[pc];
8559 
8560 		uint_t v = DIF_INSTR_VAR(instr);
8561 		uint_t subr = DIF_INSTR_SUBR(instr);
8562 		uint_t op = DIF_INSTR_OP(instr);
8563 
8564 		switch (op) {
8565 		case DIF_OP_OR:
8566 		case DIF_OP_XOR:
8567 		case DIF_OP_AND:
8568 		case DIF_OP_SLL:
8569 		case DIF_OP_SRL:
8570 		case DIF_OP_SRA:
8571 		case DIF_OP_SUB:
8572 		case DIF_OP_ADD:
8573 		case DIF_OP_MUL:
8574 		case DIF_OP_SDIV:
8575 		case DIF_OP_UDIV:
8576 		case DIF_OP_SREM:
8577 		case DIF_OP_UREM:
8578 		case DIF_OP_COPYS:
8579 		case DIF_OP_NOT:
8580 		case DIF_OP_MOV:
8581 		case DIF_OP_RLDSB:
8582 		case DIF_OP_RLDSH:
8583 		case DIF_OP_RLDSW:
8584 		case DIF_OP_RLDUB:
8585 		case DIF_OP_RLDUH:
8586 		case DIF_OP_RLDUW:
8587 		case DIF_OP_RLDX:
8588 		case DIF_OP_ULDSB:
8589 		case DIF_OP_ULDSH:
8590 		case DIF_OP_ULDSW:
8591 		case DIF_OP_ULDUB:
8592 		case DIF_OP_ULDUH:
8593 		case DIF_OP_ULDUW:
8594 		case DIF_OP_ULDX:
8595 		case DIF_OP_STB:
8596 		case DIF_OP_STH:
8597 		case DIF_OP_STW:
8598 		case DIF_OP_STX:
8599 		case DIF_OP_ALLOCS:
8600 		case DIF_OP_CMP:
8601 		case DIF_OP_SCMP:
8602 		case DIF_OP_TST:
8603 		case DIF_OP_BA:
8604 		case DIF_OP_BE:
8605 		case DIF_OP_BNE:
8606 		case DIF_OP_BG:
8607 		case DIF_OP_BGU:
8608 		case DIF_OP_BGE:
8609 		case DIF_OP_BGEU:
8610 		case DIF_OP_BL:
8611 		case DIF_OP_BLU:
8612 		case DIF_OP_BLE:
8613 		case DIF_OP_BLEU:
8614 		case DIF_OP_RET:
8615 		case DIF_OP_NOP:
8616 		case DIF_OP_POPTS:
8617 		case DIF_OP_FLUSHTS:
8618 		case DIF_OP_SETX:
8619 		case DIF_OP_SETS:
8620 		case DIF_OP_LDGA:
8621 		case DIF_OP_LDLS:
8622 		case DIF_OP_STGS:
8623 		case DIF_OP_STLS:
8624 		case DIF_OP_PUSHTR:
8625 		case DIF_OP_PUSHTV:
8626 			break;
8627 
8628 		case DIF_OP_LDGS:
8629 			if (v >= DIF_VAR_OTHER_UBASE)
8630 				break;
8631 
8632 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
8633 				break;
8634 
8635 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
8636 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
8637 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
8638 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
8639 				break;
8640 
8641 			err += efunc(pc, "illegal variable %u\n", v);
8642 			break;
8643 
8644 		case DIF_OP_LDTA:
8645 		case DIF_OP_LDTS:
8646 		case DIF_OP_LDGAA:
8647 		case DIF_OP_LDTAA:
8648 			err += efunc(pc, "illegal dynamic variable load\n");
8649 			break;
8650 
8651 		case DIF_OP_STTS:
8652 		case DIF_OP_STGAA:
8653 		case DIF_OP_STTAA:
8654 			err += efunc(pc, "illegal dynamic variable store\n");
8655 			break;
8656 
8657 		case DIF_OP_CALL:
8658 			if (subr == DIF_SUBR_ALLOCA ||
8659 			    subr == DIF_SUBR_BCOPY ||
8660 			    subr == DIF_SUBR_COPYIN ||
8661 			    subr == DIF_SUBR_COPYINTO ||
8662 			    subr == DIF_SUBR_COPYINSTR ||
8663 			    subr == DIF_SUBR_INDEX ||
8664 			    subr == DIF_SUBR_INET_NTOA ||
8665 			    subr == DIF_SUBR_INET_NTOA6 ||
8666 			    subr == DIF_SUBR_INET_NTOP ||
8667 			    subr == DIF_SUBR_LLTOSTR ||
8668 			    subr == DIF_SUBR_RINDEX ||
8669 			    subr == DIF_SUBR_STRCHR ||
8670 			    subr == DIF_SUBR_STRJOIN ||
8671 			    subr == DIF_SUBR_STRRCHR ||
8672 			    subr == DIF_SUBR_STRSTR ||
8673 			    subr == DIF_SUBR_HTONS ||
8674 			    subr == DIF_SUBR_HTONL ||
8675 			    subr == DIF_SUBR_HTONLL ||
8676 			    subr == DIF_SUBR_NTOHS ||
8677 			    subr == DIF_SUBR_NTOHL ||
8678 			    subr == DIF_SUBR_NTOHLL)
8679 				break;
8680 
8681 			err += efunc(pc, "invalid subr %u\n", subr);
8682 			break;
8683 
8684 		default:
8685 			err += efunc(pc, "invalid opcode %u\n",
8686 			    DIF_INSTR_OP(instr));
8687 		}
8688 	}
8689 
8690 	return (err);
8691 }
8692 
8693 /*
8694  * Returns 1 if the expression in the DIF object can be cached on a per-thread
8695  * basis; 0 if not.
8696  */
8697 static int
8698 dtrace_difo_cacheable(dtrace_difo_t *dp)
8699 {
8700 	int i;
8701 
8702 	if (dp == NULL)
8703 		return (0);
8704 
8705 	for (i = 0; i < dp->dtdo_varlen; i++) {
8706 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8707 
8708 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
8709 			continue;
8710 
8711 		switch (v->dtdv_id) {
8712 		case DIF_VAR_CURTHREAD:
8713 		case DIF_VAR_PID:
8714 		case DIF_VAR_TID:
8715 		case DIF_VAR_EXECNAME:
8716 		case DIF_VAR_ZONENAME:
8717 			break;
8718 
8719 		default:
8720 			return (0);
8721 		}
8722 	}
8723 
8724 	/*
8725 	 * This DIF object may be cacheable.  Now we need to look for any
8726 	 * array loading instructions, any memory loading instructions, or
8727 	 * any stores to thread-local variables.
8728 	 */
8729 	for (i = 0; i < dp->dtdo_len; i++) {
8730 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
8731 
8732 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
8733 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
8734 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
8735 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
8736 			return (0);
8737 	}
8738 
8739 	return (1);
8740 }
8741 
8742 static void
8743 dtrace_difo_hold(dtrace_difo_t *dp)
8744 {
8745 	int i;
8746 
8747 	ASSERT(MUTEX_HELD(&dtrace_lock));
8748 
8749 	dp->dtdo_refcnt++;
8750 	ASSERT(dp->dtdo_refcnt != 0);
8751 
8752 	/*
8753 	 * We need to check this DIF object for references to the variable
8754 	 * DIF_VAR_VTIMESTAMP.
8755 	 */
8756 	for (i = 0; i < dp->dtdo_varlen; i++) {
8757 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8758 
8759 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8760 			continue;
8761 
8762 		if (dtrace_vtime_references++ == 0)
8763 			dtrace_vtime_enable();
8764 	}
8765 }
8766 
8767 /*
8768  * This routine calculates the dynamic variable chunksize for a given DIF
8769  * object.  The calculation is not fool-proof, and can probably be tricked by
8770  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
8771  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
8772  * if a dynamic variable size exceeds the chunksize.
8773  */
8774 static void
8775 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8776 {
8777 	uint64_t sval;
8778 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
8779 	const dif_instr_t *text = dp->dtdo_buf;
8780 	uint_t pc, srd = 0;
8781 	uint_t ttop = 0;
8782 	size_t size, ksize;
8783 	uint_t id, i;
8784 
8785 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8786 		dif_instr_t instr = text[pc];
8787 		uint_t op = DIF_INSTR_OP(instr);
8788 		uint_t rd = DIF_INSTR_RD(instr);
8789 		uint_t r1 = DIF_INSTR_R1(instr);
8790 		uint_t nkeys = 0;
8791 		uchar_t scope;
8792 
8793 		dtrace_key_t *key = tupregs;
8794 
8795 		switch (op) {
8796 		case DIF_OP_SETX:
8797 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
8798 			srd = rd;
8799 			continue;
8800 
8801 		case DIF_OP_STTS:
8802 			key = &tupregs[DIF_DTR_NREGS];
8803 			key[0].dttk_size = 0;
8804 			key[1].dttk_size = 0;
8805 			nkeys = 2;
8806 			scope = DIFV_SCOPE_THREAD;
8807 			break;
8808 
8809 		case DIF_OP_STGAA:
8810 		case DIF_OP_STTAA:
8811 			nkeys = ttop;
8812 
8813 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
8814 				key[nkeys++].dttk_size = 0;
8815 
8816 			key[nkeys++].dttk_size = 0;
8817 
8818 			if (op == DIF_OP_STTAA) {
8819 				scope = DIFV_SCOPE_THREAD;
8820 			} else {
8821 				scope = DIFV_SCOPE_GLOBAL;
8822 			}
8823 
8824 			break;
8825 
8826 		case DIF_OP_PUSHTR:
8827 			if (ttop == DIF_DTR_NREGS)
8828 				return;
8829 
8830 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
8831 				/*
8832 				 * If the register for the size of the "pushtr"
8833 				 * is %r0 (or the value is 0) and the type is
8834 				 * a string, we'll use the system-wide default
8835 				 * string size.
8836 				 */
8837 				tupregs[ttop++].dttk_size =
8838 				    dtrace_strsize_default;
8839 			} else {
8840 				if (srd == 0)
8841 					return;
8842 
8843 				tupregs[ttop++].dttk_size = sval;
8844 			}
8845 
8846 			break;
8847 
8848 		case DIF_OP_PUSHTV:
8849 			if (ttop == DIF_DTR_NREGS)
8850 				return;
8851 
8852 			tupregs[ttop++].dttk_size = 0;
8853 			break;
8854 
8855 		case DIF_OP_FLUSHTS:
8856 			ttop = 0;
8857 			break;
8858 
8859 		case DIF_OP_POPTS:
8860 			if (ttop != 0)
8861 				ttop--;
8862 			break;
8863 		}
8864 
8865 		sval = 0;
8866 		srd = 0;
8867 
8868 		if (nkeys == 0)
8869 			continue;
8870 
8871 		/*
8872 		 * We have a dynamic variable allocation; calculate its size.
8873 		 */
8874 		for (ksize = 0, i = 0; i < nkeys; i++)
8875 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
8876 
8877 		size = sizeof (dtrace_dynvar_t);
8878 		size += sizeof (dtrace_key_t) * (nkeys - 1);
8879 		size += ksize;
8880 
8881 		/*
8882 		 * Now we need to determine the size of the stored data.
8883 		 */
8884 		id = DIF_INSTR_VAR(instr);
8885 
8886 		for (i = 0; i < dp->dtdo_varlen; i++) {
8887 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
8888 
8889 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
8890 				size += v->dtdv_type.dtdt_size;
8891 				break;
8892 			}
8893 		}
8894 
8895 		if (i == dp->dtdo_varlen)
8896 			return;
8897 
8898 		/*
8899 		 * We have the size.  If this is larger than the chunk size
8900 		 * for our dynamic variable state, reset the chunk size.
8901 		 */
8902 		size = P2ROUNDUP(size, sizeof (uint64_t));
8903 
8904 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
8905 			vstate->dtvs_dynvars.dtds_chunksize = size;
8906 	}
8907 }
8908 
8909 static void
8910 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8911 {
8912 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
8913 	uint_t id;
8914 
8915 	ASSERT(MUTEX_HELD(&dtrace_lock));
8916 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
8917 
8918 	for (i = 0; i < dp->dtdo_varlen; i++) {
8919 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8920 		dtrace_statvar_t *svar, ***svarp;
8921 		size_t dsize = 0;
8922 		uint8_t scope = v->dtdv_scope;
8923 		int *np;
8924 
8925 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8926 			continue;
8927 
8928 		id -= DIF_VAR_OTHER_UBASE;
8929 
8930 		switch (scope) {
8931 		case DIFV_SCOPE_THREAD:
8932 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
8933 				dtrace_difv_t *tlocals;
8934 
8935 				if ((ntlocals = (otlocals << 1)) == 0)
8936 					ntlocals = 1;
8937 
8938 				osz = otlocals * sizeof (dtrace_difv_t);
8939 				nsz = ntlocals * sizeof (dtrace_difv_t);
8940 
8941 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
8942 
8943 				if (osz != 0) {
8944 					bcopy(vstate->dtvs_tlocals,
8945 					    tlocals, osz);
8946 					kmem_free(vstate->dtvs_tlocals, osz);
8947 				}
8948 
8949 				vstate->dtvs_tlocals = tlocals;
8950 				vstate->dtvs_ntlocals = ntlocals;
8951 			}
8952 
8953 			vstate->dtvs_tlocals[id] = *v;
8954 			continue;
8955 
8956 		case DIFV_SCOPE_LOCAL:
8957 			np = &vstate->dtvs_nlocals;
8958 			svarp = &vstate->dtvs_locals;
8959 
8960 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8961 				dsize = NCPU * (v->dtdv_type.dtdt_size +
8962 				    sizeof (uint64_t));
8963 			else
8964 				dsize = NCPU * sizeof (uint64_t);
8965 
8966 			break;
8967 
8968 		case DIFV_SCOPE_GLOBAL:
8969 			np = &vstate->dtvs_nglobals;
8970 			svarp = &vstate->dtvs_globals;
8971 
8972 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8973 				dsize = v->dtdv_type.dtdt_size +
8974 				    sizeof (uint64_t);
8975 
8976 			break;
8977 
8978 		default:
8979 			ASSERT(0);
8980 		}
8981 
8982 		while (id >= (oldsvars = *np)) {
8983 			dtrace_statvar_t **statics;
8984 			int newsvars, oldsize, newsize;
8985 
8986 			if ((newsvars = (oldsvars << 1)) == 0)
8987 				newsvars = 1;
8988 
8989 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
8990 			newsize = newsvars * sizeof (dtrace_statvar_t *);
8991 
8992 			statics = kmem_zalloc(newsize, KM_SLEEP);
8993 
8994 			if (oldsize != 0) {
8995 				bcopy(*svarp, statics, oldsize);
8996 				kmem_free(*svarp, oldsize);
8997 			}
8998 
8999 			*svarp = statics;
9000 			*np = newsvars;
9001 		}
9002 
9003 		if ((svar = (*svarp)[id]) == NULL) {
9004 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
9005 			svar->dtsv_var = *v;
9006 
9007 			if ((svar->dtsv_size = dsize) != 0) {
9008 				svar->dtsv_data = (uint64_t)(uintptr_t)
9009 				    kmem_zalloc(dsize, KM_SLEEP);
9010 			}
9011 
9012 			(*svarp)[id] = svar;
9013 		}
9014 
9015 		svar->dtsv_refcnt++;
9016 	}
9017 
9018 	dtrace_difo_chunksize(dp, vstate);
9019 	dtrace_difo_hold(dp);
9020 }
9021 
9022 static dtrace_difo_t *
9023 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9024 {
9025 	dtrace_difo_t *new;
9026 	size_t sz;
9027 
9028 	ASSERT(dp->dtdo_buf != NULL);
9029 	ASSERT(dp->dtdo_refcnt != 0);
9030 
9031 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
9032 
9033 	ASSERT(dp->dtdo_buf != NULL);
9034 	sz = dp->dtdo_len * sizeof (dif_instr_t);
9035 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
9036 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
9037 	new->dtdo_len = dp->dtdo_len;
9038 
9039 	if (dp->dtdo_strtab != NULL) {
9040 		ASSERT(dp->dtdo_strlen != 0);
9041 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
9042 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
9043 		new->dtdo_strlen = dp->dtdo_strlen;
9044 	}
9045 
9046 	if (dp->dtdo_inttab != NULL) {
9047 		ASSERT(dp->dtdo_intlen != 0);
9048 		sz = dp->dtdo_intlen * sizeof (uint64_t);
9049 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
9050 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
9051 		new->dtdo_intlen = dp->dtdo_intlen;
9052 	}
9053 
9054 	if (dp->dtdo_vartab != NULL) {
9055 		ASSERT(dp->dtdo_varlen != 0);
9056 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
9057 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
9058 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
9059 		new->dtdo_varlen = dp->dtdo_varlen;
9060 	}
9061 
9062 	dtrace_difo_init(new, vstate);
9063 	return (new);
9064 }
9065 
9066 static void
9067 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9068 {
9069 	int i;
9070 
9071 	ASSERT(dp->dtdo_refcnt == 0);
9072 
9073 	for (i = 0; i < dp->dtdo_varlen; i++) {
9074 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9075 		dtrace_statvar_t *svar, **svarp;
9076 		uint_t id;
9077 		uint8_t scope = v->dtdv_scope;
9078 		int *np;
9079 
9080 		switch (scope) {
9081 		case DIFV_SCOPE_THREAD:
9082 			continue;
9083 
9084 		case DIFV_SCOPE_LOCAL:
9085 			np = &vstate->dtvs_nlocals;
9086 			svarp = vstate->dtvs_locals;
9087 			break;
9088 
9089 		case DIFV_SCOPE_GLOBAL:
9090 			np = &vstate->dtvs_nglobals;
9091 			svarp = vstate->dtvs_globals;
9092 			break;
9093 
9094 		default:
9095 			ASSERT(0);
9096 		}
9097 
9098 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
9099 			continue;
9100 
9101 		id -= DIF_VAR_OTHER_UBASE;
9102 		ASSERT(id < *np);
9103 
9104 		svar = svarp[id];
9105 		ASSERT(svar != NULL);
9106 		ASSERT(svar->dtsv_refcnt > 0);
9107 
9108 		if (--svar->dtsv_refcnt > 0)
9109 			continue;
9110 
9111 		if (svar->dtsv_size != 0) {
9112 			ASSERT(svar->dtsv_data != NULL);
9113 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
9114 			    svar->dtsv_size);
9115 		}
9116 
9117 		kmem_free(svar, sizeof (dtrace_statvar_t));
9118 		svarp[id] = NULL;
9119 	}
9120 
9121 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
9122 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
9123 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
9124 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
9125 
9126 	kmem_free(dp, sizeof (dtrace_difo_t));
9127 }
9128 
9129 static void
9130 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9131 {
9132 	int i;
9133 
9134 	ASSERT(MUTEX_HELD(&dtrace_lock));
9135 	ASSERT(dp->dtdo_refcnt != 0);
9136 
9137 	for (i = 0; i < dp->dtdo_varlen; i++) {
9138 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9139 
9140 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9141 			continue;
9142 
9143 		ASSERT(dtrace_vtime_references > 0);
9144 		if (--dtrace_vtime_references == 0)
9145 			dtrace_vtime_disable();
9146 	}
9147 
9148 	if (--dp->dtdo_refcnt == 0)
9149 		dtrace_difo_destroy(dp, vstate);
9150 }
9151 
9152 /*
9153  * DTrace Format Functions
9154  */
9155 static uint16_t
9156 dtrace_format_add(dtrace_state_t *state, char *str)
9157 {
9158 	char *fmt, **new;
9159 	uint16_t ndx, len = strlen(str) + 1;
9160 
9161 	fmt = kmem_zalloc(len, KM_SLEEP);
9162 	bcopy(str, fmt, len);
9163 
9164 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
9165 		if (state->dts_formats[ndx] == NULL) {
9166 			state->dts_formats[ndx] = fmt;
9167 			return (ndx + 1);
9168 		}
9169 	}
9170 
9171 	if (state->dts_nformats == USHRT_MAX) {
9172 		/*
9173 		 * This is only likely if a denial-of-service attack is being
9174 		 * attempted.  As such, it's okay to fail silently here.
9175 		 */
9176 		kmem_free(fmt, len);
9177 		return (0);
9178 	}
9179 
9180 	/*
9181 	 * For simplicity, we always resize the formats array to be exactly the
9182 	 * number of formats.
9183 	 */
9184 	ndx = state->dts_nformats++;
9185 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
9186 
9187 	if (state->dts_formats != NULL) {
9188 		ASSERT(ndx != 0);
9189 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
9190 		kmem_free(state->dts_formats, ndx * sizeof (char *));
9191 	}
9192 
9193 	state->dts_formats = new;
9194 	state->dts_formats[ndx] = fmt;
9195 
9196 	return (ndx + 1);
9197 }
9198 
9199 static void
9200 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
9201 {
9202 	char *fmt;
9203 
9204 	ASSERT(state->dts_formats != NULL);
9205 	ASSERT(format <= state->dts_nformats);
9206 	ASSERT(state->dts_formats[format - 1] != NULL);
9207 
9208 	fmt = state->dts_formats[format - 1];
9209 	kmem_free(fmt, strlen(fmt) + 1);
9210 	state->dts_formats[format - 1] = NULL;
9211 }
9212 
9213 static void
9214 dtrace_format_destroy(dtrace_state_t *state)
9215 {
9216 	int i;
9217 
9218 	if (state->dts_nformats == 0) {
9219 		ASSERT(state->dts_formats == NULL);
9220 		return;
9221 	}
9222 
9223 	ASSERT(state->dts_formats != NULL);
9224 
9225 	for (i = 0; i < state->dts_nformats; i++) {
9226 		char *fmt = state->dts_formats[i];
9227 
9228 		if (fmt == NULL)
9229 			continue;
9230 
9231 		kmem_free(fmt, strlen(fmt) + 1);
9232 	}
9233 
9234 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
9235 	state->dts_nformats = 0;
9236 	state->dts_formats = NULL;
9237 }
9238 
9239 /*
9240  * DTrace Predicate Functions
9241  */
9242 static dtrace_predicate_t *
9243 dtrace_predicate_create(dtrace_difo_t *dp)
9244 {
9245 	dtrace_predicate_t *pred;
9246 
9247 	ASSERT(MUTEX_HELD(&dtrace_lock));
9248 	ASSERT(dp->dtdo_refcnt != 0);
9249 
9250 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
9251 	pred->dtp_difo = dp;
9252 	pred->dtp_refcnt = 1;
9253 
9254 	if (!dtrace_difo_cacheable(dp))
9255 		return (pred);
9256 
9257 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
9258 		/*
9259 		 * This is only theoretically possible -- we have had 2^32
9260 		 * cacheable predicates on this machine.  We cannot allow any
9261 		 * more predicates to become cacheable:  as unlikely as it is,
9262 		 * there may be a thread caching a (now stale) predicate cache
9263 		 * ID. (N.B.: the temptation is being successfully resisted to
9264 		 * have this cmn_err() "Holy shit -- we executed this code!")
9265 		 */
9266 		return (pred);
9267 	}
9268 
9269 	pred->dtp_cacheid = dtrace_predcache_id++;
9270 
9271 	return (pred);
9272 }
9273 
9274 static void
9275 dtrace_predicate_hold(dtrace_predicate_t *pred)
9276 {
9277 	ASSERT(MUTEX_HELD(&dtrace_lock));
9278 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
9279 	ASSERT(pred->dtp_refcnt > 0);
9280 
9281 	pred->dtp_refcnt++;
9282 }
9283 
9284 static void
9285 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
9286 {
9287 	dtrace_difo_t *dp = pred->dtp_difo;
9288 
9289 	ASSERT(MUTEX_HELD(&dtrace_lock));
9290 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
9291 	ASSERT(pred->dtp_refcnt > 0);
9292 
9293 	if (--pred->dtp_refcnt == 0) {
9294 		dtrace_difo_release(pred->dtp_difo, vstate);
9295 		kmem_free(pred, sizeof (dtrace_predicate_t));
9296 	}
9297 }
9298 
9299 /*
9300  * DTrace Action Description Functions
9301  */
9302 static dtrace_actdesc_t *
9303 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
9304     uint64_t uarg, uint64_t arg)
9305 {
9306 	dtrace_actdesc_t *act;
9307 
9308 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
9309 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
9310 
9311 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9312 	act->dtad_kind = kind;
9313 	act->dtad_ntuple = ntuple;
9314 	act->dtad_uarg = uarg;
9315 	act->dtad_arg = arg;
9316 	act->dtad_refcnt = 1;
9317 
9318 	return (act);
9319 }
9320 
9321 static void
9322 dtrace_actdesc_hold(dtrace_actdesc_t *act)
9323 {
9324 	ASSERT(act->dtad_refcnt >= 1);
9325 	act->dtad_refcnt++;
9326 }
9327 
9328 static void
9329 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9330 {
9331 	dtrace_actkind_t kind = act->dtad_kind;
9332 	dtrace_difo_t *dp;
9333 
9334 	ASSERT(act->dtad_refcnt >= 1);
9335 
9336 	if (--act->dtad_refcnt != 0)
9337 		return;
9338 
9339 	if ((dp = act->dtad_difo) != NULL)
9340 		dtrace_difo_release(dp, vstate);
9341 
9342 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
9343 		char *str = (char *)(uintptr_t)act->dtad_arg;
9344 
9345 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
9346 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9347 
9348 		if (str != NULL)
9349 			kmem_free(str, strlen(str) + 1);
9350 	}
9351 
9352 	kmem_free(act, sizeof (dtrace_actdesc_t));
9353 }
9354 
9355 /*
9356  * DTrace ECB Functions
9357  */
9358 static dtrace_ecb_t *
9359 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9360 {
9361 	dtrace_ecb_t *ecb;
9362 	dtrace_epid_t epid;
9363 
9364 	ASSERT(MUTEX_HELD(&dtrace_lock));
9365 
9366 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9367 	ecb->dte_predicate = NULL;
9368 	ecb->dte_probe = probe;
9369 
9370 	/*
9371 	 * The default size is the size of the default action: recording
9372 	 * the epid.
9373 	 */
9374 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
9375 	ecb->dte_alignment = sizeof (dtrace_epid_t);
9376 
9377 	epid = state->dts_epid++;
9378 
9379 	if (epid - 1 >= state->dts_necbs) {
9380 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9381 		int necbs = state->dts_necbs << 1;
9382 
9383 		ASSERT(epid == state->dts_necbs + 1);
9384 
9385 		if (necbs == 0) {
9386 			ASSERT(oecbs == NULL);
9387 			necbs = 1;
9388 		}
9389 
9390 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9391 
9392 		if (oecbs != NULL)
9393 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9394 
9395 		dtrace_membar_producer();
9396 		state->dts_ecbs = ecbs;
9397 
9398 		if (oecbs != NULL) {
9399 			/*
9400 			 * If this state is active, we must dtrace_sync()
9401 			 * before we can free the old dts_ecbs array:  we're
9402 			 * coming in hot, and there may be active ring
9403 			 * buffer processing (which indexes into the dts_ecbs
9404 			 * array) on another CPU.
9405 			 */
9406 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9407 				dtrace_sync();
9408 
9409 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9410 		}
9411 
9412 		dtrace_membar_producer();
9413 		state->dts_necbs = necbs;
9414 	}
9415 
9416 	ecb->dte_state = state;
9417 
9418 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
9419 	dtrace_membar_producer();
9420 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
9421 
9422 	return (ecb);
9423 }
9424 
9425 static int
9426 dtrace_ecb_enable(dtrace_ecb_t *ecb)
9427 {
9428 	dtrace_probe_t *probe = ecb->dte_probe;
9429 
9430 	ASSERT(MUTEX_HELD(&cpu_lock));
9431 	ASSERT(MUTEX_HELD(&dtrace_lock));
9432 	ASSERT(ecb->dte_next == NULL);
9433 
9434 	if (probe == NULL) {
9435 		/*
9436 		 * This is the NULL probe -- there's nothing to do.
9437 		 */
9438 		return (0);
9439 	}
9440 
9441 	if (probe->dtpr_ecb == NULL) {
9442 		dtrace_provider_t *prov = probe->dtpr_provider;
9443 
9444 		/*
9445 		 * We're the first ECB on this probe.
9446 		 */
9447 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9448 
9449 		if (ecb->dte_predicate != NULL)
9450 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9451 
9452 		return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9453 		    probe->dtpr_id, probe->dtpr_arg));
9454 	} else {
9455 		/*
9456 		 * This probe is already active.  Swing the last pointer to
9457 		 * point to the new ECB, and issue a dtrace_sync() to assure
9458 		 * that all CPUs have seen the change.
9459 		 */
9460 		ASSERT(probe->dtpr_ecb_last != NULL);
9461 		probe->dtpr_ecb_last->dte_next = ecb;
9462 		probe->dtpr_ecb_last = ecb;
9463 		probe->dtpr_predcache = 0;
9464 
9465 		dtrace_sync();
9466 		return (0);
9467 	}
9468 }
9469 
9470 static void
9471 dtrace_ecb_resize(dtrace_ecb_t *ecb)
9472 {
9473 	uint32_t maxalign = sizeof (dtrace_epid_t);
9474 	uint32_t align = sizeof (uint8_t), offs, diff;
9475 	dtrace_action_t *act;
9476 	int wastuple = 0;
9477 	uint32_t aggbase = UINT32_MAX;
9478 	dtrace_state_t *state = ecb->dte_state;
9479 
9480 	/*
9481 	 * If we record anything, we always record the epid.  (And we always
9482 	 * record it first.)
9483 	 */
9484 	offs = sizeof (dtrace_epid_t);
9485 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
9486 
9487 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9488 		dtrace_recdesc_t *rec = &act->dta_rec;
9489 
9490 		if ((align = rec->dtrd_alignment) > maxalign)
9491 			maxalign = align;
9492 
9493 		if (!wastuple && act->dta_intuple) {
9494 			/*
9495 			 * This is the first record in a tuple.  Align the
9496 			 * offset to be at offset 4 in an 8-byte aligned
9497 			 * block.
9498 			 */
9499 			diff = offs + sizeof (dtrace_aggid_t);
9500 
9501 			if (diff = (diff & (sizeof (uint64_t) - 1)))
9502 				offs += sizeof (uint64_t) - diff;
9503 
9504 			aggbase = offs - sizeof (dtrace_aggid_t);
9505 			ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
9506 		}
9507 
9508 		/*LINTED*/
9509 		if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
9510 			/*
9511 			 * The current offset is not properly aligned; align it.
9512 			 */
9513 			offs += align - diff;
9514 		}
9515 
9516 		rec->dtrd_offset = offs;
9517 
9518 		if (offs + rec->dtrd_size > ecb->dte_needed) {
9519 			ecb->dte_needed = offs + rec->dtrd_size;
9520 
9521 			if (ecb->dte_needed > state->dts_needed)
9522 				state->dts_needed = ecb->dte_needed;
9523 		}
9524 
9525 		if (DTRACEACT_ISAGG(act->dta_kind)) {
9526 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9527 			dtrace_action_t *first = agg->dtag_first, *prev;
9528 
9529 			ASSERT(rec->dtrd_size != 0 && first != NULL);
9530 			ASSERT(wastuple);
9531 			ASSERT(aggbase != UINT32_MAX);
9532 
9533 			agg->dtag_base = aggbase;
9534 
9535 			while ((prev = first->dta_prev) != NULL &&
9536 			    DTRACEACT_ISAGG(prev->dta_kind)) {
9537 				agg = (dtrace_aggregation_t *)prev;
9538 				first = agg->dtag_first;
9539 			}
9540 
9541 			if (prev != NULL) {
9542 				offs = prev->dta_rec.dtrd_offset +
9543 				    prev->dta_rec.dtrd_size;
9544 			} else {
9545 				offs = sizeof (dtrace_epid_t);
9546 			}
9547 			wastuple = 0;
9548 		} else {
9549 			if (!act->dta_intuple)
9550 				ecb->dte_size = offs + rec->dtrd_size;
9551 
9552 			offs += rec->dtrd_size;
9553 		}
9554 
9555 		wastuple = act->dta_intuple;
9556 	}
9557 
9558 	if ((act = ecb->dte_action) != NULL &&
9559 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9560 	    ecb->dte_size == sizeof (dtrace_epid_t)) {
9561 		/*
9562 		 * If the size is still sizeof (dtrace_epid_t), then all
9563 		 * actions store no data; set the size to 0.
9564 		 */
9565 		ecb->dte_alignment = maxalign;
9566 		ecb->dte_size = 0;
9567 
9568 		/*
9569 		 * If the needed space is still sizeof (dtrace_epid_t), then
9570 		 * all actions need no additional space; set the needed
9571 		 * size to 0.
9572 		 */
9573 		if (ecb->dte_needed == sizeof (dtrace_epid_t))
9574 			ecb->dte_needed = 0;
9575 
9576 		return;
9577 	}
9578 
9579 	/*
9580 	 * Set our alignment, and make sure that the dte_size and dte_needed
9581 	 * are aligned to the size of an EPID.
9582 	 */
9583 	ecb->dte_alignment = maxalign;
9584 	ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
9585 	    ~(sizeof (dtrace_epid_t) - 1);
9586 	ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
9587 	    ~(sizeof (dtrace_epid_t) - 1);
9588 	ASSERT(ecb->dte_size <= ecb->dte_needed);
9589 }
9590 
9591 static dtrace_action_t *
9592 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9593 {
9594 	dtrace_aggregation_t *agg;
9595 	size_t size = sizeof (uint64_t);
9596 	int ntuple = desc->dtad_ntuple;
9597 	dtrace_action_t *act;
9598 	dtrace_recdesc_t *frec;
9599 	dtrace_aggid_t aggid;
9600 	dtrace_state_t *state = ecb->dte_state;
9601 
9602 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
9603 	agg->dtag_ecb = ecb;
9604 
9605 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
9606 
9607 	switch (desc->dtad_kind) {
9608 	case DTRACEAGG_MIN:
9609 		agg->dtag_initial = INT64_MAX;
9610 		agg->dtag_aggregate = dtrace_aggregate_min;
9611 		break;
9612 
9613 	case DTRACEAGG_MAX:
9614 		agg->dtag_initial = INT64_MIN;
9615 		agg->dtag_aggregate = dtrace_aggregate_max;
9616 		break;
9617 
9618 	case DTRACEAGG_COUNT:
9619 		agg->dtag_aggregate = dtrace_aggregate_count;
9620 		break;
9621 
9622 	case DTRACEAGG_QUANTIZE:
9623 		agg->dtag_aggregate = dtrace_aggregate_quantize;
9624 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
9625 		    sizeof (uint64_t);
9626 		break;
9627 
9628 	case DTRACEAGG_LQUANTIZE: {
9629 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
9630 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
9631 
9632 		agg->dtag_initial = desc->dtad_arg;
9633 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
9634 
9635 		if (step == 0 || levels == 0)
9636 			goto err;
9637 
9638 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
9639 		break;
9640 	}
9641 
9642 	case DTRACEAGG_LLQUANTIZE: {
9643 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
9644 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
9645 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
9646 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
9647 		int64_t v;
9648 
9649 		agg->dtag_initial = desc->dtad_arg;
9650 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
9651 
9652 		if (factor < 2 || low >= high || nsteps < factor)
9653 			goto err;
9654 
9655 		/*
9656 		 * Now check that the number of steps evenly divides a power
9657 		 * of the factor.  (This assures both integer bucket size and
9658 		 * linearity within each magnitude.)
9659 		 */
9660 		for (v = factor; v < nsteps; v *= factor)
9661 			continue;
9662 
9663 		if ((v % nsteps) || (nsteps % factor))
9664 			goto err;
9665 
9666 		size = (dtrace_aggregate_llquantize_bucket(factor,
9667 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
9668 		break;
9669 	}
9670 
9671 	case DTRACEAGG_AVG:
9672 		agg->dtag_aggregate = dtrace_aggregate_avg;
9673 		size = sizeof (uint64_t) * 2;
9674 		break;
9675 
9676 	case DTRACEAGG_STDDEV:
9677 		agg->dtag_aggregate = dtrace_aggregate_stddev;
9678 		size = sizeof (uint64_t) * 4;
9679 		break;
9680 
9681 	case DTRACEAGG_SUM:
9682 		agg->dtag_aggregate = dtrace_aggregate_sum;
9683 		break;
9684 
9685 	default:
9686 		goto err;
9687 	}
9688 
9689 	agg->dtag_action.dta_rec.dtrd_size = size;
9690 
9691 	if (ntuple == 0)
9692 		goto err;
9693 
9694 	/*
9695 	 * We must make sure that we have enough actions for the n-tuple.
9696 	 */
9697 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
9698 		if (DTRACEACT_ISAGG(act->dta_kind))
9699 			break;
9700 
9701 		if (--ntuple == 0) {
9702 			/*
9703 			 * This is the action with which our n-tuple begins.
9704 			 */
9705 			agg->dtag_first = act;
9706 			goto success;
9707 		}
9708 	}
9709 
9710 	/*
9711 	 * This n-tuple is short by ntuple elements.  Return failure.
9712 	 */
9713 	ASSERT(ntuple != 0);
9714 err:
9715 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9716 	return (NULL);
9717 
9718 success:
9719 	/*
9720 	 * If the last action in the tuple has a size of zero, it's actually
9721 	 * an expression argument for the aggregating action.
9722 	 */
9723 	ASSERT(ecb->dte_action_last != NULL);
9724 	act = ecb->dte_action_last;
9725 
9726 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
9727 		ASSERT(act->dta_difo != NULL);
9728 
9729 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
9730 			agg->dtag_hasarg = 1;
9731 	}
9732 
9733 	/*
9734 	 * We need to allocate an id for this aggregation.
9735 	 */
9736 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
9737 	    VM_BESTFIT | VM_SLEEP);
9738 
9739 	if (aggid - 1 >= state->dts_naggregations) {
9740 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
9741 		dtrace_aggregation_t **aggs;
9742 		int naggs = state->dts_naggregations << 1;
9743 		int onaggs = state->dts_naggregations;
9744 
9745 		ASSERT(aggid == state->dts_naggregations + 1);
9746 
9747 		if (naggs == 0) {
9748 			ASSERT(oaggs == NULL);
9749 			naggs = 1;
9750 		}
9751 
9752 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
9753 
9754 		if (oaggs != NULL) {
9755 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
9756 			kmem_free(oaggs, onaggs * sizeof (*aggs));
9757 		}
9758 
9759 		state->dts_aggregations = aggs;
9760 		state->dts_naggregations = naggs;
9761 	}
9762 
9763 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
9764 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
9765 
9766 	frec = &agg->dtag_first->dta_rec;
9767 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
9768 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
9769 
9770 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
9771 		ASSERT(!act->dta_intuple);
9772 		act->dta_intuple = 1;
9773 	}
9774 
9775 	return (&agg->dtag_action);
9776 }
9777 
9778 static void
9779 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
9780 {
9781 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9782 	dtrace_state_t *state = ecb->dte_state;
9783 	dtrace_aggid_t aggid = agg->dtag_id;
9784 
9785 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
9786 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
9787 
9788 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
9789 	state->dts_aggregations[aggid - 1] = NULL;
9790 
9791 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9792 }
9793 
9794 static int
9795 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9796 {
9797 	dtrace_action_t *action, *last;
9798 	dtrace_difo_t *dp = desc->dtad_difo;
9799 	uint32_t size = 0, align = sizeof (uint8_t), mask;
9800 	uint16_t format = 0;
9801 	dtrace_recdesc_t *rec;
9802 	dtrace_state_t *state = ecb->dte_state;
9803 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
9804 	uint64_t arg = desc->dtad_arg;
9805 
9806 	ASSERT(MUTEX_HELD(&dtrace_lock));
9807 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
9808 
9809 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
9810 		/*
9811 		 * If this is an aggregating action, there must be neither
9812 		 * a speculate nor a commit on the action chain.
9813 		 */
9814 		dtrace_action_t *act;
9815 
9816 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9817 			if (act->dta_kind == DTRACEACT_COMMIT)
9818 				return (EINVAL);
9819 
9820 			if (act->dta_kind == DTRACEACT_SPECULATE)
9821 				return (EINVAL);
9822 		}
9823 
9824 		action = dtrace_ecb_aggregation_create(ecb, desc);
9825 
9826 		if (action == NULL)
9827 			return (EINVAL);
9828 	} else {
9829 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
9830 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
9831 		    dp != NULL && dp->dtdo_destructive)) {
9832 			state->dts_destructive = 1;
9833 		}
9834 
9835 		switch (desc->dtad_kind) {
9836 		case DTRACEACT_PRINTF:
9837 		case DTRACEACT_PRINTA:
9838 		case DTRACEACT_SYSTEM:
9839 		case DTRACEACT_FREOPEN:
9840 		case DTRACEACT_DIFEXPR:
9841 			/*
9842 			 * We know that our arg is a string -- turn it into a
9843 			 * format.
9844 			 */
9845 			if (arg == NULL) {
9846 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
9847 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
9848 				format = 0;
9849 			} else {
9850 				ASSERT(arg != NULL);
9851 				ASSERT(arg > KERNELBASE);
9852 				format = dtrace_format_add(state,
9853 				    (char *)(uintptr_t)arg);
9854 			}
9855 
9856 			/*FALLTHROUGH*/
9857 		case DTRACEACT_LIBACT:
9858 		case DTRACEACT_TRACEMEM:
9859 		case DTRACEACT_TRACEMEM_DYNSIZE:
9860 			if (dp == NULL)
9861 				return (EINVAL);
9862 
9863 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
9864 				break;
9865 
9866 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
9867 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9868 					return (EINVAL);
9869 
9870 				size = opt[DTRACEOPT_STRSIZE];
9871 			}
9872 
9873 			break;
9874 
9875 		case DTRACEACT_STACK:
9876 			if ((nframes = arg) == 0) {
9877 				nframes = opt[DTRACEOPT_STACKFRAMES];
9878 				ASSERT(nframes > 0);
9879 				arg = nframes;
9880 			}
9881 
9882 			size = nframes * sizeof (pc_t);
9883 			break;
9884 
9885 		case DTRACEACT_JSTACK:
9886 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
9887 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
9888 
9889 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
9890 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
9891 
9892 			arg = DTRACE_USTACK_ARG(nframes, strsize);
9893 
9894 			/*FALLTHROUGH*/
9895 		case DTRACEACT_USTACK:
9896 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
9897 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
9898 				strsize = DTRACE_USTACK_STRSIZE(arg);
9899 				nframes = opt[DTRACEOPT_USTACKFRAMES];
9900 				ASSERT(nframes > 0);
9901 				arg = DTRACE_USTACK_ARG(nframes, strsize);
9902 			}
9903 
9904 			/*
9905 			 * Save a slot for the pid.
9906 			 */
9907 			size = (nframes + 1) * sizeof (uint64_t);
9908 			size += DTRACE_USTACK_STRSIZE(arg);
9909 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
9910 
9911 			break;
9912 
9913 		case DTRACEACT_SYM:
9914 		case DTRACEACT_MOD:
9915 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
9916 			    sizeof (uint64_t)) ||
9917 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9918 				return (EINVAL);
9919 			break;
9920 
9921 		case DTRACEACT_USYM:
9922 		case DTRACEACT_UMOD:
9923 		case DTRACEACT_UADDR:
9924 			if (dp == NULL ||
9925 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
9926 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9927 				return (EINVAL);
9928 
9929 			/*
9930 			 * We have a slot for the pid, plus a slot for the
9931 			 * argument.  To keep things simple (aligned with
9932 			 * bitness-neutral sizing), we store each as a 64-bit
9933 			 * quantity.
9934 			 */
9935 			size = 2 * sizeof (uint64_t);
9936 			break;
9937 
9938 		case DTRACEACT_STOP:
9939 		case DTRACEACT_BREAKPOINT:
9940 		case DTRACEACT_PANIC:
9941 			break;
9942 
9943 		case DTRACEACT_CHILL:
9944 		case DTRACEACT_DISCARD:
9945 		case DTRACEACT_RAISE:
9946 			if (dp == NULL)
9947 				return (EINVAL);
9948 			break;
9949 
9950 		case DTRACEACT_EXIT:
9951 			if (dp == NULL ||
9952 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
9953 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9954 				return (EINVAL);
9955 			break;
9956 
9957 		case DTRACEACT_SPECULATE:
9958 			if (ecb->dte_size > sizeof (dtrace_epid_t))
9959 				return (EINVAL);
9960 
9961 			if (dp == NULL)
9962 				return (EINVAL);
9963 
9964 			state->dts_speculates = 1;
9965 			break;
9966 
9967 		case DTRACEACT_COMMIT: {
9968 			dtrace_action_t *act = ecb->dte_action;
9969 
9970 			for (; act != NULL; act = act->dta_next) {
9971 				if (act->dta_kind == DTRACEACT_COMMIT)
9972 					return (EINVAL);
9973 			}
9974 
9975 			if (dp == NULL)
9976 				return (EINVAL);
9977 			break;
9978 		}
9979 
9980 		default:
9981 			return (EINVAL);
9982 		}
9983 
9984 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
9985 			/*
9986 			 * If this is a data-storing action or a speculate,
9987 			 * we must be sure that there isn't a commit on the
9988 			 * action chain.
9989 			 */
9990 			dtrace_action_t *act = ecb->dte_action;
9991 
9992 			for (; act != NULL; act = act->dta_next) {
9993 				if (act->dta_kind == DTRACEACT_COMMIT)
9994 					return (EINVAL);
9995 			}
9996 		}
9997 
9998 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
9999 		action->dta_rec.dtrd_size = size;
10000 	}
10001 
10002 	action->dta_refcnt = 1;
10003 	rec = &action->dta_rec;
10004 	size = rec->dtrd_size;
10005 
10006 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
10007 		if (!(size & mask)) {
10008 			align = mask + 1;
10009 			break;
10010 		}
10011 	}
10012 
10013 	action->dta_kind = desc->dtad_kind;
10014 
10015 	if ((action->dta_difo = dp) != NULL)
10016 		dtrace_difo_hold(dp);
10017 
10018 	rec->dtrd_action = action->dta_kind;
10019 	rec->dtrd_arg = arg;
10020 	rec->dtrd_uarg = desc->dtad_uarg;
10021 	rec->dtrd_alignment = (uint16_t)align;
10022 	rec->dtrd_format = format;
10023 
10024 	if ((last = ecb->dte_action_last) != NULL) {
10025 		ASSERT(ecb->dte_action != NULL);
10026 		action->dta_prev = last;
10027 		last->dta_next = action;
10028 	} else {
10029 		ASSERT(ecb->dte_action == NULL);
10030 		ecb->dte_action = action;
10031 	}
10032 
10033 	ecb->dte_action_last = action;
10034 
10035 	return (0);
10036 }
10037 
10038 static void
10039 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
10040 {
10041 	dtrace_action_t *act = ecb->dte_action, *next;
10042 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
10043 	dtrace_difo_t *dp;
10044 	uint16_t format;
10045 
10046 	if (act != NULL && act->dta_refcnt > 1) {
10047 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
10048 		act->dta_refcnt--;
10049 	} else {
10050 		for (; act != NULL; act = next) {
10051 			next = act->dta_next;
10052 			ASSERT(next != NULL || act == ecb->dte_action_last);
10053 			ASSERT(act->dta_refcnt == 1);
10054 
10055 			if ((format = act->dta_rec.dtrd_format) != 0)
10056 				dtrace_format_remove(ecb->dte_state, format);
10057 
10058 			if ((dp = act->dta_difo) != NULL)
10059 				dtrace_difo_release(dp, vstate);
10060 
10061 			if (DTRACEACT_ISAGG(act->dta_kind)) {
10062 				dtrace_ecb_aggregation_destroy(ecb, act);
10063 			} else {
10064 				kmem_free(act, sizeof (dtrace_action_t));
10065 			}
10066 		}
10067 	}
10068 
10069 	ecb->dte_action = NULL;
10070 	ecb->dte_action_last = NULL;
10071 	ecb->dte_size = sizeof (dtrace_epid_t);
10072 }
10073 
10074 static void
10075 dtrace_ecb_disable(dtrace_ecb_t *ecb)
10076 {
10077 	/*
10078 	 * We disable the ECB by removing it from its probe.
10079 	 */
10080 	dtrace_ecb_t *pecb, *prev = NULL;
10081 	dtrace_probe_t *probe = ecb->dte_probe;
10082 
10083 	ASSERT(MUTEX_HELD(&dtrace_lock));
10084 
10085 	if (probe == NULL) {
10086 		/*
10087 		 * This is the NULL probe; there is nothing to disable.
10088 		 */
10089 		return;
10090 	}
10091 
10092 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
10093 		if (pecb == ecb)
10094 			break;
10095 		prev = pecb;
10096 	}
10097 
10098 	ASSERT(pecb != NULL);
10099 
10100 	if (prev == NULL) {
10101 		probe->dtpr_ecb = ecb->dte_next;
10102 	} else {
10103 		prev->dte_next = ecb->dte_next;
10104 	}
10105 
10106 	if (ecb == probe->dtpr_ecb_last) {
10107 		ASSERT(ecb->dte_next == NULL);
10108 		probe->dtpr_ecb_last = prev;
10109 	}
10110 
10111 	/*
10112 	 * The ECB has been disconnected from the probe; now sync to assure
10113 	 * that all CPUs have seen the change before returning.
10114 	 */
10115 	dtrace_sync();
10116 
10117 	if (probe->dtpr_ecb == NULL) {
10118 		/*
10119 		 * That was the last ECB on the probe; clear the predicate
10120 		 * cache ID for the probe, disable it and sync one more time
10121 		 * to assure that we'll never hit it again.
10122 		 */
10123 		dtrace_provider_t *prov = probe->dtpr_provider;
10124 
10125 		ASSERT(ecb->dte_next == NULL);
10126 		ASSERT(probe->dtpr_ecb_last == NULL);
10127 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
10128 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
10129 		    probe->dtpr_id, probe->dtpr_arg);
10130 		dtrace_sync();
10131 	} else {
10132 		/*
10133 		 * There is at least one ECB remaining on the probe.  If there
10134 		 * is _exactly_ one, set the probe's predicate cache ID to be
10135 		 * the predicate cache ID of the remaining ECB.
10136 		 */
10137 		ASSERT(probe->dtpr_ecb_last != NULL);
10138 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
10139 
10140 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
10141 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
10142 
10143 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
10144 
10145 			if (p != NULL)
10146 				probe->dtpr_predcache = p->dtp_cacheid;
10147 		}
10148 
10149 		ecb->dte_next = NULL;
10150 	}
10151 }
10152 
10153 static void
10154 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
10155 {
10156 	dtrace_state_t *state = ecb->dte_state;
10157 	dtrace_vstate_t *vstate = &state->dts_vstate;
10158 	dtrace_predicate_t *pred;
10159 	dtrace_epid_t epid = ecb->dte_epid;
10160 
10161 	ASSERT(MUTEX_HELD(&dtrace_lock));
10162 	ASSERT(ecb->dte_next == NULL);
10163 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
10164 
10165 	if ((pred = ecb->dte_predicate) != NULL)
10166 		dtrace_predicate_release(pred, vstate);
10167 
10168 	dtrace_ecb_action_remove(ecb);
10169 
10170 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
10171 	state->dts_ecbs[epid - 1] = NULL;
10172 
10173 	kmem_free(ecb, sizeof (dtrace_ecb_t));
10174 }
10175 
10176 static dtrace_ecb_t *
10177 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
10178     dtrace_enabling_t *enab)
10179 {
10180 	dtrace_ecb_t *ecb;
10181 	dtrace_predicate_t *pred;
10182 	dtrace_actdesc_t *act;
10183 	dtrace_provider_t *prov;
10184 	dtrace_ecbdesc_t *desc = enab->dten_current;
10185 
10186 	ASSERT(MUTEX_HELD(&dtrace_lock));
10187 	ASSERT(state != NULL);
10188 
10189 	ecb = dtrace_ecb_add(state, probe);
10190 	ecb->dte_uarg = desc->dted_uarg;
10191 
10192 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
10193 		dtrace_predicate_hold(pred);
10194 		ecb->dte_predicate = pred;
10195 	}
10196 
10197 	if (probe != NULL) {
10198 		/*
10199 		 * If the provider shows more leg than the consumer is old
10200 		 * enough to see, we need to enable the appropriate implicit
10201 		 * predicate bits to prevent the ecb from activating at
10202 		 * revealing times.
10203 		 *
10204 		 * Providers specifying DTRACE_PRIV_USER at register time
10205 		 * are stating that they need the /proc-style privilege
10206 		 * model to be enforced, and this is what DTRACE_COND_OWNER
10207 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
10208 		 */
10209 		prov = probe->dtpr_provider;
10210 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
10211 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10212 			ecb->dte_cond |= DTRACE_COND_OWNER;
10213 
10214 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
10215 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
10216 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
10217 
10218 		/*
10219 		 * If the provider shows us kernel innards and the user
10220 		 * is lacking sufficient privilege, enable the
10221 		 * DTRACE_COND_USERMODE implicit predicate.
10222 		 */
10223 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
10224 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
10225 			ecb->dte_cond |= DTRACE_COND_USERMODE;
10226 	}
10227 
10228 	if (dtrace_ecb_create_cache != NULL) {
10229 		/*
10230 		 * If we have a cached ecb, we'll use its action list instead
10231 		 * of creating our own (saving both time and space).
10232 		 */
10233 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
10234 		dtrace_action_t *act = cached->dte_action;
10235 
10236 		if (act != NULL) {
10237 			ASSERT(act->dta_refcnt > 0);
10238 			act->dta_refcnt++;
10239 			ecb->dte_action = act;
10240 			ecb->dte_action_last = cached->dte_action_last;
10241 			ecb->dte_needed = cached->dte_needed;
10242 			ecb->dte_size = cached->dte_size;
10243 			ecb->dte_alignment = cached->dte_alignment;
10244 		}
10245 
10246 		return (ecb);
10247 	}
10248 
10249 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
10250 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
10251 			dtrace_ecb_destroy(ecb);
10252 			return (NULL);
10253 		}
10254 	}
10255 
10256 	dtrace_ecb_resize(ecb);
10257 
10258 	return (dtrace_ecb_create_cache = ecb);
10259 }
10260 
10261 static int
10262 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
10263 {
10264 	dtrace_ecb_t *ecb;
10265 	dtrace_enabling_t *enab = arg;
10266 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
10267 
10268 	ASSERT(state != NULL);
10269 
10270 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
10271 		/*
10272 		 * This probe was created in a generation for which this
10273 		 * enabling has previously created ECBs; we don't want to
10274 		 * enable it again, so just kick out.
10275 		 */
10276 		return (DTRACE_MATCH_NEXT);
10277 	}
10278 
10279 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
10280 		return (DTRACE_MATCH_DONE);
10281 
10282 	if (dtrace_ecb_enable(ecb) < 0)
10283 		return (DTRACE_MATCH_FAIL);
10284 
10285 	return (DTRACE_MATCH_NEXT);
10286 }
10287 
10288 static dtrace_ecb_t *
10289 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
10290 {
10291 	dtrace_ecb_t *ecb;
10292 
10293 	ASSERT(MUTEX_HELD(&dtrace_lock));
10294 
10295 	if (id == 0 || id > state->dts_necbs)
10296 		return (NULL);
10297 
10298 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
10299 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
10300 
10301 	return (state->dts_ecbs[id - 1]);
10302 }
10303 
10304 static dtrace_aggregation_t *
10305 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
10306 {
10307 	dtrace_aggregation_t *agg;
10308 
10309 	ASSERT(MUTEX_HELD(&dtrace_lock));
10310 
10311 	if (id == 0 || id > state->dts_naggregations)
10312 		return (NULL);
10313 
10314 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
10315 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
10316 	    agg->dtag_id == id);
10317 
10318 	return (state->dts_aggregations[id - 1]);
10319 }
10320 
10321 /*
10322  * DTrace Buffer Functions
10323  *
10324  * The following functions manipulate DTrace buffers.  Most of these functions
10325  * are called in the context of establishing or processing consumer state;
10326  * exceptions are explicitly noted.
10327  */
10328 
10329 /*
10330  * Note:  called from cross call context.  This function switches the two
10331  * buffers on a given CPU.  The atomicity of this operation is assured by
10332  * disabling interrupts while the actual switch takes place; the disabling of
10333  * interrupts serializes the execution with any execution of dtrace_probe() on
10334  * the same CPU.
10335  */
10336 static void
10337 dtrace_buffer_switch(dtrace_buffer_t *buf)
10338 {
10339 	caddr_t tomax = buf->dtb_tomax;
10340 	caddr_t xamot = buf->dtb_xamot;
10341 	dtrace_icookie_t cookie;
10342 	hrtime_t now = dtrace_gethrtime();
10343 
10344 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10345 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10346 
10347 	cookie = dtrace_interrupt_disable();
10348 	buf->dtb_tomax = xamot;
10349 	buf->dtb_xamot = tomax;
10350 	buf->dtb_xamot_drops = buf->dtb_drops;
10351 	buf->dtb_xamot_offset = buf->dtb_offset;
10352 	buf->dtb_xamot_errors = buf->dtb_errors;
10353 	buf->dtb_xamot_flags = buf->dtb_flags;
10354 	buf->dtb_offset = 0;
10355 	buf->dtb_drops = 0;
10356 	buf->dtb_errors = 0;
10357 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10358 	buf->dtb_interval = now - buf->dtb_switched;
10359 	buf->dtb_switched = now;
10360 	dtrace_interrupt_enable(cookie);
10361 }
10362 
10363 /*
10364  * Note:  called from cross call context.  This function activates a buffer
10365  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
10366  * is guaranteed by the disabling of interrupts.
10367  */
10368 static void
10369 dtrace_buffer_activate(dtrace_state_t *state)
10370 {
10371 	dtrace_buffer_t *buf;
10372 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
10373 
10374 	buf = &state->dts_buffer[CPU->cpu_id];
10375 
10376 	if (buf->dtb_tomax != NULL) {
10377 		/*
10378 		 * We might like to assert that the buffer is marked inactive,
10379 		 * but this isn't necessarily true:  the buffer for the CPU
10380 		 * that processes the BEGIN probe has its buffer activated
10381 		 * manually.  In this case, we take the (harmless) action
10382 		 * re-clearing the bit INACTIVE bit.
10383 		 */
10384 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10385 	}
10386 
10387 	dtrace_interrupt_enable(cookie);
10388 }
10389 
10390 static int
10391 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
10392     processorid_t cpu, int *factor)
10393 {
10394 	cpu_t *cp;
10395 	dtrace_buffer_t *buf;
10396 	int allocated = 0, desired = 0;
10397 
10398 	ASSERT(MUTEX_HELD(&cpu_lock));
10399 	ASSERT(MUTEX_HELD(&dtrace_lock));
10400 
10401 	*factor = 1;
10402 
10403 	if (size > dtrace_nonroot_maxsize &&
10404 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
10405 		return (EFBIG);
10406 
10407 	cp = cpu_list;
10408 
10409 	do {
10410 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10411 			continue;
10412 
10413 		buf = &bufs[cp->cpu_id];
10414 
10415 		/*
10416 		 * If there is already a buffer allocated for this CPU, it
10417 		 * is only possible that this is a DR event.  In this case,
10418 		 * the buffer size must match our specified size.
10419 		 */
10420 		if (buf->dtb_tomax != NULL) {
10421 			ASSERT(buf->dtb_size == size);
10422 			continue;
10423 		}
10424 
10425 		ASSERT(buf->dtb_xamot == NULL);
10426 
10427 		if ((buf->dtb_tomax = kmem_zalloc(size,
10428 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10429 			goto err;
10430 
10431 		buf->dtb_size = size;
10432 		buf->dtb_flags = flags;
10433 		buf->dtb_offset = 0;
10434 		buf->dtb_drops = 0;
10435 
10436 		if (flags & DTRACEBUF_NOSWITCH)
10437 			continue;
10438 
10439 		if ((buf->dtb_xamot = kmem_zalloc(size,
10440 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
10441 			goto err;
10442 	} while ((cp = cp->cpu_next) != cpu_list);
10443 
10444 	return (0);
10445 
10446 err:
10447 	cp = cpu_list;
10448 
10449 	do {
10450 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10451 			continue;
10452 
10453 		buf = &bufs[cp->cpu_id];
10454 		desired += 2;
10455 
10456 		if (buf->dtb_xamot != NULL) {
10457 			ASSERT(buf->dtb_tomax != NULL);
10458 			ASSERT(buf->dtb_size == size);
10459 			kmem_free(buf->dtb_xamot, size);
10460 			allocated++;
10461 		}
10462 
10463 		if (buf->dtb_tomax != NULL) {
10464 			ASSERT(buf->dtb_size == size);
10465 			kmem_free(buf->dtb_tomax, size);
10466 			allocated++;
10467 		}
10468 
10469 		buf->dtb_tomax = NULL;
10470 		buf->dtb_xamot = NULL;
10471 		buf->dtb_size = 0;
10472 	} while ((cp = cp->cpu_next) != cpu_list);
10473 
10474 	*factor = desired / (allocated > 0 ? allocated : 1);
10475 
10476 	return (ENOMEM);
10477 }
10478 
10479 /*
10480  * Note:  called from probe context.  This function just increments the drop
10481  * count on a buffer.  It has been made a function to allow for the
10482  * possibility of understanding the source of mysterious drop counts.  (A
10483  * problem for which one may be particularly disappointed that DTrace cannot
10484  * be used to understand DTrace.)
10485  */
10486 static void
10487 dtrace_buffer_drop(dtrace_buffer_t *buf)
10488 {
10489 	buf->dtb_drops++;
10490 }
10491 
10492 /*
10493  * Note:  called from probe context.  This function is called to reserve space
10494  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
10495  * mstate.  Returns the new offset in the buffer, or a negative value if an
10496  * error has occurred.
10497  */
10498 static intptr_t
10499 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
10500     dtrace_state_t *state, dtrace_mstate_t *mstate)
10501 {
10502 	intptr_t offs = buf->dtb_offset, soffs;
10503 	intptr_t woffs;
10504 	caddr_t tomax;
10505 	size_t total;
10506 
10507 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
10508 		return (-1);
10509 
10510 	if ((tomax = buf->dtb_tomax) == NULL) {
10511 		dtrace_buffer_drop(buf);
10512 		return (-1);
10513 	}
10514 
10515 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
10516 		while (offs & (align - 1)) {
10517 			/*
10518 			 * Assert that our alignment is off by a number which
10519 			 * is itself sizeof (uint32_t) aligned.
10520 			 */
10521 			ASSERT(!((align - (offs & (align - 1))) &
10522 			    (sizeof (uint32_t) - 1)));
10523 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10524 			offs += sizeof (uint32_t);
10525 		}
10526 
10527 		if ((soffs = offs + needed) > buf->dtb_size) {
10528 			dtrace_buffer_drop(buf);
10529 			return (-1);
10530 		}
10531 
10532 		if (mstate == NULL)
10533 			return (offs);
10534 
10535 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
10536 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
10537 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10538 
10539 		return (offs);
10540 	}
10541 
10542 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10543 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
10544 		    (buf->dtb_flags & DTRACEBUF_FULL))
10545 			return (-1);
10546 		goto out;
10547 	}
10548 
10549 	total = needed + (offs & (align - 1));
10550 
10551 	/*
10552 	 * For a ring buffer, life is quite a bit more complicated.  Before
10553 	 * we can store any padding, we need to adjust our wrapping offset.
10554 	 * (If we've never before wrapped or we're not about to, no adjustment
10555 	 * is required.)
10556 	 */
10557 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
10558 	    offs + total > buf->dtb_size) {
10559 		woffs = buf->dtb_xamot_offset;
10560 
10561 		if (offs + total > buf->dtb_size) {
10562 			/*
10563 			 * We can't fit in the end of the buffer.  First, a
10564 			 * sanity check that we can fit in the buffer at all.
10565 			 */
10566 			if (total > buf->dtb_size) {
10567 				dtrace_buffer_drop(buf);
10568 				return (-1);
10569 			}
10570 
10571 			/*
10572 			 * We're going to be storing at the top of the buffer,
10573 			 * so now we need to deal with the wrapped offset.  We
10574 			 * only reset our wrapped offset to 0 if it is
10575 			 * currently greater than the current offset.  If it
10576 			 * is less than the current offset, it is because a
10577 			 * previous allocation induced a wrap -- but the
10578 			 * allocation didn't subsequently take the space due
10579 			 * to an error or false predicate evaluation.  In this
10580 			 * case, we'll just leave the wrapped offset alone: if
10581 			 * the wrapped offset hasn't been advanced far enough
10582 			 * for this allocation, it will be adjusted in the
10583 			 * lower loop.
10584 			 */
10585 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
10586 				if (woffs >= offs)
10587 					woffs = 0;
10588 			} else {
10589 				woffs = 0;
10590 			}
10591 
10592 			/*
10593 			 * Now we know that we're going to be storing to the
10594 			 * top of the buffer and that there is room for us
10595 			 * there.  We need to clear the buffer from the current
10596 			 * offset to the end (there may be old gunk there).
10597 			 */
10598 			while (offs < buf->dtb_size)
10599 				tomax[offs++] = 0;
10600 
10601 			/*
10602 			 * We need to set our offset to zero.  And because we
10603 			 * are wrapping, we need to set the bit indicating as
10604 			 * much.  We can also adjust our needed space back
10605 			 * down to the space required by the ECB -- we know
10606 			 * that the top of the buffer is aligned.
10607 			 */
10608 			offs = 0;
10609 			total = needed;
10610 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
10611 		} else {
10612 			/*
10613 			 * There is room for us in the buffer, so we simply
10614 			 * need to check the wrapped offset.
10615 			 */
10616 			if (woffs < offs) {
10617 				/*
10618 				 * The wrapped offset is less than the offset.
10619 				 * This can happen if we allocated buffer space
10620 				 * that induced a wrap, but then we didn't
10621 				 * subsequently take the space due to an error
10622 				 * or false predicate evaluation.  This is
10623 				 * okay; we know that _this_ allocation isn't
10624 				 * going to induce a wrap.  We still can't
10625 				 * reset the wrapped offset to be zero,
10626 				 * however: the space may have been trashed in
10627 				 * the previous failed probe attempt.  But at
10628 				 * least the wrapped offset doesn't need to
10629 				 * be adjusted at all...
10630 				 */
10631 				goto out;
10632 			}
10633 		}
10634 
10635 		while (offs + total > woffs) {
10636 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
10637 			size_t size;
10638 
10639 			if (epid == DTRACE_EPIDNONE) {
10640 				size = sizeof (uint32_t);
10641 			} else {
10642 				ASSERT(epid <= state->dts_necbs);
10643 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
10644 
10645 				size = state->dts_ecbs[epid - 1]->dte_size;
10646 			}
10647 
10648 			ASSERT(woffs + size <= buf->dtb_size);
10649 			ASSERT(size != 0);
10650 
10651 			if (woffs + size == buf->dtb_size) {
10652 				/*
10653 				 * We've reached the end of the buffer; we want
10654 				 * to set the wrapped offset to 0 and break
10655 				 * out.  However, if the offs is 0, then we're
10656 				 * in a strange edge-condition:  the amount of
10657 				 * space that we want to reserve plus the size
10658 				 * of the record that we're overwriting is
10659 				 * greater than the size of the buffer.  This
10660 				 * is problematic because if we reserve the
10661 				 * space but subsequently don't consume it (due
10662 				 * to a failed predicate or error) the wrapped
10663 				 * offset will be 0 -- yet the EPID at offset 0
10664 				 * will not be committed.  This situation is
10665 				 * relatively easy to deal with:  if we're in
10666 				 * this case, the buffer is indistinguishable
10667 				 * from one that hasn't wrapped; we need only
10668 				 * finish the job by clearing the wrapped bit,
10669 				 * explicitly setting the offset to be 0, and
10670 				 * zero'ing out the old data in the buffer.
10671 				 */
10672 				if (offs == 0) {
10673 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
10674 					buf->dtb_offset = 0;
10675 					woffs = total;
10676 
10677 					while (woffs < buf->dtb_size)
10678 						tomax[woffs++] = 0;
10679 				}
10680 
10681 				woffs = 0;
10682 				break;
10683 			}
10684 
10685 			woffs += size;
10686 		}
10687 
10688 		/*
10689 		 * We have a wrapped offset.  It may be that the wrapped offset
10690 		 * has become zero -- that's okay.
10691 		 */
10692 		buf->dtb_xamot_offset = woffs;
10693 	}
10694 
10695 out:
10696 	/*
10697 	 * Now we can plow the buffer with any necessary padding.
10698 	 */
10699 	while (offs & (align - 1)) {
10700 		/*
10701 		 * Assert that our alignment is off by a number which
10702 		 * is itself sizeof (uint32_t) aligned.
10703 		 */
10704 		ASSERT(!((align - (offs & (align - 1))) &
10705 		    (sizeof (uint32_t) - 1)));
10706 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10707 		offs += sizeof (uint32_t);
10708 	}
10709 
10710 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10711 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
10712 			buf->dtb_flags |= DTRACEBUF_FULL;
10713 			return (-1);
10714 		}
10715 	}
10716 
10717 	if (mstate == NULL)
10718 		return (offs);
10719 
10720 	/*
10721 	 * For ring buffers and fill buffers, the scratch space is always
10722 	 * the inactive buffer.
10723 	 */
10724 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
10725 	mstate->dtms_scratch_size = buf->dtb_size;
10726 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10727 
10728 	return (offs);
10729 }
10730 
10731 static void
10732 dtrace_buffer_polish(dtrace_buffer_t *buf)
10733 {
10734 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
10735 	ASSERT(MUTEX_HELD(&dtrace_lock));
10736 
10737 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
10738 		return;
10739 
10740 	/*
10741 	 * We need to polish the ring buffer.  There are three cases:
10742 	 *
10743 	 * - The first (and presumably most common) is that there is no gap
10744 	 *   between the buffer offset and the wrapped offset.  In this case,
10745 	 *   there is nothing in the buffer that isn't valid data; we can
10746 	 *   mark the buffer as polished and return.
10747 	 *
10748 	 * - The second (less common than the first but still more common
10749 	 *   than the third) is that there is a gap between the buffer offset
10750 	 *   and the wrapped offset, and the wrapped offset is larger than the
10751 	 *   buffer offset.  This can happen because of an alignment issue, or
10752 	 *   can happen because of a call to dtrace_buffer_reserve() that
10753 	 *   didn't subsequently consume the buffer space.  In this case,
10754 	 *   we need to zero the data from the buffer offset to the wrapped
10755 	 *   offset.
10756 	 *
10757 	 * - The third (and least common) is that there is a gap between the
10758 	 *   buffer offset and the wrapped offset, but the wrapped offset is
10759 	 *   _less_ than the buffer offset.  This can only happen because a
10760 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
10761 	 *   was not subsequently consumed.  In this case, we need to zero the
10762 	 *   space from the offset to the end of the buffer _and_ from the
10763 	 *   top of the buffer to the wrapped offset.
10764 	 */
10765 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
10766 		bzero(buf->dtb_tomax + buf->dtb_offset,
10767 		    buf->dtb_xamot_offset - buf->dtb_offset);
10768 	}
10769 
10770 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
10771 		bzero(buf->dtb_tomax + buf->dtb_offset,
10772 		    buf->dtb_size - buf->dtb_offset);
10773 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
10774 	}
10775 }
10776 
10777 /*
10778  * This routine determines if data generated at the specified time has likely
10779  * been entirely consumed at user-level.  This routine is called to determine
10780  * if an ECB on a defunct probe (but for an active enabling) can be safely
10781  * disabled and destroyed.
10782  */
10783 static int
10784 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
10785 {
10786 	int i;
10787 
10788 	for (i = 0; i < NCPU; i++) {
10789 		dtrace_buffer_t *buf = &bufs[i];
10790 
10791 		if (buf->dtb_size == 0)
10792 			continue;
10793 
10794 		if (buf->dtb_flags & DTRACEBUF_RING)
10795 			return (0);
10796 
10797 		if (!buf->dtb_switched && buf->dtb_offset != 0)
10798 			return (0);
10799 
10800 		if (buf->dtb_switched - buf->dtb_interval < when)
10801 			return (0);
10802 	}
10803 
10804 	return (1);
10805 }
10806 
10807 static void
10808 dtrace_buffer_free(dtrace_buffer_t *bufs)
10809 {
10810 	int i;
10811 
10812 	for (i = 0; i < NCPU; i++) {
10813 		dtrace_buffer_t *buf = &bufs[i];
10814 
10815 		if (buf->dtb_tomax == NULL) {
10816 			ASSERT(buf->dtb_xamot == NULL);
10817 			ASSERT(buf->dtb_size == 0);
10818 			continue;
10819 		}
10820 
10821 		if (buf->dtb_xamot != NULL) {
10822 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10823 			kmem_free(buf->dtb_xamot, buf->dtb_size);
10824 		}
10825 
10826 		kmem_free(buf->dtb_tomax, buf->dtb_size);
10827 		buf->dtb_size = 0;
10828 		buf->dtb_tomax = NULL;
10829 		buf->dtb_xamot = NULL;
10830 	}
10831 }
10832 
10833 /*
10834  * DTrace Enabling Functions
10835  */
10836 static dtrace_enabling_t *
10837 dtrace_enabling_create(dtrace_vstate_t *vstate)
10838 {
10839 	dtrace_enabling_t *enab;
10840 
10841 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
10842 	enab->dten_vstate = vstate;
10843 
10844 	return (enab);
10845 }
10846 
10847 static void
10848 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
10849 {
10850 	dtrace_ecbdesc_t **ndesc;
10851 	size_t osize, nsize;
10852 
10853 	/*
10854 	 * We can't add to enablings after we've enabled them, or after we've
10855 	 * retained them.
10856 	 */
10857 	ASSERT(enab->dten_probegen == 0);
10858 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10859 
10860 	if (enab->dten_ndesc < enab->dten_maxdesc) {
10861 		enab->dten_desc[enab->dten_ndesc++] = ecb;
10862 		return;
10863 	}
10864 
10865 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10866 
10867 	if (enab->dten_maxdesc == 0) {
10868 		enab->dten_maxdesc = 1;
10869 	} else {
10870 		enab->dten_maxdesc <<= 1;
10871 	}
10872 
10873 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
10874 
10875 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10876 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
10877 	bcopy(enab->dten_desc, ndesc, osize);
10878 	kmem_free(enab->dten_desc, osize);
10879 
10880 	enab->dten_desc = ndesc;
10881 	enab->dten_desc[enab->dten_ndesc++] = ecb;
10882 }
10883 
10884 static void
10885 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
10886     dtrace_probedesc_t *pd)
10887 {
10888 	dtrace_ecbdesc_t *new;
10889 	dtrace_predicate_t *pred;
10890 	dtrace_actdesc_t *act;
10891 
10892 	/*
10893 	 * We're going to create a new ECB description that matches the
10894 	 * specified ECB in every way, but has the specified probe description.
10895 	 */
10896 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
10897 
10898 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
10899 		dtrace_predicate_hold(pred);
10900 
10901 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
10902 		dtrace_actdesc_hold(act);
10903 
10904 	new->dted_action = ecb->dted_action;
10905 	new->dted_pred = ecb->dted_pred;
10906 	new->dted_probe = *pd;
10907 	new->dted_uarg = ecb->dted_uarg;
10908 
10909 	dtrace_enabling_add(enab, new);
10910 }
10911 
10912 static void
10913 dtrace_enabling_dump(dtrace_enabling_t *enab)
10914 {
10915 	int i;
10916 
10917 	for (i = 0; i < enab->dten_ndesc; i++) {
10918 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
10919 
10920 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
10921 		    desc->dtpd_provider, desc->dtpd_mod,
10922 		    desc->dtpd_func, desc->dtpd_name);
10923 	}
10924 }
10925 
10926 static void
10927 dtrace_enabling_destroy(dtrace_enabling_t *enab)
10928 {
10929 	int i;
10930 	dtrace_ecbdesc_t *ep;
10931 	dtrace_vstate_t *vstate = enab->dten_vstate;
10932 
10933 	ASSERT(MUTEX_HELD(&dtrace_lock));
10934 
10935 	for (i = 0; i < enab->dten_ndesc; i++) {
10936 		dtrace_actdesc_t *act, *next;
10937 		dtrace_predicate_t *pred;
10938 
10939 		ep = enab->dten_desc[i];
10940 
10941 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
10942 			dtrace_predicate_release(pred, vstate);
10943 
10944 		for (act = ep->dted_action; act != NULL; act = next) {
10945 			next = act->dtad_next;
10946 			dtrace_actdesc_release(act, vstate);
10947 		}
10948 
10949 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
10950 	}
10951 
10952 	kmem_free(enab->dten_desc,
10953 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
10954 
10955 	/*
10956 	 * If this was a retained enabling, decrement the dts_nretained count
10957 	 * and take it off of the dtrace_retained list.
10958 	 */
10959 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
10960 	    dtrace_retained == enab) {
10961 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10962 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
10963 		enab->dten_vstate->dtvs_state->dts_nretained--;
10964 		dtrace_retained_gen++;
10965 	}
10966 
10967 	if (enab->dten_prev == NULL) {
10968 		if (dtrace_retained == enab) {
10969 			dtrace_retained = enab->dten_next;
10970 
10971 			if (dtrace_retained != NULL)
10972 				dtrace_retained->dten_prev = NULL;
10973 		}
10974 	} else {
10975 		ASSERT(enab != dtrace_retained);
10976 		ASSERT(dtrace_retained != NULL);
10977 		enab->dten_prev->dten_next = enab->dten_next;
10978 	}
10979 
10980 	if (enab->dten_next != NULL) {
10981 		ASSERT(dtrace_retained != NULL);
10982 		enab->dten_next->dten_prev = enab->dten_prev;
10983 	}
10984 
10985 	kmem_free(enab, sizeof (dtrace_enabling_t));
10986 }
10987 
10988 static int
10989 dtrace_enabling_retain(dtrace_enabling_t *enab)
10990 {
10991 	dtrace_state_t *state;
10992 
10993 	ASSERT(MUTEX_HELD(&dtrace_lock));
10994 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10995 	ASSERT(enab->dten_vstate != NULL);
10996 
10997 	state = enab->dten_vstate->dtvs_state;
10998 	ASSERT(state != NULL);
10999 
11000 	/*
11001 	 * We only allow each state to retain dtrace_retain_max enablings.
11002 	 */
11003 	if (state->dts_nretained >= dtrace_retain_max)
11004 		return (ENOSPC);
11005 
11006 	state->dts_nretained++;
11007 	dtrace_retained_gen++;
11008 
11009 	if (dtrace_retained == NULL) {
11010 		dtrace_retained = enab;
11011 		return (0);
11012 	}
11013 
11014 	enab->dten_next = dtrace_retained;
11015 	dtrace_retained->dten_prev = enab;
11016 	dtrace_retained = enab;
11017 
11018 	return (0);
11019 }
11020 
11021 static int
11022 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
11023     dtrace_probedesc_t *create)
11024 {
11025 	dtrace_enabling_t *new, *enab;
11026 	int found = 0, err = ENOENT;
11027 
11028 	ASSERT(MUTEX_HELD(&dtrace_lock));
11029 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
11030 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
11031 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
11032 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
11033 
11034 	new = dtrace_enabling_create(&state->dts_vstate);
11035 
11036 	/*
11037 	 * Iterate over all retained enablings, looking for enablings that
11038 	 * match the specified state.
11039 	 */
11040 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11041 		int i;
11042 
11043 		/*
11044 		 * dtvs_state can only be NULL for helper enablings -- and
11045 		 * helper enablings can't be retained.
11046 		 */
11047 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11048 
11049 		if (enab->dten_vstate->dtvs_state != state)
11050 			continue;
11051 
11052 		/*
11053 		 * Now iterate over each probe description; we're looking for
11054 		 * an exact match to the specified probe description.
11055 		 */
11056 		for (i = 0; i < enab->dten_ndesc; i++) {
11057 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11058 			dtrace_probedesc_t *pd = &ep->dted_probe;
11059 
11060 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
11061 				continue;
11062 
11063 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
11064 				continue;
11065 
11066 			if (strcmp(pd->dtpd_func, match->dtpd_func))
11067 				continue;
11068 
11069 			if (strcmp(pd->dtpd_name, match->dtpd_name))
11070 				continue;
11071 
11072 			/*
11073 			 * We have a winning probe!  Add it to our growing
11074 			 * enabling.
11075 			 */
11076 			found = 1;
11077 			dtrace_enabling_addlike(new, ep, create);
11078 		}
11079 	}
11080 
11081 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
11082 		dtrace_enabling_destroy(new);
11083 		return (err);
11084 	}
11085 
11086 	return (0);
11087 }
11088 
11089 static void
11090 dtrace_enabling_retract(dtrace_state_t *state)
11091 {
11092 	dtrace_enabling_t *enab, *next;
11093 
11094 	ASSERT(MUTEX_HELD(&dtrace_lock));
11095 
11096 	/*
11097 	 * Iterate over all retained enablings, destroy the enablings retained
11098 	 * for the specified state.
11099 	 */
11100 	for (enab = dtrace_retained; enab != NULL; enab = next) {
11101 		next = enab->dten_next;
11102 
11103 		/*
11104 		 * dtvs_state can only be NULL for helper enablings -- and
11105 		 * helper enablings can't be retained.
11106 		 */
11107 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11108 
11109 		if (enab->dten_vstate->dtvs_state == state) {
11110 			ASSERT(state->dts_nretained > 0);
11111 			dtrace_enabling_destroy(enab);
11112 		}
11113 	}
11114 
11115 	ASSERT(state->dts_nretained == 0);
11116 }
11117 
11118 static int
11119 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
11120 {
11121 	int i = 0;
11122 	int total_matched = 0, matched = 0;
11123 
11124 	ASSERT(MUTEX_HELD(&cpu_lock));
11125 	ASSERT(MUTEX_HELD(&dtrace_lock));
11126 
11127 	for (i = 0; i < enab->dten_ndesc; i++) {
11128 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
11129 
11130 		enab->dten_current = ep;
11131 		enab->dten_error = 0;
11132 
11133 		/*
11134 		 * If a provider failed to enable a probe then get out and
11135 		 * let the consumer know we failed.
11136 		 */
11137 		if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
11138 			return (EBUSY);
11139 
11140 		total_matched += matched;
11141 
11142 		if (enab->dten_error != 0) {
11143 			/*
11144 			 * If we get an error half-way through enabling the
11145 			 * probes, we kick out -- perhaps with some number of
11146 			 * them enabled.  Leaving enabled probes enabled may
11147 			 * be slightly confusing for user-level, but we expect
11148 			 * that no one will attempt to actually drive on in
11149 			 * the face of such errors.  If this is an anonymous
11150 			 * enabling (indicated with a NULL nmatched pointer),
11151 			 * we cmn_err() a message.  We aren't expecting to
11152 			 * get such an error -- such as it can exist at all,
11153 			 * it would be a result of corrupted DOF in the driver
11154 			 * properties.
11155 			 */
11156 			if (nmatched == NULL) {
11157 				cmn_err(CE_WARN, "dtrace_enabling_match() "
11158 				    "error on %p: %d", (void *)ep,
11159 				    enab->dten_error);
11160 			}
11161 
11162 			return (enab->dten_error);
11163 		}
11164 	}
11165 
11166 	enab->dten_probegen = dtrace_probegen;
11167 	if (nmatched != NULL)
11168 		*nmatched = total_matched;
11169 
11170 	return (0);
11171 }
11172 
11173 static void
11174 dtrace_enabling_matchall(void)
11175 {
11176 	dtrace_enabling_t *enab;
11177 
11178 	mutex_enter(&cpu_lock);
11179 	mutex_enter(&dtrace_lock);
11180 
11181 	/*
11182 	 * Iterate over all retained enablings to see if any probes match
11183 	 * against them.  We only perform this operation on enablings for which
11184 	 * we have sufficient permissions by virtue of being in the global zone
11185 	 * or in the same zone as the DTrace client.  Because we can be called
11186 	 * after dtrace_detach() has been called, we cannot assert that there
11187 	 * are retained enablings.  We can safely load from dtrace_retained,
11188 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
11189 	 * block pending our completion.
11190 	 */
11191 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11192 		dtrace_cred_t *dcr = &enab->dten_vstate->dtvs_state->dts_cred;
11193 		cred_t *cr = dcr->dcr_cred;
11194 		zoneid_t zone = cr != NULL ? crgetzoneid(cr) : 0;
11195 
11196 		if ((dcr->dcr_visible & DTRACE_CRV_ALLZONE) || (cr != NULL &&
11197 		    (zone == GLOBAL_ZONEID || getzoneid() == zone)))
11198 			(void) dtrace_enabling_match(enab, NULL);
11199 	}
11200 
11201 	mutex_exit(&dtrace_lock);
11202 	mutex_exit(&cpu_lock);
11203 }
11204 
11205 /*
11206  * If an enabling is to be enabled without having matched probes (that is, if
11207  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
11208  * enabling must be _primed_ by creating an ECB for every ECB description.
11209  * This must be done to assure that we know the number of speculations, the
11210  * number of aggregations, the minimum buffer size needed, etc. before we
11211  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
11212  * enabling any probes, we create ECBs for every ECB decription, but with a
11213  * NULL probe -- which is exactly what this function does.
11214  */
11215 static void
11216 dtrace_enabling_prime(dtrace_state_t *state)
11217 {
11218 	dtrace_enabling_t *enab;
11219 	int i;
11220 
11221 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
11222 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
11223 
11224 		if (enab->dten_vstate->dtvs_state != state)
11225 			continue;
11226 
11227 		/*
11228 		 * We don't want to prime an enabling more than once, lest
11229 		 * we allow a malicious user to induce resource exhaustion.
11230 		 * (The ECBs that result from priming an enabling aren't
11231 		 * leaked -- but they also aren't deallocated until the
11232 		 * consumer state is destroyed.)
11233 		 */
11234 		if (enab->dten_primed)
11235 			continue;
11236 
11237 		for (i = 0; i < enab->dten_ndesc; i++) {
11238 			enab->dten_current = enab->dten_desc[i];
11239 			(void) dtrace_probe_enable(NULL, enab);
11240 		}
11241 
11242 		enab->dten_primed = 1;
11243 	}
11244 }
11245 
11246 /*
11247  * Called to indicate that probes should be provided due to retained
11248  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
11249  * must take an initial lap through the enabling calling the dtps_provide()
11250  * entry point explicitly to allow for autocreated probes.
11251  */
11252 static void
11253 dtrace_enabling_provide(dtrace_provider_t *prv)
11254 {
11255 	int i, all = 0;
11256 	dtrace_probedesc_t desc;
11257 	dtrace_genid_t gen;
11258 
11259 	ASSERT(MUTEX_HELD(&dtrace_lock));
11260 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
11261 
11262 	if (prv == NULL) {
11263 		all = 1;
11264 		prv = dtrace_provider;
11265 	}
11266 
11267 	do {
11268 		dtrace_enabling_t *enab;
11269 		void *parg = prv->dtpv_arg;
11270 
11271 retry:
11272 		gen = dtrace_retained_gen;
11273 		for (enab = dtrace_retained; enab != NULL;
11274 		    enab = enab->dten_next) {
11275 			for (i = 0; i < enab->dten_ndesc; i++) {
11276 				desc = enab->dten_desc[i]->dted_probe;
11277 				mutex_exit(&dtrace_lock);
11278 				prv->dtpv_pops.dtps_provide(parg, &desc);
11279 				mutex_enter(&dtrace_lock);
11280 				/*
11281 				 * Process the retained enablings again if
11282 				 * they have changed while we weren't holding
11283 				 * dtrace_lock.
11284 				 */
11285 				if (gen != dtrace_retained_gen)
11286 					goto retry;
11287 			}
11288 		}
11289 	} while (all && (prv = prv->dtpv_next) != NULL);
11290 
11291 	mutex_exit(&dtrace_lock);
11292 	dtrace_probe_provide(NULL, all ? NULL : prv);
11293 	mutex_enter(&dtrace_lock);
11294 }
11295 
11296 /*
11297  * Called to reap ECBs that are attached to probes from defunct providers.
11298  */
11299 static void
11300 dtrace_enabling_reap(void)
11301 {
11302 	dtrace_provider_t *prov;
11303 	dtrace_probe_t *probe;
11304 	dtrace_ecb_t *ecb;
11305 	hrtime_t when;
11306 	int i;
11307 
11308 	mutex_enter(&cpu_lock);
11309 	mutex_enter(&dtrace_lock);
11310 
11311 	for (i = 0; i < dtrace_nprobes; i++) {
11312 		if ((probe = dtrace_probes[i]) == NULL)
11313 			continue;
11314 
11315 		if (probe->dtpr_ecb == NULL)
11316 			continue;
11317 
11318 		prov = probe->dtpr_provider;
11319 
11320 		if ((when = prov->dtpv_defunct) == 0)
11321 			continue;
11322 
11323 		/*
11324 		 * We have ECBs on a defunct provider:  we want to reap these
11325 		 * ECBs to allow the provider to unregister.  The destruction
11326 		 * of these ECBs must be done carefully:  if we destroy the ECB
11327 		 * and the consumer later wishes to consume an EPID that
11328 		 * corresponds to the destroyed ECB (and if the EPID metadata
11329 		 * has not been previously consumed), the consumer will abort
11330 		 * processing on the unknown EPID.  To reduce (but not, sadly,
11331 		 * eliminate) the possibility of this, we will only destroy an
11332 		 * ECB for a defunct provider if, for the state that
11333 		 * corresponds to the ECB:
11334 		 *
11335 		 *  (a)	There is no speculative tracing (which can effectively
11336 		 *	cache an EPID for an arbitrary amount of time).
11337 		 *
11338 		 *  (b)	The principal buffers have been switched twice since the
11339 		 *	provider became defunct.
11340 		 *
11341 		 *  (c)	The aggregation buffers are of zero size or have been
11342 		 *	switched twice since the provider became defunct.
11343 		 *
11344 		 * We use dts_speculates to determine (a) and call a function
11345 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
11346 		 * that as soon as we've been unable to destroy one of the ECBs
11347 		 * associated with the probe, we quit trying -- reaping is only
11348 		 * fruitful in as much as we can destroy all ECBs associated
11349 		 * with the defunct provider's probes.
11350 		 */
11351 		while ((ecb = probe->dtpr_ecb) != NULL) {
11352 			dtrace_state_t *state = ecb->dte_state;
11353 			dtrace_buffer_t *buf = state->dts_buffer;
11354 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
11355 
11356 			if (state->dts_speculates)
11357 				break;
11358 
11359 			if (!dtrace_buffer_consumed(buf, when))
11360 				break;
11361 
11362 			if (!dtrace_buffer_consumed(aggbuf, when))
11363 				break;
11364 
11365 			dtrace_ecb_disable(ecb);
11366 			ASSERT(probe->dtpr_ecb != ecb);
11367 			dtrace_ecb_destroy(ecb);
11368 		}
11369 	}
11370 
11371 	mutex_exit(&dtrace_lock);
11372 	mutex_exit(&cpu_lock);
11373 }
11374 
11375 /*
11376  * DTrace DOF Functions
11377  */
11378 /*ARGSUSED*/
11379 static void
11380 dtrace_dof_error(dof_hdr_t *dof, const char *str)
11381 {
11382 	if (dtrace_err_verbose)
11383 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
11384 
11385 #ifdef DTRACE_ERRDEBUG
11386 	dtrace_errdebug(str);
11387 #endif
11388 }
11389 
11390 /*
11391  * Create DOF out of a currently enabled state.  Right now, we only create
11392  * DOF containing the run-time options -- but this could be expanded to create
11393  * complete DOF representing the enabled state.
11394  */
11395 static dof_hdr_t *
11396 dtrace_dof_create(dtrace_state_t *state)
11397 {
11398 	dof_hdr_t *dof;
11399 	dof_sec_t *sec;
11400 	dof_optdesc_t *opt;
11401 	int i, len = sizeof (dof_hdr_t) +
11402 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
11403 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11404 
11405 	ASSERT(MUTEX_HELD(&dtrace_lock));
11406 
11407 	dof = kmem_zalloc(len, KM_SLEEP);
11408 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
11409 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
11410 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
11411 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
11412 
11413 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
11414 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
11415 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
11416 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
11417 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
11418 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
11419 
11420 	dof->dofh_flags = 0;
11421 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
11422 	dof->dofh_secsize = sizeof (dof_sec_t);
11423 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
11424 	dof->dofh_secoff = sizeof (dof_hdr_t);
11425 	dof->dofh_loadsz = len;
11426 	dof->dofh_filesz = len;
11427 	dof->dofh_pad = 0;
11428 
11429 	/*
11430 	 * Fill in the option section header...
11431 	 */
11432 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
11433 	sec->dofs_type = DOF_SECT_OPTDESC;
11434 	sec->dofs_align = sizeof (uint64_t);
11435 	sec->dofs_flags = DOF_SECF_LOAD;
11436 	sec->dofs_entsize = sizeof (dof_optdesc_t);
11437 
11438 	opt = (dof_optdesc_t *)((uintptr_t)sec +
11439 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
11440 
11441 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
11442 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
11443 
11444 	for (i = 0; i < DTRACEOPT_MAX; i++) {
11445 		opt[i].dofo_option = i;
11446 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
11447 		opt[i].dofo_value = state->dts_options[i];
11448 	}
11449 
11450 	return (dof);
11451 }
11452 
11453 static dof_hdr_t *
11454 dtrace_dof_copyin(uintptr_t uarg, int *errp)
11455 {
11456 	dof_hdr_t hdr, *dof;
11457 
11458 	ASSERT(!MUTEX_HELD(&dtrace_lock));
11459 
11460 	/*
11461 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
11462 	 */
11463 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
11464 		dtrace_dof_error(NULL, "failed to copyin DOF header");
11465 		*errp = EFAULT;
11466 		return (NULL);
11467 	}
11468 
11469 	/*
11470 	 * Now we'll allocate the entire DOF and copy it in -- provided
11471 	 * that the length isn't outrageous.
11472 	 */
11473 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
11474 		dtrace_dof_error(&hdr, "load size exceeds maximum");
11475 		*errp = E2BIG;
11476 		return (NULL);
11477 	}
11478 
11479 	if (hdr.dofh_loadsz < sizeof (hdr)) {
11480 		dtrace_dof_error(&hdr, "invalid load size");
11481 		*errp = EINVAL;
11482 		return (NULL);
11483 	}
11484 
11485 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
11486 
11487 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
11488 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
11489 		kmem_free(dof, hdr.dofh_loadsz);
11490 		*errp = EFAULT;
11491 		return (NULL);
11492 	}
11493 
11494 	return (dof);
11495 }
11496 
11497 static dof_hdr_t *
11498 dtrace_dof_property(const char *name)
11499 {
11500 	uchar_t *buf;
11501 	uint64_t loadsz;
11502 	unsigned int len, i;
11503 	dof_hdr_t *dof;
11504 
11505 	/*
11506 	 * Unfortunately, array of values in .conf files are always (and
11507 	 * only) interpreted to be integer arrays.  We must read our DOF
11508 	 * as an integer array, and then squeeze it into a byte array.
11509 	 */
11510 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
11511 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
11512 		return (NULL);
11513 
11514 	for (i = 0; i < len; i++)
11515 		buf[i] = (uchar_t)(((int *)buf)[i]);
11516 
11517 	if (len < sizeof (dof_hdr_t)) {
11518 		ddi_prop_free(buf);
11519 		dtrace_dof_error(NULL, "truncated header");
11520 		return (NULL);
11521 	}
11522 
11523 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
11524 		ddi_prop_free(buf);
11525 		dtrace_dof_error(NULL, "truncated DOF");
11526 		return (NULL);
11527 	}
11528 
11529 	if (loadsz >= dtrace_dof_maxsize) {
11530 		ddi_prop_free(buf);
11531 		dtrace_dof_error(NULL, "oversized DOF");
11532 		return (NULL);
11533 	}
11534 
11535 	dof = kmem_alloc(loadsz, KM_SLEEP);
11536 	bcopy(buf, dof, loadsz);
11537 	ddi_prop_free(buf);
11538 
11539 	return (dof);
11540 }
11541 
11542 static void
11543 dtrace_dof_destroy(dof_hdr_t *dof)
11544 {
11545 	kmem_free(dof, dof->dofh_loadsz);
11546 }
11547 
11548 /*
11549  * Return the dof_sec_t pointer corresponding to a given section index.  If the
11550  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
11551  * a type other than DOF_SECT_NONE is specified, the header is checked against
11552  * this type and NULL is returned if the types do not match.
11553  */
11554 static dof_sec_t *
11555 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
11556 {
11557 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
11558 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
11559 
11560 	if (i >= dof->dofh_secnum) {
11561 		dtrace_dof_error(dof, "referenced section index is invalid");
11562 		return (NULL);
11563 	}
11564 
11565 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
11566 		dtrace_dof_error(dof, "referenced section is not loadable");
11567 		return (NULL);
11568 	}
11569 
11570 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
11571 		dtrace_dof_error(dof, "referenced section is the wrong type");
11572 		return (NULL);
11573 	}
11574 
11575 	return (sec);
11576 }
11577 
11578 static dtrace_probedesc_t *
11579 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
11580 {
11581 	dof_probedesc_t *probe;
11582 	dof_sec_t *strtab;
11583 	uintptr_t daddr = (uintptr_t)dof;
11584 	uintptr_t str;
11585 	size_t size;
11586 
11587 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
11588 		dtrace_dof_error(dof, "invalid probe section");
11589 		return (NULL);
11590 	}
11591 
11592 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
11593 		dtrace_dof_error(dof, "bad alignment in probe description");
11594 		return (NULL);
11595 	}
11596 
11597 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
11598 		dtrace_dof_error(dof, "truncated probe description");
11599 		return (NULL);
11600 	}
11601 
11602 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
11603 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
11604 
11605 	if (strtab == NULL)
11606 		return (NULL);
11607 
11608 	str = daddr + strtab->dofs_offset;
11609 	size = strtab->dofs_size;
11610 
11611 	if (probe->dofp_provider >= strtab->dofs_size) {
11612 		dtrace_dof_error(dof, "corrupt probe provider");
11613 		return (NULL);
11614 	}
11615 
11616 	(void) strncpy(desc->dtpd_provider,
11617 	    (char *)(str + probe->dofp_provider),
11618 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
11619 
11620 	if (probe->dofp_mod >= strtab->dofs_size) {
11621 		dtrace_dof_error(dof, "corrupt probe module");
11622 		return (NULL);
11623 	}
11624 
11625 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
11626 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
11627 
11628 	if (probe->dofp_func >= strtab->dofs_size) {
11629 		dtrace_dof_error(dof, "corrupt probe function");
11630 		return (NULL);
11631 	}
11632 
11633 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
11634 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
11635 
11636 	if (probe->dofp_name >= strtab->dofs_size) {
11637 		dtrace_dof_error(dof, "corrupt probe name");
11638 		return (NULL);
11639 	}
11640 
11641 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
11642 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
11643 
11644 	return (desc);
11645 }
11646 
11647 static dtrace_difo_t *
11648 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11649     cred_t *cr)
11650 {
11651 	dtrace_difo_t *dp;
11652 	size_t ttl = 0;
11653 	dof_difohdr_t *dofd;
11654 	uintptr_t daddr = (uintptr_t)dof;
11655 	size_t max = dtrace_difo_maxsize;
11656 	int i, l, n;
11657 
11658 	static const struct {
11659 		int section;
11660 		int bufoffs;
11661 		int lenoffs;
11662 		int entsize;
11663 		int align;
11664 		const char *msg;
11665 	} difo[] = {
11666 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
11667 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
11668 		sizeof (dif_instr_t), "multiple DIF sections" },
11669 
11670 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
11671 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
11672 		sizeof (uint64_t), "multiple integer tables" },
11673 
11674 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
11675 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
11676 		sizeof (char), "multiple string tables" },
11677 
11678 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
11679 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
11680 		sizeof (uint_t), "multiple variable tables" },
11681 
11682 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
11683 	};
11684 
11685 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
11686 		dtrace_dof_error(dof, "invalid DIFO header section");
11687 		return (NULL);
11688 	}
11689 
11690 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
11691 		dtrace_dof_error(dof, "bad alignment in DIFO header");
11692 		return (NULL);
11693 	}
11694 
11695 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
11696 	    sec->dofs_size % sizeof (dof_secidx_t)) {
11697 		dtrace_dof_error(dof, "bad size in DIFO header");
11698 		return (NULL);
11699 	}
11700 
11701 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11702 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
11703 
11704 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
11705 	dp->dtdo_rtype = dofd->dofd_rtype;
11706 
11707 	for (l = 0; l < n; l++) {
11708 		dof_sec_t *subsec;
11709 		void **bufp;
11710 		uint32_t *lenp;
11711 
11712 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
11713 		    dofd->dofd_links[l])) == NULL)
11714 			goto err; /* invalid section link */
11715 
11716 		if (ttl + subsec->dofs_size > max) {
11717 			dtrace_dof_error(dof, "exceeds maximum size");
11718 			goto err;
11719 		}
11720 
11721 		ttl += subsec->dofs_size;
11722 
11723 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
11724 			if (subsec->dofs_type != difo[i].section)
11725 				continue;
11726 
11727 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
11728 				dtrace_dof_error(dof, "section not loaded");
11729 				goto err;
11730 			}
11731 
11732 			if (subsec->dofs_align != difo[i].align) {
11733 				dtrace_dof_error(dof, "bad alignment");
11734 				goto err;
11735 			}
11736 
11737 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
11738 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
11739 
11740 			if (*bufp != NULL) {
11741 				dtrace_dof_error(dof, difo[i].msg);
11742 				goto err;
11743 			}
11744 
11745 			if (difo[i].entsize != subsec->dofs_entsize) {
11746 				dtrace_dof_error(dof, "entry size mismatch");
11747 				goto err;
11748 			}
11749 
11750 			if (subsec->dofs_entsize != 0 &&
11751 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
11752 				dtrace_dof_error(dof, "corrupt entry size");
11753 				goto err;
11754 			}
11755 
11756 			*lenp = subsec->dofs_size;
11757 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
11758 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
11759 			    *bufp, subsec->dofs_size);
11760 
11761 			if (subsec->dofs_entsize != 0)
11762 				*lenp /= subsec->dofs_entsize;
11763 
11764 			break;
11765 		}
11766 
11767 		/*
11768 		 * If we encounter a loadable DIFO sub-section that is not
11769 		 * known to us, assume this is a broken program and fail.
11770 		 */
11771 		if (difo[i].section == DOF_SECT_NONE &&
11772 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
11773 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
11774 			goto err;
11775 		}
11776 	}
11777 
11778 	if (dp->dtdo_buf == NULL) {
11779 		/*
11780 		 * We can't have a DIF object without DIF text.
11781 		 */
11782 		dtrace_dof_error(dof, "missing DIF text");
11783 		goto err;
11784 	}
11785 
11786 	/*
11787 	 * Before we validate the DIF object, run through the variable table
11788 	 * looking for the strings -- if any of their size are under, we'll set
11789 	 * their size to be the system-wide default string size.  Note that
11790 	 * this should _not_ happen if the "strsize" option has been set --
11791 	 * in this case, the compiler should have set the size to reflect the
11792 	 * setting of the option.
11793 	 */
11794 	for (i = 0; i < dp->dtdo_varlen; i++) {
11795 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
11796 		dtrace_diftype_t *t = &v->dtdv_type;
11797 
11798 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
11799 			continue;
11800 
11801 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
11802 			t->dtdt_size = dtrace_strsize_default;
11803 	}
11804 
11805 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
11806 		goto err;
11807 
11808 	dtrace_difo_init(dp, vstate);
11809 	return (dp);
11810 
11811 err:
11812 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
11813 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
11814 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
11815 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
11816 
11817 	kmem_free(dp, sizeof (dtrace_difo_t));
11818 	return (NULL);
11819 }
11820 
11821 static dtrace_predicate_t *
11822 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11823     cred_t *cr)
11824 {
11825 	dtrace_difo_t *dp;
11826 
11827 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
11828 		return (NULL);
11829 
11830 	return (dtrace_predicate_create(dp));
11831 }
11832 
11833 static dtrace_actdesc_t *
11834 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11835     cred_t *cr)
11836 {
11837 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
11838 	dof_actdesc_t *desc;
11839 	dof_sec_t *difosec;
11840 	size_t offs;
11841 	uintptr_t daddr = (uintptr_t)dof;
11842 	uint64_t arg;
11843 	dtrace_actkind_t kind;
11844 
11845 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
11846 		dtrace_dof_error(dof, "invalid action section");
11847 		return (NULL);
11848 	}
11849 
11850 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
11851 		dtrace_dof_error(dof, "truncated action description");
11852 		return (NULL);
11853 	}
11854 
11855 	if (sec->dofs_align != sizeof (uint64_t)) {
11856 		dtrace_dof_error(dof, "bad alignment in action description");
11857 		return (NULL);
11858 	}
11859 
11860 	if (sec->dofs_size < sec->dofs_entsize) {
11861 		dtrace_dof_error(dof, "section entry size exceeds total size");
11862 		return (NULL);
11863 	}
11864 
11865 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
11866 		dtrace_dof_error(dof, "bad entry size in action description");
11867 		return (NULL);
11868 	}
11869 
11870 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
11871 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
11872 		return (NULL);
11873 	}
11874 
11875 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
11876 		desc = (dof_actdesc_t *)(daddr +
11877 		    (uintptr_t)sec->dofs_offset + offs);
11878 		kind = (dtrace_actkind_t)desc->dofa_kind;
11879 
11880 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
11881 		    (kind != DTRACEACT_PRINTA ||
11882 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
11883 		    (kind == DTRACEACT_DIFEXPR &&
11884 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
11885 			dof_sec_t *strtab;
11886 			char *str, *fmt;
11887 			uint64_t i;
11888 
11889 			/*
11890 			 * The argument to these actions is an index into the
11891 			 * DOF string table.  For printf()-like actions, this
11892 			 * is the format string.  For print(), this is the
11893 			 * CTF type of the expression result.
11894 			 */
11895 			if ((strtab = dtrace_dof_sect(dof,
11896 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
11897 				goto err;
11898 
11899 			str = (char *)((uintptr_t)dof +
11900 			    (uintptr_t)strtab->dofs_offset);
11901 
11902 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
11903 				if (str[i] == '\0')
11904 					break;
11905 			}
11906 
11907 			if (i >= strtab->dofs_size) {
11908 				dtrace_dof_error(dof, "bogus format string");
11909 				goto err;
11910 			}
11911 
11912 			if (i == desc->dofa_arg) {
11913 				dtrace_dof_error(dof, "empty format string");
11914 				goto err;
11915 			}
11916 
11917 			i -= desc->dofa_arg;
11918 			fmt = kmem_alloc(i + 1, KM_SLEEP);
11919 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
11920 			arg = (uint64_t)(uintptr_t)fmt;
11921 		} else {
11922 			if (kind == DTRACEACT_PRINTA) {
11923 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
11924 				arg = 0;
11925 			} else {
11926 				arg = desc->dofa_arg;
11927 			}
11928 		}
11929 
11930 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
11931 		    desc->dofa_uarg, arg);
11932 
11933 		if (last != NULL) {
11934 			last->dtad_next = act;
11935 		} else {
11936 			first = act;
11937 		}
11938 
11939 		last = act;
11940 
11941 		if (desc->dofa_difo == DOF_SECIDX_NONE)
11942 			continue;
11943 
11944 		if ((difosec = dtrace_dof_sect(dof,
11945 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
11946 			goto err;
11947 
11948 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
11949 
11950 		if (act->dtad_difo == NULL)
11951 			goto err;
11952 	}
11953 
11954 	ASSERT(first != NULL);
11955 	return (first);
11956 
11957 err:
11958 	for (act = first; act != NULL; act = next) {
11959 		next = act->dtad_next;
11960 		dtrace_actdesc_release(act, vstate);
11961 	}
11962 
11963 	return (NULL);
11964 }
11965 
11966 static dtrace_ecbdesc_t *
11967 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11968     cred_t *cr)
11969 {
11970 	dtrace_ecbdesc_t *ep;
11971 	dof_ecbdesc_t *ecb;
11972 	dtrace_probedesc_t *desc;
11973 	dtrace_predicate_t *pred = NULL;
11974 
11975 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
11976 		dtrace_dof_error(dof, "truncated ECB description");
11977 		return (NULL);
11978 	}
11979 
11980 	if (sec->dofs_align != sizeof (uint64_t)) {
11981 		dtrace_dof_error(dof, "bad alignment in ECB description");
11982 		return (NULL);
11983 	}
11984 
11985 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
11986 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
11987 
11988 	if (sec == NULL)
11989 		return (NULL);
11990 
11991 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11992 	ep->dted_uarg = ecb->dofe_uarg;
11993 	desc = &ep->dted_probe;
11994 
11995 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
11996 		goto err;
11997 
11998 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
11999 		if ((sec = dtrace_dof_sect(dof,
12000 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
12001 			goto err;
12002 
12003 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
12004 			goto err;
12005 
12006 		ep->dted_pred.dtpdd_predicate = pred;
12007 	}
12008 
12009 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
12010 		if ((sec = dtrace_dof_sect(dof,
12011 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
12012 			goto err;
12013 
12014 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
12015 
12016 		if (ep->dted_action == NULL)
12017 			goto err;
12018 	}
12019 
12020 	return (ep);
12021 
12022 err:
12023 	if (pred != NULL)
12024 		dtrace_predicate_release(pred, vstate);
12025 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12026 	return (NULL);
12027 }
12028 
12029 /*
12030  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
12031  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
12032  * site of any user SETX relocations to account for load object base address.
12033  * In the future, if we need other relocations, this function can be extended.
12034  */
12035 static int
12036 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
12037 {
12038 	uintptr_t daddr = (uintptr_t)dof;
12039 	dof_relohdr_t *dofr =
12040 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12041 	dof_sec_t *ss, *rs, *ts;
12042 	dof_relodesc_t *r;
12043 	uint_t i, n;
12044 
12045 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
12046 	    sec->dofs_align != sizeof (dof_secidx_t)) {
12047 		dtrace_dof_error(dof, "invalid relocation header");
12048 		return (-1);
12049 	}
12050 
12051 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
12052 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
12053 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
12054 
12055 	if (ss == NULL || rs == NULL || ts == NULL)
12056 		return (-1); /* dtrace_dof_error() has been called already */
12057 
12058 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
12059 	    rs->dofs_align != sizeof (uint64_t)) {
12060 		dtrace_dof_error(dof, "invalid relocation section");
12061 		return (-1);
12062 	}
12063 
12064 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
12065 	n = rs->dofs_size / rs->dofs_entsize;
12066 
12067 	for (i = 0; i < n; i++) {
12068 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
12069 
12070 		switch (r->dofr_type) {
12071 		case DOF_RELO_NONE:
12072 			break;
12073 		case DOF_RELO_SETX:
12074 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
12075 			    sizeof (uint64_t) > ts->dofs_size) {
12076 				dtrace_dof_error(dof, "bad relocation offset");
12077 				return (-1);
12078 			}
12079 
12080 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
12081 				dtrace_dof_error(dof, "misaligned setx relo");
12082 				return (-1);
12083 			}
12084 
12085 			*(uint64_t *)taddr += ubase;
12086 			break;
12087 		default:
12088 			dtrace_dof_error(dof, "invalid relocation type");
12089 			return (-1);
12090 		}
12091 
12092 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
12093 	}
12094 
12095 	return (0);
12096 }
12097 
12098 /*
12099  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
12100  * header:  it should be at the front of a memory region that is at least
12101  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
12102  * size.  It need not be validated in any other way.
12103  */
12104 static int
12105 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
12106     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
12107 {
12108 	uint64_t len = dof->dofh_loadsz, seclen;
12109 	uintptr_t daddr = (uintptr_t)dof;
12110 	dtrace_ecbdesc_t *ep;
12111 	dtrace_enabling_t *enab;
12112 	uint_t i;
12113 
12114 	ASSERT(MUTEX_HELD(&dtrace_lock));
12115 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
12116 
12117 	/*
12118 	 * Check the DOF header identification bytes.  In addition to checking
12119 	 * valid settings, we also verify that unused bits/bytes are zeroed so
12120 	 * we can use them later without fear of regressing existing binaries.
12121 	 */
12122 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
12123 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
12124 		dtrace_dof_error(dof, "DOF magic string mismatch");
12125 		return (-1);
12126 	}
12127 
12128 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
12129 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
12130 		dtrace_dof_error(dof, "DOF has invalid data model");
12131 		return (-1);
12132 	}
12133 
12134 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
12135 		dtrace_dof_error(dof, "DOF encoding mismatch");
12136 		return (-1);
12137 	}
12138 
12139 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12140 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
12141 		dtrace_dof_error(dof, "DOF version mismatch");
12142 		return (-1);
12143 	}
12144 
12145 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
12146 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
12147 		return (-1);
12148 	}
12149 
12150 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
12151 		dtrace_dof_error(dof, "DOF uses too many integer registers");
12152 		return (-1);
12153 	}
12154 
12155 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
12156 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
12157 		return (-1);
12158 	}
12159 
12160 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
12161 		if (dof->dofh_ident[i] != 0) {
12162 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
12163 			return (-1);
12164 		}
12165 	}
12166 
12167 	if (dof->dofh_flags & ~DOF_FL_VALID) {
12168 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
12169 		return (-1);
12170 	}
12171 
12172 	if (dof->dofh_secsize == 0) {
12173 		dtrace_dof_error(dof, "zero section header size");
12174 		return (-1);
12175 	}
12176 
12177 	/*
12178 	 * Check that the section headers don't exceed the amount of DOF
12179 	 * data.  Note that we cast the section size and number of sections
12180 	 * to uint64_t's to prevent possible overflow in the multiplication.
12181 	 */
12182 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
12183 
12184 	if (dof->dofh_secoff > len || seclen > len ||
12185 	    dof->dofh_secoff + seclen > len) {
12186 		dtrace_dof_error(dof, "truncated section headers");
12187 		return (-1);
12188 	}
12189 
12190 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
12191 		dtrace_dof_error(dof, "misaligned section headers");
12192 		return (-1);
12193 	}
12194 
12195 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
12196 		dtrace_dof_error(dof, "misaligned section size");
12197 		return (-1);
12198 	}
12199 
12200 	/*
12201 	 * Take an initial pass through the section headers to be sure that
12202 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
12203 	 * set, do not permit sections relating to providers, probes, or args.
12204 	 */
12205 	for (i = 0; i < dof->dofh_secnum; i++) {
12206 		dof_sec_t *sec = (dof_sec_t *)(daddr +
12207 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12208 
12209 		if (noprobes) {
12210 			switch (sec->dofs_type) {
12211 			case DOF_SECT_PROVIDER:
12212 			case DOF_SECT_PROBES:
12213 			case DOF_SECT_PRARGS:
12214 			case DOF_SECT_PROFFS:
12215 				dtrace_dof_error(dof, "illegal sections "
12216 				    "for enabling");
12217 				return (-1);
12218 			}
12219 		}
12220 
12221 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
12222 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
12223 			dtrace_dof_error(dof, "loadable section with load "
12224 			    "flag unset");
12225 			return (-1);
12226 		}
12227 
12228 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
12229 			continue; /* just ignore non-loadable sections */
12230 
12231 		if (sec->dofs_align & (sec->dofs_align - 1)) {
12232 			dtrace_dof_error(dof, "bad section alignment");
12233 			return (-1);
12234 		}
12235 
12236 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
12237 			dtrace_dof_error(dof, "misaligned section");
12238 			return (-1);
12239 		}
12240 
12241 		if (sec->dofs_offset > len || sec->dofs_size > len ||
12242 		    sec->dofs_offset + sec->dofs_size > len) {
12243 			dtrace_dof_error(dof, "corrupt section header");
12244 			return (-1);
12245 		}
12246 
12247 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
12248 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
12249 			dtrace_dof_error(dof, "non-terminating string table");
12250 			return (-1);
12251 		}
12252 	}
12253 
12254 	/*
12255 	 * Take a second pass through the sections and locate and perform any
12256 	 * relocations that are present.  We do this after the first pass to
12257 	 * be sure that all sections have had their headers validated.
12258 	 */
12259 	for (i = 0; i < dof->dofh_secnum; i++) {
12260 		dof_sec_t *sec = (dof_sec_t *)(daddr +
12261 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12262 
12263 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
12264 			continue; /* skip sections that are not loadable */
12265 
12266 		switch (sec->dofs_type) {
12267 		case DOF_SECT_URELHDR:
12268 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
12269 				return (-1);
12270 			break;
12271 		}
12272 	}
12273 
12274 	if ((enab = *enabp) == NULL)
12275 		enab = *enabp = dtrace_enabling_create(vstate);
12276 
12277 	for (i = 0; i < dof->dofh_secnum; i++) {
12278 		dof_sec_t *sec = (dof_sec_t *)(daddr +
12279 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12280 
12281 		if (sec->dofs_type != DOF_SECT_ECBDESC)
12282 			continue;
12283 
12284 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
12285 			dtrace_enabling_destroy(enab);
12286 			*enabp = NULL;
12287 			return (-1);
12288 		}
12289 
12290 		dtrace_enabling_add(enab, ep);
12291 	}
12292 
12293 	return (0);
12294 }
12295 
12296 /*
12297  * Process DOF for any options.  This routine assumes that the DOF has been
12298  * at least processed by dtrace_dof_slurp().
12299  */
12300 static int
12301 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
12302 {
12303 	int i, rval;
12304 	uint32_t entsize;
12305 	size_t offs;
12306 	dof_optdesc_t *desc;
12307 
12308 	for (i = 0; i < dof->dofh_secnum; i++) {
12309 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
12310 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
12311 
12312 		if (sec->dofs_type != DOF_SECT_OPTDESC)
12313 			continue;
12314 
12315 		if (sec->dofs_align != sizeof (uint64_t)) {
12316 			dtrace_dof_error(dof, "bad alignment in "
12317 			    "option description");
12318 			return (EINVAL);
12319 		}
12320 
12321 		if ((entsize = sec->dofs_entsize) == 0) {
12322 			dtrace_dof_error(dof, "zeroed option entry size");
12323 			return (EINVAL);
12324 		}
12325 
12326 		if (entsize < sizeof (dof_optdesc_t)) {
12327 			dtrace_dof_error(dof, "bad option entry size");
12328 			return (EINVAL);
12329 		}
12330 
12331 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
12332 			desc = (dof_optdesc_t *)((uintptr_t)dof +
12333 			    (uintptr_t)sec->dofs_offset + offs);
12334 
12335 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
12336 				dtrace_dof_error(dof, "non-zero option string");
12337 				return (EINVAL);
12338 			}
12339 
12340 			if (desc->dofo_value == DTRACEOPT_UNSET) {
12341 				dtrace_dof_error(dof, "unset option");
12342 				return (EINVAL);
12343 			}
12344 
12345 			if ((rval = dtrace_state_option(state,
12346 			    desc->dofo_option, desc->dofo_value)) != 0) {
12347 				dtrace_dof_error(dof, "rejected option");
12348 				return (rval);
12349 			}
12350 		}
12351 	}
12352 
12353 	return (0);
12354 }
12355 
12356 /*
12357  * DTrace Consumer State Functions
12358  */
12359 int
12360 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
12361 {
12362 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
12363 	void *base;
12364 	uintptr_t limit;
12365 	dtrace_dynvar_t *dvar, *next, *start;
12366 	int i;
12367 
12368 	ASSERT(MUTEX_HELD(&dtrace_lock));
12369 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
12370 
12371 	bzero(dstate, sizeof (dtrace_dstate_t));
12372 
12373 	if ((dstate->dtds_chunksize = chunksize) == 0)
12374 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
12375 
12376 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
12377 		size = min;
12378 
12379 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
12380 		return (ENOMEM);
12381 
12382 	dstate->dtds_size = size;
12383 	dstate->dtds_base = base;
12384 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
12385 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
12386 
12387 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
12388 
12389 	if (hashsize != 1 && (hashsize & 1))
12390 		hashsize--;
12391 
12392 	dstate->dtds_hashsize = hashsize;
12393 	dstate->dtds_hash = dstate->dtds_base;
12394 
12395 	/*
12396 	 * Set all of our hash buckets to point to the single sink, and (if
12397 	 * it hasn't already been set), set the sink's hash value to be the
12398 	 * sink sentinel value.  The sink is needed for dynamic variable
12399 	 * lookups to know that they have iterated over an entire, valid hash
12400 	 * chain.
12401 	 */
12402 	for (i = 0; i < hashsize; i++)
12403 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
12404 
12405 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
12406 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
12407 
12408 	/*
12409 	 * Determine number of active CPUs.  Divide free list evenly among
12410 	 * active CPUs.
12411 	 */
12412 	start = (dtrace_dynvar_t *)
12413 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
12414 	limit = (uintptr_t)base + size;
12415 
12416 	maxper = (limit - (uintptr_t)start) / NCPU;
12417 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
12418 
12419 	for (i = 0; i < NCPU; i++) {
12420 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
12421 
12422 		/*
12423 		 * If we don't even have enough chunks to make it once through
12424 		 * NCPUs, we're just going to allocate everything to the first
12425 		 * CPU.  And if we're on the last CPU, we're going to allocate
12426 		 * whatever is left over.  In either case, we set the limit to
12427 		 * be the limit of the dynamic variable space.
12428 		 */
12429 		if (maxper == 0 || i == NCPU - 1) {
12430 			limit = (uintptr_t)base + size;
12431 			start = NULL;
12432 		} else {
12433 			limit = (uintptr_t)start + maxper;
12434 			start = (dtrace_dynvar_t *)limit;
12435 		}
12436 
12437 		ASSERT(limit <= (uintptr_t)base + size);
12438 
12439 		for (;;) {
12440 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
12441 			    dstate->dtds_chunksize);
12442 
12443 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
12444 				break;
12445 
12446 			dvar->dtdv_next = next;
12447 			dvar = next;
12448 		}
12449 
12450 		if (maxper == 0)
12451 			break;
12452 	}
12453 
12454 	return (0);
12455 }
12456 
12457 void
12458 dtrace_dstate_fini(dtrace_dstate_t *dstate)
12459 {
12460 	ASSERT(MUTEX_HELD(&cpu_lock));
12461 
12462 	if (dstate->dtds_base == NULL)
12463 		return;
12464 
12465 	kmem_free(dstate->dtds_base, dstate->dtds_size);
12466 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
12467 }
12468 
12469 static void
12470 dtrace_vstate_fini(dtrace_vstate_t *vstate)
12471 {
12472 	/*
12473 	 * Logical XOR, where are you?
12474 	 */
12475 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
12476 
12477 	if (vstate->dtvs_nglobals > 0) {
12478 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
12479 		    sizeof (dtrace_statvar_t *));
12480 	}
12481 
12482 	if (vstate->dtvs_ntlocals > 0) {
12483 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
12484 		    sizeof (dtrace_difv_t));
12485 	}
12486 
12487 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
12488 
12489 	if (vstate->dtvs_nlocals > 0) {
12490 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
12491 		    sizeof (dtrace_statvar_t *));
12492 	}
12493 }
12494 
12495 static void
12496 dtrace_state_clean(dtrace_state_t *state)
12497 {
12498 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
12499 		return;
12500 
12501 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
12502 	dtrace_speculation_clean(state);
12503 }
12504 
12505 static void
12506 dtrace_state_deadman(dtrace_state_t *state)
12507 {
12508 	hrtime_t now;
12509 
12510 	dtrace_sync();
12511 
12512 	now = dtrace_gethrtime();
12513 
12514 	if (state != dtrace_anon.dta_state &&
12515 	    now - state->dts_laststatus >= dtrace_deadman_user)
12516 		return;
12517 
12518 	/*
12519 	 * We must be sure that dts_alive never appears to be less than the
12520 	 * value upon entry to dtrace_state_deadman(), and because we lack a
12521 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
12522 	 * store INT64_MAX to it, followed by a memory barrier, followed by
12523 	 * the new value.  This assures that dts_alive never appears to be
12524 	 * less than its true value, regardless of the order in which the
12525 	 * stores to the underlying storage are issued.
12526 	 */
12527 	state->dts_alive = INT64_MAX;
12528 	dtrace_membar_producer();
12529 	state->dts_alive = now;
12530 }
12531 
12532 dtrace_state_t *
12533 dtrace_state_create(dev_t *devp, cred_t *cr)
12534 {
12535 	minor_t minor;
12536 	major_t major;
12537 	char c[30];
12538 	dtrace_state_t *state;
12539 	dtrace_optval_t *opt;
12540 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
12541 
12542 	ASSERT(MUTEX_HELD(&dtrace_lock));
12543 	ASSERT(MUTEX_HELD(&cpu_lock));
12544 
12545 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
12546 	    VM_BESTFIT | VM_SLEEP);
12547 
12548 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
12549 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12550 		return (NULL);
12551 	}
12552 
12553 	state = ddi_get_soft_state(dtrace_softstate, minor);
12554 	state->dts_epid = DTRACE_EPIDNONE + 1;
12555 
12556 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
12557 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
12558 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
12559 
12560 	if (devp != NULL) {
12561 		major = getemajor(*devp);
12562 	} else {
12563 		major = ddi_driver_major(dtrace_devi);
12564 	}
12565 
12566 	state->dts_dev = makedevice(major, minor);
12567 
12568 	if (devp != NULL)
12569 		*devp = state->dts_dev;
12570 
12571 	/*
12572 	 * We allocate NCPU buffers.  On the one hand, this can be quite
12573 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
12574 	 * other hand, it saves an additional memory reference in the probe
12575 	 * path.
12576 	 */
12577 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
12578 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
12579 	state->dts_cleaner = CYCLIC_NONE;
12580 	state->dts_deadman = CYCLIC_NONE;
12581 	state->dts_vstate.dtvs_state = state;
12582 
12583 	for (i = 0; i < DTRACEOPT_MAX; i++)
12584 		state->dts_options[i] = DTRACEOPT_UNSET;
12585 
12586 	/*
12587 	 * Set the default options.
12588 	 */
12589 	opt = state->dts_options;
12590 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
12591 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
12592 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
12593 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
12594 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
12595 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
12596 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
12597 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
12598 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
12599 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
12600 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
12601 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
12602 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
12603 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
12604 
12605 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
12606 
12607 	/*
12608 	 * Depending on the user credentials, we set flag bits which alter probe
12609 	 * visibility or the amount of destructiveness allowed.  In the case of
12610 	 * actual anonymous tracing, or the possession of all privileges, all of
12611 	 * the normal checks are bypassed.
12612 	 */
12613 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
12614 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
12615 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
12616 	} else {
12617 		/*
12618 		 * Set up the credentials for this instantiation.  We take a
12619 		 * hold on the credential to prevent it from disappearing on
12620 		 * us; this in turn prevents the zone_t referenced by this
12621 		 * credential from disappearing.  This means that we can
12622 		 * examine the credential and the zone from probe context.
12623 		 */
12624 		crhold(cr);
12625 		state->dts_cred.dcr_cred = cr;
12626 
12627 		/*
12628 		 * CRA_PROC means "we have *some* privilege for dtrace" and
12629 		 * unlocks the use of variables like pid, zonename, etc.
12630 		 */
12631 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
12632 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12633 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
12634 		}
12635 
12636 		/*
12637 		 * dtrace_user allows use of syscall and profile providers.
12638 		 * If the user also has proc_owner and/or proc_zone, we
12639 		 * extend the scope to include additional visibility and
12640 		 * destructive power.
12641 		 */
12642 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
12643 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
12644 				state->dts_cred.dcr_visible |=
12645 				    DTRACE_CRV_ALLPROC;
12646 
12647 				state->dts_cred.dcr_action |=
12648 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12649 			}
12650 
12651 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
12652 				state->dts_cred.dcr_visible |=
12653 				    DTRACE_CRV_ALLZONE;
12654 
12655 				state->dts_cred.dcr_action |=
12656 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12657 			}
12658 
12659 			/*
12660 			 * If we have all privs in whatever zone this is,
12661 			 * we can do destructive things to processes which
12662 			 * have altered credentials.
12663 			 */
12664 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12665 			    cr->cr_zone->zone_privset)) {
12666 				state->dts_cred.dcr_action |=
12667 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12668 			}
12669 		}
12670 
12671 		/*
12672 		 * Holding the dtrace_kernel privilege also implies that
12673 		 * the user has the dtrace_user privilege from a visibility
12674 		 * perspective.  But without further privileges, some
12675 		 * destructive actions are not available.
12676 		 */
12677 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
12678 			/*
12679 			 * Make all probes in all zones visible.  However,
12680 			 * this doesn't mean that all actions become available
12681 			 * to all zones.
12682 			 */
12683 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
12684 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
12685 
12686 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
12687 			    DTRACE_CRA_PROC;
12688 			/*
12689 			 * Holding proc_owner means that destructive actions
12690 			 * for *this* zone are allowed.
12691 			 */
12692 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12693 				state->dts_cred.dcr_action |=
12694 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12695 
12696 			/*
12697 			 * Holding proc_zone means that destructive actions
12698 			 * for this user/group ID in all zones is allowed.
12699 			 */
12700 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12701 				state->dts_cred.dcr_action |=
12702 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12703 
12704 			/*
12705 			 * If we have all privs in whatever zone this is,
12706 			 * we can do destructive things to processes which
12707 			 * have altered credentials.
12708 			 */
12709 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12710 			    cr->cr_zone->zone_privset)) {
12711 				state->dts_cred.dcr_action |=
12712 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12713 			}
12714 		}
12715 
12716 		/*
12717 		 * Holding the dtrace_proc privilege gives control over fasttrap
12718 		 * and pid providers.  We need to grant wider destructive
12719 		 * privileges in the event that the user has proc_owner and/or
12720 		 * proc_zone.
12721 		 */
12722 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12723 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12724 				state->dts_cred.dcr_action |=
12725 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12726 
12727 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12728 				state->dts_cred.dcr_action |=
12729 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12730 		}
12731 	}
12732 
12733 	return (state);
12734 }
12735 
12736 static int
12737 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
12738 {
12739 	dtrace_optval_t *opt = state->dts_options, size;
12740 	processorid_t cpu;
12741 	int flags = 0, rval, factor, divisor = 1;
12742 
12743 	ASSERT(MUTEX_HELD(&dtrace_lock));
12744 	ASSERT(MUTEX_HELD(&cpu_lock));
12745 	ASSERT(which < DTRACEOPT_MAX);
12746 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
12747 	    (state == dtrace_anon.dta_state &&
12748 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
12749 
12750 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
12751 		return (0);
12752 
12753 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
12754 		cpu = opt[DTRACEOPT_CPU];
12755 
12756 	if (which == DTRACEOPT_SPECSIZE)
12757 		flags |= DTRACEBUF_NOSWITCH;
12758 
12759 	if (which == DTRACEOPT_BUFSIZE) {
12760 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
12761 			flags |= DTRACEBUF_RING;
12762 
12763 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
12764 			flags |= DTRACEBUF_FILL;
12765 
12766 		if (state != dtrace_anon.dta_state ||
12767 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
12768 			flags |= DTRACEBUF_INACTIVE;
12769 	}
12770 
12771 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
12772 		/*
12773 		 * The size must be 8-byte aligned.  If the size is not 8-byte
12774 		 * aligned, drop it down by the difference.
12775 		 */
12776 		if (size & (sizeof (uint64_t) - 1))
12777 			size -= size & (sizeof (uint64_t) - 1);
12778 
12779 		if (size < state->dts_reserve) {
12780 			/*
12781 			 * Buffers always must be large enough to accommodate
12782 			 * their prereserved space.  We return E2BIG instead
12783 			 * of ENOMEM in this case to allow for user-level
12784 			 * software to differentiate the cases.
12785 			 */
12786 			return (E2BIG);
12787 		}
12788 
12789 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
12790 
12791 		if (rval != ENOMEM) {
12792 			opt[which] = size;
12793 			return (rval);
12794 		}
12795 
12796 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12797 			return (rval);
12798 
12799 		for (divisor = 2; divisor < factor; divisor <<= 1)
12800 			continue;
12801 	}
12802 
12803 	return (ENOMEM);
12804 }
12805 
12806 static int
12807 dtrace_state_buffers(dtrace_state_t *state)
12808 {
12809 	dtrace_speculation_t *spec = state->dts_speculations;
12810 	int rval, i;
12811 
12812 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
12813 	    DTRACEOPT_BUFSIZE)) != 0)
12814 		return (rval);
12815 
12816 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
12817 	    DTRACEOPT_AGGSIZE)) != 0)
12818 		return (rval);
12819 
12820 	for (i = 0; i < state->dts_nspeculations; i++) {
12821 		if ((rval = dtrace_state_buffer(state,
12822 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
12823 			return (rval);
12824 	}
12825 
12826 	return (0);
12827 }
12828 
12829 static void
12830 dtrace_state_prereserve(dtrace_state_t *state)
12831 {
12832 	dtrace_ecb_t *ecb;
12833 	dtrace_probe_t *probe;
12834 
12835 	state->dts_reserve = 0;
12836 
12837 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
12838 		return;
12839 
12840 	/*
12841 	 * If our buffer policy is a "fill" buffer policy, we need to set the
12842 	 * prereserved space to be the space required by the END probes.
12843 	 */
12844 	probe = dtrace_probes[dtrace_probeid_end - 1];
12845 	ASSERT(probe != NULL);
12846 
12847 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
12848 		if (ecb->dte_state != state)
12849 			continue;
12850 
12851 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
12852 	}
12853 }
12854 
12855 static int
12856 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
12857 {
12858 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
12859 	dtrace_speculation_t *spec;
12860 	dtrace_buffer_t *buf;
12861 	cyc_handler_t hdlr;
12862 	cyc_time_t when;
12863 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12864 	dtrace_icookie_t cookie;
12865 
12866 	mutex_enter(&cpu_lock);
12867 	mutex_enter(&dtrace_lock);
12868 
12869 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
12870 		rval = EBUSY;
12871 		goto out;
12872 	}
12873 
12874 	/*
12875 	 * Before we can perform any checks, we must prime all of the
12876 	 * retained enablings that correspond to this state.
12877 	 */
12878 	dtrace_enabling_prime(state);
12879 
12880 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
12881 		rval = EACCES;
12882 		goto out;
12883 	}
12884 
12885 	dtrace_state_prereserve(state);
12886 
12887 	/*
12888 	 * Now we want to do is try to allocate our speculations.
12889 	 * We do not automatically resize the number of speculations; if
12890 	 * this fails, we will fail the operation.
12891 	 */
12892 	nspec = opt[DTRACEOPT_NSPEC];
12893 	ASSERT(nspec != DTRACEOPT_UNSET);
12894 
12895 	if (nspec > INT_MAX) {
12896 		rval = ENOMEM;
12897 		goto out;
12898 	}
12899 
12900 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
12901 	    KM_NOSLEEP | KM_NORMALPRI);
12902 
12903 	if (spec == NULL) {
12904 		rval = ENOMEM;
12905 		goto out;
12906 	}
12907 
12908 	state->dts_speculations = spec;
12909 	state->dts_nspeculations = (int)nspec;
12910 
12911 	for (i = 0; i < nspec; i++) {
12912 		if ((buf = kmem_zalloc(bufsize,
12913 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
12914 			rval = ENOMEM;
12915 			goto err;
12916 		}
12917 
12918 		spec[i].dtsp_buffer = buf;
12919 	}
12920 
12921 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
12922 		if (dtrace_anon.dta_state == NULL) {
12923 			rval = ENOENT;
12924 			goto out;
12925 		}
12926 
12927 		if (state->dts_necbs != 0) {
12928 			rval = EALREADY;
12929 			goto out;
12930 		}
12931 
12932 		state->dts_anon = dtrace_anon_grab();
12933 		ASSERT(state->dts_anon != NULL);
12934 		state = state->dts_anon;
12935 
12936 		/*
12937 		 * We want "grabanon" to be set in the grabbed state, so we'll
12938 		 * copy that option value from the grabbing state into the
12939 		 * grabbed state.
12940 		 */
12941 		state->dts_options[DTRACEOPT_GRABANON] =
12942 		    opt[DTRACEOPT_GRABANON];
12943 
12944 		*cpu = dtrace_anon.dta_beganon;
12945 
12946 		/*
12947 		 * If the anonymous state is active (as it almost certainly
12948 		 * is if the anonymous enabling ultimately matched anything),
12949 		 * we don't allow any further option processing -- but we
12950 		 * don't return failure.
12951 		 */
12952 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12953 			goto out;
12954 	}
12955 
12956 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
12957 	    opt[DTRACEOPT_AGGSIZE] != 0) {
12958 		if (state->dts_aggregations == NULL) {
12959 			/*
12960 			 * We're not going to create an aggregation buffer
12961 			 * because we don't have any ECBs that contain
12962 			 * aggregations -- set this option to 0.
12963 			 */
12964 			opt[DTRACEOPT_AGGSIZE] = 0;
12965 		} else {
12966 			/*
12967 			 * If we have an aggregation buffer, we must also have
12968 			 * a buffer to use as scratch.
12969 			 */
12970 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
12971 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
12972 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
12973 			}
12974 		}
12975 	}
12976 
12977 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
12978 	    opt[DTRACEOPT_SPECSIZE] != 0) {
12979 		if (!state->dts_speculates) {
12980 			/*
12981 			 * We're not going to create speculation buffers
12982 			 * because we don't have any ECBs that actually
12983 			 * speculate -- set the speculation size to 0.
12984 			 */
12985 			opt[DTRACEOPT_SPECSIZE] = 0;
12986 		}
12987 	}
12988 
12989 	/*
12990 	 * The bare minimum size for any buffer that we're actually going to
12991 	 * do anything to is sizeof (uint64_t).
12992 	 */
12993 	sz = sizeof (uint64_t);
12994 
12995 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
12996 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
12997 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
12998 		/*
12999 		 * A buffer size has been explicitly set to 0 (or to a size
13000 		 * that will be adjusted to 0) and we need the space -- we
13001 		 * need to return failure.  We return ENOSPC to differentiate
13002 		 * it from failing to allocate a buffer due to failure to meet
13003 		 * the reserve (for which we return E2BIG).
13004 		 */
13005 		rval = ENOSPC;
13006 		goto out;
13007 	}
13008 
13009 	if ((rval = dtrace_state_buffers(state)) != 0)
13010 		goto err;
13011 
13012 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
13013 		sz = dtrace_dstate_defsize;
13014 
13015 	do {
13016 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
13017 
13018 		if (rval == 0)
13019 			break;
13020 
13021 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13022 			goto err;
13023 	} while (sz >>= 1);
13024 
13025 	opt[DTRACEOPT_DYNVARSIZE] = sz;
13026 
13027 	if (rval != 0)
13028 		goto err;
13029 
13030 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
13031 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
13032 
13033 	if (opt[DTRACEOPT_CLEANRATE] == 0)
13034 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13035 
13036 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
13037 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
13038 
13039 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
13040 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
13041 
13042 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
13043 	hdlr.cyh_arg = state;
13044 	hdlr.cyh_level = CY_LOW_LEVEL;
13045 
13046 	when.cyt_when = 0;
13047 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
13048 
13049 	state->dts_cleaner = cyclic_add(&hdlr, &when);
13050 
13051 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
13052 	hdlr.cyh_arg = state;
13053 	hdlr.cyh_level = CY_LOW_LEVEL;
13054 
13055 	when.cyt_when = 0;
13056 	when.cyt_interval = dtrace_deadman_interval;
13057 
13058 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
13059 	state->dts_deadman = cyclic_add(&hdlr, &when);
13060 
13061 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
13062 
13063 	/*
13064 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
13065 	 * interrupts here both to record the CPU on which we fired the BEGIN
13066 	 * probe (the data from this CPU will be processed first at user
13067 	 * level) and to manually activate the buffer for this CPU.
13068 	 */
13069 	cookie = dtrace_interrupt_disable();
13070 	*cpu = CPU->cpu_id;
13071 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
13072 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
13073 
13074 	dtrace_probe(dtrace_probeid_begin,
13075 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13076 	dtrace_interrupt_enable(cookie);
13077 	/*
13078 	 * We may have had an exit action from a BEGIN probe; only change our
13079 	 * state to ACTIVE if we're still in WARMUP.
13080 	 */
13081 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
13082 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
13083 
13084 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
13085 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
13086 
13087 	/*
13088 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
13089 	 * want each CPU to transition its principal buffer out of the
13090 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
13091 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
13092 	 * atomically transition from processing none of a state's ECBs to
13093 	 * processing all of them.
13094 	 */
13095 	dtrace_xcall(DTRACE_CPUALL,
13096 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
13097 	goto out;
13098 
13099 err:
13100 	dtrace_buffer_free(state->dts_buffer);
13101 	dtrace_buffer_free(state->dts_aggbuffer);
13102 
13103 	if ((nspec = state->dts_nspeculations) == 0) {
13104 		ASSERT(state->dts_speculations == NULL);
13105 		goto out;
13106 	}
13107 
13108 	spec = state->dts_speculations;
13109 	ASSERT(spec != NULL);
13110 
13111 	for (i = 0; i < state->dts_nspeculations; i++) {
13112 		if ((buf = spec[i].dtsp_buffer) == NULL)
13113 			break;
13114 
13115 		dtrace_buffer_free(buf);
13116 		kmem_free(buf, bufsize);
13117 	}
13118 
13119 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13120 	state->dts_nspeculations = 0;
13121 	state->dts_speculations = NULL;
13122 
13123 out:
13124 	mutex_exit(&dtrace_lock);
13125 	mutex_exit(&cpu_lock);
13126 
13127 	return (rval);
13128 }
13129 
13130 static int
13131 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
13132 {
13133 	dtrace_icookie_t cookie;
13134 
13135 	ASSERT(MUTEX_HELD(&dtrace_lock));
13136 
13137 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
13138 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
13139 		return (EINVAL);
13140 
13141 	/*
13142 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
13143 	 * to be sure that every CPU has seen it.  See below for the details
13144 	 * on why this is done.
13145 	 */
13146 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
13147 	dtrace_sync();
13148 
13149 	/*
13150 	 * By this point, it is impossible for any CPU to be still processing
13151 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
13152 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
13153 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
13154 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
13155 	 * iff we're in the END probe.
13156 	 */
13157 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
13158 	dtrace_sync();
13159 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
13160 
13161 	/*
13162 	 * Finally, we can release the reserve and call the END probe.  We
13163 	 * disable interrupts across calling the END probe to allow us to
13164 	 * return the CPU on which we actually called the END probe.  This
13165 	 * allows user-land to be sure that this CPU's principal buffer is
13166 	 * processed last.
13167 	 */
13168 	state->dts_reserve = 0;
13169 
13170 	cookie = dtrace_interrupt_disable();
13171 	*cpu = CPU->cpu_id;
13172 	dtrace_probe(dtrace_probeid_end,
13173 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
13174 	dtrace_interrupt_enable(cookie);
13175 
13176 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
13177 	dtrace_sync();
13178 
13179 	return (0);
13180 }
13181 
13182 static int
13183 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
13184     dtrace_optval_t val)
13185 {
13186 	ASSERT(MUTEX_HELD(&dtrace_lock));
13187 
13188 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
13189 		return (EBUSY);
13190 
13191 	if (option >= DTRACEOPT_MAX)
13192 		return (EINVAL);
13193 
13194 	if (option != DTRACEOPT_CPU && val < 0)
13195 		return (EINVAL);
13196 
13197 	switch (option) {
13198 	case DTRACEOPT_DESTRUCTIVE:
13199 		if (dtrace_destructive_disallow)
13200 			return (EACCES);
13201 
13202 		state->dts_cred.dcr_destructive = 1;
13203 		break;
13204 
13205 	case DTRACEOPT_BUFSIZE:
13206 	case DTRACEOPT_DYNVARSIZE:
13207 	case DTRACEOPT_AGGSIZE:
13208 	case DTRACEOPT_SPECSIZE:
13209 	case DTRACEOPT_STRSIZE:
13210 		if (val < 0)
13211 			return (EINVAL);
13212 
13213 		if (val >= LONG_MAX) {
13214 			/*
13215 			 * If this is an otherwise negative value, set it to
13216 			 * the highest multiple of 128m less than LONG_MAX.
13217 			 * Technically, we're adjusting the size without
13218 			 * regard to the buffer resizing policy, but in fact,
13219 			 * this has no effect -- if we set the buffer size to
13220 			 * ~LONG_MAX and the buffer policy is ultimately set to
13221 			 * be "manual", the buffer allocation is guaranteed to
13222 			 * fail, if only because the allocation requires two
13223 			 * buffers.  (We set the the size to the highest
13224 			 * multiple of 128m because it ensures that the size
13225 			 * will remain a multiple of a megabyte when
13226 			 * repeatedly halved -- all the way down to 15m.)
13227 			 */
13228 			val = LONG_MAX - (1 << 27) + 1;
13229 		}
13230 	}
13231 
13232 	state->dts_options[option] = val;
13233 
13234 	return (0);
13235 }
13236 
13237 static void
13238 dtrace_state_destroy(dtrace_state_t *state)
13239 {
13240 	dtrace_ecb_t *ecb;
13241 	dtrace_vstate_t *vstate = &state->dts_vstate;
13242 	minor_t minor = getminor(state->dts_dev);
13243 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
13244 	dtrace_speculation_t *spec = state->dts_speculations;
13245 	int nspec = state->dts_nspeculations;
13246 	uint32_t match;
13247 
13248 	ASSERT(MUTEX_HELD(&dtrace_lock));
13249 	ASSERT(MUTEX_HELD(&cpu_lock));
13250 
13251 	/*
13252 	 * First, retract any retained enablings for this state.
13253 	 */
13254 	dtrace_enabling_retract(state);
13255 	ASSERT(state->dts_nretained == 0);
13256 
13257 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
13258 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
13259 		/*
13260 		 * We have managed to come into dtrace_state_destroy() on a
13261 		 * hot enabling -- almost certainly because of a disorderly
13262 		 * shutdown of a consumer.  (That is, a consumer that is
13263 		 * exiting without having called dtrace_stop().) In this case,
13264 		 * we're going to set our activity to be KILLED, and then
13265 		 * issue a sync to be sure that everyone is out of probe
13266 		 * context before we start blowing away ECBs.
13267 		 */
13268 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
13269 		dtrace_sync();
13270 	}
13271 
13272 	/*
13273 	 * Release the credential hold we took in dtrace_state_create().
13274 	 */
13275 	if (state->dts_cred.dcr_cred != NULL)
13276 		crfree(state->dts_cred.dcr_cred);
13277 
13278 	/*
13279 	 * Now we can safely disable and destroy any enabled probes.  Because
13280 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
13281 	 * (especially if they're all enabled), we take two passes through the
13282 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
13283 	 * in the second we disable whatever is left over.
13284 	 */
13285 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
13286 		for (i = 0; i < state->dts_necbs; i++) {
13287 			if ((ecb = state->dts_ecbs[i]) == NULL)
13288 				continue;
13289 
13290 			if (match && ecb->dte_probe != NULL) {
13291 				dtrace_probe_t *probe = ecb->dte_probe;
13292 				dtrace_provider_t *prov = probe->dtpr_provider;
13293 
13294 				if (!(prov->dtpv_priv.dtpp_flags & match))
13295 					continue;
13296 			}
13297 
13298 			dtrace_ecb_disable(ecb);
13299 			dtrace_ecb_destroy(ecb);
13300 		}
13301 
13302 		if (!match)
13303 			break;
13304 	}
13305 
13306 	/*
13307 	 * Before we free the buffers, perform one more sync to assure that
13308 	 * every CPU is out of probe context.
13309 	 */
13310 	dtrace_sync();
13311 
13312 	dtrace_buffer_free(state->dts_buffer);
13313 	dtrace_buffer_free(state->dts_aggbuffer);
13314 
13315 	for (i = 0; i < nspec; i++)
13316 		dtrace_buffer_free(spec[i].dtsp_buffer);
13317 
13318 	if (state->dts_cleaner != CYCLIC_NONE)
13319 		cyclic_remove(state->dts_cleaner);
13320 
13321 	if (state->dts_deadman != CYCLIC_NONE)
13322 		cyclic_remove(state->dts_deadman);
13323 
13324 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
13325 	dtrace_vstate_fini(vstate);
13326 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
13327 
13328 	if (state->dts_aggregations != NULL) {
13329 #ifdef DEBUG
13330 		for (i = 0; i < state->dts_naggregations; i++)
13331 			ASSERT(state->dts_aggregations[i] == NULL);
13332 #endif
13333 		ASSERT(state->dts_naggregations > 0);
13334 		kmem_free(state->dts_aggregations,
13335 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
13336 	}
13337 
13338 	kmem_free(state->dts_buffer, bufsize);
13339 	kmem_free(state->dts_aggbuffer, bufsize);
13340 
13341 	for (i = 0; i < nspec; i++)
13342 		kmem_free(spec[i].dtsp_buffer, bufsize);
13343 
13344 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
13345 
13346 	dtrace_format_destroy(state);
13347 
13348 	vmem_destroy(state->dts_aggid_arena);
13349 	ddi_soft_state_free(dtrace_softstate, minor);
13350 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13351 }
13352 
13353 /*
13354  * DTrace Anonymous Enabling Functions
13355  */
13356 static dtrace_state_t *
13357 dtrace_anon_grab(void)
13358 {
13359 	dtrace_state_t *state;
13360 
13361 	ASSERT(MUTEX_HELD(&dtrace_lock));
13362 
13363 	if ((state = dtrace_anon.dta_state) == NULL) {
13364 		ASSERT(dtrace_anon.dta_enabling == NULL);
13365 		return (NULL);
13366 	}
13367 
13368 	ASSERT(dtrace_anon.dta_enabling != NULL);
13369 	ASSERT(dtrace_retained != NULL);
13370 
13371 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
13372 	dtrace_anon.dta_enabling = NULL;
13373 	dtrace_anon.dta_state = NULL;
13374 
13375 	return (state);
13376 }
13377 
13378 static void
13379 dtrace_anon_property(void)
13380 {
13381 	int i, rv;
13382 	dtrace_state_t *state;
13383 	dof_hdr_t *dof;
13384 	char c[32];		/* enough for "dof-data-" + digits */
13385 
13386 	ASSERT(MUTEX_HELD(&dtrace_lock));
13387 	ASSERT(MUTEX_HELD(&cpu_lock));
13388 
13389 	for (i = 0; ; i++) {
13390 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
13391 
13392 		dtrace_err_verbose = 1;
13393 
13394 		if ((dof = dtrace_dof_property(c)) == NULL) {
13395 			dtrace_err_verbose = 0;
13396 			break;
13397 		}
13398 
13399 		/*
13400 		 * We want to create anonymous state, so we need to transition
13401 		 * the kernel debugger to indicate that DTrace is active.  If
13402 		 * this fails (e.g. because the debugger has modified text in
13403 		 * some way), we won't continue with the processing.
13404 		 */
13405 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
13406 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
13407 			    "enabling ignored.");
13408 			dtrace_dof_destroy(dof);
13409 			break;
13410 		}
13411 
13412 		/*
13413 		 * If we haven't allocated an anonymous state, we'll do so now.
13414 		 */
13415 		if ((state = dtrace_anon.dta_state) == NULL) {
13416 			state = dtrace_state_create(NULL, NULL);
13417 			dtrace_anon.dta_state = state;
13418 
13419 			if (state == NULL) {
13420 				/*
13421 				 * This basically shouldn't happen:  the only
13422 				 * failure mode from dtrace_state_create() is a
13423 				 * failure of ddi_soft_state_zalloc() that
13424 				 * itself should never happen.  Still, the
13425 				 * interface allows for a failure mode, and
13426 				 * we want to fail as gracefully as possible:
13427 				 * we'll emit an error message and cease
13428 				 * processing anonymous state in this case.
13429 				 */
13430 				cmn_err(CE_WARN, "failed to create "
13431 				    "anonymous state");
13432 				dtrace_dof_destroy(dof);
13433 				break;
13434 			}
13435 		}
13436 
13437 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
13438 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
13439 
13440 		if (rv == 0)
13441 			rv = dtrace_dof_options(dof, state);
13442 
13443 		dtrace_err_verbose = 0;
13444 		dtrace_dof_destroy(dof);
13445 
13446 		if (rv != 0) {
13447 			/*
13448 			 * This is malformed DOF; chuck any anonymous state
13449 			 * that we created.
13450 			 */
13451 			ASSERT(dtrace_anon.dta_enabling == NULL);
13452 			dtrace_state_destroy(state);
13453 			dtrace_anon.dta_state = NULL;
13454 			break;
13455 		}
13456 
13457 		ASSERT(dtrace_anon.dta_enabling != NULL);
13458 	}
13459 
13460 	if (dtrace_anon.dta_enabling != NULL) {
13461 		int rval;
13462 
13463 		/*
13464 		 * dtrace_enabling_retain() can only fail because we are
13465 		 * trying to retain more enablings than are allowed -- but
13466 		 * we only have one anonymous enabling, and we are guaranteed
13467 		 * to be allowed at least one retained enabling; we assert
13468 		 * that dtrace_enabling_retain() returns success.
13469 		 */
13470 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
13471 		ASSERT(rval == 0);
13472 
13473 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
13474 	}
13475 }
13476 
13477 /*
13478  * DTrace Helper Functions
13479  */
13480 static void
13481 dtrace_helper_trace(dtrace_helper_action_t *helper,
13482     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
13483 {
13484 	uint32_t size, next, nnext, i;
13485 	dtrace_helptrace_t *ent;
13486 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13487 
13488 	if (!dtrace_helptrace_enabled)
13489 		return;
13490 
13491 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
13492 
13493 	/*
13494 	 * What would a tracing framework be without its own tracing
13495 	 * framework?  (Well, a hell of a lot simpler, for starters...)
13496 	 */
13497 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
13498 	    sizeof (uint64_t) - sizeof (uint64_t);
13499 
13500 	/*
13501 	 * Iterate until we can allocate a slot in the trace buffer.
13502 	 */
13503 	do {
13504 		next = dtrace_helptrace_next;
13505 
13506 		if (next + size < dtrace_helptrace_bufsize) {
13507 			nnext = next + size;
13508 		} else {
13509 			nnext = size;
13510 		}
13511 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
13512 
13513 	/*
13514 	 * We have our slot; fill it in.
13515 	 */
13516 	if (nnext == size)
13517 		next = 0;
13518 
13519 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
13520 	ent->dtht_helper = helper;
13521 	ent->dtht_where = where;
13522 	ent->dtht_nlocals = vstate->dtvs_nlocals;
13523 
13524 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
13525 	    mstate->dtms_fltoffs : -1;
13526 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
13527 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
13528 
13529 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
13530 		dtrace_statvar_t *svar;
13531 
13532 		if ((svar = vstate->dtvs_locals[i]) == NULL)
13533 			continue;
13534 
13535 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
13536 		ent->dtht_locals[i] =
13537 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
13538 	}
13539 }
13540 
13541 static uint64_t
13542 dtrace_helper(int which, dtrace_mstate_t *mstate,
13543     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
13544 {
13545 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13546 	uint64_t sarg0 = mstate->dtms_arg[0];
13547 	uint64_t sarg1 = mstate->dtms_arg[1];
13548 	uint64_t rval;
13549 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
13550 	dtrace_helper_action_t *helper;
13551 	dtrace_vstate_t *vstate;
13552 	dtrace_difo_t *pred;
13553 	int i, trace = dtrace_helptrace_enabled;
13554 
13555 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
13556 
13557 	if (helpers == NULL)
13558 		return (0);
13559 
13560 	if ((helper = helpers->dthps_actions[which]) == NULL)
13561 		return (0);
13562 
13563 	vstate = &helpers->dthps_vstate;
13564 	mstate->dtms_arg[0] = arg0;
13565 	mstate->dtms_arg[1] = arg1;
13566 
13567 	/*
13568 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
13569 	 * we'll call the corresponding actions.  Note that the below calls
13570 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
13571 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
13572 	 * the stored DIF offset with its own (which is the desired behavior).
13573 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
13574 	 * from machine state; this is okay, too.
13575 	 */
13576 	for (; helper != NULL; helper = helper->dtha_next) {
13577 		if ((pred = helper->dtha_predicate) != NULL) {
13578 			if (trace)
13579 				dtrace_helper_trace(helper, mstate, vstate, 0);
13580 
13581 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
13582 				goto next;
13583 
13584 			if (*flags & CPU_DTRACE_FAULT)
13585 				goto err;
13586 		}
13587 
13588 		for (i = 0; i < helper->dtha_nactions; i++) {
13589 			if (trace)
13590 				dtrace_helper_trace(helper,
13591 				    mstate, vstate, i + 1);
13592 
13593 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
13594 			    mstate, vstate, state);
13595 
13596 			if (*flags & CPU_DTRACE_FAULT)
13597 				goto err;
13598 		}
13599 
13600 next:
13601 		if (trace)
13602 			dtrace_helper_trace(helper, mstate, vstate,
13603 			    DTRACE_HELPTRACE_NEXT);
13604 	}
13605 
13606 	if (trace)
13607 		dtrace_helper_trace(helper, mstate, vstate,
13608 		    DTRACE_HELPTRACE_DONE);
13609 
13610 	/*
13611 	 * Restore the arg0 that we saved upon entry.
13612 	 */
13613 	mstate->dtms_arg[0] = sarg0;
13614 	mstate->dtms_arg[1] = sarg1;
13615 
13616 	return (rval);
13617 
13618 err:
13619 	if (trace)
13620 		dtrace_helper_trace(helper, mstate, vstate,
13621 		    DTRACE_HELPTRACE_ERR);
13622 
13623 	/*
13624 	 * Restore the arg0 that we saved upon entry.
13625 	 */
13626 	mstate->dtms_arg[0] = sarg0;
13627 	mstate->dtms_arg[1] = sarg1;
13628 
13629 	return (NULL);
13630 }
13631 
13632 static void
13633 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
13634     dtrace_vstate_t *vstate)
13635 {
13636 	int i;
13637 
13638 	if (helper->dtha_predicate != NULL)
13639 		dtrace_difo_release(helper->dtha_predicate, vstate);
13640 
13641 	for (i = 0; i < helper->dtha_nactions; i++) {
13642 		ASSERT(helper->dtha_actions[i] != NULL);
13643 		dtrace_difo_release(helper->dtha_actions[i], vstate);
13644 	}
13645 
13646 	kmem_free(helper->dtha_actions,
13647 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
13648 	kmem_free(helper, sizeof (dtrace_helper_action_t));
13649 }
13650 
13651 static int
13652 dtrace_helper_destroygen(int gen)
13653 {
13654 	proc_t *p = curproc;
13655 	dtrace_helpers_t *help = p->p_dtrace_helpers;
13656 	dtrace_vstate_t *vstate;
13657 	int i;
13658 
13659 	ASSERT(MUTEX_HELD(&dtrace_lock));
13660 
13661 	if (help == NULL || gen > help->dthps_generation)
13662 		return (EINVAL);
13663 
13664 	vstate = &help->dthps_vstate;
13665 
13666 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13667 		dtrace_helper_action_t *last = NULL, *h, *next;
13668 
13669 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13670 			next = h->dtha_next;
13671 
13672 			if (h->dtha_generation == gen) {
13673 				if (last != NULL) {
13674 					last->dtha_next = next;
13675 				} else {
13676 					help->dthps_actions[i] = next;
13677 				}
13678 
13679 				dtrace_helper_action_destroy(h, vstate);
13680 			} else {
13681 				last = h;
13682 			}
13683 		}
13684 	}
13685 
13686 	/*
13687 	 * Interate until we've cleared out all helper providers with the
13688 	 * given generation number.
13689 	 */
13690 	for (;;) {
13691 		dtrace_helper_provider_t *prov;
13692 
13693 		/*
13694 		 * Look for a helper provider with the right generation. We
13695 		 * have to start back at the beginning of the list each time
13696 		 * because we drop dtrace_lock. It's unlikely that we'll make
13697 		 * more than two passes.
13698 		 */
13699 		for (i = 0; i < help->dthps_nprovs; i++) {
13700 			prov = help->dthps_provs[i];
13701 
13702 			if (prov->dthp_generation == gen)
13703 				break;
13704 		}
13705 
13706 		/*
13707 		 * If there were no matches, we're done.
13708 		 */
13709 		if (i == help->dthps_nprovs)
13710 			break;
13711 
13712 		/*
13713 		 * Move the last helper provider into this slot.
13714 		 */
13715 		help->dthps_nprovs--;
13716 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
13717 		help->dthps_provs[help->dthps_nprovs] = NULL;
13718 
13719 		mutex_exit(&dtrace_lock);
13720 
13721 		/*
13722 		 * If we have a meta provider, remove this helper provider.
13723 		 */
13724 		mutex_enter(&dtrace_meta_lock);
13725 		if (dtrace_meta_pid != NULL) {
13726 			ASSERT(dtrace_deferred_pid == NULL);
13727 			dtrace_helper_provider_remove(&prov->dthp_prov,
13728 			    p->p_pid);
13729 		}
13730 		mutex_exit(&dtrace_meta_lock);
13731 
13732 		dtrace_helper_provider_destroy(prov);
13733 
13734 		mutex_enter(&dtrace_lock);
13735 	}
13736 
13737 	return (0);
13738 }
13739 
13740 static int
13741 dtrace_helper_validate(dtrace_helper_action_t *helper)
13742 {
13743 	int err = 0, i;
13744 	dtrace_difo_t *dp;
13745 
13746 	if ((dp = helper->dtha_predicate) != NULL)
13747 		err += dtrace_difo_validate_helper(dp);
13748 
13749 	for (i = 0; i < helper->dtha_nactions; i++)
13750 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
13751 
13752 	return (err == 0);
13753 }
13754 
13755 static int
13756 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
13757 {
13758 	dtrace_helpers_t *help;
13759 	dtrace_helper_action_t *helper, *last;
13760 	dtrace_actdesc_t *act;
13761 	dtrace_vstate_t *vstate;
13762 	dtrace_predicate_t *pred;
13763 	int count = 0, nactions = 0, i;
13764 
13765 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
13766 		return (EINVAL);
13767 
13768 	help = curproc->p_dtrace_helpers;
13769 	last = help->dthps_actions[which];
13770 	vstate = &help->dthps_vstate;
13771 
13772 	for (count = 0; last != NULL; last = last->dtha_next) {
13773 		count++;
13774 		if (last->dtha_next == NULL)
13775 			break;
13776 	}
13777 
13778 	/*
13779 	 * If we already have dtrace_helper_actions_max helper actions for this
13780 	 * helper action type, we'll refuse to add a new one.
13781 	 */
13782 	if (count >= dtrace_helper_actions_max)
13783 		return (ENOSPC);
13784 
13785 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
13786 	helper->dtha_generation = help->dthps_generation;
13787 
13788 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
13789 		ASSERT(pred->dtp_difo != NULL);
13790 		dtrace_difo_hold(pred->dtp_difo);
13791 		helper->dtha_predicate = pred->dtp_difo;
13792 	}
13793 
13794 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
13795 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
13796 			goto err;
13797 
13798 		if (act->dtad_difo == NULL)
13799 			goto err;
13800 
13801 		nactions++;
13802 	}
13803 
13804 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
13805 	    (helper->dtha_nactions = nactions), KM_SLEEP);
13806 
13807 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
13808 		dtrace_difo_hold(act->dtad_difo);
13809 		helper->dtha_actions[i++] = act->dtad_difo;
13810 	}
13811 
13812 	if (!dtrace_helper_validate(helper))
13813 		goto err;
13814 
13815 	if (last == NULL) {
13816 		help->dthps_actions[which] = helper;
13817 	} else {
13818 		last->dtha_next = helper;
13819 	}
13820 
13821 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
13822 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
13823 		dtrace_helptrace_next = 0;
13824 	}
13825 
13826 	return (0);
13827 err:
13828 	dtrace_helper_action_destroy(helper, vstate);
13829 	return (EINVAL);
13830 }
13831 
13832 static void
13833 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
13834     dof_helper_t *dofhp)
13835 {
13836 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
13837 
13838 	mutex_enter(&dtrace_meta_lock);
13839 	mutex_enter(&dtrace_lock);
13840 
13841 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
13842 		/*
13843 		 * If the dtrace module is loaded but not attached, or if
13844 		 * there aren't isn't a meta provider registered to deal with
13845 		 * these provider descriptions, we need to postpone creating
13846 		 * the actual providers until later.
13847 		 */
13848 
13849 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
13850 		    dtrace_deferred_pid != help) {
13851 			help->dthps_deferred = 1;
13852 			help->dthps_pid = p->p_pid;
13853 			help->dthps_next = dtrace_deferred_pid;
13854 			help->dthps_prev = NULL;
13855 			if (dtrace_deferred_pid != NULL)
13856 				dtrace_deferred_pid->dthps_prev = help;
13857 			dtrace_deferred_pid = help;
13858 		}
13859 
13860 		mutex_exit(&dtrace_lock);
13861 
13862 	} else if (dofhp != NULL) {
13863 		/*
13864 		 * If the dtrace module is loaded and we have a particular
13865 		 * helper provider description, pass that off to the
13866 		 * meta provider.
13867 		 */
13868 
13869 		mutex_exit(&dtrace_lock);
13870 
13871 		dtrace_helper_provide(dofhp, p->p_pid);
13872 
13873 	} else {
13874 		/*
13875 		 * Otherwise, just pass all the helper provider descriptions
13876 		 * off to the meta provider.
13877 		 */
13878 
13879 		int i;
13880 		mutex_exit(&dtrace_lock);
13881 
13882 		for (i = 0; i < help->dthps_nprovs; i++) {
13883 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
13884 			    p->p_pid);
13885 		}
13886 	}
13887 
13888 	mutex_exit(&dtrace_meta_lock);
13889 }
13890 
13891 static int
13892 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
13893 {
13894 	dtrace_helpers_t *help;
13895 	dtrace_helper_provider_t *hprov, **tmp_provs;
13896 	uint_t tmp_maxprovs, i;
13897 
13898 	ASSERT(MUTEX_HELD(&dtrace_lock));
13899 
13900 	help = curproc->p_dtrace_helpers;
13901 	ASSERT(help != NULL);
13902 
13903 	/*
13904 	 * If we already have dtrace_helper_providers_max helper providers,
13905 	 * we're refuse to add a new one.
13906 	 */
13907 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
13908 		return (ENOSPC);
13909 
13910 	/*
13911 	 * Check to make sure this isn't a duplicate.
13912 	 */
13913 	for (i = 0; i < help->dthps_nprovs; i++) {
13914 		if (dofhp->dofhp_addr ==
13915 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
13916 			return (EALREADY);
13917 	}
13918 
13919 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
13920 	hprov->dthp_prov = *dofhp;
13921 	hprov->dthp_ref = 1;
13922 	hprov->dthp_generation = gen;
13923 
13924 	/*
13925 	 * Allocate a bigger table for helper providers if it's already full.
13926 	 */
13927 	if (help->dthps_maxprovs == help->dthps_nprovs) {
13928 		tmp_maxprovs = help->dthps_maxprovs;
13929 		tmp_provs = help->dthps_provs;
13930 
13931 		if (help->dthps_maxprovs == 0)
13932 			help->dthps_maxprovs = 2;
13933 		else
13934 			help->dthps_maxprovs *= 2;
13935 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
13936 			help->dthps_maxprovs = dtrace_helper_providers_max;
13937 
13938 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
13939 
13940 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
13941 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13942 
13943 		if (tmp_provs != NULL) {
13944 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
13945 			    sizeof (dtrace_helper_provider_t *));
13946 			kmem_free(tmp_provs, tmp_maxprovs *
13947 			    sizeof (dtrace_helper_provider_t *));
13948 		}
13949 	}
13950 
13951 	help->dthps_provs[help->dthps_nprovs] = hprov;
13952 	help->dthps_nprovs++;
13953 
13954 	return (0);
13955 }
13956 
13957 static void
13958 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
13959 {
13960 	mutex_enter(&dtrace_lock);
13961 
13962 	if (--hprov->dthp_ref == 0) {
13963 		dof_hdr_t *dof;
13964 		mutex_exit(&dtrace_lock);
13965 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
13966 		dtrace_dof_destroy(dof);
13967 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
13968 	} else {
13969 		mutex_exit(&dtrace_lock);
13970 	}
13971 }
13972 
13973 static int
13974 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
13975 {
13976 	uintptr_t daddr = (uintptr_t)dof;
13977 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
13978 	dof_provider_t *provider;
13979 	dof_probe_t *probe;
13980 	uint8_t *arg;
13981 	char *strtab, *typestr;
13982 	dof_stridx_t typeidx;
13983 	size_t typesz;
13984 	uint_t nprobes, j, k;
13985 
13986 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
13987 
13988 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
13989 		dtrace_dof_error(dof, "misaligned section offset");
13990 		return (-1);
13991 	}
13992 
13993 	/*
13994 	 * The section needs to be large enough to contain the DOF provider
13995 	 * structure appropriate for the given version.
13996 	 */
13997 	if (sec->dofs_size <
13998 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
13999 	    offsetof(dof_provider_t, dofpv_prenoffs) :
14000 	    sizeof (dof_provider_t))) {
14001 		dtrace_dof_error(dof, "provider section too small");
14002 		return (-1);
14003 	}
14004 
14005 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
14006 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
14007 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
14008 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
14009 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
14010 
14011 	if (str_sec == NULL || prb_sec == NULL ||
14012 	    arg_sec == NULL || off_sec == NULL)
14013 		return (-1);
14014 
14015 	enoff_sec = NULL;
14016 
14017 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
14018 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
14019 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
14020 	    provider->dofpv_prenoffs)) == NULL)
14021 		return (-1);
14022 
14023 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
14024 
14025 	if (provider->dofpv_name >= str_sec->dofs_size ||
14026 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
14027 		dtrace_dof_error(dof, "invalid provider name");
14028 		return (-1);
14029 	}
14030 
14031 	if (prb_sec->dofs_entsize == 0 ||
14032 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
14033 		dtrace_dof_error(dof, "invalid entry size");
14034 		return (-1);
14035 	}
14036 
14037 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
14038 		dtrace_dof_error(dof, "misaligned entry size");
14039 		return (-1);
14040 	}
14041 
14042 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
14043 		dtrace_dof_error(dof, "invalid entry size");
14044 		return (-1);
14045 	}
14046 
14047 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
14048 		dtrace_dof_error(dof, "misaligned section offset");
14049 		return (-1);
14050 	}
14051 
14052 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
14053 		dtrace_dof_error(dof, "invalid entry size");
14054 		return (-1);
14055 	}
14056 
14057 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
14058 
14059 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
14060 
14061 	/*
14062 	 * Take a pass through the probes to check for errors.
14063 	 */
14064 	for (j = 0; j < nprobes; j++) {
14065 		probe = (dof_probe_t *)(uintptr_t)(daddr +
14066 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
14067 
14068 		if (probe->dofpr_func >= str_sec->dofs_size) {
14069 			dtrace_dof_error(dof, "invalid function name");
14070 			return (-1);
14071 		}
14072 
14073 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
14074 			dtrace_dof_error(dof, "function name too long");
14075 			return (-1);
14076 		}
14077 
14078 		if (probe->dofpr_name >= str_sec->dofs_size ||
14079 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
14080 			dtrace_dof_error(dof, "invalid probe name");
14081 			return (-1);
14082 		}
14083 
14084 		/*
14085 		 * The offset count must not wrap the index, and the offsets
14086 		 * must also not overflow the section's data.
14087 		 */
14088 		if (probe->dofpr_offidx + probe->dofpr_noffs <
14089 		    probe->dofpr_offidx ||
14090 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
14091 		    off_sec->dofs_entsize > off_sec->dofs_size) {
14092 			dtrace_dof_error(dof, "invalid probe offset");
14093 			return (-1);
14094 		}
14095 
14096 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
14097 			/*
14098 			 * If there's no is-enabled offset section, make sure
14099 			 * there aren't any is-enabled offsets. Otherwise
14100 			 * perform the same checks as for probe offsets
14101 			 * (immediately above).
14102 			 */
14103 			if (enoff_sec == NULL) {
14104 				if (probe->dofpr_enoffidx != 0 ||
14105 				    probe->dofpr_nenoffs != 0) {
14106 					dtrace_dof_error(dof, "is-enabled "
14107 					    "offsets with null section");
14108 					return (-1);
14109 				}
14110 			} else if (probe->dofpr_enoffidx +
14111 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
14112 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
14113 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
14114 				dtrace_dof_error(dof, "invalid is-enabled "
14115 				    "offset");
14116 				return (-1);
14117 			}
14118 
14119 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
14120 				dtrace_dof_error(dof, "zero probe and "
14121 				    "is-enabled offsets");
14122 				return (-1);
14123 			}
14124 		} else if (probe->dofpr_noffs == 0) {
14125 			dtrace_dof_error(dof, "zero probe offsets");
14126 			return (-1);
14127 		}
14128 
14129 		if (probe->dofpr_argidx + probe->dofpr_xargc <
14130 		    probe->dofpr_argidx ||
14131 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
14132 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
14133 			dtrace_dof_error(dof, "invalid args");
14134 			return (-1);
14135 		}
14136 
14137 		typeidx = probe->dofpr_nargv;
14138 		typestr = strtab + probe->dofpr_nargv;
14139 		for (k = 0; k < probe->dofpr_nargc; k++) {
14140 			if (typeidx >= str_sec->dofs_size) {
14141 				dtrace_dof_error(dof, "bad "
14142 				    "native argument type");
14143 				return (-1);
14144 			}
14145 
14146 			typesz = strlen(typestr) + 1;
14147 			if (typesz > DTRACE_ARGTYPELEN) {
14148 				dtrace_dof_error(dof, "native "
14149 				    "argument type too long");
14150 				return (-1);
14151 			}
14152 			typeidx += typesz;
14153 			typestr += typesz;
14154 		}
14155 
14156 		typeidx = probe->dofpr_xargv;
14157 		typestr = strtab + probe->dofpr_xargv;
14158 		for (k = 0; k < probe->dofpr_xargc; k++) {
14159 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
14160 				dtrace_dof_error(dof, "bad "
14161 				    "native argument index");
14162 				return (-1);
14163 			}
14164 
14165 			if (typeidx >= str_sec->dofs_size) {
14166 				dtrace_dof_error(dof, "bad "
14167 				    "translated argument type");
14168 				return (-1);
14169 			}
14170 
14171 			typesz = strlen(typestr) + 1;
14172 			if (typesz > DTRACE_ARGTYPELEN) {
14173 				dtrace_dof_error(dof, "translated argument "
14174 				    "type too long");
14175 				return (-1);
14176 			}
14177 
14178 			typeidx += typesz;
14179 			typestr += typesz;
14180 		}
14181 	}
14182 
14183 	return (0);
14184 }
14185 
14186 static int
14187 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
14188 {
14189 	dtrace_helpers_t *help;
14190 	dtrace_vstate_t *vstate;
14191 	dtrace_enabling_t *enab = NULL;
14192 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
14193 	uintptr_t daddr = (uintptr_t)dof;
14194 
14195 	ASSERT(MUTEX_HELD(&dtrace_lock));
14196 
14197 	if ((help = curproc->p_dtrace_helpers) == NULL)
14198 		help = dtrace_helpers_create(curproc);
14199 
14200 	vstate = &help->dthps_vstate;
14201 
14202 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
14203 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
14204 		dtrace_dof_destroy(dof);
14205 		return (rv);
14206 	}
14207 
14208 	/*
14209 	 * Look for helper providers and validate their descriptions.
14210 	 */
14211 	if (dhp != NULL) {
14212 		for (i = 0; i < dof->dofh_secnum; i++) {
14213 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
14214 			    dof->dofh_secoff + i * dof->dofh_secsize);
14215 
14216 			if (sec->dofs_type != DOF_SECT_PROVIDER)
14217 				continue;
14218 
14219 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
14220 				dtrace_enabling_destroy(enab);
14221 				dtrace_dof_destroy(dof);
14222 				return (-1);
14223 			}
14224 
14225 			nprovs++;
14226 		}
14227 	}
14228 
14229 	/*
14230 	 * Now we need to walk through the ECB descriptions in the enabling.
14231 	 */
14232 	for (i = 0; i < enab->dten_ndesc; i++) {
14233 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
14234 		dtrace_probedesc_t *desc = &ep->dted_probe;
14235 
14236 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
14237 			continue;
14238 
14239 		if (strcmp(desc->dtpd_mod, "helper") != 0)
14240 			continue;
14241 
14242 		if (strcmp(desc->dtpd_func, "ustack") != 0)
14243 			continue;
14244 
14245 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
14246 		    ep)) != 0) {
14247 			/*
14248 			 * Adding this helper action failed -- we are now going
14249 			 * to rip out the entire generation and return failure.
14250 			 */
14251 			(void) dtrace_helper_destroygen(help->dthps_generation);
14252 			dtrace_enabling_destroy(enab);
14253 			dtrace_dof_destroy(dof);
14254 			return (-1);
14255 		}
14256 
14257 		nhelpers++;
14258 	}
14259 
14260 	if (nhelpers < enab->dten_ndesc)
14261 		dtrace_dof_error(dof, "unmatched helpers");
14262 
14263 	gen = help->dthps_generation++;
14264 	dtrace_enabling_destroy(enab);
14265 
14266 	if (dhp != NULL && nprovs > 0) {
14267 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
14268 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
14269 			mutex_exit(&dtrace_lock);
14270 			dtrace_helper_provider_register(curproc, help, dhp);
14271 			mutex_enter(&dtrace_lock);
14272 
14273 			destroy = 0;
14274 		}
14275 	}
14276 
14277 	if (destroy)
14278 		dtrace_dof_destroy(dof);
14279 
14280 	return (gen);
14281 }
14282 
14283 static dtrace_helpers_t *
14284 dtrace_helpers_create(proc_t *p)
14285 {
14286 	dtrace_helpers_t *help;
14287 
14288 	ASSERT(MUTEX_HELD(&dtrace_lock));
14289 	ASSERT(p->p_dtrace_helpers == NULL);
14290 
14291 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
14292 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
14293 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
14294 
14295 	p->p_dtrace_helpers = help;
14296 	dtrace_helpers++;
14297 
14298 	return (help);
14299 }
14300 
14301 static void
14302 dtrace_helpers_destroy(void)
14303 {
14304 	dtrace_helpers_t *help;
14305 	dtrace_vstate_t *vstate;
14306 	proc_t *p = curproc;
14307 	int i;
14308 
14309 	mutex_enter(&dtrace_lock);
14310 
14311 	ASSERT(p->p_dtrace_helpers != NULL);
14312 	ASSERT(dtrace_helpers > 0);
14313 
14314 	help = p->p_dtrace_helpers;
14315 	vstate = &help->dthps_vstate;
14316 
14317 	/*
14318 	 * We're now going to lose the help from this process.
14319 	 */
14320 	p->p_dtrace_helpers = NULL;
14321 	dtrace_sync();
14322 
14323 	/*
14324 	 * Destory the helper actions.
14325 	 */
14326 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14327 		dtrace_helper_action_t *h, *next;
14328 
14329 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
14330 			next = h->dtha_next;
14331 			dtrace_helper_action_destroy(h, vstate);
14332 			h = next;
14333 		}
14334 	}
14335 
14336 	mutex_exit(&dtrace_lock);
14337 
14338 	/*
14339 	 * Destroy the helper providers.
14340 	 */
14341 	if (help->dthps_maxprovs > 0) {
14342 		mutex_enter(&dtrace_meta_lock);
14343 		if (dtrace_meta_pid != NULL) {
14344 			ASSERT(dtrace_deferred_pid == NULL);
14345 
14346 			for (i = 0; i < help->dthps_nprovs; i++) {
14347 				dtrace_helper_provider_remove(
14348 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
14349 			}
14350 		} else {
14351 			mutex_enter(&dtrace_lock);
14352 			ASSERT(help->dthps_deferred == 0 ||
14353 			    help->dthps_next != NULL ||
14354 			    help->dthps_prev != NULL ||
14355 			    help == dtrace_deferred_pid);
14356 
14357 			/*
14358 			 * Remove the helper from the deferred list.
14359 			 */
14360 			if (help->dthps_next != NULL)
14361 				help->dthps_next->dthps_prev = help->dthps_prev;
14362 			if (help->dthps_prev != NULL)
14363 				help->dthps_prev->dthps_next = help->dthps_next;
14364 			if (dtrace_deferred_pid == help) {
14365 				dtrace_deferred_pid = help->dthps_next;
14366 				ASSERT(help->dthps_prev == NULL);
14367 			}
14368 
14369 			mutex_exit(&dtrace_lock);
14370 		}
14371 
14372 		mutex_exit(&dtrace_meta_lock);
14373 
14374 		for (i = 0; i < help->dthps_nprovs; i++) {
14375 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
14376 		}
14377 
14378 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
14379 		    sizeof (dtrace_helper_provider_t *));
14380 	}
14381 
14382 	mutex_enter(&dtrace_lock);
14383 
14384 	dtrace_vstate_fini(&help->dthps_vstate);
14385 	kmem_free(help->dthps_actions,
14386 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
14387 	kmem_free(help, sizeof (dtrace_helpers_t));
14388 
14389 	--dtrace_helpers;
14390 	mutex_exit(&dtrace_lock);
14391 }
14392 
14393 static void
14394 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
14395 {
14396 	dtrace_helpers_t *help, *newhelp;
14397 	dtrace_helper_action_t *helper, *new, *last;
14398 	dtrace_difo_t *dp;
14399 	dtrace_vstate_t *vstate;
14400 	int i, j, sz, hasprovs = 0;
14401 
14402 	mutex_enter(&dtrace_lock);
14403 	ASSERT(from->p_dtrace_helpers != NULL);
14404 	ASSERT(dtrace_helpers > 0);
14405 
14406 	help = from->p_dtrace_helpers;
14407 	newhelp = dtrace_helpers_create(to);
14408 	ASSERT(to->p_dtrace_helpers != NULL);
14409 
14410 	newhelp->dthps_generation = help->dthps_generation;
14411 	vstate = &newhelp->dthps_vstate;
14412 
14413 	/*
14414 	 * Duplicate the helper actions.
14415 	 */
14416 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14417 		if ((helper = help->dthps_actions[i]) == NULL)
14418 			continue;
14419 
14420 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
14421 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
14422 			    KM_SLEEP);
14423 			new->dtha_generation = helper->dtha_generation;
14424 
14425 			if ((dp = helper->dtha_predicate) != NULL) {
14426 				dp = dtrace_difo_duplicate(dp, vstate);
14427 				new->dtha_predicate = dp;
14428 			}
14429 
14430 			new->dtha_nactions = helper->dtha_nactions;
14431 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
14432 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
14433 
14434 			for (j = 0; j < new->dtha_nactions; j++) {
14435 				dtrace_difo_t *dp = helper->dtha_actions[j];
14436 
14437 				ASSERT(dp != NULL);
14438 				dp = dtrace_difo_duplicate(dp, vstate);
14439 				new->dtha_actions[j] = dp;
14440 			}
14441 
14442 			if (last != NULL) {
14443 				last->dtha_next = new;
14444 			} else {
14445 				newhelp->dthps_actions[i] = new;
14446 			}
14447 
14448 			last = new;
14449 		}
14450 	}
14451 
14452 	/*
14453 	 * Duplicate the helper providers and register them with the
14454 	 * DTrace framework.
14455 	 */
14456 	if (help->dthps_nprovs > 0) {
14457 		newhelp->dthps_nprovs = help->dthps_nprovs;
14458 		newhelp->dthps_maxprovs = help->dthps_nprovs;
14459 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
14460 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
14461 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
14462 			newhelp->dthps_provs[i] = help->dthps_provs[i];
14463 			newhelp->dthps_provs[i]->dthp_ref++;
14464 		}
14465 
14466 		hasprovs = 1;
14467 	}
14468 
14469 	mutex_exit(&dtrace_lock);
14470 
14471 	if (hasprovs)
14472 		dtrace_helper_provider_register(to, newhelp, NULL);
14473 }
14474 
14475 /*
14476  * DTrace Hook Functions
14477  */
14478 static void
14479 dtrace_module_loaded(struct modctl *ctl)
14480 {
14481 	dtrace_provider_t *prv;
14482 
14483 	mutex_enter(&dtrace_provider_lock);
14484 	mutex_enter(&mod_lock);
14485 
14486 	ASSERT(ctl->mod_busy);
14487 
14488 	/*
14489 	 * We're going to call each providers per-module provide operation
14490 	 * specifying only this module.
14491 	 */
14492 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
14493 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
14494 
14495 	mutex_exit(&mod_lock);
14496 	mutex_exit(&dtrace_provider_lock);
14497 
14498 	/*
14499 	 * If we have any retained enablings, we need to match against them.
14500 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
14501 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
14502 	 * module.  (In particular, this happens when loading scheduling
14503 	 * classes.)  So if we have any retained enablings, we need to dispatch
14504 	 * our task queue to do the match for us.
14505 	 */
14506 	mutex_enter(&dtrace_lock);
14507 
14508 	if (dtrace_retained == NULL) {
14509 		mutex_exit(&dtrace_lock);
14510 		return;
14511 	}
14512 
14513 	(void) taskq_dispatch(dtrace_taskq,
14514 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
14515 
14516 	mutex_exit(&dtrace_lock);
14517 
14518 	/*
14519 	 * And now, for a little heuristic sleaze:  in general, we want to
14520 	 * match modules as soon as they load.  However, we cannot guarantee
14521 	 * this, because it would lead us to the lock ordering violation
14522 	 * outlined above.  The common case, of course, is that cpu_lock is
14523 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
14524 	 * long enough for the task queue to do its work.  If it's not, it's
14525 	 * not a serious problem -- it just means that the module that we
14526 	 * just loaded may not be immediately instrumentable.
14527 	 */
14528 	delay(1);
14529 }
14530 
14531 static void
14532 dtrace_module_unloaded(struct modctl *ctl)
14533 {
14534 	dtrace_probe_t template, *probe, *first, *next;
14535 	dtrace_provider_t *prov;
14536 
14537 	template.dtpr_mod = ctl->mod_modname;
14538 
14539 	mutex_enter(&dtrace_provider_lock);
14540 	mutex_enter(&mod_lock);
14541 	mutex_enter(&dtrace_lock);
14542 
14543 	if (dtrace_bymod == NULL) {
14544 		/*
14545 		 * The DTrace module is loaded (obviously) but not attached;
14546 		 * we don't have any work to do.
14547 		 */
14548 		mutex_exit(&dtrace_provider_lock);
14549 		mutex_exit(&mod_lock);
14550 		mutex_exit(&dtrace_lock);
14551 		return;
14552 	}
14553 
14554 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
14555 	    probe != NULL; probe = probe->dtpr_nextmod) {
14556 		if (probe->dtpr_ecb != NULL) {
14557 			mutex_exit(&dtrace_provider_lock);
14558 			mutex_exit(&mod_lock);
14559 			mutex_exit(&dtrace_lock);
14560 
14561 			/*
14562 			 * This shouldn't _actually_ be possible -- we're
14563 			 * unloading a module that has an enabled probe in it.
14564 			 * (It's normally up to the provider to make sure that
14565 			 * this can't happen.)  However, because dtps_enable()
14566 			 * doesn't have a failure mode, there can be an
14567 			 * enable/unload race.  Upshot:  we don't want to
14568 			 * assert, but we're not going to disable the
14569 			 * probe, either.
14570 			 */
14571 			if (dtrace_err_verbose) {
14572 				cmn_err(CE_WARN, "unloaded module '%s' had "
14573 				    "enabled probes", ctl->mod_modname);
14574 			}
14575 
14576 			return;
14577 		}
14578 	}
14579 
14580 	probe = first;
14581 
14582 	for (first = NULL; probe != NULL; probe = next) {
14583 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
14584 
14585 		dtrace_probes[probe->dtpr_id - 1] = NULL;
14586 
14587 		next = probe->dtpr_nextmod;
14588 		dtrace_hash_remove(dtrace_bymod, probe);
14589 		dtrace_hash_remove(dtrace_byfunc, probe);
14590 		dtrace_hash_remove(dtrace_byname, probe);
14591 
14592 		if (first == NULL) {
14593 			first = probe;
14594 			probe->dtpr_nextmod = NULL;
14595 		} else {
14596 			probe->dtpr_nextmod = first;
14597 			first = probe;
14598 		}
14599 	}
14600 
14601 	/*
14602 	 * We've removed all of the module's probes from the hash chains and
14603 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
14604 	 * everyone has cleared out from any probe array processing.
14605 	 */
14606 	dtrace_sync();
14607 
14608 	for (probe = first; probe != NULL; probe = first) {
14609 		first = probe->dtpr_nextmod;
14610 		prov = probe->dtpr_provider;
14611 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
14612 		    probe->dtpr_arg);
14613 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
14614 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
14615 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
14616 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
14617 		kmem_free(probe, sizeof (dtrace_probe_t));
14618 	}
14619 
14620 	mutex_exit(&dtrace_lock);
14621 	mutex_exit(&mod_lock);
14622 	mutex_exit(&dtrace_provider_lock);
14623 }
14624 
14625 void
14626 dtrace_suspend(void)
14627 {
14628 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
14629 }
14630 
14631 void
14632 dtrace_resume(void)
14633 {
14634 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
14635 }
14636 
14637 static int
14638 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
14639 {
14640 	ASSERT(MUTEX_HELD(&cpu_lock));
14641 	mutex_enter(&dtrace_lock);
14642 
14643 	switch (what) {
14644 	case CPU_CONFIG: {
14645 		dtrace_state_t *state;
14646 		dtrace_optval_t *opt, rs, c;
14647 
14648 		/*
14649 		 * For now, we only allocate a new buffer for anonymous state.
14650 		 */
14651 		if ((state = dtrace_anon.dta_state) == NULL)
14652 			break;
14653 
14654 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14655 			break;
14656 
14657 		opt = state->dts_options;
14658 		c = opt[DTRACEOPT_CPU];
14659 
14660 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
14661 			break;
14662 
14663 		/*
14664 		 * Regardless of what the actual policy is, we're going to
14665 		 * temporarily set our resize policy to be manual.  We're
14666 		 * also going to temporarily set our CPU option to denote
14667 		 * the newly configured CPU.
14668 		 */
14669 		rs = opt[DTRACEOPT_BUFRESIZE];
14670 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
14671 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
14672 
14673 		(void) dtrace_state_buffers(state);
14674 
14675 		opt[DTRACEOPT_BUFRESIZE] = rs;
14676 		opt[DTRACEOPT_CPU] = c;
14677 
14678 		break;
14679 	}
14680 
14681 	case CPU_UNCONFIG:
14682 		/*
14683 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
14684 		 * buffer will be freed when the consumer exits.)
14685 		 */
14686 		break;
14687 
14688 	default:
14689 		break;
14690 	}
14691 
14692 	mutex_exit(&dtrace_lock);
14693 	return (0);
14694 }
14695 
14696 static void
14697 dtrace_cpu_setup_initial(processorid_t cpu)
14698 {
14699 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
14700 }
14701 
14702 static void
14703 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
14704 {
14705 	if (dtrace_toxranges >= dtrace_toxranges_max) {
14706 		int osize, nsize;
14707 		dtrace_toxrange_t *range;
14708 
14709 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14710 
14711 		if (osize == 0) {
14712 			ASSERT(dtrace_toxrange == NULL);
14713 			ASSERT(dtrace_toxranges_max == 0);
14714 			dtrace_toxranges_max = 1;
14715 		} else {
14716 			dtrace_toxranges_max <<= 1;
14717 		}
14718 
14719 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14720 		range = kmem_zalloc(nsize, KM_SLEEP);
14721 
14722 		if (dtrace_toxrange != NULL) {
14723 			ASSERT(osize != 0);
14724 			bcopy(dtrace_toxrange, range, osize);
14725 			kmem_free(dtrace_toxrange, osize);
14726 		}
14727 
14728 		dtrace_toxrange = range;
14729 	}
14730 
14731 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
14732 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
14733 
14734 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
14735 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
14736 	dtrace_toxranges++;
14737 }
14738 
14739 /*
14740  * DTrace Driver Cookbook Functions
14741  */
14742 /*ARGSUSED*/
14743 static int
14744 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
14745 {
14746 	dtrace_provider_id_t id;
14747 	dtrace_state_t *state = NULL;
14748 	dtrace_enabling_t *enab;
14749 
14750 	mutex_enter(&cpu_lock);
14751 	mutex_enter(&dtrace_provider_lock);
14752 	mutex_enter(&dtrace_lock);
14753 
14754 	if (ddi_soft_state_init(&dtrace_softstate,
14755 	    sizeof (dtrace_state_t), 0) != 0) {
14756 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
14757 		mutex_exit(&cpu_lock);
14758 		mutex_exit(&dtrace_provider_lock);
14759 		mutex_exit(&dtrace_lock);
14760 		return (DDI_FAILURE);
14761 	}
14762 
14763 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
14764 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
14765 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
14766 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
14767 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
14768 		ddi_remove_minor_node(devi, NULL);
14769 		ddi_soft_state_fini(&dtrace_softstate);
14770 		mutex_exit(&cpu_lock);
14771 		mutex_exit(&dtrace_provider_lock);
14772 		mutex_exit(&dtrace_lock);
14773 		return (DDI_FAILURE);
14774 	}
14775 
14776 	ddi_report_dev(devi);
14777 	dtrace_devi = devi;
14778 
14779 	dtrace_modload = dtrace_module_loaded;
14780 	dtrace_modunload = dtrace_module_unloaded;
14781 	dtrace_cpu_init = dtrace_cpu_setup_initial;
14782 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
14783 	dtrace_helpers_fork = dtrace_helpers_duplicate;
14784 	dtrace_cpustart_init = dtrace_suspend;
14785 	dtrace_cpustart_fini = dtrace_resume;
14786 	dtrace_debugger_init = dtrace_suspend;
14787 	dtrace_debugger_fini = dtrace_resume;
14788 
14789 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
14790 
14791 	ASSERT(MUTEX_HELD(&cpu_lock));
14792 
14793 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
14794 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14795 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
14796 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
14797 	    VM_SLEEP | VMC_IDENTIFIER);
14798 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
14799 	    1, INT_MAX, 0);
14800 
14801 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
14802 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
14803 	    NULL, NULL, NULL, NULL, NULL, 0);
14804 
14805 	ASSERT(MUTEX_HELD(&cpu_lock));
14806 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
14807 	    offsetof(dtrace_probe_t, dtpr_nextmod),
14808 	    offsetof(dtrace_probe_t, dtpr_prevmod));
14809 
14810 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
14811 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
14812 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
14813 
14814 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
14815 	    offsetof(dtrace_probe_t, dtpr_nextname),
14816 	    offsetof(dtrace_probe_t, dtpr_prevname));
14817 
14818 	if (dtrace_retain_max < 1) {
14819 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
14820 		    "setting to 1", dtrace_retain_max);
14821 		dtrace_retain_max = 1;
14822 	}
14823 
14824 	/*
14825 	 * Now discover our toxic ranges.
14826 	 */
14827 	dtrace_toxic_ranges(dtrace_toxrange_add);
14828 
14829 	/*
14830 	 * Before we register ourselves as a provider to our own framework,
14831 	 * we would like to assert that dtrace_provider is NULL -- but that's
14832 	 * not true if we were loaded as a dependency of a DTrace provider.
14833 	 * Once we've registered, we can assert that dtrace_provider is our
14834 	 * pseudo provider.
14835 	 */
14836 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
14837 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
14838 
14839 	ASSERT(dtrace_provider != NULL);
14840 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
14841 
14842 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
14843 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
14844 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
14845 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
14846 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
14847 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
14848 
14849 	dtrace_anon_property();
14850 	mutex_exit(&cpu_lock);
14851 
14852 	/*
14853 	 * If DTrace helper tracing is enabled, we need to allocate the
14854 	 * trace buffer and initialize the values.
14855 	 */
14856 	if (dtrace_helptrace_enabled) {
14857 		ASSERT(dtrace_helptrace_buffer == NULL);
14858 		dtrace_helptrace_buffer =
14859 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
14860 		dtrace_helptrace_next = 0;
14861 	}
14862 
14863 	/*
14864 	 * If there are already providers, we must ask them to provide their
14865 	 * probes, and then match any anonymous enabling against them.  Note
14866 	 * that there should be no other retained enablings at this time:
14867 	 * the only retained enablings at this time should be the anonymous
14868 	 * enabling.
14869 	 */
14870 	if (dtrace_anon.dta_enabling != NULL) {
14871 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
14872 
14873 		dtrace_enabling_provide(NULL);
14874 		state = dtrace_anon.dta_state;
14875 
14876 		/*
14877 		 * We couldn't hold cpu_lock across the above call to
14878 		 * dtrace_enabling_provide(), but we must hold it to actually
14879 		 * enable the probes.  We have to drop all of our locks, pick
14880 		 * up cpu_lock, and regain our locks before matching the
14881 		 * retained anonymous enabling.
14882 		 */
14883 		mutex_exit(&dtrace_lock);
14884 		mutex_exit(&dtrace_provider_lock);
14885 
14886 		mutex_enter(&cpu_lock);
14887 		mutex_enter(&dtrace_provider_lock);
14888 		mutex_enter(&dtrace_lock);
14889 
14890 		if ((enab = dtrace_anon.dta_enabling) != NULL)
14891 			(void) dtrace_enabling_match(enab, NULL);
14892 
14893 		mutex_exit(&cpu_lock);
14894 	}
14895 
14896 	mutex_exit(&dtrace_lock);
14897 	mutex_exit(&dtrace_provider_lock);
14898 
14899 	if (state != NULL) {
14900 		/*
14901 		 * If we created any anonymous state, set it going now.
14902 		 */
14903 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
14904 	}
14905 
14906 	return (DDI_SUCCESS);
14907 }
14908 
14909 /*ARGSUSED*/
14910 static int
14911 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
14912 {
14913 	dtrace_state_t *state;
14914 	uint32_t priv;
14915 	uid_t uid;
14916 	zoneid_t zoneid;
14917 
14918 	if (getminor(*devp) == DTRACEMNRN_HELPER)
14919 		return (0);
14920 
14921 	/*
14922 	 * If this wasn't an open with the "helper" minor, then it must be
14923 	 * the "dtrace" minor.
14924 	 */
14925 	if (getminor(*devp) != DTRACEMNRN_DTRACE)
14926 		return (ENXIO);
14927 
14928 	/*
14929 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
14930 	 * caller lacks sufficient permission to do anything with DTrace.
14931 	 */
14932 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
14933 	if (priv == DTRACE_PRIV_NONE)
14934 		return (EACCES);
14935 
14936 	/*
14937 	 * Ask all providers to provide all their probes.
14938 	 */
14939 	mutex_enter(&dtrace_provider_lock);
14940 	dtrace_probe_provide(NULL, NULL);
14941 	mutex_exit(&dtrace_provider_lock);
14942 
14943 	mutex_enter(&cpu_lock);
14944 	mutex_enter(&dtrace_lock);
14945 	dtrace_opens++;
14946 	dtrace_membar_producer();
14947 
14948 	/*
14949 	 * If the kernel debugger is active (that is, if the kernel debugger
14950 	 * modified text in some way), we won't allow the open.
14951 	 */
14952 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14953 		dtrace_opens--;
14954 		mutex_exit(&cpu_lock);
14955 		mutex_exit(&dtrace_lock);
14956 		return (EBUSY);
14957 	}
14958 
14959 	state = dtrace_state_create(devp, cred_p);
14960 	mutex_exit(&cpu_lock);
14961 
14962 	if (state == NULL) {
14963 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
14964 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14965 		mutex_exit(&dtrace_lock);
14966 		return (EAGAIN);
14967 	}
14968 
14969 	mutex_exit(&dtrace_lock);
14970 
14971 	return (0);
14972 }
14973 
14974 /*ARGSUSED*/
14975 static int
14976 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
14977 {
14978 	minor_t minor = getminor(dev);
14979 	dtrace_state_t *state;
14980 
14981 	if (minor == DTRACEMNRN_HELPER)
14982 		return (0);
14983 
14984 	state = ddi_get_soft_state(dtrace_softstate, minor);
14985 
14986 	mutex_enter(&cpu_lock);
14987 	mutex_enter(&dtrace_lock);
14988 
14989 	if (state->dts_anon) {
14990 		/*
14991 		 * There is anonymous state. Destroy that first.
14992 		 */
14993 		ASSERT(dtrace_anon.dta_state == NULL);
14994 		dtrace_state_destroy(state->dts_anon);
14995 	}
14996 
14997 	dtrace_state_destroy(state);
14998 	ASSERT(dtrace_opens > 0);
14999 
15000 	/*
15001 	 * Only relinquish control of the kernel debugger interface when there
15002 	 * are no consumers and no anonymous enablings.
15003 	 */
15004 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
15005 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15006 
15007 	mutex_exit(&dtrace_lock);
15008 	mutex_exit(&cpu_lock);
15009 
15010 	return (0);
15011 }
15012 
15013 /*ARGSUSED*/
15014 static int
15015 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
15016 {
15017 	int rval;
15018 	dof_helper_t help, *dhp = NULL;
15019 
15020 	switch (cmd) {
15021 	case DTRACEHIOC_ADDDOF:
15022 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
15023 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
15024 			return (EFAULT);
15025 		}
15026 
15027 		dhp = &help;
15028 		arg = (intptr_t)help.dofhp_dof;
15029 		/*FALLTHROUGH*/
15030 
15031 	case DTRACEHIOC_ADD: {
15032 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
15033 
15034 		if (dof == NULL)
15035 			return (rval);
15036 
15037 		mutex_enter(&dtrace_lock);
15038 
15039 		/*
15040 		 * dtrace_helper_slurp() takes responsibility for the dof --
15041 		 * it may free it now or it may save it and free it later.
15042 		 */
15043 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
15044 			*rv = rval;
15045 			rval = 0;
15046 		} else {
15047 			rval = EINVAL;
15048 		}
15049 
15050 		mutex_exit(&dtrace_lock);
15051 		return (rval);
15052 	}
15053 
15054 	case DTRACEHIOC_REMOVE: {
15055 		mutex_enter(&dtrace_lock);
15056 		rval = dtrace_helper_destroygen(arg);
15057 		mutex_exit(&dtrace_lock);
15058 
15059 		return (rval);
15060 	}
15061 
15062 	default:
15063 		break;
15064 	}
15065 
15066 	return (ENOTTY);
15067 }
15068 
15069 /*ARGSUSED*/
15070 static int
15071 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
15072 {
15073 	minor_t minor = getminor(dev);
15074 	dtrace_state_t *state;
15075 	int rval;
15076 
15077 	if (minor == DTRACEMNRN_HELPER)
15078 		return (dtrace_ioctl_helper(cmd, arg, rv));
15079 
15080 	state = ddi_get_soft_state(dtrace_softstate, minor);
15081 
15082 	if (state->dts_anon) {
15083 		ASSERT(dtrace_anon.dta_state == NULL);
15084 		state = state->dts_anon;
15085 	}
15086 
15087 	switch (cmd) {
15088 	case DTRACEIOC_PROVIDER: {
15089 		dtrace_providerdesc_t pvd;
15090 		dtrace_provider_t *pvp;
15091 
15092 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
15093 			return (EFAULT);
15094 
15095 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
15096 		mutex_enter(&dtrace_provider_lock);
15097 
15098 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
15099 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
15100 				break;
15101 		}
15102 
15103 		mutex_exit(&dtrace_provider_lock);
15104 
15105 		if (pvp == NULL)
15106 			return (ESRCH);
15107 
15108 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
15109 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
15110 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
15111 			return (EFAULT);
15112 
15113 		return (0);
15114 	}
15115 
15116 	case DTRACEIOC_EPROBE: {
15117 		dtrace_eprobedesc_t epdesc;
15118 		dtrace_ecb_t *ecb;
15119 		dtrace_action_t *act;
15120 		void *buf;
15121 		size_t size;
15122 		uintptr_t dest;
15123 		int nrecs;
15124 
15125 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
15126 			return (EFAULT);
15127 
15128 		mutex_enter(&dtrace_lock);
15129 
15130 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
15131 			mutex_exit(&dtrace_lock);
15132 			return (EINVAL);
15133 		}
15134 
15135 		if (ecb->dte_probe == NULL) {
15136 			mutex_exit(&dtrace_lock);
15137 			return (EINVAL);
15138 		}
15139 
15140 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
15141 		epdesc.dtepd_uarg = ecb->dte_uarg;
15142 		epdesc.dtepd_size = ecb->dte_size;
15143 
15144 		nrecs = epdesc.dtepd_nrecs;
15145 		epdesc.dtepd_nrecs = 0;
15146 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15147 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15148 				continue;
15149 
15150 			epdesc.dtepd_nrecs++;
15151 		}
15152 
15153 		/*
15154 		 * Now that we have the size, we need to allocate a temporary
15155 		 * buffer in which to store the complete description.  We need
15156 		 * the temporary buffer to be able to drop dtrace_lock()
15157 		 * across the copyout(), below.
15158 		 */
15159 		size = sizeof (dtrace_eprobedesc_t) +
15160 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
15161 
15162 		buf = kmem_alloc(size, KM_SLEEP);
15163 		dest = (uintptr_t)buf;
15164 
15165 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
15166 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
15167 
15168 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
15169 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
15170 				continue;
15171 
15172 			if (nrecs-- == 0)
15173 				break;
15174 
15175 			bcopy(&act->dta_rec, (void *)dest,
15176 			    sizeof (dtrace_recdesc_t));
15177 			dest += sizeof (dtrace_recdesc_t);
15178 		}
15179 
15180 		mutex_exit(&dtrace_lock);
15181 
15182 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
15183 			kmem_free(buf, size);
15184 			return (EFAULT);
15185 		}
15186 
15187 		kmem_free(buf, size);
15188 		return (0);
15189 	}
15190 
15191 	case DTRACEIOC_AGGDESC: {
15192 		dtrace_aggdesc_t aggdesc;
15193 		dtrace_action_t *act;
15194 		dtrace_aggregation_t *agg;
15195 		int nrecs;
15196 		uint32_t offs;
15197 		dtrace_recdesc_t *lrec;
15198 		void *buf;
15199 		size_t size;
15200 		uintptr_t dest;
15201 
15202 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
15203 			return (EFAULT);
15204 
15205 		mutex_enter(&dtrace_lock);
15206 
15207 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
15208 			mutex_exit(&dtrace_lock);
15209 			return (EINVAL);
15210 		}
15211 
15212 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
15213 
15214 		nrecs = aggdesc.dtagd_nrecs;
15215 		aggdesc.dtagd_nrecs = 0;
15216 
15217 		offs = agg->dtag_base;
15218 		lrec = &agg->dtag_action.dta_rec;
15219 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
15220 
15221 		for (act = agg->dtag_first; ; act = act->dta_next) {
15222 			ASSERT(act->dta_intuple ||
15223 			    DTRACEACT_ISAGG(act->dta_kind));
15224 
15225 			/*
15226 			 * If this action has a record size of zero, it
15227 			 * denotes an argument to the aggregating action.
15228 			 * Because the presence of this record doesn't (or
15229 			 * shouldn't) affect the way the data is interpreted,
15230 			 * we don't copy it out to save user-level the
15231 			 * confusion of dealing with a zero-length record.
15232 			 */
15233 			if (act->dta_rec.dtrd_size == 0) {
15234 				ASSERT(agg->dtag_hasarg);
15235 				continue;
15236 			}
15237 
15238 			aggdesc.dtagd_nrecs++;
15239 
15240 			if (act == &agg->dtag_action)
15241 				break;
15242 		}
15243 
15244 		/*
15245 		 * Now that we have the size, we need to allocate a temporary
15246 		 * buffer in which to store the complete description.  We need
15247 		 * the temporary buffer to be able to drop dtrace_lock()
15248 		 * across the copyout(), below.
15249 		 */
15250 		size = sizeof (dtrace_aggdesc_t) +
15251 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
15252 
15253 		buf = kmem_alloc(size, KM_SLEEP);
15254 		dest = (uintptr_t)buf;
15255 
15256 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
15257 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
15258 
15259 		for (act = agg->dtag_first; ; act = act->dta_next) {
15260 			dtrace_recdesc_t rec = act->dta_rec;
15261 
15262 			/*
15263 			 * See the comment in the above loop for why we pass
15264 			 * over zero-length records.
15265 			 */
15266 			if (rec.dtrd_size == 0) {
15267 				ASSERT(agg->dtag_hasarg);
15268 				continue;
15269 			}
15270 
15271 			if (nrecs-- == 0)
15272 				break;
15273 
15274 			rec.dtrd_offset -= offs;
15275 			bcopy(&rec, (void *)dest, sizeof (rec));
15276 			dest += sizeof (dtrace_recdesc_t);
15277 
15278 			if (act == &agg->dtag_action)
15279 				break;
15280 		}
15281 
15282 		mutex_exit(&dtrace_lock);
15283 
15284 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
15285 			kmem_free(buf, size);
15286 			return (EFAULT);
15287 		}
15288 
15289 		kmem_free(buf, size);
15290 		return (0);
15291 	}
15292 
15293 	case DTRACEIOC_ENABLE: {
15294 		dof_hdr_t *dof;
15295 		dtrace_enabling_t *enab = NULL;
15296 		dtrace_vstate_t *vstate;
15297 		int err = 0;
15298 
15299 		*rv = 0;
15300 
15301 		/*
15302 		 * If a NULL argument has been passed, we take this as our
15303 		 * cue to reevaluate our enablings.
15304 		 */
15305 		if (arg == NULL) {
15306 			dtrace_enabling_matchall();
15307 
15308 			return (0);
15309 		}
15310 
15311 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
15312 			return (rval);
15313 
15314 		mutex_enter(&cpu_lock);
15315 		mutex_enter(&dtrace_lock);
15316 		vstate = &state->dts_vstate;
15317 
15318 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
15319 			mutex_exit(&dtrace_lock);
15320 			mutex_exit(&cpu_lock);
15321 			dtrace_dof_destroy(dof);
15322 			return (EBUSY);
15323 		}
15324 
15325 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
15326 			mutex_exit(&dtrace_lock);
15327 			mutex_exit(&cpu_lock);
15328 			dtrace_dof_destroy(dof);
15329 			return (EINVAL);
15330 		}
15331 
15332 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
15333 			dtrace_enabling_destroy(enab);
15334 			mutex_exit(&dtrace_lock);
15335 			mutex_exit(&cpu_lock);
15336 			dtrace_dof_destroy(dof);
15337 			return (rval);
15338 		}
15339 
15340 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
15341 			err = dtrace_enabling_retain(enab);
15342 		} else {
15343 			dtrace_enabling_destroy(enab);
15344 		}
15345 
15346 		mutex_exit(&cpu_lock);
15347 		mutex_exit(&dtrace_lock);
15348 		dtrace_dof_destroy(dof);
15349 
15350 		return (err);
15351 	}
15352 
15353 	case DTRACEIOC_REPLICATE: {
15354 		dtrace_repldesc_t desc;
15355 		dtrace_probedesc_t *match = &desc.dtrpd_match;
15356 		dtrace_probedesc_t *create = &desc.dtrpd_create;
15357 		int err;
15358 
15359 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15360 			return (EFAULT);
15361 
15362 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15363 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15364 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15365 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15366 
15367 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15368 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15369 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15370 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15371 
15372 		mutex_enter(&dtrace_lock);
15373 		err = dtrace_enabling_replicate(state, match, create);
15374 		mutex_exit(&dtrace_lock);
15375 
15376 		return (err);
15377 	}
15378 
15379 	case DTRACEIOC_PROBEMATCH:
15380 	case DTRACEIOC_PROBES: {
15381 		dtrace_probe_t *probe = NULL;
15382 		dtrace_probedesc_t desc;
15383 		dtrace_probekey_t pkey;
15384 		dtrace_id_t i;
15385 		int m = 0;
15386 		uint32_t priv;
15387 		uid_t uid;
15388 		zoneid_t zoneid;
15389 
15390 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15391 			return (EFAULT);
15392 
15393 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
15394 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
15395 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
15396 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
15397 
15398 		/*
15399 		 * Before we attempt to match this probe, we want to give
15400 		 * all providers the opportunity to provide it.
15401 		 */
15402 		if (desc.dtpd_id == DTRACE_IDNONE) {
15403 			mutex_enter(&dtrace_provider_lock);
15404 			dtrace_probe_provide(&desc, NULL);
15405 			mutex_exit(&dtrace_provider_lock);
15406 			desc.dtpd_id++;
15407 		}
15408 
15409 		if (cmd == DTRACEIOC_PROBEMATCH)  {
15410 			dtrace_probekey(&desc, &pkey);
15411 			pkey.dtpk_id = DTRACE_IDNONE;
15412 		}
15413 
15414 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
15415 
15416 		mutex_enter(&dtrace_lock);
15417 
15418 		if (cmd == DTRACEIOC_PROBEMATCH) {
15419 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
15420 				if ((probe = dtrace_probes[i - 1]) != NULL &&
15421 				    (m = dtrace_match_probe(probe, &pkey,
15422 				    priv, uid, zoneid)) != 0)
15423 					break;
15424 			}
15425 
15426 			if (m < 0) {
15427 				mutex_exit(&dtrace_lock);
15428 				return (EINVAL);
15429 			}
15430 
15431 		} else {
15432 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
15433 				if ((probe = dtrace_probes[i - 1]) != NULL &&
15434 				    dtrace_match_priv(probe, priv, uid, zoneid))
15435 					break;
15436 			}
15437 		}
15438 
15439 		if (probe == NULL) {
15440 			mutex_exit(&dtrace_lock);
15441 			return (ESRCH);
15442 		}
15443 
15444 		dtrace_probe_description(probe, &desc);
15445 		mutex_exit(&dtrace_lock);
15446 
15447 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15448 			return (EFAULT);
15449 
15450 		return (0);
15451 	}
15452 
15453 	case DTRACEIOC_PROBEARG: {
15454 		dtrace_argdesc_t desc;
15455 		dtrace_probe_t *probe;
15456 		dtrace_provider_t *prov;
15457 
15458 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15459 			return (EFAULT);
15460 
15461 		if (desc.dtargd_id == DTRACE_IDNONE)
15462 			return (EINVAL);
15463 
15464 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
15465 			return (EINVAL);
15466 
15467 		mutex_enter(&dtrace_provider_lock);
15468 		mutex_enter(&mod_lock);
15469 		mutex_enter(&dtrace_lock);
15470 
15471 		if (desc.dtargd_id > dtrace_nprobes) {
15472 			mutex_exit(&dtrace_lock);
15473 			mutex_exit(&mod_lock);
15474 			mutex_exit(&dtrace_provider_lock);
15475 			return (EINVAL);
15476 		}
15477 
15478 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
15479 			mutex_exit(&dtrace_lock);
15480 			mutex_exit(&mod_lock);
15481 			mutex_exit(&dtrace_provider_lock);
15482 			return (EINVAL);
15483 		}
15484 
15485 		mutex_exit(&dtrace_lock);
15486 
15487 		prov = probe->dtpr_provider;
15488 
15489 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
15490 			/*
15491 			 * There isn't any typed information for this probe.
15492 			 * Set the argument number to DTRACE_ARGNONE.
15493 			 */
15494 			desc.dtargd_ndx = DTRACE_ARGNONE;
15495 		} else {
15496 			desc.dtargd_native[0] = '\0';
15497 			desc.dtargd_xlate[0] = '\0';
15498 			desc.dtargd_mapping = desc.dtargd_ndx;
15499 
15500 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
15501 			    probe->dtpr_id, probe->dtpr_arg, &desc);
15502 		}
15503 
15504 		mutex_exit(&mod_lock);
15505 		mutex_exit(&dtrace_provider_lock);
15506 
15507 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15508 			return (EFAULT);
15509 
15510 		return (0);
15511 	}
15512 
15513 	case DTRACEIOC_GO: {
15514 		processorid_t cpuid;
15515 		rval = dtrace_state_go(state, &cpuid);
15516 
15517 		if (rval != 0)
15518 			return (rval);
15519 
15520 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
15521 			return (EFAULT);
15522 
15523 		return (0);
15524 	}
15525 
15526 	case DTRACEIOC_STOP: {
15527 		processorid_t cpuid;
15528 
15529 		mutex_enter(&dtrace_lock);
15530 		rval = dtrace_state_stop(state, &cpuid);
15531 		mutex_exit(&dtrace_lock);
15532 
15533 		if (rval != 0)
15534 			return (rval);
15535 
15536 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
15537 			return (EFAULT);
15538 
15539 		return (0);
15540 	}
15541 
15542 	case DTRACEIOC_DOFGET: {
15543 		dof_hdr_t hdr, *dof;
15544 		uint64_t len;
15545 
15546 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
15547 			return (EFAULT);
15548 
15549 		mutex_enter(&dtrace_lock);
15550 		dof = dtrace_dof_create(state);
15551 		mutex_exit(&dtrace_lock);
15552 
15553 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
15554 		rval = copyout(dof, (void *)arg, len);
15555 		dtrace_dof_destroy(dof);
15556 
15557 		return (rval == 0 ? 0 : EFAULT);
15558 	}
15559 
15560 	case DTRACEIOC_AGGSNAP:
15561 	case DTRACEIOC_BUFSNAP: {
15562 		dtrace_bufdesc_t desc;
15563 		caddr_t cached;
15564 		dtrace_buffer_t *buf;
15565 
15566 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15567 			return (EFAULT);
15568 
15569 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
15570 			return (EINVAL);
15571 
15572 		mutex_enter(&dtrace_lock);
15573 
15574 		if (cmd == DTRACEIOC_BUFSNAP) {
15575 			buf = &state->dts_buffer[desc.dtbd_cpu];
15576 		} else {
15577 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
15578 		}
15579 
15580 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
15581 			size_t sz = buf->dtb_offset;
15582 
15583 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
15584 				mutex_exit(&dtrace_lock);
15585 				return (EBUSY);
15586 			}
15587 
15588 			/*
15589 			 * If this buffer has already been consumed, we're
15590 			 * going to indicate that there's nothing left here
15591 			 * to consume.
15592 			 */
15593 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
15594 				mutex_exit(&dtrace_lock);
15595 
15596 				desc.dtbd_size = 0;
15597 				desc.dtbd_drops = 0;
15598 				desc.dtbd_errors = 0;
15599 				desc.dtbd_oldest = 0;
15600 				sz = sizeof (desc);
15601 
15602 				if (copyout(&desc, (void *)arg, sz) != 0)
15603 					return (EFAULT);
15604 
15605 				return (0);
15606 			}
15607 
15608 			/*
15609 			 * If this is a ring buffer that has wrapped, we want
15610 			 * to copy the whole thing out.
15611 			 */
15612 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
15613 				dtrace_buffer_polish(buf);
15614 				sz = buf->dtb_size;
15615 			}
15616 
15617 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
15618 				mutex_exit(&dtrace_lock);
15619 				return (EFAULT);
15620 			}
15621 
15622 			desc.dtbd_size = sz;
15623 			desc.dtbd_drops = buf->dtb_drops;
15624 			desc.dtbd_errors = buf->dtb_errors;
15625 			desc.dtbd_oldest = buf->dtb_xamot_offset;
15626 
15627 			mutex_exit(&dtrace_lock);
15628 
15629 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15630 				return (EFAULT);
15631 
15632 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
15633 
15634 			return (0);
15635 		}
15636 
15637 		if (buf->dtb_tomax == NULL) {
15638 			ASSERT(buf->dtb_xamot == NULL);
15639 			mutex_exit(&dtrace_lock);
15640 			return (ENOENT);
15641 		}
15642 
15643 		cached = buf->dtb_tomax;
15644 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
15645 
15646 		dtrace_xcall(desc.dtbd_cpu,
15647 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
15648 
15649 		state->dts_errors += buf->dtb_xamot_errors;
15650 
15651 		/*
15652 		 * If the buffers did not actually switch, then the cross call
15653 		 * did not take place -- presumably because the given CPU is
15654 		 * not in the ready set.  If this is the case, we'll return
15655 		 * ENOENT.
15656 		 */
15657 		if (buf->dtb_tomax == cached) {
15658 			ASSERT(buf->dtb_xamot != cached);
15659 			mutex_exit(&dtrace_lock);
15660 			return (ENOENT);
15661 		}
15662 
15663 		ASSERT(cached == buf->dtb_xamot);
15664 
15665 		/*
15666 		 * We have our snapshot; now copy it out.
15667 		 */
15668 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
15669 		    buf->dtb_xamot_offset) != 0) {
15670 			mutex_exit(&dtrace_lock);
15671 			return (EFAULT);
15672 		}
15673 
15674 		desc.dtbd_size = buf->dtb_xamot_offset;
15675 		desc.dtbd_drops = buf->dtb_xamot_drops;
15676 		desc.dtbd_errors = buf->dtb_xamot_errors;
15677 		desc.dtbd_oldest = 0;
15678 
15679 		mutex_exit(&dtrace_lock);
15680 
15681 		/*
15682 		 * Finally, copy out the buffer description.
15683 		 */
15684 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15685 			return (EFAULT);
15686 
15687 		return (0);
15688 	}
15689 
15690 	case DTRACEIOC_CONF: {
15691 		dtrace_conf_t conf;
15692 
15693 		bzero(&conf, sizeof (conf));
15694 		conf.dtc_difversion = DIF_VERSION;
15695 		conf.dtc_difintregs = DIF_DIR_NREGS;
15696 		conf.dtc_diftupregs = DIF_DTR_NREGS;
15697 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
15698 
15699 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
15700 			return (EFAULT);
15701 
15702 		return (0);
15703 	}
15704 
15705 	case DTRACEIOC_STATUS: {
15706 		dtrace_status_t stat;
15707 		dtrace_dstate_t *dstate;
15708 		int i, j;
15709 		uint64_t nerrs;
15710 
15711 		/*
15712 		 * See the comment in dtrace_state_deadman() for the reason
15713 		 * for setting dts_laststatus to INT64_MAX before setting
15714 		 * it to the correct value.
15715 		 */
15716 		state->dts_laststatus = INT64_MAX;
15717 		dtrace_membar_producer();
15718 		state->dts_laststatus = dtrace_gethrtime();
15719 
15720 		bzero(&stat, sizeof (stat));
15721 
15722 		mutex_enter(&dtrace_lock);
15723 
15724 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
15725 			mutex_exit(&dtrace_lock);
15726 			return (ENOENT);
15727 		}
15728 
15729 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
15730 			stat.dtst_exiting = 1;
15731 
15732 		nerrs = state->dts_errors;
15733 		dstate = &state->dts_vstate.dtvs_dynvars;
15734 
15735 		for (i = 0; i < NCPU; i++) {
15736 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
15737 
15738 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
15739 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
15740 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
15741 
15742 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
15743 				stat.dtst_filled++;
15744 
15745 			nerrs += state->dts_buffer[i].dtb_errors;
15746 
15747 			for (j = 0; j < state->dts_nspeculations; j++) {
15748 				dtrace_speculation_t *spec;
15749 				dtrace_buffer_t *buf;
15750 
15751 				spec = &state->dts_speculations[j];
15752 				buf = &spec->dtsp_buffer[i];
15753 				stat.dtst_specdrops += buf->dtb_xamot_drops;
15754 			}
15755 		}
15756 
15757 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
15758 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
15759 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
15760 		stat.dtst_dblerrors = state->dts_dblerrors;
15761 		stat.dtst_killed =
15762 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
15763 		stat.dtst_errors = nerrs;
15764 
15765 		mutex_exit(&dtrace_lock);
15766 
15767 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
15768 			return (EFAULT);
15769 
15770 		return (0);
15771 	}
15772 
15773 	case DTRACEIOC_FORMAT: {
15774 		dtrace_fmtdesc_t fmt;
15775 		char *str;
15776 		int len;
15777 
15778 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
15779 			return (EFAULT);
15780 
15781 		mutex_enter(&dtrace_lock);
15782 
15783 		if (fmt.dtfd_format == 0 ||
15784 		    fmt.dtfd_format > state->dts_nformats) {
15785 			mutex_exit(&dtrace_lock);
15786 			return (EINVAL);
15787 		}
15788 
15789 		/*
15790 		 * Format strings are allocated contiguously and they are
15791 		 * never freed; if a format index is less than the number
15792 		 * of formats, we can assert that the format map is non-NULL
15793 		 * and that the format for the specified index is non-NULL.
15794 		 */
15795 		ASSERT(state->dts_formats != NULL);
15796 		str = state->dts_formats[fmt.dtfd_format - 1];
15797 		ASSERT(str != NULL);
15798 
15799 		len = strlen(str) + 1;
15800 
15801 		if (len > fmt.dtfd_length) {
15802 			fmt.dtfd_length = len;
15803 
15804 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
15805 				mutex_exit(&dtrace_lock);
15806 				return (EINVAL);
15807 			}
15808 		} else {
15809 			if (copyout(str, fmt.dtfd_string, len) != 0) {
15810 				mutex_exit(&dtrace_lock);
15811 				return (EINVAL);
15812 			}
15813 		}
15814 
15815 		mutex_exit(&dtrace_lock);
15816 		return (0);
15817 	}
15818 
15819 	default:
15820 		break;
15821 	}
15822 
15823 	return (ENOTTY);
15824 }
15825 
15826 /*ARGSUSED*/
15827 static int
15828 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
15829 {
15830 	dtrace_state_t *state;
15831 
15832 	switch (cmd) {
15833 	case DDI_DETACH:
15834 		break;
15835 
15836 	case DDI_SUSPEND:
15837 		return (DDI_SUCCESS);
15838 
15839 	default:
15840 		return (DDI_FAILURE);
15841 	}
15842 
15843 	mutex_enter(&cpu_lock);
15844 	mutex_enter(&dtrace_provider_lock);
15845 	mutex_enter(&dtrace_lock);
15846 
15847 	ASSERT(dtrace_opens == 0);
15848 
15849 	if (dtrace_helpers > 0) {
15850 		mutex_exit(&dtrace_provider_lock);
15851 		mutex_exit(&dtrace_lock);
15852 		mutex_exit(&cpu_lock);
15853 		return (DDI_FAILURE);
15854 	}
15855 
15856 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
15857 		mutex_exit(&dtrace_provider_lock);
15858 		mutex_exit(&dtrace_lock);
15859 		mutex_exit(&cpu_lock);
15860 		return (DDI_FAILURE);
15861 	}
15862 
15863 	dtrace_provider = NULL;
15864 
15865 	if ((state = dtrace_anon_grab()) != NULL) {
15866 		/*
15867 		 * If there were ECBs on this state, the provider should
15868 		 * have not been allowed to detach; assert that there is
15869 		 * none.
15870 		 */
15871 		ASSERT(state->dts_necbs == 0);
15872 		dtrace_state_destroy(state);
15873 
15874 		/*
15875 		 * If we're being detached with anonymous state, we need to
15876 		 * indicate to the kernel debugger that DTrace is now inactive.
15877 		 */
15878 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15879 	}
15880 
15881 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
15882 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15883 	dtrace_cpu_init = NULL;
15884 	dtrace_helpers_cleanup = NULL;
15885 	dtrace_helpers_fork = NULL;
15886 	dtrace_cpustart_init = NULL;
15887 	dtrace_cpustart_fini = NULL;
15888 	dtrace_debugger_init = NULL;
15889 	dtrace_debugger_fini = NULL;
15890 	dtrace_modload = NULL;
15891 	dtrace_modunload = NULL;
15892 
15893 	mutex_exit(&cpu_lock);
15894 
15895 	if (dtrace_helptrace_enabled) {
15896 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
15897 		dtrace_helptrace_buffer = NULL;
15898 	}
15899 
15900 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
15901 	dtrace_probes = NULL;
15902 	dtrace_nprobes = 0;
15903 
15904 	dtrace_hash_destroy(dtrace_bymod);
15905 	dtrace_hash_destroy(dtrace_byfunc);
15906 	dtrace_hash_destroy(dtrace_byname);
15907 	dtrace_bymod = NULL;
15908 	dtrace_byfunc = NULL;
15909 	dtrace_byname = NULL;
15910 
15911 	kmem_cache_destroy(dtrace_state_cache);
15912 	vmem_destroy(dtrace_minor);
15913 	vmem_destroy(dtrace_arena);
15914 
15915 	if (dtrace_toxrange != NULL) {
15916 		kmem_free(dtrace_toxrange,
15917 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
15918 		dtrace_toxrange = NULL;
15919 		dtrace_toxranges = 0;
15920 		dtrace_toxranges_max = 0;
15921 	}
15922 
15923 	ddi_remove_minor_node(dtrace_devi, NULL);
15924 	dtrace_devi = NULL;
15925 
15926 	ddi_soft_state_fini(&dtrace_softstate);
15927 
15928 	ASSERT(dtrace_vtime_references == 0);
15929 	ASSERT(dtrace_opens == 0);
15930 	ASSERT(dtrace_retained == NULL);
15931 
15932 	mutex_exit(&dtrace_lock);
15933 	mutex_exit(&dtrace_provider_lock);
15934 
15935 	/*
15936 	 * We don't destroy the task queue until after we have dropped our
15937 	 * locks (taskq_destroy() may block on running tasks).  To prevent
15938 	 * attempting to do work after we have effectively detached but before
15939 	 * the task queue has been destroyed, all tasks dispatched via the
15940 	 * task queue must check that DTrace is still attached before
15941 	 * performing any operation.
15942 	 */
15943 	taskq_destroy(dtrace_taskq);
15944 	dtrace_taskq = NULL;
15945 
15946 	return (DDI_SUCCESS);
15947 }
15948 
15949 /*ARGSUSED*/
15950 static int
15951 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
15952 {
15953 	int error;
15954 
15955 	switch (infocmd) {
15956 	case DDI_INFO_DEVT2DEVINFO:
15957 		*result = (void *)dtrace_devi;
15958 		error = DDI_SUCCESS;
15959 		break;
15960 	case DDI_INFO_DEVT2INSTANCE:
15961 		*result = (void *)0;
15962 		error = DDI_SUCCESS;
15963 		break;
15964 	default:
15965 		error = DDI_FAILURE;
15966 	}
15967 	return (error);
15968 }
15969 
15970 static struct cb_ops dtrace_cb_ops = {
15971 	dtrace_open,		/* open */
15972 	dtrace_close,		/* close */
15973 	nulldev,		/* strategy */
15974 	nulldev,		/* print */
15975 	nodev,			/* dump */
15976 	nodev,			/* read */
15977 	nodev,			/* write */
15978 	dtrace_ioctl,		/* ioctl */
15979 	nodev,			/* devmap */
15980 	nodev,			/* mmap */
15981 	nodev,			/* segmap */
15982 	nochpoll,		/* poll */
15983 	ddi_prop_op,		/* cb_prop_op */
15984 	0,			/* streamtab  */
15985 	D_NEW | D_MP		/* Driver compatibility flag */
15986 };
15987 
15988 static struct dev_ops dtrace_ops = {
15989 	DEVO_REV,		/* devo_rev */
15990 	0,			/* refcnt */
15991 	dtrace_info,		/* get_dev_info */
15992 	nulldev,		/* identify */
15993 	nulldev,		/* probe */
15994 	dtrace_attach,		/* attach */
15995 	dtrace_detach,		/* detach */
15996 	nodev,			/* reset */
15997 	&dtrace_cb_ops,		/* driver operations */
15998 	NULL,			/* bus operations */
15999 	nodev,			/* dev power */
16000 	ddi_quiesce_not_needed,		/* quiesce */
16001 };
16002 
16003 static struct modldrv modldrv = {
16004 	&mod_driverops,		/* module type (this is a pseudo driver) */
16005 	"Dynamic Tracing",	/* name of module */
16006 	&dtrace_ops,		/* driver ops */
16007 };
16008 
16009 static struct modlinkage modlinkage = {
16010 	MODREV_1,
16011 	(void *)&modldrv,
16012 	NULL
16013 };
16014 
16015 int
16016 _init(void)
16017 {
16018 	return (mod_install(&modlinkage));
16019 }
16020 
16021 int
16022 _info(struct modinfo *modinfop)
16023 {
16024 	return (mod_info(&modlinkage, modinfop));
16025 }
16026 
16027 int
16028 _fini(void)
16029 {
16030 	return (mod_remove(&modlinkage));
16031 }
16032