xref: /titanic_44/usr/src/uts/common/dtrace/dtrace.c (revision 6918308b4f7a98b1ab7146af715a679a95b03288)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 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_state_t	*dtrace_state;		/* temporary variable */
188 static int		dtrace_err;		/* temporary variable */
189 
190 /*
191  * DTrace Locking
192  * DTrace is protected by three (relatively coarse-grained) locks:
193  *
194  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
195  *     including enabling state, probes, ECBs, consumer state, helper state,
196  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
197  *     probe context is lock-free -- synchronization is handled via the
198  *     dtrace_sync() cross call mechanism.
199  *
200  * (2) dtrace_provider_lock is required when manipulating provider state, or
201  *     when provider state must be held constant.
202  *
203  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
204  *     when meta provider state must be held constant.
205  *
206  * The lock ordering between these three locks is dtrace_meta_lock before
207  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
208  * several places where dtrace_provider_lock is held by the framework as it
209  * calls into the providers -- which then call back into the framework,
210  * grabbing dtrace_lock.)
211  *
212  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
213  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
214  * role as a coarse-grained lock; it is acquired before both of these locks.
215  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
216  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
217  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
218  * acquired _between_ dtrace_provider_lock and dtrace_lock.
219  */
220 static kmutex_t		dtrace_lock;		/* probe state lock */
221 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
222 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
223 
224 /*
225  * DTrace Provider Variables
226  *
227  * These are the variables relating to DTrace as a provider (that is, the
228  * provider of the BEGIN, END, and ERROR probes).
229  */
230 static dtrace_pattr_t	dtrace_provider_attr = {
231 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
232 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
233 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
234 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
235 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
236 };
237 
238 static void
239 dtrace_nullop(void)
240 {}
241 
242 static dtrace_pops_t	dtrace_provider_ops = {
243 	(void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
244 	(void (*)(void *, struct modctl *))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 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
249 	NULL,
250 	NULL,
251 	NULL,
252 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
253 };
254 
255 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
256 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
257 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
258 
259 /*
260  * DTrace Helper Tracing Variables
261  */
262 uint32_t dtrace_helptrace_next = 0;
263 uint32_t dtrace_helptrace_nlocals;
264 char	*dtrace_helptrace_buffer;
265 int	dtrace_helptrace_bufsize = 512 * 1024;
266 
267 #ifdef DEBUG
268 int	dtrace_helptrace_enabled = 1;
269 #else
270 int	dtrace_helptrace_enabled = 0;
271 #endif
272 
273 /*
274  * DTrace Error Hashing
275  *
276  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
277  * table.  This is very useful for checking coverage of tests that are
278  * expected to induce DIF or DOF processing errors, and may be useful for
279  * debugging problems in the DIF code generator or in DOF generation .  The
280  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
281  */
282 #ifdef DEBUG
283 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
284 static const char *dtrace_errlast;
285 static kthread_t *dtrace_errthread;
286 static kmutex_t dtrace_errlock;
287 #endif
288 
289 /*
290  * DTrace Macros and Constants
291  *
292  * These are various macros that are useful in various spots in the
293  * implementation, along with a few random constants that have no meaning
294  * outside of the implementation.  There is no real structure to this cpp
295  * mishmash -- but is there ever?
296  */
297 #define	DTRACE_HASHSTR(hash, probe)	\
298 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
299 
300 #define	DTRACE_HASHNEXT(hash, probe)	\
301 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
302 
303 #define	DTRACE_HASHPREV(hash, probe)	\
304 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
305 
306 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
307 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
308 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
309 
310 #define	DTRACE_AGGHASHSIZE_SLEW		17
311 
312 /*
313  * The key for a thread-local variable consists of the lower 61 bits of the
314  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
315  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
316  * equal to a variable identifier.  This is necessary (but not sufficient) to
317  * assure that global associative arrays never collide with thread-local
318  * variables.  To guarantee that they cannot collide, we must also define the
319  * order for keying dynamic variables.  That order is:
320  *
321  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
322  *
323  * Because the variable-key and the tls-key are in orthogonal spaces, there is
324  * no way for a global variable key signature to match a thread-local key
325  * signature.
326  */
327 #define	DTRACE_TLS_THRKEY(where) { \
328 	uint_t intr = 0; \
329 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
330 	for (; actv; actv >>= 1) \
331 		intr++; \
332 	ASSERT(intr < (1 << 3)); \
333 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
334 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
335 }
336 
337 #define	DTRACE_STORE(type, tomax, offset, what) \
338 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
339 
340 #ifndef __i386
341 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
342 	if (addr & (size - 1)) {					\
343 		*flags |= CPU_DTRACE_BADALIGN;				\
344 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
345 		return (0);						\
346 	}
347 #else
348 #define	DTRACE_ALIGNCHECK(addr, size, flags)
349 #endif
350 
351 #define	DTRACE_LOADFUNC(bits)						\
352 /*CSTYLED*/								\
353 uint##bits##_t								\
354 dtrace_load##bits(uintptr_t addr)					\
355 {									\
356 	size_t size = bits / NBBY;					\
357 	/*CSTYLED*/							\
358 	uint##bits##_t rval;						\
359 	int i;								\
360 	volatile uint16_t *flags = (volatile uint16_t *)		\
361 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
362 									\
363 	DTRACE_ALIGNCHECK(addr, size, flags);				\
364 									\
365 	for (i = 0; i < dtrace_toxranges; i++) {			\
366 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
367 			continue;					\
368 									\
369 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
370 			continue;					\
371 									\
372 		/*							\
373 		 * This address falls within a toxic region; return 0.	\
374 		 */							\
375 		*flags |= CPU_DTRACE_BADADDR;				\
376 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
377 		return (0);						\
378 	}								\
379 									\
380 	*flags |= CPU_DTRACE_NOFAULT;					\
381 	/*CSTYLED*/							\
382 	rval = *((volatile uint##bits##_t *)addr);			\
383 	*flags &= ~CPU_DTRACE_NOFAULT;					\
384 									\
385 	return (rval);							\
386 }
387 
388 #ifdef _LP64
389 #define	dtrace_loadptr	dtrace_load64
390 #else
391 #define	dtrace_loadptr	dtrace_load32
392 #endif
393 
394 #define	DTRACE_MATCH_NEXT	0
395 #define	DTRACE_MATCH_DONE	1
396 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
397 #define	DTRACE_STATE_ALIGN	64
398 
399 #define	DTRACE_FLAGS2FLT(flags)						\
400 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
401 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
402 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
403 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
404 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
405 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
406 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
407 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
408 	DTRACEFLT_UNKNOWN)
409 
410 #define	DTRACEACT_ISSTRING(act)						\
411 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
412 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
413 
414 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
415 static void dtrace_enabling_provide(dtrace_provider_t *);
416 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
417 static void dtrace_enabling_matchall(void);
418 static dtrace_state_t *dtrace_anon_grab(void);
419 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
420     dtrace_state_t *, uint64_t, uint64_t);
421 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
422 static void dtrace_buffer_drop(dtrace_buffer_t *);
423 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
424     dtrace_state_t *, dtrace_mstate_t *);
425 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
426     dtrace_optval_t);
427 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
428 
429 /*
430  * DTrace Probe Context Functions
431  *
432  * These functions are called from probe context.  Because probe context is
433  * any context in which C may be called, arbitrarily locks may be held,
434  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
435  * As a result, functions called from probe context may only call other DTrace
436  * support functions -- they may not interact at all with the system at large.
437  * (Note that the ASSERT macro is made probe-context safe by redefining it in
438  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
439  * loads are to be performed from probe context, they _must_ be in terms of
440  * the safe dtrace_load*() variants.
441  *
442  * Some functions in this block are not actually called from probe context;
443  * for these functions, there will be a comment above the function reading
444  * "Note:  not called from probe context."
445  */
446 void
447 dtrace_panic(const char *format, ...)
448 {
449 	va_list alist;
450 
451 	va_start(alist, format);
452 	dtrace_vpanic(format, alist);
453 	va_end(alist);
454 }
455 
456 int
457 dtrace_assfail(const char *a, const char *f, int l)
458 {
459 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
460 
461 	/*
462 	 * We just need something here that even the most clever compiler
463 	 * cannot optimize away.
464 	 */
465 	return (a[(uintptr_t)f]);
466 }
467 
468 /*
469  * Atomically increment a specified error counter from probe context.
470  */
471 static void
472 dtrace_error(uint32_t *counter)
473 {
474 	/*
475 	 * Most counters stored to in probe context are per-CPU counters.
476 	 * However, there are some error conditions that are sufficiently
477 	 * arcane that they don't merit per-CPU storage.  If these counters
478 	 * are incremented concurrently on different CPUs, scalability will be
479 	 * adversely affected -- but we don't expect them to be white-hot in a
480 	 * correctly constructed enabling...
481 	 */
482 	uint32_t oval, nval;
483 
484 	do {
485 		oval = *counter;
486 
487 		if ((nval = oval + 1) == 0) {
488 			/*
489 			 * If the counter would wrap, set it to 1 -- assuring
490 			 * that the counter is never zero when we have seen
491 			 * errors.  (The counter must be 32-bits because we
492 			 * aren't guaranteed a 64-bit compare&swap operation.)
493 			 * To save this code both the infamy of being fingered
494 			 * by a priggish news story and the indignity of being
495 			 * the target of a neo-puritan witch trial, we're
496 			 * carefully avoiding any colorful description of the
497 			 * likelihood of this condition -- but suffice it to
498 			 * say that it is only slightly more likely than the
499 			 * overflow of predicate cache IDs, as discussed in
500 			 * dtrace_predicate_create().
501 			 */
502 			nval = 1;
503 		}
504 	} while (dtrace_cas32(counter, oval, nval) != oval);
505 }
506 
507 /*
508  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
509  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
510  */
511 DTRACE_LOADFUNC(8)
512 DTRACE_LOADFUNC(16)
513 DTRACE_LOADFUNC(32)
514 DTRACE_LOADFUNC(64)
515 
516 static int
517 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
518 {
519 	if (dest < mstate->dtms_scratch_base)
520 		return (0);
521 
522 	if (dest + size < dest)
523 		return (0);
524 
525 	if (dest + size > mstate->dtms_scratch_ptr)
526 		return (0);
527 
528 	return (1);
529 }
530 
531 static int
532 dtrace_canstore_statvar(uint64_t addr, size_t sz,
533     dtrace_statvar_t **svars, int nsvars)
534 {
535 	int i;
536 
537 	for (i = 0; i < nsvars; i++) {
538 		dtrace_statvar_t *svar = svars[i];
539 
540 		if (svar == NULL || svar->dtsv_size == 0)
541 			continue;
542 
543 		if (addr - svar->dtsv_data < svar->dtsv_size &&
544 		    addr + sz <= svar->dtsv_data + svar->dtsv_size)
545 			return (1);
546 	}
547 
548 	return (0);
549 }
550 
551 /*
552  * Check to see if the address is within a memory region to which a store may
553  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
554  * region.  The caller of dtrace_canstore() is responsible for performing any
555  * alignment checks that are needed before stores are actually executed.
556  */
557 static int
558 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
559     dtrace_vstate_t *vstate)
560 {
561 	uintptr_t a;
562 	size_t s;
563 
564 	/*
565 	 * First, check to see if the address is in scratch space...
566 	 */
567 	a = mstate->dtms_scratch_base;
568 	s = mstate->dtms_scratch_size;
569 
570 	if (addr - a < s && addr + sz <= a + s)
571 		return (1);
572 
573 	/*
574 	 * Now check to see if it's a dynamic variable.  This check will pick
575 	 * up both thread-local variables and any global dynamically-allocated
576 	 * variables.
577 	 */
578 	a = (uintptr_t)vstate->dtvs_dynvars.dtds_base;
579 	s = vstate->dtvs_dynvars.dtds_size;
580 	if (addr - a < s && addr + sz <= a + s)
581 		return (1);
582 
583 	/*
584 	 * Finally, check the static local and global variables.  These checks
585 	 * take the longest, so we perform them last.
586 	 */
587 	if (dtrace_canstore_statvar(addr, sz,
588 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
589 		return (1);
590 
591 	if (dtrace_canstore_statvar(addr, sz,
592 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
593 		return (1);
594 
595 	return (0);
596 }
597 
598 /*
599  * Compare two strings using safe loads.
600  */
601 static int
602 dtrace_strncmp(char *s1, char *s2, size_t limit)
603 {
604 	uint8_t c1, c2;
605 	volatile uint16_t *flags;
606 
607 	if (s1 == s2 || limit == 0)
608 		return (0);
609 
610 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
611 
612 	do {
613 		if (s1 == NULL) {
614 			c1 = '\0';
615 		} else {
616 			c1 = dtrace_load8((uintptr_t)s1++);
617 		}
618 
619 		if (s2 == NULL) {
620 			c2 = '\0';
621 		} else {
622 			c2 = dtrace_load8((uintptr_t)s2++);
623 		}
624 
625 		if (c1 != c2)
626 			return (c1 - c2);
627 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
628 
629 	return (0);
630 }
631 
632 /*
633  * Compute strlen(s) for a string using safe memory accesses.  The additional
634  * len parameter is used to specify a maximum length to ensure completion.
635  */
636 static size_t
637 dtrace_strlen(const char *s, size_t lim)
638 {
639 	uint_t len;
640 
641 	for (len = 0; len != lim; len++) {
642 		if (dtrace_load8((uintptr_t)s++) == '\0')
643 			break;
644 	}
645 
646 	return (len);
647 }
648 
649 /*
650  * Check if an address falls within a toxic region.
651  */
652 static int
653 dtrace_istoxic(uintptr_t kaddr, size_t size)
654 {
655 	uintptr_t taddr, tsize;
656 	int i;
657 
658 	for (i = 0; i < dtrace_toxranges; i++) {
659 		taddr = dtrace_toxrange[i].dtt_base;
660 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
661 
662 		if (kaddr - taddr < tsize) {
663 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
664 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
665 			return (1);
666 		}
667 
668 		if (taddr - kaddr < size) {
669 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
670 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
671 			return (1);
672 		}
673 	}
674 
675 	return (0);
676 }
677 
678 /*
679  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
680  * memory specified by the DIF program.  The dst is assumed to be safe memory
681  * that we can store to directly because it is managed by DTrace.  As with
682  * standard bcopy, overlapping copies are handled properly.
683  */
684 static void
685 dtrace_bcopy(const void *src, void *dst, size_t len)
686 {
687 	if (len != 0) {
688 		uint8_t *s1 = dst;
689 		const uint8_t *s2 = src;
690 
691 		if (s1 <= s2) {
692 			do {
693 				*s1++ = dtrace_load8((uintptr_t)s2++);
694 			} while (--len != 0);
695 		} else {
696 			s2 += len;
697 			s1 += len;
698 
699 			do {
700 				*--s1 = dtrace_load8((uintptr_t)--s2);
701 			} while (--len != 0);
702 		}
703 	}
704 }
705 
706 /*
707  * Copy src to dst using safe memory accesses, up to either the specified
708  * length, or the point that a nul byte is encountered.  The src is assumed to
709  * be unsafe memory specified by the DIF program.  The dst is assumed to be
710  * safe memory that we can store to directly because it is managed by DTrace.
711  * Unlike dtrace_bcopy(), overlapping regions are not handled.
712  */
713 static void
714 dtrace_strcpy(const void *src, void *dst, size_t len)
715 {
716 	if (len != 0) {
717 		uint8_t *s1 = dst, c;
718 		const uint8_t *s2 = src;
719 
720 		do {
721 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
722 		} while (--len != 0 && c != '\0');
723 	}
724 }
725 
726 /*
727  * Copy src to dst, deriving the size and type from the specified (BYREF)
728  * variable type.  The src is assumed to be unsafe memory specified by the DIF
729  * program.  The dst is assumed to be DTrace variable memory that is of the
730  * specified type; we assume that we can store to directly.
731  */
732 static void
733 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
734 {
735 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
736 
737 	if (type->dtdt_kind == DIF_TYPE_STRING) {
738 		dtrace_strcpy(src, dst, type->dtdt_size);
739 	} else {
740 		dtrace_bcopy(src, dst, type->dtdt_size);
741 	}
742 }
743 
744 /*
745  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
746  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
747  * safe memory that we can access directly because it is managed by DTrace.
748  */
749 static int
750 dtrace_bcmp(const void *s1, const void *s2, size_t len)
751 {
752 	volatile uint16_t *flags;
753 
754 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
755 
756 	if (s1 == s2)
757 		return (0);
758 
759 	if (s1 == NULL || s2 == NULL)
760 		return (1);
761 
762 	if (s1 != s2 && len != 0) {
763 		const uint8_t *ps1 = s1;
764 		const uint8_t *ps2 = s2;
765 
766 		do {
767 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
768 				return (1);
769 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
770 	}
771 	return (0);
772 }
773 
774 /*
775  * Zero the specified region using a simple byte-by-byte loop.  Note that this
776  * is for safe DTrace-managed memory only.
777  */
778 static void
779 dtrace_bzero(void *dst, size_t len)
780 {
781 	uchar_t *cp;
782 
783 	for (cp = dst; len != 0; len--)
784 		*cp++ = 0;
785 }
786 
787 /*
788  * This privilege checks should be used by actions and subroutines to
789  * verify the credentials of the process that enabled the invoking ECB.
790  */
791 static int
792 dtrace_priv_proc_common(dtrace_state_t *state)
793 {
794 	uid_t uid = state->dts_cred.dcr_uid;
795 	gid_t gid = state->dts_cred.dcr_gid;
796 	cred_t *cr;
797 	proc_t *proc;
798 
799 	if ((cr = CRED()) != NULL &&
800 	    uid == cr->cr_uid &&
801 	    uid == cr->cr_ruid &&
802 	    uid == cr->cr_suid &&
803 	    gid == cr->cr_gid &&
804 	    gid == cr->cr_rgid &&
805 	    gid == cr->cr_sgid &&
806 	    (proc = ttoproc(curthread)) != NULL &&
807 	    !(proc->p_flag & SNOCD))
808 		return (1);
809 
810 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
811 
812 	return (0);
813 }
814 
815 static int
816 dtrace_priv_proc_destructive(dtrace_state_t *state)
817 {
818 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_DESTRUCTIVE)
819 		return (1);
820 
821 	return (dtrace_priv_proc_common(state));
822 }
823 
824 static int
825 dtrace_priv_proc_control(dtrace_state_t *state)
826 {
827 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
828 		return (1);
829 
830 	return (dtrace_priv_proc_common(state));
831 }
832 
833 static int
834 dtrace_priv_proc(dtrace_state_t *state)
835 {
836 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
837 		return (1);
838 
839 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
840 
841 	return (0);
842 }
843 
844 static int
845 dtrace_priv_kernel(dtrace_state_t *state)
846 {
847 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
848 		return (1);
849 
850 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
851 
852 	return (0);
853 }
854 
855 static int
856 dtrace_priv_kernel_destructive(dtrace_state_t *state)
857 {
858 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
859 		return (1);
860 
861 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
862 
863 	return (0);
864 }
865 
866 /*
867  * Note:  not called from probe context.  This function is called
868  * asynchronously (and at a regular interval) from outside of probe context to
869  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
870  * cleaning is explained in detail in <sys/dtrace_impl.h>.
871  */
872 void
873 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
874 {
875 	dtrace_dynvar_t *dirty;
876 	dtrace_dstate_percpu_t *dcpu;
877 	int i, work = 0;
878 
879 	for (i = 0; i < NCPU; i++) {
880 		dcpu = &dstate->dtds_percpu[i];
881 
882 		ASSERT(dcpu->dtdsc_rinsing == NULL);
883 
884 		/*
885 		 * If the dirty list is NULL, there is no dirty work to do.
886 		 */
887 		if (dcpu->dtdsc_dirty == NULL)
888 			continue;
889 
890 		/*
891 		 * If the clean list is non-NULL, then we're not going to do
892 		 * any work for this CPU -- it means that there has not been
893 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
894 		 * since the last time we cleaned house.
895 		 */
896 		if (dcpu->dtdsc_clean != NULL)
897 			continue;
898 
899 		work = 1;
900 
901 		/*
902 		 * Atomically move the dirty list aside.
903 		 */
904 		do {
905 			dirty = dcpu->dtdsc_dirty;
906 
907 			/*
908 			 * Before we zap the dirty list, set the rinsing list.
909 			 * (This allows for a potential assertion in
910 			 * dtrace_dynvar():  if a free dynamic variable appears
911 			 * on a hash chain, either the dirty list or the
912 			 * rinsing list for some CPU must be non-NULL.)
913 			 */
914 			dcpu->dtdsc_rinsing = dirty;
915 			dtrace_membar_producer();
916 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
917 		    dirty, NULL) != dirty);
918 	}
919 
920 	if (!work) {
921 		/*
922 		 * We have no work to do; we can simply return.
923 		 */
924 		return;
925 	}
926 
927 	dtrace_sync();
928 
929 	for (i = 0; i < NCPU; i++) {
930 		dcpu = &dstate->dtds_percpu[i];
931 
932 		if (dcpu->dtdsc_rinsing == NULL)
933 			continue;
934 
935 		/*
936 		 * We are now guaranteed that no hash chain contains a pointer
937 		 * into this dirty list; we can make it clean.
938 		 */
939 		ASSERT(dcpu->dtdsc_clean == NULL);
940 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
941 		dcpu->dtdsc_rinsing = NULL;
942 	}
943 
944 	/*
945 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
946 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
947 	 * This prevents a race whereby a CPU incorrectly decides that
948 	 * the state should be something other than DTRACE_DSTATE_CLEAN
949 	 * after dtrace_dynvar_clean() has completed.
950 	 */
951 	dtrace_sync();
952 
953 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
954 }
955 
956 /*
957  * Depending on the value of the op parameter, this function looks-up,
958  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
959  * allocation is requested, this function will return a pointer to a
960  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
961  * variable can be allocated.  If NULL is returned, the appropriate counter
962  * will be incremented.
963  */
964 dtrace_dynvar_t *
965 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
966     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op)
967 {
968 	uint64_t hashval = 1;
969 	dtrace_dynhash_t *hash = dstate->dtds_hash;
970 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
971 	processorid_t me = CPU->cpu_id, cpu = me;
972 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
973 	size_t bucket, ksize;
974 	size_t chunksize = dstate->dtds_chunksize;
975 	uintptr_t kdata, lock, nstate;
976 	uint_t i;
977 
978 	ASSERT(nkeys != 0);
979 
980 	/*
981 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
982 	 * algorithm.  For the by-value portions, we perform the algorithm in
983 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
984 	 * bit, and seems to have only a minute effect on distribution.  For
985 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
986 	 * over each referenced byte.  It's painful to do this, but it's much
987 	 * better than pathological hash distribution.  The efficacy of the
988 	 * hashing algorithm (and a comparison with other algorithms) may be
989 	 * found by running the ::dtrace_dynstat MDB dcmd.
990 	 */
991 	for (i = 0; i < nkeys; i++) {
992 		if (key[i].dttk_size == 0) {
993 			uint64_t val = key[i].dttk_value;
994 
995 			hashval += (val >> 48) & 0xffff;
996 			hashval += (hashval << 10);
997 			hashval ^= (hashval >> 6);
998 
999 			hashval += (val >> 32) & 0xffff;
1000 			hashval += (hashval << 10);
1001 			hashval ^= (hashval >> 6);
1002 
1003 			hashval += (val >> 16) & 0xffff;
1004 			hashval += (hashval << 10);
1005 			hashval ^= (hashval >> 6);
1006 
1007 			hashval += val & 0xffff;
1008 			hashval += (hashval << 10);
1009 			hashval ^= (hashval >> 6);
1010 		} else {
1011 			/*
1012 			 * This is incredibly painful, but it beats the hell
1013 			 * out of the alternative.
1014 			 */
1015 			uint64_t j, size = key[i].dttk_size;
1016 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1017 
1018 			for (j = 0; j < size; j++) {
1019 				hashval += dtrace_load8(base + j);
1020 				hashval += (hashval << 10);
1021 				hashval ^= (hashval >> 6);
1022 			}
1023 		}
1024 	}
1025 
1026 	hashval += (hashval << 3);
1027 	hashval ^= (hashval >> 11);
1028 	hashval += (hashval << 15);
1029 
1030 	/*
1031 	 * There is a remote chance (ideally, 1 in 2^32) that our hashval
1032 	 * comes out to be 0.  We rely on a zero hashval denoting a free
1033 	 * element; if this actually happens, we set the hashval to 1.
1034 	 */
1035 	if (hashval == 0)
1036 		hashval = 1;
1037 
1038 	/*
1039 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1040 	 * important here, tricks can be pulled to reduce it.  (However, it's
1041 	 * critical that hash collisions be kept to an absolute minimum;
1042 	 * they're much more painful than a divide.)  It's better to have a
1043 	 * solution that generates few collisions and still keeps things
1044 	 * relatively simple.
1045 	 */
1046 	bucket = hashval % dstate->dtds_hashsize;
1047 
1048 	if (op == DTRACE_DYNVAR_DEALLOC) {
1049 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1050 
1051 		for (;;) {
1052 			while ((lock = *lockp) & 1)
1053 				continue;
1054 
1055 			if (dtrace_casptr((void *)lockp,
1056 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1057 				break;
1058 		}
1059 
1060 		dtrace_membar_producer();
1061 	}
1062 
1063 top:
1064 	prev = NULL;
1065 	lock = hash[bucket].dtdh_lock;
1066 
1067 	dtrace_membar_consumer();
1068 
1069 	start = hash[bucket].dtdh_chain;
1070 	ASSERT(start == NULL || start->dtdv_hashval != 0 ||
1071 	    op != DTRACE_DYNVAR_DEALLOC);
1072 
1073 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1074 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1075 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1076 
1077 		if (dvar->dtdv_hashval != hashval) {
1078 			if (dvar->dtdv_hashval == 0) {
1079 				/*
1080 				 * We've gone off the rails.  Somewhere
1081 				 * along the line, one of the members of this
1082 				 * hash chain was deleted.  We could assert
1083 				 * that either the dirty list or the rinsing
1084 				 * list is non-NULL.  (The dtrace_sync() in
1085 				 * dtrace_dynvar_clean() would validate this
1086 				 * assertion.)
1087 				 */
1088 				ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1089 				goto top;
1090 			}
1091 
1092 			goto next;
1093 		}
1094 
1095 		if (dtuple->dtt_nkeys != nkeys)
1096 			goto next;
1097 
1098 		for (i = 0; i < nkeys; i++, dkey++) {
1099 			if (dkey->dttk_size != key[i].dttk_size)
1100 				goto next; /* size or type mismatch */
1101 
1102 			if (dkey->dttk_size != 0) {
1103 				if (dtrace_bcmp(
1104 				    (void *)(uintptr_t)key[i].dttk_value,
1105 				    (void *)(uintptr_t)dkey->dttk_value,
1106 				    dkey->dttk_size))
1107 					goto next;
1108 			} else {
1109 				if (dkey->dttk_value != key[i].dttk_value)
1110 					goto next;
1111 			}
1112 		}
1113 
1114 		if (op != DTRACE_DYNVAR_DEALLOC)
1115 			return (dvar);
1116 
1117 		ASSERT(dvar->dtdv_next == NULL ||
1118 		    dvar->dtdv_next->dtdv_hashval != 0);
1119 
1120 		if (prev != NULL) {
1121 			ASSERT(hash[bucket].dtdh_chain != dvar);
1122 			ASSERT(start != dvar);
1123 			ASSERT(prev->dtdv_next == dvar);
1124 			prev->dtdv_next = dvar->dtdv_next;
1125 		} else {
1126 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1127 			    start, dvar->dtdv_next) != start) {
1128 				/*
1129 				 * We have failed to atomically swing the
1130 				 * hash table head pointer, presumably because
1131 				 * of a conflicting allocation on another CPU.
1132 				 * We need to reread the hash chain and try
1133 				 * again.
1134 				 */
1135 				goto top;
1136 			}
1137 		}
1138 
1139 		dtrace_membar_producer();
1140 
1141 		/*
1142 		 * Now clear the hash value to indicate that it's free.
1143 		 */
1144 		ASSERT(hash[bucket].dtdh_chain != dvar);
1145 		dvar->dtdv_hashval = 0;
1146 
1147 		dtrace_membar_producer();
1148 
1149 		/*
1150 		 * Set the next pointer to point at the dirty list, and
1151 		 * atomically swing the dirty pointer to the newly freed dvar.
1152 		 */
1153 		do {
1154 			next = dcpu->dtdsc_dirty;
1155 			dvar->dtdv_next = next;
1156 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1157 
1158 		/*
1159 		 * Finally, unlock this hash bucket.
1160 		 */
1161 		ASSERT(hash[bucket].dtdh_lock == lock);
1162 		ASSERT(lock & 1);
1163 		hash[bucket].dtdh_lock++;
1164 
1165 		return (NULL);
1166 next:
1167 		prev = dvar;
1168 		continue;
1169 	}
1170 
1171 	if (op != DTRACE_DYNVAR_ALLOC) {
1172 		/*
1173 		 * If we are not to allocate a new variable, we want to
1174 		 * return NULL now.  Before we return, check that the value
1175 		 * of the lock word hasn't changed.  If it has, we may have
1176 		 * seen an inconsistent snapshot.
1177 		 */
1178 		if (op == DTRACE_DYNVAR_NOALLOC) {
1179 			if (hash[bucket].dtdh_lock != lock)
1180 				goto top;
1181 		} else {
1182 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1183 			ASSERT(hash[bucket].dtdh_lock == lock);
1184 			ASSERT(lock & 1);
1185 			hash[bucket].dtdh_lock++;
1186 		}
1187 
1188 		return (NULL);
1189 	}
1190 
1191 	/*
1192 	 * We need to allocate a new dynamic variable.  The size we need is the
1193 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1194 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1195 	 * the size of any referred-to data (dsize).  We then round the final
1196 	 * size up to the chunksize for allocation.
1197 	 */
1198 	for (ksize = 0, i = 0; i < nkeys; i++)
1199 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1200 
1201 	/*
1202 	 * This should be pretty much impossible, but could happen if, say,
1203 	 * strange DIF specified the tuple.  Ideally, this should be an
1204 	 * assertion and not an error condition -- but that requires that the
1205 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1206 	 * bullet-proof.  (That is, it must not be able to be fooled by
1207 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1208 	 * solving this would presumably not amount to solving the Halting
1209 	 * Problem -- but it still seems awfully hard.
1210 	 */
1211 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1212 	    ksize + dsize > chunksize) {
1213 		dcpu->dtdsc_drops++;
1214 		return (NULL);
1215 	}
1216 
1217 	nstate = DTRACE_DSTATE_EMPTY;
1218 
1219 	do {
1220 retry:
1221 		free = dcpu->dtdsc_free;
1222 
1223 		if (free == NULL) {
1224 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1225 			void *rval;
1226 
1227 			if (clean == NULL) {
1228 				/*
1229 				 * We're out of dynamic variable space on
1230 				 * this CPU.  Unless we have tried all CPUs,
1231 				 * we'll try to allocate from a different
1232 				 * CPU.
1233 				 */
1234 				switch (dstate->dtds_state) {
1235 				case DTRACE_DSTATE_CLEAN: {
1236 					void *sp = &dstate->dtds_state;
1237 
1238 					if (++cpu >= NCPU)
1239 						cpu = 0;
1240 
1241 					if (dcpu->dtdsc_dirty != NULL &&
1242 					    nstate == DTRACE_DSTATE_EMPTY)
1243 						nstate = DTRACE_DSTATE_DIRTY;
1244 
1245 					if (dcpu->dtdsc_rinsing != NULL)
1246 						nstate = DTRACE_DSTATE_RINSING;
1247 
1248 					dcpu = &dstate->dtds_percpu[cpu];
1249 
1250 					if (cpu != me)
1251 						goto retry;
1252 
1253 					(void) dtrace_cas32(sp,
1254 					    DTRACE_DSTATE_CLEAN, nstate);
1255 
1256 					/*
1257 					 * To increment the correct bean
1258 					 * counter, take another lap.
1259 					 */
1260 					goto retry;
1261 				}
1262 
1263 				case DTRACE_DSTATE_DIRTY:
1264 					dcpu->dtdsc_dirty_drops++;
1265 					break;
1266 
1267 				case DTRACE_DSTATE_RINSING:
1268 					dcpu->dtdsc_rinsing_drops++;
1269 					break;
1270 
1271 				case DTRACE_DSTATE_EMPTY:
1272 					dcpu->dtdsc_drops++;
1273 					break;
1274 				}
1275 
1276 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1277 				return (NULL);
1278 			}
1279 
1280 			/*
1281 			 * The clean list appears to be non-empty.  We want to
1282 			 * move the clean list to the free list; we start by
1283 			 * moving the clean pointer aside.
1284 			 */
1285 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1286 			    clean, NULL) != clean) {
1287 				/*
1288 				 * We are in one of two situations:
1289 				 *
1290 				 *  (a)	The clean list was switched to the
1291 				 *	free list by another CPU.
1292 				 *
1293 				 *  (b)	The clean list was added to by the
1294 				 *	cleansing cyclic.
1295 				 *
1296 				 * In either of these situations, we can
1297 				 * just reattempt the free list allocation.
1298 				 */
1299 				goto retry;
1300 			}
1301 
1302 			ASSERT(clean->dtdv_hashval == 0);
1303 
1304 			/*
1305 			 * Now we'll move the clean list to the free list.
1306 			 * It's impossible for this to fail:  the only way
1307 			 * the free list can be updated is through this
1308 			 * code path, and only one CPU can own the clean list.
1309 			 * Thus, it would only be possible for this to fail if
1310 			 * this code were racing with dtrace_dynvar_clean().
1311 			 * (That is, if dtrace_dynvar_clean() updated the clean
1312 			 * list, and we ended up racing to update the free
1313 			 * list.)  This race is prevented by the dtrace_sync()
1314 			 * in dtrace_dynvar_clean() -- which flushes the
1315 			 * owners of the clean lists out before resetting
1316 			 * the clean lists.
1317 			 */
1318 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1319 			ASSERT(rval == NULL);
1320 			goto retry;
1321 		}
1322 
1323 		dvar = free;
1324 		new_free = dvar->dtdv_next;
1325 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1326 
1327 	/*
1328 	 * We have now allocated a new chunk.  We copy the tuple keys into the
1329 	 * tuple array and copy any referenced key data into the data space
1330 	 * following the tuple array.  As we do this, we relocate dttk_value
1331 	 * in the final tuple to point to the key data address in the chunk.
1332 	 */
1333 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1334 	dvar->dtdv_data = (void *)(kdata + ksize);
1335 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
1336 
1337 	for (i = 0; i < nkeys; i++) {
1338 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1339 		size_t kesize = key[i].dttk_size;
1340 
1341 		if (kesize != 0) {
1342 			dtrace_bcopy(
1343 			    (const void *)(uintptr_t)key[i].dttk_value,
1344 			    (void *)kdata, kesize);
1345 			dkey->dttk_value = kdata;
1346 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1347 		} else {
1348 			dkey->dttk_value = key[i].dttk_value;
1349 		}
1350 
1351 		dkey->dttk_size = kesize;
1352 	}
1353 
1354 	ASSERT(dvar->dtdv_hashval == 0);
1355 	dvar->dtdv_hashval = hashval;
1356 	dvar->dtdv_next = start;
1357 
1358 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1359 		return (dvar);
1360 
1361 	/*
1362 	 * The cas has failed.  Either another CPU is adding an element to
1363 	 * this hash chain, or another CPU is deleting an element from this
1364 	 * hash chain.  The simplest way to deal with both of these cases
1365 	 * (though not necessarily the most efficient) is to free our
1366 	 * allocated block and tail-call ourselves.  Note that the free is
1367 	 * to the dirty list and _not_ to the free list.  This is to prevent
1368 	 * races with allocators, above.
1369 	 */
1370 	dvar->dtdv_hashval = 0;
1371 
1372 	dtrace_membar_producer();
1373 
1374 	do {
1375 		free = dcpu->dtdsc_dirty;
1376 		dvar->dtdv_next = free;
1377 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1378 
1379 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op));
1380 }
1381 
1382 /*ARGSUSED*/
1383 static void
1384 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1385 {
1386 	if (nval < *oval)
1387 		*oval = nval;
1388 }
1389 
1390 /*ARGSUSED*/
1391 static void
1392 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1393 {
1394 	if (nval > *oval)
1395 		*oval = nval;
1396 }
1397 
1398 static void
1399 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1400 {
1401 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1402 	int64_t val = (int64_t)nval;
1403 
1404 	if (val < 0) {
1405 		for (i = 0; i < zero; i++) {
1406 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1407 				quanta[i] += incr;
1408 				return;
1409 			}
1410 		}
1411 	} else {
1412 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1413 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1414 				quanta[i - 1] += incr;
1415 				return;
1416 			}
1417 		}
1418 
1419 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1420 		return;
1421 	}
1422 
1423 	ASSERT(0);
1424 }
1425 
1426 static void
1427 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1428 {
1429 	uint64_t arg = *lquanta++;
1430 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1431 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1432 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1433 	int32_t val = (int32_t)nval, level;
1434 
1435 	ASSERT(step != 0);
1436 	ASSERT(levels != 0);
1437 
1438 	if (val < base) {
1439 		/*
1440 		 * This is an underflow.
1441 		 */
1442 		lquanta[0] += incr;
1443 		return;
1444 	}
1445 
1446 	level = (val - base) / step;
1447 
1448 	if (level < levels) {
1449 		lquanta[level + 1] += incr;
1450 		return;
1451 	}
1452 
1453 	/*
1454 	 * This is an overflow.
1455 	 */
1456 	lquanta[levels + 1] += incr;
1457 }
1458 
1459 /*ARGSUSED*/
1460 static void
1461 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
1462 {
1463 	data[0]++;
1464 	data[1] += nval;
1465 }
1466 
1467 /*ARGSUSED*/
1468 static void
1469 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
1470 {
1471 	*oval = *oval + 1;
1472 }
1473 
1474 /*ARGSUSED*/
1475 static void
1476 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
1477 {
1478 	*oval += nval;
1479 }
1480 
1481 /*
1482  * Aggregate given the tuple in the principal data buffer, and the aggregating
1483  * action denoted by the specified dtrace_aggregation_t.  The aggregation
1484  * buffer is specified as the buf parameter.  This routine does not return
1485  * failure; if there is no space in the aggregation buffer, the data will be
1486  * dropped, and a corresponding counter incremented.
1487  */
1488 static void
1489 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
1490     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
1491 {
1492 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
1493 	uint32_t i, ndx, size, fsize;
1494 	uint32_t align = sizeof (uint64_t) - 1;
1495 	dtrace_aggbuffer_t *agb;
1496 	dtrace_aggkey_t *key;
1497 	uint32_t hashval = 0, limit, isstr;
1498 	caddr_t tomax, data, kdata;
1499 	dtrace_actkind_t action;
1500 	dtrace_action_t *act;
1501 	uintptr_t offs;
1502 
1503 	if (buf == NULL)
1504 		return;
1505 
1506 	if (!agg->dtag_hasarg) {
1507 		/*
1508 		 * Currently, only quantize() and lquantize() take additional
1509 		 * arguments, and they have the same semantics:  an increment
1510 		 * value that defaults to 1 when not present.  If additional
1511 		 * aggregating actions take arguments, the setting of the
1512 		 * default argument value will presumably have to become more
1513 		 * sophisticated...
1514 		 */
1515 		arg = 1;
1516 	}
1517 
1518 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
1519 	size = rec->dtrd_offset - agg->dtag_base;
1520 	fsize = size + rec->dtrd_size;
1521 
1522 	ASSERT(dbuf->dtb_tomax != NULL);
1523 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
1524 
1525 	if ((tomax = buf->dtb_tomax) == NULL) {
1526 		dtrace_buffer_drop(buf);
1527 		return;
1528 	}
1529 
1530 	/*
1531 	 * The metastructure is always at the bottom of the buffer.
1532 	 */
1533 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
1534 	    sizeof (dtrace_aggbuffer_t));
1535 
1536 	if (buf->dtb_offset == 0) {
1537 		/*
1538 		 * We just kludge up approximately 1/8th of the size to be
1539 		 * buckets.  If this guess ends up being routinely
1540 		 * off-the-mark, we may need to dynamically readjust this
1541 		 * based on past performance.
1542 		 */
1543 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
1544 
1545 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
1546 		    (uintptr_t)tomax || hashsize == 0) {
1547 			/*
1548 			 * We've been given a ludicrously small buffer;
1549 			 * increment our drop count and leave.
1550 			 */
1551 			dtrace_buffer_drop(buf);
1552 			return;
1553 		}
1554 
1555 		/*
1556 		 * And now, a pathetic attempt to try to get a an odd (or
1557 		 * perchance, a prime) hash size for better hash distribution.
1558 		 */
1559 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
1560 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
1561 
1562 		agb->dtagb_hashsize = hashsize;
1563 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
1564 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
1565 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
1566 
1567 		for (i = 0; i < agb->dtagb_hashsize; i++)
1568 			agb->dtagb_hash[i] = NULL;
1569 	}
1570 
1571 	ASSERT(agg->dtag_first != NULL);
1572 	ASSERT(agg->dtag_first->dta_intuple);
1573 
1574 	/*
1575 	 * Calculate the hash value based on the key.  Note that we _don't_
1576 	 * include the aggid in the hashing (but we will store it as part of
1577 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
1578 	 * algorithm: a simple, quick algorithm that has no known funnels, and
1579 	 * gets good distribution in practice.  The efficacy of the hashing
1580 	 * algorithm (and a comparison with other algorithms) may be found by
1581 	 * running the ::dtrace_aggstat MDB dcmd.
1582 	 */
1583 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1584 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1585 		limit = i + act->dta_rec.dtrd_size;
1586 		ASSERT(limit <= size);
1587 		isstr = DTRACEACT_ISSTRING(act);
1588 
1589 		for (; i < limit; i++) {
1590 			hashval += data[i];
1591 			hashval += (hashval << 10);
1592 			hashval ^= (hashval >> 6);
1593 
1594 			if (isstr && data[i] == '\0')
1595 				break;
1596 		}
1597 	}
1598 
1599 	hashval += (hashval << 3);
1600 	hashval ^= (hashval >> 11);
1601 	hashval += (hashval << 15);
1602 
1603 	/*
1604 	 * Yes, the divide here is expensive -- but it's generally the least
1605 	 * of the performance issues given the amount of data that we iterate
1606 	 * over to compute hash values, compare data, etc.
1607 	 */
1608 	ndx = hashval % agb->dtagb_hashsize;
1609 
1610 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
1611 		ASSERT((caddr_t)key >= tomax);
1612 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
1613 
1614 		if (hashval != key->dtak_hashval || key->dtak_size != size)
1615 			continue;
1616 
1617 		kdata = key->dtak_data;
1618 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
1619 
1620 		for (act = agg->dtag_first; act->dta_intuple;
1621 		    act = act->dta_next) {
1622 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
1623 			limit = i + act->dta_rec.dtrd_size;
1624 			ASSERT(limit <= size);
1625 			isstr = DTRACEACT_ISSTRING(act);
1626 
1627 			for (; i < limit; i++) {
1628 				if (kdata[i] != data[i])
1629 					goto next;
1630 
1631 				if (isstr && data[i] == '\0')
1632 					break;
1633 			}
1634 		}
1635 
1636 		if (action != key->dtak_action) {
1637 			/*
1638 			 * We are aggregating on the same value in the same
1639 			 * aggregation with two different aggregating actions.
1640 			 * (This should have been picked up in the compiler,
1641 			 * so we may be dealing with errant or devious DIF.)
1642 			 * This is an error condition; we indicate as much,
1643 			 * and return.
1644 			 */
1645 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
1646 			return;
1647 		}
1648 
1649 		/*
1650 		 * This is a hit:  we need to apply the aggregator to
1651 		 * the value at this key.
1652 		 */
1653 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
1654 		return;
1655 next:
1656 		continue;
1657 	}
1658 
1659 	/*
1660 	 * We didn't find it.  We need to allocate some zero-filled space,
1661 	 * link it into the hash table appropriately, and apply the aggregator
1662 	 * to the (zero-filled) value.
1663 	 */
1664 	offs = buf->dtb_offset;
1665 	while (offs & (align - 1))
1666 		offs += sizeof (uint32_t);
1667 
1668 	/*
1669 	 * If we don't have enough room to both allocate a new key _and_
1670 	 * its associated data, increment the drop count and return.
1671 	 */
1672 	if ((uintptr_t)tomax + offs + fsize >
1673 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
1674 		dtrace_buffer_drop(buf);
1675 		return;
1676 	}
1677 
1678 	/*CONSTCOND*/
1679 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
1680 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
1681 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
1682 
1683 	key->dtak_data = kdata = tomax + offs;
1684 	buf->dtb_offset = offs + fsize;
1685 
1686 	/*
1687 	 * Now copy the data across.
1688 	 */
1689 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
1690 
1691 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
1692 		kdata[i] = data[i];
1693 
1694 	/*
1695 	 * Because strings are not zeroed out by default, we need to iterate
1696 	 * looking for actions that store strings, and we need to explicitly
1697 	 * pad these strings out with zeroes.
1698 	 */
1699 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1700 		int nul;
1701 
1702 		if (!DTRACEACT_ISSTRING(act))
1703 			continue;
1704 
1705 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1706 		limit = i + act->dta_rec.dtrd_size;
1707 		ASSERT(limit <= size);
1708 
1709 		for (nul = 0; i < limit; i++) {
1710 			if (nul) {
1711 				kdata[i] = '\0';
1712 				continue;
1713 			}
1714 
1715 			if (data[i] != '\0')
1716 				continue;
1717 
1718 			nul = 1;
1719 		}
1720 	}
1721 
1722 	for (i = size; i < fsize; i++)
1723 		kdata[i] = 0;
1724 
1725 	key->dtak_hashval = hashval;
1726 	key->dtak_size = size;
1727 	key->dtak_action = action;
1728 	key->dtak_next = agb->dtagb_hash[ndx];
1729 	agb->dtagb_hash[ndx] = key;
1730 
1731 	/*
1732 	 * Finally, apply the aggregator.
1733 	 */
1734 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
1735 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
1736 }
1737 
1738 /*
1739  * Given consumer state, this routine finds a speculation in the INACTIVE
1740  * state and transitions it into the ACTIVE state.  If there is no speculation
1741  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
1742  * incremented -- it is up to the caller to take appropriate action.
1743  */
1744 static int
1745 dtrace_speculation(dtrace_state_t *state)
1746 {
1747 	int i = 0;
1748 	dtrace_speculation_state_t current;
1749 	uint32_t *stat = &state->dts_speculations_unavail, count;
1750 
1751 	while (i < state->dts_nspeculations) {
1752 		dtrace_speculation_t *spec = &state->dts_speculations[i];
1753 
1754 		current = spec->dtsp_state;
1755 
1756 		if (current != DTRACESPEC_INACTIVE) {
1757 			if (current == DTRACESPEC_COMMITTINGMANY ||
1758 			    current == DTRACESPEC_COMMITTING ||
1759 			    current == DTRACESPEC_DISCARDING)
1760 				stat = &state->dts_speculations_busy;
1761 			i++;
1762 			continue;
1763 		}
1764 
1765 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
1766 		    current, DTRACESPEC_ACTIVE) == current)
1767 			return (i + 1);
1768 	}
1769 
1770 	/*
1771 	 * We couldn't find a speculation.  If we found as much as a single
1772 	 * busy speculation buffer, we'll attribute this failure as "busy"
1773 	 * instead of "unavail".
1774 	 */
1775 	do {
1776 		count = *stat;
1777 	} while (dtrace_cas32(stat, count, count + 1) != count);
1778 
1779 	return (0);
1780 }
1781 
1782 /*
1783  * This routine commits an active speculation.  If the specified speculation
1784  * is not in a valid state to perform a commit(), this routine will silently do
1785  * nothing.  The state of the specified speculation is transitioned according
1786  * to the state transition diagram outlined in <sys/dtrace_impl.h>
1787  */
1788 static void
1789 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
1790     dtrace_specid_t which)
1791 {
1792 	dtrace_speculation_t *spec;
1793 	dtrace_buffer_t *src, *dest;
1794 	uintptr_t daddr, saddr, dlimit;
1795 	dtrace_speculation_state_t current, new;
1796 	intptr_t offs;
1797 
1798 	if (which == 0)
1799 		return;
1800 
1801 	if (which > state->dts_nspeculations) {
1802 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
1803 		return;
1804 	}
1805 
1806 	spec = &state->dts_speculations[which - 1];
1807 	src = &spec->dtsp_buffer[cpu];
1808 	dest = &state->dts_buffer[cpu];
1809 
1810 	do {
1811 		current = spec->dtsp_state;
1812 
1813 		if (current == DTRACESPEC_COMMITTINGMANY)
1814 			break;
1815 
1816 		switch (current) {
1817 		case DTRACESPEC_INACTIVE:
1818 		case DTRACESPEC_DISCARDING:
1819 			return;
1820 
1821 		case DTRACESPEC_COMMITTING:
1822 			/*
1823 			 * This is only possible if we are (a) commit()'ing
1824 			 * without having done a prior speculate() on this CPU
1825 			 * and (b) racing with another commit() on a different
1826 			 * CPU.  There's nothing to do -- we just assert that
1827 			 * our offset is 0.
1828 			 */
1829 			ASSERT(src->dtb_offset == 0);
1830 			return;
1831 
1832 		case DTRACESPEC_ACTIVE:
1833 			new = DTRACESPEC_COMMITTING;
1834 			break;
1835 
1836 		case DTRACESPEC_ACTIVEONE:
1837 			/*
1838 			 * This speculation is active on one CPU.  If our
1839 			 * buffer offset is non-zero, we know that the one CPU
1840 			 * must be us.  Otherwise, we are committing on a
1841 			 * different CPU from the speculate(), and we must
1842 			 * rely on being asynchronously cleaned.
1843 			 */
1844 			if (src->dtb_offset != 0) {
1845 				new = DTRACESPEC_COMMITTING;
1846 				break;
1847 			}
1848 			/*FALLTHROUGH*/
1849 
1850 		case DTRACESPEC_ACTIVEMANY:
1851 			new = DTRACESPEC_COMMITTINGMANY;
1852 			break;
1853 
1854 		default:
1855 			ASSERT(0);
1856 		}
1857 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
1858 	    current, new) != current);
1859 
1860 	/*
1861 	 * We have set the state to indicate that we are committing this
1862 	 * speculation.  Now reserve the necessary space in the destination
1863 	 * buffer.
1864 	 */
1865 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
1866 	    sizeof (uint64_t), state, NULL)) < 0) {
1867 		dtrace_buffer_drop(dest);
1868 		goto out;
1869 	}
1870 
1871 	/*
1872 	 * We have the space; copy the buffer across.  (Note that this is a
1873 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
1874 	 * a serious performance issue, a high-performance DTrace-specific
1875 	 * bcopy() should obviously be invented.)
1876 	 */
1877 	daddr = (uintptr_t)dest->dtb_tomax + offs;
1878 	dlimit = daddr + src->dtb_offset;
1879 	saddr = (uintptr_t)src->dtb_tomax;
1880 
1881 	/*
1882 	 * First, the aligned portion.
1883 	 */
1884 	while (dlimit - daddr >= sizeof (uint64_t)) {
1885 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
1886 
1887 		daddr += sizeof (uint64_t);
1888 		saddr += sizeof (uint64_t);
1889 	}
1890 
1891 	/*
1892 	 * Now any left-over bit...
1893 	 */
1894 	while (dlimit - daddr)
1895 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
1896 
1897 	/*
1898 	 * Finally, commit the reserved space in the destination buffer.
1899 	 */
1900 	dest->dtb_offset = offs + src->dtb_offset;
1901 
1902 out:
1903 	/*
1904 	 * If we're lucky enough to be the only active CPU on this speculation
1905 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
1906 	 */
1907 	if (current == DTRACESPEC_ACTIVE ||
1908 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
1909 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
1910 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
1911 
1912 		ASSERT(rval == DTRACESPEC_COMMITTING);
1913 	}
1914 
1915 	src->dtb_offset = 0;
1916 	src->dtb_xamot_drops += src->dtb_drops;
1917 	src->dtb_drops = 0;
1918 }
1919 
1920 /*
1921  * This routine discards an active speculation.  If the specified speculation
1922  * is not in a valid state to perform a discard(), this routine will silently
1923  * do nothing.  The state of the specified speculation is transitioned
1924  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
1925  */
1926 static void
1927 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
1928     dtrace_specid_t which)
1929 {
1930 	dtrace_speculation_t *spec;
1931 	dtrace_speculation_state_t current, new;
1932 	dtrace_buffer_t *buf;
1933 
1934 	if (which == 0)
1935 		return;
1936 
1937 	if (which > state->dts_nspeculations) {
1938 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
1939 		return;
1940 	}
1941 
1942 	spec = &state->dts_speculations[which - 1];
1943 	buf = &spec->dtsp_buffer[cpu];
1944 
1945 	do {
1946 		current = spec->dtsp_state;
1947 
1948 		switch (current) {
1949 		case DTRACESPEC_INACTIVE:
1950 		case DTRACESPEC_COMMITTINGMANY:
1951 		case DTRACESPEC_COMMITTING:
1952 		case DTRACESPEC_DISCARDING:
1953 			return;
1954 
1955 		case DTRACESPEC_ACTIVE:
1956 		case DTRACESPEC_ACTIVEMANY:
1957 			new = DTRACESPEC_DISCARDING;
1958 			break;
1959 
1960 		case DTRACESPEC_ACTIVEONE:
1961 			if (buf->dtb_offset != 0) {
1962 				new = DTRACESPEC_INACTIVE;
1963 			} else {
1964 				new = DTRACESPEC_DISCARDING;
1965 			}
1966 			break;
1967 
1968 		default:
1969 			ASSERT(0);
1970 		}
1971 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
1972 	    current, new) != current);
1973 
1974 	buf->dtb_offset = 0;
1975 	buf->dtb_drops = 0;
1976 }
1977 
1978 /*
1979  * Note:  not called from probe context.  This function is called
1980  * asynchronously from cross call context to clean any speculations that are
1981  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
1982  * transitioned back to the INACTIVE state until all CPUs have cleaned the
1983  * speculation.
1984  */
1985 static void
1986 dtrace_speculation_clean_here(dtrace_state_t *state)
1987 {
1988 	dtrace_icookie_t cookie;
1989 	processorid_t cpu = CPU->cpu_id;
1990 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
1991 	dtrace_specid_t i;
1992 
1993 	cookie = dtrace_interrupt_disable();
1994 
1995 	if (dest->dtb_tomax == NULL) {
1996 		dtrace_interrupt_enable(cookie);
1997 		return;
1998 	}
1999 
2000 	for (i = 0; i < state->dts_nspeculations; i++) {
2001 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2002 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2003 
2004 		if (src->dtb_tomax == NULL)
2005 			continue;
2006 
2007 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2008 			src->dtb_offset = 0;
2009 			continue;
2010 		}
2011 
2012 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2013 			continue;
2014 
2015 		if (src->dtb_offset == 0)
2016 			continue;
2017 
2018 		dtrace_speculation_commit(state, cpu, i + 1);
2019 	}
2020 
2021 	dtrace_interrupt_enable(cookie);
2022 }
2023 
2024 /*
2025  * Note:  not called from probe context.  This function is called
2026  * asynchronously (and at a regular interval) to clean any speculations that
2027  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2028  * is work to be done, it cross calls all CPUs to perform that work;
2029  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2030  * INACTIVE state until they have been cleaned by all CPUs.
2031  */
2032 static void
2033 dtrace_speculation_clean(dtrace_state_t *state)
2034 {
2035 	int work = 0, rv;
2036 	dtrace_specid_t i;
2037 
2038 	for (i = 0; i < state->dts_nspeculations; i++) {
2039 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2040 
2041 		ASSERT(!spec->dtsp_cleaning);
2042 
2043 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2044 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2045 			continue;
2046 
2047 		work++;
2048 		spec->dtsp_cleaning = 1;
2049 	}
2050 
2051 	if (!work)
2052 		return;
2053 
2054 	dtrace_xcall(DTRACE_CPUALL,
2055 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2056 
2057 	/*
2058 	 * We now know that all CPUs have committed or discarded their
2059 	 * speculation buffers, as appropriate.  We can now set the state
2060 	 * to inactive.
2061 	 */
2062 	for (i = 0; i < state->dts_nspeculations; i++) {
2063 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2064 		dtrace_speculation_state_t current, new;
2065 
2066 		if (!spec->dtsp_cleaning)
2067 			continue;
2068 
2069 		current = spec->dtsp_state;
2070 		ASSERT(current == DTRACESPEC_DISCARDING ||
2071 		    current == DTRACESPEC_COMMITTINGMANY);
2072 
2073 		new = DTRACESPEC_INACTIVE;
2074 
2075 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2076 		ASSERT(rv == current);
2077 		spec->dtsp_cleaning = 0;
2078 	}
2079 }
2080 
2081 /*
2082  * Called as part of a speculate() to get the speculative buffer associated
2083  * with a given speculation.  Returns NULL if the specified speculation is not
2084  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2085  * the active CPU is not the specified CPU -- the speculation will be
2086  * atomically transitioned into the ACTIVEMANY state.
2087  */
2088 static dtrace_buffer_t *
2089 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2090     dtrace_specid_t which)
2091 {
2092 	dtrace_speculation_t *spec;
2093 	dtrace_speculation_state_t current, new;
2094 	dtrace_buffer_t *buf;
2095 
2096 	if (which == 0)
2097 		return (NULL);
2098 
2099 	if (which > state->dts_nspeculations) {
2100 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2101 		return (NULL);
2102 	}
2103 
2104 	spec = &state->dts_speculations[which - 1];
2105 	buf = &spec->dtsp_buffer[cpuid];
2106 
2107 	do {
2108 		current = spec->dtsp_state;
2109 
2110 		switch (current) {
2111 		case DTRACESPEC_INACTIVE:
2112 		case DTRACESPEC_COMMITTINGMANY:
2113 		case DTRACESPEC_DISCARDING:
2114 			return (NULL);
2115 
2116 		case DTRACESPEC_COMMITTING:
2117 			ASSERT(buf->dtb_offset == 0);
2118 			return (NULL);
2119 
2120 		case DTRACESPEC_ACTIVEONE:
2121 			/*
2122 			 * This speculation is currently active on one CPU.
2123 			 * Check the offset in the buffer; if it's non-zero,
2124 			 * that CPU must be us (and we leave the state alone).
2125 			 * If it's zero, assume that we're starting on a new
2126 			 * CPU -- and change the state to indicate that the
2127 			 * speculation is active on more than one CPU.
2128 			 */
2129 			if (buf->dtb_offset != 0)
2130 				return (buf);
2131 
2132 			new = DTRACESPEC_ACTIVEMANY;
2133 			break;
2134 
2135 		case DTRACESPEC_ACTIVEMANY:
2136 			return (buf);
2137 
2138 		case DTRACESPEC_ACTIVE:
2139 			new = DTRACESPEC_ACTIVEONE;
2140 			break;
2141 
2142 		default:
2143 			ASSERT(0);
2144 		}
2145 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2146 	    current, new) != current);
2147 
2148 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2149 	return (buf);
2150 }
2151 
2152 /*
2153  * This function implements the DIF emulator's variable lookups.  The emulator
2154  * passes a reserved variable identifier and optional built-in array index.
2155  */
2156 static uint64_t
2157 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2158     uint64_t ndx)
2159 {
2160 	/*
2161 	 * If we're accessing one of the uncached arguments, we'll turn this
2162 	 * into a reference in the args array.
2163 	 */
2164 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2165 		ndx = v - DIF_VAR_ARG0;
2166 		v = DIF_VAR_ARGS;
2167 	}
2168 
2169 	switch (v) {
2170 	case DIF_VAR_ARGS:
2171 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2172 		if (ndx >= sizeof (mstate->dtms_arg) /
2173 		    sizeof (mstate->dtms_arg[0])) {
2174 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2175 			dtrace_provider_t *pv;
2176 			uint64_t val;
2177 
2178 			pv = mstate->dtms_probe->dtpr_provider;
2179 			if (pv->dtpv_pops.dtps_getargval != NULL)
2180 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2181 				    mstate->dtms_probe->dtpr_id,
2182 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
2183 			else
2184 				val = dtrace_getarg(ndx, aframes);
2185 
2186 			/*
2187 			 * This is regrettably required to keep the compiler
2188 			 * from tail-optimizing the call to dtrace_getarg().
2189 			 * The condition always evaluates to true, but the
2190 			 * compiler has no way of figuring that out a priori.
2191 			 * (None of this would be necessary if the compiler
2192 			 * could be relied upon to _always_ tail-optimize
2193 			 * the call to dtrace_getarg() -- but it can't.)
2194 			 */
2195 			if (mstate->dtms_probe != NULL)
2196 				return (val);
2197 
2198 			ASSERT(0);
2199 		}
2200 
2201 		return (mstate->dtms_arg[ndx]);
2202 
2203 	case DIF_VAR_UREGS: {
2204 		klwp_t *lwp;
2205 
2206 		if (!dtrace_priv_proc(state))
2207 			return (0);
2208 
2209 		if ((lwp = curthread->t_lwp) == NULL) {
2210 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2211 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
2212 			return (0);
2213 		}
2214 
2215 		return (dtrace_getreg(lwp->lwp_regs, ndx));
2216 	}
2217 
2218 	case DIF_VAR_CURTHREAD:
2219 		if (!dtrace_priv_kernel(state))
2220 			return (0);
2221 		return ((uint64_t)(uintptr_t)curthread);
2222 
2223 	case DIF_VAR_TIMESTAMP:
2224 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2225 			mstate->dtms_timestamp = dtrace_gethrtime();
2226 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2227 		}
2228 		return (mstate->dtms_timestamp);
2229 
2230 	case DIF_VAR_VTIMESTAMP:
2231 		ASSERT(dtrace_vtime_references != 0);
2232 		return (curthread->t_dtrace_vtime);
2233 
2234 	case DIF_VAR_WALLTIMESTAMP:
2235 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2236 			mstate->dtms_walltimestamp = dtrace_gethrestime();
2237 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2238 		}
2239 		return (mstate->dtms_walltimestamp);
2240 
2241 	case DIF_VAR_IPL:
2242 		if (!dtrace_priv_kernel(state))
2243 			return (0);
2244 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2245 			mstate->dtms_ipl = dtrace_getipl();
2246 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
2247 		}
2248 		return (mstate->dtms_ipl);
2249 
2250 	case DIF_VAR_EPID:
2251 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2252 		return (mstate->dtms_epid);
2253 
2254 	case DIF_VAR_ID:
2255 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2256 		return (mstate->dtms_probe->dtpr_id);
2257 
2258 	case DIF_VAR_STACKDEPTH:
2259 		if (!dtrace_priv_kernel(state))
2260 			return (0);
2261 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2262 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2263 
2264 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2265 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2266 		}
2267 		return (mstate->dtms_stackdepth);
2268 
2269 	case DIF_VAR_USTACKDEPTH:
2270 		if (!dtrace_priv_proc(state))
2271 			return (0);
2272 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2273 			/*
2274 			 * See comment in DIF_VAR_PID.
2275 			 */
2276 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2277 			    CPU_ON_INTR(CPU)) {
2278 				mstate->dtms_ustackdepth = 0;
2279 			} else {
2280 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2281 				mstate->dtms_ustackdepth =
2282 				    dtrace_getustackdepth();
2283 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2284 			}
2285 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2286 		}
2287 		return (mstate->dtms_ustackdepth);
2288 
2289 	case DIF_VAR_CALLER:
2290 		if (!dtrace_priv_kernel(state))
2291 			return (0);
2292 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2293 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2294 
2295 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2296 				/*
2297 				 * If this is an unanchored probe, we are
2298 				 * required to go through the slow path:
2299 				 * dtrace_caller() only guarantees correct
2300 				 * results for anchored probes.
2301 				 */
2302 				pc_t caller[2];
2303 
2304 				dtrace_getpcstack(caller, 2, aframes,
2305 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2306 				mstate->dtms_caller = caller[1];
2307 			} else if ((mstate->dtms_caller =
2308 			    dtrace_caller(aframes)) == -1) {
2309 				/*
2310 				 * We have failed to do this the quick way;
2311 				 * we must resort to the slower approach of
2312 				 * calling dtrace_getpcstack().
2313 				 */
2314 				pc_t caller;
2315 
2316 				dtrace_getpcstack(&caller, 1, aframes, NULL);
2317 				mstate->dtms_caller = caller;
2318 			}
2319 
2320 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
2321 		}
2322 		return (mstate->dtms_caller);
2323 
2324 	case DIF_VAR_UCALLER:
2325 		if (!dtrace_priv_proc(state))
2326 			return (0);
2327 
2328 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
2329 			uint64_t ustack[3];
2330 
2331 			/*
2332 			 * dtrace_getupcstack() fills in the first uint64_t
2333 			 * with the current PID.  The second uint64_t will
2334 			 * be the program counter at user-level.  The third
2335 			 * uint64_t will contain the caller, which is what
2336 			 * we're after.
2337 			 */
2338 			ustack[2] = NULL;
2339 			dtrace_getupcstack(ustack, 3);
2340 			mstate->dtms_ucaller = ustack[2];
2341 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
2342 		}
2343 
2344 		return (mstate->dtms_ucaller);
2345 
2346 	case DIF_VAR_PROBEPROV:
2347 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2348 		return ((uint64_t)(uintptr_t)
2349 		    mstate->dtms_probe->dtpr_provider->dtpv_name);
2350 
2351 	case DIF_VAR_PROBEMOD:
2352 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2353 		return ((uint64_t)(uintptr_t)
2354 		    mstate->dtms_probe->dtpr_mod);
2355 
2356 	case DIF_VAR_PROBEFUNC:
2357 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2358 		return ((uint64_t)(uintptr_t)
2359 		    mstate->dtms_probe->dtpr_func);
2360 
2361 	case DIF_VAR_PROBENAME:
2362 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2363 		return ((uint64_t)(uintptr_t)
2364 		    mstate->dtms_probe->dtpr_name);
2365 
2366 	case DIF_VAR_PID:
2367 		if (!dtrace_priv_proc(state))
2368 			return (0);
2369 
2370 		/*
2371 		 * Note that we are assuming that an unanchored probe is
2372 		 * always due to a high-level interrupt.  (And we're assuming
2373 		 * that there is only a single high level interrupt.)
2374 		 */
2375 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2376 			return (pid0.pid_id);
2377 
2378 		/*
2379 		 * It is always safe to dereference one's own t_procp pointer:
2380 		 * it always points to a valid, allocated proc structure.
2381 		 * Further, it is always safe to dereference the p_pidp member
2382 		 * of one's own proc structure.  (These are truisms becuase
2383 		 * threads and processes don't clean up their own state --
2384 		 * they leave that task to whomever reaps them.)
2385 		 */
2386 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
2387 
2388 	case DIF_VAR_TID:
2389 		/*
2390 		 * See comment in DIF_VAR_PID.
2391 		 */
2392 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2393 			return (0);
2394 
2395 		return ((uint64_t)curthread->t_tid);
2396 
2397 	case DIF_VAR_EXECNAME:
2398 		if (!dtrace_priv_proc(state))
2399 			return (0);
2400 
2401 		/*
2402 		 * See comment in DIF_VAR_PID.
2403 		 */
2404 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2405 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
2406 
2407 		/*
2408 		 * It is always safe to dereference one's own t_procp pointer:
2409 		 * it always points to a valid, allocated proc structure.
2410 		 * (This is true because threads don't clean up their own
2411 		 * state -- they leave that task to whomever reaps them.)
2412 		 */
2413 		return ((uint64_t)(uintptr_t)
2414 		    curthread->t_procp->p_user.u_comm);
2415 
2416 	case DIF_VAR_ZONENAME:
2417 		if (!dtrace_priv_proc(state))
2418 			return (0);
2419 
2420 		/*
2421 		 * See comment in DIF_VAR_PID.
2422 		 */
2423 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2424 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
2425 
2426 		/*
2427 		 * It is always safe to dereference one's own t_procp pointer:
2428 		 * it always points to a valid, allocated proc structure.
2429 		 * (This is true because threads don't clean up their own
2430 		 * state -- they leave that task to whomever reaps them.)
2431 		 */
2432 		return ((uint64_t)(uintptr_t)
2433 		    curthread->t_procp->p_zone->zone_name);
2434 
2435 	default:
2436 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2437 		return (0);
2438 	}
2439 }
2440 
2441 /*
2442  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
2443  * Notice that we don't bother validating the proper number of arguments or
2444  * their types in the tuple stack.  This isn't needed because all argument
2445  * interpretation is safe because of our load safety -- the worst that can
2446  * happen is that a bogus program can obtain bogus results.
2447  */
2448 static void
2449 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
2450     dtrace_key_t *tupregs, int nargs,
2451     dtrace_mstate_t *mstate, dtrace_state_t *state)
2452 {
2453 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
2454 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
2455 
2456 	union {
2457 		mutex_impl_t mi;
2458 		uint64_t mx;
2459 	} m;
2460 
2461 	union {
2462 		krwlock_t ri;
2463 		uintptr_t rw;
2464 	} r;
2465 
2466 	switch (subr) {
2467 	case DIF_SUBR_RAND:
2468 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
2469 		break;
2470 
2471 	case DIF_SUBR_MUTEX_OWNED:
2472 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2473 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
2474 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
2475 		else
2476 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
2477 		break;
2478 
2479 	case DIF_SUBR_MUTEX_OWNER:
2480 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2481 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
2482 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
2483 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
2484 		else
2485 			regs[rd] = 0;
2486 		break;
2487 
2488 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
2489 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2490 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
2491 		break;
2492 
2493 	case DIF_SUBR_MUTEX_TYPE_SPIN:
2494 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2495 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
2496 		break;
2497 
2498 	case DIF_SUBR_RW_READ_HELD: {
2499 		uintptr_t tmp;
2500 
2501 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2502 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
2503 		break;
2504 	}
2505 
2506 	case DIF_SUBR_RW_WRITE_HELD:
2507 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2508 		regs[rd] = _RW_WRITE_HELD(&r.ri);
2509 		break;
2510 
2511 	case DIF_SUBR_RW_ISWRITER:
2512 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2513 		regs[rd] = _RW_ISWRITER(&r.ri);
2514 		break;
2515 
2516 	case DIF_SUBR_BCOPY: {
2517 		/*
2518 		 * We need to be sure that the destination is in the scratch
2519 		 * region -- no other region is allowed.
2520 		 */
2521 		uintptr_t src = tupregs[0].dttk_value;
2522 		uintptr_t dest = tupregs[1].dttk_value;
2523 		size_t size = tupregs[2].dttk_value;
2524 
2525 		if (!dtrace_inscratch(dest, size, mstate)) {
2526 			*flags |= CPU_DTRACE_BADADDR;
2527 			*illval = regs[rd];
2528 			break;
2529 		}
2530 
2531 		dtrace_bcopy((void *)src, (void *)dest, size);
2532 		break;
2533 	}
2534 
2535 	case DIF_SUBR_ALLOCA:
2536 	case DIF_SUBR_COPYIN: {
2537 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
2538 		uint64_t size =
2539 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
2540 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
2541 
2542 		/*
2543 		 * This action doesn't require any credential checks since
2544 		 * probes will not activate in user contexts to which the
2545 		 * enabling user does not have permissions.
2546 		 */
2547 		if (mstate->dtms_scratch_ptr + scratch_size >
2548 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2549 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2550 			regs[rd] = NULL;
2551 			break;
2552 		}
2553 
2554 		if (subr == DIF_SUBR_COPYIN) {
2555 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2556 			dtrace_copyin(tupregs[0].dttk_value, dest, size);
2557 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2558 		}
2559 
2560 		mstate->dtms_scratch_ptr += scratch_size;
2561 		regs[rd] = dest;
2562 		break;
2563 	}
2564 
2565 	case DIF_SUBR_COPYINTO: {
2566 		uint64_t size = tupregs[1].dttk_value;
2567 		uintptr_t dest = tupregs[2].dttk_value;
2568 
2569 		/*
2570 		 * This action doesn't require any credential checks since
2571 		 * probes will not activate in user contexts to which the
2572 		 * enabling user does not have permissions.
2573 		 */
2574 		if (!dtrace_inscratch(dest, size, mstate)) {
2575 			*flags |= CPU_DTRACE_BADADDR;
2576 			*illval = regs[rd];
2577 			break;
2578 		}
2579 
2580 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2581 		dtrace_copyin(tupregs[0].dttk_value, dest, size);
2582 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2583 		break;
2584 	}
2585 
2586 	case DIF_SUBR_COPYINSTR: {
2587 		uintptr_t dest = mstate->dtms_scratch_ptr;
2588 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2589 
2590 		if (nargs > 1 && tupregs[1].dttk_value < size)
2591 			size = tupregs[1].dttk_value + 1;
2592 
2593 		/*
2594 		 * This action doesn't require any credential checks since
2595 		 * probes will not activate in user contexts to which the
2596 		 * enabling user does not have permissions.
2597 		 */
2598 		if (mstate->dtms_scratch_ptr + size >
2599 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2600 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2601 			regs[rd] = NULL;
2602 			break;
2603 		}
2604 
2605 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2606 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size);
2607 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2608 
2609 		((char *)dest)[size - 1] = '\0';
2610 		mstate->dtms_scratch_ptr += size;
2611 		regs[rd] = dest;
2612 		break;
2613 	}
2614 
2615 	case DIF_SUBR_MSGSIZE:
2616 	case DIF_SUBR_MSGDSIZE: {
2617 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
2618 		uintptr_t wptr, rptr;
2619 		size_t count = 0;
2620 		int cont = 0;
2621 
2622 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
2623 			wptr = dtrace_loadptr(baddr +
2624 			    offsetof(mblk_t, b_wptr));
2625 
2626 			rptr = dtrace_loadptr(baddr +
2627 			    offsetof(mblk_t, b_rptr));
2628 
2629 			if (wptr < rptr) {
2630 				*flags |= CPU_DTRACE_BADADDR;
2631 				*illval = tupregs[0].dttk_value;
2632 				break;
2633 			}
2634 
2635 			daddr = dtrace_loadptr(baddr +
2636 			    offsetof(mblk_t, b_datap));
2637 
2638 			baddr = dtrace_loadptr(baddr +
2639 			    offsetof(mblk_t, b_cont));
2640 
2641 			/*
2642 			 * We want to prevent against denial-of-service here,
2643 			 * so we're only going to search the list for
2644 			 * dtrace_msgdsize_max mblks.
2645 			 */
2646 			if (cont++ > dtrace_msgdsize_max) {
2647 				*flags |= CPU_DTRACE_ILLOP;
2648 				break;
2649 			}
2650 
2651 			if (subr == DIF_SUBR_MSGDSIZE) {
2652 				if (dtrace_load8(daddr +
2653 				    offsetof(dblk_t, db_type)) != M_DATA)
2654 					continue;
2655 			}
2656 
2657 			count += wptr - rptr;
2658 		}
2659 
2660 		if (!(*flags & CPU_DTRACE_FAULT))
2661 			regs[rd] = count;
2662 
2663 		break;
2664 	}
2665 
2666 	case DIF_SUBR_PROGENYOF: {
2667 		pid_t pid = tupregs[0].dttk_value;
2668 		proc_t *p;
2669 		int rval = 0;
2670 
2671 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2672 
2673 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
2674 			if (p->p_pidp->pid_id == pid) {
2675 				rval = 1;
2676 				break;
2677 			}
2678 		}
2679 
2680 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2681 
2682 		regs[rd] = rval;
2683 		break;
2684 	}
2685 
2686 	case DIF_SUBR_SPECULATION:
2687 		regs[rd] = dtrace_speculation(state);
2688 		break;
2689 
2690 	case DIF_SUBR_COPYOUT: {
2691 		uintptr_t kaddr = tupregs[0].dttk_value;
2692 		uintptr_t uaddr = tupregs[1].dttk_value;
2693 		uint64_t size = tupregs[2].dttk_value;
2694 
2695 		if (!dtrace_destructive_disallow &&
2696 		    dtrace_priv_proc_control(state) &&
2697 		    !dtrace_istoxic(kaddr, size)) {
2698 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2699 			dtrace_copyout(kaddr, uaddr, size);
2700 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2701 		}
2702 		break;
2703 	}
2704 
2705 	case DIF_SUBR_COPYOUTSTR: {
2706 		uintptr_t kaddr = tupregs[0].dttk_value;
2707 		uintptr_t uaddr = tupregs[1].dttk_value;
2708 		uint64_t size = tupregs[2].dttk_value;
2709 
2710 		if (!dtrace_destructive_disallow &&
2711 		    dtrace_priv_proc_control(state) &&
2712 		    !dtrace_istoxic(kaddr, size)) {
2713 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2714 			dtrace_copyoutstr(kaddr, uaddr, size);
2715 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2716 		}
2717 		break;
2718 	}
2719 
2720 	case DIF_SUBR_STRLEN:
2721 		regs[rd] = dtrace_strlen((char *)(uintptr_t)
2722 		    tupregs[0].dttk_value,
2723 		    state->dts_options[DTRACEOPT_STRSIZE]);
2724 		break;
2725 
2726 	case DIF_SUBR_STRCHR:
2727 	case DIF_SUBR_STRRCHR: {
2728 		/*
2729 		 * We're going to iterate over the string looking for the
2730 		 * specified character.  We will iterate until we have reached
2731 		 * the string length or we have found the character.  If this
2732 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
2733 		 * of the specified character instead of the first.
2734 		 */
2735 		uintptr_t addr = tupregs[0].dttk_value;
2736 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
2737 		char c, target = (char)tupregs[1].dttk_value;
2738 
2739 		for (regs[rd] = NULL; addr < limit; addr++) {
2740 			if ((c = dtrace_load8(addr)) == target) {
2741 				regs[rd] = addr;
2742 
2743 				if (subr == DIF_SUBR_STRCHR)
2744 					break;
2745 			}
2746 
2747 			if (c == '\0')
2748 				break;
2749 		}
2750 
2751 		break;
2752 	}
2753 
2754 	case DIF_SUBR_STRSTR:
2755 	case DIF_SUBR_INDEX:
2756 	case DIF_SUBR_RINDEX: {
2757 		/*
2758 		 * We're going to iterate over the string looking for the
2759 		 * specified string.  We will iterate until we have reached
2760 		 * the string length or we have found the string.  (Yes, this
2761 		 * is done in the most naive way possible -- but considering
2762 		 * that the string we're searching for is likely to be
2763 		 * relatively short, the complexity of Rabin-Karp or similar
2764 		 * hardly seems merited.)
2765 		 */
2766 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
2767 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
2768 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2769 		size_t len = dtrace_strlen(addr, size);
2770 		size_t sublen = dtrace_strlen(substr, size);
2771 		char *limit = addr + len, *orig = addr;
2772 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
2773 		int inc = 1;
2774 
2775 		regs[rd] = notfound;
2776 
2777 		/*
2778 		 * strstr() and index()/rindex() have similar semantics if
2779 		 * both strings are the empty string: strstr() returns a
2780 		 * pointer to the (empty) string, and index() and rindex()
2781 		 * both return index 0 (regardless of any position argument).
2782 		 */
2783 		if (sublen == 0 && len == 0) {
2784 			if (subr == DIF_SUBR_STRSTR)
2785 				regs[rd] = (uintptr_t)addr;
2786 			else
2787 				regs[rd] = 0;
2788 			break;
2789 		}
2790 
2791 		if (subr != DIF_SUBR_STRSTR) {
2792 			if (subr == DIF_SUBR_RINDEX) {
2793 				limit = orig - 1;
2794 				addr += len;
2795 				inc = -1;
2796 			}
2797 
2798 			/*
2799 			 * Both index() and rindex() take an optional position
2800 			 * argument that denotes the starting position.
2801 			 */
2802 			if (nargs == 3) {
2803 				int64_t pos = (int64_t)tupregs[2].dttk_value;
2804 
2805 				/*
2806 				 * If the position argument to index() is
2807 				 * negative, Perl implicitly clamps it at
2808 				 * zero.  This semantic is a little surprising
2809 				 * given the special meaning of negative
2810 				 * positions to similar Perl functions like
2811 				 * substr(), but it appears to reflect a
2812 				 * notion that index() can start from a
2813 				 * negative index and increment its way up to
2814 				 * the string.  Given this notion, Perl's
2815 				 * rindex() is at least self-consistent in
2816 				 * that it implicitly clamps positions greater
2817 				 * than the string length to be the string
2818 				 * length.  Where Perl completely loses
2819 				 * coherence, however, is when the specified
2820 				 * substring is the empty string ("").  In
2821 				 * this case, even if the position is
2822 				 * negative, rindex() returns 0 -- and even if
2823 				 * the position is greater than the length,
2824 				 * index() returns the string length.  These
2825 				 * semantics violate the notion that index()
2826 				 * should never return a value less than the
2827 				 * specified position and that rindex() should
2828 				 * never return a value greater than the
2829 				 * specified position.  (One assumes that
2830 				 * these semantics are artifacts of Perl's
2831 				 * implementation and not the results of
2832 				 * deliberate design -- it beggars belief that
2833 				 * even Larry Wall could desire such oddness.)
2834 				 * While in the abstract one would wish for
2835 				 * consistent position semantics across
2836 				 * substr(), index() and rindex() -- or at the
2837 				 * very least self-consistent position
2838 				 * semantics for index() and rindex() -- we
2839 				 * instead opt to keep with the extant Perl
2840 				 * semantics, in all their broken glory.  (Do
2841 				 * we have more desire to maintain Perl's
2842 				 * semantics than Perl does?  Probably.)
2843 				 */
2844 				if (subr == DIF_SUBR_RINDEX) {
2845 					if (pos < 0) {
2846 						if (sublen == 0)
2847 							regs[rd] = 0;
2848 						break;
2849 					}
2850 
2851 					if (pos > len)
2852 						pos = len;
2853 				} else {
2854 					if (pos < 0)
2855 						pos = 0;
2856 
2857 					if (pos >= len) {
2858 						if (sublen == 0)
2859 							regs[rd] = len;
2860 						break;
2861 					}
2862 				}
2863 
2864 				addr = orig + pos;
2865 			}
2866 		}
2867 
2868 		for (regs[rd] = notfound; addr != limit; addr += inc) {
2869 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
2870 				if (subr != DIF_SUBR_STRSTR) {
2871 					/*
2872 					 * As D index() and rindex() are
2873 					 * modeled on Perl (and not on awk),
2874 					 * we return a zero-based (and not a
2875 					 * one-based) index.  (For you Perl
2876 					 * weenies: no, we're not going to add
2877 					 * $[ -- and shouldn't you be at a con
2878 					 * or something?)
2879 					 */
2880 					regs[rd] = (uintptr_t)(addr - orig);
2881 					break;
2882 				}
2883 
2884 				ASSERT(subr == DIF_SUBR_STRSTR);
2885 				regs[rd] = (uintptr_t)addr;
2886 				break;
2887 			}
2888 		}
2889 
2890 		break;
2891 	}
2892 
2893 	case DIF_SUBR_STRTOK: {
2894 		uintptr_t addr = tupregs[0].dttk_value;
2895 		uintptr_t tokaddr = tupregs[1].dttk_value;
2896 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2897 		uintptr_t limit, toklimit = tokaddr + size;
2898 		uint8_t c, tokmap[32];	 /* 256 / 8 */
2899 		char *dest = (char *)mstate->dtms_scratch_ptr;
2900 		int i;
2901 
2902 		if (mstate->dtms_scratch_ptr + size >
2903 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2904 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2905 			regs[rd] = NULL;
2906 			break;
2907 		}
2908 
2909 		if (addr == NULL) {
2910 			/*
2911 			 * If the address specified is NULL, we use our saved
2912 			 * strtok pointer from the mstate.  Note that this
2913 			 * means that the saved strtok pointer is _only_
2914 			 * valid within multiple enablings of the same probe --
2915 			 * it behaves like an implicit clause-local variable.
2916 			 */
2917 			addr = mstate->dtms_strtok;
2918 		}
2919 
2920 		/*
2921 		 * First, zero the token map, and then process the token
2922 		 * string -- setting a bit in the map for every character
2923 		 * found in the token string.
2924 		 */
2925 		for (i = 0; i < sizeof (tokmap); i++)
2926 			tokmap[i] = 0;
2927 
2928 		for (; tokaddr < toklimit; tokaddr++) {
2929 			if ((c = dtrace_load8(tokaddr)) == '\0')
2930 				break;
2931 
2932 			ASSERT((c >> 3) < sizeof (tokmap));
2933 			tokmap[c >> 3] |= (1 << (c & 0x7));
2934 		}
2935 
2936 		for (limit = addr + size; addr < limit; addr++) {
2937 			/*
2938 			 * We're looking for a character that is _not_ contained
2939 			 * in the token string.
2940 			 */
2941 			if ((c = dtrace_load8(addr)) == '\0')
2942 				break;
2943 
2944 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
2945 				break;
2946 		}
2947 
2948 		if (c == '\0') {
2949 			/*
2950 			 * We reached the end of the string without finding
2951 			 * any character that was not in the token string.
2952 			 * We return NULL in this case, and we set the saved
2953 			 * address to NULL as well.
2954 			 */
2955 			regs[rd] = NULL;
2956 			mstate->dtms_strtok = NULL;
2957 			break;
2958 		}
2959 
2960 		/*
2961 		 * From here on, we're copying into the destination string.
2962 		 */
2963 		for (i = 0; addr < limit && i < size - 1; addr++) {
2964 			if ((c = dtrace_load8(addr)) == '\0')
2965 				break;
2966 
2967 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
2968 				break;
2969 
2970 			ASSERT(i < size);
2971 			dest[i++] = c;
2972 		}
2973 
2974 		ASSERT(i < size);
2975 		dest[i] = '\0';
2976 		regs[rd] = (uintptr_t)dest;
2977 		mstate->dtms_scratch_ptr += size;
2978 		mstate->dtms_strtok = addr;
2979 		break;
2980 	}
2981 
2982 	case DIF_SUBR_SUBSTR: {
2983 		uintptr_t s = tupregs[0].dttk_value;
2984 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2985 		char *d = (char *)mstate->dtms_scratch_ptr;
2986 		int64_t index = (int64_t)tupregs[1].dttk_value;
2987 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
2988 		size_t len = dtrace_strlen((char *)s, size);
2989 		int64_t i = 0;
2990 
2991 		if (nargs <= 2)
2992 			remaining = (int64_t)size;
2993 
2994 		if (mstate->dtms_scratch_ptr + size >
2995 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2996 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2997 			regs[rd] = NULL;
2998 			break;
2999 		}
3000 
3001 		if (index < 0) {
3002 			index += len;
3003 
3004 			if (index < 0 && index + remaining > 0) {
3005 				remaining += index;
3006 				index = 0;
3007 			}
3008 		}
3009 
3010 		if (index >= len || index < 0)
3011 			index = len;
3012 
3013 		for (d[0] = '\0'; remaining > 0; remaining--) {
3014 			if ((d[i++] = dtrace_load8(s++ + index)) == '\0')
3015 				break;
3016 
3017 			if (i == size) {
3018 				d[i - 1] = '\0';
3019 				break;
3020 			}
3021 		}
3022 
3023 		mstate->dtms_scratch_ptr += size;
3024 		regs[rd] = (uintptr_t)d;
3025 		break;
3026 	}
3027 
3028 	case DIF_SUBR_GETMAJOR:
3029 #ifdef _LP64
3030 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
3031 #else
3032 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
3033 #endif
3034 		break;
3035 
3036 	case DIF_SUBR_GETMINOR:
3037 #ifdef _LP64
3038 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
3039 #else
3040 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
3041 #endif
3042 		break;
3043 
3044 	case DIF_SUBR_DDI_PATHNAME: {
3045 		/*
3046 		 * This one is a galactic mess.  We are going to roughly
3047 		 * emulate ddi_pathname(), but it's made more complicated
3048 		 * by the fact that we (a) want to include the minor name and
3049 		 * (b) must proceed iteratively instead of recursively.
3050 		 */
3051 		uintptr_t dest = mstate->dtms_scratch_ptr;
3052 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3053 		char *start = (char *)dest, *end = start + size - 1;
3054 		uintptr_t daddr = tupregs[0].dttk_value;
3055 		int64_t minor = (int64_t)tupregs[1].dttk_value;
3056 		char *s;
3057 		int i, len, depth = 0;
3058 
3059 		if (size == 0 || mstate->dtms_scratch_ptr + size >
3060 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3061 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3062 			regs[rd] = NULL;
3063 			break;
3064 		}
3065 
3066 		*end = '\0';
3067 
3068 		/*
3069 		 * We want to have a name for the minor.  In order to do this,
3070 		 * we need to walk the minor list from the devinfo.  We want
3071 		 * to be sure that we don't infinitely walk a circular list,
3072 		 * so we check for circularity by sending a scout pointer
3073 		 * ahead two elements for every element that we iterate over;
3074 		 * if the list is circular, these will ultimately point to the
3075 		 * same element.  You may recognize this little trick as the
3076 		 * answer to a stupid interview question -- one that always
3077 		 * seems to be asked by those who had to have it laboriously
3078 		 * explained to them, and who can't even concisely describe
3079 		 * the conditions under which one would be forced to resort to
3080 		 * this technique.  Needless to say, those conditions are
3081 		 * found here -- and probably only here.  Is this is the only
3082 		 * use of this infamous trick in shipping, production code?
3083 		 * If it isn't, it probably should be...
3084 		 */
3085 		if (minor != -1) {
3086 			uintptr_t maddr = dtrace_loadptr(daddr +
3087 			    offsetof(struct dev_info, devi_minor));
3088 
3089 			uintptr_t next = offsetof(struct ddi_minor_data, next);
3090 			uintptr_t name = offsetof(struct ddi_minor_data,
3091 			    d_minor) + offsetof(struct ddi_minor, name);
3092 			uintptr_t dev = offsetof(struct ddi_minor_data,
3093 			    d_minor) + offsetof(struct ddi_minor, dev);
3094 			uintptr_t scout;
3095 
3096 			if (maddr != NULL)
3097 				scout = dtrace_loadptr(maddr + next);
3098 
3099 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3100 				uint64_t m;
3101 #ifdef _LP64
3102 				m = dtrace_load64(maddr + dev) & MAXMIN64;
3103 #else
3104 				m = dtrace_load32(maddr + dev) & MAXMIN;
3105 #endif
3106 				if (m != minor) {
3107 					maddr = dtrace_loadptr(maddr + next);
3108 
3109 					if (scout == NULL)
3110 						continue;
3111 
3112 					scout = dtrace_loadptr(scout + next);
3113 
3114 					if (scout == NULL)
3115 						continue;
3116 
3117 					scout = dtrace_loadptr(scout + next);
3118 
3119 					if (scout == NULL)
3120 						continue;
3121 
3122 					if (scout == maddr) {
3123 						*flags |= CPU_DTRACE_ILLOP;
3124 						break;
3125 					}
3126 
3127 					continue;
3128 				}
3129 
3130 				/*
3131 				 * We have the minor data.  Now we need to
3132 				 * copy the minor's name into the end of the
3133 				 * pathname.
3134 				 */
3135 				s = (char *)dtrace_loadptr(maddr + name);
3136 				len = dtrace_strlen(s, size);
3137 
3138 				if (*flags & CPU_DTRACE_FAULT)
3139 					break;
3140 
3141 				if (len != 0) {
3142 					if ((end -= (len + 1)) < start)
3143 						break;
3144 
3145 					*end = ':';
3146 				}
3147 
3148 				for (i = 1; i <= len; i++)
3149 					end[i] = dtrace_load8((uintptr_t)s++);
3150 				break;
3151 			}
3152 		}
3153 
3154 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3155 			ddi_node_state_t devi_state;
3156 
3157 			devi_state = dtrace_load32(daddr +
3158 			    offsetof(struct dev_info, devi_node_state));
3159 
3160 			if (*flags & CPU_DTRACE_FAULT)
3161 				break;
3162 
3163 			if (devi_state >= DS_INITIALIZED) {
3164 				s = (char *)dtrace_loadptr(daddr +
3165 				    offsetof(struct dev_info, devi_addr));
3166 				len = dtrace_strlen(s, size);
3167 
3168 				if (*flags & CPU_DTRACE_FAULT)
3169 					break;
3170 
3171 				if (len != 0) {
3172 					if ((end -= (len + 1)) < start)
3173 						break;
3174 
3175 					*end = '@';
3176 				}
3177 
3178 				for (i = 1; i <= len; i++)
3179 					end[i] = dtrace_load8((uintptr_t)s++);
3180 			}
3181 
3182 			/*
3183 			 * Now for the node name...
3184 			 */
3185 			s = (char *)dtrace_loadptr(daddr +
3186 			    offsetof(struct dev_info, devi_node_name));
3187 
3188 			daddr = dtrace_loadptr(daddr +
3189 			    offsetof(struct dev_info, devi_parent));
3190 
3191 			/*
3192 			 * If our parent is NULL (that is, if we're the root
3193 			 * node), we're going to use the special path
3194 			 * "devices".
3195 			 */
3196 			if (daddr == NULL)
3197 				s = "devices";
3198 
3199 			len = dtrace_strlen(s, size);
3200 			if (*flags & CPU_DTRACE_FAULT)
3201 				break;
3202 
3203 			if ((end -= (len + 1)) < start)
3204 				break;
3205 
3206 			for (i = 1; i <= len; i++)
3207 				end[i] = dtrace_load8((uintptr_t)s++);
3208 			*end = '/';
3209 
3210 			if (depth++ > dtrace_devdepth_max) {
3211 				*flags |= CPU_DTRACE_ILLOP;
3212 				break;
3213 			}
3214 		}
3215 
3216 		if (end < start)
3217 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3218 
3219 		if (daddr == NULL) {
3220 			regs[rd] = (uintptr_t)end;
3221 			mstate->dtms_scratch_ptr += size;
3222 		}
3223 
3224 		break;
3225 	}
3226 
3227 	case DIF_SUBR_STRJOIN: {
3228 		char *d = (char *)mstate->dtms_scratch_ptr;
3229 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3230 		uintptr_t s1 = tupregs[0].dttk_value;
3231 		uintptr_t s2 = tupregs[1].dttk_value;
3232 		int i = 0;
3233 
3234 		if (mstate->dtms_scratch_ptr + size >
3235 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3236 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3237 			regs[rd] = NULL;
3238 			break;
3239 		}
3240 
3241 		for (;;) {
3242 			if (i >= size) {
3243 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3244 				regs[rd] = NULL;
3245 				break;
3246 			}
3247 
3248 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
3249 				i--;
3250 				break;
3251 			}
3252 		}
3253 
3254 		for (;;) {
3255 			if (i >= size) {
3256 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3257 				regs[rd] = NULL;
3258 				break;
3259 			}
3260 
3261 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
3262 				break;
3263 		}
3264 
3265 		if (i < size) {
3266 			mstate->dtms_scratch_ptr += i;
3267 			regs[rd] = (uintptr_t)d;
3268 		}
3269 
3270 		break;
3271 	}
3272 
3273 	case DIF_SUBR_LLTOSTR: {
3274 		int64_t i = (int64_t)tupregs[0].dttk_value;
3275 		int64_t val = i < 0 ? i * -1 : i;
3276 		uint64_t size = 22;	/* enough room for 2^64 in decimal */
3277 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
3278 
3279 		if (mstate->dtms_scratch_ptr + size >
3280 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3281 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3282 			regs[rd] = NULL;
3283 			break;
3284 		}
3285 
3286 		for (*end-- = '\0'; val; val /= 10)
3287 			*end-- = '0' + (val % 10);
3288 
3289 		if (i == 0)
3290 			*end-- = '0';
3291 
3292 		if (i < 0)
3293 			*end-- = '-';
3294 
3295 		regs[rd] = (uintptr_t)end + 1;
3296 		mstate->dtms_scratch_ptr += size;
3297 		break;
3298 	}
3299 
3300 	case DIF_SUBR_DIRNAME:
3301 	case DIF_SUBR_BASENAME: {
3302 		char *dest = (char *)mstate->dtms_scratch_ptr;
3303 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3304 		uintptr_t src = tupregs[0].dttk_value;
3305 		int i, j, len = dtrace_strlen((char *)src, size);
3306 		int lastbase = -1, firstbase = -1, lastdir = -1;
3307 		int start, end;
3308 
3309 		if (mstate->dtms_scratch_ptr + size >
3310 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3311 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3312 			regs[rd] = NULL;
3313 			break;
3314 		}
3315 
3316 		/*
3317 		 * The basename and dirname for a zero-length string is
3318 		 * defined to be "."
3319 		 */
3320 		if (len == 0) {
3321 			len = 1;
3322 			src = (uintptr_t)".";
3323 		}
3324 
3325 		/*
3326 		 * Start from the back of the string, moving back toward the
3327 		 * front until we see a character that isn't a slash.  That
3328 		 * character is the last character in the basename.
3329 		 */
3330 		for (i = len - 1; i >= 0; i--) {
3331 			if (dtrace_load8(src + i) != '/')
3332 				break;
3333 		}
3334 
3335 		if (i >= 0)
3336 			lastbase = i;
3337 
3338 		/*
3339 		 * Starting from the last character in the basename, move
3340 		 * towards the front until we find a slash.  The character
3341 		 * that we processed immediately before that is the first
3342 		 * character in the basename.
3343 		 */
3344 		for (; i >= 0; i--) {
3345 			if (dtrace_load8(src + i) == '/')
3346 				break;
3347 		}
3348 
3349 		if (i >= 0)
3350 			firstbase = i + 1;
3351 
3352 		/*
3353 		 * Now keep going until we find a non-slash character.  That
3354 		 * character is the last character in the dirname.
3355 		 */
3356 		for (; i >= 0; i--) {
3357 			if (dtrace_load8(src + i) != '/')
3358 				break;
3359 		}
3360 
3361 		if (i >= 0)
3362 			lastdir = i;
3363 
3364 		ASSERT(!(lastbase == -1 && firstbase != -1));
3365 		ASSERT(!(firstbase == -1 && lastdir != -1));
3366 
3367 		if (lastbase == -1) {
3368 			/*
3369 			 * We didn't find a non-slash character.  We know that
3370 			 * the length is non-zero, so the whole string must be
3371 			 * slashes.  In either the dirname or the basename
3372 			 * case, we return '/'.
3373 			 */
3374 			ASSERT(firstbase == -1);
3375 			firstbase = lastbase = lastdir = 0;
3376 		}
3377 
3378 		if (firstbase == -1) {
3379 			/*
3380 			 * The entire string consists only of a basename
3381 			 * component.  If we're looking for dirname, we need
3382 			 * to change our string to be just "."; if we're
3383 			 * looking for a basename, we'll just set the first
3384 			 * character of the basename to be 0.
3385 			 */
3386 			if (subr == DIF_SUBR_DIRNAME) {
3387 				ASSERT(lastdir == -1);
3388 				src = (uintptr_t)".";
3389 				lastdir = 0;
3390 			} else {
3391 				firstbase = 0;
3392 			}
3393 		}
3394 
3395 		if (subr == DIF_SUBR_DIRNAME) {
3396 			if (lastdir == -1) {
3397 				/*
3398 				 * We know that we have a slash in the name --
3399 				 * or lastdir would be set to 0, above.  And
3400 				 * because lastdir is -1, we know that this
3401 				 * slash must be the first character.  (That
3402 				 * is, the full string must be of the form
3403 				 * "/basename".)  In this case, the last
3404 				 * character of the directory name is 0.
3405 				 */
3406 				lastdir = 0;
3407 			}
3408 
3409 			start = 0;
3410 			end = lastdir;
3411 		} else {
3412 			ASSERT(subr == DIF_SUBR_BASENAME);
3413 			ASSERT(firstbase != -1 && lastbase != -1);
3414 			start = firstbase;
3415 			end = lastbase;
3416 		}
3417 
3418 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
3419 			dest[j] = dtrace_load8(src + i);
3420 
3421 		dest[j] = '\0';
3422 		regs[rd] = (uintptr_t)dest;
3423 		mstate->dtms_scratch_ptr += size;
3424 		break;
3425 	}
3426 
3427 	case DIF_SUBR_CLEANPATH: {
3428 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
3429 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3430 		uintptr_t src = tupregs[0].dttk_value;
3431 		int i = 0, j = 0;
3432 
3433 		if (mstate->dtms_scratch_ptr + size >
3434 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3435 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3436 			regs[rd] = NULL;
3437 			break;
3438 		}
3439 
3440 		/*
3441 		 * Move forward, loading each character.
3442 		 */
3443 		do {
3444 			c = dtrace_load8(src + i++);
3445 next:
3446 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
3447 				break;
3448 
3449 			if (c != '/') {
3450 				dest[j++] = c;
3451 				continue;
3452 			}
3453 
3454 			c = dtrace_load8(src + i++);
3455 
3456 			if (c == '/') {
3457 				/*
3458 				 * We have two slashes -- we can just advance
3459 				 * to the next character.
3460 				 */
3461 				goto next;
3462 			}
3463 
3464 			if (c != '.') {
3465 				/*
3466 				 * This is not "." and it's not ".." -- we can
3467 				 * just store the "/" and this character and
3468 				 * drive on.
3469 				 */
3470 				dest[j++] = '/';
3471 				dest[j++] = c;
3472 				continue;
3473 			}
3474 
3475 			c = dtrace_load8(src + i++);
3476 
3477 			if (c == '/') {
3478 				/*
3479 				 * This is a "/./" component.  We're not going
3480 				 * to store anything in the destination buffer;
3481 				 * we're just going to go to the next component.
3482 				 */
3483 				goto next;
3484 			}
3485 
3486 			if (c != '.') {
3487 				/*
3488 				 * This is not ".." -- we can just store the
3489 				 * "/." and this character and continue
3490 				 * processing.
3491 				 */
3492 				dest[j++] = '/';
3493 				dest[j++] = '.';
3494 				dest[j++] = c;
3495 				continue;
3496 			}
3497 
3498 			c = dtrace_load8(src + i++);
3499 
3500 			if (c != '/' && c != '\0') {
3501 				/*
3502 				 * This is not ".." -- it's "..[mumble]".
3503 				 * We'll store the "/.." and this character
3504 				 * and continue processing.
3505 				 */
3506 				dest[j++] = '/';
3507 				dest[j++] = '.';
3508 				dest[j++] = '.';
3509 				dest[j++] = c;
3510 				continue;
3511 			}
3512 
3513 			/*
3514 			 * This is "/../" or "/..\0".  We need to back up
3515 			 * our destination pointer until we find a "/".
3516 			 */
3517 			i--;
3518 			while (j != 0 && dest[--j] != '/')
3519 				continue;
3520 
3521 			if (c == '\0')
3522 				dest[++j] = '/';
3523 		} while (c != '\0');
3524 
3525 		dest[j] = '\0';
3526 		regs[rd] = (uintptr_t)dest;
3527 		mstate->dtms_scratch_ptr += size;
3528 		break;
3529 	}
3530 	}
3531 }
3532 
3533 /*
3534  * Emulate the execution of DTrace IR instructions specified by the given
3535  * DIF object.  This function is deliberately void of assertions as all of
3536  * the necessary checks are handled by a call to dtrace_difo_validate().
3537  */
3538 static uint64_t
3539 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
3540     dtrace_vstate_t *vstate, dtrace_state_t *state)
3541 {
3542 	const dif_instr_t *text = difo->dtdo_buf;
3543 	const uint_t textlen = difo->dtdo_len;
3544 	const char *strtab = difo->dtdo_strtab;
3545 	const uint64_t *inttab = difo->dtdo_inttab;
3546 
3547 	uint64_t rval = 0;
3548 	dtrace_statvar_t *svar;
3549 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
3550 	dtrace_difv_t *v;
3551 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3552 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3553 
3554 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
3555 	uint64_t regs[DIF_DIR_NREGS];
3556 	uint64_t *tmp;
3557 
3558 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
3559 	int64_t cc_r;
3560 	uint_t pc = 0, id, opc;
3561 	uint8_t ttop = 0;
3562 	dif_instr_t instr;
3563 	uint_t r1, r2, rd;
3564 
3565 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
3566 
3567 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
3568 		opc = pc;
3569 
3570 		instr = text[pc++];
3571 		r1 = DIF_INSTR_R1(instr);
3572 		r2 = DIF_INSTR_R2(instr);
3573 		rd = DIF_INSTR_RD(instr);
3574 
3575 		switch (DIF_INSTR_OP(instr)) {
3576 		case DIF_OP_OR:
3577 			regs[rd] = regs[r1] | regs[r2];
3578 			break;
3579 		case DIF_OP_XOR:
3580 			regs[rd] = regs[r1] ^ regs[r2];
3581 			break;
3582 		case DIF_OP_AND:
3583 			regs[rd] = regs[r1] & regs[r2];
3584 			break;
3585 		case DIF_OP_SLL:
3586 			regs[rd] = regs[r1] << regs[r2];
3587 			break;
3588 		case DIF_OP_SRL:
3589 			regs[rd] = regs[r1] >> regs[r2];
3590 			break;
3591 		case DIF_OP_SUB:
3592 			regs[rd] = regs[r1] - regs[r2];
3593 			break;
3594 		case DIF_OP_ADD:
3595 			regs[rd] = regs[r1] + regs[r2];
3596 			break;
3597 		case DIF_OP_MUL:
3598 			regs[rd] = regs[r1] * regs[r2];
3599 			break;
3600 		case DIF_OP_SDIV:
3601 			if (regs[r2] == 0) {
3602 				regs[rd] = 0;
3603 				*flags |= CPU_DTRACE_DIVZERO;
3604 			} else {
3605 				regs[rd] = (int64_t)regs[r1] /
3606 				    (int64_t)regs[r2];
3607 			}
3608 			break;
3609 
3610 		case DIF_OP_UDIV:
3611 			if (regs[r2] == 0) {
3612 				regs[rd] = 0;
3613 				*flags |= CPU_DTRACE_DIVZERO;
3614 			} else {
3615 				regs[rd] = regs[r1] / regs[r2];
3616 			}
3617 			break;
3618 
3619 		case DIF_OP_SREM:
3620 			if (regs[r2] == 0) {
3621 				regs[rd] = 0;
3622 				*flags |= CPU_DTRACE_DIVZERO;
3623 			} else {
3624 				regs[rd] = (int64_t)regs[r1] %
3625 				    (int64_t)regs[r2];
3626 			}
3627 			break;
3628 
3629 		case DIF_OP_UREM:
3630 			if (regs[r2] == 0) {
3631 				regs[rd] = 0;
3632 				*flags |= CPU_DTRACE_DIVZERO;
3633 			} else {
3634 				regs[rd] = regs[r1] % regs[r2];
3635 			}
3636 			break;
3637 
3638 		case DIF_OP_NOT:
3639 			regs[rd] = ~regs[r1];
3640 			break;
3641 		case DIF_OP_MOV:
3642 			regs[rd] = regs[r1];
3643 			break;
3644 		case DIF_OP_CMP:
3645 			cc_r = regs[r1] - regs[r2];
3646 			cc_n = cc_r < 0;
3647 			cc_z = cc_r == 0;
3648 			cc_v = 0;
3649 			cc_c = regs[r1] < regs[r2];
3650 			break;
3651 		case DIF_OP_TST:
3652 			cc_n = cc_v = cc_c = 0;
3653 			cc_z = regs[r1] == 0;
3654 			break;
3655 		case DIF_OP_BA:
3656 			pc = DIF_INSTR_LABEL(instr);
3657 			break;
3658 		case DIF_OP_BE:
3659 			if (cc_z)
3660 				pc = DIF_INSTR_LABEL(instr);
3661 			break;
3662 		case DIF_OP_BNE:
3663 			if (cc_z == 0)
3664 				pc = DIF_INSTR_LABEL(instr);
3665 			break;
3666 		case DIF_OP_BG:
3667 			if ((cc_z | (cc_n ^ cc_v)) == 0)
3668 				pc = DIF_INSTR_LABEL(instr);
3669 			break;
3670 		case DIF_OP_BGU:
3671 			if ((cc_c | cc_z) == 0)
3672 				pc = DIF_INSTR_LABEL(instr);
3673 			break;
3674 		case DIF_OP_BGE:
3675 			if ((cc_n ^ cc_v) == 0)
3676 				pc = DIF_INSTR_LABEL(instr);
3677 			break;
3678 		case DIF_OP_BGEU:
3679 			if (cc_c == 0)
3680 				pc = DIF_INSTR_LABEL(instr);
3681 			break;
3682 		case DIF_OP_BL:
3683 			if (cc_n ^ cc_v)
3684 				pc = DIF_INSTR_LABEL(instr);
3685 			break;
3686 		case DIF_OP_BLU:
3687 			if (cc_c)
3688 				pc = DIF_INSTR_LABEL(instr);
3689 			break;
3690 		case DIF_OP_BLE:
3691 			if (cc_z | (cc_n ^ cc_v))
3692 				pc = DIF_INSTR_LABEL(instr);
3693 			break;
3694 		case DIF_OP_BLEU:
3695 			if (cc_c | cc_z)
3696 				pc = DIF_INSTR_LABEL(instr);
3697 			break;
3698 		case DIF_OP_RLDSB:
3699 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
3700 				*flags |= CPU_DTRACE_KPRIV;
3701 				*illval = regs[r1];
3702 				break;
3703 			}
3704 			/*FALLTHROUGH*/
3705 		case DIF_OP_LDSB:
3706 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
3707 			break;
3708 		case DIF_OP_RLDSH:
3709 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
3710 				*flags |= CPU_DTRACE_KPRIV;
3711 				*illval = regs[r1];
3712 				break;
3713 			}
3714 			/*FALLTHROUGH*/
3715 		case DIF_OP_LDSH:
3716 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
3717 			break;
3718 		case DIF_OP_RLDSW:
3719 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
3720 				*flags |= CPU_DTRACE_KPRIV;
3721 				*illval = regs[r1];
3722 				break;
3723 			}
3724 			/*FALLTHROUGH*/
3725 		case DIF_OP_LDSW:
3726 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
3727 			break;
3728 		case DIF_OP_RLDUB:
3729 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
3730 				*flags |= CPU_DTRACE_KPRIV;
3731 				*illval = regs[r1];
3732 				break;
3733 			}
3734 			/*FALLTHROUGH*/
3735 		case DIF_OP_LDUB:
3736 			regs[rd] = dtrace_load8(regs[r1]);
3737 			break;
3738 		case DIF_OP_RLDUH:
3739 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
3740 				*flags |= CPU_DTRACE_KPRIV;
3741 				*illval = regs[r1];
3742 				break;
3743 			}
3744 			/*FALLTHROUGH*/
3745 		case DIF_OP_LDUH:
3746 			regs[rd] = dtrace_load16(regs[r1]);
3747 			break;
3748 		case DIF_OP_RLDUW:
3749 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
3750 				*flags |= CPU_DTRACE_KPRIV;
3751 				*illval = regs[r1];
3752 				break;
3753 			}
3754 			/*FALLTHROUGH*/
3755 		case DIF_OP_LDUW:
3756 			regs[rd] = dtrace_load32(regs[r1]);
3757 			break;
3758 		case DIF_OP_RLDX:
3759 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
3760 				*flags |= CPU_DTRACE_KPRIV;
3761 				*illval = regs[r1];
3762 				break;
3763 			}
3764 			/*FALLTHROUGH*/
3765 		case DIF_OP_LDX:
3766 			regs[rd] = dtrace_load64(regs[r1]);
3767 			break;
3768 		case DIF_OP_ULDSB:
3769 			regs[rd] = (int8_t)
3770 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
3771 			break;
3772 		case DIF_OP_ULDSH:
3773 			regs[rd] = (int16_t)
3774 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
3775 			break;
3776 		case DIF_OP_ULDSW:
3777 			regs[rd] = (int32_t)
3778 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
3779 			break;
3780 		case DIF_OP_ULDUB:
3781 			regs[rd] =
3782 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
3783 			break;
3784 		case DIF_OP_ULDUH:
3785 			regs[rd] =
3786 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
3787 			break;
3788 		case DIF_OP_ULDUW:
3789 			regs[rd] =
3790 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
3791 			break;
3792 		case DIF_OP_ULDX:
3793 			regs[rd] =
3794 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
3795 			break;
3796 		case DIF_OP_RET:
3797 			rval = regs[rd];
3798 			break;
3799 		case DIF_OP_NOP:
3800 			break;
3801 		case DIF_OP_SETX:
3802 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
3803 			break;
3804 		case DIF_OP_SETS:
3805 			regs[rd] = (uint64_t)(uintptr_t)
3806 			    (strtab + DIF_INSTR_STRING(instr));
3807 			break;
3808 		case DIF_OP_SCMP:
3809 			cc_r = dtrace_strncmp((char *)(uintptr_t)regs[r1],
3810 			    (char *)(uintptr_t)regs[r2],
3811 			    state->dts_options[DTRACEOPT_STRSIZE]);
3812 
3813 			cc_n = cc_r < 0;
3814 			cc_z = cc_r == 0;
3815 			cc_v = cc_c = 0;
3816 			break;
3817 		case DIF_OP_LDGA:
3818 			regs[rd] = dtrace_dif_variable(mstate, state,
3819 			    r1, regs[r2]);
3820 			break;
3821 		case DIF_OP_LDGS:
3822 			id = DIF_INSTR_VAR(instr);
3823 
3824 			if (id >= DIF_VAR_OTHER_UBASE) {
3825 				uintptr_t a;
3826 
3827 				id -= DIF_VAR_OTHER_UBASE;
3828 				svar = vstate->dtvs_globals[id];
3829 				ASSERT(svar != NULL);
3830 				v = &svar->dtsv_var;
3831 
3832 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
3833 					regs[rd] = svar->dtsv_data;
3834 					break;
3835 				}
3836 
3837 				a = (uintptr_t)svar->dtsv_data;
3838 
3839 				if (*(uint8_t *)a == UINT8_MAX) {
3840 					/*
3841 					 * If the 0th byte is set to UINT8_MAX
3842 					 * then this is to be treated as a
3843 					 * reference to a NULL variable.
3844 					 */
3845 					regs[rd] = NULL;
3846 				} else {
3847 					regs[rd] = a + sizeof (uint64_t);
3848 				}
3849 
3850 				break;
3851 			}
3852 
3853 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
3854 			break;
3855 
3856 		case DIF_OP_STGS:
3857 			id = DIF_INSTR_VAR(instr);
3858 
3859 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
3860 			id -= DIF_VAR_OTHER_UBASE;
3861 
3862 			svar = vstate->dtvs_globals[id];
3863 			ASSERT(svar != NULL);
3864 			v = &svar->dtsv_var;
3865 
3866 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
3867 				uintptr_t a = (uintptr_t)svar->dtsv_data;
3868 
3869 				ASSERT(a != NULL);
3870 				ASSERT(svar->dtsv_size != 0);
3871 
3872 				if (regs[rd] == NULL) {
3873 					*(uint8_t *)a = UINT8_MAX;
3874 					break;
3875 				} else {
3876 					*(uint8_t *)a = 0;
3877 					a += sizeof (uint64_t);
3878 				}
3879 
3880 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
3881 				    (void *)a, &v->dtdv_type);
3882 				break;
3883 			}
3884 
3885 			svar->dtsv_data = regs[rd];
3886 			break;
3887 
3888 		case DIF_OP_LDTA:
3889 			/*
3890 			 * There are no DTrace built-in thread-local arrays at
3891 			 * present.  This opcode is saved for future work.
3892 			 */
3893 			*flags |= CPU_DTRACE_ILLOP;
3894 			regs[rd] = 0;
3895 			break;
3896 
3897 		case DIF_OP_LDLS:
3898 			id = DIF_INSTR_VAR(instr);
3899 
3900 			if (id < DIF_VAR_OTHER_UBASE) {
3901 				/*
3902 				 * For now, this has no meaning.
3903 				 */
3904 				regs[rd] = 0;
3905 				break;
3906 			}
3907 
3908 			id -= DIF_VAR_OTHER_UBASE;
3909 
3910 			ASSERT(id < vstate->dtvs_nlocals);
3911 			ASSERT(vstate->dtvs_locals != NULL);
3912 
3913 			svar = vstate->dtvs_locals[id];
3914 			ASSERT(svar != NULL);
3915 			v = &svar->dtsv_var;
3916 
3917 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
3918 				uintptr_t a = (uintptr_t)svar->dtsv_data;
3919 				size_t sz = v->dtdv_type.dtdt_size;
3920 
3921 				sz += sizeof (uint64_t);
3922 				ASSERT(svar->dtsv_size == NCPU * sz);
3923 				a += CPU->cpu_id * sz;
3924 
3925 				if (*(uint8_t *)a == UINT8_MAX) {
3926 					/*
3927 					 * If the 0th byte is set to UINT8_MAX
3928 					 * then this is to be treated as a
3929 					 * reference to a NULL variable.
3930 					 */
3931 					regs[rd] = NULL;
3932 				} else {
3933 					regs[rd] = a + sizeof (uint64_t);
3934 				}
3935 
3936 				break;
3937 			}
3938 
3939 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
3940 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
3941 			regs[rd] = tmp[CPU->cpu_id];
3942 			break;
3943 
3944 		case DIF_OP_STLS:
3945 			id = DIF_INSTR_VAR(instr);
3946 
3947 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
3948 			id -= DIF_VAR_OTHER_UBASE;
3949 			ASSERT(id < vstate->dtvs_nlocals);
3950 
3951 			ASSERT(vstate->dtvs_locals != NULL);
3952 			svar = vstate->dtvs_locals[id];
3953 			ASSERT(svar != NULL);
3954 			v = &svar->dtsv_var;
3955 
3956 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
3957 				uintptr_t a = (uintptr_t)svar->dtsv_data;
3958 				size_t sz = v->dtdv_type.dtdt_size;
3959 
3960 				sz += sizeof (uint64_t);
3961 				ASSERT(svar->dtsv_size == NCPU * sz);
3962 				a += CPU->cpu_id * sz;
3963 
3964 				if (regs[rd] == NULL) {
3965 					*(uint8_t *)a = UINT8_MAX;
3966 					break;
3967 				} else {
3968 					*(uint8_t *)a = 0;
3969 					a += sizeof (uint64_t);
3970 				}
3971 
3972 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
3973 				    (void *)a, &v->dtdv_type);
3974 				break;
3975 			}
3976 
3977 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
3978 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
3979 			tmp[CPU->cpu_id] = regs[rd];
3980 			break;
3981 
3982 		case DIF_OP_LDTS: {
3983 			dtrace_dynvar_t *dvar;
3984 			dtrace_key_t *key;
3985 
3986 			id = DIF_INSTR_VAR(instr);
3987 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
3988 			id -= DIF_VAR_OTHER_UBASE;
3989 			v = &vstate->dtvs_tlocals[id];
3990 
3991 			key = &tupregs[DIF_DTR_NREGS];
3992 			key[0].dttk_value = (uint64_t)id;
3993 			key[0].dttk_size = 0;
3994 			DTRACE_TLS_THRKEY(key[1].dttk_value);
3995 			key[1].dttk_size = 0;
3996 
3997 			dvar = dtrace_dynvar(dstate, 2, key,
3998 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC);
3999 
4000 			if (dvar == NULL) {
4001 				regs[rd] = 0;
4002 				break;
4003 			}
4004 
4005 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4006 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4007 			} else {
4008 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4009 			}
4010 
4011 			break;
4012 		}
4013 
4014 		case DIF_OP_STTS: {
4015 			dtrace_dynvar_t *dvar;
4016 			dtrace_key_t *key;
4017 
4018 			id = DIF_INSTR_VAR(instr);
4019 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4020 			id -= DIF_VAR_OTHER_UBASE;
4021 
4022 			key = &tupregs[DIF_DTR_NREGS];
4023 			key[0].dttk_value = (uint64_t)id;
4024 			key[0].dttk_size = 0;
4025 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4026 			key[1].dttk_size = 0;
4027 			v = &vstate->dtvs_tlocals[id];
4028 
4029 			dvar = dtrace_dynvar(dstate, 2, key,
4030 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4031 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4032 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4033 			    DTRACE_DYNVAR_DEALLOC);
4034 
4035 			/*
4036 			 * Given that we're storing to thread-local data,
4037 			 * we need to flush our predicate cache.
4038 			 */
4039 			curthread->t_predcache = NULL;
4040 
4041 			if (dvar == NULL)
4042 				break;
4043 
4044 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4045 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4046 				    dvar->dtdv_data, &v->dtdv_type);
4047 			} else {
4048 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4049 			}
4050 
4051 			break;
4052 		}
4053 
4054 		case DIF_OP_SRA:
4055 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
4056 			break;
4057 
4058 		case DIF_OP_CALL:
4059 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
4060 			    regs, tupregs, ttop, mstate, state);
4061 			break;
4062 
4063 		case DIF_OP_PUSHTR:
4064 			if (ttop == DIF_DTR_NREGS) {
4065 				*flags |= CPU_DTRACE_TUPOFLOW;
4066 				break;
4067 			}
4068 
4069 			if (r1 == DIF_TYPE_STRING) {
4070 				/*
4071 				 * If this is a string type and the size is 0,
4072 				 * we'll use the system-wide default string
4073 				 * size.  Note that we are _not_ looking at
4074 				 * the value of the DTRACEOPT_STRSIZE option;
4075 				 * had this been set, we would expect to have
4076 				 * a non-zero size value in the "pushtr".
4077 				 */
4078 				tupregs[ttop].dttk_size =
4079 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
4080 				    regs[r2] ? regs[r2] :
4081 				    dtrace_strsize_default) + 1;
4082 			} else {
4083 				tupregs[ttop].dttk_size = regs[r2];
4084 			}
4085 
4086 			tupregs[ttop++].dttk_value = regs[rd];
4087 			break;
4088 
4089 		case DIF_OP_PUSHTV:
4090 			if (ttop == DIF_DTR_NREGS) {
4091 				*flags |= CPU_DTRACE_TUPOFLOW;
4092 				break;
4093 			}
4094 
4095 			tupregs[ttop].dttk_value = regs[rd];
4096 			tupregs[ttop++].dttk_size = 0;
4097 			break;
4098 
4099 		case DIF_OP_POPTS:
4100 			if (ttop != 0)
4101 				ttop--;
4102 			break;
4103 
4104 		case DIF_OP_FLUSHTS:
4105 			ttop = 0;
4106 			break;
4107 
4108 		case DIF_OP_LDGAA:
4109 		case DIF_OP_LDTAA: {
4110 			dtrace_dynvar_t *dvar;
4111 			dtrace_key_t *key = tupregs;
4112 			uint_t nkeys = ttop;
4113 
4114 			id = DIF_INSTR_VAR(instr);
4115 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4116 			id -= DIF_VAR_OTHER_UBASE;
4117 
4118 			key[nkeys].dttk_value = (uint64_t)id;
4119 			key[nkeys++].dttk_size = 0;
4120 
4121 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
4122 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4123 				key[nkeys++].dttk_size = 0;
4124 				v = &vstate->dtvs_tlocals[id];
4125 			} else {
4126 				v = &vstate->dtvs_globals[id]->dtsv_var;
4127 			}
4128 
4129 			dvar = dtrace_dynvar(dstate, nkeys, key,
4130 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4131 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4132 			    DTRACE_DYNVAR_NOALLOC);
4133 
4134 			if (dvar == NULL) {
4135 				regs[rd] = 0;
4136 				break;
4137 			}
4138 
4139 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4140 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4141 			} else {
4142 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4143 			}
4144 
4145 			break;
4146 		}
4147 
4148 		case DIF_OP_STGAA:
4149 		case DIF_OP_STTAA: {
4150 			dtrace_dynvar_t *dvar;
4151 			dtrace_key_t *key = tupregs;
4152 			uint_t nkeys = ttop;
4153 
4154 			id = DIF_INSTR_VAR(instr);
4155 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4156 			id -= DIF_VAR_OTHER_UBASE;
4157 
4158 			key[nkeys].dttk_value = (uint64_t)id;
4159 			key[nkeys++].dttk_size = 0;
4160 
4161 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
4162 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4163 				key[nkeys++].dttk_size = 0;
4164 				v = &vstate->dtvs_tlocals[id];
4165 			} else {
4166 				v = &vstate->dtvs_globals[id]->dtsv_var;
4167 			}
4168 
4169 			dvar = dtrace_dynvar(dstate, nkeys, key,
4170 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4171 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4172 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4173 			    DTRACE_DYNVAR_DEALLOC);
4174 
4175 			if (dvar == NULL)
4176 				break;
4177 
4178 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4179 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4180 				    dvar->dtdv_data, &v->dtdv_type);
4181 			} else {
4182 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4183 			}
4184 
4185 			break;
4186 		}
4187 
4188 		case DIF_OP_ALLOCS: {
4189 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4190 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
4191 
4192 			if (mstate->dtms_scratch_ptr + size >
4193 			    mstate->dtms_scratch_base +
4194 			    mstate->dtms_scratch_size) {
4195 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4196 				regs[rd] = NULL;
4197 			} else {
4198 				dtrace_bzero((void *)
4199 				    mstate->dtms_scratch_ptr, size);
4200 				mstate->dtms_scratch_ptr += size;
4201 				regs[rd] = ptr;
4202 			}
4203 			break;
4204 		}
4205 
4206 		case DIF_OP_COPYS:
4207 			if (!dtrace_canstore(regs[rd], regs[r2],
4208 			    mstate, vstate)) {
4209 				*flags |= CPU_DTRACE_BADADDR;
4210 				*illval = regs[rd];
4211 				break;
4212 			}
4213 
4214 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
4215 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
4216 			break;
4217 
4218 		case DIF_OP_STB:
4219 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
4220 				*flags |= CPU_DTRACE_BADADDR;
4221 				*illval = regs[rd];
4222 				break;
4223 			}
4224 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
4225 			break;
4226 
4227 		case DIF_OP_STH:
4228 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
4229 				*flags |= CPU_DTRACE_BADADDR;
4230 				*illval = regs[rd];
4231 				break;
4232 			}
4233 			if (regs[rd] & 1) {
4234 				*flags |= CPU_DTRACE_BADALIGN;
4235 				*illval = regs[rd];
4236 				break;
4237 			}
4238 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
4239 			break;
4240 
4241 		case DIF_OP_STW:
4242 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
4243 				*flags |= CPU_DTRACE_BADADDR;
4244 				*illval = regs[rd];
4245 				break;
4246 			}
4247 			if (regs[rd] & 3) {
4248 				*flags |= CPU_DTRACE_BADALIGN;
4249 				*illval = regs[rd];
4250 				break;
4251 			}
4252 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
4253 			break;
4254 
4255 		case DIF_OP_STX:
4256 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
4257 				*flags |= CPU_DTRACE_BADADDR;
4258 				*illval = regs[rd];
4259 				break;
4260 			}
4261 			if (regs[rd] & 7) {
4262 				*flags |= CPU_DTRACE_BADALIGN;
4263 				*illval = regs[rd];
4264 				break;
4265 			}
4266 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
4267 			break;
4268 		}
4269 	}
4270 
4271 	if (!(*flags & CPU_DTRACE_FAULT))
4272 		return (rval);
4273 
4274 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
4275 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
4276 
4277 	return (0);
4278 }
4279 
4280 static void
4281 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
4282 {
4283 	dtrace_probe_t *probe = ecb->dte_probe;
4284 	dtrace_provider_t *prov = probe->dtpr_provider;
4285 	char c[DTRACE_FULLNAMELEN + 80], *str;
4286 	char *msg = "dtrace: breakpoint action at probe ";
4287 	char *ecbmsg = " (ecb ";
4288 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
4289 	uintptr_t val = (uintptr_t)ecb;
4290 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
4291 
4292 	if (dtrace_destructive_disallow)
4293 		return;
4294 
4295 	/*
4296 	 * It's impossible to be taking action on the NULL probe.
4297 	 */
4298 	ASSERT(probe != NULL);
4299 
4300 	/*
4301 	 * This is a poor man's (destitute man's?) sprintf():  we want to
4302 	 * print the provider name, module name, function name and name of
4303 	 * the probe, along with the hex address of the ECB with the breakpoint
4304 	 * action -- all of which we must place in the character buffer by
4305 	 * hand.
4306 	 */
4307 	while (*msg != '\0')
4308 		c[i++] = *msg++;
4309 
4310 	for (str = prov->dtpv_name; *str != '\0'; str++)
4311 		c[i++] = *str;
4312 	c[i++] = ':';
4313 
4314 	for (str = probe->dtpr_mod; *str != '\0'; str++)
4315 		c[i++] = *str;
4316 	c[i++] = ':';
4317 
4318 	for (str = probe->dtpr_func; *str != '\0'; str++)
4319 		c[i++] = *str;
4320 	c[i++] = ':';
4321 
4322 	for (str = probe->dtpr_name; *str != '\0'; str++)
4323 		c[i++] = *str;
4324 
4325 	while (*ecbmsg != '\0')
4326 		c[i++] = *ecbmsg++;
4327 
4328 	while (shift >= 0) {
4329 		mask = (uintptr_t)0xf << shift;
4330 
4331 		if (val >= ((uintptr_t)1 << shift))
4332 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
4333 		shift -= 4;
4334 	}
4335 
4336 	c[i++] = ')';
4337 	c[i] = '\0';
4338 
4339 	debug_enter(c);
4340 }
4341 
4342 static void
4343 dtrace_action_panic(dtrace_ecb_t *ecb)
4344 {
4345 	dtrace_probe_t *probe = ecb->dte_probe;
4346 
4347 	/*
4348 	 * It's impossible to be taking action on the NULL probe.
4349 	 */
4350 	ASSERT(probe != NULL);
4351 
4352 	if (dtrace_destructive_disallow)
4353 		return;
4354 
4355 	if (dtrace_panicked != NULL)
4356 		return;
4357 
4358 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
4359 		return;
4360 
4361 	/*
4362 	 * We won the right to panic.  (We want to be sure that only one
4363 	 * thread calls panic() from dtrace_probe(), and that panic() is
4364 	 * called exactly once.)
4365 	 */
4366 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
4367 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
4368 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
4369 }
4370 
4371 static void
4372 dtrace_action_raise(uint64_t sig)
4373 {
4374 	if (dtrace_destructive_disallow)
4375 		return;
4376 
4377 	if (sig >= NSIG) {
4378 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4379 		return;
4380 	}
4381 
4382 	/*
4383 	 * raise() has a queue depth of 1 -- we ignore all subsequent
4384 	 * invocations of the raise() action.
4385 	 */
4386 	if (curthread->t_dtrace_sig == 0)
4387 		curthread->t_dtrace_sig = (uint8_t)sig;
4388 
4389 	curthread->t_sig_check = 1;
4390 	aston(curthread);
4391 }
4392 
4393 static void
4394 dtrace_action_stop(void)
4395 {
4396 	if (dtrace_destructive_disallow)
4397 		return;
4398 
4399 	if (!curthread->t_dtrace_stop) {
4400 		curthread->t_dtrace_stop = 1;
4401 		curthread->t_sig_check = 1;
4402 		aston(curthread);
4403 	}
4404 }
4405 
4406 static void
4407 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
4408 {
4409 	hrtime_t now;
4410 	volatile uint16_t *flags;
4411 	cpu_t *cpu = CPU;
4412 
4413 	if (dtrace_destructive_disallow)
4414 		return;
4415 
4416 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
4417 
4418 	now = dtrace_gethrtime();
4419 
4420 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
4421 		/*
4422 		 * We need to advance the mark to the current time.
4423 		 */
4424 		cpu->cpu_dtrace_chillmark = now;
4425 		cpu->cpu_dtrace_chilled = 0;
4426 	}
4427 
4428 	/*
4429 	 * Now check to see if the requested chill time would take us over
4430 	 * the maximum amount of time allowed in the chill interval.  (Or
4431 	 * worse, if the calculation itself induces overflow.)
4432 	 */
4433 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
4434 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
4435 		*flags |= CPU_DTRACE_ILLOP;
4436 		return;
4437 	}
4438 
4439 	while (dtrace_gethrtime() - now < val)
4440 		continue;
4441 
4442 	/*
4443 	 * Normally, we assure that the value of the variable "timestamp" does
4444 	 * not change within an ECB.  The presence of chill() represents an
4445 	 * exception to this rule, however.
4446 	 */
4447 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
4448 	cpu->cpu_dtrace_chilled += val;
4449 }
4450 
4451 static void
4452 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
4453     uint64_t *buf, uint64_t arg)
4454 {
4455 	int nframes = DTRACE_USTACK_NFRAMES(arg);
4456 	int strsize = DTRACE_USTACK_STRSIZE(arg);
4457 	uint64_t *pcs = &buf[1], *fps;
4458 	char *str = (char *)&pcs[nframes];
4459 	int size, offs = 0, i, j;
4460 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
4461 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4462 	char *sym;
4463 
4464 	/*
4465 	 * Should be taking a faster path if string space has not been
4466 	 * allocated.
4467 	 */
4468 	ASSERT(strsize != 0);
4469 
4470 	/*
4471 	 * We will first allocate some temporary space for the frame pointers.
4472 	 */
4473 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4474 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
4475 	    (nframes * sizeof (uint64_t));
4476 
4477 	if (mstate->dtms_scratch_ptr + size >
4478 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
4479 		/*
4480 		 * Not enough room for our frame pointers -- need to indicate
4481 		 * that we ran out of scratch space.
4482 		 */
4483 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4484 		return;
4485 	}
4486 
4487 	mstate->dtms_scratch_ptr += size;
4488 	saved = mstate->dtms_scratch_ptr;
4489 
4490 	/*
4491 	 * Now get a stack with both program counters and frame pointers.
4492 	 */
4493 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4494 	dtrace_getufpstack(buf, fps, nframes + 1);
4495 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4496 
4497 	/*
4498 	 * If that faulted, we're cooked.
4499 	 */
4500 	if (*flags & CPU_DTRACE_FAULT)
4501 		goto out;
4502 
4503 	/*
4504 	 * Now we want to walk up the stack, calling the USTACK helper.  For
4505 	 * each iteration, we restore the scratch pointer.
4506 	 */
4507 	for (i = 0; i < nframes; i++) {
4508 		mstate->dtms_scratch_ptr = saved;
4509 
4510 		if (offs >= strsize)
4511 			break;
4512 
4513 		sym = (char *)(uintptr_t)dtrace_helper(
4514 		    DTRACE_HELPER_ACTION_USTACK,
4515 		    mstate, state, pcs[i], fps[i]);
4516 
4517 		/*
4518 		 * If we faulted while running the helper, we're going to
4519 		 * clear the fault and null out the corresponding string.
4520 		 */
4521 		if (*flags & CPU_DTRACE_FAULT) {
4522 			*flags &= ~CPU_DTRACE_FAULT;
4523 			str[offs++] = '\0';
4524 			continue;
4525 		}
4526 
4527 		if (sym == NULL) {
4528 			str[offs++] = '\0';
4529 			continue;
4530 		}
4531 
4532 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4533 
4534 		/*
4535 		 * Now copy in the string that the helper returned to us.
4536 		 */
4537 		for (j = 0; offs + j < strsize; j++) {
4538 			if ((str[offs + j] = sym[j]) == '\0')
4539 				break;
4540 		}
4541 
4542 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4543 
4544 		offs += j + 1;
4545 	}
4546 
4547 	if (offs >= strsize) {
4548 		/*
4549 		 * If we didn't have room for all of the strings, we don't
4550 		 * abort processing -- this needn't be a fatal error -- but we
4551 		 * still want to increment a counter (dts_stkstroverflows) to
4552 		 * allow this condition to be warned about.  (If this is from
4553 		 * a jstack() action, it is easily tuned via jstackstrsize.)
4554 		 */
4555 		dtrace_error(&state->dts_stkstroverflows);
4556 	}
4557 
4558 	while (offs < strsize)
4559 		str[offs++] = '\0';
4560 
4561 out:
4562 	mstate->dtms_scratch_ptr = old;
4563 }
4564 
4565 /*
4566  * If you're looking for the epicenter of DTrace, you just found it.  This
4567  * is the function called by the provider to fire a probe -- from which all
4568  * subsequent probe-context DTrace activity emanates.
4569  */
4570 void
4571 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
4572     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
4573 {
4574 	processorid_t cpuid;
4575 	dtrace_icookie_t cookie;
4576 	dtrace_probe_t *probe;
4577 	dtrace_mstate_t mstate;
4578 	dtrace_ecb_t *ecb;
4579 	dtrace_action_t *act;
4580 	intptr_t offs;
4581 	size_t size;
4582 	int vtime, onintr;
4583 	volatile uint16_t *flags;
4584 	hrtime_t now;
4585 
4586 	/*
4587 	 * Kick out immediately if this CPU is still being born (in which case
4588 	 * curthread will be set to -1)
4589 	 */
4590 	if ((uintptr_t)curthread & 1)
4591 		return;
4592 
4593 	cookie = dtrace_interrupt_disable();
4594 	probe = dtrace_probes[id - 1];
4595 	cpuid = CPU->cpu_id;
4596 	onintr = CPU_ON_INTR(CPU);
4597 
4598 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
4599 	    probe->dtpr_predcache == curthread->t_predcache) {
4600 		/*
4601 		 * We have hit in the predicate cache; we know that
4602 		 * this predicate would evaluate to be false.
4603 		 */
4604 		dtrace_interrupt_enable(cookie);
4605 		return;
4606 	}
4607 
4608 	if (panic_quiesce) {
4609 		/*
4610 		 * We don't trace anything if we're panicking.
4611 		 */
4612 		dtrace_interrupt_enable(cookie);
4613 		return;
4614 	}
4615 
4616 	now = dtrace_gethrtime();
4617 	vtime = dtrace_vtime_references != 0;
4618 
4619 	if (vtime && curthread->t_dtrace_start)
4620 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
4621 
4622 	mstate.dtms_probe = probe;
4623 	mstate.dtms_arg[0] = arg0;
4624 	mstate.dtms_arg[1] = arg1;
4625 	mstate.dtms_arg[2] = arg2;
4626 	mstate.dtms_arg[3] = arg3;
4627 	mstate.dtms_arg[4] = arg4;
4628 
4629 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
4630 
4631 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
4632 		dtrace_predicate_t *pred = ecb->dte_predicate;
4633 		dtrace_state_t *state = ecb->dte_state;
4634 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
4635 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
4636 		dtrace_vstate_t *vstate = &state->dts_vstate;
4637 		dtrace_provider_t *prov = probe->dtpr_provider;
4638 		int committed = 0;
4639 		caddr_t tomax;
4640 
4641 		/*
4642 		 * A little subtlety with the following (seemingly innocuous)
4643 		 * declaration of the automatic 'val':  by looking at the
4644 		 * code, you might think that it could be declared in the
4645 		 * action processing loop, below.  (That is, it's only used in
4646 		 * the action processing loop.)  However, it must be declared
4647 		 * out of that scope because in the case of DIF expression
4648 		 * arguments to aggregating actions, one iteration of the
4649 		 * action loop will use the last iteration's value.
4650 		 */
4651 #ifdef lint
4652 		uint64_t val = 0;
4653 #else
4654 		uint64_t val;
4655 #endif
4656 
4657 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
4658 		*flags &= ~CPU_DTRACE_ERROR;
4659 
4660 		if (prov == dtrace_provider) {
4661 			/*
4662 			 * If dtrace itself is the provider of this probe,
4663 			 * we're only going to continue processing the ECB if
4664 			 * arg0 (the dtrace_state_t) is equal to the ECB's
4665 			 * creating state.  (This prevents disjoint consumers
4666 			 * from seeing one another's metaprobes.)
4667 			 */
4668 			if (arg0 != (uint64_t)(uintptr_t)state)
4669 				continue;
4670 		}
4671 
4672 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
4673 			/*
4674 			 * We're not currently active.  If our provider isn't
4675 			 * the dtrace pseudo provider, we're not interested.
4676 			 */
4677 			if (prov != dtrace_provider)
4678 				continue;
4679 
4680 			/*
4681 			 * Now we must further check if we are in the BEGIN
4682 			 * probe.  If we are, we will only continue processing
4683 			 * if we're still in WARMUP -- if one BEGIN enabling
4684 			 * has invoked the exit() action, we don't want to
4685 			 * evaluate subsequent BEGIN enablings.
4686 			 */
4687 			if (probe->dtpr_id == dtrace_probeid_begin &&
4688 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
4689 				ASSERT(state->dts_activity ==
4690 				    DTRACE_ACTIVITY_DRAINING);
4691 				continue;
4692 			}
4693 		}
4694 
4695 		if (ecb->dte_cond) {
4696 			/*
4697 			 * If the dte_cond bits indicate that this
4698 			 * consumer is only allowed to see user-mode firings
4699 			 * of this probe, call the provider's dtps_usermode()
4700 			 * entry point to check that the probe was fired
4701 			 * while in a user context. Skip this ECB if that's
4702 			 * not the case.
4703 			 */
4704 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
4705 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
4706 			    probe->dtpr_id, probe->dtpr_arg) == 0)
4707 				continue;
4708 
4709 			/*
4710 			 * This is more subtle than it looks. We have to be
4711 			 * absolutely certain that CRED() isn't going to
4712 			 * change out from under us so it's only legit to
4713 			 * examine that structure if we're in constrained
4714 			 * situations. Currently, the only times we'll this
4715 			 * check is if a non-super-user has enabled the
4716 			 * profile or syscall providers -- providers that
4717 			 * allow visibility of all processes. For the
4718 			 * profile case, the check above will ensure that
4719 			 * we're examining a user context.
4720 			 */
4721 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
4722 				uid_t uid = ecb->dte_state->dts_cred.dcr_uid;
4723 				gid_t gid = ecb->dte_state->dts_cred.dcr_gid;
4724 				cred_t *cr;
4725 				proc_t *proc;
4726 
4727 				if ((cr = CRED()) == NULL ||
4728 				    uid != cr->cr_uid ||
4729 				    uid != cr->cr_ruid ||
4730 				    uid != cr->cr_suid ||
4731 				    gid != cr->cr_gid ||
4732 				    gid != cr->cr_rgid ||
4733 				    gid != cr->cr_sgid ||
4734 				    (proc = ttoproc(curthread)) == NULL ||
4735 				    (proc->p_flag & SNOCD))
4736 					continue;
4737 
4738 			}
4739 		}
4740 
4741 		if (now - state->dts_alive > dtrace_deadman_timeout) {
4742 			/*
4743 			 * We seem to be dead.  Unless we (a) have kernel
4744 			 * destructive permissions (b) have expicitly enabled
4745 			 * destructive actions and (c) destructive actions have
4746 			 * not been disabled, we're going to transition into
4747 			 * the KILLED state, from which no further processing
4748 			 * on this state will be performed.
4749 			 */
4750 			if (!dtrace_priv_kernel_destructive(state) ||
4751 			    !state->dts_cred.dcr_destructive ||
4752 			    dtrace_destructive_disallow) {
4753 				void *activity = &state->dts_activity;
4754 				dtrace_activity_t current;
4755 
4756 				do {
4757 					current = state->dts_activity;
4758 				} while (dtrace_cas32(activity, current,
4759 				    DTRACE_ACTIVITY_KILLED) != current);
4760 
4761 				continue;
4762 			}
4763 		}
4764 
4765 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
4766 		    ecb->dte_alignment, state, &mstate)) < 0)
4767 			continue;
4768 
4769 		tomax = buf->dtb_tomax;
4770 		ASSERT(tomax != NULL);
4771 
4772 		if (ecb->dte_size != 0)
4773 			DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
4774 
4775 		mstate.dtms_epid = ecb->dte_epid;
4776 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
4777 
4778 		if (pred != NULL) {
4779 			dtrace_difo_t *dp = pred->dtp_difo;
4780 			int rval;
4781 
4782 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
4783 
4784 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
4785 				dtrace_cacheid_t cid = probe->dtpr_predcache;
4786 
4787 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
4788 					/*
4789 					 * Update the predicate cache...
4790 					 */
4791 					ASSERT(cid == pred->dtp_cacheid);
4792 					curthread->t_predcache = cid;
4793 				}
4794 
4795 				continue;
4796 			}
4797 		}
4798 
4799 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
4800 		    act != NULL; act = act->dta_next) {
4801 			size_t valoffs;
4802 			dtrace_difo_t *dp;
4803 			dtrace_recdesc_t *rec = &act->dta_rec;
4804 
4805 			size = rec->dtrd_size;
4806 			valoffs = offs + rec->dtrd_offset;
4807 
4808 			if (DTRACEACT_ISAGG(act->dta_kind)) {
4809 				uint64_t v = 0xbad;
4810 				dtrace_aggregation_t *agg;
4811 
4812 				agg = (dtrace_aggregation_t *)act;
4813 
4814 				if ((dp = act->dta_difo) != NULL)
4815 					v = dtrace_dif_emulate(dp,
4816 					    &mstate, vstate, state);
4817 
4818 				if (*flags & CPU_DTRACE_ERROR)
4819 					continue;
4820 
4821 				/*
4822 				 * Note that we always pass the expression
4823 				 * value from the previous iteration of the
4824 				 * action loop.  This value will only be used
4825 				 * if there is an expression argument to the
4826 				 * aggregating action, denoted by the
4827 				 * dtag_hasarg field.
4828 				 */
4829 				dtrace_aggregate(agg, buf,
4830 				    offs, aggbuf, v, val);
4831 				continue;
4832 			}
4833 
4834 			switch (act->dta_kind) {
4835 			case DTRACEACT_STOP:
4836 				if (dtrace_priv_proc_destructive(state))
4837 					dtrace_action_stop();
4838 				continue;
4839 
4840 			case DTRACEACT_BREAKPOINT:
4841 				if (dtrace_priv_kernel_destructive(state))
4842 					dtrace_action_breakpoint(ecb);
4843 				continue;
4844 
4845 			case DTRACEACT_PANIC:
4846 				if (dtrace_priv_kernel_destructive(state))
4847 					dtrace_action_panic(ecb);
4848 				continue;
4849 
4850 			case DTRACEACT_STACK:
4851 				if (!dtrace_priv_kernel(state))
4852 					continue;
4853 
4854 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
4855 				    size / sizeof (pc_t), probe->dtpr_aframes,
4856 				    DTRACE_ANCHORED(probe) ? NULL :
4857 				    (uint32_t *)arg0);
4858 
4859 				continue;
4860 
4861 			case DTRACEACT_JSTACK:
4862 			case DTRACEACT_USTACK:
4863 				if (!dtrace_priv_proc(state))
4864 					continue;
4865 
4866 				/*
4867 				 * See comment in DIF_VAR_PID.
4868 				 */
4869 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
4870 				    CPU_ON_INTR(CPU)) {
4871 					int depth = DTRACE_USTACK_NFRAMES(
4872 					    rec->dtrd_arg) + 1;
4873 
4874 					dtrace_bzero((void *)(tomax + valoffs),
4875 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
4876 					    + depth * sizeof (uint64_t));
4877 
4878 					continue;
4879 				}
4880 
4881 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
4882 				    curproc->p_dtrace_helpers != NULL) {
4883 					/*
4884 					 * This is the slow path -- we have
4885 					 * allocated string space, and we're
4886 					 * getting the stack of a process that
4887 					 * has helpers.  Call into a separate
4888 					 * routine to perform this processing.
4889 					 */
4890 					dtrace_action_ustack(&mstate, state,
4891 					    (uint64_t *)(tomax + valoffs),
4892 					    rec->dtrd_arg);
4893 					continue;
4894 				}
4895 
4896 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4897 				dtrace_getupcstack((uint64_t *)
4898 				    (tomax + valoffs),
4899 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
4900 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4901 				continue;
4902 
4903 			default:
4904 				break;
4905 			}
4906 
4907 			dp = act->dta_difo;
4908 			ASSERT(dp != NULL);
4909 
4910 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
4911 
4912 			if (*flags & CPU_DTRACE_ERROR)
4913 				continue;
4914 
4915 			switch (act->dta_kind) {
4916 			case DTRACEACT_SPECULATE:
4917 				ASSERT(buf == &state->dts_buffer[cpuid]);
4918 				buf = dtrace_speculation_buffer(state,
4919 				    cpuid, val);
4920 
4921 				if (buf == NULL) {
4922 					*flags |= CPU_DTRACE_DROP;
4923 					continue;
4924 				}
4925 
4926 				offs = dtrace_buffer_reserve(buf,
4927 				    ecb->dte_needed, ecb->dte_alignment,
4928 				    state, NULL);
4929 
4930 				if (offs < 0) {
4931 					*flags |= CPU_DTRACE_DROP;
4932 					continue;
4933 				}
4934 
4935 				tomax = buf->dtb_tomax;
4936 				ASSERT(tomax != NULL);
4937 
4938 				if (ecb->dte_size != 0)
4939 					DTRACE_STORE(uint32_t, tomax, offs,
4940 					    ecb->dte_epid);
4941 				continue;
4942 
4943 			case DTRACEACT_CHILL:
4944 				if (dtrace_priv_kernel_destructive(state))
4945 					dtrace_action_chill(&mstate, val);
4946 				continue;
4947 
4948 			case DTRACEACT_RAISE:
4949 				if (dtrace_priv_proc_destructive(state))
4950 					dtrace_action_raise(val);
4951 				continue;
4952 
4953 			case DTRACEACT_COMMIT:
4954 				ASSERT(!committed);
4955 
4956 				/*
4957 				 * We need to commit our buffer state.
4958 				 */
4959 				if (ecb->dte_size)
4960 					buf->dtb_offset = offs + ecb->dte_size;
4961 				buf = &state->dts_buffer[cpuid];
4962 				dtrace_speculation_commit(state, cpuid, val);
4963 				committed = 1;
4964 				continue;
4965 
4966 			case DTRACEACT_DISCARD:
4967 				dtrace_speculation_discard(state, cpuid, val);
4968 				continue;
4969 
4970 			case DTRACEACT_DIFEXPR:
4971 			case DTRACEACT_LIBACT:
4972 			case DTRACEACT_PRINTF:
4973 			case DTRACEACT_PRINTA:
4974 			case DTRACEACT_SYSTEM:
4975 			case DTRACEACT_FREOPEN:
4976 				break;
4977 
4978 			case DTRACEACT_SYM:
4979 			case DTRACEACT_MOD:
4980 				if (!dtrace_priv_kernel(state))
4981 					continue;
4982 				break;
4983 
4984 			case DTRACEACT_USYM:
4985 			case DTRACEACT_UMOD:
4986 			case DTRACEACT_UADDR: {
4987 				struct pid *pid = curthread->t_procp->p_pidp;
4988 
4989 				if (!dtrace_priv_proc(state))
4990 					continue;
4991 
4992 				DTRACE_STORE(uint64_t, tomax,
4993 				    valoffs, (uint64_t)pid->pid_id);
4994 				DTRACE_STORE(uint64_t, tomax,
4995 				    valoffs + sizeof (uint64_t), val);
4996 
4997 				continue;
4998 			}
4999 
5000 			case DTRACEACT_EXIT: {
5001 				/*
5002 				 * For the exit action, we are going to attempt
5003 				 * to atomically set our activity to be
5004 				 * draining.  If this fails (either because
5005 				 * another CPU has beat us to the exit action,
5006 				 * or because our current activity is something
5007 				 * other than ACTIVE or WARMUP), we will
5008 				 * continue.  This assures that the exit action
5009 				 * can be successfully recorded at most once
5010 				 * when we're in the ACTIVE state.  If we're
5011 				 * encountering the exit() action while in
5012 				 * COOLDOWN, however, we want to honor the new
5013 				 * status code.  (We know that we're the only
5014 				 * thread in COOLDOWN, so there is no race.)
5015 				 */
5016 				void *activity = &state->dts_activity;
5017 				dtrace_activity_t current = state->dts_activity;
5018 
5019 				if (current == DTRACE_ACTIVITY_COOLDOWN)
5020 					break;
5021 
5022 				if (current != DTRACE_ACTIVITY_WARMUP)
5023 					current = DTRACE_ACTIVITY_ACTIVE;
5024 
5025 				if (dtrace_cas32(activity, current,
5026 				    DTRACE_ACTIVITY_DRAINING) != current) {
5027 					*flags |= CPU_DTRACE_DROP;
5028 					continue;
5029 				}
5030 
5031 				break;
5032 			}
5033 
5034 			default:
5035 				ASSERT(0);
5036 			}
5037 
5038 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
5039 				uintptr_t end = valoffs + size;
5040 
5041 				/*
5042 				 * If this is a string, we're going to only
5043 				 * load until we find the zero byte -- after
5044 				 * which we'll store zero bytes.
5045 				 */
5046 				if (dp->dtdo_rtype.dtdt_kind ==
5047 				    DIF_TYPE_STRING) {
5048 					char c = '\0' + 1;
5049 					int intuple = act->dta_intuple;
5050 					size_t s;
5051 
5052 					for (s = 0; s < size; s++) {
5053 						if (c != '\0')
5054 							c = dtrace_load8(val++);
5055 
5056 						DTRACE_STORE(uint8_t, tomax,
5057 						    valoffs++, c);
5058 
5059 						if (c == '\0' && intuple)
5060 							break;
5061 					}
5062 
5063 					continue;
5064 				}
5065 
5066 				while (valoffs < end) {
5067 					DTRACE_STORE(uint8_t, tomax, valoffs++,
5068 					    dtrace_load8(val++));
5069 				}
5070 
5071 				continue;
5072 			}
5073 
5074 			switch (size) {
5075 			case 0:
5076 				break;
5077 
5078 			case sizeof (uint8_t):
5079 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
5080 				break;
5081 			case sizeof (uint16_t):
5082 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
5083 				break;
5084 			case sizeof (uint32_t):
5085 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
5086 				break;
5087 			case sizeof (uint64_t):
5088 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
5089 				break;
5090 			default:
5091 				/*
5092 				 * Any other size should have been returned by
5093 				 * reference, not by value.
5094 				 */
5095 				ASSERT(0);
5096 				break;
5097 			}
5098 		}
5099 
5100 		if (*flags & CPU_DTRACE_DROP)
5101 			continue;
5102 
5103 		if (*flags & CPU_DTRACE_FAULT) {
5104 			int ndx;
5105 			dtrace_action_t *err;
5106 
5107 			buf->dtb_errors++;
5108 
5109 			if (probe->dtpr_id == dtrace_probeid_error) {
5110 				/*
5111 				 * There's nothing we can do -- we had an
5112 				 * error on the error probe.  We bump an
5113 				 * error counter to at least indicate that
5114 				 * this condition happened.
5115 				 */
5116 				dtrace_error(&state->dts_dblerrors);
5117 				continue;
5118 			}
5119 
5120 			if (vtime) {
5121 				/*
5122 				 * Before recursing on dtrace_probe(), we
5123 				 * need to explicitly clear out our start
5124 				 * time to prevent it from being accumulated
5125 				 * into t_dtrace_vtime.
5126 				 */
5127 				curthread->t_dtrace_start = 0;
5128 			}
5129 
5130 			/*
5131 			 * Iterate over the actions to figure out which action
5132 			 * we were processing when we experienced the error.
5133 			 * Note that act points _past_ the faulting action; if
5134 			 * act is ecb->dte_action, the fault was in the
5135 			 * predicate, if it's ecb->dte_action->dta_next it's
5136 			 * in action #1, and so on.
5137 			 */
5138 			for (err = ecb->dte_action, ndx = 0;
5139 			    err != act; err = err->dta_next, ndx++)
5140 				continue;
5141 
5142 			dtrace_probe_error(state, ecb->dte_epid, ndx,
5143 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
5144 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
5145 			    cpu_core[cpuid].cpuc_dtrace_illval);
5146 
5147 			continue;
5148 		}
5149 
5150 		if (!committed)
5151 			buf->dtb_offset = offs + ecb->dte_size;
5152 	}
5153 
5154 	if (vtime)
5155 		curthread->t_dtrace_start = dtrace_gethrtime();
5156 
5157 	dtrace_interrupt_enable(cookie);
5158 }
5159 
5160 /*
5161  * DTrace Probe Hashing Functions
5162  *
5163  * The functions in this section (and indeed, the functions in remaining
5164  * sections) are not _called_ from probe context.  (Any exceptions to this are
5165  * marked with a "Note:".)  Rather, they are called from elsewhere in the
5166  * DTrace framework to look-up probes in, add probes to and remove probes from
5167  * the DTrace probe hashes.  (Each probe is hashed by each element of the
5168  * probe tuple -- allowing for fast lookups, regardless of what was
5169  * specified.)
5170  */
5171 static uint_t
5172 dtrace_hash_str(char *p)
5173 {
5174 	unsigned int g;
5175 	uint_t hval = 0;
5176 
5177 	while (*p) {
5178 		hval = (hval << 4) + *p++;
5179 		if ((g = (hval & 0xf0000000)) != 0)
5180 			hval ^= g >> 24;
5181 		hval &= ~g;
5182 	}
5183 	return (hval);
5184 }
5185 
5186 static dtrace_hash_t *
5187 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
5188 {
5189 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
5190 
5191 	hash->dth_stroffs = stroffs;
5192 	hash->dth_nextoffs = nextoffs;
5193 	hash->dth_prevoffs = prevoffs;
5194 
5195 	hash->dth_size = 1;
5196 	hash->dth_mask = hash->dth_size - 1;
5197 
5198 	hash->dth_tab = kmem_zalloc(hash->dth_size *
5199 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
5200 
5201 	return (hash);
5202 }
5203 
5204 static void
5205 dtrace_hash_destroy(dtrace_hash_t *hash)
5206 {
5207 #ifdef DEBUG
5208 	int i;
5209 
5210 	for (i = 0; i < hash->dth_size; i++)
5211 		ASSERT(hash->dth_tab[i] == NULL);
5212 #endif
5213 
5214 	kmem_free(hash->dth_tab,
5215 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
5216 	kmem_free(hash, sizeof (dtrace_hash_t));
5217 }
5218 
5219 static void
5220 dtrace_hash_resize(dtrace_hash_t *hash)
5221 {
5222 	int size = hash->dth_size, i, ndx;
5223 	int new_size = hash->dth_size << 1;
5224 	int new_mask = new_size - 1;
5225 	dtrace_hashbucket_t **new_tab, *bucket, *next;
5226 
5227 	ASSERT((new_size & new_mask) == 0);
5228 
5229 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
5230 
5231 	for (i = 0; i < size; i++) {
5232 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
5233 			dtrace_probe_t *probe = bucket->dthb_chain;
5234 
5235 			ASSERT(probe != NULL);
5236 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
5237 
5238 			next = bucket->dthb_next;
5239 			bucket->dthb_next = new_tab[ndx];
5240 			new_tab[ndx] = bucket;
5241 		}
5242 	}
5243 
5244 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
5245 	hash->dth_tab = new_tab;
5246 	hash->dth_size = new_size;
5247 	hash->dth_mask = new_mask;
5248 }
5249 
5250 static void
5251 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
5252 {
5253 	int hashval = DTRACE_HASHSTR(hash, new);
5254 	int ndx = hashval & hash->dth_mask;
5255 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5256 	dtrace_probe_t **nextp, **prevp;
5257 
5258 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5259 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
5260 			goto add;
5261 	}
5262 
5263 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
5264 		dtrace_hash_resize(hash);
5265 		dtrace_hash_add(hash, new);
5266 		return;
5267 	}
5268 
5269 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
5270 	bucket->dthb_next = hash->dth_tab[ndx];
5271 	hash->dth_tab[ndx] = bucket;
5272 	hash->dth_nbuckets++;
5273 
5274 add:
5275 	nextp = DTRACE_HASHNEXT(hash, new);
5276 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
5277 	*nextp = bucket->dthb_chain;
5278 
5279 	if (bucket->dthb_chain != NULL) {
5280 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
5281 		ASSERT(*prevp == NULL);
5282 		*prevp = new;
5283 	}
5284 
5285 	bucket->dthb_chain = new;
5286 	bucket->dthb_len++;
5287 }
5288 
5289 static dtrace_probe_t *
5290 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
5291 {
5292 	int hashval = DTRACE_HASHSTR(hash, template);
5293 	int ndx = hashval & hash->dth_mask;
5294 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5295 
5296 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5297 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
5298 			return (bucket->dthb_chain);
5299 	}
5300 
5301 	return (NULL);
5302 }
5303 
5304 static int
5305 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
5306 {
5307 	int hashval = DTRACE_HASHSTR(hash, template);
5308 	int ndx = hashval & hash->dth_mask;
5309 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5310 
5311 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5312 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
5313 			return (bucket->dthb_len);
5314 	}
5315 
5316 	return (NULL);
5317 }
5318 
5319 static void
5320 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
5321 {
5322 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
5323 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5324 
5325 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
5326 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
5327 
5328 	/*
5329 	 * Find the bucket that we're removing this probe from.
5330 	 */
5331 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5332 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
5333 			break;
5334 	}
5335 
5336 	ASSERT(bucket != NULL);
5337 
5338 	if (*prevp == NULL) {
5339 		if (*nextp == NULL) {
5340 			/*
5341 			 * The removed probe was the only probe on this
5342 			 * bucket; we need to remove the bucket.
5343 			 */
5344 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
5345 
5346 			ASSERT(bucket->dthb_chain == probe);
5347 			ASSERT(b != NULL);
5348 
5349 			if (b == bucket) {
5350 				hash->dth_tab[ndx] = bucket->dthb_next;
5351 			} else {
5352 				while (b->dthb_next != bucket)
5353 					b = b->dthb_next;
5354 				b->dthb_next = bucket->dthb_next;
5355 			}
5356 
5357 			ASSERT(hash->dth_nbuckets > 0);
5358 			hash->dth_nbuckets--;
5359 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
5360 			return;
5361 		}
5362 
5363 		bucket->dthb_chain = *nextp;
5364 	} else {
5365 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
5366 	}
5367 
5368 	if (*nextp != NULL)
5369 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
5370 }
5371 
5372 /*
5373  * DTrace Utility Functions
5374  *
5375  * These are random utility functions that are _not_ called from probe context.
5376  */
5377 static int
5378 dtrace_badattr(const dtrace_attribute_t *a)
5379 {
5380 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
5381 	    a->dtat_data > DTRACE_STABILITY_MAX ||
5382 	    a->dtat_class > DTRACE_CLASS_MAX);
5383 }
5384 
5385 /*
5386  * Return a duplicate copy of a string.  If the specified string is NULL,
5387  * this function returns a zero-length string.
5388  */
5389 static char *
5390 dtrace_strdup(const char *str)
5391 {
5392 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
5393 
5394 	if (str != NULL)
5395 		(void) strcpy(new, str);
5396 
5397 	return (new);
5398 }
5399 
5400 #define	DTRACE_ISALPHA(c)	\
5401 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
5402 
5403 static int
5404 dtrace_badname(const char *s)
5405 {
5406 	char c;
5407 
5408 	if (s == NULL || (c = *s++) == '\0')
5409 		return (0);
5410 
5411 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
5412 		return (1);
5413 
5414 	while ((c = *s++) != '\0') {
5415 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
5416 		    c != '-' && c != '_' && c != '.' && c != '`')
5417 			return (1);
5418 	}
5419 
5420 	return (0);
5421 }
5422 
5423 static void
5424 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp)
5425 {
5426 	uint32_t priv;
5427 
5428 	*uidp = crgetuid(cr);
5429 	if (PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
5430 		priv = DTRACE_PRIV_ALL;
5431 	} else {
5432 		priv = 0;
5433 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
5434 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
5435 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
5436 			priv |= DTRACE_PRIV_USER;
5437 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
5438 			priv |= DTRACE_PRIV_PROC;
5439 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
5440 			priv |= DTRACE_PRIV_OWNER;
5441 	}
5442 
5443 	*privp = priv;
5444 }
5445 
5446 #ifdef DTRACE_ERRDEBUG
5447 static void
5448 dtrace_errdebug(const char *str)
5449 {
5450 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
5451 	int occupied = 0;
5452 
5453 	mutex_enter(&dtrace_errlock);
5454 	dtrace_errlast = str;
5455 	dtrace_errthread = curthread;
5456 
5457 	while (occupied++ < DTRACE_ERRHASHSZ) {
5458 		if (dtrace_errhash[hval].dter_msg == str) {
5459 			dtrace_errhash[hval].dter_count++;
5460 			goto out;
5461 		}
5462 
5463 		if (dtrace_errhash[hval].dter_msg != NULL) {
5464 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
5465 			continue;
5466 		}
5467 
5468 		dtrace_errhash[hval].dter_msg = str;
5469 		dtrace_errhash[hval].dter_count = 1;
5470 		goto out;
5471 	}
5472 
5473 	panic("dtrace: undersized error hash");
5474 out:
5475 	mutex_exit(&dtrace_errlock);
5476 }
5477 #endif
5478 
5479 /*
5480  * DTrace Matching Functions
5481  *
5482  * These functions are used to match groups of probes, given some elements of
5483  * a probe tuple, or some globbed expressions for elements of a probe tuple.
5484  */
5485 static int
5486 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid)
5487 {
5488 	if (priv != DTRACE_PRIV_ALL) {
5489 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
5490 		uint32_t match = priv & ppriv;
5491 
5492 		/*
5493 		 * No PRIV_DTRACE_* privileges...
5494 		 */
5495 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
5496 		    DTRACE_PRIV_KERNEL)) == 0)
5497 			return (0);
5498 
5499 		/*
5500 		 * No matching bits, but there were bits to match...
5501 		 */
5502 		if (match == 0 && ppriv != 0)
5503 			return (0);
5504 
5505 		/*
5506 		 * Need to have permissions to the process, but don't...
5507 		 */
5508 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
5509 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid)
5510 			return (0);
5511 	}
5512 
5513 	return (1);
5514 }
5515 
5516 /*
5517  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
5518  * consists of input pattern strings and an ops-vector to evaluate them.
5519  * This function returns >0 for match, 0 for no match, and <0 for error.
5520  */
5521 static int
5522 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
5523     uint32_t priv, uid_t uid)
5524 {
5525 	dtrace_provider_t *pvp = prp->dtpr_provider;
5526 	int rv;
5527 
5528 	if (pvp->dtpv_defunct)
5529 		return (0);
5530 
5531 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
5532 		return (rv);
5533 
5534 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
5535 		return (rv);
5536 
5537 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
5538 		return (rv);
5539 
5540 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
5541 		return (rv);
5542 
5543 	if (dtrace_match_priv(prp, priv, uid) == 0)
5544 		return (0);
5545 
5546 	return (rv);
5547 }
5548 
5549 /*
5550  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
5551  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
5552  * libc's version, the kernel version only applies to 8-bit ASCII strings.
5553  * In addition, all of the recursion cases except for '*' matching have been
5554  * unwound.  For '*', we still implement recursive evaluation, but a depth
5555  * counter is maintained and matching is aborted if we recurse too deep.
5556  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
5557  */
5558 static int
5559 dtrace_match_glob(const char *s, const char *p, int depth)
5560 {
5561 	const char *olds;
5562 	char s1, c;
5563 	int gs;
5564 
5565 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
5566 		return (-1);
5567 
5568 	if (s == NULL)
5569 		s = ""; /* treat NULL as empty string */
5570 
5571 top:
5572 	olds = s;
5573 	s1 = *s++;
5574 
5575 	if (p == NULL)
5576 		return (0);
5577 
5578 	if ((c = *p++) == '\0')
5579 		return (s1 == '\0');
5580 
5581 	switch (c) {
5582 	case '[': {
5583 		int ok = 0, notflag = 0;
5584 		char lc = '\0';
5585 
5586 		if (s1 == '\0')
5587 			return (0);
5588 
5589 		if (*p == '!') {
5590 			notflag = 1;
5591 			p++;
5592 		}
5593 
5594 		if ((c = *p++) == '\0')
5595 			return (0);
5596 
5597 		do {
5598 			if (c == '-' && lc != '\0' && *p != ']') {
5599 				if ((c = *p++) == '\0')
5600 					return (0);
5601 				if (c == '\\' && (c = *p++) == '\0')
5602 					return (0);
5603 
5604 				if (notflag) {
5605 					if (s1 < lc || s1 > c)
5606 						ok++;
5607 					else
5608 						return (0);
5609 				} else if (lc <= s1 && s1 <= c)
5610 					ok++;
5611 
5612 			} else if (c == '\\' && (c = *p++) == '\0')
5613 				return (0);
5614 
5615 			lc = c; /* save left-hand 'c' for next iteration */
5616 
5617 			if (notflag) {
5618 				if (s1 != c)
5619 					ok++;
5620 				else
5621 					return (0);
5622 			} else if (s1 == c)
5623 				ok++;
5624 
5625 			if ((c = *p++) == '\0')
5626 				return (0);
5627 
5628 		} while (c != ']');
5629 
5630 		if (ok)
5631 			goto top;
5632 
5633 		return (0);
5634 	}
5635 
5636 	case '\\':
5637 		if ((c = *p++) == '\0')
5638 			return (0);
5639 		/*FALLTHRU*/
5640 
5641 	default:
5642 		if (c != s1)
5643 			return (0);
5644 		/*FALLTHRU*/
5645 
5646 	case '?':
5647 		if (s1 != '\0')
5648 			goto top;
5649 		return (0);
5650 
5651 	case '*':
5652 		while (*p == '*')
5653 			p++; /* consecutive *'s are identical to a single one */
5654 
5655 		if (*p == '\0')
5656 			return (1);
5657 
5658 		for (s = olds; *s != '\0'; s++) {
5659 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
5660 				return (gs);
5661 		}
5662 
5663 		return (0);
5664 	}
5665 }
5666 
5667 /*ARGSUSED*/
5668 static int
5669 dtrace_match_string(const char *s, const char *p, int depth)
5670 {
5671 	return (s != NULL && strcmp(s, p) == 0);
5672 }
5673 
5674 /*ARGSUSED*/
5675 static int
5676 dtrace_match_nul(const char *s, const char *p, int depth)
5677 {
5678 	return (1); /* always match the empty pattern */
5679 }
5680 
5681 /*ARGSUSED*/
5682 static int
5683 dtrace_match_nonzero(const char *s, const char *p, int depth)
5684 {
5685 	return (s != NULL && s[0] != '\0');
5686 }
5687 
5688 static int
5689 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
5690     int (*matched)(dtrace_probe_t *, void *), void *arg)
5691 {
5692 	dtrace_probe_t template, *probe;
5693 	dtrace_hash_t *hash = NULL;
5694 	int len, best = INT_MAX, nmatched = 0;
5695 	dtrace_id_t i;
5696 
5697 	ASSERT(MUTEX_HELD(&dtrace_lock));
5698 
5699 	/*
5700 	 * If the probe ID is specified in the key, just lookup by ID and
5701 	 * invoke the match callback once if a matching probe is found.
5702 	 */
5703 	if (pkp->dtpk_id != DTRACE_IDNONE) {
5704 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
5705 		    dtrace_match_probe(probe, pkp, priv, uid) > 0) {
5706 			(void) (*matched)(probe, arg);
5707 			nmatched++;
5708 		}
5709 		return (nmatched);
5710 	}
5711 
5712 	template.dtpr_mod = (char *)pkp->dtpk_mod;
5713 	template.dtpr_func = (char *)pkp->dtpk_func;
5714 	template.dtpr_name = (char *)pkp->dtpk_name;
5715 
5716 	/*
5717 	 * We want to find the most distinct of the module name, function
5718 	 * name, and name.  So for each one that is not a glob pattern or
5719 	 * empty string, we perform a lookup in the corresponding hash and
5720 	 * use the hash table with the fewest collisions to do our search.
5721 	 */
5722 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
5723 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
5724 		best = len;
5725 		hash = dtrace_bymod;
5726 	}
5727 
5728 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
5729 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
5730 		best = len;
5731 		hash = dtrace_byfunc;
5732 	}
5733 
5734 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
5735 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
5736 		best = len;
5737 		hash = dtrace_byname;
5738 	}
5739 
5740 	/*
5741 	 * If we did not select a hash table, iterate over every probe and
5742 	 * invoke our callback for each one that matches our input probe key.
5743 	 */
5744 	if (hash == NULL) {
5745 		for (i = 0; i < dtrace_nprobes; i++) {
5746 			if ((probe = dtrace_probes[i]) == NULL ||
5747 			    dtrace_match_probe(probe, pkp, priv, uid) <= 0)
5748 				continue;
5749 
5750 			nmatched++;
5751 
5752 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
5753 				break;
5754 		}
5755 
5756 		return (nmatched);
5757 	}
5758 
5759 	/*
5760 	 * If we selected a hash table, iterate over each probe of the same key
5761 	 * name and invoke the callback for every probe that matches the other
5762 	 * attributes of our input probe key.
5763 	 */
5764 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
5765 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
5766 
5767 		if (dtrace_match_probe(probe, pkp, priv, uid) <= 0)
5768 			continue;
5769 
5770 		nmatched++;
5771 
5772 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
5773 			break;
5774 	}
5775 
5776 	return (nmatched);
5777 }
5778 
5779 /*
5780  * Return the function pointer dtrace_probecmp() should use to compare the
5781  * specified pattern with a string.  For NULL or empty patterns, we select
5782  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
5783  * For non-empty non-glob strings, we use dtrace_match_string().
5784  */
5785 static dtrace_probekey_f *
5786 dtrace_probekey_func(const char *p)
5787 {
5788 	char c;
5789 
5790 	if (p == NULL || *p == '\0')
5791 		return (&dtrace_match_nul);
5792 
5793 	while ((c = *p++) != '\0') {
5794 		if (c == '[' || c == '?' || c == '*' || c == '\\')
5795 			return (&dtrace_match_glob);
5796 	}
5797 
5798 	return (&dtrace_match_string);
5799 }
5800 
5801 /*
5802  * Build a probe comparison key for use with dtrace_match_probe() from the
5803  * given probe description.  By convention, a null key only matches anchored
5804  * probes: if each field is the empty string, reset dtpk_fmatch to
5805  * dtrace_match_nonzero().
5806  */
5807 static void
5808 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
5809 {
5810 	pkp->dtpk_prov = pdp->dtpd_provider;
5811 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
5812 
5813 	pkp->dtpk_mod = pdp->dtpd_mod;
5814 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
5815 
5816 	pkp->dtpk_func = pdp->dtpd_func;
5817 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
5818 
5819 	pkp->dtpk_name = pdp->dtpd_name;
5820 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
5821 
5822 	pkp->dtpk_id = pdp->dtpd_id;
5823 
5824 	if (pkp->dtpk_id == DTRACE_IDNONE &&
5825 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
5826 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
5827 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
5828 	    pkp->dtpk_nmatch == &dtrace_match_nul)
5829 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
5830 }
5831 
5832 /*
5833  * DTrace Provider-to-Framework API Functions
5834  *
5835  * These functions implement much of the Provider-to-Framework API, as
5836  * described in <sys/dtrace.h>.  The parts of the API not in this section are
5837  * the functions in the API for probe management (found below), and
5838  * dtrace_probe() itself (found above).
5839  */
5840 
5841 /*
5842  * Register the calling provider with the DTrace framework.  This should
5843  * generally be called by DTrace providers in their attach(9E) entry point.
5844  */
5845 int
5846 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
5847     uid_t uid, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
5848 {
5849 	dtrace_provider_t *provider;
5850 
5851 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
5852 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
5853 		    "arguments", name ? name : "<NULL>");
5854 		return (EINVAL);
5855 	}
5856 
5857 	if (name[0] == '\0' || dtrace_badname(name)) {
5858 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
5859 		    "provider name", name);
5860 		return (EINVAL);
5861 	}
5862 
5863 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
5864 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
5865 	    pops->dtps_destroy == NULL ||
5866 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
5867 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
5868 		    "provider ops", name);
5869 		return (EINVAL);
5870 	}
5871 
5872 	if (dtrace_badattr(&pap->dtpa_provider) ||
5873 	    dtrace_badattr(&pap->dtpa_mod) ||
5874 	    dtrace_badattr(&pap->dtpa_func) ||
5875 	    dtrace_badattr(&pap->dtpa_name) ||
5876 	    dtrace_badattr(&pap->dtpa_args)) {
5877 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
5878 		    "provider attributes", name);
5879 		return (EINVAL);
5880 	}
5881 
5882 	if (priv & ~DTRACE_PRIV_ALL) {
5883 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
5884 		    "privilege attributes", name);
5885 		return (EINVAL);
5886 	}
5887 
5888 	if ((priv & DTRACE_PRIV_KERNEL) &&
5889 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
5890 	    pops->dtps_usermode == NULL) {
5891 		cmn_err(CE_WARN, "failed to register provider '%s': need "
5892 		    "dtps_usermode() op for given privilege attributes", name);
5893 		return (EINVAL);
5894 	}
5895 
5896 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
5897 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
5898 	(void) strcpy(provider->dtpv_name, name);
5899 
5900 	provider->dtpv_attr = *pap;
5901 	provider->dtpv_priv.dtpp_flags = priv;
5902 	provider->dtpv_priv.dtpp_uid = uid;
5903 	provider->dtpv_pops = *pops;
5904 
5905 	if (pops->dtps_provide == NULL) {
5906 		ASSERT(pops->dtps_provide_module != NULL);
5907 		provider->dtpv_pops.dtps_provide =
5908 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
5909 	}
5910 
5911 	if (pops->dtps_provide_module == NULL) {
5912 		ASSERT(pops->dtps_provide != NULL);
5913 		provider->dtpv_pops.dtps_provide_module =
5914 		    (void (*)(void *, struct modctl *))dtrace_nullop;
5915 	}
5916 
5917 	if (pops->dtps_suspend == NULL) {
5918 		ASSERT(pops->dtps_resume == NULL);
5919 		provider->dtpv_pops.dtps_suspend =
5920 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
5921 		provider->dtpv_pops.dtps_resume =
5922 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
5923 	}
5924 
5925 	provider->dtpv_arg = arg;
5926 	*idp = (dtrace_provider_id_t)provider;
5927 
5928 	if (pops == &dtrace_provider_ops) {
5929 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
5930 		ASSERT(MUTEX_HELD(&dtrace_lock));
5931 		ASSERT(dtrace_anon.dta_enabling == NULL);
5932 
5933 		/*
5934 		 * We make sure that the DTrace provider is at the head of
5935 		 * the provider chain.
5936 		 */
5937 		provider->dtpv_next = dtrace_provider;
5938 		dtrace_provider = provider;
5939 		return (0);
5940 	}
5941 
5942 	mutex_enter(&dtrace_provider_lock);
5943 	mutex_enter(&dtrace_lock);
5944 
5945 	/*
5946 	 * If there is at least one provider registered, we'll add this
5947 	 * provider after the first provider.
5948 	 */
5949 	if (dtrace_provider != NULL) {
5950 		provider->dtpv_next = dtrace_provider->dtpv_next;
5951 		dtrace_provider->dtpv_next = provider;
5952 	} else {
5953 		dtrace_provider = provider;
5954 	}
5955 
5956 	if (dtrace_retained != NULL) {
5957 		dtrace_enabling_provide(provider);
5958 
5959 		/*
5960 		 * Now we need to call dtrace_enabling_matchall() -- which
5961 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
5962 		 * to drop all of our locks before calling into it...
5963 		 */
5964 		mutex_exit(&dtrace_lock);
5965 		mutex_exit(&dtrace_provider_lock);
5966 		dtrace_enabling_matchall();
5967 
5968 		return (0);
5969 	}
5970 
5971 	mutex_exit(&dtrace_lock);
5972 	mutex_exit(&dtrace_provider_lock);
5973 
5974 	return (0);
5975 }
5976 
5977 /*
5978  * Unregister the specified provider from the DTrace framework.  This should
5979  * generally be called by DTrace providers in their detach(9E) entry point.
5980  */
5981 int
5982 dtrace_unregister(dtrace_provider_id_t id)
5983 {
5984 	dtrace_provider_t *old = (dtrace_provider_t *)id;
5985 	dtrace_provider_t *prev = NULL;
5986 	int i, self = 0;
5987 	dtrace_probe_t *probe, *first = NULL;
5988 
5989 	if (old->dtpv_pops.dtps_enable ==
5990 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
5991 		/*
5992 		 * If DTrace itself is the provider, we're called with locks
5993 		 * already held.
5994 		 */
5995 		ASSERT(old == dtrace_provider);
5996 		ASSERT(dtrace_devi != NULL);
5997 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
5998 		ASSERT(MUTEX_HELD(&dtrace_lock));
5999 		self = 1;
6000 
6001 		if (dtrace_provider->dtpv_next != NULL) {
6002 			/*
6003 			 * There's another provider here; return failure.
6004 			 */
6005 			return (EBUSY);
6006 		}
6007 	} else {
6008 		mutex_enter(&dtrace_provider_lock);
6009 		mutex_enter(&mod_lock);
6010 		mutex_enter(&dtrace_lock);
6011 	}
6012 
6013 	/*
6014 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
6015 	 * probes, we refuse to let providers slither away, unless this
6016 	 * provider has already been explicitly invalidated.
6017 	 */
6018 	if (!old->dtpv_defunct &&
6019 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
6020 	    dtrace_anon.dta_state->dts_necbs > 0))) {
6021 		if (!self) {
6022 			mutex_exit(&dtrace_lock);
6023 			mutex_exit(&mod_lock);
6024 			mutex_exit(&dtrace_provider_lock);
6025 		}
6026 		return (EBUSY);
6027 	}
6028 
6029 	/*
6030 	 * Attempt to destroy the probes associated with this provider.
6031 	 */
6032 	for (i = 0; i < dtrace_nprobes; i++) {
6033 		if ((probe = dtrace_probes[i]) == NULL)
6034 			continue;
6035 
6036 		if (probe->dtpr_provider != old)
6037 			continue;
6038 
6039 		if (probe->dtpr_ecb == NULL)
6040 			continue;
6041 
6042 		/*
6043 		 * We have at least one ECB; we can't remove this provider.
6044 		 */
6045 		if (!self) {
6046 			mutex_exit(&dtrace_lock);
6047 			mutex_exit(&mod_lock);
6048 			mutex_exit(&dtrace_provider_lock);
6049 		}
6050 		return (EBUSY);
6051 	}
6052 
6053 	/*
6054 	 * All of the probes for this provider are disabled; we can safely
6055 	 * remove all of them from their hash chains and from the probe array.
6056 	 */
6057 	for (i = 0; i < dtrace_nprobes; i++) {
6058 		if ((probe = dtrace_probes[i]) == NULL)
6059 			continue;
6060 
6061 		if (probe->dtpr_provider != old)
6062 			continue;
6063 
6064 		dtrace_probes[i] = NULL;
6065 
6066 		dtrace_hash_remove(dtrace_bymod, probe);
6067 		dtrace_hash_remove(dtrace_byfunc, probe);
6068 		dtrace_hash_remove(dtrace_byname, probe);
6069 
6070 		if (first == NULL) {
6071 			first = probe;
6072 			probe->dtpr_nextmod = NULL;
6073 		} else {
6074 			probe->dtpr_nextmod = first;
6075 			first = probe;
6076 		}
6077 	}
6078 
6079 	/*
6080 	 * The provider's probes have been removed from the hash chains and
6081 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
6082 	 * everyone has cleared out from any probe array processing.
6083 	 */
6084 	dtrace_sync();
6085 
6086 	for (probe = first; probe != NULL; probe = first) {
6087 		first = probe->dtpr_nextmod;
6088 
6089 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
6090 		    probe->dtpr_arg);
6091 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
6092 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
6093 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
6094 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
6095 		kmem_free(probe, sizeof (dtrace_probe_t));
6096 	}
6097 
6098 	if ((prev = dtrace_provider) == old) {
6099 		ASSERT(self || dtrace_devi == NULL);
6100 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
6101 		dtrace_provider = old->dtpv_next;
6102 	} else {
6103 		while (prev != NULL && prev->dtpv_next != old)
6104 			prev = prev->dtpv_next;
6105 
6106 		if (prev == NULL) {
6107 			panic("attempt to unregister non-existent "
6108 			    "dtrace provider %p\n", (void *)id);
6109 		}
6110 
6111 		prev->dtpv_next = old->dtpv_next;
6112 	}
6113 
6114 	if (!self) {
6115 		mutex_exit(&dtrace_lock);
6116 		mutex_exit(&mod_lock);
6117 		mutex_exit(&dtrace_provider_lock);
6118 	}
6119 
6120 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
6121 	kmem_free(old, sizeof (dtrace_provider_t));
6122 
6123 	return (0);
6124 }
6125 
6126 /*
6127  * Invalidate the specified provider.  All subsequent probe lookups for the
6128  * specified provider will fail, but its probes will not be removed.
6129  */
6130 void
6131 dtrace_invalidate(dtrace_provider_id_t id)
6132 {
6133 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
6134 
6135 	ASSERT(pvp->dtpv_pops.dtps_enable !=
6136 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6137 
6138 	mutex_enter(&dtrace_provider_lock);
6139 	mutex_enter(&dtrace_lock);
6140 
6141 	pvp->dtpv_defunct = 1;
6142 
6143 	mutex_exit(&dtrace_lock);
6144 	mutex_exit(&dtrace_provider_lock);
6145 }
6146 
6147 /*
6148  * Indicate whether or not DTrace has attached.
6149  */
6150 int
6151 dtrace_attached(void)
6152 {
6153 	/*
6154 	 * dtrace_provider will be non-NULL iff the DTrace driver has
6155 	 * attached.  (It's non-NULL because DTrace is always itself a
6156 	 * provider.)
6157 	 */
6158 	return (dtrace_provider != NULL);
6159 }
6160 
6161 /*
6162  * Remove all the unenabled probes for the given provider.  This function is
6163  * not unlike dtrace_unregister(), except that it doesn't remove the provider
6164  * -- just as many of its associated probes as it can.
6165  */
6166 int
6167 dtrace_condense(dtrace_provider_id_t id)
6168 {
6169 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
6170 	int i;
6171 	dtrace_probe_t *probe;
6172 
6173 	/*
6174 	 * Make sure this isn't the dtrace provider itself.
6175 	 */
6176 	ASSERT(prov->dtpv_pops.dtps_enable !=
6177 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6178 
6179 	mutex_enter(&dtrace_provider_lock);
6180 	mutex_enter(&dtrace_lock);
6181 
6182 	/*
6183 	 * Attempt to destroy the probes associated with this provider.
6184 	 */
6185 	for (i = 0; i < dtrace_nprobes; i++) {
6186 		if ((probe = dtrace_probes[i]) == NULL)
6187 			continue;
6188 
6189 		if (probe->dtpr_provider != prov)
6190 			continue;
6191 
6192 		if (probe->dtpr_ecb != NULL)
6193 			continue;
6194 
6195 		dtrace_probes[i] = NULL;
6196 
6197 		dtrace_hash_remove(dtrace_bymod, probe);
6198 		dtrace_hash_remove(dtrace_byfunc, probe);
6199 		dtrace_hash_remove(dtrace_byname, probe);
6200 
6201 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
6202 		    probe->dtpr_arg);
6203 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
6204 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
6205 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
6206 		kmem_free(probe, sizeof (dtrace_probe_t));
6207 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
6208 	}
6209 
6210 	mutex_exit(&dtrace_lock);
6211 	mutex_exit(&dtrace_provider_lock);
6212 
6213 	return (0);
6214 }
6215 
6216 /*
6217  * DTrace Probe Management Functions
6218  *
6219  * The functions in this section perform the DTrace probe management,
6220  * including functions to create probes, look-up probes, and call into the
6221  * providers to request that probes be provided.  Some of these functions are
6222  * in the Provider-to-Framework API; these functions can be identified by the
6223  * fact that they are not declared "static".
6224  */
6225 
6226 /*
6227  * Create a probe with the specified module name, function name, and name.
6228  */
6229 dtrace_id_t
6230 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
6231     const char *func, const char *name, int aframes, void *arg)
6232 {
6233 	dtrace_probe_t *probe, **probes;
6234 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
6235 	dtrace_id_t id;
6236 
6237 	if (provider == dtrace_provider) {
6238 		ASSERT(MUTEX_HELD(&dtrace_lock));
6239 	} else {
6240 		mutex_enter(&dtrace_lock);
6241 	}
6242 
6243 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
6244 	    VM_BESTFIT | VM_SLEEP);
6245 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
6246 
6247 	probe->dtpr_id = id;
6248 	probe->dtpr_gen = dtrace_probegen++;
6249 	probe->dtpr_mod = dtrace_strdup(mod);
6250 	probe->dtpr_func = dtrace_strdup(func);
6251 	probe->dtpr_name = dtrace_strdup(name);
6252 	probe->dtpr_arg = arg;
6253 	probe->dtpr_aframes = aframes;
6254 	probe->dtpr_provider = provider;
6255 
6256 	dtrace_hash_add(dtrace_bymod, probe);
6257 	dtrace_hash_add(dtrace_byfunc, probe);
6258 	dtrace_hash_add(dtrace_byname, probe);
6259 
6260 	if (id - 1 >= dtrace_nprobes) {
6261 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
6262 		size_t nsize = osize << 1;
6263 
6264 		if (nsize == 0) {
6265 			ASSERT(osize == 0);
6266 			ASSERT(dtrace_probes == NULL);
6267 			nsize = sizeof (dtrace_probe_t *);
6268 		}
6269 
6270 		probes = kmem_zalloc(nsize, KM_SLEEP);
6271 
6272 		if (dtrace_probes == NULL) {
6273 			ASSERT(osize == 0);
6274 			dtrace_probes = probes;
6275 			dtrace_nprobes = 1;
6276 		} else {
6277 			dtrace_probe_t **oprobes = dtrace_probes;
6278 
6279 			bcopy(oprobes, probes, osize);
6280 			dtrace_membar_producer();
6281 			dtrace_probes = probes;
6282 
6283 			dtrace_sync();
6284 
6285 			/*
6286 			 * All CPUs are now seeing the new probes array; we can
6287 			 * safely free the old array.
6288 			 */
6289 			kmem_free(oprobes, osize);
6290 			dtrace_nprobes <<= 1;
6291 		}
6292 
6293 		ASSERT(id - 1 < dtrace_nprobes);
6294 	}
6295 
6296 	ASSERT(dtrace_probes[id - 1] == NULL);
6297 	dtrace_probes[id - 1] = probe;
6298 
6299 	if (provider != dtrace_provider)
6300 		mutex_exit(&dtrace_lock);
6301 
6302 	return (id);
6303 }
6304 
6305 static dtrace_probe_t *
6306 dtrace_probe_lookup_id(dtrace_id_t id)
6307 {
6308 	ASSERT(MUTEX_HELD(&dtrace_lock));
6309 
6310 	if (id == 0 || id > dtrace_nprobes)
6311 		return (NULL);
6312 
6313 	return (dtrace_probes[id - 1]);
6314 }
6315 
6316 static int
6317 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
6318 {
6319 	*((dtrace_id_t *)arg) = probe->dtpr_id;
6320 
6321 	return (DTRACE_MATCH_DONE);
6322 }
6323 
6324 /*
6325  * Look up a probe based on provider and one or more of module name, function
6326  * name and probe name.
6327  */
6328 dtrace_id_t
6329 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
6330     const char *func, const char *name)
6331 {
6332 	dtrace_probekey_t pkey;
6333 	dtrace_id_t id;
6334 	int match;
6335 
6336 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
6337 	pkey.dtpk_pmatch = &dtrace_match_string;
6338 	pkey.dtpk_mod = mod;
6339 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
6340 	pkey.dtpk_func = func;
6341 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
6342 	pkey.dtpk_name = name;
6343 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
6344 	pkey.dtpk_id = DTRACE_IDNONE;
6345 
6346 	mutex_enter(&dtrace_lock);
6347 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0,
6348 	    dtrace_probe_lookup_match, &id);
6349 	mutex_exit(&dtrace_lock);
6350 
6351 	ASSERT(match == 1 || match == 0);
6352 	return (match ? id : 0);
6353 }
6354 
6355 /*
6356  * Returns the probe argument associated with the specified probe.
6357  */
6358 void *
6359 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
6360 {
6361 	dtrace_probe_t *probe;
6362 	void *rval = NULL;
6363 
6364 	mutex_enter(&dtrace_lock);
6365 
6366 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
6367 	    probe->dtpr_provider == (dtrace_provider_t *)id)
6368 		rval = probe->dtpr_arg;
6369 
6370 	mutex_exit(&dtrace_lock);
6371 
6372 	return (rval);
6373 }
6374 
6375 /*
6376  * Copy a probe into a probe description.
6377  */
6378 static void
6379 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
6380 {
6381 	bzero(pdp, sizeof (dtrace_probedesc_t));
6382 	pdp->dtpd_id = prp->dtpr_id;
6383 
6384 	(void) strncpy(pdp->dtpd_provider,
6385 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
6386 
6387 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
6388 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
6389 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
6390 }
6391 
6392 /*
6393  * Called to indicate that a probe -- or probes -- should be provided by a
6394  * specfied provider.  If the specified description is NULL, the provider will
6395  * be told to provide all of its probes.  (This is done whenever a new
6396  * consumer comes along, or whenever a retained enabling is to be matched.) If
6397  * the specified description is non-NULL, the provider is given the
6398  * opportunity to dynamically provide the specified probe, allowing providers
6399  * to support the creation of probes on-the-fly.  (So-called _autocreated_
6400  * probes.)  If the provider is NULL, the operations will be applied to all
6401  * providers; if the provider is non-NULL the operations will only be applied
6402  * to the specified provider.  The dtrace_provider_lock must be held, and the
6403  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
6404  * will need to grab the dtrace_lock when it reenters the framework through
6405  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
6406  */
6407 static void
6408 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
6409 {
6410 	struct modctl *ctl;
6411 	int all = 0;
6412 
6413 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6414 
6415 	if (prv == NULL) {
6416 		all = 1;
6417 		prv = dtrace_provider;
6418 	}
6419 
6420 	do {
6421 		/*
6422 		 * First, call the blanket provide operation.
6423 		 */
6424 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
6425 
6426 		/*
6427 		 * Now call the per-module provide operation.  We will grab
6428 		 * mod_lock to prevent the list from being modified.  Note
6429 		 * that this also prevents the mod_busy bits from changing.
6430 		 * (mod_busy can only be changed with mod_lock held.)
6431 		 */
6432 		mutex_enter(&mod_lock);
6433 
6434 		ctl = &modules;
6435 		do {
6436 			if (ctl->mod_busy || ctl->mod_mp == NULL)
6437 				continue;
6438 
6439 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
6440 
6441 		} while ((ctl = ctl->mod_next) != &modules);
6442 
6443 		mutex_exit(&mod_lock);
6444 	} while (all && (prv = prv->dtpv_next) != NULL);
6445 }
6446 
6447 /*
6448  * Iterate over each probe, and call the Framework-to-Provider API function
6449  * denoted by offs.
6450  */
6451 static void
6452 dtrace_probe_foreach(uintptr_t offs)
6453 {
6454 	dtrace_provider_t *prov;
6455 	void (*func)(void *, dtrace_id_t, void *);
6456 	dtrace_probe_t *probe;
6457 	dtrace_icookie_t cookie;
6458 	int i;
6459 
6460 	/*
6461 	 * We disable interrupts to walk through the probe array.  This is
6462 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
6463 	 * won't see stale data.
6464 	 */
6465 	cookie = dtrace_interrupt_disable();
6466 
6467 	for (i = 0; i < dtrace_nprobes; i++) {
6468 		if ((probe = dtrace_probes[i]) == NULL)
6469 			continue;
6470 
6471 		if (probe->dtpr_ecb == NULL) {
6472 			/*
6473 			 * This probe isn't enabled -- don't call the function.
6474 			 */
6475 			continue;
6476 		}
6477 
6478 		prov = probe->dtpr_provider;
6479 		func = *((void(**)(void *, dtrace_id_t, void *))
6480 		    ((uintptr_t)&prov->dtpv_pops + offs));
6481 
6482 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
6483 	}
6484 
6485 	dtrace_interrupt_enable(cookie);
6486 }
6487 
6488 static int
6489 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
6490 {
6491 	dtrace_probekey_t pkey;
6492 	uint32_t priv;
6493 	uid_t uid;
6494 
6495 	ASSERT(MUTEX_HELD(&dtrace_lock));
6496 	dtrace_ecb_create_cache = NULL;
6497 
6498 	if (desc == NULL) {
6499 		/*
6500 		 * If we're passed a NULL description, we're being asked to
6501 		 * create an ECB with a NULL probe.
6502 		 */
6503 		(void) dtrace_ecb_create_enable(NULL, enab);
6504 		return (0);
6505 	}
6506 
6507 	dtrace_probekey(desc, &pkey);
6508 	dtrace_cred2priv(CRED(), &priv, &uid);
6509 
6510 	return (dtrace_match(&pkey, priv, uid, dtrace_ecb_create_enable, enab));
6511 }
6512 
6513 /*
6514  * DTrace Helper Provider Functions
6515  */
6516 static void
6517 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
6518 {
6519 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
6520 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
6521 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
6522 }
6523 
6524 static void
6525 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
6526     const dof_provider_t *dofprov, char *strtab)
6527 {
6528 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
6529 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
6530 	    dofprov->dofpv_provattr);
6531 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
6532 	    dofprov->dofpv_modattr);
6533 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
6534 	    dofprov->dofpv_funcattr);
6535 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
6536 	    dofprov->dofpv_nameattr);
6537 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
6538 	    dofprov->dofpv_argsattr);
6539 }
6540 
6541 static void
6542 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
6543 {
6544 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6545 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6546 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec;
6547 	dof_provider_t *provider;
6548 	dof_probe_t *probe;
6549 	uint32_t *off;
6550 	uint8_t *arg;
6551 	char *strtab;
6552 	uint_t i, nprobes;
6553 	dtrace_helper_provdesc_t dhpv;
6554 	dtrace_helper_probedesc_t dhpb;
6555 	dtrace_meta_t *meta = dtrace_meta_pid;
6556 	dtrace_mops_t *mops = &meta->dtm_mops;
6557 	void *parg;
6558 
6559 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
6560 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6561 	    provider->dofpv_strtab * dof->dofh_secsize);
6562 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6563 	    provider->dofpv_probes * dof->dofh_secsize);
6564 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6565 	    provider->dofpv_prargs * dof->dofh_secsize);
6566 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6567 	    provider->dofpv_proffs * dof->dofh_secsize);
6568 
6569 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
6570 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
6571 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
6572 
6573 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
6574 
6575 	/*
6576 	 * Create the provider.
6577 	 */
6578 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
6579 
6580 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
6581 		return;
6582 
6583 	meta->dtm_count++;
6584 
6585 	/*
6586 	 * Create the probes.
6587 	 */
6588 	for (i = 0; i < nprobes; i++) {
6589 		probe = (dof_probe_t *)(uintptr_t)(daddr +
6590 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
6591 
6592 		dhpb.dthpb_mod = dhp->dofhp_mod;
6593 		dhpb.dthpb_func = strtab + probe->dofpr_func;
6594 		dhpb.dthpb_name = strtab + probe->dofpr_name;
6595 		dhpb.dthpb_base = probe->dofpr_addr;
6596 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
6597 		dhpb.dthpb_noffs = probe->dofpr_noffs;
6598 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
6599 		dhpb.dthpb_nargc = probe->dofpr_nargc;
6600 		dhpb.dthpb_xargc = probe->dofpr_xargc;
6601 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
6602 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
6603 
6604 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
6605 	}
6606 }
6607 
6608 static void
6609 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
6610 {
6611 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6612 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6613 	int i;
6614 
6615 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
6616 
6617 	for (i = 0; i < dof->dofh_secnum; i++) {
6618 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
6619 		    dof->dofh_secoff + i * dof->dofh_secsize);
6620 
6621 		if (sec->dofs_type != DOF_SECT_PROVIDER)
6622 			continue;
6623 
6624 		dtrace_helper_provide_one(dhp, sec, pid);
6625 	}
6626 
6627 	/*
6628 	 * We may have just created probes, so we must now rematch against
6629 	 * any retained enablings.  Note that this call will acquire both
6630 	 * cpu_lock and dtrace_lock; the fact that we are holding
6631 	 * dtrace_meta_lock now is what defines the ordering with respect to
6632 	 * these three locks.
6633 	 */
6634 	dtrace_enabling_matchall();
6635 }
6636 
6637 static void
6638 dtrace_helper_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
6639 {
6640 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6641 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6642 	dof_sec_t *str_sec;
6643 	dof_provider_t *provider;
6644 	char *strtab;
6645 	dtrace_helper_provdesc_t dhpv;
6646 	dtrace_meta_t *meta = dtrace_meta_pid;
6647 	dtrace_mops_t *mops = &meta->dtm_mops;
6648 
6649 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
6650 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6651 	    provider->dofpv_strtab * dof->dofh_secsize);
6652 
6653 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
6654 
6655 	/*
6656 	 * Create the provider.
6657 	 */
6658 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
6659 
6660 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
6661 
6662 	meta->dtm_count--;
6663 }
6664 
6665 static void
6666 dtrace_helper_remove(dof_helper_t *dhp, pid_t pid)
6667 {
6668 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6669 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6670 	int i;
6671 
6672 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
6673 
6674 	for (i = 0; i < dof->dofh_secnum; i++) {
6675 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
6676 		    dof->dofh_secoff + i * dof->dofh_secsize);
6677 
6678 		if (sec->dofs_type != DOF_SECT_PROVIDER)
6679 			continue;
6680 
6681 		dtrace_helper_remove_one(dhp, sec, pid);
6682 	}
6683 }
6684 
6685 /*
6686  * DTrace Meta Provider-to-Framework API Functions
6687  *
6688  * These functions implement the Meta Provider-to-Framework API, as described
6689  * in <sys/dtrace.h>.
6690  */
6691 int
6692 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
6693     dtrace_meta_provider_id_t *idp)
6694 {
6695 	dtrace_meta_t *meta;
6696 	dtrace_helpers_t *help, *next;
6697 	int i;
6698 
6699 	*idp = DTRACE_METAPROVNONE;
6700 
6701 	/*
6702 	 * We strictly don't need the name, but we hold onto it for
6703 	 * debuggability. All hail error queues!
6704 	 */
6705 	if (name == NULL) {
6706 		cmn_err(CE_WARN, "failed to register meta-provider: "
6707 		    "invalid name");
6708 		return (EINVAL);
6709 	}
6710 
6711 	if (mops == NULL ||
6712 	    mops->dtms_create_probe == NULL ||
6713 	    mops->dtms_provide_pid == NULL ||
6714 	    mops->dtms_remove_pid == NULL) {
6715 		cmn_err(CE_WARN, "failed to register meta-register %s: "
6716 		    "invalid ops", name);
6717 		return (EINVAL);
6718 	}
6719 
6720 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
6721 	meta->dtm_mops = *mops;
6722 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
6723 	(void) strcpy(meta->dtm_name, name);
6724 	meta->dtm_arg = arg;
6725 
6726 	mutex_enter(&dtrace_meta_lock);
6727 	mutex_enter(&dtrace_lock);
6728 
6729 	if (dtrace_meta_pid != NULL) {
6730 		mutex_exit(&dtrace_lock);
6731 		mutex_exit(&dtrace_meta_lock);
6732 		cmn_err(CE_WARN, "failed to register meta-register %s: "
6733 		    "user-land meta-provider exists", name);
6734 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
6735 		kmem_free(meta, sizeof (dtrace_meta_t));
6736 		return (EINVAL);
6737 	}
6738 
6739 	dtrace_meta_pid = meta;
6740 	*idp = (dtrace_meta_provider_id_t)meta;
6741 
6742 	/*
6743 	 * If there are providers and probes ready to go, pass them
6744 	 * off to the new meta provider now.
6745 	 */
6746 
6747 	help = dtrace_deferred_pid;
6748 	dtrace_deferred_pid = NULL;
6749 
6750 	mutex_exit(&dtrace_lock);
6751 
6752 	while (help != NULL) {
6753 		for (i = 0; i < help->dthps_nprovs; i++) {
6754 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
6755 			    help->dthps_pid);
6756 		}
6757 
6758 		next = help->dthps_next;
6759 		help->dthps_next = NULL;
6760 		help->dthps_prev = NULL;
6761 		help->dthps_deferred = 0;
6762 		help = next;
6763 	}
6764 
6765 	mutex_exit(&dtrace_meta_lock);
6766 
6767 	return (0);
6768 }
6769 
6770 int
6771 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
6772 {
6773 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
6774 
6775 	mutex_enter(&dtrace_meta_lock);
6776 	mutex_enter(&dtrace_lock);
6777 
6778 	if (old == dtrace_meta_pid) {
6779 		pp = &dtrace_meta_pid;
6780 	} else {
6781 		panic("attempt to unregister non-existent "
6782 		    "dtrace meta-provider %p\n", (void *)old);
6783 	}
6784 
6785 	if (old->dtm_count != 0) {
6786 		mutex_exit(&dtrace_lock);
6787 		mutex_exit(&dtrace_meta_lock);
6788 		return (EBUSY);
6789 	}
6790 
6791 	*pp = NULL;
6792 
6793 	mutex_exit(&dtrace_lock);
6794 	mutex_exit(&dtrace_meta_lock);
6795 
6796 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
6797 	kmem_free(old, sizeof (dtrace_meta_t));
6798 
6799 	return (0);
6800 }
6801 
6802 
6803 /*
6804  * DTrace DIF Object Functions
6805  */
6806 static int
6807 dtrace_difo_err(uint_t pc, const char *format, ...)
6808 {
6809 	if (dtrace_err_verbose) {
6810 		va_list alist;
6811 
6812 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
6813 		va_start(alist, format);
6814 		(void) vuprintf(format, alist);
6815 		va_end(alist);
6816 	}
6817 
6818 #ifdef DTRACE_ERRDEBUG
6819 	dtrace_errdebug(format);
6820 #endif
6821 	return (1);
6822 }
6823 
6824 /*
6825  * Validate a DTrace DIF object by checking the IR instructions.  The following
6826  * rules are currently enforced by dtrace_difo_validate():
6827  *
6828  * 1. Each instruction must have a valid opcode
6829  * 2. Each register, string, variable, or subroutine reference must be valid
6830  * 3. No instruction can modify register %r0 (must be zero)
6831  * 4. All instruction reserved bits must be set to zero
6832  * 5. The last instruction must be a "ret" instruction
6833  * 6. All branch targets must reference a valid instruction _after_ the branch
6834  */
6835 static int
6836 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
6837     cred_t *cr)
6838 {
6839 	int err = 0, i;
6840 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
6841 	int kcheck;
6842 	uint_t pc;
6843 
6844 	kcheck = cr == NULL ||
6845 	    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE) == 0;
6846 
6847 	dp->dtdo_destructive = 0;
6848 
6849 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
6850 		dif_instr_t instr = dp->dtdo_buf[pc];
6851 
6852 		uint_t r1 = DIF_INSTR_R1(instr);
6853 		uint_t r2 = DIF_INSTR_R2(instr);
6854 		uint_t rd = DIF_INSTR_RD(instr);
6855 		uint_t rs = DIF_INSTR_RS(instr);
6856 		uint_t label = DIF_INSTR_LABEL(instr);
6857 		uint_t v = DIF_INSTR_VAR(instr);
6858 		uint_t subr = DIF_INSTR_SUBR(instr);
6859 		uint_t type = DIF_INSTR_TYPE(instr);
6860 		uint_t op = DIF_INSTR_OP(instr);
6861 
6862 		switch (op) {
6863 		case DIF_OP_OR:
6864 		case DIF_OP_XOR:
6865 		case DIF_OP_AND:
6866 		case DIF_OP_SLL:
6867 		case DIF_OP_SRL:
6868 		case DIF_OP_SRA:
6869 		case DIF_OP_SUB:
6870 		case DIF_OP_ADD:
6871 		case DIF_OP_MUL:
6872 		case DIF_OP_SDIV:
6873 		case DIF_OP_UDIV:
6874 		case DIF_OP_SREM:
6875 		case DIF_OP_UREM:
6876 		case DIF_OP_COPYS:
6877 			if (r1 >= nregs)
6878 				err += efunc(pc, "invalid register %u\n", r1);
6879 			if (r2 >= nregs)
6880 				err += efunc(pc, "invalid register %u\n", r2);
6881 			if (rd >= nregs)
6882 				err += efunc(pc, "invalid register %u\n", rd);
6883 			if (rd == 0)
6884 				err += efunc(pc, "cannot write to %r0\n");
6885 			break;
6886 		case DIF_OP_NOT:
6887 		case DIF_OP_MOV:
6888 		case DIF_OP_ALLOCS:
6889 			if (r1 >= nregs)
6890 				err += efunc(pc, "invalid register %u\n", r1);
6891 			if (r2 != 0)
6892 				err += efunc(pc, "non-zero reserved bits\n");
6893 			if (rd >= nregs)
6894 				err += efunc(pc, "invalid register %u\n", rd);
6895 			if (rd == 0)
6896 				err += efunc(pc, "cannot write to %r0\n");
6897 			break;
6898 		case DIF_OP_LDSB:
6899 		case DIF_OP_LDSH:
6900 		case DIF_OP_LDSW:
6901 		case DIF_OP_LDUB:
6902 		case DIF_OP_LDUH:
6903 		case DIF_OP_LDUW:
6904 		case DIF_OP_LDX:
6905 			if (r1 >= nregs)
6906 				err += efunc(pc, "invalid register %u\n", r1);
6907 			if (r2 != 0)
6908 				err += efunc(pc, "non-zero reserved bits\n");
6909 			if (rd >= nregs)
6910 				err += efunc(pc, "invalid register %u\n", rd);
6911 			if (rd == 0)
6912 				err += efunc(pc, "cannot write to %r0\n");
6913 			if (kcheck)
6914 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
6915 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
6916 			break;
6917 		case DIF_OP_RLDSB:
6918 		case DIF_OP_RLDSH:
6919 		case DIF_OP_RLDSW:
6920 		case DIF_OP_RLDUB:
6921 		case DIF_OP_RLDUH:
6922 		case DIF_OP_RLDUW:
6923 		case DIF_OP_RLDX:
6924 			if (r1 >= nregs)
6925 				err += efunc(pc, "invalid register %u\n", r1);
6926 			if (r2 != 0)
6927 				err += efunc(pc, "non-zero reserved bits\n");
6928 			if (rd >= nregs)
6929 				err += efunc(pc, "invalid register %u\n", rd);
6930 			if (rd == 0)
6931 				err += efunc(pc, "cannot write to %r0\n");
6932 			break;
6933 		case DIF_OP_ULDSB:
6934 		case DIF_OP_ULDSH:
6935 		case DIF_OP_ULDSW:
6936 		case DIF_OP_ULDUB:
6937 		case DIF_OP_ULDUH:
6938 		case DIF_OP_ULDUW:
6939 		case DIF_OP_ULDX:
6940 			if (r1 >= nregs)
6941 				err += efunc(pc, "invalid register %u\n", r1);
6942 			if (r2 != 0)
6943 				err += efunc(pc, "non-zero reserved bits\n");
6944 			if (rd >= nregs)
6945 				err += efunc(pc, "invalid register %u\n", rd);
6946 			if (rd == 0)
6947 				err += efunc(pc, "cannot write to %r0\n");
6948 			break;
6949 		case DIF_OP_STB:
6950 		case DIF_OP_STH:
6951 		case DIF_OP_STW:
6952 		case DIF_OP_STX:
6953 			if (r1 >= nregs)
6954 				err += efunc(pc, "invalid register %u\n", r1);
6955 			if (r2 != 0)
6956 				err += efunc(pc, "non-zero reserved bits\n");
6957 			if (rd >= nregs)
6958 				err += efunc(pc, "invalid register %u\n", rd);
6959 			if (rd == 0)
6960 				err += efunc(pc, "cannot write to 0 address\n");
6961 			break;
6962 		case DIF_OP_CMP:
6963 		case DIF_OP_SCMP:
6964 			if (r1 >= nregs)
6965 				err += efunc(pc, "invalid register %u\n", r1);
6966 			if (r2 >= nregs)
6967 				err += efunc(pc, "invalid register %u\n", r2);
6968 			if (rd != 0)
6969 				err += efunc(pc, "non-zero reserved bits\n");
6970 			break;
6971 		case DIF_OP_TST:
6972 			if (r1 >= nregs)
6973 				err += efunc(pc, "invalid register %u\n", r1);
6974 			if (r2 != 0 || rd != 0)
6975 				err += efunc(pc, "non-zero reserved bits\n");
6976 			break;
6977 		case DIF_OP_BA:
6978 		case DIF_OP_BE:
6979 		case DIF_OP_BNE:
6980 		case DIF_OP_BG:
6981 		case DIF_OP_BGU:
6982 		case DIF_OP_BGE:
6983 		case DIF_OP_BGEU:
6984 		case DIF_OP_BL:
6985 		case DIF_OP_BLU:
6986 		case DIF_OP_BLE:
6987 		case DIF_OP_BLEU:
6988 			if (label >= dp->dtdo_len) {
6989 				err += efunc(pc, "invalid branch target %u\n",
6990 				    label);
6991 			}
6992 			if (label <= pc) {
6993 				err += efunc(pc, "backward branch to %u\n",
6994 				    label);
6995 			}
6996 			break;
6997 		case DIF_OP_RET:
6998 			if (r1 != 0 || r2 != 0)
6999 				err += efunc(pc, "non-zero reserved bits\n");
7000 			if (rd >= nregs)
7001 				err += efunc(pc, "invalid register %u\n", rd);
7002 			break;
7003 		case DIF_OP_NOP:
7004 		case DIF_OP_POPTS:
7005 		case DIF_OP_FLUSHTS:
7006 			if (r1 != 0 || r2 != 0 || rd != 0)
7007 				err += efunc(pc, "non-zero reserved bits\n");
7008 			break;
7009 		case DIF_OP_SETX:
7010 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
7011 				err += efunc(pc, "invalid integer ref %u\n",
7012 				    DIF_INSTR_INTEGER(instr));
7013 			}
7014 			if (rd >= nregs)
7015 				err += efunc(pc, "invalid register %u\n", rd);
7016 			if (rd == 0)
7017 				err += efunc(pc, "cannot write to %r0\n");
7018 			break;
7019 		case DIF_OP_SETS:
7020 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
7021 				err += efunc(pc, "invalid string ref %u\n",
7022 				    DIF_INSTR_STRING(instr));
7023 			}
7024 			if (rd >= nregs)
7025 				err += efunc(pc, "invalid register %u\n", rd);
7026 			if (rd == 0)
7027 				err += efunc(pc, "cannot write to %r0\n");
7028 			break;
7029 		case DIF_OP_LDGA:
7030 		case DIF_OP_LDTA:
7031 			if (r1 > DIF_VAR_ARRAY_MAX)
7032 				err += efunc(pc, "invalid array %u\n", r1);
7033 			if (r2 >= nregs)
7034 				err += efunc(pc, "invalid register %u\n", r2);
7035 			if (rd >= nregs)
7036 				err += efunc(pc, "invalid register %u\n", rd);
7037 			if (rd == 0)
7038 				err += efunc(pc, "cannot write to %r0\n");
7039 			break;
7040 		case DIF_OP_LDGS:
7041 		case DIF_OP_LDTS:
7042 		case DIF_OP_LDLS:
7043 		case DIF_OP_LDGAA:
7044 		case DIF_OP_LDTAA:
7045 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
7046 				err += efunc(pc, "invalid variable %u\n", v);
7047 			if (rd >= nregs)
7048 				err += efunc(pc, "invalid register %u\n", rd);
7049 			if (rd == 0)
7050 				err += efunc(pc, "cannot write to %r0\n");
7051 			break;
7052 		case DIF_OP_STGS:
7053 		case DIF_OP_STTS:
7054 		case DIF_OP_STLS:
7055 		case DIF_OP_STGAA:
7056 		case DIF_OP_STTAA:
7057 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
7058 				err += efunc(pc, "invalid variable %u\n", v);
7059 			if (rs >= nregs)
7060 				err += efunc(pc, "invalid register %u\n", rd);
7061 			break;
7062 		case DIF_OP_CALL:
7063 			if (subr > DIF_SUBR_MAX)
7064 				err += efunc(pc, "invalid subr %u\n", subr);
7065 			if (rd >= nregs)
7066 				err += efunc(pc, "invalid register %u\n", rd);
7067 			if (rd == 0)
7068 				err += efunc(pc, "cannot write to %r0\n");
7069 
7070 			if (subr == DIF_SUBR_COPYOUT ||
7071 			    subr == DIF_SUBR_COPYOUTSTR) {
7072 				dp->dtdo_destructive = 1;
7073 			}
7074 			break;
7075 		case DIF_OP_PUSHTR:
7076 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
7077 				err += efunc(pc, "invalid ref type %u\n", type);
7078 			if (r2 >= nregs)
7079 				err += efunc(pc, "invalid register %u\n", r2);
7080 			if (rs >= nregs)
7081 				err += efunc(pc, "invalid register %u\n", rs);
7082 			break;
7083 		case DIF_OP_PUSHTV:
7084 			if (type != DIF_TYPE_CTF)
7085 				err += efunc(pc, "invalid val type %u\n", type);
7086 			if (r2 >= nregs)
7087 				err += efunc(pc, "invalid register %u\n", r2);
7088 			if (rs >= nregs)
7089 				err += efunc(pc, "invalid register %u\n", rs);
7090 			break;
7091 		default:
7092 			err += efunc(pc, "invalid opcode %u\n",
7093 			    DIF_INSTR_OP(instr));
7094 		}
7095 	}
7096 
7097 	if (dp->dtdo_len != 0 &&
7098 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
7099 		err += efunc(dp->dtdo_len - 1,
7100 		    "expected 'ret' as last DIF instruction\n");
7101 	}
7102 
7103 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
7104 		/*
7105 		 * If we're not returning by reference, the size must be either
7106 		 * 0 or the size of one of the base types.
7107 		 */
7108 		switch (dp->dtdo_rtype.dtdt_size) {
7109 		case 0:
7110 		case sizeof (uint8_t):
7111 		case sizeof (uint16_t):
7112 		case sizeof (uint32_t):
7113 		case sizeof (uint64_t):
7114 			break;
7115 
7116 		default:
7117 			err += efunc(dp->dtdo_len - 1, "bad return size");
7118 		}
7119 	}
7120 
7121 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
7122 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
7123 		dtrace_diftype_t *vt, *et;
7124 		uint_t id, ndx;
7125 
7126 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
7127 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
7128 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
7129 			err += efunc(i, "unrecognized variable scope %d\n",
7130 			    v->dtdv_scope);
7131 			break;
7132 		}
7133 
7134 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
7135 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
7136 			err += efunc(i, "unrecognized variable type %d\n",
7137 			    v->dtdv_kind);
7138 			break;
7139 		}
7140 
7141 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
7142 			err += efunc(i, "%d exceeds variable id limit\n", id);
7143 			break;
7144 		}
7145 
7146 		if (id < DIF_VAR_OTHER_UBASE)
7147 			continue;
7148 
7149 		/*
7150 		 * For user-defined variables, we need to check that this
7151 		 * definition is identical to any previous definition that we
7152 		 * encountered.
7153 		 */
7154 		ndx = id - DIF_VAR_OTHER_UBASE;
7155 
7156 		switch (v->dtdv_scope) {
7157 		case DIFV_SCOPE_GLOBAL:
7158 			if (ndx < vstate->dtvs_nglobals) {
7159 				dtrace_statvar_t *svar;
7160 
7161 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
7162 					existing = &svar->dtsv_var;
7163 			}
7164 
7165 			break;
7166 
7167 		case DIFV_SCOPE_THREAD:
7168 			if (ndx < vstate->dtvs_ntlocals)
7169 				existing = &vstate->dtvs_tlocals[ndx];
7170 			break;
7171 
7172 		case DIFV_SCOPE_LOCAL:
7173 			if (ndx < vstate->dtvs_nlocals) {
7174 				dtrace_statvar_t *svar;
7175 
7176 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
7177 					existing = &svar->dtsv_var;
7178 			}
7179 
7180 			break;
7181 		}
7182 
7183 		vt = &v->dtdv_type;
7184 
7185 		if (vt->dtdt_flags & DIF_TF_BYREF) {
7186 			if (vt->dtdt_size == 0) {
7187 				err += efunc(i, "zero-sized variable\n");
7188 				break;
7189 			}
7190 
7191 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
7192 			    vt->dtdt_size > dtrace_global_maxsize) {
7193 				err += efunc(i, "oversized by-ref global\n");
7194 				break;
7195 			}
7196 		}
7197 
7198 		if (existing == NULL || existing->dtdv_id == 0)
7199 			continue;
7200 
7201 		ASSERT(existing->dtdv_id == v->dtdv_id);
7202 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
7203 
7204 		if (existing->dtdv_kind != v->dtdv_kind)
7205 			err += efunc(i, "%d changed variable kind\n", id);
7206 
7207 		et = &existing->dtdv_type;
7208 
7209 		if (vt->dtdt_flags != et->dtdt_flags) {
7210 			err += efunc(i, "%d changed variable type flags\n", id);
7211 			break;
7212 		}
7213 
7214 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
7215 			err += efunc(i, "%d changed variable type size\n", id);
7216 			break;
7217 		}
7218 	}
7219 
7220 	return (err);
7221 }
7222 
7223 /*
7224  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
7225  * are much more constrained than normal DIFOs.  Specifically, they may
7226  * not:
7227  *
7228  * 1. Make calls to subroutines other than copyin(), copyinstr() or
7229  *    miscellaneous string routines
7230  * 2. Access DTrace variables other than the args[] array, and the
7231  *    curthread, pid, tid and execname variables.
7232  * 3. Have thread-local variables.
7233  * 4. Have dynamic variables.
7234  */
7235 static int
7236 dtrace_difo_validate_helper(dtrace_difo_t *dp)
7237 {
7238 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
7239 	int err = 0;
7240 	uint_t pc;
7241 
7242 	for (pc = 0; pc < dp->dtdo_len; pc++) {
7243 		dif_instr_t instr = dp->dtdo_buf[pc];
7244 
7245 		uint_t v = DIF_INSTR_VAR(instr);
7246 		uint_t subr = DIF_INSTR_SUBR(instr);
7247 		uint_t op = DIF_INSTR_OP(instr);
7248 
7249 		switch (op) {
7250 		case DIF_OP_OR:
7251 		case DIF_OP_XOR:
7252 		case DIF_OP_AND:
7253 		case DIF_OP_SLL:
7254 		case DIF_OP_SRL:
7255 		case DIF_OP_SRA:
7256 		case DIF_OP_SUB:
7257 		case DIF_OP_ADD:
7258 		case DIF_OP_MUL:
7259 		case DIF_OP_SDIV:
7260 		case DIF_OP_UDIV:
7261 		case DIF_OP_SREM:
7262 		case DIF_OP_UREM:
7263 		case DIF_OP_COPYS:
7264 		case DIF_OP_NOT:
7265 		case DIF_OP_MOV:
7266 		case DIF_OP_RLDSB:
7267 		case DIF_OP_RLDSH:
7268 		case DIF_OP_RLDSW:
7269 		case DIF_OP_RLDUB:
7270 		case DIF_OP_RLDUH:
7271 		case DIF_OP_RLDUW:
7272 		case DIF_OP_RLDX:
7273 		case DIF_OP_ULDSB:
7274 		case DIF_OP_ULDSH:
7275 		case DIF_OP_ULDSW:
7276 		case DIF_OP_ULDUB:
7277 		case DIF_OP_ULDUH:
7278 		case DIF_OP_ULDUW:
7279 		case DIF_OP_ULDX:
7280 		case DIF_OP_STB:
7281 		case DIF_OP_STH:
7282 		case DIF_OP_STW:
7283 		case DIF_OP_STX:
7284 		case DIF_OP_ALLOCS:
7285 		case DIF_OP_CMP:
7286 		case DIF_OP_SCMP:
7287 		case DIF_OP_TST:
7288 		case DIF_OP_BA:
7289 		case DIF_OP_BE:
7290 		case DIF_OP_BNE:
7291 		case DIF_OP_BG:
7292 		case DIF_OP_BGU:
7293 		case DIF_OP_BGE:
7294 		case DIF_OP_BGEU:
7295 		case DIF_OP_BL:
7296 		case DIF_OP_BLU:
7297 		case DIF_OP_BLE:
7298 		case DIF_OP_BLEU:
7299 		case DIF_OP_RET:
7300 		case DIF_OP_NOP:
7301 		case DIF_OP_POPTS:
7302 		case DIF_OP_FLUSHTS:
7303 		case DIF_OP_SETX:
7304 		case DIF_OP_SETS:
7305 		case DIF_OP_LDGA:
7306 		case DIF_OP_LDLS:
7307 		case DIF_OP_STGS:
7308 		case DIF_OP_STLS:
7309 		case DIF_OP_PUSHTR:
7310 		case DIF_OP_PUSHTV:
7311 			break;
7312 
7313 		case DIF_OP_LDGS:
7314 			if (v >= DIF_VAR_OTHER_UBASE)
7315 				break;
7316 
7317 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
7318 				break;
7319 
7320 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
7321 			    v == DIF_VAR_TID || v == DIF_VAR_EXECNAME ||
7322 			    v == DIF_VAR_ZONENAME)
7323 				break;
7324 
7325 			err += efunc(pc, "illegal variable %u\n", v);
7326 			break;
7327 
7328 		case DIF_OP_LDTA:
7329 		case DIF_OP_LDTS:
7330 		case DIF_OP_LDGAA:
7331 		case DIF_OP_LDTAA:
7332 			err += efunc(pc, "illegal dynamic variable load\n");
7333 			break;
7334 
7335 		case DIF_OP_STTS:
7336 		case DIF_OP_STGAA:
7337 		case DIF_OP_STTAA:
7338 			err += efunc(pc, "illegal dynamic variable store\n");
7339 			break;
7340 
7341 		case DIF_OP_CALL:
7342 			if (subr == DIF_SUBR_ALLOCA ||
7343 			    subr == DIF_SUBR_BCOPY ||
7344 			    subr == DIF_SUBR_COPYIN ||
7345 			    subr == DIF_SUBR_COPYINTO ||
7346 			    subr == DIF_SUBR_COPYINSTR ||
7347 			    subr == DIF_SUBR_INDEX ||
7348 			    subr == DIF_SUBR_LLTOSTR ||
7349 			    subr == DIF_SUBR_RINDEX ||
7350 			    subr == DIF_SUBR_STRCHR ||
7351 			    subr == DIF_SUBR_STRJOIN ||
7352 			    subr == DIF_SUBR_STRRCHR ||
7353 			    subr == DIF_SUBR_STRSTR)
7354 				break;
7355 
7356 			err += efunc(pc, "invalid subr %u\n", subr);
7357 			break;
7358 
7359 		default:
7360 			err += efunc(pc, "invalid opcode %u\n",
7361 			    DIF_INSTR_OP(instr));
7362 		}
7363 	}
7364 
7365 	return (err);
7366 }
7367 
7368 /*
7369  * Returns 1 if the expression in the DIF object can be cached on a per-thread
7370  * basis; 0 if not.
7371  */
7372 static int
7373 dtrace_difo_cacheable(dtrace_difo_t *dp)
7374 {
7375 	int i;
7376 
7377 	if (dp == NULL)
7378 		return (0);
7379 
7380 	for (i = 0; i < dp->dtdo_varlen; i++) {
7381 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7382 
7383 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
7384 			continue;
7385 
7386 		switch (v->dtdv_id) {
7387 		case DIF_VAR_CURTHREAD:
7388 		case DIF_VAR_PID:
7389 		case DIF_VAR_TID:
7390 		case DIF_VAR_EXECNAME:
7391 		case DIF_VAR_ZONENAME:
7392 			break;
7393 
7394 		default:
7395 			return (0);
7396 		}
7397 	}
7398 
7399 	/*
7400 	 * This DIF object may be cacheable.  Now we need to look for any
7401 	 * array loading instructions, any memory loading instructions, or
7402 	 * any stores to thread-local variables.
7403 	 */
7404 	for (i = 0; i < dp->dtdo_len; i++) {
7405 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
7406 
7407 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
7408 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
7409 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
7410 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
7411 			return (0);
7412 	}
7413 
7414 	return (1);
7415 }
7416 
7417 static void
7418 dtrace_difo_hold(dtrace_difo_t *dp)
7419 {
7420 	int i;
7421 
7422 	ASSERT(MUTEX_HELD(&dtrace_lock));
7423 
7424 	dp->dtdo_refcnt++;
7425 	ASSERT(dp->dtdo_refcnt != 0);
7426 
7427 	/*
7428 	 * We need to check this DIF object for references to the variable
7429 	 * DIF_VAR_VTIMESTAMP.
7430 	 */
7431 	for (i = 0; i < dp->dtdo_varlen; i++) {
7432 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7433 
7434 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
7435 			continue;
7436 
7437 		if (dtrace_vtime_references++ == 0)
7438 			dtrace_vtime_enable();
7439 	}
7440 }
7441 
7442 /*
7443  * This routine calculates the dynamic variable chunksize for a given DIF
7444  * object.  The calculation is not fool-proof, and can probably be tricked by
7445  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
7446  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
7447  * if a dynamic variable size exceeds the chunksize.
7448  */
7449 static void
7450 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7451 {
7452 	uint64_t sval;
7453 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
7454 	const dif_instr_t *text = dp->dtdo_buf;
7455 	uint_t pc, srd = 0;
7456 	uint_t ttop = 0;
7457 	size_t size, ksize;
7458 	uint_t id, i;
7459 
7460 	for (pc = 0; pc < dp->dtdo_len; pc++) {
7461 		dif_instr_t instr = text[pc];
7462 		uint_t op = DIF_INSTR_OP(instr);
7463 		uint_t rd = DIF_INSTR_RD(instr);
7464 		uint_t r1 = DIF_INSTR_R1(instr);
7465 		uint_t nkeys = 0;
7466 		uchar_t scope;
7467 
7468 		dtrace_key_t *key = tupregs;
7469 
7470 		switch (op) {
7471 		case DIF_OP_SETX:
7472 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
7473 			srd = rd;
7474 			continue;
7475 
7476 		case DIF_OP_STTS:
7477 			key = &tupregs[DIF_DTR_NREGS];
7478 			key[0].dttk_size = 0;
7479 			key[1].dttk_size = 0;
7480 			nkeys = 2;
7481 			scope = DIFV_SCOPE_THREAD;
7482 			break;
7483 
7484 		case DIF_OP_STGAA:
7485 		case DIF_OP_STTAA:
7486 			nkeys = ttop;
7487 
7488 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
7489 				key[nkeys++].dttk_size = 0;
7490 
7491 			key[nkeys++].dttk_size = 0;
7492 
7493 			if (op == DIF_OP_STTAA) {
7494 				scope = DIFV_SCOPE_THREAD;
7495 			} else {
7496 				scope = DIFV_SCOPE_GLOBAL;
7497 			}
7498 
7499 			break;
7500 
7501 		case DIF_OP_PUSHTR:
7502 			if (ttop == DIF_DTR_NREGS)
7503 				return;
7504 
7505 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
7506 				/*
7507 				 * If the register for the size of the "pushtr"
7508 				 * is %r0 (or the value is 0) and the type is
7509 				 * a string, we'll use the system-wide default
7510 				 * string size.
7511 				 */
7512 				tupregs[ttop++].dttk_size =
7513 				    dtrace_strsize_default;
7514 			} else {
7515 				if (srd == 0)
7516 					return;
7517 
7518 				tupregs[ttop++].dttk_size = sval;
7519 			}
7520 
7521 			break;
7522 
7523 		case DIF_OP_PUSHTV:
7524 			if (ttop == DIF_DTR_NREGS)
7525 				return;
7526 
7527 			tupregs[ttop++].dttk_size = 0;
7528 			break;
7529 
7530 		case DIF_OP_FLUSHTS:
7531 			ttop = 0;
7532 			break;
7533 
7534 		case DIF_OP_POPTS:
7535 			if (ttop != 0)
7536 				ttop--;
7537 			break;
7538 		}
7539 
7540 		sval = 0;
7541 		srd = 0;
7542 
7543 		if (nkeys == 0)
7544 			continue;
7545 
7546 		/*
7547 		 * We have a dynamic variable allocation; calculate its size.
7548 		 */
7549 		for (ksize = 0, i = 0; i < nkeys; i++)
7550 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
7551 
7552 		size = sizeof (dtrace_dynvar_t);
7553 		size += sizeof (dtrace_key_t) * (nkeys - 1);
7554 		size += ksize;
7555 
7556 		/*
7557 		 * Now we need to determine the size of the stored data.
7558 		 */
7559 		id = DIF_INSTR_VAR(instr);
7560 
7561 		for (i = 0; i < dp->dtdo_varlen; i++) {
7562 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
7563 
7564 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
7565 				size += v->dtdv_type.dtdt_size;
7566 				break;
7567 			}
7568 		}
7569 
7570 		if (i == dp->dtdo_varlen)
7571 			return;
7572 
7573 		/*
7574 		 * We have the size.  If this is larger than the chunk size
7575 		 * for our dynamic variable state, reset the chunk size.
7576 		 */
7577 		size = P2ROUNDUP(size, sizeof (uint64_t));
7578 
7579 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
7580 			vstate->dtvs_dynvars.dtds_chunksize = size;
7581 	}
7582 }
7583 
7584 static void
7585 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7586 {
7587 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
7588 	uint_t id;
7589 
7590 	ASSERT(MUTEX_HELD(&dtrace_lock));
7591 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
7592 
7593 	for (i = 0; i < dp->dtdo_varlen; i++) {
7594 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7595 		dtrace_statvar_t *svar, ***svarp;
7596 		size_t dsize = 0;
7597 		uint8_t scope = v->dtdv_scope;
7598 		int *np;
7599 
7600 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
7601 			continue;
7602 
7603 		id -= DIF_VAR_OTHER_UBASE;
7604 
7605 		switch (scope) {
7606 		case DIFV_SCOPE_THREAD:
7607 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
7608 				dtrace_difv_t *tlocals;
7609 
7610 				if ((ntlocals = (otlocals << 1)) == 0)
7611 					ntlocals = 1;
7612 
7613 				osz = otlocals * sizeof (dtrace_difv_t);
7614 				nsz = ntlocals * sizeof (dtrace_difv_t);
7615 
7616 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
7617 
7618 				if (osz != 0) {
7619 					bcopy(vstate->dtvs_tlocals,
7620 					    tlocals, osz);
7621 					kmem_free(vstate->dtvs_tlocals, osz);
7622 				}
7623 
7624 				vstate->dtvs_tlocals = tlocals;
7625 				vstate->dtvs_ntlocals = ntlocals;
7626 			}
7627 
7628 			vstate->dtvs_tlocals[id] = *v;
7629 			continue;
7630 
7631 		case DIFV_SCOPE_LOCAL:
7632 			np = &vstate->dtvs_nlocals;
7633 			svarp = &vstate->dtvs_locals;
7634 
7635 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
7636 				dsize = NCPU * (v->dtdv_type.dtdt_size +
7637 				    sizeof (uint64_t));
7638 			else
7639 				dsize = NCPU * sizeof (uint64_t);
7640 
7641 			break;
7642 
7643 		case DIFV_SCOPE_GLOBAL:
7644 			np = &vstate->dtvs_nglobals;
7645 			svarp = &vstate->dtvs_globals;
7646 
7647 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
7648 				dsize = v->dtdv_type.dtdt_size +
7649 				    sizeof (uint64_t);
7650 
7651 			break;
7652 
7653 		default:
7654 			ASSERT(0);
7655 		}
7656 
7657 		while (id >= (oldsvars = *np)) {
7658 			dtrace_statvar_t **statics;
7659 			int newsvars, oldsize, newsize;
7660 
7661 			if ((newsvars = (oldsvars << 1)) == 0)
7662 				newsvars = 1;
7663 
7664 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
7665 			newsize = newsvars * sizeof (dtrace_statvar_t *);
7666 
7667 			statics = kmem_zalloc(newsize, KM_SLEEP);
7668 
7669 			if (oldsize != 0) {
7670 				bcopy(*svarp, statics, oldsize);
7671 				kmem_free(*svarp, oldsize);
7672 			}
7673 
7674 			*svarp = statics;
7675 			*np = newsvars;
7676 		}
7677 
7678 		if ((svar = (*svarp)[id]) == NULL) {
7679 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
7680 			svar->dtsv_var = *v;
7681 
7682 			if ((svar->dtsv_size = dsize) != 0) {
7683 				svar->dtsv_data = (uint64_t)(uintptr_t)
7684 				    kmem_zalloc(dsize, KM_SLEEP);
7685 			}
7686 
7687 			(*svarp)[id] = svar;
7688 		}
7689 
7690 		svar->dtsv_refcnt++;
7691 	}
7692 
7693 	dtrace_difo_chunksize(dp, vstate);
7694 	dtrace_difo_hold(dp);
7695 }
7696 
7697 static dtrace_difo_t *
7698 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7699 {
7700 	dtrace_difo_t *new;
7701 	size_t sz;
7702 
7703 	ASSERT(dp->dtdo_buf != NULL);
7704 	ASSERT(dp->dtdo_refcnt != 0);
7705 
7706 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
7707 
7708 	ASSERT(dp->dtdo_buf != NULL);
7709 	sz = dp->dtdo_len * sizeof (dif_instr_t);
7710 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
7711 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
7712 	new->dtdo_len = dp->dtdo_len;
7713 
7714 	if (dp->dtdo_strtab != NULL) {
7715 		ASSERT(dp->dtdo_strlen != 0);
7716 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
7717 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
7718 		new->dtdo_strlen = dp->dtdo_strlen;
7719 	}
7720 
7721 	if (dp->dtdo_inttab != NULL) {
7722 		ASSERT(dp->dtdo_intlen != 0);
7723 		sz = dp->dtdo_intlen * sizeof (uint64_t);
7724 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
7725 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
7726 		new->dtdo_intlen = dp->dtdo_intlen;
7727 	}
7728 
7729 	if (dp->dtdo_vartab != NULL) {
7730 		ASSERT(dp->dtdo_varlen != 0);
7731 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
7732 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
7733 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
7734 		new->dtdo_varlen = dp->dtdo_varlen;
7735 	}
7736 
7737 	dtrace_difo_init(new, vstate);
7738 	return (new);
7739 }
7740 
7741 static void
7742 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7743 {
7744 	int i;
7745 
7746 	ASSERT(dp->dtdo_refcnt == 0);
7747 
7748 	for (i = 0; i < dp->dtdo_varlen; i++) {
7749 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7750 		dtrace_statvar_t *svar, **svarp;
7751 		uint_t id;
7752 		uint8_t scope = v->dtdv_scope;
7753 		int *np;
7754 
7755 		switch (scope) {
7756 		case DIFV_SCOPE_THREAD:
7757 			continue;
7758 
7759 		case DIFV_SCOPE_LOCAL:
7760 			np = &vstate->dtvs_nlocals;
7761 			svarp = vstate->dtvs_locals;
7762 			break;
7763 
7764 		case DIFV_SCOPE_GLOBAL:
7765 			np = &vstate->dtvs_nglobals;
7766 			svarp = vstate->dtvs_globals;
7767 			break;
7768 
7769 		default:
7770 			ASSERT(0);
7771 		}
7772 
7773 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
7774 			continue;
7775 
7776 		id -= DIF_VAR_OTHER_UBASE;
7777 		ASSERT(id < *np);
7778 
7779 		svar = svarp[id];
7780 		ASSERT(svar != NULL);
7781 		ASSERT(svar->dtsv_refcnt > 0);
7782 
7783 		if (--svar->dtsv_refcnt > 0)
7784 			continue;
7785 
7786 		if (svar->dtsv_size != 0) {
7787 			ASSERT(svar->dtsv_data != NULL);
7788 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
7789 			    svar->dtsv_size);
7790 		}
7791 
7792 		kmem_free(svar, sizeof (dtrace_statvar_t));
7793 		svarp[id] = NULL;
7794 	}
7795 
7796 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
7797 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
7798 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
7799 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
7800 
7801 	kmem_free(dp, sizeof (dtrace_difo_t));
7802 }
7803 
7804 static void
7805 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7806 {
7807 	int i;
7808 
7809 	ASSERT(MUTEX_HELD(&dtrace_lock));
7810 	ASSERT(dp->dtdo_refcnt != 0);
7811 
7812 	for (i = 0; i < dp->dtdo_varlen; i++) {
7813 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7814 
7815 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
7816 			continue;
7817 
7818 		ASSERT(dtrace_vtime_references > 0);
7819 		if (--dtrace_vtime_references == 0)
7820 			dtrace_vtime_disable();
7821 	}
7822 
7823 	if (--dp->dtdo_refcnt == 0)
7824 		dtrace_difo_destroy(dp, vstate);
7825 }
7826 
7827 /*
7828  * DTrace Format Functions
7829  */
7830 static uint16_t
7831 dtrace_format_add(dtrace_state_t *state, char *str)
7832 {
7833 	char *fmt, **new;
7834 	uint16_t ndx, len = strlen(str) + 1;
7835 
7836 	fmt = kmem_zalloc(len, KM_SLEEP);
7837 	bcopy(str, fmt, len);
7838 
7839 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
7840 		if (state->dts_formats[ndx] == NULL) {
7841 			state->dts_formats[ndx] = fmt;
7842 			return (ndx + 1);
7843 		}
7844 	}
7845 
7846 	if (state->dts_nformats == USHRT_MAX) {
7847 		/*
7848 		 * This is only likely if a denial-of-service attack is being
7849 		 * attempted.  As such, it's okay to fail silently here.
7850 		 */
7851 		kmem_free(fmt, len);
7852 		return (0);
7853 	}
7854 
7855 	/*
7856 	 * For simplicity, we always resize the formats array to be exactly the
7857 	 * number of formats.
7858 	 */
7859 	ndx = state->dts_nformats++;
7860 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
7861 
7862 	if (state->dts_formats != NULL) {
7863 		ASSERT(ndx != 0);
7864 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
7865 		kmem_free(state->dts_formats, ndx * sizeof (char *));
7866 	}
7867 
7868 	state->dts_formats = new;
7869 	state->dts_formats[ndx] = fmt;
7870 
7871 	return (ndx + 1);
7872 }
7873 
7874 static void
7875 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
7876 {
7877 	char *fmt;
7878 
7879 	ASSERT(state->dts_formats != NULL);
7880 	ASSERT(format <= state->dts_nformats);
7881 	ASSERT(state->dts_formats[format - 1] != NULL);
7882 
7883 	fmt = state->dts_formats[format - 1];
7884 	kmem_free(fmt, strlen(fmt) + 1);
7885 	state->dts_formats[format - 1] = NULL;
7886 }
7887 
7888 static void
7889 dtrace_format_destroy(dtrace_state_t *state)
7890 {
7891 	int i;
7892 
7893 	if (state->dts_nformats == 0) {
7894 		ASSERT(state->dts_formats == NULL);
7895 		return;
7896 	}
7897 
7898 	ASSERT(state->dts_formats != NULL);
7899 
7900 	for (i = 0; i < state->dts_nformats; i++) {
7901 		char *fmt = state->dts_formats[i];
7902 
7903 		if (fmt == NULL)
7904 			continue;
7905 
7906 		kmem_free(fmt, strlen(fmt) + 1);
7907 	}
7908 
7909 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
7910 	state->dts_nformats = 0;
7911 	state->dts_formats = NULL;
7912 }
7913 
7914 /*
7915  * DTrace Predicate Functions
7916  */
7917 static dtrace_predicate_t *
7918 dtrace_predicate_create(dtrace_difo_t *dp)
7919 {
7920 	dtrace_predicate_t *pred;
7921 
7922 	ASSERT(MUTEX_HELD(&dtrace_lock));
7923 	ASSERT(dp->dtdo_refcnt != 0);
7924 
7925 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
7926 	pred->dtp_difo = dp;
7927 	pred->dtp_refcnt = 1;
7928 
7929 	if (!dtrace_difo_cacheable(dp))
7930 		return (pred);
7931 
7932 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
7933 		/*
7934 		 * This is only theoretically possible -- we have had 2^32
7935 		 * cacheable predicates on this machine.  We cannot allow any
7936 		 * more predicates to become cacheable:  as unlikely as it is,
7937 		 * there may be a thread caching a (now stale) predicate cache
7938 		 * ID. (N.B.: the temptation is being successfully resisted to
7939 		 * have this cmn_err() "Holy shit -- we executed this code!")
7940 		 */
7941 		return (pred);
7942 	}
7943 
7944 	pred->dtp_cacheid = dtrace_predcache_id++;
7945 
7946 	return (pred);
7947 }
7948 
7949 static void
7950 dtrace_predicate_hold(dtrace_predicate_t *pred)
7951 {
7952 	ASSERT(MUTEX_HELD(&dtrace_lock));
7953 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
7954 	ASSERT(pred->dtp_refcnt > 0);
7955 
7956 	pred->dtp_refcnt++;
7957 }
7958 
7959 static void
7960 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
7961 {
7962 	dtrace_difo_t *dp = pred->dtp_difo;
7963 
7964 	ASSERT(MUTEX_HELD(&dtrace_lock));
7965 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
7966 	ASSERT(pred->dtp_refcnt > 0);
7967 
7968 	if (--pred->dtp_refcnt == 0) {
7969 		dtrace_difo_release(pred->dtp_difo, vstate);
7970 		kmem_free(pred, sizeof (dtrace_predicate_t));
7971 	}
7972 }
7973 
7974 /*
7975  * DTrace Action Description Functions
7976  */
7977 static dtrace_actdesc_t *
7978 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
7979     uint64_t uarg, uint64_t arg)
7980 {
7981 	dtrace_actdesc_t *act;
7982 
7983 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
7984 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
7985 
7986 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
7987 	act->dtad_kind = kind;
7988 	act->dtad_ntuple = ntuple;
7989 	act->dtad_uarg = uarg;
7990 	act->dtad_arg = arg;
7991 	act->dtad_refcnt = 1;
7992 
7993 	return (act);
7994 }
7995 
7996 static void
7997 dtrace_actdesc_hold(dtrace_actdesc_t *act)
7998 {
7999 	ASSERT(act->dtad_refcnt >= 1);
8000 	act->dtad_refcnt++;
8001 }
8002 
8003 static void
8004 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
8005 {
8006 	dtrace_actkind_t kind = act->dtad_kind;
8007 	dtrace_difo_t *dp;
8008 
8009 	ASSERT(act->dtad_refcnt >= 1);
8010 
8011 	if (--act->dtad_refcnt != 0)
8012 		return;
8013 
8014 	if ((dp = act->dtad_difo) != NULL)
8015 		dtrace_difo_release(dp, vstate);
8016 
8017 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
8018 		char *str = (char *)(uintptr_t)act->dtad_arg;
8019 
8020 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
8021 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
8022 
8023 		if (str != NULL)
8024 			kmem_free(str, strlen(str) + 1);
8025 	}
8026 
8027 	kmem_free(act, sizeof (dtrace_actdesc_t));
8028 }
8029 
8030 /*
8031  * DTrace ECB Functions
8032  */
8033 static dtrace_ecb_t *
8034 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
8035 {
8036 	dtrace_ecb_t *ecb;
8037 	dtrace_epid_t epid;
8038 
8039 	ASSERT(MUTEX_HELD(&dtrace_lock));
8040 
8041 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
8042 	ecb->dte_predicate = NULL;
8043 	ecb->dte_probe = probe;
8044 
8045 	/*
8046 	 * The default size is the size of the default action: recording
8047 	 * the epid.
8048 	 */
8049 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
8050 	ecb->dte_alignment = sizeof (dtrace_epid_t);
8051 
8052 	epid = state->dts_epid++;
8053 
8054 	if (epid - 1 >= state->dts_necbs) {
8055 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
8056 		int necbs = state->dts_necbs << 1;
8057 
8058 		ASSERT(epid == state->dts_necbs + 1);
8059 
8060 		if (necbs == 0) {
8061 			ASSERT(oecbs == NULL);
8062 			necbs = 1;
8063 		}
8064 
8065 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
8066 
8067 		if (oecbs != NULL)
8068 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
8069 
8070 		dtrace_membar_producer();
8071 		state->dts_ecbs = ecbs;
8072 
8073 		if (oecbs != NULL) {
8074 			/*
8075 			 * If this state is active, we must dtrace_sync()
8076 			 * before we can free the old dts_ecbs array:  we're
8077 			 * coming in hot, and there may be active ring
8078 			 * buffer processing (which indexes into the dts_ecbs
8079 			 * array) on another CPU.
8080 			 */
8081 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
8082 				dtrace_sync();
8083 
8084 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
8085 		}
8086 
8087 		dtrace_membar_producer();
8088 		state->dts_necbs = necbs;
8089 	}
8090 
8091 	ecb->dte_state = state;
8092 
8093 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
8094 	dtrace_membar_producer();
8095 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
8096 
8097 	return (ecb);
8098 }
8099 
8100 static void
8101 dtrace_ecb_enable(dtrace_ecb_t *ecb)
8102 {
8103 	dtrace_probe_t *probe = ecb->dte_probe;
8104 
8105 	ASSERT(MUTEX_HELD(&cpu_lock));
8106 	ASSERT(MUTEX_HELD(&dtrace_lock));
8107 	ASSERT(ecb->dte_next == NULL);
8108 
8109 	if (probe == NULL) {
8110 		/*
8111 		 * This is the NULL probe -- there's nothing to do.
8112 		 */
8113 		return;
8114 	}
8115 
8116 	if (probe->dtpr_ecb == NULL) {
8117 		dtrace_provider_t *prov = probe->dtpr_provider;
8118 
8119 		/*
8120 		 * We're the first ECB on this probe.
8121 		 */
8122 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
8123 
8124 		if (ecb->dte_predicate != NULL)
8125 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
8126 
8127 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
8128 		    probe->dtpr_id, probe->dtpr_arg);
8129 	} else {
8130 		/*
8131 		 * This probe is already active.  Swing the last pointer to
8132 		 * point to the new ECB, and issue a dtrace_sync() to assure
8133 		 * that all CPUs have seen the change.
8134 		 */
8135 		ASSERT(probe->dtpr_ecb_last != NULL);
8136 		probe->dtpr_ecb_last->dte_next = ecb;
8137 		probe->dtpr_ecb_last = ecb;
8138 		probe->dtpr_predcache = 0;
8139 
8140 		dtrace_sync();
8141 	}
8142 }
8143 
8144 static void
8145 dtrace_ecb_resize(dtrace_ecb_t *ecb)
8146 {
8147 	uint32_t maxalign = sizeof (dtrace_epid_t);
8148 	uint32_t align = sizeof (uint8_t), offs, diff;
8149 	dtrace_action_t *act;
8150 	int wastuple = 0;
8151 	uint32_t aggbase = UINT32_MAX;
8152 	dtrace_state_t *state = ecb->dte_state;
8153 
8154 	/*
8155 	 * If we record anything, we always record the epid.  (And we always
8156 	 * record it first.)
8157 	 */
8158 	offs = sizeof (dtrace_epid_t);
8159 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
8160 
8161 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
8162 		dtrace_recdesc_t *rec = &act->dta_rec;
8163 
8164 		if ((align = rec->dtrd_alignment) > maxalign)
8165 			maxalign = align;
8166 
8167 		if (!wastuple && act->dta_intuple) {
8168 			/*
8169 			 * This is the first record in a tuple.  Align the
8170 			 * offset to be at offset 4 in an 8-byte aligned
8171 			 * block.
8172 			 */
8173 			diff = offs + sizeof (dtrace_aggid_t);
8174 
8175 			if (diff = (diff & (sizeof (uint64_t) - 1)))
8176 				offs += sizeof (uint64_t) - diff;
8177 
8178 			aggbase = offs - sizeof (dtrace_aggid_t);
8179 			ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
8180 		}
8181 
8182 		/*LINTED*/
8183 		if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
8184 			/*
8185 			 * The current offset is not properly aligned; align it.
8186 			 */
8187 			offs += align - diff;
8188 		}
8189 
8190 		rec->dtrd_offset = offs;
8191 
8192 		if (offs + rec->dtrd_size > ecb->dte_needed) {
8193 			ecb->dte_needed = offs + rec->dtrd_size;
8194 
8195 			if (ecb->dte_needed > state->dts_needed)
8196 				state->dts_needed = ecb->dte_needed;
8197 		}
8198 
8199 		if (DTRACEACT_ISAGG(act->dta_kind)) {
8200 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
8201 			dtrace_action_t *first = agg->dtag_first, *prev;
8202 
8203 			ASSERT(rec->dtrd_size != 0 && first != NULL);
8204 			ASSERT(wastuple);
8205 			ASSERT(aggbase != UINT32_MAX);
8206 
8207 			agg->dtag_base = aggbase;
8208 
8209 			while ((prev = first->dta_prev) != NULL &&
8210 			    DTRACEACT_ISAGG(prev->dta_kind)) {
8211 				agg = (dtrace_aggregation_t *)prev;
8212 				first = agg->dtag_first;
8213 			}
8214 
8215 			if (prev != NULL) {
8216 				offs = prev->dta_rec.dtrd_offset +
8217 				    prev->dta_rec.dtrd_size;
8218 			} else {
8219 				offs = sizeof (dtrace_epid_t);
8220 			}
8221 			wastuple = 0;
8222 		} else {
8223 			if (!act->dta_intuple)
8224 				ecb->dte_size = offs + rec->dtrd_size;
8225 
8226 			offs += rec->dtrd_size;
8227 		}
8228 
8229 		wastuple = act->dta_intuple;
8230 	}
8231 
8232 	if ((act = ecb->dte_action) != NULL &&
8233 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
8234 	    ecb->dte_size == sizeof (dtrace_epid_t)) {
8235 		/*
8236 		 * If the size is still sizeof (dtrace_epid_t), then all
8237 		 * actions store no data; set the size to 0.
8238 		 */
8239 		ecb->dte_alignment = maxalign;
8240 		ecb->dte_size = 0;
8241 
8242 		/*
8243 		 * If the needed space is still sizeof (dtrace_epid_t), then
8244 		 * all actions need no additional space; set the needed
8245 		 * size to 0.
8246 		 */
8247 		if (ecb->dte_needed == sizeof (dtrace_epid_t))
8248 			ecb->dte_needed = 0;
8249 
8250 		return;
8251 	}
8252 
8253 	/*
8254 	 * Set our alignment, and make sure that the dte_size and dte_needed
8255 	 * are aligned to the size of an EPID.
8256 	 */
8257 	ecb->dte_alignment = maxalign;
8258 	ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
8259 	    ~(sizeof (dtrace_epid_t) - 1);
8260 	ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
8261 	    ~(sizeof (dtrace_epid_t) - 1);
8262 	ASSERT(ecb->dte_size <= ecb->dte_needed);
8263 }
8264 
8265 static dtrace_action_t *
8266 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
8267 {
8268 	dtrace_aggregation_t *agg;
8269 	size_t size = sizeof (uint64_t);
8270 	int ntuple = desc->dtad_ntuple;
8271 	dtrace_action_t *act;
8272 	dtrace_recdesc_t *frec;
8273 	dtrace_aggid_t aggid;
8274 	dtrace_state_t *state = ecb->dte_state;
8275 
8276 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
8277 	agg->dtag_ecb = ecb;
8278 
8279 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
8280 
8281 	switch (desc->dtad_kind) {
8282 	case DTRACEAGG_MIN:
8283 		agg->dtag_initial = UINT64_MAX;
8284 		agg->dtag_aggregate = dtrace_aggregate_min;
8285 		break;
8286 
8287 	case DTRACEAGG_MAX:
8288 		agg->dtag_aggregate = dtrace_aggregate_max;
8289 		break;
8290 
8291 	case DTRACEAGG_COUNT:
8292 		agg->dtag_aggregate = dtrace_aggregate_count;
8293 		break;
8294 
8295 	case DTRACEAGG_QUANTIZE:
8296 		agg->dtag_aggregate = dtrace_aggregate_quantize;
8297 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
8298 		    sizeof (uint64_t);
8299 		break;
8300 
8301 	case DTRACEAGG_LQUANTIZE: {
8302 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
8303 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
8304 
8305 		agg->dtag_initial = desc->dtad_arg;
8306 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
8307 
8308 		if (step == 0 || levels == 0)
8309 			goto err;
8310 
8311 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
8312 		break;
8313 	}
8314 
8315 	case DTRACEAGG_AVG:
8316 		agg->dtag_aggregate = dtrace_aggregate_avg;
8317 		size = sizeof (uint64_t) * 2;
8318 		break;
8319 
8320 	case DTRACEAGG_SUM:
8321 		agg->dtag_aggregate = dtrace_aggregate_sum;
8322 		break;
8323 
8324 	default:
8325 		goto err;
8326 	}
8327 
8328 	agg->dtag_action.dta_rec.dtrd_size = size;
8329 
8330 	if (ntuple == 0)
8331 		goto err;
8332 
8333 	/*
8334 	 * We must make sure that we have enough actions for the n-tuple.
8335 	 */
8336 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
8337 		if (DTRACEACT_ISAGG(act->dta_kind))
8338 			break;
8339 
8340 		if (--ntuple == 0) {
8341 			/*
8342 			 * This is the action with which our n-tuple begins.
8343 			 */
8344 			agg->dtag_first = act;
8345 			goto success;
8346 		}
8347 	}
8348 
8349 	/*
8350 	 * This n-tuple is short by ntuple elements.  Return failure.
8351 	 */
8352 	ASSERT(ntuple != 0);
8353 err:
8354 	kmem_free(agg, sizeof (dtrace_aggregation_t));
8355 	return (NULL);
8356 
8357 success:
8358 	/*
8359 	 * If the last action in the tuple has a size of zero, it's actually
8360 	 * an expression argument for the aggregating action.
8361 	 */
8362 	ASSERT(ecb->dte_action_last != NULL);
8363 	act = ecb->dte_action_last;
8364 
8365 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
8366 		ASSERT(act->dta_difo != NULL);
8367 
8368 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
8369 			agg->dtag_hasarg = 1;
8370 	}
8371 
8372 	/*
8373 	 * We need to allocate an id for this aggregation.
8374 	 */
8375 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
8376 	    VM_BESTFIT | VM_SLEEP);
8377 
8378 	if (aggid - 1 >= state->dts_naggregations) {
8379 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
8380 		dtrace_aggregation_t **aggs;
8381 		int naggs = state->dts_naggregations << 1;
8382 		int onaggs = state->dts_naggregations;
8383 
8384 		ASSERT(aggid == state->dts_naggregations + 1);
8385 
8386 		if (naggs == 0) {
8387 			ASSERT(oaggs == NULL);
8388 			naggs = 1;
8389 		}
8390 
8391 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
8392 
8393 		if (oaggs != NULL) {
8394 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
8395 			kmem_free(oaggs, onaggs * sizeof (*aggs));
8396 		}
8397 
8398 		state->dts_aggregations = aggs;
8399 		state->dts_naggregations = naggs;
8400 	}
8401 
8402 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
8403 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
8404 
8405 	frec = &agg->dtag_first->dta_rec;
8406 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
8407 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
8408 
8409 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
8410 		ASSERT(!act->dta_intuple);
8411 		act->dta_intuple = 1;
8412 	}
8413 
8414 	return (&agg->dtag_action);
8415 }
8416 
8417 static void
8418 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
8419 {
8420 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
8421 	dtrace_state_t *state = ecb->dte_state;
8422 	dtrace_aggid_t aggid = agg->dtag_id;
8423 
8424 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
8425 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
8426 
8427 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
8428 	state->dts_aggregations[aggid - 1] = NULL;
8429 
8430 	kmem_free(agg, sizeof (dtrace_aggregation_t));
8431 }
8432 
8433 static int
8434 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
8435 {
8436 	dtrace_action_t *action, *last;
8437 	dtrace_difo_t *dp = desc->dtad_difo;
8438 	uint32_t size = 0, align = sizeof (uint8_t), mask;
8439 	uint16_t format = 0;
8440 	dtrace_recdesc_t *rec;
8441 	dtrace_state_t *state = ecb->dte_state;
8442 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
8443 	uint64_t arg = desc->dtad_arg;
8444 
8445 	ASSERT(MUTEX_HELD(&dtrace_lock));
8446 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
8447 
8448 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
8449 		/*
8450 		 * If this is an aggregating action, there must be neither
8451 		 * a speculate nor a commit on the action chain.
8452 		 */
8453 		dtrace_action_t *act;
8454 
8455 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
8456 			if (act->dta_kind == DTRACEACT_COMMIT)
8457 				return (EINVAL);
8458 
8459 			if (act->dta_kind == DTRACEACT_SPECULATE)
8460 				return (EINVAL);
8461 		}
8462 
8463 		action = dtrace_ecb_aggregation_create(ecb, desc);
8464 
8465 		if (action == NULL)
8466 			return (EINVAL);
8467 	} else {
8468 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
8469 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
8470 		    dp != NULL && dp->dtdo_destructive)) {
8471 			state->dts_destructive = 1;
8472 		}
8473 
8474 		switch (desc->dtad_kind) {
8475 		case DTRACEACT_PRINTF:
8476 		case DTRACEACT_PRINTA:
8477 		case DTRACEACT_SYSTEM:
8478 		case DTRACEACT_FREOPEN:
8479 			/*
8480 			 * We know that our arg is a string -- turn it into a
8481 			 * format.
8482 			 */
8483 			if (arg == NULL) {
8484 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
8485 				format = 0;
8486 			} else {
8487 				ASSERT(arg != NULL);
8488 				ASSERT(arg > KERNELBASE);
8489 				format = dtrace_format_add(state,
8490 				    (char *)(uintptr_t)arg);
8491 			}
8492 
8493 			/*FALLTHROUGH*/
8494 		case DTRACEACT_LIBACT:
8495 		case DTRACEACT_DIFEXPR:
8496 			if (dp == NULL)
8497 				return (EINVAL);
8498 
8499 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
8500 				break;
8501 
8502 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
8503 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8504 					return (EINVAL);
8505 
8506 				size = opt[DTRACEOPT_STRSIZE];
8507 			}
8508 
8509 			break;
8510 
8511 		case DTRACEACT_STACK:
8512 			if ((nframes = arg) == 0) {
8513 				nframes = opt[DTRACEOPT_STACKFRAMES];
8514 				ASSERT(nframes > 0);
8515 				arg = nframes;
8516 			}
8517 
8518 			size = nframes * sizeof (pc_t);
8519 			break;
8520 
8521 		case DTRACEACT_JSTACK:
8522 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
8523 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
8524 
8525 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
8526 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
8527 
8528 			arg = DTRACE_USTACK_ARG(nframes, strsize);
8529 
8530 			/*FALLTHROUGH*/
8531 		case DTRACEACT_USTACK:
8532 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
8533 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
8534 				strsize = DTRACE_USTACK_STRSIZE(arg);
8535 				nframes = opt[DTRACEOPT_USTACKFRAMES];
8536 				ASSERT(nframes > 0);
8537 				arg = DTRACE_USTACK_ARG(nframes, strsize);
8538 			}
8539 
8540 			/*
8541 			 * Save a slot for the pid.
8542 			 */
8543 			size = (nframes + 1) * sizeof (uint64_t);
8544 			size += DTRACE_USTACK_STRSIZE(arg);
8545 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
8546 
8547 			break;
8548 
8549 		case DTRACEACT_SYM:
8550 		case DTRACEACT_MOD:
8551 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
8552 			    sizeof (uint64_t)) ||
8553 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8554 				return (EINVAL);
8555 			break;
8556 
8557 		case DTRACEACT_USYM:
8558 		case DTRACEACT_UMOD:
8559 		case DTRACEACT_UADDR:
8560 			if (dp == NULL ||
8561 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
8562 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8563 				return (EINVAL);
8564 
8565 			/*
8566 			 * We have a slot for the pid, plus a slot for the
8567 			 * argument.  To keep things simple (aligned with
8568 			 * bitness-neutral sizing), we store each as a 64-bit
8569 			 * quantity.
8570 			 */
8571 			size = 2 * sizeof (uint64_t);
8572 			break;
8573 
8574 		case DTRACEACT_STOP:
8575 		case DTRACEACT_BREAKPOINT:
8576 		case DTRACEACT_PANIC:
8577 			break;
8578 
8579 		case DTRACEACT_CHILL:
8580 		case DTRACEACT_DISCARD:
8581 		case DTRACEACT_RAISE:
8582 			if (dp == NULL)
8583 				return (EINVAL);
8584 			break;
8585 
8586 		case DTRACEACT_EXIT:
8587 			if (dp == NULL ||
8588 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
8589 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8590 				return (EINVAL);
8591 			break;
8592 
8593 		case DTRACEACT_SPECULATE:
8594 			if (ecb->dte_size > sizeof (dtrace_epid_t))
8595 				return (EINVAL);
8596 
8597 			if (dp == NULL)
8598 				return (EINVAL);
8599 
8600 			state->dts_speculates = 1;
8601 			break;
8602 
8603 		case DTRACEACT_COMMIT: {
8604 			dtrace_action_t *act = ecb->dte_action;
8605 
8606 			for (; act != NULL; act = act->dta_next) {
8607 				if (act->dta_kind == DTRACEACT_COMMIT)
8608 					return (EINVAL);
8609 			}
8610 
8611 			if (dp == NULL)
8612 				return (EINVAL);
8613 			break;
8614 		}
8615 
8616 		default:
8617 			return (EINVAL);
8618 		}
8619 
8620 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
8621 			/*
8622 			 * If this is a data-storing action or a speculate,
8623 			 * we must be sure that there isn't a commit on the
8624 			 * action chain.
8625 			 */
8626 			dtrace_action_t *act = ecb->dte_action;
8627 
8628 			for (; act != NULL; act = act->dta_next) {
8629 				if (act->dta_kind == DTRACEACT_COMMIT)
8630 					return (EINVAL);
8631 			}
8632 		}
8633 
8634 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
8635 		action->dta_rec.dtrd_size = size;
8636 	}
8637 
8638 	action->dta_refcnt = 1;
8639 	rec = &action->dta_rec;
8640 	size = rec->dtrd_size;
8641 
8642 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
8643 		if (!(size & mask)) {
8644 			align = mask + 1;
8645 			break;
8646 		}
8647 	}
8648 
8649 	action->dta_kind = desc->dtad_kind;
8650 
8651 	if ((action->dta_difo = dp) != NULL)
8652 		dtrace_difo_hold(dp);
8653 
8654 	rec->dtrd_action = action->dta_kind;
8655 	rec->dtrd_arg = arg;
8656 	rec->dtrd_uarg = desc->dtad_uarg;
8657 	rec->dtrd_alignment = (uint16_t)align;
8658 	rec->dtrd_format = format;
8659 
8660 	if ((last = ecb->dte_action_last) != NULL) {
8661 		ASSERT(ecb->dte_action != NULL);
8662 		action->dta_prev = last;
8663 		last->dta_next = action;
8664 	} else {
8665 		ASSERT(ecb->dte_action == NULL);
8666 		ecb->dte_action = action;
8667 	}
8668 
8669 	ecb->dte_action_last = action;
8670 
8671 	return (0);
8672 }
8673 
8674 static void
8675 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
8676 {
8677 	dtrace_action_t *act = ecb->dte_action, *next;
8678 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
8679 	dtrace_difo_t *dp;
8680 	uint16_t format;
8681 
8682 	if (act != NULL && act->dta_refcnt > 1) {
8683 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
8684 		act->dta_refcnt--;
8685 	} else {
8686 		for (; act != NULL; act = next) {
8687 			next = act->dta_next;
8688 			ASSERT(next != NULL || act == ecb->dte_action_last);
8689 			ASSERT(act->dta_refcnt == 1);
8690 
8691 			if ((format = act->dta_rec.dtrd_format) != 0)
8692 				dtrace_format_remove(ecb->dte_state, format);
8693 
8694 			if ((dp = act->dta_difo) != NULL)
8695 				dtrace_difo_release(dp, vstate);
8696 
8697 			if (DTRACEACT_ISAGG(act->dta_kind)) {
8698 				dtrace_ecb_aggregation_destroy(ecb, act);
8699 			} else {
8700 				kmem_free(act, sizeof (dtrace_action_t));
8701 			}
8702 		}
8703 	}
8704 
8705 	ecb->dte_action = NULL;
8706 	ecb->dte_action_last = NULL;
8707 	ecb->dte_size = sizeof (dtrace_epid_t);
8708 }
8709 
8710 static void
8711 dtrace_ecb_disable(dtrace_ecb_t *ecb)
8712 {
8713 	/*
8714 	 * We disable the ECB by removing it from its probe.
8715 	 */
8716 	dtrace_ecb_t *pecb, *prev = NULL;
8717 	dtrace_probe_t *probe = ecb->dte_probe;
8718 
8719 	ASSERT(MUTEX_HELD(&dtrace_lock));
8720 
8721 	if (probe == NULL) {
8722 		/*
8723 		 * This is the NULL probe; there is nothing to disable.
8724 		 */
8725 		return;
8726 	}
8727 
8728 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
8729 		if (pecb == ecb)
8730 			break;
8731 		prev = pecb;
8732 	}
8733 
8734 	ASSERT(pecb != NULL);
8735 
8736 	if (prev == NULL) {
8737 		probe->dtpr_ecb = ecb->dte_next;
8738 	} else {
8739 		prev->dte_next = ecb->dte_next;
8740 	}
8741 
8742 	if (ecb == probe->dtpr_ecb_last) {
8743 		ASSERT(ecb->dte_next == NULL);
8744 		probe->dtpr_ecb_last = prev;
8745 	}
8746 
8747 	/*
8748 	 * The ECB has been disconnected from the probe; now sync to assure
8749 	 * that all CPUs have seen the change before returning.
8750 	 */
8751 	dtrace_sync();
8752 
8753 	if (probe->dtpr_ecb == NULL) {
8754 		/*
8755 		 * That was the last ECB on the probe; clear the predicate
8756 		 * cache ID for the probe, disable it and sync one more time
8757 		 * to assure that we'll never hit it again.
8758 		 */
8759 		dtrace_provider_t *prov = probe->dtpr_provider;
8760 
8761 		ASSERT(ecb->dte_next == NULL);
8762 		ASSERT(probe->dtpr_ecb_last == NULL);
8763 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
8764 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
8765 		    probe->dtpr_id, probe->dtpr_arg);
8766 		dtrace_sync();
8767 	} else {
8768 		/*
8769 		 * There is at least one ECB remaining on the probe.  If there
8770 		 * is _exactly_ one, set the probe's predicate cache ID to be
8771 		 * the predicate cache ID of the remaining ECB.
8772 		 */
8773 		ASSERT(probe->dtpr_ecb_last != NULL);
8774 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
8775 
8776 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
8777 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
8778 
8779 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
8780 
8781 			if (p != NULL)
8782 				probe->dtpr_predcache = p->dtp_cacheid;
8783 		}
8784 
8785 		ecb->dte_next = NULL;
8786 	}
8787 }
8788 
8789 static void
8790 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
8791 {
8792 	dtrace_state_t *state = ecb->dte_state;
8793 	dtrace_vstate_t *vstate = &state->dts_vstate;
8794 	dtrace_predicate_t *pred;
8795 	dtrace_epid_t epid = ecb->dte_epid;
8796 
8797 	ASSERT(MUTEX_HELD(&dtrace_lock));
8798 	ASSERT(ecb->dte_next == NULL);
8799 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
8800 
8801 	if ((pred = ecb->dte_predicate) != NULL)
8802 		dtrace_predicate_release(pred, vstate);
8803 
8804 	dtrace_ecb_action_remove(ecb);
8805 
8806 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
8807 	state->dts_ecbs[epid - 1] = NULL;
8808 
8809 	kmem_free(ecb, sizeof (dtrace_ecb_t));
8810 }
8811 
8812 static dtrace_ecb_t *
8813 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
8814     dtrace_enabling_t *enab)
8815 {
8816 	dtrace_ecb_t *ecb;
8817 	dtrace_predicate_t *pred;
8818 	dtrace_actdesc_t *act;
8819 	dtrace_provider_t *prov;
8820 	dtrace_ecbdesc_t *desc = enab->dten_current;
8821 
8822 	ASSERT(MUTEX_HELD(&dtrace_lock));
8823 	ASSERT(state != NULL);
8824 
8825 	ecb = dtrace_ecb_add(state, probe);
8826 	ecb->dte_uarg = desc->dted_uarg;
8827 
8828 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
8829 		dtrace_predicate_hold(pred);
8830 		ecb->dte_predicate = pred;
8831 	}
8832 
8833 	if (probe != NULL) {
8834 		/*
8835 		 * If the provider shows more leg than the consumer is old
8836 		 * enough to see, we need to enable the appropriate implicit
8837 		 * predicate bits to prevent the ecb from activating at
8838 		 * revealing times.
8839 		 */
8840 		prov = probe->dtpr_provider;
8841 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
8842 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
8843 			ecb->dte_cond |= DTRACE_COND_OWNER;
8844 
8845 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
8846 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
8847 			ecb->dte_cond |= DTRACE_COND_USERMODE;
8848 	}
8849 
8850 	if (dtrace_ecb_create_cache != NULL) {
8851 		/*
8852 		 * If we have a cached ecb, we'll use its action list instead
8853 		 * of creating our own (saving both time and space).
8854 		 */
8855 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
8856 		dtrace_action_t *act = cached->dte_action;
8857 
8858 		if (act != NULL) {
8859 			ASSERT(act->dta_refcnt > 0);
8860 			act->dta_refcnt++;
8861 			ecb->dte_action = act;
8862 			ecb->dte_action_last = cached->dte_action_last;
8863 			ecb->dte_needed = cached->dte_needed;
8864 			ecb->dte_size = cached->dte_size;
8865 			ecb->dte_alignment = cached->dte_alignment;
8866 		}
8867 
8868 		return (ecb);
8869 	}
8870 
8871 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
8872 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
8873 			dtrace_ecb_destroy(ecb);
8874 			return (NULL);
8875 		}
8876 	}
8877 
8878 	dtrace_ecb_resize(ecb);
8879 
8880 	return (dtrace_ecb_create_cache = ecb);
8881 }
8882 
8883 static int
8884 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
8885 {
8886 	dtrace_ecb_t *ecb;
8887 	dtrace_enabling_t *enab = arg;
8888 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
8889 
8890 	ASSERT(state != NULL);
8891 
8892 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
8893 		/*
8894 		 * This probe was created in a generation for which this
8895 		 * enabling has previously created ECBs; we don't want to
8896 		 * enable it again, so just kick out.
8897 		 */
8898 		return (DTRACE_MATCH_NEXT);
8899 	}
8900 
8901 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
8902 		return (DTRACE_MATCH_DONE);
8903 
8904 	dtrace_ecb_enable(ecb);
8905 	return (DTRACE_MATCH_NEXT);
8906 }
8907 
8908 static dtrace_ecb_t *
8909 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
8910 {
8911 	dtrace_ecb_t *ecb;
8912 
8913 	ASSERT(MUTEX_HELD(&dtrace_lock));
8914 
8915 	if (id == 0 || id > state->dts_necbs)
8916 		return (NULL);
8917 
8918 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
8919 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
8920 
8921 	return (state->dts_ecbs[id - 1]);
8922 }
8923 
8924 static dtrace_aggregation_t *
8925 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
8926 {
8927 	dtrace_aggregation_t *agg;
8928 
8929 	ASSERT(MUTEX_HELD(&dtrace_lock));
8930 
8931 	if (id == 0 || id > state->dts_naggregations)
8932 		return (NULL);
8933 
8934 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
8935 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
8936 	    agg->dtag_id == id);
8937 
8938 	return (state->dts_aggregations[id - 1]);
8939 }
8940 
8941 /*
8942  * DTrace Buffer Functions
8943  *
8944  * The following functions manipulate DTrace buffers.  Most of these functions
8945  * are called in the context of establishing or processing consumer state;
8946  * exceptions are explicitly noted.
8947  */
8948 
8949 /*
8950  * Note:  called from cross call context.  This function switches the two
8951  * buffers on a given CPU.  The atomicity of this operation is assured by
8952  * disabling interrupts while the actual switch takes place; the disabling of
8953  * interrupts serializes the execution with any execution of dtrace_probe() on
8954  * the same CPU.
8955  */
8956 static void
8957 dtrace_buffer_switch(dtrace_buffer_t *buf)
8958 {
8959 	caddr_t tomax = buf->dtb_tomax;
8960 	caddr_t xamot = buf->dtb_xamot;
8961 	dtrace_icookie_t cookie;
8962 
8963 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
8964 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
8965 
8966 	cookie = dtrace_interrupt_disable();
8967 	buf->dtb_tomax = xamot;
8968 	buf->dtb_xamot = tomax;
8969 	buf->dtb_xamot_drops = buf->dtb_drops;
8970 	buf->dtb_xamot_offset = buf->dtb_offset;
8971 	buf->dtb_xamot_errors = buf->dtb_errors;
8972 	buf->dtb_xamot_flags = buf->dtb_flags;
8973 	buf->dtb_offset = 0;
8974 	buf->dtb_drops = 0;
8975 	buf->dtb_errors = 0;
8976 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
8977 	dtrace_interrupt_enable(cookie);
8978 }
8979 
8980 /*
8981  * Note:  called from cross call context.  This function activates a buffer
8982  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
8983  * is guaranteed by the disabling of interrupts.
8984  */
8985 static void
8986 dtrace_buffer_activate(dtrace_state_t *state)
8987 {
8988 	dtrace_buffer_t *buf;
8989 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
8990 
8991 	buf = &state->dts_buffer[CPU->cpu_id];
8992 
8993 	if (buf->dtb_tomax != NULL) {
8994 		/*
8995 		 * We might like to assert that the buffer is marked inactive,
8996 		 * but this isn't necessarily true:  the buffer for the CPU
8997 		 * that processes the BEGIN probe has its buffer activated
8998 		 * manually.  In this case, we take the (harmless) action
8999 		 * re-clearing the bit INACTIVE bit.
9000 		 */
9001 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
9002 	}
9003 
9004 	dtrace_interrupt_enable(cookie);
9005 }
9006 
9007 static int
9008 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
9009     processorid_t cpu)
9010 {
9011 	cpu_t *cp;
9012 	dtrace_buffer_t *buf;
9013 
9014 	ASSERT(MUTEX_HELD(&cpu_lock));
9015 	ASSERT(MUTEX_HELD(&dtrace_lock));
9016 
9017 	if (crgetuid(CRED()) != 0 && size > dtrace_nonroot_maxsize)
9018 		return (EFBIG);
9019 
9020 	cp = cpu_list;
9021 
9022 	do {
9023 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9024 			continue;
9025 
9026 		buf = &bufs[cp->cpu_id];
9027 
9028 		/*
9029 		 * If there is already a buffer allocated for this CPU, it
9030 		 * is only possible that this is a DR event.  In this case,
9031 		 * the buffer size must match our specified size.
9032 		 */
9033 		if (buf->dtb_tomax != NULL) {
9034 			ASSERT(buf->dtb_size == size);
9035 			continue;
9036 		}
9037 
9038 		ASSERT(buf->dtb_xamot == NULL);
9039 
9040 		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9041 			goto err;
9042 
9043 		buf->dtb_size = size;
9044 		buf->dtb_flags = flags;
9045 		buf->dtb_offset = 0;
9046 		buf->dtb_drops = 0;
9047 
9048 		if (flags & DTRACEBUF_NOSWITCH)
9049 			continue;
9050 
9051 		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9052 			goto err;
9053 	} while ((cp = cp->cpu_next) != cpu_list);
9054 
9055 	return (0);
9056 
9057 err:
9058 	cp = cpu_list;
9059 
9060 	do {
9061 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9062 			continue;
9063 
9064 		buf = &bufs[cp->cpu_id];
9065 
9066 		if (buf->dtb_xamot != NULL) {
9067 			ASSERT(buf->dtb_tomax != NULL);
9068 			ASSERT(buf->dtb_size == size);
9069 			kmem_free(buf->dtb_xamot, size);
9070 		}
9071 
9072 		if (buf->dtb_tomax != NULL) {
9073 			ASSERT(buf->dtb_size == size);
9074 			kmem_free(buf->dtb_tomax, size);
9075 		}
9076 
9077 		buf->dtb_tomax = NULL;
9078 		buf->dtb_xamot = NULL;
9079 		buf->dtb_size = 0;
9080 	} while ((cp = cp->cpu_next) != cpu_list);
9081 
9082 	return (ENOMEM);
9083 }
9084 
9085 /*
9086  * Note:  called from probe context.  This function just increments the drop
9087  * count on a buffer.  It has been made a function to allow for the
9088  * possibility of understanding the source of mysterious drop counts.  (A
9089  * problem for which one may be particularly disappointed that DTrace cannot
9090  * be used to understand DTrace.)
9091  */
9092 static void
9093 dtrace_buffer_drop(dtrace_buffer_t *buf)
9094 {
9095 	buf->dtb_drops++;
9096 }
9097 
9098 /*
9099  * Note:  called from probe context.  This function is called to reserve space
9100  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
9101  * mstate.  Returns the new offset in the buffer, or a negative value if an
9102  * error has occurred.
9103  */
9104 static intptr_t
9105 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
9106     dtrace_state_t *state, dtrace_mstate_t *mstate)
9107 {
9108 	intptr_t offs = buf->dtb_offset, soffs;
9109 	intptr_t woffs;
9110 	caddr_t tomax;
9111 	size_t total;
9112 
9113 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
9114 		return (-1);
9115 
9116 	if ((tomax = buf->dtb_tomax) == NULL) {
9117 		dtrace_buffer_drop(buf);
9118 		return (-1);
9119 	}
9120 
9121 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
9122 		while (offs & (align - 1)) {
9123 			/*
9124 			 * Assert that our alignment is off by a number which
9125 			 * is itself sizeof (uint32_t) aligned.
9126 			 */
9127 			ASSERT(!((align - (offs & (align - 1))) &
9128 			    (sizeof (uint32_t) - 1)));
9129 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
9130 			offs += sizeof (uint32_t);
9131 		}
9132 
9133 		if ((soffs = offs + needed) > buf->dtb_size) {
9134 			dtrace_buffer_drop(buf);
9135 			return (-1);
9136 		}
9137 
9138 		if (mstate == NULL)
9139 			return (offs);
9140 
9141 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
9142 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
9143 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
9144 
9145 		return (offs);
9146 	}
9147 
9148 	if (buf->dtb_flags & DTRACEBUF_FILL) {
9149 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
9150 		    (buf->dtb_flags & DTRACEBUF_FULL))
9151 			return (-1);
9152 		goto out;
9153 	}
9154 
9155 	total = needed + (offs & (align - 1));
9156 
9157 	/*
9158 	 * For a ring buffer, life is quite a bit more complicated.  Before
9159 	 * we can store any padding, we need to adjust our wrapping offset.
9160 	 * (If we've never before wrapped or we're not about to, no adjustment
9161 	 * is required.)
9162 	 */
9163 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
9164 	    offs + total > buf->dtb_size) {
9165 		woffs = buf->dtb_xamot_offset;
9166 
9167 		if (offs + total > buf->dtb_size) {
9168 			/*
9169 			 * We can't fit in the end of the buffer.  First, a
9170 			 * sanity check that we can fit in the buffer at all.
9171 			 */
9172 			if (total > buf->dtb_size) {
9173 				dtrace_buffer_drop(buf);
9174 				return (-1);
9175 			}
9176 
9177 			/*
9178 			 * We're going to be storing at the top of the buffer,
9179 			 * so now we need to deal with the wrapped offset.  We
9180 			 * only reset our wrapped offset to 0 if it is
9181 			 * currently greater than the current offset.  If it
9182 			 * is less than the current offset, it is because a
9183 			 * previous allocation induced a wrap -- but the
9184 			 * allocation didn't subsequently take the space due
9185 			 * to an error or false predicate evaluation.  In this
9186 			 * case, we'll just leave the wrapped offset alone: if
9187 			 * the wrapped offset hasn't been advanced far enough
9188 			 * for this allocation, it will be adjusted in the
9189 			 * lower loop.
9190 			 */
9191 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
9192 				if (woffs >= offs)
9193 					woffs = 0;
9194 			} else {
9195 				woffs = 0;
9196 			}
9197 
9198 			/*
9199 			 * Now we know that we're going to be storing to the
9200 			 * top of the buffer and that there is room for us
9201 			 * there.  We need to clear the buffer from the current
9202 			 * offset to the end (there may be old gunk there).
9203 			 */
9204 			while (offs < buf->dtb_size)
9205 				tomax[offs++] = 0;
9206 
9207 			/*
9208 			 * We need to set our offset to zero.  And because we
9209 			 * are wrapping, we need to set the bit indicating as
9210 			 * much.  We can also adjust our needed space back
9211 			 * down to the space required by the ECB -- we know
9212 			 * that the top of the buffer is aligned.
9213 			 */
9214 			offs = 0;
9215 			total = needed;
9216 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
9217 		} else {
9218 			/*
9219 			 * There is room for us in the buffer, so we simply
9220 			 * need to check the wrapped offset.
9221 			 */
9222 			if (woffs < offs) {
9223 				/*
9224 				 * The wrapped offset is less than the offset.
9225 				 * This can happen if we allocated buffer space
9226 				 * that induced a wrap, but then we didn't
9227 				 * subsequently take the space due to an error
9228 				 * or false predicate evaluation.  This is
9229 				 * okay; we know that _this_ allocation isn't
9230 				 * going to induce a wrap.  We still can't
9231 				 * reset the wrapped offset to be zero,
9232 				 * however: the space may have been trashed in
9233 				 * the previous failed probe attempt.  But at
9234 				 * least the wrapped offset doesn't need to
9235 				 * be adjusted at all...
9236 				 */
9237 				goto out;
9238 			}
9239 		}
9240 
9241 		while (offs + total > woffs) {
9242 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
9243 			size_t size;
9244 
9245 			if (epid == DTRACE_EPIDNONE) {
9246 				size = sizeof (uint32_t);
9247 			} else {
9248 				ASSERT(epid <= state->dts_necbs);
9249 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
9250 
9251 				size = state->dts_ecbs[epid - 1]->dte_size;
9252 			}
9253 
9254 			ASSERT(woffs + size <= buf->dtb_size);
9255 			ASSERT(size != 0);
9256 
9257 			if (woffs + size == buf->dtb_size) {
9258 				/*
9259 				 * We've reached the end of the buffer; we want
9260 				 * to set the wrapped offset to 0 and break
9261 				 * out.  However, if the offs is 0, then we're
9262 				 * in a strange edge-condition:  the amount of
9263 				 * space that we want to reserve plus the size
9264 				 * of the record that we're overwriting is
9265 				 * greater than the size of the buffer.  This
9266 				 * is problematic because if we reserve the
9267 				 * space but subsequently don't consume it (due
9268 				 * to a failed predicate or error) the wrapped
9269 				 * offset will be 0 -- yet the EPID at offset 0
9270 				 * will not be committed.  This situation is
9271 				 * relatively easy to deal with:  if we're in
9272 				 * this case, the buffer is indistinguishable
9273 				 * from one that hasn't wrapped; we need only
9274 				 * finish the job by clearing the wrapped bit,
9275 				 * explicitly setting the offset to be 0, and
9276 				 * zero'ing out the old data in the buffer.
9277 				 */
9278 				if (offs == 0) {
9279 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
9280 					buf->dtb_offset = 0;
9281 					woffs = total;
9282 
9283 					while (woffs < buf->dtb_size)
9284 						tomax[woffs++] = 0;
9285 				}
9286 
9287 				woffs = 0;
9288 				break;
9289 			}
9290 
9291 			woffs += size;
9292 		}
9293 
9294 		/*
9295 		 * We have a wrapped offset.  It may be that the wrapped offset
9296 		 * has become zero -- that's okay.
9297 		 */
9298 		buf->dtb_xamot_offset = woffs;
9299 	}
9300 
9301 out:
9302 	/*
9303 	 * Now we can plow the buffer with any necessary padding.
9304 	 */
9305 	while (offs & (align - 1)) {
9306 		/*
9307 		 * Assert that our alignment is off by a number which
9308 		 * is itself sizeof (uint32_t) aligned.
9309 		 */
9310 		ASSERT(!((align - (offs & (align - 1))) &
9311 		    (sizeof (uint32_t) - 1)));
9312 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
9313 		offs += sizeof (uint32_t);
9314 	}
9315 
9316 	if (buf->dtb_flags & DTRACEBUF_FILL) {
9317 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
9318 			buf->dtb_flags |= DTRACEBUF_FULL;
9319 			return (-1);
9320 		}
9321 	}
9322 
9323 	if (mstate == NULL)
9324 		return (offs);
9325 
9326 	/*
9327 	 * For ring buffers and fill buffers, the scratch space is always
9328 	 * the inactive buffer.
9329 	 */
9330 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
9331 	mstate->dtms_scratch_size = buf->dtb_size;
9332 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
9333 
9334 	return (offs);
9335 }
9336 
9337 static void
9338 dtrace_buffer_polish(dtrace_buffer_t *buf)
9339 {
9340 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
9341 	ASSERT(MUTEX_HELD(&dtrace_lock));
9342 
9343 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
9344 		return;
9345 
9346 	/*
9347 	 * We need to polish the ring buffer.  There are three cases:
9348 	 *
9349 	 * - The first (and presumably most common) is that there is no gap
9350 	 *   between the buffer offset and the wrapped offset.  In this case,
9351 	 *   there is nothing in the buffer that isn't valid data; we can
9352 	 *   mark the buffer as polished and return.
9353 	 *
9354 	 * - The second (less common than the first but still more common
9355 	 *   than the third) is that there is a gap between the buffer offset
9356 	 *   and the wrapped offset, and the wrapped offset is larger than the
9357 	 *   buffer offset.  This can happen because of an alignment issue, or
9358 	 *   can happen because of a call to dtrace_buffer_reserve() that
9359 	 *   didn't subsequently consume the buffer space.  In this case,
9360 	 *   we need to zero the data from the buffer offset to the wrapped
9361 	 *   offset.
9362 	 *
9363 	 * - The third (and least common) is that there is a gap between the
9364 	 *   buffer offset and the wrapped offset, but the wrapped offset is
9365 	 *   _less_ than the buffer offset.  This can only happen because a
9366 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
9367 	 *   was not subsequently consumed.  In this case, we need to zero the
9368 	 *   space from the offset to the end of the buffer _and_ from the
9369 	 *   top of the buffer to the wrapped offset.
9370 	 */
9371 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
9372 		bzero(buf->dtb_tomax + buf->dtb_offset,
9373 		    buf->dtb_xamot_offset - buf->dtb_offset);
9374 	}
9375 
9376 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
9377 		bzero(buf->dtb_tomax + buf->dtb_offset,
9378 		    buf->dtb_size - buf->dtb_offset);
9379 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
9380 	}
9381 }
9382 
9383 static void
9384 dtrace_buffer_free(dtrace_buffer_t *bufs)
9385 {
9386 	int i;
9387 
9388 	for (i = 0; i < NCPU; i++) {
9389 		dtrace_buffer_t *buf = &bufs[i];
9390 
9391 		if (buf->dtb_tomax == NULL) {
9392 			ASSERT(buf->dtb_xamot == NULL);
9393 			ASSERT(buf->dtb_size == 0);
9394 			continue;
9395 		}
9396 
9397 		if (buf->dtb_xamot != NULL) {
9398 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
9399 			kmem_free(buf->dtb_xamot, buf->dtb_size);
9400 		}
9401 
9402 		kmem_free(buf->dtb_tomax, buf->dtb_size);
9403 		buf->dtb_size = 0;
9404 		buf->dtb_tomax = NULL;
9405 		buf->dtb_xamot = NULL;
9406 	}
9407 }
9408 
9409 /*
9410  * DTrace Enabling Functions
9411  */
9412 static dtrace_enabling_t *
9413 dtrace_enabling_create(dtrace_vstate_t *vstate)
9414 {
9415 	dtrace_enabling_t *enab;
9416 
9417 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
9418 	enab->dten_vstate = vstate;
9419 
9420 	return (enab);
9421 }
9422 
9423 static void
9424 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
9425 {
9426 	dtrace_ecbdesc_t **ndesc;
9427 	size_t osize, nsize;
9428 
9429 	/*
9430 	 * We can't add to enablings after we've enabled them, or after we've
9431 	 * retained them.
9432 	 */
9433 	ASSERT(enab->dten_probegen == 0);
9434 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
9435 
9436 	if (enab->dten_ndesc < enab->dten_maxdesc) {
9437 		enab->dten_desc[enab->dten_ndesc++] = ecb;
9438 		return;
9439 	}
9440 
9441 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
9442 
9443 	if (enab->dten_maxdesc == 0) {
9444 		enab->dten_maxdesc = 1;
9445 	} else {
9446 		enab->dten_maxdesc <<= 1;
9447 	}
9448 
9449 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
9450 
9451 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
9452 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
9453 	bcopy(enab->dten_desc, ndesc, osize);
9454 	kmem_free(enab->dten_desc, osize);
9455 
9456 	enab->dten_desc = ndesc;
9457 	enab->dten_desc[enab->dten_ndesc++] = ecb;
9458 }
9459 
9460 static void
9461 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
9462     dtrace_probedesc_t *pd)
9463 {
9464 	dtrace_ecbdesc_t *new;
9465 	dtrace_predicate_t *pred;
9466 	dtrace_actdesc_t *act;
9467 
9468 	/*
9469 	 * We're going to create a new ECB description that matches the
9470 	 * specified ECB in every way, but has the specified probe description.
9471 	 */
9472 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
9473 
9474 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
9475 		dtrace_predicate_hold(pred);
9476 
9477 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
9478 		dtrace_actdesc_hold(act);
9479 
9480 	new->dted_action = ecb->dted_action;
9481 	new->dted_pred = ecb->dted_pred;
9482 	new->dted_probe = *pd;
9483 	new->dted_uarg = ecb->dted_uarg;
9484 
9485 	dtrace_enabling_add(enab, new);
9486 }
9487 
9488 static void
9489 dtrace_enabling_dump(dtrace_enabling_t *enab)
9490 {
9491 	int i;
9492 
9493 	for (i = 0; i < enab->dten_ndesc; i++) {
9494 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
9495 
9496 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
9497 		    desc->dtpd_provider, desc->dtpd_mod,
9498 		    desc->dtpd_func, desc->dtpd_name);
9499 	}
9500 }
9501 
9502 static void
9503 dtrace_enabling_destroy(dtrace_enabling_t *enab)
9504 {
9505 	int i;
9506 	dtrace_ecbdesc_t *ep;
9507 	dtrace_vstate_t *vstate = enab->dten_vstate;
9508 
9509 	ASSERT(MUTEX_HELD(&dtrace_lock));
9510 
9511 	for (i = 0; i < enab->dten_ndesc; i++) {
9512 		dtrace_actdesc_t *act, *next;
9513 		dtrace_predicate_t *pred;
9514 
9515 		ep = enab->dten_desc[i];
9516 
9517 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
9518 			dtrace_predicate_release(pred, vstate);
9519 
9520 		for (act = ep->dted_action; act != NULL; act = next) {
9521 			next = act->dtad_next;
9522 			dtrace_actdesc_release(act, vstate);
9523 		}
9524 
9525 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
9526 	}
9527 
9528 	kmem_free(enab->dten_desc,
9529 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
9530 
9531 	/*
9532 	 * If this was a retained enabling, decrement the dts_nretained count
9533 	 * and take it off of the dtrace_retained list.
9534 	 */
9535 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
9536 	    dtrace_retained == enab) {
9537 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9538 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
9539 		enab->dten_vstate->dtvs_state->dts_nretained--;
9540 	}
9541 
9542 	if (enab->dten_prev == NULL) {
9543 		if (dtrace_retained == enab) {
9544 			dtrace_retained = enab->dten_next;
9545 
9546 			if (dtrace_retained != NULL)
9547 				dtrace_retained->dten_prev = NULL;
9548 		}
9549 	} else {
9550 		ASSERT(enab != dtrace_retained);
9551 		ASSERT(dtrace_retained != NULL);
9552 		enab->dten_prev->dten_next = enab->dten_next;
9553 	}
9554 
9555 	if (enab->dten_next != NULL) {
9556 		ASSERT(dtrace_retained != NULL);
9557 		enab->dten_next->dten_prev = enab->dten_prev;
9558 	}
9559 
9560 	kmem_free(enab, sizeof (dtrace_enabling_t));
9561 }
9562 
9563 static int
9564 dtrace_enabling_retain(dtrace_enabling_t *enab)
9565 {
9566 	dtrace_state_t *state;
9567 
9568 	ASSERT(MUTEX_HELD(&dtrace_lock));
9569 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
9570 	ASSERT(enab->dten_vstate != NULL);
9571 
9572 	state = enab->dten_vstate->dtvs_state;
9573 	ASSERT(state != NULL);
9574 
9575 	/*
9576 	 * We only allow each state to retain dtrace_retain_max enablings.
9577 	 */
9578 	if (state->dts_nretained >= dtrace_retain_max)
9579 		return (ENOSPC);
9580 
9581 	state->dts_nretained++;
9582 
9583 	if (dtrace_retained == NULL) {
9584 		dtrace_retained = enab;
9585 		return (0);
9586 	}
9587 
9588 	enab->dten_next = dtrace_retained;
9589 	dtrace_retained->dten_prev = enab;
9590 	dtrace_retained = enab;
9591 
9592 	return (0);
9593 }
9594 
9595 static int
9596 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
9597     dtrace_probedesc_t *create)
9598 {
9599 	dtrace_enabling_t *new, *enab;
9600 	int found = 0, err = ENOENT;
9601 
9602 	ASSERT(MUTEX_HELD(&dtrace_lock));
9603 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
9604 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
9605 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
9606 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
9607 
9608 	new = dtrace_enabling_create(&state->dts_vstate);
9609 
9610 	/*
9611 	 * Iterate over all retained enablings, looking for enablings that
9612 	 * match the specified state.
9613 	 */
9614 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
9615 		int i;
9616 
9617 		/*
9618 		 * dtvs_state can only be NULL for helper enablings -- and
9619 		 * helper enablings can't be retained.
9620 		 */
9621 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9622 
9623 		if (enab->dten_vstate->dtvs_state != state)
9624 			continue;
9625 
9626 		/*
9627 		 * Now iterate over each probe description; we're looking for
9628 		 * an exact match to the specified probe description.
9629 		 */
9630 		for (i = 0; i < enab->dten_ndesc; i++) {
9631 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
9632 			dtrace_probedesc_t *pd = &ep->dted_probe;
9633 
9634 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
9635 				continue;
9636 
9637 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
9638 				continue;
9639 
9640 			if (strcmp(pd->dtpd_func, match->dtpd_func))
9641 				continue;
9642 
9643 			if (strcmp(pd->dtpd_name, match->dtpd_name))
9644 				continue;
9645 
9646 			/*
9647 			 * We have a winning probe!  Add it to our growing
9648 			 * enabling.
9649 			 */
9650 			found = 1;
9651 			dtrace_enabling_addlike(new, ep, create);
9652 		}
9653 	}
9654 
9655 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
9656 		dtrace_enabling_destroy(new);
9657 		return (err);
9658 	}
9659 
9660 	return (0);
9661 }
9662 
9663 static void
9664 dtrace_enabling_retract(dtrace_state_t *state)
9665 {
9666 	dtrace_enabling_t *enab, *next;
9667 
9668 	ASSERT(MUTEX_HELD(&dtrace_lock));
9669 
9670 	/*
9671 	 * Iterate over all retained enablings, destroy the enablings retained
9672 	 * for the specified state.
9673 	 */
9674 	for (enab = dtrace_retained; enab != NULL; enab = next) {
9675 		next = enab->dten_next;
9676 
9677 		/*
9678 		 * dtvs_state can only be NULL for helper enablings -- and
9679 		 * helper enablings can't be retained.
9680 		 */
9681 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9682 
9683 		if (enab->dten_vstate->dtvs_state == state) {
9684 			ASSERT(state->dts_nretained > 0);
9685 			dtrace_enabling_destroy(enab);
9686 		}
9687 	}
9688 
9689 	ASSERT(state->dts_nretained == 0);
9690 }
9691 
9692 static int
9693 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
9694 {
9695 	int i = 0;
9696 	int matched = 0;
9697 
9698 	ASSERT(MUTEX_HELD(&cpu_lock));
9699 	ASSERT(MUTEX_HELD(&dtrace_lock));
9700 
9701 	for (i = 0; i < enab->dten_ndesc; i++) {
9702 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
9703 
9704 		enab->dten_current = ep;
9705 		enab->dten_error = 0;
9706 
9707 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
9708 
9709 		if (enab->dten_error != 0) {
9710 			/*
9711 			 * If we get an error half-way through enabling the
9712 			 * probes, we kick out -- perhaps with some number of
9713 			 * them enabled.  Leaving enabled probes enabled may
9714 			 * be slightly confusing for user-level, but we expect
9715 			 * that no one will attempt to actually drive on in
9716 			 * the face of such errors.  If this is an anonymous
9717 			 * enabling (indicated with a NULL nmatched pointer),
9718 			 * we cmn_err() a message.  We aren't expecting to
9719 			 * get such an error -- such as it can exist at all,
9720 			 * it would be a result of corrupted DOF in the driver
9721 			 * properties.
9722 			 */
9723 			if (nmatched == NULL) {
9724 				cmn_err(CE_WARN, "dtrace_enabling_match() "
9725 				    "error on %p: %d", (void *)ep,
9726 				    enab->dten_error);
9727 			}
9728 
9729 			return (enab->dten_error);
9730 		}
9731 	}
9732 
9733 	enab->dten_probegen = dtrace_probegen;
9734 	if (nmatched != NULL)
9735 		*nmatched = matched;
9736 
9737 	return (0);
9738 }
9739 
9740 static void
9741 dtrace_enabling_matchall(void)
9742 {
9743 	dtrace_enabling_t *enab;
9744 
9745 	mutex_enter(&cpu_lock);
9746 	mutex_enter(&dtrace_lock);
9747 
9748 	/*
9749 	 * Because we can be called after dtrace_detach() has been called, we
9750 	 * cannot assert that there are retained enablings.  We can safely
9751 	 * load from dtrace_retained, however:  the taskq_destroy() at the
9752 	 * end of dtrace_detach() will block pending our completion.
9753 	 */
9754 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next)
9755 		(void) dtrace_enabling_match(enab, NULL);
9756 
9757 	mutex_exit(&dtrace_lock);
9758 	mutex_exit(&cpu_lock);
9759 }
9760 
9761 static int
9762 dtrace_enabling_matchstate(dtrace_state_t *state, int *nmatched)
9763 {
9764 	dtrace_enabling_t *enab;
9765 	int matched, total = 0, err;
9766 
9767 	ASSERT(MUTEX_HELD(&cpu_lock));
9768 	ASSERT(MUTEX_HELD(&dtrace_lock));
9769 
9770 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
9771 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9772 
9773 		if (enab->dten_vstate->dtvs_state != state)
9774 			continue;
9775 
9776 		if ((err = dtrace_enabling_match(enab, &matched)) != 0)
9777 			return (err);
9778 
9779 		total += matched;
9780 	}
9781 
9782 	if (nmatched != NULL)
9783 		*nmatched = total;
9784 
9785 	return (0);
9786 }
9787 
9788 /*
9789  * If an enabling is to be enabled without having matched probes (that is, if
9790  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
9791  * enabling must be _primed_ by creating an ECB for every ECB description.
9792  * This must be done to assure that we know the number of speculations, the
9793  * number of aggregations, the minimum buffer size needed, etc. before we
9794  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
9795  * enabling any probes, we create ECBs for every ECB decription, but with a
9796  * NULL probe -- which is exactly what this function does.
9797  */
9798 static void
9799 dtrace_enabling_prime(dtrace_state_t *state)
9800 {
9801 	dtrace_enabling_t *enab;
9802 	int i;
9803 
9804 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
9805 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9806 
9807 		if (enab->dten_vstate->dtvs_state != state)
9808 			continue;
9809 
9810 		/*
9811 		 * We don't want to prime an enabling more than once, lest
9812 		 * we allow a malicious user to induce resource exhaustion.
9813 		 * (The ECBs that result from priming an enabling aren't
9814 		 * leaked -- but they also aren't deallocated until the
9815 		 * consumer state is destroyed.)
9816 		 */
9817 		if (enab->dten_primed)
9818 			continue;
9819 
9820 		for (i = 0; i < enab->dten_ndesc; i++) {
9821 			enab->dten_current = enab->dten_desc[i];
9822 			(void) dtrace_probe_enable(NULL, enab);
9823 		}
9824 
9825 		enab->dten_primed = 1;
9826 	}
9827 }
9828 
9829 /*
9830  * Called to indicate that probes should be provided due to retained
9831  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
9832  * must take an initial lap through the enabling calling the dtps_provide()
9833  * entry point explicitly to allow for autocreated probes.
9834  */
9835 static void
9836 dtrace_enabling_provide(dtrace_provider_t *prv)
9837 {
9838 	int i, all = 0;
9839 	dtrace_probedesc_t desc;
9840 
9841 	ASSERT(MUTEX_HELD(&dtrace_lock));
9842 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
9843 
9844 	if (prv == NULL) {
9845 		all = 1;
9846 		prv = dtrace_provider;
9847 	}
9848 
9849 	do {
9850 		dtrace_enabling_t *enab = dtrace_retained;
9851 		void *parg = prv->dtpv_arg;
9852 
9853 		for (; enab != NULL; enab = enab->dten_next) {
9854 			for (i = 0; i < enab->dten_ndesc; i++) {
9855 				desc = enab->dten_desc[i]->dted_probe;
9856 				mutex_exit(&dtrace_lock);
9857 				prv->dtpv_pops.dtps_provide(parg, &desc);
9858 				mutex_enter(&dtrace_lock);
9859 			}
9860 		}
9861 	} while (all && (prv = prv->dtpv_next) != NULL);
9862 
9863 	mutex_exit(&dtrace_lock);
9864 	dtrace_probe_provide(NULL, all ? NULL : prv);
9865 	mutex_enter(&dtrace_lock);
9866 }
9867 
9868 /*
9869  * DTrace DOF Functions
9870  */
9871 /*ARGSUSED*/
9872 static void
9873 dtrace_dof_error(dof_hdr_t *dof, const char *str)
9874 {
9875 	if (dtrace_err_verbose)
9876 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
9877 
9878 #ifdef DTRACE_ERRDEBUG
9879 	dtrace_errdebug(str);
9880 #endif
9881 }
9882 
9883 /*
9884  * Create DOF out of a currently enabled state.  Right now, we only create
9885  * DOF containing the run-time options -- but this could be expanded to create
9886  * complete DOF representing the enabled state.
9887  */
9888 static dof_hdr_t *
9889 dtrace_dof_create(dtrace_state_t *state)
9890 {
9891 	dof_hdr_t *dof;
9892 	dof_sec_t *sec;
9893 	dof_optdesc_t *opt;
9894 	int i, len = sizeof (dof_hdr_t) +
9895 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
9896 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
9897 
9898 	ASSERT(MUTEX_HELD(&dtrace_lock));
9899 
9900 	dof = kmem_zalloc(len, KM_SLEEP);
9901 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
9902 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
9903 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
9904 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
9905 
9906 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
9907 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
9908 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION_1;
9909 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
9910 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
9911 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
9912 
9913 	dof->dofh_flags = 0;
9914 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
9915 	dof->dofh_secsize = sizeof (dof_sec_t);
9916 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
9917 	dof->dofh_secoff = sizeof (dof_hdr_t);
9918 	dof->dofh_loadsz = len;
9919 	dof->dofh_filesz = len;
9920 	dof->dofh_pad = 0;
9921 
9922 	/*
9923 	 * Fill in the option section header...
9924 	 */
9925 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
9926 	sec->dofs_type = DOF_SECT_OPTDESC;
9927 	sec->dofs_align = sizeof (uint64_t);
9928 	sec->dofs_flags = DOF_SECF_LOAD;
9929 	sec->dofs_entsize = sizeof (dof_optdesc_t);
9930 
9931 	opt = (dof_optdesc_t *)((uintptr_t)sec +
9932 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
9933 
9934 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
9935 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
9936 
9937 	for (i = 0; i < DTRACEOPT_MAX; i++) {
9938 		opt[i].dofo_option = i;
9939 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
9940 		opt[i].dofo_value = state->dts_options[i];
9941 	}
9942 
9943 	return (dof);
9944 }
9945 
9946 static dof_hdr_t *
9947 dtrace_dof_copyin(uintptr_t uarg, int *errp)
9948 {
9949 	dof_hdr_t hdr, *dof;
9950 
9951 	ASSERT(!MUTEX_HELD(&dtrace_lock));
9952 
9953 	/*
9954 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
9955 	 */
9956 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
9957 		dtrace_dof_error(NULL, "failed to copyin DOF header");
9958 		*errp = EFAULT;
9959 		return (NULL);
9960 	}
9961 
9962 	/*
9963 	 * Now we'll allocate the entire DOF and copy it in -- provided
9964 	 * that the length isn't outrageous.
9965 	 */
9966 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
9967 		dtrace_dof_error(&hdr, "load size exceeds maximum");
9968 		*errp = E2BIG;
9969 		return (NULL);
9970 	}
9971 
9972 	if (hdr.dofh_loadsz < sizeof (hdr)) {
9973 		dtrace_dof_error(&hdr, "invalid load size");
9974 		*errp = EINVAL;
9975 		return (NULL);
9976 	}
9977 
9978 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
9979 
9980 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
9981 		kmem_free(dof, hdr.dofh_loadsz);
9982 		*errp = EFAULT;
9983 		return (NULL);
9984 	}
9985 
9986 	return (dof);
9987 }
9988 
9989 static dof_hdr_t *
9990 dtrace_dof_property(const char *name)
9991 {
9992 	uchar_t *buf;
9993 	uint64_t loadsz;
9994 	unsigned int len, i;
9995 	dof_hdr_t *dof;
9996 
9997 	/*
9998 	 * Unfortunately, array of values in .conf files are always (and
9999 	 * only) interpreted to be integer arrays.  We must read our DOF
10000 	 * as an integer array, and then squeeze it into a byte array.
10001 	 */
10002 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
10003 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
10004 		return (NULL);
10005 
10006 	for (i = 0; i < len; i++)
10007 		buf[i] = (uchar_t)(((int *)buf)[i]);
10008 
10009 	if (len < sizeof (dof_hdr_t)) {
10010 		ddi_prop_free(buf);
10011 		dtrace_dof_error(NULL, "truncated header");
10012 		return (NULL);
10013 	}
10014 
10015 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
10016 		ddi_prop_free(buf);
10017 		dtrace_dof_error(NULL, "truncated DOF");
10018 		return (NULL);
10019 	}
10020 
10021 	if (loadsz >= dtrace_dof_maxsize) {
10022 		ddi_prop_free(buf);
10023 		dtrace_dof_error(NULL, "oversized DOF");
10024 		return (NULL);
10025 	}
10026 
10027 	dof = kmem_alloc(loadsz, KM_SLEEP);
10028 	bcopy(buf, dof, loadsz);
10029 	ddi_prop_free(buf);
10030 
10031 	return (dof);
10032 }
10033 
10034 static void
10035 dtrace_dof_destroy(dof_hdr_t *dof)
10036 {
10037 	kmem_free(dof, dof->dofh_loadsz);
10038 }
10039 
10040 /*
10041  * Return the dof_sec_t pointer corresponding to a given section index.  If the
10042  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
10043  * a type other than DOF_SECT_NONE is specified, the header is checked against
10044  * this type and NULL is returned if the types do not match.
10045  */
10046 static dof_sec_t *
10047 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
10048 {
10049 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
10050 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
10051 
10052 	if (i >= dof->dofh_secnum) {
10053 		dtrace_dof_error(dof, "referenced section index is invalid");
10054 		return (NULL);
10055 	}
10056 
10057 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
10058 		dtrace_dof_error(dof, "referenced section is not loadable");
10059 		return (NULL);
10060 	}
10061 
10062 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
10063 		dtrace_dof_error(dof, "referenced section is the wrong type");
10064 		return (NULL);
10065 	}
10066 
10067 	return (sec);
10068 }
10069 
10070 static dtrace_probedesc_t *
10071 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
10072 {
10073 	dof_probedesc_t *probe;
10074 	dof_sec_t *strtab;
10075 	uintptr_t daddr = (uintptr_t)dof;
10076 	uintptr_t str;
10077 	size_t size;
10078 
10079 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
10080 		dtrace_dof_error(dof, "invalid probe section");
10081 		return (NULL);
10082 	}
10083 
10084 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
10085 		dtrace_dof_error(dof, "bad alignment in probe description");
10086 		return (NULL);
10087 	}
10088 
10089 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
10090 		dtrace_dof_error(dof, "truncated probe description");
10091 		return (NULL);
10092 	}
10093 
10094 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
10095 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
10096 
10097 	if (strtab == NULL)
10098 		return (NULL);
10099 
10100 	str = daddr + strtab->dofs_offset;
10101 	size = strtab->dofs_size;
10102 
10103 	if (probe->dofp_provider >= strtab->dofs_size) {
10104 		dtrace_dof_error(dof, "corrupt probe provider");
10105 		return (NULL);
10106 	}
10107 
10108 	(void) strncpy(desc->dtpd_provider,
10109 	    (char *)(str + probe->dofp_provider),
10110 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
10111 
10112 	if (probe->dofp_mod >= strtab->dofs_size) {
10113 		dtrace_dof_error(dof, "corrupt probe module");
10114 		return (NULL);
10115 	}
10116 
10117 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
10118 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
10119 
10120 	if (probe->dofp_func >= strtab->dofs_size) {
10121 		dtrace_dof_error(dof, "corrupt probe function");
10122 		return (NULL);
10123 	}
10124 
10125 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
10126 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
10127 
10128 	if (probe->dofp_name >= strtab->dofs_size) {
10129 		dtrace_dof_error(dof, "corrupt probe name");
10130 		return (NULL);
10131 	}
10132 
10133 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
10134 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
10135 
10136 	return (desc);
10137 }
10138 
10139 static dtrace_difo_t *
10140 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10141     cred_t *cr)
10142 {
10143 	dtrace_difo_t *dp;
10144 	size_t ttl = 0;
10145 	dof_difohdr_t *dofd;
10146 	uintptr_t daddr = (uintptr_t)dof;
10147 	size_t max = dtrace_difo_maxsize;
10148 	int i, l, n;
10149 
10150 	static const struct {
10151 		int section;
10152 		int bufoffs;
10153 		int lenoffs;
10154 		int entsize;
10155 		int align;
10156 		const char *msg;
10157 	} difo[] = {
10158 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
10159 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
10160 		sizeof (dif_instr_t), "multiple DIF sections" },
10161 
10162 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
10163 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
10164 		sizeof (uint64_t), "multiple integer tables" },
10165 
10166 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
10167 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
10168 		sizeof (char), "multiple string tables" },
10169 
10170 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
10171 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
10172 		sizeof (uint_t), "multiple variable tables" },
10173 
10174 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
10175 	};
10176 
10177 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
10178 		dtrace_dof_error(dof, "invalid DIFO header section");
10179 		return (NULL);
10180 	}
10181 
10182 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
10183 		dtrace_dof_error(dof, "bad alignment in DIFO header");
10184 		return (NULL);
10185 	}
10186 
10187 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
10188 	    sec->dofs_size % sizeof (dof_secidx_t)) {
10189 		dtrace_dof_error(dof, "bad size in DIFO header");
10190 		return (NULL);
10191 	}
10192 
10193 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
10194 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
10195 
10196 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10197 	dp->dtdo_rtype = dofd->dofd_rtype;
10198 
10199 	for (l = 0; l < n; l++) {
10200 		dof_sec_t *subsec;
10201 		void **bufp;
10202 		uint32_t *lenp;
10203 
10204 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
10205 		    dofd->dofd_links[l])) == NULL)
10206 			goto err; /* invalid section link */
10207 
10208 		if (ttl + subsec->dofs_size > max) {
10209 			dtrace_dof_error(dof, "exceeds maximum size");
10210 			goto err;
10211 		}
10212 
10213 		ttl += subsec->dofs_size;
10214 
10215 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
10216 			if (subsec->dofs_type != difo[i].section)
10217 				continue;
10218 
10219 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
10220 				dtrace_dof_error(dof, "section not loaded");
10221 				goto err;
10222 			}
10223 
10224 			if (subsec->dofs_align != difo[i].align) {
10225 				dtrace_dof_error(dof, "bad alignment");
10226 				goto err;
10227 			}
10228 
10229 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
10230 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
10231 
10232 			if (*bufp != NULL) {
10233 				dtrace_dof_error(dof, difo[i].msg);
10234 				goto err;
10235 			}
10236 
10237 			if (difo[i].entsize != subsec->dofs_entsize) {
10238 				dtrace_dof_error(dof, "entry size mismatch");
10239 				goto err;
10240 			}
10241 
10242 			if (subsec->dofs_entsize != 0 &&
10243 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
10244 				dtrace_dof_error(dof, "corrupt entry size");
10245 				goto err;
10246 			}
10247 
10248 			*lenp = subsec->dofs_size;
10249 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
10250 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
10251 			    *bufp, subsec->dofs_size);
10252 
10253 			if (subsec->dofs_entsize != 0)
10254 				*lenp /= subsec->dofs_entsize;
10255 
10256 			break;
10257 		}
10258 
10259 		/*
10260 		 * If we encounter a loadable DIFO sub-section that is not
10261 		 * known to us, assume this is a broken program and fail.
10262 		 */
10263 		if (difo[i].section == DOF_SECT_NONE &&
10264 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
10265 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
10266 			goto err;
10267 		}
10268 	}
10269 
10270 	if (dp->dtdo_buf == NULL) {
10271 		/*
10272 		 * We can't have a DIF object without DIF text.
10273 		 */
10274 		dtrace_dof_error(dof, "missing DIF text");
10275 		goto err;
10276 	}
10277 
10278 	/*
10279 	 * Before we validate the DIF object, run through the variable table
10280 	 * looking for the strings -- if any of their size are under, we'll set
10281 	 * their size to be the system-wide default string size.  Note that
10282 	 * this should _not_ happen if the "strsize" option has been set --
10283 	 * in this case, the compiler should have set the size to reflect the
10284 	 * setting of the option.
10285 	 */
10286 	for (i = 0; i < dp->dtdo_varlen; i++) {
10287 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10288 		dtrace_diftype_t *t = &v->dtdv_type;
10289 
10290 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
10291 			continue;
10292 
10293 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
10294 			t->dtdt_size = dtrace_strsize_default;
10295 	}
10296 
10297 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
10298 		goto err;
10299 
10300 	dtrace_difo_init(dp, vstate);
10301 	return (dp);
10302 
10303 err:
10304 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10305 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10306 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10307 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10308 
10309 	kmem_free(dp, sizeof (dtrace_difo_t));
10310 	return (NULL);
10311 }
10312 
10313 static dtrace_predicate_t *
10314 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10315     cred_t *cr)
10316 {
10317 	dtrace_difo_t *dp;
10318 
10319 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
10320 		return (NULL);
10321 
10322 	return (dtrace_predicate_create(dp));
10323 }
10324 
10325 static dtrace_actdesc_t *
10326 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10327     cred_t *cr)
10328 {
10329 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
10330 	dof_actdesc_t *desc;
10331 	dof_sec_t *difosec;
10332 	size_t offs;
10333 	uintptr_t daddr = (uintptr_t)dof;
10334 	uint64_t arg;
10335 	dtrace_actkind_t kind;
10336 
10337 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
10338 		dtrace_dof_error(dof, "invalid action section");
10339 		return (NULL);
10340 	}
10341 
10342 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
10343 		dtrace_dof_error(dof, "truncated action description");
10344 		return (NULL);
10345 	}
10346 
10347 	if (sec->dofs_align != sizeof (uint64_t)) {
10348 		dtrace_dof_error(dof, "bad alignment in action description");
10349 		return (NULL);
10350 	}
10351 
10352 	if (sec->dofs_size < sec->dofs_entsize) {
10353 		dtrace_dof_error(dof, "section entry size exceeds total size");
10354 		return (NULL);
10355 	}
10356 
10357 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
10358 		dtrace_dof_error(dof, "bad entry size in action description");
10359 		return (NULL);
10360 	}
10361 
10362 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
10363 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
10364 		return (NULL);
10365 	}
10366 
10367 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
10368 		desc = (dof_actdesc_t *)(daddr +
10369 		    (uintptr_t)sec->dofs_offset + offs);
10370 		kind = (dtrace_actkind_t)desc->dofa_kind;
10371 
10372 		if (DTRACEACT_ISPRINTFLIKE(kind) &&
10373 		    (kind != DTRACEACT_PRINTA ||
10374 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
10375 			dof_sec_t *strtab;
10376 			char *str, *fmt;
10377 			uint64_t i;
10378 
10379 			/*
10380 			 * printf()-like actions must have a format string.
10381 			 */
10382 			if ((strtab = dtrace_dof_sect(dof,
10383 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
10384 				goto err;
10385 
10386 			str = (char *)((uintptr_t)dof +
10387 			    (uintptr_t)strtab->dofs_offset);
10388 
10389 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
10390 				if (str[i] == '\0')
10391 					break;
10392 			}
10393 
10394 			if (i >= strtab->dofs_size) {
10395 				dtrace_dof_error(dof, "bogus format string");
10396 				goto err;
10397 			}
10398 
10399 			if (i == desc->dofa_arg) {
10400 				dtrace_dof_error(dof, "empty format string");
10401 				goto err;
10402 			}
10403 
10404 			i -= desc->dofa_arg;
10405 			fmt = kmem_alloc(i + 1, KM_SLEEP);
10406 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
10407 			arg = (uint64_t)(uintptr_t)fmt;
10408 		} else {
10409 			if (kind == DTRACEACT_PRINTA) {
10410 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
10411 				arg = 0;
10412 			} else {
10413 				arg = desc->dofa_arg;
10414 			}
10415 		}
10416 
10417 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
10418 		    desc->dofa_uarg, arg);
10419 
10420 		if (last != NULL) {
10421 			last->dtad_next = act;
10422 		} else {
10423 			first = act;
10424 		}
10425 
10426 		last = act;
10427 
10428 		if (desc->dofa_difo == DOF_SECIDX_NONE)
10429 			continue;
10430 
10431 		if ((difosec = dtrace_dof_sect(dof,
10432 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
10433 			goto err;
10434 
10435 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
10436 
10437 		if (act->dtad_difo == NULL)
10438 			goto err;
10439 	}
10440 
10441 	ASSERT(first != NULL);
10442 	return (first);
10443 
10444 err:
10445 	for (act = first; act != NULL; act = next) {
10446 		next = act->dtad_next;
10447 		dtrace_actdesc_release(act, vstate);
10448 	}
10449 
10450 	return (NULL);
10451 }
10452 
10453 static dtrace_ecbdesc_t *
10454 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10455     cred_t *cr)
10456 {
10457 	dtrace_ecbdesc_t *ep;
10458 	dof_ecbdesc_t *ecb;
10459 	dtrace_probedesc_t *desc;
10460 	dtrace_predicate_t *pred = NULL;
10461 
10462 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
10463 		dtrace_dof_error(dof, "truncated ECB description");
10464 		return (NULL);
10465 	}
10466 
10467 	if (sec->dofs_align != sizeof (uint64_t)) {
10468 		dtrace_dof_error(dof, "bad alignment in ECB description");
10469 		return (NULL);
10470 	}
10471 
10472 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
10473 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
10474 
10475 	if (sec == NULL)
10476 		return (NULL);
10477 
10478 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
10479 	ep->dted_uarg = ecb->dofe_uarg;
10480 	desc = &ep->dted_probe;
10481 
10482 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
10483 		goto err;
10484 
10485 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
10486 		if ((sec = dtrace_dof_sect(dof,
10487 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
10488 			goto err;
10489 
10490 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
10491 			goto err;
10492 
10493 		ep->dted_pred.dtpdd_predicate = pred;
10494 	}
10495 
10496 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
10497 		if ((sec = dtrace_dof_sect(dof,
10498 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
10499 			goto err;
10500 
10501 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
10502 
10503 		if (ep->dted_action == NULL)
10504 			goto err;
10505 	}
10506 
10507 	return (ep);
10508 
10509 err:
10510 	if (pred != NULL)
10511 		dtrace_predicate_release(pred, vstate);
10512 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
10513 	return (NULL);
10514 }
10515 
10516 /*
10517  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
10518  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
10519  * site of any user SETX relocations to account for load object base address.
10520  * In the future, if we need other relocations, this function can be extended.
10521  */
10522 static int
10523 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
10524 {
10525 	uintptr_t daddr = (uintptr_t)dof;
10526 	dof_relohdr_t *dofr =
10527 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
10528 	dof_sec_t *ss, *rs, *ts;
10529 	dof_relodesc_t *r;
10530 	uint_t i, n;
10531 
10532 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
10533 	    sec->dofs_align != sizeof (dof_secidx_t)) {
10534 		dtrace_dof_error(dof, "invalid relocation header");
10535 		return (-1);
10536 	}
10537 
10538 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
10539 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
10540 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
10541 
10542 	if (ss == NULL || rs == NULL || ts == NULL)
10543 		return (-1); /* dtrace_dof_error() has been called already */
10544 
10545 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
10546 	    rs->dofs_align != sizeof (uint64_t)) {
10547 		dtrace_dof_error(dof, "invalid relocation section");
10548 		return (-1);
10549 	}
10550 
10551 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
10552 	n = rs->dofs_size / rs->dofs_entsize;
10553 
10554 	for (i = 0; i < n; i++) {
10555 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
10556 
10557 		switch (r->dofr_type) {
10558 		case DOF_RELO_NONE:
10559 			break;
10560 		case DOF_RELO_SETX:
10561 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
10562 			    sizeof (uint64_t) > ts->dofs_size) {
10563 				dtrace_dof_error(dof, "bad relocation offset");
10564 				return (-1);
10565 			}
10566 
10567 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
10568 				dtrace_dof_error(dof, "misaligned setx relo");
10569 				return (-1);
10570 			}
10571 
10572 			*(uint64_t *)taddr += ubase;
10573 			break;
10574 		default:
10575 			dtrace_dof_error(dof, "invalid relocation type");
10576 			return (-1);
10577 		}
10578 
10579 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
10580 	}
10581 
10582 	return (0);
10583 }
10584 
10585 /*
10586  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
10587  * header:  it should be at the front of a memory region that is at least
10588  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
10589  * size.  It need not be validated in any other way.
10590  */
10591 static int
10592 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
10593     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
10594 {
10595 	uint64_t len = dof->dofh_loadsz, seclen;
10596 	uintptr_t daddr = (uintptr_t)dof;
10597 	dtrace_ecbdesc_t *ep;
10598 	dtrace_enabling_t *enab;
10599 	uint_t i;
10600 
10601 	ASSERT(MUTEX_HELD(&dtrace_lock));
10602 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
10603 
10604 	/*
10605 	 * Check the DOF header identification bytes.  In addition to checking
10606 	 * valid settings, we also verify that unused bits/bytes are zeroed so
10607 	 * we can use them later without fear of regressing existing binaries.
10608 	 */
10609 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
10610 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
10611 		dtrace_dof_error(dof, "DOF magic string mismatch");
10612 		return (-1);
10613 	}
10614 
10615 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
10616 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
10617 		dtrace_dof_error(dof, "DOF has invalid data model");
10618 		return (-1);
10619 	}
10620 
10621 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
10622 		dtrace_dof_error(dof, "DOF encoding mismatch");
10623 		return (-1);
10624 	}
10625 
10626 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
10627 		dtrace_dof_error(dof, "DOF version mismatch");
10628 		return (-1);
10629 	}
10630 
10631 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
10632 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
10633 		return (-1);
10634 	}
10635 
10636 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
10637 		dtrace_dof_error(dof, "DOF uses too many integer registers");
10638 		return (-1);
10639 	}
10640 
10641 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
10642 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
10643 		return (-1);
10644 	}
10645 
10646 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
10647 		if (dof->dofh_ident[i] != 0) {
10648 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
10649 			return (-1);
10650 		}
10651 	}
10652 
10653 	if (dof->dofh_flags & ~DOF_FL_VALID) {
10654 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
10655 		return (-1);
10656 	}
10657 
10658 	if (dof->dofh_secsize == 0) {
10659 		dtrace_dof_error(dof, "zero section header size");
10660 		return (-1);
10661 	}
10662 
10663 	/*
10664 	 * Check that the section headers don't exceed the amount of DOF
10665 	 * data.  Note that we cast the section size and number of sections
10666 	 * to uint64_t's to prevent possible overflow in the multiplication.
10667 	 */
10668 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
10669 
10670 	if (dof->dofh_secoff > len || seclen > len ||
10671 	    dof->dofh_secoff + seclen > len) {
10672 		dtrace_dof_error(dof, "truncated section headers");
10673 		return (-1);
10674 	}
10675 
10676 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
10677 		dtrace_dof_error(dof, "misaligned section headers");
10678 		return (-1);
10679 	}
10680 
10681 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
10682 		dtrace_dof_error(dof, "misaligned section size");
10683 		return (-1);
10684 	}
10685 
10686 	/*
10687 	 * Take an initial pass through the section headers to be sure that
10688 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
10689 	 * set, do not permit sections relating to providers, probes, or args.
10690 	 */
10691 	for (i = 0; i < dof->dofh_secnum; i++) {
10692 		dof_sec_t *sec = (dof_sec_t *)(daddr +
10693 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
10694 
10695 		if (noprobes) {
10696 			switch (sec->dofs_type) {
10697 			case DOF_SECT_PROVIDER:
10698 			case DOF_SECT_PROBES:
10699 			case DOF_SECT_PRARGS:
10700 			case DOF_SECT_PROFFS:
10701 				dtrace_dof_error(dof, "illegal sections "
10702 				    "for enabling");
10703 				return (-1);
10704 			}
10705 		}
10706 
10707 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
10708 			continue; /* just ignore non-loadable sections */
10709 
10710 		if (sec->dofs_align & (sec->dofs_align - 1)) {
10711 			dtrace_dof_error(dof, "bad section alignment");
10712 			return (-1);
10713 		}
10714 
10715 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
10716 			dtrace_dof_error(dof, "misaligned section");
10717 			return (-1);
10718 		}
10719 
10720 		if (sec->dofs_offset > len || sec->dofs_size > len ||
10721 		    sec->dofs_offset + sec->dofs_size > len) {
10722 			dtrace_dof_error(dof, "corrupt section header");
10723 			return (-1);
10724 		}
10725 
10726 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
10727 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
10728 			dtrace_dof_error(dof, "non-terminating string table");
10729 			return (-1);
10730 		}
10731 	}
10732 
10733 	/*
10734 	 * Take a second pass through the sections and locate and perform any
10735 	 * relocations that are present.  We do this after the first pass to
10736 	 * be sure that all sections have had their headers validated.
10737 	 */
10738 	for (i = 0; i < dof->dofh_secnum; i++) {
10739 		dof_sec_t *sec = (dof_sec_t *)(daddr +
10740 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
10741 
10742 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
10743 			continue; /* skip sections that are not loadable */
10744 
10745 		switch (sec->dofs_type) {
10746 		case DOF_SECT_URELHDR:
10747 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
10748 				return (-1);
10749 			break;
10750 		}
10751 	}
10752 
10753 	if ((enab = *enabp) == NULL)
10754 		enab = *enabp = dtrace_enabling_create(vstate);
10755 
10756 	for (i = 0; i < dof->dofh_secnum; i++) {
10757 		dof_sec_t *sec = (dof_sec_t *)(daddr +
10758 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
10759 
10760 		if (sec->dofs_type != DOF_SECT_ECBDESC)
10761 			continue;
10762 
10763 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
10764 			dtrace_enabling_destroy(enab);
10765 			*enabp = NULL;
10766 			return (-1);
10767 		}
10768 
10769 		dtrace_enabling_add(enab, ep);
10770 	}
10771 
10772 	return (0);
10773 }
10774 
10775 /*
10776  * Process DOF for any options.  This routine assumes that the DOF has been
10777  * at least processed by dtrace_dof_slurp().
10778  */
10779 static int
10780 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
10781 {
10782 	int i, rval;
10783 	uint32_t entsize;
10784 	size_t offs;
10785 	dof_optdesc_t *desc;
10786 
10787 	for (i = 0; i < dof->dofh_secnum; i++) {
10788 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
10789 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
10790 
10791 		if (sec->dofs_type != DOF_SECT_OPTDESC)
10792 			continue;
10793 
10794 		if (sec->dofs_align != sizeof (uint64_t)) {
10795 			dtrace_dof_error(dof, "bad alignment in "
10796 			    "option description");
10797 			return (EINVAL);
10798 		}
10799 
10800 		if ((entsize = sec->dofs_entsize) == 0) {
10801 			dtrace_dof_error(dof, "zeroed option entry size");
10802 			return (EINVAL);
10803 		}
10804 
10805 		if (entsize < sizeof (dof_optdesc_t)) {
10806 			dtrace_dof_error(dof, "bad option entry size");
10807 			return (EINVAL);
10808 		}
10809 
10810 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
10811 			desc = (dof_optdesc_t *)((uintptr_t)dof +
10812 			    (uintptr_t)sec->dofs_offset + offs);
10813 
10814 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
10815 				dtrace_dof_error(dof, "non-zero option string");
10816 				return (EINVAL);
10817 			}
10818 
10819 			if (desc->dofo_value == DTRACEOPT_UNSET) {
10820 				dtrace_dof_error(dof, "unset option");
10821 				return (EINVAL);
10822 			}
10823 
10824 			if ((rval = dtrace_state_option(state,
10825 			    desc->dofo_option, desc->dofo_value)) != 0) {
10826 				dtrace_dof_error(dof, "rejected option");
10827 				return (rval);
10828 			}
10829 		}
10830 	}
10831 
10832 	return (0);
10833 }
10834 
10835 /*
10836  * DTrace Consumer State Functions
10837  */
10838 int
10839 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
10840 {
10841 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
10842 	void *base;
10843 	uintptr_t limit;
10844 	dtrace_dynvar_t *dvar, *next, *start;
10845 	int i;
10846 
10847 	ASSERT(MUTEX_HELD(&dtrace_lock));
10848 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
10849 
10850 	bzero(dstate, sizeof (dtrace_dstate_t));
10851 
10852 	if ((dstate->dtds_chunksize = chunksize) == 0)
10853 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
10854 
10855 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
10856 		size = min;
10857 
10858 	if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10859 		return (ENOMEM);
10860 
10861 	dstate->dtds_size = size;
10862 	dstate->dtds_base = base;
10863 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
10864 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
10865 
10866 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
10867 
10868 	if (hashsize != 1 && (hashsize & 1))
10869 		hashsize--;
10870 
10871 	dstate->dtds_hashsize = hashsize;
10872 	dstate->dtds_hash = dstate->dtds_base;
10873 
10874 	/*
10875 	 * Determine number of active CPUs.  Divide free list evenly among
10876 	 * active CPUs.
10877 	 */
10878 	start = (dtrace_dynvar_t *)
10879 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
10880 	limit = (uintptr_t)base + size;
10881 
10882 	maxper = (limit - (uintptr_t)start) / NCPU;
10883 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
10884 
10885 	for (i = 0; i < NCPU; i++) {
10886 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
10887 
10888 		/*
10889 		 * If we don't even have enough chunks to make it once through
10890 		 * NCPUs, we're just going to allocate everything to the first
10891 		 * CPU.  And if we're on the last CPU, we're going to allocate
10892 		 * whatever is left over.  In either case, we set the limit to
10893 		 * be the limit of the dynamic variable space.
10894 		 */
10895 		if (maxper == 0 || i == NCPU - 1) {
10896 			limit = (uintptr_t)base + size;
10897 			start = NULL;
10898 		} else {
10899 			limit = (uintptr_t)start + maxper;
10900 			start = (dtrace_dynvar_t *)limit;
10901 		}
10902 
10903 		ASSERT(limit <= (uintptr_t)base + size);
10904 
10905 		for (;;) {
10906 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
10907 			    dstate->dtds_chunksize);
10908 
10909 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
10910 				break;
10911 
10912 			dvar->dtdv_next = next;
10913 			dvar = next;
10914 		}
10915 
10916 		if (maxper == 0)
10917 			break;
10918 	}
10919 
10920 	return (0);
10921 }
10922 
10923 void
10924 dtrace_dstate_fini(dtrace_dstate_t *dstate)
10925 {
10926 	ASSERT(MUTEX_HELD(&cpu_lock));
10927 
10928 	if (dstate->dtds_base == NULL)
10929 		return;
10930 
10931 	kmem_free(dstate->dtds_base, dstate->dtds_size);
10932 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
10933 }
10934 
10935 static void
10936 dtrace_vstate_fini(dtrace_vstate_t *vstate)
10937 {
10938 	/*
10939 	 * Logical XOR, where are you?
10940 	 */
10941 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
10942 
10943 	if (vstate->dtvs_nglobals > 0) {
10944 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
10945 		    sizeof (dtrace_statvar_t *));
10946 	}
10947 
10948 	if (vstate->dtvs_ntlocals > 0) {
10949 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
10950 		    sizeof (dtrace_difv_t));
10951 	}
10952 
10953 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
10954 
10955 	if (vstate->dtvs_nlocals > 0) {
10956 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
10957 		    sizeof (dtrace_statvar_t *));
10958 	}
10959 }
10960 
10961 static void
10962 dtrace_state_clean(dtrace_state_t *state)
10963 {
10964 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
10965 		return;
10966 
10967 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
10968 	dtrace_speculation_clean(state);
10969 }
10970 
10971 static void
10972 dtrace_state_deadman(dtrace_state_t *state)
10973 {
10974 	hrtime_t now;
10975 
10976 	dtrace_sync();
10977 
10978 	now = dtrace_gethrtime();
10979 
10980 	if (state != dtrace_anon.dta_state &&
10981 	    now - state->dts_laststatus >= dtrace_deadman_user)
10982 		return;
10983 
10984 	/*
10985 	 * We must be sure that dts_alive never appears to be less than the
10986 	 * value upon entry to dtrace_state_deadman(), and because we lack a
10987 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
10988 	 * store INT64_MAX to it, followed by a memory barrier, followed by
10989 	 * the new value.  This assures that dts_alive never appears to be
10990 	 * less than its true value, regardless of the order in which the
10991 	 * stores to the underlying storage are issued.
10992 	 */
10993 	state->dts_alive = INT64_MAX;
10994 	dtrace_membar_producer();
10995 	state->dts_alive = now;
10996 }
10997 
10998 dtrace_state_t *
10999 dtrace_state_create(dev_t *devp, cred_t *cr)
11000 {
11001 	minor_t minor;
11002 	major_t major;
11003 	char c[30];
11004 	dtrace_state_t *state;
11005 	dtrace_optval_t *opt;
11006 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
11007 
11008 	ASSERT(MUTEX_HELD(&dtrace_lock));
11009 	ASSERT(MUTEX_HELD(&cpu_lock));
11010 
11011 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
11012 	    VM_BESTFIT | VM_SLEEP);
11013 
11014 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
11015 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
11016 		return (NULL);
11017 	}
11018 
11019 	state = ddi_get_soft_state(dtrace_softstate, minor);
11020 	state->dts_epid = DTRACE_EPIDNONE + 1;
11021 
11022 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
11023 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
11024 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
11025 
11026 	if (devp != NULL) {
11027 		major = getemajor(*devp);
11028 	} else {
11029 		major = ddi_driver_major(dtrace_devi);
11030 	}
11031 
11032 	state->dts_dev = makedevice(major, minor);
11033 
11034 	if (devp != NULL)
11035 		*devp = state->dts_dev;
11036 
11037 	/*
11038 	 * We allocate NCPU buffers.  On the one hand, this can be quite
11039 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
11040 	 * other hand, it saves an additional memory reference in the probe
11041 	 * path.
11042 	 */
11043 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
11044 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
11045 	state->dts_cleaner = CYCLIC_NONE;
11046 	state->dts_deadman = CYCLIC_NONE;
11047 	state->dts_vstate.dtvs_state = state;
11048 
11049 	for (i = 0; i < DTRACEOPT_MAX; i++)
11050 		state->dts_options[i] = DTRACEOPT_UNSET;
11051 
11052 	/*
11053 	 * Set the default options.
11054 	 */
11055 	opt = state->dts_options;
11056 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
11057 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
11058 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
11059 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
11060 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
11061 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
11062 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
11063 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
11064 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
11065 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
11066 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
11067 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
11068 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
11069 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
11070 
11071 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
11072 
11073 	/*
11074 	 * Set up the credentials for this instantiation.
11075 	 */
11076 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
11077 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
11078 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
11079 	} else {
11080 		state->dts_cred.dcr_uid = crgetuid(cr);
11081 		state->dts_cred.dcr_gid = crgetgid(cr);
11082 
11083 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
11084 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
11085 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
11086 		}
11087 
11088 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) &&
11089 		    PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
11090 			state->dts_cred.dcr_visible |= DTRACE_CRV_ALLPROC;
11091 			state->dts_cred.dcr_action |=
11092 			    DTRACE_CRA_PROC_DESTRUCTIVE;
11093 		}
11094 
11095 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
11096 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
11097 			    DTRACE_CRV_ALLPROC;
11098 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
11099 			    DTRACE_CRA_PROC;
11100 
11101 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
11102 				state->dts_cred.dcr_action |=
11103 				    DTRACE_CRA_PROC_DESTRUCTIVE;
11104 		}
11105 	}
11106 
11107 	return (state);
11108 }
11109 
11110 static int
11111 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
11112 {
11113 	dtrace_optval_t *opt = state->dts_options, size;
11114 	processorid_t cpu;
11115 	int flags = 0, rval;
11116 
11117 	ASSERT(MUTEX_HELD(&dtrace_lock));
11118 	ASSERT(MUTEX_HELD(&cpu_lock));
11119 	ASSERT(which < DTRACEOPT_MAX);
11120 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
11121 	    (state == dtrace_anon.dta_state &&
11122 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
11123 
11124 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
11125 		return (0);
11126 
11127 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
11128 		cpu = opt[DTRACEOPT_CPU];
11129 
11130 	if (which == DTRACEOPT_SPECSIZE)
11131 		flags |= DTRACEBUF_NOSWITCH;
11132 
11133 	if (which == DTRACEOPT_BUFSIZE) {
11134 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
11135 			flags |= DTRACEBUF_RING;
11136 
11137 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
11138 			flags |= DTRACEBUF_FILL;
11139 
11140 		flags |= DTRACEBUF_INACTIVE;
11141 	}
11142 
11143 	for (size = opt[which]; size >= sizeof (uint64_t); size >>= 1) {
11144 		/*
11145 		 * The size must be 8-byte aligned.  If the size is not 8-byte
11146 		 * aligned, drop it down by the difference.
11147 		 */
11148 		if (size & (sizeof (uint64_t) - 1))
11149 			size -= size & (sizeof (uint64_t) - 1);
11150 
11151 		if (size < state->dts_reserve) {
11152 			/*
11153 			 * Buffers always must be large enough to accommodate
11154 			 * their prereserved space.  We return E2BIG instead
11155 			 * of ENOMEM in this case to allow for user-level
11156 			 * software to differentiate the cases.
11157 			 */
11158 			return (E2BIG);
11159 		}
11160 
11161 		rval = dtrace_buffer_alloc(buf, size, flags, cpu);
11162 
11163 		if (rval != ENOMEM) {
11164 			opt[which] = size;
11165 			return (rval);
11166 		}
11167 
11168 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
11169 			return (rval);
11170 	}
11171 
11172 	return (ENOMEM);
11173 }
11174 
11175 static int
11176 dtrace_state_buffers(dtrace_state_t *state)
11177 {
11178 	dtrace_speculation_t *spec = state->dts_speculations;
11179 	int rval, i;
11180 
11181 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
11182 	    DTRACEOPT_BUFSIZE)) != 0)
11183 		return (rval);
11184 
11185 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
11186 	    DTRACEOPT_AGGSIZE)) != 0)
11187 		return (rval);
11188 
11189 	for (i = 0; i < state->dts_nspeculations; i++) {
11190 		if ((rval = dtrace_state_buffer(state,
11191 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
11192 			return (rval);
11193 	}
11194 
11195 	return (0);
11196 }
11197 
11198 static void
11199 dtrace_state_prereserve(dtrace_state_t *state)
11200 {
11201 	dtrace_ecb_t *ecb;
11202 	dtrace_probe_t *probe;
11203 
11204 	state->dts_reserve = 0;
11205 
11206 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
11207 		return;
11208 
11209 	/*
11210 	 * If our buffer policy is a "fill" buffer policy, we need to set the
11211 	 * prereserved space to be the space required by the END probes.
11212 	 */
11213 	probe = dtrace_probes[dtrace_probeid_end - 1];
11214 	ASSERT(probe != NULL);
11215 
11216 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
11217 		if (ecb->dte_state != state)
11218 			continue;
11219 
11220 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
11221 	}
11222 }
11223 
11224 static int
11225 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
11226 {
11227 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
11228 	dtrace_speculation_t *spec;
11229 	dtrace_buffer_t *buf;
11230 	cyc_handler_t hdlr;
11231 	cyc_time_t when;
11232 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
11233 	dtrace_icookie_t cookie;
11234 
11235 	mutex_enter(&cpu_lock);
11236 	mutex_enter(&dtrace_lock);
11237 
11238 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
11239 		rval = EBUSY;
11240 		goto out;
11241 	}
11242 
11243 	/*
11244 	 * Before we can perform any checks, we must prime all of the
11245 	 * retained enablings that correspond to this state.
11246 	 */
11247 	dtrace_enabling_prime(state);
11248 
11249 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
11250 		rval = EACCES;
11251 		goto out;
11252 	}
11253 
11254 	dtrace_state_prereserve(state);
11255 
11256 	/*
11257 	 * Now we want to do is try to allocate our speculations.
11258 	 * We do not automatically resize the number of speculations; if
11259 	 * this fails, we will fail the operation.
11260 	 */
11261 	nspec = opt[DTRACEOPT_NSPEC];
11262 	ASSERT(nspec != DTRACEOPT_UNSET);
11263 
11264 	if (nspec > INT_MAX) {
11265 		rval = ENOMEM;
11266 		goto out;
11267 	}
11268 
11269 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
11270 
11271 	if (spec == NULL) {
11272 		rval = ENOMEM;
11273 		goto out;
11274 	}
11275 
11276 	state->dts_speculations = spec;
11277 	state->dts_nspeculations = (int)nspec;
11278 
11279 	for (i = 0; i < nspec; i++) {
11280 		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
11281 			rval = ENOMEM;
11282 			goto err;
11283 		}
11284 
11285 		spec[i].dtsp_buffer = buf;
11286 	}
11287 
11288 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
11289 		if (dtrace_anon.dta_state == NULL) {
11290 			rval = ENOENT;
11291 			goto out;
11292 		}
11293 
11294 		if (state->dts_necbs != 0) {
11295 			rval = EALREADY;
11296 			goto out;
11297 		}
11298 
11299 		state->dts_anon = dtrace_anon_grab();
11300 		ASSERT(state->dts_anon != NULL);
11301 		state = state->dts_anon;
11302 
11303 		/*
11304 		 * We want "grabanon" to be set in the grabbed state, so we'll
11305 		 * copy that option value from the grabbing state into the
11306 		 * grabbed state.
11307 		 */
11308 		state->dts_options[DTRACEOPT_GRABANON] =
11309 		    opt[DTRACEOPT_GRABANON];
11310 
11311 		*cpu = dtrace_anon.dta_beganon;
11312 
11313 		/*
11314 		 * If the anonymous state is active (as it almost certainly
11315 		 * is if the anonymous enabling ultimately matched anything),
11316 		 * we don't allow any further option processing -- but we
11317 		 * don't return failure.
11318 		 */
11319 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11320 			goto out;
11321 	}
11322 
11323 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
11324 	    opt[DTRACEOPT_AGGSIZE] != 0) {
11325 		if (state->dts_aggregations == NULL) {
11326 			/*
11327 			 * We're not going to create an aggregation buffer
11328 			 * because we don't have any ECBs that contain
11329 			 * aggregations -- set this option to 0.
11330 			 */
11331 			opt[DTRACEOPT_AGGSIZE] = 0;
11332 		} else {
11333 			/*
11334 			 * If we have an aggregation buffer, we must also have
11335 			 * a buffer to use as scratch.
11336 			 */
11337 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
11338 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
11339 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
11340 			}
11341 		}
11342 	}
11343 
11344 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
11345 	    opt[DTRACEOPT_SPECSIZE] != 0) {
11346 		if (!state->dts_speculates) {
11347 			/*
11348 			 * We're not going to create speculation buffers
11349 			 * because we don't have any ECBs that actually
11350 			 * speculate -- set the speculation size to 0.
11351 			 */
11352 			opt[DTRACEOPT_SPECSIZE] = 0;
11353 		}
11354 	}
11355 
11356 	/*
11357 	 * The bare minimum size for any buffer that we're actually going to
11358 	 * do anything to is sizeof (uint64_t).
11359 	 */
11360 	sz = sizeof (uint64_t);
11361 
11362 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
11363 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
11364 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
11365 		/*
11366 		 * A buffer size has been explicitly set to 0 (or to a size
11367 		 * that will be adjusted to 0) and we need the space -- we
11368 		 * need to return failure.  We return ENOSPC to differentiate
11369 		 * it from failing to allocate a buffer due to failure to meet
11370 		 * the reserve (for which we return E2BIG).
11371 		 */
11372 		rval = ENOSPC;
11373 		goto out;
11374 	}
11375 
11376 	if ((rval = dtrace_state_buffers(state)) != 0)
11377 		goto err;
11378 
11379 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
11380 		sz = dtrace_dstate_defsize;
11381 
11382 	do {
11383 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
11384 
11385 		if (rval == 0)
11386 			break;
11387 
11388 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
11389 			goto err;
11390 	} while (sz >>= 1);
11391 
11392 	opt[DTRACEOPT_DYNVARSIZE] = sz;
11393 
11394 	if (rval != 0)
11395 		goto err;
11396 
11397 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
11398 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
11399 
11400 	if (opt[DTRACEOPT_CLEANRATE] == 0)
11401 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
11402 
11403 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
11404 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
11405 
11406 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
11407 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
11408 
11409 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
11410 	hdlr.cyh_arg = state;
11411 	hdlr.cyh_level = CY_LOW_LEVEL;
11412 
11413 	when.cyt_when = 0;
11414 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
11415 
11416 	state->dts_cleaner = cyclic_add(&hdlr, &when);
11417 
11418 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
11419 	hdlr.cyh_arg = state;
11420 	hdlr.cyh_level = CY_LOW_LEVEL;
11421 
11422 	when.cyt_when = 0;
11423 	when.cyt_interval = dtrace_deadman_interval;
11424 
11425 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
11426 	state->dts_deadman = cyclic_add(&hdlr, &when);
11427 
11428 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
11429 
11430 	/*
11431 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
11432 	 * interrupts here both to record the CPU on which we fired the BEGIN
11433 	 * probe (the data from this CPU will be processed first at user
11434 	 * level) and to manually activate the buffer for this CPU.
11435 	 */
11436 	cookie = dtrace_interrupt_disable();
11437 	*cpu = CPU->cpu_id;
11438 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
11439 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
11440 
11441 	dtrace_probe(dtrace_probeid_begin,
11442 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
11443 	dtrace_interrupt_enable(cookie);
11444 	/*
11445 	 * We may have had an exit action from a BEGIN probe; only change our
11446 	 * state to ACTIVE if we're still in WARMUP.
11447 	 */
11448 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
11449 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
11450 
11451 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
11452 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
11453 
11454 	/*
11455 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
11456 	 * want each CPU to transition its principal buffer out of the
11457 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
11458 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
11459 	 * atomically transition from processing none of a state's ECBs to
11460 	 * processing all of them.
11461 	 */
11462 	dtrace_xcall(DTRACE_CPUALL,
11463 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
11464 	goto out;
11465 
11466 err:
11467 	dtrace_buffer_free(state->dts_buffer);
11468 	dtrace_buffer_free(state->dts_aggbuffer);
11469 
11470 	if ((nspec = state->dts_nspeculations) == 0) {
11471 		ASSERT(state->dts_speculations == NULL);
11472 		goto out;
11473 	}
11474 
11475 	spec = state->dts_speculations;
11476 	ASSERT(spec != NULL);
11477 
11478 	for (i = 0; i < state->dts_nspeculations; i++) {
11479 		if ((buf = spec[i].dtsp_buffer) == NULL)
11480 			break;
11481 
11482 		dtrace_buffer_free(buf);
11483 		kmem_free(buf, bufsize);
11484 	}
11485 
11486 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
11487 	state->dts_nspeculations = 0;
11488 	state->dts_speculations = NULL;
11489 
11490 out:
11491 	mutex_exit(&dtrace_lock);
11492 	mutex_exit(&cpu_lock);
11493 
11494 	return (rval);
11495 }
11496 
11497 static int
11498 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
11499 {
11500 	dtrace_icookie_t cookie;
11501 
11502 	ASSERT(MUTEX_HELD(&dtrace_lock));
11503 
11504 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
11505 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
11506 		return (EINVAL);
11507 
11508 	/*
11509 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
11510 	 * to be sure that every CPU has seen it.  See below for the details
11511 	 * on why this is done.
11512 	 */
11513 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
11514 	dtrace_sync();
11515 
11516 	/*
11517 	 * By this point, it is impossible for any CPU to be still processing
11518 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
11519 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
11520 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
11521 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
11522 	 * iff we're in the END probe.
11523 	 */
11524 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
11525 	dtrace_sync();
11526 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
11527 
11528 	/*
11529 	 * Finally, we can release the reserve and call the END probe.  We
11530 	 * disable interrupts across calling the END probe to allow us to
11531 	 * return the CPU on which we actually called the END probe.  This
11532 	 * allows user-land to be sure that this CPU's principal buffer is
11533 	 * processed last.
11534 	 */
11535 	state->dts_reserve = 0;
11536 
11537 	cookie = dtrace_interrupt_disable();
11538 	*cpu = CPU->cpu_id;
11539 	dtrace_probe(dtrace_probeid_end,
11540 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
11541 	dtrace_interrupt_enable(cookie);
11542 
11543 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
11544 	dtrace_sync();
11545 
11546 	return (0);
11547 }
11548 
11549 static int
11550 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
11551     dtrace_optval_t val)
11552 {
11553 	ASSERT(MUTEX_HELD(&dtrace_lock));
11554 
11555 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11556 		return (EBUSY);
11557 
11558 	if (option >= DTRACEOPT_MAX)
11559 		return (EINVAL);
11560 
11561 	if (option != DTRACEOPT_CPU && val < 0)
11562 		return (EINVAL);
11563 
11564 	switch (option) {
11565 	case DTRACEOPT_DESTRUCTIVE:
11566 		if (dtrace_destructive_disallow)
11567 			return (EACCES);
11568 
11569 		state->dts_cred.dcr_destructive = 1;
11570 		break;
11571 
11572 	case DTRACEOPT_BUFSIZE:
11573 	case DTRACEOPT_DYNVARSIZE:
11574 	case DTRACEOPT_AGGSIZE:
11575 	case DTRACEOPT_SPECSIZE:
11576 	case DTRACEOPT_STRSIZE:
11577 		if (val < 0)
11578 			return (EINVAL);
11579 
11580 		if (val >= LONG_MAX) {
11581 			/*
11582 			 * If this is an otherwise negative value, set it to
11583 			 * the highest multiple of 128m less than LONG_MAX.
11584 			 * Technically, we're adjusting the size without
11585 			 * regard to the buffer resizing policy, but in fact,
11586 			 * this has no effect -- if we set the buffer size to
11587 			 * ~LONG_MAX and the buffer policy is ultimately set to
11588 			 * be "manual", the buffer allocation is guaranteed to
11589 			 * fail, if only because the allocation requires two
11590 			 * buffers.  (We set the the size to the highest
11591 			 * multiple of 128m because it ensures that the size
11592 			 * will remain a multiple of a megabyte when
11593 			 * repeatedly halved -- all the way down to 15m.)
11594 			 */
11595 			val = LONG_MAX - (1 << 27) + 1;
11596 		}
11597 	}
11598 
11599 	state->dts_options[option] = val;
11600 
11601 	return (0);
11602 }
11603 
11604 static void
11605 dtrace_state_destroy(dtrace_state_t *state)
11606 {
11607 	dtrace_ecb_t *ecb;
11608 	dtrace_vstate_t *vstate = &state->dts_vstate;
11609 	minor_t minor = getminor(state->dts_dev);
11610 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
11611 	dtrace_speculation_t *spec = state->dts_speculations;
11612 	int nspec = state->dts_nspeculations;
11613 	uint32_t match;
11614 
11615 	ASSERT(MUTEX_HELD(&dtrace_lock));
11616 	ASSERT(MUTEX_HELD(&cpu_lock));
11617 
11618 	/*
11619 	 * First, retract any retained enablings for this state.
11620 	 */
11621 	dtrace_enabling_retract(state);
11622 	ASSERT(state->dts_nretained == 0);
11623 
11624 	/*
11625 	 * Now we need to disable and destroy any enabled probes.  Because any
11626 	 * DTRACE_PRIV_KERNEL probes may actually be slowing our progress
11627 	 * (especially if they're all enabled), we take two passes through
11628 	 * the ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes,
11629 	 * and in the second we disable whatever is left over.
11630 	 */
11631 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
11632 		for (i = 0; i < state->dts_necbs; i++) {
11633 			if ((ecb = state->dts_ecbs[i]) == NULL)
11634 				continue;
11635 
11636 			if (match && ecb->dte_probe != NULL) {
11637 				dtrace_probe_t *probe = ecb->dte_probe;
11638 				dtrace_provider_t *prov = probe->dtpr_provider;
11639 
11640 				if (!(prov->dtpv_priv.dtpp_flags & match))
11641 					continue;
11642 			}
11643 
11644 			dtrace_ecb_disable(ecb);
11645 			dtrace_ecb_destroy(ecb);
11646 		}
11647 
11648 		if (!match)
11649 			break;
11650 	}
11651 
11652 	/*
11653 	 * Before we free the buffers, perform one more sync to assure that
11654 	 * every CPU is out of probe context.
11655 	 */
11656 	dtrace_sync();
11657 
11658 	dtrace_buffer_free(state->dts_buffer);
11659 	dtrace_buffer_free(state->dts_aggbuffer);
11660 
11661 	for (i = 0; i < nspec; i++)
11662 		dtrace_buffer_free(spec[i].dtsp_buffer);
11663 
11664 	if (state->dts_cleaner != CYCLIC_NONE)
11665 		cyclic_remove(state->dts_cleaner);
11666 
11667 	if (state->dts_deadman != CYCLIC_NONE)
11668 		cyclic_remove(state->dts_deadman);
11669 
11670 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
11671 	dtrace_vstate_fini(vstate);
11672 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
11673 
11674 	if (state->dts_aggregations != NULL) {
11675 #ifdef DEBUG
11676 		for (i = 0; i < state->dts_naggregations; i++)
11677 			ASSERT(state->dts_aggregations[i] == NULL);
11678 #endif
11679 		ASSERT(state->dts_naggregations > 0);
11680 		kmem_free(state->dts_aggregations,
11681 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
11682 	}
11683 
11684 	kmem_free(state->dts_buffer, bufsize);
11685 	kmem_free(state->dts_aggbuffer, bufsize);
11686 
11687 	for (i = 0; i < nspec; i++)
11688 		kmem_free(spec[i].dtsp_buffer, bufsize);
11689 
11690 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
11691 
11692 	dtrace_format_destroy(state);
11693 
11694 	vmem_destroy(state->dts_aggid_arena);
11695 	ddi_soft_state_free(dtrace_softstate, minor);
11696 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
11697 }
11698 
11699 /*
11700  * DTrace Anonymous Enabling Functions
11701  */
11702 static dtrace_state_t *
11703 dtrace_anon_grab(void)
11704 {
11705 	dtrace_state_t *state;
11706 
11707 	ASSERT(MUTEX_HELD(&dtrace_lock));
11708 
11709 	if ((state = dtrace_anon.dta_state) == NULL) {
11710 		ASSERT(dtrace_anon.dta_enabling == NULL);
11711 		return (NULL);
11712 	}
11713 
11714 	ASSERT(dtrace_anon.dta_enabling != NULL);
11715 	ASSERT(dtrace_retained != NULL);
11716 
11717 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
11718 	dtrace_anon.dta_enabling = NULL;
11719 	dtrace_anon.dta_state = NULL;
11720 
11721 	return (state);
11722 }
11723 
11724 static void
11725 dtrace_anon_property(void)
11726 {
11727 	int i, rv;
11728 	dtrace_state_t *state;
11729 	dof_hdr_t *dof;
11730 	char c[32];		/* enough for "dof-data-" + digits */
11731 
11732 	ASSERT(MUTEX_HELD(&dtrace_lock));
11733 	ASSERT(MUTEX_HELD(&cpu_lock));
11734 
11735 	for (i = 0; ; i++) {
11736 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
11737 
11738 		dtrace_err_verbose = 1;
11739 
11740 		if ((dof = dtrace_dof_property(c)) == NULL) {
11741 			dtrace_err_verbose = 0;
11742 			break;
11743 		}
11744 
11745 		/*
11746 		 * We want to create anonymous state, so we need to transition
11747 		 * the kernel debugger to indicate that DTrace is active.  If
11748 		 * this fails (e.g. because the debugger has modified text in
11749 		 * some way), we won't continue with the processing.
11750 		 */
11751 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
11752 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
11753 			    "enabling ignored.");
11754 			dtrace_dof_destroy(dof);
11755 			break;
11756 		}
11757 
11758 		/*
11759 		 * If we haven't allocated an anonymous state, we'll do so now.
11760 		 */
11761 		if ((state = dtrace_anon.dta_state) == NULL) {
11762 			state = dtrace_state_create(NULL, NULL);
11763 			dtrace_anon.dta_state = state;
11764 
11765 			if (state == NULL) {
11766 				/*
11767 				 * This basically shouldn't happen:  the only
11768 				 * failure mode from dtrace_state_create() is a
11769 				 * failure of ddi_soft_state_zalloc() that
11770 				 * itself should never happen.  Still, the
11771 				 * interface allows for a failure mode, and
11772 				 * we want to fail as gracefully as possible:
11773 				 * we'll emit an error message and cease
11774 				 * processing anonymous state in this case.
11775 				 */
11776 				cmn_err(CE_WARN, "failed to create "
11777 				    "anonymous state");
11778 				dtrace_dof_destroy(dof);
11779 				break;
11780 			}
11781 		}
11782 
11783 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
11784 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
11785 
11786 		if (rv == 0)
11787 			rv = dtrace_dof_options(dof, state);
11788 
11789 		dtrace_err_verbose = 0;
11790 		dtrace_dof_destroy(dof);
11791 
11792 		if (rv != 0) {
11793 			/*
11794 			 * This is malformed DOF; chuck any anonymous state
11795 			 * that we created.
11796 			 */
11797 			ASSERT(dtrace_anon.dta_enabling == NULL);
11798 			dtrace_state_destroy(state);
11799 			dtrace_anon.dta_state = NULL;
11800 			break;
11801 		}
11802 
11803 		ASSERT(dtrace_anon.dta_enabling != NULL);
11804 	}
11805 
11806 	if (dtrace_anon.dta_enabling != NULL) {
11807 		int rval;
11808 
11809 		/*
11810 		 * dtrace_enabling_retain() can only fail because we are
11811 		 * trying to retain more enablings than are allowed -- but
11812 		 * we only have one anonymous enabling, and we are guaranteed
11813 		 * to be allowed at least one retained enabling; we assert
11814 		 * that dtrace_enabling_retain() returns success.
11815 		 */
11816 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
11817 		ASSERT(rval == 0);
11818 
11819 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
11820 	}
11821 }
11822 
11823 /*
11824  * DTrace Helper Functions
11825  */
11826 static void
11827 dtrace_helper_trace(dtrace_helper_action_t *helper,
11828     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
11829 {
11830 	uint32_t size, next, nnext, i;
11831 	dtrace_helptrace_t *ent;
11832 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
11833 
11834 	if (!dtrace_helptrace_enabled)
11835 		return;
11836 
11837 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
11838 
11839 	/*
11840 	 * What would a tracing framework be without its own tracing
11841 	 * framework?  (Well, a hell of a lot simpler, for starters...)
11842 	 */
11843 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
11844 	    sizeof (uint64_t) - sizeof (uint64_t);
11845 
11846 	/*
11847 	 * Iterate until we can allocate a slot in the trace buffer.
11848 	 */
11849 	do {
11850 		next = dtrace_helptrace_next;
11851 
11852 		if (next + size < dtrace_helptrace_bufsize) {
11853 			nnext = next + size;
11854 		} else {
11855 			nnext = size;
11856 		}
11857 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
11858 
11859 	/*
11860 	 * We have our slot; fill it in.
11861 	 */
11862 	if (nnext == size)
11863 		next = 0;
11864 
11865 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
11866 	ent->dtht_helper = helper;
11867 	ent->dtht_where = where;
11868 	ent->dtht_nlocals = vstate->dtvs_nlocals;
11869 
11870 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
11871 	    mstate->dtms_fltoffs : -1;
11872 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
11873 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
11874 
11875 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
11876 		dtrace_statvar_t *svar;
11877 
11878 		if ((svar = vstate->dtvs_locals[i]) == NULL)
11879 			continue;
11880 
11881 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
11882 		ent->dtht_locals[i] =
11883 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
11884 	}
11885 }
11886 
11887 static uint64_t
11888 dtrace_helper(int which, dtrace_mstate_t *mstate,
11889     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
11890 {
11891 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
11892 	uint64_t sarg0 = mstate->dtms_arg[0];
11893 	uint64_t sarg1 = mstate->dtms_arg[1];
11894 	uint64_t rval;
11895 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
11896 	dtrace_helper_action_t *helper;
11897 	dtrace_vstate_t *vstate;
11898 	dtrace_difo_t *pred;
11899 	int i, trace = dtrace_helptrace_enabled;
11900 
11901 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
11902 
11903 	if (helpers == NULL)
11904 		return (0);
11905 
11906 	if ((helper = helpers->dthps_actions[which]) == NULL)
11907 		return (0);
11908 
11909 	vstate = &helpers->dthps_vstate;
11910 	mstate->dtms_arg[0] = arg0;
11911 	mstate->dtms_arg[1] = arg1;
11912 
11913 	/*
11914 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
11915 	 * we'll call the corresponding actions.  Note that the below calls
11916 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
11917 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
11918 	 * the stored DIF offset with its own (which is the desired behavior).
11919 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
11920 	 * from machine state; this is okay, too.
11921 	 */
11922 	for (; helper != NULL; helper = helper->dthp_next) {
11923 		if ((pred = helper->dthp_predicate) != NULL) {
11924 			if (trace)
11925 				dtrace_helper_trace(helper, mstate, vstate, 0);
11926 
11927 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
11928 				goto next;
11929 
11930 			if (*flags & CPU_DTRACE_FAULT)
11931 				goto err;
11932 		}
11933 
11934 		for (i = 0; i < helper->dthp_nactions; i++) {
11935 			if (trace)
11936 				dtrace_helper_trace(helper,
11937 				    mstate, vstate, i + 1);
11938 
11939 			rval = dtrace_dif_emulate(helper->dthp_actions[i],
11940 			    mstate, vstate, state);
11941 
11942 			if (*flags & CPU_DTRACE_FAULT)
11943 				goto err;
11944 		}
11945 
11946 next:
11947 		if (trace)
11948 			dtrace_helper_trace(helper, mstate, vstate,
11949 			    DTRACE_HELPTRACE_NEXT);
11950 	}
11951 
11952 	if (trace)
11953 		dtrace_helper_trace(helper, mstate, vstate,
11954 		    DTRACE_HELPTRACE_DONE);
11955 
11956 	/*
11957 	 * Restore the arg0 that we saved upon entry.
11958 	 */
11959 	mstate->dtms_arg[0] = sarg0;
11960 	mstate->dtms_arg[1] = sarg1;
11961 
11962 	return (rval);
11963 
11964 err:
11965 	if (trace)
11966 		dtrace_helper_trace(helper, mstate, vstate,
11967 		    DTRACE_HELPTRACE_ERR);
11968 
11969 	/*
11970 	 * Restore the arg0 that we saved upon entry.
11971 	 */
11972 	mstate->dtms_arg[0] = sarg0;
11973 	mstate->dtms_arg[1] = sarg1;
11974 
11975 	return (NULL);
11976 }
11977 
11978 static void
11979 dtrace_helper_destroy(dtrace_helper_action_t *helper, dtrace_vstate_t *vstate)
11980 {
11981 	int i;
11982 
11983 	if (helper->dthp_predicate != NULL)
11984 		dtrace_difo_release(helper->dthp_predicate, vstate);
11985 
11986 	for (i = 0; i < helper->dthp_nactions; i++) {
11987 		ASSERT(helper->dthp_actions[i] != NULL);
11988 		dtrace_difo_release(helper->dthp_actions[i], vstate);
11989 	}
11990 
11991 	kmem_free(helper->dthp_actions,
11992 	    helper->dthp_nactions * sizeof (dtrace_difo_t *));
11993 	kmem_free(helper, sizeof (dtrace_helper_action_t));
11994 }
11995 
11996 static int
11997 dtrace_helper_destroygen(int gen)
11998 {
11999 	dtrace_helpers_t *help = curproc->p_dtrace_helpers;
12000 	dtrace_vstate_t *vstate;
12001 	int i;
12002 
12003 	ASSERT(MUTEX_HELD(&dtrace_lock));
12004 
12005 	if (help == NULL || gen > help->dthps_generation)
12006 		return (EINVAL);
12007 
12008 	vstate = &help->dthps_vstate;
12009 
12010 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
12011 		dtrace_helper_action_t *last = NULL, *h, *next;
12012 
12013 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
12014 			next = h->dthp_next;
12015 
12016 			if (h->dthp_generation == gen) {
12017 				if (last != NULL) {
12018 					last->dthp_next = next;
12019 				} else {
12020 					help->dthps_actions[i] = next;
12021 				}
12022 
12023 				dtrace_helper_destroy(h, vstate);
12024 			} else {
12025 				last = h;
12026 			}
12027 		}
12028 	}
12029 
12030 	return (0);
12031 }
12032 
12033 static int
12034 dtrace_helper_validate(dtrace_helper_action_t *helper)
12035 {
12036 	int err = 0, i;
12037 	dtrace_difo_t *dp;
12038 
12039 	if ((dp = helper->dthp_predicate) != NULL)
12040 		err += dtrace_difo_validate_helper(dp);
12041 
12042 	for (i = 0; i < helper->dthp_nactions; i++)
12043 		err += dtrace_difo_validate_helper(helper->dthp_actions[i]);
12044 
12045 	return (err == 0);
12046 }
12047 
12048 static int
12049 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
12050 {
12051 	dtrace_helpers_t *help;
12052 	dtrace_helper_action_t *helper, *last;
12053 	dtrace_actdesc_t *act;
12054 	dtrace_vstate_t *vstate;
12055 	dtrace_predicate_t *pred;
12056 	int count = 0, nactions = 0, i;
12057 
12058 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
12059 		return (EINVAL);
12060 
12061 	help = curproc->p_dtrace_helpers;
12062 	last = help->dthps_actions[which];
12063 	vstate = &help->dthps_vstate;
12064 
12065 	for (count = 0; last != NULL; last = last->dthp_next) {
12066 		count++;
12067 		if (last->dthp_next == NULL)
12068 			break;
12069 	}
12070 
12071 	/*
12072 	 * If we already have dtrace_helper_actions_max helper actions for this
12073 	 * helper action type, we'll refuse to add a new one.
12074 	 */
12075 	if (count >= dtrace_helper_actions_max)
12076 		return (ENOSPC);
12077 
12078 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
12079 	helper->dthp_generation = help->dthps_generation;
12080 
12081 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
12082 		ASSERT(pred->dtp_difo != NULL);
12083 		dtrace_difo_hold(pred->dtp_difo);
12084 		helper->dthp_predicate = pred->dtp_difo;
12085 	}
12086 
12087 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
12088 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
12089 			goto err;
12090 
12091 		if (act->dtad_difo == NULL)
12092 			goto err;
12093 
12094 		nactions++;
12095 	}
12096 
12097 	helper->dthp_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
12098 	    (helper->dthp_nactions = nactions), KM_SLEEP);
12099 
12100 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
12101 		dtrace_difo_hold(act->dtad_difo);
12102 		helper->dthp_actions[i++] = act->dtad_difo;
12103 	}
12104 
12105 	if (!dtrace_helper_validate(helper))
12106 		goto err;
12107 
12108 	if (last == NULL) {
12109 		help->dthps_actions[which] = helper;
12110 	} else {
12111 		last->dthp_next = helper;
12112 	}
12113 
12114 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
12115 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
12116 		dtrace_helptrace_next = 0;
12117 	}
12118 
12119 	return (0);
12120 err:
12121 	dtrace_helper_destroy(helper, vstate);
12122 	return (EINVAL);
12123 }
12124 
12125 static void
12126 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
12127     dof_helper_t *dofhp)
12128 {
12129 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
12130 
12131 	mutex_enter(&dtrace_meta_lock);
12132 	mutex_enter(&dtrace_lock);
12133 
12134 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
12135 		/*
12136 		 * If the dtrace module is loaded but not attached, or if
12137 		 * there aren't isn't a meta provider registered to deal with
12138 		 * these provider descriptions, we need to postpone creating
12139 		 * the actual providers until later.
12140 		 */
12141 
12142 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
12143 		    dtrace_deferred_pid != help) {
12144 			help->dthps_deferred = 1;
12145 			help->dthps_pid = p->p_pid;
12146 			help->dthps_next = dtrace_deferred_pid;
12147 			help->dthps_prev = NULL;
12148 			if (dtrace_deferred_pid != NULL)
12149 				dtrace_deferred_pid->dthps_prev = help;
12150 			dtrace_deferred_pid = help;
12151 		}
12152 
12153 		mutex_exit(&dtrace_lock);
12154 
12155 	} else if (dofhp != NULL) {
12156 		/*
12157 		 * If the dtrace module is loaded and we have a particular
12158 		 * helper provider description, pass that off to the
12159 		 * meta provider.
12160 		 */
12161 
12162 		mutex_exit(&dtrace_lock);
12163 
12164 		dtrace_helper_provide(dofhp, p->p_pid);
12165 
12166 	} else {
12167 		/*
12168 		 * Otherwise, just pass all the helper provider descriptions
12169 		 * off to the meta provider.
12170 		 */
12171 
12172 		int i;
12173 		mutex_exit(&dtrace_lock);
12174 
12175 		for (i = 0; i < help->dthps_nprovs; i++) {
12176 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
12177 			    p->p_pid);
12178 		}
12179 	}
12180 
12181 	mutex_exit(&dtrace_meta_lock);
12182 }
12183 
12184 static int
12185 dtrace_helper_provider_add(dof_helper_t *dofhp)
12186 {
12187 	dtrace_helpers_t *help;
12188 	dtrace_helper_provider_t *hprov, **tmp_provs;
12189 	uint_t tmp_nprovs, i;
12190 
12191 	help = curproc->p_dtrace_helpers;
12192 	ASSERT(help != NULL);
12193 
12194 	/*
12195 	 * If we already have dtrace_helper_providers_max helper providers,
12196 	 * we're refuse to add a new one.
12197 	 */
12198 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
12199 		return (ENOSPC);
12200 
12201 	/*
12202 	 * Check to make sure this isn't a duplicate.
12203 	 */
12204 	for (i = 0; i < help->dthps_nprovs; i++) {
12205 		if (dofhp->dofhp_addr ==
12206 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
12207 			return (EALREADY);
12208 	}
12209 
12210 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
12211 	hprov->dthp_prov = *dofhp;
12212 	hprov->dthp_ref = 1;
12213 
12214 	tmp_nprovs = help->dthps_nprovs;
12215 	tmp_provs = help->dthps_provs;
12216 	help->dthps_nprovs++;
12217 	help->dthps_provs = kmem_zalloc(help->dthps_nprovs *
12218 	    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
12219 
12220 	help->dthps_provs[tmp_nprovs] = hprov;
12221 	if (tmp_provs != NULL) {
12222 		bcopy(tmp_provs, help->dthps_provs, tmp_nprovs *
12223 		    sizeof (dtrace_helper_provider_t *));
12224 		kmem_free(tmp_provs, tmp_nprovs *
12225 		    sizeof (dtrace_helper_provider_t *));
12226 	}
12227 
12228 	return (0);
12229 }
12230 
12231 static void
12232 dtrace_helper_provider_remove(dtrace_helper_provider_t *hprov)
12233 {
12234 	mutex_enter(&dtrace_lock);
12235 
12236 	if (--hprov->dthp_ref == 0) {
12237 		dof_hdr_t *dof;
12238 		mutex_exit(&dtrace_lock);
12239 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
12240 		dtrace_dof_destroy(dof);
12241 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
12242 	} else {
12243 		mutex_exit(&dtrace_lock);
12244 	}
12245 }
12246 
12247 static int
12248 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
12249 {
12250 	uintptr_t daddr = (uintptr_t)dof;
12251 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec;
12252 	dof_provider_t *provider;
12253 	dof_probe_t *probe;
12254 	uint8_t *arg;
12255 	char *strtab, *typestr;
12256 	dof_stridx_t typeidx;
12257 	size_t typesz;
12258 	uint_t nprobes, j, k;
12259 
12260 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
12261 
12262 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
12263 		dtrace_dof_error(dof, "misaligned section offset");
12264 		return (-1);
12265 	}
12266 
12267 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
12268 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
12269 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
12270 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
12271 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
12272 
12273 	if (str_sec == NULL || prb_sec == NULL ||
12274 	    arg_sec == NULL || off_sec == NULL)
12275 		return (-1);
12276 
12277 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
12278 
12279 	if (provider->dofpv_name >= str_sec->dofs_size ||
12280 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
12281 		dtrace_dof_error(dof, "invalid provider name");
12282 		return (-1);
12283 	}
12284 
12285 	if (prb_sec->dofs_entsize == 0 ||
12286 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
12287 		dtrace_dof_error(dof, "invalid entry size");
12288 		return (-1);
12289 	}
12290 
12291 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
12292 		dtrace_dof_error(dof, "misaligned entry size");
12293 		return (-1);
12294 	}
12295 
12296 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
12297 		dtrace_dof_error(dof, "invalid entry size");
12298 		return (-1);
12299 	}
12300 
12301 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
12302 		dtrace_dof_error(dof, "misaligned section offset");
12303 		return (-1);
12304 	}
12305 
12306 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
12307 		dtrace_dof_error(dof, "invalid entry size");
12308 		return (-1);
12309 	}
12310 
12311 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
12312 
12313 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
12314 
12315 	/*
12316 	 * Take a pass through the probes to check for errors.
12317 	 */
12318 	for (j = 0; j < nprobes; j++) {
12319 		probe = (dof_probe_t *)(uintptr_t)(daddr +
12320 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
12321 
12322 		if (probe->dofpr_func >= str_sec->dofs_size) {
12323 			dtrace_dof_error(dof, "invalid function name");
12324 			return (-1);
12325 		}
12326 
12327 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
12328 			dtrace_dof_error(dof, "function name too long");
12329 			return (-1);
12330 		}
12331 
12332 		if (probe->dofpr_name >= str_sec->dofs_size ||
12333 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
12334 			dtrace_dof_error(dof, "invalid probe name");
12335 			return (-1);
12336 		}
12337 
12338 
12339 		if (probe->dofpr_offidx + probe->dofpr_noffs <
12340 		    probe->dofpr_offidx ||
12341 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
12342 		    off_sec->dofs_entsize > off_sec->dofs_size) {
12343 			dtrace_dof_error(dof, "invalid probe offset");
12344 			return (-1);
12345 		}
12346 
12347 		if (probe->dofpr_argidx + probe->dofpr_xargc <
12348 		    probe->dofpr_argidx ||
12349 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
12350 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
12351 			dtrace_dof_error(dof, "invalid args");
12352 			return (-1);
12353 		}
12354 
12355 		typeidx = probe->dofpr_nargv;
12356 		typestr = strtab + probe->dofpr_nargv;
12357 		for (k = 0; k < probe->dofpr_nargc; k++) {
12358 			if (typeidx >= str_sec->dofs_size) {
12359 				dtrace_dof_error(dof, "bad "
12360 				    "native argument type");
12361 				return (-1);
12362 			}
12363 
12364 			typesz = strlen(typestr) + 1;
12365 			if (typesz > DTRACE_ARGTYPELEN) {
12366 				dtrace_dof_error(dof, "native "
12367 				    "argument type too long");
12368 				return (-1);
12369 			}
12370 			typeidx += typesz;
12371 			typestr += typesz;
12372 		}
12373 
12374 		typeidx = probe->dofpr_xargv;
12375 		typestr = strtab + probe->dofpr_xargv;
12376 		for (k = 0; k < probe->dofpr_xargc; k++) {
12377 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
12378 				dtrace_dof_error(dof, "bad "
12379 				    "native argument index");
12380 				return (-1);
12381 			}
12382 
12383 			if (typeidx >= str_sec->dofs_size) {
12384 				dtrace_dof_error(dof, "bad "
12385 				    "translated argument type");
12386 				return (-1);
12387 			}
12388 
12389 			typesz = strlen(typestr) + 1;
12390 			if (typesz > DTRACE_ARGTYPELEN) {
12391 				dtrace_dof_error(dof, "translated argument "
12392 				    "type too long");
12393 				return (-1);
12394 			}
12395 
12396 			typeidx += typesz;
12397 			typestr += typesz;
12398 		}
12399 	}
12400 
12401 	return (0);
12402 }
12403 
12404 static int
12405 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
12406 {
12407 	dtrace_helpers_t *help;
12408 	dtrace_vstate_t *vstate;
12409 	dtrace_enabling_t *enab = NULL;
12410 	int i, gen, rv, nhelpers = 0, destroy = 1;
12411 
12412 	ASSERT(MUTEX_HELD(&dtrace_lock));
12413 
12414 	if ((help = curproc->p_dtrace_helpers) == NULL)
12415 		help = dtrace_helpers_create(curproc);
12416 
12417 	vstate = &help->dthps_vstate;
12418 
12419 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
12420 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
12421 		dtrace_dof_destroy(dof);
12422 		return (rv);
12423 	}
12424 
12425 	/*
12426 	 * Now we need to walk through the ECB descriptions in the enabling.
12427 	 */
12428 	for (i = 0; i < enab->dten_ndesc; i++) {
12429 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12430 		dtrace_probedesc_t *desc = &ep->dted_probe;
12431 
12432 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
12433 			continue;
12434 
12435 		if (strcmp(desc->dtpd_mod, "helper") != 0)
12436 			continue;
12437 
12438 		if (strcmp(desc->dtpd_func, "ustack") != 0)
12439 			continue;
12440 
12441 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
12442 		    ep)) != 0) {
12443 			/*
12444 			 * Adding this helper action failed -- we are now going
12445 			 * to rip out the entire generation and return failure.
12446 			 */
12447 			(void) dtrace_helper_destroygen(help->dthps_generation);
12448 			dtrace_enabling_destroy(enab);
12449 			dtrace_dof_destroy(dof);
12450 			dtrace_err = rv;
12451 			return (-1);
12452 		}
12453 
12454 		nhelpers++;
12455 	}
12456 
12457 	if (nhelpers < enab->dten_ndesc)
12458 		dtrace_dof_error(dof, "unmatched helpers");
12459 
12460 	if (dhp != NULL) {
12461 		uintptr_t daddr = (uintptr_t)dof;
12462 		int err = 0, count = 0;
12463 
12464 		/*
12465 		 * Look for helper probes.
12466 		 */
12467 		for (i = 0; i < dof->dofh_secnum; i++) {
12468 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
12469 			    dof->dofh_secoff + i * dof->dofh_secsize);
12470 
12471 			if (sec->dofs_type != DOF_SECT_PROVIDER)
12472 				continue;
12473 
12474 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
12475 				err = 1;
12476 				break;
12477 			}
12478 
12479 			count++;
12480 		}
12481 
12482 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
12483 		if (err == 0 && count > 0 &&
12484 		    dtrace_helper_provider_add(dhp) == 0)
12485 			destroy = 0;
12486 		else
12487 			dhp = NULL;
12488 	}
12489 
12490 	gen = help->dthps_generation++;
12491 	dtrace_enabling_destroy(enab);
12492 
12493 	if (dhp != NULL) {
12494 		mutex_exit(&dtrace_lock);
12495 		dtrace_helper_provider_register(curproc, help, dhp);
12496 		mutex_enter(&dtrace_lock);
12497 	}
12498 
12499 	if (destroy)
12500 		dtrace_dof_destroy(dof);
12501 
12502 	return (gen);
12503 }
12504 
12505 static dtrace_helpers_t *
12506 dtrace_helpers_create(proc_t *p)
12507 {
12508 	dtrace_helpers_t *help;
12509 
12510 	ASSERT(MUTEX_HELD(&dtrace_lock));
12511 	ASSERT(p->p_dtrace_helpers == NULL);
12512 
12513 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
12514 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
12515 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
12516 
12517 	p->p_dtrace_helpers = help;
12518 	dtrace_helpers++;
12519 
12520 	return (help);
12521 }
12522 
12523 static void
12524 dtrace_helpers_destroy(void)
12525 {
12526 	dtrace_helpers_t *help;
12527 	dtrace_vstate_t *vstate;
12528 	proc_t *p = curproc;
12529 	int i;
12530 
12531 	mutex_enter(&dtrace_lock);
12532 
12533 	ASSERT(p->p_dtrace_helpers != NULL);
12534 	ASSERT(dtrace_helpers > 0);
12535 
12536 	help = p->p_dtrace_helpers;
12537 	vstate = &help->dthps_vstate;
12538 
12539 	/*
12540 	 * We're now going to lose the help from this process.
12541 	 */
12542 	p->p_dtrace_helpers = NULL;
12543 	dtrace_sync();
12544 
12545 	/*
12546 	 * Destory the helper actions.
12547 	 */
12548 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
12549 		dtrace_helper_action_t *h, *next;
12550 
12551 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
12552 			next = h->dthp_next;
12553 			dtrace_helper_destroy(h, vstate);
12554 			h = next;
12555 		}
12556 	}
12557 
12558 	mutex_exit(&dtrace_lock);
12559 
12560 	/*
12561 	 * Destroy the helper providers.
12562 	 */
12563 	if (help->dthps_nprovs > 0) {
12564 		mutex_enter(&dtrace_meta_lock);
12565 		if (dtrace_meta_pid != NULL) {
12566 			ASSERT(dtrace_deferred_pid == NULL);
12567 
12568 			for (i = 0; i < help->dthps_nprovs; i++) {
12569 				dtrace_helper_remove(
12570 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
12571 			}
12572 		} else {
12573 			mutex_enter(&dtrace_lock);
12574 			ASSERT(help->dthps_deferred == 0 ||
12575 			    help->dthps_next != NULL ||
12576 			    help->dthps_prev != NULL ||
12577 			    help == dtrace_deferred_pid);
12578 
12579 			/*
12580 			 * Remove the helper from the deferred list.
12581 			 */
12582 			if (help->dthps_next != NULL)
12583 				help->dthps_next->dthps_prev = help->dthps_prev;
12584 			if (help->dthps_prev != NULL)
12585 				help->dthps_prev->dthps_next = help->dthps_next;
12586 			if (dtrace_deferred_pid == help) {
12587 				dtrace_deferred_pid = help->dthps_next;
12588 				ASSERT(help->dthps_prev == NULL);
12589 			}
12590 
12591 			mutex_exit(&dtrace_lock);
12592 		}
12593 
12594 		mutex_exit(&dtrace_meta_lock);
12595 
12596 		for (i = 0; i < help->dthps_nprovs; i++) {
12597 			dtrace_helper_provider_remove(help->dthps_provs[i]);
12598 		}
12599 
12600 		kmem_free(help->dthps_provs, help->dthps_nprovs *
12601 		    sizeof (dtrace_helper_provider_t *));
12602 	}
12603 
12604 	mutex_enter(&dtrace_lock);
12605 
12606 	dtrace_vstate_fini(&help->dthps_vstate);
12607 	kmem_free(help->dthps_actions,
12608 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
12609 	kmem_free(help, sizeof (dtrace_helpers_t));
12610 
12611 	--dtrace_helpers;
12612 	mutex_exit(&dtrace_lock);
12613 }
12614 
12615 static void
12616 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
12617 {
12618 	dtrace_helpers_t *help, *newhelp;
12619 	dtrace_helper_action_t *helper, *new, *last;
12620 	dtrace_difo_t *dp;
12621 	dtrace_vstate_t *vstate;
12622 	int i, j, sz, hasprovs = 0;
12623 
12624 	mutex_enter(&dtrace_lock);
12625 	ASSERT(from->p_dtrace_helpers != NULL);
12626 	ASSERT(dtrace_helpers > 0);
12627 
12628 	help = from->p_dtrace_helpers;
12629 	newhelp = dtrace_helpers_create(to);
12630 	ASSERT(to->p_dtrace_helpers != NULL);
12631 
12632 	newhelp->dthps_generation = help->dthps_generation;
12633 	vstate = &newhelp->dthps_vstate;
12634 
12635 	/*
12636 	 * Duplicate the helper actions.
12637 	 */
12638 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
12639 		if ((helper = help->dthps_actions[i]) == NULL)
12640 			continue;
12641 
12642 		for (last = NULL; helper != NULL; helper = helper->dthp_next) {
12643 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
12644 			    KM_SLEEP);
12645 			new->dthp_generation = helper->dthp_generation;
12646 
12647 			if ((dp = helper->dthp_predicate) != NULL) {
12648 				dp = dtrace_difo_duplicate(dp, vstate);
12649 				new->dthp_predicate = dp;
12650 			}
12651 
12652 			new->dthp_nactions = helper->dthp_nactions;
12653 			sz = sizeof (dtrace_difo_t *) * new->dthp_nactions;
12654 			new->dthp_actions = kmem_alloc(sz, KM_SLEEP);
12655 
12656 			for (j = 0; j < new->dthp_nactions; j++) {
12657 				dtrace_difo_t *dp = helper->dthp_actions[j];
12658 
12659 				ASSERT(dp != NULL);
12660 				dp = dtrace_difo_duplicate(dp, vstate);
12661 				new->dthp_actions[j] = dp;
12662 			}
12663 
12664 			if (last != NULL) {
12665 				last->dthp_next = new;
12666 			} else {
12667 				newhelp->dthps_actions[i] = new;
12668 			}
12669 
12670 			last = new;
12671 		}
12672 	}
12673 
12674 	/*
12675 	 * Duplicate the helper providers and register them with the
12676 	 * DTrace framework.
12677 	 */
12678 	if (help->dthps_nprovs > 0) {
12679 		newhelp->dthps_nprovs = help->dthps_nprovs;
12680 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
12681 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
12682 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
12683 			newhelp->dthps_provs[i] = help->dthps_provs[i];
12684 			newhelp->dthps_provs[i]->dthp_ref++;
12685 		}
12686 
12687 		hasprovs = 1;
12688 	}
12689 
12690 	mutex_exit(&dtrace_lock);
12691 
12692 	if (hasprovs)
12693 		dtrace_helper_provider_register(to, newhelp, NULL);
12694 }
12695 
12696 /*
12697  * DTrace Hook Functions
12698  */
12699 static void
12700 dtrace_module_loaded(struct modctl *ctl)
12701 {
12702 	dtrace_provider_t *prv;
12703 
12704 	mutex_enter(&dtrace_provider_lock);
12705 	mutex_enter(&mod_lock);
12706 
12707 	ASSERT(ctl->mod_busy);
12708 
12709 	/*
12710 	 * We're going to call each providers per-module provide operation
12711 	 * specifying only this module.
12712 	 */
12713 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
12714 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
12715 
12716 	mutex_exit(&mod_lock);
12717 	mutex_exit(&dtrace_provider_lock);
12718 
12719 	/*
12720 	 * If we have any retained enablings, we need to match against them.
12721 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
12722 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
12723 	 * module.  (In particular, this happens when loading scheduling
12724 	 * classes.)  So if we have any retained enablings, we need to dispatch
12725 	 * our task queue to do the match for us.
12726 	 */
12727 	mutex_enter(&dtrace_lock);
12728 
12729 	if (dtrace_retained == NULL) {
12730 		mutex_exit(&dtrace_lock);
12731 		return;
12732 	}
12733 
12734 	(void) taskq_dispatch(dtrace_taskq,
12735 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
12736 
12737 	mutex_exit(&dtrace_lock);
12738 
12739 	/*
12740 	 * And now, for a little heuristic sleaze:  in general, we want to
12741 	 * match modules as soon as they load.  However, we cannot guarantee
12742 	 * this, because it would lead us to the lock ordering violation
12743 	 * outlined above.  The common case, of course, is that cpu_lock is
12744 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
12745 	 * long enough for the task queue to do its work.  If it's not, it's
12746 	 * not a serious problem -- it just means that the module that we
12747 	 * just loaded may not be immediately instrumentable.
12748 	 */
12749 	delay(1);
12750 }
12751 
12752 static void
12753 dtrace_module_unloaded(struct modctl *ctl)
12754 {
12755 	dtrace_probe_t template, *probe, *first, *next;
12756 	dtrace_provider_t *prov;
12757 
12758 	template.dtpr_mod = ctl->mod_modname;
12759 
12760 	mutex_enter(&dtrace_provider_lock);
12761 	mutex_enter(&mod_lock);
12762 	mutex_enter(&dtrace_lock);
12763 
12764 	if (dtrace_bymod == NULL) {
12765 		/*
12766 		 * The DTrace module is loaded (obviously) but not attached;
12767 		 * we don't have any work to do.
12768 		 */
12769 		mutex_exit(&dtrace_provider_lock);
12770 		mutex_exit(&mod_lock);
12771 		mutex_exit(&dtrace_lock);
12772 		return;
12773 	}
12774 
12775 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
12776 	    probe != NULL; probe = probe->dtpr_nextmod) {
12777 		if (probe->dtpr_ecb != NULL) {
12778 			mutex_exit(&dtrace_provider_lock);
12779 			mutex_exit(&mod_lock);
12780 			mutex_exit(&dtrace_lock);
12781 
12782 			/*
12783 			 * This shouldn't _actually_ be possible -- we're
12784 			 * unloading a module that has an enabled probe in it.
12785 			 * (It's normally up to the provider to make sure that
12786 			 * this can't happen.)  However, because dtps_enable()
12787 			 * doesn't have a failure mode, there can be an
12788 			 * enable/unload race.  Upshot:  we don't want to
12789 			 * assert, but we're not going to disable the
12790 			 * probe, either.
12791 			 */
12792 			if (dtrace_err_verbose) {
12793 				cmn_err(CE_WARN, "unloaded module '%s' had "
12794 				    "enabled probes", ctl->mod_modname);
12795 			}
12796 
12797 			return;
12798 		}
12799 	}
12800 
12801 	probe = first;
12802 
12803 	for (first = NULL; probe != NULL; probe = next) {
12804 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
12805 
12806 		dtrace_probes[probe->dtpr_id - 1] = NULL;
12807 
12808 		next = probe->dtpr_nextmod;
12809 		dtrace_hash_remove(dtrace_bymod, probe);
12810 		dtrace_hash_remove(dtrace_byfunc, probe);
12811 		dtrace_hash_remove(dtrace_byname, probe);
12812 
12813 		if (first == NULL) {
12814 			first = probe;
12815 			probe->dtpr_nextmod = NULL;
12816 		} else {
12817 			probe->dtpr_nextmod = first;
12818 			first = probe;
12819 		}
12820 	}
12821 
12822 	/*
12823 	 * We've removed all of the module's probes from the hash chains and
12824 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
12825 	 * everyone has cleared out from any probe array processing.
12826 	 */
12827 	dtrace_sync();
12828 
12829 	for (probe = first; probe != NULL; probe = first) {
12830 		first = probe->dtpr_nextmod;
12831 		prov = probe->dtpr_provider;
12832 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
12833 		    probe->dtpr_arg);
12834 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
12835 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
12836 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
12837 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
12838 		kmem_free(probe, sizeof (dtrace_probe_t));
12839 	}
12840 
12841 	mutex_exit(&dtrace_lock);
12842 	mutex_exit(&mod_lock);
12843 	mutex_exit(&dtrace_provider_lock);
12844 }
12845 
12846 void
12847 dtrace_suspend(void)
12848 {
12849 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
12850 }
12851 
12852 void
12853 dtrace_resume(void)
12854 {
12855 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
12856 }
12857 
12858 static int
12859 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
12860 {
12861 	ASSERT(MUTEX_HELD(&cpu_lock));
12862 	mutex_enter(&dtrace_lock);
12863 
12864 	switch (what) {
12865 	case CPU_CONFIG: {
12866 		dtrace_state_t *state;
12867 		dtrace_optval_t *opt, rs, c;
12868 
12869 		/*
12870 		 * For now, we only allocate a new buffer for anonymous state.
12871 		 */
12872 		if ((state = dtrace_anon.dta_state) == NULL)
12873 			break;
12874 
12875 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
12876 			break;
12877 
12878 		opt = state->dts_options;
12879 		c = opt[DTRACEOPT_CPU];
12880 
12881 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
12882 			break;
12883 
12884 		/*
12885 		 * Regardless of what the actual policy is, we're going to
12886 		 * temporarily set our resize policy to be manual.  We're
12887 		 * also going to temporarily set our CPU option to denote
12888 		 * the newly configured CPU.
12889 		 */
12890 		rs = opt[DTRACEOPT_BUFRESIZE];
12891 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
12892 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
12893 
12894 		(void) dtrace_state_buffers(state);
12895 
12896 		opt[DTRACEOPT_BUFRESIZE] = rs;
12897 		opt[DTRACEOPT_CPU] = c;
12898 
12899 		break;
12900 	}
12901 
12902 	case CPU_UNCONFIG:
12903 		/*
12904 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
12905 		 * buffer will be freed when the consumer exits.)
12906 		 */
12907 		break;
12908 
12909 	default:
12910 		break;
12911 	}
12912 
12913 	mutex_exit(&dtrace_lock);
12914 	return (0);
12915 }
12916 
12917 static void
12918 dtrace_cpu_setup_initial(processorid_t cpu)
12919 {
12920 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
12921 }
12922 
12923 static void
12924 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
12925 {
12926 	if (dtrace_toxranges >= dtrace_toxranges_max) {
12927 		int osize, nsize;
12928 		dtrace_toxrange_t *range;
12929 
12930 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
12931 
12932 		if (osize == 0) {
12933 			ASSERT(dtrace_toxrange == NULL);
12934 			ASSERT(dtrace_toxranges_max == 0);
12935 			dtrace_toxranges_max = 1;
12936 		} else {
12937 			dtrace_toxranges_max <<= 1;
12938 		}
12939 
12940 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
12941 		range = kmem_zalloc(nsize, KM_SLEEP);
12942 
12943 		if (dtrace_toxrange != NULL) {
12944 			ASSERT(osize != 0);
12945 			bcopy(dtrace_toxrange, range, osize);
12946 			kmem_free(dtrace_toxrange, osize);
12947 		}
12948 
12949 		dtrace_toxrange = range;
12950 	}
12951 
12952 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
12953 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
12954 
12955 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
12956 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
12957 	dtrace_toxranges++;
12958 }
12959 
12960 /*
12961  * DTrace Driver Cookbook Functions
12962  */
12963 /*ARGSUSED*/
12964 static int
12965 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
12966 {
12967 	dtrace_provider_id_t id;
12968 	dtrace_state_t *state = NULL;
12969 	dtrace_enabling_t *enab;
12970 
12971 	mutex_enter(&cpu_lock);
12972 	mutex_enter(&dtrace_provider_lock);
12973 	mutex_enter(&dtrace_lock);
12974 
12975 	if (ddi_soft_state_init(&dtrace_softstate, sizeof (dtrace_state_t) +
12976 	    NCPU * sizeof (dtrace_buffer_t), 0) != 0) {
12977 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
12978 		mutex_exit(&cpu_lock);
12979 		mutex_exit(&dtrace_provider_lock);
12980 		mutex_exit(&dtrace_lock);
12981 		return (DDI_FAILURE);
12982 	}
12983 
12984 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
12985 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
12986 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
12987 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
12988 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
12989 		ddi_remove_minor_node(devi, NULL);
12990 		ddi_soft_state_fini(&dtrace_softstate);
12991 		mutex_exit(&cpu_lock);
12992 		mutex_exit(&dtrace_provider_lock);
12993 		mutex_exit(&dtrace_lock);
12994 		return (DDI_FAILURE);
12995 	}
12996 
12997 	ddi_report_dev(devi);
12998 	dtrace_devi = devi;
12999 
13000 	dtrace_modload = dtrace_module_loaded;
13001 	dtrace_modunload = dtrace_module_unloaded;
13002 	dtrace_cpu_init = dtrace_cpu_setup_initial;
13003 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
13004 	dtrace_helpers_fork = dtrace_helpers_duplicate;
13005 	dtrace_cpustart_init = dtrace_suspend;
13006 	dtrace_cpustart_fini = dtrace_resume;
13007 	dtrace_debugger_init = dtrace_suspend;
13008 	dtrace_debugger_fini = dtrace_resume;
13009 	dtrace_kreloc_init = dtrace_suspend;
13010 	dtrace_kreloc_fini = dtrace_resume;
13011 
13012 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
13013 
13014 	ASSERT(MUTEX_HELD(&cpu_lock));
13015 
13016 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
13017 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13018 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
13019 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
13020 	    VM_SLEEP | VMC_IDENTIFIER);
13021 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
13022 	    1, INT_MAX, 0);
13023 
13024 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
13025 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
13026 	    NULL, NULL, NULL, NULL, NULL, 0);
13027 
13028 	ASSERT(MUTEX_HELD(&cpu_lock));
13029 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
13030 	    offsetof(dtrace_probe_t, dtpr_nextmod),
13031 	    offsetof(dtrace_probe_t, dtpr_prevmod));
13032 
13033 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
13034 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
13035 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
13036 
13037 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
13038 	    offsetof(dtrace_probe_t, dtpr_nextname),
13039 	    offsetof(dtrace_probe_t, dtpr_prevname));
13040 
13041 	if (dtrace_retain_max < 1) {
13042 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
13043 		    "setting to 1", dtrace_retain_max);
13044 		dtrace_retain_max = 1;
13045 	}
13046 
13047 	/*
13048 	 * Now discover our toxic ranges.
13049 	 */
13050 	dtrace_toxic_ranges(dtrace_toxrange_add);
13051 
13052 	/*
13053 	 * Before we register ourselves as a provider to our own framework,
13054 	 * we would like to assert that dtrace_provider is NULL -- but that's
13055 	 * not true if we were loaded as a dependency of a DTrace provider.
13056 	 * Once we've registered, we can assert that dtrace_provider is our
13057 	 * pseudo provider.
13058 	 */
13059 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
13060 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
13061 
13062 	ASSERT(dtrace_provider != NULL);
13063 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
13064 
13065 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
13066 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
13067 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
13068 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
13069 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
13070 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
13071 
13072 	dtrace_anon_property();
13073 	mutex_exit(&cpu_lock);
13074 
13075 	/*
13076 	 * If DTrace helper tracing is enabled, we need to allocate the
13077 	 * trace buffer and initialize the values.
13078 	 */
13079 	if (dtrace_helptrace_enabled) {
13080 		ASSERT(dtrace_helptrace_buffer == NULL);
13081 		dtrace_helptrace_buffer =
13082 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
13083 		dtrace_helptrace_next = 0;
13084 	}
13085 
13086 	/*
13087 	 * If there are already providers, we must ask them to provide their
13088 	 * probes, and then match any anonymous enabling against them.  Note
13089 	 * that there should be no other retained enablings at this time:
13090 	 * the only retained enablings at this time should be the anonymous
13091 	 * enabling.
13092 	 */
13093 	if (dtrace_anon.dta_enabling != NULL) {
13094 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
13095 
13096 		dtrace_enabling_provide(NULL);
13097 		state = dtrace_anon.dta_state;
13098 
13099 		/*
13100 		 * We couldn't hold cpu_lock across the above call to
13101 		 * dtrace_enabling_provide(), but we must hold it to actually
13102 		 * enable the probes.  We have to drop all of our locks, pick
13103 		 * up cpu_lock, and regain our locks before matching the
13104 		 * retained anonymous enabling.
13105 		 */
13106 		mutex_exit(&dtrace_lock);
13107 		mutex_exit(&dtrace_provider_lock);
13108 
13109 		mutex_enter(&cpu_lock);
13110 		mutex_enter(&dtrace_provider_lock);
13111 		mutex_enter(&dtrace_lock);
13112 
13113 		if ((enab = dtrace_anon.dta_enabling) != NULL)
13114 			(void) dtrace_enabling_match(enab, NULL);
13115 
13116 		mutex_exit(&cpu_lock);
13117 	}
13118 
13119 	mutex_exit(&dtrace_lock);
13120 	mutex_exit(&dtrace_provider_lock);
13121 
13122 	if (state != NULL) {
13123 		/*
13124 		 * If we created any anonymous state, set it going now.
13125 		 */
13126 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
13127 	}
13128 
13129 	return (DDI_SUCCESS);
13130 }
13131 
13132 /*ARGSUSED*/
13133 static int
13134 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
13135 {
13136 	dtrace_state_t *state;
13137 	uint32_t priv;
13138 	uid_t uid;
13139 
13140 	if (getminor(*devp) == DTRACEMNRN_HELPER)
13141 		return (0);
13142 
13143 	/*
13144 	 * If this wasn't an open with the "helper" minor, then it must be
13145 	 * the "dtrace" minor.
13146 	 */
13147 	ASSERT(getminor(*devp) == DTRACEMNRN_DTRACE);
13148 
13149 	/*
13150 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
13151 	 * caller lacks sufficient permission to do anything with DTrace.
13152 	 */
13153 	dtrace_cred2priv(cred_p, &priv, &uid);
13154 	if (priv == DTRACE_PRIV_NONE)
13155 		return (EACCES);
13156 
13157 	/*
13158 	 * Ask all providers to provide all their probes.
13159 	 */
13160 	mutex_enter(&dtrace_provider_lock);
13161 	dtrace_probe_provide(NULL, NULL);
13162 	mutex_exit(&dtrace_provider_lock);
13163 
13164 	mutex_enter(&cpu_lock);
13165 	mutex_enter(&dtrace_lock);
13166 	dtrace_opens++;
13167 	dtrace_membar_producer();
13168 
13169 	/*
13170 	 * If the kernel debugger is active (that is, if the kernel debugger
13171 	 * modified text in some way), we won't allow the open.
13172 	 */
13173 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
13174 		dtrace_opens--;
13175 		mutex_exit(&cpu_lock);
13176 		mutex_exit(&dtrace_lock);
13177 		return (EBUSY);
13178 	}
13179 
13180 	state = dtrace_state_create(devp, cred_p);
13181 	mutex_exit(&cpu_lock);
13182 
13183 	if (state == NULL) {
13184 		if (--dtrace_opens == 0)
13185 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
13186 		mutex_exit(&dtrace_lock);
13187 		return (EAGAIN);
13188 	}
13189 
13190 	mutex_exit(&dtrace_lock);
13191 
13192 	return (0);
13193 }
13194 
13195 /*ARGSUSED*/
13196 static int
13197 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
13198 {
13199 	minor_t minor = getminor(dev);
13200 	dtrace_state_t *state;
13201 
13202 	if (minor == DTRACEMNRN_HELPER)
13203 		return (0);
13204 
13205 	state = ddi_get_soft_state(dtrace_softstate, minor);
13206 
13207 	mutex_enter(&cpu_lock);
13208 	mutex_enter(&dtrace_lock);
13209 
13210 	if (state->dts_anon) {
13211 		/*
13212 		 * There is anonymous state. Destroy that first.
13213 		 */
13214 		ASSERT(dtrace_anon.dta_state == NULL);
13215 		dtrace_state_destroy(state->dts_anon);
13216 	}
13217 
13218 	dtrace_state_destroy(state);
13219 	ASSERT(dtrace_opens > 0);
13220 	if (--dtrace_opens == 0)
13221 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
13222 
13223 	mutex_exit(&dtrace_lock);
13224 	mutex_exit(&cpu_lock);
13225 
13226 	return (0);
13227 }
13228 
13229 /*ARGSUSED*/
13230 static int
13231 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
13232 {
13233 	int rval;
13234 	dof_helper_t help, *dhp = NULL;
13235 
13236 	switch (cmd) {
13237 	case DTRACEHIOC_ADDDOF:
13238 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
13239 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
13240 			return (EFAULT);
13241 		}
13242 
13243 		dhp = &help;
13244 		arg = (intptr_t)help.dofhp_dof;
13245 		/*FALLTHROUGH*/
13246 
13247 	case DTRACEHIOC_ADD: {
13248 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
13249 
13250 		if (dof == NULL)
13251 			return (rval);
13252 
13253 		mutex_enter(&dtrace_lock);
13254 		dtrace_err = 0;
13255 
13256 		/*
13257 		 * dtrace_helper_slurp() takes responsibility for the dof --
13258 		 * it may free it now or it may save it and free it later.
13259 		 */
13260 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
13261 			*rv = rval;
13262 			rval = 0;
13263 		} else {
13264 			rval = EINVAL;
13265 		}
13266 
13267 		mutex_exit(&dtrace_lock);
13268 		return (rval);
13269 	}
13270 
13271 	case DTRACEHIOC_REMOVE: {
13272 		mutex_enter(&dtrace_lock);
13273 		rval = dtrace_helper_destroygen(arg);
13274 		mutex_exit(&dtrace_lock);
13275 
13276 		return (rval);
13277 	}
13278 
13279 	default:
13280 		break;
13281 	}
13282 
13283 	return (ENOTTY);
13284 }
13285 
13286 /*ARGSUSED*/
13287 static int
13288 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
13289 {
13290 	minor_t minor = getminor(dev);
13291 	dtrace_state_t *state;
13292 	int rval;
13293 
13294 	if (minor == DTRACEMNRN_HELPER)
13295 		return (dtrace_ioctl_helper(cmd, arg, rv));
13296 
13297 	state = ddi_get_soft_state(dtrace_softstate, minor);
13298 
13299 	if (state->dts_anon) {
13300 		ASSERT(dtrace_anon.dta_state == NULL);
13301 		state = state->dts_anon;
13302 	}
13303 
13304 	switch (cmd) {
13305 	case DTRACEIOC_PROVIDER: {
13306 		dtrace_providerdesc_t pvd;
13307 		dtrace_provider_t *pvp;
13308 
13309 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
13310 			return (EFAULT);
13311 
13312 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
13313 		mutex_enter(&dtrace_provider_lock);
13314 
13315 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
13316 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
13317 				break;
13318 		}
13319 
13320 		mutex_exit(&dtrace_provider_lock);
13321 
13322 		if (pvp == NULL)
13323 			return (ESRCH);
13324 
13325 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
13326 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
13327 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
13328 			return (EFAULT);
13329 
13330 		return (0);
13331 	}
13332 
13333 	case DTRACEIOC_EPROBE: {
13334 		dtrace_eprobedesc_t epdesc;
13335 		dtrace_ecb_t *ecb;
13336 		dtrace_action_t *act;
13337 		void *buf;
13338 		size_t size;
13339 		uintptr_t dest;
13340 		int nrecs;
13341 
13342 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
13343 			return (EFAULT);
13344 
13345 		mutex_enter(&dtrace_lock);
13346 
13347 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
13348 			mutex_exit(&dtrace_lock);
13349 			return (EINVAL);
13350 		}
13351 
13352 		if (ecb->dte_probe == NULL) {
13353 			mutex_exit(&dtrace_lock);
13354 			return (EINVAL);
13355 		}
13356 
13357 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
13358 		epdesc.dtepd_uarg = ecb->dte_uarg;
13359 		epdesc.dtepd_size = ecb->dte_size;
13360 
13361 		nrecs = epdesc.dtepd_nrecs;
13362 		epdesc.dtepd_nrecs = 0;
13363 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
13364 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
13365 				continue;
13366 
13367 			epdesc.dtepd_nrecs++;
13368 		}
13369 
13370 		/*
13371 		 * Now that we have the size, we need to allocate a temporary
13372 		 * buffer in which to store the complete description.  We need
13373 		 * the temporary buffer to be able to drop dtrace_lock()
13374 		 * across the copyout(), below.
13375 		 */
13376 		size = sizeof (dtrace_eprobedesc_t) +
13377 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
13378 
13379 		buf = kmem_alloc(size, KM_SLEEP);
13380 		dest = (uintptr_t)buf;
13381 
13382 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
13383 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
13384 
13385 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
13386 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
13387 				continue;
13388 
13389 			if (nrecs-- == 0)
13390 				break;
13391 
13392 			bcopy(&act->dta_rec, (void *)dest,
13393 			    sizeof (dtrace_recdesc_t));
13394 			dest += sizeof (dtrace_recdesc_t);
13395 		}
13396 
13397 		mutex_exit(&dtrace_lock);
13398 
13399 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
13400 			kmem_free(buf, size);
13401 			return (EFAULT);
13402 		}
13403 
13404 		kmem_free(buf, size);
13405 		return (0);
13406 	}
13407 
13408 	case DTRACEIOC_AGGDESC: {
13409 		dtrace_aggdesc_t aggdesc;
13410 		dtrace_action_t *act;
13411 		dtrace_aggregation_t *agg;
13412 		int nrecs;
13413 		uint32_t offs;
13414 		dtrace_recdesc_t *lrec;
13415 		void *buf;
13416 		size_t size;
13417 		uintptr_t dest;
13418 
13419 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
13420 			return (EFAULT);
13421 
13422 		mutex_enter(&dtrace_lock);
13423 
13424 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
13425 			mutex_exit(&dtrace_lock);
13426 			return (EINVAL);
13427 		}
13428 
13429 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
13430 
13431 		nrecs = aggdesc.dtagd_nrecs;
13432 		aggdesc.dtagd_nrecs = 0;
13433 
13434 		offs = agg->dtag_base;
13435 		lrec = &agg->dtag_action.dta_rec;
13436 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
13437 
13438 		for (act = agg->dtag_first; ; act = act->dta_next) {
13439 			ASSERT(act->dta_intuple ||
13440 			    DTRACEACT_ISAGG(act->dta_kind));
13441 
13442 			/*
13443 			 * If this action has a record size of zero, it
13444 			 * denotes an argument to the aggregating action.
13445 			 * Because the presence of this record doesn't (or
13446 			 * shouldn't) affect the way the data is interpreted,
13447 			 * we don't copy it out to save user-level the
13448 			 * confusion of dealing with a zero-length record.
13449 			 */
13450 			if (act->dta_rec.dtrd_size == 0) {
13451 				ASSERT(agg->dtag_hasarg);
13452 				continue;
13453 			}
13454 
13455 			aggdesc.dtagd_nrecs++;
13456 
13457 			if (act == &agg->dtag_action)
13458 				break;
13459 		}
13460 
13461 		/*
13462 		 * Now that we have the size, we need to allocate a temporary
13463 		 * buffer in which to store the complete description.  We need
13464 		 * the temporary buffer to be able to drop dtrace_lock()
13465 		 * across the copyout(), below.
13466 		 */
13467 		size = sizeof (dtrace_aggdesc_t) +
13468 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
13469 
13470 		buf = kmem_alloc(size, KM_SLEEP);
13471 		dest = (uintptr_t)buf;
13472 
13473 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
13474 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
13475 
13476 		for (act = agg->dtag_first; ; act = act->dta_next) {
13477 			dtrace_recdesc_t rec = act->dta_rec;
13478 
13479 			/*
13480 			 * See the comment in the above loop for why we pass
13481 			 * over zero-length records.
13482 			 */
13483 			if (rec.dtrd_size == 0) {
13484 				ASSERT(agg->dtag_hasarg);
13485 				continue;
13486 			}
13487 
13488 			if (nrecs-- == 0)
13489 				break;
13490 
13491 			rec.dtrd_offset -= offs;
13492 			bcopy(&rec, (void *)dest, sizeof (rec));
13493 			dest += sizeof (dtrace_recdesc_t);
13494 
13495 			if (act == &agg->dtag_action)
13496 				break;
13497 		}
13498 
13499 		mutex_exit(&dtrace_lock);
13500 
13501 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
13502 			kmem_free(buf, size);
13503 			return (EFAULT);
13504 		}
13505 
13506 		kmem_free(buf, size);
13507 		return (0);
13508 	}
13509 
13510 	case DTRACEIOC_ENABLE: {
13511 		dof_hdr_t *dof;
13512 		dtrace_enabling_t *enab = NULL;
13513 		dtrace_vstate_t *vstate;
13514 		int err = 0;
13515 
13516 		*rv = 0;
13517 
13518 		/*
13519 		 * If a NULL argument has been passed, we take this as our
13520 		 * cue to reevaluate our enablings.
13521 		 */
13522 		if (arg == NULL) {
13523 			mutex_enter(&cpu_lock);
13524 			mutex_enter(&dtrace_lock);
13525 			err = dtrace_enabling_matchstate(state, rv);
13526 			mutex_exit(&dtrace_lock);
13527 			mutex_exit(&cpu_lock);
13528 
13529 			return (err);
13530 		}
13531 
13532 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
13533 			return (rval);
13534 
13535 		mutex_enter(&cpu_lock);
13536 		mutex_enter(&dtrace_lock);
13537 		vstate = &state->dts_vstate;
13538 
13539 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
13540 			mutex_exit(&dtrace_lock);
13541 			mutex_exit(&cpu_lock);
13542 			dtrace_dof_destroy(dof);
13543 			return (EBUSY);
13544 		}
13545 
13546 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
13547 			mutex_exit(&dtrace_lock);
13548 			mutex_exit(&cpu_lock);
13549 			dtrace_dof_destroy(dof);
13550 			return (EINVAL);
13551 		}
13552 
13553 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
13554 			dtrace_enabling_destroy(enab);
13555 			mutex_exit(&dtrace_lock);
13556 			mutex_exit(&cpu_lock);
13557 			dtrace_dof_destroy(dof);
13558 			return (rval);
13559 		}
13560 
13561 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
13562 			err = dtrace_enabling_retain(enab);
13563 		} else {
13564 			dtrace_enabling_destroy(enab);
13565 		}
13566 
13567 		mutex_exit(&cpu_lock);
13568 		mutex_exit(&dtrace_lock);
13569 		dtrace_dof_destroy(dof);
13570 
13571 		return (err);
13572 	}
13573 
13574 	case DTRACEIOC_REPLICATE: {
13575 		dtrace_repldesc_t desc;
13576 		dtrace_probedesc_t *match = &desc.dtrpd_match;
13577 		dtrace_probedesc_t *create = &desc.dtrpd_create;
13578 		int err;
13579 
13580 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
13581 			return (EFAULT);
13582 
13583 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
13584 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
13585 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
13586 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
13587 
13588 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
13589 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
13590 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
13591 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
13592 
13593 		mutex_enter(&dtrace_lock);
13594 		err = dtrace_enabling_replicate(state, match, create);
13595 		mutex_exit(&dtrace_lock);
13596 
13597 		return (err);
13598 	}
13599 
13600 	case DTRACEIOC_PROBEMATCH:
13601 	case DTRACEIOC_PROBES: {
13602 		dtrace_probe_t *probe = NULL;
13603 		dtrace_probedesc_t desc;
13604 		dtrace_probekey_t pkey;
13605 		dtrace_id_t i;
13606 		int m = 0;
13607 		uint32_t priv;
13608 		uid_t uid;
13609 
13610 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
13611 			return (EFAULT);
13612 
13613 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
13614 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
13615 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
13616 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
13617 
13618 		/*
13619 		 * Before we attempt to match this probe, we want to give
13620 		 * all providers the opportunity to provide it.
13621 		 */
13622 		if (desc.dtpd_id == DTRACE_IDNONE) {
13623 			mutex_enter(&dtrace_provider_lock);
13624 			dtrace_probe_provide(&desc, NULL);
13625 			mutex_exit(&dtrace_provider_lock);
13626 			desc.dtpd_id++;
13627 		}
13628 
13629 		if (cmd == DTRACEIOC_PROBEMATCH)  {
13630 			dtrace_probekey(&desc, &pkey);
13631 			pkey.dtpk_id = DTRACE_IDNONE;
13632 		}
13633 
13634 		uid = crgetuid(cr);
13635 		dtrace_cred2priv(cr, &priv, &uid);
13636 
13637 		mutex_enter(&dtrace_lock);
13638 
13639 		if (cmd == DTRACEIOC_PROBEMATCH) {
13640 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
13641 				if ((probe = dtrace_probes[i - 1]) != NULL &&
13642 				    (m = dtrace_match_probe(probe, &pkey,
13643 				    priv, uid)) != 0)
13644 					break;
13645 			}
13646 
13647 			if (m < 0) {
13648 				mutex_exit(&dtrace_lock);
13649 				return (EINVAL);
13650 			}
13651 
13652 		} else {
13653 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
13654 				if ((probe = dtrace_probes[i - 1]) != NULL &&
13655 				    dtrace_match_priv(probe, priv, uid))
13656 					break;
13657 			}
13658 		}
13659 
13660 		if (probe == NULL) {
13661 			mutex_exit(&dtrace_lock);
13662 			return (ESRCH);
13663 		}
13664 
13665 		dtrace_probe_description(probe, &desc);
13666 		mutex_exit(&dtrace_lock);
13667 
13668 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
13669 			return (EFAULT);
13670 
13671 		return (0);
13672 	}
13673 
13674 	case DTRACEIOC_PROBEARG: {
13675 		dtrace_argdesc_t desc;
13676 		dtrace_probe_t *probe;
13677 		dtrace_provider_t *prov;
13678 
13679 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
13680 			return (EFAULT);
13681 
13682 		if (desc.dtargd_id == DTRACE_IDNONE)
13683 			return (EINVAL);
13684 
13685 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
13686 			return (EINVAL);
13687 
13688 		mutex_enter(&dtrace_provider_lock);
13689 		mutex_enter(&mod_lock);
13690 		mutex_enter(&dtrace_lock);
13691 
13692 		if (desc.dtargd_id > dtrace_nprobes) {
13693 			mutex_exit(&dtrace_lock);
13694 			mutex_exit(&mod_lock);
13695 			mutex_exit(&dtrace_provider_lock);
13696 			return (EINVAL);
13697 		}
13698 
13699 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
13700 			mutex_exit(&dtrace_lock);
13701 			mutex_exit(&mod_lock);
13702 			mutex_exit(&dtrace_provider_lock);
13703 			return (EINVAL);
13704 		}
13705 
13706 		mutex_exit(&dtrace_lock);
13707 
13708 		prov = probe->dtpr_provider;
13709 
13710 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
13711 			/*
13712 			 * There isn't any typed information for this probe.
13713 			 * Set the argument number to DTRACE_ARGNONE.
13714 			 */
13715 			desc.dtargd_ndx = DTRACE_ARGNONE;
13716 		} else {
13717 			desc.dtargd_native[0] = '\0';
13718 			desc.dtargd_xlate[0] = '\0';
13719 			desc.dtargd_mapping = desc.dtargd_ndx;
13720 
13721 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
13722 			    probe->dtpr_id, probe->dtpr_arg, &desc);
13723 		}
13724 
13725 		mutex_exit(&mod_lock);
13726 		mutex_exit(&dtrace_provider_lock);
13727 
13728 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
13729 			return (EFAULT);
13730 
13731 		return (0);
13732 	}
13733 
13734 	case DTRACEIOC_GO: {
13735 		processorid_t cpuid;
13736 		rval = dtrace_state_go(state, &cpuid);
13737 
13738 		if (rval != 0)
13739 			return (rval);
13740 
13741 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
13742 			return (EFAULT);
13743 
13744 		return (0);
13745 	}
13746 
13747 	case DTRACEIOC_STOP: {
13748 		processorid_t cpuid;
13749 
13750 		mutex_enter(&dtrace_lock);
13751 		rval = dtrace_state_stop(state, &cpuid);
13752 		mutex_exit(&dtrace_lock);
13753 
13754 		if (rval != 0)
13755 			return (rval);
13756 
13757 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
13758 			return (EFAULT);
13759 
13760 		return (0);
13761 	}
13762 
13763 	case DTRACEIOC_DOFGET: {
13764 		dof_hdr_t hdr, *dof;
13765 		uint64_t len;
13766 
13767 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
13768 			return (EFAULT);
13769 
13770 		mutex_enter(&dtrace_lock);
13771 		dof = dtrace_dof_create(state);
13772 		mutex_exit(&dtrace_lock);
13773 
13774 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
13775 		rval = copyout(dof, (void *)arg, len);
13776 		dtrace_dof_destroy(dof);
13777 
13778 		return (rval == 0 ? 0 : EFAULT);
13779 	}
13780 
13781 	case DTRACEIOC_AGGSNAP:
13782 	case DTRACEIOC_BUFSNAP: {
13783 		dtrace_bufdesc_t desc;
13784 		caddr_t cached;
13785 		dtrace_buffer_t *buf;
13786 
13787 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
13788 			return (EFAULT);
13789 
13790 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
13791 			return (EINVAL);
13792 
13793 		mutex_enter(&dtrace_lock);
13794 
13795 		if (cmd == DTRACEIOC_BUFSNAP) {
13796 			buf = &state->dts_buffer[desc.dtbd_cpu];
13797 		} else {
13798 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
13799 		}
13800 
13801 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
13802 			size_t sz = buf->dtb_offset;
13803 
13804 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
13805 				mutex_exit(&dtrace_lock);
13806 				return (EBUSY);
13807 			}
13808 
13809 			/*
13810 			 * If this buffer has already been consumed, we're
13811 			 * going to indicate that there's nothing left here
13812 			 * to consume.
13813 			 */
13814 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
13815 				mutex_exit(&dtrace_lock);
13816 
13817 				desc.dtbd_size = 0;
13818 				desc.dtbd_drops = 0;
13819 				desc.dtbd_errors = 0;
13820 				desc.dtbd_oldest = 0;
13821 				sz = sizeof (desc);
13822 
13823 				if (copyout(&desc, (void *)arg, sz) != 0)
13824 					return (EFAULT);
13825 
13826 				return (0);
13827 			}
13828 
13829 			/*
13830 			 * If this is a ring buffer that has wrapped, we want
13831 			 * to copy the whole thing out.
13832 			 */
13833 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
13834 				dtrace_buffer_polish(buf);
13835 				sz = buf->dtb_size;
13836 			}
13837 
13838 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
13839 				mutex_exit(&dtrace_lock);
13840 				return (EFAULT);
13841 			}
13842 
13843 			desc.dtbd_size = sz;
13844 			desc.dtbd_drops = buf->dtb_drops;
13845 			desc.dtbd_errors = buf->dtb_errors;
13846 			desc.dtbd_oldest = buf->dtb_xamot_offset;
13847 
13848 			mutex_exit(&dtrace_lock);
13849 
13850 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
13851 				return (EFAULT);
13852 
13853 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
13854 
13855 			return (0);
13856 		}
13857 
13858 		if (buf->dtb_tomax == NULL) {
13859 			ASSERT(buf->dtb_xamot == NULL);
13860 			mutex_exit(&dtrace_lock);
13861 			return (ENOENT);
13862 		}
13863 
13864 		cached = buf->dtb_tomax;
13865 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
13866 
13867 		dtrace_xcall(desc.dtbd_cpu,
13868 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
13869 
13870 		state->dts_errors += buf->dtb_xamot_errors;
13871 
13872 		/*
13873 		 * If the buffers did not actually switch, then the cross call
13874 		 * did not take place -- presumably because the given CPU is
13875 		 * not in the ready set.  If this is the case, we'll return
13876 		 * ENOENT.
13877 		 */
13878 		if (buf->dtb_tomax == cached) {
13879 			ASSERT(buf->dtb_xamot != cached);
13880 			mutex_exit(&dtrace_lock);
13881 			return (ENOENT);
13882 		}
13883 
13884 		ASSERT(cached == buf->dtb_xamot);
13885 
13886 		/*
13887 		 * We have our snapshot; now copy it out.
13888 		 */
13889 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
13890 		    buf->dtb_xamot_offset) != 0) {
13891 			mutex_exit(&dtrace_lock);
13892 			return (EFAULT);
13893 		}
13894 
13895 		desc.dtbd_size = buf->dtb_xamot_offset;
13896 		desc.dtbd_drops = buf->dtb_xamot_drops;
13897 		desc.dtbd_errors = buf->dtb_xamot_errors;
13898 		desc.dtbd_oldest = 0;
13899 
13900 		mutex_exit(&dtrace_lock);
13901 
13902 		/*
13903 		 * Finally, copy out the buffer description.
13904 		 */
13905 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
13906 			return (EFAULT);
13907 
13908 		return (0);
13909 	}
13910 
13911 	case DTRACEIOC_CONF: {
13912 		dtrace_conf_t conf;
13913 
13914 		bzero(&conf, sizeof (conf));
13915 		conf.dtc_difversion = DIF_VERSION;
13916 		conf.dtc_difintregs = DIF_DIR_NREGS;
13917 		conf.dtc_diftupregs = DIF_DTR_NREGS;
13918 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
13919 
13920 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
13921 			return (EFAULT);
13922 
13923 		return (0);
13924 	}
13925 
13926 	case DTRACEIOC_STATUS: {
13927 		dtrace_status_t stat;
13928 		dtrace_dstate_t *dstate;
13929 		int i, j;
13930 		uint64_t nerrs;
13931 
13932 		/*
13933 		 * See the comment in dtrace_state_deadman() for the reason
13934 		 * for setting dts_laststatus to INT64_MAX before setting
13935 		 * it to the correct value.
13936 		 */
13937 		state->dts_laststatus = INT64_MAX;
13938 		dtrace_membar_producer();
13939 		state->dts_laststatus = dtrace_gethrtime();
13940 
13941 		bzero(&stat, sizeof (stat));
13942 
13943 		mutex_enter(&dtrace_lock);
13944 
13945 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
13946 			mutex_exit(&dtrace_lock);
13947 			return (ENOENT);
13948 		}
13949 
13950 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
13951 			stat.dtst_exiting = 1;
13952 
13953 		nerrs = state->dts_errors;
13954 		dstate = &state->dts_vstate.dtvs_dynvars;
13955 
13956 		for (i = 0; i < NCPU; i++) {
13957 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
13958 
13959 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
13960 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
13961 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
13962 
13963 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
13964 				stat.dtst_filled++;
13965 
13966 			nerrs += state->dts_buffer[i].dtb_errors;
13967 
13968 			for (j = 0; j < state->dts_nspeculations; j++) {
13969 				dtrace_speculation_t *spec;
13970 				dtrace_buffer_t *buf;
13971 
13972 				spec = &state->dts_speculations[j];
13973 				buf = &spec->dtsp_buffer[i];
13974 				stat.dtst_specdrops += buf->dtb_xamot_drops;
13975 			}
13976 		}
13977 
13978 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
13979 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
13980 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
13981 		stat.dtst_dblerrors = state->dts_dblerrors;
13982 		stat.dtst_killed =
13983 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
13984 		stat.dtst_errors = nerrs;
13985 
13986 		mutex_exit(&dtrace_lock);
13987 
13988 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
13989 			return (EFAULT);
13990 
13991 		return (0);
13992 	}
13993 
13994 	case DTRACEIOC_FORMAT: {
13995 		dtrace_fmtdesc_t fmt;
13996 		char *str;
13997 		int len;
13998 
13999 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
14000 			return (EFAULT);
14001 
14002 		mutex_enter(&dtrace_lock);
14003 
14004 		if (fmt.dtfd_format == 0 ||
14005 		    fmt.dtfd_format > state->dts_nformats) {
14006 			mutex_exit(&dtrace_lock);
14007 			return (EINVAL);
14008 		}
14009 
14010 		/*
14011 		 * Format strings are allocated contiguously and they are
14012 		 * never freed; if a format index is less than the number
14013 		 * of formats, we can assert that the format map is non-NULL
14014 		 * and that the format for the specified index is non-NULL.
14015 		 */
14016 		ASSERT(state->dts_formats != NULL);
14017 		str = state->dts_formats[fmt.dtfd_format - 1];
14018 		ASSERT(str != NULL);
14019 
14020 		len = strlen(str) + 1;
14021 
14022 		if (len > fmt.dtfd_length) {
14023 			fmt.dtfd_length = len;
14024 
14025 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
14026 				mutex_exit(&dtrace_lock);
14027 				return (EINVAL);
14028 			}
14029 		} else {
14030 			if (copyout(str, fmt.dtfd_string, len) != 0) {
14031 				mutex_exit(&dtrace_lock);
14032 				return (EINVAL);
14033 			}
14034 		}
14035 
14036 		mutex_exit(&dtrace_lock);
14037 		return (0);
14038 	}
14039 
14040 	default:
14041 		break;
14042 	}
14043 
14044 	return (ENOTTY);
14045 }
14046 
14047 /*ARGSUSED*/
14048 static int
14049 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
14050 {
14051 	dtrace_state_t *state;
14052 
14053 	switch (cmd) {
14054 	case DDI_DETACH:
14055 		break;
14056 
14057 	case DDI_SUSPEND:
14058 		return (DDI_SUCCESS);
14059 
14060 	default:
14061 		return (DDI_FAILURE);
14062 	}
14063 
14064 	mutex_enter(&cpu_lock);
14065 	mutex_enter(&dtrace_provider_lock);
14066 	mutex_enter(&dtrace_lock);
14067 
14068 	ASSERT(dtrace_opens == 0);
14069 
14070 	if (dtrace_helpers > 0) {
14071 		mutex_exit(&dtrace_provider_lock);
14072 		mutex_exit(&dtrace_lock);
14073 		mutex_exit(&cpu_lock);
14074 		return (DDI_FAILURE);
14075 	}
14076 
14077 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
14078 		mutex_exit(&dtrace_provider_lock);
14079 		mutex_exit(&dtrace_lock);
14080 		mutex_exit(&cpu_lock);
14081 		return (DDI_FAILURE);
14082 	}
14083 
14084 	dtrace_provider = NULL;
14085 
14086 	if ((state = dtrace_anon_grab()) != NULL) {
14087 		/*
14088 		 * If there were ECBs on this state, the provider should
14089 		 * have not been allowed to detach; assert that there is
14090 		 * none.
14091 		 */
14092 		ASSERT(state->dts_necbs == 0);
14093 		dtrace_state_destroy(state);
14094 
14095 		/*
14096 		 * If we're being detached with anonymous state, we need to
14097 		 * indicate to the kernel debugger that DTrace is now inactive.
14098 		 */
14099 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14100 	}
14101 
14102 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
14103 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
14104 	dtrace_cpu_init = NULL;
14105 	dtrace_helpers_cleanup = NULL;
14106 	dtrace_helpers_fork = NULL;
14107 	dtrace_cpustart_init = NULL;
14108 	dtrace_cpustart_fini = NULL;
14109 	dtrace_debugger_init = NULL;
14110 	dtrace_debugger_fini = NULL;
14111 	dtrace_kreloc_init = NULL;
14112 	dtrace_kreloc_fini = NULL;
14113 	dtrace_modload = NULL;
14114 	dtrace_modunload = NULL;
14115 
14116 	mutex_exit(&cpu_lock);
14117 
14118 	if (dtrace_helptrace_enabled) {
14119 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
14120 		dtrace_helptrace_buffer = NULL;
14121 	}
14122 
14123 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
14124 	dtrace_probes = NULL;
14125 	dtrace_nprobes = 0;
14126 
14127 	dtrace_hash_destroy(dtrace_bymod);
14128 	dtrace_hash_destroy(dtrace_byfunc);
14129 	dtrace_hash_destroy(dtrace_byname);
14130 	dtrace_bymod = NULL;
14131 	dtrace_byfunc = NULL;
14132 	dtrace_byname = NULL;
14133 
14134 	kmem_cache_destroy(dtrace_state_cache);
14135 	vmem_destroy(dtrace_minor);
14136 	vmem_destroy(dtrace_arena);
14137 
14138 	if (dtrace_toxrange != NULL) {
14139 		kmem_free(dtrace_toxrange,
14140 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
14141 		dtrace_toxrange = NULL;
14142 		dtrace_toxranges = 0;
14143 		dtrace_toxranges_max = 0;
14144 	}
14145 
14146 	ddi_remove_minor_node(dtrace_devi, NULL);
14147 	dtrace_devi = NULL;
14148 
14149 	ddi_soft_state_fini(&dtrace_softstate);
14150 
14151 	ASSERT(dtrace_vtime_references == 0);
14152 	ASSERT(dtrace_opens == 0);
14153 	ASSERT(dtrace_retained == NULL);
14154 
14155 	mutex_exit(&dtrace_lock);
14156 	mutex_exit(&dtrace_provider_lock);
14157 
14158 	/*
14159 	 * We don't destroy the task queue until after we have dropped our
14160 	 * locks (taskq_destroy() may block on running tasks).  To prevent
14161 	 * attempting to do work after we have effectively detached but before
14162 	 * the task queue has been destroyed, all tasks dispatched via the
14163 	 * task queue must check that DTrace is still attached before
14164 	 * performing any operation.
14165 	 */
14166 	taskq_destroy(dtrace_taskq);
14167 	dtrace_taskq = NULL;
14168 
14169 	return (DDI_SUCCESS);
14170 }
14171 
14172 /*ARGSUSED*/
14173 static int
14174 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
14175 {
14176 	int error;
14177 
14178 	switch (infocmd) {
14179 	case DDI_INFO_DEVT2DEVINFO:
14180 		*result = (void *)dtrace_devi;
14181 		error = DDI_SUCCESS;
14182 		break;
14183 	case DDI_INFO_DEVT2INSTANCE:
14184 		*result = (void *)0;
14185 		error = DDI_SUCCESS;
14186 		break;
14187 	default:
14188 		error = DDI_FAILURE;
14189 	}
14190 	return (error);
14191 }
14192 
14193 static struct cb_ops dtrace_cb_ops = {
14194 	dtrace_open,		/* open */
14195 	dtrace_close,		/* close */
14196 	nulldev,		/* strategy */
14197 	nulldev,		/* print */
14198 	nodev,			/* dump */
14199 	nodev,			/* read */
14200 	nodev,			/* write */
14201 	dtrace_ioctl,		/* ioctl */
14202 	nodev,			/* devmap */
14203 	nodev,			/* mmap */
14204 	nodev,			/* segmap */
14205 	nochpoll,		/* poll */
14206 	ddi_prop_op,		/* cb_prop_op */
14207 	0,			/* streamtab  */
14208 	D_NEW | D_MP		/* Driver compatibility flag */
14209 };
14210 
14211 static struct dev_ops dtrace_ops = {
14212 	DEVO_REV,		/* devo_rev */
14213 	0,			/* refcnt */
14214 	dtrace_info,		/* get_dev_info */
14215 	nulldev,		/* identify */
14216 	nulldev,		/* probe */
14217 	dtrace_attach,		/* attach */
14218 	dtrace_detach,		/* detach */
14219 	nodev,			/* reset */
14220 	&dtrace_cb_ops,		/* driver operations */
14221 	NULL,			/* bus operations */
14222 	nodev			/* dev power */
14223 };
14224 
14225 static struct modldrv modldrv = {
14226 	&mod_driverops,		/* module type (this is a pseudo driver) */
14227 	"Dynamic Tracing",	/* name of module */
14228 	&dtrace_ops,		/* driver ops */
14229 };
14230 
14231 static struct modlinkage modlinkage = {
14232 	MODREV_1,
14233 	(void *)&modldrv,
14234 	NULL
14235 };
14236 
14237 int
14238 _init(void)
14239 {
14240 	return (mod_install(&modlinkage));
14241 }
14242 
14243 int
14244 _info(struct modinfo *modinfop)
14245 {
14246 	return (mod_info(&modlinkage, modinfop));
14247 }
14248 
14249 int
14250 _fini(void)
14251 {
14252 	return (mod_remove(&modlinkage));
14253 }
14254