xref: /illumos-gate/usr/src/uts/common/dtrace/dtrace.c (revision 586d07d095794b3debc231dad6a567b554248e19)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * DTrace - Dynamic Tracing for Solaris
31  *
32  * This is the implementation of the Solaris Dynamic Tracing framework
33  * (DTrace).  The user-visible interface to DTrace is described at length in
34  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
35  * library, the in-kernel DTrace framework, and the DTrace providers are
36  * described in the block comments in the <sys/dtrace.h> header file.  The
37  * internal architecture of DTrace is described in the block comments in the
38  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
39  * implementation very much assume mastery of all of these sources; if one has
40  * an unanswered question about the implementation, one should consult them
41  * first.
42  *
43  * The functions here are ordered roughly as follows:
44  *
45  *   - Probe context functions
46  *   - Probe hashing functions
47  *   - Non-probe context utility functions
48  *   - Matching functions
49  *   - Provider-to-Framework API functions
50  *   - Probe management functions
51  *   - DIF object functions
52  *   - Format functions
53  *   - Predicate functions
54  *   - ECB functions
55  *   - Buffer functions
56  *   - Enabling functions
57  *   - DOF functions
58  *   - Anonymous enabling functions
59  *   - Consumer state functions
60  *   - Helper functions
61  *   - Hook functions
62  *   - Driver cookbook functions
63  *
64  * Each group of functions begins with a block comment labelled the "DTrace
65  * [Group] Functions", allowing one to find each block by searching forward
66  * on capital-f functions.
67  */
68 #include <sys/errno.h>
69 #include <sys/stat.h>
70 #include <sys/modctl.h>
71 #include <sys/conf.h>
72 #include <sys/systm.h>
73 #include <sys/ddi.h>
74 #include <sys/sunddi.h>
75 #include <sys/cpuvar.h>
76 #include <sys/kmem.h>
77 #include <sys/strsubr.h>
78 #include <sys/sysmacros.h>
79 #include <sys/dtrace_impl.h>
80 #include <sys/atomic.h>
81 #include <sys/cmn_err.h>
82 #include <sys/mutex_impl.h>
83 #include <sys/rwlock_impl.h>
84 #include <sys/ctf_api.h>
85 #include <sys/panic.h>
86 #include <sys/priv_impl.h>
87 #include <sys/policy.h>
88 #include <sys/cred_impl.h>
89 #include <sys/procfs_isa.h>
90 #include <sys/taskq.h>
91 #include <sys/mkdev.h>
92 #include <sys/kdi.h>
93 #include <sys/zone.h>
94 
95 /*
96  * DTrace Tunable Variables
97  *
98  * The following variables may be tuned by adding a line to /etc/system that
99  * includes both the name of the DTrace module ("dtrace") and the name of the
100  * variable.  For example:
101  *
102  *   set dtrace:dtrace_destructive_disallow = 1
103  *
104  * In general, the only variables that one should be tuning this way are those
105  * that affect system-wide DTrace behavior, and for which the default behavior
106  * is undesirable.  Most of these variables are tunable on a per-consumer
107  * basis using DTrace options, and need not be tuned on a system-wide basis.
108  * When tuning these variables, avoid pathological values; while some attempt
109  * is made to verify the integrity of these variables, they are not considered
110  * part of the supported interface to DTrace, and they are therefore not
111  * checked comprehensively.  Further, these variables should not be tuned
112  * dynamically via "mdb -kw" or other means; they should only be tuned via
113  * /etc/system.
114  */
115 int		dtrace_destructive_disallow = 0;
116 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
117 size_t		dtrace_difo_maxsize = (256 * 1024);
118 dtrace_optval_t	dtrace_dof_maxsize = (256 * 1024);
119 size_t		dtrace_global_maxsize = (16 * 1024);
120 size_t		dtrace_actions_max = (16 * 1024);
121 size_t		dtrace_retain_max = 1024;
122 dtrace_optval_t	dtrace_helper_actions_max = 32;
123 dtrace_optval_t	dtrace_helper_providers_max = 32;
124 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
125 size_t		dtrace_strsize_default = 256;
126 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
127 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
128 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
129 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
130 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
131 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
132 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
133 dtrace_optval_t	dtrace_nspec_default = 1;
134 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
135 dtrace_optval_t dtrace_stackframes_default = 20;
136 dtrace_optval_t dtrace_ustackframes_default = 20;
137 dtrace_optval_t dtrace_jstackframes_default = 50;
138 dtrace_optval_t dtrace_jstackstrsize_default = 512;
139 int		dtrace_msgdsize_max = 128;
140 hrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
141 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
142 int		dtrace_devdepth_max = 32;
143 int		dtrace_err_verbose;
144 hrtime_t	dtrace_deadman_interval = NANOSEC;
145 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
146 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
147 
148 /*
149  * DTrace External Variables
150  *
151  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
152  * available to DTrace consumers via the backtick (`) syntax.  One of these,
153  * dtrace_zero, is made deliberately so:  it is provided as a source of
154  * well-known, zero-filled memory.  While this variable is not documented,
155  * it is used by some translators as an implementation detail.
156  */
157 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
158 
159 /*
160  * DTrace Internal Variables
161  */
162 static dev_info_t	*dtrace_devi;		/* device info */
163 static vmem_t		*dtrace_arena;		/* probe ID arena */
164 static vmem_t		*dtrace_minor;		/* minor number arena */
165 static taskq_t		*dtrace_taskq;		/* task queue */
166 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
167 static int		dtrace_nprobes;		/* number of probes */
168 static dtrace_provider_t *dtrace_provider;	/* provider list */
169 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
170 static int		dtrace_opens;		/* number of opens */
171 static int		dtrace_helpers;		/* number of helpers */
172 static void		*dtrace_softstate;	/* softstate pointer */
173 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
174 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
175 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
176 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
177 static int		dtrace_toxranges;	/* number of toxic ranges */
178 static int		dtrace_toxranges_max;	/* size of toxic range array */
179 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
180 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
181 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
182 static kthread_t	*dtrace_panicked;	/* panicking thread */
183 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
184 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
185 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
186 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
187 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
188 
189 /*
190  * DTrace Locking
191  * DTrace is protected by three (relatively coarse-grained) locks:
192  *
193  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
194  *     including enabling state, probes, ECBs, consumer state, helper state,
195  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
196  *     probe context is lock-free -- synchronization is handled via the
197  *     dtrace_sync() cross call mechanism.
198  *
199  * (2) dtrace_provider_lock is required when manipulating provider state, or
200  *     when provider state must be held constant.
201  *
202  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
203  *     when meta provider state must be held constant.
204  *
205  * The lock ordering between these three locks is dtrace_meta_lock before
206  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
207  * several places where dtrace_provider_lock is held by the framework as it
208  * calls into the providers -- which then call back into the framework,
209  * grabbing dtrace_lock.)
210  *
211  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
212  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
213  * role as a coarse-grained lock; it is acquired before both of these locks.
214  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
215  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
216  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
217  * acquired _between_ dtrace_provider_lock and dtrace_lock.
218  */
219 static kmutex_t		dtrace_lock;		/* probe state lock */
220 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
221 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
222 
223 /*
224  * DTrace Provider Variables
225  *
226  * These are the variables relating to DTrace as a provider (that is, the
227  * provider of the BEGIN, END, and ERROR probes).
228  */
229 static dtrace_pattr_t	dtrace_provider_attr = {
230 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
231 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
232 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
233 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
234 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
235 };
236 
237 static void
238 dtrace_nullop(void)
239 {}
240 
241 static dtrace_pops_t	dtrace_provider_ops = {
242 	(void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
243 	(void (*)(void *, struct modctl *))dtrace_nullop,
244 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
245 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
246 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
247 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
248 	NULL,
249 	NULL,
250 	NULL,
251 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
252 };
253 
254 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
255 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
256 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
257 
258 /*
259  * DTrace Helper Tracing Variables
260  */
261 uint32_t dtrace_helptrace_next = 0;
262 uint32_t dtrace_helptrace_nlocals;
263 char	*dtrace_helptrace_buffer;
264 int	dtrace_helptrace_bufsize = 512 * 1024;
265 
266 #ifdef DEBUG
267 int	dtrace_helptrace_enabled = 1;
268 #else
269 int	dtrace_helptrace_enabled = 0;
270 #endif
271 
272 /*
273  * DTrace Error Hashing
274  *
275  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
276  * table.  This is very useful for checking coverage of tests that are
277  * expected to induce DIF or DOF processing errors, and may be useful for
278  * debugging problems in the DIF code generator or in DOF generation .  The
279  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
280  */
281 #ifdef DEBUG
282 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
283 static const char *dtrace_errlast;
284 static kthread_t *dtrace_errthread;
285 static kmutex_t dtrace_errlock;
286 #endif
287 
288 /*
289  * DTrace Macros and Constants
290  *
291  * These are various macros that are useful in various spots in the
292  * implementation, along with a few random constants that have no meaning
293  * outside of the implementation.  There is no real structure to this cpp
294  * mishmash -- but is there ever?
295  */
296 #define	DTRACE_HASHSTR(hash, probe)	\
297 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
298 
299 #define	DTRACE_HASHNEXT(hash, probe)	\
300 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
301 
302 #define	DTRACE_HASHPREV(hash, probe)	\
303 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
304 
305 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
306 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
307 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
308 
309 #define	DTRACE_AGGHASHSIZE_SLEW		17
310 
311 /*
312  * The key for a thread-local variable consists of the lower 61 bits of the
313  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
314  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
315  * equal to a variable identifier.  This is necessary (but not sufficient) to
316  * assure that global associative arrays never collide with thread-local
317  * variables.  To guarantee that they cannot collide, we must also define the
318  * order for keying dynamic variables.  That order is:
319  *
320  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
321  *
322  * Because the variable-key and the tls-key are in orthogonal spaces, there is
323  * no way for a global variable key signature to match a thread-local key
324  * signature.
325  */
326 #define	DTRACE_TLS_THRKEY(where) { \
327 	uint_t intr = 0; \
328 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
329 	for (; actv; actv >>= 1) \
330 		intr++; \
331 	ASSERT(intr < (1 << 3)); \
332 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
333 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
334 }
335 
336 #define	DTRACE_STORE(type, tomax, offset, what) \
337 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
338 
339 #ifndef __i386
340 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
341 	if (addr & (size - 1)) {					\
342 		*flags |= CPU_DTRACE_BADALIGN;				\
343 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
344 		return (0);						\
345 	}
346 #else
347 #define	DTRACE_ALIGNCHECK(addr, size, flags)
348 #endif
349 
350 #define	DTRACE_LOADFUNC(bits)						\
351 /*CSTYLED*/								\
352 uint##bits##_t								\
353 dtrace_load##bits(uintptr_t addr)					\
354 {									\
355 	size_t size = bits / NBBY;					\
356 	/*CSTYLED*/							\
357 	uint##bits##_t rval;						\
358 	int i;								\
359 	volatile uint16_t *flags = (volatile uint16_t *)		\
360 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
361 									\
362 	DTRACE_ALIGNCHECK(addr, size, flags);				\
363 									\
364 	for (i = 0; i < dtrace_toxranges; i++) {			\
365 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
366 			continue;					\
367 									\
368 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
369 			continue;					\
370 									\
371 		/*							\
372 		 * This address falls within a toxic region; return 0.	\
373 		 */							\
374 		*flags |= CPU_DTRACE_BADADDR;				\
375 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
376 		return (0);						\
377 	}								\
378 									\
379 	*flags |= CPU_DTRACE_NOFAULT;					\
380 	/*CSTYLED*/							\
381 	rval = *((volatile uint##bits##_t *)addr);			\
382 	*flags &= ~CPU_DTRACE_NOFAULT;					\
383 									\
384 	return (rval);							\
385 }
386 
387 #ifdef _LP64
388 #define	dtrace_loadptr	dtrace_load64
389 #else
390 #define	dtrace_loadptr	dtrace_load32
391 #endif
392 
393 #define	DTRACE_DYNHASH_FREE	0
394 #define	DTRACE_DYNHASH_SINK	1
395 #define	DTRACE_DYNHASH_VALID	2
396 
397 #define	DTRACE_MATCH_NEXT	0
398 #define	DTRACE_MATCH_DONE	1
399 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
400 #define	DTRACE_STATE_ALIGN	64
401 
402 #define	DTRACE_FLAGS2FLT(flags)						\
403 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
404 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
405 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
406 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
407 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
408 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
409 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
410 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
411 	DTRACEFLT_UNKNOWN)
412 
413 #define	DTRACEACT_ISSTRING(act)						\
414 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
415 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
416 
417 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
418 static void dtrace_enabling_provide(dtrace_provider_t *);
419 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
420 static void dtrace_enabling_matchall(void);
421 static dtrace_state_t *dtrace_anon_grab(void);
422 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
423     dtrace_state_t *, uint64_t, uint64_t);
424 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
425 static void dtrace_buffer_drop(dtrace_buffer_t *);
426 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
427     dtrace_state_t *, dtrace_mstate_t *);
428 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
429     dtrace_optval_t);
430 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
431 
432 /*
433  * DTrace Probe Context Functions
434  *
435  * These functions are called from probe context.  Because probe context is
436  * any context in which C may be called, arbitrarily locks may be held,
437  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
438  * As a result, functions called from probe context may only call other DTrace
439  * support functions -- they may not interact at all with the system at large.
440  * (Note that the ASSERT macro is made probe-context safe by redefining it in
441  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
442  * loads are to be performed from probe context, they _must_ be in terms of
443  * the safe dtrace_load*() variants.
444  *
445  * Some functions in this block are not actually called from probe context;
446  * for these functions, there will be a comment above the function reading
447  * "Note:  not called from probe context."
448  */
449 void
450 dtrace_panic(const char *format, ...)
451 {
452 	va_list alist;
453 
454 	va_start(alist, format);
455 	dtrace_vpanic(format, alist);
456 	va_end(alist);
457 }
458 
459 int
460 dtrace_assfail(const char *a, const char *f, int l)
461 {
462 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
463 
464 	/*
465 	 * We just need something here that even the most clever compiler
466 	 * cannot optimize away.
467 	 */
468 	return (a[(uintptr_t)f]);
469 }
470 
471 /*
472  * Atomically increment a specified error counter from probe context.
473  */
474 static void
475 dtrace_error(uint32_t *counter)
476 {
477 	/*
478 	 * Most counters stored to in probe context are per-CPU counters.
479 	 * However, there are some error conditions that are sufficiently
480 	 * arcane that they don't merit per-CPU storage.  If these counters
481 	 * are incremented concurrently on different CPUs, scalability will be
482 	 * adversely affected -- but we don't expect them to be white-hot in a
483 	 * correctly constructed enabling...
484 	 */
485 	uint32_t oval, nval;
486 
487 	do {
488 		oval = *counter;
489 
490 		if ((nval = oval + 1) == 0) {
491 			/*
492 			 * If the counter would wrap, set it to 1 -- assuring
493 			 * that the counter is never zero when we have seen
494 			 * errors.  (The counter must be 32-bits because we
495 			 * aren't guaranteed a 64-bit compare&swap operation.)
496 			 * To save this code both the infamy of being fingered
497 			 * by a priggish news story and the indignity of being
498 			 * the target of a neo-puritan witch trial, we're
499 			 * carefully avoiding any colorful description of the
500 			 * likelihood of this condition -- but suffice it to
501 			 * say that it is only slightly more likely than the
502 			 * overflow of predicate cache IDs, as discussed in
503 			 * dtrace_predicate_create().
504 			 */
505 			nval = 1;
506 		}
507 	} while (dtrace_cas32(counter, oval, nval) != oval);
508 }
509 
510 /*
511  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
512  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
513  */
514 DTRACE_LOADFUNC(8)
515 DTRACE_LOADFUNC(16)
516 DTRACE_LOADFUNC(32)
517 DTRACE_LOADFUNC(64)
518 
519 static int
520 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
521 {
522 	if (dest < mstate->dtms_scratch_base)
523 		return (0);
524 
525 	if (dest + size < dest)
526 		return (0);
527 
528 	if (dest + size > mstate->dtms_scratch_ptr)
529 		return (0);
530 
531 	return (1);
532 }
533 
534 static int
535 dtrace_canstore_statvar(uint64_t addr, size_t sz,
536     dtrace_statvar_t **svars, int nsvars)
537 {
538 	int i;
539 
540 	for (i = 0; i < nsvars; i++) {
541 		dtrace_statvar_t *svar = svars[i];
542 
543 		if (svar == NULL || svar->dtsv_size == 0)
544 			continue;
545 
546 		if (addr - svar->dtsv_data < svar->dtsv_size &&
547 		    addr + sz <= svar->dtsv_data + svar->dtsv_size)
548 			return (1);
549 	}
550 
551 	return (0);
552 }
553 
554 /*
555  * Check to see if the address is within a memory region to which a store may
556  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
557  * region.  The caller of dtrace_canstore() is responsible for performing any
558  * alignment checks that are needed before stores are actually executed.
559  */
560 static int
561 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
562     dtrace_vstate_t *vstate)
563 {
564 	uintptr_t a;
565 	size_t s;
566 
567 	/*
568 	 * First, check to see if the address is in scratch space...
569 	 */
570 	a = mstate->dtms_scratch_base;
571 	s = mstate->dtms_scratch_size;
572 
573 	if (addr - a < s && addr + sz <= a + s)
574 		return (1);
575 
576 	/*
577 	 * Now check to see if it's a dynamic variable.  This check will pick
578 	 * up both thread-local variables and any global dynamically-allocated
579 	 * variables.
580 	 */
581 	a = (uintptr_t)vstate->dtvs_dynvars.dtds_base;
582 	s = vstate->dtvs_dynvars.dtds_size;
583 	if (addr - a < s && addr + sz <= a + s)
584 		return (1);
585 
586 	/*
587 	 * Finally, check the static local and global variables.  These checks
588 	 * take the longest, so we perform them last.
589 	 */
590 	if (dtrace_canstore_statvar(addr, sz,
591 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
592 		return (1);
593 
594 	if (dtrace_canstore_statvar(addr, sz,
595 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
596 		return (1);
597 
598 	return (0);
599 }
600 
601 /*
602  * Compare two strings using safe loads.
603  */
604 static int
605 dtrace_strncmp(char *s1, char *s2, size_t limit)
606 {
607 	uint8_t c1, c2;
608 	volatile uint16_t *flags;
609 
610 	if (s1 == s2 || limit == 0)
611 		return (0);
612 
613 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
614 
615 	do {
616 		if (s1 == NULL) {
617 			c1 = '\0';
618 		} else {
619 			c1 = dtrace_load8((uintptr_t)s1++);
620 		}
621 
622 		if (s2 == NULL) {
623 			c2 = '\0';
624 		} else {
625 			c2 = dtrace_load8((uintptr_t)s2++);
626 		}
627 
628 		if (c1 != c2)
629 			return (c1 - c2);
630 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
631 
632 	return (0);
633 }
634 
635 /*
636  * Compute strlen(s) for a string using safe memory accesses.  The additional
637  * len parameter is used to specify a maximum length to ensure completion.
638  */
639 static size_t
640 dtrace_strlen(const char *s, size_t lim)
641 {
642 	uint_t len;
643 
644 	for (len = 0; len != lim; len++) {
645 		if (dtrace_load8((uintptr_t)s++) == '\0')
646 			break;
647 	}
648 
649 	return (len);
650 }
651 
652 /*
653  * Check if an address falls within a toxic region.
654  */
655 static int
656 dtrace_istoxic(uintptr_t kaddr, size_t size)
657 {
658 	uintptr_t taddr, tsize;
659 	int i;
660 
661 	for (i = 0; i < dtrace_toxranges; i++) {
662 		taddr = dtrace_toxrange[i].dtt_base;
663 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
664 
665 		if (kaddr - taddr < tsize) {
666 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
667 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
668 			return (1);
669 		}
670 
671 		if (taddr - kaddr < size) {
672 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
673 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
674 			return (1);
675 		}
676 	}
677 
678 	return (0);
679 }
680 
681 /*
682  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
683  * memory specified by the DIF program.  The dst is assumed to be safe memory
684  * that we can store to directly because it is managed by DTrace.  As with
685  * standard bcopy, overlapping copies are handled properly.
686  */
687 static void
688 dtrace_bcopy(const void *src, void *dst, size_t len)
689 {
690 	if (len != 0) {
691 		uint8_t *s1 = dst;
692 		const uint8_t *s2 = src;
693 
694 		if (s1 <= s2) {
695 			do {
696 				*s1++ = dtrace_load8((uintptr_t)s2++);
697 			} while (--len != 0);
698 		} else {
699 			s2 += len;
700 			s1 += len;
701 
702 			do {
703 				*--s1 = dtrace_load8((uintptr_t)--s2);
704 			} while (--len != 0);
705 		}
706 	}
707 }
708 
709 /*
710  * Copy src to dst using safe memory accesses, up to either the specified
711  * length, or the point that a nul byte is encountered.  The src is assumed to
712  * be unsafe memory specified by the DIF program.  The dst is assumed to be
713  * safe memory that we can store to directly because it is managed by DTrace.
714  * Unlike dtrace_bcopy(), overlapping regions are not handled.
715  */
716 static void
717 dtrace_strcpy(const void *src, void *dst, size_t len)
718 {
719 	if (len != 0) {
720 		uint8_t *s1 = dst, c;
721 		const uint8_t *s2 = src;
722 
723 		do {
724 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
725 		} while (--len != 0 && c != '\0');
726 	}
727 }
728 
729 /*
730  * Copy src to dst, deriving the size and type from the specified (BYREF)
731  * variable type.  The src is assumed to be unsafe memory specified by the DIF
732  * program.  The dst is assumed to be DTrace variable memory that is of the
733  * specified type; we assume that we can store to directly.
734  */
735 static void
736 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
737 {
738 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
739 
740 	if (type->dtdt_kind == DIF_TYPE_STRING) {
741 		dtrace_strcpy(src, dst, type->dtdt_size);
742 	} else {
743 		dtrace_bcopy(src, dst, type->dtdt_size);
744 	}
745 }
746 
747 /*
748  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
749  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
750  * safe memory that we can access directly because it is managed by DTrace.
751  */
752 static int
753 dtrace_bcmp(const void *s1, const void *s2, size_t len)
754 {
755 	volatile uint16_t *flags;
756 
757 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
758 
759 	if (s1 == s2)
760 		return (0);
761 
762 	if (s1 == NULL || s2 == NULL)
763 		return (1);
764 
765 	if (s1 != s2 && len != 0) {
766 		const uint8_t *ps1 = s1;
767 		const uint8_t *ps2 = s2;
768 
769 		do {
770 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
771 				return (1);
772 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
773 	}
774 	return (0);
775 }
776 
777 /*
778  * Zero the specified region using a simple byte-by-byte loop.  Note that this
779  * is for safe DTrace-managed memory only.
780  */
781 static void
782 dtrace_bzero(void *dst, size_t len)
783 {
784 	uchar_t *cp;
785 
786 	for (cp = dst; len != 0; len--)
787 		*cp++ = 0;
788 }
789 
790 /*
791  * This privilege check should be used by actions and subroutines to
792  * verify that the user credentials of the process that enabled the
793  * invoking ECB match the target credentials
794  */
795 static int
796 dtrace_priv_proc_common_user(dtrace_state_t *state)
797 {
798 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
799 
800 	/*
801 	 * We should always have a non-NULL state cred here, since if cred
802 	 * is null (anonymous tracing), we fast-path bypass this routine.
803 	 */
804 	ASSERT(s_cr != NULL);
805 
806 	if ((cr = CRED()) != NULL &&
807 	    s_cr->cr_uid == cr->cr_uid &&
808 	    s_cr->cr_uid == cr->cr_ruid &&
809 	    s_cr->cr_uid == cr->cr_suid &&
810 	    s_cr->cr_gid == cr->cr_gid &&
811 	    s_cr->cr_gid == cr->cr_rgid &&
812 	    s_cr->cr_gid == cr->cr_sgid)
813 		return (1);
814 
815 	return (0);
816 }
817 
818 /*
819  * This privilege check should be used by actions and subroutines to
820  * verify that the zone of the process that enabled the invoking ECB
821  * matches the target credentials
822  */
823 static int
824 dtrace_priv_proc_common_zone(dtrace_state_t *state)
825 {
826 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
827 
828 	/*
829 	 * We should always have a non-NULL state cred here, since if cred
830 	 * is null (anonymous tracing), we fast-path bypass this routine.
831 	 */
832 	ASSERT(s_cr != NULL);
833 
834 	if ((cr = CRED()) != NULL &&
835 	    s_cr->cr_zone == cr->cr_zone)
836 		return (1);
837 
838 	return (0);
839 }
840 
841 /*
842  * This privilege check should be used by actions and subroutines to
843  * verify that the process has not setuid or changed credentials.
844  */
845 static int
846 dtrace_priv_proc_common_nocd()
847 {
848 	proc_t *proc;
849 
850 	if ((proc = ttoproc(curthread)) != NULL &&
851 	    !(proc->p_flag & SNOCD))
852 		return (1);
853 
854 	return (0);
855 }
856 
857 static int
858 dtrace_priv_proc_destructive(dtrace_state_t *state)
859 {
860 	int action = state->dts_cred.dcr_action;
861 
862 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
863 	    dtrace_priv_proc_common_zone(state) == 0)
864 		goto bad;
865 
866 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
867 	    dtrace_priv_proc_common_user(state) == 0)
868 		goto bad;
869 
870 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
871 	    dtrace_priv_proc_common_nocd() == 0)
872 		goto bad;
873 
874 	return (1);
875 
876 bad:
877 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
878 
879 	return (0);
880 }
881 
882 static int
883 dtrace_priv_proc_control(dtrace_state_t *state)
884 {
885 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
886 		return (1);
887 
888 	if (dtrace_priv_proc_common_zone(state) &&
889 	    dtrace_priv_proc_common_user(state) &&
890 	    dtrace_priv_proc_common_nocd())
891 		return (1);
892 
893 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
894 
895 	return (0);
896 }
897 
898 static int
899 dtrace_priv_proc(dtrace_state_t *state)
900 {
901 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
902 		return (1);
903 
904 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
905 
906 	return (0);
907 }
908 
909 static int
910 dtrace_priv_kernel(dtrace_state_t *state)
911 {
912 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
913 		return (1);
914 
915 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
916 
917 	return (0);
918 }
919 
920 static int
921 dtrace_priv_kernel_destructive(dtrace_state_t *state)
922 {
923 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
924 		return (1);
925 
926 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
927 
928 	return (0);
929 }
930 
931 /*
932  * Note:  not called from probe context.  This function is called
933  * asynchronously (and at a regular interval) from outside of probe context to
934  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
935  * cleaning is explained in detail in <sys/dtrace_impl.h>.
936  */
937 void
938 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
939 {
940 	dtrace_dynvar_t *dirty;
941 	dtrace_dstate_percpu_t *dcpu;
942 	int i, work = 0;
943 
944 	for (i = 0; i < NCPU; i++) {
945 		dcpu = &dstate->dtds_percpu[i];
946 
947 		ASSERT(dcpu->dtdsc_rinsing == NULL);
948 
949 		/*
950 		 * If the dirty list is NULL, there is no dirty work to do.
951 		 */
952 		if (dcpu->dtdsc_dirty == NULL)
953 			continue;
954 
955 		/*
956 		 * If the clean list is non-NULL, then we're not going to do
957 		 * any work for this CPU -- it means that there has not been
958 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
959 		 * since the last time we cleaned house.
960 		 */
961 		if (dcpu->dtdsc_clean != NULL)
962 			continue;
963 
964 		work = 1;
965 
966 		/*
967 		 * Atomically move the dirty list aside.
968 		 */
969 		do {
970 			dirty = dcpu->dtdsc_dirty;
971 
972 			/*
973 			 * Before we zap the dirty list, set the rinsing list.
974 			 * (This allows for a potential assertion in
975 			 * dtrace_dynvar():  if a free dynamic variable appears
976 			 * on a hash chain, either the dirty list or the
977 			 * rinsing list for some CPU must be non-NULL.)
978 			 */
979 			dcpu->dtdsc_rinsing = dirty;
980 			dtrace_membar_producer();
981 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
982 		    dirty, NULL) != dirty);
983 	}
984 
985 	if (!work) {
986 		/*
987 		 * We have no work to do; we can simply return.
988 		 */
989 		return;
990 	}
991 
992 	dtrace_sync();
993 
994 	for (i = 0; i < NCPU; i++) {
995 		dcpu = &dstate->dtds_percpu[i];
996 
997 		if (dcpu->dtdsc_rinsing == NULL)
998 			continue;
999 
1000 		/*
1001 		 * We are now guaranteed that no hash chain contains a pointer
1002 		 * into this dirty list; we can make it clean.
1003 		 */
1004 		ASSERT(dcpu->dtdsc_clean == NULL);
1005 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1006 		dcpu->dtdsc_rinsing = NULL;
1007 	}
1008 
1009 	/*
1010 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1011 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1012 	 * This prevents a race whereby a CPU incorrectly decides that
1013 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1014 	 * after dtrace_dynvar_clean() has completed.
1015 	 */
1016 	dtrace_sync();
1017 
1018 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1019 }
1020 
1021 /*
1022  * Depending on the value of the op parameter, this function looks-up,
1023  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1024  * allocation is requested, this function will return a pointer to a
1025  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1026  * variable can be allocated.  If NULL is returned, the appropriate counter
1027  * will be incremented.
1028  */
1029 dtrace_dynvar_t *
1030 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1031     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op)
1032 {
1033 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1034 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1035 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1036 	processorid_t me = CPU->cpu_id, cpu = me;
1037 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1038 	size_t bucket, ksize;
1039 	size_t chunksize = dstate->dtds_chunksize;
1040 	uintptr_t kdata, lock, nstate;
1041 	uint_t i;
1042 
1043 	ASSERT(nkeys != 0);
1044 
1045 	/*
1046 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1047 	 * algorithm.  For the by-value portions, we perform the algorithm in
1048 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1049 	 * bit, and seems to have only a minute effect on distribution.  For
1050 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1051 	 * over each referenced byte.  It's painful to do this, but it's much
1052 	 * better than pathological hash distribution.  The efficacy of the
1053 	 * hashing algorithm (and a comparison with other algorithms) may be
1054 	 * found by running the ::dtrace_dynstat MDB dcmd.
1055 	 */
1056 	for (i = 0; i < nkeys; i++) {
1057 		if (key[i].dttk_size == 0) {
1058 			uint64_t val = key[i].dttk_value;
1059 
1060 			hashval += (val >> 48) & 0xffff;
1061 			hashval += (hashval << 10);
1062 			hashval ^= (hashval >> 6);
1063 
1064 			hashval += (val >> 32) & 0xffff;
1065 			hashval += (hashval << 10);
1066 			hashval ^= (hashval >> 6);
1067 
1068 			hashval += (val >> 16) & 0xffff;
1069 			hashval += (hashval << 10);
1070 			hashval ^= (hashval >> 6);
1071 
1072 			hashval += val & 0xffff;
1073 			hashval += (hashval << 10);
1074 			hashval ^= (hashval >> 6);
1075 		} else {
1076 			/*
1077 			 * This is incredibly painful, but it beats the hell
1078 			 * out of the alternative.
1079 			 */
1080 			uint64_t j, size = key[i].dttk_size;
1081 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1082 
1083 			for (j = 0; j < size; j++) {
1084 				hashval += dtrace_load8(base + j);
1085 				hashval += (hashval << 10);
1086 				hashval ^= (hashval >> 6);
1087 			}
1088 		}
1089 	}
1090 
1091 	hashval += (hashval << 3);
1092 	hashval ^= (hashval >> 11);
1093 	hashval += (hashval << 15);
1094 
1095 	/*
1096 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1097 	 * comes out to be one of our two sentinel hash values.  If this
1098 	 * actually happens, we set the hashval to be a value known to be a
1099 	 * non-sentinel value.
1100 	 */
1101 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1102 		hashval = DTRACE_DYNHASH_VALID;
1103 
1104 	/*
1105 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1106 	 * important here, tricks can be pulled to reduce it.  (However, it's
1107 	 * critical that hash collisions be kept to an absolute minimum;
1108 	 * they're much more painful than a divide.)  It's better to have a
1109 	 * solution that generates few collisions and still keeps things
1110 	 * relatively simple.
1111 	 */
1112 	bucket = hashval % dstate->dtds_hashsize;
1113 
1114 	if (op == DTRACE_DYNVAR_DEALLOC) {
1115 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1116 
1117 		for (;;) {
1118 			while ((lock = *lockp) & 1)
1119 				continue;
1120 
1121 			if (dtrace_casptr((void *)lockp,
1122 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1123 				break;
1124 		}
1125 
1126 		dtrace_membar_producer();
1127 	}
1128 
1129 top:
1130 	prev = NULL;
1131 	lock = hash[bucket].dtdh_lock;
1132 
1133 	dtrace_membar_consumer();
1134 
1135 	start = hash[bucket].dtdh_chain;
1136 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1137 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1138 	    op != DTRACE_DYNVAR_DEALLOC));
1139 
1140 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1141 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1142 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1143 
1144 		if (dvar->dtdv_hashval != hashval) {
1145 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1146 				/*
1147 				 * We've reached the sink, and therefore the
1148 				 * end of the hash chain; we can kick out of
1149 				 * the loop knowing that we have seen a valid
1150 				 * snapshot of state.
1151 				 */
1152 				ASSERT(dvar->dtdv_next == NULL);
1153 				ASSERT(dvar == &dtrace_dynhash_sink);
1154 				break;
1155 			}
1156 
1157 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1158 				/*
1159 				 * We've gone off the rails:  somewhere along
1160 				 * the line, one of the members of this hash
1161 				 * chain was deleted.  Note that we could also
1162 				 * detect this by simply letting this loop run
1163 				 * to completion, as we would eventually hit
1164 				 * the end of the dirty list.  However, we
1165 				 * want to avoid running the length of the
1166 				 * dirty list unnecessarily (it might be quite
1167 				 * long), so we catch this as early as
1168 				 * possible by detecting the hash marker.  In
1169 				 * this case, we simply set dvar to NULL and
1170 				 * break; the conditional after the loop will
1171 				 * send us back to top.
1172 				 */
1173 				dvar = NULL;
1174 				break;
1175 			}
1176 
1177 			goto next;
1178 		}
1179 
1180 		if (dtuple->dtt_nkeys != nkeys)
1181 			goto next;
1182 
1183 		for (i = 0; i < nkeys; i++, dkey++) {
1184 			if (dkey->dttk_size != key[i].dttk_size)
1185 				goto next; /* size or type mismatch */
1186 
1187 			if (dkey->dttk_size != 0) {
1188 				if (dtrace_bcmp(
1189 				    (void *)(uintptr_t)key[i].dttk_value,
1190 				    (void *)(uintptr_t)dkey->dttk_value,
1191 				    dkey->dttk_size))
1192 					goto next;
1193 			} else {
1194 				if (dkey->dttk_value != key[i].dttk_value)
1195 					goto next;
1196 			}
1197 		}
1198 
1199 		if (op != DTRACE_DYNVAR_DEALLOC)
1200 			return (dvar);
1201 
1202 		ASSERT(dvar->dtdv_next == NULL ||
1203 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1204 
1205 		if (prev != NULL) {
1206 			ASSERT(hash[bucket].dtdh_chain != dvar);
1207 			ASSERT(start != dvar);
1208 			ASSERT(prev->dtdv_next == dvar);
1209 			prev->dtdv_next = dvar->dtdv_next;
1210 		} else {
1211 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1212 			    start, dvar->dtdv_next) != start) {
1213 				/*
1214 				 * We have failed to atomically swing the
1215 				 * hash table head pointer, presumably because
1216 				 * of a conflicting allocation on another CPU.
1217 				 * We need to reread the hash chain and try
1218 				 * again.
1219 				 */
1220 				goto top;
1221 			}
1222 		}
1223 
1224 		dtrace_membar_producer();
1225 
1226 		/*
1227 		 * Now set the hash value to indicate that it's free.
1228 		 */
1229 		ASSERT(hash[bucket].dtdh_chain != dvar);
1230 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1231 
1232 		dtrace_membar_producer();
1233 
1234 		/*
1235 		 * Set the next pointer to point at the dirty list, and
1236 		 * atomically swing the dirty pointer to the newly freed dvar.
1237 		 */
1238 		do {
1239 			next = dcpu->dtdsc_dirty;
1240 			dvar->dtdv_next = next;
1241 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1242 
1243 		/*
1244 		 * Finally, unlock this hash bucket.
1245 		 */
1246 		ASSERT(hash[bucket].dtdh_lock == lock);
1247 		ASSERT(lock & 1);
1248 		hash[bucket].dtdh_lock++;
1249 
1250 		return (NULL);
1251 next:
1252 		prev = dvar;
1253 		continue;
1254 	}
1255 
1256 	if (dvar == NULL) {
1257 		/*
1258 		 * If dvar is NULL, it is because we went off the rails:
1259 		 * one of the elements that we traversed in the hash chain
1260 		 * was deleted while we were traversing it.  In this case,
1261 		 * we assert that we aren't doing a dealloc (deallocs lock
1262 		 * the hash bucket to prevent themselves from racing with
1263 		 * one another), and retry the hash chain traversal.
1264 		 */
1265 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1266 		goto top;
1267 	}
1268 
1269 	if (op != DTRACE_DYNVAR_ALLOC) {
1270 		/*
1271 		 * If we are not to allocate a new variable, we want to
1272 		 * return NULL now.  Before we return, check that the value
1273 		 * of the lock word hasn't changed.  If it has, we may have
1274 		 * seen an inconsistent snapshot.
1275 		 */
1276 		if (op == DTRACE_DYNVAR_NOALLOC) {
1277 			if (hash[bucket].dtdh_lock != lock)
1278 				goto top;
1279 		} else {
1280 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1281 			ASSERT(hash[bucket].dtdh_lock == lock);
1282 			ASSERT(lock & 1);
1283 			hash[bucket].dtdh_lock++;
1284 		}
1285 
1286 		return (NULL);
1287 	}
1288 
1289 	/*
1290 	 * We need to allocate a new dynamic variable.  The size we need is the
1291 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1292 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1293 	 * the size of any referred-to data (dsize).  We then round the final
1294 	 * size up to the chunksize for allocation.
1295 	 */
1296 	for (ksize = 0, i = 0; i < nkeys; i++)
1297 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1298 
1299 	/*
1300 	 * This should be pretty much impossible, but could happen if, say,
1301 	 * strange DIF specified the tuple.  Ideally, this should be an
1302 	 * assertion and not an error condition -- but that requires that the
1303 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1304 	 * bullet-proof.  (That is, it must not be able to be fooled by
1305 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1306 	 * solving this would presumably not amount to solving the Halting
1307 	 * Problem -- but it still seems awfully hard.
1308 	 */
1309 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1310 	    ksize + dsize > chunksize) {
1311 		dcpu->dtdsc_drops++;
1312 		return (NULL);
1313 	}
1314 
1315 	nstate = DTRACE_DSTATE_EMPTY;
1316 
1317 	do {
1318 retry:
1319 		free = dcpu->dtdsc_free;
1320 
1321 		if (free == NULL) {
1322 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1323 			void *rval;
1324 
1325 			if (clean == NULL) {
1326 				/*
1327 				 * We're out of dynamic variable space on
1328 				 * this CPU.  Unless we have tried all CPUs,
1329 				 * we'll try to allocate from a different
1330 				 * CPU.
1331 				 */
1332 				switch (dstate->dtds_state) {
1333 				case DTRACE_DSTATE_CLEAN: {
1334 					void *sp = &dstate->dtds_state;
1335 
1336 					if (++cpu >= NCPU)
1337 						cpu = 0;
1338 
1339 					if (dcpu->dtdsc_dirty != NULL &&
1340 					    nstate == DTRACE_DSTATE_EMPTY)
1341 						nstate = DTRACE_DSTATE_DIRTY;
1342 
1343 					if (dcpu->dtdsc_rinsing != NULL)
1344 						nstate = DTRACE_DSTATE_RINSING;
1345 
1346 					dcpu = &dstate->dtds_percpu[cpu];
1347 
1348 					if (cpu != me)
1349 						goto retry;
1350 
1351 					(void) dtrace_cas32(sp,
1352 					    DTRACE_DSTATE_CLEAN, nstate);
1353 
1354 					/*
1355 					 * To increment the correct bean
1356 					 * counter, take another lap.
1357 					 */
1358 					goto retry;
1359 				}
1360 
1361 				case DTRACE_DSTATE_DIRTY:
1362 					dcpu->dtdsc_dirty_drops++;
1363 					break;
1364 
1365 				case DTRACE_DSTATE_RINSING:
1366 					dcpu->dtdsc_rinsing_drops++;
1367 					break;
1368 
1369 				case DTRACE_DSTATE_EMPTY:
1370 					dcpu->dtdsc_drops++;
1371 					break;
1372 				}
1373 
1374 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1375 				return (NULL);
1376 			}
1377 
1378 			/*
1379 			 * The clean list appears to be non-empty.  We want to
1380 			 * move the clean list to the free list; we start by
1381 			 * moving the clean pointer aside.
1382 			 */
1383 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1384 			    clean, NULL) != clean) {
1385 				/*
1386 				 * We are in one of two situations:
1387 				 *
1388 				 *  (a)	The clean list was switched to the
1389 				 *	free list by another CPU.
1390 				 *
1391 				 *  (b)	The clean list was added to by the
1392 				 *	cleansing cyclic.
1393 				 *
1394 				 * In either of these situations, we can
1395 				 * just reattempt the free list allocation.
1396 				 */
1397 				goto retry;
1398 			}
1399 
1400 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1401 
1402 			/*
1403 			 * Now we'll move the clean list to the free list.
1404 			 * It's impossible for this to fail:  the only way
1405 			 * the free list can be updated is through this
1406 			 * code path, and only one CPU can own the clean list.
1407 			 * Thus, it would only be possible for this to fail if
1408 			 * this code were racing with dtrace_dynvar_clean().
1409 			 * (That is, if dtrace_dynvar_clean() updated the clean
1410 			 * list, and we ended up racing to update the free
1411 			 * list.)  This race is prevented by the dtrace_sync()
1412 			 * in dtrace_dynvar_clean() -- which flushes the
1413 			 * owners of the clean lists out before resetting
1414 			 * the clean lists.
1415 			 */
1416 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1417 			ASSERT(rval == NULL);
1418 			goto retry;
1419 		}
1420 
1421 		dvar = free;
1422 		new_free = dvar->dtdv_next;
1423 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1424 
1425 	/*
1426 	 * We have now allocated a new chunk.  We copy the tuple keys into the
1427 	 * tuple array and copy any referenced key data into the data space
1428 	 * following the tuple array.  As we do this, we relocate dttk_value
1429 	 * in the final tuple to point to the key data address in the chunk.
1430 	 */
1431 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1432 	dvar->dtdv_data = (void *)(kdata + ksize);
1433 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
1434 
1435 	for (i = 0; i < nkeys; i++) {
1436 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1437 		size_t kesize = key[i].dttk_size;
1438 
1439 		if (kesize != 0) {
1440 			dtrace_bcopy(
1441 			    (const void *)(uintptr_t)key[i].dttk_value,
1442 			    (void *)kdata, kesize);
1443 			dkey->dttk_value = kdata;
1444 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1445 		} else {
1446 			dkey->dttk_value = key[i].dttk_value;
1447 		}
1448 
1449 		dkey->dttk_size = kesize;
1450 	}
1451 
1452 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1453 	dvar->dtdv_hashval = hashval;
1454 	dvar->dtdv_next = start;
1455 
1456 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1457 		return (dvar);
1458 
1459 	/*
1460 	 * The cas has failed.  Either another CPU is adding an element to
1461 	 * this hash chain, or another CPU is deleting an element from this
1462 	 * hash chain.  The simplest way to deal with both of these cases
1463 	 * (though not necessarily the most efficient) is to free our
1464 	 * allocated block and tail-call ourselves.  Note that the free is
1465 	 * to the dirty list and _not_ to the free list.  This is to prevent
1466 	 * races with allocators, above.
1467 	 */
1468 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1469 
1470 	dtrace_membar_producer();
1471 
1472 	do {
1473 		free = dcpu->dtdsc_dirty;
1474 		dvar->dtdv_next = free;
1475 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1476 
1477 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op));
1478 }
1479 
1480 /*ARGSUSED*/
1481 static void
1482 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1483 {
1484 	if (nval < *oval)
1485 		*oval = nval;
1486 }
1487 
1488 /*ARGSUSED*/
1489 static void
1490 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1491 {
1492 	if (nval > *oval)
1493 		*oval = nval;
1494 }
1495 
1496 static void
1497 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1498 {
1499 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1500 	int64_t val = (int64_t)nval;
1501 
1502 	if (val < 0) {
1503 		for (i = 0; i < zero; i++) {
1504 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1505 				quanta[i] += incr;
1506 				return;
1507 			}
1508 		}
1509 	} else {
1510 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1511 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1512 				quanta[i - 1] += incr;
1513 				return;
1514 			}
1515 		}
1516 
1517 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1518 		return;
1519 	}
1520 
1521 	ASSERT(0);
1522 }
1523 
1524 static void
1525 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1526 {
1527 	uint64_t arg = *lquanta++;
1528 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1529 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1530 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1531 	int32_t val = (int32_t)nval, level;
1532 
1533 	ASSERT(step != 0);
1534 	ASSERT(levels != 0);
1535 
1536 	if (val < base) {
1537 		/*
1538 		 * This is an underflow.
1539 		 */
1540 		lquanta[0] += incr;
1541 		return;
1542 	}
1543 
1544 	level = (val - base) / step;
1545 
1546 	if (level < levels) {
1547 		lquanta[level + 1] += incr;
1548 		return;
1549 	}
1550 
1551 	/*
1552 	 * This is an overflow.
1553 	 */
1554 	lquanta[levels + 1] += incr;
1555 }
1556 
1557 /*ARGSUSED*/
1558 static void
1559 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
1560 {
1561 	data[0]++;
1562 	data[1] += nval;
1563 }
1564 
1565 /*ARGSUSED*/
1566 static void
1567 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
1568 {
1569 	*oval = *oval + 1;
1570 }
1571 
1572 /*ARGSUSED*/
1573 static void
1574 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
1575 {
1576 	*oval += nval;
1577 }
1578 
1579 /*
1580  * Aggregate given the tuple in the principal data buffer, and the aggregating
1581  * action denoted by the specified dtrace_aggregation_t.  The aggregation
1582  * buffer is specified as the buf parameter.  This routine does not return
1583  * failure; if there is no space in the aggregation buffer, the data will be
1584  * dropped, and a corresponding counter incremented.
1585  */
1586 static void
1587 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
1588     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
1589 {
1590 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
1591 	uint32_t i, ndx, size, fsize;
1592 	uint32_t align = sizeof (uint64_t) - 1;
1593 	dtrace_aggbuffer_t *agb;
1594 	dtrace_aggkey_t *key;
1595 	uint32_t hashval = 0, limit, isstr;
1596 	caddr_t tomax, data, kdata;
1597 	dtrace_actkind_t action;
1598 	dtrace_action_t *act;
1599 	uintptr_t offs;
1600 
1601 	if (buf == NULL)
1602 		return;
1603 
1604 	if (!agg->dtag_hasarg) {
1605 		/*
1606 		 * Currently, only quantize() and lquantize() take additional
1607 		 * arguments, and they have the same semantics:  an increment
1608 		 * value that defaults to 1 when not present.  If additional
1609 		 * aggregating actions take arguments, the setting of the
1610 		 * default argument value will presumably have to become more
1611 		 * sophisticated...
1612 		 */
1613 		arg = 1;
1614 	}
1615 
1616 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
1617 	size = rec->dtrd_offset - agg->dtag_base;
1618 	fsize = size + rec->dtrd_size;
1619 
1620 	ASSERT(dbuf->dtb_tomax != NULL);
1621 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
1622 
1623 	if ((tomax = buf->dtb_tomax) == NULL) {
1624 		dtrace_buffer_drop(buf);
1625 		return;
1626 	}
1627 
1628 	/*
1629 	 * The metastructure is always at the bottom of the buffer.
1630 	 */
1631 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
1632 	    sizeof (dtrace_aggbuffer_t));
1633 
1634 	if (buf->dtb_offset == 0) {
1635 		/*
1636 		 * We just kludge up approximately 1/8th of the size to be
1637 		 * buckets.  If this guess ends up being routinely
1638 		 * off-the-mark, we may need to dynamically readjust this
1639 		 * based on past performance.
1640 		 */
1641 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
1642 
1643 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
1644 		    (uintptr_t)tomax || hashsize == 0) {
1645 			/*
1646 			 * We've been given a ludicrously small buffer;
1647 			 * increment our drop count and leave.
1648 			 */
1649 			dtrace_buffer_drop(buf);
1650 			return;
1651 		}
1652 
1653 		/*
1654 		 * And now, a pathetic attempt to try to get a an odd (or
1655 		 * perchance, a prime) hash size for better hash distribution.
1656 		 */
1657 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
1658 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
1659 
1660 		agb->dtagb_hashsize = hashsize;
1661 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
1662 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
1663 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
1664 
1665 		for (i = 0; i < agb->dtagb_hashsize; i++)
1666 			agb->dtagb_hash[i] = NULL;
1667 	}
1668 
1669 	ASSERT(agg->dtag_first != NULL);
1670 	ASSERT(agg->dtag_first->dta_intuple);
1671 
1672 	/*
1673 	 * Calculate the hash value based on the key.  Note that we _don't_
1674 	 * include the aggid in the hashing (but we will store it as part of
1675 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
1676 	 * algorithm: a simple, quick algorithm that has no known funnels, and
1677 	 * gets good distribution in practice.  The efficacy of the hashing
1678 	 * algorithm (and a comparison with other algorithms) may be found by
1679 	 * running the ::dtrace_aggstat MDB dcmd.
1680 	 */
1681 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1682 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1683 		limit = i + act->dta_rec.dtrd_size;
1684 		ASSERT(limit <= size);
1685 		isstr = DTRACEACT_ISSTRING(act);
1686 
1687 		for (; i < limit; i++) {
1688 			hashval += data[i];
1689 			hashval += (hashval << 10);
1690 			hashval ^= (hashval >> 6);
1691 
1692 			if (isstr && data[i] == '\0')
1693 				break;
1694 		}
1695 	}
1696 
1697 	hashval += (hashval << 3);
1698 	hashval ^= (hashval >> 11);
1699 	hashval += (hashval << 15);
1700 
1701 	/*
1702 	 * Yes, the divide here is expensive -- but it's generally the least
1703 	 * of the performance issues given the amount of data that we iterate
1704 	 * over to compute hash values, compare data, etc.
1705 	 */
1706 	ndx = hashval % agb->dtagb_hashsize;
1707 
1708 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
1709 		ASSERT((caddr_t)key >= tomax);
1710 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
1711 
1712 		if (hashval != key->dtak_hashval || key->dtak_size != size)
1713 			continue;
1714 
1715 		kdata = key->dtak_data;
1716 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
1717 
1718 		for (act = agg->dtag_first; act->dta_intuple;
1719 		    act = act->dta_next) {
1720 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
1721 			limit = i + act->dta_rec.dtrd_size;
1722 			ASSERT(limit <= size);
1723 			isstr = DTRACEACT_ISSTRING(act);
1724 
1725 			for (; i < limit; i++) {
1726 				if (kdata[i] != data[i])
1727 					goto next;
1728 
1729 				if (isstr && data[i] == '\0')
1730 					break;
1731 			}
1732 		}
1733 
1734 		if (action != key->dtak_action) {
1735 			/*
1736 			 * We are aggregating on the same value in the same
1737 			 * aggregation with two different aggregating actions.
1738 			 * (This should have been picked up in the compiler,
1739 			 * so we may be dealing with errant or devious DIF.)
1740 			 * This is an error condition; we indicate as much,
1741 			 * and return.
1742 			 */
1743 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
1744 			return;
1745 		}
1746 
1747 		/*
1748 		 * This is a hit:  we need to apply the aggregator to
1749 		 * the value at this key.
1750 		 */
1751 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
1752 		return;
1753 next:
1754 		continue;
1755 	}
1756 
1757 	/*
1758 	 * We didn't find it.  We need to allocate some zero-filled space,
1759 	 * link it into the hash table appropriately, and apply the aggregator
1760 	 * to the (zero-filled) value.
1761 	 */
1762 	offs = buf->dtb_offset;
1763 	while (offs & (align - 1))
1764 		offs += sizeof (uint32_t);
1765 
1766 	/*
1767 	 * If we don't have enough room to both allocate a new key _and_
1768 	 * its associated data, increment the drop count and return.
1769 	 */
1770 	if ((uintptr_t)tomax + offs + fsize >
1771 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
1772 		dtrace_buffer_drop(buf);
1773 		return;
1774 	}
1775 
1776 	/*CONSTCOND*/
1777 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
1778 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
1779 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
1780 
1781 	key->dtak_data = kdata = tomax + offs;
1782 	buf->dtb_offset = offs + fsize;
1783 
1784 	/*
1785 	 * Now copy the data across.
1786 	 */
1787 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
1788 
1789 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
1790 		kdata[i] = data[i];
1791 
1792 	/*
1793 	 * Because strings are not zeroed out by default, we need to iterate
1794 	 * looking for actions that store strings, and we need to explicitly
1795 	 * pad these strings out with zeroes.
1796 	 */
1797 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1798 		int nul;
1799 
1800 		if (!DTRACEACT_ISSTRING(act))
1801 			continue;
1802 
1803 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1804 		limit = i + act->dta_rec.dtrd_size;
1805 		ASSERT(limit <= size);
1806 
1807 		for (nul = 0; i < limit; i++) {
1808 			if (nul) {
1809 				kdata[i] = '\0';
1810 				continue;
1811 			}
1812 
1813 			if (data[i] != '\0')
1814 				continue;
1815 
1816 			nul = 1;
1817 		}
1818 	}
1819 
1820 	for (i = size; i < fsize; i++)
1821 		kdata[i] = 0;
1822 
1823 	key->dtak_hashval = hashval;
1824 	key->dtak_size = size;
1825 	key->dtak_action = action;
1826 	key->dtak_next = agb->dtagb_hash[ndx];
1827 	agb->dtagb_hash[ndx] = key;
1828 
1829 	/*
1830 	 * Finally, apply the aggregator.
1831 	 */
1832 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
1833 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
1834 }
1835 
1836 /*
1837  * Given consumer state, this routine finds a speculation in the INACTIVE
1838  * state and transitions it into the ACTIVE state.  If there is no speculation
1839  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
1840  * incremented -- it is up to the caller to take appropriate action.
1841  */
1842 static int
1843 dtrace_speculation(dtrace_state_t *state)
1844 {
1845 	int i = 0;
1846 	dtrace_speculation_state_t current;
1847 	uint32_t *stat = &state->dts_speculations_unavail, count;
1848 
1849 	while (i < state->dts_nspeculations) {
1850 		dtrace_speculation_t *spec = &state->dts_speculations[i];
1851 
1852 		current = spec->dtsp_state;
1853 
1854 		if (current != DTRACESPEC_INACTIVE) {
1855 			if (current == DTRACESPEC_COMMITTINGMANY ||
1856 			    current == DTRACESPEC_COMMITTING ||
1857 			    current == DTRACESPEC_DISCARDING)
1858 				stat = &state->dts_speculations_busy;
1859 			i++;
1860 			continue;
1861 		}
1862 
1863 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
1864 		    current, DTRACESPEC_ACTIVE) == current)
1865 			return (i + 1);
1866 	}
1867 
1868 	/*
1869 	 * We couldn't find a speculation.  If we found as much as a single
1870 	 * busy speculation buffer, we'll attribute this failure as "busy"
1871 	 * instead of "unavail".
1872 	 */
1873 	do {
1874 		count = *stat;
1875 	} while (dtrace_cas32(stat, count, count + 1) != count);
1876 
1877 	return (0);
1878 }
1879 
1880 /*
1881  * This routine commits an active speculation.  If the specified speculation
1882  * is not in a valid state to perform a commit(), this routine will silently do
1883  * nothing.  The state of the specified speculation is transitioned according
1884  * to the state transition diagram outlined in <sys/dtrace_impl.h>
1885  */
1886 static void
1887 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
1888     dtrace_specid_t which)
1889 {
1890 	dtrace_speculation_t *spec;
1891 	dtrace_buffer_t *src, *dest;
1892 	uintptr_t daddr, saddr, dlimit;
1893 	dtrace_speculation_state_t current, new;
1894 	intptr_t offs;
1895 
1896 	if (which == 0)
1897 		return;
1898 
1899 	if (which > state->dts_nspeculations) {
1900 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
1901 		return;
1902 	}
1903 
1904 	spec = &state->dts_speculations[which - 1];
1905 	src = &spec->dtsp_buffer[cpu];
1906 	dest = &state->dts_buffer[cpu];
1907 
1908 	do {
1909 		current = spec->dtsp_state;
1910 
1911 		if (current == DTRACESPEC_COMMITTINGMANY)
1912 			break;
1913 
1914 		switch (current) {
1915 		case DTRACESPEC_INACTIVE:
1916 		case DTRACESPEC_DISCARDING:
1917 			return;
1918 
1919 		case DTRACESPEC_COMMITTING:
1920 			/*
1921 			 * This is only possible if we are (a) commit()'ing
1922 			 * without having done a prior speculate() on this CPU
1923 			 * and (b) racing with another commit() on a different
1924 			 * CPU.  There's nothing to do -- we just assert that
1925 			 * our offset is 0.
1926 			 */
1927 			ASSERT(src->dtb_offset == 0);
1928 			return;
1929 
1930 		case DTRACESPEC_ACTIVE:
1931 			new = DTRACESPEC_COMMITTING;
1932 			break;
1933 
1934 		case DTRACESPEC_ACTIVEONE:
1935 			/*
1936 			 * This speculation is active on one CPU.  If our
1937 			 * buffer offset is non-zero, we know that the one CPU
1938 			 * must be us.  Otherwise, we are committing on a
1939 			 * different CPU from the speculate(), and we must
1940 			 * rely on being asynchronously cleaned.
1941 			 */
1942 			if (src->dtb_offset != 0) {
1943 				new = DTRACESPEC_COMMITTING;
1944 				break;
1945 			}
1946 			/*FALLTHROUGH*/
1947 
1948 		case DTRACESPEC_ACTIVEMANY:
1949 			new = DTRACESPEC_COMMITTINGMANY;
1950 			break;
1951 
1952 		default:
1953 			ASSERT(0);
1954 		}
1955 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
1956 	    current, new) != current);
1957 
1958 	/*
1959 	 * We have set the state to indicate that we are committing this
1960 	 * speculation.  Now reserve the necessary space in the destination
1961 	 * buffer.
1962 	 */
1963 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
1964 	    sizeof (uint64_t), state, NULL)) < 0) {
1965 		dtrace_buffer_drop(dest);
1966 		goto out;
1967 	}
1968 
1969 	/*
1970 	 * We have the space; copy the buffer across.  (Note that this is a
1971 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
1972 	 * a serious performance issue, a high-performance DTrace-specific
1973 	 * bcopy() should obviously be invented.)
1974 	 */
1975 	daddr = (uintptr_t)dest->dtb_tomax + offs;
1976 	dlimit = daddr + src->dtb_offset;
1977 	saddr = (uintptr_t)src->dtb_tomax;
1978 
1979 	/*
1980 	 * First, the aligned portion.
1981 	 */
1982 	while (dlimit - daddr >= sizeof (uint64_t)) {
1983 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
1984 
1985 		daddr += sizeof (uint64_t);
1986 		saddr += sizeof (uint64_t);
1987 	}
1988 
1989 	/*
1990 	 * Now any left-over bit...
1991 	 */
1992 	while (dlimit - daddr)
1993 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
1994 
1995 	/*
1996 	 * Finally, commit the reserved space in the destination buffer.
1997 	 */
1998 	dest->dtb_offset = offs + src->dtb_offset;
1999 
2000 out:
2001 	/*
2002 	 * If we're lucky enough to be the only active CPU on this speculation
2003 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2004 	 */
2005 	if (current == DTRACESPEC_ACTIVE ||
2006 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2007 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2008 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2009 
2010 		ASSERT(rval == DTRACESPEC_COMMITTING);
2011 	}
2012 
2013 	src->dtb_offset = 0;
2014 	src->dtb_xamot_drops += src->dtb_drops;
2015 	src->dtb_drops = 0;
2016 }
2017 
2018 /*
2019  * This routine discards an active speculation.  If the specified speculation
2020  * is not in a valid state to perform a discard(), this routine will silently
2021  * do nothing.  The state of the specified speculation is transitioned
2022  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2023  */
2024 static void
2025 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2026     dtrace_specid_t which)
2027 {
2028 	dtrace_speculation_t *spec;
2029 	dtrace_speculation_state_t current, new;
2030 	dtrace_buffer_t *buf;
2031 
2032 	if (which == 0)
2033 		return;
2034 
2035 	if (which > state->dts_nspeculations) {
2036 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2037 		return;
2038 	}
2039 
2040 	spec = &state->dts_speculations[which - 1];
2041 	buf = &spec->dtsp_buffer[cpu];
2042 
2043 	do {
2044 		current = spec->dtsp_state;
2045 
2046 		switch (current) {
2047 		case DTRACESPEC_INACTIVE:
2048 		case DTRACESPEC_COMMITTINGMANY:
2049 		case DTRACESPEC_COMMITTING:
2050 		case DTRACESPEC_DISCARDING:
2051 			return;
2052 
2053 		case DTRACESPEC_ACTIVE:
2054 		case DTRACESPEC_ACTIVEMANY:
2055 			new = DTRACESPEC_DISCARDING;
2056 			break;
2057 
2058 		case DTRACESPEC_ACTIVEONE:
2059 			if (buf->dtb_offset != 0) {
2060 				new = DTRACESPEC_INACTIVE;
2061 			} else {
2062 				new = DTRACESPEC_DISCARDING;
2063 			}
2064 			break;
2065 
2066 		default:
2067 			ASSERT(0);
2068 		}
2069 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2070 	    current, new) != current);
2071 
2072 	buf->dtb_offset = 0;
2073 	buf->dtb_drops = 0;
2074 }
2075 
2076 /*
2077  * Note:  not called from probe context.  This function is called
2078  * asynchronously from cross call context to clean any speculations that are
2079  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2080  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2081  * speculation.
2082  */
2083 static void
2084 dtrace_speculation_clean_here(dtrace_state_t *state)
2085 {
2086 	dtrace_icookie_t cookie;
2087 	processorid_t cpu = CPU->cpu_id;
2088 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2089 	dtrace_specid_t i;
2090 
2091 	cookie = dtrace_interrupt_disable();
2092 
2093 	if (dest->dtb_tomax == NULL) {
2094 		dtrace_interrupt_enable(cookie);
2095 		return;
2096 	}
2097 
2098 	for (i = 0; i < state->dts_nspeculations; i++) {
2099 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2100 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2101 
2102 		if (src->dtb_tomax == NULL)
2103 			continue;
2104 
2105 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2106 			src->dtb_offset = 0;
2107 			continue;
2108 		}
2109 
2110 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2111 			continue;
2112 
2113 		if (src->dtb_offset == 0)
2114 			continue;
2115 
2116 		dtrace_speculation_commit(state, cpu, i + 1);
2117 	}
2118 
2119 	dtrace_interrupt_enable(cookie);
2120 }
2121 
2122 /*
2123  * Note:  not called from probe context.  This function is called
2124  * asynchronously (and at a regular interval) to clean any speculations that
2125  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2126  * is work to be done, it cross calls all CPUs to perform that work;
2127  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2128  * INACTIVE state until they have been cleaned by all CPUs.
2129  */
2130 static void
2131 dtrace_speculation_clean(dtrace_state_t *state)
2132 {
2133 	int work = 0, rv;
2134 	dtrace_specid_t i;
2135 
2136 	for (i = 0; i < state->dts_nspeculations; i++) {
2137 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2138 
2139 		ASSERT(!spec->dtsp_cleaning);
2140 
2141 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2142 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2143 			continue;
2144 
2145 		work++;
2146 		spec->dtsp_cleaning = 1;
2147 	}
2148 
2149 	if (!work)
2150 		return;
2151 
2152 	dtrace_xcall(DTRACE_CPUALL,
2153 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2154 
2155 	/*
2156 	 * We now know that all CPUs have committed or discarded their
2157 	 * speculation buffers, as appropriate.  We can now set the state
2158 	 * to inactive.
2159 	 */
2160 	for (i = 0; i < state->dts_nspeculations; i++) {
2161 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2162 		dtrace_speculation_state_t current, new;
2163 
2164 		if (!spec->dtsp_cleaning)
2165 			continue;
2166 
2167 		current = spec->dtsp_state;
2168 		ASSERT(current == DTRACESPEC_DISCARDING ||
2169 		    current == DTRACESPEC_COMMITTINGMANY);
2170 
2171 		new = DTRACESPEC_INACTIVE;
2172 
2173 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2174 		ASSERT(rv == current);
2175 		spec->dtsp_cleaning = 0;
2176 	}
2177 }
2178 
2179 /*
2180  * Called as part of a speculate() to get the speculative buffer associated
2181  * with a given speculation.  Returns NULL if the specified speculation is not
2182  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2183  * the active CPU is not the specified CPU -- the speculation will be
2184  * atomically transitioned into the ACTIVEMANY state.
2185  */
2186 static dtrace_buffer_t *
2187 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2188     dtrace_specid_t which)
2189 {
2190 	dtrace_speculation_t *spec;
2191 	dtrace_speculation_state_t current, new;
2192 	dtrace_buffer_t *buf;
2193 
2194 	if (which == 0)
2195 		return (NULL);
2196 
2197 	if (which > state->dts_nspeculations) {
2198 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2199 		return (NULL);
2200 	}
2201 
2202 	spec = &state->dts_speculations[which - 1];
2203 	buf = &spec->dtsp_buffer[cpuid];
2204 
2205 	do {
2206 		current = spec->dtsp_state;
2207 
2208 		switch (current) {
2209 		case DTRACESPEC_INACTIVE:
2210 		case DTRACESPEC_COMMITTINGMANY:
2211 		case DTRACESPEC_DISCARDING:
2212 			return (NULL);
2213 
2214 		case DTRACESPEC_COMMITTING:
2215 			ASSERT(buf->dtb_offset == 0);
2216 			return (NULL);
2217 
2218 		case DTRACESPEC_ACTIVEONE:
2219 			/*
2220 			 * This speculation is currently active on one CPU.
2221 			 * Check the offset in the buffer; if it's non-zero,
2222 			 * that CPU must be us (and we leave the state alone).
2223 			 * If it's zero, assume that we're starting on a new
2224 			 * CPU -- and change the state to indicate that the
2225 			 * speculation is active on more than one CPU.
2226 			 */
2227 			if (buf->dtb_offset != 0)
2228 				return (buf);
2229 
2230 			new = DTRACESPEC_ACTIVEMANY;
2231 			break;
2232 
2233 		case DTRACESPEC_ACTIVEMANY:
2234 			return (buf);
2235 
2236 		case DTRACESPEC_ACTIVE:
2237 			new = DTRACESPEC_ACTIVEONE;
2238 			break;
2239 
2240 		default:
2241 			ASSERT(0);
2242 		}
2243 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2244 	    current, new) != current);
2245 
2246 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2247 	return (buf);
2248 }
2249 
2250 /*
2251  * This function implements the DIF emulator's variable lookups.  The emulator
2252  * passes a reserved variable identifier and optional built-in array index.
2253  */
2254 static uint64_t
2255 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2256     uint64_t ndx)
2257 {
2258 	/*
2259 	 * If we're accessing one of the uncached arguments, we'll turn this
2260 	 * into a reference in the args array.
2261 	 */
2262 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2263 		ndx = v - DIF_VAR_ARG0;
2264 		v = DIF_VAR_ARGS;
2265 	}
2266 
2267 	switch (v) {
2268 	case DIF_VAR_ARGS:
2269 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2270 		if (ndx >= sizeof (mstate->dtms_arg) /
2271 		    sizeof (mstate->dtms_arg[0])) {
2272 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2273 			dtrace_provider_t *pv;
2274 			uint64_t val;
2275 
2276 			pv = mstate->dtms_probe->dtpr_provider;
2277 			if (pv->dtpv_pops.dtps_getargval != NULL)
2278 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2279 				    mstate->dtms_probe->dtpr_id,
2280 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
2281 			else
2282 				val = dtrace_getarg(ndx, aframes);
2283 
2284 			/*
2285 			 * This is regrettably required to keep the compiler
2286 			 * from tail-optimizing the call to dtrace_getarg().
2287 			 * The condition always evaluates to true, but the
2288 			 * compiler has no way of figuring that out a priori.
2289 			 * (None of this would be necessary if the compiler
2290 			 * could be relied upon to _always_ tail-optimize
2291 			 * the call to dtrace_getarg() -- but it can't.)
2292 			 */
2293 			if (mstate->dtms_probe != NULL)
2294 				return (val);
2295 
2296 			ASSERT(0);
2297 		}
2298 
2299 		return (mstate->dtms_arg[ndx]);
2300 
2301 	case DIF_VAR_UREGS: {
2302 		klwp_t *lwp;
2303 
2304 		if (!dtrace_priv_proc(state))
2305 			return (0);
2306 
2307 		if ((lwp = curthread->t_lwp) == NULL) {
2308 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2309 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
2310 			return (0);
2311 		}
2312 
2313 		return (dtrace_getreg(lwp->lwp_regs, ndx));
2314 	}
2315 
2316 	case DIF_VAR_CURTHREAD:
2317 		if (!dtrace_priv_kernel(state))
2318 			return (0);
2319 		return ((uint64_t)(uintptr_t)curthread);
2320 
2321 	case DIF_VAR_TIMESTAMP:
2322 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2323 			mstate->dtms_timestamp = dtrace_gethrtime();
2324 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2325 		}
2326 		return (mstate->dtms_timestamp);
2327 
2328 	case DIF_VAR_VTIMESTAMP:
2329 		ASSERT(dtrace_vtime_references != 0);
2330 		return (curthread->t_dtrace_vtime);
2331 
2332 	case DIF_VAR_WALLTIMESTAMP:
2333 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2334 			mstate->dtms_walltimestamp = dtrace_gethrestime();
2335 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2336 		}
2337 		return (mstate->dtms_walltimestamp);
2338 
2339 	case DIF_VAR_IPL:
2340 		if (!dtrace_priv_kernel(state))
2341 			return (0);
2342 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2343 			mstate->dtms_ipl = dtrace_getipl();
2344 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
2345 		}
2346 		return (mstate->dtms_ipl);
2347 
2348 	case DIF_VAR_EPID:
2349 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2350 		return (mstate->dtms_epid);
2351 
2352 	case DIF_VAR_ID:
2353 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2354 		return (mstate->dtms_probe->dtpr_id);
2355 
2356 	case DIF_VAR_STACKDEPTH:
2357 		if (!dtrace_priv_kernel(state))
2358 			return (0);
2359 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2360 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2361 
2362 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2363 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2364 		}
2365 		return (mstate->dtms_stackdepth);
2366 
2367 	case DIF_VAR_USTACKDEPTH:
2368 		if (!dtrace_priv_proc(state))
2369 			return (0);
2370 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2371 			/*
2372 			 * See comment in DIF_VAR_PID.
2373 			 */
2374 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2375 			    CPU_ON_INTR(CPU)) {
2376 				mstate->dtms_ustackdepth = 0;
2377 			} else {
2378 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2379 				mstate->dtms_ustackdepth =
2380 				    dtrace_getustackdepth();
2381 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2382 			}
2383 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2384 		}
2385 		return (mstate->dtms_ustackdepth);
2386 
2387 	case DIF_VAR_CALLER:
2388 		if (!dtrace_priv_kernel(state))
2389 			return (0);
2390 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2391 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2392 
2393 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2394 				/*
2395 				 * If this is an unanchored probe, we are
2396 				 * required to go through the slow path:
2397 				 * dtrace_caller() only guarantees correct
2398 				 * results for anchored probes.
2399 				 */
2400 				pc_t caller[2];
2401 
2402 				dtrace_getpcstack(caller, 2, aframes,
2403 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2404 				mstate->dtms_caller = caller[1];
2405 			} else if ((mstate->dtms_caller =
2406 			    dtrace_caller(aframes)) == -1) {
2407 				/*
2408 				 * We have failed to do this the quick way;
2409 				 * we must resort to the slower approach of
2410 				 * calling dtrace_getpcstack().
2411 				 */
2412 				pc_t caller;
2413 
2414 				dtrace_getpcstack(&caller, 1, aframes, NULL);
2415 				mstate->dtms_caller = caller;
2416 			}
2417 
2418 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
2419 		}
2420 		return (mstate->dtms_caller);
2421 
2422 	case DIF_VAR_UCALLER:
2423 		if (!dtrace_priv_proc(state))
2424 			return (0);
2425 
2426 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
2427 			uint64_t ustack[3];
2428 
2429 			/*
2430 			 * dtrace_getupcstack() fills in the first uint64_t
2431 			 * with the current PID.  The second uint64_t will
2432 			 * be the program counter at user-level.  The third
2433 			 * uint64_t will contain the caller, which is what
2434 			 * we're after.
2435 			 */
2436 			ustack[2] = NULL;
2437 			dtrace_getupcstack(ustack, 3);
2438 			mstate->dtms_ucaller = ustack[2];
2439 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
2440 		}
2441 
2442 		return (mstate->dtms_ucaller);
2443 
2444 	case DIF_VAR_PROBEPROV:
2445 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2446 		return ((uint64_t)(uintptr_t)
2447 		    mstate->dtms_probe->dtpr_provider->dtpv_name);
2448 
2449 	case DIF_VAR_PROBEMOD:
2450 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2451 		return ((uint64_t)(uintptr_t)
2452 		    mstate->dtms_probe->dtpr_mod);
2453 
2454 	case DIF_VAR_PROBEFUNC:
2455 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2456 		return ((uint64_t)(uintptr_t)
2457 		    mstate->dtms_probe->dtpr_func);
2458 
2459 	case DIF_VAR_PROBENAME:
2460 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2461 		return ((uint64_t)(uintptr_t)
2462 		    mstate->dtms_probe->dtpr_name);
2463 
2464 	case DIF_VAR_PID:
2465 		if (!dtrace_priv_proc(state))
2466 			return (0);
2467 
2468 		/*
2469 		 * Note that we are assuming that an unanchored probe is
2470 		 * always due to a high-level interrupt.  (And we're assuming
2471 		 * that there is only a single high level interrupt.)
2472 		 */
2473 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2474 			return (pid0.pid_id);
2475 
2476 		/*
2477 		 * It is always safe to dereference one's own t_procp pointer:
2478 		 * it always points to a valid, allocated proc structure.
2479 		 * Further, it is always safe to dereference the p_pidp member
2480 		 * of one's own proc structure.  (These are truisms becuase
2481 		 * threads and processes don't clean up their own state --
2482 		 * they leave that task to whomever reaps them.)
2483 		 */
2484 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
2485 
2486 	case DIF_VAR_TID:
2487 		/*
2488 		 * See comment in DIF_VAR_PID.
2489 		 */
2490 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2491 			return (0);
2492 
2493 		return ((uint64_t)curthread->t_tid);
2494 
2495 	case DIF_VAR_EXECNAME:
2496 		if (!dtrace_priv_proc(state))
2497 			return (0);
2498 
2499 		/*
2500 		 * See comment in DIF_VAR_PID.
2501 		 */
2502 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2503 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
2504 
2505 		/*
2506 		 * It is always safe to dereference one's own t_procp pointer:
2507 		 * it always points to a valid, allocated proc structure.
2508 		 * (This is true because threads don't clean up their own
2509 		 * state -- they leave that task to whomever reaps them.)
2510 		 */
2511 		return ((uint64_t)(uintptr_t)
2512 		    curthread->t_procp->p_user.u_comm);
2513 
2514 	case DIF_VAR_ZONENAME:
2515 		if (!dtrace_priv_proc(state))
2516 			return (0);
2517 
2518 		/*
2519 		 * See comment in DIF_VAR_PID.
2520 		 */
2521 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2522 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
2523 
2524 		/*
2525 		 * It is always safe to dereference one's own t_procp pointer:
2526 		 * it always points to a valid, allocated proc structure.
2527 		 * (This is true because threads don't clean up their own
2528 		 * state -- they leave that task to whomever reaps them.)
2529 		 */
2530 		return ((uint64_t)(uintptr_t)
2531 		    curthread->t_procp->p_zone->zone_name);
2532 
2533 	default:
2534 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2535 		return (0);
2536 	}
2537 }
2538 
2539 /*
2540  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
2541  * Notice that we don't bother validating the proper number of arguments or
2542  * their types in the tuple stack.  This isn't needed because all argument
2543  * interpretation is safe because of our load safety -- the worst that can
2544  * happen is that a bogus program can obtain bogus results.
2545  */
2546 static void
2547 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
2548     dtrace_key_t *tupregs, int nargs,
2549     dtrace_mstate_t *mstate, dtrace_state_t *state)
2550 {
2551 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
2552 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
2553 
2554 	union {
2555 		mutex_impl_t mi;
2556 		uint64_t mx;
2557 	} m;
2558 
2559 	union {
2560 		krwlock_t ri;
2561 		uintptr_t rw;
2562 	} r;
2563 
2564 	switch (subr) {
2565 	case DIF_SUBR_RAND:
2566 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
2567 		break;
2568 
2569 	case DIF_SUBR_MUTEX_OWNED:
2570 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2571 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
2572 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
2573 		else
2574 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
2575 		break;
2576 
2577 	case DIF_SUBR_MUTEX_OWNER:
2578 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2579 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
2580 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
2581 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
2582 		else
2583 			regs[rd] = 0;
2584 		break;
2585 
2586 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
2587 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2588 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
2589 		break;
2590 
2591 	case DIF_SUBR_MUTEX_TYPE_SPIN:
2592 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2593 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
2594 		break;
2595 
2596 	case DIF_SUBR_RW_READ_HELD: {
2597 		uintptr_t tmp;
2598 
2599 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2600 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
2601 		break;
2602 	}
2603 
2604 	case DIF_SUBR_RW_WRITE_HELD:
2605 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2606 		regs[rd] = _RW_WRITE_HELD(&r.ri);
2607 		break;
2608 
2609 	case DIF_SUBR_RW_ISWRITER:
2610 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2611 		regs[rd] = _RW_ISWRITER(&r.ri);
2612 		break;
2613 
2614 	case DIF_SUBR_BCOPY: {
2615 		/*
2616 		 * We need to be sure that the destination is in the scratch
2617 		 * region -- no other region is allowed.
2618 		 */
2619 		uintptr_t src = tupregs[0].dttk_value;
2620 		uintptr_t dest = tupregs[1].dttk_value;
2621 		size_t size = tupregs[2].dttk_value;
2622 
2623 		if (!dtrace_inscratch(dest, size, mstate)) {
2624 			*flags |= CPU_DTRACE_BADADDR;
2625 			*illval = regs[rd];
2626 			break;
2627 		}
2628 
2629 		dtrace_bcopy((void *)src, (void *)dest, size);
2630 		break;
2631 	}
2632 
2633 	case DIF_SUBR_ALLOCA:
2634 	case DIF_SUBR_COPYIN: {
2635 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
2636 		uint64_t size =
2637 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
2638 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
2639 
2640 		/*
2641 		 * This action doesn't require any credential checks since
2642 		 * probes will not activate in user contexts to which the
2643 		 * enabling user does not have permissions.
2644 		 */
2645 		if (mstate->dtms_scratch_ptr + scratch_size >
2646 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2647 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2648 			regs[rd] = NULL;
2649 			break;
2650 		}
2651 
2652 		if (subr == DIF_SUBR_COPYIN) {
2653 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2654 			dtrace_copyin(tupregs[0].dttk_value, dest, size);
2655 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2656 		}
2657 
2658 		mstate->dtms_scratch_ptr += scratch_size;
2659 		regs[rd] = dest;
2660 		break;
2661 	}
2662 
2663 	case DIF_SUBR_COPYINTO: {
2664 		uint64_t size = tupregs[1].dttk_value;
2665 		uintptr_t dest = tupregs[2].dttk_value;
2666 
2667 		/*
2668 		 * This action doesn't require any credential checks since
2669 		 * probes will not activate in user contexts to which the
2670 		 * enabling user does not have permissions.
2671 		 */
2672 		if (!dtrace_inscratch(dest, size, mstate)) {
2673 			*flags |= CPU_DTRACE_BADADDR;
2674 			*illval = regs[rd];
2675 			break;
2676 		}
2677 
2678 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2679 		dtrace_copyin(tupregs[0].dttk_value, dest, size);
2680 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2681 		break;
2682 	}
2683 
2684 	case DIF_SUBR_COPYINSTR: {
2685 		uintptr_t dest = mstate->dtms_scratch_ptr;
2686 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2687 
2688 		if (nargs > 1 && tupregs[1].dttk_value < size)
2689 			size = tupregs[1].dttk_value + 1;
2690 
2691 		/*
2692 		 * This action doesn't require any credential checks since
2693 		 * probes will not activate in user contexts to which the
2694 		 * enabling user does not have permissions.
2695 		 */
2696 		if (mstate->dtms_scratch_ptr + size >
2697 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2698 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2699 			regs[rd] = NULL;
2700 			break;
2701 		}
2702 
2703 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2704 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size);
2705 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2706 
2707 		((char *)dest)[size - 1] = '\0';
2708 		mstate->dtms_scratch_ptr += size;
2709 		regs[rd] = dest;
2710 		break;
2711 	}
2712 
2713 	case DIF_SUBR_MSGSIZE:
2714 	case DIF_SUBR_MSGDSIZE: {
2715 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
2716 		uintptr_t wptr, rptr;
2717 		size_t count = 0;
2718 		int cont = 0;
2719 
2720 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
2721 			wptr = dtrace_loadptr(baddr +
2722 			    offsetof(mblk_t, b_wptr));
2723 
2724 			rptr = dtrace_loadptr(baddr +
2725 			    offsetof(mblk_t, b_rptr));
2726 
2727 			if (wptr < rptr) {
2728 				*flags |= CPU_DTRACE_BADADDR;
2729 				*illval = tupregs[0].dttk_value;
2730 				break;
2731 			}
2732 
2733 			daddr = dtrace_loadptr(baddr +
2734 			    offsetof(mblk_t, b_datap));
2735 
2736 			baddr = dtrace_loadptr(baddr +
2737 			    offsetof(mblk_t, b_cont));
2738 
2739 			/*
2740 			 * We want to prevent against denial-of-service here,
2741 			 * so we're only going to search the list for
2742 			 * dtrace_msgdsize_max mblks.
2743 			 */
2744 			if (cont++ > dtrace_msgdsize_max) {
2745 				*flags |= CPU_DTRACE_ILLOP;
2746 				break;
2747 			}
2748 
2749 			if (subr == DIF_SUBR_MSGDSIZE) {
2750 				if (dtrace_load8(daddr +
2751 				    offsetof(dblk_t, db_type)) != M_DATA)
2752 					continue;
2753 			}
2754 
2755 			count += wptr - rptr;
2756 		}
2757 
2758 		if (!(*flags & CPU_DTRACE_FAULT))
2759 			regs[rd] = count;
2760 
2761 		break;
2762 	}
2763 
2764 	case DIF_SUBR_PROGENYOF: {
2765 		pid_t pid = tupregs[0].dttk_value;
2766 		proc_t *p;
2767 		int rval = 0;
2768 
2769 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2770 
2771 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
2772 			if (p->p_pidp->pid_id == pid) {
2773 				rval = 1;
2774 				break;
2775 			}
2776 		}
2777 
2778 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2779 
2780 		regs[rd] = rval;
2781 		break;
2782 	}
2783 
2784 	case DIF_SUBR_SPECULATION:
2785 		regs[rd] = dtrace_speculation(state);
2786 		break;
2787 
2788 	case DIF_SUBR_COPYOUT: {
2789 		uintptr_t kaddr = tupregs[0].dttk_value;
2790 		uintptr_t uaddr = tupregs[1].dttk_value;
2791 		uint64_t size = tupregs[2].dttk_value;
2792 
2793 		if (!dtrace_destructive_disallow &&
2794 		    dtrace_priv_proc_control(state) &&
2795 		    !dtrace_istoxic(kaddr, size)) {
2796 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2797 			dtrace_copyout(kaddr, uaddr, size);
2798 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2799 		}
2800 		break;
2801 	}
2802 
2803 	case DIF_SUBR_COPYOUTSTR: {
2804 		uintptr_t kaddr = tupregs[0].dttk_value;
2805 		uintptr_t uaddr = tupregs[1].dttk_value;
2806 		uint64_t size = tupregs[2].dttk_value;
2807 
2808 		if (!dtrace_destructive_disallow &&
2809 		    dtrace_priv_proc_control(state) &&
2810 		    !dtrace_istoxic(kaddr, size)) {
2811 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2812 			dtrace_copyoutstr(kaddr, uaddr, size);
2813 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2814 		}
2815 		break;
2816 	}
2817 
2818 	case DIF_SUBR_STRLEN:
2819 		regs[rd] = dtrace_strlen((char *)(uintptr_t)
2820 		    tupregs[0].dttk_value,
2821 		    state->dts_options[DTRACEOPT_STRSIZE]);
2822 		break;
2823 
2824 	case DIF_SUBR_STRCHR:
2825 	case DIF_SUBR_STRRCHR: {
2826 		/*
2827 		 * We're going to iterate over the string looking for the
2828 		 * specified character.  We will iterate until we have reached
2829 		 * the string length or we have found the character.  If this
2830 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
2831 		 * of the specified character instead of the first.
2832 		 */
2833 		uintptr_t addr = tupregs[0].dttk_value;
2834 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
2835 		char c, target = (char)tupregs[1].dttk_value;
2836 
2837 		for (regs[rd] = NULL; addr < limit; addr++) {
2838 			if ((c = dtrace_load8(addr)) == target) {
2839 				regs[rd] = addr;
2840 
2841 				if (subr == DIF_SUBR_STRCHR)
2842 					break;
2843 			}
2844 
2845 			if (c == '\0')
2846 				break;
2847 		}
2848 
2849 		break;
2850 	}
2851 
2852 	case DIF_SUBR_STRSTR:
2853 	case DIF_SUBR_INDEX:
2854 	case DIF_SUBR_RINDEX: {
2855 		/*
2856 		 * We're going to iterate over the string looking for the
2857 		 * specified string.  We will iterate until we have reached
2858 		 * the string length or we have found the string.  (Yes, this
2859 		 * is done in the most naive way possible -- but considering
2860 		 * that the string we're searching for is likely to be
2861 		 * relatively short, the complexity of Rabin-Karp or similar
2862 		 * hardly seems merited.)
2863 		 */
2864 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
2865 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
2866 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2867 		size_t len = dtrace_strlen(addr, size);
2868 		size_t sublen = dtrace_strlen(substr, size);
2869 		char *limit = addr + len, *orig = addr;
2870 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
2871 		int inc = 1;
2872 
2873 		regs[rd] = notfound;
2874 
2875 		/*
2876 		 * strstr() and index()/rindex() have similar semantics if
2877 		 * both strings are the empty string: strstr() returns a
2878 		 * pointer to the (empty) string, and index() and rindex()
2879 		 * both return index 0 (regardless of any position argument).
2880 		 */
2881 		if (sublen == 0 && len == 0) {
2882 			if (subr == DIF_SUBR_STRSTR)
2883 				regs[rd] = (uintptr_t)addr;
2884 			else
2885 				regs[rd] = 0;
2886 			break;
2887 		}
2888 
2889 		if (subr != DIF_SUBR_STRSTR) {
2890 			if (subr == DIF_SUBR_RINDEX) {
2891 				limit = orig - 1;
2892 				addr += len;
2893 				inc = -1;
2894 			}
2895 
2896 			/*
2897 			 * Both index() and rindex() take an optional position
2898 			 * argument that denotes the starting position.
2899 			 */
2900 			if (nargs == 3) {
2901 				int64_t pos = (int64_t)tupregs[2].dttk_value;
2902 
2903 				/*
2904 				 * If the position argument to index() is
2905 				 * negative, Perl implicitly clamps it at
2906 				 * zero.  This semantic is a little surprising
2907 				 * given the special meaning of negative
2908 				 * positions to similar Perl functions like
2909 				 * substr(), but it appears to reflect a
2910 				 * notion that index() can start from a
2911 				 * negative index and increment its way up to
2912 				 * the string.  Given this notion, Perl's
2913 				 * rindex() is at least self-consistent in
2914 				 * that it implicitly clamps positions greater
2915 				 * than the string length to be the string
2916 				 * length.  Where Perl completely loses
2917 				 * coherence, however, is when the specified
2918 				 * substring is the empty string ("").  In
2919 				 * this case, even if the position is
2920 				 * negative, rindex() returns 0 -- and even if
2921 				 * the position is greater than the length,
2922 				 * index() returns the string length.  These
2923 				 * semantics violate the notion that index()
2924 				 * should never return a value less than the
2925 				 * specified position and that rindex() should
2926 				 * never return a value greater than the
2927 				 * specified position.  (One assumes that
2928 				 * these semantics are artifacts of Perl's
2929 				 * implementation and not the results of
2930 				 * deliberate design -- it beggars belief that
2931 				 * even Larry Wall could desire such oddness.)
2932 				 * While in the abstract one would wish for
2933 				 * consistent position semantics across
2934 				 * substr(), index() and rindex() -- or at the
2935 				 * very least self-consistent position
2936 				 * semantics for index() and rindex() -- we
2937 				 * instead opt to keep with the extant Perl
2938 				 * semantics, in all their broken glory.  (Do
2939 				 * we have more desire to maintain Perl's
2940 				 * semantics than Perl does?  Probably.)
2941 				 */
2942 				if (subr == DIF_SUBR_RINDEX) {
2943 					if (pos < 0) {
2944 						if (sublen == 0)
2945 							regs[rd] = 0;
2946 						break;
2947 					}
2948 
2949 					if (pos > len)
2950 						pos = len;
2951 				} else {
2952 					if (pos < 0)
2953 						pos = 0;
2954 
2955 					if (pos >= len) {
2956 						if (sublen == 0)
2957 							regs[rd] = len;
2958 						break;
2959 					}
2960 				}
2961 
2962 				addr = orig + pos;
2963 			}
2964 		}
2965 
2966 		for (regs[rd] = notfound; addr != limit; addr += inc) {
2967 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
2968 				if (subr != DIF_SUBR_STRSTR) {
2969 					/*
2970 					 * As D index() and rindex() are
2971 					 * modeled on Perl (and not on awk),
2972 					 * we return a zero-based (and not a
2973 					 * one-based) index.  (For you Perl
2974 					 * weenies: no, we're not going to add
2975 					 * $[ -- and shouldn't you be at a con
2976 					 * or something?)
2977 					 */
2978 					regs[rd] = (uintptr_t)(addr - orig);
2979 					break;
2980 				}
2981 
2982 				ASSERT(subr == DIF_SUBR_STRSTR);
2983 				regs[rd] = (uintptr_t)addr;
2984 				break;
2985 			}
2986 		}
2987 
2988 		break;
2989 	}
2990 
2991 	case DIF_SUBR_STRTOK: {
2992 		uintptr_t addr = tupregs[0].dttk_value;
2993 		uintptr_t tokaddr = tupregs[1].dttk_value;
2994 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2995 		uintptr_t limit, toklimit = tokaddr + size;
2996 		uint8_t c, tokmap[32];	 /* 256 / 8 */
2997 		char *dest = (char *)mstate->dtms_scratch_ptr;
2998 		int i;
2999 
3000 		if (mstate->dtms_scratch_ptr + size >
3001 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3002 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3003 			regs[rd] = NULL;
3004 			break;
3005 		}
3006 
3007 		if (addr == NULL) {
3008 			/*
3009 			 * If the address specified is NULL, we use our saved
3010 			 * strtok pointer from the mstate.  Note that this
3011 			 * means that the saved strtok pointer is _only_
3012 			 * valid within multiple enablings of the same probe --
3013 			 * it behaves like an implicit clause-local variable.
3014 			 */
3015 			addr = mstate->dtms_strtok;
3016 		}
3017 
3018 		/*
3019 		 * First, zero the token map, and then process the token
3020 		 * string -- setting a bit in the map for every character
3021 		 * found in the token string.
3022 		 */
3023 		for (i = 0; i < sizeof (tokmap); i++)
3024 			tokmap[i] = 0;
3025 
3026 		for (; tokaddr < toklimit; tokaddr++) {
3027 			if ((c = dtrace_load8(tokaddr)) == '\0')
3028 				break;
3029 
3030 			ASSERT((c >> 3) < sizeof (tokmap));
3031 			tokmap[c >> 3] |= (1 << (c & 0x7));
3032 		}
3033 
3034 		for (limit = addr + size; addr < limit; addr++) {
3035 			/*
3036 			 * We're looking for a character that is _not_ contained
3037 			 * in the token string.
3038 			 */
3039 			if ((c = dtrace_load8(addr)) == '\0')
3040 				break;
3041 
3042 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3043 				break;
3044 		}
3045 
3046 		if (c == '\0') {
3047 			/*
3048 			 * We reached the end of the string without finding
3049 			 * any character that was not in the token string.
3050 			 * We return NULL in this case, and we set the saved
3051 			 * address to NULL as well.
3052 			 */
3053 			regs[rd] = NULL;
3054 			mstate->dtms_strtok = NULL;
3055 			break;
3056 		}
3057 
3058 		/*
3059 		 * From here on, we're copying into the destination string.
3060 		 */
3061 		for (i = 0; addr < limit && i < size - 1; addr++) {
3062 			if ((c = dtrace_load8(addr)) == '\0')
3063 				break;
3064 
3065 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
3066 				break;
3067 
3068 			ASSERT(i < size);
3069 			dest[i++] = c;
3070 		}
3071 
3072 		ASSERT(i < size);
3073 		dest[i] = '\0';
3074 		regs[rd] = (uintptr_t)dest;
3075 		mstate->dtms_scratch_ptr += size;
3076 		mstate->dtms_strtok = addr;
3077 		break;
3078 	}
3079 
3080 	case DIF_SUBR_SUBSTR: {
3081 		uintptr_t s = tupregs[0].dttk_value;
3082 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3083 		char *d = (char *)mstate->dtms_scratch_ptr;
3084 		int64_t index = (int64_t)tupregs[1].dttk_value;
3085 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
3086 		size_t len = dtrace_strlen((char *)s, size);
3087 		int64_t i = 0;
3088 
3089 		if (nargs <= 2)
3090 			remaining = (int64_t)size;
3091 
3092 		if (mstate->dtms_scratch_ptr + size >
3093 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3094 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3095 			regs[rd] = NULL;
3096 			break;
3097 		}
3098 
3099 		if (index < 0) {
3100 			index += len;
3101 
3102 			if (index < 0 && index + remaining > 0) {
3103 				remaining += index;
3104 				index = 0;
3105 			}
3106 		}
3107 
3108 		if (index >= len || index < 0)
3109 			index = len;
3110 
3111 		for (d[0] = '\0'; remaining > 0; remaining--) {
3112 			if ((d[i++] = dtrace_load8(s++ + index)) == '\0')
3113 				break;
3114 
3115 			if (i == size) {
3116 				d[i - 1] = '\0';
3117 				break;
3118 			}
3119 		}
3120 
3121 		mstate->dtms_scratch_ptr += size;
3122 		regs[rd] = (uintptr_t)d;
3123 		break;
3124 	}
3125 
3126 	case DIF_SUBR_GETMAJOR:
3127 #ifdef _LP64
3128 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
3129 #else
3130 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
3131 #endif
3132 		break;
3133 
3134 	case DIF_SUBR_GETMINOR:
3135 #ifdef _LP64
3136 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
3137 #else
3138 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
3139 #endif
3140 		break;
3141 
3142 	case DIF_SUBR_DDI_PATHNAME: {
3143 		/*
3144 		 * This one is a galactic mess.  We are going to roughly
3145 		 * emulate ddi_pathname(), but it's made more complicated
3146 		 * by the fact that we (a) want to include the minor name and
3147 		 * (b) must proceed iteratively instead of recursively.
3148 		 */
3149 		uintptr_t dest = mstate->dtms_scratch_ptr;
3150 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3151 		char *start = (char *)dest, *end = start + size - 1;
3152 		uintptr_t daddr = tupregs[0].dttk_value;
3153 		int64_t minor = (int64_t)tupregs[1].dttk_value;
3154 		char *s;
3155 		int i, len, depth = 0;
3156 
3157 		if (size == 0 || mstate->dtms_scratch_ptr + size >
3158 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3159 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3160 			regs[rd] = NULL;
3161 			break;
3162 		}
3163 
3164 		*end = '\0';
3165 
3166 		/*
3167 		 * We want to have a name for the minor.  In order to do this,
3168 		 * we need to walk the minor list from the devinfo.  We want
3169 		 * to be sure that we don't infinitely walk a circular list,
3170 		 * so we check for circularity by sending a scout pointer
3171 		 * ahead two elements for every element that we iterate over;
3172 		 * if the list is circular, these will ultimately point to the
3173 		 * same element.  You may recognize this little trick as the
3174 		 * answer to a stupid interview question -- one that always
3175 		 * seems to be asked by those who had to have it laboriously
3176 		 * explained to them, and who can't even concisely describe
3177 		 * the conditions under which one would be forced to resort to
3178 		 * this technique.  Needless to say, those conditions are
3179 		 * found here -- and probably only here.  Is this is the only
3180 		 * use of this infamous trick in shipping, production code?
3181 		 * If it isn't, it probably should be...
3182 		 */
3183 		if (minor != -1) {
3184 			uintptr_t maddr = dtrace_loadptr(daddr +
3185 			    offsetof(struct dev_info, devi_minor));
3186 
3187 			uintptr_t next = offsetof(struct ddi_minor_data, next);
3188 			uintptr_t name = offsetof(struct ddi_minor_data,
3189 			    d_minor) + offsetof(struct ddi_minor, name);
3190 			uintptr_t dev = offsetof(struct ddi_minor_data,
3191 			    d_minor) + offsetof(struct ddi_minor, dev);
3192 			uintptr_t scout;
3193 
3194 			if (maddr != NULL)
3195 				scout = dtrace_loadptr(maddr + next);
3196 
3197 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3198 				uint64_t m;
3199 #ifdef _LP64
3200 				m = dtrace_load64(maddr + dev) & MAXMIN64;
3201 #else
3202 				m = dtrace_load32(maddr + dev) & MAXMIN;
3203 #endif
3204 				if (m != minor) {
3205 					maddr = dtrace_loadptr(maddr + next);
3206 
3207 					if (scout == NULL)
3208 						continue;
3209 
3210 					scout = dtrace_loadptr(scout + next);
3211 
3212 					if (scout == NULL)
3213 						continue;
3214 
3215 					scout = dtrace_loadptr(scout + next);
3216 
3217 					if (scout == NULL)
3218 						continue;
3219 
3220 					if (scout == maddr) {
3221 						*flags |= CPU_DTRACE_ILLOP;
3222 						break;
3223 					}
3224 
3225 					continue;
3226 				}
3227 
3228 				/*
3229 				 * We have the minor data.  Now we need to
3230 				 * copy the minor's name into the end of the
3231 				 * pathname.
3232 				 */
3233 				s = (char *)dtrace_loadptr(maddr + name);
3234 				len = dtrace_strlen(s, size);
3235 
3236 				if (*flags & CPU_DTRACE_FAULT)
3237 					break;
3238 
3239 				if (len != 0) {
3240 					if ((end -= (len + 1)) < start)
3241 						break;
3242 
3243 					*end = ':';
3244 				}
3245 
3246 				for (i = 1; i <= len; i++)
3247 					end[i] = dtrace_load8((uintptr_t)s++);
3248 				break;
3249 			}
3250 		}
3251 
3252 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3253 			ddi_node_state_t devi_state;
3254 
3255 			devi_state = dtrace_load32(daddr +
3256 			    offsetof(struct dev_info, devi_node_state));
3257 
3258 			if (*flags & CPU_DTRACE_FAULT)
3259 				break;
3260 
3261 			if (devi_state >= DS_INITIALIZED) {
3262 				s = (char *)dtrace_loadptr(daddr +
3263 				    offsetof(struct dev_info, devi_addr));
3264 				len = dtrace_strlen(s, size);
3265 
3266 				if (*flags & CPU_DTRACE_FAULT)
3267 					break;
3268 
3269 				if (len != 0) {
3270 					if ((end -= (len + 1)) < start)
3271 						break;
3272 
3273 					*end = '@';
3274 				}
3275 
3276 				for (i = 1; i <= len; i++)
3277 					end[i] = dtrace_load8((uintptr_t)s++);
3278 			}
3279 
3280 			/*
3281 			 * Now for the node name...
3282 			 */
3283 			s = (char *)dtrace_loadptr(daddr +
3284 			    offsetof(struct dev_info, devi_node_name));
3285 
3286 			daddr = dtrace_loadptr(daddr +
3287 			    offsetof(struct dev_info, devi_parent));
3288 
3289 			/*
3290 			 * If our parent is NULL (that is, if we're the root
3291 			 * node), we're going to use the special path
3292 			 * "devices".
3293 			 */
3294 			if (daddr == NULL)
3295 				s = "devices";
3296 
3297 			len = dtrace_strlen(s, size);
3298 			if (*flags & CPU_DTRACE_FAULT)
3299 				break;
3300 
3301 			if ((end -= (len + 1)) < start)
3302 				break;
3303 
3304 			for (i = 1; i <= len; i++)
3305 				end[i] = dtrace_load8((uintptr_t)s++);
3306 			*end = '/';
3307 
3308 			if (depth++ > dtrace_devdepth_max) {
3309 				*flags |= CPU_DTRACE_ILLOP;
3310 				break;
3311 			}
3312 		}
3313 
3314 		if (end < start)
3315 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3316 
3317 		if (daddr == NULL) {
3318 			regs[rd] = (uintptr_t)end;
3319 			mstate->dtms_scratch_ptr += size;
3320 		}
3321 
3322 		break;
3323 	}
3324 
3325 	case DIF_SUBR_STRJOIN: {
3326 		char *d = (char *)mstate->dtms_scratch_ptr;
3327 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3328 		uintptr_t s1 = tupregs[0].dttk_value;
3329 		uintptr_t s2 = tupregs[1].dttk_value;
3330 		int i = 0;
3331 
3332 		if (mstate->dtms_scratch_ptr + size >
3333 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3334 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3335 			regs[rd] = NULL;
3336 			break;
3337 		}
3338 
3339 		for (;;) {
3340 			if (i >= size) {
3341 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3342 				regs[rd] = NULL;
3343 				break;
3344 			}
3345 
3346 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
3347 				i--;
3348 				break;
3349 			}
3350 		}
3351 
3352 		for (;;) {
3353 			if (i >= size) {
3354 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3355 				regs[rd] = NULL;
3356 				break;
3357 			}
3358 
3359 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
3360 				break;
3361 		}
3362 
3363 		if (i < size) {
3364 			mstate->dtms_scratch_ptr += i;
3365 			regs[rd] = (uintptr_t)d;
3366 		}
3367 
3368 		break;
3369 	}
3370 
3371 	case DIF_SUBR_LLTOSTR: {
3372 		int64_t i = (int64_t)tupregs[0].dttk_value;
3373 		int64_t val = i < 0 ? i * -1 : i;
3374 		uint64_t size = 22;	/* enough room for 2^64 in decimal */
3375 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
3376 
3377 		if (mstate->dtms_scratch_ptr + size >
3378 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3379 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3380 			regs[rd] = NULL;
3381 			break;
3382 		}
3383 
3384 		for (*end-- = '\0'; val; val /= 10)
3385 			*end-- = '0' + (val % 10);
3386 
3387 		if (i == 0)
3388 			*end-- = '0';
3389 
3390 		if (i < 0)
3391 			*end-- = '-';
3392 
3393 		regs[rd] = (uintptr_t)end + 1;
3394 		mstate->dtms_scratch_ptr += size;
3395 		break;
3396 	}
3397 
3398 	case DIF_SUBR_DIRNAME:
3399 	case DIF_SUBR_BASENAME: {
3400 		char *dest = (char *)mstate->dtms_scratch_ptr;
3401 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3402 		uintptr_t src = tupregs[0].dttk_value;
3403 		int i, j, len = dtrace_strlen((char *)src, size);
3404 		int lastbase = -1, firstbase = -1, lastdir = -1;
3405 		int start, end;
3406 
3407 		if (mstate->dtms_scratch_ptr + size >
3408 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3409 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3410 			regs[rd] = NULL;
3411 			break;
3412 		}
3413 
3414 		/*
3415 		 * The basename and dirname for a zero-length string is
3416 		 * defined to be "."
3417 		 */
3418 		if (len == 0) {
3419 			len = 1;
3420 			src = (uintptr_t)".";
3421 		}
3422 
3423 		/*
3424 		 * Start from the back of the string, moving back toward the
3425 		 * front until we see a character that isn't a slash.  That
3426 		 * character is the last character in the basename.
3427 		 */
3428 		for (i = len - 1; i >= 0; i--) {
3429 			if (dtrace_load8(src + i) != '/')
3430 				break;
3431 		}
3432 
3433 		if (i >= 0)
3434 			lastbase = i;
3435 
3436 		/*
3437 		 * Starting from the last character in the basename, move
3438 		 * towards the front until we find a slash.  The character
3439 		 * that we processed immediately before that is the first
3440 		 * character in the basename.
3441 		 */
3442 		for (; i >= 0; i--) {
3443 			if (dtrace_load8(src + i) == '/')
3444 				break;
3445 		}
3446 
3447 		if (i >= 0)
3448 			firstbase = i + 1;
3449 
3450 		/*
3451 		 * Now keep going until we find a non-slash character.  That
3452 		 * character is the last character in the dirname.
3453 		 */
3454 		for (; i >= 0; i--) {
3455 			if (dtrace_load8(src + i) != '/')
3456 				break;
3457 		}
3458 
3459 		if (i >= 0)
3460 			lastdir = i;
3461 
3462 		ASSERT(!(lastbase == -1 && firstbase != -1));
3463 		ASSERT(!(firstbase == -1 && lastdir != -1));
3464 
3465 		if (lastbase == -1) {
3466 			/*
3467 			 * We didn't find a non-slash character.  We know that
3468 			 * the length is non-zero, so the whole string must be
3469 			 * slashes.  In either the dirname or the basename
3470 			 * case, we return '/'.
3471 			 */
3472 			ASSERT(firstbase == -1);
3473 			firstbase = lastbase = lastdir = 0;
3474 		}
3475 
3476 		if (firstbase == -1) {
3477 			/*
3478 			 * The entire string consists only of a basename
3479 			 * component.  If we're looking for dirname, we need
3480 			 * to change our string to be just "."; if we're
3481 			 * looking for a basename, we'll just set the first
3482 			 * character of the basename to be 0.
3483 			 */
3484 			if (subr == DIF_SUBR_DIRNAME) {
3485 				ASSERT(lastdir == -1);
3486 				src = (uintptr_t)".";
3487 				lastdir = 0;
3488 			} else {
3489 				firstbase = 0;
3490 			}
3491 		}
3492 
3493 		if (subr == DIF_SUBR_DIRNAME) {
3494 			if (lastdir == -1) {
3495 				/*
3496 				 * We know that we have a slash in the name --
3497 				 * or lastdir would be set to 0, above.  And
3498 				 * because lastdir is -1, we know that this
3499 				 * slash must be the first character.  (That
3500 				 * is, the full string must be of the form
3501 				 * "/basename".)  In this case, the last
3502 				 * character of the directory name is 0.
3503 				 */
3504 				lastdir = 0;
3505 			}
3506 
3507 			start = 0;
3508 			end = lastdir;
3509 		} else {
3510 			ASSERT(subr == DIF_SUBR_BASENAME);
3511 			ASSERT(firstbase != -1 && lastbase != -1);
3512 			start = firstbase;
3513 			end = lastbase;
3514 		}
3515 
3516 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
3517 			dest[j] = dtrace_load8(src + i);
3518 
3519 		dest[j] = '\0';
3520 		regs[rd] = (uintptr_t)dest;
3521 		mstate->dtms_scratch_ptr += size;
3522 		break;
3523 	}
3524 
3525 	case DIF_SUBR_CLEANPATH: {
3526 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
3527 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3528 		uintptr_t src = tupregs[0].dttk_value;
3529 		int i = 0, j = 0;
3530 
3531 		if (mstate->dtms_scratch_ptr + size >
3532 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3533 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3534 			regs[rd] = NULL;
3535 			break;
3536 		}
3537 
3538 		/*
3539 		 * Move forward, loading each character.
3540 		 */
3541 		do {
3542 			c = dtrace_load8(src + i++);
3543 next:
3544 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
3545 				break;
3546 
3547 			if (c != '/') {
3548 				dest[j++] = c;
3549 				continue;
3550 			}
3551 
3552 			c = dtrace_load8(src + i++);
3553 
3554 			if (c == '/') {
3555 				/*
3556 				 * We have two slashes -- we can just advance
3557 				 * to the next character.
3558 				 */
3559 				goto next;
3560 			}
3561 
3562 			if (c != '.') {
3563 				/*
3564 				 * This is not "." and it's not ".." -- we can
3565 				 * just store the "/" and this character and
3566 				 * drive on.
3567 				 */
3568 				dest[j++] = '/';
3569 				dest[j++] = c;
3570 				continue;
3571 			}
3572 
3573 			c = dtrace_load8(src + i++);
3574 
3575 			if (c == '/') {
3576 				/*
3577 				 * This is a "/./" component.  We're not going
3578 				 * to store anything in the destination buffer;
3579 				 * we're just going to go to the next component.
3580 				 */
3581 				goto next;
3582 			}
3583 
3584 			if (c != '.') {
3585 				/*
3586 				 * This is not ".." -- we can just store the
3587 				 * "/." and this character and continue
3588 				 * processing.
3589 				 */
3590 				dest[j++] = '/';
3591 				dest[j++] = '.';
3592 				dest[j++] = c;
3593 				continue;
3594 			}
3595 
3596 			c = dtrace_load8(src + i++);
3597 
3598 			if (c != '/' && c != '\0') {
3599 				/*
3600 				 * This is not ".." -- it's "..[mumble]".
3601 				 * We'll store the "/.." and this character
3602 				 * and continue processing.
3603 				 */
3604 				dest[j++] = '/';
3605 				dest[j++] = '.';
3606 				dest[j++] = '.';
3607 				dest[j++] = c;
3608 				continue;
3609 			}
3610 
3611 			/*
3612 			 * This is "/../" or "/..\0".  We need to back up
3613 			 * our destination pointer until we find a "/".
3614 			 */
3615 			i--;
3616 			while (j != 0 && dest[--j] != '/')
3617 				continue;
3618 
3619 			if (c == '\0')
3620 				dest[++j] = '/';
3621 		} while (c != '\0');
3622 
3623 		dest[j] = '\0';
3624 		regs[rd] = (uintptr_t)dest;
3625 		mstate->dtms_scratch_ptr += size;
3626 		break;
3627 	}
3628 	}
3629 }
3630 
3631 /*
3632  * Emulate the execution of DTrace IR instructions specified by the given
3633  * DIF object.  This function is deliberately void of assertions as all of
3634  * the necessary checks are handled by a call to dtrace_difo_validate().
3635  */
3636 static uint64_t
3637 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
3638     dtrace_vstate_t *vstate, dtrace_state_t *state)
3639 {
3640 	const dif_instr_t *text = difo->dtdo_buf;
3641 	const uint_t textlen = difo->dtdo_len;
3642 	const char *strtab = difo->dtdo_strtab;
3643 	const uint64_t *inttab = difo->dtdo_inttab;
3644 
3645 	uint64_t rval = 0;
3646 	dtrace_statvar_t *svar;
3647 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
3648 	dtrace_difv_t *v;
3649 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3650 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3651 
3652 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
3653 	uint64_t regs[DIF_DIR_NREGS];
3654 	uint64_t *tmp;
3655 
3656 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
3657 	int64_t cc_r;
3658 	uint_t pc = 0, id, opc;
3659 	uint8_t ttop = 0;
3660 	dif_instr_t instr;
3661 	uint_t r1, r2, rd;
3662 
3663 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
3664 
3665 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
3666 		opc = pc;
3667 
3668 		instr = text[pc++];
3669 		r1 = DIF_INSTR_R1(instr);
3670 		r2 = DIF_INSTR_R2(instr);
3671 		rd = DIF_INSTR_RD(instr);
3672 
3673 		switch (DIF_INSTR_OP(instr)) {
3674 		case DIF_OP_OR:
3675 			regs[rd] = regs[r1] | regs[r2];
3676 			break;
3677 		case DIF_OP_XOR:
3678 			regs[rd] = regs[r1] ^ regs[r2];
3679 			break;
3680 		case DIF_OP_AND:
3681 			regs[rd] = regs[r1] & regs[r2];
3682 			break;
3683 		case DIF_OP_SLL:
3684 			regs[rd] = regs[r1] << regs[r2];
3685 			break;
3686 		case DIF_OP_SRL:
3687 			regs[rd] = regs[r1] >> regs[r2];
3688 			break;
3689 		case DIF_OP_SUB:
3690 			regs[rd] = regs[r1] - regs[r2];
3691 			break;
3692 		case DIF_OP_ADD:
3693 			regs[rd] = regs[r1] + regs[r2];
3694 			break;
3695 		case DIF_OP_MUL:
3696 			regs[rd] = regs[r1] * regs[r2];
3697 			break;
3698 		case DIF_OP_SDIV:
3699 			if (regs[r2] == 0) {
3700 				regs[rd] = 0;
3701 				*flags |= CPU_DTRACE_DIVZERO;
3702 			} else {
3703 				regs[rd] = (int64_t)regs[r1] /
3704 				    (int64_t)regs[r2];
3705 			}
3706 			break;
3707 
3708 		case DIF_OP_UDIV:
3709 			if (regs[r2] == 0) {
3710 				regs[rd] = 0;
3711 				*flags |= CPU_DTRACE_DIVZERO;
3712 			} else {
3713 				regs[rd] = regs[r1] / regs[r2];
3714 			}
3715 			break;
3716 
3717 		case DIF_OP_SREM:
3718 			if (regs[r2] == 0) {
3719 				regs[rd] = 0;
3720 				*flags |= CPU_DTRACE_DIVZERO;
3721 			} else {
3722 				regs[rd] = (int64_t)regs[r1] %
3723 				    (int64_t)regs[r2];
3724 			}
3725 			break;
3726 
3727 		case DIF_OP_UREM:
3728 			if (regs[r2] == 0) {
3729 				regs[rd] = 0;
3730 				*flags |= CPU_DTRACE_DIVZERO;
3731 			} else {
3732 				regs[rd] = regs[r1] % regs[r2];
3733 			}
3734 			break;
3735 
3736 		case DIF_OP_NOT:
3737 			regs[rd] = ~regs[r1];
3738 			break;
3739 		case DIF_OP_MOV:
3740 			regs[rd] = regs[r1];
3741 			break;
3742 		case DIF_OP_CMP:
3743 			cc_r = regs[r1] - regs[r2];
3744 			cc_n = cc_r < 0;
3745 			cc_z = cc_r == 0;
3746 			cc_v = 0;
3747 			cc_c = regs[r1] < regs[r2];
3748 			break;
3749 		case DIF_OP_TST:
3750 			cc_n = cc_v = cc_c = 0;
3751 			cc_z = regs[r1] == 0;
3752 			break;
3753 		case DIF_OP_BA:
3754 			pc = DIF_INSTR_LABEL(instr);
3755 			break;
3756 		case DIF_OP_BE:
3757 			if (cc_z)
3758 				pc = DIF_INSTR_LABEL(instr);
3759 			break;
3760 		case DIF_OP_BNE:
3761 			if (cc_z == 0)
3762 				pc = DIF_INSTR_LABEL(instr);
3763 			break;
3764 		case DIF_OP_BG:
3765 			if ((cc_z | (cc_n ^ cc_v)) == 0)
3766 				pc = DIF_INSTR_LABEL(instr);
3767 			break;
3768 		case DIF_OP_BGU:
3769 			if ((cc_c | cc_z) == 0)
3770 				pc = DIF_INSTR_LABEL(instr);
3771 			break;
3772 		case DIF_OP_BGE:
3773 			if ((cc_n ^ cc_v) == 0)
3774 				pc = DIF_INSTR_LABEL(instr);
3775 			break;
3776 		case DIF_OP_BGEU:
3777 			if (cc_c == 0)
3778 				pc = DIF_INSTR_LABEL(instr);
3779 			break;
3780 		case DIF_OP_BL:
3781 			if (cc_n ^ cc_v)
3782 				pc = DIF_INSTR_LABEL(instr);
3783 			break;
3784 		case DIF_OP_BLU:
3785 			if (cc_c)
3786 				pc = DIF_INSTR_LABEL(instr);
3787 			break;
3788 		case DIF_OP_BLE:
3789 			if (cc_z | (cc_n ^ cc_v))
3790 				pc = DIF_INSTR_LABEL(instr);
3791 			break;
3792 		case DIF_OP_BLEU:
3793 			if (cc_c | cc_z)
3794 				pc = DIF_INSTR_LABEL(instr);
3795 			break;
3796 		case DIF_OP_RLDSB:
3797 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
3798 				*flags |= CPU_DTRACE_KPRIV;
3799 				*illval = regs[r1];
3800 				break;
3801 			}
3802 			/*FALLTHROUGH*/
3803 		case DIF_OP_LDSB:
3804 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
3805 			break;
3806 		case DIF_OP_RLDSH:
3807 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
3808 				*flags |= CPU_DTRACE_KPRIV;
3809 				*illval = regs[r1];
3810 				break;
3811 			}
3812 			/*FALLTHROUGH*/
3813 		case DIF_OP_LDSH:
3814 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
3815 			break;
3816 		case DIF_OP_RLDSW:
3817 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
3818 				*flags |= CPU_DTRACE_KPRIV;
3819 				*illval = regs[r1];
3820 				break;
3821 			}
3822 			/*FALLTHROUGH*/
3823 		case DIF_OP_LDSW:
3824 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
3825 			break;
3826 		case DIF_OP_RLDUB:
3827 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
3828 				*flags |= CPU_DTRACE_KPRIV;
3829 				*illval = regs[r1];
3830 				break;
3831 			}
3832 			/*FALLTHROUGH*/
3833 		case DIF_OP_LDUB:
3834 			regs[rd] = dtrace_load8(regs[r1]);
3835 			break;
3836 		case DIF_OP_RLDUH:
3837 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
3838 				*flags |= CPU_DTRACE_KPRIV;
3839 				*illval = regs[r1];
3840 				break;
3841 			}
3842 			/*FALLTHROUGH*/
3843 		case DIF_OP_LDUH:
3844 			regs[rd] = dtrace_load16(regs[r1]);
3845 			break;
3846 		case DIF_OP_RLDUW:
3847 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
3848 				*flags |= CPU_DTRACE_KPRIV;
3849 				*illval = regs[r1];
3850 				break;
3851 			}
3852 			/*FALLTHROUGH*/
3853 		case DIF_OP_LDUW:
3854 			regs[rd] = dtrace_load32(regs[r1]);
3855 			break;
3856 		case DIF_OP_RLDX:
3857 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
3858 				*flags |= CPU_DTRACE_KPRIV;
3859 				*illval = regs[r1];
3860 				break;
3861 			}
3862 			/*FALLTHROUGH*/
3863 		case DIF_OP_LDX:
3864 			regs[rd] = dtrace_load64(regs[r1]);
3865 			break;
3866 		case DIF_OP_ULDSB:
3867 			regs[rd] = (int8_t)
3868 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
3869 			break;
3870 		case DIF_OP_ULDSH:
3871 			regs[rd] = (int16_t)
3872 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
3873 			break;
3874 		case DIF_OP_ULDSW:
3875 			regs[rd] = (int32_t)
3876 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
3877 			break;
3878 		case DIF_OP_ULDUB:
3879 			regs[rd] =
3880 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
3881 			break;
3882 		case DIF_OP_ULDUH:
3883 			regs[rd] =
3884 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
3885 			break;
3886 		case DIF_OP_ULDUW:
3887 			regs[rd] =
3888 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
3889 			break;
3890 		case DIF_OP_ULDX:
3891 			regs[rd] =
3892 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
3893 			break;
3894 		case DIF_OP_RET:
3895 			rval = regs[rd];
3896 			break;
3897 		case DIF_OP_NOP:
3898 			break;
3899 		case DIF_OP_SETX:
3900 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
3901 			break;
3902 		case DIF_OP_SETS:
3903 			regs[rd] = (uint64_t)(uintptr_t)
3904 			    (strtab + DIF_INSTR_STRING(instr));
3905 			break;
3906 		case DIF_OP_SCMP:
3907 			cc_r = dtrace_strncmp((char *)(uintptr_t)regs[r1],
3908 			    (char *)(uintptr_t)regs[r2],
3909 			    state->dts_options[DTRACEOPT_STRSIZE]);
3910 
3911 			cc_n = cc_r < 0;
3912 			cc_z = cc_r == 0;
3913 			cc_v = cc_c = 0;
3914 			break;
3915 		case DIF_OP_LDGA:
3916 			regs[rd] = dtrace_dif_variable(mstate, state,
3917 			    r1, regs[r2]);
3918 			break;
3919 		case DIF_OP_LDGS:
3920 			id = DIF_INSTR_VAR(instr);
3921 
3922 			if (id >= DIF_VAR_OTHER_UBASE) {
3923 				uintptr_t a;
3924 
3925 				id -= DIF_VAR_OTHER_UBASE;
3926 				svar = vstate->dtvs_globals[id];
3927 				ASSERT(svar != NULL);
3928 				v = &svar->dtsv_var;
3929 
3930 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
3931 					regs[rd] = svar->dtsv_data;
3932 					break;
3933 				}
3934 
3935 				a = (uintptr_t)svar->dtsv_data;
3936 
3937 				if (*(uint8_t *)a == UINT8_MAX) {
3938 					/*
3939 					 * If the 0th byte is set to UINT8_MAX
3940 					 * then this is to be treated as a
3941 					 * reference to a NULL variable.
3942 					 */
3943 					regs[rd] = NULL;
3944 				} else {
3945 					regs[rd] = a + sizeof (uint64_t);
3946 				}
3947 
3948 				break;
3949 			}
3950 
3951 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
3952 			break;
3953 
3954 		case DIF_OP_STGS:
3955 			id = DIF_INSTR_VAR(instr);
3956 
3957 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
3958 			id -= DIF_VAR_OTHER_UBASE;
3959 
3960 			svar = vstate->dtvs_globals[id];
3961 			ASSERT(svar != NULL);
3962 			v = &svar->dtsv_var;
3963 
3964 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
3965 				uintptr_t a = (uintptr_t)svar->dtsv_data;
3966 
3967 				ASSERT(a != NULL);
3968 				ASSERT(svar->dtsv_size != 0);
3969 
3970 				if (regs[rd] == NULL) {
3971 					*(uint8_t *)a = UINT8_MAX;
3972 					break;
3973 				} else {
3974 					*(uint8_t *)a = 0;
3975 					a += sizeof (uint64_t);
3976 				}
3977 
3978 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
3979 				    (void *)a, &v->dtdv_type);
3980 				break;
3981 			}
3982 
3983 			svar->dtsv_data = regs[rd];
3984 			break;
3985 
3986 		case DIF_OP_LDTA:
3987 			/*
3988 			 * There are no DTrace built-in thread-local arrays at
3989 			 * present.  This opcode is saved for future work.
3990 			 */
3991 			*flags |= CPU_DTRACE_ILLOP;
3992 			regs[rd] = 0;
3993 			break;
3994 
3995 		case DIF_OP_LDLS:
3996 			id = DIF_INSTR_VAR(instr);
3997 
3998 			if (id < DIF_VAR_OTHER_UBASE) {
3999 				/*
4000 				 * For now, this has no meaning.
4001 				 */
4002 				regs[rd] = 0;
4003 				break;
4004 			}
4005 
4006 			id -= DIF_VAR_OTHER_UBASE;
4007 
4008 			ASSERT(id < vstate->dtvs_nlocals);
4009 			ASSERT(vstate->dtvs_locals != NULL);
4010 
4011 			svar = vstate->dtvs_locals[id];
4012 			ASSERT(svar != NULL);
4013 			v = &svar->dtsv_var;
4014 
4015 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4016 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4017 				size_t sz = v->dtdv_type.dtdt_size;
4018 
4019 				sz += sizeof (uint64_t);
4020 				ASSERT(svar->dtsv_size == NCPU * sz);
4021 				a += CPU->cpu_id * sz;
4022 
4023 				if (*(uint8_t *)a == UINT8_MAX) {
4024 					/*
4025 					 * If the 0th byte is set to UINT8_MAX
4026 					 * then this is to be treated as a
4027 					 * reference to a NULL variable.
4028 					 */
4029 					regs[rd] = NULL;
4030 				} else {
4031 					regs[rd] = a + sizeof (uint64_t);
4032 				}
4033 
4034 				break;
4035 			}
4036 
4037 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4038 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4039 			regs[rd] = tmp[CPU->cpu_id];
4040 			break;
4041 
4042 		case DIF_OP_STLS:
4043 			id = DIF_INSTR_VAR(instr);
4044 
4045 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4046 			id -= DIF_VAR_OTHER_UBASE;
4047 			ASSERT(id < vstate->dtvs_nlocals);
4048 
4049 			ASSERT(vstate->dtvs_locals != NULL);
4050 			svar = vstate->dtvs_locals[id];
4051 			ASSERT(svar != NULL);
4052 			v = &svar->dtsv_var;
4053 
4054 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4055 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4056 				size_t sz = v->dtdv_type.dtdt_size;
4057 
4058 				sz += sizeof (uint64_t);
4059 				ASSERT(svar->dtsv_size == NCPU * sz);
4060 				a += CPU->cpu_id * sz;
4061 
4062 				if (regs[rd] == NULL) {
4063 					*(uint8_t *)a = UINT8_MAX;
4064 					break;
4065 				} else {
4066 					*(uint8_t *)a = 0;
4067 					a += sizeof (uint64_t);
4068 				}
4069 
4070 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4071 				    (void *)a, &v->dtdv_type);
4072 				break;
4073 			}
4074 
4075 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4076 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4077 			tmp[CPU->cpu_id] = regs[rd];
4078 			break;
4079 
4080 		case DIF_OP_LDTS: {
4081 			dtrace_dynvar_t *dvar;
4082 			dtrace_key_t *key;
4083 
4084 			id = DIF_INSTR_VAR(instr);
4085 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4086 			id -= DIF_VAR_OTHER_UBASE;
4087 			v = &vstate->dtvs_tlocals[id];
4088 
4089 			key = &tupregs[DIF_DTR_NREGS];
4090 			key[0].dttk_value = (uint64_t)id;
4091 			key[0].dttk_size = 0;
4092 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4093 			key[1].dttk_size = 0;
4094 
4095 			dvar = dtrace_dynvar(dstate, 2, key,
4096 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC);
4097 
4098 			if (dvar == NULL) {
4099 				regs[rd] = 0;
4100 				break;
4101 			}
4102 
4103 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4104 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4105 			} else {
4106 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4107 			}
4108 
4109 			break;
4110 		}
4111 
4112 		case DIF_OP_STTS: {
4113 			dtrace_dynvar_t *dvar;
4114 			dtrace_key_t *key;
4115 
4116 			id = DIF_INSTR_VAR(instr);
4117 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4118 			id -= DIF_VAR_OTHER_UBASE;
4119 
4120 			key = &tupregs[DIF_DTR_NREGS];
4121 			key[0].dttk_value = (uint64_t)id;
4122 			key[0].dttk_size = 0;
4123 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4124 			key[1].dttk_size = 0;
4125 			v = &vstate->dtvs_tlocals[id];
4126 
4127 			dvar = dtrace_dynvar(dstate, 2, key,
4128 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4129 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4130 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4131 			    DTRACE_DYNVAR_DEALLOC);
4132 
4133 			/*
4134 			 * Given that we're storing to thread-local data,
4135 			 * we need to flush our predicate cache.
4136 			 */
4137 			curthread->t_predcache = NULL;
4138 
4139 			if (dvar == NULL)
4140 				break;
4141 
4142 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4143 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4144 				    dvar->dtdv_data, &v->dtdv_type);
4145 			} else {
4146 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4147 			}
4148 
4149 			break;
4150 		}
4151 
4152 		case DIF_OP_SRA:
4153 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
4154 			break;
4155 
4156 		case DIF_OP_CALL:
4157 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
4158 			    regs, tupregs, ttop, mstate, state);
4159 			break;
4160 
4161 		case DIF_OP_PUSHTR:
4162 			if (ttop == DIF_DTR_NREGS) {
4163 				*flags |= CPU_DTRACE_TUPOFLOW;
4164 				break;
4165 			}
4166 
4167 			if (r1 == DIF_TYPE_STRING) {
4168 				/*
4169 				 * If this is a string type and the size is 0,
4170 				 * we'll use the system-wide default string
4171 				 * size.  Note that we are _not_ looking at
4172 				 * the value of the DTRACEOPT_STRSIZE option;
4173 				 * had this been set, we would expect to have
4174 				 * a non-zero size value in the "pushtr".
4175 				 */
4176 				tupregs[ttop].dttk_size =
4177 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
4178 				    regs[r2] ? regs[r2] :
4179 				    dtrace_strsize_default) + 1;
4180 			} else {
4181 				tupregs[ttop].dttk_size = regs[r2];
4182 			}
4183 
4184 			tupregs[ttop++].dttk_value = regs[rd];
4185 			break;
4186 
4187 		case DIF_OP_PUSHTV:
4188 			if (ttop == DIF_DTR_NREGS) {
4189 				*flags |= CPU_DTRACE_TUPOFLOW;
4190 				break;
4191 			}
4192 
4193 			tupregs[ttop].dttk_value = regs[rd];
4194 			tupregs[ttop++].dttk_size = 0;
4195 			break;
4196 
4197 		case DIF_OP_POPTS:
4198 			if (ttop != 0)
4199 				ttop--;
4200 			break;
4201 
4202 		case DIF_OP_FLUSHTS:
4203 			ttop = 0;
4204 			break;
4205 
4206 		case DIF_OP_LDGAA:
4207 		case DIF_OP_LDTAA: {
4208 			dtrace_dynvar_t *dvar;
4209 			dtrace_key_t *key = tupregs;
4210 			uint_t nkeys = ttop;
4211 
4212 			id = DIF_INSTR_VAR(instr);
4213 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4214 			id -= DIF_VAR_OTHER_UBASE;
4215 
4216 			key[nkeys].dttk_value = (uint64_t)id;
4217 			key[nkeys++].dttk_size = 0;
4218 
4219 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
4220 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4221 				key[nkeys++].dttk_size = 0;
4222 				v = &vstate->dtvs_tlocals[id];
4223 			} else {
4224 				v = &vstate->dtvs_globals[id]->dtsv_var;
4225 			}
4226 
4227 			dvar = dtrace_dynvar(dstate, nkeys, key,
4228 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4229 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4230 			    DTRACE_DYNVAR_NOALLOC);
4231 
4232 			if (dvar == NULL) {
4233 				regs[rd] = 0;
4234 				break;
4235 			}
4236 
4237 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4238 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4239 			} else {
4240 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4241 			}
4242 
4243 			break;
4244 		}
4245 
4246 		case DIF_OP_STGAA:
4247 		case DIF_OP_STTAA: {
4248 			dtrace_dynvar_t *dvar;
4249 			dtrace_key_t *key = tupregs;
4250 			uint_t nkeys = ttop;
4251 
4252 			id = DIF_INSTR_VAR(instr);
4253 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4254 			id -= DIF_VAR_OTHER_UBASE;
4255 
4256 			key[nkeys].dttk_value = (uint64_t)id;
4257 			key[nkeys++].dttk_size = 0;
4258 
4259 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
4260 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4261 				key[nkeys++].dttk_size = 0;
4262 				v = &vstate->dtvs_tlocals[id];
4263 			} else {
4264 				v = &vstate->dtvs_globals[id]->dtsv_var;
4265 			}
4266 
4267 			dvar = dtrace_dynvar(dstate, nkeys, key,
4268 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4269 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4270 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4271 			    DTRACE_DYNVAR_DEALLOC);
4272 
4273 			if (dvar == NULL)
4274 				break;
4275 
4276 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4277 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4278 				    dvar->dtdv_data, &v->dtdv_type);
4279 			} else {
4280 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4281 			}
4282 
4283 			break;
4284 		}
4285 
4286 		case DIF_OP_ALLOCS: {
4287 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4288 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
4289 
4290 			if (mstate->dtms_scratch_ptr + size >
4291 			    mstate->dtms_scratch_base +
4292 			    mstate->dtms_scratch_size) {
4293 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4294 				regs[rd] = NULL;
4295 			} else {
4296 				dtrace_bzero((void *)
4297 				    mstate->dtms_scratch_ptr, size);
4298 				mstate->dtms_scratch_ptr += size;
4299 				regs[rd] = ptr;
4300 			}
4301 			break;
4302 		}
4303 
4304 		case DIF_OP_COPYS:
4305 			if (!dtrace_canstore(regs[rd], regs[r2],
4306 			    mstate, vstate)) {
4307 				*flags |= CPU_DTRACE_BADADDR;
4308 				*illval = regs[rd];
4309 				break;
4310 			}
4311 
4312 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
4313 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
4314 			break;
4315 
4316 		case DIF_OP_STB:
4317 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
4318 				*flags |= CPU_DTRACE_BADADDR;
4319 				*illval = regs[rd];
4320 				break;
4321 			}
4322 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
4323 			break;
4324 
4325 		case DIF_OP_STH:
4326 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
4327 				*flags |= CPU_DTRACE_BADADDR;
4328 				*illval = regs[rd];
4329 				break;
4330 			}
4331 			if (regs[rd] & 1) {
4332 				*flags |= CPU_DTRACE_BADALIGN;
4333 				*illval = regs[rd];
4334 				break;
4335 			}
4336 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
4337 			break;
4338 
4339 		case DIF_OP_STW:
4340 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
4341 				*flags |= CPU_DTRACE_BADADDR;
4342 				*illval = regs[rd];
4343 				break;
4344 			}
4345 			if (regs[rd] & 3) {
4346 				*flags |= CPU_DTRACE_BADALIGN;
4347 				*illval = regs[rd];
4348 				break;
4349 			}
4350 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
4351 			break;
4352 
4353 		case DIF_OP_STX:
4354 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
4355 				*flags |= CPU_DTRACE_BADADDR;
4356 				*illval = regs[rd];
4357 				break;
4358 			}
4359 			if (regs[rd] & 7) {
4360 				*flags |= CPU_DTRACE_BADALIGN;
4361 				*illval = regs[rd];
4362 				break;
4363 			}
4364 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
4365 			break;
4366 		}
4367 	}
4368 
4369 	if (!(*flags & CPU_DTRACE_FAULT))
4370 		return (rval);
4371 
4372 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
4373 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
4374 
4375 	return (0);
4376 }
4377 
4378 static void
4379 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
4380 {
4381 	dtrace_probe_t *probe = ecb->dte_probe;
4382 	dtrace_provider_t *prov = probe->dtpr_provider;
4383 	char c[DTRACE_FULLNAMELEN + 80], *str;
4384 	char *msg = "dtrace: breakpoint action at probe ";
4385 	char *ecbmsg = " (ecb ";
4386 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
4387 	uintptr_t val = (uintptr_t)ecb;
4388 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
4389 
4390 	if (dtrace_destructive_disallow)
4391 		return;
4392 
4393 	/*
4394 	 * It's impossible to be taking action on the NULL probe.
4395 	 */
4396 	ASSERT(probe != NULL);
4397 
4398 	/*
4399 	 * This is a poor man's (destitute man's?) sprintf():  we want to
4400 	 * print the provider name, module name, function name and name of
4401 	 * the probe, along with the hex address of the ECB with the breakpoint
4402 	 * action -- all of which we must place in the character buffer by
4403 	 * hand.
4404 	 */
4405 	while (*msg != '\0')
4406 		c[i++] = *msg++;
4407 
4408 	for (str = prov->dtpv_name; *str != '\0'; str++)
4409 		c[i++] = *str;
4410 	c[i++] = ':';
4411 
4412 	for (str = probe->dtpr_mod; *str != '\0'; str++)
4413 		c[i++] = *str;
4414 	c[i++] = ':';
4415 
4416 	for (str = probe->dtpr_func; *str != '\0'; str++)
4417 		c[i++] = *str;
4418 	c[i++] = ':';
4419 
4420 	for (str = probe->dtpr_name; *str != '\0'; str++)
4421 		c[i++] = *str;
4422 
4423 	while (*ecbmsg != '\0')
4424 		c[i++] = *ecbmsg++;
4425 
4426 	while (shift >= 0) {
4427 		mask = (uintptr_t)0xf << shift;
4428 
4429 		if (val >= ((uintptr_t)1 << shift))
4430 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
4431 		shift -= 4;
4432 	}
4433 
4434 	c[i++] = ')';
4435 	c[i] = '\0';
4436 
4437 	debug_enter(c);
4438 }
4439 
4440 static void
4441 dtrace_action_panic(dtrace_ecb_t *ecb)
4442 {
4443 	dtrace_probe_t *probe = ecb->dte_probe;
4444 
4445 	/*
4446 	 * It's impossible to be taking action on the NULL probe.
4447 	 */
4448 	ASSERT(probe != NULL);
4449 
4450 	if (dtrace_destructive_disallow)
4451 		return;
4452 
4453 	if (dtrace_panicked != NULL)
4454 		return;
4455 
4456 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
4457 		return;
4458 
4459 	/*
4460 	 * We won the right to panic.  (We want to be sure that only one
4461 	 * thread calls panic() from dtrace_probe(), and that panic() is
4462 	 * called exactly once.)
4463 	 */
4464 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
4465 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
4466 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
4467 }
4468 
4469 static void
4470 dtrace_action_raise(uint64_t sig)
4471 {
4472 	if (dtrace_destructive_disallow)
4473 		return;
4474 
4475 	if (sig >= NSIG) {
4476 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4477 		return;
4478 	}
4479 
4480 	/*
4481 	 * raise() has a queue depth of 1 -- we ignore all subsequent
4482 	 * invocations of the raise() action.
4483 	 */
4484 	if (curthread->t_dtrace_sig == 0)
4485 		curthread->t_dtrace_sig = (uint8_t)sig;
4486 
4487 	curthread->t_sig_check = 1;
4488 	aston(curthread);
4489 }
4490 
4491 static void
4492 dtrace_action_stop(void)
4493 {
4494 	if (dtrace_destructive_disallow)
4495 		return;
4496 
4497 	if (!curthread->t_dtrace_stop) {
4498 		curthread->t_dtrace_stop = 1;
4499 		curthread->t_sig_check = 1;
4500 		aston(curthread);
4501 	}
4502 }
4503 
4504 static void
4505 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
4506 {
4507 	hrtime_t now;
4508 	volatile uint16_t *flags;
4509 	cpu_t *cpu = CPU;
4510 
4511 	if (dtrace_destructive_disallow)
4512 		return;
4513 
4514 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
4515 
4516 	now = dtrace_gethrtime();
4517 
4518 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
4519 		/*
4520 		 * We need to advance the mark to the current time.
4521 		 */
4522 		cpu->cpu_dtrace_chillmark = now;
4523 		cpu->cpu_dtrace_chilled = 0;
4524 	}
4525 
4526 	/*
4527 	 * Now check to see if the requested chill time would take us over
4528 	 * the maximum amount of time allowed in the chill interval.  (Or
4529 	 * worse, if the calculation itself induces overflow.)
4530 	 */
4531 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
4532 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
4533 		*flags |= CPU_DTRACE_ILLOP;
4534 		return;
4535 	}
4536 
4537 	while (dtrace_gethrtime() - now < val)
4538 		continue;
4539 
4540 	/*
4541 	 * Normally, we assure that the value of the variable "timestamp" does
4542 	 * not change within an ECB.  The presence of chill() represents an
4543 	 * exception to this rule, however.
4544 	 */
4545 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
4546 	cpu->cpu_dtrace_chilled += val;
4547 }
4548 
4549 static void
4550 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
4551     uint64_t *buf, uint64_t arg)
4552 {
4553 	int nframes = DTRACE_USTACK_NFRAMES(arg);
4554 	int strsize = DTRACE_USTACK_STRSIZE(arg);
4555 	uint64_t *pcs = &buf[1], *fps;
4556 	char *str = (char *)&pcs[nframes];
4557 	int size, offs = 0, i, j;
4558 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
4559 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4560 	char *sym;
4561 
4562 	/*
4563 	 * Should be taking a faster path if string space has not been
4564 	 * allocated.
4565 	 */
4566 	ASSERT(strsize != 0);
4567 
4568 	/*
4569 	 * We will first allocate some temporary space for the frame pointers.
4570 	 */
4571 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4572 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
4573 	    (nframes * sizeof (uint64_t));
4574 
4575 	if (mstate->dtms_scratch_ptr + size >
4576 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
4577 		/*
4578 		 * Not enough room for our frame pointers -- need to indicate
4579 		 * that we ran out of scratch space.
4580 		 */
4581 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4582 		return;
4583 	}
4584 
4585 	mstate->dtms_scratch_ptr += size;
4586 	saved = mstate->dtms_scratch_ptr;
4587 
4588 	/*
4589 	 * Now get a stack with both program counters and frame pointers.
4590 	 */
4591 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4592 	dtrace_getufpstack(buf, fps, nframes + 1);
4593 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4594 
4595 	/*
4596 	 * If that faulted, we're cooked.
4597 	 */
4598 	if (*flags & CPU_DTRACE_FAULT)
4599 		goto out;
4600 
4601 	/*
4602 	 * Now we want to walk up the stack, calling the USTACK helper.  For
4603 	 * each iteration, we restore the scratch pointer.
4604 	 */
4605 	for (i = 0; i < nframes; i++) {
4606 		mstate->dtms_scratch_ptr = saved;
4607 
4608 		if (offs >= strsize)
4609 			break;
4610 
4611 		sym = (char *)(uintptr_t)dtrace_helper(
4612 		    DTRACE_HELPER_ACTION_USTACK,
4613 		    mstate, state, pcs[i], fps[i]);
4614 
4615 		/*
4616 		 * If we faulted while running the helper, we're going to
4617 		 * clear the fault and null out the corresponding string.
4618 		 */
4619 		if (*flags & CPU_DTRACE_FAULT) {
4620 			*flags &= ~CPU_DTRACE_FAULT;
4621 			str[offs++] = '\0';
4622 			continue;
4623 		}
4624 
4625 		if (sym == NULL) {
4626 			str[offs++] = '\0';
4627 			continue;
4628 		}
4629 
4630 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4631 
4632 		/*
4633 		 * Now copy in the string that the helper returned to us.
4634 		 */
4635 		for (j = 0; offs + j < strsize; j++) {
4636 			if ((str[offs + j] = sym[j]) == '\0')
4637 				break;
4638 		}
4639 
4640 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4641 
4642 		offs += j + 1;
4643 	}
4644 
4645 	if (offs >= strsize) {
4646 		/*
4647 		 * If we didn't have room for all of the strings, we don't
4648 		 * abort processing -- this needn't be a fatal error -- but we
4649 		 * still want to increment a counter (dts_stkstroverflows) to
4650 		 * allow this condition to be warned about.  (If this is from
4651 		 * a jstack() action, it is easily tuned via jstackstrsize.)
4652 		 */
4653 		dtrace_error(&state->dts_stkstroverflows);
4654 	}
4655 
4656 	while (offs < strsize)
4657 		str[offs++] = '\0';
4658 
4659 out:
4660 	mstate->dtms_scratch_ptr = old;
4661 }
4662 
4663 /*
4664  * If you're looking for the epicenter of DTrace, you just found it.  This
4665  * is the function called by the provider to fire a probe -- from which all
4666  * subsequent probe-context DTrace activity emanates.
4667  */
4668 void
4669 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
4670     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
4671 {
4672 	processorid_t cpuid;
4673 	dtrace_icookie_t cookie;
4674 	dtrace_probe_t *probe;
4675 	dtrace_mstate_t mstate;
4676 	dtrace_ecb_t *ecb;
4677 	dtrace_action_t *act;
4678 	intptr_t offs;
4679 	size_t size;
4680 	int vtime, onintr;
4681 	volatile uint16_t *flags;
4682 	hrtime_t now;
4683 
4684 	/*
4685 	 * Kick out immediately if this CPU is still being born (in which case
4686 	 * curthread will be set to -1)
4687 	 */
4688 	if ((uintptr_t)curthread & 1)
4689 		return;
4690 
4691 	cookie = dtrace_interrupt_disable();
4692 	probe = dtrace_probes[id - 1];
4693 	cpuid = CPU->cpu_id;
4694 	onintr = CPU_ON_INTR(CPU);
4695 
4696 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
4697 	    probe->dtpr_predcache == curthread->t_predcache) {
4698 		/*
4699 		 * We have hit in the predicate cache; we know that
4700 		 * this predicate would evaluate to be false.
4701 		 */
4702 		dtrace_interrupt_enable(cookie);
4703 		return;
4704 	}
4705 
4706 	if (panic_quiesce) {
4707 		/*
4708 		 * We don't trace anything if we're panicking.
4709 		 */
4710 		dtrace_interrupt_enable(cookie);
4711 		return;
4712 	}
4713 
4714 	now = dtrace_gethrtime();
4715 	vtime = dtrace_vtime_references != 0;
4716 
4717 	if (vtime && curthread->t_dtrace_start)
4718 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
4719 
4720 	mstate.dtms_probe = probe;
4721 	mstate.dtms_arg[0] = arg0;
4722 	mstate.dtms_arg[1] = arg1;
4723 	mstate.dtms_arg[2] = arg2;
4724 	mstate.dtms_arg[3] = arg3;
4725 	mstate.dtms_arg[4] = arg4;
4726 
4727 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
4728 
4729 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
4730 		dtrace_predicate_t *pred = ecb->dte_predicate;
4731 		dtrace_state_t *state = ecb->dte_state;
4732 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
4733 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
4734 		dtrace_vstate_t *vstate = &state->dts_vstate;
4735 		dtrace_provider_t *prov = probe->dtpr_provider;
4736 		int committed = 0;
4737 		caddr_t tomax;
4738 
4739 		/*
4740 		 * A little subtlety with the following (seemingly innocuous)
4741 		 * declaration of the automatic 'val':  by looking at the
4742 		 * code, you might think that it could be declared in the
4743 		 * action processing loop, below.  (That is, it's only used in
4744 		 * the action processing loop.)  However, it must be declared
4745 		 * out of that scope because in the case of DIF expression
4746 		 * arguments to aggregating actions, one iteration of the
4747 		 * action loop will use the last iteration's value.
4748 		 */
4749 #ifdef lint
4750 		uint64_t val = 0;
4751 #else
4752 		uint64_t val;
4753 #endif
4754 
4755 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
4756 		*flags &= ~CPU_DTRACE_ERROR;
4757 
4758 		if (prov == dtrace_provider) {
4759 			/*
4760 			 * If dtrace itself is the provider of this probe,
4761 			 * we're only going to continue processing the ECB if
4762 			 * arg0 (the dtrace_state_t) is equal to the ECB's
4763 			 * creating state.  (This prevents disjoint consumers
4764 			 * from seeing one another's metaprobes.)
4765 			 */
4766 			if (arg0 != (uint64_t)(uintptr_t)state)
4767 				continue;
4768 		}
4769 
4770 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
4771 			/*
4772 			 * We're not currently active.  If our provider isn't
4773 			 * the dtrace pseudo provider, we're not interested.
4774 			 */
4775 			if (prov != dtrace_provider)
4776 				continue;
4777 
4778 			/*
4779 			 * Now we must further check if we are in the BEGIN
4780 			 * probe.  If we are, we will only continue processing
4781 			 * if we're still in WARMUP -- if one BEGIN enabling
4782 			 * has invoked the exit() action, we don't want to
4783 			 * evaluate subsequent BEGIN enablings.
4784 			 */
4785 			if (probe->dtpr_id == dtrace_probeid_begin &&
4786 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
4787 				ASSERT(state->dts_activity ==
4788 				    DTRACE_ACTIVITY_DRAINING);
4789 				continue;
4790 			}
4791 		}
4792 
4793 		if (ecb->dte_cond) {
4794 			/*
4795 			 * If the dte_cond bits indicate that this
4796 			 * consumer is only allowed to see user-mode firings
4797 			 * of this probe, call the provider's dtps_usermode()
4798 			 * entry point to check that the probe was fired
4799 			 * while in a user context. Skip this ECB if that's
4800 			 * not the case.
4801 			 */
4802 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
4803 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
4804 			    probe->dtpr_id, probe->dtpr_arg) == 0)
4805 				continue;
4806 
4807 			/*
4808 			 * This is more subtle than it looks. We have to be
4809 			 * absolutely certain that CRED() isn't going to
4810 			 * change out from under us so it's only legit to
4811 			 * examine that structure if we're in constrained
4812 			 * situations. Currently, the only times we'll this
4813 			 * check is if a non-super-user has enabled the
4814 			 * profile or syscall providers -- providers that
4815 			 * allow visibility of all processes. For the
4816 			 * profile case, the check above will ensure that
4817 			 * we're examining a user context.
4818 			 */
4819 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
4820 				cred_t *cr;
4821 				cred_t *s_cr =
4822 				    ecb->dte_state->dts_cred.dcr_cred;
4823 				proc_t *proc;
4824 
4825 				ASSERT(s_cr != NULL);
4826 
4827 				if ((cr = CRED()) == NULL ||
4828 				    s_cr->cr_uid != cr->cr_uid ||
4829 				    s_cr->cr_uid != cr->cr_ruid ||
4830 				    s_cr->cr_uid != cr->cr_suid ||
4831 				    s_cr->cr_gid != cr->cr_gid ||
4832 				    s_cr->cr_gid != cr->cr_rgid ||
4833 				    s_cr->cr_gid != cr->cr_sgid ||
4834 				    (proc = ttoproc(curthread)) == NULL ||
4835 				    (proc->p_flag & SNOCD))
4836 					continue;
4837 			}
4838 
4839 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
4840 				cred_t *cr;
4841 				cred_t *s_cr =
4842 				    ecb->dte_state->dts_cred.dcr_cred;
4843 
4844 				ASSERT(s_cr != NULL);
4845 
4846 				if ((cr = CRED()) == NULL ||
4847 				    s_cr->cr_zone->zone_id !=
4848 				    cr->cr_zone->zone_id)
4849 					continue;
4850 			}
4851 		}
4852 
4853 		if (now - state->dts_alive > dtrace_deadman_timeout) {
4854 			/*
4855 			 * We seem to be dead.  Unless we (a) have kernel
4856 			 * destructive permissions (b) have expicitly enabled
4857 			 * destructive actions and (c) destructive actions have
4858 			 * not been disabled, we're going to transition into
4859 			 * the KILLED state, from which no further processing
4860 			 * on this state will be performed.
4861 			 */
4862 			if (!dtrace_priv_kernel_destructive(state) ||
4863 			    !state->dts_cred.dcr_destructive ||
4864 			    dtrace_destructive_disallow) {
4865 				void *activity = &state->dts_activity;
4866 				dtrace_activity_t current;
4867 
4868 				do {
4869 					current = state->dts_activity;
4870 				} while (dtrace_cas32(activity, current,
4871 				    DTRACE_ACTIVITY_KILLED) != current);
4872 
4873 				continue;
4874 			}
4875 		}
4876 
4877 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
4878 		    ecb->dte_alignment, state, &mstate)) < 0)
4879 			continue;
4880 
4881 		tomax = buf->dtb_tomax;
4882 		ASSERT(tomax != NULL);
4883 
4884 		if (ecb->dte_size != 0)
4885 			DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
4886 
4887 		mstate.dtms_epid = ecb->dte_epid;
4888 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
4889 
4890 		if (pred != NULL) {
4891 			dtrace_difo_t *dp = pred->dtp_difo;
4892 			int rval;
4893 
4894 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
4895 
4896 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
4897 				dtrace_cacheid_t cid = probe->dtpr_predcache;
4898 
4899 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
4900 					/*
4901 					 * Update the predicate cache...
4902 					 */
4903 					ASSERT(cid == pred->dtp_cacheid);
4904 					curthread->t_predcache = cid;
4905 				}
4906 
4907 				continue;
4908 			}
4909 		}
4910 
4911 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
4912 		    act != NULL; act = act->dta_next) {
4913 			size_t valoffs;
4914 			dtrace_difo_t *dp;
4915 			dtrace_recdesc_t *rec = &act->dta_rec;
4916 
4917 			size = rec->dtrd_size;
4918 			valoffs = offs + rec->dtrd_offset;
4919 
4920 			if (DTRACEACT_ISAGG(act->dta_kind)) {
4921 				uint64_t v = 0xbad;
4922 				dtrace_aggregation_t *agg;
4923 
4924 				agg = (dtrace_aggregation_t *)act;
4925 
4926 				if ((dp = act->dta_difo) != NULL)
4927 					v = dtrace_dif_emulate(dp,
4928 					    &mstate, vstate, state);
4929 
4930 				if (*flags & CPU_DTRACE_ERROR)
4931 					continue;
4932 
4933 				/*
4934 				 * Note that we always pass the expression
4935 				 * value from the previous iteration of the
4936 				 * action loop.  This value will only be used
4937 				 * if there is an expression argument to the
4938 				 * aggregating action, denoted by the
4939 				 * dtag_hasarg field.
4940 				 */
4941 				dtrace_aggregate(agg, buf,
4942 				    offs, aggbuf, v, val);
4943 				continue;
4944 			}
4945 
4946 			switch (act->dta_kind) {
4947 			case DTRACEACT_STOP:
4948 				if (dtrace_priv_proc_destructive(state))
4949 					dtrace_action_stop();
4950 				continue;
4951 
4952 			case DTRACEACT_BREAKPOINT:
4953 				if (dtrace_priv_kernel_destructive(state))
4954 					dtrace_action_breakpoint(ecb);
4955 				continue;
4956 
4957 			case DTRACEACT_PANIC:
4958 				if (dtrace_priv_kernel_destructive(state))
4959 					dtrace_action_panic(ecb);
4960 				continue;
4961 
4962 			case DTRACEACT_STACK:
4963 				if (!dtrace_priv_kernel(state))
4964 					continue;
4965 
4966 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
4967 				    size / sizeof (pc_t), probe->dtpr_aframes,
4968 				    DTRACE_ANCHORED(probe) ? NULL :
4969 				    (uint32_t *)arg0);
4970 
4971 				continue;
4972 
4973 			case DTRACEACT_JSTACK:
4974 			case DTRACEACT_USTACK:
4975 				if (!dtrace_priv_proc(state))
4976 					continue;
4977 
4978 				/*
4979 				 * See comment in DIF_VAR_PID.
4980 				 */
4981 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
4982 				    CPU_ON_INTR(CPU)) {
4983 					int depth = DTRACE_USTACK_NFRAMES(
4984 					    rec->dtrd_arg) + 1;
4985 
4986 					dtrace_bzero((void *)(tomax + valoffs),
4987 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
4988 					    + depth * sizeof (uint64_t));
4989 
4990 					continue;
4991 				}
4992 
4993 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
4994 				    curproc->p_dtrace_helpers != NULL) {
4995 					/*
4996 					 * This is the slow path -- we have
4997 					 * allocated string space, and we're
4998 					 * getting the stack of a process that
4999 					 * has helpers.  Call into a separate
5000 					 * routine to perform this processing.
5001 					 */
5002 					dtrace_action_ustack(&mstate, state,
5003 					    (uint64_t *)(tomax + valoffs),
5004 					    rec->dtrd_arg);
5005 					continue;
5006 				}
5007 
5008 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5009 				dtrace_getupcstack((uint64_t *)
5010 				    (tomax + valoffs),
5011 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
5012 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5013 				continue;
5014 
5015 			default:
5016 				break;
5017 			}
5018 
5019 			dp = act->dta_difo;
5020 			ASSERT(dp != NULL);
5021 
5022 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
5023 
5024 			if (*flags & CPU_DTRACE_ERROR)
5025 				continue;
5026 
5027 			switch (act->dta_kind) {
5028 			case DTRACEACT_SPECULATE:
5029 				ASSERT(buf == &state->dts_buffer[cpuid]);
5030 				buf = dtrace_speculation_buffer(state,
5031 				    cpuid, val);
5032 
5033 				if (buf == NULL) {
5034 					*flags |= CPU_DTRACE_DROP;
5035 					continue;
5036 				}
5037 
5038 				offs = dtrace_buffer_reserve(buf,
5039 				    ecb->dte_needed, ecb->dte_alignment,
5040 				    state, NULL);
5041 
5042 				if (offs < 0) {
5043 					*flags |= CPU_DTRACE_DROP;
5044 					continue;
5045 				}
5046 
5047 				tomax = buf->dtb_tomax;
5048 				ASSERT(tomax != NULL);
5049 
5050 				if (ecb->dte_size != 0)
5051 					DTRACE_STORE(uint32_t, tomax, offs,
5052 					    ecb->dte_epid);
5053 				continue;
5054 
5055 			case DTRACEACT_CHILL:
5056 				if (dtrace_priv_kernel_destructive(state))
5057 					dtrace_action_chill(&mstate, val);
5058 				continue;
5059 
5060 			case DTRACEACT_RAISE:
5061 				if (dtrace_priv_proc_destructive(state))
5062 					dtrace_action_raise(val);
5063 				continue;
5064 
5065 			case DTRACEACT_COMMIT:
5066 				ASSERT(!committed);
5067 
5068 				/*
5069 				 * We need to commit our buffer state.
5070 				 */
5071 				if (ecb->dte_size)
5072 					buf->dtb_offset = offs + ecb->dte_size;
5073 				buf = &state->dts_buffer[cpuid];
5074 				dtrace_speculation_commit(state, cpuid, val);
5075 				committed = 1;
5076 				continue;
5077 
5078 			case DTRACEACT_DISCARD:
5079 				dtrace_speculation_discard(state, cpuid, val);
5080 				continue;
5081 
5082 			case DTRACEACT_DIFEXPR:
5083 			case DTRACEACT_LIBACT:
5084 			case DTRACEACT_PRINTF:
5085 			case DTRACEACT_PRINTA:
5086 			case DTRACEACT_SYSTEM:
5087 			case DTRACEACT_FREOPEN:
5088 				break;
5089 
5090 			case DTRACEACT_SYM:
5091 			case DTRACEACT_MOD:
5092 				if (!dtrace_priv_kernel(state))
5093 					continue;
5094 				break;
5095 
5096 			case DTRACEACT_USYM:
5097 			case DTRACEACT_UMOD:
5098 			case DTRACEACT_UADDR: {
5099 				struct pid *pid = curthread->t_procp->p_pidp;
5100 
5101 				if (!dtrace_priv_proc(state))
5102 					continue;
5103 
5104 				DTRACE_STORE(uint64_t, tomax,
5105 				    valoffs, (uint64_t)pid->pid_id);
5106 				DTRACE_STORE(uint64_t, tomax,
5107 				    valoffs + sizeof (uint64_t), val);
5108 
5109 				continue;
5110 			}
5111 
5112 			case DTRACEACT_EXIT: {
5113 				/*
5114 				 * For the exit action, we are going to attempt
5115 				 * to atomically set our activity to be
5116 				 * draining.  If this fails (either because
5117 				 * another CPU has beat us to the exit action,
5118 				 * or because our current activity is something
5119 				 * other than ACTIVE or WARMUP), we will
5120 				 * continue.  This assures that the exit action
5121 				 * can be successfully recorded at most once
5122 				 * when we're in the ACTIVE state.  If we're
5123 				 * encountering the exit() action while in
5124 				 * COOLDOWN, however, we want to honor the new
5125 				 * status code.  (We know that we're the only
5126 				 * thread in COOLDOWN, so there is no race.)
5127 				 */
5128 				void *activity = &state->dts_activity;
5129 				dtrace_activity_t current = state->dts_activity;
5130 
5131 				if (current == DTRACE_ACTIVITY_COOLDOWN)
5132 					break;
5133 
5134 				if (current != DTRACE_ACTIVITY_WARMUP)
5135 					current = DTRACE_ACTIVITY_ACTIVE;
5136 
5137 				if (dtrace_cas32(activity, current,
5138 				    DTRACE_ACTIVITY_DRAINING) != current) {
5139 					*flags |= CPU_DTRACE_DROP;
5140 					continue;
5141 				}
5142 
5143 				break;
5144 			}
5145 
5146 			default:
5147 				ASSERT(0);
5148 			}
5149 
5150 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
5151 				uintptr_t end = valoffs + size;
5152 
5153 				/*
5154 				 * If this is a string, we're going to only
5155 				 * load until we find the zero byte -- after
5156 				 * which we'll store zero bytes.
5157 				 */
5158 				if (dp->dtdo_rtype.dtdt_kind ==
5159 				    DIF_TYPE_STRING) {
5160 					char c = '\0' + 1;
5161 					int intuple = act->dta_intuple;
5162 					size_t s;
5163 
5164 					for (s = 0; s < size; s++) {
5165 						if (c != '\0')
5166 							c = dtrace_load8(val++);
5167 
5168 						DTRACE_STORE(uint8_t, tomax,
5169 						    valoffs++, c);
5170 
5171 						if (c == '\0' && intuple)
5172 							break;
5173 					}
5174 
5175 					continue;
5176 				}
5177 
5178 				while (valoffs < end) {
5179 					DTRACE_STORE(uint8_t, tomax, valoffs++,
5180 					    dtrace_load8(val++));
5181 				}
5182 
5183 				continue;
5184 			}
5185 
5186 			switch (size) {
5187 			case 0:
5188 				break;
5189 
5190 			case sizeof (uint8_t):
5191 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
5192 				break;
5193 			case sizeof (uint16_t):
5194 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
5195 				break;
5196 			case sizeof (uint32_t):
5197 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
5198 				break;
5199 			case sizeof (uint64_t):
5200 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
5201 				break;
5202 			default:
5203 				/*
5204 				 * Any other size should have been returned by
5205 				 * reference, not by value.
5206 				 */
5207 				ASSERT(0);
5208 				break;
5209 			}
5210 		}
5211 
5212 		if (*flags & CPU_DTRACE_DROP)
5213 			continue;
5214 
5215 		if (*flags & CPU_DTRACE_FAULT) {
5216 			int ndx;
5217 			dtrace_action_t *err;
5218 
5219 			buf->dtb_errors++;
5220 
5221 			if (probe->dtpr_id == dtrace_probeid_error) {
5222 				/*
5223 				 * There's nothing we can do -- we had an
5224 				 * error on the error probe.  We bump an
5225 				 * error counter to at least indicate that
5226 				 * this condition happened.
5227 				 */
5228 				dtrace_error(&state->dts_dblerrors);
5229 				continue;
5230 			}
5231 
5232 			if (vtime) {
5233 				/*
5234 				 * Before recursing on dtrace_probe(), we
5235 				 * need to explicitly clear out our start
5236 				 * time to prevent it from being accumulated
5237 				 * into t_dtrace_vtime.
5238 				 */
5239 				curthread->t_dtrace_start = 0;
5240 			}
5241 
5242 			/*
5243 			 * Iterate over the actions to figure out which action
5244 			 * we were processing when we experienced the error.
5245 			 * Note that act points _past_ the faulting action; if
5246 			 * act is ecb->dte_action, the fault was in the
5247 			 * predicate, if it's ecb->dte_action->dta_next it's
5248 			 * in action #1, and so on.
5249 			 */
5250 			for (err = ecb->dte_action, ndx = 0;
5251 			    err != act; err = err->dta_next, ndx++)
5252 				continue;
5253 
5254 			dtrace_probe_error(state, ecb->dte_epid, ndx,
5255 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
5256 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
5257 			    cpu_core[cpuid].cpuc_dtrace_illval);
5258 
5259 			continue;
5260 		}
5261 
5262 		if (!committed)
5263 			buf->dtb_offset = offs + ecb->dte_size;
5264 	}
5265 
5266 	if (vtime)
5267 		curthread->t_dtrace_start = dtrace_gethrtime();
5268 
5269 	dtrace_interrupt_enable(cookie);
5270 }
5271 
5272 /*
5273  * DTrace Probe Hashing Functions
5274  *
5275  * The functions in this section (and indeed, the functions in remaining
5276  * sections) are not _called_ from probe context.  (Any exceptions to this are
5277  * marked with a "Note:".)  Rather, they are called from elsewhere in the
5278  * DTrace framework to look-up probes in, add probes to and remove probes from
5279  * the DTrace probe hashes.  (Each probe is hashed by each element of the
5280  * probe tuple -- allowing for fast lookups, regardless of what was
5281  * specified.)
5282  */
5283 static uint_t
5284 dtrace_hash_str(char *p)
5285 {
5286 	unsigned int g;
5287 	uint_t hval = 0;
5288 
5289 	while (*p) {
5290 		hval = (hval << 4) + *p++;
5291 		if ((g = (hval & 0xf0000000)) != 0)
5292 			hval ^= g >> 24;
5293 		hval &= ~g;
5294 	}
5295 	return (hval);
5296 }
5297 
5298 static dtrace_hash_t *
5299 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
5300 {
5301 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
5302 
5303 	hash->dth_stroffs = stroffs;
5304 	hash->dth_nextoffs = nextoffs;
5305 	hash->dth_prevoffs = prevoffs;
5306 
5307 	hash->dth_size = 1;
5308 	hash->dth_mask = hash->dth_size - 1;
5309 
5310 	hash->dth_tab = kmem_zalloc(hash->dth_size *
5311 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
5312 
5313 	return (hash);
5314 }
5315 
5316 static void
5317 dtrace_hash_destroy(dtrace_hash_t *hash)
5318 {
5319 #ifdef DEBUG
5320 	int i;
5321 
5322 	for (i = 0; i < hash->dth_size; i++)
5323 		ASSERT(hash->dth_tab[i] == NULL);
5324 #endif
5325 
5326 	kmem_free(hash->dth_tab,
5327 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
5328 	kmem_free(hash, sizeof (dtrace_hash_t));
5329 }
5330 
5331 static void
5332 dtrace_hash_resize(dtrace_hash_t *hash)
5333 {
5334 	int size = hash->dth_size, i, ndx;
5335 	int new_size = hash->dth_size << 1;
5336 	int new_mask = new_size - 1;
5337 	dtrace_hashbucket_t **new_tab, *bucket, *next;
5338 
5339 	ASSERT((new_size & new_mask) == 0);
5340 
5341 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
5342 
5343 	for (i = 0; i < size; i++) {
5344 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
5345 			dtrace_probe_t *probe = bucket->dthb_chain;
5346 
5347 			ASSERT(probe != NULL);
5348 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
5349 
5350 			next = bucket->dthb_next;
5351 			bucket->dthb_next = new_tab[ndx];
5352 			new_tab[ndx] = bucket;
5353 		}
5354 	}
5355 
5356 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
5357 	hash->dth_tab = new_tab;
5358 	hash->dth_size = new_size;
5359 	hash->dth_mask = new_mask;
5360 }
5361 
5362 static void
5363 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
5364 {
5365 	int hashval = DTRACE_HASHSTR(hash, new);
5366 	int ndx = hashval & hash->dth_mask;
5367 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5368 	dtrace_probe_t **nextp, **prevp;
5369 
5370 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5371 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
5372 			goto add;
5373 	}
5374 
5375 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
5376 		dtrace_hash_resize(hash);
5377 		dtrace_hash_add(hash, new);
5378 		return;
5379 	}
5380 
5381 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
5382 	bucket->dthb_next = hash->dth_tab[ndx];
5383 	hash->dth_tab[ndx] = bucket;
5384 	hash->dth_nbuckets++;
5385 
5386 add:
5387 	nextp = DTRACE_HASHNEXT(hash, new);
5388 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
5389 	*nextp = bucket->dthb_chain;
5390 
5391 	if (bucket->dthb_chain != NULL) {
5392 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
5393 		ASSERT(*prevp == NULL);
5394 		*prevp = new;
5395 	}
5396 
5397 	bucket->dthb_chain = new;
5398 	bucket->dthb_len++;
5399 }
5400 
5401 static dtrace_probe_t *
5402 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
5403 {
5404 	int hashval = DTRACE_HASHSTR(hash, template);
5405 	int ndx = hashval & hash->dth_mask;
5406 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5407 
5408 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5409 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
5410 			return (bucket->dthb_chain);
5411 	}
5412 
5413 	return (NULL);
5414 }
5415 
5416 static int
5417 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
5418 {
5419 	int hashval = DTRACE_HASHSTR(hash, template);
5420 	int ndx = hashval & hash->dth_mask;
5421 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5422 
5423 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5424 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
5425 			return (bucket->dthb_len);
5426 	}
5427 
5428 	return (NULL);
5429 }
5430 
5431 static void
5432 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
5433 {
5434 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
5435 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5436 
5437 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
5438 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
5439 
5440 	/*
5441 	 * Find the bucket that we're removing this probe from.
5442 	 */
5443 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5444 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
5445 			break;
5446 	}
5447 
5448 	ASSERT(bucket != NULL);
5449 
5450 	if (*prevp == NULL) {
5451 		if (*nextp == NULL) {
5452 			/*
5453 			 * The removed probe was the only probe on this
5454 			 * bucket; we need to remove the bucket.
5455 			 */
5456 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
5457 
5458 			ASSERT(bucket->dthb_chain == probe);
5459 			ASSERT(b != NULL);
5460 
5461 			if (b == bucket) {
5462 				hash->dth_tab[ndx] = bucket->dthb_next;
5463 			} else {
5464 				while (b->dthb_next != bucket)
5465 					b = b->dthb_next;
5466 				b->dthb_next = bucket->dthb_next;
5467 			}
5468 
5469 			ASSERT(hash->dth_nbuckets > 0);
5470 			hash->dth_nbuckets--;
5471 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
5472 			return;
5473 		}
5474 
5475 		bucket->dthb_chain = *nextp;
5476 	} else {
5477 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
5478 	}
5479 
5480 	if (*nextp != NULL)
5481 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
5482 }
5483 
5484 /*
5485  * DTrace Utility Functions
5486  *
5487  * These are random utility functions that are _not_ called from probe context.
5488  */
5489 static int
5490 dtrace_badattr(const dtrace_attribute_t *a)
5491 {
5492 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
5493 	    a->dtat_data > DTRACE_STABILITY_MAX ||
5494 	    a->dtat_class > DTRACE_CLASS_MAX);
5495 }
5496 
5497 /*
5498  * Return a duplicate copy of a string.  If the specified string is NULL,
5499  * this function returns a zero-length string.
5500  */
5501 static char *
5502 dtrace_strdup(const char *str)
5503 {
5504 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
5505 
5506 	if (str != NULL)
5507 		(void) strcpy(new, str);
5508 
5509 	return (new);
5510 }
5511 
5512 #define	DTRACE_ISALPHA(c)	\
5513 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
5514 
5515 static int
5516 dtrace_badname(const char *s)
5517 {
5518 	char c;
5519 
5520 	if (s == NULL || (c = *s++) == '\0')
5521 		return (0);
5522 
5523 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
5524 		return (1);
5525 
5526 	while ((c = *s++) != '\0') {
5527 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
5528 		    c != '-' && c != '_' && c != '.' && c != '`')
5529 			return (1);
5530 	}
5531 
5532 	return (0);
5533 }
5534 
5535 static void
5536 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
5537 {
5538 	uint32_t priv;
5539 
5540 	*uidp = crgetuid(cr);
5541 	*zoneidp = crgetzoneid(cr);
5542 	if (PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
5543 		priv = DTRACE_PRIV_ALL;
5544 	} else {
5545 		priv = 0;
5546 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
5547 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
5548 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
5549 			priv |= DTRACE_PRIV_USER;
5550 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
5551 			priv |= DTRACE_PRIV_PROC;
5552 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
5553 			priv |= DTRACE_PRIV_OWNER;
5554 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
5555 			priv |= DTRACE_PRIV_ZONEOWNER;
5556 	}
5557 
5558 	*privp = priv;
5559 }
5560 
5561 #ifdef DTRACE_ERRDEBUG
5562 static void
5563 dtrace_errdebug(const char *str)
5564 {
5565 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
5566 	int occupied = 0;
5567 
5568 	mutex_enter(&dtrace_errlock);
5569 	dtrace_errlast = str;
5570 	dtrace_errthread = curthread;
5571 
5572 	while (occupied++ < DTRACE_ERRHASHSZ) {
5573 		if (dtrace_errhash[hval].dter_msg == str) {
5574 			dtrace_errhash[hval].dter_count++;
5575 			goto out;
5576 		}
5577 
5578 		if (dtrace_errhash[hval].dter_msg != NULL) {
5579 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
5580 			continue;
5581 		}
5582 
5583 		dtrace_errhash[hval].dter_msg = str;
5584 		dtrace_errhash[hval].dter_count = 1;
5585 		goto out;
5586 	}
5587 
5588 	panic("dtrace: undersized error hash");
5589 out:
5590 	mutex_exit(&dtrace_errlock);
5591 }
5592 #endif
5593 
5594 /*
5595  * DTrace Matching Functions
5596  *
5597  * These functions are used to match groups of probes, given some elements of
5598  * a probe tuple, or some globbed expressions for elements of a probe tuple.
5599  */
5600 static int
5601 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
5602     zoneid_t zoneid)
5603 {
5604 	if (priv != DTRACE_PRIV_ALL) {
5605 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
5606 		uint32_t match = priv & ppriv;
5607 
5608 		/*
5609 		 * No PRIV_DTRACE_* privileges...
5610 		 */
5611 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
5612 		    DTRACE_PRIV_KERNEL)) == 0)
5613 			return (0);
5614 
5615 		/*
5616 		 * No matching bits, but there were bits to match...
5617 		 */
5618 		if (match == 0 && ppriv != 0)
5619 			return (0);
5620 
5621 		/*
5622 		 * Need to have permissions to the process, but don't...
5623 		 */
5624 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
5625 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
5626 			return (0);
5627 		}
5628 
5629 		/*
5630 		 * Need to be in the same zone unless we possess the
5631 		 * privilege to examine all zones.
5632 		 */
5633 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
5634 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
5635 			return (0);
5636 		}
5637 	}
5638 
5639 	return (1);
5640 }
5641 
5642 /*
5643  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
5644  * consists of input pattern strings and an ops-vector to evaluate them.
5645  * This function returns >0 for match, 0 for no match, and <0 for error.
5646  */
5647 static int
5648 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
5649     uint32_t priv, uid_t uid, zoneid_t zoneid)
5650 {
5651 	dtrace_provider_t *pvp = prp->dtpr_provider;
5652 	int rv;
5653 
5654 	if (pvp->dtpv_defunct)
5655 		return (0);
5656 
5657 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
5658 		return (rv);
5659 
5660 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
5661 		return (rv);
5662 
5663 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
5664 		return (rv);
5665 
5666 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
5667 		return (rv);
5668 
5669 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
5670 		return (0);
5671 
5672 	return (rv);
5673 }
5674 
5675 /*
5676  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
5677  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
5678  * libc's version, the kernel version only applies to 8-bit ASCII strings.
5679  * In addition, all of the recursion cases except for '*' matching have been
5680  * unwound.  For '*', we still implement recursive evaluation, but a depth
5681  * counter is maintained and matching is aborted if we recurse too deep.
5682  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
5683  */
5684 static int
5685 dtrace_match_glob(const char *s, const char *p, int depth)
5686 {
5687 	const char *olds;
5688 	char s1, c;
5689 	int gs;
5690 
5691 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
5692 		return (-1);
5693 
5694 	if (s == NULL)
5695 		s = ""; /* treat NULL as empty string */
5696 
5697 top:
5698 	olds = s;
5699 	s1 = *s++;
5700 
5701 	if (p == NULL)
5702 		return (0);
5703 
5704 	if ((c = *p++) == '\0')
5705 		return (s1 == '\0');
5706 
5707 	switch (c) {
5708 	case '[': {
5709 		int ok = 0, notflag = 0;
5710 		char lc = '\0';
5711 
5712 		if (s1 == '\0')
5713 			return (0);
5714 
5715 		if (*p == '!') {
5716 			notflag = 1;
5717 			p++;
5718 		}
5719 
5720 		if ((c = *p++) == '\0')
5721 			return (0);
5722 
5723 		do {
5724 			if (c == '-' && lc != '\0' && *p != ']') {
5725 				if ((c = *p++) == '\0')
5726 					return (0);
5727 				if (c == '\\' && (c = *p++) == '\0')
5728 					return (0);
5729 
5730 				if (notflag) {
5731 					if (s1 < lc || s1 > c)
5732 						ok++;
5733 					else
5734 						return (0);
5735 				} else if (lc <= s1 && s1 <= c)
5736 					ok++;
5737 
5738 			} else if (c == '\\' && (c = *p++) == '\0')
5739 				return (0);
5740 
5741 			lc = c; /* save left-hand 'c' for next iteration */
5742 
5743 			if (notflag) {
5744 				if (s1 != c)
5745 					ok++;
5746 				else
5747 					return (0);
5748 			} else if (s1 == c)
5749 				ok++;
5750 
5751 			if ((c = *p++) == '\0')
5752 				return (0);
5753 
5754 		} while (c != ']');
5755 
5756 		if (ok)
5757 			goto top;
5758 
5759 		return (0);
5760 	}
5761 
5762 	case '\\':
5763 		if ((c = *p++) == '\0')
5764 			return (0);
5765 		/*FALLTHRU*/
5766 
5767 	default:
5768 		if (c != s1)
5769 			return (0);
5770 		/*FALLTHRU*/
5771 
5772 	case '?':
5773 		if (s1 != '\0')
5774 			goto top;
5775 		return (0);
5776 
5777 	case '*':
5778 		while (*p == '*')
5779 			p++; /* consecutive *'s are identical to a single one */
5780 
5781 		if (*p == '\0')
5782 			return (1);
5783 
5784 		for (s = olds; *s != '\0'; s++) {
5785 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
5786 				return (gs);
5787 		}
5788 
5789 		return (0);
5790 	}
5791 }
5792 
5793 /*ARGSUSED*/
5794 static int
5795 dtrace_match_string(const char *s, const char *p, int depth)
5796 {
5797 	return (s != NULL && strcmp(s, p) == 0);
5798 }
5799 
5800 /*ARGSUSED*/
5801 static int
5802 dtrace_match_nul(const char *s, const char *p, int depth)
5803 {
5804 	return (1); /* always match the empty pattern */
5805 }
5806 
5807 /*ARGSUSED*/
5808 static int
5809 dtrace_match_nonzero(const char *s, const char *p, int depth)
5810 {
5811 	return (s != NULL && s[0] != '\0');
5812 }
5813 
5814 static int
5815 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
5816     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
5817 {
5818 	dtrace_probe_t template, *probe;
5819 	dtrace_hash_t *hash = NULL;
5820 	int len, best = INT_MAX, nmatched = 0;
5821 	dtrace_id_t i;
5822 
5823 	ASSERT(MUTEX_HELD(&dtrace_lock));
5824 
5825 	/*
5826 	 * If the probe ID is specified in the key, just lookup by ID and
5827 	 * invoke the match callback once if a matching probe is found.
5828 	 */
5829 	if (pkp->dtpk_id != DTRACE_IDNONE) {
5830 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
5831 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
5832 			(void) (*matched)(probe, arg);
5833 			nmatched++;
5834 		}
5835 		return (nmatched);
5836 	}
5837 
5838 	template.dtpr_mod = (char *)pkp->dtpk_mod;
5839 	template.dtpr_func = (char *)pkp->dtpk_func;
5840 	template.dtpr_name = (char *)pkp->dtpk_name;
5841 
5842 	/*
5843 	 * We want to find the most distinct of the module name, function
5844 	 * name, and name.  So for each one that is not a glob pattern or
5845 	 * empty string, we perform a lookup in the corresponding hash and
5846 	 * use the hash table with the fewest collisions to do our search.
5847 	 */
5848 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
5849 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
5850 		best = len;
5851 		hash = dtrace_bymod;
5852 	}
5853 
5854 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
5855 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
5856 		best = len;
5857 		hash = dtrace_byfunc;
5858 	}
5859 
5860 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
5861 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
5862 		best = len;
5863 		hash = dtrace_byname;
5864 	}
5865 
5866 	/*
5867 	 * If we did not select a hash table, iterate over every probe and
5868 	 * invoke our callback for each one that matches our input probe key.
5869 	 */
5870 	if (hash == NULL) {
5871 		for (i = 0; i < dtrace_nprobes; i++) {
5872 			if ((probe = dtrace_probes[i]) == NULL ||
5873 			    dtrace_match_probe(probe, pkp, priv, uid,
5874 			    zoneid) <= 0)
5875 				continue;
5876 
5877 			nmatched++;
5878 
5879 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
5880 				break;
5881 		}
5882 
5883 		return (nmatched);
5884 	}
5885 
5886 	/*
5887 	 * If we selected a hash table, iterate over each probe of the same key
5888 	 * name and invoke the callback for every probe that matches the other
5889 	 * attributes of our input probe key.
5890 	 */
5891 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
5892 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
5893 
5894 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
5895 			continue;
5896 
5897 		nmatched++;
5898 
5899 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
5900 			break;
5901 	}
5902 
5903 	return (nmatched);
5904 }
5905 
5906 /*
5907  * Return the function pointer dtrace_probecmp() should use to compare the
5908  * specified pattern with a string.  For NULL or empty patterns, we select
5909  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
5910  * For non-empty non-glob strings, we use dtrace_match_string().
5911  */
5912 static dtrace_probekey_f *
5913 dtrace_probekey_func(const char *p)
5914 {
5915 	char c;
5916 
5917 	if (p == NULL || *p == '\0')
5918 		return (&dtrace_match_nul);
5919 
5920 	while ((c = *p++) != '\0') {
5921 		if (c == '[' || c == '?' || c == '*' || c == '\\')
5922 			return (&dtrace_match_glob);
5923 	}
5924 
5925 	return (&dtrace_match_string);
5926 }
5927 
5928 /*
5929  * Build a probe comparison key for use with dtrace_match_probe() from the
5930  * given probe description.  By convention, a null key only matches anchored
5931  * probes: if each field is the empty string, reset dtpk_fmatch to
5932  * dtrace_match_nonzero().
5933  */
5934 static void
5935 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
5936 {
5937 	pkp->dtpk_prov = pdp->dtpd_provider;
5938 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
5939 
5940 	pkp->dtpk_mod = pdp->dtpd_mod;
5941 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
5942 
5943 	pkp->dtpk_func = pdp->dtpd_func;
5944 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
5945 
5946 	pkp->dtpk_name = pdp->dtpd_name;
5947 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
5948 
5949 	pkp->dtpk_id = pdp->dtpd_id;
5950 
5951 	if (pkp->dtpk_id == DTRACE_IDNONE &&
5952 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
5953 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
5954 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
5955 	    pkp->dtpk_nmatch == &dtrace_match_nul)
5956 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
5957 }
5958 
5959 /*
5960  * DTrace Provider-to-Framework API Functions
5961  *
5962  * These functions implement much of the Provider-to-Framework API, as
5963  * described in <sys/dtrace.h>.  The parts of the API not in this section are
5964  * the functions in the API for probe management (found below), and
5965  * dtrace_probe() itself (found above).
5966  */
5967 
5968 /*
5969  * Register the calling provider with the DTrace framework.  This should
5970  * generally be called by DTrace providers in their attach(9E) entry point.
5971  */
5972 int
5973 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
5974     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
5975 {
5976 	dtrace_provider_t *provider;
5977 
5978 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
5979 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
5980 		    "arguments", name ? name : "<NULL>");
5981 		return (EINVAL);
5982 	}
5983 
5984 	if (name[0] == '\0' || dtrace_badname(name)) {
5985 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
5986 		    "provider name", name);
5987 		return (EINVAL);
5988 	}
5989 
5990 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
5991 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
5992 	    pops->dtps_destroy == NULL ||
5993 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
5994 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
5995 		    "provider ops", name);
5996 		return (EINVAL);
5997 	}
5998 
5999 	if (dtrace_badattr(&pap->dtpa_provider) ||
6000 	    dtrace_badattr(&pap->dtpa_mod) ||
6001 	    dtrace_badattr(&pap->dtpa_func) ||
6002 	    dtrace_badattr(&pap->dtpa_name) ||
6003 	    dtrace_badattr(&pap->dtpa_args)) {
6004 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6005 		    "provider attributes", name);
6006 		return (EINVAL);
6007 	}
6008 
6009 	if (priv & ~DTRACE_PRIV_ALL) {
6010 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6011 		    "privilege attributes", name);
6012 		return (EINVAL);
6013 	}
6014 
6015 	if ((priv & DTRACE_PRIV_KERNEL) &&
6016 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
6017 	    pops->dtps_usermode == NULL) {
6018 		cmn_err(CE_WARN, "failed to register provider '%s': need "
6019 		    "dtps_usermode() op for given privilege attributes", name);
6020 		return (EINVAL);
6021 	}
6022 
6023 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
6024 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
6025 	(void) strcpy(provider->dtpv_name, name);
6026 
6027 	provider->dtpv_attr = *pap;
6028 	provider->dtpv_priv.dtpp_flags = priv;
6029 	if (cr != NULL) {
6030 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
6031 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
6032 	}
6033 	provider->dtpv_pops = *pops;
6034 
6035 	if (pops->dtps_provide == NULL) {
6036 		ASSERT(pops->dtps_provide_module != NULL);
6037 		provider->dtpv_pops.dtps_provide =
6038 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
6039 	}
6040 
6041 	if (pops->dtps_provide_module == NULL) {
6042 		ASSERT(pops->dtps_provide != NULL);
6043 		provider->dtpv_pops.dtps_provide_module =
6044 		    (void (*)(void *, struct modctl *))dtrace_nullop;
6045 	}
6046 
6047 	if (pops->dtps_suspend == NULL) {
6048 		ASSERT(pops->dtps_resume == NULL);
6049 		provider->dtpv_pops.dtps_suspend =
6050 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6051 		provider->dtpv_pops.dtps_resume =
6052 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6053 	}
6054 
6055 	provider->dtpv_arg = arg;
6056 	*idp = (dtrace_provider_id_t)provider;
6057 
6058 	if (pops == &dtrace_provider_ops) {
6059 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6060 		ASSERT(MUTEX_HELD(&dtrace_lock));
6061 		ASSERT(dtrace_anon.dta_enabling == NULL);
6062 
6063 		/*
6064 		 * We make sure that the DTrace provider is at the head of
6065 		 * the provider chain.
6066 		 */
6067 		provider->dtpv_next = dtrace_provider;
6068 		dtrace_provider = provider;
6069 		return (0);
6070 	}
6071 
6072 	mutex_enter(&dtrace_provider_lock);
6073 	mutex_enter(&dtrace_lock);
6074 
6075 	/*
6076 	 * If there is at least one provider registered, we'll add this
6077 	 * provider after the first provider.
6078 	 */
6079 	if (dtrace_provider != NULL) {
6080 		provider->dtpv_next = dtrace_provider->dtpv_next;
6081 		dtrace_provider->dtpv_next = provider;
6082 	} else {
6083 		dtrace_provider = provider;
6084 	}
6085 
6086 	if (dtrace_retained != NULL) {
6087 		dtrace_enabling_provide(provider);
6088 
6089 		/*
6090 		 * Now we need to call dtrace_enabling_matchall() -- which
6091 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
6092 		 * to drop all of our locks before calling into it...
6093 		 */
6094 		mutex_exit(&dtrace_lock);
6095 		mutex_exit(&dtrace_provider_lock);
6096 		dtrace_enabling_matchall();
6097 
6098 		return (0);
6099 	}
6100 
6101 	mutex_exit(&dtrace_lock);
6102 	mutex_exit(&dtrace_provider_lock);
6103 
6104 	return (0);
6105 }
6106 
6107 /*
6108  * Unregister the specified provider from the DTrace framework.  This should
6109  * generally be called by DTrace providers in their detach(9E) entry point.
6110  */
6111 int
6112 dtrace_unregister(dtrace_provider_id_t id)
6113 {
6114 	dtrace_provider_t *old = (dtrace_provider_t *)id;
6115 	dtrace_provider_t *prev = NULL;
6116 	int i, self = 0;
6117 	dtrace_probe_t *probe, *first = NULL;
6118 
6119 	if (old->dtpv_pops.dtps_enable ==
6120 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
6121 		/*
6122 		 * If DTrace itself is the provider, we're called with locks
6123 		 * already held.
6124 		 */
6125 		ASSERT(old == dtrace_provider);
6126 		ASSERT(dtrace_devi != NULL);
6127 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6128 		ASSERT(MUTEX_HELD(&dtrace_lock));
6129 		self = 1;
6130 
6131 		if (dtrace_provider->dtpv_next != NULL) {
6132 			/*
6133 			 * There's another provider here; return failure.
6134 			 */
6135 			return (EBUSY);
6136 		}
6137 	} else {
6138 		mutex_enter(&dtrace_provider_lock);
6139 		mutex_enter(&mod_lock);
6140 		mutex_enter(&dtrace_lock);
6141 	}
6142 
6143 	/*
6144 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
6145 	 * probes, we refuse to let providers slither away, unless this
6146 	 * provider has already been explicitly invalidated.
6147 	 */
6148 	if (!old->dtpv_defunct &&
6149 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
6150 	    dtrace_anon.dta_state->dts_necbs > 0))) {
6151 		if (!self) {
6152 			mutex_exit(&dtrace_lock);
6153 			mutex_exit(&mod_lock);
6154 			mutex_exit(&dtrace_provider_lock);
6155 		}
6156 		return (EBUSY);
6157 	}
6158 
6159 	/*
6160 	 * Attempt to destroy the probes associated with this provider.
6161 	 */
6162 	for (i = 0; i < dtrace_nprobes; i++) {
6163 		if ((probe = dtrace_probes[i]) == NULL)
6164 			continue;
6165 
6166 		if (probe->dtpr_provider != old)
6167 			continue;
6168 
6169 		if (probe->dtpr_ecb == NULL)
6170 			continue;
6171 
6172 		/*
6173 		 * We have at least one ECB; we can't remove this provider.
6174 		 */
6175 		if (!self) {
6176 			mutex_exit(&dtrace_lock);
6177 			mutex_exit(&mod_lock);
6178 			mutex_exit(&dtrace_provider_lock);
6179 		}
6180 		return (EBUSY);
6181 	}
6182 
6183 	/*
6184 	 * All of the probes for this provider are disabled; we can safely
6185 	 * remove all of them from their hash chains and from the probe array.
6186 	 */
6187 	for (i = 0; i < dtrace_nprobes; i++) {
6188 		if ((probe = dtrace_probes[i]) == NULL)
6189 			continue;
6190 
6191 		if (probe->dtpr_provider != old)
6192 			continue;
6193 
6194 		dtrace_probes[i] = NULL;
6195 
6196 		dtrace_hash_remove(dtrace_bymod, probe);
6197 		dtrace_hash_remove(dtrace_byfunc, probe);
6198 		dtrace_hash_remove(dtrace_byname, probe);
6199 
6200 		if (first == NULL) {
6201 			first = probe;
6202 			probe->dtpr_nextmod = NULL;
6203 		} else {
6204 			probe->dtpr_nextmod = first;
6205 			first = probe;
6206 		}
6207 	}
6208 
6209 	/*
6210 	 * The provider's probes have been removed from the hash chains and
6211 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
6212 	 * everyone has cleared out from any probe array processing.
6213 	 */
6214 	dtrace_sync();
6215 
6216 	for (probe = first; probe != NULL; probe = first) {
6217 		first = probe->dtpr_nextmod;
6218 
6219 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
6220 		    probe->dtpr_arg);
6221 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
6222 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
6223 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
6224 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
6225 		kmem_free(probe, sizeof (dtrace_probe_t));
6226 	}
6227 
6228 	if ((prev = dtrace_provider) == old) {
6229 		ASSERT(self || dtrace_devi == NULL);
6230 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
6231 		dtrace_provider = old->dtpv_next;
6232 	} else {
6233 		while (prev != NULL && prev->dtpv_next != old)
6234 			prev = prev->dtpv_next;
6235 
6236 		if (prev == NULL) {
6237 			panic("attempt to unregister non-existent "
6238 			    "dtrace provider %p\n", (void *)id);
6239 		}
6240 
6241 		prev->dtpv_next = old->dtpv_next;
6242 	}
6243 
6244 	if (!self) {
6245 		mutex_exit(&dtrace_lock);
6246 		mutex_exit(&mod_lock);
6247 		mutex_exit(&dtrace_provider_lock);
6248 	}
6249 
6250 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
6251 	kmem_free(old, sizeof (dtrace_provider_t));
6252 
6253 	return (0);
6254 }
6255 
6256 /*
6257  * Invalidate the specified provider.  All subsequent probe lookups for the
6258  * specified provider will fail, but its probes will not be removed.
6259  */
6260 void
6261 dtrace_invalidate(dtrace_provider_id_t id)
6262 {
6263 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
6264 
6265 	ASSERT(pvp->dtpv_pops.dtps_enable !=
6266 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6267 
6268 	mutex_enter(&dtrace_provider_lock);
6269 	mutex_enter(&dtrace_lock);
6270 
6271 	pvp->dtpv_defunct = 1;
6272 
6273 	mutex_exit(&dtrace_lock);
6274 	mutex_exit(&dtrace_provider_lock);
6275 }
6276 
6277 /*
6278  * Indicate whether or not DTrace has attached.
6279  */
6280 int
6281 dtrace_attached(void)
6282 {
6283 	/*
6284 	 * dtrace_provider will be non-NULL iff the DTrace driver has
6285 	 * attached.  (It's non-NULL because DTrace is always itself a
6286 	 * provider.)
6287 	 */
6288 	return (dtrace_provider != NULL);
6289 }
6290 
6291 /*
6292  * Remove all the unenabled probes for the given provider.  This function is
6293  * not unlike dtrace_unregister(), except that it doesn't remove the provider
6294  * -- just as many of its associated probes as it can.
6295  */
6296 int
6297 dtrace_condense(dtrace_provider_id_t id)
6298 {
6299 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
6300 	int i;
6301 	dtrace_probe_t *probe;
6302 
6303 	/*
6304 	 * Make sure this isn't the dtrace provider itself.
6305 	 */
6306 	ASSERT(prov->dtpv_pops.dtps_enable !=
6307 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6308 
6309 	mutex_enter(&dtrace_provider_lock);
6310 	mutex_enter(&dtrace_lock);
6311 
6312 	/*
6313 	 * Attempt to destroy the probes associated with this provider.
6314 	 */
6315 	for (i = 0; i < dtrace_nprobes; i++) {
6316 		if ((probe = dtrace_probes[i]) == NULL)
6317 			continue;
6318 
6319 		if (probe->dtpr_provider != prov)
6320 			continue;
6321 
6322 		if (probe->dtpr_ecb != NULL)
6323 			continue;
6324 
6325 		dtrace_probes[i] = NULL;
6326 
6327 		dtrace_hash_remove(dtrace_bymod, probe);
6328 		dtrace_hash_remove(dtrace_byfunc, probe);
6329 		dtrace_hash_remove(dtrace_byname, probe);
6330 
6331 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
6332 		    probe->dtpr_arg);
6333 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
6334 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
6335 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
6336 		kmem_free(probe, sizeof (dtrace_probe_t));
6337 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
6338 	}
6339 
6340 	mutex_exit(&dtrace_lock);
6341 	mutex_exit(&dtrace_provider_lock);
6342 
6343 	return (0);
6344 }
6345 
6346 /*
6347  * DTrace Probe Management Functions
6348  *
6349  * The functions in this section perform the DTrace probe management,
6350  * including functions to create probes, look-up probes, and call into the
6351  * providers to request that probes be provided.  Some of these functions are
6352  * in the Provider-to-Framework API; these functions can be identified by the
6353  * fact that they are not declared "static".
6354  */
6355 
6356 /*
6357  * Create a probe with the specified module name, function name, and name.
6358  */
6359 dtrace_id_t
6360 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
6361     const char *func, const char *name, int aframes, void *arg)
6362 {
6363 	dtrace_probe_t *probe, **probes;
6364 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
6365 	dtrace_id_t id;
6366 
6367 	if (provider == dtrace_provider) {
6368 		ASSERT(MUTEX_HELD(&dtrace_lock));
6369 	} else {
6370 		mutex_enter(&dtrace_lock);
6371 	}
6372 
6373 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
6374 	    VM_BESTFIT | VM_SLEEP);
6375 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
6376 
6377 	probe->dtpr_id = id;
6378 	probe->dtpr_gen = dtrace_probegen++;
6379 	probe->dtpr_mod = dtrace_strdup(mod);
6380 	probe->dtpr_func = dtrace_strdup(func);
6381 	probe->dtpr_name = dtrace_strdup(name);
6382 	probe->dtpr_arg = arg;
6383 	probe->dtpr_aframes = aframes;
6384 	probe->dtpr_provider = provider;
6385 
6386 	dtrace_hash_add(dtrace_bymod, probe);
6387 	dtrace_hash_add(dtrace_byfunc, probe);
6388 	dtrace_hash_add(dtrace_byname, probe);
6389 
6390 	if (id - 1 >= dtrace_nprobes) {
6391 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
6392 		size_t nsize = osize << 1;
6393 
6394 		if (nsize == 0) {
6395 			ASSERT(osize == 0);
6396 			ASSERT(dtrace_probes == NULL);
6397 			nsize = sizeof (dtrace_probe_t *);
6398 		}
6399 
6400 		probes = kmem_zalloc(nsize, KM_SLEEP);
6401 
6402 		if (dtrace_probes == NULL) {
6403 			ASSERT(osize == 0);
6404 			dtrace_probes = probes;
6405 			dtrace_nprobes = 1;
6406 		} else {
6407 			dtrace_probe_t **oprobes = dtrace_probes;
6408 
6409 			bcopy(oprobes, probes, osize);
6410 			dtrace_membar_producer();
6411 			dtrace_probes = probes;
6412 
6413 			dtrace_sync();
6414 
6415 			/*
6416 			 * All CPUs are now seeing the new probes array; we can
6417 			 * safely free the old array.
6418 			 */
6419 			kmem_free(oprobes, osize);
6420 			dtrace_nprobes <<= 1;
6421 		}
6422 
6423 		ASSERT(id - 1 < dtrace_nprobes);
6424 	}
6425 
6426 	ASSERT(dtrace_probes[id - 1] == NULL);
6427 	dtrace_probes[id - 1] = probe;
6428 
6429 	if (provider != dtrace_provider)
6430 		mutex_exit(&dtrace_lock);
6431 
6432 	return (id);
6433 }
6434 
6435 static dtrace_probe_t *
6436 dtrace_probe_lookup_id(dtrace_id_t id)
6437 {
6438 	ASSERT(MUTEX_HELD(&dtrace_lock));
6439 
6440 	if (id == 0 || id > dtrace_nprobes)
6441 		return (NULL);
6442 
6443 	return (dtrace_probes[id - 1]);
6444 }
6445 
6446 static int
6447 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
6448 {
6449 	*((dtrace_id_t *)arg) = probe->dtpr_id;
6450 
6451 	return (DTRACE_MATCH_DONE);
6452 }
6453 
6454 /*
6455  * Look up a probe based on provider and one or more of module name, function
6456  * name and probe name.
6457  */
6458 dtrace_id_t
6459 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
6460     const char *func, const char *name)
6461 {
6462 	dtrace_probekey_t pkey;
6463 	dtrace_id_t id;
6464 	int match;
6465 
6466 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
6467 	pkey.dtpk_pmatch = &dtrace_match_string;
6468 	pkey.dtpk_mod = mod;
6469 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
6470 	pkey.dtpk_func = func;
6471 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
6472 	pkey.dtpk_name = name;
6473 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
6474 	pkey.dtpk_id = DTRACE_IDNONE;
6475 
6476 	mutex_enter(&dtrace_lock);
6477 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
6478 	    dtrace_probe_lookup_match, &id);
6479 	mutex_exit(&dtrace_lock);
6480 
6481 	ASSERT(match == 1 || match == 0);
6482 	return (match ? id : 0);
6483 }
6484 
6485 /*
6486  * Returns the probe argument associated with the specified probe.
6487  */
6488 void *
6489 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
6490 {
6491 	dtrace_probe_t *probe;
6492 	void *rval = NULL;
6493 
6494 	mutex_enter(&dtrace_lock);
6495 
6496 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
6497 	    probe->dtpr_provider == (dtrace_provider_t *)id)
6498 		rval = probe->dtpr_arg;
6499 
6500 	mutex_exit(&dtrace_lock);
6501 
6502 	return (rval);
6503 }
6504 
6505 /*
6506  * Copy a probe into a probe description.
6507  */
6508 static void
6509 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
6510 {
6511 	bzero(pdp, sizeof (dtrace_probedesc_t));
6512 	pdp->dtpd_id = prp->dtpr_id;
6513 
6514 	(void) strncpy(pdp->dtpd_provider,
6515 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
6516 
6517 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
6518 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
6519 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
6520 }
6521 
6522 /*
6523  * Called to indicate that a probe -- or probes -- should be provided by a
6524  * specfied provider.  If the specified description is NULL, the provider will
6525  * be told to provide all of its probes.  (This is done whenever a new
6526  * consumer comes along, or whenever a retained enabling is to be matched.) If
6527  * the specified description is non-NULL, the provider is given the
6528  * opportunity to dynamically provide the specified probe, allowing providers
6529  * to support the creation of probes on-the-fly.  (So-called _autocreated_
6530  * probes.)  If the provider is NULL, the operations will be applied to all
6531  * providers; if the provider is non-NULL the operations will only be applied
6532  * to the specified provider.  The dtrace_provider_lock must be held, and the
6533  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
6534  * will need to grab the dtrace_lock when it reenters the framework through
6535  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
6536  */
6537 static void
6538 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
6539 {
6540 	struct modctl *ctl;
6541 	int all = 0;
6542 
6543 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6544 
6545 	if (prv == NULL) {
6546 		all = 1;
6547 		prv = dtrace_provider;
6548 	}
6549 
6550 	do {
6551 		/*
6552 		 * First, call the blanket provide operation.
6553 		 */
6554 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
6555 
6556 		/*
6557 		 * Now call the per-module provide operation.  We will grab
6558 		 * mod_lock to prevent the list from being modified.  Note
6559 		 * that this also prevents the mod_busy bits from changing.
6560 		 * (mod_busy can only be changed with mod_lock held.)
6561 		 */
6562 		mutex_enter(&mod_lock);
6563 
6564 		ctl = &modules;
6565 		do {
6566 			if (ctl->mod_busy || ctl->mod_mp == NULL)
6567 				continue;
6568 
6569 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
6570 
6571 		} while ((ctl = ctl->mod_next) != &modules);
6572 
6573 		mutex_exit(&mod_lock);
6574 	} while (all && (prv = prv->dtpv_next) != NULL);
6575 }
6576 
6577 /*
6578  * Iterate over each probe, and call the Framework-to-Provider API function
6579  * denoted by offs.
6580  */
6581 static void
6582 dtrace_probe_foreach(uintptr_t offs)
6583 {
6584 	dtrace_provider_t *prov;
6585 	void (*func)(void *, dtrace_id_t, void *);
6586 	dtrace_probe_t *probe;
6587 	dtrace_icookie_t cookie;
6588 	int i;
6589 
6590 	/*
6591 	 * We disable interrupts to walk through the probe array.  This is
6592 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
6593 	 * won't see stale data.
6594 	 */
6595 	cookie = dtrace_interrupt_disable();
6596 
6597 	for (i = 0; i < dtrace_nprobes; i++) {
6598 		if ((probe = dtrace_probes[i]) == NULL)
6599 			continue;
6600 
6601 		if (probe->dtpr_ecb == NULL) {
6602 			/*
6603 			 * This probe isn't enabled -- don't call the function.
6604 			 */
6605 			continue;
6606 		}
6607 
6608 		prov = probe->dtpr_provider;
6609 		func = *((void(**)(void *, dtrace_id_t, void *))
6610 		    ((uintptr_t)&prov->dtpv_pops + offs));
6611 
6612 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
6613 	}
6614 
6615 	dtrace_interrupt_enable(cookie);
6616 }
6617 
6618 static int
6619 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
6620 {
6621 	dtrace_probekey_t pkey;
6622 	uint32_t priv;
6623 	uid_t uid;
6624 	zoneid_t zoneid;
6625 
6626 	ASSERT(MUTEX_HELD(&dtrace_lock));
6627 	dtrace_ecb_create_cache = NULL;
6628 
6629 	if (desc == NULL) {
6630 		/*
6631 		 * If we're passed a NULL description, we're being asked to
6632 		 * create an ECB with a NULL probe.
6633 		 */
6634 		(void) dtrace_ecb_create_enable(NULL, enab);
6635 		return (0);
6636 	}
6637 
6638 	dtrace_probekey(desc, &pkey);
6639 	dtrace_cred2priv(CRED(), &priv, &uid, &zoneid);
6640 
6641 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
6642 	    enab));
6643 }
6644 
6645 /*
6646  * DTrace Helper Provider Functions
6647  */
6648 static void
6649 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
6650 {
6651 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
6652 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
6653 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
6654 }
6655 
6656 static void
6657 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
6658     const dof_provider_t *dofprov, char *strtab)
6659 {
6660 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
6661 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
6662 	    dofprov->dofpv_provattr);
6663 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
6664 	    dofprov->dofpv_modattr);
6665 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
6666 	    dofprov->dofpv_funcattr);
6667 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
6668 	    dofprov->dofpv_nameattr);
6669 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
6670 	    dofprov->dofpv_argsattr);
6671 }
6672 
6673 static void
6674 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
6675 {
6676 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6677 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6678 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
6679 	dof_provider_t *provider;
6680 	dof_probe_t *probe;
6681 	uint32_t *off, *enoff;
6682 	uint8_t *arg;
6683 	char *strtab;
6684 	uint_t i, nprobes;
6685 	dtrace_helper_provdesc_t dhpv;
6686 	dtrace_helper_probedesc_t dhpb;
6687 	dtrace_meta_t *meta = dtrace_meta_pid;
6688 	dtrace_mops_t *mops = &meta->dtm_mops;
6689 	void *parg;
6690 
6691 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
6692 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6693 	    provider->dofpv_strtab * dof->dofh_secsize);
6694 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6695 	    provider->dofpv_probes * dof->dofh_secsize);
6696 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6697 	    provider->dofpv_prargs * dof->dofh_secsize);
6698 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6699 	    provider->dofpv_proffs * dof->dofh_secsize);
6700 
6701 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
6702 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
6703 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
6704 	enoff = NULL;
6705 
6706 	/*
6707 	 * See dtrace_helper_provider_validate().
6708 	 */
6709 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
6710 	    provider->dofpv_prenoffs != 0) {
6711 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6712 		    provider->dofpv_prenoffs * dof->dofh_secsize);
6713 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
6714 	}
6715 
6716 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
6717 
6718 	/*
6719 	 * Create the provider.
6720 	 */
6721 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
6722 
6723 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
6724 		return;
6725 
6726 	meta->dtm_count++;
6727 
6728 	/*
6729 	 * Create the probes.
6730 	 */
6731 	for (i = 0; i < nprobes; i++) {
6732 		probe = (dof_probe_t *)(uintptr_t)(daddr +
6733 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
6734 
6735 		dhpb.dthpb_mod = dhp->dofhp_mod;
6736 		dhpb.dthpb_func = strtab + probe->dofpr_func;
6737 		dhpb.dthpb_name = strtab + probe->dofpr_name;
6738 		dhpb.dthpb_base = probe->dofpr_addr;
6739 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
6740 		dhpb.dthpb_noffs = probe->dofpr_noffs;
6741 		if (enoff != NULL) {
6742 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
6743 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
6744 		} else {
6745 			dhpb.dthpb_enoffs = NULL;
6746 			dhpb.dthpb_nenoffs = 0;
6747 		}
6748 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
6749 		dhpb.dthpb_nargc = probe->dofpr_nargc;
6750 		dhpb.dthpb_xargc = probe->dofpr_xargc;
6751 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
6752 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
6753 
6754 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
6755 	}
6756 }
6757 
6758 static void
6759 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
6760 {
6761 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6762 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6763 	int i;
6764 
6765 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
6766 
6767 	for (i = 0; i < dof->dofh_secnum; i++) {
6768 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
6769 		    dof->dofh_secoff + i * dof->dofh_secsize);
6770 
6771 		if (sec->dofs_type != DOF_SECT_PROVIDER)
6772 			continue;
6773 
6774 		dtrace_helper_provide_one(dhp, sec, pid);
6775 	}
6776 
6777 	/*
6778 	 * We may have just created probes, so we must now rematch against
6779 	 * any retained enablings.  Note that this call will acquire both
6780 	 * cpu_lock and dtrace_lock; the fact that we are holding
6781 	 * dtrace_meta_lock now is what defines the ordering with respect to
6782 	 * these three locks.
6783 	 */
6784 	dtrace_enabling_matchall();
6785 }
6786 
6787 static void
6788 dtrace_helper_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
6789 {
6790 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6791 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6792 	dof_sec_t *str_sec;
6793 	dof_provider_t *provider;
6794 	char *strtab;
6795 	dtrace_helper_provdesc_t dhpv;
6796 	dtrace_meta_t *meta = dtrace_meta_pid;
6797 	dtrace_mops_t *mops = &meta->dtm_mops;
6798 
6799 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
6800 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6801 	    provider->dofpv_strtab * dof->dofh_secsize);
6802 
6803 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
6804 
6805 	/*
6806 	 * Create the provider.
6807 	 */
6808 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
6809 
6810 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
6811 
6812 	meta->dtm_count--;
6813 }
6814 
6815 static void
6816 dtrace_helper_remove(dof_helper_t *dhp, pid_t pid)
6817 {
6818 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6819 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6820 	int i;
6821 
6822 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
6823 
6824 	for (i = 0; i < dof->dofh_secnum; i++) {
6825 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
6826 		    dof->dofh_secoff + i * dof->dofh_secsize);
6827 
6828 		if (sec->dofs_type != DOF_SECT_PROVIDER)
6829 			continue;
6830 
6831 		dtrace_helper_remove_one(dhp, sec, pid);
6832 	}
6833 }
6834 
6835 /*
6836  * DTrace Meta Provider-to-Framework API Functions
6837  *
6838  * These functions implement the Meta Provider-to-Framework API, as described
6839  * in <sys/dtrace.h>.
6840  */
6841 int
6842 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
6843     dtrace_meta_provider_id_t *idp)
6844 {
6845 	dtrace_meta_t *meta;
6846 	dtrace_helpers_t *help, *next;
6847 	int i;
6848 
6849 	*idp = DTRACE_METAPROVNONE;
6850 
6851 	/*
6852 	 * We strictly don't need the name, but we hold onto it for
6853 	 * debuggability. All hail error queues!
6854 	 */
6855 	if (name == NULL) {
6856 		cmn_err(CE_WARN, "failed to register meta-provider: "
6857 		    "invalid name");
6858 		return (EINVAL);
6859 	}
6860 
6861 	if (mops == NULL ||
6862 	    mops->dtms_create_probe == NULL ||
6863 	    mops->dtms_provide_pid == NULL ||
6864 	    mops->dtms_remove_pid == NULL) {
6865 		cmn_err(CE_WARN, "failed to register meta-register %s: "
6866 		    "invalid ops", name);
6867 		return (EINVAL);
6868 	}
6869 
6870 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
6871 	meta->dtm_mops = *mops;
6872 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
6873 	(void) strcpy(meta->dtm_name, name);
6874 	meta->dtm_arg = arg;
6875 
6876 	mutex_enter(&dtrace_meta_lock);
6877 	mutex_enter(&dtrace_lock);
6878 
6879 	if (dtrace_meta_pid != NULL) {
6880 		mutex_exit(&dtrace_lock);
6881 		mutex_exit(&dtrace_meta_lock);
6882 		cmn_err(CE_WARN, "failed to register meta-register %s: "
6883 		    "user-land meta-provider exists", name);
6884 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
6885 		kmem_free(meta, sizeof (dtrace_meta_t));
6886 		return (EINVAL);
6887 	}
6888 
6889 	dtrace_meta_pid = meta;
6890 	*idp = (dtrace_meta_provider_id_t)meta;
6891 
6892 	/*
6893 	 * If there are providers and probes ready to go, pass them
6894 	 * off to the new meta provider now.
6895 	 */
6896 
6897 	help = dtrace_deferred_pid;
6898 	dtrace_deferred_pid = NULL;
6899 
6900 	mutex_exit(&dtrace_lock);
6901 
6902 	while (help != NULL) {
6903 		for (i = 0; i < help->dthps_nprovs; i++) {
6904 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
6905 			    help->dthps_pid);
6906 		}
6907 
6908 		next = help->dthps_next;
6909 		help->dthps_next = NULL;
6910 		help->dthps_prev = NULL;
6911 		help->dthps_deferred = 0;
6912 		help = next;
6913 	}
6914 
6915 	mutex_exit(&dtrace_meta_lock);
6916 
6917 	return (0);
6918 }
6919 
6920 int
6921 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
6922 {
6923 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
6924 
6925 	mutex_enter(&dtrace_meta_lock);
6926 	mutex_enter(&dtrace_lock);
6927 
6928 	if (old == dtrace_meta_pid) {
6929 		pp = &dtrace_meta_pid;
6930 	} else {
6931 		panic("attempt to unregister non-existent "
6932 		    "dtrace meta-provider %p\n", (void *)old);
6933 	}
6934 
6935 	if (old->dtm_count != 0) {
6936 		mutex_exit(&dtrace_lock);
6937 		mutex_exit(&dtrace_meta_lock);
6938 		return (EBUSY);
6939 	}
6940 
6941 	*pp = NULL;
6942 
6943 	mutex_exit(&dtrace_lock);
6944 	mutex_exit(&dtrace_meta_lock);
6945 
6946 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
6947 	kmem_free(old, sizeof (dtrace_meta_t));
6948 
6949 	return (0);
6950 }
6951 
6952 
6953 /*
6954  * DTrace DIF Object Functions
6955  */
6956 static int
6957 dtrace_difo_err(uint_t pc, const char *format, ...)
6958 {
6959 	if (dtrace_err_verbose) {
6960 		va_list alist;
6961 
6962 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
6963 		va_start(alist, format);
6964 		(void) vuprintf(format, alist);
6965 		va_end(alist);
6966 	}
6967 
6968 #ifdef DTRACE_ERRDEBUG
6969 	dtrace_errdebug(format);
6970 #endif
6971 	return (1);
6972 }
6973 
6974 /*
6975  * Validate a DTrace DIF object by checking the IR instructions.  The following
6976  * rules are currently enforced by dtrace_difo_validate():
6977  *
6978  * 1. Each instruction must have a valid opcode
6979  * 2. Each register, string, variable, or subroutine reference must be valid
6980  * 3. No instruction can modify register %r0 (must be zero)
6981  * 4. All instruction reserved bits must be set to zero
6982  * 5. The last instruction must be a "ret" instruction
6983  * 6. All branch targets must reference a valid instruction _after_ the branch
6984  */
6985 static int
6986 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
6987     cred_t *cr)
6988 {
6989 	int err = 0, i;
6990 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
6991 	int kcheck;
6992 	uint_t pc;
6993 
6994 	kcheck = cr == NULL ||
6995 	    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE) == 0;
6996 
6997 	dp->dtdo_destructive = 0;
6998 
6999 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
7000 		dif_instr_t instr = dp->dtdo_buf[pc];
7001 
7002 		uint_t r1 = DIF_INSTR_R1(instr);
7003 		uint_t r2 = DIF_INSTR_R2(instr);
7004 		uint_t rd = DIF_INSTR_RD(instr);
7005 		uint_t rs = DIF_INSTR_RS(instr);
7006 		uint_t label = DIF_INSTR_LABEL(instr);
7007 		uint_t v = DIF_INSTR_VAR(instr);
7008 		uint_t subr = DIF_INSTR_SUBR(instr);
7009 		uint_t type = DIF_INSTR_TYPE(instr);
7010 		uint_t op = DIF_INSTR_OP(instr);
7011 
7012 		switch (op) {
7013 		case DIF_OP_OR:
7014 		case DIF_OP_XOR:
7015 		case DIF_OP_AND:
7016 		case DIF_OP_SLL:
7017 		case DIF_OP_SRL:
7018 		case DIF_OP_SRA:
7019 		case DIF_OP_SUB:
7020 		case DIF_OP_ADD:
7021 		case DIF_OP_MUL:
7022 		case DIF_OP_SDIV:
7023 		case DIF_OP_UDIV:
7024 		case DIF_OP_SREM:
7025 		case DIF_OP_UREM:
7026 		case DIF_OP_COPYS:
7027 			if (r1 >= nregs)
7028 				err += efunc(pc, "invalid register %u\n", r1);
7029 			if (r2 >= nregs)
7030 				err += efunc(pc, "invalid register %u\n", r2);
7031 			if (rd >= nregs)
7032 				err += efunc(pc, "invalid register %u\n", rd);
7033 			if (rd == 0)
7034 				err += efunc(pc, "cannot write to %r0\n");
7035 			break;
7036 		case DIF_OP_NOT:
7037 		case DIF_OP_MOV:
7038 		case DIF_OP_ALLOCS:
7039 			if (r1 >= nregs)
7040 				err += efunc(pc, "invalid register %u\n", r1);
7041 			if (r2 != 0)
7042 				err += efunc(pc, "non-zero reserved bits\n");
7043 			if (rd >= nregs)
7044 				err += efunc(pc, "invalid register %u\n", rd);
7045 			if (rd == 0)
7046 				err += efunc(pc, "cannot write to %r0\n");
7047 			break;
7048 		case DIF_OP_LDSB:
7049 		case DIF_OP_LDSH:
7050 		case DIF_OP_LDSW:
7051 		case DIF_OP_LDUB:
7052 		case DIF_OP_LDUH:
7053 		case DIF_OP_LDUW:
7054 		case DIF_OP_LDX:
7055 			if (r1 >= nregs)
7056 				err += efunc(pc, "invalid register %u\n", r1);
7057 			if (r2 != 0)
7058 				err += efunc(pc, "non-zero reserved bits\n");
7059 			if (rd >= nregs)
7060 				err += efunc(pc, "invalid register %u\n", rd);
7061 			if (rd == 0)
7062 				err += efunc(pc, "cannot write to %r0\n");
7063 			if (kcheck)
7064 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
7065 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
7066 			break;
7067 		case DIF_OP_RLDSB:
7068 		case DIF_OP_RLDSH:
7069 		case DIF_OP_RLDSW:
7070 		case DIF_OP_RLDUB:
7071 		case DIF_OP_RLDUH:
7072 		case DIF_OP_RLDUW:
7073 		case DIF_OP_RLDX:
7074 			if (r1 >= nregs)
7075 				err += efunc(pc, "invalid register %u\n", r1);
7076 			if (r2 != 0)
7077 				err += efunc(pc, "non-zero reserved bits\n");
7078 			if (rd >= nregs)
7079 				err += efunc(pc, "invalid register %u\n", rd);
7080 			if (rd == 0)
7081 				err += efunc(pc, "cannot write to %r0\n");
7082 			break;
7083 		case DIF_OP_ULDSB:
7084 		case DIF_OP_ULDSH:
7085 		case DIF_OP_ULDSW:
7086 		case DIF_OP_ULDUB:
7087 		case DIF_OP_ULDUH:
7088 		case DIF_OP_ULDUW:
7089 		case DIF_OP_ULDX:
7090 			if (r1 >= nregs)
7091 				err += efunc(pc, "invalid register %u\n", r1);
7092 			if (r2 != 0)
7093 				err += efunc(pc, "non-zero reserved bits\n");
7094 			if (rd >= nregs)
7095 				err += efunc(pc, "invalid register %u\n", rd);
7096 			if (rd == 0)
7097 				err += efunc(pc, "cannot write to %r0\n");
7098 			break;
7099 		case DIF_OP_STB:
7100 		case DIF_OP_STH:
7101 		case DIF_OP_STW:
7102 		case DIF_OP_STX:
7103 			if (r1 >= nregs)
7104 				err += efunc(pc, "invalid register %u\n", r1);
7105 			if (r2 != 0)
7106 				err += efunc(pc, "non-zero reserved bits\n");
7107 			if (rd >= nregs)
7108 				err += efunc(pc, "invalid register %u\n", rd);
7109 			if (rd == 0)
7110 				err += efunc(pc, "cannot write to 0 address\n");
7111 			break;
7112 		case DIF_OP_CMP:
7113 		case DIF_OP_SCMP:
7114 			if (r1 >= nregs)
7115 				err += efunc(pc, "invalid register %u\n", r1);
7116 			if (r2 >= nregs)
7117 				err += efunc(pc, "invalid register %u\n", r2);
7118 			if (rd != 0)
7119 				err += efunc(pc, "non-zero reserved bits\n");
7120 			break;
7121 		case DIF_OP_TST:
7122 			if (r1 >= nregs)
7123 				err += efunc(pc, "invalid register %u\n", r1);
7124 			if (r2 != 0 || rd != 0)
7125 				err += efunc(pc, "non-zero reserved bits\n");
7126 			break;
7127 		case DIF_OP_BA:
7128 		case DIF_OP_BE:
7129 		case DIF_OP_BNE:
7130 		case DIF_OP_BG:
7131 		case DIF_OP_BGU:
7132 		case DIF_OP_BGE:
7133 		case DIF_OP_BGEU:
7134 		case DIF_OP_BL:
7135 		case DIF_OP_BLU:
7136 		case DIF_OP_BLE:
7137 		case DIF_OP_BLEU:
7138 			if (label >= dp->dtdo_len) {
7139 				err += efunc(pc, "invalid branch target %u\n",
7140 				    label);
7141 			}
7142 			if (label <= pc) {
7143 				err += efunc(pc, "backward branch to %u\n",
7144 				    label);
7145 			}
7146 			break;
7147 		case DIF_OP_RET:
7148 			if (r1 != 0 || r2 != 0)
7149 				err += efunc(pc, "non-zero reserved bits\n");
7150 			if (rd >= nregs)
7151 				err += efunc(pc, "invalid register %u\n", rd);
7152 			break;
7153 		case DIF_OP_NOP:
7154 		case DIF_OP_POPTS:
7155 		case DIF_OP_FLUSHTS:
7156 			if (r1 != 0 || r2 != 0 || rd != 0)
7157 				err += efunc(pc, "non-zero reserved bits\n");
7158 			break;
7159 		case DIF_OP_SETX:
7160 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
7161 				err += efunc(pc, "invalid integer ref %u\n",
7162 				    DIF_INSTR_INTEGER(instr));
7163 			}
7164 			if (rd >= nregs)
7165 				err += efunc(pc, "invalid register %u\n", rd);
7166 			if (rd == 0)
7167 				err += efunc(pc, "cannot write to %r0\n");
7168 			break;
7169 		case DIF_OP_SETS:
7170 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
7171 				err += efunc(pc, "invalid string ref %u\n",
7172 				    DIF_INSTR_STRING(instr));
7173 			}
7174 			if (rd >= nregs)
7175 				err += efunc(pc, "invalid register %u\n", rd);
7176 			if (rd == 0)
7177 				err += efunc(pc, "cannot write to %r0\n");
7178 			break;
7179 		case DIF_OP_LDGA:
7180 		case DIF_OP_LDTA:
7181 			if (r1 > DIF_VAR_ARRAY_MAX)
7182 				err += efunc(pc, "invalid array %u\n", r1);
7183 			if (r2 >= nregs)
7184 				err += efunc(pc, "invalid register %u\n", r2);
7185 			if (rd >= nregs)
7186 				err += efunc(pc, "invalid register %u\n", rd);
7187 			if (rd == 0)
7188 				err += efunc(pc, "cannot write to %r0\n");
7189 			break;
7190 		case DIF_OP_LDGS:
7191 		case DIF_OP_LDTS:
7192 		case DIF_OP_LDLS:
7193 		case DIF_OP_LDGAA:
7194 		case DIF_OP_LDTAA:
7195 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
7196 				err += efunc(pc, "invalid variable %u\n", v);
7197 			if (rd >= nregs)
7198 				err += efunc(pc, "invalid register %u\n", rd);
7199 			if (rd == 0)
7200 				err += efunc(pc, "cannot write to %r0\n");
7201 			break;
7202 		case DIF_OP_STGS:
7203 		case DIF_OP_STTS:
7204 		case DIF_OP_STLS:
7205 		case DIF_OP_STGAA:
7206 		case DIF_OP_STTAA:
7207 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
7208 				err += efunc(pc, "invalid variable %u\n", v);
7209 			if (rs >= nregs)
7210 				err += efunc(pc, "invalid register %u\n", rd);
7211 			break;
7212 		case DIF_OP_CALL:
7213 			if (subr > DIF_SUBR_MAX)
7214 				err += efunc(pc, "invalid subr %u\n", subr);
7215 			if (rd >= nregs)
7216 				err += efunc(pc, "invalid register %u\n", rd);
7217 			if (rd == 0)
7218 				err += efunc(pc, "cannot write to %r0\n");
7219 
7220 			if (subr == DIF_SUBR_COPYOUT ||
7221 			    subr == DIF_SUBR_COPYOUTSTR) {
7222 				dp->dtdo_destructive = 1;
7223 			}
7224 			break;
7225 		case DIF_OP_PUSHTR:
7226 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
7227 				err += efunc(pc, "invalid ref type %u\n", type);
7228 			if (r2 >= nregs)
7229 				err += efunc(pc, "invalid register %u\n", r2);
7230 			if (rs >= nregs)
7231 				err += efunc(pc, "invalid register %u\n", rs);
7232 			break;
7233 		case DIF_OP_PUSHTV:
7234 			if (type != DIF_TYPE_CTF)
7235 				err += efunc(pc, "invalid val type %u\n", type);
7236 			if (r2 >= nregs)
7237 				err += efunc(pc, "invalid register %u\n", r2);
7238 			if (rs >= nregs)
7239 				err += efunc(pc, "invalid register %u\n", rs);
7240 			break;
7241 		default:
7242 			err += efunc(pc, "invalid opcode %u\n",
7243 			    DIF_INSTR_OP(instr));
7244 		}
7245 	}
7246 
7247 	if (dp->dtdo_len != 0 &&
7248 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
7249 		err += efunc(dp->dtdo_len - 1,
7250 		    "expected 'ret' as last DIF instruction\n");
7251 	}
7252 
7253 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
7254 		/*
7255 		 * If we're not returning by reference, the size must be either
7256 		 * 0 or the size of one of the base types.
7257 		 */
7258 		switch (dp->dtdo_rtype.dtdt_size) {
7259 		case 0:
7260 		case sizeof (uint8_t):
7261 		case sizeof (uint16_t):
7262 		case sizeof (uint32_t):
7263 		case sizeof (uint64_t):
7264 			break;
7265 
7266 		default:
7267 			err += efunc(dp->dtdo_len - 1, "bad return size");
7268 		}
7269 	}
7270 
7271 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
7272 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
7273 		dtrace_diftype_t *vt, *et;
7274 		uint_t id, ndx;
7275 
7276 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
7277 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
7278 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
7279 			err += efunc(i, "unrecognized variable scope %d\n",
7280 			    v->dtdv_scope);
7281 			break;
7282 		}
7283 
7284 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
7285 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
7286 			err += efunc(i, "unrecognized variable type %d\n",
7287 			    v->dtdv_kind);
7288 			break;
7289 		}
7290 
7291 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
7292 			err += efunc(i, "%d exceeds variable id limit\n", id);
7293 			break;
7294 		}
7295 
7296 		if (id < DIF_VAR_OTHER_UBASE)
7297 			continue;
7298 
7299 		/*
7300 		 * For user-defined variables, we need to check that this
7301 		 * definition is identical to any previous definition that we
7302 		 * encountered.
7303 		 */
7304 		ndx = id - DIF_VAR_OTHER_UBASE;
7305 
7306 		switch (v->dtdv_scope) {
7307 		case DIFV_SCOPE_GLOBAL:
7308 			if (ndx < vstate->dtvs_nglobals) {
7309 				dtrace_statvar_t *svar;
7310 
7311 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
7312 					existing = &svar->dtsv_var;
7313 			}
7314 
7315 			break;
7316 
7317 		case DIFV_SCOPE_THREAD:
7318 			if (ndx < vstate->dtvs_ntlocals)
7319 				existing = &vstate->dtvs_tlocals[ndx];
7320 			break;
7321 
7322 		case DIFV_SCOPE_LOCAL:
7323 			if (ndx < vstate->dtvs_nlocals) {
7324 				dtrace_statvar_t *svar;
7325 
7326 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
7327 					existing = &svar->dtsv_var;
7328 			}
7329 
7330 			break;
7331 		}
7332 
7333 		vt = &v->dtdv_type;
7334 
7335 		if (vt->dtdt_flags & DIF_TF_BYREF) {
7336 			if (vt->dtdt_size == 0) {
7337 				err += efunc(i, "zero-sized variable\n");
7338 				break;
7339 			}
7340 
7341 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
7342 			    vt->dtdt_size > dtrace_global_maxsize) {
7343 				err += efunc(i, "oversized by-ref global\n");
7344 				break;
7345 			}
7346 		}
7347 
7348 		if (existing == NULL || existing->dtdv_id == 0)
7349 			continue;
7350 
7351 		ASSERT(existing->dtdv_id == v->dtdv_id);
7352 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
7353 
7354 		if (existing->dtdv_kind != v->dtdv_kind)
7355 			err += efunc(i, "%d changed variable kind\n", id);
7356 
7357 		et = &existing->dtdv_type;
7358 
7359 		if (vt->dtdt_flags != et->dtdt_flags) {
7360 			err += efunc(i, "%d changed variable type flags\n", id);
7361 			break;
7362 		}
7363 
7364 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
7365 			err += efunc(i, "%d changed variable type size\n", id);
7366 			break;
7367 		}
7368 	}
7369 
7370 	return (err);
7371 }
7372 
7373 /*
7374  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
7375  * are much more constrained than normal DIFOs.  Specifically, they may
7376  * not:
7377  *
7378  * 1. Make calls to subroutines other than copyin(), copyinstr() or
7379  *    miscellaneous string routines
7380  * 2. Access DTrace variables other than the args[] array, and the
7381  *    curthread, pid, tid and execname variables.
7382  * 3. Have thread-local variables.
7383  * 4. Have dynamic variables.
7384  */
7385 static int
7386 dtrace_difo_validate_helper(dtrace_difo_t *dp)
7387 {
7388 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
7389 	int err = 0;
7390 	uint_t pc;
7391 
7392 	for (pc = 0; pc < dp->dtdo_len; pc++) {
7393 		dif_instr_t instr = dp->dtdo_buf[pc];
7394 
7395 		uint_t v = DIF_INSTR_VAR(instr);
7396 		uint_t subr = DIF_INSTR_SUBR(instr);
7397 		uint_t op = DIF_INSTR_OP(instr);
7398 
7399 		switch (op) {
7400 		case DIF_OP_OR:
7401 		case DIF_OP_XOR:
7402 		case DIF_OP_AND:
7403 		case DIF_OP_SLL:
7404 		case DIF_OP_SRL:
7405 		case DIF_OP_SRA:
7406 		case DIF_OP_SUB:
7407 		case DIF_OP_ADD:
7408 		case DIF_OP_MUL:
7409 		case DIF_OP_SDIV:
7410 		case DIF_OP_UDIV:
7411 		case DIF_OP_SREM:
7412 		case DIF_OP_UREM:
7413 		case DIF_OP_COPYS:
7414 		case DIF_OP_NOT:
7415 		case DIF_OP_MOV:
7416 		case DIF_OP_RLDSB:
7417 		case DIF_OP_RLDSH:
7418 		case DIF_OP_RLDSW:
7419 		case DIF_OP_RLDUB:
7420 		case DIF_OP_RLDUH:
7421 		case DIF_OP_RLDUW:
7422 		case DIF_OP_RLDX:
7423 		case DIF_OP_ULDSB:
7424 		case DIF_OP_ULDSH:
7425 		case DIF_OP_ULDSW:
7426 		case DIF_OP_ULDUB:
7427 		case DIF_OP_ULDUH:
7428 		case DIF_OP_ULDUW:
7429 		case DIF_OP_ULDX:
7430 		case DIF_OP_STB:
7431 		case DIF_OP_STH:
7432 		case DIF_OP_STW:
7433 		case DIF_OP_STX:
7434 		case DIF_OP_ALLOCS:
7435 		case DIF_OP_CMP:
7436 		case DIF_OP_SCMP:
7437 		case DIF_OP_TST:
7438 		case DIF_OP_BA:
7439 		case DIF_OP_BE:
7440 		case DIF_OP_BNE:
7441 		case DIF_OP_BG:
7442 		case DIF_OP_BGU:
7443 		case DIF_OP_BGE:
7444 		case DIF_OP_BGEU:
7445 		case DIF_OP_BL:
7446 		case DIF_OP_BLU:
7447 		case DIF_OP_BLE:
7448 		case DIF_OP_BLEU:
7449 		case DIF_OP_RET:
7450 		case DIF_OP_NOP:
7451 		case DIF_OP_POPTS:
7452 		case DIF_OP_FLUSHTS:
7453 		case DIF_OP_SETX:
7454 		case DIF_OP_SETS:
7455 		case DIF_OP_LDGA:
7456 		case DIF_OP_LDLS:
7457 		case DIF_OP_STGS:
7458 		case DIF_OP_STLS:
7459 		case DIF_OP_PUSHTR:
7460 		case DIF_OP_PUSHTV:
7461 			break;
7462 
7463 		case DIF_OP_LDGS:
7464 			if (v >= DIF_VAR_OTHER_UBASE)
7465 				break;
7466 
7467 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
7468 				break;
7469 
7470 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
7471 			    v == DIF_VAR_TID || v == DIF_VAR_EXECNAME ||
7472 			    v == DIF_VAR_ZONENAME)
7473 				break;
7474 
7475 			err += efunc(pc, "illegal variable %u\n", v);
7476 			break;
7477 
7478 		case DIF_OP_LDTA:
7479 		case DIF_OP_LDTS:
7480 		case DIF_OP_LDGAA:
7481 		case DIF_OP_LDTAA:
7482 			err += efunc(pc, "illegal dynamic variable load\n");
7483 			break;
7484 
7485 		case DIF_OP_STTS:
7486 		case DIF_OP_STGAA:
7487 		case DIF_OP_STTAA:
7488 			err += efunc(pc, "illegal dynamic variable store\n");
7489 			break;
7490 
7491 		case DIF_OP_CALL:
7492 			if (subr == DIF_SUBR_ALLOCA ||
7493 			    subr == DIF_SUBR_BCOPY ||
7494 			    subr == DIF_SUBR_COPYIN ||
7495 			    subr == DIF_SUBR_COPYINTO ||
7496 			    subr == DIF_SUBR_COPYINSTR ||
7497 			    subr == DIF_SUBR_INDEX ||
7498 			    subr == DIF_SUBR_LLTOSTR ||
7499 			    subr == DIF_SUBR_RINDEX ||
7500 			    subr == DIF_SUBR_STRCHR ||
7501 			    subr == DIF_SUBR_STRJOIN ||
7502 			    subr == DIF_SUBR_STRRCHR ||
7503 			    subr == DIF_SUBR_STRSTR)
7504 				break;
7505 
7506 			err += efunc(pc, "invalid subr %u\n", subr);
7507 			break;
7508 
7509 		default:
7510 			err += efunc(pc, "invalid opcode %u\n",
7511 			    DIF_INSTR_OP(instr));
7512 		}
7513 	}
7514 
7515 	return (err);
7516 }
7517 
7518 /*
7519  * Returns 1 if the expression in the DIF object can be cached on a per-thread
7520  * basis; 0 if not.
7521  */
7522 static int
7523 dtrace_difo_cacheable(dtrace_difo_t *dp)
7524 {
7525 	int i;
7526 
7527 	if (dp == NULL)
7528 		return (0);
7529 
7530 	for (i = 0; i < dp->dtdo_varlen; i++) {
7531 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7532 
7533 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
7534 			continue;
7535 
7536 		switch (v->dtdv_id) {
7537 		case DIF_VAR_CURTHREAD:
7538 		case DIF_VAR_PID:
7539 		case DIF_VAR_TID:
7540 		case DIF_VAR_EXECNAME:
7541 		case DIF_VAR_ZONENAME:
7542 			break;
7543 
7544 		default:
7545 			return (0);
7546 		}
7547 	}
7548 
7549 	/*
7550 	 * This DIF object may be cacheable.  Now we need to look for any
7551 	 * array loading instructions, any memory loading instructions, or
7552 	 * any stores to thread-local variables.
7553 	 */
7554 	for (i = 0; i < dp->dtdo_len; i++) {
7555 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
7556 
7557 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
7558 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
7559 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
7560 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
7561 			return (0);
7562 	}
7563 
7564 	return (1);
7565 }
7566 
7567 static void
7568 dtrace_difo_hold(dtrace_difo_t *dp)
7569 {
7570 	int i;
7571 
7572 	ASSERT(MUTEX_HELD(&dtrace_lock));
7573 
7574 	dp->dtdo_refcnt++;
7575 	ASSERT(dp->dtdo_refcnt != 0);
7576 
7577 	/*
7578 	 * We need to check this DIF object for references to the variable
7579 	 * DIF_VAR_VTIMESTAMP.
7580 	 */
7581 	for (i = 0; i < dp->dtdo_varlen; i++) {
7582 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7583 
7584 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
7585 			continue;
7586 
7587 		if (dtrace_vtime_references++ == 0)
7588 			dtrace_vtime_enable();
7589 	}
7590 }
7591 
7592 /*
7593  * This routine calculates the dynamic variable chunksize for a given DIF
7594  * object.  The calculation is not fool-proof, and can probably be tricked by
7595  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
7596  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
7597  * if a dynamic variable size exceeds the chunksize.
7598  */
7599 static void
7600 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7601 {
7602 	uint64_t sval;
7603 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
7604 	const dif_instr_t *text = dp->dtdo_buf;
7605 	uint_t pc, srd = 0;
7606 	uint_t ttop = 0;
7607 	size_t size, ksize;
7608 	uint_t id, i;
7609 
7610 	for (pc = 0; pc < dp->dtdo_len; pc++) {
7611 		dif_instr_t instr = text[pc];
7612 		uint_t op = DIF_INSTR_OP(instr);
7613 		uint_t rd = DIF_INSTR_RD(instr);
7614 		uint_t r1 = DIF_INSTR_R1(instr);
7615 		uint_t nkeys = 0;
7616 		uchar_t scope;
7617 
7618 		dtrace_key_t *key = tupregs;
7619 
7620 		switch (op) {
7621 		case DIF_OP_SETX:
7622 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
7623 			srd = rd;
7624 			continue;
7625 
7626 		case DIF_OP_STTS:
7627 			key = &tupregs[DIF_DTR_NREGS];
7628 			key[0].dttk_size = 0;
7629 			key[1].dttk_size = 0;
7630 			nkeys = 2;
7631 			scope = DIFV_SCOPE_THREAD;
7632 			break;
7633 
7634 		case DIF_OP_STGAA:
7635 		case DIF_OP_STTAA:
7636 			nkeys = ttop;
7637 
7638 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
7639 				key[nkeys++].dttk_size = 0;
7640 
7641 			key[nkeys++].dttk_size = 0;
7642 
7643 			if (op == DIF_OP_STTAA) {
7644 				scope = DIFV_SCOPE_THREAD;
7645 			} else {
7646 				scope = DIFV_SCOPE_GLOBAL;
7647 			}
7648 
7649 			break;
7650 
7651 		case DIF_OP_PUSHTR:
7652 			if (ttop == DIF_DTR_NREGS)
7653 				return;
7654 
7655 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
7656 				/*
7657 				 * If the register for the size of the "pushtr"
7658 				 * is %r0 (or the value is 0) and the type is
7659 				 * a string, we'll use the system-wide default
7660 				 * string size.
7661 				 */
7662 				tupregs[ttop++].dttk_size =
7663 				    dtrace_strsize_default;
7664 			} else {
7665 				if (srd == 0)
7666 					return;
7667 
7668 				tupregs[ttop++].dttk_size = sval;
7669 			}
7670 
7671 			break;
7672 
7673 		case DIF_OP_PUSHTV:
7674 			if (ttop == DIF_DTR_NREGS)
7675 				return;
7676 
7677 			tupregs[ttop++].dttk_size = 0;
7678 			break;
7679 
7680 		case DIF_OP_FLUSHTS:
7681 			ttop = 0;
7682 			break;
7683 
7684 		case DIF_OP_POPTS:
7685 			if (ttop != 0)
7686 				ttop--;
7687 			break;
7688 		}
7689 
7690 		sval = 0;
7691 		srd = 0;
7692 
7693 		if (nkeys == 0)
7694 			continue;
7695 
7696 		/*
7697 		 * We have a dynamic variable allocation; calculate its size.
7698 		 */
7699 		for (ksize = 0, i = 0; i < nkeys; i++)
7700 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
7701 
7702 		size = sizeof (dtrace_dynvar_t);
7703 		size += sizeof (dtrace_key_t) * (nkeys - 1);
7704 		size += ksize;
7705 
7706 		/*
7707 		 * Now we need to determine the size of the stored data.
7708 		 */
7709 		id = DIF_INSTR_VAR(instr);
7710 
7711 		for (i = 0; i < dp->dtdo_varlen; i++) {
7712 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
7713 
7714 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
7715 				size += v->dtdv_type.dtdt_size;
7716 				break;
7717 			}
7718 		}
7719 
7720 		if (i == dp->dtdo_varlen)
7721 			return;
7722 
7723 		/*
7724 		 * We have the size.  If this is larger than the chunk size
7725 		 * for our dynamic variable state, reset the chunk size.
7726 		 */
7727 		size = P2ROUNDUP(size, sizeof (uint64_t));
7728 
7729 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
7730 			vstate->dtvs_dynvars.dtds_chunksize = size;
7731 	}
7732 }
7733 
7734 static void
7735 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7736 {
7737 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
7738 	uint_t id;
7739 
7740 	ASSERT(MUTEX_HELD(&dtrace_lock));
7741 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
7742 
7743 	for (i = 0; i < dp->dtdo_varlen; i++) {
7744 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7745 		dtrace_statvar_t *svar, ***svarp;
7746 		size_t dsize = 0;
7747 		uint8_t scope = v->dtdv_scope;
7748 		int *np;
7749 
7750 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
7751 			continue;
7752 
7753 		id -= DIF_VAR_OTHER_UBASE;
7754 
7755 		switch (scope) {
7756 		case DIFV_SCOPE_THREAD:
7757 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
7758 				dtrace_difv_t *tlocals;
7759 
7760 				if ((ntlocals = (otlocals << 1)) == 0)
7761 					ntlocals = 1;
7762 
7763 				osz = otlocals * sizeof (dtrace_difv_t);
7764 				nsz = ntlocals * sizeof (dtrace_difv_t);
7765 
7766 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
7767 
7768 				if (osz != 0) {
7769 					bcopy(vstate->dtvs_tlocals,
7770 					    tlocals, osz);
7771 					kmem_free(vstate->dtvs_tlocals, osz);
7772 				}
7773 
7774 				vstate->dtvs_tlocals = tlocals;
7775 				vstate->dtvs_ntlocals = ntlocals;
7776 			}
7777 
7778 			vstate->dtvs_tlocals[id] = *v;
7779 			continue;
7780 
7781 		case DIFV_SCOPE_LOCAL:
7782 			np = &vstate->dtvs_nlocals;
7783 			svarp = &vstate->dtvs_locals;
7784 
7785 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
7786 				dsize = NCPU * (v->dtdv_type.dtdt_size +
7787 				    sizeof (uint64_t));
7788 			else
7789 				dsize = NCPU * sizeof (uint64_t);
7790 
7791 			break;
7792 
7793 		case DIFV_SCOPE_GLOBAL:
7794 			np = &vstate->dtvs_nglobals;
7795 			svarp = &vstate->dtvs_globals;
7796 
7797 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
7798 				dsize = v->dtdv_type.dtdt_size +
7799 				    sizeof (uint64_t);
7800 
7801 			break;
7802 
7803 		default:
7804 			ASSERT(0);
7805 		}
7806 
7807 		while (id >= (oldsvars = *np)) {
7808 			dtrace_statvar_t **statics;
7809 			int newsvars, oldsize, newsize;
7810 
7811 			if ((newsvars = (oldsvars << 1)) == 0)
7812 				newsvars = 1;
7813 
7814 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
7815 			newsize = newsvars * sizeof (dtrace_statvar_t *);
7816 
7817 			statics = kmem_zalloc(newsize, KM_SLEEP);
7818 
7819 			if (oldsize != 0) {
7820 				bcopy(*svarp, statics, oldsize);
7821 				kmem_free(*svarp, oldsize);
7822 			}
7823 
7824 			*svarp = statics;
7825 			*np = newsvars;
7826 		}
7827 
7828 		if ((svar = (*svarp)[id]) == NULL) {
7829 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
7830 			svar->dtsv_var = *v;
7831 
7832 			if ((svar->dtsv_size = dsize) != 0) {
7833 				svar->dtsv_data = (uint64_t)(uintptr_t)
7834 				    kmem_zalloc(dsize, KM_SLEEP);
7835 			}
7836 
7837 			(*svarp)[id] = svar;
7838 		}
7839 
7840 		svar->dtsv_refcnt++;
7841 	}
7842 
7843 	dtrace_difo_chunksize(dp, vstate);
7844 	dtrace_difo_hold(dp);
7845 }
7846 
7847 static dtrace_difo_t *
7848 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7849 {
7850 	dtrace_difo_t *new;
7851 	size_t sz;
7852 
7853 	ASSERT(dp->dtdo_buf != NULL);
7854 	ASSERT(dp->dtdo_refcnt != 0);
7855 
7856 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
7857 
7858 	ASSERT(dp->dtdo_buf != NULL);
7859 	sz = dp->dtdo_len * sizeof (dif_instr_t);
7860 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
7861 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
7862 	new->dtdo_len = dp->dtdo_len;
7863 
7864 	if (dp->dtdo_strtab != NULL) {
7865 		ASSERT(dp->dtdo_strlen != 0);
7866 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
7867 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
7868 		new->dtdo_strlen = dp->dtdo_strlen;
7869 	}
7870 
7871 	if (dp->dtdo_inttab != NULL) {
7872 		ASSERT(dp->dtdo_intlen != 0);
7873 		sz = dp->dtdo_intlen * sizeof (uint64_t);
7874 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
7875 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
7876 		new->dtdo_intlen = dp->dtdo_intlen;
7877 	}
7878 
7879 	if (dp->dtdo_vartab != NULL) {
7880 		ASSERT(dp->dtdo_varlen != 0);
7881 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
7882 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
7883 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
7884 		new->dtdo_varlen = dp->dtdo_varlen;
7885 	}
7886 
7887 	dtrace_difo_init(new, vstate);
7888 	return (new);
7889 }
7890 
7891 static void
7892 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7893 {
7894 	int i;
7895 
7896 	ASSERT(dp->dtdo_refcnt == 0);
7897 
7898 	for (i = 0; i < dp->dtdo_varlen; i++) {
7899 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7900 		dtrace_statvar_t *svar, **svarp;
7901 		uint_t id;
7902 		uint8_t scope = v->dtdv_scope;
7903 		int *np;
7904 
7905 		switch (scope) {
7906 		case DIFV_SCOPE_THREAD:
7907 			continue;
7908 
7909 		case DIFV_SCOPE_LOCAL:
7910 			np = &vstate->dtvs_nlocals;
7911 			svarp = vstate->dtvs_locals;
7912 			break;
7913 
7914 		case DIFV_SCOPE_GLOBAL:
7915 			np = &vstate->dtvs_nglobals;
7916 			svarp = vstate->dtvs_globals;
7917 			break;
7918 
7919 		default:
7920 			ASSERT(0);
7921 		}
7922 
7923 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
7924 			continue;
7925 
7926 		id -= DIF_VAR_OTHER_UBASE;
7927 		ASSERT(id < *np);
7928 
7929 		svar = svarp[id];
7930 		ASSERT(svar != NULL);
7931 		ASSERT(svar->dtsv_refcnt > 0);
7932 
7933 		if (--svar->dtsv_refcnt > 0)
7934 			continue;
7935 
7936 		if (svar->dtsv_size != 0) {
7937 			ASSERT(svar->dtsv_data != NULL);
7938 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
7939 			    svar->dtsv_size);
7940 		}
7941 
7942 		kmem_free(svar, sizeof (dtrace_statvar_t));
7943 		svarp[id] = NULL;
7944 	}
7945 
7946 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
7947 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
7948 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
7949 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
7950 
7951 	kmem_free(dp, sizeof (dtrace_difo_t));
7952 }
7953 
7954 static void
7955 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7956 {
7957 	int i;
7958 
7959 	ASSERT(MUTEX_HELD(&dtrace_lock));
7960 	ASSERT(dp->dtdo_refcnt != 0);
7961 
7962 	for (i = 0; i < dp->dtdo_varlen; i++) {
7963 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7964 
7965 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
7966 			continue;
7967 
7968 		ASSERT(dtrace_vtime_references > 0);
7969 		if (--dtrace_vtime_references == 0)
7970 			dtrace_vtime_disable();
7971 	}
7972 
7973 	if (--dp->dtdo_refcnt == 0)
7974 		dtrace_difo_destroy(dp, vstate);
7975 }
7976 
7977 /*
7978  * DTrace Format Functions
7979  */
7980 static uint16_t
7981 dtrace_format_add(dtrace_state_t *state, char *str)
7982 {
7983 	char *fmt, **new;
7984 	uint16_t ndx, len = strlen(str) + 1;
7985 
7986 	fmt = kmem_zalloc(len, KM_SLEEP);
7987 	bcopy(str, fmt, len);
7988 
7989 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
7990 		if (state->dts_formats[ndx] == NULL) {
7991 			state->dts_formats[ndx] = fmt;
7992 			return (ndx + 1);
7993 		}
7994 	}
7995 
7996 	if (state->dts_nformats == USHRT_MAX) {
7997 		/*
7998 		 * This is only likely if a denial-of-service attack is being
7999 		 * attempted.  As such, it's okay to fail silently here.
8000 		 */
8001 		kmem_free(fmt, len);
8002 		return (0);
8003 	}
8004 
8005 	/*
8006 	 * For simplicity, we always resize the formats array to be exactly the
8007 	 * number of formats.
8008 	 */
8009 	ndx = state->dts_nformats++;
8010 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
8011 
8012 	if (state->dts_formats != NULL) {
8013 		ASSERT(ndx != 0);
8014 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
8015 		kmem_free(state->dts_formats, ndx * sizeof (char *));
8016 	}
8017 
8018 	state->dts_formats = new;
8019 	state->dts_formats[ndx] = fmt;
8020 
8021 	return (ndx + 1);
8022 }
8023 
8024 static void
8025 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
8026 {
8027 	char *fmt;
8028 
8029 	ASSERT(state->dts_formats != NULL);
8030 	ASSERT(format <= state->dts_nformats);
8031 	ASSERT(state->dts_formats[format - 1] != NULL);
8032 
8033 	fmt = state->dts_formats[format - 1];
8034 	kmem_free(fmt, strlen(fmt) + 1);
8035 	state->dts_formats[format - 1] = NULL;
8036 }
8037 
8038 static void
8039 dtrace_format_destroy(dtrace_state_t *state)
8040 {
8041 	int i;
8042 
8043 	if (state->dts_nformats == 0) {
8044 		ASSERT(state->dts_formats == NULL);
8045 		return;
8046 	}
8047 
8048 	ASSERT(state->dts_formats != NULL);
8049 
8050 	for (i = 0; i < state->dts_nformats; i++) {
8051 		char *fmt = state->dts_formats[i];
8052 
8053 		if (fmt == NULL)
8054 			continue;
8055 
8056 		kmem_free(fmt, strlen(fmt) + 1);
8057 	}
8058 
8059 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
8060 	state->dts_nformats = 0;
8061 	state->dts_formats = NULL;
8062 }
8063 
8064 /*
8065  * DTrace Predicate Functions
8066  */
8067 static dtrace_predicate_t *
8068 dtrace_predicate_create(dtrace_difo_t *dp)
8069 {
8070 	dtrace_predicate_t *pred;
8071 
8072 	ASSERT(MUTEX_HELD(&dtrace_lock));
8073 	ASSERT(dp->dtdo_refcnt != 0);
8074 
8075 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
8076 	pred->dtp_difo = dp;
8077 	pred->dtp_refcnt = 1;
8078 
8079 	if (!dtrace_difo_cacheable(dp))
8080 		return (pred);
8081 
8082 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
8083 		/*
8084 		 * This is only theoretically possible -- we have had 2^32
8085 		 * cacheable predicates on this machine.  We cannot allow any
8086 		 * more predicates to become cacheable:  as unlikely as it is,
8087 		 * there may be a thread caching a (now stale) predicate cache
8088 		 * ID. (N.B.: the temptation is being successfully resisted to
8089 		 * have this cmn_err() "Holy shit -- we executed this code!")
8090 		 */
8091 		return (pred);
8092 	}
8093 
8094 	pred->dtp_cacheid = dtrace_predcache_id++;
8095 
8096 	return (pred);
8097 }
8098 
8099 static void
8100 dtrace_predicate_hold(dtrace_predicate_t *pred)
8101 {
8102 	ASSERT(MUTEX_HELD(&dtrace_lock));
8103 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
8104 	ASSERT(pred->dtp_refcnt > 0);
8105 
8106 	pred->dtp_refcnt++;
8107 }
8108 
8109 static void
8110 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
8111 {
8112 	dtrace_difo_t *dp = pred->dtp_difo;
8113 
8114 	ASSERT(MUTEX_HELD(&dtrace_lock));
8115 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
8116 	ASSERT(pred->dtp_refcnt > 0);
8117 
8118 	if (--pred->dtp_refcnt == 0) {
8119 		dtrace_difo_release(pred->dtp_difo, vstate);
8120 		kmem_free(pred, sizeof (dtrace_predicate_t));
8121 	}
8122 }
8123 
8124 /*
8125  * DTrace Action Description Functions
8126  */
8127 static dtrace_actdesc_t *
8128 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
8129     uint64_t uarg, uint64_t arg)
8130 {
8131 	dtrace_actdesc_t *act;
8132 
8133 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
8134 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
8135 
8136 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
8137 	act->dtad_kind = kind;
8138 	act->dtad_ntuple = ntuple;
8139 	act->dtad_uarg = uarg;
8140 	act->dtad_arg = arg;
8141 	act->dtad_refcnt = 1;
8142 
8143 	return (act);
8144 }
8145 
8146 static void
8147 dtrace_actdesc_hold(dtrace_actdesc_t *act)
8148 {
8149 	ASSERT(act->dtad_refcnt >= 1);
8150 	act->dtad_refcnt++;
8151 }
8152 
8153 static void
8154 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
8155 {
8156 	dtrace_actkind_t kind = act->dtad_kind;
8157 	dtrace_difo_t *dp;
8158 
8159 	ASSERT(act->dtad_refcnt >= 1);
8160 
8161 	if (--act->dtad_refcnt != 0)
8162 		return;
8163 
8164 	if ((dp = act->dtad_difo) != NULL)
8165 		dtrace_difo_release(dp, vstate);
8166 
8167 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
8168 		char *str = (char *)(uintptr_t)act->dtad_arg;
8169 
8170 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
8171 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
8172 
8173 		if (str != NULL)
8174 			kmem_free(str, strlen(str) + 1);
8175 	}
8176 
8177 	kmem_free(act, sizeof (dtrace_actdesc_t));
8178 }
8179 
8180 /*
8181  * DTrace ECB Functions
8182  */
8183 static dtrace_ecb_t *
8184 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
8185 {
8186 	dtrace_ecb_t *ecb;
8187 	dtrace_epid_t epid;
8188 
8189 	ASSERT(MUTEX_HELD(&dtrace_lock));
8190 
8191 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
8192 	ecb->dte_predicate = NULL;
8193 	ecb->dte_probe = probe;
8194 
8195 	/*
8196 	 * The default size is the size of the default action: recording
8197 	 * the epid.
8198 	 */
8199 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
8200 	ecb->dte_alignment = sizeof (dtrace_epid_t);
8201 
8202 	epid = state->dts_epid++;
8203 
8204 	if (epid - 1 >= state->dts_necbs) {
8205 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
8206 		int necbs = state->dts_necbs << 1;
8207 
8208 		ASSERT(epid == state->dts_necbs + 1);
8209 
8210 		if (necbs == 0) {
8211 			ASSERT(oecbs == NULL);
8212 			necbs = 1;
8213 		}
8214 
8215 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
8216 
8217 		if (oecbs != NULL)
8218 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
8219 
8220 		dtrace_membar_producer();
8221 		state->dts_ecbs = ecbs;
8222 
8223 		if (oecbs != NULL) {
8224 			/*
8225 			 * If this state is active, we must dtrace_sync()
8226 			 * before we can free the old dts_ecbs array:  we're
8227 			 * coming in hot, and there may be active ring
8228 			 * buffer processing (which indexes into the dts_ecbs
8229 			 * array) on another CPU.
8230 			 */
8231 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
8232 				dtrace_sync();
8233 
8234 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
8235 		}
8236 
8237 		dtrace_membar_producer();
8238 		state->dts_necbs = necbs;
8239 	}
8240 
8241 	ecb->dte_state = state;
8242 
8243 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
8244 	dtrace_membar_producer();
8245 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
8246 
8247 	return (ecb);
8248 }
8249 
8250 static void
8251 dtrace_ecb_enable(dtrace_ecb_t *ecb)
8252 {
8253 	dtrace_probe_t *probe = ecb->dte_probe;
8254 
8255 	ASSERT(MUTEX_HELD(&cpu_lock));
8256 	ASSERT(MUTEX_HELD(&dtrace_lock));
8257 	ASSERT(ecb->dte_next == NULL);
8258 
8259 	if (probe == NULL) {
8260 		/*
8261 		 * This is the NULL probe -- there's nothing to do.
8262 		 */
8263 		return;
8264 	}
8265 
8266 	if (probe->dtpr_ecb == NULL) {
8267 		dtrace_provider_t *prov = probe->dtpr_provider;
8268 
8269 		/*
8270 		 * We're the first ECB on this probe.
8271 		 */
8272 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
8273 
8274 		if (ecb->dte_predicate != NULL)
8275 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
8276 
8277 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
8278 		    probe->dtpr_id, probe->dtpr_arg);
8279 	} else {
8280 		/*
8281 		 * This probe is already active.  Swing the last pointer to
8282 		 * point to the new ECB, and issue a dtrace_sync() to assure
8283 		 * that all CPUs have seen the change.
8284 		 */
8285 		ASSERT(probe->dtpr_ecb_last != NULL);
8286 		probe->dtpr_ecb_last->dte_next = ecb;
8287 		probe->dtpr_ecb_last = ecb;
8288 		probe->dtpr_predcache = 0;
8289 
8290 		dtrace_sync();
8291 	}
8292 }
8293 
8294 static void
8295 dtrace_ecb_resize(dtrace_ecb_t *ecb)
8296 {
8297 	uint32_t maxalign = sizeof (dtrace_epid_t);
8298 	uint32_t align = sizeof (uint8_t), offs, diff;
8299 	dtrace_action_t *act;
8300 	int wastuple = 0;
8301 	uint32_t aggbase = UINT32_MAX;
8302 	dtrace_state_t *state = ecb->dte_state;
8303 
8304 	/*
8305 	 * If we record anything, we always record the epid.  (And we always
8306 	 * record it first.)
8307 	 */
8308 	offs = sizeof (dtrace_epid_t);
8309 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
8310 
8311 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
8312 		dtrace_recdesc_t *rec = &act->dta_rec;
8313 
8314 		if ((align = rec->dtrd_alignment) > maxalign)
8315 			maxalign = align;
8316 
8317 		if (!wastuple && act->dta_intuple) {
8318 			/*
8319 			 * This is the first record in a tuple.  Align the
8320 			 * offset to be at offset 4 in an 8-byte aligned
8321 			 * block.
8322 			 */
8323 			diff = offs + sizeof (dtrace_aggid_t);
8324 
8325 			if (diff = (diff & (sizeof (uint64_t) - 1)))
8326 				offs += sizeof (uint64_t) - diff;
8327 
8328 			aggbase = offs - sizeof (dtrace_aggid_t);
8329 			ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
8330 		}
8331 
8332 		/*LINTED*/
8333 		if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
8334 			/*
8335 			 * The current offset is not properly aligned; align it.
8336 			 */
8337 			offs += align - diff;
8338 		}
8339 
8340 		rec->dtrd_offset = offs;
8341 
8342 		if (offs + rec->dtrd_size > ecb->dte_needed) {
8343 			ecb->dte_needed = offs + rec->dtrd_size;
8344 
8345 			if (ecb->dte_needed > state->dts_needed)
8346 				state->dts_needed = ecb->dte_needed;
8347 		}
8348 
8349 		if (DTRACEACT_ISAGG(act->dta_kind)) {
8350 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
8351 			dtrace_action_t *first = agg->dtag_first, *prev;
8352 
8353 			ASSERT(rec->dtrd_size != 0 && first != NULL);
8354 			ASSERT(wastuple);
8355 			ASSERT(aggbase != UINT32_MAX);
8356 
8357 			agg->dtag_base = aggbase;
8358 
8359 			while ((prev = first->dta_prev) != NULL &&
8360 			    DTRACEACT_ISAGG(prev->dta_kind)) {
8361 				agg = (dtrace_aggregation_t *)prev;
8362 				first = agg->dtag_first;
8363 			}
8364 
8365 			if (prev != NULL) {
8366 				offs = prev->dta_rec.dtrd_offset +
8367 				    prev->dta_rec.dtrd_size;
8368 			} else {
8369 				offs = sizeof (dtrace_epid_t);
8370 			}
8371 			wastuple = 0;
8372 		} else {
8373 			if (!act->dta_intuple)
8374 				ecb->dte_size = offs + rec->dtrd_size;
8375 
8376 			offs += rec->dtrd_size;
8377 		}
8378 
8379 		wastuple = act->dta_intuple;
8380 	}
8381 
8382 	if ((act = ecb->dte_action) != NULL &&
8383 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
8384 	    ecb->dte_size == sizeof (dtrace_epid_t)) {
8385 		/*
8386 		 * If the size is still sizeof (dtrace_epid_t), then all
8387 		 * actions store no data; set the size to 0.
8388 		 */
8389 		ecb->dte_alignment = maxalign;
8390 		ecb->dte_size = 0;
8391 
8392 		/*
8393 		 * If the needed space is still sizeof (dtrace_epid_t), then
8394 		 * all actions need no additional space; set the needed
8395 		 * size to 0.
8396 		 */
8397 		if (ecb->dte_needed == sizeof (dtrace_epid_t))
8398 			ecb->dte_needed = 0;
8399 
8400 		return;
8401 	}
8402 
8403 	/*
8404 	 * Set our alignment, and make sure that the dte_size and dte_needed
8405 	 * are aligned to the size of an EPID.
8406 	 */
8407 	ecb->dte_alignment = maxalign;
8408 	ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
8409 	    ~(sizeof (dtrace_epid_t) - 1);
8410 	ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
8411 	    ~(sizeof (dtrace_epid_t) - 1);
8412 	ASSERT(ecb->dte_size <= ecb->dte_needed);
8413 }
8414 
8415 static dtrace_action_t *
8416 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
8417 {
8418 	dtrace_aggregation_t *agg;
8419 	size_t size = sizeof (uint64_t);
8420 	int ntuple = desc->dtad_ntuple;
8421 	dtrace_action_t *act;
8422 	dtrace_recdesc_t *frec;
8423 	dtrace_aggid_t aggid;
8424 	dtrace_state_t *state = ecb->dte_state;
8425 
8426 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
8427 	agg->dtag_ecb = ecb;
8428 
8429 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
8430 
8431 	switch (desc->dtad_kind) {
8432 	case DTRACEAGG_MIN:
8433 		agg->dtag_initial = UINT64_MAX;
8434 		agg->dtag_aggregate = dtrace_aggregate_min;
8435 		break;
8436 
8437 	case DTRACEAGG_MAX:
8438 		agg->dtag_aggregate = dtrace_aggregate_max;
8439 		break;
8440 
8441 	case DTRACEAGG_COUNT:
8442 		agg->dtag_aggregate = dtrace_aggregate_count;
8443 		break;
8444 
8445 	case DTRACEAGG_QUANTIZE:
8446 		agg->dtag_aggregate = dtrace_aggregate_quantize;
8447 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
8448 		    sizeof (uint64_t);
8449 		break;
8450 
8451 	case DTRACEAGG_LQUANTIZE: {
8452 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
8453 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
8454 
8455 		agg->dtag_initial = desc->dtad_arg;
8456 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
8457 
8458 		if (step == 0 || levels == 0)
8459 			goto err;
8460 
8461 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
8462 		break;
8463 	}
8464 
8465 	case DTRACEAGG_AVG:
8466 		agg->dtag_aggregate = dtrace_aggregate_avg;
8467 		size = sizeof (uint64_t) * 2;
8468 		break;
8469 
8470 	case DTRACEAGG_SUM:
8471 		agg->dtag_aggregate = dtrace_aggregate_sum;
8472 		break;
8473 
8474 	default:
8475 		goto err;
8476 	}
8477 
8478 	agg->dtag_action.dta_rec.dtrd_size = size;
8479 
8480 	if (ntuple == 0)
8481 		goto err;
8482 
8483 	/*
8484 	 * We must make sure that we have enough actions for the n-tuple.
8485 	 */
8486 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
8487 		if (DTRACEACT_ISAGG(act->dta_kind))
8488 			break;
8489 
8490 		if (--ntuple == 0) {
8491 			/*
8492 			 * This is the action with which our n-tuple begins.
8493 			 */
8494 			agg->dtag_first = act;
8495 			goto success;
8496 		}
8497 	}
8498 
8499 	/*
8500 	 * This n-tuple is short by ntuple elements.  Return failure.
8501 	 */
8502 	ASSERT(ntuple != 0);
8503 err:
8504 	kmem_free(agg, sizeof (dtrace_aggregation_t));
8505 	return (NULL);
8506 
8507 success:
8508 	/*
8509 	 * If the last action in the tuple has a size of zero, it's actually
8510 	 * an expression argument for the aggregating action.
8511 	 */
8512 	ASSERT(ecb->dte_action_last != NULL);
8513 	act = ecb->dte_action_last;
8514 
8515 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
8516 		ASSERT(act->dta_difo != NULL);
8517 
8518 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
8519 			agg->dtag_hasarg = 1;
8520 	}
8521 
8522 	/*
8523 	 * We need to allocate an id for this aggregation.
8524 	 */
8525 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
8526 	    VM_BESTFIT | VM_SLEEP);
8527 
8528 	if (aggid - 1 >= state->dts_naggregations) {
8529 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
8530 		dtrace_aggregation_t **aggs;
8531 		int naggs = state->dts_naggregations << 1;
8532 		int onaggs = state->dts_naggregations;
8533 
8534 		ASSERT(aggid == state->dts_naggregations + 1);
8535 
8536 		if (naggs == 0) {
8537 			ASSERT(oaggs == NULL);
8538 			naggs = 1;
8539 		}
8540 
8541 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
8542 
8543 		if (oaggs != NULL) {
8544 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
8545 			kmem_free(oaggs, onaggs * sizeof (*aggs));
8546 		}
8547 
8548 		state->dts_aggregations = aggs;
8549 		state->dts_naggregations = naggs;
8550 	}
8551 
8552 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
8553 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
8554 
8555 	frec = &agg->dtag_first->dta_rec;
8556 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
8557 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
8558 
8559 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
8560 		ASSERT(!act->dta_intuple);
8561 		act->dta_intuple = 1;
8562 	}
8563 
8564 	return (&agg->dtag_action);
8565 }
8566 
8567 static void
8568 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
8569 {
8570 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
8571 	dtrace_state_t *state = ecb->dte_state;
8572 	dtrace_aggid_t aggid = agg->dtag_id;
8573 
8574 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
8575 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
8576 
8577 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
8578 	state->dts_aggregations[aggid - 1] = NULL;
8579 
8580 	kmem_free(agg, sizeof (dtrace_aggregation_t));
8581 }
8582 
8583 static int
8584 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
8585 {
8586 	dtrace_action_t *action, *last;
8587 	dtrace_difo_t *dp = desc->dtad_difo;
8588 	uint32_t size = 0, align = sizeof (uint8_t), mask;
8589 	uint16_t format = 0;
8590 	dtrace_recdesc_t *rec;
8591 	dtrace_state_t *state = ecb->dte_state;
8592 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
8593 	uint64_t arg = desc->dtad_arg;
8594 
8595 	ASSERT(MUTEX_HELD(&dtrace_lock));
8596 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
8597 
8598 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
8599 		/*
8600 		 * If this is an aggregating action, there must be neither
8601 		 * a speculate nor a commit on the action chain.
8602 		 */
8603 		dtrace_action_t *act;
8604 
8605 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
8606 			if (act->dta_kind == DTRACEACT_COMMIT)
8607 				return (EINVAL);
8608 
8609 			if (act->dta_kind == DTRACEACT_SPECULATE)
8610 				return (EINVAL);
8611 		}
8612 
8613 		action = dtrace_ecb_aggregation_create(ecb, desc);
8614 
8615 		if (action == NULL)
8616 			return (EINVAL);
8617 	} else {
8618 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
8619 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
8620 		    dp != NULL && dp->dtdo_destructive)) {
8621 			state->dts_destructive = 1;
8622 		}
8623 
8624 		switch (desc->dtad_kind) {
8625 		case DTRACEACT_PRINTF:
8626 		case DTRACEACT_PRINTA:
8627 		case DTRACEACT_SYSTEM:
8628 		case DTRACEACT_FREOPEN:
8629 			/*
8630 			 * We know that our arg is a string -- turn it into a
8631 			 * format.
8632 			 */
8633 			if (arg == NULL) {
8634 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
8635 				format = 0;
8636 			} else {
8637 				ASSERT(arg != NULL);
8638 				ASSERT(arg > KERNELBASE);
8639 				format = dtrace_format_add(state,
8640 				    (char *)(uintptr_t)arg);
8641 			}
8642 
8643 			/*FALLTHROUGH*/
8644 		case DTRACEACT_LIBACT:
8645 		case DTRACEACT_DIFEXPR:
8646 			if (dp == NULL)
8647 				return (EINVAL);
8648 
8649 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
8650 				break;
8651 
8652 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
8653 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8654 					return (EINVAL);
8655 
8656 				size = opt[DTRACEOPT_STRSIZE];
8657 			}
8658 
8659 			break;
8660 
8661 		case DTRACEACT_STACK:
8662 			if ((nframes = arg) == 0) {
8663 				nframes = opt[DTRACEOPT_STACKFRAMES];
8664 				ASSERT(nframes > 0);
8665 				arg = nframes;
8666 			}
8667 
8668 			size = nframes * sizeof (pc_t);
8669 			break;
8670 
8671 		case DTRACEACT_JSTACK:
8672 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
8673 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
8674 
8675 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
8676 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
8677 
8678 			arg = DTRACE_USTACK_ARG(nframes, strsize);
8679 
8680 			/*FALLTHROUGH*/
8681 		case DTRACEACT_USTACK:
8682 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
8683 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
8684 				strsize = DTRACE_USTACK_STRSIZE(arg);
8685 				nframes = opt[DTRACEOPT_USTACKFRAMES];
8686 				ASSERT(nframes > 0);
8687 				arg = DTRACE_USTACK_ARG(nframes, strsize);
8688 			}
8689 
8690 			/*
8691 			 * Save a slot for the pid.
8692 			 */
8693 			size = (nframes + 1) * sizeof (uint64_t);
8694 			size += DTRACE_USTACK_STRSIZE(arg);
8695 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
8696 
8697 			break;
8698 
8699 		case DTRACEACT_SYM:
8700 		case DTRACEACT_MOD:
8701 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
8702 			    sizeof (uint64_t)) ||
8703 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8704 				return (EINVAL);
8705 			break;
8706 
8707 		case DTRACEACT_USYM:
8708 		case DTRACEACT_UMOD:
8709 		case DTRACEACT_UADDR:
8710 			if (dp == NULL ||
8711 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
8712 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8713 				return (EINVAL);
8714 
8715 			/*
8716 			 * We have a slot for the pid, plus a slot for the
8717 			 * argument.  To keep things simple (aligned with
8718 			 * bitness-neutral sizing), we store each as a 64-bit
8719 			 * quantity.
8720 			 */
8721 			size = 2 * sizeof (uint64_t);
8722 			break;
8723 
8724 		case DTRACEACT_STOP:
8725 		case DTRACEACT_BREAKPOINT:
8726 		case DTRACEACT_PANIC:
8727 			break;
8728 
8729 		case DTRACEACT_CHILL:
8730 		case DTRACEACT_DISCARD:
8731 		case DTRACEACT_RAISE:
8732 			if (dp == NULL)
8733 				return (EINVAL);
8734 			break;
8735 
8736 		case DTRACEACT_EXIT:
8737 			if (dp == NULL ||
8738 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
8739 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8740 				return (EINVAL);
8741 			break;
8742 
8743 		case DTRACEACT_SPECULATE:
8744 			if (ecb->dte_size > sizeof (dtrace_epid_t))
8745 				return (EINVAL);
8746 
8747 			if (dp == NULL)
8748 				return (EINVAL);
8749 
8750 			state->dts_speculates = 1;
8751 			break;
8752 
8753 		case DTRACEACT_COMMIT: {
8754 			dtrace_action_t *act = ecb->dte_action;
8755 
8756 			for (; act != NULL; act = act->dta_next) {
8757 				if (act->dta_kind == DTRACEACT_COMMIT)
8758 					return (EINVAL);
8759 			}
8760 
8761 			if (dp == NULL)
8762 				return (EINVAL);
8763 			break;
8764 		}
8765 
8766 		default:
8767 			return (EINVAL);
8768 		}
8769 
8770 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
8771 			/*
8772 			 * If this is a data-storing action or a speculate,
8773 			 * we must be sure that there isn't a commit on the
8774 			 * action chain.
8775 			 */
8776 			dtrace_action_t *act = ecb->dte_action;
8777 
8778 			for (; act != NULL; act = act->dta_next) {
8779 				if (act->dta_kind == DTRACEACT_COMMIT)
8780 					return (EINVAL);
8781 			}
8782 		}
8783 
8784 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
8785 		action->dta_rec.dtrd_size = size;
8786 	}
8787 
8788 	action->dta_refcnt = 1;
8789 	rec = &action->dta_rec;
8790 	size = rec->dtrd_size;
8791 
8792 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
8793 		if (!(size & mask)) {
8794 			align = mask + 1;
8795 			break;
8796 		}
8797 	}
8798 
8799 	action->dta_kind = desc->dtad_kind;
8800 
8801 	if ((action->dta_difo = dp) != NULL)
8802 		dtrace_difo_hold(dp);
8803 
8804 	rec->dtrd_action = action->dta_kind;
8805 	rec->dtrd_arg = arg;
8806 	rec->dtrd_uarg = desc->dtad_uarg;
8807 	rec->dtrd_alignment = (uint16_t)align;
8808 	rec->dtrd_format = format;
8809 
8810 	if ((last = ecb->dte_action_last) != NULL) {
8811 		ASSERT(ecb->dte_action != NULL);
8812 		action->dta_prev = last;
8813 		last->dta_next = action;
8814 	} else {
8815 		ASSERT(ecb->dte_action == NULL);
8816 		ecb->dte_action = action;
8817 	}
8818 
8819 	ecb->dte_action_last = action;
8820 
8821 	return (0);
8822 }
8823 
8824 static void
8825 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
8826 {
8827 	dtrace_action_t *act = ecb->dte_action, *next;
8828 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
8829 	dtrace_difo_t *dp;
8830 	uint16_t format;
8831 
8832 	if (act != NULL && act->dta_refcnt > 1) {
8833 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
8834 		act->dta_refcnt--;
8835 	} else {
8836 		for (; act != NULL; act = next) {
8837 			next = act->dta_next;
8838 			ASSERT(next != NULL || act == ecb->dte_action_last);
8839 			ASSERT(act->dta_refcnt == 1);
8840 
8841 			if ((format = act->dta_rec.dtrd_format) != 0)
8842 				dtrace_format_remove(ecb->dte_state, format);
8843 
8844 			if ((dp = act->dta_difo) != NULL)
8845 				dtrace_difo_release(dp, vstate);
8846 
8847 			if (DTRACEACT_ISAGG(act->dta_kind)) {
8848 				dtrace_ecb_aggregation_destroy(ecb, act);
8849 			} else {
8850 				kmem_free(act, sizeof (dtrace_action_t));
8851 			}
8852 		}
8853 	}
8854 
8855 	ecb->dte_action = NULL;
8856 	ecb->dte_action_last = NULL;
8857 	ecb->dte_size = sizeof (dtrace_epid_t);
8858 }
8859 
8860 static void
8861 dtrace_ecb_disable(dtrace_ecb_t *ecb)
8862 {
8863 	/*
8864 	 * We disable the ECB by removing it from its probe.
8865 	 */
8866 	dtrace_ecb_t *pecb, *prev = NULL;
8867 	dtrace_probe_t *probe = ecb->dte_probe;
8868 
8869 	ASSERT(MUTEX_HELD(&dtrace_lock));
8870 
8871 	if (probe == NULL) {
8872 		/*
8873 		 * This is the NULL probe; there is nothing to disable.
8874 		 */
8875 		return;
8876 	}
8877 
8878 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
8879 		if (pecb == ecb)
8880 			break;
8881 		prev = pecb;
8882 	}
8883 
8884 	ASSERT(pecb != NULL);
8885 
8886 	if (prev == NULL) {
8887 		probe->dtpr_ecb = ecb->dte_next;
8888 	} else {
8889 		prev->dte_next = ecb->dte_next;
8890 	}
8891 
8892 	if (ecb == probe->dtpr_ecb_last) {
8893 		ASSERT(ecb->dte_next == NULL);
8894 		probe->dtpr_ecb_last = prev;
8895 	}
8896 
8897 	/*
8898 	 * The ECB has been disconnected from the probe; now sync to assure
8899 	 * that all CPUs have seen the change before returning.
8900 	 */
8901 	dtrace_sync();
8902 
8903 	if (probe->dtpr_ecb == NULL) {
8904 		/*
8905 		 * That was the last ECB on the probe; clear the predicate
8906 		 * cache ID for the probe, disable it and sync one more time
8907 		 * to assure that we'll never hit it again.
8908 		 */
8909 		dtrace_provider_t *prov = probe->dtpr_provider;
8910 
8911 		ASSERT(ecb->dte_next == NULL);
8912 		ASSERT(probe->dtpr_ecb_last == NULL);
8913 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
8914 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
8915 		    probe->dtpr_id, probe->dtpr_arg);
8916 		dtrace_sync();
8917 	} else {
8918 		/*
8919 		 * There is at least one ECB remaining on the probe.  If there
8920 		 * is _exactly_ one, set the probe's predicate cache ID to be
8921 		 * the predicate cache ID of the remaining ECB.
8922 		 */
8923 		ASSERT(probe->dtpr_ecb_last != NULL);
8924 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
8925 
8926 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
8927 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
8928 
8929 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
8930 
8931 			if (p != NULL)
8932 				probe->dtpr_predcache = p->dtp_cacheid;
8933 		}
8934 
8935 		ecb->dte_next = NULL;
8936 	}
8937 }
8938 
8939 static void
8940 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
8941 {
8942 	dtrace_state_t *state = ecb->dte_state;
8943 	dtrace_vstate_t *vstate = &state->dts_vstate;
8944 	dtrace_predicate_t *pred;
8945 	dtrace_epid_t epid = ecb->dte_epid;
8946 
8947 	ASSERT(MUTEX_HELD(&dtrace_lock));
8948 	ASSERT(ecb->dte_next == NULL);
8949 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
8950 
8951 	if ((pred = ecb->dte_predicate) != NULL)
8952 		dtrace_predicate_release(pred, vstate);
8953 
8954 	dtrace_ecb_action_remove(ecb);
8955 
8956 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
8957 	state->dts_ecbs[epid - 1] = NULL;
8958 
8959 	kmem_free(ecb, sizeof (dtrace_ecb_t));
8960 }
8961 
8962 static dtrace_ecb_t *
8963 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
8964     dtrace_enabling_t *enab)
8965 {
8966 	dtrace_ecb_t *ecb;
8967 	dtrace_predicate_t *pred;
8968 	dtrace_actdesc_t *act;
8969 	dtrace_provider_t *prov;
8970 	dtrace_ecbdesc_t *desc = enab->dten_current;
8971 
8972 	ASSERT(MUTEX_HELD(&dtrace_lock));
8973 	ASSERT(state != NULL);
8974 
8975 	ecb = dtrace_ecb_add(state, probe);
8976 	ecb->dte_uarg = desc->dted_uarg;
8977 
8978 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
8979 		dtrace_predicate_hold(pred);
8980 		ecb->dte_predicate = pred;
8981 	}
8982 
8983 	if (probe != NULL) {
8984 		/*
8985 		 * If the provider shows more leg than the consumer is old
8986 		 * enough to see, we need to enable the appropriate implicit
8987 		 * predicate bits to prevent the ecb from activating at
8988 		 * revealing times.
8989 		 *
8990 		 * Providers specifying DTRACE_PRIV_USER at register time
8991 		 * are stating that they need the /proc-style privilege
8992 		 * model to be enforced, and this is what DTRACE_COND_OWNER
8993 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
8994 		 */
8995 		prov = probe->dtpr_provider;
8996 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
8997 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
8998 			ecb->dte_cond |= DTRACE_COND_OWNER;
8999 
9000 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
9001 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9002 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
9003 
9004 		/*
9005 		 * If the provider shows us kernel innards and the user
9006 		 * is lacking sufficient privilege, enable the
9007 		 * DTRACE_COND_USERMODE implicit predicate.
9008 		 */
9009 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
9010 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
9011 			ecb->dte_cond |= DTRACE_COND_USERMODE;
9012 	}
9013 
9014 	if (dtrace_ecb_create_cache != NULL) {
9015 		/*
9016 		 * If we have a cached ecb, we'll use its action list instead
9017 		 * of creating our own (saving both time and space).
9018 		 */
9019 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
9020 		dtrace_action_t *act = cached->dte_action;
9021 
9022 		if (act != NULL) {
9023 			ASSERT(act->dta_refcnt > 0);
9024 			act->dta_refcnt++;
9025 			ecb->dte_action = act;
9026 			ecb->dte_action_last = cached->dte_action_last;
9027 			ecb->dte_needed = cached->dte_needed;
9028 			ecb->dte_size = cached->dte_size;
9029 			ecb->dte_alignment = cached->dte_alignment;
9030 		}
9031 
9032 		return (ecb);
9033 	}
9034 
9035 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
9036 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
9037 			dtrace_ecb_destroy(ecb);
9038 			return (NULL);
9039 		}
9040 	}
9041 
9042 	dtrace_ecb_resize(ecb);
9043 
9044 	return (dtrace_ecb_create_cache = ecb);
9045 }
9046 
9047 static int
9048 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
9049 {
9050 	dtrace_ecb_t *ecb;
9051 	dtrace_enabling_t *enab = arg;
9052 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
9053 
9054 	ASSERT(state != NULL);
9055 
9056 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
9057 		/*
9058 		 * This probe was created in a generation for which this
9059 		 * enabling has previously created ECBs; we don't want to
9060 		 * enable it again, so just kick out.
9061 		 */
9062 		return (DTRACE_MATCH_NEXT);
9063 	}
9064 
9065 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
9066 		return (DTRACE_MATCH_DONE);
9067 
9068 	dtrace_ecb_enable(ecb);
9069 	return (DTRACE_MATCH_NEXT);
9070 }
9071 
9072 static dtrace_ecb_t *
9073 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
9074 {
9075 	dtrace_ecb_t *ecb;
9076 
9077 	ASSERT(MUTEX_HELD(&dtrace_lock));
9078 
9079 	if (id == 0 || id > state->dts_necbs)
9080 		return (NULL);
9081 
9082 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
9083 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
9084 
9085 	return (state->dts_ecbs[id - 1]);
9086 }
9087 
9088 static dtrace_aggregation_t *
9089 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
9090 {
9091 	dtrace_aggregation_t *agg;
9092 
9093 	ASSERT(MUTEX_HELD(&dtrace_lock));
9094 
9095 	if (id == 0 || id > state->dts_naggregations)
9096 		return (NULL);
9097 
9098 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
9099 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
9100 	    agg->dtag_id == id);
9101 
9102 	return (state->dts_aggregations[id - 1]);
9103 }
9104 
9105 /*
9106  * DTrace Buffer Functions
9107  *
9108  * The following functions manipulate DTrace buffers.  Most of these functions
9109  * are called in the context of establishing or processing consumer state;
9110  * exceptions are explicitly noted.
9111  */
9112 
9113 /*
9114  * Note:  called from cross call context.  This function switches the two
9115  * buffers on a given CPU.  The atomicity of this operation is assured by
9116  * disabling interrupts while the actual switch takes place; the disabling of
9117  * interrupts serializes the execution with any execution of dtrace_probe() on
9118  * the same CPU.
9119  */
9120 static void
9121 dtrace_buffer_switch(dtrace_buffer_t *buf)
9122 {
9123 	caddr_t tomax = buf->dtb_tomax;
9124 	caddr_t xamot = buf->dtb_xamot;
9125 	dtrace_icookie_t cookie;
9126 
9127 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
9128 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
9129 
9130 	cookie = dtrace_interrupt_disable();
9131 	buf->dtb_tomax = xamot;
9132 	buf->dtb_xamot = tomax;
9133 	buf->dtb_xamot_drops = buf->dtb_drops;
9134 	buf->dtb_xamot_offset = buf->dtb_offset;
9135 	buf->dtb_xamot_errors = buf->dtb_errors;
9136 	buf->dtb_xamot_flags = buf->dtb_flags;
9137 	buf->dtb_offset = 0;
9138 	buf->dtb_drops = 0;
9139 	buf->dtb_errors = 0;
9140 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
9141 	dtrace_interrupt_enable(cookie);
9142 }
9143 
9144 /*
9145  * Note:  called from cross call context.  This function activates a buffer
9146  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
9147  * is guaranteed by the disabling of interrupts.
9148  */
9149 static void
9150 dtrace_buffer_activate(dtrace_state_t *state)
9151 {
9152 	dtrace_buffer_t *buf;
9153 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
9154 
9155 	buf = &state->dts_buffer[CPU->cpu_id];
9156 
9157 	if (buf->dtb_tomax != NULL) {
9158 		/*
9159 		 * We might like to assert that the buffer is marked inactive,
9160 		 * but this isn't necessarily true:  the buffer for the CPU
9161 		 * that processes the BEGIN probe has its buffer activated
9162 		 * manually.  In this case, we take the (harmless) action
9163 		 * re-clearing the bit INACTIVE bit.
9164 		 */
9165 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
9166 	}
9167 
9168 	dtrace_interrupt_enable(cookie);
9169 }
9170 
9171 static int
9172 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
9173     processorid_t cpu)
9174 {
9175 	cpu_t *cp;
9176 	dtrace_buffer_t *buf;
9177 
9178 	ASSERT(MUTEX_HELD(&cpu_lock));
9179 	ASSERT(MUTEX_HELD(&dtrace_lock));
9180 
9181 	if (size > dtrace_nonroot_maxsize &&
9182 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
9183 		return (EFBIG);
9184 
9185 	cp = cpu_list;
9186 
9187 	do {
9188 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9189 			continue;
9190 
9191 		buf = &bufs[cp->cpu_id];
9192 
9193 		/*
9194 		 * If there is already a buffer allocated for this CPU, it
9195 		 * is only possible that this is a DR event.  In this case,
9196 		 * the buffer size must match our specified size.
9197 		 */
9198 		if (buf->dtb_tomax != NULL) {
9199 			ASSERT(buf->dtb_size == size);
9200 			continue;
9201 		}
9202 
9203 		ASSERT(buf->dtb_xamot == NULL);
9204 
9205 		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9206 			goto err;
9207 
9208 		buf->dtb_size = size;
9209 		buf->dtb_flags = flags;
9210 		buf->dtb_offset = 0;
9211 		buf->dtb_drops = 0;
9212 
9213 		if (flags & DTRACEBUF_NOSWITCH)
9214 			continue;
9215 
9216 		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9217 			goto err;
9218 	} while ((cp = cp->cpu_next) != cpu_list);
9219 
9220 	return (0);
9221 
9222 err:
9223 	cp = cpu_list;
9224 
9225 	do {
9226 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9227 			continue;
9228 
9229 		buf = &bufs[cp->cpu_id];
9230 
9231 		if (buf->dtb_xamot != NULL) {
9232 			ASSERT(buf->dtb_tomax != NULL);
9233 			ASSERT(buf->dtb_size == size);
9234 			kmem_free(buf->dtb_xamot, size);
9235 		}
9236 
9237 		if (buf->dtb_tomax != NULL) {
9238 			ASSERT(buf->dtb_size == size);
9239 			kmem_free(buf->dtb_tomax, size);
9240 		}
9241 
9242 		buf->dtb_tomax = NULL;
9243 		buf->dtb_xamot = NULL;
9244 		buf->dtb_size = 0;
9245 	} while ((cp = cp->cpu_next) != cpu_list);
9246 
9247 	return (ENOMEM);
9248 }
9249 
9250 /*
9251  * Note:  called from probe context.  This function just increments the drop
9252  * count on a buffer.  It has been made a function to allow for the
9253  * possibility of understanding the source of mysterious drop counts.  (A
9254  * problem for which one may be particularly disappointed that DTrace cannot
9255  * be used to understand DTrace.)
9256  */
9257 static void
9258 dtrace_buffer_drop(dtrace_buffer_t *buf)
9259 {
9260 	buf->dtb_drops++;
9261 }
9262 
9263 /*
9264  * Note:  called from probe context.  This function is called to reserve space
9265  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
9266  * mstate.  Returns the new offset in the buffer, or a negative value if an
9267  * error has occurred.
9268  */
9269 static intptr_t
9270 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
9271     dtrace_state_t *state, dtrace_mstate_t *mstate)
9272 {
9273 	intptr_t offs = buf->dtb_offset, soffs;
9274 	intptr_t woffs;
9275 	caddr_t tomax;
9276 	size_t total;
9277 
9278 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
9279 		return (-1);
9280 
9281 	if ((tomax = buf->dtb_tomax) == NULL) {
9282 		dtrace_buffer_drop(buf);
9283 		return (-1);
9284 	}
9285 
9286 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
9287 		while (offs & (align - 1)) {
9288 			/*
9289 			 * Assert that our alignment is off by a number which
9290 			 * is itself sizeof (uint32_t) aligned.
9291 			 */
9292 			ASSERT(!((align - (offs & (align - 1))) &
9293 			    (sizeof (uint32_t) - 1)));
9294 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
9295 			offs += sizeof (uint32_t);
9296 		}
9297 
9298 		if ((soffs = offs + needed) > buf->dtb_size) {
9299 			dtrace_buffer_drop(buf);
9300 			return (-1);
9301 		}
9302 
9303 		if (mstate == NULL)
9304 			return (offs);
9305 
9306 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
9307 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
9308 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
9309 
9310 		return (offs);
9311 	}
9312 
9313 	if (buf->dtb_flags & DTRACEBUF_FILL) {
9314 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
9315 		    (buf->dtb_flags & DTRACEBUF_FULL))
9316 			return (-1);
9317 		goto out;
9318 	}
9319 
9320 	total = needed + (offs & (align - 1));
9321 
9322 	/*
9323 	 * For a ring buffer, life is quite a bit more complicated.  Before
9324 	 * we can store any padding, we need to adjust our wrapping offset.
9325 	 * (If we've never before wrapped or we're not about to, no adjustment
9326 	 * is required.)
9327 	 */
9328 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
9329 	    offs + total > buf->dtb_size) {
9330 		woffs = buf->dtb_xamot_offset;
9331 
9332 		if (offs + total > buf->dtb_size) {
9333 			/*
9334 			 * We can't fit in the end of the buffer.  First, a
9335 			 * sanity check that we can fit in the buffer at all.
9336 			 */
9337 			if (total > buf->dtb_size) {
9338 				dtrace_buffer_drop(buf);
9339 				return (-1);
9340 			}
9341 
9342 			/*
9343 			 * We're going to be storing at the top of the buffer,
9344 			 * so now we need to deal with the wrapped offset.  We
9345 			 * only reset our wrapped offset to 0 if it is
9346 			 * currently greater than the current offset.  If it
9347 			 * is less than the current offset, it is because a
9348 			 * previous allocation induced a wrap -- but the
9349 			 * allocation didn't subsequently take the space due
9350 			 * to an error or false predicate evaluation.  In this
9351 			 * case, we'll just leave the wrapped offset alone: if
9352 			 * the wrapped offset hasn't been advanced far enough
9353 			 * for this allocation, it will be adjusted in the
9354 			 * lower loop.
9355 			 */
9356 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
9357 				if (woffs >= offs)
9358 					woffs = 0;
9359 			} else {
9360 				woffs = 0;
9361 			}
9362 
9363 			/*
9364 			 * Now we know that we're going to be storing to the
9365 			 * top of the buffer and that there is room for us
9366 			 * there.  We need to clear the buffer from the current
9367 			 * offset to the end (there may be old gunk there).
9368 			 */
9369 			while (offs < buf->dtb_size)
9370 				tomax[offs++] = 0;
9371 
9372 			/*
9373 			 * We need to set our offset to zero.  And because we
9374 			 * are wrapping, we need to set the bit indicating as
9375 			 * much.  We can also adjust our needed space back
9376 			 * down to the space required by the ECB -- we know
9377 			 * that the top of the buffer is aligned.
9378 			 */
9379 			offs = 0;
9380 			total = needed;
9381 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
9382 		} else {
9383 			/*
9384 			 * There is room for us in the buffer, so we simply
9385 			 * need to check the wrapped offset.
9386 			 */
9387 			if (woffs < offs) {
9388 				/*
9389 				 * The wrapped offset is less than the offset.
9390 				 * This can happen if we allocated buffer space
9391 				 * that induced a wrap, but then we didn't
9392 				 * subsequently take the space due to an error
9393 				 * or false predicate evaluation.  This is
9394 				 * okay; we know that _this_ allocation isn't
9395 				 * going to induce a wrap.  We still can't
9396 				 * reset the wrapped offset to be zero,
9397 				 * however: the space may have been trashed in
9398 				 * the previous failed probe attempt.  But at
9399 				 * least the wrapped offset doesn't need to
9400 				 * be adjusted at all...
9401 				 */
9402 				goto out;
9403 			}
9404 		}
9405 
9406 		while (offs + total > woffs) {
9407 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
9408 			size_t size;
9409 
9410 			if (epid == DTRACE_EPIDNONE) {
9411 				size = sizeof (uint32_t);
9412 			} else {
9413 				ASSERT(epid <= state->dts_necbs);
9414 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
9415 
9416 				size = state->dts_ecbs[epid - 1]->dte_size;
9417 			}
9418 
9419 			ASSERT(woffs + size <= buf->dtb_size);
9420 			ASSERT(size != 0);
9421 
9422 			if (woffs + size == buf->dtb_size) {
9423 				/*
9424 				 * We've reached the end of the buffer; we want
9425 				 * to set the wrapped offset to 0 and break
9426 				 * out.  However, if the offs is 0, then we're
9427 				 * in a strange edge-condition:  the amount of
9428 				 * space that we want to reserve plus the size
9429 				 * of the record that we're overwriting is
9430 				 * greater than the size of the buffer.  This
9431 				 * is problematic because if we reserve the
9432 				 * space but subsequently don't consume it (due
9433 				 * to a failed predicate or error) the wrapped
9434 				 * offset will be 0 -- yet the EPID at offset 0
9435 				 * will not be committed.  This situation is
9436 				 * relatively easy to deal with:  if we're in
9437 				 * this case, the buffer is indistinguishable
9438 				 * from one that hasn't wrapped; we need only
9439 				 * finish the job by clearing the wrapped bit,
9440 				 * explicitly setting the offset to be 0, and
9441 				 * zero'ing out the old data in the buffer.
9442 				 */
9443 				if (offs == 0) {
9444 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
9445 					buf->dtb_offset = 0;
9446 					woffs = total;
9447 
9448 					while (woffs < buf->dtb_size)
9449 						tomax[woffs++] = 0;
9450 				}
9451 
9452 				woffs = 0;
9453 				break;
9454 			}
9455 
9456 			woffs += size;
9457 		}
9458 
9459 		/*
9460 		 * We have a wrapped offset.  It may be that the wrapped offset
9461 		 * has become zero -- that's okay.
9462 		 */
9463 		buf->dtb_xamot_offset = woffs;
9464 	}
9465 
9466 out:
9467 	/*
9468 	 * Now we can plow the buffer with any necessary padding.
9469 	 */
9470 	while (offs & (align - 1)) {
9471 		/*
9472 		 * Assert that our alignment is off by a number which
9473 		 * is itself sizeof (uint32_t) aligned.
9474 		 */
9475 		ASSERT(!((align - (offs & (align - 1))) &
9476 		    (sizeof (uint32_t) - 1)));
9477 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
9478 		offs += sizeof (uint32_t);
9479 	}
9480 
9481 	if (buf->dtb_flags & DTRACEBUF_FILL) {
9482 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
9483 			buf->dtb_flags |= DTRACEBUF_FULL;
9484 			return (-1);
9485 		}
9486 	}
9487 
9488 	if (mstate == NULL)
9489 		return (offs);
9490 
9491 	/*
9492 	 * For ring buffers and fill buffers, the scratch space is always
9493 	 * the inactive buffer.
9494 	 */
9495 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
9496 	mstate->dtms_scratch_size = buf->dtb_size;
9497 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
9498 
9499 	return (offs);
9500 }
9501 
9502 static void
9503 dtrace_buffer_polish(dtrace_buffer_t *buf)
9504 {
9505 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
9506 	ASSERT(MUTEX_HELD(&dtrace_lock));
9507 
9508 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
9509 		return;
9510 
9511 	/*
9512 	 * We need to polish the ring buffer.  There are three cases:
9513 	 *
9514 	 * - The first (and presumably most common) is that there is no gap
9515 	 *   between the buffer offset and the wrapped offset.  In this case,
9516 	 *   there is nothing in the buffer that isn't valid data; we can
9517 	 *   mark the buffer as polished and return.
9518 	 *
9519 	 * - The second (less common than the first but still more common
9520 	 *   than the third) is that there is a gap between the buffer offset
9521 	 *   and the wrapped offset, and the wrapped offset is larger than the
9522 	 *   buffer offset.  This can happen because of an alignment issue, or
9523 	 *   can happen because of a call to dtrace_buffer_reserve() that
9524 	 *   didn't subsequently consume the buffer space.  In this case,
9525 	 *   we need to zero the data from the buffer offset to the wrapped
9526 	 *   offset.
9527 	 *
9528 	 * - The third (and least common) is that there is a gap between the
9529 	 *   buffer offset and the wrapped offset, but the wrapped offset is
9530 	 *   _less_ than the buffer offset.  This can only happen because a
9531 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
9532 	 *   was not subsequently consumed.  In this case, we need to zero the
9533 	 *   space from the offset to the end of the buffer _and_ from the
9534 	 *   top of the buffer to the wrapped offset.
9535 	 */
9536 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
9537 		bzero(buf->dtb_tomax + buf->dtb_offset,
9538 		    buf->dtb_xamot_offset - buf->dtb_offset);
9539 	}
9540 
9541 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
9542 		bzero(buf->dtb_tomax + buf->dtb_offset,
9543 		    buf->dtb_size - buf->dtb_offset);
9544 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
9545 	}
9546 }
9547 
9548 static void
9549 dtrace_buffer_free(dtrace_buffer_t *bufs)
9550 {
9551 	int i;
9552 
9553 	for (i = 0; i < NCPU; i++) {
9554 		dtrace_buffer_t *buf = &bufs[i];
9555 
9556 		if (buf->dtb_tomax == NULL) {
9557 			ASSERT(buf->dtb_xamot == NULL);
9558 			ASSERT(buf->dtb_size == 0);
9559 			continue;
9560 		}
9561 
9562 		if (buf->dtb_xamot != NULL) {
9563 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
9564 			kmem_free(buf->dtb_xamot, buf->dtb_size);
9565 		}
9566 
9567 		kmem_free(buf->dtb_tomax, buf->dtb_size);
9568 		buf->dtb_size = 0;
9569 		buf->dtb_tomax = NULL;
9570 		buf->dtb_xamot = NULL;
9571 	}
9572 }
9573 
9574 /*
9575  * DTrace Enabling Functions
9576  */
9577 static dtrace_enabling_t *
9578 dtrace_enabling_create(dtrace_vstate_t *vstate)
9579 {
9580 	dtrace_enabling_t *enab;
9581 
9582 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
9583 	enab->dten_vstate = vstate;
9584 
9585 	return (enab);
9586 }
9587 
9588 static void
9589 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
9590 {
9591 	dtrace_ecbdesc_t **ndesc;
9592 	size_t osize, nsize;
9593 
9594 	/*
9595 	 * We can't add to enablings after we've enabled them, or after we've
9596 	 * retained them.
9597 	 */
9598 	ASSERT(enab->dten_probegen == 0);
9599 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
9600 
9601 	if (enab->dten_ndesc < enab->dten_maxdesc) {
9602 		enab->dten_desc[enab->dten_ndesc++] = ecb;
9603 		return;
9604 	}
9605 
9606 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
9607 
9608 	if (enab->dten_maxdesc == 0) {
9609 		enab->dten_maxdesc = 1;
9610 	} else {
9611 		enab->dten_maxdesc <<= 1;
9612 	}
9613 
9614 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
9615 
9616 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
9617 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
9618 	bcopy(enab->dten_desc, ndesc, osize);
9619 	kmem_free(enab->dten_desc, osize);
9620 
9621 	enab->dten_desc = ndesc;
9622 	enab->dten_desc[enab->dten_ndesc++] = ecb;
9623 }
9624 
9625 static void
9626 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
9627     dtrace_probedesc_t *pd)
9628 {
9629 	dtrace_ecbdesc_t *new;
9630 	dtrace_predicate_t *pred;
9631 	dtrace_actdesc_t *act;
9632 
9633 	/*
9634 	 * We're going to create a new ECB description that matches the
9635 	 * specified ECB in every way, but has the specified probe description.
9636 	 */
9637 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
9638 
9639 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
9640 		dtrace_predicate_hold(pred);
9641 
9642 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
9643 		dtrace_actdesc_hold(act);
9644 
9645 	new->dted_action = ecb->dted_action;
9646 	new->dted_pred = ecb->dted_pred;
9647 	new->dted_probe = *pd;
9648 	new->dted_uarg = ecb->dted_uarg;
9649 
9650 	dtrace_enabling_add(enab, new);
9651 }
9652 
9653 static void
9654 dtrace_enabling_dump(dtrace_enabling_t *enab)
9655 {
9656 	int i;
9657 
9658 	for (i = 0; i < enab->dten_ndesc; i++) {
9659 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
9660 
9661 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
9662 		    desc->dtpd_provider, desc->dtpd_mod,
9663 		    desc->dtpd_func, desc->dtpd_name);
9664 	}
9665 }
9666 
9667 static void
9668 dtrace_enabling_destroy(dtrace_enabling_t *enab)
9669 {
9670 	int i;
9671 	dtrace_ecbdesc_t *ep;
9672 	dtrace_vstate_t *vstate = enab->dten_vstate;
9673 
9674 	ASSERT(MUTEX_HELD(&dtrace_lock));
9675 
9676 	for (i = 0; i < enab->dten_ndesc; i++) {
9677 		dtrace_actdesc_t *act, *next;
9678 		dtrace_predicate_t *pred;
9679 
9680 		ep = enab->dten_desc[i];
9681 
9682 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
9683 			dtrace_predicate_release(pred, vstate);
9684 
9685 		for (act = ep->dted_action; act != NULL; act = next) {
9686 			next = act->dtad_next;
9687 			dtrace_actdesc_release(act, vstate);
9688 		}
9689 
9690 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
9691 	}
9692 
9693 	kmem_free(enab->dten_desc,
9694 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
9695 
9696 	/*
9697 	 * If this was a retained enabling, decrement the dts_nretained count
9698 	 * and take it off of the dtrace_retained list.
9699 	 */
9700 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
9701 	    dtrace_retained == enab) {
9702 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9703 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
9704 		enab->dten_vstate->dtvs_state->dts_nretained--;
9705 	}
9706 
9707 	if (enab->dten_prev == NULL) {
9708 		if (dtrace_retained == enab) {
9709 			dtrace_retained = enab->dten_next;
9710 
9711 			if (dtrace_retained != NULL)
9712 				dtrace_retained->dten_prev = NULL;
9713 		}
9714 	} else {
9715 		ASSERT(enab != dtrace_retained);
9716 		ASSERT(dtrace_retained != NULL);
9717 		enab->dten_prev->dten_next = enab->dten_next;
9718 	}
9719 
9720 	if (enab->dten_next != NULL) {
9721 		ASSERT(dtrace_retained != NULL);
9722 		enab->dten_next->dten_prev = enab->dten_prev;
9723 	}
9724 
9725 	kmem_free(enab, sizeof (dtrace_enabling_t));
9726 }
9727 
9728 static int
9729 dtrace_enabling_retain(dtrace_enabling_t *enab)
9730 {
9731 	dtrace_state_t *state;
9732 
9733 	ASSERT(MUTEX_HELD(&dtrace_lock));
9734 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
9735 	ASSERT(enab->dten_vstate != NULL);
9736 
9737 	state = enab->dten_vstate->dtvs_state;
9738 	ASSERT(state != NULL);
9739 
9740 	/*
9741 	 * We only allow each state to retain dtrace_retain_max enablings.
9742 	 */
9743 	if (state->dts_nretained >= dtrace_retain_max)
9744 		return (ENOSPC);
9745 
9746 	state->dts_nretained++;
9747 
9748 	if (dtrace_retained == NULL) {
9749 		dtrace_retained = enab;
9750 		return (0);
9751 	}
9752 
9753 	enab->dten_next = dtrace_retained;
9754 	dtrace_retained->dten_prev = enab;
9755 	dtrace_retained = enab;
9756 
9757 	return (0);
9758 }
9759 
9760 static int
9761 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
9762     dtrace_probedesc_t *create)
9763 {
9764 	dtrace_enabling_t *new, *enab;
9765 	int found = 0, err = ENOENT;
9766 
9767 	ASSERT(MUTEX_HELD(&dtrace_lock));
9768 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
9769 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
9770 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
9771 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
9772 
9773 	new = dtrace_enabling_create(&state->dts_vstate);
9774 
9775 	/*
9776 	 * Iterate over all retained enablings, looking for enablings that
9777 	 * match the specified state.
9778 	 */
9779 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
9780 		int i;
9781 
9782 		/*
9783 		 * dtvs_state can only be NULL for helper enablings -- and
9784 		 * helper enablings can't be retained.
9785 		 */
9786 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9787 
9788 		if (enab->dten_vstate->dtvs_state != state)
9789 			continue;
9790 
9791 		/*
9792 		 * Now iterate over each probe description; we're looking for
9793 		 * an exact match to the specified probe description.
9794 		 */
9795 		for (i = 0; i < enab->dten_ndesc; i++) {
9796 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
9797 			dtrace_probedesc_t *pd = &ep->dted_probe;
9798 
9799 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
9800 				continue;
9801 
9802 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
9803 				continue;
9804 
9805 			if (strcmp(pd->dtpd_func, match->dtpd_func))
9806 				continue;
9807 
9808 			if (strcmp(pd->dtpd_name, match->dtpd_name))
9809 				continue;
9810 
9811 			/*
9812 			 * We have a winning probe!  Add it to our growing
9813 			 * enabling.
9814 			 */
9815 			found = 1;
9816 			dtrace_enabling_addlike(new, ep, create);
9817 		}
9818 	}
9819 
9820 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
9821 		dtrace_enabling_destroy(new);
9822 		return (err);
9823 	}
9824 
9825 	return (0);
9826 }
9827 
9828 static void
9829 dtrace_enabling_retract(dtrace_state_t *state)
9830 {
9831 	dtrace_enabling_t *enab, *next;
9832 
9833 	ASSERT(MUTEX_HELD(&dtrace_lock));
9834 
9835 	/*
9836 	 * Iterate over all retained enablings, destroy the enablings retained
9837 	 * for the specified state.
9838 	 */
9839 	for (enab = dtrace_retained; enab != NULL; enab = next) {
9840 		next = enab->dten_next;
9841 
9842 		/*
9843 		 * dtvs_state can only be NULL for helper enablings -- and
9844 		 * helper enablings can't be retained.
9845 		 */
9846 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9847 
9848 		if (enab->dten_vstate->dtvs_state == state) {
9849 			ASSERT(state->dts_nretained > 0);
9850 			dtrace_enabling_destroy(enab);
9851 		}
9852 	}
9853 
9854 	ASSERT(state->dts_nretained == 0);
9855 }
9856 
9857 static int
9858 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
9859 {
9860 	int i = 0;
9861 	int matched = 0;
9862 
9863 	ASSERT(MUTEX_HELD(&cpu_lock));
9864 	ASSERT(MUTEX_HELD(&dtrace_lock));
9865 
9866 	for (i = 0; i < enab->dten_ndesc; i++) {
9867 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
9868 
9869 		enab->dten_current = ep;
9870 		enab->dten_error = 0;
9871 
9872 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
9873 
9874 		if (enab->dten_error != 0) {
9875 			/*
9876 			 * If we get an error half-way through enabling the
9877 			 * probes, we kick out -- perhaps with some number of
9878 			 * them enabled.  Leaving enabled probes enabled may
9879 			 * be slightly confusing for user-level, but we expect
9880 			 * that no one will attempt to actually drive on in
9881 			 * the face of such errors.  If this is an anonymous
9882 			 * enabling (indicated with a NULL nmatched pointer),
9883 			 * we cmn_err() a message.  We aren't expecting to
9884 			 * get such an error -- such as it can exist at all,
9885 			 * it would be a result of corrupted DOF in the driver
9886 			 * properties.
9887 			 */
9888 			if (nmatched == NULL) {
9889 				cmn_err(CE_WARN, "dtrace_enabling_match() "
9890 				    "error on %p: %d", (void *)ep,
9891 				    enab->dten_error);
9892 			}
9893 
9894 			return (enab->dten_error);
9895 		}
9896 	}
9897 
9898 	enab->dten_probegen = dtrace_probegen;
9899 	if (nmatched != NULL)
9900 		*nmatched = matched;
9901 
9902 	return (0);
9903 }
9904 
9905 static void
9906 dtrace_enabling_matchall(void)
9907 {
9908 	dtrace_enabling_t *enab;
9909 
9910 	mutex_enter(&cpu_lock);
9911 	mutex_enter(&dtrace_lock);
9912 
9913 	/*
9914 	 * Because we can be called after dtrace_detach() has been called, we
9915 	 * cannot assert that there are retained enablings.  We can safely
9916 	 * load from dtrace_retained, however:  the taskq_destroy() at the
9917 	 * end of dtrace_detach() will block pending our completion.
9918 	 */
9919 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next)
9920 		(void) dtrace_enabling_match(enab, NULL);
9921 
9922 	mutex_exit(&dtrace_lock);
9923 	mutex_exit(&cpu_lock);
9924 }
9925 
9926 static int
9927 dtrace_enabling_matchstate(dtrace_state_t *state, int *nmatched)
9928 {
9929 	dtrace_enabling_t *enab;
9930 	int matched, total = 0, err;
9931 
9932 	ASSERT(MUTEX_HELD(&cpu_lock));
9933 	ASSERT(MUTEX_HELD(&dtrace_lock));
9934 
9935 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
9936 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9937 
9938 		if (enab->dten_vstate->dtvs_state != state)
9939 			continue;
9940 
9941 		if ((err = dtrace_enabling_match(enab, &matched)) != 0)
9942 			return (err);
9943 
9944 		total += matched;
9945 	}
9946 
9947 	if (nmatched != NULL)
9948 		*nmatched = total;
9949 
9950 	return (0);
9951 }
9952 
9953 /*
9954  * If an enabling is to be enabled without having matched probes (that is, if
9955  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
9956  * enabling must be _primed_ by creating an ECB for every ECB description.
9957  * This must be done to assure that we know the number of speculations, the
9958  * number of aggregations, the minimum buffer size needed, etc. before we
9959  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
9960  * enabling any probes, we create ECBs for every ECB decription, but with a
9961  * NULL probe -- which is exactly what this function does.
9962  */
9963 static void
9964 dtrace_enabling_prime(dtrace_state_t *state)
9965 {
9966 	dtrace_enabling_t *enab;
9967 	int i;
9968 
9969 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
9970 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9971 
9972 		if (enab->dten_vstate->dtvs_state != state)
9973 			continue;
9974 
9975 		/*
9976 		 * We don't want to prime an enabling more than once, lest
9977 		 * we allow a malicious user to induce resource exhaustion.
9978 		 * (The ECBs that result from priming an enabling aren't
9979 		 * leaked -- but they also aren't deallocated until the
9980 		 * consumer state is destroyed.)
9981 		 */
9982 		if (enab->dten_primed)
9983 			continue;
9984 
9985 		for (i = 0; i < enab->dten_ndesc; i++) {
9986 			enab->dten_current = enab->dten_desc[i];
9987 			(void) dtrace_probe_enable(NULL, enab);
9988 		}
9989 
9990 		enab->dten_primed = 1;
9991 	}
9992 }
9993 
9994 /*
9995  * Called to indicate that probes should be provided due to retained
9996  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
9997  * must take an initial lap through the enabling calling the dtps_provide()
9998  * entry point explicitly to allow for autocreated probes.
9999  */
10000 static void
10001 dtrace_enabling_provide(dtrace_provider_t *prv)
10002 {
10003 	int i, all = 0;
10004 	dtrace_probedesc_t desc;
10005 
10006 	ASSERT(MUTEX_HELD(&dtrace_lock));
10007 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
10008 
10009 	if (prv == NULL) {
10010 		all = 1;
10011 		prv = dtrace_provider;
10012 	}
10013 
10014 	do {
10015 		dtrace_enabling_t *enab = dtrace_retained;
10016 		void *parg = prv->dtpv_arg;
10017 
10018 		for (; enab != NULL; enab = enab->dten_next) {
10019 			for (i = 0; i < enab->dten_ndesc; i++) {
10020 				desc = enab->dten_desc[i]->dted_probe;
10021 				mutex_exit(&dtrace_lock);
10022 				prv->dtpv_pops.dtps_provide(parg, &desc);
10023 				mutex_enter(&dtrace_lock);
10024 			}
10025 		}
10026 	} while (all && (prv = prv->dtpv_next) != NULL);
10027 
10028 	mutex_exit(&dtrace_lock);
10029 	dtrace_probe_provide(NULL, all ? NULL : prv);
10030 	mutex_enter(&dtrace_lock);
10031 }
10032 
10033 /*
10034  * DTrace DOF Functions
10035  */
10036 /*ARGSUSED*/
10037 static void
10038 dtrace_dof_error(dof_hdr_t *dof, const char *str)
10039 {
10040 	if (dtrace_err_verbose)
10041 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
10042 
10043 #ifdef DTRACE_ERRDEBUG
10044 	dtrace_errdebug(str);
10045 #endif
10046 }
10047 
10048 /*
10049  * Create DOF out of a currently enabled state.  Right now, we only create
10050  * DOF containing the run-time options -- but this could be expanded to create
10051  * complete DOF representing the enabled state.
10052  */
10053 static dof_hdr_t *
10054 dtrace_dof_create(dtrace_state_t *state)
10055 {
10056 	dof_hdr_t *dof;
10057 	dof_sec_t *sec;
10058 	dof_optdesc_t *opt;
10059 	int i, len = sizeof (dof_hdr_t) +
10060 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
10061 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10062 
10063 	ASSERT(MUTEX_HELD(&dtrace_lock));
10064 
10065 	dof = kmem_zalloc(len, KM_SLEEP);
10066 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
10067 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
10068 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
10069 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
10070 
10071 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
10072 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
10073 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
10074 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
10075 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
10076 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
10077 
10078 	dof->dofh_flags = 0;
10079 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
10080 	dof->dofh_secsize = sizeof (dof_sec_t);
10081 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
10082 	dof->dofh_secoff = sizeof (dof_hdr_t);
10083 	dof->dofh_loadsz = len;
10084 	dof->dofh_filesz = len;
10085 	dof->dofh_pad = 0;
10086 
10087 	/*
10088 	 * Fill in the option section header...
10089 	 */
10090 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
10091 	sec->dofs_type = DOF_SECT_OPTDESC;
10092 	sec->dofs_align = sizeof (uint64_t);
10093 	sec->dofs_flags = DOF_SECF_LOAD;
10094 	sec->dofs_entsize = sizeof (dof_optdesc_t);
10095 
10096 	opt = (dof_optdesc_t *)((uintptr_t)sec +
10097 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
10098 
10099 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
10100 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10101 
10102 	for (i = 0; i < DTRACEOPT_MAX; i++) {
10103 		opt[i].dofo_option = i;
10104 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
10105 		opt[i].dofo_value = state->dts_options[i];
10106 	}
10107 
10108 	return (dof);
10109 }
10110 
10111 static dof_hdr_t *
10112 dtrace_dof_copyin(uintptr_t uarg, int *errp)
10113 {
10114 	dof_hdr_t hdr, *dof;
10115 
10116 	ASSERT(!MUTEX_HELD(&dtrace_lock));
10117 
10118 	/*
10119 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
10120 	 */
10121 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
10122 		dtrace_dof_error(NULL, "failed to copyin DOF header");
10123 		*errp = EFAULT;
10124 		return (NULL);
10125 	}
10126 
10127 	/*
10128 	 * Now we'll allocate the entire DOF and copy it in -- provided
10129 	 * that the length isn't outrageous.
10130 	 */
10131 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
10132 		dtrace_dof_error(&hdr, "load size exceeds maximum");
10133 		*errp = E2BIG;
10134 		return (NULL);
10135 	}
10136 
10137 	if (hdr.dofh_loadsz < sizeof (hdr)) {
10138 		dtrace_dof_error(&hdr, "invalid load size");
10139 		*errp = EINVAL;
10140 		return (NULL);
10141 	}
10142 
10143 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
10144 
10145 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
10146 		kmem_free(dof, hdr.dofh_loadsz);
10147 		*errp = EFAULT;
10148 		return (NULL);
10149 	}
10150 
10151 	return (dof);
10152 }
10153 
10154 static dof_hdr_t *
10155 dtrace_dof_property(const char *name)
10156 {
10157 	uchar_t *buf;
10158 	uint64_t loadsz;
10159 	unsigned int len, i;
10160 	dof_hdr_t *dof;
10161 
10162 	/*
10163 	 * Unfortunately, array of values in .conf files are always (and
10164 	 * only) interpreted to be integer arrays.  We must read our DOF
10165 	 * as an integer array, and then squeeze it into a byte array.
10166 	 */
10167 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
10168 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
10169 		return (NULL);
10170 
10171 	for (i = 0; i < len; i++)
10172 		buf[i] = (uchar_t)(((int *)buf)[i]);
10173 
10174 	if (len < sizeof (dof_hdr_t)) {
10175 		ddi_prop_free(buf);
10176 		dtrace_dof_error(NULL, "truncated header");
10177 		return (NULL);
10178 	}
10179 
10180 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
10181 		ddi_prop_free(buf);
10182 		dtrace_dof_error(NULL, "truncated DOF");
10183 		return (NULL);
10184 	}
10185 
10186 	if (loadsz >= dtrace_dof_maxsize) {
10187 		ddi_prop_free(buf);
10188 		dtrace_dof_error(NULL, "oversized DOF");
10189 		return (NULL);
10190 	}
10191 
10192 	dof = kmem_alloc(loadsz, KM_SLEEP);
10193 	bcopy(buf, dof, loadsz);
10194 	ddi_prop_free(buf);
10195 
10196 	return (dof);
10197 }
10198 
10199 static void
10200 dtrace_dof_destroy(dof_hdr_t *dof)
10201 {
10202 	kmem_free(dof, dof->dofh_loadsz);
10203 }
10204 
10205 /*
10206  * Return the dof_sec_t pointer corresponding to a given section index.  If the
10207  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
10208  * a type other than DOF_SECT_NONE is specified, the header is checked against
10209  * this type and NULL is returned if the types do not match.
10210  */
10211 static dof_sec_t *
10212 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
10213 {
10214 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
10215 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
10216 
10217 	if (i >= dof->dofh_secnum) {
10218 		dtrace_dof_error(dof, "referenced section index is invalid");
10219 		return (NULL);
10220 	}
10221 
10222 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
10223 		dtrace_dof_error(dof, "referenced section is not loadable");
10224 		return (NULL);
10225 	}
10226 
10227 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
10228 		dtrace_dof_error(dof, "referenced section is the wrong type");
10229 		return (NULL);
10230 	}
10231 
10232 	return (sec);
10233 }
10234 
10235 static dtrace_probedesc_t *
10236 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
10237 {
10238 	dof_probedesc_t *probe;
10239 	dof_sec_t *strtab;
10240 	uintptr_t daddr = (uintptr_t)dof;
10241 	uintptr_t str;
10242 	size_t size;
10243 
10244 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
10245 		dtrace_dof_error(dof, "invalid probe section");
10246 		return (NULL);
10247 	}
10248 
10249 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
10250 		dtrace_dof_error(dof, "bad alignment in probe description");
10251 		return (NULL);
10252 	}
10253 
10254 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
10255 		dtrace_dof_error(dof, "truncated probe description");
10256 		return (NULL);
10257 	}
10258 
10259 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
10260 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
10261 
10262 	if (strtab == NULL)
10263 		return (NULL);
10264 
10265 	str = daddr + strtab->dofs_offset;
10266 	size = strtab->dofs_size;
10267 
10268 	if (probe->dofp_provider >= strtab->dofs_size) {
10269 		dtrace_dof_error(dof, "corrupt probe provider");
10270 		return (NULL);
10271 	}
10272 
10273 	(void) strncpy(desc->dtpd_provider,
10274 	    (char *)(str + probe->dofp_provider),
10275 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
10276 
10277 	if (probe->dofp_mod >= strtab->dofs_size) {
10278 		dtrace_dof_error(dof, "corrupt probe module");
10279 		return (NULL);
10280 	}
10281 
10282 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
10283 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
10284 
10285 	if (probe->dofp_func >= strtab->dofs_size) {
10286 		dtrace_dof_error(dof, "corrupt probe function");
10287 		return (NULL);
10288 	}
10289 
10290 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
10291 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
10292 
10293 	if (probe->dofp_name >= strtab->dofs_size) {
10294 		dtrace_dof_error(dof, "corrupt probe name");
10295 		return (NULL);
10296 	}
10297 
10298 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
10299 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
10300 
10301 	return (desc);
10302 }
10303 
10304 static dtrace_difo_t *
10305 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10306     cred_t *cr)
10307 {
10308 	dtrace_difo_t *dp;
10309 	size_t ttl = 0;
10310 	dof_difohdr_t *dofd;
10311 	uintptr_t daddr = (uintptr_t)dof;
10312 	size_t max = dtrace_difo_maxsize;
10313 	int i, l, n;
10314 
10315 	static const struct {
10316 		int section;
10317 		int bufoffs;
10318 		int lenoffs;
10319 		int entsize;
10320 		int align;
10321 		const char *msg;
10322 	} difo[] = {
10323 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
10324 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
10325 		sizeof (dif_instr_t), "multiple DIF sections" },
10326 
10327 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
10328 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
10329 		sizeof (uint64_t), "multiple integer tables" },
10330 
10331 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
10332 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
10333 		sizeof (char), "multiple string tables" },
10334 
10335 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
10336 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
10337 		sizeof (uint_t), "multiple variable tables" },
10338 
10339 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
10340 	};
10341 
10342 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
10343 		dtrace_dof_error(dof, "invalid DIFO header section");
10344 		return (NULL);
10345 	}
10346 
10347 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
10348 		dtrace_dof_error(dof, "bad alignment in DIFO header");
10349 		return (NULL);
10350 	}
10351 
10352 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
10353 	    sec->dofs_size % sizeof (dof_secidx_t)) {
10354 		dtrace_dof_error(dof, "bad size in DIFO header");
10355 		return (NULL);
10356 	}
10357 
10358 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
10359 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
10360 
10361 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10362 	dp->dtdo_rtype = dofd->dofd_rtype;
10363 
10364 	for (l = 0; l < n; l++) {
10365 		dof_sec_t *subsec;
10366 		void **bufp;
10367 		uint32_t *lenp;
10368 
10369 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
10370 		    dofd->dofd_links[l])) == NULL)
10371 			goto err; /* invalid section link */
10372 
10373 		if (ttl + subsec->dofs_size > max) {
10374 			dtrace_dof_error(dof, "exceeds maximum size");
10375 			goto err;
10376 		}
10377 
10378 		ttl += subsec->dofs_size;
10379 
10380 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
10381 			if (subsec->dofs_type != difo[i].section)
10382 				continue;
10383 
10384 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
10385 				dtrace_dof_error(dof, "section not loaded");
10386 				goto err;
10387 			}
10388 
10389 			if (subsec->dofs_align != difo[i].align) {
10390 				dtrace_dof_error(dof, "bad alignment");
10391 				goto err;
10392 			}
10393 
10394 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
10395 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
10396 
10397 			if (*bufp != NULL) {
10398 				dtrace_dof_error(dof, difo[i].msg);
10399 				goto err;
10400 			}
10401 
10402 			if (difo[i].entsize != subsec->dofs_entsize) {
10403 				dtrace_dof_error(dof, "entry size mismatch");
10404 				goto err;
10405 			}
10406 
10407 			if (subsec->dofs_entsize != 0 &&
10408 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
10409 				dtrace_dof_error(dof, "corrupt entry size");
10410 				goto err;
10411 			}
10412 
10413 			*lenp = subsec->dofs_size;
10414 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
10415 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
10416 			    *bufp, subsec->dofs_size);
10417 
10418 			if (subsec->dofs_entsize != 0)
10419 				*lenp /= subsec->dofs_entsize;
10420 
10421 			break;
10422 		}
10423 
10424 		/*
10425 		 * If we encounter a loadable DIFO sub-section that is not
10426 		 * known to us, assume this is a broken program and fail.
10427 		 */
10428 		if (difo[i].section == DOF_SECT_NONE &&
10429 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
10430 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
10431 			goto err;
10432 		}
10433 	}
10434 
10435 	if (dp->dtdo_buf == NULL) {
10436 		/*
10437 		 * We can't have a DIF object without DIF text.
10438 		 */
10439 		dtrace_dof_error(dof, "missing DIF text");
10440 		goto err;
10441 	}
10442 
10443 	/*
10444 	 * Before we validate the DIF object, run through the variable table
10445 	 * looking for the strings -- if any of their size are under, we'll set
10446 	 * their size to be the system-wide default string size.  Note that
10447 	 * this should _not_ happen if the "strsize" option has been set --
10448 	 * in this case, the compiler should have set the size to reflect the
10449 	 * setting of the option.
10450 	 */
10451 	for (i = 0; i < dp->dtdo_varlen; i++) {
10452 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10453 		dtrace_diftype_t *t = &v->dtdv_type;
10454 
10455 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
10456 			continue;
10457 
10458 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
10459 			t->dtdt_size = dtrace_strsize_default;
10460 	}
10461 
10462 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
10463 		goto err;
10464 
10465 	dtrace_difo_init(dp, vstate);
10466 	return (dp);
10467 
10468 err:
10469 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10470 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10471 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10472 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10473 
10474 	kmem_free(dp, sizeof (dtrace_difo_t));
10475 	return (NULL);
10476 }
10477 
10478 static dtrace_predicate_t *
10479 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10480     cred_t *cr)
10481 {
10482 	dtrace_difo_t *dp;
10483 
10484 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
10485 		return (NULL);
10486 
10487 	return (dtrace_predicate_create(dp));
10488 }
10489 
10490 static dtrace_actdesc_t *
10491 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10492     cred_t *cr)
10493 {
10494 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
10495 	dof_actdesc_t *desc;
10496 	dof_sec_t *difosec;
10497 	size_t offs;
10498 	uintptr_t daddr = (uintptr_t)dof;
10499 	uint64_t arg;
10500 	dtrace_actkind_t kind;
10501 
10502 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
10503 		dtrace_dof_error(dof, "invalid action section");
10504 		return (NULL);
10505 	}
10506 
10507 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
10508 		dtrace_dof_error(dof, "truncated action description");
10509 		return (NULL);
10510 	}
10511 
10512 	if (sec->dofs_align != sizeof (uint64_t)) {
10513 		dtrace_dof_error(dof, "bad alignment in action description");
10514 		return (NULL);
10515 	}
10516 
10517 	if (sec->dofs_size < sec->dofs_entsize) {
10518 		dtrace_dof_error(dof, "section entry size exceeds total size");
10519 		return (NULL);
10520 	}
10521 
10522 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
10523 		dtrace_dof_error(dof, "bad entry size in action description");
10524 		return (NULL);
10525 	}
10526 
10527 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
10528 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
10529 		return (NULL);
10530 	}
10531 
10532 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
10533 		desc = (dof_actdesc_t *)(daddr +
10534 		    (uintptr_t)sec->dofs_offset + offs);
10535 		kind = (dtrace_actkind_t)desc->dofa_kind;
10536 
10537 		if (DTRACEACT_ISPRINTFLIKE(kind) &&
10538 		    (kind != DTRACEACT_PRINTA ||
10539 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
10540 			dof_sec_t *strtab;
10541 			char *str, *fmt;
10542 			uint64_t i;
10543 
10544 			/*
10545 			 * printf()-like actions must have a format string.
10546 			 */
10547 			if ((strtab = dtrace_dof_sect(dof,
10548 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
10549 				goto err;
10550 
10551 			str = (char *)((uintptr_t)dof +
10552 			    (uintptr_t)strtab->dofs_offset);
10553 
10554 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
10555 				if (str[i] == '\0')
10556 					break;
10557 			}
10558 
10559 			if (i >= strtab->dofs_size) {
10560 				dtrace_dof_error(dof, "bogus format string");
10561 				goto err;
10562 			}
10563 
10564 			if (i == desc->dofa_arg) {
10565 				dtrace_dof_error(dof, "empty format string");
10566 				goto err;
10567 			}
10568 
10569 			i -= desc->dofa_arg;
10570 			fmt = kmem_alloc(i + 1, KM_SLEEP);
10571 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
10572 			arg = (uint64_t)(uintptr_t)fmt;
10573 		} else {
10574 			if (kind == DTRACEACT_PRINTA) {
10575 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
10576 				arg = 0;
10577 			} else {
10578 				arg = desc->dofa_arg;
10579 			}
10580 		}
10581 
10582 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
10583 		    desc->dofa_uarg, arg);
10584 
10585 		if (last != NULL) {
10586 			last->dtad_next = act;
10587 		} else {
10588 			first = act;
10589 		}
10590 
10591 		last = act;
10592 
10593 		if (desc->dofa_difo == DOF_SECIDX_NONE)
10594 			continue;
10595 
10596 		if ((difosec = dtrace_dof_sect(dof,
10597 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
10598 			goto err;
10599 
10600 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
10601 
10602 		if (act->dtad_difo == NULL)
10603 			goto err;
10604 	}
10605 
10606 	ASSERT(first != NULL);
10607 	return (first);
10608 
10609 err:
10610 	for (act = first; act != NULL; act = next) {
10611 		next = act->dtad_next;
10612 		dtrace_actdesc_release(act, vstate);
10613 	}
10614 
10615 	return (NULL);
10616 }
10617 
10618 static dtrace_ecbdesc_t *
10619 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10620     cred_t *cr)
10621 {
10622 	dtrace_ecbdesc_t *ep;
10623 	dof_ecbdesc_t *ecb;
10624 	dtrace_probedesc_t *desc;
10625 	dtrace_predicate_t *pred = NULL;
10626 
10627 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
10628 		dtrace_dof_error(dof, "truncated ECB description");
10629 		return (NULL);
10630 	}
10631 
10632 	if (sec->dofs_align != sizeof (uint64_t)) {
10633 		dtrace_dof_error(dof, "bad alignment in ECB description");
10634 		return (NULL);
10635 	}
10636 
10637 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
10638 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
10639 
10640 	if (sec == NULL)
10641 		return (NULL);
10642 
10643 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
10644 	ep->dted_uarg = ecb->dofe_uarg;
10645 	desc = &ep->dted_probe;
10646 
10647 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
10648 		goto err;
10649 
10650 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
10651 		if ((sec = dtrace_dof_sect(dof,
10652 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
10653 			goto err;
10654 
10655 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
10656 			goto err;
10657 
10658 		ep->dted_pred.dtpdd_predicate = pred;
10659 	}
10660 
10661 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
10662 		if ((sec = dtrace_dof_sect(dof,
10663 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
10664 			goto err;
10665 
10666 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
10667 
10668 		if (ep->dted_action == NULL)
10669 			goto err;
10670 	}
10671 
10672 	return (ep);
10673 
10674 err:
10675 	if (pred != NULL)
10676 		dtrace_predicate_release(pred, vstate);
10677 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
10678 	return (NULL);
10679 }
10680 
10681 /*
10682  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
10683  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
10684  * site of any user SETX relocations to account for load object base address.
10685  * In the future, if we need other relocations, this function can be extended.
10686  */
10687 static int
10688 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
10689 {
10690 	uintptr_t daddr = (uintptr_t)dof;
10691 	dof_relohdr_t *dofr =
10692 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
10693 	dof_sec_t *ss, *rs, *ts;
10694 	dof_relodesc_t *r;
10695 	uint_t i, n;
10696 
10697 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
10698 	    sec->dofs_align != sizeof (dof_secidx_t)) {
10699 		dtrace_dof_error(dof, "invalid relocation header");
10700 		return (-1);
10701 	}
10702 
10703 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
10704 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
10705 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
10706 
10707 	if (ss == NULL || rs == NULL || ts == NULL)
10708 		return (-1); /* dtrace_dof_error() has been called already */
10709 
10710 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
10711 	    rs->dofs_align != sizeof (uint64_t)) {
10712 		dtrace_dof_error(dof, "invalid relocation section");
10713 		return (-1);
10714 	}
10715 
10716 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
10717 	n = rs->dofs_size / rs->dofs_entsize;
10718 
10719 	for (i = 0; i < n; i++) {
10720 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
10721 
10722 		switch (r->dofr_type) {
10723 		case DOF_RELO_NONE:
10724 			break;
10725 		case DOF_RELO_SETX:
10726 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
10727 			    sizeof (uint64_t) > ts->dofs_size) {
10728 				dtrace_dof_error(dof, "bad relocation offset");
10729 				return (-1);
10730 			}
10731 
10732 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
10733 				dtrace_dof_error(dof, "misaligned setx relo");
10734 				return (-1);
10735 			}
10736 
10737 			*(uint64_t *)taddr += ubase;
10738 			break;
10739 		default:
10740 			dtrace_dof_error(dof, "invalid relocation type");
10741 			return (-1);
10742 		}
10743 
10744 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
10745 	}
10746 
10747 	return (0);
10748 }
10749 
10750 /*
10751  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
10752  * header:  it should be at the front of a memory region that is at least
10753  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
10754  * size.  It need not be validated in any other way.
10755  */
10756 static int
10757 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
10758     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
10759 {
10760 	uint64_t len = dof->dofh_loadsz, seclen;
10761 	uintptr_t daddr = (uintptr_t)dof;
10762 	dtrace_ecbdesc_t *ep;
10763 	dtrace_enabling_t *enab;
10764 	uint_t i;
10765 
10766 	ASSERT(MUTEX_HELD(&dtrace_lock));
10767 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
10768 
10769 	/*
10770 	 * Check the DOF header identification bytes.  In addition to checking
10771 	 * valid settings, we also verify that unused bits/bytes are zeroed so
10772 	 * we can use them later without fear of regressing existing binaries.
10773 	 */
10774 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
10775 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
10776 		dtrace_dof_error(dof, "DOF magic string mismatch");
10777 		return (-1);
10778 	}
10779 
10780 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
10781 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
10782 		dtrace_dof_error(dof, "DOF has invalid data model");
10783 		return (-1);
10784 	}
10785 
10786 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
10787 		dtrace_dof_error(dof, "DOF encoding mismatch");
10788 		return (-1);
10789 	}
10790 
10791 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
10792 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
10793 		dtrace_dof_error(dof, "DOF version mismatch");
10794 		return (-1);
10795 	}
10796 
10797 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
10798 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
10799 		return (-1);
10800 	}
10801 
10802 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
10803 		dtrace_dof_error(dof, "DOF uses too many integer registers");
10804 		return (-1);
10805 	}
10806 
10807 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
10808 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
10809 		return (-1);
10810 	}
10811 
10812 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
10813 		if (dof->dofh_ident[i] != 0) {
10814 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
10815 			return (-1);
10816 		}
10817 	}
10818 
10819 	if (dof->dofh_flags & ~DOF_FL_VALID) {
10820 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
10821 		return (-1);
10822 	}
10823 
10824 	if (dof->dofh_secsize == 0) {
10825 		dtrace_dof_error(dof, "zero section header size");
10826 		return (-1);
10827 	}
10828 
10829 	/*
10830 	 * Check that the section headers don't exceed the amount of DOF
10831 	 * data.  Note that we cast the section size and number of sections
10832 	 * to uint64_t's to prevent possible overflow in the multiplication.
10833 	 */
10834 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
10835 
10836 	if (dof->dofh_secoff > len || seclen > len ||
10837 	    dof->dofh_secoff + seclen > len) {
10838 		dtrace_dof_error(dof, "truncated section headers");
10839 		return (-1);
10840 	}
10841 
10842 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
10843 		dtrace_dof_error(dof, "misaligned section headers");
10844 		return (-1);
10845 	}
10846 
10847 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
10848 		dtrace_dof_error(dof, "misaligned section size");
10849 		return (-1);
10850 	}
10851 
10852 	/*
10853 	 * Take an initial pass through the section headers to be sure that
10854 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
10855 	 * set, do not permit sections relating to providers, probes, or args.
10856 	 */
10857 	for (i = 0; i < dof->dofh_secnum; i++) {
10858 		dof_sec_t *sec = (dof_sec_t *)(daddr +
10859 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
10860 
10861 		if (noprobes) {
10862 			switch (sec->dofs_type) {
10863 			case DOF_SECT_PROVIDER:
10864 			case DOF_SECT_PROBES:
10865 			case DOF_SECT_PRARGS:
10866 			case DOF_SECT_PROFFS:
10867 				dtrace_dof_error(dof, "illegal sections "
10868 				    "for enabling");
10869 				return (-1);
10870 			}
10871 		}
10872 
10873 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
10874 			continue; /* just ignore non-loadable sections */
10875 
10876 		if (sec->dofs_align & (sec->dofs_align - 1)) {
10877 			dtrace_dof_error(dof, "bad section alignment");
10878 			return (-1);
10879 		}
10880 
10881 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
10882 			dtrace_dof_error(dof, "misaligned section");
10883 			return (-1);
10884 		}
10885 
10886 		if (sec->dofs_offset > len || sec->dofs_size > len ||
10887 		    sec->dofs_offset + sec->dofs_size > len) {
10888 			dtrace_dof_error(dof, "corrupt section header");
10889 			return (-1);
10890 		}
10891 
10892 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
10893 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
10894 			dtrace_dof_error(dof, "non-terminating string table");
10895 			return (-1);
10896 		}
10897 	}
10898 
10899 	/*
10900 	 * Take a second pass through the sections and locate and perform any
10901 	 * relocations that are present.  We do this after the first pass to
10902 	 * be sure that all sections have had their headers validated.
10903 	 */
10904 	for (i = 0; i < dof->dofh_secnum; i++) {
10905 		dof_sec_t *sec = (dof_sec_t *)(daddr +
10906 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
10907 
10908 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
10909 			continue; /* skip sections that are not loadable */
10910 
10911 		switch (sec->dofs_type) {
10912 		case DOF_SECT_URELHDR:
10913 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
10914 				return (-1);
10915 			break;
10916 		}
10917 	}
10918 
10919 	if ((enab = *enabp) == NULL)
10920 		enab = *enabp = dtrace_enabling_create(vstate);
10921 
10922 	for (i = 0; i < dof->dofh_secnum; i++) {
10923 		dof_sec_t *sec = (dof_sec_t *)(daddr +
10924 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
10925 
10926 		if (sec->dofs_type != DOF_SECT_ECBDESC)
10927 			continue;
10928 
10929 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
10930 			dtrace_enabling_destroy(enab);
10931 			*enabp = NULL;
10932 			return (-1);
10933 		}
10934 
10935 		dtrace_enabling_add(enab, ep);
10936 	}
10937 
10938 	return (0);
10939 }
10940 
10941 /*
10942  * Process DOF for any options.  This routine assumes that the DOF has been
10943  * at least processed by dtrace_dof_slurp().
10944  */
10945 static int
10946 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
10947 {
10948 	int i, rval;
10949 	uint32_t entsize;
10950 	size_t offs;
10951 	dof_optdesc_t *desc;
10952 
10953 	for (i = 0; i < dof->dofh_secnum; i++) {
10954 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
10955 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
10956 
10957 		if (sec->dofs_type != DOF_SECT_OPTDESC)
10958 			continue;
10959 
10960 		if (sec->dofs_align != sizeof (uint64_t)) {
10961 			dtrace_dof_error(dof, "bad alignment in "
10962 			    "option description");
10963 			return (EINVAL);
10964 		}
10965 
10966 		if ((entsize = sec->dofs_entsize) == 0) {
10967 			dtrace_dof_error(dof, "zeroed option entry size");
10968 			return (EINVAL);
10969 		}
10970 
10971 		if (entsize < sizeof (dof_optdesc_t)) {
10972 			dtrace_dof_error(dof, "bad option entry size");
10973 			return (EINVAL);
10974 		}
10975 
10976 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
10977 			desc = (dof_optdesc_t *)((uintptr_t)dof +
10978 			    (uintptr_t)sec->dofs_offset + offs);
10979 
10980 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
10981 				dtrace_dof_error(dof, "non-zero option string");
10982 				return (EINVAL);
10983 			}
10984 
10985 			if (desc->dofo_value == DTRACEOPT_UNSET) {
10986 				dtrace_dof_error(dof, "unset option");
10987 				return (EINVAL);
10988 			}
10989 
10990 			if ((rval = dtrace_state_option(state,
10991 			    desc->dofo_option, desc->dofo_value)) != 0) {
10992 				dtrace_dof_error(dof, "rejected option");
10993 				return (rval);
10994 			}
10995 		}
10996 	}
10997 
10998 	return (0);
10999 }
11000 
11001 /*
11002  * DTrace Consumer State Functions
11003  */
11004 int
11005 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
11006 {
11007 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
11008 	void *base;
11009 	uintptr_t limit;
11010 	dtrace_dynvar_t *dvar, *next, *start;
11011 	int i;
11012 
11013 	ASSERT(MUTEX_HELD(&dtrace_lock));
11014 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
11015 
11016 	bzero(dstate, sizeof (dtrace_dstate_t));
11017 
11018 	if ((dstate->dtds_chunksize = chunksize) == 0)
11019 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
11020 
11021 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
11022 		size = min;
11023 
11024 	if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11025 		return (ENOMEM);
11026 
11027 	dstate->dtds_size = size;
11028 	dstate->dtds_base = base;
11029 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
11030 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
11031 
11032 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
11033 
11034 	if (hashsize != 1 && (hashsize & 1))
11035 		hashsize--;
11036 
11037 	dstate->dtds_hashsize = hashsize;
11038 	dstate->dtds_hash = dstate->dtds_base;
11039 
11040 	/*
11041 	 * Set all of our hash buckets to point to the single sink, and (if
11042 	 * it hasn't already been set), set the sink's hash value to be the
11043 	 * sink sentinel value.  The sink is needed for dynamic variable
11044 	 * lookups to know that they have iterated over an entire, valid hash
11045 	 * chain.
11046 	 */
11047 	for (i = 0; i < hashsize; i++)
11048 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
11049 
11050 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
11051 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
11052 
11053 	/*
11054 	 * Determine number of active CPUs.  Divide free list evenly among
11055 	 * active CPUs.
11056 	 */
11057 	start = (dtrace_dynvar_t *)
11058 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
11059 	limit = (uintptr_t)base + size;
11060 
11061 	maxper = (limit - (uintptr_t)start) / NCPU;
11062 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
11063 
11064 	for (i = 0; i < NCPU; i++) {
11065 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
11066 
11067 		/*
11068 		 * If we don't even have enough chunks to make it once through
11069 		 * NCPUs, we're just going to allocate everything to the first
11070 		 * CPU.  And if we're on the last CPU, we're going to allocate
11071 		 * whatever is left over.  In either case, we set the limit to
11072 		 * be the limit of the dynamic variable space.
11073 		 */
11074 		if (maxper == 0 || i == NCPU - 1) {
11075 			limit = (uintptr_t)base + size;
11076 			start = NULL;
11077 		} else {
11078 			limit = (uintptr_t)start + maxper;
11079 			start = (dtrace_dynvar_t *)limit;
11080 		}
11081 
11082 		ASSERT(limit <= (uintptr_t)base + size);
11083 
11084 		for (;;) {
11085 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
11086 			    dstate->dtds_chunksize);
11087 
11088 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
11089 				break;
11090 
11091 			dvar->dtdv_next = next;
11092 			dvar = next;
11093 		}
11094 
11095 		if (maxper == 0)
11096 			break;
11097 	}
11098 
11099 	return (0);
11100 }
11101 
11102 void
11103 dtrace_dstate_fini(dtrace_dstate_t *dstate)
11104 {
11105 	ASSERT(MUTEX_HELD(&cpu_lock));
11106 
11107 	if (dstate->dtds_base == NULL)
11108 		return;
11109 
11110 	kmem_free(dstate->dtds_base, dstate->dtds_size);
11111 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
11112 }
11113 
11114 static void
11115 dtrace_vstate_fini(dtrace_vstate_t *vstate)
11116 {
11117 	/*
11118 	 * Logical XOR, where are you?
11119 	 */
11120 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
11121 
11122 	if (vstate->dtvs_nglobals > 0) {
11123 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
11124 		    sizeof (dtrace_statvar_t *));
11125 	}
11126 
11127 	if (vstate->dtvs_ntlocals > 0) {
11128 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
11129 		    sizeof (dtrace_difv_t));
11130 	}
11131 
11132 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
11133 
11134 	if (vstate->dtvs_nlocals > 0) {
11135 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
11136 		    sizeof (dtrace_statvar_t *));
11137 	}
11138 }
11139 
11140 static void
11141 dtrace_state_clean(dtrace_state_t *state)
11142 {
11143 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
11144 		return;
11145 
11146 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
11147 	dtrace_speculation_clean(state);
11148 }
11149 
11150 static void
11151 dtrace_state_deadman(dtrace_state_t *state)
11152 {
11153 	hrtime_t now;
11154 
11155 	dtrace_sync();
11156 
11157 	now = dtrace_gethrtime();
11158 
11159 	if (state != dtrace_anon.dta_state &&
11160 	    now - state->dts_laststatus >= dtrace_deadman_user)
11161 		return;
11162 
11163 	/*
11164 	 * We must be sure that dts_alive never appears to be less than the
11165 	 * value upon entry to dtrace_state_deadman(), and because we lack a
11166 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
11167 	 * store INT64_MAX to it, followed by a memory barrier, followed by
11168 	 * the new value.  This assures that dts_alive never appears to be
11169 	 * less than its true value, regardless of the order in which the
11170 	 * stores to the underlying storage are issued.
11171 	 */
11172 	state->dts_alive = INT64_MAX;
11173 	dtrace_membar_producer();
11174 	state->dts_alive = now;
11175 }
11176 
11177 dtrace_state_t *
11178 dtrace_state_create(dev_t *devp, cred_t *cr)
11179 {
11180 	minor_t minor;
11181 	major_t major;
11182 	char c[30];
11183 	dtrace_state_t *state;
11184 	dtrace_optval_t *opt;
11185 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
11186 
11187 	ASSERT(MUTEX_HELD(&dtrace_lock));
11188 	ASSERT(MUTEX_HELD(&cpu_lock));
11189 
11190 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
11191 	    VM_BESTFIT | VM_SLEEP);
11192 
11193 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
11194 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
11195 		return (NULL);
11196 	}
11197 
11198 	state = ddi_get_soft_state(dtrace_softstate, minor);
11199 	state->dts_epid = DTRACE_EPIDNONE + 1;
11200 
11201 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
11202 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
11203 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
11204 
11205 	if (devp != NULL) {
11206 		major = getemajor(*devp);
11207 	} else {
11208 		major = ddi_driver_major(dtrace_devi);
11209 	}
11210 
11211 	state->dts_dev = makedevice(major, minor);
11212 
11213 	if (devp != NULL)
11214 		*devp = state->dts_dev;
11215 
11216 	/*
11217 	 * We allocate NCPU buffers.  On the one hand, this can be quite
11218 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
11219 	 * other hand, it saves an additional memory reference in the probe
11220 	 * path.
11221 	 */
11222 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
11223 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
11224 	state->dts_cleaner = CYCLIC_NONE;
11225 	state->dts_deadman = CYCLIC_NONE;
11226 	state->dts_vstate.dtvs_state = state;
11227 
11228 	for (i = 0; i < DTRACEOPT_MAX; i++)
11229 		state->dts_options[i] = DTRACEOPT_UNSET;
11230 
11231 	/*
11232 	 * Set the default options.
11233 	 */
11234 	opt = state->dts_options;
11235 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
11236 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
11237 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
11238 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
11239 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
11240 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
11241 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
11242 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
11243 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
11244 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
11245 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
11246 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
11247 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
11248 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
11249 
11250 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
11251 
11252 	/*
11253 	 * Depending on the user credentials, we set flag bits which alter probe
11254 	 * visibility or the amount of destructiveness allowed.  In the case of
11255 	 * actual anonymous tracing, or the possession of all privileges, all of
11256 	 * the normal checks are bypassed.
11257 	 */
11258 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
11259 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
11260 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
11261 	} else {
11262 		/*
11263 		 * Set up the credentials for this instantiation.  We take a
11264 		 * hold on the credential to prevent it from disappearing on
11265 		 * us; this in turn prevents the zone_t referenced by this
11266 		 * credential from disappearing.  This means that we can
11267 		 * examine the credential and the zone from probe context.
11268 		 */
11269 		crhold(cr);
11270 		state->dts_cred.dcr_cred = cr;
11271 
11272 		/*
11273 		 * CRA_PROC means "we have *some* privilege for dtrace" and
11274 		 * unlocks the use of variables like pid, zonename, etc.
11275 		 */
11276 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
11277 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
11278 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
11279 		}
11280 
11281 		/*
11282 		 * dtrace_user allows use of syscall and profile providers.
11283 		 * If the user also has proc_owner and/or proc_zone, we
11284 		 * extend the scope to include additional visibility and
11285 		 * destructive power.
11286 		 */
11287 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
11288 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
11289 				state->dts_cred.dcr_visible |=
11290 				    DTRACE_CRV_ALLPROC;
11291 
11292 				state->dts_cred.dcr_action |=
11293 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
11294 			}
11295 
11296 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
11297 				state->dts_cred.dcr_visible |=
11298 				    DTRACE_CRV_ALLZONE;
11299 
11300 				state->dts_cred.dcr_action |=
11301 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
11302 			}
11303 
11304 			/*
11305 			 * If we have all privs in whatever zone this is,
11306 			 * we can do destructive things to processes which
11307 			 * have altered credentials.
11308 			 */
11309 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
11310 			    cr->cr_zone->zone_privset)) {
11311 				state->dts_cred.dcr_action |=
11312 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
11313 			}
11314 		}
11315 
11316 		/*
11317 		 * Holding the dtrace_kernel privilege also implies that
11318 		 * the user has the dtrace_user privilege from a visibility
11319 		 * perspective.  But without further privileges, some
11320 		 * destructive actions are not available.
11321 		 */
11322 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
11323 			/*
11324 			 * Make all probes in all zones visible.  However,
11325 			 * this doesn't mean that all actions become available
11326 			 * to all zones.
11327 			 */
11328 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
11329 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
11330 
11331 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
11332 			    DTRACE_CRA_PROC;
11333 			/*
11334 			 * Holding proc_owner means that destructive actions
11335 			 * for *this* zone are allowed.
11336 			 */
11337 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
11338 				state->dts_cred.dcr_action |=
11339 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
11340 
11341 			/*
11342 			 * Holding proc_zone means that destructive actions
11343 			 * for this user/group ID in all zones is allowed.
11344 			 */
11345 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
11346 				state->dts_cred.dcr_action |=
11347 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
11348 
11349 			/*
11350 			 * If we have all privs in whatever zone this is,
11351 			 * we can do destructive things to processes which
11352 			 * have altered credentials.
11353 			 */
11354 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
11355 			    cr->cr_zone->zone_privset)) {
11356 				state->dts_cred.dcr_action |=
11357 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
11358 			}
11359 		}
11360 
11361 		/*
11362 		 * Holding the dtrace_proc privilege gives control over fasttrap
11363 		 * and pid providers.  We need to grant wider destructive
11364 		 * privileges in the event that the user has proc_owner and/or
11365 		 * proc_zone.
11366 		 */
11367 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
11368 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
11369 				state->dts_cred.dcr_action |=
11370 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
11371 
11372 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
11373 				state->dts_cred.dcr_action |=
11374 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
11375 		}
11376 	}
11377 
11378 	return (state);
11379 }
11380 
11381 static int
11382 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
11383 {
11384 	dtrace_optval_t *opt = state->dts_options, size;
11385 	processorid_t cpu;
11386 	int flags = 0, rval;
11387 
11388 	ASSERT(MUTEX_HELD(&dtrace_lock));
11389 	ASSERT(MUTEX_HELD(&cpu_lock));
11390 	ASSERT(which < DTRACEOPT_MAX);
11391 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
11392 	    (state == dtrace_anon.dta_state &&
11393 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
11394 
11395 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
11396 		return (0);
11397 
11398 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
11399 		cpu = opt[DTRACEOPT_CPU];
11400 
11401 	if (which == DTRACEOPT_SPECSIZE)
11402 		flags |= DTRACEBUF_NOSWITCH;
11403 
11404 	if (which == DTRACEOPT_BUFSIZE) {
11405 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
11406 			flags |= DTRACEBUF_RING;
11407 
11408 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
11409 			flags |= DTRACEBUF_FILL;
11410 
11411 		flags |= DTRACEBUF_INACTIVE;
11412 	}
11413 
11414 	for (size = opt[which]; size >= sizeof (uint64_t); size >>= 1) {
11415 		/*
11416 		 * The size must be 8-byte aligned.  If the size is not 8-byte
11417 		 * aligned, drop it down by the difference.
11418 		 */
11419 		if (size & (sizeof (uint64_t) - 1))
11420 			size -= size & (sizeof (uint64_t) - 1);
11421 
11422 		if (size < state->dts_reserve) {
11423 			/*
11424 			 * Buffers always must be large enough to accommodate
11425 			 * their prereserved space.  We return E2BIG instead
11426 			 * of ENOMEM in this case to allow for user-level
11427 			 * software to differentiate the cases.
11428 			 */
11429 			return (E2BIG);
11430 		}
11431 
11432 		rval = dtrace_buffer_alloc(buf, size, flags, cpu);
11433 
11434 		if (rval != ENOMEM) {
11435 			opt[which] = size;
11436 			return (rval);
11437 		}
11438 
11439 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
11440 			return (rval);
11441 	}
11442 
11443 	return (ENOMEM);
11444 }
11445 
11446 static int
11447 dtrace_state_buffers(dtrace_state_t *state)
11448 {
11449 	dtrace_speculation_t *spec = state->dts_speculations;
11450 	int rval, i;
11451 
11452 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
11453 	    DTRACEOPT_BUFSIZE)) != 0)
11454 		return (rval);
11455 
11456 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
11457 	    DTRACEOPT_AGGSIZE)) != 0)
11458 		return (rval);
11459 
11460 	for (i = 0; i < state->dts_nspeculations; i++) {
11461 		if ((rval = dtrace_state_buffer(state,
11462 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
11463 			return (rval);
11464 	}
11465 
11466 	return (0);
11467 }
11468 
11469 static void
11470 dtrace_state_prereserve(dtrace_state_t *state)
11471 {
11472 	dtrace_ecb_t *ecb;
11473 	dtrace_probe_t *probe;
11474 
11475 	state->dts_reserve = 0;
11476 
11477 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
11478 		return;
11479 
11480 	/*
11481 	 * If our buffer policy is a "fill" buffer policy, we need to set the
11482 	 * prereserved space to be the space required by the END probes.
11483 	 */
11484 	probe = dtrace_probes[dtrace_probeid_end - 1];
11485 	ASSERT(probe != NULL);
11486 
11487 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
11488 		if (ecb->dte_state != state)
11489 			continue;
11490 
11491 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
11492 	}
11493 }
11494 
11495 static int
11496 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
11497 {
11498 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
11499 	dtrace_speculation_t *spec;
11500 	dtrace_buffer_t *buf;
11501 	cyc_handler_t hdlr;
11502 	cyc_time_t when;
11503 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
11504 	dtrace_icookie_t cookie;
11505 
11506 	mutex_enter(&cpu_lock);
11507 	mutex_enter(&dtrace_lock);
11508 
11509 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
11510 		rval = EBUSY;
11511 		goto out;
11512 	}
11513 
11514 	/*
11515 	 * Before we can perform any checks, we must prime all of the
11516 	 * retained enablings that correspond to this state.
11517 	 */
11518 	dtrace_enabling_prime(state);
11519 
11520 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
11521 		rval = EACCES;
11522 		goto out;
11523 	}
11524 
11525 	dtrace_state_prereserve(state);
11526 
11527 	/*
11528 	 * Now we want to do is try to allocate our speculations.
11529 	 * We do not automatically resize the number of speculations; if
11530 	 * this fails, we will fail the operation.
11531 	 */
11532 	nspec = opt[DTRACEOPT_NSPEC];
11533 	ASSERT(nspec != DTRACEOPT_UNSET);
11534 
11535 	if (nspec > INT_MAX) {
11536 		rval = ENOMEM;
11537 		goto out;
11538 	}
11539 
11540 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
11541 
11542 	if (spec == NULL) {
11543 		rval = ENOMEM;
11544 		goto out;
11545 	}
11546 
11547 	state->dts_speculations = spec;
11548 	state->dts_nspeculations = (int)nspec;
11549 
11550 	for (i = 0; i < nspec; i++) {
11551 		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
11552 			rval = ENOMEM;
11553 			goto err;
11554 		}
11555 
11556 		spec[i].dtsp_buffer = buf;
11557 	}
11558 
11559 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
11560 		if (dtrace_anon.dta_state == NULL) {
11561 			rval = ENOENT;
11562 			goto out;
11563 		}
11564 
11565 		if (state->dts_necbs != 0) {
11566 			rval = EALREADY;
11567 			goto out;
11568 		}
11569 
11570 		state->dts_anon = dtrace_anon_grab();
11571 		ASSERT(state->dts_anon != NULL);
11572 		state = state->dts_anon;
11573 
11574 		/*
11575 		 * We want "grabanon" to be set in the grabbed state, so we'll
11576 		 * copy that option value from the grabbing state into the
11577 		 * grabbed state.
11578 		 */
11579 		state->dts_options[DTRACEOPT_GRABANON] =
11580 		    opt[DTRACEOPT_GRABANON];
11581 
11582 		*cpu = dtrace_anon.dta_beganon;
11583 
11584 		/*
11585 		 * If the anonymous state is active (as it almost certainly
11586 		 * is if the anonymous enabling ultimately matched anything),
11587 		 * we don't allow any further option processing -- but we
11588 		 * don't return failure.
11589 		 */
11590 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11591 			goto out;
11592 	}
11593 
11594 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
11595 	    opt[DTRACEOPT_AGGSIZE] != 0) {
11596 		if (state->dts_aggregations == NULL) {
11597 			/*
11598 			 * We're not going to create an aggregation buffer
11599 			 * because we don't have any ECBs that contain
11600 			 * aggregations -- set this option to 0.
11601 			 */
11602 			opt[DTRACEOPT_AGGSIZE] = 0;
11603 		} else {
11604 			/*
11605 			 * If we have an aggregation buffer, we must also have
11606 			 * a buffer to use as scratch.
11607 			 */
11608 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
11609 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
11610 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
11611 			}
11612 		}
11613 	}
11614 
11615 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
11616 	    opt[DTRACEOPT_SPECSIZE] != 0) {
11617 		if (!state->dts_speculates) {
11618 			/*
11619 			 * We're not going to create speculation buffers
11620 			 * because we don't have any ECBs that actually
11621 			 * speculate -- set the speculation size to 0.
11622 			 */
11623 			opt[DTRACEOPT_SPECSIZE] = 0;
11624 		}
11625 	}
11626 
11627 	/*
11628 	 * The bare minimum size for any buffer that we're actually going to
11629 	 * do anything to is sizeof (uint64_t).
11630 	 */
11631 	sz = sizeof (uint64_t);
11632 
11633 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
11634 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
11635 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
11636 		/*
11637 		 * A buffer size has been explicitly set to 0 (or to a size
11638 		 * that will be adjusted to 0) and we need the space -- we
11639 		 * need to return failure.  We return ENOSPC to differentiate
11640 		 * it from failing to allocate a buffer due to failure to meet
11641 		 * the reserve (for which we return E2BIG).
11642 		 */
11643 		rval = ENOSPC;
11644 		goto out;
11645 	}
11646 
11647 	if ((rval = dtrace_state_buffers(state)) != 0)
11648 		goto err;
11649 
11650 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
11651 		sz = dtrace_dstate_defsize;
11652 
11653 	do {
11654 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
11655 
11656 		if (rval == 0)
11657 			break;
11658 
11659 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
11660 			goto err;
11661 	} while (sz >>= 1);
11662 
11663 	opt[DTRACEOPT_DYNVARSIZE] = sz;
11664 
11665 	if (rval != 0)
11666 		goto err;
11667 
11668 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
11669 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
11670 
11671 	if (opt[DTRACEOPT_CLEANRATE] == 0)
11672 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
11673 
11674 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
11675 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
11676 
11677 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
11678 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
11679 
11680 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
11681 	hdlr.cyh_arg = state;
11682 	hdlr.cyh_level = CY_LOW_LEVEL;
11683 
11684 	when.cyt_when = 0;
11685 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
11686 
11687 	state->dts_cleaner = cyclic_add(&hdlr, &when);
11688 
11689 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
11690 	hdlr.cyh_arg = state;
11691 	hdlr.cyh_level = CY_LOW_LEVEL;
11692 
11693 	when.cyt_when = 0;
11694 	when.cyt_interval = dtrace_deadman_interval;
11695 
11696 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
11697 	state->dts_deadman = cyclic_add(&hdlr, &when);
11698 
11699 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
11700 
11701 	/*
11702 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
11703 	 * interrupts here both to record the CPU on which we fired the BEGIN
11704 	 * probe (the data from this CPU will be processed first at user
11705 	 * level) and to manually activate the buffer for this CPU.
11706 	 */
11707 	cookie = dtrace_interrupt_disable();
11708 	*cpu = CPU->cpu_id;
11709 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
11710 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
11711 
11712 	dtrace_probe(dtrace_probeid_begin,
11713 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
11714 	dtrace_interrupt_enable(cookie);
11715 	/*
11716 	 * We may have had an exit action from a BEGIN probe; only change our
11717 	 * state to ACTIVE if we're still in WARMUP.
11718 	 */
11719 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
11720 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
11721 
11722 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
11723 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
11724 
11725 	/*
11726 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
11727 	 * want each CPU to transition its principal buffer out of the
11728 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
11729 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
11730 	 * atomically transition from processing none of a state's ECBs to
11731 	 * processing all of them.
11732 	 */
11733 	dtrace_xcall(DTRACE_CPUALL,
11734 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
11735 	goto out;
11736 
11737 err:
11738 	dtrace_buffer_free(state->dts_buffer);
11739 	dtrace_buffer_free(state->dts_aggbuffer);
11740 
11741 	if ((nspec = state->dts_nspeculations) == 0) {
11742 		ASSERT(state->dts_speculations == NULL);
11743 		goto out;
11744 	}
11745 
11746 	spec = state->dts_speculations;
11747 	ASSERT(spec != NULL);
11748 
11749 	for (i = 0; i < state->dts_nspeculations; i++) {
11750 		if ((buf = spec[i].dtsp_buffer) == NULL)
11751 			break;
11752 
11753 		dtrace_buffer_free(buf);
11754 		kmem_free(buf, bufsize);
11755 	}
11756 
11757 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
11758 	state->dts_nspeculations = 0;
11759 	state->dts_speculations = NULL;
11760 
11761 out:
11762 	mutex_exit(&dtrace_lock);
11763 	mutex_exit(&cpu_lock);
11764 
11765 	return (rval);
11766 }
11767 
11768 static int
11769 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
11770 {
11771 	dtrace_icookie_t cookie;
11772 
11773 	ASSERT(MUTEX_HELD(&dtrace_lock));
11774 
11775 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
11776 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
11777 		return (EINVAL);
11778 
11779 	/*
11780 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
11781 	 * to be sure that every CPU has seen it.  See below for the details
11782 	 * on why this is done.
11783 	 */
11784 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
11785 	dtrace_sync();
11786 
11787 	/*
11788 	 * By this point, it is impossible for any CPU to be still processing
11789 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
11790 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
11791 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
11792 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
11793 	 * iff we're in the END probe.
11794 	 */
11795 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
11796 	dtrace_sync();
11797 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
11798 
11799 	/*
11800 	 * Finally, we can release the reserve and call the END probe.  We
11801 	 * disable interrupts across calling the END probe to allow us to
11802 	 * return the CPU on which we actually called the END probe.  This
11803 	 * allows user-land to be sure that this CPU's principal buffer is
11804 	 * processed last.
11805 	 */
11806 	state->dts_reserve = 0;
11807 
11808 	cookie = dtrace_interrupt_disable();
11809 	*cpu = CPU->cpu_id;
11810 	dtrace_probe(dtrace_probeid_end,
11811 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
11812 	dtrace_interrupt_enable(cookie);
11813 
11814 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
11815 	dtrace_sync();
11816 
11817 	return (0);
11818 }
11819 
11820 static int
11821 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
11822     dtrace_optval_t val)
11823 {
11824 	ASSERT(MUTEX_HELD(&dtrace_lock));
11825 
11826 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11827 		return (EBUSY);
11828 
11829 	if (option >= DTRACEOPT_MAX)
11830 		return (EINVAL);
11831 
11832 	if (option != DTRACEOPT_CPU && val < 0)
11833 		return (EINVAL);
11834 
11835 	switch (option) {
11836 	case DTRACEOPT_DESTRUCTIVE:
11837 		if (dtrace_destructive_disallow)
11838 			return (EACCES);
11839 
11840 		state->dts_cred.dcr_destructive = 1;
11841 		break;
11842 
11843 	case DTRACEOPT_BUFSIZE:
11844 	case DTRACEOPT_DYNVARSIZE:
11845 	case DTRACEOPT_AGGSIZE:
11846 	case DTRACEOPT_SPECSIZE:
11847 	case DTRACEOPT_STRSIZE:
11848 		if (val < 0)
11849 			return (EINVAL);
11850 
11851 		if (val >= LONG_MAX) {
11852 			/*
11853 			 * If this is an otherwise negative value, set it to
11854 			 * the highest multiple of 128m less than LONG_MAX.
11855 			 * Technically, we're adjusting the size without
11856 			 * regard to the buffer resizing policy, but in fact,
11857 			 * this has no effect -- if we set the buffer size to
11858 			 * ~LONG_MAX and the buffer policy is ultimately set to
11859 			 * be "manual", the buffer allocation is guaranteed to
11860 			 * fail, if only because the allocation requires two
11861 			 * buffers.  (We set the the size to the highest
11862 			 * multiple of 128m because it ensures that the size
11863 			 * will remain a multiple of a megabyte when
11864 			 * repeatedly halved -- all the way down to 15m.)
11865 			 */
11866 			val = LONG_MAX - (1 << 27) + 1;
11867 		}
11868 	}
11869 
11870 	state->dts_options[option] = val;
11871 
11872 	return (0);
11873 }
11874 
11875 static void
11876 dtrace_state_destroy(dtrace_state_t *state)
11877 {
11878 	dtrace_ecb_t *ecb;
11879 	dtrace_vstate_t *vstate = &state->dts_vstate;
11880 	minor_t minor = getminor(state->dts_dev);
11881 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
11882 	dtrace_speculation_t *spec = state->dts_speculations;
11883 	int nspec = state->dts_nspeculations;
11884 	uint32_t match;
11885 
11886 	ASSERT(MUTEX_HELD(&dtrace_lock));
11887 	ASSERT(MUTEX_HELD(&cpu_lock));
11888 
11889 	/*
11890 	 * First, retract any retained enablings for this state.
11891 	 */
11892 	dtrace_enabling_retract(state);
11893 	ASSERT(state->dts_nretained == 0);
11894 
11895 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
11896 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
11897 		/*
11898 		 * We have managed to come into dtrace_state_destroy() on a
11899 		 * hot enabling -- almost certainly because of a disorderly
11900 		 * shutdown of a consumer.  (That is, a consumer that is
11901 		 * exiting without having called dtrace_stop().) In this case,
11902 		 * we're going to set our activity to be KILLED, and then
11903 		 * issue a sync to be sure that everyone is out of probe
11904 		 * context before we start blowing away ECBs.
11905 		 */
11906 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
11907 		dtrace_sync();
11908 	}
11909 
11910 	/*
11911 	 * Release the credential hold we took in dtrace_state_create().
11912 	 */
11913 	if (state->dts_cred.dcr_cred != NULL)
11914 		crfree(state->dts_cred.dcr_cred);
11915 
11916 	/*
11917 	 * Now we can safely disable and destroy any enabled probes.  Because
11918 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
11919 	 * (especially if they're all enabled), we take two passes through the
11920 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
11921 	 * in the second we disable whatever is left over.
11922 	 */
11923 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
11924 		for (i = 0; i < state->dts_necbs; i++) {
11925 			if ((ecb = state->dts_ecbs[i]) == NULL)
11926 				continue;
11927 
11928 			if (match && ecb->dte_probe != NULL) {
11929 				dtrace_probe_t *probe = ecb->dte_probe;
11930 				dtrace_provider_t *prov = probe->dtpr_provider;
11931 
11932 				if (!(prov->dtpv_priv.dtpp_flags & match))
11933 					continue;
11934 			}
11935 
11936 			dtrace_ecb_disable(ecb);
11937 			dtrace_ecb_destroy(ecb);
11938 		}
11939 
11940 		if (!match)
11941 			break;
11942 	}
11943 
11944 	/*
11945 	 * Before we free the buffers, perform one more sync to assure that
11946 	 * every CPU is out of probe context.
11947 	 */
11948 	dtrace_sync();
11949 
11950 	dtrace_buffer_free(state->dts_buffer);
11951 	dtrace_buffer_free(state->dts_aggbuffer);
11952 
11953 	for (i = 0; i < nspec; i++)
11954 		dtrace_buffer_free(spec[i].dtsp_buffer);
11955 
11956 	if (state->dts_cleaner != CYCLIC_NONE)
11957 		cyclic_remove(state->dts_cleaner);
11958 
11959 	if (state->dts_deadman != CYCLIC_NONE)
11960 		cyclic_remove(state->dts_deadman);
11961 
11962 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
11963 	dtrace_vstate_fini(vstate);
11964 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
11965 
11966 	if (state->dts_aggregations != NULL) {
11967 #ifdef DEBUG
11968 		for (i = 0; i < state->dts_naggregations; i++)
11969 			ASSERT(state->dts_aggregations[i] == NULL);
11970 #endif
11971 		ASSERT(state->dts_naggregations > 0);
11972 		kmem_free(state->dts_aggregations,
11973 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
11974 	}
11975 
11976 	kmem_free(state->dts_buffer, bufsize);
11977 	kmem_free(state->dts_aggbuffer, bufsize);
11978 
11979 	for (i = 0; i < nspec; i++)
11980 		kmem_free(spec[i].dtsp_buffer, bufsize);
11981 
11982 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
11983 
11984 	dtrace_format_destroy(state);
11985 
11986 	vmem_destroy(state->dts_aggid_arena);
11987 	ddi_soft_state_free(dtrace_softstate, minor);
11988 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
11989 }
11990 
11991 /*
11992  * DTrace Anonymous Enabling Functions
11993  */
11994 static dtrace_state_t *
11995 dtrace_anon_grab(void)
11996 {
11997 	dtrace_state_t *state;
11998 
11999 	ASSERT(MUTEX_HELD(&dtrace_lock));
12000 
12001 	if ((state = dtrace_anon.dta_state) == NULL) {
12002 		ASSERT(dtrace_anon.dta_enabling == NULL);
12003 		return (NULL);
12004 	}
12005 
12006 	ASSERT(dtrace_anon.dta_enabling != NULL);
12007 	ASSERT(dtrace_retained != NULL);
12008 
12009 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
12010 	dtrace_anon.dta_enabling = NULL;
12011 	dtrace_anon.dta_state = NULL;
12012 
12013 	return (state);
12014 }
12015 
12016 static void
12017 dtrace_anon_property(void)
12018 {
12019 	int i, rv;
12020 	dtrace_state_t *state;
12021 	dof_hdr_t *dof;
12022 	char c[32];		/* enough for "dof-data-" + digits */
12023 
12024 	ASSERT(MUTEX_HELD(&dtrace_lock));
12025 	ASSERT(MUTEX_HELD(&cpu_lock));
12026 
12027 	for (i = 0; ; i++) {
12028 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
12029 
12030 		dtrace_err_verbose = 1;
12031 
12032 		if ((dof = dtrace_dof_property(c)) == NULL) {
12033 			dtrace_err_verbose = 0;
12034 			break;
12035 		}
12036 
12037 		/*
12038 		 * We want to create anonymous state, so we need to transition
12039 		 * the kernel debugger to indicate that DTrace is active.  If
12040 		 * this fails (e.g. because the debugger has modified text in
12041 		 * some way), we won't continue with the processing.
12042 		 */
12043 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
12044 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
12045 			    "enabling ignored.");
12046 			dtrace_dof_destroy(dof);
12047 			break;
12048 		}
12049 
12050 		/*
12051 		 * If we haven't allocated an anonymous state, we'll do so now.
12052 		 */
12053 		if ((state = dtrace_anon.dta_state) == NULL) {
12054 			state = dtrace_state_create(NULL, NULL);
12055 			dtrace_anon.dta_state = state;
12056 
12057 			if (state == NULL) {
12058 				/*
12059 				 * This basically shouldn't happen:  the only
12060 				 * failure mode from dtrace_state_create() is a
12061 				 * failure of ddi_soft_state_zalloc() that
12062 				 * itself should never happen.  Still, the
12063 				 * interface allows for a failure mode, and
12064 				 * we want to fail as gracefully as possible:
12065 				 * we'll emit an error message and cease
12066 				 * processing anonymous state in this case.
12067 				 */
12068 				cmn_err(CE_WARN, "failed to create "
12069 				    "anonymous state");
12070 				dtrace_dof_destroy(dof);
12071 				break;
12072 			}
12073 		}
12074 
12075 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
12076 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
12077 
12078 		if (rv == 0)
12079 			rv = dtrace_dof_options(dof, state);
12080 
12081 		dtrace_err_verbose = 0;
12082 		dtrace_dof_destroy(dof);
12083 
12084 		if (rv != 0) {
12085 			/*
12086 			 * This is malformed DOF; chuck any anonymous state
12087 			 * that we created.
12088 			 */
12089 			ASSERT(dtrace_anon.dta_enabling == NULL);
12090 			dtrace_state_destroy(state);
12091 			dtrace_anon.dta_state = NULL;
12092 			break;
12093 		}
12094 
12095 		ASSERT(dtrace_anon.dta_enabling != NULL);
12096 	}
12097 
12098 	if (dtrace_anon.dta_enabling != NULL) {
12099 		int rval;
12100 
12101 		/*
12102 		 * dtrace_enabling_retain() can only fail because we are
12103 		 * trying to retain more enablings than are allowed -- but
12104 		 * we only have one anonymous enabling, and we are guaranteed
12105 		 * to be allowed at least one retained enabling; we assert
12106 		 * that dtrace_enabling_retain() returns success.
12107 		 */
12108 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
12109 		ASSERT(rval == 0);
12110 
12111 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
12112 	}
12113 }
12114 
12115 /*
12116  * DTrace Helper Functions
12117  */
12118 static void
12119 dtrace_helper_trace(dtrace_helper_action_t *helper,
12120     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
12121 {
12122 	uint32_t size, next, nnext, i;
12123 	dtrace_helptrace_t *ent;
12124 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12125 
12126 	if (!dtrace_helptrace_enabled)
12127 		return;
12128 
12129 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
12130 
12131 	/*
12132 	 * What would a tracing framework be without its own tracing
12133 	 * framework?  (Well, a hell of a lot simpler, for starters...)
12134 	 */
12135 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
12136 	    sizeof (uint64_t) - sizeof (uint64_t);
12137 
12138 	/*
12139 	 * Iterate until we can allocate a slot in the trace buffer.
12140 	 */
12141 	do {
12142 		next = dtrace_helptrace_next;
12143 
12144 		if (next + size < dtrace_helptrace_bufsize) {
12145 			nnext = next + size;
12146 		} else {
12147 			nnext = size;
12148 		}
12149 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
12150 
12151 	/*
12152 	 * We have our slot; fill it in.
12153 	 */
12154 	if (nnext == size)
12155 		next = 0;
12156 
12157 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
12158 	ent->dtht_helper = helper;
12159 	ent->dtht_where = where;
12160 	ent->dtht_nlocals = vstate->dtvs_nlocals;
12161 
12162 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
12163 	    mstate->dtms_fltoffs : -1;
12164 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
12165 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
12166 
12167 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
12168 		dtrace_statvar_t *svar;
12169 
12170 		if ((svar = vstate->dtvs_locals[i]) == NULL)
12171 			continue;
12172 
12173 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
12174 		ent->dtht_locals[i] =
12175 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
12176 	}
12177 }
12178 
12179 static uint64_t
12180 dtrace_helper(int which, dtrace_mstate_t *mstate,
12181     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
12182 {
12183 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12184 	uint64_t sarg0 = mstate->dtms_arg[0];
12185 	uint64_t sarg1 = mstate->dtms_arg[1];
12186 	uint64_t rval;
12187 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
12188 	dtrace_helper_action_t *helper;
12189 	dtrace_vstate_t *vstate;
12190 	dtrace_difo_t *pred;
12191 	int i, trace = dtrace_helptrace_enabled;
12192 
12193 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
12194 
12195 	if (helpers == NULL)
12196 		return (0);
12197 
12198 	if ((helper = helpers->dthps_actions[which]) == NULL)
12199 		return (0);
12200 
12201 	vstate = &helpers->dthps_vstate;
12202 	mstate->dtms_arg[0] = arg0;
12203 	mstate->dtms_arg[1] = arg1;
12204 
12205 	/*
12206 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
12207 	 * we'll call the corresponding actions.  Note that the below calls
12208 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
12209 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
12210 	 * the stored DIF offset with its own (which is the desired behavior).
12211 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
12212 	 * from machine state; this is okay, too.
12213 	 */
12214 	for (; helper != NULL; helper = helper->dthp_next) {
12215 		if ((pred = helper->dthp_predicate) != NULL) {
12216 			if (trace)
12217 				dtrace_helper_trace(helper, mstate, vstate, 0);
12218 
12219 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
12220 				goto next;
12221 
12222 			if (*flags & CPU_DTRACE_FAULT)
12223 				goto err;
12224 		}
12225 
12226 		for (i = 0; i < helper->dthp_nactions; i++) {
12227 			if (trace)
12228 				dtrace_helper_trace(helper,
12229 				    mstate, vstate, i + 1);
12230 
12231 			rval = dtrace_dif_emulate(helper->dthp_actions[i],
12232 			    mstate, vstate, state);
12233 
12234 			if (*flags & CPU_DTRACE_FAULT)
12235 				goto err;
12236 		}
12237 
12238 next:
12239 		if (trace)
12240 			dtrace_helper_trace(helper, mstate, vstate,
12241 			    DTRACE_HELPTRACE_NEXT);
12242 	}
12243 
12244 	if (trace)
12245 		dtrace_helper_trace(helper, mstate, vstate,
12246 		    DTRACE_HELPTRACE_DONE);
12247 
12248 	/*
12249 	 * Restore the arg0 that we saved upon entry.
12250 	 */
12251 	mstate->dtms_arg[0] = sarg0;
12252 	mstate->dtms_arg[1] = sarg1;
12253 
12254 	return (rval);
12255 
12256 err:
12257 	if (trace)
12258 		dtrace_helper_trace(helper, mstate, vstate,
12259 		    DTRACE_HELPTRACE_ERR);
12260 
12261 	/*
12262 	 * Restore the arg0 that we saved upon entry.
12263 	 */
12264 	mstate->dtms_arg[0] = sarg0;
12265 	mstate->dtms_arg[1] = sarg1;
12266 
12267 	return (NULL);
12268 }
12269 
12270 static void
12271 dtrace_helper_destroy(dtrace_helper_action_t *helper, dtrace_vstate_t *vstate)
12272 {
12273 	int i;
12274 
12275 	if (helper->dthp_predicate != NULL)
12276 		dtrace_difo_release(helper->dthp_predicate, vstate);
12277 
12278 	for (i = 0; i < helper->dthp_nactions; i++) {
12279 		ASSERT(helper->dthp_actions[i] != NULL);
12280 		dtrace_difo_release(helper->dthp_actions[i], vstate);
12281 	}
12282 
12283 	kmem_free(helper->dthp_actions,
12284 	    helper->dthp_nactions * sizeof (dtrace_difo_t *));
12285 	kmem_free(helper, sizeof (dtrace_helper_action_t));
12286 }
12287 
12288 static int
12289 dtrace_helper_destroygen(int gen)
12290 {
12291 	dtrace_helpers_t *help = curproc->p_dtrace_helpers;
12292 	dtrace_vstate_t *vstate;
12293 	int i;
12294 
12295 	ASSERT(MUTEX_HELD(&dtrace_lock));
12296 
12297 	if (help == NULL || gen > help->dthps_generation)
12298 		return (EINVAL);
12299 
12300 	vstate = &help->dthps_vstate;
12301 
12302 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
12303 		dtrace_helper_action_t *last = NULL, *h, *next;
12304 
12305 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
12306 			next = h->dthp_next;
12307 
12308 			if (h->dthp_generation == gen) {
12309 				if (last != NULL) {
12310 					last->dthp_next = next;
12311 				} else {
12312 					help->dthps_actions[i] = next;
12313 				}
12314 
12315 				dtrace_helper_destroy(h, vstate);
12316 			} else {
12317 				last = h;
12318 			}
12319 		}
12320 	}
12321 
12322 	return (0);
12323 }
12324 
12325 static int
12326 dtrace_helper_validate(dtrace_helper_action_t *helper)
12327 {
12328 	int err = 0, i;
12329 	dtrace_difo_t *dp;
12330 
12331 	if ((dp = helper->dthp_predicate) != NULL)
12332 		err += dtrace_difo_validate_helper(dp);
12333 
12334 	for (i = 0; i < helper->dthp_nactions; i++)
12335 		err += dtrace_difo_validate_helper(helper->dthp_actions[i]);
12336 
12337 	return (err == 0);
12338 }
12339 
12340 static int
12341 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
12342 {
12343 	dtrace_helpers_t *help;
12344 	dtrace_helper_action_t *helper, *last;
12345 	dtrace_actdesc_t *act;
12346 	dtrace_vstate_t *vstate;
12347 	dtrace_predicate_t *pred;
12348 	int count = 0, nactions = 0, i;
12349 
12350 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
12351 		return (EINVAL);
12352 
12353 	help = curproc->p_dtrace_helpers;
12354 	last = help->dthps_actions[which];
12355 	vstate = &help->dthps_vstate;
12356 
12357 	for (count = 0; last != NULL; last = last->dthp_next) {
12358 		count++;
12359 		if (last->dthp_next == NULL)
12360 			break;
12361 	}
12362 
12363 	/*
12364 	 * If we already have dtrace_helper_actions_max helper actions for this
12365 	 * helper action type, we'll refuse to add a new one.
12366 	 */
12367 	if (count >= dtrace_helper_actions_max)
12368 		return (ENOSPC);
12369 
12370 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
12371 	helper->dthp_generation = help->dthps_generation;
12372 
12373 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
12374 		ASSERT(pred->dtp_difo != NULL);
12375 		dtrace_difo_hold(pred->dtp_difo);
12376 		helper->dthp_predicate = pred->dtp_difo;
12377 	}
12378 
12379 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
12380 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
12381 			goto err;
12382 
12383 		if (act->dtad_difo == NULL)
12384 			goto err;
12385 
12386 		nactions++;
12387 	}
12388 
12389 	helper->dthp_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
12390 	    (helper->dthp_nactions = nactions), KM_SLEEP);
12391 
12392 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
12393 		dtrace_difo_hold(act->dtad_difo);
12394 		helper->dthp_actions[i++] = act->dtad_difo;
12395 	}
12396 
12397 	if (!dtrace_helper_validate(helper))
12398 		goto err;
12399 
12400 	if (last == NULL) {
12401 		help->dthps_actions[which] = helper;
12402 	} else {
12403 		last->dthp_next = helper;
12404 	}
12405 
12406 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
12407 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
12408 		dtrace_helptrace_next = 0;
12409 	}
12410 
12411 	return (0);
12412 err:
12413 	dtrace_helper_destroy(helper, vstate);
12414 	return (EINVAL);
12415 }
12416 
12417 static void
12418 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
12419     dof_helper_t *dofhp)
12420 {
12421 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
12422 
12423 	mutex_enter(&dtrace_meta_lock);
12424 	mutex_enter(&dtrace_lock);
12425 
12426 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
12427 		/*
12428 		 * If the dtrace module is loaded but not attached, or if
12429 		 * there aren't isn't a meta provider registered to deal with
12430 		 * these provider descriptions, we need to postpone creating
12431 		 * the actual providers until later.
12432 		 */
12433 
12434 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
12435 		    dtrace_deferred_pid != help) {
12436 			help->dthps_deferred = 1;
12437 			help->dthps_pid = p->p_pid;
12438 			help->dthps_next = dtrace_deferred_pid;
12439 			help->dthps_prev = NULL;
12440 			if (dtrace_deferred_pid != NULL)
12441 				dtrace_deferred_pid->dthps_prev = help;
12442 			dtrace_deferred_pid = help;
12443 		}
12444 
12445 		mutex_exit(&dtrace_lock);
12446 
12447 	} else if (dofhp != NULL) {
12448 		/*
12449 		 * If the dtrace module is loaded and we have a particular
12450 		 * helper provider description, pass that off to the
12451 		 * meta provider.
12452 		 */
12453 
12454 		mutex_exit(&dtrace_lock);
12455 
12456 		dtrace_helper_provide(dofhp, p->p_pid);
12457 
12458 	} else {
12459 		/*
12460 		 * Otherwise, just pass all the helper provider descriptions
12461 		 * off to the meta provider.
12462 		 */
12463 
12464 		int i;
12465 		mutex_exit(&dtrace_lock);
12466 
12467 		for (i = 0; i < help->dthps_nprovs; i++) {
12468 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
12469 			    p->p_pid);
12470 		}
12471 	}
12472 
12473 	mutex_exit(&dtrace_meta_lock);
12474 }
12475 
12476 static int
12477 dtrace_helper_provider_add(dof_helper_t *dofhp)
12478 {
12479 	dtrace_helpers_t *help;
12480 	dtrace_helper_provider_t *hprov, **tmp_provs;
12481 	uint_t tmp_nprovs, i;
12482 
12483 	help = curproc->p_dtrace_helpers;
12484 	ASSERT(help != NULL);
12485 
12486 	/*
12487 	 * If we already have dtrace_helper_providers_max helper providers,
12488 	 * we're refuse to add a new one.
12489 	 */
12490 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
12491 		return (ENOSPC);
12492 
12493 	/*
12494 	 * Check to make sure this isn't a duplicate.
12495 	 */
12496 	for (i = 0; i < help->dthps_nprovs; i++) {
12497 		if (dofhp->dofhp_addr ==
12498 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
12499 			return (EALREADY);
12500 	}
12501 
12502 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
12503 	hprov->dthp_prov = *dofhp;
12504 	hprov->dthp_ref = 1;
12505 
12506 	tmp_nprovs = help->dthps_nprovs;
12507 	tmp_provs = help->dthps_provs;
12508 	help->dthps_nprovs++;
12509 	help->dthps_provs = kmem_zalloc(help->dthps_nprovs *
12510 	    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
12511 
12512 	help->dthps_provs[tmp_nprovs] = hprov;
12513 	if (tmp_provs != NULL) {
12514 		bcopy(tmp_provs, help->dthps_provs, tmp_nprovs *
12515 		    sizeof (dtrace_helper_provider_t *));
12516 		kmem_free(tmp_provs, tmp_nprovs *
12517 		    sizeof (dtrace_helper_provider_t *));
12518 	}
12519 
12520 	return (0);
12521 }
12522 
12523 static void
12524 dtrace_helper_provider_remove(dtrace_helper_provider_t *hprov)
12525 {
12526 	mutex_enter(&dtrace_lock);
12527 
12528 	if (--hprov->dthp_ref == 0) {
12529 		dof_hdr_t *dof;
12530 		mutex_exit(&dtrace_lock);
12531 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
12532 		dtrace_dof_destroy(dof);
12533 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
12534 	} else {
12535 		mutex_exit(&dtrace_lock);
12536 	}
12537 }
12538 
12539 static int
12540 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
12541 {
12542 	uintptr_t daddr = (uintptr_t)dof;
12543 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
12544 	dof_provider_t *provider;
12545 	dof_probe_t *probe;
12546 	uint8_t *arg;
12547 	char *strtab, *typestr;
12548 	dof_stridx_t typeidx;
12549 	size_t typesz;
12550 	uint_t nprobes, j, k;
12551 
12552 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
12553 
12554 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
12555 		dtrace_dof_error(dof, "misaligned section offset");
12556 		return (-1);
12557 	}
12558 
12559 	/*
12560 	 * The section needs to be large enough to contain the DOF provider
12561 	 * structure appropriate for the given version.
12562 	 */
12563 	if (sec->dofs_size <
12564 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
12565 	    offsetof(dof_provider_t, dofpv_prenoffs) :
12566 	    sizeof (dof_provider_t))) {
12567 		dtrace_dof_error(dof, "provider section too small");
12568 		return (-1);
12569 	}
12570 
12571 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
12572 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
12573 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
12574 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
12575 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
12576 
12577 	if (str_sec == NULL || prb_sec == NULL ||
12578 	    arg_sec == NULL || off_sec == NULL)
12579 		return (-1);
12580 
12581 	enoff_sec = NULL;
12582 
12583 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12584 	    provider->dofpv_prenoffs != 0 && (enoff_sec = dtrace_dof_sect(dof,
12585 	    DOF_SECT_PRENOFFS, provider->dofpv_prenoffs)) == NULL)
12586 		return (-1);
12587 
12588 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
12589 
12590 	if (provider->dofpv_name >= str_sec->dofs_size ||
12591 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
12592 		dtrace_dof_error(dof, "invalid provider name");
12593 		return (-1);
12594 	}
12595 
12596 	if (prb_sec->dofs_entsize == 0 ||
12597 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
12598 		dtrace_dof_error(dof, "invalid entry size");
12599 		return (-1);
12600 	}
12601 
12602 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
12603 		dtrace_dof_error(dof, "misaligned entry size");
12604 		return (-1);
12605 	}
12606 
12607 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
12608 		dtrace_dof_error(dof, "invalid entry size");
12609 		return (-1);
12610 	}
12611 
12612 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
12613 		dtrace_dof_error(dof, "misaligned section offset");
12614 		return (-1);
12615 	}
12616 
12617 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
12618 		dtrace_dof_error(dof, "invalid entry size");
12619 		return (-1);
12620 	}
12621 
12622 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
12623 
12624 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
12625 
12626 	/*
12627 	 * Take a pass through the probes to check for errors.
12628 	 */
12629 	for (j = 0; j < nprobes; j++) {
12630 		probe = (dof_probe_t *)(uintptr_t)(daddr +
12631 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
12632 
12633 		if (probe->dofpr_func >= str_sec->dofs_size) {
12634 			dtrace_dof_error(dof, "invalid function name");
12635 			return (-1);
12636 		}
12637 
12638 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
12639 			dtrace_dof_error(dof, "function name too long");
12640 			return (-1);
12641 		}
12642 
12643 		if (probe->dofpr_name >= str_sec->dofs_size ||
12644 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
12645 			dtrace_dof_error(dof, "invalid probe name");
12646 			return (-1);
12647 		}
12648 
12649 		/*
12650 		 * The offset count must not wrap the index and there must be
12651 		 * at least one offset. The offsets must also not overflow the
12652 		 * section's data.
12653 		 */
12654 		if (probe->dofpr_offidx + probe->dofpr_noffs <=
12655 		    probe->dofpr_offidx ||
12656 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
12657 		    off_sec->dofs_entsize > off_sec->dofs_size) {
12658 			dtrace_dof_error(dof, "invalid probe offset");
12659 			return (-1);
12660 		}
12661 
12662 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
12663 			/*
12664 			 * If there's no is-enabled offset section, make sure
12665 			 * there aren't any is-enabled offsets. Otherwise
12666 			 * perform the same checks as for probe offsets
12667 			 * (immediately above), except that having zero
12668 			 * is-enabled offsets is permitted.
12669 			 */
12670 			if (enoff_sec == NULL) {
12671 				if (probe->dofpr_enoffidx != 0 ||
12672 				    probe->dofpr_nenoffs != 0) {
12673 					dtrace_dof_error(dof, "is-enabled "
12674 					    "offsets with null section");
12675 					return (-1);
12676 				}
12677 			} else if (probe->dofpr_enoffidx +
12678 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
12679 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
12680 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
12681 				dtrace_dof_error(dof, "invalid is-enabled "
12682 				    "offset");
12683 				return (-1);
12684 			}
12685 		}
12686 
12687 		if (probe->dofpr_argidx + probe->dofpr_xargc <
12688 		    probe->dofpr_argidx ||
12689 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
12690 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
12691 			dtrace_dof_error(dof, "invalid args");
12692 			return (-1);
12693 		}
12694 
12695 		typeidx = probe->dofpr_nargv;
12696 		typestr = strtab + probe->dofpr_nargv;
12697 		for (k = 0; k < probe->dofpr_nargc; k++) {
12698 			if (typeidx >= str_sec->dofs_size) {
12699 				dtrace_dof_error(dof, "bad "
12700 				    "native argument type");
12701 				return (-1);
12702 			}
12703 
12704 			typesz = strlen(typestr) + 1;
12705 			if (typesz > DTRACE_ARGTYPELEN) {
12706 				dtrace_dof_error(dof, "native "
12707 				    "argument type too long");
12708 				return (-1);
12709 			}
12710 			typeidx += typesz;
12711 			typestr += typesz;
12712 		}
12713 
12714 		typeidx = probe->dofpr_xargv;
12715 		typestr = strtab + probe->dofpr_xargv;
12716 		for (k = 0; k < probe->dofpr_xargc; k++) {
12717 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
12718 				dtrace_dof_error(dof, "bad "
12719 				    "native argument index");
12720 				return (-1);
12721 			}
12722 
12723 			if (typeidx >= str_sec->dofs_size) {
12724 				dtrace_dof_error(dof, "bad "
12725 				    "translated argument type");
12726 				return (-1);
12727 			}
12728 
12729 			typesz = strlen(typestr) + 1;
12730 			if (typesz > DTRACE_ARGTYPELEN) {
12731 				dtrace_dof_error(dof, "translated argument "
12732 				    "type too long");
12733 				return (-1);
12734 			}
12735 
12736 			typeidx += typesz;
12737 			typestr += typesz;
12738 		}
12739 	}
12740 
12741 	return (0);
12742 }
12743 
12744 static int
12745 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
12746 {
12747 	dtrace_helpers_t *help;
12748 	dtrace_vstate_t *vstate;
12749 	dtrace_enabling_t *enab = NULL;
12750 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
12751 	uintptr_t daddr = (uintptr_t)dof;
12752 
12753 	ASSERT(MUTEX_HELD(&dtrace_lock));
12754 
12755 	if ((help = curproc->p_dtrace_helpers) == NULL)
12756 		help = dtrace_helpers_create(curproc);
12757 
12758 	vstate = &help->dthps_vstate;
12759 
12760 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
12761 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
12762 		dtrace_dof_destroy(dof);
12763 		return (rv);
12764 	}
12765 
12766 	/*
12767 	 * Look for helper providers and validate their descriptions.
12768 	 */
12769 	if (dhp != NULL) {
12770 		for (i = 0; i < dof->dofh_secnum; i++) {
12771 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
12772 			    dof->dofh_secoff + i * dof->dofh_secsize);
12773 
12774 			if (sec->dofs_type != DOF_SECT_PROVIDER)
12775 				continue;
12776 
12777 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
12778 				dtrace_enabling_destroy(enab);
12779 				dtrace_dof_destroy(dof);
12780 				return (-1);
12781 			}
12782 
12783 			nprovs++;
12784 		}
12785 	}
12786 
12787 	/*
12788 	 * Now we need to walk through the ECB descriptions in the enabling.
12789 	 */
12790 	for (i = 0; i < enab->dten_ndesc; i++) {
12791 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12792 		dtrace_probedesc_t *desc = &ep->dted_probe;
12793 
12794 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
12795 			continue;
12796 
12797 		if (strcmp(desc->dtpd_mod, "helper") != 0)
12798 			continue;
12799 
12800 		if (strcmp(desc->dtpd_func, "ustack") != 0)
12801 			continue;
12802 
12803 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
12804 		    ep)) != 0) {
12805 			/*
12806 			 * Adding this helper action failed -- we are now going
12807 			 * to rip out the entire generation and return failure.
12808 			 */
12809 			(void) dtrace_helper_destroygen(help->dthps_generation);
12810 			dtrace_enabling_destroy(enab);
12811 			dtrace_dof_destroy(dof);
12812 			return (-1);
12813 		}
12814 
12815 		nhelpers++;
12816 	}
12817 
12818 	if (nhelpers < enab->dten_ndesc)
12819 		dtrace_dof_error(dof, "unmatched helpers");
12820 
12821 	gen = help->dthps_generation++;
12822 	dtrace_enabling_destroy(enab);
12823 
12824 	if (dhp != NULL && nprovs > 0) {
12825 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
12826 		if (dtrace_helper_provider_add(dhp) == 0) {
12827 			mutex_exit(&dtrace_lock);
12828 			dtrace_helper_provider_register(curproc, help, dhp);
12829 			mutex_enter(&dtrace_lock);
12830 
12831 			destroy = 0;
12832 		}
12833 	}
12834 
12835 	if (destroy)
12836 		dtrace_dof_destroy(dof);
12837 
12838 	return (gen);
12839 }
12840 
12841 static dtrace_helpers_t *
12842 dtrace_helpers_create(proc_t *p)
12843 {
12844 	dtrace_helpers_t *help;
12845 
12846 	ASSERT(MUTEX_HELD(&dtrace_lock));
12847 	ASSERT(p->p_dtrace_helpers == NULL);
12848 
12849 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
12850 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
12851 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
12852 
12853 	p->p_dtrace_helpers = help;
12854 	dtrace_helpers++;
12855 
12856 	return (help);
12857 }
12858 
12859 static void
12860 dtrace_helpers_destroy(void)
12861 {
12862 	dtrace_helpers_t *help;
12863 	dtrace_vstate_t *vstate;
12864 	proc_t *p = curproc;
12865 	int i;
12866 
12867 	mutex_enter(&dtrace_lock);
12868 
12869 	ASSERT(p->p_dtrace_helpers != NULL);
12870 	ASSERT(dtrace_helpers > 0);
12871 
12872 	help = p->p_dtrace_helpers;
12873 	vstate = &help->dthps_vstate;
12874 
12875 	/*
12876 	 * We're now going to lose the help from this process.
12877 	 */
12878 	p->p_dtrace_helpers = NULL;
12879 	dtrace_sync();
12880 
12881 	/*
12882 	 * Destory the helper actions.
12883 	 */
12884 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
12885 		dtrace_helper_action_t *h, *next;
12886 
12887 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
12888 			next = h->dthp_next;
12889 			dtrace_helper_destroy(h, vstate);
12890 			h = next;
12891 		}
12892 	}
12893 
12894 	mutex_exit(&dtrace_lock);
12895 
12896 	/*
12897 	 * Destroy the helper providers.
12898 	 */
12899 	if (help->dthps_nprovs > 0) {
12900 		mutex_enter(&dtrace_meta_lock);
12901 		if (dtrace_meta_pid != NULL) {
12902 			ASSERT(dtrace_deferred_pid == NULL);
12903 
12904 			for (i = 0; i < help->dthps_nprovs; i++) {
12905 				dtrace_helper_remove(
12906 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
12907 			}
12908 		} else {
12909 			mutex_enter(&dtrace_lock);
12910 			ASSERT(help->dthps_deferred == 0 ||
12911 			    help->dthps_next != NULL ||
12912 			    help->dthps_prev != NULL ||
12913 			    help == dtrace_deferred_pid);
12914 
12915 			/*
12916 			 * Remove the helper from the deferred list.
12917 			 */
12918 			if (help->dthps_next != NULL)
12919 				help->dthps_next->dthps_prev = help->dthps_prev;
12920 			if (help->dthps_prev != NULL)
12921 				help->dthps_prev->dthps_next = help->dthps_next;
12922 			if (dtrace_deferred_pid == help) {
12923 				dtrace_deferred_pid = help->dthps_next;
12924 				ASSERT(help->dthps_prev == NULL);
12925 			}
12926 
12927 			mutex_exit(&dtrace_lock);
12928 		}
12929 
12930 		mutex_exit(&dtrace_meta_lock);
12931 
12932 		for (i = 0; i < help->dthps_nprovs; i++) {
12933 			dtrace_helper_provider_remove(help->dthps_provs[i]);
12934 		}
12935 
12936 		kmem_free(help->dthps_provs, help->dthps_nprovs *
12937 		    sizeof (dtrace_helper_provider_t *));
12938 	}
12939 
12940 	mutex_enter(&dtrace_lock);
12941 
12942 	dtrace_vstate_fini(&help->dthps_vstate);
12943 	kmem_free(help->dthps_actions,
12944 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
12945 	kmem_free(help, sizeof (dtrace_helpers_t));
12946 
12947 	--dtrace_helpers;
12948 	mutex_exit(&dtrace_lock);
12949 }
12950 
12951 static void
12952 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
12953 {
12954 	dtrace_helpers_t *help, *newhelp;
12955 	dtrace_helper_action_t *helper, *new, *last;
12956 	dtrace_difo_t *dp;
12957 	dtrace_vstate_t *vstate;
12958 	int i, j, sz, hasprovs = 0;
12959 
12960 	mutex_enter(&dtrace_lock);
12961 	ASSERT(from->p_dtrace_helpers != NULL);
12962 	ASSERT(dtrace_helpers > 0);
12963 
12964 	help = from->p_dtrace_helpers;
12965 	newhelp = dtrace_helpers_create(to);
12966 	ASSERT(to->p_dtrace_helpers != NULL);
12967 
12968 	newhelp->dthps_generation = help->dthps_generation;
12969 	vstate = &newhelp->dthps_vstate;
12970 
12971 	/*
12972 	 * Duplicate the helper actions.
12973 	 */
12974 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
12975 		if ((helper = help->dthps_actions[i]) == NULL)
12976 			continue;
12977 
12978 		for (last = NULL; helper != NULL; helper = helper->dthp_next) {
12979 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
12980 			    KM_SLEEP);
12981 			new->dthp_generation = helper->dthp_generation;
12982 
12983 			if ((dp = helper->dthp_predicate) != NULL) {
12984 				dp = dtrace_difo_duplicate(dp, vstate);
12985 				new->dthp_predicate = dp;
12986 			}
12987 
12988 			new->dthp_nactions = helper->dthp_nactions;
12989 			sz = sizeof (dtrace_difo_t *) * new->dthp_nactions;
12990 			new->dthp_actions = kmem_alloc(sz, KM_SLEEP);
12991 
12992 			for (j = 0; j < new->dthp_nactions; j++) {
12993 				dtrace_difo_t *dp = helper->dthp_actions[j];
12994 
12995 				ASSERT(dp != NULL);
12996 				dp = dtrace_difo_duplicate(dp, vstate);
12997 				new->dthp_actions[j] = dp;
12998 			}
12999 
13000 			if (last != NULL) {
13001 				last->dthp_next = new;
13002 			} else {
13003 				newhelp->dthps_actions[i] = new;
13004 			}
13005 
13006 			last = new;
13007 		}
13008 	}
13009 
13010 	/*
13011 	 * Duplicate the helper providers and register them with the
13012 	 * DTrace framework.
13013 	 */
13014 	if (help->dthps_nprovs > 0) {
13015 		newhelp->dthps_nprovs = help->dthps_nprovs;
13016 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
13017 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13018 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
13019 			newhelp->dthps_provs[i] = help->dthps_provs[i];
13020 			newhelp->dthps_provs[i]->dthp_ref++;
13021 		}
13022 
13023 		hasprovs = 1;
13024 	}
13025 
13026 	mutex_exit(&dtrace_lock);
13027 
13028 	if (hasprovs)
13029 		dtrace_helper_provider_register(to, newhelp, NULL);
13030 }
13031 
13032 /*
13033  * DTrace Hook Functions
13034  */
13035 static void
13036 dtrace_module_loaded(struct modctl *ctl)
13037 {
13038 	dtrace_provider_t *prv;
13039 
13040 	mutex_enter(&dtrace_provider_lock);
13041 	mutex_enter(&mod_lock);
13042 
13043 	ASSERT(ctl->mod_busy);
13044 
13045 	/*
13046 	 * We're going to call each providers per-module provide operation
13047 	 * specifying only this module.
13048 	 */
13049 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
13050 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
13051 
13052 	mutex_exit(&mod_lock);
13053 	mutex_exit(&dtrace_provider_lock);
13054 
13055 	/*
13056 	 * If we have any retained enablings, we need to match against them.
13057 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
13058 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
13059 	 * module.  (In particular, this happens when loading scheduling
13060 	 * classes.)  So if we have any retained enablings, we need to dispatch
13061 	 * our task queue to do the match for us.
13062 	 */
13063 	mutex_enter(&dtrace_lock);
13064 
13065 	if (dtrace_retained == NULL) {
13066 		mutex_exit(&dtrace_lock);
13067 		return;
13068 	}
13069 
13070 	(void) taskq_dispatch(dtrace_taskq,
13071 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
13072 
13073 	mutex_exit(&dtrace_lock);
13074 
13075 	/*
13076 	 * And now, for a little heuristic sleaze:  in general, we want to
13077 	 * match modules as soon as they load.  However, we cannot guarantee
13078 	 * this, because it would lead us to the lock ordering violation
13079 	 * outlined above.  The common case, of course, is that cpu_lock is
13080 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
13081 	 * long enough for the task queue to do its work.  If it's not, it's
13082 	 * not a serious problem -- it just means that the module that we
13083 	 * just loaded may not be immediately instrumentable.
13084 	 */
13085 	delay(1);
13086 }
13087 
13088 static void
13089 dtrace_module_unloaded(struct modctl *ctl)
13090 {
13091 	dtrace_probe_t template, *probe, *first, *next;
13092 	dtrace_provider_t *prov;
13093 
13094 	template.dtpr_mod = ctl->mod_modname;
13095 
13096 	mutex_enter(&dtrace_provider_lock);
13097 	mutex_enter(&mod_lock);
13098 	mutex_enter(&dtrace_lock);
13099 
13100 	if (dtrace_bymod == NULL) {
13101 		/*
13102 		 * The DTrace module is loaded (obviously) but not attached;
13103 		 * we don't have any work to do.
13104 		 */
13105 		mutex_exit(&dtrace_provider_lock);
13106 		mutex_exit(&mod_lock);
13107 		mutex_exit(&dtrace_lock);
13108 		return;
13109 	}
13110 
13111 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
13112 	    probe != NULL; probe = probe->dtpr_nextmod) {
13113 		if (probe->dtpr_ecb != NULL) {
13114 			mutex_exit(&dtrace_provider_lock);
13115 			mutex_exit(&mod_lock);
13116 			mutex_exit(&dtrace_lock);
13117 
13118 			/*
13119 			 * This shouldn't _actually_ be possible -- we're
13120 			 * unloading a module that has an enabled probe in it.
13121 			 * (It's normally up to the provider to make sure that
13122 			 * this can't happen.)  However, because dtps_enable()
13123 			 * doesn't have a failure mode, there can be an
13124 			 * enable/unload race.  Upshot:  we don't want to
13125 			 * assert, but we're not going to disable the
13126 			 * probe, either.
13127 			 */
13128 			if (dtrace_err_verbose) {
13129 				cmn_err(CE_WARN, "unloaded module '%s' had "
13130 				    "enabled probes", ctl->mod_modname);
13131 			}
13132 
13133 			return;
13134 		}
13135 	}
13136 
13137 	probe = first;
13138 
13139 	for (first = NULL; probe != NULL; probe = next) {
13140 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
13141 
13142 		dtrace_probes[probe->dtpr_id - 1] = NULL;
13143 
13144 		next = probe->dtpr_nextmod;
13145 		dtrace_hash_remove(dtrace_bymod, probe);
13146 		dtrace_hash_remove(dtrace_byfunc, probe);
13147 		dtrace_hash_remove(dtrace_byname, probe);
13148 
13149 		if (first == NULL) {
13150 			first = probe;
13151 			probe->dtpr_nextmod = NULL;
13152 		} else {
13153 			probe->dtpr_nextmod = first;
13154 			first = probe;
13155 		}
13156 	}
13157 
13158 	/*
13159 	 * We've removed all of the module's probes from the hash chains and
13160 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
13161 	 * everyone has cleared out from any probe array processing.
13162 	 */
13163 	dtrace_sync();
13164 
13165 	for (probe = first; probe != NULL; probe = first) {
13166 		first = probe->dtpr_nextmod;
13167 		prov = probe->dtpr_provider;
13168 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
13169 		    probe->dtpr_arg);
13170 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
13171 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
13172 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
13173 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
13174 		kmem_free(probe, sizeof (dtrace_probe_t));
13175 	}
13176 
13177 	mutex_exit(&dtrace_lock);
13178 	mutex_exit(&mod_lock);
13179 	mutex_exit(&dtrace_provider_lock);
13180 }
13181 
13182 void
13183 dtrace_suspend(void)
13184 {
13185 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
13186 }
13187 
13188 void
13189 dtrace_resume(void)
13190 {
13191 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
13192 }
13193 
13194 static int
13195 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
13196 {
13197 	ASSERT(MUTEX_HELD(&cpu_lock));
13198 	mutex_enter(&dtrace_lock);
13199 
13200 	switch (what) {
13201 	case CPU_CONFIG: {
13202 		dtrace_state_t *state;
13203 		dtrace_optval_t *opt, rs, c;
13204 
13205 		/*
13206 		 * For now, we only allocate a new buffer for anonymous state.
13207 		 */
13208 		if ((state = dtrace_anon.dta_state) == NULL)
13209 			break;
13210 
13211 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13212 			break;
13213 
13214 		opt = state->dts_options;
13215 		c = opt[DTRACEOPT_CPU];
13216 
13217 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
13218 			break;
13219 
13220 		/*
13221 		 * Regardless of what the actual policy is, we're going to
13222 		 * temporarily set our resize policy to be manual.  We're
13223 		 * also going to temporarily set our CPU option to denote
13224 		 * the newly configured CPU.
13225 		 */
13226 		rs = opt[DTRACEOPT_BUFRESIZE];
13227 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
13228 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
13229 
13230 		(void) dtrace_state_buffers(state);
13231 
13232 		opt[DTRACEOPT_BUFRESIZE] = rs;
13233 		opt[DTRACEOPT_CPU] = c;
13234 
13235 		break;
13236 	}
13237 
13238 	case CPU_UNCONFIG:
13239 		/*
13240 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
13241 		 * buffer will be freed when the consumer exits.)
13242 		 */
13243 		break;
13244 
13245 	default:
13246 		break;
13247 	}
13248 
13249 	mutex_exit(&dtrace_lock);
13250 	return (0);
13251 }
13252 
13253 static void
13254 dtrace_cpu_setup_initial(processorid_t cpu)
13255 {
13256 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
13257 }
13258 
13259 static void
13260 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
13261 {
13262 	if (dtrace_toxranges >= dtrace_toxranges_max) {
13263 		int osize, nsize;
13264 		dtrace_toxrange_t *range;
13265 
13266 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
13267 
13268 		if (osize == 0) {
13269 			ASSERT(dtrace_toxrange == NULL);
13270 			ASSERT(dtrace_toxranges_max == 0);
13271 			dtrace_toxranges_max = 1;
13272 		} else {
13273 			dtrace_toxranges_max <<= 1;
13274 		}
13275 
13276 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
13277 		range = kmem_zalloc(nsize, KM_SLEEP);
13278 
13279 		if (dtrace_toxrange != NULL) {
13280 			ASSERT(osize != 0);
13281 			bcopy(dtrace_toxrange, range, osize);
13282 			kmem_free(dtrace_toxrange, osize);
13283 		}
13284 
13285 		dtrace_toxrange = range;
13286 	}
13287 
13288 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
13289 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
13290 
13291 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
13292 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
13293 	dtrace_toxranges++;
13294 }
13295 
13296 /*
13297  * DTrace Driver Cookbook Functions
13298  */
13299 /*ARGSUSED*/
13300 static int
13301 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
13302 {
13303 	dtrace_provider_id_t id;
13304 	dtrace_state_t *state = NULL;
13305 	dtrace_enabling_t *enab;
13306 
13307 	mutex_enter(&cpu_lock);
13308 	mutex_enter(&dtrace_provider_lock);
13309 	mutex_enter(&dtrace_lock);
13310 
13311 	if (ddi_soft_state_init(&dtrace_softstate,
13312 	    sizeof (dtrace_state_t), 0) != 0) {
13313 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
13314 		mutex_exit(&cpu_lock);
13315 		mutex_exit(&dtrace_provider_lock);
13316 		mutex_exit(&dtrace_lock);
13317 		return (DDI_FAILURE);
13318 	}
13319 
13320 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
13321 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
13322 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
13323 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
13324 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
13325 		ddi_remove_minor_node(devi, NULL);
13326 		ddi_soft_state_fini(&dtrace_softstate);
13327 		mutex_exit(&cpu_lock);
13328 		mutex_exit(&dtrace_provider_lock);
13329 		mutex_exit(&dtrace_lock);
13330 		return (DDI_FAILURE);
13331 	}
13332 
13333 	ddi_report_dev(devi);
13334 	dtrace_devi = devi;
13335 
13336 	dtrace_modload = dtrace_module_loaded;
13337 	dtrace_modunload = dtrace_module_unloaded;
13338 	dtrace_cpu_init = dtrace_cpu_setup_initial;
13339 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
13340 	dtrace_helpers_fork = dtrace_helpers_duplicate;
13341 	dtrace_cpustart_init = dtrace_suspend;
13342 	dtrace_cpustart_fini = dtrace_resume;
13343 	dtrace_debugger_init = dtrace_suspend;
13344 	dtrace_debugger_fini = dtrace_resume;
13345 	dtrace_kreloc_init = dtrace_suspend;
13346 	dtrace_kreloc_fini = dtrace_resume;
13347 
13348 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
13349 
13350 	ASSERT(MUTEX_HELD(&cpu_lock));
13351 
13352 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
13353 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13354 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
13355 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
13356 	    VM_SLEEP | VMC_IDENTIFIER);
13357 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
13358 	    1, INT_MAX, 0);
13359 
13360 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
13361 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
13362 	    NULL, NULL, NULL, NULL, NULL, 0);
13363 
13364 	ASSERT(MUTEX_HELD(&cpu_lock));
13365 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
13366 	    offsetof(dtrace_probe_t, dtpr_nextmod),
13367 	    offsetof(dtrace_probe_t, dtpr_prevmod));
13368 
13369 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
13370 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
13371 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
13372 
13373 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
13374 	    offsetof(dtrace_probe_t, dtpr_nextname),
13375 	    offsetof(dtrace_probe_t, dtpr_prevname));
13376 
13377 	if (dtrace_retain_max < 1) {
13378 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
13379 		    "setting to 1", dtrace_retain_max);
13380 		dtrace_retain_max = 1;
13381 	}
13382 
13383 	/*
13384 	 * Now discover our toxic ranges.
13385 	 */
13386 	dtrace_toxic_ranges(dtrace_toxrange_add);
13387 
13388 	/*
13389 	 * Before we register ourselves as a provider to our own framework,
13390 	 * we would like to assert that dtrace_provider is NULL -- but that's
13391 	 * not true if we were loaded as a dependency of a DTrace provider.
13392 	 * Once we've registered, we can assert that dtrace_provider is our
13393 	 * pseudo provider.
13394 	 */
13395 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
13396 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
13397 
13398 	ASSERT(dtrace_provider != NULL);
13399 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
13400 
13401 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
13402 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
13403 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
13404 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
13405 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
13406 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
13407 
13408 	dtrace_anon_property();
13409 	mutex_exit(&cpu_lock);
13410 
13411 	/*
13412 	 * If DTrace helper tracing is enabled, we need to allocate the
13413 	 * trace buffer and initialize the values.
13414 	 */
13415 	if (dtrace_helptrace_enabled) {
13416 		ASSERT(dtrace_helptrace_buffer == NULL);
13417 		dtrace_helptrace_buffer =
13418 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
13419 		dtrace_helptrace_next = 0;
13420 	}
13421 
13422 	/*
13423 	 * If there are already providers, we must ask them to provide their
13424 	 * probes, and then match any anonymous enabling against them.  Note
13425 	 * that there should be no other retained enablings at this time:
13426 	 * the only retained enablings at this time should be the anonymous
13427 	 * enabling.
13428 	 */
13429 	if (dtrace_anon.dta_enabling != NULL) {
13430 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
13431 
13432 		dtrace_enabling_provide(NULL);
13433 		state = dtrace_anon.dta_state;
13434 
13435 		/*
13436 		 * We couldn't hold cpu_lock across the above call to
13437 		 * dtrace_enabling_provide(), but we must hold it to actually
13438 		 * enable the probes.  We have to drop all of our locks, pick
13439 		 * up cpu_lock, and regain our locks before matching the
13440 		 * retained anonymous enabling.
13441 		 */
13442 		mutex_exit(&dtrace_lock);
13443 		mutex_exit(&dtrace_provider_lock);
13444 
13445 		mutex_enter(&cpu_lock);
13446 		mutex_enter(&dtrace_provider_lock);
13447 		mutex_enter(&dtrace_lock);
13448 
13449 		if ((enab = dtrace_anon.dta_enabling) != NULL)
13450 			(void) dtrace_enabling_match(enab, NULL);
13451 
13452 		mutex_exit(&cpu_lock);
13453 	}
13454 
13455 	mutex_exit(&dtrace_lock);
13456 	mutex_exit(&dtrace_provider_lock);
13457 
13458 	if (state != NULL) {
13459 		/*
13460 		 * If we created any anonymous state, set it going now.
13461 		 */
13462 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
13463 	}
13464 
13465 	return (DDI_SUCCESS);
13466 }
13467 
13468 /*ARGSUSED*/
13469 static int
13470 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
13471 {
13472 	dtrace_state_t *state;
13473 	uint32_t priv;
13474 	uid_t uid;
13475 	zoneid_t zoneid;
13476 
13477 	if (getminor(*devp) == DTRACEMNRN_HELPER)
13478 		return (0);
13479 
13480 	/*
13481 	 * If this wasn't an open with the "helper" minor, then it must be
13482 	 * the "dtrace" minor.
13483 	 */
13484 	ASSERT(getminor(*devp) == DTRACEMNRN_DTRACE);
13485 
13486 	/*
13487 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
13488 	 * caller lacks sufficient permission to do anything with DTrace.
13489 	 */
13490 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
13491 	if (priv == DTRACE_PRIV_NONE)
13492 		return (EACCES);
13493 
13494 	/*
13495 	 * Ask all providers to provide all their probes.
13496 	 */
13497 	mutex_enter(&dtrace_provider_lock);
13498 	dtrace_probe_provide(NULL, NULL);
13499 	mutex_exit(&dtrace_provider_lock);
13500 
13501 	mutex_enter(&cpu_lock);
13502 	mutex_enter(&dtrace_lock);
13503 	dtrace_opens++;
13504 	dtrace_membar_producer();
13505 
13506 	/*
13507 	 * If the kernel debugger is active (that is, if the kernel debugger
13508 	 * modified text in some way), we won't allow the open.
13509 	 */
13510 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
13511 		dtrace_opens--;
13512 		mutex_exit(&cpu_lock);
13513 		mutex_exit(&dtrace_lock);
13514 		return (EBUSY);
13515 	}
13516 
13517 	state = dtrace_state_create(devp, cred_p);
13518 	mutex_exit(&cpu_lock);
13519 
13520 	if (state == NULL) {
13521 		if (--dtrace_opens == 0)
13522 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
13523 		mutex_exit(&dtrace_lock);
13524 		return (EAGAIN);
13525 	}
13526 
13527 	mutex_exit(&dtrace_lock);
13528 
13529 	return (0);
13530 }
13531 
13532 /*ARGSUSED*/
13533 static int
13534 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
13535 {
13536 	minor_t minor = getminor(dev);
13537 	dtrace_state_t *state;
13538 
13539 	if (minor == DTRACEMNRN_HELPER)
13540 		return (0);
13541 
13542 	state = ddi_get_soft_state(dtrace_softstate, minor);
13543 
13544 	mutex_enter(&cpu_lock);
13545 	mutex_enter(&dtrace_lock);
13546 
13547 	if (state->dts_anon) {
13548 		/*
13549 		 * There is anonymous state. Destroy that first.
13550 		 */
13551 		ASSERT(dtrace_anon.dta_state == NULL);
13552 		dtrace_state_destroy(state->dts_anon);
13553 	}
13554 
13555 	dtrace_state_destroy(state);
13556 	ASSERT(dtrace_opens > 0);
13557 	if (--dtrace_opens == 0)
13558 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
13559 
13560 	mutex_exit(&dtrace_lock);
13561 	mutex_exit(&cpu_lock);
13562 
13563 	return (0);
13564 }
13565 
13566 /*ARGSUSED*/
13567 static int
13568 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
13569 {
13570 	int rval;
13571 	dof_helper_t help, *dhp = NULL;
13572 
13573 	switch (cmd) {
13574 	case DTRACEHIOC_ADDDOF:
13575 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
13576 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
13577 			return (EFAULT);
13578 		}
13579 
13580 		dhp = &help;
13581 		arg = (intptr_t)help.dofhp_dof;
13582 		/*FALLTHROUGH*/
13583 
13584 	case DTRACEHIOC_ADD: {
13585 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
13586 
13587 		if (dof == NULL)
13588 			return (rval);
13589 
13590 		mutex_enter(&dtrace_lock);
13591 
13592 		/*
13593 		 * dtrace_helper_slurp() takes responsibility for the dof --
13594 		 * it may free it now or it may save it and free it later.
13595 		 */
13596 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
13597 			*rv = rval;
13598 			rval = 0;
13599 		} else {
13600 			rval = EINVAL;
13601 		}
13602 
13603 		mutex_exit(&dtrace_lock);
13604 		return (rval);
13605 	}
13606 
13607 	case DTRACEHIOC_REMOVE: {
13608 		mutex_enter(&dtrace_lock);
13609 		rval = dtrace_helper_destroygen(arg);
13610 		mutex_exit(&dtrace_lock);
13611 
13612 		return (rval);
13613 	}
13614 
13615 	default:
13616 		break;
13617 	}
13618 
13619 	return (ENOTTY);
13620 }
13621 
13622 /*ARGSUSED*/
13623 static int
13624 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
13625 {
13626 	minor_t minor = getminor(dev);
13627 	dtrace_state_t *state;
13628 	int rval;
13629 
13630 	if (minor == DTRACEMNRN_HELPER)
13631 		return (dtrace_ioctl_helper(cmd, arg, rv));
13632 
13633 	state = ddi_get_soft_state(dtrace_softstate, minor);
13634 
13635 	if (state->dts_anon) {
13636 		ASSERT(dtrace_anon.dta_state == NULL);
13637 		state = state->dts_anon;
13638 	}
13639 
13640 	switch (cmd) {
13641 	case DTRACEIOC_PROVIDER: {
13642 		dtrace_providerdesc_t pvd;
13643 		dtrace_provider_t *pvp;
13644 
13645 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
13646 			return (EFAULT);
13647 
13648 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
13649 		mutex_enter(&dtrace_provider_lock);
13650 
13651 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
13652 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
13653 				break;
13654 		}
13655 
13656 		mutex_exit(&dtrace_provider_lock);
13657 
13658 		if (pvp == NULL)
13659 			return (ESRCH);
13660 
13661 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
13662 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
13663 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
13664 			return (EFAULT);
13665 
13666 		return (0);
13667 	}
13668 
13669 	case DTRACEIOC_EPROBE: {
13670 		dtrace_eprobedesc_t epdesc;
13671 		dtrace_ecb_t *ecb;
13672 		dtrace_action_t *act;
13673 		void *buf;
13674 		size_t size;
13675 		uintptr_t dest;
13676 		int nrecs;
13677 
13678 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
13679 			return (EFAULT);
13680 
13681 		mutex_enter(&dtrace_lock);
13682 
13683 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
13684 			mutex_exit(&dtrace_lock);
13685 			return (EINVAL);
13686 		}
13687 
13688 		if (ecb->dte_probe == NULL) {
13689 			mutex_exit(&dtrace_lock);
13690 			return (EINVAL);
13691 		}
13692 
13693 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
13694 		epdesc.dtepd_uarg = ecb->dte_uarg;
13695 		epdesc.dtepd_size = ecb->dte_size;
13696 
13697 		nrecs = epdesc.dtepd_nrecs;
13698 		epdesc.dtepd_nrecs = 0;
13699 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
13700 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
13701 				continue;
13702 
13703 			epdesc.dtepd_nrecs++;
13704 		}
13705 
13706 		/*
13707 		 * Now that we have the size, we need to allocate a temporary
13708 		 * buffer in which to store the complete description.  We need
13709 		 * the temporary buffer to be able to drop dtrace_lock()
13710 		 * across the copyout(), below.
13711 		 */
13712 		size = sizeof (dtrace_eprobedesc_t) +
13713 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
13714 
13715 		buf = kmem_alloc(size, KM_SLEEP);
13716 		dest = (uintptr_t)buf;
13717 
13718 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
13719 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
13720 
13721 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
13722 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
13723 				continue;
13724 
13725 			if (nrecs-- == 0)
13726 				break;
13727 
13728 			bcopy(&act->dta_rec, (void *)dest,
13729 			    sizeof (dtrace_recdesc_t));
13730 			dest += sizeof (dtrace_recdesc_t);
13731 		}
13732 
13733 		mutex_exit(&dtrace_lock);
13734 
13735 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
13736 			kmem_free(buf, size);
13737 			return (EFAULT);
13738 		}
13739 
13740 		kmem_free(buf, size);
13741 		return (0);
13742 	}
13743 
13744 	case DTRACEIOC_AGGDESC: {
13745 		dtrace_aggdesc_t aggdesc;
13746 		dtrace_action_t *act;
13747 		dtrace_aggregation_t *agg;
13748 		int nrecs;
13749 		uint32_t offs;
13750 		dtrace_recdesc_t *lrec;
13751 		void *buf;
13752 		size_t size;
13753 		uintptr_t dest;
13754 
13755 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
13756 			return (EFAULT);
13757 
13758 		mutex_enter(&dtrace_lock);
13759 
13760 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
13761 			mutex_exit(&dtrace_lock);
13762 			return (EINVAL);
13763 		}
13764 
13765 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
13766 
13767 		nrecs = aggdesc.dtagd_nrecs;
13768 		aggdesc.dtagd_nrecs = 0;
13769 
13770 		offs = agg->dtag_base;
13771 		lrec = &agg->dtag_action.dta_rec;
13772 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
13773 
13774 		for (act = agg->dtag_first; ; act = act->dta_next) {
13775 			ASSERT(act->dta_intuple ||
13776 			    DTRACEACT_ISAGG(act->dta_kind));
13777 
13778 			/*
13779 			 * If this action has a record size of zero, it
13780 			 * denotes an argument to the aggregating action.
13781 			 * Because the presence of this record doesn't (or
13782 			 * shouldn't) affect the way the data is interpreted,
13783 			 * we don't copy it out to save user-level the
13784 			 * confusion of dealing with a zero-length record.
13785 			 */
13786 			if (act->dta_rec.dtrd_size == 0) {
13787 				ASSERT(agg->dtag_hasarg);
13788 				continue;
13789 			}
13790 
13791 			aggdesc.dtagd_nrecs++;
13792 
13793 			if (act == &agg->dtag_action)
13794 				break;
13795 		}
13796 
13797 		/*
13798 		 * Now that we have the size, we need to allocate a temporary
13799 		 * buffer in which to store the complete description.  We need
13800 		 * the temporary buffer to be able to drop dtrace_lock()
13801 		 * across the copyout(), below.
13802 		 */
13803 		size = sizeof (dtrace_aggdesc_t) +
13804 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
13805 
13806 		buf = kmem_alloc(size, KM_SLEEP);
13807 		dest = (uintptr_t)buf;
13808 
13809 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
13810 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
13811 
13812 		for (act = agg->dtag_first; ; act = act->dta_next) {
13813 			dtrace_recdesc_t rec = act->dta_rec;
13814 
13815 			/*
13816 			 * See the comment in the above loop for why we pass
13817 			 * over zero-length records.
13818 			 */
13819 			if (rec.dtrd_size == 0) {
13820 				ASSERT(agg->dtag_hasarg);
13821 				continue;
13822 			}
13823 
13824 			if (nrecs-- == 0)
13825 				break;
13826 
13827 			rec.dtrd_offset -= offs;
13828 			bcopy(&rec, (void *)dest, sizeof (rec));
13829 			dest += sizeof (dtrace_recdesc_t);
13830 
13831 			if (act == &agg->dtag_action)
13832 				break;
13833 		}
13834 
13835 		mutex_exit(&dtrace_lock);
13836 
13837 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
13838 			kmem_free(buf, size);
13839 			return (EFAULT);
13840 		}
13841 
13842 		kmem_free(buf, size);
13843 		return (0);
13844 	}
13845 
13846 	case DTRACEIOC_ENABLE: {
13847 		dof_hdr_t *dof;
13848 		dtrace_enabling_t *enab = NULL;
13849 		dtrace_vstate_t *vstate;
13850 		int err = 0;
13851 
13852 		*rv = 0;
13853 
13854 		/*
13855 		 * If a NULL argument has been passed, we take this as our
13856 		 * cue to reevaluate our enablings.
13857 		 */
13858 		if (arg == NULL) {
13859 			mutex_enter(&cpu_lock);
13860 			mutex_enter(&dtrace_lock);
13861 			err = dtrace_enabling_matchstate(state, rv);
13862 			mutex_exit(&dtrace_lock);
13863 			mutex_exit(&cpu_lock);
13864 
13865 			return (err);
13866 		}
13867 
13868 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
13869 			return (rval);
13870 
13871 		mutex_enter(&cpu_lock);
13872 		mutex_enter(&dtrace_lock);
13873 		vstate = &state->dts_vstate;
13874 
13875 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13876 			mutex_exit(&dtrace_lock);
13877 			mutex_exit(&cpu_lock);
13878 			dtrace_dof_destroy(dof);
13879 			return (EBUSY);
13880 		}
13881 
13882 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
13883 			mutex_exit(&dtrace_lock);
13884 			mutex_exit(&cpu_lock);
13885 			dtrace_dof_destroy(dof);
13886 			return (EINVAL);
13887 		}
13888 
13889 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
13890 			dtrace_enabling_destroy(enab);
13891 			mutex_exit(&dtrace_lock);
13892 			mutex_exit(&cpu_lock);
13893 			dtrace_dof_destroy(dof);
13894 			return (rval);
13895 		}
13896 
13897 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
13898 			err = dtrace_enabling_retain(enab);
13899 		} else {
13900 			dtrace_enabling_destroy(enab);
13901 		}
13902 
13903 		mutex_exit(&cpu_lock);
13904 		mutex_exit(&dtrace_lock);
13905 		dtrace_dof_destroy(dof);
13906 
13907 		return (err);
13908 	}
13909 
13910 	case DTRACEIOC_REPLICATE: {
13911 		dtrace_repldesc_t desc;
13912 		dtrace_probedesc_t *match = &desc.dtrpd_match;
13913 		dtrace_probedesc_t *create = &desc.dtrpd_create;
13914 		int err;
13915 
13916 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
13917 			return (EFAULT);
13918 
13919 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
13920 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
13921 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
13922 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
13923 
13924 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
13925 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
13926 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
13927 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
13928 
13929 		mutex_enter(&dtrace_lock);
13930 		err = dtrace_enabling_replicate(state, match, create);
13931 		mutex_exit(&dtrace_lock);
13932 
13933 		return (err);
13934 	}
13935 
13936 	case DTRACEIOC_PROBEMATCH:
13937 	case DTRACEIOC_PROBES: {
13938 		dtrace_probe_t *probe = NULL;
13939 		dtrace_probedesc_t desc;
13940 		dtrace_probekey_t pkey;
13941 		dtrace_id_t i;
13942 		int m = 0;
13943 		uint32_t priv;
13944 		uid_t uid;
13945 		zoneid_t zoneid;
13946 
13947 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
13948 			return (EFAULT);
13949 
13950 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
13951 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
13952 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
13953 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
13954 
13955 		/*
13956 		 * Before we attempt to match this probe, we want to give
13957 		 * all providers the opportunity to provide it.
13958 		 */
13959 		if (desc.dtpd_id == DTRACE_IDNONE) {
13960 			mutex_enter(&dtrace_provider_lock);
13961 			dtrace_probe_provide(&desc, NULL);
13962 			mutex_exit(&dtrace_provider_lock);
13963 			desc.dtpd_id++;
13964 		}
13965 
13966 		if (cmd == DTRACEIOC_PROBEMATCH)  {
13967 			dtrace_probekey(&desc, &pkey);
13968 			pkey.dtpk_id = DTRACE_IDNONE;
13969 		}
13970 
13971 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
13972 
13973 		mutex_enter(&dtrace_lock);
13974 
13975 		if (cmd == DTRACEIOC_PROBEMATCH) {
13976 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
13977 				if ((probe = dtrace_probes[i - 1]) != NULL &&
13978 				    (m = dtrace_match_probe(probe, &pkey,
13979 				    priv, uid, zoneid)) != 0)
13980 					break;
13981 			}
13982 
13983 			if (m < 0) {
13984 				mutex_exit(&dtrace_lock);
13985 				return (EINVAL);
13986 			}
13987 
13988 		} else {
13989 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
13990 				if ((probe = dtrace_probes[i - 1]) != NULL &&
13991 				    dtrace_match_priv(probe, priv, uid, zoneid))
13992 					break;
13993 			}
13994 		}
13995 
13996 		if (probe == NULL) {
13997 			mutex_exit(&dtrace_lock);
13998 			return (ESRCH);
13999 		}
14000 
14001 		dtrace_probe_description(probe, &desc);
14002 		mutex_exit(&dtrace_lock);
14003 
14004 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14005 			return (EFAULT);
14006 
14007 		return (0);
14008 	}
14009 
14010 	case DTRACEIOC_PROBEARG: {
14011 		dtrace_argdesc_t desc;
14012 		dtrace_probe_t *probe;
14013 		dtrace_provider_t *prov;
14014 
14015 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14016 			return (EFAULT);
14017 
14018 		if (desc.dtargd_id == DTRACE_IDNONE)
14019 			return (EINVAL);
14020 
14021 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
14022 			return (EINVAL);
14023 
14024 		mutex_enter(&dtrace_provider_lock);
14025 		mutex_enter(&mod_lock);
14026 		mutex_enter(&dtrace_lock);
14027 
14028 		if (desc.dtargd_id > dtrace_nprobes) {
14029 			mutex_exit(&dtrace_lock);
14030 			mutex_exit(&mod_lock);
14031 			mutex_exit(&dtrace_provider_lock);
14032 			return (EINVAL);
14033 		}
14034 
14035 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
14036 			mutex_exit(&dtrace_lock);
14037 			mutex_exit(&mod_lock);
14038 			mutex_exit(&dtrace_provider_lock);
14039 			return (EINVAL);
14040 		}
14041 
14042 		mutex_exit(&dtrace_lock);
14043 
14044 		prov = probe->dtpr_provider;
14045 
14046 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
14047 			/*
14048 			 * There isn't any typed information for this probe.
14049 			 * Set the argument number to DTRACE_ARGNONE.
14050 			 */
14051 			desc.dtargd_ndx = DTRACE_ARGNONE;
14052 		} else {
14053 			desc.dtargd_native[0] = '\0';
14054 			desc.dtargd_xlate[0] = '\0';
14055 			desc.dtargd_mapping = desc.dtargd_ndx;
14056 
14057 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
14058 			    probe->dtpr_id, probe->dtpr_arg, &desc);
14059 		}
14060 
14061 		mutex_exit(&mod_lock);
14062 		mutex_exit(&dtrace_provider_lock);
14063 
14064 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14065 			return (EFAULT);
14066 
14067 		return (0);
14068 	}
14069 
14070 	case DTRACEIOC_GO: {
14071 		processorid_t cpuid;
14072 		rval = dtrace_state_go(state, &cpuid);
14073 
14074 		if (rval != 0)
14075 			return (rval);
14076 
14077 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14078 			return (EFAULT);
14079 
14080 		return (0);
14081 	}
14082 
14083 	case DTRACEIOC_STOP: {
14084 		processorid_t cpuid;
14085 
14086 		mutex_enter(&dtrace_lock);
14087 		rval = dtrace_state_stop(state, &cpuid);
14088 		mutex_exit(&dtrace_lock);
14089 
14090 		if (rval != 0)
14091 			return (rval);
14092 
14093 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14094 			return (EFAULT);
14095 
14096 		return (0);
14097 	}
14098 
14099 	case DTRACEIOC_DOFGET: {
14100 		dof_hdr_t hdr, *dof;
14101 		uint64_t len;
14102 
14103 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
14104 			return (EFAULT);
14105 
14106 		mutex_enter(&dtrace_lock);
14107 		dof = dtrace_dof_create(state);
14108 		mutex_exit(&dtrace_lock);
14109 
14110 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
14111 		rval = copyout(dof, (void *)arg, len);
14112 		dtrace_dof_destroy(dof);
14113 
14114 		return (rval == 0 ? 0 : EFAULT);
14115 	}
14116 
14117 	case DTRACEIOC_AGGSNAP:
14118 	case DTRACEIOC_BUFSNAP: {
14119 		dtrace_bufdesc_t desc;
14120 		caddr_t cached;
14121 		dtrace_buffer_t *buf;
14122 
14123 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14124 			return (EFAULT);
14125 
14126 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
14127 			return (EINVAL);
14128 
14129 		mutex_enter(&dtrace_lock);
14130 
14131 		if (cmd == DTRACEIOC_BUFSNAP) {
14132 			buf = &state->dts_buffer[desc.dtbd_cpu];
14133 		} else {
14134 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
14135 		}
14136 
14137 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
14138 			size_t sz = buf->dtb_offset;
14139 
14140 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
14141 				mutex_exit(&dtrace_lock);
14142 				return (EBUSY);
14143 			}
14144 
14145 			/*
14146 			 * If this buffer has already been consumed, we're
14147 			 * going to indicate that there's nothing left here
14148 			 * to consume.
14149 			 */
14150 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
14151 				mutex_exit(&dtrace_lock);
14152 
14153 				desc.dtbd_size = 0;
14154 				desc.dtbd_drops = 0;
14155 				desc.dtbd_errors = 0;
14156 				desc.dtbd_oldest = 0;
14157 				sz = sizeof (desc);
14158 
14159 				if (copyout(&desc, (void *)arg, sz) != 0)
14160 					return (EFAULT);
14161 
14162 				return (0);
14163 			}
14164 
14165 			/*
14166 			 * If this is a ring buffer that has wrapped, we want
14167 			 * to copy the whole thing out.
14168 			 */
14169 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
14170 				dtrace_buffer_polish(buf);
14171 				sz = buf->dtb_size;
14172 			}
14173 
14174 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
14175 				mutex_exit(&dtrace_lock);
14176 				return (EFAULT);
14177 			}
14178 
14179 			desc.dtbd_size = sz;
14180 			desc.dtbd_drops = buf->dtb_drops;
14181 			desc.dtbd_errors = buf->dtb_errors;
14182 			desc.dtbd_oldest = buf->dtb_xamot_offset;
14183 
14184 			mutex_exit(&dtrace_lock);
14185 
14186 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14187 				return (EFAULT);
14188 
14189 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
14190 
14191 			return (0);
14192 		}
14193 
14194 		if (buf->dtb_tomax == NULL) {
14195 			ASSERT(buf->dtb_xamot == NULL);
14196 			mutex_exit(&dtrace_lock);
14197 			return (ENOENT);
14198 		}
14199 
14200 		cached = buf->dtb_tomax;
14201 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
14202 
14203 		dtrace_xcall(desc.dtbd_cpu,
14204 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
14205 
14206 		state->dts_errors += buf->dtb_xamot_errors;
14207 
14208 		/*
14209 		 * If the buffers did not actually switch, then the cross call
14210 		 * did not take place -- presumably because the given CPU is
14211 		 * not in the ready set.  If this is the case, we'll return
14212 		 * ENOENT.
14213 		 */
14214 		if (buf->dtb_tomax == cached) {
14215 			ASSERT(buf->dtb_xamot != cached);
14216 			mutex_exit(&dtrace_lock);
14217 			return (ENOENT);
14218 		}
14219 
14220 		ASSERT(cached == buf->dtb_xamot);
14221 
14222 		/*
14223 		 * We have our snapshot; now copy it out.
14224 		 */
14225 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
14226 		    buf->dtb_xamot_offset) != 0) {
14227 			mutex_exit(&dtrace_lock);
14228 			return (EFAULT);
14229 		}
14230 
14231 		desc.dtbd_size = buf->dtb_xamot_offset;
14232 		desc.dtbd_drops = buf->dtb_xamot_drops;
14233 		desc.dtbd_errors = buf->dtb_xamot_errors;
14234 		desc.dtbd_oldest = 0;
14235 
14236 		mutex_exit(&dtrace_lock);
14237 
14238 		/*
14239 		 * Finally, copy out the buffer description.
14240 		 */
14241 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14242 			return (EFAULT);
14243 
14244 		return (0);
14245 	}
14246 
14247 	case DTRACEIOC_CONF: {
14248 		dtrace_conf_t conf;
14249 
14250 		bzero(&conf, sizeof (conf));
14251 		conf.dtc_difversion = DIF_VERSION;
14252 		conf.dtc_difintregs = DIF_DIR_NREGS;
14253 		conf.dtc_diftupregs = DIF_DTR_NREGS;
14254 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
14255 
14256 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
14257 			return (EFAULT);
14258 
14259 		return (0);
14260 	}
14261 
14262 	case DTRACEIOC_STATUS: {
14263 		dtrace_status_t stat;
14264 		dtrace_dstate_t *dstate;
14265 		int i, j;
14266 		uint64_t nerrs;
14267 
14268 		/*
14269 		 * See the comment in dtrace_state_deadman() for the reason
14270 		 * for setting dts_laststatus to INT64_MAX before setting
14271 		 * it to the correct value.
14272 		 */
14273 		state->dts_laststatus = INT64_MAX;
14274 		dtrace_membar_producer();
14275 		state->dts_laststatus = dtrace_gethrtime();
14276 
14277 		bzero(&stat, sizeof (stat));
14278 
14279 		mutex_enter(&dtrace_lock);
14280 
14281 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
14282 			mutex_exit(&dtrace_lock);
14283 			return (ENOENT);
14284 		}
14285 
14286 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
14287 			stat.dtst_exiting = 1;
14288 
14289 		nerrs = state->dts_errors;
14290 		dstate = &state->dts_vstate.dtvs_dynvars;
14291 
14292 		for (i = 0; i < NCPU; i++) {
14293 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
14294 
14295 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
14296 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
14297 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
14298 
14299 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
14300 				stat.dtst_filled++;
14301 
14302 			nerrs += state->dts_buffer[i].dtb_errors;
14303 
14304 			for (j = 0; j < state->dts_nspeculations; j++) {
14305 				dtrace_speculation_t *spec;
14306 				dtrace_buffer_t *buf;
14307 
14308 				spec = &state->dts_speculations[j];
14309 				buf = &spec->dtsp_buffer[i];
14310 				stat.dtst_specdrops += buf->dtb_xamot_drops;
14311 			}
14312 		}
14313 
14314 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
14315 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
14316 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
14317 		stat.dtst_dblerrors = state->dts_dblerrors;
14318 		stat.dtst_killed =
14319 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
14320 		stat.dtst_errors = nerrs;
14321 
14322 		mutex_exit(&dtrace_lock);
14323 
14324 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
14325 			return (EFAULT);
14326 
14327 		return (0);
14328 	}
14329 
14330 	case DTRACEIOC_FORMAT: {
14331 		dtrace_fmtdesc_t fmt;
14332 		char *str;
14333 		int len;
14334 
14335 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
14336 			return (EFAULT);
14337 
14338 		mutex_enter(&dtrace_lock);
14339 
14340 		if (fmt.dtfd_format == 0 ||
14341 		    fmt.dtfd_format > state->dts_nformats) {
14342 			mutex_exit(&dtrace_lock);
14343 			return (EINVAL);
14344 		}
14345 
14346 		/*
14347 		 * Format strings are allocated contiguously and they are
14348 		 * never freed; if a format index is less than the number
14349 		 * of formats, we can assert that the format map is non-NULL
14350 		 * and that the format for the specified index is non-NULL.
14351 		 */
14352 		ASSERT(state->dts_formats != NULL);
14353 		str = state->dts_formats[fmt.dtfd_format - 1];
14354 		ASSERT(str != NULL);
14355 
14356 		len = strlen(str) + 1;
14357 
14358 		if (len > fmt.dtfd_length) {
14359 			fmt.dtfd_length = len;
14360 
14361 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
14362 				mutex_exit(&dtrace_lock);
14363 				return (EINVAL);
14364 			}
14365 		} else {
14366 			if (copyout(str, fmt.dtfd_string, len) != 0) {
14367 				mutex_exit(&dtrace_lock);
14368 				return (EINVAL);
14369 			}
14370 		}
14371 
14372 		mutex_exit(&dtrace_lock);
14373 		return (0);
14374 	}
14375 
14376 	default:
14377 		break;
14378 	}
14379 
14380 	return (ENOTTY);
14381 }
14382 
14383 /*ARGSUSED*/
14384 static int
14385 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
14386 {
14387 	dtrace_state_t *state;
14388 
14389 	switch (cmd) {
14390 	case DDI_DETACH:
14391 		break;
14392 
14393 	case DDI_SUSPEND:
14394 		return (DDI_SUCCESS);
14395 
14396 	default:
14397 		return (DDI_FAILURE);
14398 	}
14399 
14400 	mutex_enter(&cpu_lock);
14401 	mutex_enter(&dtrace_provider_lock);
14402 	mutex_enter(&dtrace_lock);
14403 
14404 	ASSERT(dtrace_opens == 0);
14405 
14406 	if (dtrace_helpers > 0) {
14407 		mutex_exit(&dtrace_provider_lock);
14408 		mutex_exit(&dtrace_lock);
14409 		mutex_exit(&cpu_lock);
14410 		return (DDI_FAILURE);
14411 	}
14412 
14413 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
14414 		mutex_exit(&dtrace_provider_lock);
14415 		mutex_exit(&dtrace_lock);
14416 		mutex_exit(&cpu_lock);
14417 		return (DDI_FAILURE);
14418 	}
14419 
14420 	dtrace_provider = NULL;
14421 
14422 	if ((state = dtrace_anon_grab()) != NULL) {
14423 		/*
14424 		 * If there were ECBs on this state, the provider should
14425 		 * have not been allowed to detach; assert that there is
14426 		 * none.
14427 		 */
14428 		ASSERT(state->dts_necbs == 0);
14429 		dtrace_state_destroy(state);
14430 
14431 		/*
14432 		 * If we're being detached with anonymous state, we need to
14433 		 * indicate to the kernel debugger that DTrace is now inactive.
14434 		 */
14435 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14436 	}
14437 
14438 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
14439 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
14440 	dtrace_cpu_init = NULL;
14441 	dtrace_helpers_cleanup = NULL;
14442 	dtrace_helpers_fork = NULL;
14443 	dtrace_cpustart_init = NULL;
14444 	dtrace_cpustart_fini = NULL;
14445 	dtrace_debugger_init = NULL;
14446 	dtrace_debugger_fini = NULL;
14447 	dtrace_kreloc_init = NULL;
14448 	dtrace_kreloc_fini = NULL;
14449 	dtrace_modload = NULL;
14450 	dtrace_modunload = NULL;
14451 
14452 	mutex_exit(&cpu_lock);
14453 
14454 	if (dtrace_helptrace_enabled) {
14455 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
14456 		dtrace_helptrace_buffer = NULL;
14457 	}
14458 
14459 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
14460 	dtrace_probes = NULL;
14461 	dtrace_nprobes = 0;
14462 
14463 	dtrace_hash_destroy(dtrace_bymod);
14464 	dtrace_hash_destroy(dtrace_byfunc);
14465 	dtrace_hash_destroy(dtrace_byname);
14466 	dtrace_bymod = NULL;
14467 	dtrace_byfunc = NULL;
14468 	dtrace_byname = NULL;
14469 
14470 	kmem_cache_destroy(dtrace_state_cache);
14471 	vmem_destroy(dtrace_minor);
14472 	vmem_destroy(dtrace_arena);
14473 
14474 	if (dtrace_toxrange != NULL) {
14475 		kmem_free(dtrace_toxrange,
14476 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
14477 		dtrace_toxrange = NULL;
14478 		dtrace_toxranges = 0;
14479 		dtrace_toxranges_max = 0;
14480 	}
14481 
14482 	ddi_remove_minor_node(dtrace_devi, NULL);
14483 	dtrace_devi = NULL;
14484 
14485 	ddi_soft_state_fini(&dtrace_softstate);
14486 
14487 	ASSERT(dtrace_vtime_references == 0);
14488 	ASSERT(dtrace_opens == 0);
14489 	ASSERT(dtrace_retained == NULL);
14490 
14491 	mutex_exit(&dtrace_lock);
14492 	mutex_exit(&dtrace_provider_lock);
14493 
14494 	/*
14495 	 * We don't destroy the task queue until after we have dropped our
14496 	 * locks (taskq_destroy() may block on running tasks).  To prevent
14497 	 * attempting to do work after we have effectively detached but before
14498 	 * the task queue has been destroyed, all tasks dispatched via the
14499 	 * task queue must check that DTrace is still attached before
14500 	 * performing any operation.
14501 	 */
14502 	taskq_destroy(dtrace_taskq);
14503 	dtrace_taskq = NULL;
14504 
14505 	return (DDI_SUCCESS);
14506 }
14507 
14508 /*ARGSUSED*/
14509 static int
14510 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
14511 {
14512 	int error;
14513 
14514 	switch (infocmd) {
14515 	case DDI_INFO_DEVT2DEVINFO:
14516 		*result = (void *)dtrace_devi;
14517 		error = DDI_SUCCESS;
14518 		break;
14519 	case DDI_INFO_DEVT2INSTANCE:
14520 		*result = (void *)0;
14521 		error = DDI_SUCCESS;
14522 		break;
14523 	default:
14524 		error = DDI_FAILURE;
14525 	}
14526 	return (error);
14527 }
14528 
14529 static struct cb_ops dtrace_cb_ops = {
14530 	dtrace_open,		/* open */
14531 	dtrace_close,		/* close */
14532 	nulldev,		/* strategy */
14533 	nulldev,		/* print */
14534 	nodev,			/* dump */
14535 	nodev,			/* read */
14536 	nodev,			/* write */
14537 	dtrace_ioctl,		/* ioctl */
14538 	nodev,			/* devmap */
14539 	nodev,			/* mmap */
14540 	nodev,			/* segmap */
14541 	nochpoll,		/* poll */
14542 	ddi_prop_op,		/* cb_prop_op */
14543 	0,			/* streamtab  */
14544 	D_NEW | D_MP		/* Driver compatibility flag */
14545 };
14546 
14547 static struct dev_ops dtrace_ops = {
14548 	DEVO_REV,		/* devo_rev */
14549 	0,			/* refcnt */
14550 	dtrace_info,		/* get_dev_info */
14551 	nulldev,		/* identify */
14552 	nulldev,		/* probe */
14553 	dtrace_attach,		/* attach */
14554 	dtrace_detach,		/* detach */
14555 	nodev,			/* reset */
14556 	&dtrace_cb_ops,		/* driver operations */
14557 	NULL,			/* bus operations */
14558 	nodev			/* dev power */
14559 };
14560 
14561 static struct modldrv modldrv = {
14562 	&mod_driverops,		/* module type (this is a pseudo driver) */
14563 	"Dynamic Tracing",	/* name of module */
14564 	&dtrace_ops,		/* driver ops */
14565 };
14566 
14567 static struct modlinkage modlinkage = {
14568 	MODREV_1,
14569 	(void *)&modldrv,
14570 	NULL
14571 };
14572 
14573 int
14574 _init(void)
14575 {
14576 	return (mod_install(&modlinkage));
14577 }
14578 
14579 int
14580 _info(struct modinfo *modinfop)
14581 {
14582 	return (mod_info(&modlinkage, modinfop));
14583 }
14584 
14585 int
14586 _fini(void)
14587 {
14588 	return (mod_remove(&modlinkage));
14589 }
14590