xref: /titanic_51/usr/src/uts/common/dtrace/dtrace.c (revision dffe6dfdb1d8eb284d0bd0625c028c38d633429c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * DTrace - Dynamic Tracing for Solaris
31  *
32  * This is the implementation of the Solaris Dynamic Tracing framework
33  * (DTrace).  The user-visible interface to DTrace is described at length in
34  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
35  * library, the in-kernel DTrace framework, and the DTrace providers are
36  * described in the block comments in the <sys/dtrace.h> header file.  The
37  * internal architecture of DTrace is described in the block comments in the
38  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
39  * implementation very much assume mastery of all of these sources; if one has
40  * an unanswered question about the implementation, one should consult them
41  * first.
42  *
43  * The functions here are ordered roughly as follows:
44  *
45  *   - Probe context functions
46  *   - Probe hashing functions
47  *   - Non-probe context utility functions
48  *   - Matching functions
49  *   - Provider-to-Framework API functions
50  *   - Probe management functions
51  *   - DIF object functions
52  *   - Format functions
53  *   - Predicate functions
54  *   - ECB functions
55  *   - Buffer functions
56  *   - Enabling functions
57  *   - DOF functions
58  *   - Anonymous enabling functions
59  *   - Consumer state functions
60  *   - Helper functions
61  *   - Hook functions
62  *   - Driver cookbook functions
63  *
64  * Each group of functions begins with a block comment labelled the "DTrace
65  * [Group] Functions", allowing one to find each block by searching forward
66  * on capital-f functions.
67  */
68 #include <sys/errno.h>
69 #include <sys/stat.h>
70 #include <sys/modctl.h>
71 #include <sys/conf.h>
72 #include <sys/systm.h>
73 #include <sys/ddi.h>
74 #include <sys/sunddi.h>
75 #include <sys/cpuvar.h>
76 #include <sys/kmem.h>
77 #include <sys/strsubr.h>
78 #include <sys/sysmacros.h>
79 #include <sys/dtrace_impl.h>
80 #include <sys/atomic.h>
81 #include <sys/cmn_err.h>
82 #include <sys/mutex_impl.h>
83 #include <sys/rwlock_impl.h>
84 #include <sys/ctf_api.h>
85 #include <sys/panic.h>
86 #include <sys/priv_impl.h>
87 #include <sys/policy.h>
88 #include <sys/cred_impl.h>
89 #include <sys/procfs_isa.h>
90 #include <sys/taskq.h>
91 #include <sys/mkdev.h>
92 #include <sys/kdi.h>
93 #include <sys/zone.h>
94 
95 /*
96  * DTrace Tunable Variables
97  *
98  * The following variables may be tuned by adding a line to /etc/system that
99  * includes both the name of the DTrace module ("dtrace") and the name of the
100  * variable.  For example:
101  *
102  *   set dtrace:dtrace_destructive_disallow = 1
103  *
104  * In general, the only variables that one should be tuning this way are those
105  * that affect system-wide DTrace behavior, and for which the default behavior
106  * is undesirable.  Most of these variables are tunable on a per-consumer
107  * basis using DTrace options, and need not be tuned on a system-wide basis.
108  * When tuning these variables, avoid pathological values; while some attempt
109  * is made to verify the integrity of these variables, they are not considered
110  * part of the supported interface to DTrace, and they are therefore not
111  * checked comprehensively.  Further, these variables should not be tuned
112  * dynamically via "mdb -kw" or other means; they should only be tuned via
113  * /etc/system.
114  */
115 int		dtrace_destructive_disallow = 0;
116 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
117 size_t		dtrace_difo_maxsize = (256 * 1024);
118 dtrace_optval_t	dtrace_dof_maxsize = (256 * 1024);
119 size_t		dtrace_global_maxsize = (16 * 1024);
120 size_t		dtrace_actions_max = (16 * 1024);
121 size_t		dtrace_retain_max = 1024;
122 dtrace_optval_t	dtrace_helper_actions_max = 32;
123 dtrace_optval_t	dtrace_helper_providers_max = 32;
124 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
125 size_t		dtrace_strsize_default = 256;
126 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
127 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
128 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
129 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
130 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
131 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
132 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
133 dtrace_optval_t	dtrace_nspec_default = 1;
134 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
135 dtrace_optval_t dtrace_stackframes_default = 20;
136 dtrace_optval_t dtrace_ustackframes_default = 20;
137 dtrace_optval_t dtrace_jstackframes_default = 50;
138 dtrace_optval_t dtrace_jstackstrsize_default = 512;
139 int		dtrace_msgdsize_max = 128;
140 hrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
141 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
142 int		dtrace_devdepth_max = 32;
143 int		dtrace_err_verbose;
144 hrtime_t	dtrace_deadman_interval = NANOSEC;
145 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
146 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
147 
148 /*
149  * DTrace External Variables
150  *
151  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
152  * available to DTrace consumers via the backtick (`) syntax.  One of these,
153  * dtrace_zero, is made deliberately so:  it is provided as a source of
154  * well-known, zero-filled memory.  While this variable is not documented,
155  * it is used by some translators as an implementation detail.
156  */
157 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
158 
159 /*
160  * DTrace Internal Variables
161  */
162 static dev_info_t	*dtrace_devi;		/* device info */
163 static vmem_t		*dtrace_arena;		/* probe ID arena */
164 static vmem_t		*dtrace_minor;		/* minor number arena */
165 static taskq_t		*dtrace_taskq;		/* task queue */
166 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
167 static int		dtrace_nprobes;		/* number of probes */
168 static dtrace_provider_t *dtrace_provider;	/* provider list */
169 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
170 static int		dtrace_opens;		/* number of opens */
171 static int		dtrace_helpers;		/* number of helpers */
172 static void		*dtrace_softstate;	/* softstate pointer */
173 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
174 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
175 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
176 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
177 static int		dtrace_toxranges;	/* number of toxic ranges */
178 static int		dtrace_toxranges_max;	/* size of toxic range array */
179 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
180 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
181 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
182 static kthread_t	*dtrace_panicked;	/* panicking thread */
183 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
184 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
185 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
186 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
187 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
188 
189 /*
190  * DTrace Locking
191  * DTrace is protected by three (relatively coarse-grained) locks:
192  *
193  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
194  *     including enabling state, probes, ECBs, consumer state, helper state,
195  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
196  *     probe context is lock-free -- synchronization is handled via the
197  *     dtrace_sync() cross call mechanism.
198  *
199  * (2) dtrace_provider_lock is required when manipulating provider state, or
200  *     when provider state must be held constant.
201  *
202  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
203  *     when meta provider state must be held constant.
204  *
205  * The lock ordering between these three locks is dtrace_meta_lock before
206  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
207  * several places where dtrace_provider_lock is held by the framework as it
208  * calls into the providers -- which then call back into the framework,
209  * grabbing dtrace_lock.)
210  *
211  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
212  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
213  * role as a coarse-grained lock; it is acquired before both of these locks.
214  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
215  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
216  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
217  * acquired _between_ dtrace_provider_lock and dtrace_lock.
218  */
219 static kmutex_t		dtrace_lock;		/* probe state lock */
220 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
221 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
222 
223 /*
224  * DTrace Provider Variables
225  *
226  * These are the variables relating to DTrace as a provider (that is, the
227  * provider of the BEGIN, END, and ERROR probes).
228  */
229 static dtrace_pattr_t	dtrace_provider_attr = {
230 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
231 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
232 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
233 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
234 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
235 };
236 
237 static void
238 dtrace_nullop(void)
239 {}
240 
241 static dtrace_pops_t	dtrace_provider_ops = {
242 	(void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
243 	(void (*)(void *, struct modctl *))dtrace_nullop,
244 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
245 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
246 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
247 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
248 	NULL,
249 	NULL,
250 	NULL,
251 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
252 };
253 
254 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
255 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
256 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
257 
258 /*
259  * DTrace Helper Tracing Variables
260  */
261 uint32_t dtrace_helptrace_next = 0;
262 uint32_t dtrace_helptrace_nlocals;
263 char	*dtrace_helptrace_buffer;
264 int	dtrace_helptrace_bufsize = 512 * 1024;
265 
266 #ifdef DEBUG
267 int	dtrace_helptrace_enabled = 1;
268 #else
269 int	dtrace_helptrace_enabled = 0;
270 #endif
271 
272 /*
273  * DTrace Error Hashing
274  *
275  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
276  * table.  This is very useful for checking coverage of tests that are
277  * expected to induce DIF or DOF processing errors, and may be useful for
278  * debugging problems in the DIF code generator or in DOF generation .  The
279  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
280  */
281 #ifdef DEBUG
282 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
283 static const char *dtrace_errlast;
284 static kthread_t *dtrace_errthread;
285 static kmutex_t dtrace_errlock;
286 #endif
287 
288 /*
289  * DTrace Macros and Constants
290  *
291  * These are various macros that are useful in various spots in the
292  * implementation, along with a few random constants that have no meaning
293  * outside of the implementation.  There is no real structure to this cpp
294  * mishmash -- but is there ever?
295  */
296 #define	DTRACE_HASHSTR(hash, probe)	\
297 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
298 
299 #define	DTRACE_HASHNEXT(hash, probe)	\
300 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
301 
302 #define	DTRACE_HASHPREV(hash, probe)	\
303 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
304 
305 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
306 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
307 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
308 
309 #define	DTRACE_AGGHASHSIZE_SLEW		17
310 
311 /*
312  * The key for a thread-local variable consists of the lower 61 bits of the
313  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
314  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
315  * equal to a variable identifier.  This is necessary (but not sufficient) to
316  * assure that global associative arrays never collide with thread-local
317  * variables.  To guarantee that they cannot collide, we must also define the
318  * order for keying dynamic variables.  That order is:
319  *
320  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
321  *
322  * Because the variable-key and the tls-key are in orthogonal spaces, there is
323  * no way for a global variable key signature to match a thread-local key
324  * signature.
325  */
326 #define	DTRACE_TLS_THRKEY(where) { \
327 	uint_t intr = 0; \
328 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
329 	for (; actv; actv >>= 1) \
330 		intr++; \
331 	ASSERT(intr < (1 << 3)); \
332 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
333 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
334 }
335 
336 #define	DTRACE_STORE(type, tomax, offset, what) \
337 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
338 
339 #ifndef __i386
340 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
341 	if (addr & (size - 1)) {					\
342 		*flags |= CPU_DTRACE_BADALIGN;				\
343 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
344 		return (0);						\
345 	}
346 #else
347 #define	DTRACE_ALIGNCHECK(addr, size, flags)
348 #endif
349 
350 #define	DTRACE_LOADFUNC(bits)						\
351 /*CSTYLED*/								\
352 uint##bits##_t								\
353 dtrace_load##bits(uintptr_t addr)					\
354 {									\
355 	size_t size = bits / NBBY;					\
356 	/*CSTYLED*/							\
357 	uint##bits##_t rval;						\
358 	int i;								\
359 	volatile uint16_t *flags = (volatile uint16_t *)		\
360 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
361 									\
362 	DTRACE_ALIGNCHECK(addr, size, flags);				\
363 									\
364 	for (i = 0; i < dtrace_toxranges; i++) {			\
365 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
366 			continue;					\
367 									\
368 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
369 			continue;					\
370 									\
371 		/*							\
372 		 * This address falls within a toxic region; return 0.	\
373 		 */							\
374 		*flags |= CPU_DTRACE_BADADDR;				\
375 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
376 		return (0);						\
377 	}								\
378 									\
379 	*flags |= CPU_DTRACE_NOFAULT;					\
380 	/*CSTYLED*/							\
381 	rval = *((volatile uint##bits##_t *)addr);			\
382 	*flags &= ~CPU_DTRACE_NOFAULT;					\
383 									\
384 	return (rval);							\
385 }
386 
387 #ifdef _LP64
388 #define	dtrace_loadptr	dtrace_load64
389 #else
390 #define	dtrace_loadptr	dtrace_load32
391 #endif
392 
393 #define	DTRACE_DYNHASH_FREE	0
394 #define	DTRACE_DYNHASH_SINK	1
395 #define	DTRACE_DYNHASH_VALID	2
396 
397 #define	DTRACE_MATCH_NEXT	0
398 #define	DTRACE_MATCH_DONE	1
399 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
400 #define	DTRACE_STATE_ALIGN	64
401 
402 #define	DTRACE_FLAGS2FLT(flags)						\
403 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
404 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
405 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
406 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
407 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
408 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
409 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
410 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
411 	DTRACEFLT_UNKNOWN)
412 
413 #define	DTRACEACT_ISSTRING(act)						\
414 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
415 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
416 
417 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
418 static void dtrace_enabling_provide(dtrace_provider_t *);
419 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
420 static void dtrace_enabling_matchall(void);
421 static dtrace_state_t *dtrace_anon_grab(void);
422 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
423     dtrace_state_t *, uint64_t, uint64_t);
424 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
425 static void dtrace_buffer_drop(dtrace_buffer_t *);
426 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
427     dtrace_state_t *, dtrace_mstate_t *);
428 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
429     dtrace_optval_t);
430 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
431 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
432 
433 /*
434  * DTrace Probe Context Functions
435  *
436  * These functions are called from probe context.  Because probe context is
437  * any context in which C may be called, arbitrarily locks may be held,
438  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
439  * As a result, functions called from probe context may only call other DTrace
440  * support functions -- they may not interact at all with the system at large.
441  * (Note that the ASSERT macro is made probe-context safe by redefining it in
442  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
443  * loads are to be performed from probe context, they _must_ be in terms of
444  * the safe dtrace_load*() variants.
445  *
446  * Some functions in this block are not actually called from probe context;
447  * for these functions, there will be a comment above the function reading
448  * "Note:  not called from probe context."
449  */
450 void
451 dtrace_panic(const char *format, ...)
452 {
453 	va_list alist;
454 
455 	va_start(alist, format);
456 	dtrace_vpanic(format, alist);
457 	va_end(alist);
458 }
459 
460 int
461 dtrace_assfail(const char *a, const char *f, int l)
462 {
463 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
464 
465 	/*
466 	 * We just need something here that even the most clever compiler
467 	 * cannot optimize away.
468 	 */
469 	return (a[(uintptr_t)f]);
470 }
471 
472 /*
473  * Atomically increment a specified error counter from probe context.
474  */
475 static void
476 dtrace_error(uint32_t *counter)
477 {
478 	/*
479 	 * Most counters stored to in probe context are per-CPU counters.
480 	 * However, there are some error conditions that are sufficiently
481 	 * arcane that they don't merit per-CPU storage.  If these counters
482 	 * are incremented concurrently on different CPUs, scalability will be
483 	 * adversely affected -- but we don't expect them to be white-hot in a
484 	 * correctly constructed enabling...
485 	 */
486 	uint32_t oval, nval;
487 
488 	do {
489 		oval = *counter;
490 
491 		if ((nval = oval + 1) == 0) {
492 			/*
493 			 * If the counter would wrap, set it to 1 -- assuring
494 			 * that the counter is never zero when we have seen
495 			 * errors.  (The counter must be 32-bits because we
496 			 * aren't guaranteed a 64-bit compare&swap operation.)
497 			 * To save this code both the infamy of being fingered
498 			 * by a priggish news story and the indignity of being
499 			 * the target of a neo-puritan witch trial, we're
500 			 * carefully avoiding any colorful description of the
501 			 * likelihood of this condition -- but suffice it to
502 			 * say that it is only slightly more likely than the
503 			 * overflow of predicate cache IDs, as discussed in
504 			 * dtrace_predicate_create().
505 			 */
506 			nval = 1;
507 		}
508 	} while (dtrace_cas32(counter, oval, nval) != oval);
509 }
510 
511 /*
512  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
513  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
514  */
515 DTRACE_LOADFUNC(8)
516 DTRACE_LOADFUNC(16)
517 DTRACE_LOADFUNC(32)
518 DTRACE_LOADFUNC(64)
519 
520 static int
521 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
522 {
523 	if (dest < mstate->dtms_scratch_base)
524 		return (0);
525 
526 	if (dest + size < dest)
527 		return (0);
528 
529 	if (dest + size > mstate->dtms_scratch_ptr)
530 		return (0);
531 
532 	return (1);
533 }
534 
535 static int
536 dtrace_canstore_statvar(uint64_t addr, size_t sz,
537     dtrace_statvar_t **svars, int nsvars)
538 {
539 	int i;
540 
541 	for (i = 0; i < nsvars; i++) {
542 		dtrace_statvar_t *svar = svars[i];
543 
544 		if (svar == NULL || svar->dtsv_size == 0)
545 			continue;
546 
547 		if (addr - svar->dtsv_data < svar->dtsv_size &&
548 		    addr + sz <= svar->dtsv_data + svar->dtsv_size)
549 			return (1);
550 	}
551 
552 	return (0);
553 }
554 
555 /*
556  * Check to see if the address is within a memory region to which a store may
557  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
558  * region.  The caller of dtrace_canstore() is responsible for performing any
559  * alignment checks that are needed before stores are actually executed.
560  */
561 static int
562 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
563     dtrace_vstate_t *vstate)
564 {
565 	uintptr_t a;
566 	size_t s;
567 
568 	/*
569 	 * First, check to see if the address is in scratch space...
570 	 */
571 	a = mstate->dtms_scratch_base;
572 	s = mstate->dtms_scratch_size;
573 
574 	if (addr - a < s && addr + sz <= a + s)
575 		return (1);
576 
577 	/*
578 	 * Now check to see if it's a dynamic variable.  This check will pick
579 	 * up both thread-local variables and any global dynamically-allocated
580 	 * variables.
581 	 */
582 	a = (uintptr_t)vstate->dtvs_dynvars.dtds_base;
583 	s = vstate->dtvs_dynvars.dtds_size;
584 	if (addr - a < s && addr + sz <= a + s)
585 		return (1);
586 
587 	/*
588 	 * Finally, check the static local and global variables.  These checks
589 	 * take the longest, so we perform them last.
590 	 */
591 	if (dtrace_canstore_statvar(addr, sz,
592 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
593 		return (1);
594 
595 	if (dtrace_canstore_statvar(addr, sz,
596 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
597 		return (1);
598 
599 	return (0);
600 }
601 
602 /*
603  * Compare two strings using safe loads.
604  */
605 static int
606 dtrace_strncmp(char *s1, char *s2, size_t limit)
607 {
608 	uint8_t c1, c2;
609 	volatile uint16_t *flags;
610 
611 	if (s1 == s2 || limit == 0)
612 		return (0);
613 
614 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
615 
616 	do {
617 		if (s1 == NULL) {
618 			c1 = '\0';
619 		} else {
620 			c1 = dtrace_load8((uintptr_t)s1++);
621 		}
622 
623 		if (s2 == NULL) {
624 			c2 = '\0';
625 		} else {
626 			c2 = dtrace_load8((uintptr_t)s2++);
627 		}
628 
629 		if (c1 != c2)
630 			return (c1 - c2);
631 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
632 
633 	return (0);
634 }
635 
636 /*
637  * Compute strlen(s) for a string using safe memory accesses.  The additional
638  * len parameter is used to specify a maximum length to ensure completion.
639  */
640 static size_t
641 dtrace_strlen(const char *s, size_t lim)
642 {
643 	uint_t len;
644 
645 	for (len = 0; len != lim; len++) {
646 		if (dtrace_load8((uintptr_t)s++) == '\0')
647 			break;
648 	}
649 
650 	return (len);
651 }
652 
653 /*
654  * Check if an address falls within a toxic region.
655  */
656 static int
657 dtrace_istoxic(uintptr_t kaddr, size_t size)
658 {
659 	uintptr_t taddr, tsize;
660 	int i;
661 
662 	for (i = 0; i < dtrace_toxranges; i++) {
663 		taddr = dtrace_toxrange[i].dtt_base;
664 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
665 
666 		if (kaddr - taddr < tsize) {
667 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
668 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
669 			return (1);
670 		}
671 
672 		if (taddr - kaddr < size) {
673 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
674 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
675 			return (1);
676 		}
677 	}
678 
679 	return (0);
680 }
681 
682 /*
683  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
684  * memory specified by the DIF program.  The dst is assumed to be safe memory
685  * that we can store to directly because it is managed by DTrace.  As with
686  * standard bcopy, overlapping copies are handled properly.
687  */
688 static void
689 dtrace_bcopy(const void *src, void *dst, size_t len)
690 {
691 	if (len != 0) {
692 		uint8_t *s1 = dst;
693 		const uint8_t *s2 = src;
694 
695 		if (s1 <= s2) {
696 			do {
697 				*s1++ = dtrace_load8((uintptr_t)s2++);
698 			} while (--len != 0);
699 		} else {
700 			s2 += len;
701 			s1 += len;
702 
703 			do {
704 				*--s1 = dtrace_load8((uintptr_t)--s2);
705 			} while (--len != 0);
706 		}
707 	}
708 }
709 
710 /*
711  * Copy src to dst using safe memory accesses, up to either the specified
712  * length, or the point that a nul byte is encountered.  The src is assumed to
713  * be unsafe memory specified by the DIF program.  The dst is assumed to be
714  * safe memory that we can store to directly because it is managed by DTrace.
715  * Unlike dtrace_bcopy(), overlapping regions are not handled.
716  */
717 static void
718 dtrace_strcpy(const void *src, void *dst, size_t len)
719 {
720 	if (len != 0) {
721 		uint8_t *s1 = dst, c;
722 		const uint8_t *s2 = src;
723 
724 		do {
725 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
726 		} while (--len != 0 && c != '\0');
727 	}
728 }
729 
730 /*
731  * Copy src to dst, deriving the size and type from the specified (BYREF)
732  * variable type.  The src is assumed to be unsafe memory specified by the DIF
733  * program.  The dst is assumed to be DTrace variable memory that is of the
734  * specified type; we assume that we can store to directly.
735  */
736 static void
737 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
738 {
739 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
740 
741 	if (type->dtdt_kind == DIF_TYPE_STRING) {
742 		dtrace_strcpy(src, dst, type->dtdt_size);
743 	} else {
744 		dtrace_bcopy(src, dst, type->dtdt_size);
745 	}
746 }
747 
748 /*
749  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
750  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
751  * safe memory that we can access directly because it is managed by DTrace.
752  */
753 static int
754 dtrace_bcmp(const void *s1, const void *s2, size_t len)
755 {
756 	volatile uint16_t *flags;
757 
758 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
759 
760 	if (s1 == s2)
761 		return (0);
762 
763 	if (s1 == NULL || s2 == NULL)
764 		return (1);
765 
766 	if (s1 != s2 && len != 0) {
767 		const uint8_t *ps1 = s1;
768 		const uint8_t *ps2 = s2;
769 
770 		do {
771 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
772 				return (1);
773 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
774 	}
775 	return (0);
776 }
777 
778 /*
779  * Zero the specified region using a simple byte-by-byte loop.  Note that this
780  * is for safe DTrace-managed memory only.
781  */
782 static void
783 dtrace_bzero(void *dst, size_t len)
784 {
785 	uchar_t *cp;
786 
787 	for (cp = dst; len != 0; len--)
788 		*cp++ = 0;
789 }
790 
791 /*
792  * This privilege check should be used by actions and subroutines to
793  * verify that the user credentials of the process that enabled the
794  * invoking ECB match the target credentials
795  */
796 static int
797 dtrace_priv_proc_common_user(dtrace_state_t *state)
798 {
799 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
800 
801 	/*
802 	 * We should always have a non-NULL state cred here, since if cred
803 	 * is null (anonymous tracing), we fast-path bypass this routine.
804 	 */
805 	ASSERT(s_cr != NULL);
806 
807 	if ((cr = CRED()) != NULL &&
808 	    s_cr->cr_uid == cr->cr_uid &&
809 	    s_cr->cr_uid == cr->cr_ruid &&
810 	    s_cr->cr_uid == cr->cr_suid &&
811 	    s_cr->cr_gid == cr->cr_gid &&
812 	    s_cr->cr_gid == cr->cr_rgid &&
813 	    s_cr->cr_gid == cr->cr_sgid)
814 		return (1);
815 
816 	return (0);
817 }
818 
819 /*
820  * This privilege check should be used by actions and subroutines to
821  * verify that the zone of the process that enabled the invoking ECB
822  * matches the target credentials
823  */
824 static int
825 dtrace_priv_proc_common_zone(dtrace_state_t *state)
826 {
827 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
828 
829 	/*
830 	 * We should always have a non-NULL state cred here, since if cred
831 	 * is null (anonymous tracing), we fast-path bypass this routine.
832 	 */
833 	ASSERT(s_cr != NULL);
834 
835 	if ((cr = CRED()) != NULL &&
836 	    s_cr->cr_zone == cr->cr_zone)
837 		return (1);
838 
839 	return (0);
840 }
841 
842 /*
843  * This privilege check should be used by actions and subroutines to
844  * verify that the process has not setuid or changed credentials.
845  */
846 static int
847 dtrace_priv_proc_common_nocd()
848 {
849 	proc_t *proc;
850 
851 	if ((proc = ttoproc(curthread)) != NULL &&
852 	    !(proc->p_flag & SNOCD))
853 		return (1);
854 
855 	return (0);
856 }
857 
858 static int
859 dtrace_priv_proc_destructive(dtrace_state_t *state)
860 {
861 	int action = state->dts_cred.dcr_action;
862 
863 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
864 	    dtrace_priv_proc_common_zone(state) == 0)
865 		goto bad;
866 
867 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
868 	    dtrace_priv_proc_common_user(state) == 0)
869 		goto bad;
870 
871 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
872 	    dtrace_priv_proc_common_nocd() == 0)
873 		goto bad;
874 
875 	return (1);
876 
877 bad:
878 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
879 
880 	return (0);
881 }
882 
883 static int
884 dtrace_priv_proc_control(dtrace_state_t *state)
885 {
886 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
887 		return (1);
888 
889 	if (dtrace_priv_proc_common_zone(state) &&
890 	    dtrace_priv_proc_common_user(state) &&
891 	    dtrace_priv_proc_common_nocd())
892 		return (1);
893 
894 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
895 
896 	return (0);
897 }
898 
899 static int
900 dtrace_priv_proc(dtrace_state_t *state)
901 {
902 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
903 		return (1);
904 
905 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
906 
907 	return (0);
908 }
909 
910 static int
911 dtrace_priv_kernel(dtrace_state_t *state)
912 {
913 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
914 		return (1);
915 
916 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
917 
918 	return (0);
919 }
920 
921 static int
922 dtrace_priv_kernel_destructive(dtrace_state_t *state)
923 {
924 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
925 		return (1);
926 
927 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
928 
929 	return (0);
930 }
931 
932 /*
933  * Note:  not called from probe context.  This function is called
934  * asynchronously (and at a regular interval) from outside of probe context to
935  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
936  * cleaning is explained in detail in <sys/dtrace_impl.h>.
937  */
938 void
939 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
940 {
941 	dtrace_dynvar_t *dirty;
942 	dtrace_dstate_percpu_t *dcpu;
943 	int i, work = 0;
944 
945 	for (i = 0; i < NCPU; i++) {
946 		dcpu = &dstate->dtds_percpu[i];
947 
948 		ASSERT(dcpu->dtdsc_rinsing == NULL);
949 
950 		/*
951 		 * If the dirty list is NULL, there is no dirty work to do.
952 		 */
953 		if (dcpu->dtdsc_dirty == NULL)
954 			continue;
955 
956 		/*
957 		 * If the clean list is non-NULL, then we're not going to do
958 		 * any work for this CPU -- it means that there has not been
959 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
960 		 * since the last time we cleaned house.
961 		 */
962 		if (dcpu->dtdsc_clean != NULL)
963 			continue;
964 
965 		work = 1;
966 
967 		/*
968 		 * Atomically move the dirty list aside.
969 		 */
970 		do {
971 			dirty = dcpu->dtdsc_dirty;
972 
973 			/*
974 			 * Before we zap the dirty list, set the rinsing list.
975 			 * (This allows for a potential assertion in
976 			 * dtrace_dynvar():  if a free dynamic variable appears
977 			 * on a hash chain, either the dirty list or the
978 			 * rinsing list for some CPU must be non-NULL.)
979 			 */
980 			dcpu->dtdsc_rinsing = dirty;
981 			dtrace_membar_producer();
982 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
983 		    dirty, NULL) != dirty);
984 	}
985 
986 	if (!work) {
987 		/*
988 		 * We have no work to do; we can simply return.
989 		 */
990 		return;
991 	}
992 
993 	dtrace_sync();
994 
995 	for (i = 0; i < NCPU; i++) {
996 		dcpu = &dstate->dtds_percpu[i];
997 
998 		if (dcpu->dtdsc_rinsing == NULL)
999 			continue;
1000 
1001 		/*
1002 		 * We are now guaranteed that no hash chain contains a pointer
1003 		 * into this dirty list; we can make it clean.
1004 		 */
1005 		ASSERT(dcpu->dtdsc_clean == NULL);
1006 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1007 		dcpu->dtdsc_rinsing = NULL;
1008 	}
1009 
1010 	/*
1011 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1012 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1013 	 * This prevents a race whereby a CPU incorrectly decides that
1014 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1015 	 * after dtrace_dynvar_clean() has completed.
1016 	 */
1017 	dtrace_sync();
1018 
1019 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1020 }
1021 
1022 /*
1023  * Depending on the value of the op parameter, this function looks-up,
1024  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1025  * allocation is requested, this function will return a pointer to a
1026  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1027  * variable can be allocated.  If NULL is returned, the appropriate counter
1028  * will be incremented.
1029  */
1030 dtrace_dynvar_t *
1031 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1032     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op)
1033 {
1034 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1035 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1036 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1037 	processorid_t me = CPU->cpu_id, cpu = me;
1038 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1039 	size_t bucket, ksize;
1040 	size_t chunksize = dstate->dtds_chunksize;
1041 	uintptr_t kdata, lock, nstate;
1042 	uint_t i;
1043 
1044 	ASSERT(nkeys != 0);
1045 
1046 	/*
1047 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1048 	 * algorithm.  For the by-value portions, we perform the algorithm in
1049 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1050 	 * bit, and seems to have only a minute effect on distribution.  For
1051 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1052 	 * over each referenced byte.  It's painful to do this, but it's much
1053 	 * better than pathological hash distribution.  The efficacy of the
1054 	 * hashing algorithm (and a comparison with other algorithms) may be
1055 	 * found by running the ::dtrace_dynstat MDB dcmd.
1056 	 */
1057 	for (i = 0; i < nkeys; i++) {
1058 		if (key[i].dttk_size == 0) {
1059 			uint64_t val = key[i].dttk_value;
1060 
1061 			hashval += (val >> 48) & 0xffff;
1062 			hashval += (hashval << 10);
1063 			hashval ^= (hashval >> 6);
1064 
1065 			hashval += (val >> 32) & 0xffff;
1066 			hashval += (hashval << 10);
1067 			hashval ^= (hashval >> 6);
1068 
1069 			hashval += (val >> 16) & 0xffff;
1070 			hashval += (hashval << 10);
1071 			hashval ^= (hashval >> 6);
1072 
1073 			hashval += val & 0xffff;
1074 			hashval += (hashval << 10);
1075 			hashval ^= (hashval >> 6);
1076 		} else {
1077 			/*
1078 			 * This is incredibly painful, but it beats the hell
1079 			 * out of the alternative.
1080 			 */
1081 			uint64_t j, size = key[i].dttk_size;
1082 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1083 
1084 			for (j = 0; j < size; j++) {
1085 				hashval += dtrace_load8(base + j);
1086 				hashval += (hashval << 10);
1087 				hashval ^= (hashval >> 6);
1088 			}
1089 		}
1090 	}
1091 
1092 	hashval += (hashval << 3);
1093 	hashval ^= (hashval >> 11);
1094 	hashval += (hashval << 15);
1095 
1096 	/*
1097 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1098 	 * comes out to be one of our two sentinel hash values.  If this
1099 	 * actually happens, we set the hashval to be a value known to be a
1100 	 * non-sentinel value.
1101 	 */
1102 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1103 		hashval = DTRACE_DYNHASH_VALID;
1104 
1105 	/*
1106 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1107 	 * important here, tricks can be pulled to reduce it.  (However, it's
1108 	 * critical that hash collisions be kept to an absolute minimum;
1109 	 * they're much more painful than a divide.)  It's better to have a
1110 	 * solution that generates few collisions and still keeps things
1111 	 * relatively simple.
1112 	 */
1113 	bucket = hashval % dstate->dtds_hashsize;
1114 
1115 	if (op == DTRACE_DYNVAR_DEALLOC) {
1116 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1117 
1118 		for (;;) {
1119 			while ((lock = *lockp) & 1)
1120 				continue;
1121 
1122 			if (dtrace_casptr((void *)lockp,
1123 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1124 				break;
1125 		}
1126 
1127 		dtrace_membar_producer();
1128 	}
1129 
1130 top:
1131 	prev = NULL;
1132 	lock = hash[bucket].dtdh_lock;
1133 
1134 	dtrace_membar_consumer();
1135 
1136 	start = hash[bucket].dtdh_chain;
1137 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1138 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1139 	    op != DTRACE_DYNVAR_DEALLOC));
1140 
1141 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1142 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1143 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1144 
1145 		if (dvar->dtdv_hashval != hashval) {
1146 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1147 				/*
1148 				 * We've reached the sink, and therefore the
1149 				 * end of the hash chain; we can kick out of
1150 				 * the loop knowing that we have seen a valid
1151 				 * snapshot of state.
1152 				 */
1153 				ASSERT(dvar->dtdv_next == NULL);
1154 				ASSERT(dvar == &dtrace_dynhash_sink);
1155 				break;
1156 			}
1157 
1158 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1159 				/*
1160 				 * We've gone off the rails:  somewhere along
1161 				 * the line, one of the members of this hash
1162 				 * chain was deleted.  Note that we could also
1163 				 * detect this by simply letting this loop run
1164 				 * to completion, as we would eventually hit
1165 				 * the end of the dirty list.  However, we
1166 				 * want to avoid running the length of the
1167 				 * dirty list unnecessarily (it might be quite
1168 				 * long), so we catch this as early as
1169 				 * possible by detecting the hash marker.  In
1170 				 * this case, we simply set dvar to NULL and
1171 				 * break; the conditional after the loop will
1172 				 * send us back to top.
1173 				 */
1174 				dvar = NULL;
1175 				break;
1176 			}
1177 
1178 			goto next;
1179 		}
1180 
1181 		if (dtuple->dtt_nkeys != nkeys)
1182 			goto next;
1183 
1184 		for (i = 0; i < nkeys; i++, dkey++) {
1185 			if (dkey->dttk_size != key[i].dttk_size)
1186 				goto next; /* size or type mismatch */
1187 
1188 			if (dkey->dttk_size != 0) {
1189 				if (dtrace_bcmp(
1190 				    (void *)(uintptr_t)key[i].dttk_value,
1191 				    (void *)(uintptr_t)dkey->dttk_value,
1192 				    dkey->dttk_size))
1193 					goto next;
1194 			} else {
1195 				if (dkey->dttk_value != key[i].dttk_value)
1196 					goto next;
1197 			}
1198 		}
1199 
1200 		if (op != DTRACE_DYNVAR_DEALLOC)
1201 			return (dvar);
1202 
1203 		ASSERT(dvar->dtdv_next == NULL ||
1204 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1205 
1206 		if (prev != NULL) {
1207 			ASSERT(hash[bucket].dtdh_chain != dvar);
1208 			ASSERT(start != dvar);
1209 			ASSERT(prev->dtdv_next == dvar);
1210 			prev->dtdv_next = dvar->dtdv_next;
1211 		} else {
1212 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1213 			    start, dvar->dtdv_next) != start) {
1214 				/*
1215 				 * We have failed to atomically swing the
1216 				 * hash table head pointer, presumably because
1217 				 * of a conflicting allocation on another CPU.
1218 				 * We need to reread the hash chain and try
1219 				 * again.
1220 				 */
1221 				goto top;
1222 			}
1223 		}
1224 
1225 		dtrace_membar_producer();
1226 
1227 		/*
1228 		 * Now set the hash value to indicate that it's free.
1229 		 */
1230 		ASSERT(hash[bucket].dtdh_chain != dvar);
1231 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1232 
1233 		dtrace_membar_producer();
1234 
1235 		/*
1236 		 * Set the next pointer to point at the dirty list, and
1237 		 * atomically swing the dirty pointer to the newly freed dvar.
1238 		 */
1239 		do {
1240 			next = dcpu->dtdsc_dirty;
1241 			dvar->dtdv_next = next;
1242 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1243 
1244 		/*
1245 		 * Finally, unlock this hash bucket.
1246 		 */
1247 		ASSERT(hash[bucket].dtdh_lock == lock);
1248 		ASSERT(lock & 1);
1249 		hash[bucket].dtdh_lock++;
1250 
1251 		return (NULL);
1252 next:
1253 		prev = dvar;
1254 		continue;
1255 	}
1256 
1257 	if (dvar == NULL) {
1258 		/*
1259 		 * If dvar is NULL, it is because we went off the rails:
1260 		 * one of the elements that we traversed in the hash chain
1261 		 * was deleted while we were traversing it.  In this case,
1262 		 * we assert that we aren't doing a dealloc (deallocs lock
1263 		 * the hash bucket to prevent themselves from racing with
1264 		 * one another), and retry the hash chain traversal.
1265 		 */
1266 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1267 		goto top;
1268 	}
1269 
1270 	if (op != DTRACE_DYNVAR_ALLOC) {
1271 		/*
1272 		 * If we are not to allocate a new variable, we want to
1273 		 * return NULL now.  Before we return, check that the value
1274 		 * of the lock word hasn't changed.  If it has, we may have
1275 		 * seen an inconsistent snapshot.
1276 		 */
1277 		if (op == DTRACE_DYNVAR_NOALLOC) {
1278 			if (hash[bucket].dtdh_lock != lock)
1279 				goto top;
1280 		} else {
1281 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1282 			ASSERT(hash[bucket].dtdh_lock == lock);
1283 			ASSERT(lock & 1);
1284 			hash[bucket].dtdh_lock++;
1285 		}
1286 
1287 		return (NULL);
1288 	}
1289 
1290 	/*
1291 	 * We need to allocate a new dynamic variable.  The size we need is the
1292 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1293 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1294 	 * the size of any referred-to data (dsize).  We then round the final
1295 	 * size up to the chunksize for allocation.
1296 	 */
1297 	for (ksize = 0, i = 0; i < nkeys; i++)
1298 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1299 
1300 	/*
1301 	 * This should be pretty much impossible, but could happen if, say,
1302 	 * strange DIF specified the tuple.  Ideally, this should be an
1303 	 * assertion and not an error condition -- but that requires that the
1304 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1305 	 * bullet-proof.  (That is, it must not be able to be fooled by
1306 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1307 	 * solving this would presumably not amount to solving the Halting
1308 	 * Problem -- but it still seems awfully hard.
1309 	 */
1310 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1311 	    ksize + dsize > chunksize) {
1312 		dcpu->dtdsc_drops++;
1313 		return (NULL);
1314 	}
1315 
1316 	nstate = DTRACE_DSTATE_EMPTY;
1317 
1318 	do {
1319 retry:
1320 		free = dcpu->dtdsc_free;
1321 
1322 		if (free == NULL) {
1323 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1324 			void *rval;
1325 
1326 			if (clean == NULL) {
1327 				/*
1328 				 * We're out of dynamic variable space on
1329 				 * this CPU.  Unless we have tried all CPUs,
1330 				 * we'll try to allocate from a different
1331 				 * CPU.
1332 				 */
1333 				switch (dstate->dtds_state) {
1334 				case DTRACE_DSTATE_CLEAN: {
1335 					void *sp = &dstate->dtds_state;
1336 
1337 					if (++cpu >= NCPU)
1338 						cpu = 0;
1339 
1340 					if (dcpu->dtdsc_dirty != NULL &&
1341 					    nstate == DTRACE_DSTATE_EMPTY)
1342 						nstate = DTRACE_DSTATE_DIRTY;
1343 
1344 					if (dcpu->dtdsc_rinsing != NULL)
1345 						nstate = DTRACE_DSTATE_RINSING;
1346 
1347 					dcpu = &dstate->dtds_percpu[cpu];
1348 
1349 					if (cpu != me)
1350 						goto retry;
1351 
1352 					(void) dtrace_cas32(sp,
1353 					    DTRACE_DSTATE_CLEAN, nstate);
1354 
1355 					/*
1356 					 * To increment the correct bean
1357 					 * counter, take another lap.
1358 					 */
1359 					goto retry;
1360 				}
1361 
1362 				case DTRACE_DSTATE_DIRTY:
1363 					dcpu->dtdsc_dirty_drops++;
1364 					break;
1365 
1366 				case DTRACE_DSTATE_RINSING:
1367 					dcpu->dtdsc_rinsing_drops++;
1368 					break;
1369 
1370 				case DTRACE_DSTATE_EMPTY:
1371 					dcpu->dtdsc_drops++;
1372 					break;
1373 				}
1374 
1375 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1376 				return (NULL);
1377 			}
1378 
1379 			/*
1380 			 * The clean list appears to be non-empty.  We want to
1381 			 * move the clean list to the free list; we start by
1382 			 * moving the clean pointer aside.
1383 			 */
1384 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1385 			    clean, NULL) != clean) {
1386 				/*
1387 				 * We are in one of two situations:
1388 				 *
1389 				 *  (a)	The clean list was switched to the
1390 				 *	free list by another CPU.
1391 				 *
1392 				 *  (b)	The clean list was added to by the
1393 				 *	cleansing cyclic.
1394 				 *
1395 				 * In either of these situations, we can
1396 				 * just reattempt the free list allocation.
1397 				 */
1398 				goto retry;
1399 			}
1400 
1401 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1402 
1403 			/*
1404 			 * Now we'll move the clean list to the free list.
1405 			 * It's impossible for this to fail:  the only way
1406 			 * the free list can be updated is through this
1407 			 * code path, and only one CPU can own the clean list.
1408 			 * Thus, it would only be possible for this to fail if
1409 			 * this code were racing with dtrace_dynvar_clean().
1410 			 * (That is, if dtrace_dynvar_clean() updated the clean
1411 			 * list, and we ended up racing to update the free
1412 			 * list.)  This race is prevented by the dtrace_sync()
1413 			 * in dtrace_dynvar_clean() -- which flushes the
1414 			 * owners of the clean lists out before resetting
1415 			 * the clean lists.
1416 			 */
1417 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1418 			ASSERT(rval == NULL);
1419 			goto retry;
1420 		}
1421 
1422 		dvar = free;
1423 		new_free = dvar->dtdv_next;
1424 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1425 
1426 	/*
1427 	 * We have now allocated a new chunk.  We copy the tuple keys into the
1428 	 * tuple array and copy any referenced key data into the data space
1429 	 * following the tuple array.  As we do this, we relocate dttk_value
1430 	 * in the final tuple to point to the key data address in the chunk.
1431 	 */
1432 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1433 	dvar->dtdv_data = (void *)(kdata + ksize);
1434 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
1435 
1436 	for (i = 0; i < nkeys; i++) {
1437 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1438 		size_t kesize = key[i].dttk_size;
1439 
1440 		if (kesize != 0) {
1441 			dtrace_bcopy(
1442 			    (const void *)(uintptr_t)key[i].dttk_value,
1443 			    (void *)kdata, kesize);
1444 			dkey->dttk_value = kdata;
1445 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1446 		} else {
1447 			dkey->dttk_value = key[i].dttk_value;
1448 		}
1449 
1450 		dkey->dttk_size = kesize;
1451 	}
1452 
1453 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1454 	dvar->dtdv_hashval = hashval;
1455 	dvar->dtdv_next = start;
1456 
1457 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1458 		return (dvar);
1459 
1460 	/*
1461 	 * The cas has failed.  Either another CPU is adding an element to
1462 	 * this hash chain, or another CPU is deleting an element from this
1463 	 * hash chain.  The simplest way to deal with both of these cases
1464 	 * (though not necessarily the most efficient) is to free our
1465 	 * allocated block and tail-call ourselves.  Note that the free is
1466 	 * to the dirty list and _not_ to the free list.  This is to prevent
1467 	 * races with allocators, above.
1468 	 */
1469 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1470 
1471 	dtrace_membar_producer();
1472 
1473 	do {
1474 		free = dcpu->dtdsc_dirty;
1475 		dvar->dtdv_next = free;
1476 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1477 
1478 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op));
1479 }
1480 
1481 /*ARGSUSED*/
1482 static void
1483 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1484 {
1485 	if (nval < *oval)
1486 		*oval = nval;
1487 }
1488 
1489 /*ARGSUSED*/
1490 static void
1491 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1492 {
1493 	if (nval > *oval)
1494 		*oval = nval;
1495 }
1496 
1497 static void
1498 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1499 {
1500 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1501 	int64_t val = (int64_t)nval;
1502 
1503 	if (val < 0) {
1504 		for (i = 0; i < zero; i++) {
1505 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1506 				quanta[i] += incr;
1507 				return;
1508 			}
1509 		}
1510 	} else {
1511 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1512 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1513 				quanta[i - 1] += incr;
1514 				return;
1515 			}
1516 		}
1517 
1518 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1519 		return;
1520 	}
1521 
1522 	ASSERT(0);
1523 }
1524 
1525 static void
1526 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1527 {
1528 	uint64_t arg = *lquanta++;
1529 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1530 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1531 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1532 	int32_t val = (int32_t)nval, level;
1533 
1534 	ASSERT(step != 0);
1535 	ASSERT(levels != 0);
1536 
1537 	if (val < base) {
1538 		/*
1539 		 * This is an underflow.
1540 		 */
1541 		lquanta[0] += incr;
1542 		return;
1543 	}
1544 
1545 	level = (val - base) / step;
1546 
1547 	if (level < levels) {
1548 		lquanta[level + 1] += incr;
1549 		return;
1550 	}
1551 
1552 	/*
1553 	 * This is an overflow.
1554 	 */
1555 	lquanta[levels + 1] += incr;
1556 }
1557 
1558 /*ARGSUSED*/
1559 static void
1560 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
1561 {
1562 	data[0]++;
1563 	data[1] += nval;
1564 }
1565 
1566 /*ARGSUSED*/
1567 static void
1568 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
1569 {
1570 	*oval = *oval + 1;
1571 }
1572 
1573 /*ARGSUSED*/
1574 static void
1575 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
1576 {
1577 	*oval += nval;
1578 }
1579 
1580 /*
1581  * Aggregate given the tuple in the principal data buffer, and the aggregating
1582  * action denoted by the specified dtrace_aggregation_t.  The aggregation
1583  * buffer is specified as the buf parameter.  This routine does not return
1584  * failure; if there is no space in the aggregation buffer, the data will be
1585  * dropped, and a corresponding counter incremented.
1586  */
1587 static void
1588 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
1589     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
1590 {
1591 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
1592 	uint32_t i, ndx, size, fsize;
1593 	uint32_t align = sizeof (uint64_t) - 1;
1594 	dtrace_aggbuffer_t *agb;
1595 	dtrace_aggkey_t *key;
1596 	uint32_t hashval = 0, limit, isstr;
1597 	caddr_t tomax, data, kdata;
1598 	dtrace_actkind_t action;
1599 	dtrace_action_t *act;
1600 	uintptr_t offs;
1601 
1602 	if (buf == NULL)
1603 		return;
1604 
1605 	if (!agg->dtag_hasarg) {
1606 		/*
1607 		 * Currently, only quantize() and lquantize() take additional
1608 		 * arguments, and they have the same semantics:  an increment
1609 		 * value that defaults to 1 when not present.  If additional
1610 		 * aggregating actions take arguments, the setting of the
1611 		 * default argument value will presumably have to become more
1612 		 * sophisticated...
1613 		 */
1614 		arg = 1;
1615 	}
1616 
1617 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
1618 	size = rec->dtrd_offset - agg->dtag_base;
1619 	fsize = size + rec->dtrd_size;
1620 
1621 	ASSERT(dbuf->dtb_tomax != NULL);
1622 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
1623 
1624 	if ((tomax = buf->dtb_tomax) == NULL) {
1625 		dtrace_buffer_drop(buf);
1626 		return;
1627 	}
1628 
1629 	/*
1630 	 * The metastructure is always at the bottom of the buffer.
1631 	 */
1632 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
1633 	    sizeof (dtrace_aggbuffer_t));
1634 
1635 	if (buf->dtb_offset == 0) {
1636 		/*
1637 		 * We just kludge up approximately 1/8th of the size to be
1638 		 * buckets.  If this guess ends up being routinely
1639 		 * off-the-mark, we may need to dynamically readjust this
1640 		 * based on past performance.
1641 		 */
1642 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
1643 
1644 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
1645 		    (uintptr_t)tomax || hashsize == 0) {
1646 			/*
1647 			 * We've been given a ludicrously small buffer;
1648 			 * increment our drop count and leave.
1649 			 */
1650 			dtrace_buffer_drop(buf);
1651 			return;
1652 		}
1653 
1654 		/*
1655 		 * And now, a pathetic attempt to try to get a an odd (or
1656 		 * perchance, a prime) hash size for better hash distribution.
1657 		 */
1658 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
1659 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
1660 
1661 		agb->dtagb_hashsize = hashsize;
1662 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
1663 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
1664 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
1665 
1666 		for (i = 0; i < agb->dtagb_hashsize; i++)
1667 			agb->dtagb_hash[i] = NULL;
1668 	}
1669 
1670 	ASSERT(agg->dtag_first != NULL);
1671 	ASSERT(agg->dtag_first->dta_intuple);
1672 
1673 	/*
1674 	 * Calculate the hash value based on the key.  Note that we _don't_
1675 	 * include the aggid in the hashing (but we will store it as part of
1676 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
1677 	 * algorithm: a simple, quick algorithm that has no known funnels, and
1678 	 * gets good distribution in practice.  The efficacy of the hashing
1679 	 * algorithm (and a comparison with other algorithms) may be found by
1680 	 * running the ::dtrace_aggstat MDB dcmd.
1681 	 */
1682 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1683 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1684 		limit = i + act->dta_rec.dtrd_size;
1685 		ASSERT(limit <= size);
1686 		isstr = DTRACEACT_ISSTRING(act);
1687 
1688 		for (; i < limit; i++) {
1689 			hashval += data[i];
1690 			hashval += (hashval << 10);
1691 			hashval ^= (hashval >> 6);
1692 
1693 			if (isstr && data[i] == '\0')
1694 				break;
1695 		}
1696 	}
1697 
1698 	hashval += (hashval << 3);
1699 	hashval ^= (hashval >> 11);
1700 	hashval += (hashval << 15);
1701 
1702 	/*
1703 	 * Yes, the divide here is expensive -- but it's generally the least
1704 	 * of the performance issues given the amount of data that we iterate
1705 	 * over to compute hash values, compare data, etc.
1706 	 */
1707 	ndx = hashval % agb->dtagb_hashsize;
1708 
1709 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
1710 		ASSERT((caddr_t)key >= tomax);
1711 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
1712 
1713 		if (hashval != key->dtak_hashval || key->dtak_size != size)
1714 			continue;
1715 
1716 		kdata = key->dtak_data;
1717 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
1718 
1719 		for (act = agg->dtag_first; act->dta_intuple;
1720 		    act = act->dta_next) {
1721 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
1722 			limit = i + act->dta_rec.dtrd_size;
1723 			ASSERT(limit <= size);
1724 			isstr = DTRACEACT_ISSTRING(act);
1725 
1726 			for (; i < limit; i++) {
1727 				if (kdata[i] != data[i])
1728 					goto next;
1729 
1730 				if (isstr && data[i] == '\0')
1731 					break;
1732 			}
1733 		}
1734 
1735 		if (action != key->dtak_action) {
1736 			/*
1737 			 * We are aggregating on the same value in the same
1738 			 * aggregation with two different aggregating actions.
1739 			 * (This should have been picked up in the compiler,
1740 			 * so we may be dealing with errant or devious DIF.)
1741 			 * This is an error condition; we indicate as much,
1742 			 * and return.
1743 			 */
1744 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
1745 			return;
1746 		}
1747 
1748 		/*
1749 		 * This is a hit:  we need to apply the aggregator to
1750 		 * the value at this key.
1751 		 */
1752 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
1753 		return;
1754 next:
1755 		continue;
1756 	}
1757 
1758 	/*
1759 	 * We didn't find it.  We need to allocate some zero-filled space,
1760 	 * link it into the hash table appropriately, and apply the aggregator
1761 	 * to the (zero-filled) value.
1762 	 */
1763 	offs = buf->dtb_offset;
1764 	while (offs & (align - 1))
1765 		offs += sizeof (uint32_t);
1766 
1767 	/*
1768 	 * If we don't have enough room to both allocate a new key _and_
1769 	 * its associated data, increment the drop count and return.
1770 	 */
1771 	if ((uintptr_t)tomax + offs + fsize >
1772 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
1773 		dtrace_buffer_drop(buf);
1774 		return;
1775 	}
1776 
1777 	/*CONSTCOND*/
1778 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
1779 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
1780 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
1781 
1782 	key->dtak_data = kdata = tomax + offs;
1783 	buf->dtb_offset = offs + fsize;
1784 
1785 	/*
1786 	 * Now copy the data across.
1787 	 */
1788 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
1789 
1790 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
1791 		kdata[i] = data[i];
1792 
1793 	/*
1794 	 * Because strings are not zeroed out by default, we need to iterate
1795 	 * looking for actions that store strings, and we need to explicitly
1796 	 * pad these strings out with zeroes.
1797 	 */
1798 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1799 		int nul;
1800 
1801 		if (!DTRACEACT_ISSTRING(act))
1802 			continue;
1803 
1804 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1805 		limit = i + act->dta_rec.dtrd_size;
1806 		ASSERT(limit <= size);
1807 
1808 		for (nul = 0; i < limit; i++) {
1809 			if (nul) {
1810 				kdata[i] = '\0';
1811 				continue;
1812 			}
1813 
1814 			if (data[i] != '\0')
1815 				continue;
1816 
1817 			nul = 1;
1818 		}
1819 	}
1820 
1821 	for (i = size; i < fsize; i++)
1822 		kdata[i] = 0;
1823 
1824 	key->dtak_hashval = hashval;
1825 	key->dtak_size = size;
1826 	key->dtak_action = action;
1827 	key->dtak_next = agb->dtagb_hash[ndx];
1828 	agb->dtagb_hash[ndx] = key;
1829 
1830 	/*
1831 	 * Finally, apply the aggregator.
1832 	 */
1833 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
1834 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
1835 }
1836 
1837 /*
1838  * Given consumer state, this routine finds a speculation in the INACTIVE
1839  * state and transitions it into the ACTIVE state.  If there is no speculation
1840  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
1841  * incremented -- it is up to the caller to take appropriate action.
1842  */
1843 static int
1844 dtrace_speculation(dtrace_state_t *state)
1845 {
1846 	int i = 0;
1847 	dtrace_speculation_state_t current;
1848 	uint32_t *stat = &state->dts_speculations_unavail, count;
1849 
1850 	while (i < state->dts_nspeculations) {
1851 		dtrace_speculation_t *spec = &state->dts_speculations[i];
1852 
1853 		current = spec->dtsp_state;
1854 
1855 		if (current != DTRACESPEC_INACTIVE) {
1856 			if (current == DTRACESPEC_COMMITTINGMANY ||
1857 			    current == DTRACESPEC_COMMITTING ||
1858 			    current == DTRACESPEC_DISCARDING)
1859 				stat = &state->dts_speculations_busy;
1860 			i++;
1861 			continue;
1862 		}
1863 
1864 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
1865 		    current, DTRACESPEC_ACTIVE) == current)
1866 			return (i + 1);
1867 	}
1868 
1869 	/*
1870 	 * We couldn't find a speculation.  If we found as much as a single
1871 	 * busy speculation buffer, we'll attribute this failure as "busy"
1872 	 * instead of "unavail".
1873 	 */
1874 	do {
1875 		count = *stat;
1876 	} while (dtrace_cas32(stat, count, count + 1) != count);
1877 
1878 	return (0);
1879 }
1880 
1881 /*
1882  * This routine commits an active speculation.  If the specified speculation
1883  * is not in a valid state to perform a commit(), this routine will silently do
1884  * nothing.  The state of the specified speculation is transitioned according
1885  * to the state transition diagram outlined in <sys/dtrace_impl.h>
1886  */
1887 static void
1888 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
1889     dtrace_specid_t which)
1890 {
1891 	dtrace_speculation_t *spec;
1892 	dtrace_buffer_t *src, *dest;
1893 	uintptr_t daddr, saddr, dlimit;
1894 	dtrace_speculation_state_t current, new;
1895 	intptr_t offs;
1896 
1897 	if (which == 0)
1898 		return;
1899 
1900 	if (which > state->dts_nspeculations) {
1901 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
1902 		return;
1903 	}
1904 
1905 	spec = &state->dts_speculations[which - 1];
1906 	src = &spec->dtsp_buffer[cpu];
1907 	dest = &state->dts_buffer[cpu];
1908 
1909 	do {
1910 		current = spec->dtsp_state;
1911 
1912 		if (current == DTRACESPEC_COMMITTINGMANY)
1913 			break;
1914 
1915 		switch (current) {
1916 		case DTRACESPEC_INACTIVE:
1917 		case DTRACESPEC_DISCARDING:
1918 			return;
1919 
1920 		case DTRACESPEC_COMMITTING:
1921 			/*
1922 			 * This is only possible if we are (a) commit()'ing
1923 			 * without having done a prior speculate() on this CPU
1924 			 * and (b) racing with another commit() on a different
1925 			 * CPU.  There's nothing to do -- we just assert that
1926 			 * our offset is 0.
1927 			 */
1928 			ASSERT(src->dtb_offset == 0);
1929 			return;
1930 
1931 		case DTRACESPEC_ACTIVE:
1932 			new = DTRACESPEC_COMMITTING;
1933 			break;
1934 
1935 		case DTRACESPEC_ACTIVEONE:
1936 			/*
1937 			 * This speculation is active on one CPU.  If our
1938 			 * buffer offset is non-zero, we know that the one CPU
1939 			 * must be us.  Otherwise, we are committing on a
1940 			 * different CPU from the speculate(), and we must
1941 			 * rely on being asynchronously cleaned.
1942 			 */
1943 			if (src->dtb_offset != 0) {
1944 				new = DTRACESPEC_COMMITTING;
1945 				break;
1946 			}
1947 			/*FALLTHROUGH*/
1948 
1949 		case DTRACESPEC_ACTIVEMANY:
1950 			new = DTRACESPEC_COMMITTINGMANY;
1951 			break;
1952 
1953 		default:
1954 			ASSERT(0);
1955 		}
1956 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
1957 	    current, new) != current);
1958 
1959 	/*
1960 	 * We have set the state to indicate that we are committing this
1961 	 * speculation.  Now reserve the necessary space in the destination
1962 	 * buffer.
1963 	 */
1964 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
1965 	    sizeof (uint64_t), state, NULL)) < 0) {
1966 		dtrace_buffer_drop(dest);
1967 		goto out;
1968 	}
1969 
1970 	/*
1971 	 * We have the space; copy the buffer across.  (Note that this is a
1972 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
1973 	 * a serious performance issue, a high-performance DTrace-specific
1974 	 * bcopy() should obviously be invented.)
1975 	 */
1976 	daddr = (uintptr_t)dest->dtb_tomax + offs;
1977 	dlimit = daddr + src->dtb_offset;
1978 	saddr = (uintptr_t)src->dtb_tomax;
1979 
1980 	/*
1981 	 * First, the aligned portion.
1982 	 */
1983 	while (dlimit - daddr >= sizeof (uint64_t)) {
1984 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
1985 
1986 		daddr += sizeof (uint64_t);
1987 		saddr += sizeof (uint64_t);
1988 	}
1989 
1990 	/*
1991 	 * Now any left-over bit...
1992 	 */
1993 	while (dlimit - daddr)
1994 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
1995 
1996 	/*
1997 	 * Finally, commit the reserved space in the destination buffer.
1998 	 */
1999 	dest->dtb_offset = offs + src->dtb_offset;
2000 
2001 out:
2002 	/*
2003 	 * If we're lucky enough to be the only active CPU on this speculation
2004 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2005 	 */
2006 	if (current == DTRACESPEC_ACTIVE ||
2007 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2008 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2009 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2010 
2011 		ASSERT(rval == DTRACESPEC_COMMITTING);
2012 	}
2013 
2014 	src->dtb_offset = 0;
2015 	src->dtb_xamot_drops += src->dtb_drops;
2016 	src->dtb_drops = 0;
2017 }
2018 
2019 /*
2020  * This routine discards an active speculation.  If the specified speculation
2021  * is not in a valid state to perform a discard(), this routine will silently
2022  * do nothing.  The state of the specified speculation is transitioned
2023  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2024  */
2025 static void
2026 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2027     dtrace_specid_t which)
2028 {
2029 	dtrace_speculation_t *spec;
2030 	dtrace_speculation_state_t current, new;
2031 	dtrace_buffer_t *buf;
2032 
2033 	if (which == 0)
2034 		return;
2035 
2036 	if (which > state->dts_nspeculations) {
2037 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2038 		return;
2039 	}
2040 
2041 	spec = &state->dts_speculations[which - 1];
2042 	buf = &spec->dtsp_buffer[cpu];
2043 
2044 	do {
2045 		current = spec->dtsp_state;
2046 
2047 		switch (current) {
2048 		case DTRACESPEC_INACTIVE:
2049 		case DTRACESPEC_COMMITTINGMANY:
2050 		case DTRACESPEC_COMMITTING:
2051 		case DTRACESPEC_DISCARDING:
2052 			return;
2053 
2054 		case DTRACESPEC_ACTIVE:
2055 		case DTRACESPEC_ACTIVEMANY:
2056 			new = DTRACESPEC_DISCARDING;
2057 			break;
2058 
2059 		case DTRACESPEC_ACTIVEONE:
2060 			if (buf->dtb_offset != 0) {
2061 				new = DTRACESPEC_INACTIVE;
2062 			} else {
2063 				new = DTRACESPEC_DISCARDING;
2064 			}
2065 			break;
2066 
2067 		default:
2068 			ASSERT(0);
2069 		}
2070 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2071 	    current, new) != current);
2072 
2073 	buf->dtb_offset = 0;
2074 	buf->dtb_drops = 0;
2075 }
2076 
2077 /*
2078  * Note:  not called from probe context.  This function is called
2079  * asynchronously from cross call context to clean any speculations that are
2080  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2081  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2082  * speculation.
2083  */
2084 static void
2085 dtrace_speculation_clean_here(dtrace_state_t *state)
2086 {
2087 	dtrace_icookie_t cookie;
2088 	processorid_t cpu = CPU->cpu_id;
2089 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2090 	dtrace_specid_t i;
2091 
2092 	cookie = dtrace_interrupt_disable();
2093 
2094 	if (dest->dtb_tomax == NULL) {
2095 		dtrace_interrupt_enable(cookie);
2096 		return;
2097 	}
2098 
2099 	for (i = 0; i < state->dts_nspeculations; i++) {
2100 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2101 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2102 
2103 		if (src->dtb_tomax == NULL)
2104 			continue;
2105 
2106 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2107 			src->dtb_offset = 0;
2108 			continue;
2109 		}
2110 
2111 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2112 			continue;
2113 
2114 		if (src->dtb_offset == 0)
2115 			continue;
2116 
2117 		dtrace_speculation_commit(state, cpu, i + 1);
2118 	}
2119 
2120 	dtrace_interrupt_enable(cookie);
2121 }
2122 
2123 /*
2124  * Note:  not called from probe context.  This function is called
2125  * asynchronously (and at a regular interval) to clean any speculations that
2126  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2127  * is work to be done, it cross calls all CPUs to perform that work;
2128  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2129  * INACTIVE state until they have been cleaned by all CPUs.
2130  */
2131 static void
2132 dtrace_speculation_clean(dtrace_state_t *state)
2133 {
2134 	int work = 0, rv;
2135 	dtrace_specid_t i;
2136 
2137 	for (i = 0; i < state->dts_nspeculations; i++) {
2138 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2139 
2140 		ASSERT(!spec->dtsp_cleaning);
2141 
2142 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2143 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2144 			continue;
2145 
2146 		work++;
2147 		spec->dtsp_cleaning = 1;
2148 	}
2149 
2150 	if (!work)
2151 		return;
2152 
2153 	dtrace_xcall(DTRACE_CPUALL,
2154 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2155 
2156 	/*
2157 	 * We now know that all CPUs have committed or discarded their
2158 	 * speculation buffers, as appropriate.  We can now set the state
2159 	 * to inactive.
2160 	 */
2161 	for (i = 0; i < state->dts_nspeculations; i++) {
2162 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2163 		dtrace_speculation_state_t current, new;
2164 
2165 		if (!spec->dtsp_cleaning)
2166 			continue;
2167 
2168 		current = spec->dtsp_state;
2169 		ASSERT(current == DTRACESPEC_DISCARDING ||
2170 		    current == DTRACESPEC_COMMITTINGMANY);
2171 
2172 		new = DTRACESPEC_INACTIVE;
2173 
2174 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2175 		ASSERT(rv == current);
2176 		spec->dtsp_cleaning = 0;
2177 	}
2178 }
2179 
2180 /*
2181  * Called as part of a speculate() to get the speculative buffer associated
2182  * with a given speculation.  Returns NULL if the specified speculation is not
2183  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2184  * the active CPU is not the specified CPU -- the speculation will be
2185  * atomically transitioned into the ACTIVEMANY state.
2186  */
2187 static dtrace_buffer_t *
2188 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2189     dtrace_specid_t which)
2190 {
2191 	dtrace_speculation_t *spec;
2192 	dtrace_speculation_state_t current, new;
2193 	dtrace_buffer_t *buf;
2194 
2195 	if (which == 0)
2196 		return (NULL);
2197 
2198 	if (which > state->dts_nspeculations) {
2199 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2200 		return (NULL);
2201 	}
2202 
2203 	spec = &state->dts_speculations[which - 1];
2204 	buf = &spec->dtsp_buffer[cpuid];
2205 
2206 	do {
2207 		current = spec->dtsp_state;
2208 
2209 		switch (current) {
2210 		case DTRACESPEC_INACTIVE:
2211 		case DTRACESPEC_COMMITTINGMANY:
2212 		case DTRACESPEC_DISCARDING:
2213 			return (NULL);
2214 
2215 		case DTRACESPEC_COMMITTING:
2216 			ASSERT(buf->dtb_offset == 0);
2217 			return (NULL);
2218 
2219 		case DTRACESPEC_ACTIVEONE:
2220 			/*
2221 			 * This speculation is currently active on one CPU.
2222 			 * Check the offset in the buffer; if it's non-zero,
2223 			 * that CPU must be us (and we leave the state alone).
2224 			 * If it's zero, assume that we're starting on a new
2225 			 * CPU -- and change the state to indicate that the
2226 			 * speculation is active on more than one CPU.
2227 			 */
2228 			if (buf->dtb_offset != 0)
2229 				return (buf);
2230 
2231 			new = DTRACESPEC_ACTIVEMANY;
2232 			break;
2233 
2234 		case DTRACESPEC_ACTIVEMANY:
2235 			return (buf);
2236 
2237 		case DTRACESPEC_ACTIVE:
2238 			new = DTRACESPEC_ACTIVEONE;
2239 			break;
2240 
2241 		default:
2242 			ASSERT(0);
2243 		}
2244 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2245 	    current, new) != current);
2246 
2247 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2248 	return (buf);
2249 }
2250 
2251 /*
2252  * This function implements the DIF emulator's variable lookups.  The emulator
2253  * passes a reserved variable identifier and optional built-in array index.
2254  */
2255 static uint64_t
2256 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2257     uint64_t ndx)
2258 {
2259 	/*
2260 	 * If we're accessing one of the uncached arguments, we'll turn this
2261 	 * into a reference in the args array.
2262 	 */
2263 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2264 		ndx = v - DIF_VAR_ARG0;
2265 		v = DIF_VAR_ARGS;
2266 	}
2267 
2268 	switch (v) {
2269 	case DIF_VAR_ARGS:
2270 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2271 		if (ndx >= sizeof (mstate->dtms_arg) /
2272 		    sizeof (mstate->dtms_arg[0])) {
2273 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2274 			dtrace_provider_t *pv;
2275 			uint64_t val;
2276 
2277 			pv = mstate->dtms_probe->dtpr_provider;
2278 			if (pv->dtpv_pops.dtps_getargval != NULL)
2279 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2280 				    mstate->dtms_probe->dtpr_id,
2281 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
2282 			else
2283 				val = dtrace_getarg(ndx, aframes);
2284 
2285 			/*
2286 			 * This is regrettably required to keep the compiler
2287 			 * from tail-optimizing the call to dtrace_getarg().
2288 			 * The condition always evaluates to true, but the
2289 			 * compiler has no way of figuring that out a priori.
2290 			 * (None of this would be necessary if the compiler
2291 			 * could be relied upon to _always_ tail-optimize
2292 			 * the call to dtrace_getarg() -- but it can't.)
2293 			 */
2294 			if (mstate->dtms_probe != NULL)
2295 				return (val);
2296 
2297 			ASSERT(0);
2298 		}
2299 
2300 		return (mstate->dtms_arg[ndx]);
2301 
2302 	case DIF_VAR_UREGS: {
2303 		klwp_t *lwp;
2304 
2305 		if (!dtrace_priv_proc(state))
2306 			return (0);
2307 
2308 		if ((lwp = curthread->t_lwp) == NULL) {
2309 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2310 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
2311 			return (0);
2312 		}
2313 
2314 		return (dtrace_getreg(lwp->lwp_regs, ndx));
2315 	}
2316 
2317 	case DIF_VAR_CURTHREAD:
2318 		if (!dtrace_priv_kernel(state))
2319 			return (0);
2320 		return ((uint64_t)(uintptr_t)curthread);
2321 
2322 	case DIF_VAR_TIMESTAMP:
2323 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2324 			mstate->dtms_timestamp = dtrace_gethrtime();
2325 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2326 		}
2327 		return (mstate->dtms_timestamp);
2328 
2329 	case DIF_VAR_VTIMESTAMP:
2330 		ASSERT(dtrace_vtime_references != 0);
2331 		return (curthread->t_dtrace_vtime);
2332 
2333 	case DIF_VAR_WALLTIMESTAMP:
2334 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2335 			mstate->dtms_walltimestamp = dtrace_gethrestime();
2336 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2337 		}
2338 		return (mstate->dtms_walltimestamp);
2339 
2340 	case DIF_VAR_IPL:
2341 		if (!dtrace_priv_kernel(state))
2342 			return (0);
2343 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2344 			mstate->dtms_ipl = dtrace_getipl();
2345 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
2346 		}
2347 		return (mstate->dtms_ipl);
2348 
2349 	case DIF_VAR_EPID:
2350 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2351 		return (mstate->dtms_epid);
2352 
2353 	case DIF_VAR_ID:
2354 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2355 		return (mstate->dtms_probe->dtpr_id);
2356 
2357 	case DIF_VAR_STACKDEPTH:
2358 		if (!dtrace_priv_kernel(state))
2359 			return (0);
2360 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2361 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2362 
2363 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2364 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2365 		}
2366 		return (mstate->dtms_stackdepth);
2367 
2368 	case DIF_VAR_USTACKDEPTH:
2369 		if (!dtrace_priv_proc(state))
2370 			return (0);
2371 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2372 			/*
2373 			 * See comment in DIF_VAR_PID.
2374 			 */
2375 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2376 			    CPU_ON_INTR(CPU)) {
2377 				mstate->dtms_ustackdepth = 0;
2378 			} else {
2379 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2380 				mstate->dtms_ustackdepth =
2381 				    dtrace_getustackdepth();
2382 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2383 			}
2384 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2385 		}
2386 		return (mstate->dtms_ustackdepth);
2387 
2388 	case DIF_VAR_CALLER:
2389 		if (!dtrace_priv_kernel(state))
2390 			return (0);
2391 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2392 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2393 
2394 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2395 				/*
2396 				 * If this is an unanchored probe, we are
2397 				 * required to go through the slow path:
2398 				 * dtrace_caller() only guarantees correct
2399 				 * results for anchored probes.
2400 				 */
2401 				pc_t caller[2];
2402 
2403 				dtrace_getpcstack(caller, 2, aframes,
2404 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2405 				mstate->dtms_caller = caller[1];
2406 			} else if ((mstate->dtms_caller =
2407 			    dtrace_caller(aframes)) == -1) {
2408 				/*
2409 				 * We have failed to do this the quick way;
2410 				 * we must resort to the slower approach of
2411 				 * calling dtrace_getpcstack().
2412 				 */
2413 				pc_t caller;
2414 
2415 				dtrace_getpcstack(&caller, 1, aframes, NULL);
2416 				mstate->dtms_caller = caller;
2417 			}
2418 
2419 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
2420 		}
2421 		return (mstate->dtms_caller);
2422 
2423 	case DIF_VAR_UCALLER:
2424 		if (!dtrace_priv_proc(state))
2425 			return (0);
2426 
2427 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
2428 			uint64_t ustack[3];
2429 
2430 			/*
2431 			 * dtrace_getupcstack() fills in the first uint64_t
2432 			 * with the current PID.  The second uint64_t will
2433 			 * be the program counter at user-level.  The third
2434 			 * uint64_t will contain the caller, which is what
2435 			 * we're after.
2436 			 */
2437 			ustack[2] = NULL;
2438 			dtrace_getupcstack(ustack, 3);
2439 			mstate->dtms_ucaller = ustack[2];
2440 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
2441 		}
2442 
2443 		return (mstate->dtms_ucaller);
2444 
2445 	case DIF_VAR_PROBEPROV:
2446 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2447 		return ((uint64_t)(uintptr_t)
2448 		    mstate->dtms_probe->dtpr_provider->dtpv_name);
2449 
2450 	case DIF_VAR_PROBEMOD:
2451 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2452 		return ((uint64_t)(uintptr_t)
2453 		    mstate->dtms_probe->dtpr_mod);
2454 
2455 	case DIF_VAR_PROBEFUNC:
2456 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2457 		return ((uint64_t)(uintptr_t)
2458 		    mstate->dtms_probe->dtpr_func);
2459 
2460 	case DIF_VAR_PROBENAME:
2461 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2462 		return ((uint64_t)(uintptr_t)
2463 		    mstate->dtms_probe->dtpr_name);
2464 
2465 	case DIF_VAR_PID:
2466 		if (!dtrace_priv_proc(state))
2467 			return (0);
2468 
2469 		/*
2470 		 * Note that we are assuming that an unanchored probe is
2471 		 * always due to a high-level interrupt.  (And we're assuming
2472 		 * that there is only a single high level interrupt.)
2473 		 */
2474 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2475 			return (pid0.pid_id);
2476 
2477 		/*
2478 		 * It is always safe to dereference one's own t_procp pointer:
2479 		 * it always points to a valid, allocated proc structure.
2480 		 * Further, it is always safe to dereference the p_pidp member
2481 		 * of one's own proc structure.  (These are truisms becuase
2482 		 * threads and processes don't clean up their own state --
2483 		 * they leave that task to whomever reaps them.)
2484 		 */
2485 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
2486 
2487 	case DIF_VAR_PPID:
2488 		if (!dtrace_priv_proc(state))
2489 			return (0);
2490 
2491 		/*
2492 		 * See comment in DIF_VAR_PID.
2493 		 */
2494 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2495 			return (pid0.pid_id);
2496 
2497 		/*
2498 		 * It is always safe to dereference one's own t_procp pointer:
2499 		 * it always points to a valid, allocated proc structure.
2500 		 * (This is true because threads don't clean up their own
2501 		 * state -- they leave that task to whomever reaps them.)
2502 		 */
2503 		return ((uint64_t)curthread->t_procp->p_ppid);
2504 
2505 	case DIF_VAR_TID:
2506 		/*
2507 		 * See comment in DIF_VAR_PID.
2508 		 */
2509 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2510 			return (0);
2511 
2512 		return ((uint64_t)curthread->t_tid);
2513 
2514 	case DIF_VAR_EXECNAME:
2515 		if (!dtrace_priv_proc(state))
2516 			return (0);
2517 
2518 		/*
2519 		 * See comment in DIF_VAR_PID.
2520 		 */
2521 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2522 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
2523 
2524 		/*
2525 		 * It is always safe to dereference one's own t_procp pointer:
2526 		 * it always points to a valid, allocated proc structure.
2527 		 * (This is true because threads don't clean up their own
2528 		 * state -- they leave that task to whomever reaps them.)
2529 		 */
2530 		return ((uint64_t)(uintptr_t)
2531 		    curthread->t_procp->p_user.u_comm);
2532 
2533 	case DIF_VAR_ZONENAME:
2534 		if (!dtrace_priv_proc(state))
2535 			return (0);
2536 
2537 		/*
2538 		 * See comment in DIF_VAR_PID.
2539 		 */
2540 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2541 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
2542 
2543 		/*
2544 		 * It is always safe to dereference one's own t_procp pointer:
2545 		 * it always points to a valid, allocated proc structure.
2546 		 * (This is true because threads don't clean up their own
2547 		 * state -- they leave that task to whomever reaps them.)
2548 		 */
2549 		return ((uint64_t)(uintptr_t)
2550 		    curthread->t_procp->p_zone->zone_name);
2551 
2552 	case DIF_VAR_UID:
2553 		if (!dtrace_priv_proc(state))
2554 			return (0);
2555 
2556 		/*
2557 		 * See comment in DIF_VAR_PID.
2558 		 */
2559 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2560 			return ((uint64_t)p0.p_cred->cr_uid);
2561 
2562 		/*
2563 		 * It is always safe to dereference one's own t_procp pointer:
2564 		 * it always points to a valid, allocated proc structure.
2565 		 * (This is true because threads don't clean up their own
2566 		 * state -- they leave that task to whomever reaps them.)
2567 		 *
2568 		 * Additionally, it is safe to dereference one's own process
2569 		 * credential, since this is never NULL after process birth.
2570 		 */
2571 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
2572 
2573 	case DIF_VAR_GID:
2574 		if (!dtrace_priv_proc(state))
2575 			return (0);
2576 
2577 		/*
2578 		 * See comment in DIF_VAR_PID.
2579 		 */
2580 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2581 			return ((uint64_t)p0.p_cred->cr_gid);
2582 
2583 		/*
2584 		 * It is always safe to dereference one's own t_procp pointer:
2585 		 * it always points to a valid, allocated proc structure.
2586 		 * (This is true because threads don't clean up their own
2587 		 * state -- they leave that task to whomever reaps them.)
2588 		 *
2589 		 * Additionally, it is safe to dereference one's own process
2590 		 * credential, since this is never NULL after process birth.
2591 		 */
2592 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
2593 
2594 	case DIF_VAR_ERRNO: {
2595 		klwp_t *lwp;
2596 		if (!dtrace_priv_proc(state))
2597 			return (0);
2598 
2599 		/*
2600 		 * See comment in DIF_VAR_PID.
2601 		 */
2602 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2603 			return (0);
2604 
2605 		/*
2606 		 * It is always safe to dereference one's own t_lwp pointer in
2607 		 * the event that this pointer is non-NULL.  (This is true
2608 		 * because threads and lwps don't clean up their own state --
2609 		 * they leave that task to whomever reaps them.)
2610 		 */
2611 		if ((lwp = curthread->t_lwp) == NULL)
2612 			return (0);
2613 
2614 		return ((uint64_t)lwp->lwp_errno);
2615 	}
2616 	default:
2617 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2618 		return (0);
2619 	}
2620 }
2621 
2622 /*
2623  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
2624  * Notice that we don't bother validating the proper number of arguments or
2625  * their types in the tuple stack.  This isn't needed because all argument
2626  * interpretation is safe because of our load safety -- the worst that can
2627  * happen is that a bogus program can obtain bogus results.
2628  */
2629 static void
2630 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
2631     dtrace_key_t *tupregs, int nargs,
2632     dtrace_mstate_t *mstate, dtrace_state_t *state)
2633 {
2634 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
2635 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
2636 
2637 	union {
2638 		mutex_impl_t mi;
2639 		uint64_t mx;
2640 	} m;
2641 
2642 	union {
2643 		krwlock_t ri;
2644 		uintptr_t rw;
2645 	} r;
2646 
2647 	switch (subr) {
2648 	case DIF_SUBR_RAND:
2649 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
2650 		break;
2651 
2652 	case DIF_SUBR_MUTEX_OWNED:
2653 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2654 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
2655 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
2656 		else
2657 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
2658 		break;
2659 
2660 	case DIF_SUBR_MUTEX_OWNER:
2661 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2662 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
2663 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
2664 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
2665 		else
2666 			regs[rd] = 0;
2667 		break;
2668 
2669 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
2670 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2671 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
2672 		break;
2673 
2674 	case DIF_SUBR_MUTEX_TYPE_SPIN:
2675 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2676 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
2677 		break;
2678 
2679 	case DIF_SUBR_RW_READ_HELD: {
2680 		uintptr_t tmp;
2681 
2682 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2683 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
2684 		break;
2685 	}
2686 
2687 	case DIF_SUBR_RW_WRITE_HELD:
2688 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2689 		regs[rd] = _RW_WRITE_HELD(&r.ri);
2690 		break;
2691 
2692 	case DIF_SUBR_RW_ISWRITER:
2693 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2694 		regs[rd] = _RW_ISWRITER(&r.ri);
2695 		break;
2696 
2697 	case DIF_SUBR_BCOPY: {
2698 		/*
2699 		 * We need to be sure that the destination is in the scratch
2700 		 * region -- no other region is allowed.
2701 		 */
2702 		uintptr_t src = tupregs[0].dttk_value;
2703 		uintptr_t dest = tupregs[1].dttk_value;
2704 		size_t size = tupregs[2].dttk_value;
2705 
2706 		if (!dtrace_inscratch(dest, size, mstate)) {
2707 			*flags |= CPU_DTRACE_BADADDR;
2708 			*illval = regs[rd];
2709 			break;
2710 		}
2711 
2712 		dtrace_bcopy((void *)src, (void *)dest, size);
2713 		break;
2714 	}
2715 
2716 	case DIF_SUBR_ALLOCA:
2717 	case DIF_SUBR_COPYIN: {
2718 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
2719 		uint64_t size =
2720 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
2721 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
2722 
2723 		/*
2724 		 * This action doesn't require any credential checks since
2725 		 * probes will not activate in user contexts to which the
2726 		 * enabling user does not have permissions.
2727 		 */
2728 		if (mstate->dtms_scratch_ptr + scratch_size >
2729 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2730 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2731 			regs[rd] = NULL;
2732 			break;
2733 		}
2734 
2735 		if (subr == DIF_SUBR_COPYIN) {
2736 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2737 			dtrace_copyin(tupregs[0].dttk_value, dest, size);
2738 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2739 		}
2740 
2741 		mstate->dtms_scratch_ptr += scratch_size;
2742 		regs[rd] = dest;
2743 		break;
2744 	}
2745 
2746 	case DIF_SUBR_COPYINTO: {
2747 		uint64_t size = tupregs[1].dttk_value;
2748 		uintptr_t dest = tupregs[2].dttk_value;
2749 
2750 		/*
2751 		 * This action doesn't require any credential checks since
2752 		 * probes will not activate in user contexts to which the
2753 		 * enabling user does not have permissions.
2754 		 */
2755 		if (!dtrace_inscratch(dest, size, mstate)) {
2756 			*flags |= CPU_DTRACE_BADADDR;
2757 			*illval = regs[rd];
2758 			break;
2759 		}
2760 
2761 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2762 		dtrace_copyin(tupregs[0].dttk_value, dest, size);
2763 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2764 		break;
2765 	}
2766 
2767 	case DIF_SUBR_COPYINSTR: {
2768 		uintptr_t dest = mstate->dtms_scratch_ptr;
2769 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2770 
2771 		if (nargs > 1 && tupregs[1].dttk_value < size)
2772 			size = tupregs[1].dttk_value + 1;
2773 
2774 		/*
2775 		 * This action doesn't require any credential checks since
2776 		 * probes will not activate in user contexts to which the
2777 		 * enabling user does not have permissions.
2778 		 */
2779 		if (mstate->dtms_scratch_ptr + size >
2780 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2781 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2782 			regs[rd] = NULL;
2783 			break;
2784 		}
2785 
2786 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2787 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size);
2788 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2789 
2790 		((char *)dest)[size - 1] = '\0';
2791 		mstate->dtms_scratch_ptr += size;
2792 		regs[rd] = dest;
2793 		break;
2794 	}
2795 
2796 	case DIF_SUBR_MSGSIZE:
2797 	case DIF_SUBR_MSGDSIZE: {
2798 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
2799 		uintptr_t wptr, rptr;
2800 		size_t count = 0;
2801 		int cont = 0;
2802 
2803 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
2804 			wptr = dtrace_loadptr(baddr +
2805 			    offsetof(mblk_t, b_wptr));
2806 
2807 			rptr = dtrace_loadptr(baddr +
2808 			    offsetof(mblk_t, b_rptr));
2809 
2810 			if (wptr < rptr) {
2811 				*flags |= CPU_DTRACE_BADADDR;
2812 				*illval = tupregs[0].dttk_value;
2813 				break;
2814 			}
2815 
2816 			daddr = dtrace_loadptr(baddr +
2817 			    offsetof(mblk_t, b_datap));
2818 
2819 			baddr = dtrace_loadptr(baddr +
2820 			    offsetof(mblk_t, b_cont));
2821 
2822 			/*
2823 			 * We want to prevent against denial-of-service here,
2824 			 * so we're only going to search the list for
2825 			 * dtrace_msgdsize_max mblks.
2826 			 */
2827 			if (cont++ > dtrace_msgdsize_max) {
2828 				*flags |= CPU_DTRACE_ILLOP;
2829 				break;
2830 			}
2831 
2832 			if (subr == DIF_SUBR_MSGDSIZE) {
2833 				if (dtrace_load8(daddr +
2834 				    offsetof(dblk_t, db_type)) != M_DATA)
2835 					continue;
2836 			}
2837 
2838 			count += wptr - rptr;
2839 		}
2840 
2841 		if (!(*flags & CPU_DTRACE_FAULT))
2842 			regs[rd] = count;
2843 
2844 		break;
2845 	}
2846 
2847 	case DIF_SUBR_PROGENYOF: {
2848 		pid_t pid = tupregs[0].dttk_value;
2849 		proc_t *p;
2850 		int rval = 0;
2851 
2852 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2853 
2854 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
2855 			if (p->p_pidp->pid_id == pid) {
2856 				rval = 1;
2857 				break;
2858 			}
2859 		}
2860 
2861 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2862 
2863 		regs[rd] = rval;
2864 		break;
2865 	}
2866 
2867 	case DIF_SUBR_SPECULATION:
2868 		regs[rd] = dtrace_speculation(state);
2869 		break;
2870 
2871 	case DIF_SUBR_COPYOUT: {
2872 		uintptr_t kaddr = tupregs[0].dttk_value;
2873 		uintptr_t uaddr = tupregs[1].dttk_value;
2874 		uint64_t size = tupregs[2].dttk_value;
2875 
2876 		if (!dtrace_destructive_disallow &&
2877 		    dtrace_priv_proc_control(state) &&
2878 		    !dtrace_istoxic(kaddr, size)) {
2879 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2880 			dtrace_copyout(kaddr, uaddr, size);
2881 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2882 		}
2883 		break;
2884 	}
2885 
2886 	case DIF_SUBR_COPYOUTSTR: {
2887 		uintptr_t kaddr = tupregs[0].dttk_value;
2888 		uintptr_t uaddr = tupregs[1].dttk_value;
2889 		uint64_t size = tupregs[2].dttk_value;
2890 
2891 		if (!dtrace_destructive_disallow &&
2892 		    dtrace_priv_proc_control(state) &&
2893 		    !dtrace_istoxic(kaddr, size)) {
2894 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2895 			dtrace_copyoutstr(kaddr, uaddr, size);
2896 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2897 		}
2898 		break;
2899 	}
2900 
2901 	case DIF_SUBR_STRLEN:
2902 		regs[rd] = dtrace_strlen((char *)(uintptr_t)
2903 		    tupregs[0].dttk_value,
2904 		    state->dts_options[DTRACEOPT_STRSIZE]);
2905 		break;
2906 
2907 	case DIF_SUBR_STRCHR:
2908 	case DIF_SUBR_STRRCHR: {
2909 		/*
2910 		 * We're going to iterate over the string looking for the
2911 		 * specified character.  We will iterate until we have reached
2912 		 * the string length or we have found the character.  If this
2913 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
2914 		 * of the specified character instead of the first.
2915 		 */
2916 		uintptr_t addr = tupregs[0].dttk_value;
2917 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
2918 		char c, target = (char)tupregs[1].dttk_value;
2919 
2920 		for (regs[rd] = NULL; addr < limit; addr++) {
2921 			if ((c = dtrace_load8(addr)) == target) {
2922 				regs[rd] = addr;
2923 
2924 				if (subr == DIF_SUBR_STRCHR)
2925 					break;
2926 			}
2927 
2928 			if (c == '\0')
2929 				break;
2930 		}
2931 
2932 		break;
2933 	}
2934 
2935 	case DIF_SUBR_STRSTR:
2936 	case DIF_SUBR_INDEX:
2937 	case DIF_SUBR_RINDEX: {
2938 		/*
2939 		 * We're going to iterate over the string looking for the
2940 		 * specified string.  We will iterate until we have reached
2941 		 * the string length or we have found the string.  (Yes, this
2942 		 * is done in the most naive way possible -- but considering
2943 		 * that the string we're searching for is likely to be
2944 		 * relatively short, the complexity of Rabin-Karp or similar
2945 		 * hardly seems merited.)
2946 		 */
2947 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
2948 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
2949 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2950 		size_t len = dtrace_strlen(addr, size);
2951 		size_t sublen = dtrace_strlen(substr, size);
2952 		char *limit = addr + len, *orig = addr;
2953 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
2954 		int inc = 1;
2955 
2956 		regs[rd] = notfound;
2957 
2958 		/*
2959 		 * strstr() and index()/rindex() have similar semantics if
2960 		 * both strings are the empty string: strstr() returns a
2961 		 * pointer to the (empty) string, and index() and rindex()
2962 		 * both return index 0 (regardless of any position argument).
2963 		 */
2964 		if (sublen == 0 && len == 0) {
2965 			if (subr == DIF_SUBR_STRSTR)
2966 				regs[rd] = (uintptr_t)addr;
2967 			else
2968 				regs[rd] = 0;
2969 			break;
2970 		}
2971 
2972 		if (subr != DIF_SUBR_STRSTR) {
2973 			if (subr == DIF_SUBR_RINDEX) {
2974 				limit = orig - 1;
2975 				addr += len;
2976 				inc = -1;
2977 			}
2978 
2979 			/*
2980 			 * Both index() and rindex() take an optional position
2981 			 * argument that denotes the starting position.
2982 			 */
2983 			if (nargs == 3) {
2984 				int64_t pos = (int64_t)tupregs[2].dttk_value;
2985 
2986 				/*
2987 				 * If the position argument to index() is
2988 				 * negative, Perl implicitly clamps it at
2989 				 * zero.  This semantic is a little surprising
2990 				 * given the special meaning of negative
2991 				 * positions to similar Perl functions like
2992 				 * substr(), but it appears to reflect a
2993 				 * notion that index() can start from a
2994 				 * negative index and increment its way up to
2995 				 * the string.  Given this notion, Perl's
2996 				 * rindex() is at least self-consistent in
2997 				 * that it implicitly clamps positions greater
2998 				 * than the string length to be the string
2999 				 * length.  Where Perl completely loses
3000 				 * coherence, however, is when the specified
3001 				 * substring is the empty string ("").  In
3002 				 * this case, even if the position is
3003 				 * negative, rindex() returns 0 -- and even if
3004 				 * the position is greater than the length,
3005 				 * index() returns the string length.  These
3006 				 * semantics violate the notion that index()
3007 				 * should never return a value less than the
3008 				 * specified position and that rindex() should
3009 				 * never return a value greater than the
3010 				 * specified position.  (One assumes that
3011 				 * these semantics are artifacts of Perl's
3012 				 * implementation and not the results of
3013 				 * deliberate design -- it beggars belief that
3014 				 * even Larry Wall could desire such oddness.)
3015 				 * While in the abstract one would wish for
3016 				 * consistent position semantics across
3017 				 * substr(), index() and rindex() -- or at the
3018 				 * very least self-consistent position
3019 				 * semantics for index() and rindex() -- we
3020 				 * instead opt to keep with the extant Perl
3021 				 * semantics, in all their broken glory.  (Do
3022 				 * we have more desire to maintain Perl's
3023 				 * semantics than Perl does?  Probably.)
3024 				 */
3025 				if (subr == DIF_SUBR_RINDEX) {
3026 					if (pos < 0) {
3027 						if (sublen == 0)
3028 							regs[rd] = 0;
3029 						break;
3030 					}
3031 
3032 					if (pos > len)
3033 						pos = len;
3034 				} else {
3035 					if (pos < 0)
3036 						pos = 0;
3037 
3038 					if (pos >= len) {
3039 						if (sublen == 0)
3040 							regs[rd] = len;
3041 						break;
3042 					}
3043 				}
3044 
3045 				addr = orig + pos;
3046 			}
3047 		}
3048 
3049 		for (regs[rd] = notfound; addr != limit; addr += inc) {
3050 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
3051 				if (subr != DIF_SUBR_STRSTR) {
3052 					/*
3053 					 * As D index() and rindex() are
3054 					 * modeled on Perl (and not on awk),
3055 					 * we return a zero-based (and not a
3056 					 * one-based) index.  (For you Perl
3057 					 * weenies: no, we're not going to add
3058 					 * $[ -- and shouldn't you be at a con
3059 					 * or something?)
3060 					 */
3061 					regs[rd] = (uintptr_t)(addr - orig);
3062 					break;
3063 				}
3064 
3065 				ASSERT(subr == DIF_SUBR_STRSTR);
3066 				regs[rd] = (uintptr_t)addr;
3067 				break;
3068 			}
3069 		}
3070 
3071 		break;
3072 	}
3073 
3074 	case DIF_SUBR_STRTOK: {
3075 		uintptr_t addr = tupregs[0].dttk_value;
3076 		uintptr_t tokaddr = tupregs[1].dttk_value;
3077 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3078 		uintptr_t limit, toklimit = tokaddr + size;
3079 		uint8_t c, tokmap[32];	 /* 256 / 8 */
3080 		char *dest = (char *)mstate->dtms_scratch_ptr;
3081 		int i;
3082 
3083 		if (mstate->dtms_scratch_ptr + size >
3084 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3085 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3086 			regs[rd] = NULL;
3087 			break;
3088 		}
3089 
3090 		if (addr == NULL) {
3091 			/*
3092 			 * If the address specified is NULL, we use our saved
3093 			 * strtok pointer from the mstate.  Note that this
3094 			 * means that the saved strtok pointer is _only_
3095 			 * valid within multiple enablings of the same probe --
3096 			 * it behaves like an implicit clause-local variable.
3097 			 */
3098 			addr = mstate->dtms_strtok;
3099 		}
3100 
3101 		/*
3102 		 * First, zero the token map, and then process the token
3103 		 * string -- setting a bit in the map for every character
3104 		 * found in the token string.
3105 		 */
3106 		for (i = 0; i < sizeof (tokmap); i++)
3107 			tokmap[i] = 0;
3108 
3109 		for (; tokaddr < toklimit; tokaddr++) {
3110 			if ((c = dtrace_load8(tokaddr)) == '\0')
3111 				break;
3112 
3113 			ASSERT((c >> 3) < sizeof (tokmap));
3114 			tokmap[c >> 3] |= (1 << (c & 0x7));
3115 		}
3116 
3117 		for (limit = addr + size; addr < limit; addr++) {
3118 			/*
3119 			 * We're looking for a character that is _not_ contained
3120 			 * in the token string.
3121 			 */
3122 			if ((c = dtrace_load8(addr)) == '\0')
3123 				break;
3124 
3125 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3126 				break;
3127 		}
3128 
3129 		if (c == '\0') {
3130 			/*
3131 			 * We reached the end of the string without finding
3132 			 * any character that was not in the token string.
3133 			 * We return NULL in this case, and we set the saved
3134 			 * address to NULL as well.
3135 			 */
3136 			regs[rd] = NULL;
3137 			mstate->dtms_strtok = NULL;
3138 			break;
3139 		}
3140 
3141 		/*
3142 		 * From here on, we're copying into the destination string.
3143 		 */
3144 		for (i = 0; addr < limit && i < size - 1; addr++) {
3145 			if ((c = dtrace_load8(addr)) == '\0')
3146 				break;
3147 
3148 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
3149 				break;
3150 
3151 			ASSERT(i < size);
3152 			dest[i++] = c;
3153 		}
3154 
3155 		ASSERT(i < size);
3156 		dest[i] = '\0';
3157 		regs[rd] = (uintptr_t)dest;
3158 		mstate->dtms_scratch_ptr += size;
3159 		mstate->dtms_strtok = addr;
3160 		break;
3161 	}
3162 
3163 	case DIF_SUBR_SUBSTR: {
3164 		uintptr_t s = tupregs[0].dttk_value;
3165 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3166 		char *d = (char *)mstate->dtms_scratch_ptr;
3167 		int64_t index = (int64_t)tupregs[1].dttk_value;
3168 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
3169 		size_t len = dtrace_strlen((char *)s, size);
3170 		int64_t i = 0;
3171 
3172 		if (nargs <= 2)
3173 			remaining = (int64_t)size;
3174 
3175 		if (mstate->dtms_scratch_ptr + size >
3176 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3177 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3178 			regs[rd] = NULL;
3179 			break;
3180 		}
3181 
3182 		if (index < 0) {
3183 			index += len;
3184 
3185 			if (index < 0 && index + remaining > 0) {
3186 				remaining += index;
3187 				index = 0;
3188 			}
3189 		}
3190 
3191 		if (index >= len || index < 0)
3192 			index = len;
3193 
3194 		for (d[0] = '\0'; remaining > 0; remaining--) {
3195 			if ((d[i++] = dtrace_load8(s++ + index)) == '\0')
3196 				break;
3197 
3198 			if (i == size) {
3199 				d[i - 1] = '\0';
3200 				break;
3201 			}
3202 		}
3203 
3204 		mstate->dtms_scratch_ptr += size;
3205 		regs[rd] = (uintptr_t)d;
3206 		break;
3207 	}
3208 
3209 	case DIF_SUBR_GETMAJOR:
3210 #ifdef _LP64
3211 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
3212 #else
3213 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
3214 #endif
3215 		break;
3216 
3217 	case DIF_SUBR_GETMINOR:
3218 #ifdef _LP64
3219 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
3220 #else
3221 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
3222 #endif
3223 		break;
3224 
3225 	case DIF_SUBR_DDI_PATHNAME: {
3226 		/*
3227 		 * This one is a galactic mess.  We are going to roughly
3228 		 * emulate ddi_pathname(), but it's made more complicated
3229 		 * by the fact that we (a) want to include the minor name and
3230 		 * (b) must proceed iteratively instead of recursively.
3231 		 */
3232 		uintptr_t dest = mstate->dtms_scratch_ptr;
3233 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3234 		char *start = (char *)dest, *end = start + size - 1;
3235 		uintptr_t daddr = tupregs[0].dttk_value;
3236 		int64_t minor = (int64_t)tupregs[1].dttk_value;
3237 		char *s;
3238 		int i, len, depth = 0;
3239 
3240 		if (size == 0 || mstate->dtms_scratch_ptr + size >
3241 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3242 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3243 			regs[rd] = NULL;
3244 			break;
3245 		}
3246 
3247 		*end = '\0';
3248 
3249 		/*
3250 		 * We want to have a name for the minor.  In order to do this,
3251 		 * we need to walk the minor list from the devinfo.  We want
3252 		 * to be sure that we don't infinitely walk a circular list,
3253 		 * so we check for circularity by sending a scout pointer
3254 		 * ahead two elements for every element that we iterate over;
3255 		 * if the list is circular, these will ultimately point to the
3256 		 * same element.  You may recognize this little trick as the
3257 		 * answer to a stupid interview question -- one that always
3258 		 * seems to be asked by those who had to have it laboriously
3259 		 * explained to them, and who can't even concisely describe
3260 		 * the conditions under which one would be forced to resort to
3261 		 * this technique.  Needless to say, those conditions are
3262 		 * found here -- and probably only here.  Is this is the only
3263 		 * use of this infamous trick in shipping, production code?
3264 		 * If it isn't, it probably should be...
3265 		 */
3266 		if (minor != -1) {
3267 			uintptr_t maddr = dtrace_loadptr(daddr +
3268 			    offsetof(struct dev_info, devi_minor));
3269 
3270 			uintptr_t next = offsetof(struct ddi_minor_data, next);
3271 			uintptr_t name = offsetof(struct ddi_minor_data,
3272 			    d_minor) + offsetof(struct ddi_minor, name);
3273 			uintptr_t dev = offsetof(struct ddi_minor_data,
3274 			    d_minor) + offsetof(struct ddi_minor, dev);
3275 			uintptr_t scout;
3276 
3277 			if (maddr != NULL)
3278 				scout = dtrace_loadptr(maddr + next);
3279 
3280 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3281 				uint64_t m;
3282 #ifdef _LP64
3283 				m = dtrace_load64(maddr + dev) & MAXMIN64;
3284 #else
3285 				m = dtrace_load32(maddr + dev) & MAXMIN;
3286 #endif
3287 				if (m != minor) {
3288 					maddr = dtrace_loadptr(maddr + next);
3289 
3290 					if (scout == NULL)
3291 						continue;
3292 
3293 					scout = dtrace_loadptr(scout + next);
3294 
3295 					if (scout == NULL)
3296 						continue;
3297 
3298 					scout = dtrace_loadptr(scout + next);
3299 
3300 					if (scout == NULL)
3301 						continue;
3302 
3303 					if (scout == maddr) {
3304 						*flags |= CPU_DTRACE_ILLOP;
3305 						break;
3306 					}
3307 
3308 					continue;
3309 				}
3310 
3311 				/*
3312 				 * We have the minor data.  Now we need to
3313 				 * copy the minor's name into the end of the
3314 				 * pathname.
3315 				 */
3316 				s = (char *)dtrace_loadptr(maddr + name);
3317 				len = dtrace_strlen(s, size);
3318 
3319 				if (*flags & CPU_DTRACE_FAULT)
3320 					break;
3321 
3322 				if (len != 0) {
3323 					if ((end -= (len + 1)) < start)
3324 						break;
3325 
3326 					*end = ':';
3327 				}
3328 
3329 				for (i = 1; i <= len; i++)
3330 					end[i] = dtrace_load8((uintptr_t)s++);
3331 				break;
3332 			}
3333 		}
3334 
3335 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3336 			ddi_node_state_t devi_state;
3337 
3338 			devi_state = dtrace_load32(daddr +
3339 			    offsetof(struct dev_info, devi_node_state));
3340 
3341 			if (*flags & CPU_DTRACE_FAULT)
3342 				break;
3343 
3344 			if (devi_state >= DS_INITIALIZED) {
3345 				s = (char *)dtrace_loadptr(daddr +
3346 				    offsetof(struct dev_info, devi_addr));
3347 				len = dtrace_strlen(s, size);
3348 
3349 				if (*flags & CPU_DTRACE_FAULT)
3350 					break;
3351 
3352 				if (len != 0) {
3353 					if ((end -= (len + 1)) < start)
3354 						break;
3355 
3356 					*end = '@';
3357 				}
3358 
3359 				for (i = 1; i <= len; i++)
3360 					end[i] = dtrace_load8((uintptr_t)s++);
3361 			}
3362 
3363 			/*
3364 			 * Now for the node name...
3365 			 */
3366 			s = (char *)dtrace_loadptr(daddr +
3367 			    offsetof(struct dev_info, devi_node_name));
3368 
3369 			daddr = dtrace_loadptr(daddr +
3370 			    offsetof(struct dev_info, devi_parent));
3371 
3372 			/*
3373 			 * If our parent is NULL (that is, if we're the root
3374 			 * node), we're going to use the special path
3375 			 * "devices".
3376 			 */
3377 			if (daddr == NULL)
3378 				s = "devices";
3379 
3380 			len = dtrace_strlen(s, size);
3381 			if (*flags & CPU_DTRACE_FAULT)
3382 				break;
3383 
3384 			if ((end -= (len + 1)) < start)
3385 				break;
3386 
3387 			for (i = 1; i <= len; i++)
3388 				end[i] = dtrace_load8((uintptr_t)s++);
3389 			*end = '/';
3390 
3391 			if (depth++ > dtrace_devdepth_max) {
3392 				*flags |= CPU_DTRACE_ILLOP;
3393 				break;
3394 			}
3395 		}
3396 
3397 		if (end < start)
3398 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3399 
3400 		if (daddr == NULL) {
3401 			regs[rd] = (uintptr_t)end;
3402 			mstate->dtms_scratch_ptr += size;
3403 		}
3404 
3405 		break;
3406 	}
3407 
3408 	case DIF_SUBR_STRJOIN: {
3409 		char *d = (char *)mstate->dtms_scratch_ptr;
3410 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3411 		uintptr_t s1 = tupregs[0].dttk_value;
3412 		uintptr_t s2 = tupregs[1].dttk_value;
3413 		int i = 0;
3414 
3415 		if (mstate->dtms_scratch_ptr + size >
3416 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3417 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3418 			regs[rd] = NULL;
3419 			break;
3420 		}
3421 
3422 		for (;;) {
3423 			if (i >= size) {
3424 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3425 				regs[rd] = NULL;
3426 				break;
3427 			}
3428 
3429 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
3430 				i--;
3431 				break;
3432 			}
3433 		}
3434 
3435 		for (;;) {
3436 			if (i >= size) {
3437 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3438 				regs[rd] = NULL;
3439 				break;
3440 			}
3441 
3442 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
3443 				break;
3444 		}
3445 
3446 		if (i < size) {
3447 			mstate->dtms_scratch_ptr += i;
3448 			regs[rd] = (uintptr_t)d;
3449 		}
3450 
3451 		break;
3452 	}
3453 
3454 	case DIF_SUBR_LLTOSTR: {
3455 		int64_t i = (int64_t)tupregs[0].dttk_value;
3456 		int64_t val = i < 0 ? i * -1 : i;
3457 		uint64_t size = 22;	/* enough room for 2^64 in decimal */
3458 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
3459 
3460 		if (mstate->dtms_scratch_ptr + size >
3461 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3462 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3463 			regs[rd] = NULL;
3464 			break;
3465 		}
3466 
3467 		for (*end-- = '\0'; val; val /= 10)
3468 			*end-- = '0' + (val % 10);
3469 
3470 		if (i == 0)
3471 			*end-- = '0';
3472 
3473 		if (i < 0)
3474 			*end-- = '-';
3475 
3476 		regs[rd] = (uintptr_t)end + 1;
3477 		mstate->dtms_scratch_ptr += size;
3478 		break;
3479 	}
3480 
3481 	case DIF_SUBR_DIRNAME:
3482 	case DIF_SUBR_BASENAME: {
3483 		char *dest = (char *)mstate->dtms_scratch_ptr;
3484 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3485 		uintptr_t src = tupregs[0].dttk_value;
3486 		int i, j, len = dtrace_strlen((char *)src, size);
3487 		int lastbase = -1, firstbase = -1, lastdir = -1;
3488 		int start, end;
3489 
3490 		if (mstate->dtms_scratch_ptr + size >
3491 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3492 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3493 			regs[rd] = NULL;
3494 			break;
3495 		}
3496 
3497 		/*
3498 		 * The basename and dirname for a zero-length string is
3499 		 * defined to be "."
3500 		 */
3501 		if (len == 0) {
3502 			len = 1;
3503 			src = (uintptr_t)".";
3504 		}
3505 
3506 		/*
3507 		 * Start from the back of the string, moving back toward the
3508 		 * front until we see a character that isn't a slash.  That
3509 		 * character is the last character in the basename.
3510 		 */
3511 		for (i = len - 1; i >= 0; i--) {
3512 			if (dtrace_load8(src + i) != '/')
3513 				break;
3514 		}
3515 
3516 		if (i >= 0)
3517 			lastbase = i;
3518 
3519 		/*
3520 		 * Starting from the last character in the basename, move
3521 		 * towards the front until we find a slash.  The character
3522 		 * that we processed immediately before that is the first
3523 		 * character in the basename.
3524 		 */
3525 		for (; i >= 0; i--) {
3526 			if (dtrace_load8(src + i) == '/')
3527 				break;
3528 		}
3529 
3530 		if (i >= 0)
3531 			firstbase = i + 1;
3532 
3533 		/*
3534 		 * Now keep going until we find a non-slash character.  That
3535 		 * character is the last character in the dirname.
3536 		 */
3537 		for (; i >= 0; i--) {
3538 			if (dtrace_load8(src + i) != '/')
3539 				break;
3540 		}
3541 
3542 		if (i >= 0)
3543 			lastdir = i;
3544 
3545 		ASSERT(!(lastbase == -1 && firstbase != -1));
3546 		ASSERT(!(firstbase == -1 && lastdir != -1));
3547 
3548 		if (lastbase == -1) {
3549 			/*
3550 			 * We didn't find a non-slash character.  We know that
3551 			 * the length is non-zero, so the whole string must be
3552 			 * slashes.  In either the dirname or the basename
3553 			 * case, we return '/'.
3554 			 */
3555 			ASSERT(firstbase == -1);
3556 			firstbase = lastbase = lastdir = 0;
3557 		}
3558 
3559 		if (firstbase == -1) {
3560 			/*
3561 			 * The entire string consists only of a basename
3562 			 * component.  If we're looking for dirname, we need
3563 			 * to change our string to be just "."; if we're
3564 			 * looking for a basename, we'll just set the first
3565 			 * character of the basename to be 0.
3566 			 */
3567 			if (subr == DIF_SUBR_DIRNAME) {
3568 				ASSERT(lastdir == -1);
3569 				src = (uintptr_t)".";
3570 				lastdir = 0;
3571 			} else {
3572 				firstbase = 0;
3573 			}
3574 		}
3575 
3576 		if (subr == DIF_SUBR_DIRNAME) {
3577 			if (lastdir == -1) {
3578 				/*
3579 				 * We know that we have a slash in the name --
3580 				 * or lastdir would be set to 0, above.  And
3581 				 * because lastdir is -1, we know that this
3582 				 * slash must be the first character.  (That
3583 				 * is, the full string must be of the form
3584 				 * "/basename".)  In this case, the last
3585 				 * character of the directory name is 0.
3586 				 */
3587 				lastdir = 0;
3588 			}
3589 
3590 			start = 0;
3591 			end = lastdir;
3592 		} else {
3593 			ASSERT(subr == DIF_SUBR_BASENAME);
3594 			ASSERT(firstbase != -1 && lastbase != -1);
3595 			start = firstbase;
3596 			end = lastbase;
3597 		}
3598 
3599 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
3600 			dest[j] = dtrace_load8(src + i);
3601 
3602 		dest[j] = '\0';
3603 		regs[rd] = (uintptr_t)dest;
3604 		mstate->dtms_scratch_ptr += size;
3605 		break;
3606 	}
3607 
3608 	case DIF_SUBR_CLEANPATH: {
3609 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
3610 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3611 		uintptr_t src = tupregs[0].dttk_value;
3612 		int i = 0, j = 0;
3613 
3614 		if (mstate->dtms_scratch_ptr + size >
3615 		    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3616 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3617 			regs[rd] = NULL;
3618 			break;
3619 		}
3620 
3621 		/*
3622 		 * Move forward, loading each character.
3623 		 */
3624 		do {
3625 			c = dtrace_load8(src + i++);
3626 next:
3627 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
3628 				break;
3629 
3630 			if (c != '/') {
3631 				dest[j++] = c;
3632 				continue;
3633 			}
3634 
3635 			c = dtrace_load8(src + i++);
3636 
3637 			if (c == '/') {
3638 				/*
3639 				 * We have two slashes -- we can just advance
3640 				 * to the next character.
3641 				 */
3642 				goto next;
3643 			}
3644 
3645 			if (c != '.') {
3646 				/*
3647 				 * This is not "." and it's not ".." -- we can
3648 				 * just store the "/" and this character and
3649 				 * drive on.
3650 				 */
3651 				dest[j++] = '/';
3652 				dest[j++] = c;
3653 				continue;
3654 			}
3655 
3656 			c = dtrace_load8(src + i++);
3657 
3658 			if (c == '/') {
3659 				/*
3660 				 * This is a "/./" component.  We're not going
3661 				 * to store anything in the destination buffer;
3662 				 * we're just going to go to the next component.
3663 				 */
3664 				goto next;
3665 			}
3666 
3667 			if (c != '.') {
3668 				/*
3669 				 * This is not ".." -- we can just store the
3670 				 * "/." and this character and continue
3671 				 * processing.
3672 				 */
3673 				dest[j++] = '/';
3674 				dest[j++] = '.';
3675 				dest[j++] = c;
3676 				continue;
3677 			}
3678 
3679 			c = dtrace_load8(src + i++);
3680 
3681 			if (c != '/' && c != '\0') {
3682 				/*
3683 				 * This is not ".." -- it's "..[mumble]".
3684 				 * We'll store the "/.." and this character
3685 				 * and continue processing.
3686 				 */
3687 				dest[j++] = '/';
3688 				dest[j++] = '.';
3689 				dest[j++] = '.';
3690 				dest[j++] = c;
3691 				continue;
3692 			}
3693 
3694 			/*
3695 			 * This is "/../" or "/..\0".  We need to back up
3696 			 * our destination pointer until we find a "/".
3697 			 */
3698 			i--;
3699 			while (j != 0 && dest[--j] != '/')
3700 				continue;
3701 
3702 			if (c == '\0')
3703 				dest[++j] = '/';
3704 		} while (c != '\0');
3705 
3706 		dest[j] = '\0';
3707 		regs[rd] = (uintptr_t)dest;
3708 		mstate->dtms_scratch_ptr += size;
3709 		break;
3710 	}
3711 	}
3712 }
3713 
3714 /*
3715  * Emulate the execution of DTrace IR instructions specified by the given
3716  * DIF object.  This function is deliberately void of assertions as all of
3717  * the necessary checks are handled by a call to dtrace_difo_validate().
3718  */
3719 static uint64_t
3720 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
3721     dtrace_vstate_t *vstate, dtrace_state_t *state)
3722 {
3723 	const dif_instr_t *text = difo->dtdo_buf;
3724 	const uint_t textlen = difo->dtdo_len;
3725 	const char *strtab = difo->dtdo_strtab;
3726 	const uint64_t *inttab = difo->dtdo_inttab;
3727 
3728 	uint64_t rval = 0;
3729 	dtrace_statvar_t *svar;
3730 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
3731 	dtrace_difv_t *v;
3732 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
3733 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
3734 
3735 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
3736 	uint64_t regs[DIF_DIR_NREGS];
3737 	uint64_t *tmp;
3738 
3739 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
3740 	int64_t cc_r;
3741 	uint_t pc = 0, id, opc;
3742 	uint8_t ttop = 0;
3743 	dif_instr_t instr;
3744 	uint_t r1, r2, rd;
3745 
3746 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
3747 
3748 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
3749 		opc = pc;
3750 
3751 		instr = text[pc++];
3752 		r1 = DIF_INSTR_R1(instr);
3753 		r2 = DIF_INSTR_R2(instr);
3754 		rd = DIF_INSTR_RD(instr);
3755 
3756 		switch (DIF_INSTR_OP(instr)) {
3757 		case DIF_OP_OR:
3758 			regs[rd] = regs[r1] | regs[r2];
3759 			break;
3760 		case DIF_OP_XOR:
3761 			regs[rd] = regs[r1] ^ regs[r2];
3762 			break;
3763 		case DIF_OP_AND:
3764 			regs[rd] = regs[r1] & regs[r2];
3765 			break;
3766 		case DIF_OP_SLL:
3767 			regs[rd] = regs[r1] << regs[r2];
3768 			break;
3769 		case DIF_OP_SRL:
3770 			regs[rd] = regs[r1] >> regs[r2];
3771 			break;
3772 		case DIF_OP_SUB:
3773 			regs[rd] = regs[r1] - regs[r2];
3774 			break;
3775 		case DIF_OP_ADD:
3776 			regs[rd] = regs[r1] + regs[r2];
3777 			break;
3778 		case DIF_OP_MUL:
3779 			regs[rd] = regs[r1] * regs[r2];
3780 			break;
3781 		case DIF_OP_SDIV:
3782 			if (regs[r2] == 0) {
3783 				regs[rd] = 0;
3784 				*flags |= CPU_DTRACE_DIVZERO;
3785 			} else {
3786 				regs[rd] = (int64_t)regs[r1] /
3787 				    (int64_t)regs[r2];
3788 			}
3789 			break;
3790 
3791 		case DIF_OP_UDIV:
3792 			if (regs[r2] == 0) {
3793 				regs[rd] = 0;
3794 				*flags |= CPU_DTRACE_DIVZERO;
3795 			} else {
3796 				regs[rd] = regs[r1] / regs[r2];
3797 			}
3798 			break;
3799 
3800 		case DIF_OP_SREM:
3801 			if (regs[r2] == 0) {
3802 				regs[rd] = 0;
3803 				*flags |= CPU_DTRACE_DIVZERO;
3804 			} else {
3805 				regs[rd] = (int64_t)regs[r1] %
3806 				    (int64_t)regs[r2];
3807 			}
3808 			break;
3809 
3810 		case DIF_OP_UREM:
3811 			if (regs[r2] == 0) {
3812 				regs[rd] = 0;
3813 				*flags |= CPU_DTRACE_DIVZERO;
3814 			} else {
3815 				regs[rd] = regs[r1] % regs[r2];
3816 			}
3817 			break;
3818 
3819 		case DIF_OP_NOT:
3820 			regs[rd] = ~regs[r1];
3821 			break;
3822 		case DIF_OP_MOV:
3823 			regs[rd] = regs[r1];
3824 			break;
3825 		case DIF_OP_CMP:
3826 			cc_r = regs[r1] - regs[r2];
3827 			cc_n = cc_r < 0;
3828 			cc_z = cc_r == 0;
3829 			cc_v = 0;
3830 			cc_c = regs[r1] < regs[r2];
3831 			break;
3832 		case DIF_OP_TST:
3833 			cc_n = cc_v = cc_c = 0;
3834 			cc_z = regs[r1] == 0;
3835 			break;
3836 		case DIF_OP_BA:
3837 			pc = DIF_INSTR_LABEL(instr);
3838 			break;
3839 		case DIF_OP_BE:
3840 			if (cc_z)
3841 				pc = DIF_INSTR_LABEL(instr);
3842 			break;
3843 		case DIF_OP_BNE:
3844 			if (cc_z == 0)
3845 				pc = DIF_INSTR_LABEL(instr);
3846 			break;
3847 		case DIF_OP_BG:
3848 			if ((cc_z | (cc_n ^ cc_v)) == 0)
3849 				pc = DIF_INSTR_LABEL(instr);
3850 			break;
3851 		case DIF_OP_BGU:
3852 			if ((cc_c | cc_z) == 0)
3853 				pc = DIF_INSTR_LABEL(instr);
3854 			break;
3855 		case DIF_OP_BGE:
3856 			if ((cc_n ^ cc_v) == 0)
3857 				pc = DIF_INSTR_LABEL(instr);
3858 			break;
3859 		case DIF_OP_BGEU:
3860 			if (cc_c == 0)
3861 				pc = DIF_INSTR_LABEL(instr);
3862 			break;
3863 		case DIF_OP_BL:
3864 			if (cc_n ^ cc_v)
3865 				pc = DIF_INSTR_LABEL(instr);
3866 			break;
3867 		case DIF_OP_BLU:
3868 			if (cc_c)
3869 				pc = DIF_INSTR_LABEL(instr);
3870 			break;
3871 		case DIF_OP_BLE:
3872 			if (cc_z | (cc_n ^ cc_v))
3873 				pc = DIF_INSTR_LABEL(instr);
3874 			break;
3875 		case DIF_OP_BLEU:
3876 			if (cc_c | cc_z)
3877 				pc = DIF_INSTR_LABEL(instr);
3878 			break;
3879 		case DIF_OP_RLDSB:
3880 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
3881 				*flags |= CPU_DTRACE_KPRIV;
3882 				*illval = regs[r1];
3883 				break;
3884 			}
3885 			/*FALLTHROUGH*/
3886 		case DIF_OP_LDSB:
3887 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
3888 			break;
3889 		case DIF_OP_RLDSH:
3890 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
3891 				*flags |= CPU_DTRACE_KPRIV;
3892 				*illval = regs[r1];
3893 				break;
3894 			}
3895 			/*FALLTHROUGH*/
3896 		case DIF_OP_LDSH:
3897 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
3898 			break;
3899 		case DIF_OP_RLDSW:
3900 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
3901 				*flags |= CPU_DTRACE_KPRIV;
3902 				*illval = regs[r1];
3903 				break;
3904 			}
3905 			/*FALLTHROUGH*/
3906 		case DIF_OP_LDSW:
3907 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
3908 			break;
3909 		case DIF_OP_RLDUB:
3910 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
3911 				*flags |= CPU_DTRACE_KPRIV;
3912 				*illval = regs[r1];
3913 				break;
3914 			}
3915 			/*FALLTHROUGH*/
3916 		case DIF_OP_LDUB:
3917 			regs[rd] = dtrace_load8(regs[r1]);
3918 			break;
3919 		case DIF_OP_RLDUH:
3920 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
3921 				*flags |= CPU_DTRACE_KPRIV;
3922 				*illval = regs[r1];
3923 				break;
3924 			}
3925 			/*FALLTHROUGH*/
3926 		case DIF_OP_LDUH:
3927 			regs[rd] = dtrace_load16(regs[r1]);
3928 			break;
3929 		case DIF_OP_RLDUW:
3930 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
3931 				*flags |= CPU_DTRACE_KPRIV;
3932 				*illval = regs[r1];
3933 				break;
3934 			}
3935 			/*FALLTHROUGH*/
3936 		case DIF_OP_LDUW:
3937 			regs[rd] = dtrace_load32(regs[r1]);
3938 			break;
3939 		case DIF_OP_RLDX:
3940 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
3941 				*flags |= CPU_DTRACE_KPRIV;
3942 				*illval = regs[r1];
3943 				break;
3944 			}
3945 			/*FALLTHROUGH*/
3946 		case DIF_OP_LDX:
3947 			regs[rd] = dtrace_load64(regs[r1]);
3948 			break;
3949 		case DIF_OP_ULDSB:
3950 			regs[rd] = (int8_t)
3951 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
3952 			break;
3953 		case DIF_OP_ULDSH:
3954 			regs[rd] = (int16_t)
3955 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
3956 			break;
3957 		case DIF_OP_ULDSW:
3958 			regs[rd] = (int32_t)
3959 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
3960 			break;
3961 		case DIF_OP_ULDUB:
3962 			regs[rd] =
3963 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
3964 			break;
3965 		case DIF_OP_ULDUH:
3966 			regs[rd] =
3967 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
3968 			break;
3969 		case DIF_OP_ULDUW:
3970 			regs[rd] =
3971 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
3972 			break;
3973 		case DIF_OP_ULDX:
3974 			regs[rd] =
3975 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
3976 			break;
3977 		case DIF_OP_RET:
3978 			rval = regs[rd];
3979 			break;
3980 		case DIF_OP_NOP:
3981 			break;
3982 		case DIF_OP_SETX:
3983 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
3984 			break;
3985 		case DIF_OP_SETS:
3986 			regs[rd] = (uint64_t)(uintptr_t)
3987 			    (strtab + DIF_INSTR_STRING(instr));
3988 			break;
3989 		case DIF_OP_SCMP:
3990 			cc_r = dtrace_strncmp((char *)(uintptr_t)regs[r1],
3991 			    (char *)(uintptr_t)regs[r2],
3992 			    state->dts_options[DTRACEOPT_STRSIZE]);
3993 
3994 			cc_n = cc_r < 0;
3995 			cc_z = cc_r == 0;
3996 			cc_v = cc_c = 0;
3997 			break;
3998 		case DIF_OP_LDGA:
3999 			regs[rd] = dtrace_dif_variable(mstate, state,
4000 			    r1, regs[r2]);
4001 			break;
4002 		case DIF_OP_LDGS:
4003 			id = DIF_INSTR_VAR(instr);
4004 
4005 			if (id >= DIF_VAR_OTHER_UBASE) {
4006 				uintptr_t a;
4007 
4008 				id -= DIF_VAR_OTHER_UBASE;
4009 				svar = vstate->dtvs_globals[id];
4010 				ASSERT(svar != NULL);
4011 				v = &svar->dtsv_var;
4012 
4013 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
4014 					regs[rd] = svar->dtsv_data;
4015 					break;
4016 				}
4017 
4018 				a = (uintptr_t)svar->dtsv_data;
4019 
4020 				if (*(uint8_t *)a == UINT8_MAX) {
4021 					/*
4022 					 * If the 0th byte is set to UINT8_MAX
4023 					 * then this is to be treated as a
4024 					 * reference to a NULL variable.
4025 					 */
4026 					regs[rd] = NULL;
4027 				} else {
4028 					regs[rd] = a + sizeof (uint64_t);
4029 				}
4030 
4031 				break;
4032 			}
4033 
4034 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
4035 			break;
4036 
4037 		case DIF_OP_STGS:
4038 			id = DIF_INSTR_VAR(instr);
4039 
4040 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4041 			id -= DIF_VAR_OTHER_UBASE;
4042 
4043 			svar = vstate->dtvs_globals[id];
4044 			ASSERT(svar != NULL);
4045 			v = &svar->dtsv_var;
4046 
4047 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4048 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4049 
4050 				ASSERT(a != NULL);
4051 				ASSERT(svar->dtsv_size != 0);
4052 
4053 				if (regs[rd] == NULL) {
4054 					*(uint8_t *)a = UINT8_MAX;
4055 					break;
4056 				} else {
4057 					*(uint8_t *)a = 0;
4058 					a += sizeof (uint64_t);
4059 				}
4060 
4061 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4062 				    (void *)a, &v->dtdv_type);
4063 				break;
4064 			}
4065 
4066 			svar->dtsv_data = regs[rd];
4067 			break;
4068 
4069 		case DIF_OP_LDTA:
4070 			/*
4071 			 * There are no DTrace built-in thread-local arrays at
4072 			 * present.  This opcode is saved for future work.
4073 			 */
4074 			*flags |= CPU_DTRACE_ILLOP;
4075 			regs[rd] = 0;
4076 			break;
4077 
4078 		case DIF_OP_LDLS:
4079 			id = DIF_INSTR_VAR(instr);
4080 
4081 			if (id < DIF_VAR_OTHER_UBASE) {
4082 				/*
4083 				 * For now, this has no meaning.
4084 				 */
4085 				regs[rd] = 0;
4086 				break;
4087 			}
4088 
4089 			id -= DIF_VAR_OTHER_UBASE;
4090 
4091 			ASSERT(id < vstate->dtvs_nlocals);
4092 			ASSERT(vstate->dtvs_locals != NULL);
4093 
4094 			svar = vstate->dtvs_locals[id];
4095 			ASSERT(svar != NULL);
4096 			v = &svar->dtsv_var;
4097 
4098 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4099 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4100 				size_t sz = v->dtdv_type.dtdt_size;
4101 
4102 				sz += sizeof (uint64_t);
4103 				ASSERT(svar->dtsv_size == NCPU * sz);
4104 				a += CPU->cpu_id * sz;
4105 
4106 				if (*(uint8_t *)a == UINT8_MAX) {
4107 					/*
4108 					 * If the 0th byte is set to UINT8_MAX
4109 					 * then this is to be treated as a
4110 					 * reference to a NULL variable.
4111 					 */
4112 					regs[rd] = NULL;
4113 				} else {
4114 					regs[rd] = a + sizeof (uint64_t);
4115 				}
4116 
4117 				break;
4118 			}
4119 
4120 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4121 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4122 			regs[rd] = tmp[CPU->cpu_id];
4123 			break;
4124 
4125 		case DIF_OP_STLS:
4126 			id = DIF_INSTR_VAR(instr);
4127 
4128 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4129 			id -= DIF_VAR_OTHER_UBASE;
4130 			ASSERT(id < vstate->dtvs_nlocals);
4131 
4132 			ASSERT(vstate->dtvs_locals != NULL);
4133 			svar = vstate->dtvs_locals[id];
4134 			ASSERT(svar != NULL);
4135 			v = &svar->dtsv_var;
4136 
4137 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4138 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4139 				size_t sz = v->dtdv_type.dtdt_size;
4140 
4141 				sz += sizeof (uint64_t);
4142 				ASSERT(svar->dtsv_size == NCPU * sz);
4143 				a += CPU->cpu_id * sz;
4144 
4145 				if (regs[rd] == NULL) {
4146 					*(uint8_t *)a = UINT8_MAX;
4147 					break;
4148 				} else {
4149 					*(uint8_t *)a = 0;
4150 					a += sizeof (uint64_t);
4151 				}
4152 
4153 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4154 				    (void *)a, &v->dtdv_type);
4155 				break;
4156 			}
4157 
4158 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4159 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4160 			tmp[CPU->cpu_id] = regs[rd];
4161 			break;
4162 
4163 		case DIF_OP_LDTS: {
4164 			dtrace_dynvar_t *dvar;
4165 			dtrace_key_t *key;
4166 
4167 			id = DIF_INSTR_VAR(instr);
4168 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4169 			id -= DIF_VAR_OTHER_UBASE;
4170 			v = &vstate->dtvs_tlocals[id];
4171 
4172 			key = &tupregs[DIF_DTR_NREGS];
4173 			key[0].dttk_value = (uint64_t)id;
4174 			key[0].dttk_size = 0;
4175 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4176 			key[1].dttk_size = 0;
4177 
4178 			dvar = dtrace_dynvar(dstate, 2, key,
4179 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC);
4180 
4181 			if (dvar == NULL) {
4182 				regs[rd] = 0;
4183 				break;
4184 			}
4185 
4186 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4187 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4188 			} else {
4189 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4190 			}
4191 
4192 			break;
4193 		}
4194 
4195 		case DIF_OP_STTS: {
4196 			dtrace_dynvar_t *dvar;
4197 			dtrace_key_t *key;
4198 
4199 			id = DIF_INSTR_VAR(instr);
4200 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4201 			id -= DIF_VAR_OTHER_UBASE;
4202 
4203 			key = &tupregs[DIF_DTR_NREGS];
4204 			key[0].dttk_value = (uint64_t)id;
4205 			key[0].dttk_size = 0;
4206 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4207 			key[1].dttk_size = 0;
4208 			v = &vstate->dtvs_tlocals[id];
4209 
4210 			dvar = dtrace_dynvar(dstate, 2, key,
4211 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4212 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4213 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4214 			    DTRACE_DYNVAR_DEALLOC);
4215 
4216 			/*
4217 			 * Given that we're storing to thread-local data,
4218 			 * we need to flush our predicate cache.
4219 			 */
4220 			curthread->t_predcache = NULL;
4221 
4222 			if (dvar == NULL)
4223 				break;
4224 
4225 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4226 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4227 				    dvar->dtdv_data, &v->dtdv_type);
4228 			} else {
4229 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4230 			}
4231 
4232 			break;
4233 		}
4234 
4235 		case DIF_OP_SRA:
4236 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
4237 			break;
4238 
4239 		case DIF_OP_CALL:
4240 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
4241 			    regs, tupregs, ttop, mstate, state);
4242 			break;
4243 
4244 		case DIF_OP_PUSHTR:
4245 			if (ttop == DIF_DTR_NREGS) {
4246 				*flags |= CPU_DTRACE_TUPOFLOW;
4247 				break;
4248 			}
4249 
4250 			if (r1 == DIF_TYPE_STRING) {
4251 				/*
4252 				 * If this is a string type and the size is 0,
4253 				 * we'll use the system-wide default string
4254 				 * size.  Note that we are _not_ looking at
4255 				 * the value of the DTRACEOPT_STRSIZE option;
4256 				 * had this been set, we would expect to have
4257 				 * a non-zero size value in the "pushtr".
4258 				 */
4259 				tupregs[ttop].dttk_size =
4260 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
4261 				    regs[r2] ? regs[r2] :
4262 				    dtrace_strsize_default) + 1;
4263 			} else {
4264 				tupregs[ttop].dttk_size = regs[r2];
4265 			}
4266 
4267 			tupregs[ttop++].dttk_value = regs[rd];
4268 			break;
4269 
4270 		case DIF_OP_PUSHTV:
4271 			if (ttop == DIF_DTR_NREGS) {
4272 				*flags |= CPU_DTRACE_TUPOFLOW;
4273 				break;
4274 			}
4275 
4276 			tupregs[ttop].dttk_value = regs[rd];
4277 			tupregs[ttop++].dttk_size = 0;
4278 			break;
4279 
4280 		case DIF_OP_POPTS:
4281 			if (ttop != 0)
4282 				ttop--;
4283 			break;
4284 
4285 		case DIF_OP_FLUSHTS:
4286 			ttop = 0;
4287 			break;
4288 
4289 		case DIF_OP_LDGAA:
4290 		case DIF_OP_LDTAA: {
4291 			dtrace_dynvar_t *dvar;
4292 			dtrace_key_t *key = tupregs;
4293 			uint_t nkeys = ttop;
4294 
4295 			id = DIF_INSTR_VAR(instr);
4296 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4297 			id -= DIF_VAR_OTHER_UBASE;
4298 
4299 			key[nkeys].dttk_value = (uint64_t)id;
4300 			key[nkeys++].dttk_size = 0;
4301 
4302 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
4303 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4304 				key[nkeys++].dttk_size = 0;
4305 				v = &vstate->dtvs_tlocals[id];
4306 			} else {
4307 				v = &vstate->dtvs_globals[id]->dtsv_var;
4308 			}
4309 
4310 			dvar = dtrace_dynvar(dstate, nkeys, key,
4311 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4312 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4313 			    DTRACE_DYNVAR_NOALLOC);
4314 
4315 			if (dvar == NULL) {
4316 				regs[rd] = 0;
4317 				break;
4318 			}
4319 
4320 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4321 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4322 			} else {
4323 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4324 			}
4325 
4326 			break;
4327 		}
4328 
4329 		case DIF_OP_STGAA:
4330 		case DIF_OP_STTAA: {
4331 			dtrace_dynvar_t *dvar;
4332 			dtrace_key_t *key = tupregs;
4333 			uint_t nkeys = ttop;
4334 
4335 			id = DIF_INSTR_VAR(instr);
4336 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4337 			id -= DIF_VAR_OTHER_UBASE;
4338 
4339 			key[nkeys].dttk_value = (uint64_t)id;
4340 			key[nkeys++].dttk_size = 0;
4341 
4342 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
4343 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4344 				key[nkeys++].dttk_size = 0;
4345 				v = &vstate->dtvs_tlocals[id];
4346 			} else {
4347 				v = &vstate->dtvs_globals[id]->dtsv_var;
4348 			}
4349 
4350 			dvar = dtrace_dynvar(dstate, nkeys, key,
4351 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4352 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4353 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4354 			    DTRACE_DYNVAR_DEALLOC);
4355 
4356 			if (dvar == NULL)
4357 				break;
4358 
4359 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4360 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4361 				    dvar->dtdv_data, &v->dtdv_type);
4362 			} else {
4363 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4364 			}
4365 
4366 			break;
4367 		}
4368 
4369 		case DIF_OP_ALLOCS: {
4370 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4371 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
4372 
4373 			if (mstate->dtms_scratch_ptr + size >
4374 			    mstate->dtms_scratch_base +
4375 			    mstate->dtms_scratch_size) {
4376 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4377 				regs[rd] = NULL;
4378 			} else {
4379 				dtrace_bzero((void *)
4380 				    mstate->dtms_scratch_ptr, size);
4381 				mstate->dtms_scratch_ptr += size;
4382 				regs[rd] = ptr;
4383 			}
4384 			break;
4385 		}
4386 
4387 		case DIF_OP_COPYS:
4388 			if (!dtrace_canstore(regs[rd], regs[r2],
4389 			    mstate, vstate)) {
4390 				*flags |= CPU_DTRACE_BADADDR;
4391 				*illval = regs[rd];
4392 				break;
4393 			}
4394 
4395 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
4396 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
4397 			break;
4398 
4399 		case DIF_OP_STB:
4400 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
4401 				*flags |= CPU_DTRACE_BADADDR;
4402 				*illval = regs[rd];
4403 				break;
4404 			}
4405 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
4406 			break;
4407 
4408 		case DIF_OP_STH:
4409 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
4410 				*flags |= CPU_DTRACE_BADADDR;
4411 				*illval = regs[rd];
4412 				break;
4413 			}
4414 			if (regs[rd] & 1) {
4415 				*flags |= CPU_DTRACE_BADALIGN;
4416 				*illval = regs[rd];
4417 				break;
4418 			}
4419 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
4420 			break;
4421 
4422 		case DIF_OP_STW:
4423 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
4424 				*flags |= CPU_DTRACE_BADADDR;
4425 				*illval = regs[rd];
4426 				break;
4427 			}
4428 			if (regs[rd] & 3) {
4429 				*flags |= CPU_DTRACE_BADALIGN;
4430 				*illval = regs[rd];
4431 				break;
4432 			}
4433 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
4434 			break;
4435 
4436 		case DIF_OP_STX:
4437 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
4438 				*flags |= CPU_DTRACE_BADADDR;
4439 				*illval = regs[rd];
4440 				break;
4441 			}
4442 			if (regs[rd] & 7) {
4443 				*flags |= CPU_DTRACE_BADALIGN;
4444 				*illval = regs[rd];
4445 				break;
4446 			}
4447 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
4448 			break;
4449 		}
4450 	}
4451 
4452 	if (!(*flags & CPU_DTRACE_FAULT))
4453 		return (rval);
4454 
4455 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
4456 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
4457 
4458 	return (0);
4459 }
4460 
4461 static void
4462 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
4463 {
4464 	dtrace_probe_t *probe = ecb->dte_probe;
4465 	dtrace_provider_t *prov = probe->dtpr_provider;
4466 	char c[DTRACE_FULLNAMELEN + 80], *str;
4467 	char *msg = "dtrace: breakpoint action at probe ";
4468 	char *ecbmsg = " (ecb ";
4469 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
4470 	uintptr_t val = (uintptr_t)ecb;
4471 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
4472 
4473 	if (dtrace_destructive_disallow)
4474 		return;
4475 
4476 	/*
4477 	 * It's impossible to be taking action on the NULL probe.
4478 	 */
4479 	ASSERT(probe != NULL);
4480 
4481 	/*
4482 	 * This is a poor man's (destitute man's?) sprintf():  we want to
4483 	 * print the provider name, module name, function name and name of
4484 	 * the probe, along with the hex address of the ECB with the breakpoint
4485 	 * action -- all of which we must place in the character buffer by
4486 	 * hand.
4487 	 */
4488 	while (*msg != '\0')
4489 		c[i++] = *msg++;
4490 
4491 	for (str = prov->dtpv_name; *str != '\0'; str++)
4492 		c[i++] = *str;
4493 	c[i++] = ':';
4494 
4495 	for (str = probe->dtpr_mod; *str != '\0'; str++)
4496 		c[i++] = *str;
4497 	c[i++] = ':';
4498 
4499 	for (str = probe->dtpr_func; *str != '\0'; str++)
4500 		c[i++] = *str;
4501 	c[i++] = ':';
4502 
4503 	for (str = probe->dtpr_name; *str != '\0'; str++)
4504 		c[i++] = *str;
4505 
4506 	while (*ecbmsg != '\0')
4507 		c[i++] = *ecbmsg++;
4508 
4509 	while (shift >= 0) {
4510 		mask = (uintptr_t)0xf << shift;
4511 
4512 		if (val >= ((uintptr_t)1 << shift))
4513 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
4514 		shift -= 4;
4515 	}
4516 
4517 	c[i++] = ')';
4518 	c[i] = '\0';
4519 
4520 	debug_enter(c);
4521 }
4522 
4523 static void
4524 dtrace_action_panic(dtrace_ecb_t *ecb)
4525 {
4526 	dtrace_probe_t *probe = ecb->dte_probe;
4527 
4528 	/*
4529 	 * It's impossible to be taking action on the NULL probe.
4530 	 */
4531 	ASSERT(probe != NULL);
4532 
4533 	if (dtrace_destructive_disallow)
4534 		return;
4535 
4536 	if (dtrace_panicked != NULL)
4537 		return;
4538 
4539 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
4540 		return;
4541 
4542 	/*
4543 	 * We won the right to panic.  (We want to be sure that only one
4544 	 * thread calls panic() from dtrace_probe(), and that panic() is
4545 	 * called exactly once.)
4546 	 */
4547 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
4548 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
4549 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
4550 }
4551 
4552 static void
4553 dtrace_action_raise(uint64_t sig)
4554 {
4555 	if (dtrace_destructive_disallow)
4556 		return;
4557 
4558 	if (sig >= NSIG) {
4559 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4560 		return;
4561 	}
4562 
4563 	/*
4564 	 * raise() has a queue depth of 1 -- we ignore all subsequent
4565 	 * invocations of the raise() action.
4566 	 */
4567 	if (curthread->t_dtrace_sig == 0)
4568 		curthread->t_dtrace_sig = (uint8_t)sig;
4569 
4570 	curthread->t_sig_check = 1;
4571 	aston(curthread);
4572 }
4573 
4574 static void
4575 dtrace_action_stop(void)
4576 {
4577 	if (dtrace_destructive_disallow)
4578 		return;
4579 
4580 	if (!curthread->t_dtrace_stop) {
4581 		curthread->t_dtrace_stop = 1;
4582 		curthread->t_sig_check = 1;
4583 		aston(curthread);
4584 	}
4585 }
4586 
4587 static void
4588 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
4589 {
4590 	hrtime_t now;
4591 	volatile uint16_t *flags;
4592 	cpu_t *cpu = CPU;
4593 
4594 	if (dtrace_destructive_disallow)
4595 		return;
4596 
4597 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
4598 
4599 	now = dtrace_gethrtime();
4600 
4601 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
4602 		/*
4603 		 * We need to advance the mark to the current time.
4604 		 */
4605 		cpu->cpu_dtrace_chillmark = now;
4606 		cpu->cpu_dtrace_chilled = 0;
4607 	}
4608 
4609 	/*
4610 	 * Now check to see if the requested chill time would take us over
4611 	 * the maximum amount of time allowed in the chill interval.  (Or
4612 	 * worse, if the calculation itself induces overflow.)
4613 	 */
4614 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
4615 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
4616 		*flags |= CPU_DTRACE_ILLOP;
4617 		return;
4618 	}
4619 
4620 	while (dtrace_gethrtime() - now < val)
4621 		continue;
4622 
4623 	/*
4624 	 * Normally, we assure that the value of the variable "timestamp" does
4625 	 * not change within an ECB.  The presence of chill() represents an
4626 	 * exception to this rule, however.
4627 	 */
4628 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
4629 	cpu->cpu_dtrace_chilled += val;
4630 }
4631 
4632 static void
4633 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
4634     uint64_t *buf, uint64_t arg)
4635 {
4636 	int nframes = DTRACE_USTACK_NFRAMES(arg);
4637 	int strsize = DTRACE_USTACK_STRSIZE(arg);
4638 	uint64_t *pcs = &buf[1], *fps;
4639 	char *str = (char *)&pcs[nframes];
4640 	int size, offs = 0, i, j;
4641 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
4642 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4643 	char *sym;
4644 
4645 	/*
4646 	 * Should be taking a faster path if string space has not been
4647 	 * allocated.
4648 	 */
4649 	ASSERT(strsize != 0);
4650 
4651 	/*
4652 	 * We will first allocate some temporary space for the frame pointers.
4653 	 */
4654 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4655 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
4656 	    (nframes * sizeof (uint64_t));
4657 
4658 	if (mstate->dtms_scratch_ptr + size >
4659 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
4660 		/*
4661 		 * Not enough room for our frame pointers -- need to indicate
4662 		 * that we ran out of scratch space.
4663 		 */
4664 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4665 		return;
4666 	}
4667 
4668 	mstate->dtms_scratch_ptr += size;
4669 	saved = mstate->dtms_scratch_ptr;
4670 
4671 	/*
4672 	 * Now get a stack with both program counters and frame pointers.
4673 	 */
4674 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4675 	dtrace_getufpstack(buf, fps, nframes + 1);
4676 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4677 
4678 	/*
4679 	 * If that faulted, we're cooked.
4680 	 */
4681 	if (*flags & CPU_DTRACE_FAULT)
4682 		goto out;
4683 
4684 	/*
4685 	 * Now we want to walk up the stack, calling the USTACK helper.  For
4686 	 * each iteration, we restore the scratch pointer.
4687 	 */
4688 	for (i = 0; i < nframes; i++) {
4689 		mstate->dtms_scratch_ptr = saved;
4690 
4691 		if (offs >= strsize)
4692 			break;
4693 
4694 		sym = (char *)(uintptr_t)dtrace_helper(
4695 		    DTRACE_HELPER_ACTION_USTACK,
4696 		    mstate, state, pcs[i], fps[i]);
4697 
4698 		/*
4699 		 * If we faulted while running the helper, we're going to
4700 		 * clear the fault and null out the corresponding string.
4701 		 */
4702 		if (*flags & CPU_DTRACE_FAULT) {
4703 			*flags &= ~CPU_DTRACE_FAULT;
4704 			str[offs++] = '\0';
4705 			continue;
4706 		}
4707 
4708 		if (sym == NULL) {
4709 			str[offs++] = '\0';
4710 			continue;
4711 		}
4712 
4713 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4714 
4715 		/*
4716 		 * Now copy in the string that the helper returned to us.
4717 		 */
4718 		for (j = 0; offs + j < strsize; j++) {
4719 			if ((str[offs + j] = sym[j]) == '\0')
4720 				break;
4721 		}
4722 
4723 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4724 
4725 		offs += j + 1;
4726 	}
4727 
4728 	if (offs >= strsize) {
4729 		/*
4730 		 * If we didn't have room for all of the strings, we don't
4731 		 * abort processing -- this needn't be a fatal error -- but we
4732 		 * still want to increment a counter (dts_stkstroverflows) to
4733 		 * allow this condition to be warned about.  (If this is from
4734 		 * a jstack() action, it is easily tuned via jstackstrsize.)
4735 		 */
4736 		dtrace_error(&state->dts_stkstroverflows);
4737 	}
4738 
4739 	while (offs < strsize)
4740 		str[offs++] = '\0';
4741 
4742 out:
4743 	mstate->dtms_scratch_ptr = old;
4744 }
4745 
4746 /*
4747  * If you're looking for the epicenter of DTrace, you just found it.  This
4748  * is the function called by the provider to fire a probe -- from which all
4749  * subsequent probe-context DTrace activity emanates.
4750  */
4751 void
4752 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
4753     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
4754 {
4755 	processorid_t cpuid;
4756 	dtrace_icookie_t cookie;
4757 	dtrace_probe_t *probe;
4758 	dtrace_mstate_t mstate;
4759 	dtrace_ecb_t *ecb;
4760 	dtrace_action_t *act;
4761 	intptr_t offs;
4762 	size_t size;
4763 	int vtime, onintr;
4764 	volatile uint16_t *flags;
4765 	hrtime_t now;
4766 
4767 	/*
4768 	 * Kick out immediately if this CPU is still being born (in which case
4769 	 * curthread will be set to -1)
4770 	 */
4771 	if ((uintptr_t)curthread & 1)
4772 		return;
4773 
4774 	cookie = dtrace_interrupt_disable();
4775 	probe = dtrace_probes[id - 1];
4776 	cpuid = CPU->cpu_id;
4777 	onintr = CPU_ON_INTR(CPU);
4778 
4779 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
4780 	    probe->dtpr_predcache == curthread->t_predcache) {
4781 		/*
4782 		 * We have hit in the predicate cache; we know that
4783 		 * this predicate would evaluate to be false.
4784 		 */
4785 		dtrace_interrupt_enable(cookie);
4786 		return;
4787 	}
4788 
4789 	if (panic_quiesce) {
4790 		/*
4791 		 * We don't trace anything if we're panicking.
4792 		 */
4793 		dtrace_interrupt_enable(cookie);
4794 		return;
4795 	}
4796 
4797 	now = dtrace_gethrtime();
4798 	vtime = dtrace_vtime_references != 0;
4799 
4800 	if (vtime && curthread->t_dtrace_start)
4801 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
4802 
4803 	mstate.dtms_probe = probe;
4804 	mstate.dtms_arg[0] = arg0;
4805 	mstate.dtms_arg[1] = arg1;
4806 	mstate.dtms_arg[2] = arg2;
4807 	mstate.dtms_arg[3] = arg3;
4808 	mstate.dtms_arg[4] = arg4;
4809 
4810 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
4811 
4812 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
4813 		dtrace_predicate_t *pred = ecb->dte_predicate;
4814 		dtrace_state_t *state = ecb->dte_state;
4815 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
4816 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
4817 		dtrace_vstate_t *vstate = &state->dts_vstate;
4818 		dtrace_provider_t *prov = probe->dtpr_provider;
4819 		int committed = 0;
4820 		caddr_t tomax;
4821 
4822 		/*
4823 		 * A little subtlety with the following (seemingly innocuous)
4824 		 * declaration of the automatic 'val':  by looking at the
4825 		 * code, you might think that it could be declared in the
4826 		 * action processing loop, below.  (That is, it's only used in
4827 		 * the action processing loop.)  However, it must be declared
4828 		 * out of that scope because in the case of DIF expression
4829 		 * arguments to aggregating actions, one iteration of the
4830 		 * action loop will use the last iteration's value.
4831 		 */
4832 #ifdef lint
4833 		uint64_t val = 0;
4834 #else
4835 		uint64_t val;
4836 #endif
4837 
4838 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
4839 		*flags &= ~CPU_DTRACE_ERROR;
4840 
4841 		if (prov == dtrace_provider) {
4842 			/*
4843 			 * If dtrace itself is the provider of this probe,
4844 			 * we're only going to continue processing the ECB if
4845 			 * arg0 (the dtrace_state_t) is equal to the ECB's
4846 			 * creating state.  (This prevents disjoint consumers
4847 			 * from seeing one another's metaprobes.)
4848 			 */
4849 			if (arg0 != (uint64_t)(uintptr_t)state)
4850 				continue;
4851 		}
4852 
4853 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
4854 			/*
4855 			 * We're not currently active.  If our provider isn't
4856 			 * the dtrace pseudo provider, we're not interested.
4857 			 */
4858 			if (prov != dtrace_provider)
4859 				continue;
4860 
4861 			/*
4862 			 * Now we must further check if we are in the BEGIN
4863 			 * probe.  If we are, we will only continue processing
4864 			 * if we're still in WARMUP -- if one BEGIN enabling
4865 			 * has invoked the exit() action, we don't want to
4866 			 * evaluate subsequent BEGIN enablings.
4867 			 */
4868 			if (probe->dtpr_id == dtrace_probeid_begin &&
4869 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
4870 				ASSERT(state->dts_activity ==
4871 				    DTRACE_ACTIVITY_DRAINING);
4872 				continue;
4873 			}
4874 		}
4875 
4876 		if (ecb->dte_cond) {
4877 			/*
4878 			 * If the dte_cond bits indicate that this
4879 			 * consumer is only allowed to see user-mode firings
4880 			 * of this probe, call the provider's dtps_usermode()
4881 			 * entry point to check that the probe was fired
4882 			 * while in a user context. Skip this ECB if that's
4883 			 * not the case.
4884 			 */
4885 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
4886 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
4887 			    probe->dtpr_id, probe->dtpr_arg) == 0)
4888 				continue;
4889 
4890 			/*
4891 			 * This is more subtle than it looks. We have to be
4892 			 * absolutely certain that CRED() isn't going to
4893 			 * change out from under us so it's only legit to
4894 			 * examine that structure if we're in constrained
4895 			 * situations. Currently, the only times we'll this
4896 			 * check is if a non-super-user has enabled the
4897 			 * profile or syscall providers -- providers that
4898 			 * allow visibility of all processes. For the
4899 			 * profile case, the check above will ensure that
4900 			 * we're examining a user context.
4901 			 */
4902 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
4903 				cred_t *cr;
4904 				cred_t *s_cr =
4905 				    ecb->dte_state->dts_cred.dcr_cred;
4906 				proc_t *proc;
4907 
4908 				ASSERT(s_cr != NULL);
4909 
4910 				if ((cr = CRED()) == NULL ||
4911 				    s_cr->cr_uid != cr->cr_uid ||
4912 				    s_cr->cr_uid != cr->cr_ruid ||
4913 				    s_cr->cr_uid != cr->cr_suid ||
4914 				    s_cr->cr_gid != cr->cr_gid ||
4915 				    s_cr->cr_gid != cr->cr_rgid ||
4916 				    s_cr->cr_gid != cr->cr_sgid ||
4917 				    (proc = ttoproc(curthread)) == NULL ||
4918 				    (proc->p_flag & SNOCD))
4919 					continue;
4920 			}
4921 
4922 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
4923 				cred_t *cr;
4924 				cred_t *s_cr =
4925 				    ecb->dte_state->dts_cred.dcr_cred;
4926 
4927 				ASSERT(s_cr != NULL);
4928 
4929 				if ((cr = CRED()) == NULL ||
4930 				    s_cr->cr_zone->zone_id !=
4931 				    cr->cr_zone->zone_id)
4932 					continue;
4933 			}
4934 		}
4935 
4936 		if (now - state->dts_alive > dtrace_deadman_timeout) {
4937 			/*
4938 			 * We seem to be dead.  Unless we (a) have kernel
4939 			 * destructive permissions (b) have expicitly enabled
4940 			 * destructive actions and (c) destructive actions have
4941 			 * not been disabled, we're going to transition into
4942 			 * the KILLED state, from which no further processing
4943 			 * on this state will be performed.
4944 			 */
4945 			if (!dtrace_priv_kernel_destructive(state) ||
4946 			    !state->dts_cred.dcr_destructive ||
4947 			    dtrace_destructive_disallow) {
4948 				void *activity = &state->dts_activity;
4949 				dtrace_activity_t current;
4950 
4951 				do {
4952 					current = state->dts_activity;
4953 				} while (dtrace_cas32(activity, current,
4954 				    DTRACE_ACTIVITY_KILLED) != current);
4955 
4956 				continue;
4957 			}
4958 		}
4959 
4960 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
4961 		    ecb->dte_alignment, state, &mstate)) < 0)
4962 			continue;
4963 
4964 		tomax = buf->dtb_tomax;
4965 		ASSERT(tomax != NULL);
4966 
4967 		if (ecb->dte_size != 0)
4968 			DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
4969 
4970 		mstate.dtms_epid = ecb->dte_epid;
4971 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
4972 
4973 		if (pred != NULL) {
4974 			dtrace_difo_t *dp = pred->dtp_difo;
4975 			int rval;
4976 
4977 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
4978 
4979 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
4980 				dtrace_cacheid_t cid = probe->dtpr_predcache;
4981 
4982 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
4983 					/*
4984 					 * Update the predicate cache...
4985 					 */
4986 					ASSERT(cid == pred->dtp_cacheid);
4987 					curthread->t_predcache = cid;
4988 				}
4989 
4990 				continue;
4991 			}
4992 		}
4993 
4994 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
4995 		    act != NULL; act = act->dta_next) {
4996 			size_t valoffs;
4997 			dtrace_difo_t *dp;
4998 			dtrace_recdesc_t *rec = &act->dta_rec;
4999 
5000 			size = rec->dtrd_size;
5001 			valoffs = offs + rec->dtrd_offset;
5002 
5003 			if (DTRACEACT_ISAGG(act->dta_kind)) {
5004 				uint64_t v = 0xbad;
5005 				dtrace_aggregation_t *agg;
5006 
5007 				agg = (dtrace_aggregation_t *)act;
5008 
5009 				if ((dp = act->dta_difo) != NULL)
5010 					v = dtrace_dif_emulate(dp,
5011 					    &mstate, vstate, state);
5012 
5013 				if (*flags & CPU_DTRACE_ERROR)
5014 					continue;
5015 
5016 				/*
5017 				 * Note that we always pass the expression
5018 				 * value from the previous iteration of the
5019 				 * action loop.  This value will only be used
5020 				 * if there is an expression argument to the
5021 				 * aggregating action, denoted by the
5022 				 * dtag_hasarg field.
5023 				 */
5024 				dtrace_aggregate(agg, buf,
5025 				    offs, aggbuf, v, val);
5026 				continue;
5027 			}
5028 
5029 			switch (act->dta_kind) {
5030 			case DTRACEACT_STOP:
5031 				if (dtrace_priv_proc_destructive(state))
5032 					dtrace_action_stop();
5033 				continue;
5034 
5035 			case DTRACEACT_BREAKPOINT:
5036 				if (dtrace_priv_kernel_destructive(state))
5037 					dtrace_action_breakpoint(ecb);
5038 				continue;
5039 
5040 			case DTRACEACT_PANIC:
5041 				if (dtrace_priv_kernel_destructive(state))
5042 					dtrace_action_panic(ecb);
5043 				continue;
5044 
5045 			case DTRACEACT_STACK:
5046 				if (!dtrace_priv_kernel(state))
5047 					continue;
5048 
5049 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
5050 				    size / sizeof (pc_t), probe->dtpr_aframes,
5051 				    DTRACE_ANCHORED(probe) ? NULL :
5052 				    (uint32_t *)arg0);
5053 
5054 				continue;
5055 
5056 			case DTRACEACT_JSTACK:
5057 			case DTRACEACT_USTACK:
5058 				if (!dtrace_priv_proc(state))
5059 					continue;
5060 
5061 				/*
5062 				 * See comment in DIF_VAR_PID.
5063 				 */
5064 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
5065 				    CPU_ON_INTR(CPU)) {
5066 					int depth = DTRACE_USTACK_NFRAMES(
5067 					    rec->dtrd_arg) + 1;
5068 
5069 					dtrace_bzero((void *)(tomax + valoffs),
5070 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
5071 					    + depth * sizeof (uint64_t));
5072 
5073 					continue;
5074 				}
5075 
5076 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
5077 				    curproc->p_dtrace_helpers != NULL) {
5078 					/*
5079 					 * This is the slow path -- we have
5080 					 * allocated string space, and we're
5081 					 * getting the stack of a process that
5082 					 * has helpers.  Call into a separate
5083 					 * routine to perform this processing.
5084 					 */
5085 					dtrace_action_ustack(&mstate, state,
5086 					    (uint64_t *)(tomax + valoffs),
5087 					    rec->dtrd_arg);
5088 					continue;
5089 				}
5090 
5091 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5092 				dtrace_getupcstack((uint64_t *)
5093 				    (tomax + valoffs),
5094 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
5095 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5096 				continue;
5097 
5098 			default:
5099 				break;
5100 			}
5101 
5102 			dp = act->dta_difo;
5103 			ASSERT(dp != NULL);
5104 
5105 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
5106 
5107 			if (*flags & CPU_DTRACE_ERROR)
5108 				continue;
5109 
5110 			switch (act->dta_kind) {
5111 			case DTRACEACT_SPECULATE:
5112 				ASSERT(buf == &state->dts_buffer[cpuid]);
5113 				buf = dtrace_speculation_buffer(state,
5114 				    cpuid, val);
5115 
5116 				if (buf == NULL) {
5117 					*flags |= CPU_DTRACE_DROP;
5118 					continue;
5119 				}
5120 
5121 				offs = dtrace_buffer_reserve(buf,
5122 				    ecb->dte_needed, ecb->dte_alignment,
5123 				    state, NULL);
5124 
5125 				if (offs < 0) {
5126 					*flags |= CPU_DTRACE_DROP;
5127 					continue;
5128 				}
5129 
5130 				tomax = buf->dtb_tomax;
5131 				ASSERT(tomax != NULL);
5132 
5133 				if (ecb->dte_size != 0)
5134 					DTRACE_STORE(uint32_t, tomax, offs,
5135 					    ecb->dte_epid);
5136 				continue;
5137 
5138 			case DTRACEACT_CHILL:
5139 				if (dtrace_priv_kernel_destructive(state))
5140 					dtrace_action_chill(&mstate, val);
5141 				continue;
5142 
5143 			case DTRACEACT_RAISE:
5144 				if (dtrace_priv_proc_destructive(state))
5145 					dtrace_action_raise(val);
5146 				continue;
5147 
5148 			case DTRACEACT_COMMIT:
5149 				ASSERT(!committed);
5150 
5151 				/*
5152 				 * We need to commit our buffer state.
5153 				 */
5154 				if (ecb->dte_size)
5155 					buf->dtb_offset = offs + ecb->dte_size;
5156 				buf = &state->dts_buffer[cpuid];
5157 				dtrace_speculation_commit(state, cpuid, val);
5158 				committed = 1;
5159 				continue;
5160 
5161 			case DTRACEACT_DISCARD:
5162 				dtrace_speculation_discard(state, cpuid, val);
5163 				continue;
5164 
5165 			case DTRACEACT_DIFEXPR:
5166 			case DTRACEACT_LIBACT:
5167 			case DTRACEACT_PRINTF:
5168 			case DTRACEACT_PRINTA:
5169 			case DTRACEACT_SYSTEM:
5170 			case DTRACEACT_FREOPEN:
5171 				break;
5172 
5173 			case DTRACEACT_SYM:
5174 			case DTRACEACT_MOD:
5175 				if (!dtrace_priv_kernel(state))
5176 					continue;
5177 				break;
5178 
5179 			case DTRACEACT_USYM:
5180 			case DTRACEACT_UMOD:
5181 			case DTRACEACT_UADDR: {
5182 				struct pid *pid = curthread->t_procp->p_pidp;
5183 
5184 				if (!dtrace_priv_proc(state))
5185 					continue;
5186 
5187 				DTRACE_STORE(uint64_t, tomax,
5188 				    valoffs, (uint64_t)pid->pid_id);
5189 				DTRACE_STORE(uint64_t, tomax,
5190 				    valoffs + sizeof (uint64_t), val);
5191 
5192 				continue;
5193 			}
5194 
5195 			case DTRACEACT_EXIT: {
5196 				/*
5197 				 * For the exit action, we are going to attempt
5198 				 * to atomically set our activity to be
5199 				 * draining.  If this fails (either because
5200 				 * another CPU has beat us to the exit action,
5201 				 * or because our current activity is something
5202 				 * other than ACTIVE or WARMUP), we will
5203 				 * continue.  This assures that the exit action
5204 				 * can be successfully recorded at most once
5205 				 * when we're in the ACTIVE state.  If we're
5206 				 * encountering the exit() action while in
5207 				 * COOLDOWN, however, we want to honor the new
5208 				 * status code.  (We know that we're the only
5209 				 * thread in COOLDOWN, so there is no race.)
5210 				 */
5211 				void *activity = &state->dts_activity;
5212 				dtrace_activity_t current = state->dts_activity;
5213 
5214 				if (current == DTRACE_ACTIVITY_COOLDOWN)
5215 					break;
5216 
5217 				if (current != DTRACE_ACTIVITY_WARMUP)
5218 					current = DTRACE_ACTIVITY_ACTIVE;
5219 
5220 				if (dtrace_cas32(activity, current,
5221 				    DTRACE_ACTIVITY_DRAINING) != current) {
5222 					*flags |= CPU_DTRACE_DROP;
5223 					continue;
5224 				}
5225 
5226 				break;
5227 			}
5228 
5229 			default:
5230 				ASSERT(0);
5231 			}
5232 
5233 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
5234 				uintptr_t end = valoffs + size;
5235 
5236 				/*
5237 				 * If this is a string, we're going to only
5238 				 * load until we find the zero byte -- after
5239 				 * which we'll store zero bytes.
5240 				 */
5241 				if (dp->dtdo_rtype.dtdt_kind ==
5242 				    DIF_TYPE_STRING) {
5243 					char c = '\0' + 1;
5244 					int intuple = act->dta_intuple;
5245 					size_t s;
5246 
5247 					for (s = 0; s < size; s++) {
5248 						if (c != '\0')
5249 							c = dtrace_load8(val++);
5250 
5251 						DTRACE_STORE(uint8_t, tomax,
5252 						    valoffs++, c);
5253 
5254 						if (c == '\0' && intuple)
5255 							break;
5256 					}
5257 
5258 					continue;
5259 				}
5260 
5261 				while (valoffs < end) {
5262 					DTRACE_STORE(uint8_t, tomax, valoffs++,
5263 					    dtrace_load8(val++));
5264 				}
5265 
5266 				continue;
5267 			}
5268 
5269 			switch (size) {
5270 			case 0:
5271 				break;
5272 
5273 			case sizeof (uint8_t):
5274 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
5275 				break;
5276 			case sizeof (uint16_t):
5277 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
5278 				break;
5279 			case sizeof (uint32_t):
5280 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
5281 				break;
5282 			case sizeof (uint64_t):
5283 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
5284 				break;
5285 			default:
5286 				/*
5287 				 * Any other size should have been returned by
5288 				 * reference, not by value.
5289 				 */
5290 				ASSERT(0);
5291 				break;
5292 			}
5293 		}
5294 
5295 		if (*flags & CPU_DTRACE_DROP)
5296 			continue;
5297 
5298 		if (*flags & CPU_DTRACE_FAULT) {
5299 			int ndx;
5300 			dtrace_action_t *err;
5301 
5302 			buf->dtb_errors++;
5303 
5304 			if (probe->dtpr_id == dtrace_probeid_error) {
5305 				/*
5306 				 * There's nothing we can do -- we had an
5307 				 * error on the error probe.  We bump an
5308 				 * error counter to at least indicate that
5309 				 * this condition happened.
5310 				 */
5311 				dtrace_error(&state->dts_dblerrors);
5312 				continue;
5313 			}
5314 
5315 			if (vtime) {
5316 				/*
5317 				 * Before recursing on dtrace_probe(), we
5318 				 * need to explicitly clear out our start
5319 				 * time to prevent it from being accumulated
5320 				 * into t_dtrace_vtime.
5321 				 */
5322 				curthread->t_dtrace_start = 0;
5323 			}
5324 
5325 			/*
5326 			 * Iterate over the actions to figure out which action
5327 			 * we were processing when we experienced the error.
5328 			 * Note that act points _past_ the faulting action; if
5329 			 * act is ecb->dte_action, the fault was in the
5330 			 * predicate, if it's ecb->dte_action->dta_next it's
5331 			 * in action #1, and so on.
5332 			 */
5333 			for (err = ecb->dte_action, ndx = 0;
5334 			    err != act; err = err->dta_next, ndx++)
5335 				continue;
5336 
5337 			dtrace_probe_error(state, ecb->dte_epid, ndx,
5338 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
5339 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
5340 			    cpu_core[cpuid].cpuc_dtrace_illval);
5341 
5342 			continue;
5343 		}
5344 
5345 		if (!committed)
5346 			buf->dtb_offset = offs + ecb->dte_size;
5347 	}
5348 
5349 	if (vtime)
5350 		curthread->t_dtrace_start = dtrace_gethrtime();
5351 
5352 	dtrace_interrupt_enable(cookie);
5353 }
5354 
5355 /*
5356  * DTrace Probe Hashing Functions
5357  *
5358  * The functions in this section (and indeed, the functions in remaining
5359  * sections) are not _called_ from probe context.  (Any exceptions to this are
5360  * marked with a "Note:".)  Rather, they are called from elsewhere in the
5361  * DTrace framework to look-up probes in, add probes to and remove probes from
5362  * the DTrace probe hashes.  (Each probe is hashed by each element of the
5363  * probe tuple -- allowing for fast lookups, regardless of what was
5364  * specified.)
5365  */
5366 static uint_t
5367 dtrace_hash_str(char *p)
5368 {
5369 	unsigned int g;
5370 	uint_t hval = 0;
5371 
5372 	while (*p) {
5373 		hval = (hval << 4) + *p++;
5374 		if ((g = (hval & 0xf0000000)) != 0)
5375 			hval ^= g >> 24;
5376 		hval &= ~g;
5377 	}
5378 	return (hval);
5379 }
5380 
5381 static dtrace_hash_t *
5382 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
5383 {
5384 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
5385 
5386 	hash->dth_stroffs = stroffs;
5387 	hash->dth_nextoffs = nextoffs;
5388 	hash->dth_prevoffs = prevoffs;
5389 
5390 	hash->dth_size = 1;
5391 	hash->dth_mask = hash->dth_size - 1;
5392 
5393 	hash->dth_tab = kmem_zalloc(hash->dth_size *
5394 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
5395 
5396 	return (hash);
5397 }
5398 
5399 static void
5400 dtrace_hash_destroy(dtrace_hash_t *hash)
5401 {
5402 #ifdef DEBUG
5403 	int i;
5404 
5405 	for (i = 0; i < hash->dth_size; i++)
5406 		ASSERT(hash->dth_tab[i] == NULL);
5407 #endif
5408 
5409 	kmem_free(hash->dth_tab,
5410 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
5411 	kmem_free(hash, sizeof (dtrace_hash_t));
5412 }
5413 
5414 static void
5415 dtrace_hash_resize(dtrace_hash_t *hash)
5416 {
5417 	int size = hash->dth_size, i, ndx;
5418 	int new_size = hash->dth_size << 1;
5419 	int new_mask = new_size - 1;
5420 	dtrace_hashbucket_t **new_tab, *bucket, *next;
5421 
5422 	ASSERT((new_size & new_mask) == 0);
5423 
5424 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
5425 
5426 	for (i = 0; i < size; i++) {
5427 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
5428 			dtrace_probe_t *probe = bucket->dthb_chain;
5429 
5430 			ASSERT(probe != NULL);
5431 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
5432 
5433 			next = bucket->dthb_next;
5434 			bucket->dthb_next = new_tab[ndx];
5435 			new_tab[ndx] = bucket;
5436 		}
5437 	}
5438 
5439 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
5440 	hash->dth_tab = new_tab;
5441 	hash->dth_size = new_size;
5442 	hash->dth_mask = new_mask;
5443 }
5444 
5445 static void
5446 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
5447 {
5448 	int hashval = DTRACE_HASHSTR(hash, new);
5449 	int ndx = hashval & hash->dth_mask;
5450 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5451 	dtrace_probe_t **nextp, **prevp;
5452 
5453 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5454 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
5455 			goto add;
5456 	}
5457 
5458 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
5459 		dtrace_hash_resize(hash);
5460 		dtrace_hash_add(hash, new);
5461 		return;
5462 	}
5463 
5464 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
5465 	bucket->dthb_next = hash->dth_tab[ndx];
5466 	hash->dth_tab[ndx] = bucket;
5467 	hash->dth_nbuckets++;
5468 
5469 add:
5470 	nextp = DTRACE_HASHNEXT(hash, new);
5471 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
5472 	*nextp = bucket->dthb_chain;
5473 
5474 	if (bucket->dthb_chain != NULL) {
5475 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
5476 		ASSERT(*prevp == NULL);
5477 		*prevp = new;
5478 	}
5479 
5480 	bucket->dthb_chain = new;
5481 	bucket->dthb_len++;
5482 }
5483 
5484 static dtrace_probe_t *
5485 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
5486 {
5487 	int hashval = DTRACE_HASHSTR(hash, template);
5488 	int ndx = hashval & hash->dth_mask;
5489 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5490 
5491 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5492 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
5493 			return (bucket->dthb_chain);
5494 	}
5495 
5496 	return (NULL);
5497 }
5498 
5499 static int
5500 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
5501 {
5502 	int hashval = DTRACE_HASHSTR(hash, template);
5503 	int ndx = hashval & hash->dth_mask;
5504 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5505 
5506 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5507 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
5508 			return (bucket->dthb_len);
5509 	}
5510 
5511 	return (NULL);
5512 }
5513 
5514 static void
5515 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
5516 {
5517 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
5518 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
5519 
5520 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
5521 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
5522 
5523 	/*
5524 	 * Find the bucket that we're removing this probe from.
5525 	 */
5526 	for (; bucket != NULL; bucket = bucket->dthb_next) {
5527 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
5528 			break;
5529 	}
5530 
5531 	ASSERT(bucket != NULL);
5532 
5533 	if (*prevp == NULL) {
5534 		if (*nextp == NULL) {
5535 			/*
5536 			 * The removed probe was the only probe on this
5537 			 * bucket; we need to remove the bucket.
5538 			 */
5539 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
5540 
5541 			ASSERT(bucket->dthb_chain == probe);
5542 			ASSERT(b != NULL);
5543 
5544 			if (b == bucket) {
5545 				hash->dth_tab[ndx] = bucket->dthb_next;
5546 			} else {
5547 				while (b->dthb_next != bucket)
5548 					b = b->dthb_next;
5549 				b->dthb_next = bucket->dthb_next;
5550 			}
5551 
5552 			ASSERT(hash->dth_nbuckets > 0);
5553 			hash->dth_nbuckets--;
5554 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
5555 			return;
5556 		}
5557 
5558 		bucket->dthb_chain = *nextp;
5559 	} else {
5560 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
5561 	}
5562 
5563 	if (*nextp != NULL)
5564 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
5565 }
5566 
5567 /*
5568  * DTrace Utility Functions
5569  *
5570  * These are random utility functions that are _not_ called from probe context.
5571  */
5572 static int
5573 dtrace_badattr(const dtrace_attribute_t *a)
5574 {
5575 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
5576 	    a->dtat_data > DTRACE_STABILITY_MAX ||
5577 	    a->dtat_class > DTRACE_CLASS_MAX);
5578 }
5579 
5580 /*
5581  * Return a duplicate copy of a string.  If the specified string is NULL,
5582  * this function returns a zero-length string.
5583  */
5584 static char *
5585 dtrace_strdup(const char *str)
5586 {
5587 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
5588 
5589 	if (str != NULL)
5590 		(void) strcpy(new, str);
5591 
5592 	return (new);
5593 }
5594 
5595 #define	DTRACE_ISALPHA(c)	\
5596 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
5597 
5598 static int
5599 dtrace_badname(const char *s)
5600 {
5601 	char c;
5602 
5603 	if (s == NULL || (c = *s++) == '\0')
5604 		return (0);
5605 
5606 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
5607 		return (1);
5608 
5609 	while ((c = *s++) != '\0') {
5610 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
5611 		    c != '-' && c != '_' && c != '.' && c != '`')
5612 			return (1);
5613 	}
5614 
5615 	return (0);
5616 }
5617 
5618 static void
5619 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
5620 {
5621 	uint32_t priv;
5622 
5623 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
5624 		/*
5625 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
5626 		 */
5627 		priv = DTRACE_PRIV_ALL;
5628 	} else {
5629 		*uidp = crgetuid(cr);
5630 		*zoneidp = crgetzoneid(cr);
5631 
5632 		priv = 0;
5633 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
5634 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
5635 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
5636 			priv |= DTRACE_PRIV_USER;
5637 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
5638 			priv |= DTRACE_PRIV_PROC;
5639 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
5640 			priv |= DTRACE_PRIV_OWNER;
5641 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
5642 			priv |= DTRACE_PRIV_ZONEOWNER;
5643 	}
5644 
5645 	*privp = priv;
5646 }
5647 
5648 #ifdef DTRACE_ERRDEBUG
5649 static void
5650 dtrace_errdebug(const char *str)
5651 {
5652 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
5653 	int occupied = 0;
5654 
5655 	mutex_enter(&dtrace_errlock);
5656 	dtrace_errlast = str;
5657 	dtrace_errthread = curthread;
5658 
5659 	while (occupied++ < DTRACE_ERRHASHSZ) {
5660 		if (dtrace_errhash[hval].dter_msg == str) {
5661 			dtrace_errhash[hval].dter_count++;
5662 			goto out;
5663 		}
5664 
5665 		if (dtrace_errhash[hval].dter_msg != NULL) {
5666 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
5667 			continue;
5668 		}
5669 
5670 		dtrace_errhash[hval].dter_msg = str;
5671 		dtrace_errhash[hval].dter_count = 1;
5672 		goto out;
5673 	}
5674 
5675 	panic("dtrace: undersized error hash");
5676 out:
5677 	mutex_exit(&dtrace_errlock);
5678 }
5679 #endif
5680 
5681 /*
5682  * DTrace Matching Functions
5683  *
5684  * These functions are used to match groups of probes, given some elements of
5685  * a probe tuple, or some globbed expressions for elements of a probe tuple.
5686  */
5687 static int
5688 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
5689     zoneid_t zoneid)
5690 {
5691 	if (priv != DTRACE_PRIV_ALL) {
5692 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
5693 		uint32_t match = priv & ppriv;
5694 
5695 		/*
5696 		 * No PRIV_DTRACE_* privileges...
5697 		 */
5698 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
5699 		    DTRACE_PRIV_KERNEL)) == 0)
5700 			return (0);
5701 
5702 		/*
5703 		 * No matching bits, but there were bits to match...
5704 		 */
5705 		if (match == 0 && ppriv != 0)
5706 			return (0);
5707 
5708 		/*
5709 		 * Need to have permissions to the process, but don't...
5710 		 */
5711 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
5712 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
5713 			return (0);
5714 		}
5715 
5716 		/*
5717 		 * Need to be in the same zone unless we possess the
5718 		 * privilege to examine all zones.
5719 		 */
5720 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
5721 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
5722 			return (0);
5723 		}
5724 	}
5725 
5726 	return (1);
5727 }
5728 
5729 /*
5730  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
5731  * consists of input pattern strings and an ops-vector to evaluate them.
5732  * This function returns >0 for match, 0 for no match, and <0 for error.
5733  */
5734 static int
5735 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
5736     uint32_t priv, uid_t uid, zoneid_t zoneid)
5737 {
5738 	dtrace_provider_t *pvp = prp->dtpr_provider;
5739 	int rv;
5740 
5741 	if (pvp->dtpv_defunct)
5742 		return (0);
5743 
5744 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
5745 		return (rv);
5746 
5747 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
5748 		return (rv);
5749 
5750 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
5751 		return (rv);
5752 
5753 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
5754 		return (rv);
5755 
5756 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
5757 		return (0);
5758 
5759 	return (rv);
5760 }
5761 
5762 /*
5763  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
5764  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
5765  * libc's version, the kernel version only applies to 8-bit ASCII strings.
5766  * In addition, all of the recursion cases except for '*' matching have been
5767  * unwound.  For '*', we still implement recursive evaluation, but a depth
5768  * counter is maintained and matching is aborted if we recurse too deep.
5769  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
5770  */
5771 static int
5772 dtrace_match_glob(const char *s, const char *p, int depth)
5773 {
5774 	const char *olds;
5775 	char s1, c;
5776 	int gs;
5777 
5778 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
5779 		return (-1);
5780 
5781 	if (s == NULL)
5782 		s = ""; /* treat NULL as empty string */
5783 
5784 top:
5785 	olds = s;
5786 	s1 = *s++;
5787 
5788 	if (p == NULL)
5789 		return (0);
5790 
5791 	if ((c = *p++) == '\0')
5792 		return (s1 == '\0');
5793 
5794 	switch (c) {
5795 	case '[': {
5796 		int ok = 0, notflag = 0;
5797 		char lc = '\0';
5798 
5799 		if (s1 == '\0')
5800 			return (0);
5801 
5802 		if (*p == '!') {
5803 			notflag = 1;
5804 			p++;
5805 		}
5806 
5807 		if ((c = *p++) == '\0')
5808 			return (0);
5809 
5810 		do {
5811 			if (c == '-' && lc != '\0' && *p != ']') {
5812 				if ((c = *p++) == '\0')
5813 					return (0);
5814 				if (c == '\\' && (c = *p++) == '\0')
5815 					return (0);
5816 
5817 				if (notflag) {
5818 					if (s1 < lc || s1 > c)
5819 						ok++;
5820 					else
5821 						return (0);
5822 				} else if (lc <= s1 && s1 <= c)
5823 					ok++;
5824 
5825 			} else if (c == '\\' && (c = *p++) == '\0')
5826 				return (0);
5827 
5828 			lc = c; /* save left-hand 'c' for next iteration */
5829 
5830 			if (notflag) {
5831 				if (s1 != c)
5832 					ok++;
5833 				else
5834 					return (0);
5835 			} else if (s1 == c)
5836 				ok++;
5837 
5838 			if ((c = *p++) == '\0')
5839 				return (0);
5840 
5841 		} while (c != ']');
5842 
5843 		if (ok)
5844 			goto top;
5845 
5846 		return (0);
5847 	}
5848 
5849 	case '\\':
5850 		if ((c = *p++) == '\0')
5851 			return (0);
5852 		/*FALLTHRU*/
5853 
5854 	default:
5855 		if (c != s1)
5856 			return (0);
5857 		/*FALLTHRU*/
5858 
5859 	case '?':
5860 		if (s1 != '\0')
5861 			goto top;
5862 		return (0);
5863 
5864 	case '*':
5865 		while (*p == '*')
5866 			p++; /* consecutive *'s are identical to a single one */
5867 
5868 		if (*p == '\0')
5869 			return (1);
5870 
5871 		for (s = olds; *s != '\0'; s++) {
5872 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
5873 				return (gs);
5874 		}
5875 
5876 		return (0);
5877 	}
5878 }
5879 
5880 /*ARGSUSED*/
5881 static int
5882 dtrace_match_string(const char *s, const char *p, int depth)
5883 {
5884 	return (s != NULL && strcmp(s, p) == 0);
5885 }
5886 
5887 /*ARGSUSED*/
5888 static int
5889 dtrace_match_nul(const char *s, const char *p, int depth)
5890 {
5891 	return (1); /* always match the empty pattern */
5892 }
5893 
5894 /*ARGSUSED*/
5895 static int
5896 dtrace_match_nonzero(const char *s, const char *p, int depth)
5897 {
5898 	return (s != NULL && s[0] != '\0');
5899 }
5900 
5901 static int
5902 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
5903     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
5904 {
5905 	dtrace_probe_t template, *probe;
5906 	dtrace_hash_t *hash = NULL;
5907 	int len, best = INT_MAX, nmatched = 0;
5908 	dtrace_id_t i;
5909 
5910 	ASSERT(MUTEX_HELD(&dtrace_lock));
5911 
5912 	/*
5913 	 * If the probe ID is specified in the key, just lookup by ID and
5914 	 * invoke the match callback once if a matching probe is found.
5915 	 */
5916 	if (pkp->dtpk_id != DTRACE_IDNONE) {
5917 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
5918 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
5919 			(void) (*matched)(probe, arg);
5920 			nmatched++;
5921 		}
5922 		return (nmatched);
5923 	}
5924 
5925 	template.dtpr_mod = (char *)pkp->dtpk_mod;
5926 	template.dtpr_func = (char *)pkp->dtpk_func;
5927 	template.dtpr_name = (char *)pkp->dtpk_name;
5928 
5929 	/*
5930 	 * We want to find the most distinct of the module name, function
5931 	 * name, and name.  So for each one that is not a glob pattern or
5932 	 * empty string, we perform a lookup in the corresponding hash and
5933 	 * use the hash table with the fewest collisions to do our search.
5934 	 */
5935 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
5936 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
5937 		best = len;
5938 		hash = dtrace_bymod;
5939 	}
5940 
5941 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
5942 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
5943 		best = len;
5944 		hash = dtrace_byfunc;
5945 	}
5946 
5947 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
5948 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
5949 		best = len;
5950 		hash = dtrace_byname;
5951 	}
5952 
5953 	/*
5954 	 * If we did not select a hash table, iterate over every probe and
5955 	 * invoke our callback for each one that matches our input probe key.
5956 	 */
5957 	if (hash == NULL) {
5958 		for (i = 0; i < dtrace_nprobes; i++) {
5959 			if ((probe = dtrace_probes[i]) == NULL ||
5960 			    dtrace_match_probe(probe, pkp, priv, uid,
5961 			    zoneid) <= 0)
5962 				continue;
5963 
5964 			nmatched++;
5965 
5966 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
5967 				break;
5968 		}
5969 
5970 		return (nmatched);
5971 	}
5972 
5973 	/*
5974 	 * If we selected a hash table, iterate over each probe of the same key
5975 	 * name and invoke the callback for every probe that matches the other
5976 	 * attributes of our input probe key.
5977 	 */
5978 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
5979 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
5980 
5981 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
5982 			continue;
5983 
5984 		nmatched++;
5985 
5986 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
5987 			break;
5988 	}
5989 
5990 	return (nmatched);
5991 }
5992 
5993 /*
5994  * Return the function pointer dtrace_probecmp() should use to compare the
5995  * specified pattern with a string.  For NULL or empty patterns, we select
5996  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
5997  * For non-empty non-glob strings, we use dtrace_match_string().
5998  */
5999 static dtrace_probekey_f *
6000 dtrace_probekey_func(const char *p)
6001 {
6002 	char c;
6003 
6004 	if (p == NULL || *p == '\0')
6005 		return (&dtrace_match_nul);
6006 
6007 	while ((c = *p++) != '\0') {
6008 		if (c == '[' || c == '?' || c == '*' || c == '\\')
6009 			return (&dtrace_match_glob);
6010 	}
6011 
6012 	return (&dtrace_match_string);
6013 }
6014 
6015 /*
6016  * Build a probe comparison key for use with dtrace_match_probe() from the
6017  * given probe description.  By convention, a null key only matches anchored
6018  * probes: if each field is the empty string, reset dtpk_fmatch to
6019  * dtrace_match_nonzero().
6020  */
6021 static void
6022 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
6023 {
6024 	pkp->dtpk_prov = pdp->dtpd_provider;
6025 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
6026 
6027 	pkp->dtpk_mod = pdp->dtpd_mod;
6028 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
6029 
6030 	pkp->dtpk_func = pdp->dtpd_func;
6031 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
6032 
6033 	pkp->dtpk_name = pdp->dtpd_name;
6034 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
6035 
6036 	pkp->dtpk_id = pdp->dtpd_id;
6037 
6038 	if (pkp->dtpk_id == DTRACE_IDNONE &&
6039 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
6040 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
6041 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
6042 	    pkp->dtpk_nmatch == &dtrace_match_nul)
6043 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
6044 }
6045 
6046 /*
6047  * DTrace Provider-to-Framework API Functions
6048  *
6049  * These functions implement much of the Provider-to-Framework API, as
6050  * described in <sys/dtrace.h>.  The parts of the API not in this section are
6051  * the functions in the API for probe management (found below), and
6052  * dtrace_probe() itself (found above).
6053  */
6054 
6055 /*
6056  * Register the calling provider with the DTrace framework.  This should
6057  * generally be called by DTrace providers in their attach(9E) entry point.
6058  */
6059 int
6060 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
6061     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
6062 {
6063 	dtrace_provider_t *provider;
6064 
6065 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
6066 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6067 		    "arguments", name ? name : "<NULL>");
6068 		return (EINVAL);
6069 	}
6070 
6071 	if (name[0] == '\0' || dtrace_badname(name)) {
6072 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6073 		    "provider name", name);
6074 		return (EINVAL);
6075 	}
6076 
6077 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
6078 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
6079 	    pops->dtps_destroy == NULL ||
6080 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
6081 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6082 		    "provider ops", name);
6083 		return (EINVAL);
6084 	}
6085 
6086 	if (dtrace_badattr(&pap->dtpa_provider) ||
6087 	    dtrace_badattr(&pap->dtpa_mod) ||
6088 	    dtrace_badattr(&pap->dtpa_func) ||
6089 	    dtrace_badattr(&pap->dtpa_name) ||
6090 	    dtrace_badattr(&pap->dtpa_args)) {
6091 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6092 		    "provider attributes", name);
6093 		return (EINVAL);
6094 	}
6095 
6096 	if (priv & ~DTRACE_PRIV_ALL) {
6097 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6098 		    "privilege attributes", name);
6099 		return (EINVAL);
6100 	}
6101 
6102 	if ((priv & DTRACE_PRIV_KERNEL) &&
6103 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
6104 	    pops->dtps_usermode == NULL) {
6105 		cmn_err(CE_WARN, "failed to register provider '%s': need "
6106 		    "dtps_usermode() op for given privilege attributes", name);
6107 		return (EINVAL);
6108 	}
6109 
6110 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
6111 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
6112 	(void) strcpy(provider->dtpv_name, name);
6113 
6114 	provider->dtpv_attr = *pap;
6115 	provider->dtpv_priv.dtpp_flags = priv;
6116 	if (cr != NULL) {
6117 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
6118 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
6119 	}
6120 	provider->dtpv_pops = *pops;
6121 
6122 	if (pops->dtps_provide == NULL) {
6123 		ASSERT(pops->dtps_provide_module != NULL);
6124 		provider->dtpv_pops.dtps_provide =
6125 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
6126 	}
6127 
6128 	if (pops->dtps_provide_module == NULL) {
6129 		ASSERT(pops->dtps_provide != NULL);
6130 		provider->dtpv_pops.dtps_provide_module =
6131 		    (void (*)(void *, struct modctl *))dtrace_nullop;
6132 	}
6133 
6134 	if (pops->dtps_suspend == NULL) {
6135 		ASSERT(pops->dtps_resume == NULL);
6136 		provider->dtpv_pops.dtps_suspend =
6137 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6138 		provider->dtpv_pops.dtps_resume =
6139 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6140 	}
6141 
6142 	provider->dtpv_arg = arg;
6143 	*idp = (dtrace_provider_id_t)provider;
6144 
6145 	if (pops == &dtrace_provider_ops) {
6146 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6147 		ASSERT(MUTEX_HELD(&dtrace_lock));
6148 		ASSERT(dtrace_anon.dta_enabling == NULL);
6149 
6150 		/*
6151 		 * We make sure that the DTrace provider is at the head of
6152 		 * the provider chain.
6153 		 */
6154 		provider->dtpv_next = dtrace_provider;
6155 		dtrace_provider = provider;
6156 		return (0);
6157 	}
6158 
6159 	mutex_enter(&dtrace_provider_lock);
6160 	mutex_enter(&dtrace_lock);
6161 
6162 	/*
6163 	 * If there is at least one provider registered, we'll add this
6164 	 * provider after the first provider.
6165 	 */
6166 	if (dtrace_provider != NULL) {
6167 		provider->dtpv_next = dtrace_provider->dtpv_next;
6168 		dtrace_provider->dtpv_next = provider;
6169 	} else {
6170 		dtrace_provider = provider;
6171 	}
6172 
6173 	if (dtrace_retained != NULL) {
6174 		dtrace_enabling_provide(provider);
6175 
6176 		/*
6177 		 * Now we need to call dtrace_enabling_matchall() -- which
6178 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
6179 		 * to drop all of our locks before calling into it...
6180 		 */
6181 		mutex_exit(&dtrace_lock);
6182 		mutex_exit(&dtrace_provider_lock);
6183 		dtrace_enabling_matchall();
6184 
6185 		return (0);
6186 	}
6187 
6188 	mutex_exit(&dtrace_lock);
6189 	mutex_exit(&dtrace_provider_lock);
6190 
6191 	return (0);
6192 }
6193 
6194 /*
6195  * Unregister the specified provider from the DTrace framework.  This should
6196  * generally be called by DTrace providers in their detach(9E) entry point.
6197  */
6198 int
6199 dtrace_unregister(dtrace_provider_id_t id)
6200 {
6201 	dtrace_provider_t *old = (dtrace_provider_t *)id;
6202 	dtrace_provider_t *prev = NULL;
6203 	int i, self = 0;
6204 	dtrace_probe_t *probe, *first = NULL;
6205 
6206 	if (old->dtpv_pops.dtps_enable ==
6207 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
6208 		/*
6209 		 * If DTrace itself is the provider, we're called with locks
6210 		 * already held.
6211 		 */
6212 		ASSERT(old == dtrace_provider);
6213 		ASSERT(dtrace_devi != NULL);
6214 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6215 		ASSERT(MUTEX_HELD(&dtrace_lock));
6216 		self = 1;
6217 
6218 		if (dtrace_provider->dtpv_next != NULL) {
6219 			/*
6220 			 * There's another provider here; return failure.
6221 			 */
6222 			return (EBUSY);
6223 		}
6224 	} else {
6225 		mutex_enter(&dtrace_provider_lock);
6226 		mutex_enter(&mod_lock);
6227 		mutex_enter(&dtrace_lock);
6228 	}
6229 
6230 	/*
6231 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
6232 	 * probes, we refuse to let providers slither away, unless this
6233 	 * provider has already been explicitly invalidated.
6234 	 */
6235 	if (!old->dtpv_defunct &&
6236 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
6237 	    dtrace_anon.dta_state->dts_necbs > 0))) {
6238 		if (!self) {
6239 			mutex_exit(&dtrace_lock);
6240 			mutex_exit(&mod_lock);
6241 			mutex_exit(&dtrace_provider_lock);
6242 		}
6243 		return (EBUSY);
6244 	}
6245 
6246 	/*
6247 	 * Attempt to destroy the probes associated with this provider.
6248 	 */
6249 	for (i = 0; i < dtrace_nprobes; i++) {
6250 		if ((probe = dtrace_probes[i]) == NULL)
6251 			continue;
6252 
6253 		if (probe->dtpr_provider != old)
6254 			continue;
6255 
6256 		if (probe->dtpr_ecb == NULL)
6257 			continue;
6258 
6259 		/*
6260 		 * We have at least one ECB; we can't remove this provider.
6261 		 */
6262 		if (!self) {
6263 			mutex_exit(&dtrace_lock);
6264 			mutex_exit(&mod_lock);
6265 			mutex_exit(&dtrace_provider_lock);
6266 		}
6267 		return (EBUSY);
6268 	}
6269 
6270 	/*
6271 	 * All of the probes for this provider are disabled; we can safely
6272 	 * remove all of them from their hash chains and from the probe array.
6273 	 */
6274 	for (i = 0; i < dtrace_nprobes; i++) {
6275 		if ((probe = dtrace_probes[i]) == NULL)
6276 			continue;
6277 
6278 		if (probe->dtpr_provider != old)
6279 			continue;
6280 
6281 		dtrace_probes[i] = NULL;
6282 
6283 		dtrace_hash_remove(dtrace_bymod, probe);
6284 		dtrace_hash_remove(dtrace_byfunc, probe);
6285 		dtrace_hash_remove(dtrace_byname, probe);
6286 
6287 		if (first == NULL) {
6288 			first = probe;
6289 			probe->dtpr_nextmod = NULL;
6290 		} else {
6291 			probe->dtpr_nextmod = first;
6292 			first = probe;
6293 		}
6294 	}
6295 
6296 	/*
6297 	 * The provider's probes have been removed from the hash chains and
6298 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
6299 	 * everyone has cleared out from any probe array processing.
6300 	 */
6301 	dtrace_sync();
6302 
6303 	for (probe = first; probe != NULL; probe = first) {
6304 		first = probe->dtpr_nextmod;
6305 
6306 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
6307 		    probe->dtpr_arg);
6308 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
6309 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
6310 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
6311 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
6312 		kmem_free(probe, sizeof (dtrace_probe_t));
6313 	}
6314 
6315 	if ((prev = dtrace_provider) == old) {
6316 		ASSERT(self || dtrace_devi == NULL);
6317 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
6318 		dtrace_provider = old->dtpv_next;
6319 	} else {
6320 		while (prev != NULL && prev->dtpv_next != old)
6321 			prev = prev->dtpv_next;
6322 
6323 		if (prev == NULL) {
6324 			panic("attempt to unregister non-existent "
6325 			    "dtrace provider %p\n", (void *)id);
6326 		}
6327 
6328 		prev->dtpv_next = old->dtpv_next;
6329 	}
6330 
6331 	if (!self) {
6332 		mutex_exit(&dtrace_lock);
6333 		mutex_exit(&mod_lock);
6334 		mutex_exit(&dtrace_provider_lock);
6335 	}
6336 
6337 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
6338 	kmem_free(old, sizeof (dtrace_provider_t));
6339 
6340 	return (0);
6341 }
6342 
6343 /*
6344  * Invalidate the specified provider.  All subsequent probe lookups for the
6345  * specified provider will fail, but its probes will not be removed.
6346  */
6347 void
6348 dtrace_invalidate(dtrace_provider_id_t id)
6349 {
6350 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
6351 
6352 	ASSERT(pvp->dtpv_pops.dtps_enable !=
6353 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6354 
6355 	mutex_enter(&dtrace_provider_lock);
6356 	mutex_enter(&dtrace_lock);
6357 
6358 	pvp->dtpv_defunct = 1;
6359 
6360 	mutex_exit(&dtrace_lock);
6361 	mutex_exit(&dtrace_provider_lock);
6362 }
6363 
6364 /*
6365  * Indicate whether or not DTrace has attached.
6366  */
6367 int
6368 dtrace_attached(void)
6369 {
6370 	/*
6371 	 * dtrace_provider will be non-NULL iff the DTrace driver has
6372 	 * attached.  (It's non-NULL because DTrace is always itself a
6373 	 * provider.)
6374 	 */
6375 	return (dtrace_provider != NULL);
6376 }
6377 
6378 /*
6379  * Remove all the unenabled probes for the given provider.  This function is
6380  * not unlike dtrace_unregister(), except that it doesn't remove the provider
6381  * -- just as many of its associated probes as it can.
6382  */
6383 int
6384 dtrace_condense(dtrace_provider_id_t id)
6385 {
6386 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
6387 	int i;
6388 	dtrace_probe_t *probe;
6389 
6390 	/*
6391 	 * Make sure this isn't the dtrace provider itself.
6392 	 */
6393 	ASSERT(prov->dtpv_pops.dtps_enable !=
6394 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6395 
6396 	mutex_enter(&dtrace_provider_lock);
6397 	mutex_enter(&dtrace_lock);
6398 
6399 	/*
6400 	 * Attempt to destroy the probes associated with this provider.
6401 	 */
6402 	for (i = 0; i < dtrace_nprobes; i++) {
6403 		if ((probe = dtrace_probes[i]) == NULL)
6404 			continue;
6405 
6406 		if (probe->dtpr_provider != prov)
6407 			continue;
6408 
6409 		if (probe->dtpr_ecb != NULL)
6410 			continue;
6411 
6412 		dtrace_probes[i] = NULL;
6413 
6414 		dtrace_hash_remove(dtrace_bymod, probe);
6415 		dtrace_hash_remove(dtrace_byfunc, probe);
6416 		dtrace_hash_remove(dtrace_byname, probe);
6417 
6418 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
6419 		    probe->dtpr_arg);
6420 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
6421 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
6422 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
6423 		kmem_free(probe, sizeof (dtrace_probe_t));
6424 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
6425 	}
6426 
6427 	mutex_exit(&dtrace_lock);
6428 	mutex_exit(&dtrace_provider_lock);
6429 
6430 	return (0);
6431 }
6432 
6433 /*
6434  * DTrace Probe Management Functions
6435  *
6436  * The functions in this section perform the DTrace probe management,
6437  * including functions to create probes, look-up probes, and call into the
6438  * providers to request that probes be provided.  Some of these functions are
6439  * in the Provider-to-Framework API; these functions can be identified by the
6440  * fact that they are not declared "static".
6441  */
6442 
6443 /*
6444  * Create a probe with the specified module name, function name, and name.
6445  */
6446 dtrace_id_t
6447 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
6448     const char *func, const char *name, int aframes, void *arg)
6449 {
6450 	dtrace_probe_t *probe, **probes;
6451 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
6452 	dtrace_id_t id;
6453 
6454 	if (provider == dtrace_provider) {
6455 		ASSERT(MUTEX_HELD(&dtrace_lock));
6456 	} else {
6457 		mutex_enter(&dtrace_lock);
6458 	}
6459 
6460 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
6461 	    VM_BESTFIT | VM_SLEEP);
6462 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
6463 
6464 	probe->dtpr_id = id;
6465 	probe->dtpr_gen = dtrace_probegen++;
6466 	probe->dtpr_mod = dtrace_strdup(mod);
6467 	probe->dtpr_func = dtrace_strdup(func);
6468 	probe->dtpr_name = dtrace_strdup(name);
6469 	probe->dtpr_arg = arg;
6470 	probe->dtpr_aframes = aframes;
6471 	probe->dtpr_provider = provider;
6472 
6473 	dtrace_hash_add(dtrace_bymod, probe);
6474 	dtrace_hash_add(dtrace_byfunc, probe);
6475 	dtrace_hash_add(dtrace_byname, probe);
6476 
6477 	if (id - 1 >= dtrace_nprobes) {
6478 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
6479 		size_t nsize = osize << 1;
6480 
6481 		if (nsize == 0) {
6482 			ASSERT(osize == 0);
6483 			ASSERT(dtrace_probes == NULL);
6484 			nsize = sizeof (dtrace_probe_t *);
6485 		}
6486 
6487 		probes = kmem_zalloc(nsize, KM_SLEEP);
6488 
6489 		if (dtrace_probes == NULL) {
6490 			ASSERT(osize == 0);
6491 			dtrace_probes = probes;
6492 			dtrace_nprobes = 1;
6493 		} else {
6494 			dtrace_probe_t **oprobes = dtrace_probes;
6495 
6496 			bcopy(oprobes, probes, osize);
6497 			dtrace_membar_producer();
6498 			dtrace_probes = probes;
6499 
6500 			dtrace_sync();
6501 
6502 			/*
6503 			 * All CPUs are now seeing the new probes array; we can
6504 			 * safely free the old array.
6505 			 */
6506 			kmem_free(oprobes, osize);
6507 			dtrace_nprobes <<= 1;
6508 		}
6509 
6510 		ASSERT(id - 1 < dtrace_nprobes);
6511 	}
6512 
6513 	ASSERT(dtrace_probes[id - 1] == NULL);
6514 	dtrace_probes[id - 1] = probe;
6515 
6516 	if (provider != dtrace_provider)
6517 		mutex_exit(&dtrace_lock);
6518 
6519 	return (id);
6520 }
6521 
6522 static dtrace_probe_t *
6523 dtrace_probe_lookup_id(dtrace_id_t id)
6524 {
6525 	ASSERT(MUTEX_HELD(&dtrace_lock));
6526 
6527 	if (id == 0 || id > dtrace_nprobes)
6528 		return (NULL);
6529 
6530 	return (dtrace_probes[id - 1]);
6531 }
6532 
6533 static int
6534 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
6535 {
6536 	*((dtrace_id_t *)arg) = probe->dtpr_id;
6537 
6538 	return (DTRACE_MATCH_DONE);
6539 }
6540 
6541 /*
6542  * Look up a probe based on provider and one or more of module name, function
6543  * name and probe name.
6544  */
6545 dtrace_id_t
6546 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
6547     const char *func, const char *name)
6548 {
6549 	dtrace_probekey_t pkey;
6550 	dtrace_id_t id;
6551 	int match;
6552 
6553 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
6554 	pkey.dtpk_pmatch = &dtrace_match_string;
6555 	pkey.dtpk_mod = mod;
6556 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
6557 	pkey.dtpk_func = func;
6558 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
6559 	pkey.dtpk_name = name;
6560 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
6561 	pkey.dtpk_id = DTRACE_IDNONE;
6562 
6563 	mutex_enter(&dtrace_lock);
6564 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
6565 	    dtrace_probe_lookup_match, &id);
6566 	mutex_exit(&dtrace_lock);
6567 
6568 	ASSERT(match == 1 || match == 0);
6569 	return (match ? id : 0);
6570 }
6571 
6572 /*
6573  * Returns the probe argument associated with the specified probe.
6574  */
6575 void *
6576 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
6577 {
6578 	dtrace_probe_t *probe;
6579 	void *rval = NULL;
6580 
6581 	mutex_enter(&dtrace_lock);
6582 
6583 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
6584 	    probe->dtpr_provider == (dtrace_provider_t *)id)
6585 		rval = probe->dtpr_arg;
6586 
6587 	mutex_exit(&dtrace_lock);
6588 
6589 	return (rval);
6590 }
6591 
6592 /*
6593  * Copy a probe into a probe description.
6594  */
6595 static void
6596 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
6597 {
6598 	bzero(pdp, sizeof (dtrace_probedesc_t));
6599 	pdp->dtpd_id = prp->dtpr_id;
6600 
6601 	(void) strncpy(pdp->dtpd_provider,
6602 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
6603 
6604 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
6605 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
6606 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
6607 }
6608 
6609 /*
6610  * Called to indicate that a probe -- or probes -- should be provided by a
6611  * specfied provider.  If the specified description is NULL, the provider will
6612  * be told to provide all of its probes.  (This is done whenever a new
6613  * consumer comes along, or whenever a retained enabling is to be matched.) If
6614  * the specified description is non-NULL, the provider is given the
6615  * opportunity to dynamically provide the specified probe, allowing providers
6616  * to support the creation of probes on-the-fly.  (So-called _autocreated_
6617  * probes.)  If the provider is NULL, the operations will be applied to all
6618  * providers; if the provider is non-NULL the operations will only be applied
6619  * to the specified provider.  The dtrace_provider_lock must be held, and the
6620  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
6621  * will need to grab the dtrace_lock when it reenters the framework through
6622  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
6623  */
6624 static void
6625 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
6626 {
6627 	struct modctl *ctl;
6628 	int all = 0;
6629 
6630 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6631 
6632 	if (prv == NULL) {
6633 		all = 1;
6634 		prv = dtrace_provider;
6635 	}
6636 
6637 	do {
6638 		/*
6639 		 * First, call the blanket provide operation.
6640 		 */
6641 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
6642 
6643 		/*
6644 		 * Now call the per-module provide operation.  We will grab
6645 		 * mod_lock to prevent the list from being modified.  Note
6646 		 * that this also prevents the mod_busy bits from changing.
6647 		 * (mod_busy can only be changed with mod_lock held.)
6648 		 */
6649 		mutex_enter(&mod_lock);
6650 
6651 		ctl = &modules;
6652 		do {
6653 			if (ctl->mod_busy || ctl->mod_mp == NULL)
6654 				continue;
6655 
6656 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
6657 
6658 		} while ((ctl = ctl->mod_next) != &modules);
6659 
6660 		mutex_exit(&mod_lock);
6661 	} while (all && (prv = prv->dtpv_next) != NULL);
6662 }
6663 
6664 /*
6665  * Iterate over each probe, and call the Framework-to-Provider API function
6666  * denoted by offs.
6667  */
6668 static void
6669 dtrace_probe_foreach(uintptr_t offs)
6670 {
6671 	dtrace_provider_t *prov;
6672 	void (*func)(void *, dtrace_id_t, void *);
6673 	dtrace_probe_t *probe;
6674 	dtrace_icookie_t cookie;
6675 	int i;
6676 
6677 	/*
6678 	 * We disable interrupts to walk through the probe array.  This is
6679 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
6680 	 * won't see stale data.
6681 	 */
6682 	cookie = dtrace_interrupt_disable();
6683 
6684 	for (i = 0; i < dtrace_nprobes; i++) {
6685 		if ((probe = dtrace_probes[i]) == NULL)
6686 			continue;
6687 
6688 		if (probe->dtpr_ecb == NULL) {
6689 			/*
6690 			 * This probe isn't enabled -- don't call the function.
6691 			 */
6692 			continue;
6693 		}
6694 
6695 		prov = probe->dtpr_provider;
6696 		func = *((void(**)(void *, dtrace_id_t, void *))
6697 		    ((uintptr_t)&prov->dtpv_pops + offs));
6698 
6699 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
6700 	}
6701 
6702 	dtrace_interrupt_enable(cookie);
6703 }
6704 
6705 static int
6706 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
6707 {
6708 	dtrace_probekey_t pkey;
6709 	uint32_t priv;
6710 	uid_t uid;
6711 	zoneid_t zoneid;
6712 
6713 	ASSERT(MUTEX_HELD(&dtrace_lock));
6714 	dtrace_ecb_create_cache = NULL;
6715 
6716 	if (desc == NULL) {
6717 		/*
6718 		 * If we're passed a NULL description, we're being asked to
6719 		 * create an ECB with a NULL probe.
6720 		 */
6721 		(void) dtrace_ecb_create_enable(NULL, enab);
6722 		return (0);
6723 	}
6724 
6725 	dtrace_probekey(desc, &pkey);
6726 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
6727 	    &priv, &uid, &zoneid);
6728 
6729 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
6730 	    enab));
6731 }
6732 
6733 /*
6734  * DTrace Helper Provider Functions
6735  */
6736 static void
6737 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
6738 {
6739 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
6740 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
6741 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
6742 }
6743 
6744 static void
6745 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
6746     const dof_provider_t *dofprov, char *strtab)
6747 {
6748 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
6749 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
6750 	    dofprov->dofpv_provattr);
6751 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
6752 	    dofprov->dofpv_modattr);
6753 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
6754 	    dofprov->dofpv_funcattr);
6755 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
6756 	    dofprov->dofpv_nameattr);
6757 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
6758 	    dofprov->dofpv_argsattr);
6759 }
6760 
6761 static void
6762 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
6763 {
6764 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6765 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6766 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
6767 	dof_provider_t *provider;
6768 	dof_probe_t *probe;
6769 	uint32_t *off, *enoff;
6770 	uint8_t *arg;
6771 	char *strtab;
6772 	uint_t i, nprobes;
6773 	dtrace_helper_provdesc_t dhpv;
6774 	dtrace_helper_probedesc_t dhpb;
6775 	dtrace_meta_t *meta = dtrace_meta_pid;
6776 	dtrace_mops_t *mops = &meta->dtm_mops;
6777 	void *parg;
6778 
6779 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
6780 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6781 	    provider->dofpv_strtab * dof->dofh_secsize);
6782 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6783 	    provider->dofpv_probes * dof->dofh_secsize);
6784 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6785 	    provider->dofpv_prargs * dof->dofh_secsize);
6786 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6787 	    provider->dofpv_proffs * dof->dofh_secsize);
6788 
6789 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
6790 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
6791 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
6792 	enoff = NULL;
6793 
6794 	/*
6795 	 * See dtrace_helper_provider_validate().
6796 	 */
6797 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
6798 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
6799 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6800 		    provider->dofpv_prenoffs * dof->dofh_secsize);
6801 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
6802 	}
6803 
6804 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
6805 
6806 	/*
6807 	 * Create the provider.
6808 	 */
6809 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
6810 
6811 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
6812 		return;
6813 
6814 	meta->dtm_count++;
6815 
6816 	/*
6817 	 * Create the probes.
6818 	 */
6819 	for (i = 0; i < nprobes; i++) {
6820 		probe = (dof_probe_t *)(uintptr_t)(daddr +
6821 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
6822 
6823 		dhpb.dthpb_mod = dhp->dofhp_mod;
6824 		dhpb.dthpb_func = strtab + probe->dofpr_func;
6825 		dhpb.dthpb_name = strtab + probe->dofpr_name;
6826 		dhpb.dthpb_base = probe->dofpr_addr;
6827 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
6828 		dhpb.dthpb_noffs = probe->dofpr_noffs;
6829 		if (enoff != NULL) {
6830 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
6831 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
6832 		} else {
6833 			dhpb.dthpb_enoffs = NULL;
6834 			dhpb.dthpb_nenoffs = 0;
6835 		}
6836 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
6837 		dhpb.dthpb_nargc = probe->dofpr_nargc;
6838 		dhpb.dthpb_xargc = probe->dofpr_xargc;
6839 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
6840 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
6841 
6842 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
6843 	}
6844 }
6845 
6846 static void
6847 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
6848 {
6849 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6850 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6851 	int i;
6852 
6853 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
6854 
6855 	for (i = 0; i < dof->dofh_secnum; i++) {
6856 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
6857 		    dof->dofh_secoff + i * dof->dofh_secsize);
6858 
6859 		if (sec->dofs_type != DOF_SECT_PROVIDER)
6860 			continue;
6861 
6862 		dtrace_helper_provide_one(dhp, sec, pid);
6863 	}
6864 
6865 	/*
6866 	 * We may have just created probes, so we must now rematch against
6867 	 * any retained enablings.  Note that this call will acquire both
6868 	 * cpu_lock and dtrace_lock; the fact that we are holding
6869 	 * dtrace_meta_lock now is what defines the ordering with respect to
6870 	 * these three locks.
6871 	 */
6872 	dtrace_enabling_matchall();
6873 }
6874 
6875 static void
6876 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
6877 {
6878 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6879 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6880 	dof_sec_t *str_sec;
6881 	dof_provider_t *provider;
6882 	char *strtab;
6883 	dtrace_helper_provdesc_t dhpv;
6884 	dtrace_meta_t *meta = dtrace_meta_pid;
6885 	dtrace_mops_t *mops = &meta->dtm_mops;
6886 
6887 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
6888 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
6889 	    provider->dofpv_strtab * dof->dofh_secsize);
6890 
6891 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
6892 
6893 	/*
6894 	 * Create the provider.
6895 	 */
6896 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
6897 
6898 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
6899 
6900 	meta->dtm_count--;
6901 }
6902 
6903 static void
6904 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
6905 {
6906 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
6907 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
6908 	int i;
6909 
6910 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
6911 
6912 	for (i = 0; i < dof->dofh_secnum; i++) {
6913 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
6914 		    dof->dofh_secoff + i * dof->dofh_secsize);
6915 
6916 		if (sec->dofs_type != DOF_SECT_PROVIDER)
6917 			continue;
6918 
6919 		dtrace_helper_provider_remove_one(dhp, sec, pid);
6920 	}
6921 }
6922 
6923 /*
6924  * DTrace Meta Provider-to-Framework API Functions
6925  *
6926  * These functions implement the Meta Provider-to-Framework API, as described
6927  * in <sys/dtrace.h>.
6928  */
6929 int
6930 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
6931     dtrace_meta_provider_id_t *idp)
6932 {
6933 	dtrace_meta_t *meta;
6934 	dtrace_helpers_t *help, *next;
6935 	int i;
6936 
6937 	*idp = DTRACE_METAPROVNONE;
6938 
6939 	/*
6940 	 * We strictly don't need the name, but we hold onto it for
6941 	 * debuggability. All hail error queues!
6942 	 */
6943 	if (name == NULL) {
6944 		cmn_err(CE_WARN, "failed to register meta-provider: "
6945 		    "invalid name");
6946 		return (EINVAL);
6947 	}
6948 
6949 	if (mops == NULL ||
6950 	    mops->dtms_create_probe == NULL ||
6951 	    mops->dtms_provide_pid == NULL ||
6952 	    mops->dtms_remove_pid == NULL) {
6953 		cmn_err(CE_WARN, "failed to register meta-register %s: "
6954 		    "invalid ops", name);
6955 		return (EINVAL);
6956 	}
6957 
6958 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
6959 	meta->dtm_mops = *mops;
6960 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
6961 	(void) strcpy(meta->dtm_name, name);
6962 	meta->dtm_arg = arg;
6963 
6964 	mutex_enter(&dtrace_meta_lock);
6965 	mutex_enter(&dtrace_lock);
6966 
6967 	if (dtrace_meta_pid != NULL) {
6968 		mutex_exit(&dtrace_lock);
6969 		mutex_exit(&dtrace_meta_lock);
6970 		cmn_err(CE_WARN, "failed to register meta-register %s: "
6971 		    "user-land meta-provider exists", name);
6972 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
6973 		kmem_free(meta, sizeof (dtrace_meta_t));
6974 		return (EINVAL);
6975 	}
6976 
6977 	dtrace_meta_pid = meta;
6978 	*idp = (dtrace_meta_provider_id_t)meta;
6979 
6980 	/*
6981 	 * If there are providers and probes ready to go, pass them
6982 	 * off to the new meta provider now.
6983 	 */
6984 
6985 	help = dtrace_deferred_pid;
6986 	dtrace_deferred_pid = NULL;
6987 
6988 	mutex_exit(&dtrace_lock);
6989 
6990 	while (help != NULL) {
6991 		for (i = 0; i < help->dthps_nprovs; i++) {
6992 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
6993 			    help->dthps_pid);
6994 		}
6995 
6996 		next = help->dthps_next;
6997 		help->dthps_next = NULL;
6998 		help->dthps_prev = NULL;
6999 		help->dthps_deferred = 0;
7000 		help = next;
7001 	}
7002 
7003 	mutex_exit(&dtrace_meta_lock);
7004 
7005 	return (0);
7006 }
7007 
7008 int
7009 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
7010 {
7011 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
7012 
7013 	mutex_enter(&dtrace_meta_lock);
7014 	mutex_enter(&dtrace_lock);
7015 
7016 	if (old == dtrace_meta_pid) {
7017 		pp = &dtrace_meta_pid;
7018 	} else {
7019 		panic("attempt to unregister non-existent "
7020 		    "dtrace meta-provider %p\n", (void *)old);
7021 	}
7022 
7023 	if (old->dtm_count != 0) {
7024 		mutex_exit(&dtrace_lock);
7025 		mutex_exit(&dtrace_meta_lock);
7026 		return (EBUSY);
7027 	}
7028 
7029 	*pp = NULL;
7030 
7031 	mutex_exit(&dtrace_lock);
7032 	mutex_exit(&dtrace_meta_lock);
7033 
7034 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
7035 	kmem_free(old, sizeof (dtrace_meta_t));
7036 
7037 	return (0);
7038 }
7039 
7040 
7041 /*
7042  * DTrace DIF Object Functions
7043  */
7044 static int
7045 dtrace_difo_err(uint_t pc, const char *format, ...)
7046 {
7047 	if (dtrace_err_verbose) {
7048 		va_list alist;
7049 
7050 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
7051 		va_start(alist, format);
7052 		(void) vuprintf(format, alist);
7053 		va_end(alist);
7054 	}
7055 
7056 #ifdef DTRACE_ERRDEBUG
7057 	dtrace_errdebug(format);
7058 #endif
7059 	return (1);
7060 }
7061 
7062 /*
7063  * Validate a DTrace DIF object by checking the IR instructions.  The following
7064  * rules are currently enforced by dtrace_difo_validate():
7065  *
7066  * 1. Each instruction must have a valid opcode
7067  * 2. Each register, string, variable, or subroutine reference must be valid
7068  * 3. No instruction can modify register %r0 (must be zero)
7069  * 4. All instruction reserved bits must be set to zero
7070  * 5. The last instruction must be a "ret" instruction
7071  * 6. All branch targets must reference a valid instruction _after_ the branch
7072  */
7073 static int
7074 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
7075     cred_t *cr)
7076 {
7077 	int err = 0, i;
7078 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
7079 	int kcheck;
7080 	uint_t pc;
7081 
7082 	kcheck = cr == NULL ||
7083 	    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE) == 0;
7084 
7085 	dp->dtdo_destructive = 0;
7086 
7087 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
7088 		dif_instr_t instr = dp->dtdo_buf[pc];
7089 
7090 		uint_t r1 = DIF_INSTR_R1(instr);
7091 		uint_t r2 = DIF_INSTR_R2(instr);
7092 		uint_t rd = DIF_INSTR_RD(instr);
7093 		uint_t rs = DIF_INSTR_RS(instr);
7094 		uint_t label = DIF_INSTR_LABEL(instr);
7095 		uint_t v = DIF_INSTR_VAR(instr);
7096 		uint_t subr = DIF_INSTR_SUBR(instr);
7097 		uint_t type = DIF_INSTR_TYPE(instr);
7098 		uint_t op = DIF_INSTR_OP(instr);
7099 
7100 		switch (op) {
7101 		case DIF_OP_OR:
7102 		case DIF_OP_XOR:
7103 		case DIF_OP_AND:
7104 		case DIF_OP_SLL:
7105 		case DIF_OP_SRL:
7106 		case DIF_OP_SRA:
7107 		case DIF_OP_SUB:
7108 		case DIF_OP_ADD:
7109 		case DIF_OP_MUL:
7110 		case DIF_OP_SDIV:
7111 		case DIF_OP_UDIV:
7112 		case DIF_OP_SREM:
7113 		case DIF_OP_UREM:
7114 		case DIF_OP_COPYS:
7115 			if (r1 >= nregs)
7116 				err += efunc(pc, "invalid register %u\n", r1);
7117 			if (r2 >= nregs)
7118 				err += efunc(pc, "invalid register %u\n", r2);
7119 			if (rd >= nregs)
7120 				err += efunc(pc, "invalid register %u\n", rd);
7121 			if (rd == 0)
7122 				err += efunc(pc, "cannot write to %r0\n");
7123 			break;
7124 		case DIF_OP_NOT:
7125 		case DIF_OP_MOV:
7126 		case DIF_OP_ALLOCS:
7127 			if (r1 >= nregs)
7128 				err += efunc(pc, "invalid register %u\n", r1);
7129 			if (r2 != 0)
7130 				err += efunc(pc, "non-zero reserved bits\n");
7131 			if (rd >= nregs)
7132 				err += efunc(pc, "invalid register %u\n", rd);
7133 			if (rd == 0)
7134 				err += efunc(pc, "cannot write to %r0\n");
7135 			break;
7136 		case DIF_OP_LDSB:
7137 		case DIF_OP_LDSH:
7138 		case DIF_OP_LDSW:
7139 		case DIF_OP_LDUB:
7140 		case DIF_OP_LDUH:
7141 		case DIF_OP_LDUW:
7142 		case DIF_OP_LDX:
7143 			if (r1 >= nregs)
7144 				err += efunc(pc, "invalid register %u\n", r1);
7145 			if (r2 != 0)
7146 				err += efunc(pc, "non-zero reserved bits\n");
7147 			if (rd >= nregs)
7148 				err += efunc(pc, "invalid register %u\n", rd);
7149 			if (rd == 0)
7150 				err += efunc(pc, "cannot write to %r0\n");
7151 			if (kcheck)
7152 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
7153 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
7154 			break;
7155 		case DIF_OP_RLDSB:
7156 		case DIF_OP_RLDSH:
7157 		case DIF_OP_RLDSW:
7158 		case DIF_OP_RLDUB:
7159 		case DIF_OP_RLDUH:
7160 		case DIF_OP_RLDUW:
7161 		case DIF_OP_RLDX:
7162 			if (r1 >= nregs)
7163 				err += efunc(pc, "invalid register %u\n", r1);
7164 			if (r2 != 0)
7165 				err += efunc(pc, "non-zero reserved bits\n");
7166 			if (rd >= nregs)
7167 				err += efunc(pc, "invalid register %u\n", rd);
7168 			if (rd == 0)
7169 				err += efunc(pc, "cannot write to %r0\n");
7170 			break;
7171 		case DIF_OP_ULDSB:
7172 		case DIF_OP_ULDSH:
7173 		case DIF_OP_ULDSW:
7174 		case DIF_OP_ULDUB:
7175 		case DIF_OP_ULDUH:
7176 		case DIF_OP_ULDUW:
7177 		case DIF_OP_ULDX:
7178 			if (r1 >= nregs)
7179 				err += efunc(pc, "invalid register %u\n", r1);
7180 			if (r2 != 0)
7181 				err += efunc(pc, "non-zero reserved bits\n");
7182 			if (rd >= nregs)
7183 				err += efunc(pc, "invalid register %u\n", rd);
7184 			if (rd == 0)
7185 				err += efunc(pc, "cannot write to %r0\n");
7186 			break;
7187 		case DIF_OP_STB:
7188 		case DIF_OP_STH:
7189 		case DIF_OP_STW:
7190 		case DIF_OP_STX:
7191 			if (r1 >= nregs)
7192 				err += efunc(pc, "invalid register %u\n", r1);
7193 			if (r2 != 0)
7194 				err += efunc(pc, "non-zero reserved bits\n");
7195 			if (rd >= nregs)
7196 				err += efunc(pc, "invalid register %u\n", rd);
7197 			if (rd == 0)
7198 				err += efunc(pc, "cannot write to 0 address\n");
7199 			break;
7200 		case DIF_OP_CMP:
7201 		case DIF_OP_SCMP:
7202 			if (r1 >= nregs)
7203 				err += efunc(pc, "invalid register %u\n", r1);
7204 			if (r2 >= nregs)
7205 				err += efunc(pc, "invalid register %u\n", r2);
7206 			if (rd != 0)
7207 				err += efunc(pc, "non-zero reserved bits\n");
7208 			break;
7209 		case DIF_OP_TST:
7210 			if (r1 >= nregs)
7211 				err += efunc(pc, "invalid register %u\n", r1);
7212 			if (r2 != 0 || rd != 0)
7213 				err += efunc(pc, "non-zero reserved bits\n");
7214 			break;
7215 		case DIF_OP_BA:
7216 		case DIF_OP_BE:
7217 		case DIF_OP_BNE:
7218 		case DIF_OP_BG:
7219 		case DIF_OP_BGU:
7220 		case DIF_OP_BGE:
7221 		case DIF_OP_BGEU:
7222 		case DIF_OP_BL:
7223 		case DIF_OP_BLU:
7224 		case DIF_OP_BLE:
7225 		case DIF_OP_BLEU:
7226 			if (label >= dp->dtdo_len) {
7227 				err += efunc(pc, "invalid branch target %u\n",
7228 				    label);
7229 			}
7230 			if (label <= pc) {
7231 				err += efunc(pc, "backward branch to %u\n",
7232 				    label);
7233 			}
7234 			break;
7235 		case DIF_OP_RET:
7236 			if (r1 != 0 || r2 != 0)
7237 				err += efunc(pc, "non-zero reserved bits\n");
7238 			if (rd >= nregs)
7239 				err += efunc(pc, "invalid register %u\n", rd);
7240 			break;
7241 		case DIF_OP_NOP:
7242 		case DIF_OP_POPTS:
7243 		case DIF_OP_FLUSHTS:
7244 			if (r1 != 0 || r2 != 0 || rd != 0)
7245 				err += efunc(pc, "non-zero reserved bits\n");
7246 			break;
7247 		case DIF_OP_SETX:
7248 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
7249 				err += efunc(pc, "invalid integer ref %u\n",
7250 				    DIF_INSTR_INTEGER(instr));
7251 			}
7252 			if (rd >= nregs)
7253 				err += efunc(pc, "invalid register %u\n", rd);
7254 			if (rd == 0)
7255 				err += efunc(pc, "cannot write to %r0\n");
7256 			break;
7257 		case DIF_OP_SETS:
7258 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
7259 				err += efunc(pc, "invalid string ref %u\n",
7260 				    DIF_INSTR_STRING(instr));
7261 			}
7262 			if (rd >= nregs)
7263 				err += efunc(pc, "invalid register %u\n", rd);
7264 			if (rd == 0)
7265 				err += efunc(pc, "cannot write to %r0\n");
7266 			break;
7267 		case DIF_OP_LDGA:
7268 		case DIF_OP_LDTA:
7269 			if (r1 > DIF_VAR_ARRAY_MAX)
7270 				err += efunc(pc, "invalid array %u\n", r1);
7271 			if (r2 >= nregs)
7272 				err += efunc(pc, "invalid register %u\n", r2);
7273 			if (rd >= nregs)
7274 				err += efunc(pc, "invalid register %u\n", rd);
7275 			if (rd == 0)
7276 				err += efunc(pc, "cannot write to %r0\n");
7277 			break;
7278 		case DIF_OP_LDGS:
7279 		case DIF_OP_LDTS:
7280 		case DIF_OP_LDLS:
7281 		case DIF_OP_LDGAA:
7282 		case DIF_OP_LDTAA:
7283 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
7284 				err += efunc(pc, "invalid variable %u\n", v);
7285 			if (rd >= nregs)
7286 				err += efunc(pc, "invalid register %u\n", rd);
7287 			if (rd == 0)
7288 				err += efunc(pc, "cannot write to %r0\n");
7289 			break;
7290 		case DIF_OP_STGS:
7291 		case DIF_OP_STTS:
7292 		case DIF_OP_STLS:
7293 		case DIF_OP_STGAA:
7294 		case DIF_OP_STTAA:
7295 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
7296 				err += efunc(pc, "invalid variable %u\n", v);
7297 			if (rs >= nregs)
7298 				err += efunc(pc, "invalid register %u\n", rd);
7299 			break;
7300 		case DIF_OP_CALL:
7301 			if (subr > DIF_SUBR_MAX)
7302 				err += efunc(pc, "invalid subr %u\n", subr);
7303 			if (rd >= nregs)
7304 				err += efunc(pc, "invalid register %u\n", rd);
7305 			if (rd == 0)
7306 				err += efunc(pc, "cannot write to %r0\n");
7307 
7308 			if (subr == DIF_SUBR_COPYOUT ||
7309 			    subr == DIF_SUBR_COPYOUTSTR) {
7310 				dp->dtdo_destructive = 1;
7311 			}
7312 			break;
7313 		case DIF_OP_PUSHTR:
7314 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
7315 				err += efunc(pc, "invalid ref type %u\n", type);
7316 			if (r2 >= nregs)
7317 				err += efunc(pc, "invalid register %u\n", r2);
7318 			if (rs >= nregs)
7319 				err += efunc(pc, "invalid register %u\n", rs);
7320 			break;
7321 		case DIF_OP_PUSHTV:
7322 			if (type != DIF_TYPE_CTF)
7323 				err += efunc(pc, "invalid val type %u\n", type);
7324 			if (r2 >= nregs)
7325 				err += efunc(pc, "invalid register %u\n", r2);
7326 			if (rs >= nregs)
7327 				err += efunc(pc, "invalid register %u\n", rs);
7328 			break;
7329 		default:
7330 			err += efunc(pc, "invalid opcode %u\n",
7331 			    DIF_INSTR_OP(instr));
7332 		}
7333 	}
7334 
7335 	if (dp->dtdo_len != 0 &&
7336 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
7337 		err += efunc(dp->dtdo_len - 1,
7338 		    "expected 'ret' as last DIF instruction\n");
7339 	}
7340 
7341 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
7342 		/*
7343 		 * If we're not returning by reference, the size must be either
7344 		 * 0 or the size of one of the base types.
7345 		 */
7346 		switch (dp->dtdo_rtype.dtdt_size) {
7347 		case 0:
7348 		case sizeof (uint8_t):
7349 		case sizeof (uint16_t):
7350 		case sizeof (uint32_t):
7351 		case sizeof (uint64_t):
7352 			break;
7353 
7354 		default:
7355 			err += efunc(dp->dtdo_len - 1, "bad return size");
7356 		}
7357 	}
7358 
7359 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
7360 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
7361 		dtrace_diftype_t *vt, *et;
7362 		uint_t id, ndx;
7363 
7364 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
7365 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
7366 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
7367 			err += efunc(i, "unrecognized variable scope %d\n",
7368 			    v->dtdv_scope);
7369 			break;
7370 		}
7371 
7372 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
7373 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
7374 			err += efunc(i, "unrecognized variable type %d\n",
7375 			    v->dtdv_kind);
7376 			break;
7377 		}
7378 
7379 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
7380 			err += efunc(i, "%d exceeds variable id limit\n", id);
7381 			break;
7382 		}
7383 
7384 		if (id < DIF_VAR_OTHER_UBASE)
7385 			continue;
7386 
7387 		/*
7388 		 * For user-defined variables, we need to check that this
7389 		 * definition is identical to any previous definition that we
7390 		 * encountered.
7391 		 */
7392 		ndx = id - DIF_VAR_OTHER_UBASE;
7393 
7394 		switch (v->dtdv_scope) {
7395 		case DIFV_SCOPE_GLOBAL:
7396 			if (ndx < vstate->dtvs_nglobals) {
7397 				dtrace_statvar_t *svar;
7398 
7399 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
7400 					existing = &svar->dtsv_var;
7401 			}
7402 
7403 			break;
7404 
7405 		case DIFV_SCOPE_THREAD:
7406 			if (ndx < vstate->dtvs_ntlocals)
7407 				existing = &vstate->dtvs_tlocals[ndx];
7408 			break;
7409 
7410 		case DIFV_SCOPE_LOCAL:
7411 			if (ndx < vstate->dtvs_nlocals) {
7412 				dtrace_statvar_t *svar;
7413 
7414 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
7415 					existing = &svar->dtsv_var;
7416 			}
7417 
7418 			break;
7419 		}
7420 
7421 		vt = &v->dtdv_type;
7422 
7423 		if (vt->dtdt_flags & DIF_TF_BYREF) {
7424 			if (vt->dtdt_size == 0) {
7425 				err += efunc(i, "zero-sized variable\n");
7426 				break;
7427 			}
7428 
7429 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
7430 			    vt->dtdt_size > dtrace_global_maxsize) {
7431 				err += efunc(i, "oversized by-ref global\n");
7432 				break;
7433 			}
7434 		}
7435 
7436 		if (existing == NULL || existing->dtdv_id == 0)
7437 			continue;
7438 
7439 		ASSERT(existing->dtdv_id == v->dtdv_id);
7440 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
7441 
7442 		if (existing->dtdv_kind != v->dtdv_kind)
7443 			err += efunc(i, "%d changed variable kind\n", id);
7444 
7445 		et = &existing->dtdv_type;
7446 
7447 		if (vt->dtdt_flags != et->dtdt_flags) {
7448 			err += efunc(i, "%d changed variable type flags\n", id);
7449 			break;
7450 		}
7451 
7452 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
7453 			err += efunc(i, "%d changed variable type size\n", id);
7454 			break;
7455 		}
7456 	}
7457 
7458 	return (err);
7459 }
7460 
7461 /*
7462  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
7463  * are much more constrained than normal DIFOs.  Specifically, they may
7464  * not:
7465  *
7466  * 1. Make calls to subroutines other than copyin(), copyinstr() or
7467  *    miscellaneous string routines
7468  * 2. Access DTrace variables other than the args[] array, and the
7469  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
7470  * 3. Have thread-local variables.
7471  * 4. Have dynamic variables.
7472  */
7473 static int
7474 dtrace_difo_validate_helper(dtrace_difo_t *dp)
7475 {
7476 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
7477 	int err = 0;
7478 	uint_t pc;
7479 
7480 	for (pc = 0; pc < dp->dtdo_len; pc++) {
7481 		dif_instr_t instr = dp->dtdo_buf[pc];
7482 
7483 		uint_t v = DIF_INSTR_VAR(instr);
7484 		uint_t subr = DIF_INSTR_SUBR(instr);
7485 		uint_t op = DIF_INSTR_OP(instr);
7486 
7487 		switch (op) {
7488 		case DIF_OP_OR:
7489 		case DIF_OP_XOR:
7490 		case DIF_OP_AND:
7491 		case DIF_OP_SLL:
7492 		case DIF_OP_SRL:
7493 		case DIF_OP_SRA:
7494 		case DIF_OP_SUB:
7495 		case DIF_OP_ADD:
7496 		case DIF_OP_MUL:
7497 		case DIF_OP_SDIV:
7498 		case DIF_OP_UDIV:
7499 		case DIF_OP_SREM:
7500 		case DIF_OP_UREM:
7501 		case DIF_OP_COPYS:
7502 		case DIF_OP_NOT:
7503 		case DIF_OP_MOV:
7504 		case DIF_OP_RLDSB:
7505 		case DIF_OP_RLDSH:
7506 		case DIF_OP_RLDSW:
7507 		case DIF_OP_RLDUB:
7508 		case DIF_OP_RLDUH:
7509 		case DIF_OP_RLDUW:
7510 		case DIF_OP_RLDX:
7511 		case DIF_OP_ULDSB:
7512 		case DIF_OP_ULDSH:
7513 		case DIF_OP_ULDSW:
7514 		case DIF_OP_ULDUB:
7515 		case DIF_OP_ULDUH:
7516 		case DIF_OP_ULDUW:
7517 		case DIF_OP_ULDX:
7518 		case DIF_OP_STB:
7519 		case DIF_OP_STH:
7520 		case DIF_OP_STW:
7521 		case DIF_OP_STX:
7522 		case DIF_OP_ALLOCS:
7523 		case DIF_OP_CMP:
7524 		case DIF_OP_SCMP:
7525 		case DIF_OP_TST:
7526 		case DIF_OP_BA:
7527 		case DIF_OP_BE:
7528 		case DIF_OP_BNE:
7529 		case DIF_OP_BG:
7530 		case DIF_OP_BGU:
7531 		case DIF_OP_BGE:
7532 		case DIF_OP_BGEU:
7533 		case DIF_OP_BL:
7534 		case DIF_OP_BLU:
7535 		case DIF_OP_BLE:
7536 		case DIF_OP_BLEU:
7537 		case DIF_OP_RET:
7538 		case DIF_OP_NOP:
7539 		case DIF_OP_POPTS:
7540 		case DIF_OP_FLUSHTS:
7541 		case DIF_OP_SETX:
7542 		case DIF_OP_SETS:
7543 		case DIF_OP_LDGA:
7544 		case DIF_OP_LDLS:
7545 		case DIF_OP_STGS:
7546 		case DIF_OP_STLS:
7547 		case DIF_OP_PUSHTR:
7548 		case DIF_OP_PUSHTV:
7549 			break;
7550 
7551 		case DIF_OP_LDGS:
7552 			if (v >= DIF_VAR_OTHER_UBASE)
7553 				break;
7554 
7555 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
7556 				break;
7557 
7558 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
7559 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
7560 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
7561 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
7562 				break;
7563 
7564 			err += efunc(pc, "illegal variable %u\n", v);
7565 			break;
7566 
7567 		case DIF_OP_LDTA:
7568 		case DIF_OP_LDTS:
7569 		case DIF_OP_LDGAA:
7570 		case DIF_OP_LDTAA:
7571 			err += efunc(pc, "illegal dynamic variable load\n");
7572 			break;
7573 
7574 		case DIF_OP_STTS:
7575 		case DIF_OP_STGAA:
7576 		case DIF_OP_STTAA:
7577 			err += efunc(pc, "illegal dynamic variable store\n");
7578 			break;
7579 
7580 		case DIF_OP_CALL:
7581 			if (subr == DIF_SUBR_ALLOCA ||
7582 			    subr == DIF_SUBR_BCOPY ||
7583 			    subr == DIF_SUBR_COPYIN ||
7584 			    subr == DIF_SUBR_COPYINTO ||
7585 			    subr == DIF_SUBR_COPYINSTR ||
7586 			    subr == DIF_SUBR_INDEX ||
7587 			    subr == DIF_SUBR_LLTOSTR ||
7588 			    subr == DIF_SUBR_RINDEX ||
7589 			    subr == DIF_SUBR_STRCHR ||
7590 			    subr == DIF_SUBR_STRJOIN ||
7591 			    subr == DIF_SUBR_STRRCHR ||
7592 			    subr == DIF_SUBR_STRSTR)
7593 				break;
7594 
7595 			err += efunc(pc, "invalid subr %u\n", subr);
7596 			break;
7597 
7598 		default:
7599 			err += efunc(pc, "invalid opcode %u\n",
7600 			    DIF_INSTR_OP(instr));
7601 		}
7602 	}
7603 
7604 	return (err);
7605 }
7606 
7607 /*
7608  * Returns 1 if the expression in the DIF object can be cached on a per-thread
7609  * basis; 0 if not.
7610  */
7611 static int
7612 dtrace_difo_cacheable(dtrace_difo_t *dp)
7613 {
7614 	int i;
7615 
7616 	if (dp == NULL)
7617 		return (0);
7618 
7619 	for (i = 0; i < dp->dtdo_varlen; i++) {
7620 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7621 
7622 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
7623 			continue;
7624 
7625 		switch (v->dtdv_id) {
7626 		case DIF_VAR_CURTHREAD:
7627 		case DIF_VAR_PID:
7628 		case DIF_VAR_TID:
7629 		case DIF_VAR_EXECNAME:
7630 		case DIF_VAR_ZONENAME:
7631 			break;
7632 
7633 		default:
7634 			return (0);
7635 		}
7636 	}
7637 
7638 	/*
7639 	 * This DIF object may be cacheable.  Now we need to look for any
7640 	 * array loading instructions, any memory loading instructions, or
7641 	 * any stores to thread-local variables.
7642 	 */
7643 	for (i = 0; i < dp->dtdo_len; i++) {
7644 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
7645 
7646 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
7647 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
7648 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
7649 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
7650 			return (0);
7651 	}
7652 
7653 	return (1);
7654 }
7655 
7656 static void
7657 dtrace_difo_hold(dtrace_difo_t *dp)
7658 {
7659 	int i;
7660 
7661 	ASSERT(MUTEX_HELD(&dtrace_lock));
7662 
7663 	dp->dtdo_refcnt++;
7664 	ASSERT(dp->dtdo_refcnt != 0);
7665 
7666 	/*
7667 	 * We need to check this DIF object for references to the variable
7668 	 * DIF_VAR_VTIMESTAMP.
7669 	 */
7670 	for (i = 0; i < dp->dtdo_varlen; i++) {
7671 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7672 
7673 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
7674 			continue;
7675 
7676 		if (dtrace_vtime_references++ == 0)
7677 			dtrace_vtime_enable();
7678 	}
7679 }
7680 
7681 /*
7682  * This routine calculates the dynamic variable chunksize for a given DIF
7683  * object.  The calculation is not fool-proof, and can probably be tricked by
7684  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
7685  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
7686  * if a dynamic variable size exceeds the chunksize.
7687  */
7688 static void
7689 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7690 {
7691 	uint64_t sval;
7692 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
7693 	const dif_instr_t *text = dp->dtdo_buf;
7694 	uint_t pc, srd = 0;
7695 	uint_t ttop = 0;
7696 	size_t size, ksize;
7697 	uint_t id, i;
7698 
7699 	for (pc = 0; pc < dp->dtdo_len; pc++) {
7700 		dif_instr_t instr = text[pc];
7701 		uint_t op = DIF_INSTR_OP(instr);
7702 		uint_t rd = DIF_INSTR_RD(instr);
7703 		uint_t r1 = DIF_INSTR_R1(instr);
7704 		uint_t nkeys = 0;
7705 		uchar_t scope;
7706 
7707 		dtrace_key_t *key = tupregs;
7708 
7709 		switch (op) {
7710 		case DIF_OP_SETX:
7711 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
7712 			srd = rd;
7713 			continue;
7714 
7715 		case DIF_OP_STTS:
7716 			key = &tupregs[DIF_DTR_NREGS];
7717 			key[0].dttk_size = 0;
7718 			key[1].dttk_size = 0;
7719 			nkeys = 2;
7720 			scope = DIFV_SCOPE_THREAD;
7721 			break;
7722 
7723 		case DIF_OP_STGAA:
7724 		case DIF_OP_STTAA:
7725 			nkeys = ttop;
7726 
7727 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
7728 				key[nkeys++].dttk_size = 0;
7729 
7730 			key[nkeys++].dttk_size = 0;
7731 
7732 			if (op == DIF_OP_STTAA) {
7733 				scope = DIFV_SCOPE_THREAD;
7734 			} else {
7735 				scope = DIFV_SCOPE_GLOBAL;
7736 			}
7737 
7738 			break;
7739 
7740 		case DIF_OP_PUSHTR:
7741 			if (ttop == DIF_DTR_NREGS)
7742 				return;
7743 
7744 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
7745 				/*
7746 				 * If the register for the size of the "pushtr"
7747 				 * is %r0 (or the value is 0) and the type is
7748 				 * a string, we'll use the system-wide default
7749 				 * string size.
7750 				 */
7751 				tupregs[ttop++].dttk_size =
7752 				    dtrace_strsize_default;
7753 			} else {
7754 				if (srd == 0)
7755 					return;
7756 
7757 				tupregs[ttop++].dttk_size = sval;
7758 			}
7759 
7760 			break;
7761 
7762 		case DIF_OP_PUSHTV:
7763 			if (ttop == DIF_DTR_NREGS)
7764 				return;
7765 
7766 			tupregs[ttop++].dttk_size = 0;
7767 			break;
7768 
7769 		case DIF_OP_FLUSHTS:
7770 			ttop = 0;
7771 			break;
7772 
7773 		case DIF_OP_POPTS:
7774 			if (ttop != 0)
7775 				ttop--;
7776 			break;
7777 		}
7778 
7779 		sval = 0;
7780 		srd = 0;
7781 
7782 		if (nkeys == 0)
7783 			continue;
7784 
7785 		/*
7786 		 * We have a dynamic variable allocation; calculate its size.
7787 		 */
7788 		for (ksize = 0, i = 0; i < nkeys; i++)
7789 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
7790 
7791 		size = sizeof (dtrace_dynvar_t);
7792 		size += sizeof (dtrace_key_t) * (nkeys - 1);
7793 		size += ksize;
7794 
7795 		/*
7796 		 * Now we need to determine the size of the stored data.
7797 		 */
7798 		id = DIF_INSTR_VAR(instr);
7799 
7800 		for (i = 0; i < dp->dtdo_varlen; i++) {
7801 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
7802 
7803 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
7804 				size += v->dtdv_type.dtdt_size;
7805 				break;
7806 			}
7807 		}
7808 
7809 		if (i == dp->dtdo_varlen)
7810 			return;
7811 
7812 		/*
7813 		 * We have the size.  If this is larger than the chunk size
7814 		 * for our dynamic variable state, reset the chunk size.
7815 		 */
7816 		size = P2ROUNDUP(size, sizeof (uint64_t));
7817 
7818 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
7819 			vstate->dtvs_dynvars.dtds_chunksize = size;
7820 	}
7821 }
7822 
7823 static void
7824 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7825 {
7826 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
7827 	uint_t id;
7828 
7829 	ASSERT(MUTEX_HELD(&dtrace_lock));
7830 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
7831 
7832 	for (i = 0; i < dp->dtdo_varlen; i++) {
7833 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7834 		dtrace_statvar_t *svar, ***svarp;
7835 		size_t dsize = 0;
7836 		uint8_t scope = v->dtdv_scope;
7837 		int *np;
7838 
7839 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
7840 			continue;
7841 
7842 		id -= DIF_VAR_OTHER_UBASE;
7843 
7844 		switch (scope) {
7845 		case DIFV_SCOPE_THREAD:
7846 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
7847 				dtrace_difv_t *tlocals;
7848 
7849 				if ((ntlocals = (otlocals << 1)) == 0)
7850 					ntlocals = 1;
7851 
7852 				osz = otlocals * sizeof (dtrace_difv_t);
7853 				nsz = ntlocals * sizeof (dtrace_difv_t);
7854 
7855 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
7856 
7857 				if (osz != 0) {
7858 					bcopy(vstate->dtvs_tlocals,
7859 					    tlocals, osz);
7860 					kmem_free(vstate->dtvs_tlocals, osz);
7861 				}
7862 
7863 				vstate->dtvs_tlocals = tlocals;
7864 				vstate->dtvs_ntlocals = ntlocals;
7865 			}
7866 
7867 			vstate->dtvs_tlocals[id] = *v;
7868 			continue;
7869 
7870 		case DIFV_SCOPE_LOCAL:
7871 			np = &vstate->dtvs_nlocals;
7872 			svarp = &vstate->dtvs_locals;
7873 
7874 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
7875 				dsize = NCPU * (v->dtdv_type.dtdt_size +
7876 				    sizeof (uint64_t));
7877 			else
7878 				dsize = NCPU * sizeof (uint64_t);
7879 
7880 			break;
7881 
7882 		case DIFV_SCOPE_GLOBAL:
7883 			np = &vstate->dtvs_nglobals;
7884 			svarp = &vstate->dtvs_globals;
7885 
7886 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
7887 				dsize = v->dtdv_type.dtdt_size +
7888 				    sizeof (uint64_t);
7889 
7890 			break;
7891 
7892 		default:
7893 			ASSERT(0);
7894 		}
7895 
7896 		while (id >= (oldsvars = *np)) {
7897 			dtrace_statvar_t **statics;
7898 			int newsvars, oldsize, newsize;
7899 
7900 			if ((newsvars = (oldsvars << 1)) == 0)
7901 				newsvars = 1;
7902 
7903 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
7904 			newsize = newsvars * sizeof (dtrace_statvar_t *);
7905 
7906 			statics = kmem_zalloc(newsize, KM_SLEEP);
7907 
7908 			if (oldsize != 0) {
7909 				bcopy(*svarp, statics, oldsize);
7910 				kmem_free(*svarp, oldsize);
7911 			}
7912 
7913 			*svarp = statics;
7914 			*np = newsvars;
7915 		}
7916 
7917 		if ((svar = (*svarp)[id]) == NULL) {
7918 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
7919 			svar->dtsv_var = *v;
7920 
7921 			if ((svar->dtsv_size = dsize) != 0) {
7922 				svar->dtsv_data = (uint64_t)(uintptr_t)
7923 				    kmem_zalloc(dsize, KM_SLEEP);
7924 			}
7925 
7926 			(*svarp)[id] = svar;
7927 		}
7928 
7929 		svar->dtsv_refcnt++;
7930 	}
7931 
7932 	dtrace_difo_chunksize(dp, vstate);
7933 	dtrace_difo_hold(dp);
7934 }
7935 
7936 static dtrace_difo_t *
7937 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7938 {
7939 	dtrace_difo_t *new;
7940 	size_t sz;
7941 
7942 	ASSERT(dp->dtdo_buf != NULL);
7943 	ASSERT(dp->dtdo_refcnt != 0);
7944 
7945 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
7946 
7947 	ASSERT(dp->dtdo_buf != NULL);
7948 	sz = dp->dtdo_len * sizeof (dif_instr_t);
7949 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
7950 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
7951 	new->dtdo_len = dp->dtdo_len;
7952 
7953 	if (dp->dtdo_strtab != NULL) {
7954 		ASSERT(dp->dtdo_strlen != 0);
7955 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
7956 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
7957 		new->dtdo_strlen = dp->dtdo_strlen;
7958 	}
7959 
7960 	if (dp->dtdo_inttab != NULL) {
7961 		ASSERT(dp->dtdo_intlen != 0);
7962 		sz = dp->dtdo_intlen * sizeof (uint64_t);
7963 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
7964 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
7965 		new->dtdo_intlen = dp->dtdo_intlen;
7966 	}
7967 
7968 	if (dp->dtdo_vartab != NULL) {
7969 		ASSERT(dp->dtdo_varlen != 0);
7970 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
7971 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
7972 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
7973 		new->dtdo_varlen = dp->dtdo_varlen;
7974 	}
7975 
7976 	dtrace_difo_init(new, vstate);
7977 	return (new);
7978 }
7979 
7980 static void
7981 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
7982 {
7983 	int i;
7984 
7985 	ASSERT(dp->dtdo_refcnt == 0);
7986 
7987 	for (i = 0; i < dp->dtdo_varlen; i++) {
7988 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
7989 		dtrace_statvar_t *svar, **svarp;
7990 		uint_t id;
7991 		uint8_t scope = v->dtdv_scope;
7992 		int *np;
7993 
7994 		switch (scope) {
7995 		case DIFV_SCOPE_THREAD:
7996 			continue;
7997 
7998 		case DIFV_SCOPE_LOCAL:
7999 			np = &vstate->dtvs_nlocals;
8000 			svarp = vstate->dtvs_locals;
8001 			break;
8002 
8003 		case DIFV_SCOPE_GLOBAL:
8004 			np = &vstate->dtvs_nglobals;
8005 			svarp = vstate->dtvs_globals;
8006 			break;
8007 
8008 		default:
8009 			ASSERT(0);
8010 		}
8011 
8012 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8013 			continue;
8014 
8015 		id -= DIF_VAR_OTHER_UBASE;
8016 		ASSERT(id < *np);
8017 
8018 		svar = svarp[id];
8019 		ASSERT(svar != NULL);
8020 		ASSERT(svar->dtsv_refcnt > 0);
8021 
8022 		if (--svar->dtsv_refcnt > 0)
8023 			continue;
8024 
8025 		if (svar->dtsv_size != 0) {
8026 			ASSERT(svar->dtsv_data != NULL);
8027 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
8028 			    svar->dtsv_size);
8029 		}
8030 
8031 		kmem_free(svar, sizeof (dtrace_statvar_t));
8032 		svarp[id] = NULL;
8033 	}
8034 
8035 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
8036 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
8037 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
8038 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
8039 
8040 	kmem_free(dp, sizeof (dtrace_difo_t));
8041 }
8042 
8043 static void
8044 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8045 {
8046 	int i;
8047 
8048 	ASSERT(MUTEX_HELD(&dtrace_lock));
8049 	ASSERT(dp->dtdo_refcnt != 0);
8050 
8051 	for (i = 0; i < dp->dtdo_varlen; i++) {
8052 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8053 
8054 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8055 			continue;
8056 
8057 		ASSERT(dtrace_vtime_references > 0);
8058 		if (--dtrace_vtime_references == 0)
8059 			dtrace_vtime_disable();
8060 	}
8061 
8062 	if (--dp->dtdo_refcnt == 0)
8063 		dtrace_difo_destroy(dp, vstate);
8064 }
8065 
8066 /*
8067  * DTrace Format Functions
8068  */
8069 static uint16_t
8070 dtrace_format_add(dtrace_state_t *state, char *str)
8071 {
8072 	char *fmt, **new;
8073 	uint16_t ndx, len = strlen(str) + 1;
8074 
8075 	fmt = kmem_zalloc(len, KM_SLEEP);
8076 	bcopy(str, fmt, len);
8077 
8078 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
8079 		if (state->dts_formats[ndx] == NULL) {
8080 			state->dts_formats[ndx] = fmt;
8081 			return (ndx + 1);
8082 		}
8083 	}
8084 
8085 	if (state->dts_nformats == USHRT_MAX) {
8086 		/*
8087 		 * This is only likely if a denial-of-service attack is being
8088 		 * attempted.  As such, it's okay to fail silently here.
8089 		 */
8090 		kmem_free(fmt, len);
8091 		return (0);
8092 	}
8093 
8094 	/*
8095 	 * For simplicity, we always resize the formats array to be exactly the
8096 	 * number of formats.
8097 	 */
8098 	ndx = state->dts_nformats++;
8099 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
8100 
8101 	if (state->dts_formats != NULL) {
8102 		ASSERT(ndx != 0);
8103 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
8104 		kmem_free(state->dts_formats, ndx * sizeof (char *));
8105 	}
8106 
8107 	state->dts_formats = new;
8108 	state->dts_formats[ndx] = fmt;
8109 
8110 	return (ndx + 1);
8111 }
8112 
8113 static void
8114 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
8115 {
8116 	char *fmt;
8117 
8118 	ASSERT(state->dts_formats != NULL);
8119 	ASSERT(format <= state->dts_nformats);
8120 	ASSERT(state->dts_formats[format - 1] != NULL);
8121 
8122 	fmt = state->dts_formats[format - 1];
8123 	kmem_free(fmt, strlen(fmt) + 1);
8124 	state->dts_formats[format - 1] = NULL;
8125 }
8126 
8127 static void
8128 dtrace_format_destroy(dtrace_state_t *state)
8129 {
8130 	int i;
8131 
8132 	if (state->dts_nformats == 0) {
8133 		ASSERT(state->dts_formats == NULL);
8134 		return;
8135 	}
8136 
8137 	ASSERT(state->dts_formats != NULL);
8138 
8139 	for (i = 0; i < state->dts_nformats; i++) {
8140 		char *fmt = state->dts_formats[i];
8141 
8142 		if (fmt == NULL)
8143 			continue;
8144 
8145 		kmem_free(fmt, strlen(fmt) + 1);
8146 	}
8147 
8148 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
8149 	state->dts_nformats = 0;
8150 	state->dts_formats = NULL;
8151 }
8152 
8153 /*
8154  * DTrace Predicate Functions
8155  */
8156 static dtrace_predicate_t *
8157 dtrace_predicate_create(dtrace_difo_t *dp)
8158 {
8159 	dtrace_predicate_t *pred;
8160 
8161 	ASSERT(MUTEX_HELD(&dtrace_lock));
8162 	ASSERT(dp->dtdo_refcnt != 0);
8163 
8164 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
8165 	pred->dtp_difo = dp;
8166 	pred->dtp_refcnt = 1;
8167 
8168 	if (!dtrace_difo_cacheable(dp))
8169 		return (pred);
8170 
8171 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
8172 		/*
8173 		 * This is only theoretically possible -- we have had 2^32
8174 		 * cacheable predicates on this machine.  We cannot allow any
8175 		 * more predicates to become cacheable:  as unlikely as it is,
8176 		 * there may be a thread caching a (now stale) predicate cache
8177 		 * ID. (N.B.: the temptation is being successfully resisted to
8178 		 * have this cmn_err() "Holy shit -- we executed this code!")
8179 		 */
8180 		return (pred);
8181 	}
8182 
8183 	pred->dtp_cacheid = dtrace_predcache_id++;
8184 
8185 	return (pred);
8186 }
8187 
8188 static void
8189 dtrace_predicate_hold(dtrace_predicate_t *pred)
8190 {
8191 	ASSERT(MUTEX_HELD(&dtrace_lock));
8192 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
8193 	ASSERT(pred->dtp_refcnt > 0);
8194 
8195 	pred->dtp_refcnt++;
8196 }
8197 
8198 static void
8199 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
8200 {
8201 	dtrace_difo_t *dp = pred->dtp_difo;
8202 
8203 	ASSERT(MUTEX_HELD(&dtrace_lock));
8204 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
8205 	ASSERT(pred->dtp_refcnt > 0);
8206 
8207 	if (--pred->dtp_refcnt == 0) {
8208 		dtrace_difo_release(pred->dtp_difo, vstate);
8209 		kmem_free(pred, sizeof (dtrace_predicate_t));
8210 	}
8211 }
8212 
8213 /*
8214  * DTrace Action Description Functions
8215  */
8216 static dtrace_actdesc_t *
8217 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
8218     uint64_t uarg, uint64_t arg)
8219 {
8220 	dtrace_actdesc_t *act;
8221 
8222 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
8223 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
8224 
8225 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
8226 	act->dtad_kind = kind;
8227 	act->dtad_ntuple = ntuple;
8228 	act->dtad_uarg = uarg;
8229 	act->dtad_arg = arg;
8230 	act->dtad_refcnt = 1;
8231 
8232 	return (act);
8233 }
8234 
8235 static void
8236 dtrace_actdesc_hold(dtrace_actdesc_t *act)
8237 {
8238 	ASSERT(act->dtad_refcnt >= 1);
8239 	act->dtad_refcnt++;
8240 }
8241 
8242 static void
8243 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
8244 {
8245 	dtrace_actkind_t kind = act->dtad_kind;
8246 	dtrace_difo_t *dp;
8247 
8248 	ASSERT(act->dtad_refcnt >= 1);
8249 
8250 	if (--act->dtad_refcnt != 0)
8251 		return;
8252 
8253 	if ((dp = act->dtad_difo) != NULL)
8254 		dtrace_difo_release(dp, vstate);
8255 
8256 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
8257 		char *str = (char *)(uintptr_t)act->dtad_arg;
8258 
8259 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
8260 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
8261 
8262 		if (str != NULL)
8263 			kmem_free(str, strlen(str) + 1);
8264 	}
8265 
8266 	kmem_free(act, sizeof (dtrace_actdesc_t));
8267 }
8268 
8269 /*
8270  * DTrace ECB Functions
8271  */
8272 static dtrace_ecb_t *
8273 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
8274 {
8275 	dtrace_ecb_t *ecb;
8276 	dtrace_epid_t epid;
8277 
8278 	ASSERT(MUTEX_HELD(&dtrace_lock));
8279 
8280 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
8281 	ecb->dte_predicate = NULL;
8282 	ecb->dte_probe = probe;
8283 
8284 	/*
8285 	 * The default size is the size of the default action: recording
8286 	 * the epid.
8287 	 */
8288 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
8289 	ecb->dte_alignment = sizeof (dtrace_epid_t);
8290 
8291 	epid = state->dts_epid++;
8292 
8293 	if (epid - 1 >= state->dts_necbs) {
8294 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
8295 		int necbs = state->dts_necbs << 1;
8296 
8297 		ASSERT(epid == state->dts_necbs + 1);
8298 
8299 		if (necbs == 0) {
8300 			ASSERT(oecbs == NULL);
8301 			necbs = 1;
8302 		}
8303 
8304 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
8305 
8306 		if (oecbs != NULL)
8307 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
8308 
8309 		dtrace_membar_producer();
8310 		state->dts_ecbs = ecbs;
8311 
8312 		if (oecbs != NULL) {
8313 			/*
8314 			 * If this state is active, we must dtrace_sync()
8315 			 * before we can free the old dts_ecbs array:  we're
8316 			 * coming in hot, and there may be active ring
8317 			 * buffer processing (which indexes into the dts_ecbs
8318 			 * array) on another CPU.
8319 			 */
8320 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
8321 				dtrace_sync();
8322 
8323 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
8324 		}
8325 
8326 		dtrace_membar_producer();
8327 		state->dts_necbs = necbs;
8328 	}
8329 
8330 	ecb->dte_state = state;
8331 
8332 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
8333 	dtrace_membar_producer();
8334 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
8335 
8336 	return (ecb);
8337 }
8338 
8339 static void
8340 dtrace_ecb_enable(dtrace_ecb_t *ecb)
8341 {
8342 	dtrace_probe_t *probe = ecb->dte_probe;
8343 
8344 	ASSERT(MUTEX_HELD(&cpu_lock));
8345 	ASSERT(MUTEX_HELD(&dtrace_lock));
8346 	ASSERT(ecb->dte_next == NULL);
8347 
8348 	if (probe == NULL) {
8349 		/*
8350 		 * This is the NULL probe -- there's nothing to do.
8351 		 */
8352 		return;
8353 	}
8354 
8355 	if (probe->dtpr_ecb == NULL) {
8356 		dtrace_provider_t *prov = probe->dtpr_provider;
8357 
8358 		/*
8359 		 * We're the first ECB on this probe.
8360 		 */
8361 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
8362 
8363 		if (ecb->dte_predicate != NULL)
8364 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
8365 
8366 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
8367 		    probe->dtpr_id, probe->dtpr_arg);
8368 	} else {
8369 		/*
8370 		 * This probe is already active.  Swing the last pointer to
8371 		 * point to the new ECB, and issue a dtrace_sync() to assure
8372 		 * that all CPUs have seen the change.
8373 		 */
8374 		ASSERT(probe->dtpr_ecb_last != NULL);
8375 		probe->dtpr_ecb_last->dte_next = ecb;
8376 		probe->dtpr_ecb_last = ecb;
8377 		probe->dtpr_predcache = 0;
8378 
8379 		dtrace_sync();
8380 	}
8381 }
8382 
8383 static void
8384 dtrace_ecb_resize(dtrace_ecb_t *ecb)
8385 {
8386 	uint32_t maxalign = sizeof (dtrace_epid_t);
8387 	uint32_t align = sizeof (uint8_t), offs, diff;
8388 	dtrace_action_t *act;
8389 	int wastuple = 0;
8390 	uint32_t aggbase = UINT32_MAX;
8391 	dtrace_state_t *state = ecb->dte_state;
8392 
8393 	/*
8394 	 * If we record anything, we always record the epid.  (And we always
8395 	 * record it first.)
8396 	 */
8397 	offs = sizeof (dtrace_epid_t);
8398 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
8399 
8400 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
8401 		dtrace_recdesc_t *rec = &act->dta_rec;
8402 
8403 		if ((align = rec->dtrd_alignment) > maxalign)
8404 			maxalign = align;
8405 
8406 		if (!wastuple && act->dta_intuple) {
8407 			/*
8408 			 * This is the first record in a tuple.  Align the
8409 			 * offset to be at offset 4 in an 8-byte aligned
8410 			 * block.
8411 			 */
8412 			diff = offs + sizeof (dtrace_aggid_t);
8413 
8414 			if (diff = (diff & (sizeof (uint64_t) - 1)))
8415 				offs += sizeof (uint64_t) - diff;
8416 
8417 			aggbase = offs - sizeof (dtrace_aggid_t);
8418 			ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
8419 		}
8420 
8421 		/*LINTED*/
8422 		if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
8423 			/*
8424 			 * The current offset is not properly aligned; align it.
8425 			 */
8426 			offs += align - diff;
8427 		}
8428 
8429 		rec->dtrd_offset = offs;
8430 
8431 		if (offs + rec->dtrd_size > ecb->dte_needed) {
8432 			ecb->dte_needed = offs + rec->dtrd_size;
8433 
8434 			if (ecb->dte_needed > state->dts_needed)
8435 				state->dts_needed = ecb->dte_needed;
8436 		}
8437 
8438 		if (DTRACEACT_ISAGG(act->dta_kind)) {
8439 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
8440 			dtrace_action_t *first = agg->dtag_first, *prev;
8441 
8442 			ASSERT(rec->dtrd_size != 0 && first != NULL);
8443 			ASSERT(wastuple);
8444 			ASSERT(aggbase != UINT32_MAX);
8445 
8446 			agg->dtag_base = aggbase;
8447 
8448 			while ((prev = first->dta_prev) != NULL &&
8449 			    DTRACEACT_ISAGG(prev->dta_kind)) {
8450 				agg = (dtrace_aggregation_t *)prev;
8451 				first = agg->dtag_first;
8452 			}
8453 
8454 			if (prev != NULL) {
8455 				offs = prev->dta_rec.dtrd_offset +
8456 				    prev->dta_rec.dtrd_size;
8457 			} else {
8458 				offs = sizeof (dtrace_epid_t);
8459 			}
8460 			wastuple = 0;
8461 		} else {
8462 			if (!act->dta_intuple)
8463 				ecb->dte_size = offs + rec->dtrd_size;
8464 
8465 			offs += rec->dtrd_size;
8466 		}
8467 
8468 		wastuple = act->dta_intuple;
8469 	}
8470 
8471 	if ((act = ecb->dte_action) != NULL &&
8472 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
8473 	    ecb->dte_size == sizeof (dtrace_epid_t)) {
8474 		/*
8475 		 * If the size is still sizeof (dtrace_epid_t), then all
8476 		 * actions store no data; set the size to 0.
8477 		 */
8478 		ecb->dte_alignment = maxalign;
8479 		ecb->dte_size = 0;
8480 
8481 		/*
8482 		 * If the needed space is still sizeof (dtrace_epid_t), then
8483 		 * all actions need no additional space; set the needed
8484 		 * size to 0.
8485 		 */
8486 		if (ecb->dte_needed == sizeof (dtrace_epid_t))
8487 			ecb->dte_needed = 0;
8488 
8489 		return;
8490 	}
8491 
8492 	/*
8493 	 * Set our alignment, and make sure that the dte_size and dte_needed
8494 	 * are aligned to the size of an EPID.
8495 	 */
8496 	ecb->dte_alignment = maxalign;
8497 	ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
8498 	    ~(sizeof (dtrace_epid_t) - 1);
8499 	ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
8500 	    ~(sizeof (dtrace_epid_t) - 1);
8501 	ASSERT(ecb->dte_size <= ecb->dte_needed);
8502 }
8503 
8504 static dtrace_action_t *
8505 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
8506 {
8507 	dtrace_aggregation_t *agg;
8508 	size_t size = sizeof (uint64_t);
8509 	int ntuple = desc->dtad_ntuple;
8510 	dtrace_action_t *act;
8511 	dtrace_recdesc_t *frec;
8512 	dtrace_aggid_t aggid;
8513 	dtrace_state_t *state = ecb->dte_state;
8514 
8515 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
8516 	agg->dtag_ecb = ecb;
8517 
8518 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
8519 
8520 	switch (desc->dtad_kind) {
8521 	case DTRACEAGG_MIN:
8522 		agg->dtag_initial = UINT64_MAX;
8523 		agg->dtag_aggregate = dtrace_aggregate_min;
8524 		break;
8525 
8526 	case DTRACEAGG_MAX:
8527 		agg->dtag_aggregate = dtrace_aggregate_max;
8528 		break;
8529 
8530 	case DTRACEAGG_COUNT:
8531 		agg->dtag_aggregate = dtrace_aggregate_count;
8532 		break;
8533 
8534 	case DTRACEAGG_QUANTIZE:
8535 		agg->dtag_aggregate = dtrace_aggregate_quantize;
8536 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
8537 		    sizeof (uint64_t);
8538 		break;
8539 
8540 	case DTRACEAGG_LQUANTIZE: {
8541 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
8542 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
8543 
8544 		agg->dtag_initial = desc->dtad_arg;
8545 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
8546 
8547 		if (step == 0 || levels == 0)
8548 			goto err;
8549 
8550 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
8551 		break;
8552 	}
8553 
8554 	case DTRACEAGG_AVG:
8555 		agg->dtag_aggregate = dtrace_aggregate_avg;
8556 		size = sizeof (uint64_t) * 2;
8557 		break;
8558 
8559 	case DTRACEAGG_SUM:
8560 		agg->dtag_aggregate = dtrace_aggregate_sum;
8561 		break;
8562 
8563 	default:
8564 		goto err;
8565 	}
8566 
8567 	agg->dtag_action.dta_rec.dtrd_size = size;
8568 
8569 	if (ntuple == 0)
8570 		goto err;
8571 
8572 	/*
8573 	 * We must make sure that we have enough actions for the n-tuple.
8574 	 */
8575 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
8576 		if (DTRACEACT_ISAGG(act->dta_kind))
8577 			break;
8578 
8579 		if (--ntuple == 0) {
8580 			/*
8581 			 * This is the action with which our n-tuple begins.
8582 			 */
8583 			agg->dtag_first = act;
8584 			goto success;
8585 		}
8586 	}
8587 
8588 	/*
8589 	 * This n-tuple is short by ntuple elements.  Return failure.
8590 	 */
8591 	ASSERT(ntuple != 0);
8592 err:
8593 	kmem_free(agg, sizeof (dtrace_aggregation_t));
8594 	return (NULL);
8595 
8596 success:
8597 	/*
8598 	 * If the last action in the tuple has a size of zero, it's actually
8599 	 * an expression argument for the aggregating action.
8600 	 */
8601 	ASSERT(ecb->dte_action_last != NULL);
8602 	act = ecb->dte_action_last;
8603 
8604 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
8605 		ASSERT(act->dta_difo != NULL);
8606 
8607 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
8608 			agg->dtag_hasarg = 1;
8609 	}
8610 
8611 	/*
8612 	 * We need to allocate an id for this aggregation.
8613 	 */
8614 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
8615 	    VM_BESTFIT | VM_SLEEP);
8616 
8617 	if (aggid - 1 >= state->dts_naggregations) {
8618 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
8619 		dtrace_aggregation_t **aggs;
8620 		int naggs = state->dts_naggregations << 1;
8621 		int onaggs = state->dts_naggregations;
8622 
8623 		ASSERT(aggid == state->dts_naggregations + 1);
8624 
8625 		if (naggs == 0) {
8626 			ASSERT(oaggs == NULL);
8627 			naggs = 1;
8628 		}
8629 
8630 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
8631 
8632 		if (oaggs != NULL) {
8633 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
8634 			kmem_free(oaggs, onaggs * sizeof (*aggs));
8635 		}
8636 
8637 		state->dts_aggregations = aggs;
8638 		state->dts_naggregations = naggs;
8639 	}
8640 
8641 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
8642 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
8643 
8644 	frec = &agg->dtag_first->dta_rec;
8645 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
8646 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
8647 
8648 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
8649 		ASSERT(!act->dta_intuple);
8650 		act->dta_intuple = 1;
8651 	}
8652 
8653 	return (&agg->dtag_action);
8654 }
8655 
8656 static void
8657 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
8658 {
8659 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
8660 	dtrace_state_t *state = ecb->dte_state;
8661 	dtrace_aggid_t aggid = agg->dtag_id;
8662 
8663 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
8664 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
8665 
8666 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
8667 	state->dts_aggregations[aggid - 1] = NULL;
8668 
8669 	kmem_free(agg, sizeof (dtrace_aggregation_t));
8670 }
8671 
8672 static int
8673 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
8674 {
8675 	dtrace_action_t *action, *last;
8676 	dtrace_difo_t *dp = desc->dtad_difo;
8677 	uint32_t size = 0, align = sizeof (uint8_t), mask;
8678 	uint16_t format = 0;
8679 	dtrace_recdesc_t *rec;
8680 	dtrace_state_t *state = ecb->dte_state;
8681 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
8682 	uint64_t arg = desc->dtad_arg;
8683 
8684 	ASSERT(MUTEX_HELD(&dtrace_lock));
8685 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
8686 
8687 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
8688 		/*
8689 		 * If this is an aggregating action, there must be neither
8690 		 * a speculate nor a commit on the action chain.
8691 		 */
8692 		dtrace_action_t *act;
8693 
8694 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
8695 			if (act->dta_kind == DTRACEACT_COMMIT)
8696 				return (EINVAL);
8697 
8698 			if (act->dta_kind == DTRACEACT_SPECULATE)
8699 				return (EINVAL);
8700 		}
8701 
8702 		action = dtrace_ecb_aggregation_create(ecb, desc);
8703 
8704 		if (action == NULL)
8705 			return (EINVAL);
8706 	} else {
8707 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
8708 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
8709 		    dp != NULL && dp->dtdo_destructive)) {
8710 			state->dts_destructive = 1;
8711 		}
8712 
8713 		switch (desc->dtad_kind) {
8714 		case DTRACEACT_PRINTF:
8715 		case DTRACEACT_PRINTA:
8716 		case DTRACEACT_SYSTEM:
8717 		case DTRACEACT_FREOPEN:
8718 			/*
8719 			 * We know that our arg is a string -- turn it into a
8720 			 * format.
8721 			 */
8722 			if (arg == NULL) {
8723 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
8724 				format = 0;
8725 			} else {
8726 				ASSERT(arg != NULL);
8727 				ASSERT(arg > KERNELBASE);
8728 				format = dtrace_format_add(state,
8729 				    (char *)(uintptr_t)arg);
8730 			}
8731 
8732 			/*FALLTHROUGH*/
8733 		case DTRACEACT_LIBACT:
8734 		case DTRACEACT_DIFEXPR:
8735 			if (dp == NULL)
8736 				return (EINVAL);
8737 
8738 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
8739 				break;
8740 
8741 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
8742 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8743 					return (EINVAL);
8744 
8745 				size = opt[DTRACEOPT_STRSIZE];
8746 			}
8747 
8748 			break;
8749 
8750 		case DTRACEACT_STACK:
8751 			if ((nframes = arg) == 0) {
8752 				nframes = opt[DTRACEOPT_STACKFRAMES];
8753 				ASSERT(nframes > 0);
8754 				arg = nframes;
8755 			}
8756 
8757 			size = nframes * sizeof (pc_t);
8758 			break;
8759 
8760 		case DTRACEACT_JSTACK:
8761 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
8762 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
8763 
8764 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
8765 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
8766 
8767 			arg = DTRACE_USTACK_ARG(nframes, strsize);
8768 
8769 			/*FALLTHROUGH*/
8770 		case DTRACEACT_USTACK:
8771 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
8772 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
8773 				strsize = DTRACE_USTACK_STRSIZE(arg);
8774 				nframes = opt[DTRACEOPT_USTACKFRAMES];
8775 				ASSERT(nframes > 0);
8776 				arg = DTRACE_USTACK_ARG(nframes, strsize);
8777 			}
8778 
8779 			/*
8780 			 * Save a slot for the pid.
8781 			 */
8782 			size = (nframes + 1) * sizeof (uint64_t);
8783 			size += DTRACE_USTACK_STRSIZE(arg);
8784 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
8785 
8786 			break;
8787 
8788 		case DTRACEACT_SYM:
8789 		case DTRACEACT_MOD:
8790 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
8791 			    sizeof (uint64_t)) ||
8792 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8793 				return (EINVAL);
8794 			break;
8795 
8796 		case DTRACEACT_USYM:
8797 		case DTRACEACT_UMOD:
8798 		case DTRACEACT_UADDR:
8799 			if (dp == NULL ||
8800 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
8801 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8802 				return (EINVAL);
8803 
8804 			/*
8805 			 * We have a slot for the pid, plus a slot for the
8806 			 * argument.  To keep things simple (aligned with
8807 			 * bitness-neutral sizing), we store each as a 64-bit
8808 			 * quantity.
8809 			 */
8810 			size = 2 * sizeof (uint64_t);
8811 			break;
8812 
8813 		case DTRACEACT_STOP:
8814 		case DTRACEACT_BREAKPOINT:
8815 		case DTRACEACT_PANIC:
8816 			break;
8817 
8818 		case DTRACEACT_CHILL:
8819 		case DTRACEACT_DISCARD:
8820 		case DTRACEACT_RAISE:
8821 			if (dp == NULL)
8822 				return (EINVAL);
8823 			break;
8824 
8825 		case DTRACEACT_EXIT:
8826 			if (dp == NULL ||
8827 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
8828 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
8829 				return (EINVAL);
8830 			break;
8831 
8832 		case DTRACEACT_SPECULATE:
8833 			if (ecb->dte_size > sizeof (dtrace_epid_t))
8834 				return (EINVAL);
8835 
8836 			if (dp == NULL)
8837 				return (EINVAL);
8838 
8839 			state->dts_speculates = 1;
8840 			break;
8841 
8842 		case DTRACEACT_COMMIT: {
8843 			dtrace_action_t *act = ecb->dte_action;
8844 
8845 			for (; act != NULL; act = act->dta_next) {
8846 				if (act->dta_kind == DTRACEACT_COMMIT)
8847 					return (EINVAL);
8848 			}
8849 
8850 			if (dp == NULL)
8851 				return (EINVAL);
8852 			break;
8853 		}
8854 
8855 		default:
8856 			return (EINVAL);
8857 		}
8858 
8859 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
8860 			/*
8861 			 * If this is a data-storing action or a speculate,
8862 			 * we must be sure that there isn't a commit on the
8863 			 * action chain.
8864 			 */
8865 			dtrace_action_t *act = ecb->dte_action;
8866 
8867 			for (; act != NULL; act = act->dta_next) {
8868 				if (act->dta_kind == DTRACEACT_COMMIT)
8869 					return (EINVAL);
8870 			}
8871 		}
8872 
8873 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
8874 		action->dta_rec.dtrd_size = size;
8875 	}
8876 
8877 	action->dta_refcnt = 1;
8878 	rec = &action->dta_rec;
8879 	size = rec->dtrd_size;
8880 
8881 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
8882 		if (!(size & mask)) {
8883 			align = mask + 1;
8884 			break;
8885 		}
8886 	}
8887 
8888 	action->dta_kind = desc->dtad_kind;
8889 
8890 	if ((action->dta_difo = dp) != NULL)
8891 		dtrace_difo_hold(dp);
8892 
8893 	rec->dtrd_action = action->dta_kind;
8894 	rec->dtrd_arg = arg;
8895 	rec->dtrd_uarg = desc->dtad_uarg;
8896 	rec->dtrd_alignment = (uint16_t)align;
8897 	rec->dtrd_format = format;
8898 
8899 	if ((last = ecb->dte_action_last) != NULL) {
8900 		ASSERT(ecb->dte_action != NULL);
8901 		action->dta_prev = last;
8902 		last->dta_next = action;
8903 	} else {
8904 		ASSERT(ecb->dte_action == NULL);
8905 		ecb->dte_action = action;
8906 	}
8907 
8908 	ecb->dte_action_last = action;
8909 
8910 	return (0);
8911 }
8912 
8913 static void
8914 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
8915 {
8916 	dtrace_action_t *act = ecb->dte_action, *next;
8917 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
8918 	dtrace_difo_t *dp;
8919 	uint16_t format;
8920 
8921 	if (act != NULL && act->dta_refcnt > 1) {
8922 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
8923 		act->dta_refcnt--;
8924 	} else {
8925 		for (; act != NULL; act = next) {
8926 			next = act->dta_next;
8927 			ASSERT(next != NULL || act == ecb->dte_action_last);
8928 			ASSERT(act->dta_refcnt == 1);
8929 
8930 			if ((format = act->dta_rec.dtrd_format) != 0)
8931 				dtrace_format_remove(ecb->dte_state, format);
8932 
8933 			if ((dp = act->dta_difo) != NULL)
8934 				dtrace_difo_release(dp, vstate);
8935 
8936 			if (DTRACEACT_ISAGG(act->dta_kind)) {
8937 				dtrace_ecb_aggregation_destroy(ecb, act);
8938 			} else {
8939 				kmem_free(act, sizeof (dtrace_action_t));
8940 			}
8941 		}
8942 	}
8943 
8944 	ecb->dte_action = NULL;
8945 	ecb->dte_action_last = NULL;
8946 	ecb->dte_size = sizeof (dtrace_epid_t);
8947 }
8948 
8949 static void
8950 dtrace_ecb_disable(dtrace_ecb_t *ecb)
8951 {
8952 	/*
8953 	 * We disable the ECB by removing it from its probe.
8954 	 */
8955 	dtrace_ecb_t *pecb, *prev = NULL;
8956 	dtrace_probe_t *probe = ecb->dte_probe;
8957 
8958 	ASSERT(MUTEX_HELD(&dtrace_lock));
8959 
8960 	if (probe == NULL) {
8961 		/*
8962 		 * This is the NULL probe; there is nothing to disable.
8963 		 */
8964 		return;
8965 	}
8966 
8967 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
8968 		if (pecb == ecb)
8969 			break;
8970 		prev = pecb;
8971 	}
8972 
8973 	ASSERT(pecb != NULL);
8974 
8975 	if (prev == NULL) {
8976 		probe->dtpr_ecb = ecb->dte_next;
8977 	} else {
8978 		prev->dte_next = ecb->dte_next;
8979 	}
8980 
8981 	if (ecb == probe->dtpr_ecb_last) {
8982 		ASSERT(ecb->dte_next == NULL);
8983 		probe->dtpr_ecb_last = prev;
8984 	}
8985 
8986 	/*
8987 	 * The ECB has been disconnected from the probe; now sync to assure
8988 	 * that all CPUs have seen the change before returning.
8989 	 */
8990 	dtrace_sync();
8991 
8992 	if (probe->dtpr_ecb == NULL) {
8993 		/*
8994 		 * That was the last ECB on the probe; clear the predicate
8995 		 * cache ID for the probe, disable it and sync one more time
8996 		 * to assure that we'll never hit it again.
8997 		 */
8998 		dtrace_provider_t *prov = probe->dtpr_provider;
8999 
9000 		ASSERT(ecb->dte_next == NULL);
9001 		ASSERT(probe->dtpr_ecb_last == NULL);
9002 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
9003 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
9004 		    probe->dtpr_id, probe->dtpr_arg);
9005 		dtrace_sync();
9006 	} else {
9007 		/*
9008 		 * There is at least one ECB remaining on the probe.  If there
9009 		 * is _exactly_ one, set the probe's predicate cache ID to be
9010 		 * the predicate cache ID of the remaining ECB.
9011 		 */
9012 		ASSERT(probe->dtpr_ecb_last != NULL);
9013 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
9014 
9015 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
9016 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
9017 
9018 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
9019 
9020 			if (p != NULL)
9021 				probe->dtpr_predcache = p->dtp_cacheid;
9022 		}
9023 
9024 		ecb->dte_next = NULL;
9025 	}
9026 }
9027 
9028 static void
9029 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
9030 {
9031 	dtrace_state_t *state = ecb->dte_state;
9032 	dtrace_vstate_t *vstate = &state->dts_vstate;
9033 	dtrace_predicate_t *pred;
9034 	dtrace_epid_t epid = ecb->dte_epid;
9035 
9036 	ASSERT(MUTEX_HELD(&dtrace_lock));
9037 	ASSERT(ecb->dte_next == NULL);
9038 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
9039 
9040 	if ((pred = ecb->dte_predicate) != NULL)
9041 		dtrace_predicate_release(pred, vstate);
9042 
9043 	dtrace_ecb_action_remove(ecb);
9044 
9045 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
9046 	state->dts_ecbs[epid - 1] = NULL;
9047 
9048 	kmem_free(ecb, sizeof (dtrace_ecb_t));
9049 }
9050 
9051 static dtrace_ecb_t *
9052 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
9053     dtrace_enabling_t *enab)
9054 {
9055 	dtrace_ecb_t *ecb;
9056 	dtrace_predicate_t *pred;
9057 	dtrace_actdesc_t *act;
9058 	dtrace_provider_t *prov;
9059 	dtrace_ecbdesc_t *desc = enab->dten_current;
9060 
9061 	ASSERT(MUTEX_HELD(&dtrace_lock));
9062 	ASSERT(state != NULL);
9063 
9064 	ecb = dtrace_ecb_add(state, probe);
9065 	ecb->dte_uarg = desc->dted_uarg;
9066 
9067 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
9068 		dtrace_predicate_hold(pred);
9069 		ecb->dte_predicate = pred;
9070 	}
9071 
9072 	if (probe != NULL) {
9073 		/*
9074 		 * If the provider shows more leg than the consumer is old
9075 		 * enough to see, we need to enable the appropriate implicit
9076 		 * predicate bits to prevent the ecb from activating at
9077 		 * revealing times.
9078 		 *
9079 		 * Providers specifying DTRACE_PRIV_USER at register time
9080 		 * are stating that they need the /proc-style privilege
9081 		 * model to be enforced, and this is what DTRACE_COND_OWNER
9082 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
9083 		 */
9084 		prov = probe->dtpr_provider;
9085 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
9086 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9087 			ecb->dte_cond |= DTRACE_COND_OWNER;
9088 
9089 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
9090 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9091 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
9092 
9093 		/*
9094 		 * If the provider shows us kernel innards and the user
9095 		 * is lacking sufficient privilege, enable the
9096 		 * DTRACE_COND_USERMODE implicit predicate.
9097 		 */
9098 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
9099 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
9100 			ecb->dte_cond |= DTRACE_COND_USERMODE;
9101 	}
9102 
9103 	if (dtrace_ecb_create_cache != NULL) {
9104 		/*
9105 		 * If we have a cached ecb, we'll use its action list instead
9106 		 * of creating our own (saving both time and space).
9107 		 */
9108 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
9109 		dtrace_action_t *act = cached->dte_action;
9110 
9111 		if (act != NULL) {
9112 			ASSERT(act->dta_refcnt > 0);
9113 			act->dta_refcnt++;
9114 			ecb->dte_action = act;
9115 			ecb->dte_action_last = cached->dte_action_last;
9116 			ecb->dte_needed = cached->dte_needed;
9117 			ecb->dte_size = cached->dte_size;
9118 			ecb->dte_alignment = cached->dte_alignment;
9119 		}
9120 
9121 		return (ecb);
9122 	}
9123 
9124 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
9125 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
9126 			dtrace_ecb_destroy(ecb);
9127 			return (NULL);
9128 		}
9129 	}
9130 
9131 	dtrace_ecb_resize(ecb);
9132 
9133 	return (dtrace_ecb_create_cache = ecb);
9134 }
9135 
9136 static int
9137 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
9138 {
9139 	dtrace_ecb_t *ecb;
9140 	dtrace_enabling_t *enab = arg;
9141 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
9142 
9143 	ASSERT(state != NULL);
9144 
9145 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
9146 		/*
9147 		 * This probe was created in a generation for which this
9148 		 * enabling has previously created ECBs; we don't want to
9149 		 * enable it again, so just kick out.
9150 		 */
9151 		return (DTRACE_MATCH_NEXT);
9152 	}
9153 
9154 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
9155 		return (DTRACE_MATCH_DONE);
9156 
9157 	dtrace_ecb_enable(ecb);
9158 	return (DTRACE_MATCH_NEXT);
9159 }
9160 
9161 static dtrace_ecb_t *
9162 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
9163 {
9164 	dtrace_ecb_t *ecb;
9165 
9166 	ASSERT(MUTEX_HELD(&dtrace_lock));
9167 
9168 	if (id == 0 || id > state->dts_necbs)
9169 		return (NULL);
9170 
9171 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
9172 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
9173 
9174 	return (state->dts_ecbs[id - 1]);
9175 }
9176 
9177 static dtrace_aggregation_t *
9178 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
9179 {
9180 	dtrace_aggregation_t *agg;
9181 
9182 	ASSERT(MUTEX_HELD(&dtrace_lock));
9183 
9184 	if (id == 0 || id > state->dts_naggregations)
9185 		return (NULL);
9186 
9187 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
9188 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
9189 	    agg->dtag_id == id);
9190 
9191 	return (state->dts_aggregations[id - 1]);
9192 }
9193 
9194 /*
9195  * DTrace Buffer Functions
9196  *
9197  * The following functions manipulate DTrace buffers.  Most of these functions
9198  * are called in the context of establishing or processing consumer state;
9199  * exceptions are explicitly noted.
9200  */
9201 
9202 /*
9203  * Note:  called from cross call context.  This function switches the two
9204  * buffers on a given CPU.  The atomicity of this operation is assured by
9205  * disabling interrupts while the actual switch takes place; the disabling of
9206  * interrupts serializes the execution with any execution of dtrace_probe() on
9207  * the same CPU.
9208  */
9209 static void
9210 dtrace_buffer_switch(dtrace_buffer_t *buf)
9211 {
9212 	caddr_t tomax = buf->dtb_tomax;
9213 	caddr_t xamot = buf->dtb_xamot;
9214 	dtrace_icookie_t cookie;
9215 
9216 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
9217 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
9218 
9219 	cookie = dtrace_interrupt_disable();
9220 	buf->dtb_tomax = xamot;
9221 	buf->dtb_xamot = tomax;
9222 	buf->dtb_xamot_drops = buf->dtb_drops;
9223 	buf->dtb_xamot_offset = buf->dtb_offset;
9224 	buf->dtb_xamot_errors = buf->dtb_errors;
9225 	buf->dtb_xamot_flags = buf->dtb_flags;
9226 	buf->dtb_offset = 0;
9227 	buf->dtb_drops = 0;
9228 	buf->dtb_errors = 0;
9229 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
9230 	dtrace_interrupt_enable(cookie);
9231 }
9232 
9233 /*
9234  * Note:  called from cross call context.  This function activates a buffer
9235  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
9236  * is guaranteed by the disabling of interrupts.
9237  */
9238 static void
9239 dtrace_buffer_activate(dtrace_state_t *state)
9240 {
9241 	dtrace_buffer_t *buf;
9242 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
9243 
9244 	buf = &state->dts_buffer[CPU->cpu_id];
9245 
9246 	if (buf->dtb_tomax != NULL) {
9247 		/*
9248 		 * We might like to assert that the buffer is marked inactive,
9249 		 * but this isn't necessarily true:  the buffer for the CPU
9250 		 * that processes the BEGIN probe has its buffer activated
9251 		 * manually.  In this case, we take the (harmless) action
9252 		 * re-clearing the bit INACTIVE bit.
9253 		 */
9254 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
9255 	}
9256 
9257 	dtrace_interrupt_enable(cookie);
9258 }
9259 
9260 static int
9261 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
9262     processorid_t cpu)
9263 {
9264 	cpu_t *cp;
9265 	dtrace_buffer_t *buf;
9266 
9267 	ASSERT(MUTEX_HELD(&cpu_lock));
9268 	ASSERT(MUTEX_HELD(&dtrace_lock));
9269 
9270 	if (size > dtrace_nonroot_maxsize &&
9271 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
9272 		return (EFBIG);
9273 
9274 	cp = cpu_list;
9275 
9276 	do {
9277 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9278 			continue;
9279 
9280 		buf = &bufs[cp->cpu_id];
9281 
9282 		/*
9283 		 * If there is already a buffer allocated for this CPU, it
9284 		 * is only possible that this is a DR event.  In this case,
9285 		 * the buffer size must match our specified size.
9286 		 */
9287 		if (buf->dtb_tomax != NULL) {
9288 			ASSERT(buf->dtb_size == size);
9289 			continue;
9290 		}
9291 
9292 		ASSERT(buf->dtb_xamot == NULL);
9293 
9294 		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9295 			goto err;
9296 
9297 		buf->dtb_size = size;
9298 		buf->dtb_flags = flags;
9299 		buf->dtb_offset = 0;
9300 		buf->dtb_drops = 0;
9301 
9302 		if (flags & DTRACEBUF_NOSWITCH)
9303 			continue;
9304 
9305 		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9306 			goto err;
9307 	} while ((cp = cp->cpu_next) != cpu_list);
9308 
9309 	return (0);
9310 
9311 err:
9312 	cp = cpu_list;
9313 
9314 	do {
9315 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9316 			continue;
9317 
9318 		buf = &bufs[cp->cpu_id];
9319 
9320 		if (buf->dtb_xamot != NULL) {
9321 			ASSERT(buf->dtb_tomax != NULL);
9322 			ASSERT(buf->dtb_size == size);
9323 			kmem_free(buf->dtb_xamot, size);
9324 		}
9325 
9326 		if (buf->dtb_tomax != NULL) {
9327 			ASSERT(buf->dtb_size == size);
9328 			kmem_free(buf->dtb_tomax, size);
9329 		}
9330 
9331 		buf->dtb_tomax = NULL;
9332 		buf->dtb_xamot = NULL;
9333 		buf->dtb_size = 0;
9334 	} while ((cp = cp->cpu_next) != cpu_list);
9335 
9336 	return (ENOMEM);
9337 }
9338 
9339 /*
9340  * Note:  called from probe context.  This function just increments the drop
9341  * count on a buffer.  It has been made a function to allow for the
9342  * possibility of understanding the source of mysterious drop counts.  (A
9343  * problem for which one may be particularly disappointed that DTrace cannot
9344  * be used to understand DTrace.)
9345  */
9346 static void
9347 dtrace_buffer_drop(dtrace_buffer_t *buf)
9348 {
9349 	buf->dtb_drops++;
9350 }
9351 
9352 /*
9353  * Note:  called from probe context.  This function is called to reserve space
9354  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
9355  * mstate.  Returns the new offset in the buffer, or a negative value if an
9356  * error has occurred.
9357  */
9358 static intptr_t
9359 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
9360     dtrace_state_t *state, dtrace_mstate_t *mstate)
9361 {
9362 	intptr_t offs = buf->dtb_offset, soffs;
9363 	intptr_t woffs;
9364 	caddr_t tomax;
9365 	size_t total;
9366 
9367 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
9368 		return (-1);
9369 
9370 	if ((tomax = buf->dtb_tomax) == NULL) {
9371 		dtrace_buffer_drop(buf);
9372 		return (-1);
9373 	}
9374 
9375 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
9376 		while (offs & (align - 1)) {
9377 			/*
9378 			 * Assert that our alignment is off by a number which
9379 			 * is itself sizeof (uint32_t) aligned.
9380 			 */
9381 			ASSERT(!((align - (offs & (align - 1))) &
9382 			    (sizeof (uint32_t) - 1)));
9383 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
9384 			offs += sizeof (uint32_t);
9385 		}
9386 
9387 		if ((soffs = offs + needed) > buf->dtb_size) {
9388 			dtrace_buffer_drop(buf);
9389 			return (-1);
9390 		}
9391 
9392 		if (mstate == NULL)
9393 			return (offs);
9394 
9395 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
9396 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
9397 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
9398 
9399 		return (offs);
9400 	}
9401 
9402 	if (buf->dtb_flags & DTRACEBUF_FILL) {
9403 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
9404 		    (buf->dtb_flags & DTRACEBUF_FULL))
9405 			return (-1);
9406 		goto out;
9407 	}
9408 
9409 	total = needed + (offs & (align - 1));
9410 
9411 	/*
9412 	 * For a ring buffer, life is quite a bit more complicated.  Before
9413 	 * we can store any padding, we need to adjust our wrapping offset.
9414 	 * (If we've never before wrapped or we're not about to, no adjustment
9415 	 * is required.)
9416 	 */
9417 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
9418 	    offs + total > buf->dtb_size) {
9419 		woffs = buf->dtb_xamot_offset;
9420 
9421 		if (offs + total > buf->dtb_size) {
9422 			/*
9423 			 * We can't fit in the end of the buffer.  First, a
9424 			 * sanity check that we can fit in the buffer at all.
9425 			 */
9426 			if (total > buf->dtb_size) {
9427 				dtrace_buffer_drop(buf);
9428 				return (-1);
9429 			}
9430 
9431 			/*
9432 			 * We're going to be storing at the top of the buffer,
9433 			 * so now we need to deal with the wrapped offset.  We
9434 			 * only reset our wrapped offset to 0 if it is
9435 			 * currently greater than the current offset.  If it
9436 			 * is less than the current offset, it is because a
9437 			 * previous allocation induced a wrap -- but the
9438 			 * allocation didn't subsequently take the space due
9439 			 * to an error or false predicate evaluation.  In this
9440 			 * case, we'll just leave the wrapped offset alone: if
9441 			 * the wrapped offset hasn't been advanced far enough
9442 			 * for this allocation, it will be adjusted in the
9443 			 * lower loop.
9444 			 */
9445 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
9446 				if (woffs >= offs)
9447 					woffs = 0;
9448 			} else {
9449 				woffs = 0;
9450 			}
9451 
9452 			/*
9453 			 * Now we know that we're going to be storing to the
9454 			 * top of the buffer and that there is room for us
9455 			 * there.  We need to clear the buffer from the current
9456 			 * offset to the end (there may be old gunk there).
9457 			 */
9458 			while (offs < buf->dtb_size)
9459 				tomax[offs++] = 0;
9460 
9461 			/*
9462 			 * We need to set our offset to zero.  And because we
9463 			 * are wrapping, we need to set the bit indicating as
9464 			 * much.  We can also adjust our needed space back
9465 			 * down to the space required by the ECB -- we know
9466 			 * that the top of the buffer is aligned.
9467 			 */
9468 			offs = 0;
9469 			total = needed;
9470 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
9471 		} else {
9472 			/*
9473 			 * There is room for us in the buffer, so we simply
9474 			 * need to check the wrapped offset.
9475 			 */
9476 			if (woffs < offs) {
9477 				/*
9478 				 * The wrapped offset is less than the offset.
9479 				 * This can happen if we allocated buffer space
9480 				 * that induced a wrap, but then we didn't
9481 				 * subsequently take the space due to an error
9482 				 * or false predicate evaluation.  This is
9483 				 * okay; we know that _this_ allocation isn't
9484 				 * going to induce a wrap.  We still can't
9485 				 * reset the wrapped offset to be zero,
9486 				 * however: the space may have been trashed in
9487 				 * the previous failed probe attempt.  But at
9488 				 * least the wrapped offset doesn't need to
9489 				 * be adjusted at all...
9490 				 */
9491 				goto out;
9492 			}
9493 		}
9494 
9495 		while (offs + total > woffs) {
9496 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
9497 			size_t size;
9498 
9499 			if (epid == DTRACE_EPIDNONE) {
9500 				size = sizeof (uint32_t);
9501 			} else {
9502 				ASSERT(epid <= state->dts_necbs);
9503 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
9504 
9505 				size = state->dts_ecbs[epid - 1]->dte_size;
9506 			}
9507 
9508 			ASSERT(woffs + size <= buf->dtb_size);
9509 			ASSERT(size != 0);
9510 
9511 			if (woffs + size == buf->dtb_size) {
9512 				/*
9513 				 * We've reached the end of the buffer; we want
9514 				 * to set the wrapped offset to 0 and break
9515 				 * out.  However, if the offs is 0, then we're
9516 				 * in a strange edge-condition:  the amount of
9517 				 * space that we want to reserve plus the size
9518 				 * of the record that we're overwriting is
9519 				 * greater than the size of the buffer.  This
9520 				 * is problematic because if we reserve the
9521 				 * space but subsequently don't consume it (due
9522 				 * to a failed predicate or error) the wrapped
9523 				 * offset will be 0 -- yet the EPID at offset 0
9524 				 * will not be committed.  This situation is
9525 				 * relatively easy to deal with:  if we're in
9526 				 * this case, the buffer is indistinguishable
9527 				 * from one that hasn't wrapped; we need only
9528 				 * finish the job by clearing the wrapped bit,
9529 				 * explicitly setting the offset to be 0, and
9530 				 * zero'ing out the old data in the buffer.
9531 				 */
9532 				if (offs == 0) {
9533 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
9534 					buf->dtb_offset = 0;
9535 					woffs = total;
9536 
9537 					while (woffs < buf->dtb_size)
9538 						tomax[woffs++] = 0;
9539 				}
9540 
9541 				woffs = 0;
9542 				break;
9543 			}
9544 
9545 			woffs += size;
9546 		}
9547 
9548 		/*
9549 		 * We have a wrapped offset.  It may be that the wrapped offset
9550 		 * has become zero -- that's okay.
9551 		 */
9552 		buf->dtb_xamot_offset = woffs;
9553 	}
9554 
9555 out:
9556 	/*
9557 	 * Now we can plow the buffer with any necessary padding.
9558 	 */
9559 	while (offs & (align - 1)) {
9560 		/*
9561 		 * Assert that our alignment is off by a number which
9562 		 * is itself sizeof (uint32_t) aligned.
9563 		 */
9564 		ASSERT(!((align - (offs & (align - 1))) &
9565 		    (sizeof (uint32_t) - 1)));
9566 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
9567 		offs += sizeof (uint32_t);
9568 	}
9569 
9570 	if (buf->dtb_flags & DTRACEBUF_FILL) {
9571 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
9572 			buf->dtb_flags |= DTRACEBUF_FULL;
9573 			return (-1);
9574 		}
9575 	}
9576 
9577 	if (mstate == NULL)
9578 		return (offs);
9579 
9580 	/*
9581 	 * For ring buffers and fill buffers, the scratch space is always
9582 	 * the inactive buffer.
9583 	 */
9584 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
9585 	mstate->dtms_scratch_size = buf->dtb_size;
9586 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
9587 
9588 	return (offs);
9589 }
9590 
9591 static void
9592 dtrace_buffer_polish(dtrace_buffer_t *buf)
9593 {
9594 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
9595 	ASSERT(MUTEX_HELD(&dtrace_lock));
9596 
9597 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
9598 		return;
9599 
9600 	/*
9601 	 * We need to polish the ring buffer.  There are three cases:
9602 	 *
9603 	 * - The first (and presumably most common) is that there is no gap
9604 	 *   between the buffer offset and the wrapped offset.  In this case,
9605 	 *   there is nothing in the buffer that isn't valid data; we can
9606 	 *   mark the buffer as polished and return.
9607 	 *
9608 	 * - The second (less common than the first but still more common
9609 	 *   than the third) is that there is a gap between the buffer offset
9610 	 *   and the wrapped offset, and the wrapped offset is larger than the
9611 	 *   buffer offset.  This can happen because of an alignment issue, or
9612 	 *   can happen because of a call to dtrace_buffer_reserve() that
9613 	 *   didn't subsequently consume the buffer space.  In this case,
9614 	 *   we need to zero the data from the buffer offset to the wrapped
9615 	 *   offset.
9616 	 *
9617 	 * - The third (and least common) is that there is a gap between the
9618 	 *   buffer offset and the wrapped offset, but the wrapped offset is
9619 	 *   _less_ than the buffer offset.  This can only happen because a
9620 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
9621 	 *   was not subsequently consumed.  In this case, we need to zero the
9622 	 *   space from the offset to the end of the buffer _and_ from the
9623 	 *   top of the buffer to the wrapped offset.
9624 	 */
9625 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
9626 		bzero(buf->dtb_tomax + buf->dtb_offset,
9627 		    buf->dtb_xamot_offset - buf->dtb_offset);
9628 	}
9629 
9630 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
9631 		bzero(buf->dtb_tomax + buf->dtb_offset,
9632 		    buf->dtb_size - buf->dtb_offset);
9633 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
9634 	}
9635 }
9636 
9637 static void
9638 dtrace_buffer_free(dtrace_buffer_t *bufs)
9639 {
9640 	int i;
9641 
9642 	for (i = 0; i < NCPU; i++) {
9643 		dtrace_buffer_t *buf = &bufs[i];
9644 
9645 		if (buf->dtb_tomax == NULL) {
9646 			ASSERT(buf->dtb_xamot == NULL);
9647 			ASSERT(buf->dtb_size == 0);
9648 			continue;
9649 		}
9650 
9651 		if (buf->dtb_xamot != NULL) {
9652 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
9653 			kmem_free(buf->dtb_xamot, buf->dtb_size);
9654 		}
9655 
9656 		kmem_free(buf->dtb_tomax, buf->dtb_size);
9657 		buf->dtb_size = 0;
9658 		buf->dtb_tomax = NULL;
9659 		buf->dtb_xamot = NULL;
9660 	}
9661 }
9662 
9663 /*
9664  * DTrace Enabling Functions
9665  */
9666 static dtrace_enabling_t *
9667 dtrace_enabling_create(dtrace_vstate_t *vstate)
9668 {
9669 	dtrace_enabling_t *enab;
9670 
9671 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
9672 	enab->dten_vstate = vstate;
9673 
9674 	return (enab);
9675 }
9676 
9677 static void
9678 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
9679 {
9680 	dtrace_ecbdesc_t **ndesc;
9681 	size_t osize, nsize;
9682 
9683 	/*
9684 	 * We can't add to enablings after we've enabled them, or after we've
9685 	 * retained them.
9686 	 */
9687 	ASSERT(enab->dten_probegen == 0);
9688 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
9689 
9690 	if (enab->dten_ndesc < enab->dten_maxdesc) {
9691 		enab->dten_desc[enab->dten_ndesc++] = ecb;
9692 		return;
9693 	}
9694 
9695 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
9696 
9697 	if (enab->dten_maxdesc == 0) {
9698 		enab->dten_maxdesc = 1;
9699 	} else {
9700 		enab->dten_maxdesc <<= 1;
9701 	}
9702 
9703 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
9704 
9705 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
9706 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
9707 	bcopy(enab->dten_desc, ndesc, osize);
9708 	kmem_free(enab->dten_desc, osize);
9709 
9710 	enab->dten_desc = ndesc;
9711 	enab->dten_desc[enab->dten_ndesc++] = ecb;
9712 }
9713 
9714 static void
9715 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
9716     dtrace_probedesc_t *pd)
9717 {
9718 	dtrace_ecbdesc_t *new;
9719 	dtrace_predicate_t *pred;
9720 	dtrace_actdesc_t *act;
9721 
9722 	/*
9723 	 * We're going to create a new ECB description that matches the
9724 	 * specified ECB in every way, but has the specified probe description.
9725 	 */
9726 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
9727 
9728 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
9729 		dtrace_predicate_hold(pred);
9730 
9731 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
9732 		dtrace_actdesc_hold(act);
9733 
9734 	new->dted_action = ecb->dted_action;
9735 	new->dted_pred = ecb->dted_pred;
9736 	new->dted_probe = *pd;
9737 	new->dted_uarg = ecb->dted_uarg;
9738 
9739 	dtrace_enabling_add(enab, new);
9740 }
9741 
9742 static void
9743 dtrace_enabling_dump(dtrace_enabling_t *enab)
9744 {
9745 	int i;
9746 
9747 	for (i = 0; i < enab->dten_ndesc; i++) {
9748 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
9749 
9750 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
9751 		    desc->dtpd_provider, desc->dtpd_mod,
9752 		    desc->dtpd_func, desc->dtpd_name);
9753 	}
9754 }
9755 
9756 static void
9757 dtrace_enabling_destroy(dtrace_enabling_t *enab)
9758 {
9759 	int i;
9760 	dtrace_ecbdesc_t *ep;
9761 	dtrace_vstate_t *vstate = enab->dten_vstate;
9762 
9763 	ASSERT(MUTEX_HELD(&dtrace_lock));
9764 
9765 	for (i = 0; i < enab->dten_ndesc; i++) {
9766 		dtrace_actdesc_t *act, *next;
9767 		dtrace_predicate_t *pred;
9768 
9769 		ep = enab->dten_desc[i];
9770 
9771 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
9772 			dtrace_predicate_release(pred, vstate);
9773 
9774 		for (act = ep->dted_action; act != NULL; act = next) {
9775 			next = act->dtad_next;
9776 			dtrace_actdesc_release(act, vstate);
9777 		}
9778 
9779 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
9780 	}
9781 
9782 	kmem_free(enab->dten_desc,
9783 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
9784 
9785 	/*
9786 	 * If this was a retained enabling, decrement the dts_nretained count
9787 	 * and take it off of the dtrace_retained list.
9788 	 */
9789 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
9790 	    dtrace_retained == enab) {
9791 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9792 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
9793 		enab->dten_vstate->dtvs_state->dts_nretained--;
9794 	}
9795 
9796 	if (enab->dten_prev == NULL) {
9797 		if (dtrace_retained == enab) {
9798 			dtrace_retained = enab->dten_next;
9799 
9800 			if (dtrace_retained != NULL)
9801 				dtrace_retained->dten_prev = NULL;
9802 		}
9803 	} else {
9804 		ASSERT(enab != dtrace_retained);
9805 		ASSERT(dtrace_retained != NULL);
9806 		enab->dten_prev->dten_next = enab->dten_next;
9807 	}
9808 
9809 	if (enab->dten_next != NULL) {
9810 		ASSERT(dtrace_retained != NULL);
9811 		enab->dten_next->dten_prev = enab->dten_prev;
9812 	}
9813 
9814 	kmem_free(enab, sizeof (dtrace_enabling_t));
9815 }
9816 
9817 static int
9818 dtrace_enabling_retain(dtrace_enabling_t *enab)
9819 {
9820 	dtrace_state_t *state;
9821 
9822 	ASSERT(MUTEX_HELD(&dtrace_lock));
9823 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
9824 	ASSERT(enab->dten_vstate != NULL);
9825 
9826 	state = enab->dten_vstate->dtvs_state;
9827 	ASSERT(state != NULL);
9828 
9829 	/*
9830 	 * We only allow each state to retain dtrace_retain_max enablings.
9831 	 */
9832 	if (state->dts_nretained >= dtrace_retain_max)
9833 		return (ENOSPC);
9834 
9835 	state->dts_nretained++;
9836 
9837 	if (dtrace_retained == NULL) {
9838 		dtrace_retained = enab;
9839 		return (0);
9840 	}
9841 
9842 	enab->dten_next = dtrace_retained;
9843 	dtrace_retained->dten_prev = enab;
9844 	dtrace_retained = enab;
9845 
9846 	return (0);
9847 }
9848 
9849 static int
9850 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
9851     dtrace_probedesc_t *create)
9852 {
9853 	dtrace_enabling_t *new, *enab;
9854 	int found = 0, err = ENOENT;
9855 
9856 	ASSERT(MUTEX_HELD(&dtrace_lock));
9857 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
9858 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
9859 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
9860 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
9861 
9862 	new = dtrace_enabling_create(&state->dts_vstate);
9863 
9864 	/*
9865 	 * Iterate over all retained enablings, looking for enablings that
9866 	 * match the specified state.
9867 	 */
9868 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
9869 		int i;
9870 
9871 		/*
9872 		 * dtvs_state can only be NULL for helper enablings -- and
9873 		 * helper enablings can't be retained.
9874 		 */
9875 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9876 
9877 		if (enab->dten_vstate->dtvs_state != state)
9878 			continue;
9879 
9880 		/*
9881 		 * Now iterate over each probe description; we're looking for
9882 		 * an exact match to the specified probe description.
9883 		 */
9884 		for (i = 0; i < enab->dten_ndesc; i++) {
9885 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
9886 			dtrace_probedesc_t *pd = &ep->dted_probe;
9887 
9888 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
9889 				continue;
9890 
9891 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
9892 				continue;
9893 
9894 			if (strcmp(pd->dtpd_func, match->dtpd_func))
9895 				continue;
9896 
9897 			if (strcmp(pd->dtpd_name, match->dtpd_name))
9898 				continue;
9899 
9900 			/*
9901 			 * We have a winning probe!  Add it to our growing
9902 			 * enabling.
9903 			 */
9904 			found = 1;
9905 			dtrace_enabling_addlike(new, ep, create);
9906 		}
9907 	}
9908 
9909 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
9910 		dtrace_enabling_destroy(new);
9911 		return (err);
9912 	}
9913 
9914 	return (0);
9915 }
9916 
9917 static void
9918 dtrace_enabling_retract(dtrace_state_t *state)
9919 {
9920 	dtrace_enabling_t *enab, *next;
9921 
9922 	ASSERT(MUTEX_HELD(&dtrace_lock));
9923 
9924 	/*
9925 	 * Iterate over all retained enablings, destroy the enablings retained
9926 	 * for the specified state.
9927 	 */
9928 	for (enab = dtrace_retained; enab != NULL; enab = next) {
9929 		next = enab->dten_next;
9930 
9931 		/*
9932 		 * dtvs_state can only be NULL for helper enablings -- and
9933 		 * helper enablings can't be retained.
9934 		 */
9935 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
9936 
9937 		if (enab->dten_vstate->dtvs_state == state) {
9938 			ASSERT(state->dts_nretained > 0);
9939 			dtrace_enabling_destroy(enab);
9940 		}
9941 	}
9942 
9943 	ASSERT(state->dts_nretained == 0);
9944 }
9945 
9946 static int
9947 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
9948 {
9949 	int i = 0;
9950 	int matched = 0;
9951 
9952 	ASSERT(MUTEX_HELD(&cpu_lock));
9953 	ASSERT(MUTEX_HELD(&dtrace_lock));
9954 
9955 	for (i = 0; i < enab->dten_ndesc; i++) {
9956 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
9957 
9958 		enab->dten_current = ep;
9959 		enab->dten_error = 0;
9960 
9961 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
9962 
9963 		if (enab->dten_error != 0) {
9964 			/*
9965 			 * If we get an error half-way through enabling the
9966 			 * probes, we kick out -- perhaps with some number of
9967 			 * them enabled.  Leaving enabled probes enabled may
9968 			 * be slightly confusing for user-level, but we expect
9969 			 * that no one will attempt to actually drive on in
9970 			 * the face of such errors.  If this is an anonymous
9971 			 * enabling (indicated with a NULL nmatched pointer),
9972 			 * we cmn_err() a message.  We aren't expecting to
9973 			 * get such an error -- such as it can exist at all,
9974 			 * it would be a result of corrupted DOF in the driver
9975 			 * properties.
9976 			 */
9977 			if (nmatched == NULL) {
9978 				cmn_err(CE_WARN, "dtrace_enabling_match() "
9979 				    "error on %p: %d", (void *)ep,
9980 				    enab->dten_error);
9981 			}
9982 
9983 			return (enab->dten_error);
9984 		}
9985 	}
9986 
9987 	enab->dten_probegen = dtrace_probegen;
9988 	if (nmatched != NULL)
9989 		*nmatched = matched;
9990 
9991 	return (0);
9992 }
9993 
9994 static void
9995 dtrace_enabling_matchall(void)
9996 {
9997 	dtrace_enabling_t *enab;
9998 
9999 	mutex_enter(&cpu_lock);
10000 	mutex_enter(&dtrace_lock);
10001 
10002 	/*
10003 	 * Because we can be called after dtrace_detach() has been called, we
10004 	 * cannot assert that there are retained enablings.  We can safely
10005 	 * load from dtrace_retained, however:  the taskq_destroy() at the
10006 	 * end of dtrace_detach() will block pending our completion.
10007 	 */
10008 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next)
10009 		(void) dtrace_enabling_match(enab, NULL);
10010 
10011 	mutex_exit(&dtrace_lock);
10012 	mutex_exit(&cpu_lock);
10013 }
10014 
10015 static int
10016 dtrace_enabling_matchstate(dtrace_state_t *state, int *nmatched)
10017 {
10018 	dtrace_enabling_t *enab;
10019 	int matched, total = 0, err;
10020 
10021 	ASSERT(MUTEX_HELD(&cpu_lock));
10022 	ASSERT(MUTEX_HELD(&dtrace_lock));
10023 
10024 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10025 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10026 
10027 		if (enab->dten_vstate->dtvs_state != state)
10028 			continue;
10029 
10030 		if ((err = dtrace_enabling_match(enab, &matched)) != 0)
10031 			return (err);
10032 
10033 		total += matched;
10034 	}
10035 
10036 	if (nmatched != NULL)
10037 		*nmatched = total;
10038 
10039 	return (0);
10040 }
10041 
10042 /*
10043  * If an enabling is to be enabled without having matched probes (that is, if
10044  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
10045  * enabling must be _primed_ by creating an ECB for every ECB description.
10046  * This must be done to assure that we know the number of speculations, the
10047  * number of aggregations, the minimum buffer size needed, etc. before we
10048  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
10049  * enabling any probes, we create ECBs for every ECB decription, but with a
10050  * NULL probe -- which is exactly what this function does.
10051  */
10052 static void
10053 dtrace_enabling_prime(dtrace_state_t *state)
10054 {
10055 	dtrace_enabling_t *enab;
10056 	int i;
10057 
10058 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10059 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10060 
10061 		if (enab->dten_vstate->dtvs_state != state)
10062 			continue;
10063 
10064 		/*
10065 		 * We don't want to prime an enabling more than once, lest
10066 		 * we allow a malicious user to induce resource exhaustion.
10067 		 * (The ECBs that result from priming an enabling aren't
10068 		 * leaked -- but they also aren't deallocated until the
10069 		 * consumer state is destroyed.)
10070 		 */
10071 		if (enab->dten_primed)
10072 			continue;
10073 
10074 		for (i = 0; i < enab->dten_ndesc; i++) {
10075 			enab->dten_current = enab->dten_desc[i];
10076 			(void) dtrace_probe_enable(NULL, enab);
10077 		}
10078 
10079 		enab->dten_primed = 1;
10080 	}
10081 }
10082 
10083 /*
10084  * Called to indicate that probes should be provided due to retained
10085  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
10086  * must take an initial lap through the enabling calling the dtps_provide()
10087  * entry point explicitly to allow for autocreated probes.
10088  */
10089 static void
10090 dtrace_enabling_provide(dtrace_provider_t *prv)
10091 {
10092 	int i, all = 0;
10093 	dtrace_probedesc_t desc;
10094 
10095 	ASSERT(MUTEX_HELD(&dtrace_lock));
10096 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
10097 
10098 	if (prv == NULL) {
10099 		all = 1;
10100 		prv = dtrace_provider;
10101 	}
10102 
10103 	do {
10104 		dtrace_enabling_t *enab = dtrace_retained;
10105 		void *parg = prv->dtpv_arg;
10106 
10107 		for (; enab != NULL; enab = enab->dten_next) {
10108 			for (i = 0; i < enab->dten_ndesc; i++) {
10109 				desc = enab->dten_desc[i]->dted_probe;
10110 				mutex_exit(&dtrace_lock);
10111 				prv->dtpv_pops.dtps_provide(parg, &desc);
10112 				mutex_enter(&dtrace_lock);
10113 			}
10114 		}
10115 	} while (all && (prv = prv->dtpv_next) != NULL);
10116 
10117 	mutex_exit(&dtrace_lock);
10118 	dtrace_probe_provide(NULL, all ? NULL : prv);
10119 	mutex_enter(&dtrace_lock);
10120 }
10121 
10122 /*
10123  * DTrace DOF Functions
10124  */
10125 /*ARGSUSED*/
10126 static void
10127 dtrace_dof_error(dof_hdr_t *dof, const char *str)
10128 {
10129 	if (dtrace_err_verbose)
10130 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
10131 
10132 #ifdef DTRACE_ERRDEBUG
10133 	dtrace_errdebug(str);
10134 #endif
10135 }
10136 
10137 /*
10138  * Create DOF out of a currently enabled state.  Right now, we only create
10139  * DOF containing the run-time options -- but this could be expanded to create
10140  * complete DOF representing the enabled state.
10141  */
10142 static dof_hdr_t *
10143 dtrace_dof_create(dtrace_state_t *state)
10144 {
10145 	dof_hdr_t *dof;
10146 	dof_sec_t *sec;
10147 	dof_optdesc_t *opt;
10148 	int i, len = sizeof (dof_hdr_t) +
10149 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
10150 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10151 
10152 	ASSERT(MUTEX_HELD(&dtrace_lock));
10153 
10154 	dof = kmem_zalloc(len, KM_SLEEP);
10155 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
10156 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
10157 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
10158 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
10159 
10160 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
10161 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
10162 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
10163 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
10164 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
10165 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
10166 
10167 	dof->dofh_flags = 0;
10168 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
10169 	dof->dofh_secsize = sizeof (dof_sec_t);
10170 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
10171 	dof->dofh_secoff = sizeof (dof_hdr_t);
10172 	dof->dofh_loadsz = len;
10173 	dof->dofh_filesz = len;
10174 	dof->dofh_pad = 0;
10175 
10176 	/*
10177 	 * Fill in the option section header...
10178 	 */
10179 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
10180 	sec->dofs_type = DOF_SECT_OPTDESC;
10181 	sec->dofs_align = sizeof (uint64_t);
10182 	sec->dofs_flags = DOF_SECF_LOAD;
10183 	sec->dofs_entsize = sizeof (dof_optdesc_t);
10184 
10185 	opt = (dof_optdesc_t *)((uintptr_t)sec +
10186 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
10187 
10188 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
10189 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10190 
10191 	for (i = 0; i < DTRACEOPT_MAX; i++) {
10192 		opt[i].dofo_option = i;
10193 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
10194 		opt[i].dofo_value = state->dts_options[i];
10195 	}
10196 
10197 	return (dof);
10198 }
10199 
10200 static dof_hdr_t *
10201 dtrace_dof_copyin(uintptr_t uarg, int *errp)
10202 {
10203 	dof_hdr_t hdr, *dof;
10204 
10205 	ASSERT(!MUTEX_HELD(&dtrace_lock));
10206 
10207 	/*
10208 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
10209 	 */
10210 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
10211 		dtrace_dof_error(NULL, "failed to copyin DOF header");
10212 		*errp = EFAULT;
10213 		return (NULL);
10214 	}
10215 
10216 	/*
10217 	 * Now we'll allocate the entire DOF and copy it in -- provided
10218 	 * that the length isn't outrageous.
10219 	 */
10220 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
10221 		dtrace_dof_error(&hdr, "load size exceeds maximum");
10222 		*errp = E2BIG;
10223 		return (NULL);
10224 	}
10225 
10226 	if (hdr.dofh_loadsz < sizeof (hdr)) {
10227 		dtrace_dof_error(&hdr, "invalid load size");
10228 		*errp = EINVAL;
10229 		return (NULL);
10230 	}
10231 
10232 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
10233 
10234 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
10235 		kmem_free(dof, hdr.dofh_loadsz);
10236 		*errp = EFAULT;
10237 		return (NULL);
10238 	}
10239 
10240 	return (dof);
10241 }
10242 
10243 static dof_hdr_t *
10244 dtrace_dof_property(const char *name)
10245 {
10246 	uchar_t *buf;
10247 	uint64_t loadsz;
10248 	unsigned int len, i;
10249 	dof_hdr_t *dof;
10250 
10251 	/*
10252 	 * Unfortunately, array of values in .conf files are always (and
10253 	 * only) interpreted to be integer arrays.  We must read our DOF
10254 	 * as an integer array, and then squeeze it into a byte array.
10255 	 */
10256 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
10257 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
10258 		return (NULL);
10259 
10260 	for (i = 0; i < len; i++)
10261 		buf[i] = (uchar_t)(((int *)buf)[i]);
10262 
10263 	if (len < sizeof (dof_hdr_t)) {
10264 		ddi_prop_free(buf);
10265 		dtrace_dof_error(NULL, "truncated header");
10266 		return (NULL);
10267 	}
10268 
10269 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
10270 		ddi_prop_free(buf);
10271 		dtrace_dof_error(NULL, "truncated DOF");
10272 		return (NULL);
10273 	}
10274 
10275 	if (loadsz >= dtrace_dof_maxsize) {
10276 		ddi_prop_free(buf);
10277 		dtrace_dof_error(NULL, "oversized DOF");
10278 		return (NULL);
10279 	}
10280 
10281 	dof = kmem_alloc(loadsz, KM_SLEEP);
10282 	bcopy(buf, dof, loadsz);
10283 	ddi_prop_free(buf);
10284 
10285 	return (dof);
10286 }
10287 
10288 static void
10289 dtrace_dof_destroy(dof_hdr_t *dof)
10290 {
10291 	kmem_free(dof, dof->dofh_loadsz);
10292 }
10293 
10294 /*
10295  * Return the dof_sec_t pointer corresponding to a given section index.  If the
10296  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
10297  * a type other than DOF_SECT_NONE is specified, the header is checked against
10298  * this type and NULL is returned if the types do not match.
10299  */
10300 static dof_sec_t *
10301 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
10302 {
10303 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
10304 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
10305 
10306 	if (i >= dof->dofh_secnum) {
10307 		dtrace_dof_error(dof, "referenced section index is invalid");
10308 		return (NULL);
10309 	}
10310 
10311 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
10312 		dtrace_dof_error(dof, "referenced section is not loadable");
10313 		return (NULL);
10314 	}
10315 
10316 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
10317 		dtrace_dof_error(dof, "referenced section is the wrong type");
10318 		return (NULL);
10319 	}
10320 
10321 	return (sec);
10322 }
10323 
10324 static dtrace_probedesc_t *
10325 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
10326 {
10327 	dof_probedesc_t *probe;
10328 	dof_sec_t *strtab;
10329 	uintptr_t daddr = (uintptr_t)dof;
10330 	uintptr_t str;
10331 	size_t size;
10332 
10333 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
10334 		dtrace_dof_error(dof, "invalid probe section");
10335 		return (NULL);
10336 	}
10337 
10338 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
10339 		dtrace_dof_error(dof, "bad alignment in probe description");
10340 		return (NULL);
10341 	}
10342 
10343 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
10344 		dtrace_dof_error(dof, "truncated probe description");
10345 		return (NULL);
10346 	}
10347 
10348 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
10349 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
10350 
10351 	if (strtab == NULL)
10352 		return (NULL);
10353 
10354 	str = daddr + strtab->dofs_offset;
10355 	size = strtab->dofs_size;
10356 
10357 	if (probe->dofp_provider >= strtab->dofs_size) {
10358 		dtrace_dof_error(dof, "corrupt probe provider");
10359 		return (NULL);
10360 	}
10361 
10362 	(void) strncpy(desc->dtpd_provider,
10363 	    (char *)(str + probe->dofp_provider),
10364 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
10365 
10366 	if (probe->dofp_mod >= strtab->dofs_size) {
10367 		dtrace_dof_error(dof, "corrupt probe module");
10368 		return (NULL);
10369 	}
10370 
10371 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
10372 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
10373 
10374 	if (probe->dofp_func >= strtab->dofs_size) {
10375 		dtrace_dof_error(dof, "corrupt probe function");
10376 		return (NULL);
10377 	}
10378 
10379 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
10380 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
10381 
10382 	if (probe->dofp_name >= strtab->dofs_size) {
10383 		dtrace_dof_error(dof, "corrupt probe name");
10384 		return (NULL);
10385 	}
10386 
10387 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
10388 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
10389 
10390 	return (desc);
10391 }
10392 
10393 static dtrace_difo_t *
10394 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10395     cred_t *cr)
10396 {
10397 	dtrace_difo_t *dp;
10398 	size_t ttl = 0;
10399 	dof_difohdr_t *dofd;
10400 	uintptr_t daddr = (uintptr_t)dof;
10401 	size_t max = dtrace_difo_maxsize;
10402 	int i, l, n;
10403 
10404 	static const struct {
10405 		int section;
10406 		int bufoffs;
10407 		int lenoffs;
10408 		int entsize;
10409 		int align;
10410 		const char *msg;
10411 	} difo[] = {
10412 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
10413 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
10414 		sizeof (dif_instr_t), "multiple DIF sections" },
10415 
10416 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
10417 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
10418 		sizeof (uint64_t), "multiple integer tables" },
10419 
10420 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
10421 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
10422 		sizeof (char), "multiple string tables" },
10423 
10424 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
10425 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
10426 		sizeof (uint_t), "multiple variable tables" },
10427 
10428 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
10429 	};
10430 
10431 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
10432 		dtrace_dof_error(dof, "invalid DIFO header section");
10433 		return (NULL);
10434 	}
10435 
10436 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
10437 		dtrace_dof_error(dof, "bad alignment in DIFO header");
10438 		return (NULL);
10439 	}
10440 
10441 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
10442 	    sec->dofs_size % sizeof (dof_secidx_t)) {
10443 		dtrace_dof_error(dof, "bad size in DIFO header");
10444 		return (NULL);
10445 	}
10446 
10447 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
10448 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
10449 
10450 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10451 	dp->dtdo_rtype = dofd->dofd_rtype;
10452 
10453 	for (l = 0; l < n; l++) {
10454 		dof_sec_t *subsec;
10455 		void **bufp;
10456 		uint32_t *lenp;
10457 
10458 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
10459 		    dofd->dofd_links[l])) == NULL)
10460 			goto err; /* invalid section link */
10461 
10462 		if (ttl + subsec->dofs_size > max) {
10463 			dtrace_dof_error(dof, "exceeds maximum size");
10464 			goto err;
10465 		}
10466 
10467 		ttl += subsec->dofs_size;
10468 
10469 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
10470 			if (subsec->dofs_type != difo[i].section)
10471 				continue;
10472 
10473 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
10474 				dtrace_dof_error(dof, "section not loaded");
10475 				goto err;
10476 			}
10477 
10478 			if (subsec->dofs_align != difo[i].align) {
10479 				dtrace_dof_error(dof, "bad alignment");
10480 				goto err;
10481 			}
10482 
10483 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
10484 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
10485 
10486 			if (*bufp != NULL) {
10487 				dtrace_dof_error(dof, difo[i].msg);
10488 				goto err;
10489 			}
10490 
10491 			if (difo[i].entsize != subsec->dofs_entsize) {
10492 				dtrace_dof_error(dof, "entry size mismatch");
10493 				goto err;
10494 			}
10495 
10496 			if (subsec->dofs_entsize != 0 &&
10497 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
10498 				dtrace_dof_error(dof, "corrupt entry size");
10499 				goto err;
10500 			}
10501 
10502 			*lenp = subsec->dofs_size;
10503 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
10504 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
10505 			    *bufp, subsec->dofs_size);
10506 
10507 			if (subsec->dofs_entsize != 0)
10508 				*lenp /= subsec->dofs_entsize;
10509 
10510 			break;
10511 		}
10512 
10513 		/*
10514 		 * If we encounter a loadable DIFO sub-section that is not
10515 		 * known to us, assume this is a broken program and fail.
10516 		 */
10517 		if (difo[i].section == DOF_SECT_NONE &&
10518 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
10519 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
10520 			goto err;
10521 		}
10522 	}
10523 
10524 	if (dp->dtdo_buf == NULL) {
10525 		/*
10526 		 * We can't have a DIF object without DIF text.
10527 		 */
10528 		dtrace_dof_error(dof, "missing DIF text");
10529 		goto err;
10530 	}
10531 
10532 	/*
10533 	 * Before we validate the DIF object, run through the variable table
10534 	 * looking for the strings -- if any of their size are under, we'll set
10535 	 * their size to be the system-wide default string size.  Note that
10536 	 * this should _not_ happen if the "strsize" option has been set --
10537 	 * in this case, the compiler should have set the size to reflect the
10538 	 * setting of the option.
10539 	 */
10540 	for (i = 0; i < dp->dtdo_varlen; i++) {
10541 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10542 		dtrace_diftype_t *t = &v->dtdv_type;
10543 
10544 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
10545 			continue;
10546 
10547 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
10548 			t->dtdt_size = dtrace_strsize_default;
10549 	}
10550 
10551 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
10552 		goto err;
10553 
10554 	dtrace_difo_init(dp, vstate);
10555 	return (dp);
10556 
10557 err:
10558 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10559 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10560 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10561 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10562 
10563 	kmem_free(dp, sizeof (dtrace_difo_t));
10564 	return (NULL);
10565 }
10566 
10567 static dtrace_predicate_t *
10568 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10569     cred_t *cr)
10570 {
10571 	dtrace_difo_t *dp;
10572 
10573 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
10574 		return (NULL);
10575 
10576 	return (dtrace_predicate_create(dp));
10577 }
10578 
10579 static dtrace_actdesc_t *
10580 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10581     cred_t *cr)
10582 {
10583 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
10584 	dof_actdesc_t *desc;
10585 	dof_sec_t *difosec;
10586 	size_t offs;
10587 	uintptr_t daddr = (uintptr_t)dof;
10588 	uint64_t arg;
10589 	dtrace_actkind_t kind;
10590 
10591 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
10592 		dtrace_dof_error(dof, "invalid action section");
10593 		return (NULL);
10594 	}
10595 
10596 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
10597 		dtrace_dof_error(dof, "truncated action description");
10598 		return (NULL);
10599 	}
10600 
10601 	if (sec->dofs_align != sizeof (uint64_t)) {
10602 		dtrace_dof_error(dof, "bad alignment in action description");
10603 		return (NULL);
10604 	}
10605 
10606 	if (sec->dofs_size < sec->dofs_entsize) {
10607 		dtrace_dof_error(dof, "section entry size exceeds total size");
10608 		return (NULL);
10609 	}
10610 
10611 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
10612 		dtrace_dof_error(dof, "bad entry size in action description");
10613 		return (NULL);
10614 	}
10615 
10616 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
10617 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
10618 		return (NULL);
10619 	}
10620 
10621 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
10622 		desc = (dof_actdesc_t *)(daddr +
10623 		    (uintptr_t)sec->dofs_offset + offs);
10624 		kind = (dtrace_actkind_t)desc->dofa_kind;
10625 
10626 		if (DTRACEACT_ISPRINTFLIKE(kind) &&
10627 		    (kind != DTRACEACT_PRINTA ||
10628 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
10629 			dof_sec_t *strtab;
10630 			char *str, *fmt;
10631 			uint64_t i;
10632 
10633 			/*
10634 			 * printf()-like actions must have a format string.
10635 			 */
10636 			if ((strtab = dtrace_dof_sect(dof,
10637 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
10638 				goto err;
10639 
10640 			str = (char *)((uintptr_t)dof +
10641 			    (uintptr_t)strtab->dofs_offset);
10642 
10643 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
10644 				if (str[i] == '\0')
10645 					break;
10646 			}
10647 
10648 			if (i >= strtab->dofs_size) {
10649 				dtrace_dof_error(dof, "bogus format string");
10650 				goto err;
10651 			}
10652 
10653 			if (i == desc->dofa_arg) {
10654 				dtrace_dof_error(dof, "empty format string");
10655 				goto err;
10656 			}
10657 
10658 			i -= desc->dofa_arg;
10659 			fmt = kmem_alloc(i + 1, KM_SLEEP);
10660 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
10661 			arg = (uint64_t)(uintptr_t)fmt;
10662 		} else {
10663 			if (kind == DTRACEACT_PRINTA) {
10664 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
10665 				arg = 0;
10666 			} else {
10667 				arg = desc->dofa_arg;
10668 			}
10669 		}
10670 
10671 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
10672 		    desc->dofa_uarg, arg);
10673 
10674 		if (last != NULL) {
10675 			last->dtad_next = act;
10676 		} else {
10677 			first = act;
10678 		}
10679 
10680 		last = act;
10681 
10682 		if (desc->dofa_difo == DOF_SECIDX_NONE)
10683 			continue;
10684 
10685 		if ((difosec = dtrace_dof_sect(dof,
10686 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
10687 			goto err;
10688 
10689 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
10690 
10691 		if (act->dtad_difo == NULL)
10692 			goto err;
10693 	}
10694 
10695 	ASSERT(first != NULL);
10696 	return (first);
10697 
10698 err:
10699 	for (act = first; act != NULL; act = next) {
10700 		next = act->dtad_next;
10701 		dtrace_actdesc_release(act, vstate);
10702 	}
10703 
10704 	return (NULL);
10705 }
10706 
10707 static dtrace_ecbdesc_t *
10708 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
10709     cred_t *cr)
10710 {
10711 	dtrace_ecbdesc_t *ep;
10712 	dof_ecbdesc_t *ecb;
10713 	dtrace_probedesc_t *desc;
10714 	dtrace_predicate_t *pred = NULL;
10715 
10716 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
10717 		dtrace_dof_error(dof, "truncated ECB description");
10718 		return (NULL);
10719 	}
10720 
10721 	if (sec->dofs_align != sizeof (uint64_t)) {
10722 		dtrace_dof_error(dof, "bad alignment in ECB description");
10723 		return (NULL);
10724 	}
10725 
10726 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
10727 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
10728 
10729 	if (sec == NULL)
10730 		return (NULL);
10731 
10732 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
10733 	ep->dted_uarg = ecb->dofe_uarg;
10734 	desc = &ep->dted_probe;
10735 
10736 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
10737 		goto err;
10738 
10739 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
10740 		if ((sec = dtrace_dof_sect(dof,
10741 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
10742 			goto err;
10743 
10744 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
10745 			goto err;
10746 
10747 		ep->dted_pred.dtpdd_predicate = pred;
10748 	}
10749 
10750 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
10751 		if ((sec = dtrace_dof_sect(dof,
10752 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
10753 			goto err;
10754 
10755 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
10756 
10757 		if (ep->dted_action == NULL)
10758 			goto err;
10759 	}
10760 
10761 	return (ep);
10762 
10763 err:
10764 	if (pred != NULL)
10765 		dtrace_predicate_release(pred, vstate);
10766 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
10767 	return (NULL);
10768 }
10769 
10770 /*
10771  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
10772  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
10773  * site of any user SETX relocations to account for load object base address.
10774  * In the future, if we need other relocations, this function can be extended.
10775  */
10776 static int
10777 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
10778 {
10779 	uintptr_t daddr = (uintptr_t)dof;
10780 	dof_relohdr_t *dofr =
10781 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
10782 	dof_sec_t *ss, *rs, *ts;
10783 	dof_relodesc_t *r;
10784 	uint_t i, n;
10785 
10786 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
10787 	    sec->dofs_align != sizeof (dof_secidx_t)) {
10788 		dtrace_dof_error(dof, "invalid relocation header");
10789 		return (-1);
10790 	}
10791 
10792 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
10793 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
10794 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
10795 
10796 	if (ss == NULL || rs == NULL || ts == NULL)
10797 		return (-1); /* dtrace_dof_error() has been called already */
10798 
10799 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
10800 	    rs->dofs_align != sizeof (uint64_t)) {
10801 		dtrace_dof_error(dof, "invalid relocation section");
10802 		return (-1);
10803 	}
10804 
10805 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
10806 	n = rs->dofs_size / rs->dofs_entsize;
10807 
10808 	for (i = 0; i < n; i++) {
10809 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
10810 
10811 		switch (r->dofr_type) {
10812 		case DOF_RELO_NONE:
10813 			break;
10814 		case DOF_RELO_SETX:
10815 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
10816 			    sizeof (uint64_t) > ts->dofs_size) {
10817 				dtrace_dof_error(dof, "bad relocation offset");
10818 				return (-1);
10819 			}
10820 
10821 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
10822 				dtrace_dof_error(dof, "misaligned setx relo");
10823 				return (-1);
10824 			}
10825 
10826 			*(uint64_t *)taddr += ubase;
10827 			break;
10828 		default:
10829 			dtrace_dof_error(dof, "invalid relocation type");
10830 			return (-1);
10831 		}
10832 
10833 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
10834 	}
10835 
10836 	return (0);
10837 }
10838 
10839 /*
10840  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
10841  * header:  it should be at the front of a memory region that is at least
10842  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
10843  * size.  It need not be validated in any other way.
10844  */
10845 static int
10846 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
10847     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
10848 {
10849 	uint64_t len = dof->dofh_loadsz, seclen;
10850 	uintptr_t daddr = (uintptr_t)dof;
10851 	dtrace_ecbdesc_t *ep;
10852 	dtrace_enabling_t *enab;
10853 	uint_t i;
10854 
10855 	ASSERT(MUTEX_HELD(&dtrace_lock));
10856 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
10857 
10858 	/*
10859 	 * Check the DOF header identification bytes.  In addition to checking
10860 	 * valid settings, we also verify that unused bits/bytes are zeroed so
10861 	 * we can use them later without fear of regressing existing binaries.
10862 	 */
10863 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
10864 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
10865 		dtrace_dof_error(dof, "DOF magic string mismatch");
10866 		return (-1);
10867 	}
10868 
10869 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
10870 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
10871 		dtrace_dof_error(dof, "DOF has invalid data model");
10872 		return (-1);
10873 	}
10874 
10875 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
10876 		dtrace_dof_error(dof, "DOF encoding mismatch");
10877 		return (-1);
10878 	}
10879 
10880 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
10881 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
10882 		dtrace_dof_error(dof, "DOF version mismatch");
10883 		return (-1);
10884 	}
10885 
10886 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
10887 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
10888 		return (-1);
10889 	}
10890 
10891 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
10892 		dtrace_dof_error(dof, "DOF uses too many integer registers");
10893 		return (-1);
10894 	}
10895 
10896 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
10897 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
10898 		return (-1);
10899 	}
10900 
10901 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
10902 		if (dof->dofh_ident[i] != 0) {
10903 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
10904 			return (-1);
10905 		}
10906 	}
10907 
10908 	if (dof->dofh_flags & ~DOF_FL_VALID) {
10909 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
10910 		return (-1);
10911 	}
10912 
10913 	if (dof->dofh_secsize == 0) {
10914 		dtrace_dof_error(dof, "zero section header size");
10915 		return (-1);
10916 	}
10917 
10918 	/*
10919 	 * Check that the section headers don't exceed the amount of DOF
10920 	 * data.  Note that we cast the section size and number of sections
10921 	 * to uint64_t's to prevent possible overflow in the multiplication.
10922 	 */
10923 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
10924 
10925 	if (dof->dofh_secoff > len || seclen > len ||
10926 	    dof->dofh_secoff + seclen > len) {
10927 		dtrace_dof_error(dof, "truncated section headers");
10928 		return (-1);
10929 	}
10930 
10931 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
10932 		dtrace_dof_error(dof, "misaligned section headers");
10933 		return (-1);
10934 	}
10935 
10936 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
10937 		dtrace_dof_error(dof, "misaligned section size");
10938 		return (-1);
10939 	}
10940 
10941 	/*
10942 	 * Take an initial pass through the section headers to be sure that
10943 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
10944 	 * set, do not permit sections relating to providers, probes, or args.
10945 	 */
10946 	for (i = 0; i < dof->dofh_secnum; i++) {
10947 		dof_sec_t *sec = (dof_sec_t *)(daddr +
10948 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
10949 
10950 		if (noprobes) {
10951 			switch (sec->dofs_type) {
10952 			case DOF_SECT_PROVIDER:
10953 			case DOF_SECT_PROBES:
10954 			case DOF_SECT_PRARGS:
10955 			case DOF_SECT_PROFFS:
10956 				dtrace_dof_error(dof, "illegal sections "
10957 				    "for enabling");
10958 				return (-1);
10959 			}
10960 		}
10961 
10962 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
10963 			continue; /* just ignore non-loadable sections */
10964 
10965 		if (sec->dofs_align & (sec->dofs_align - 1)) {
10966 			dtrace_dof_error(dof, "bad section alignment");
10967 			return (-1);
10968 		}
10969 
10970 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
10971 			dtrace_dof_error(dof, "misaligned section");
10972 			return (-1);
10973 		}
10974 
10975 		if (sec->dofs_offset > len || sec->dofs_size > len ||
10976 		    sec->dofs_offset + sec->dofs_size > len) {
10977 			dtrace_dof_error(dof, "corrupt section header");
10978 			return (-1);
10979 		}
10980 
10981 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
10982 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
10983 			dtrace_dof_error(dof, "non-terminating string table");
10984 			return (-1);
10985 		}
10986 	}
10987 
10988 	/*
10989 	 * Take a second pass through the sections and locate and perform any
10990 	 * relocations that are present.  We do this after the first pass to
10991 	 * be sure that all sections have had their headers validated.
10992 	 */
10993 	for (i = 0; i < dof->dofh_secnum; i++) {
10994 		dof_sec_t *sec = (dof_sec_t *)(daddr +
10995 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
10996 
10997 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
10998 			continue; /* skip sections that are not loadable */
10999 
11000 		switch (sec->dofs_type) {
11001 		case DOF_SECT_URELHDR:
11002 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
11003 				return (-1);
11004 			break;
11005 		}
11006 	}
11007 
11008 	if ((enab = *enabp) == NULL)
11009 		enab = *enabp = dtrace_enabling_create(vstate);
11010 
11011 	for (i = 0; i < dof->dofh_secnum; i++) {
11012 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11013 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11014 
11015 		if (sec->dofs_type != DOF_SECT_ECBDESC)
11016 			continue;
11017 
11018 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
11019 			dtrace_enabling_destroy(enab);
11020 			*enabp = NULL;
11021 			return (-1);
11022 		}
11023 
11024 		dtrace_enabling_add(enab, ep);
11025 	}
11026 
11027 	return (0);
11028 }
11029 
11030 /*
11031  * Process DOF for any options.  This routine assumes that the DOF has been
11032  * at least processed by dtrace_dof_slurp().
11033  */
11034 static int
11035 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
11036 {
11037 	int i, rval;
11038 	uint32_t entsize;
11039 	size_t offs;
11040 	dof_optdesc_t *desc;
11041 
11042 	for (i = 0; i < dof->dofh_secnum; i++) {
11043 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
11044 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11045 
11046 		if (sec->dofs_type != DOF_SECT_OPTDESC)
11047 			continue;
11048 
11049 		if (sec->dofs_align != sizeof (uint64_t)) {
11050 			dtrace_dof_error(dof, "bad alignment in "
11051 			    "option description");
11052 			return (EINVAL);
11053 		}
11054 
11055 		if ((entsize = sec->dofs_entsize) == 0) {
11056 			dtrace_dof_error(dof, "zeroed option entry size");
11057 			return (EINVAL);
11058 		}
11059 
11060 		if (entsize < sizeof (dof_optdesc_t)) {
11061 			dtrace_dof_error(dof, "bad option entry size");
11062 			return (EINVAL);
11063 		}
11064 
11065 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
11066 			desc = (dof_optdesc_t *)((uintptr_t)dof +
11067 			    (uintptr_t)sec->dofs_offset + offs);
11068 
11069 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
11070 				dtrace_dof_error(dof, "non-zero option string");
11071 				return (EINVAL);
11072 			}
11073 
11074 			if (desc->dofo_value == DTRACEOPT_UNSET) {
11075 				dtrace_dof_error(dof, "unset option");
11076 				return (EINVAL);
11077 			}
11078 
11079 			if ((rval = dtrace_state_option(state,
11080 			    desc->dofo_option, desc->dofo_value)) != 0) {
11081 				dtrace_dof_error(dof, "rejected option");
11082 				return (rval);
11083 			}
11084 		}
11085 	}
11086 
11087 	return (0);
11088 }
11089 
11090 /*
11091  * DTrace Consumer State Functions
11092  */
11093 int
11094 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
11095 {
11096 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
11097 	void *base;
11098 	uintptr_t limit;
11099 	dtrace_dynvar_t *dvar, *next, *start;
11100 	int i;
11101 
11102 	ASSERT(MUTEX_HELD(&dtrace_lock));
11103 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
11104 
11105 	bzero(dstate, sizeof (dtrace_dstate_t));
11106 
11107 	if ((dstate->dtds_chunksize = chunksize) == 0)
11108 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
11109 
11110 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
11111 		size = min;
11112 
11113 	if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11114 		return (ENOMEM);
11115 
11116 	dstate->dtds_size = size;
11117 	dstate->dtds_base = base;
11118 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
11119 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
11120 
11121 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
11122 
11123 	if (hashsize != 1 && (hashsize & 1))
11124 		hashsize--;
11125 
11126 	dstate->dtds_hashsize = hashsize;
11127 	dstate->dtds_hash = dstate->dtds_base;
11128 
11129 	/*
11130 	 * Set all of our hash buckets to point to the single sink, and (if
11131 	 * it hasn't already been set), set the sink's hash value to be the
11132 	 * sink sentinel value.  The sink is needed for dynamic variable
11133 	 * lookups to know that they have iterated over an entire, valid hash
11134 	 * chain.
11135 	 */
11136 	for (i = 0; i < hashsize; i++)
11137 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
11138 
11139 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
11140 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
11141 
11142 	/*
11143 	 * Determine number of active CPUs.  Divide free list evenly among
11144 	 * active CPUs.
11145 	 */
11146 	start = (dtrace_dynvar_t *)
11147 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
11148 	limit = (uintptr_t)base + size;
11149 
11150 	maxper = (limit - (uintptr_t)start) / NCPU;
11151 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
11152 
11153 	for (i = 0; i < NCPU; i++) {
11154 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
11155 
11156 		/*
11157 		 * If we don't even have enough chunks to make it once through
11158 		 * NCPUs, we're just going to allocate everything to the first
11159 		 * CPU.  And if we're on the last CPU, we're going to allocate
11160 		 * whatever is left over.  In either case, we set the limit to
11161 		 * be the limit of the dynamic variable space.
11162 		 */
11163 		if (maxper == 0 || i == NCPU - 1) {
11164 			limit = (uintptr_t)base + size;
11165 			start = NULL;
11166 		} else {
11167 			limit = (uintptr_t)start + maxper;
11168 			start = (dtrace_dynvar_t *)limit;
11169 		}
11170 
11171 		ASSERT(limit <= (uintptr_t)base + size);
11172 
11173 		for (;;) {
11174 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
11175 			    dstate->dtds_chunksize);
11176 
11177 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
11178 				break;
11179 
11180 			dvar->dtdv_next = next;
11181 			dvar = next;
11182 		}
11183 
11184 		if (maxper == 0)
11185 			break;
11186 	}
11187 
11188 	return (0);
11189 }
11190 
11191 void
11192 dtrace_dstate_fini(dtrace_dstate_t *dstate)
11193 {
11194 	ASSERT(MUTEX_HELD(&cpu_lock));
11195 
11196 	if (dstate->dtds_base == NULL)
11197 		return;
11198 
11199 	kmem_free(dstate->dtds_base, dstate->dtds_size);
11200 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
11201 }
11202 
11203 static void
11204 dtrace_vstate_fini(dtrace_vstate_t *vstate)
11205 {
11206 	/*
11207 	 * Logical XOR, where are you?
11208 	 */
11209 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
11210 
11211 	if (vstate->dtvs_nglobals > 0) {
11212 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
11213 		    sizeof (dtrace_statvar_t *));
11214 	}
11215 
11216 	if (vstate->dtvs_ntlocals > 0) {
11217 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
11218 		    sizeof (dtrace_difv_t));
11219 	}
11220 
11221 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
11222 
11223 	if (vstate->dtvs_nlocals > 0) {
11224 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
11225 		    sizeof (dtrace_statvar_t *));
11226 	}
11227 }
11228 
11229 static void
11230 dtrace_state_clean(dtrace_state_t *state)
11231 {
11232 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
11233 		return;
11234 
11235 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
11236 	dtrace_speculation_clean(state);
11237 }
11238 
11239 static void
11240 dtrace_state_deadman(dtrace_state_t *state)
11241 {
11242 	hrtime_t now;
11243 
11244 	dtrace_sync();
11245 
11246 	now = dtrace_gethrtime();
11247 
11248 	if (state != dtrace_anon.dta_state &&
11249 	    now - state->dts_laststatus >= dtrace_deadman_user)
11250 		return;
11251 
11252 	/*
11253 	 * We must be sure that dts_alive never appears to be less than the
11254 	 * value upon entry to dtrace_state_deadman(), and because we lack a
11255 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
11256 	 * store INT64_MAX to it, followed by a memory barrier, followed by
11257 	 * the new value.  This assures that dts_alive never appears to be
11258 	 * less than its true value, regardless of the order in which the
11259 	 * stores to the underlying storage are issued.
11260 	 */
11261 	state->dts_alive = INT64_MAX;
11262 	dtrace_membar_producer();
11263 	state->dts_alive = now;
11264 }
11265 
11266 dtrace_state_t *
11267 dtrace_state_create(dev_t *devp, cred_t *cr)
11268 {
11269 	minor_t minor;
11270 	major_t major;
11271 	char c[30];
11272 	dtrace_state_t *state;
11273 	dtrace_optval_t *opt;
11274 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
11275 
11276 	ASSERT(MUTEX_HELD(&dtrace_lock));
11277 	ASSERT(MUTEX_HELD(&cpu_lock));
11278 
11279 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
11280 	    VM_BESTFIT | VM_SLEEP);
11281 
11282 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
11283 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
11284 		return (NULL);
11285 	}
11286 
11287 	state = ddi_get_soft_state(dtrace_softstate, minor);
11288 	state->dts_epid = DTRACE_EPIDNONE + 1;
11289 
11290 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
11291 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
11292 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
11293 
11294 	if (devp != NULL) {
11295 		major = getemajor(*devp);
11296 	} else {
11297 		major = ddi_driver_major(dtrace_devi);
11298 	}
11299 
11300 	state->dts_dev = makedevice(major, minor);
11301 
11302 	if (devp != NULL)
11303 		*devp = state->dts_dev;
11304 
11305 	/*
11306 	 * We allocate NCPU buffers.  On the one hand, this can be quite
11307 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
11308 	 * other hand, it saves an additional memory reference in the probe
11309 	 * path.
11310 	 */
11311 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
11312 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
11313 	state->dts_cleaner = CYCLIC_NONE;
11314 	state->dts_deadman = CYCLIC_NONE;
11315 	state->dts_vstate.dtvs_state = state;
11316 
11317 	for (i = 0; i < DTRACEOPT_MAX; i++)
11318 		state->dts_options[i] = DTRACEOPT_UNSET;
11319 
11320 	/*
11321 	 * Set the default options.
11322 	 */
11323 	opt = state->dts_options;
11324 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
11325 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
11326 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
11327 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
11328 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
11329 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
11330 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
11331 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
11332 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
11333 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
11334 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
11335 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
11336 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
11337 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
11338 
11339 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
11340 
11341 	/*
11342 	 * Depending on the user credentials, we set flag bits which alter probe
11343 	 * visibility or the amount of destructiveness allowed.  In the case of
11344 	 * actual anonymous tracing, or the possession of all privileges, all of
11345 	 * the normal checks are bypassed.
11346 	 */
11347 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
11348 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
11349 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
11350 	} else {
11351 		/*
11352 		 * Set up the credentials for this instantiation.  We take a
11353 		 * hold on the credential to prevent it from disappearing on
11354 		 * us; this in turn prevents the zone_t referenced by this
11355 		 * credential from disappearing.  This means that we can
11356 		 * examine the credential and the zone from probe context.
11357 		 */
11358 		crhold(cr);
11359 		state->dts_cred.dcr_cred = cr;
11360 
11361 		/*
11362 		 * CRA_PROC means "we have *some* privilege for dtrace" and
11363 		 * unlocks the use of variables like pid, zonename, etc.
11364 		 */
11365 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
11366 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
11367 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
11368 		}
11369 
11370 		/*
11371 		 * dtrace_user allows use of syscall and profile providers.
11372 		 * If the user also has proc_owner and/or proc_zone, we
11373 		 * extend the scope to include additional visibility and
11374 		 * destructive power.
11375 		 */
11376 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
11377 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
11378 				state->dts_cred.dcr_visible |=
11379 				    DTRACE_CRV_ALLPROC;
11380 
11381 				state->dts_cred.dcr_action |=
11382 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
11383 			}
11384 
11385 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
11386 				state->dts_cred.dcr_visible |=
11387 				    DTRACE_CRV_ALLZONE;
11388 
11389 				state->dts_cred.dcr_action |=
11390 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
11391 			}
11392 
11393 			/*
11394 			 * If we have all privs in whatever zone this is,
11395 			 * we can do destructive things to processes which
11396 			 * have altered credentials.
11397 			 */
11398 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
11399 			    cr->cr_zone->zone_privset)) {
11400 				state->dts_cred.dcr_action |=
11401 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
11402 			}
11403 		}
11404 
11405 		/*
11406 		 * Holding the dtrace_kernel privilege also implies that
11407 		 * the user has the dtrace_user privilege from a visibility
11408 		 * perspective.  But without further privileges, some
11409 		 * destructive actions are not available.
11410 		 */
11411 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
11412 			/*
11413 			 * Make all probes in all zones visible.  However,
11414 			 * this doesn't mean that all actions become available
11415 			 * to all zones.
11416 			 */
11417 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
11418 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
11419 
11420 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
11421 			    DTRACE_CRA_PROC;
11422 			/*
11423 			 * Holding proc_owner means that destructive actions
11424 			 * for *this* zone are allowed.
11425 			 */
11426 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
11427 				state->dts_cred.dcr_action |=
11428 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
11429 
11430 			/*
11431 			 * Holding proc_zone means that destructive actions
11432 			 * for this user/group ID in all zones is allowed.
11433 			 */
11434 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
11435 				state->dts_cred.dcr_action |=
11436 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
11437 
11438 			/*
11439 			 * If we have all privs in whatever zone this is,
11440 			 * we can do destructive things to processes which
11441 			 * have altered credentials.
11442 			 */
11443 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
11444 			    cr->cr_zone->zone_privset)) {
11445 				state->dts_cred.dcr_action |=
11446 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
11447 			}
11448 		}
11449 
11450 		/*
11451 		 * Holding the dtrace_proc privilege gives control over fasttrap
11452 		 * and pid providers.  We need to grant wider destructive
11453 		 * privileges in the event that the user has proc_owner and/or
11454 		 * proc_zone.
11455 		 */
11456 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
11457 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
11458 				state->dts_cred.dcr_action |=
11459 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
11460 
11461 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
11462 				state->dts_cred.dcr_action |=
11463 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
11464 		}
11465 	}
11466 
11467 	return (state);
11468 }
11469 
11470 static int
11471 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
11472 {
11473 	dtrace_optval_t *opt = state->dts_options, size;
11474 	processorid_t cpu;
11475 	int flags = 0, rval;
11476 
11477 	ASSERT(MUTEX_HELD(&dtrace_lock));
11478 	ASSERT(MUTEX_HELD(&cpu_lock));
11479 	ASSERT(which < DTRACEOPT_MAX);
11480 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
11481 	    (state == dtrace_anon.dta_state &&
11482 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
11483 
11484 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
11485 		return (0);
11486 
11487 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
11488 		cpu = opt[DTRACEOPT_CPU];
11489 
11490 	if (which == DTRACEOPT_SPECSIZE)
11491 		flags |= DTRACEBUF_NOSWITCH;
11492 
11493 	if (which == DTRACEOPT_BUFSIZE) {
11494 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
11495 			flags |= DTRACEBUF_RING;
11496 
11497 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
11498 			flags |= DTRACEBUF_FILL;
11499 
11500 		if (state != dtrace_anon.dta_state ||
11501 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
11502 			flags |= DTRACEBUF_INACTIVE;
11503 	}
11504 
11505 	for (size = opt[which]; size >= sizeof (uint64_t); size >>= 1) {
11506 		/*
11507 		 * The size must be 8-byte aligned.  If the size is not 8-byte
11508 		 * aligned, drop it down by the difference.
11509 		 */
11510 		if (size & (sizeof (uint64_t) - 1))
11511 			size -= size & (sizeof (uint64_t) - 1);
11512 
11513 		if (size < state->dts_reserve) {
11514 			/*
11515 			 * Buffers always must be large enough to accommodate
11516 			 * their prereserved space.  We return E2BIG instead
11517 			 * of ENOMEM in this case to allow for user-level
11518 			 * software to differentiate the cases.
11519 			 */
11520 			return (E2BIG);
11521 		}
11522 
11523 		rval = dtrace_buffer_alloc(buf, size, flags, cpu);
11524 
11525 		if (rval != ENOMEM) {
11526 			opt[which] = size;
11527 			return (rval);
11528 		}
11529 
11530 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
11531 			return (rval);
11532 	}
11533 
11534 	return (ENOMEM);
11535 }
11536 
11537 static int
11538 dtrace_state_buffers(dtrace_state_t *state)
11539 {
11540 	dtrace_speculation_t *spec = state->dts_speculations;
11541 	int rval, i;
11542 
11543 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
11544 	    DTRACEOPT_BUFSIZE)) != 0)
11545 		return (rval);
11546 
11547 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
11548 	    DTRACEOPT_AGGSIZE)) != 0)
11549 		return (rval);
11550 
11551 	for (i = 0; i < state->dts_nspeculations; i++) {
11552 		if ((rval = dtrace_state_buffer(state,
11553 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
11554 			return (rval);
11555 	}
11556 
11557 	return (0);
11558 }
11559 
11560 static void
11561 dtrace_state_prereserve(dtrace_state_t *state)
11562 {
11563 	dtrace_ecb_t *ecb;
11564 	dtrace_probe_t *probe;
11565 
11566 	state->dts_reserve = 0;
11567 
11568 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
11569 		return;
11570 
11571 	/*
11572 	 * If our buffer policy is a "fill" buffer policy, we need to set the
11573 	 * prereserved space to be the space required by the END probes.
11574 	 */
11575 	probe = dtrace_probes[dtrace_probeid_end - 1];
11576 	ASSERT(probe != NULL);
11577 
11578 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
11579 		if (ecb->dte_state != state)
11580 			continue;
11581 
11582 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
11583 	}
11584 }
11585 
11586 static int
11587 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
11588 {
11589 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
11590 	dtrace_speculation_t *spec;
11591 	dtrace_buffer_t *buf;
11592 	cyc_handler_t hdlr;
11593 	cyc_time_t when;
11594 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
11595 	dtrace_icookie_t cookie;
11596 
11597 	mutex_enter(&cpu_lock);
11598 	mutex_enter(&dtrace_lock);
11599 
11600 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
11601 		rval = EBUSY;
11602 		goto out;
11603 	}
11604 
11605 	/*
11606 	 * Before we can perform any checks, we must prime all of the
11607 	 * retained enablings that correspond to this state.
11608 	 */
11609 	dtrace_enabling_prime(state);
11610 
11611 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
11612 		rval = EACCES;
11613 		goto out;
11614 	}
11615 
11616 	dtrace_state_prereserve(state);
11617 
11618 	/*
11619 	 * Now we want to do is try to allocate our speculations.
11620 	 * We do not automatically resize the number of speculations; if
11621 	 * this fails, we will fail the operation.
11622 	 */
11623 	nspec = opt[DTRACEOPT_NSPEC];
11624 	ASSERT(nspec != DTRACEOPT_UNSET);
11625 
11626 	if (nspec > INT_MAX) {
11627 		rval = ENOMEM;
11628 		goto out;
11629 	}
11630 
11631 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
11632 
11633 	if (spec == NULL) {
11634 		rval = ENOMEM;
11635 		goto out;
11636 	}
11637 
11638 	state->dts_speculations = spec;
11639 	state->dts_nspeculations = (int)nspec;
11640 
11641 	for (i = 0; i < nspec; i++) {
11642 		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
11643 			rval = ENOMEM;
11644 			goto err;
11645 		}
11646 
11647 		spec[i].dtsp_buffer = buf;
11648 	}
11649 
11650 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
11651 		if (dtrace_anon.dta_state == NULL) {
11652 			rval = ENOENT;
11653 			goto out;
11654 		}
11655 
11656 		if (state->dts_necbs != 0) {
11657 			rval = EALREADY;
11658 			goto out;
11659 		}
11660 
11661 		state->dts_anon = dtrace_anon_grab();
11662 		ASSERT(state->dts_anon != NULL);
11663 		state = state->dts_anon;
11664 
11665 		/*
11666 		 * We want "grabanon" to be set in the grabbed state, so we'll
11667 		 * copy that option value from the grabbing state into the
11668 		 * grabbed state.
11669 		 */
11670 		state->dts_options[DTRACEOPT_GRABANON] =
11671 		    opt[DTRACEOPT_GRABANON];
11672 
11673 		*cpu = dtrace_anon.dta_beganon;
11674 
11675 		/*
11676 		 * If the anonymous state is active (as it almost certainly
11677 		 * is if the anonymous enabling ultimately matched anything),
11678 		 * we don't allow any further option processing -- but we
11679 		 * don't return failure.
11680 		 */
11681 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11682 			goto out;
11683 	}
11684 
11685 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
11686 	    opt[DTRACEOPT_AGGSIZE] != 0) {
11687 		if (state->dts_aggregations == NULL) {
11688 			/*
11689 			 * We're not going to create an aggregation buffer
11690 			 * because we don't have any ECBs that contain
11691 			 * aggregations -- set this option to 0.
11692 			 */
11693 			opt[DTRACEOPT_AGGSIZE] = 0;
11694 		} else {
11695 			/*
11696 			 * If we have an aggregation buffer, we must also have
11697 			 * a buffer to use as scratch.
11698 			 */
11699 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
11700 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
11701 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
11702 			}
11703 		}
11704 	}
11705 
11706 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
11707 	    opt[DTRACEOPT_SPECSIZE] != 0) {
11708 		if (!state->dts_speculates) {
11709 			/*
11710 			 * We're not going to create speculation buffers
11711 			 * because we don't have any ECBs that actually
11712 			 * speculate -- set the speculation size to 0.
11713 			 */
11714 			opt[DTRACEOPT_SPECSIZE] = 0;
11715 		}
11716 	}
11717 
11718 	/*
11719 	 * The bare minimum size for any buffer that we're actually going to
11720 	 * do anything to is sizeof (uint64_t).
11721 	 */
11722 	sz = sizeof (uint64_t);
11723 
11724 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
11725 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
11726 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
11727 		/*
11728 		 * A buffer size has been explicitly set to 0 (or to a size
11729 		 * that will be adjusted to 0) and we need the space -- we
11730 		 * need to return failure.  We return ENOSPC to differentiate
11731 		 * it from failing to allocate a buffer due to failure to meet
11732 		 * the reserve (for which we return E2BIG).
11733 		 */
11734 		rval = ENOSPC;
11735 		goto out;
11736 	}
11737 
11738 	if ((rval = dtrace_state_buffers(state)) != 0)
11739 		goto err;
11740 
11741 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
11742 		sz = dtrace_dstate_defsize;
11743 
11744 	do {
11745 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
11746 
11747 		if (rval == 0)
11748 			break;
11749 
11750 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
11751 			goto err;
11752 	} while (sz >>= 1);
11753 
11754 	opt[DTRACEOPT_DYNVARSIZE] = sz;
11755 
11756 	if (rval != 0)
11757 		goto err;
11758 
11759 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
11760 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
11761 
11762 	if (opt[DTRACEOPT_CLEANRATE] == 0)
11763 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
11764 
11765 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
11766 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
11767 
11768 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
11769 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
11770 
11771 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
11772 	hdlr.cyh_arg = state;
11773 	hdlr.cyh_level = CY_LOW_LEVEL;
11774 
11775 	when.cyt_when = 0;
11776 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
11777 
11778 	state->dts_cleaner = cyclic_add(&hdlr, &when);
11779 
11780 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
11781 	hdlr.cyh_arg = state;
11782 	hdlr.cyh_level = CY_LOW_LEVEL;
11783 
11784 	when.cyt_when = 0;
11785 	when.cyt_interval = dtrace_deadman_interval;
11786 
11787 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
11788 	state->dts_deadman = cyclic_add(&hdlr, &when);
11789 
11790 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
11791 
11792 	/*
11793 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
11794 	 * interrupts here both to record the CPU on which we fired the BEGIN
11795 	 * probe (the data from this CPU will be processed first at user
11796 	 * level) and to manually activate the buffer for this CPU.
11797 	 */
11798 	cookie = dtrace_interrupt_disable();
11799 	*cpu = CPU->cpu_id;
11800 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
11801 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
11802 
11803 	dtrace_probe(dtrace_probeid_begin,
11804 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
11805 	dtrace_interrupt_enable(cookie);
11806 	/*
11807 	 * We may have had an exit action from a BEGIN probe; only change our
11808 	 * state to ACTIVE if we're still in WARMUP.
11809 	 */
11810 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
11811 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
11812 
11813 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
11814 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
11815 
11816 	/*
11817 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
11818 	 * want each CPU to transition its principal buffer out of the
11819 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
11820 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
11821 	 * atomically transition from processing none of a state's ECBs to
11822 	 * processing all of them.
11823 	 */
11824 	dtrace_xcall(DTRACE_CPUALL,
11825 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
11826 	goto out;
11827 
11828 err:
11829 	dtrace_buffer_free(state->dts_buffer);
11830 	dtrace_buffer_free(state->dts_aggbuffer);
11831 
11832 	if ((nspec = state->dts_nspeculations) == 0) {
11833 		ASSERT(state->dts_speculations == NULL);
11834 		goto out;
11835 	}
11836 
11837 	spec = state->dts_speculations;
11838 	ASSERT(spec != NULL);
11839 
11840 	for (i = 0; i < state->dts_nspeculations; i++) {
11841 		if ((buf = spec[i].dtsp_buffer) == NULL)
11842 			break;
11843 
11844 		dtrace_buffer_free(buf);
11845 		kmem_free(buf, bufsize);
11846 	}
11847 
11848 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
11849 	state->dts_nspeculations = 0;
11850 	state->dts_speculations = NULL;
11851 
11852 out:
11853 	mutex_exit(&dtrace_lock);
11854 	mutex_exit(&cpu_lock);
11855 
11856 	return (rval);
11857 }
11858 
11859 static int
11860 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
11861 {
11862 	dtrace_icookie_t cookie;
11863 
11864 	ASSERT(MUTEX_HELD(&dtrace_lock));
11865 
11866 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
11867 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
11868 		return (EINVAL);
11869 
11870 	/*
11871 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
11872 	 * to be sure that every CPU has seen it.  See below for the details
11873 	 * on why this is done.
11874 	 */
11875 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
11876 	dtrace_sync();
11877 
11878 	/*
11879 	 * By this point, it is impossible for any CPU to be still processing
11880 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
11881 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
11882 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
11883 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
11884 	 * iff we're in the END probe.
11885 	 */
11886 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
11887 	dtrace_sync();
11888 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
11889 
11890 	/*
11891 	 * Finally, we can release the reserve and call the END probe.  We
11892 	 * disable interrupts across calling the END probe to allow us to
11893 	 * return the CPU on which we actually called the END probe.  This
11894 	 * allows user-land to be sure that this CPU's principal buffer is
11895 	 * processed last.
11896 	 */
11897 	state->dts_reserve = 0;
11898 
11899 	cookie = dtrace_interrupt_disable();
11900 	*cpu = CPU->cpu_id;
11901 	dtrace_probe(dtrace_probeid_end,
11902 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
11903 	dtrace_interrupt_enable(cookie);
11904 
11905 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
11906 	dtrace_sync();
11907 
11908 	return (0);
11909 }
11910 
11911 static int
11912 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
11913     dtrace_optval_t val)
11914 {
11915 	ASSERT(MUTEX_HELD(&dtrace_lock));
11916 
11917 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
11918 		return (EBUSY);
11919 
11920 	if (option >= DTRACEOPT_MAX)
11921 		return (EINVAL);
11922 
11923 	if (option != DTRACEOPT_CPU && val < 0)
11924 		return (EINVAL);
11925 
11926 	switch (option) {
11927 	case DTRACEOPT_DESTRUCTIVE:
11928 		if (dtrace_destructive_disallow)
11929 			return (EACCES);
11930 
11931 		state->dts_cred.dcr_destructive = 1;
11932 		break;
11933 
11934 	case DTRACEOPT_BUFSIZE:
11935 	case DTRACEOPT_DYNVARSIZE:
11936 	case DTRACEOPT_AGGSIZE:
11937 	case DTRACEOPT_SPECSIZE:
11938 	case DTRACEOPT_STRSIZE:
11939 		if (val < 0)
11940 			return (EINVAL);
11941 
11942 		if (val >= LONG_MAX) {
11943 			/*
11944 			 * If this is an otherwise negative value, set it to
11945 			 * the highest multiple of 128m less than LONG_MAX.
11946 			 * Technically, we're adjusting the size without
11947 			 * regard to the buffer resizing policy, but in fact,
11948 			 * this has no effect -- if we set the buffer size to
11949 			 * ~LONG_MAX and the buffer policy is ultimately set to
11950 			 * be "manual", the buffer allocation is guaranteed to
11951 			 * fail, if only because the allocation requires two
11952 			 * buffers.  (We set the the size to the highest
11953 			 * multiple of 128m because it ensures that the size
11954 			 * will remain a multiple of a megabyte when
11955 			 * repeatedly halved -- all the way down to 15m.)
11956 			 */
11957 			val = LONG_MAX - (1 << 27) + 1;
11958 		}
11959 	}
11960 
11961 	state->dts_options[option] = val;
11962 
11963 	return (0);
11964 }
11965 
11966 static void
11967 dtrace_state_destroy(dtrace_state_t *state)
11968 {
11969 	dtrace_ecb_t *ecb;
11970 	dtrace_vstate_t *vstate = &state->dts_vstate;
11971 	minor_t minor = getminor(state->dts_dev);
11972 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
11973 	dtrace_speculation_t *spec = state->dts_speculations;
11974 	int nspec = state->dts_nspeculations;
11975 	uint32_t match;
11976 
11977 	ASSERT(MUTEX_HELD(&dtrace_lock));
11978 	ASSERT(MUTEX_HELD(&cpu_lock));
11979 
11980 	/*
11981 	 * First, retract any retained enablings for this state.
11982 	 */
11983 	dtrace_enabling_retract(state);
11984 	ASSERT(state->dts_nretained == 0);
11985 
11986 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
11987 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
11988 		/*
11989 		 * We have managed to come into dtrace_state_destroy() on a
11990 		 * hot enabling -- almost certainly because of a disorderly
11991 		 * shutdown of a consumer.  (That is, a consumer that is
11992 		 * exiting without having called dtrace_stop().) In this case,
11993 		 * we're going to set our activity to be KILLED, and then
11994 		 * issue a sync to be sure that everyone is out of probe
11995 		 * context before we start blowing away ECBs.
11996 		 */
11997 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
11998 		dtrace_sync();
11999 	}
12000 
12001 	/*
12002 	 * Release the credential hold we took in dtrace_state_create().
12003 	 */
12004 	if (state->dts_cred.dcr_cred != NULL)
12005 		crfree(state->dts_cred.dcr_cred);
12006 
12007 	/*
12008 	 * Now we can safely disable and destroy any enabled probes.  Because
12009 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
12010 	 * (especially if they're all enabled), we take two passes through the
12011 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
12012 	 * in the second we disable whatever is left over.
12013 	 */
12014 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
12015 		for (i = 0; i < state->dts_necbs; i++) {
12016 			if ((ecb = state->dts_ecbs[i]) == NULL)
12017 				continue;
12018 
12019 			if (match && ecb->dte_probe != NULL) {
12020 				dtrace_probe_t *probe = ecb->dte_probe;
12021 				dtrace_provider_t *prov = probe->dtpr_provider;
12022 
12023 				if (!(prov->dtpv_priv.dtpp_flags & match))
12024 					continue;
12025 			}
12026 
12027 			dtrace_ecb_disable(ecb);
12028 			dtrace_ecb_destroy(ecb);
12029 		}
12030 
12031 		if (!match)
12032 			break;
12033 	}
12034 
12035 	/*
12036 	 * Before we free the buffers, perform one more sync to assure that
12037 	 * every CPU is out of probe context.
12038 	 */
12039 	dtrace_sync();
12040 
12041 	dtrace_buffer_free(state->dts_buffer);
12042 	dtrace_buffer_free(state->dts_aggbuffer);
12043 
12044 	for (i = 0; i < nspec; i++)
12045 		dtrace_buffer_free(spec[i].dtsp_buffer);
12046 
12047 	if (state->dts_cleaner != CYCLIC_NONE)
12048 		cyclic_remove(state->dts_cleaner);
12049 
12050 	if (state->dts_deadman != CYCLIC_NONE)
12051 		cyclic_remove(state->dts_deadman);
12052 
12053 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
12054 	dtrace_vstate_fini(vstate);
12055 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
12056 
12057 	if (state->dts_aggregations != NULL) {
12058 #ifdef DEBUG
12059 		for (i = 0; i < state->dts_naggregations; i++)
12060 			ASSERT(state->dts_aggregations[i] == NULL);
12061 #endif
12062 		ASSERT(state->dts_naggregations > 0);
12063 		kmem_free(state->dts_aggregations,
12064 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
12065 	}
12066 
12067 	kmem_free(state->dts_buffer, bufsize);
12068 	kmem_free(state->dts_aggbuffer, bufsize);
12069 
12070 	for (i = 0; i < nspec; i++)
12071 		kmem_free(spec[i].dtsp_buffer, bufsize);
12072 
12073 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
12074 
12075 	dtrace_format_destroy(state);
12076 
12077 	vmem_destroy(state->dts_aggid_arena);
12078 	ddi_soft_state_free(dtrace_softstate, minor);
12079 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12080 }
12081 
12082 /*
12083  * DTrace Anonymous Enabling Functions
12084  */
12085 static dtrace_state_t *
12086 dtrace_anon_grab(void)
12087 {
12088 	dtrace_state_t *state;
12089 
12090 	ASSERT(MUTEX_HELD(&dtrace_lock));
12091 
12092 	if ((state = dtrace_anon.dta_state) == NULL) {
12093 		ASSERT(dtrace_anon.dta_enabling == NULL);
12094 		return (NULL);
12095 	}
12096 
12097 	ASSERT(dtrace_anon.dta_enabling != NULL);
12098 	ASSERT(dtrace_retained != NULL);
12099 
12100 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
12101 	dtrace_anon.dta_enabling = NULL;
12102 	dtrace_anon.dta_state = NULL;
12103 
12104 	return (state);
12105 }
12106 
12107 static void
12108 dtrace_anon_property(void)
12109 {
12110 	int i, rv;
12111 	dtrace_state_t *state;
12112 	dof_hdr_t *dof;
12113 	char c[32];		/* enough for "dof-data-" + digits */
12114 
12115 	ASSERT(MUTEX_HELD(&dtrace_lock));
12116 	ASSERT(MUTEX_HELD(&cpu_lock));
12117 
12118 	for (i = 0; ; i++) {
12119 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
12120 
12121 		dtrace_err_verbose = 1;
12122 
12123 		if ((dof = dtrace_dof_property(c)) == NULL) {
12124 			dtrace_err_verbose = 0;
12125 			break;
12126 		}
12127 
12128 		/*
12129 		 * We want to create anonymous state, so we need to transition
12130 		 * the kernel debugger to indicate that DTrace is active.  If
12131 		 * this fails (e.g. because the debugger has modified text in
12132 		 * some way), we won't continue with the processing.
12133 		 */
12134 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
12135 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
12136 			    "enabling ignored.");
12137 			dtrace_dof_destroy(dof);
12138 			break;
12139 		}
12140 
12141 		/*
12142 		 * If we haven't allocated an anonymous state, we'll do so now.
12143 		 */
12144 		if ((state = dtrace_anon.dta_state) == NULL) {
12145 			state = dtrace_state_create(NULL, NULL);
12146 			dtrace_anon.dta_state = state;
12147 
12148 			if (state == NULL) {
12149 				/*
12150 				 * This basically shouldn't happen:  the only
12151 				 * failure mode from dtrace_state_create() is a
12152 				 * failure of ddi_soft_state_zalloc() that
12153 				 * itself should never happen.  Still, the
12154 				 * interface allows for a failure mode, and
12155 				 * we want to fail as gracefully as possible:
12156 				 * we'll emit an error message and cease
12157 				 * processing anonymous state in this case.
12158 				 */
12159 				cmn_err(CE_WARN, "failed to create "
12160 				    "anonymous state");
12161 				dtrace_dof_destroy(dof);
12162 				break;
12163 			}
12164 		}
12165 
12166 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
12167 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
12168 
12169 		if (rv == 0)
12170 			rv = dtrace_dof_options(dof, state);
12171 
12172 		dtrace_err_verbose = 0;
12173 		dtrace_dof_destroy(dof);
12174 
12175 		if (rv != 0) {
12176 			/*
12177 			 * This is malformed DOF; chuck any anonymous state
12178 			 * that we created.
12179 			 */
12180 			ASSERT(dtrace_anon.dta_enabling == NULL);
12181 			dtrace_state_destroy(state);
12182 			dtrace_anon.dta_state = NULL;
12183 			break;
12184 		}
12185 
12186 		ASSERT(dtrace_anon.dta_enabling != NULL);
12187 	}
12188 
12189 	if (dtrace_anon.dta_enabling != NULL) {
12190 		int rval;
12191 
12192 		/*
12193 		 * dtrace_enabling_retain() can only fail because we are
12194 		 * trying to retain more enablings than are allowed -- but
12195 		 * we only have one anonymous enabling, and we are guaranteed
12196 		 * to be allowed at least one retained enabling; we assert
12197 		 * that dtrace_enabling_retain() returns success.
12198 		 */
12199 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
12200 		ASSERT(rval == 0);
12201 
12202 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
12203 	}
12204 }
12205 
12206 /*
12207  * DTrace Helper Functions
12208  */
12209 static void
12210 dtrace_helper_trace(dtrace_helper_action_t *helper,
12211     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
12212 {
12213 	uint32_t size, next, nnext, i;
12214 	dtrace_helptrace_t *ent;
12215 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12216 
12217 	if (!dtrace_helptrace_enabled)
12218 		return;
12219 
12220 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
12221 
12222 	/*
12223 	 * What would a tracing framework be without its own tracing
12224 	 * framework?  (Well, a hell of a lot simpler, for starters...)
12225 	 */
12226 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
12227 	    sizeof (uint64_t) - sizeof (uint64_t);
12228 
12229 	/*
12230 	 * Iterate until we can allocate a slot in the trace buffer.
12231 	 */
12232 	do {
12233 		next = dtrace_helptrace_next;
12234 
12235 		if (next + size < dtrace_helptrace_bufsize) {
12236 			nnext = next + size;
12237 		} else {
12238 			nnext = size;
12239 		}
12240 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
12241 
12242 	/*
12243 	 * We have our slot; fill it in.
12244 	 */
12245 	if (nnext == size)
12246 		next = 0;
12247 
12248 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
12249 	ent->dtht_helper = helper;
12250 	ent->dtht_where = where;
12251 	ent->dtht_nlocals = vstate->dtvs_nlocals;
12252 
12253 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
12254 	    mstate->dtms_fltoffs : -1;
12255 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
12256 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
12257 
12258 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
12259 		dtrace_statvar_t *svar;
12260 
12261 		if ((svar = vstate->dtvs_locals[i]) == NULL)
12262 			continue;
12263 
12264 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
12265 		ent->dtht_locals[i] =
12266 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
12267 	}
12268 }
12269 
12270 static uint64_t
12271 dtrace_helper(int which, dtrace_mstate_t *mstate,
12272     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
12273 {
12274 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12275 	uint64_t sarg0 = mstate->dtms_arg[0];
12276 	uint64_t sarg1 = mstate->dtms_arg[1];
12277 	uint64_t rval;
12278 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
12279 	dtrace_helper_action_t *helper;
12280 	dtrace_vstate_t *vstate;
12281 	dtrace_difo_t *pred;
12282 	int i, trace = dtrace_helptrace_enabled;
12283 
12284 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
12285 
12286 	if (helpers == NULL)
12287 		return (0);
12288 
12289 	if ((helper = helpers->dthps_actions[which]) == NULL)
12290 		return (0);
12291 
12292 	vstate = &helpers->dthps_vstate;
12293 	mstate->dtms_arg[0] = arg0;
12294 	mstate->dtms_arg[1] = arg1;
12295 
12296 	/*
12297 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
12298 	 * we'll call the corresponding actions.  Note that the below calls
12299 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
12300 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
12301 	 * the stored DIF offset with its own (which is the desired behavior).
12302 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
12303 	 * from machine state; this is okay, too.
12304 	 */
12305 	for (; helper != NULL; helper = helper->dtha_next) {
12306 		if ((pred = helper->dtha_predicate) != NULL) {
12307 			if (trace)
12308 				dtrace_helper_trace(helper, mstate, vstate, 0);
12309 
12310 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
12311 				goto next;
12312 
12313 			if (*flags & CPU_DTRACE_FAULT)
12314 				goto err;
12315 		}
12316 
12317 		for (i = 0; i < helper->dtha_nactions; i++) {
12318 			if (trace)
12319 				dtrace_helper_trace(helper,
12320 				    mstate, vstate, i + 1);
12321 
12322 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
12323 			    mstate, vstate, state);
12324 
12325 			if (*flags & CPU_DTRACE_FAULT)
12326 				goto err;
12327 		}
12328 
12329 next:
12330 		if (trace)
12331 			dtrace_helper_trace(helper, mstate, vstate,
12332 			    DTRACE_HELPTRACE_NEXT);
12333 	}
12334 
12335 	if (trace)
12336 		dtrace_helper_trace(helper, mstate, vstate,
12337 		    DTRACE_HELPTRACE_DONE);
12338 
12339 	/*
12340 	 * Restore the arg0 that we saved upon entry.
12341 	 */
12342 	mstate->dtms_arg[0] = sarg0;
12343 	mstate->dtms_arg[1] = sarg1;
12344 
12345 	return (rval);
12346 
12347 err:
12348 	if (trace)
12349 		dtrace_helper_trace(helper, mstate, vstate,
12350 		    DTRACE_HELPTRACE_ERR);
12351 
12352 	/*
12353 	 * Restore the arg0 that we saved upon entry.
12354 	 */
12355 	mstate->dtms_arg[0] = sarg0;
12356 	mstate->dtms_arg[1] = sarg1;
12357 
12358 	return (NULL);
12359 }
12360 
12361 static void
12362 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
12363     dtrace_vstate_t *vstate)
12364 {
12365 	int i;
12366 
12367 	if (helper->dtha_predicate != NULL)
12368 		dtrace_difo_release(helper->dtha_predicate, vstate);
12369 
12370 	for (i = 0; i < helper->dtha_nactions; i++) {
12371 		ASSERT(helper->dtha_actions[i] != NULL);
12372 		dtrace_difo_release(helper->dtha_actions[i], vstate);
12373 	}
12374 
12375 	kmem_free(helper->dtha_actions,
12376 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
12377 	kmem_free(helper, sizeof (dtrace_helper_action_t));
12378 }
12379 
12380 static int
12381 dtrace_helper_destroygen(int gen)
12382 {
12383 	proc_t *p = curproc;
12384 	dtrace_helpers_t *help = p->p_dtrace_helpers;
12385 	dtrace_vstate_t *vstate;
12386 	int i;
12387 
12388 	ASSERT(MUTEX_HELD(&dtrace_lock));
12389 
12390 	if (help == NULL || gen > help->dthps_generation)
12391 		return (EINVAL);
12392 
12393 	vstate = &help->dthps_vstate;
12394 
12395 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
12396 		dtrace_helper_action_t *last = NULL, *h, *next;
12397 
12398 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
12399 			next = h->dtha_next;
12400 
12401 			if (h->dtha_generation == gen) {
12402 				if (last != NULL) {
12403 					last->dtha_next = next;
12404 				} else {
12405 					help->dthps_actions[i] = next;
12406 				}
12407 
12408 				dtrace_helper_action_destroy(h, vstate);
12409 			} else {
12410 				last = h;
12411 			}
12412 		}
12413 	}
12414 
12415 	/*
12416 	 * Interate until we've cleared out all helper providers with the
12417 	 * given generation number.
12418 	 */
12419 	for (;;) {
12420 		dtrace_helper_provider_t *prov;
12421 
12422 		/*
12423 		 * Look for a helper provider with the right generation. We
12424 		 * have to start back at the beginning of the list each time
12425 		 * because we drop dtrace_lock. It's unlikely that we'll make
12426 		 * more than two passes.
12427 		 */
12428 		for (i = 0; i < help->dthps_nprovs; i++) {
12429 			prov = help->dthps_provs[i];
12430 
12431 			if (prov->dthp_generation == gen)
12432 				break;
12433 		}
12434 
12435 		/*
12436 		 * If there were no matches, we're done.
12437 		 */
12438 		if (i == help->dthps_nprovs)
12439 			break;
12440 
12441 		/*
12442 		 * Move the last helper provider into this slot.
12443 		 */
12444 		help->dthps_nprovs--;
12445 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
12446 		help->dthps_provs[help->dthps_nprovs] = NULL;
12447 
12448 		mutex_exit(&dtrace_lock);
12449 
12450 		/*
12451 		 * If we have a meta provider, remove this helper provider.
12452 		 */
12453 		mutex_enter(&dtrace_meta_lock);
12454 		if (dtrace_meta_pid != NULL) {
12455 			ASSERT(dtrace_deferred_pid == NULL);
12456 			dtrace_helper_provider_remove(&prov->dthp_prov,
12457 			    p->p_pid);
12458 		}
12459 		mutex_exit(&dtrace_meta_lock);
12460 
12461 		dtrace_helper_provider_destroy(prov);
12462 
12463 		mutex_enter(&dtrace_lock);
12464 	}
12465 
12466 	return (0);
12467 }
12468 
12469 static int
12470 dtrace_helper_validate(dtrace_helper_action_t *helper)
12471 {
12472 	int err = 0, i;
12473 	dtrace_difo_t *dp;
12474 
12475 	if ((dp = helper->dtha_predicate) != NULL)
12476 		err += dtrace_difo_validate_helper(dp);
12477 
12478 	for (i = 0; i < helper->dtha_nactions; i++)
12479 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
12480 
12481 	return (err == 0);
12482 }
12483 
12484 static int
12485 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
12486 {
12487 	dtrace_helpers_t *help;
12488 	dtrace_helper_action_t *helper, *last;
12489 	dtrace_actdesc_t *act;
12490 	dtrace_vstate_t *vstate;
12491 	dtrace_predicate_t *pred;
12492 	int count = 0, nactions = 0, i;
12493 
12494 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
12495 		return (EINVAL);
12496 
12497 	help = curproc->p_dtrace_helpers;
12498 	last = help->dthps_actions[which];
12499 	vstate = &help->dthps_vstate;
12500 
12501 	for (count = 0; last != NULL; last = last->dtha_next) {
12502 		count++;
12503 		if (last->dtha_next == NULL)
12504 			break;
12505 	}
12506 
12507 	/*
12508 	 * If we already have dtrace_helper_actions_max helper actions for this
12509 	 * helper action type, we'll refuse to add a new one.
12510 	 */
12511 	if (count >= dtrace_helper_actions_max)
12512 		return (ENOSPC);
12513 
12514 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
12515 	helper->dtha_generation = help->dthps_generation;
12516 
12517 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
12518 		ASSERT(pred->dtp_difo != NULL);
12519 		dtrace_difo_hold(pred->dtp_difo);
12520 		helper->dtha_predicate = pred->dtp_difo;
12521 	}
12522 
12523 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
12524 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
12525 			goto err;
12526 
12527 		if (act->dtad_difo == NULL)
12528 			goto err;
12529 
12530 		nactions++;
12531 	}
12532 
12533 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
12534 	    (helper->dtha_nactions = nactions), KM_SLEEP);
12535 
12536 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
12537 		dtrace_difo_hold(act->dtad_difo);
12538 		helper->dtha_actions[i++] = act->dtad_difo;
12539 	}
12540 
12541 	if (!dtrace_helper_validate(helper))
12542 		goto err;
12543 
12544 	if (last == NULL) {
12545 		help->dthps_actions[which] = helper;
12546 	} else {
12547 		last->dtha_next = helper;
12548 	}
12549 
12550 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
12551 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
12552 		dtrace_helptrace_next = 0;
12553 	}
12554 
12555 	return (0);
12556 err:
12557 	dtrace_helper_action_destroy(helper, vstate);
12558 	return (EINVAL);
12559 }
12560 
12561 static void
12562 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
12563     dof_helper_t *dofhp)
12564 {
12565 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
12566 
12567 	mutex_enter(&dtrace_meta_lock);
12568 	mutex_enter(&dtrace_lock);
12569 
12570 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
12571 		/*
12572 		 * If the dtrace module is loaded but not attached, or if
12573 		 * there aren't isn't a meta provider registered to deal with
12574 		 * these provider descriptions, we need to postpone creating
12575 		 * the actual providers until later.
12576 		 */
12577 
12578 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
12579 		    dtrace_deferred_pid != help) {
12580 			help->dthps_deferred = 1;
12581 			help->dthps_pid = p->p_pid;
12582 			help->dthps_next = dtrace_deferred_pid;
12583 			help->dthps_prev = NULL;
12584 			if (dtrace_deferred_pid != NULL)
12585 				dtrace_deferred_pid->dthps_prev = help;
12586 			dtrace_deferred_pid = help;
12587 		}
12588 
12589 		mutex_exit(&dtrace_lock);
12590 
12591 	} else if (dofhp != NULL) {
12592 		/*
12593 		 * If the dtrace module is loaded and we have a particular
12594 		 * helper provider description, pass that off to the
12595 		 * meta provider.
12596 		 */
12597 
12598 		mutex_exit(&dtrace_lock);
12599 
12600 		dtrace_helper_provide(dofhp, p->p_pid);
12601 
12602 	} else {
12603 		/*
12604 		 * Otherwise, just pass all the helper provider descriptions
12605 		 * off to the meta provider.
12606 		 */
12607 
12608 		int i;
12609 		mutex_exit(&dtrace_lock);
12610 
12611 		for (i = 0; i < help->dthps_nprovs; i++) {
12612 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
12613 			    p->p_pid);
12614 		}
12615 	}
12616 
12617 	mutex_exit(&dtrace_meta_lock);
12618 }
12619 
12620 static int
12621 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
12622 {
12623 	dtrace_helpers_t *help;
12624 	dtrace_helper_provider_t *hprov, **tmp_provs;
12625 	uint_t tmp_maxprovs, i;
12626 
12627 	ASSERT(MUTEX_HELD(&dtrace_lock));
12628 
12629 	help = curproc->p_dtrace_helpers;
12630 	ASSERT(help != NULL);
12631 
12632 	/*
12633 	 * If we already have dtrace_helper_providers_max helper providers,
12634 	 * we're refuse to add a new one.
12635 	 */
12636 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
12637 		return (ENOSPC);
12638 
12639 	/*
12640 	 * Check to make sure this isn't a duplicate.
12641 	 */
12642 	for (i = 0; i < help->dthps_nprovs; i++) {
12643 		if (dofhp->dofhp_addr ==
12644 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
12645 			return (EALREADY);
12646 	}
12647 
12648 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
12649 	hprov->dthp_prov = *dofhp;
12650 	hprov->dthp_ref = 1;
12651 	hprov->dthp_generation = gen;
12652 
12653 	/*
12654 	 * Allocate a bigger table for helper providers if it's already full.
12655 	 */
12656 	if (help->dthps_maxprovs == help->dthps_nprovs) {
12657 		tmp_maxprovs = help->dthps_maxprovs;
12658 		tmp_provs = help->dthps_provs;
12659 
12660 		if (help->dthps_maxprovs == 0)
12661 			help->dthps_maxprovs = 2;
12662 		else
12663 			help->dthps_maxprovs *= 2;
12664 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
12665 			help->dthps_maxprovs = dtrace_helper_providers_max;
12666 
12667 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
12668 
12669 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
12670 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
12671 
12672 		if (tmp_provs != NULL) {
12673 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
12674 			    sizeof (dtrace_helper_provider_t *));
12675 			kmem_free(tmp_provs, tmp_maxprovs *
12676 			    sizeof (dtrace_helper_provider_t *));
12677 		}
12678 	}
12679 
12680 	help->dthps_provs[help->dthps_nprovs] = hprov;
12681 	help->dthps_nprovs++;
12682 
12683 	return (0);
12684 }
12685 
12686 static void
12687 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
12688 {
12689 	mutex_enter(&dtrace_lock);
12690 
12691 	if (--hprov->dthp_ref == 0) {
12692 		dof_hdr_t *dof;
12693 		mutex_exit(&dtrace_lock);
12694 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
12695 		dtrace_dof_destroy(dof);
12696 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
12697 	} else {
12698 		mutex_exit(&dtrace_lock);
12699 	}
12700 }
12701 
12702 static int
12703 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
12704 {
12705 	uintptr_t daddr = (uintptr_t)dof;
12706 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
12707 	dof_provider_t *provider;
12708 	dof_probe_t *probe;
12709 	uint8_t *arg;
12710 	char *strtab, *typestr;
12711 	dof_stridx_t typeidx;
12712 	size_t typesz;
12713 	uint_t nprobes, j, k;
12714 
12715 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
12716 
12717 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
12718 		dtrace_dof_error(dof, "misaligned section offset");
12719 		return (-1);
12720 	}
12721 
12722 	/*
12723 	 * The section needs to be large enough to contain the DOF provider
12724 	 * structure appropriate for the given version.
12725 	 */
12726 	if (sec->dofs_size <
12727 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
12728 	    offsetof(dof_provider_t, dofpv_prenoffs) :
12729 	    sizeof (dof_provider_t))) {
12730 		dtrace_dof_error(dof, "provider section too small");
12731 		return (-1);
12732 	}
12733 
12734 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
12735 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
12736 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
12737 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
12738 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
12739 
12740 	if (str_sec == NULL || prb_sec == NULL ||
12741 	    arg_sec == NULL || off_sec == NULL)
12742 		return (-1);
12743 
12744 	enoff_sec = NULL;
12745 
12746 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
12747 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
12748 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
12749 	    provider->dofpv_prenoffs)) == NULL)
12750 		return (-1);
12751 
12752 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
12753 
12754 	if (provider->dofpv_name >= str_sec->dofs_size ||
12755 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
12756 		dtrace_dof_error(dof, "invalid provider name");
12757 		return (-1);
12758 	}
12759 
12760 	if (prb_sec->dofs_entsize == 0 ||
12761 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
12762 		dtrace_dof_error(dof, "invalid entry size");
12763 		return (-1);
12764 	}
12765 
12766 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
12767 		dtrace_dof_error(dof, "misaligned entry size");
12768 		return (-1);
12769 	}
12770 
12771 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
12772 		dtrace_dof_error(dof, "invalid entry size");
12773 		return (-1);
12774 	}
12775 
12776 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
12777 		dtrace_dof_error(dof, "misaligned section offset");
12778 		return (-1);
12779 	}
12780 
12781 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
12782 		dtrace_dof_error(dof, "invalid entry size");
12783 		return (-1);
12784 	}
12785 
12786 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
12787 
12788 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
12789 
12790 	/*
12791 	 * Take a pass through the probes to check for errors.
12792 	 */
12793 	for (j = 0; j < nprobes; j++) {
12794 		probe = (dof_probe_t *)(uintptr_t)(daddr +
12795 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
12796 
12797 		if (probe->dofpr_func >= str_sec->dofs_size) {
12798 			dtrace_dof_error(dof, "invalid function name");
12799 			return (-1);
12800 		}
12801 
12802 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
12803 			dtrace_dof_error(dof, "function name too long");
12804 			return (-1);
12805 		}
12806 
12807 		if (probe->dofpr_name >= str_sec->dofs_size ||
12808 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
12809 			dtrace_dof_error(dof, "invalid probe name");
12810 			return (-1);
12811 		}
12812 
12813 		/*
12814 		 * The offset count must not wrap the index, and the offsets
12815 		 * must also not overflow the section's data.
12816 		 */
12817 		if (probe->dofpr_offidx + probe->dofpr_noffs <
12818 		    probe->dofpr_offidx ||
12819 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
12820 		    off_sec->dofs_entsize > off_sec->dofs_size) {
12821 			dtrace_dof_error(dof, "invalid probe offset");
12822 			return (-1);
12823 		}
12824 
12825 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
12826 			/*
12827 			 * If there's no is-enabled offset section, make sure
12828 			 * there aren't any is-enabled offsets. Otherwise
12829 			 * perform the same checks as for probe offsets
12830 			 * (immediately above).
12831 			 */
12832 			if (enoff_sec == NULL) {
12833 				if (probe->dofpr_enoffidx != 0 ||
12834 				    probe->dofpr_nenoffs != 0) {
12835 					dtrace_dof_error(dof, "is-enabled "
12836 					    "offsets with null section");
12837 					return (-1);
12838 				}
12839 			} else if (probe->dofpr_enoffidx +
12840 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
12841 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
12842 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
12843 				dtrace_dof_error(dof, "invalid is-enabled "
12844 				    "offset");
12845 				return (-1);
12846 			}
12847 
12848 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
12849 				dtrace_dof_error(dof, "zero probe and "
12850 				    "is-enabled offsets");
12851 				return (-1);
12852 			}
12853 		} else if (probe->dofpr_noffs == 0) {
12854 			dtrace_dof_error(dof, "zero probe offsets");
12855 			return (-1);
12856 		}
12857 
12858 		if (probe->dofpr_argidx + probe->dofpr_xargc <
12859 		    probe->dofpr_argidx ||
12860 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
12861 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
12862 			dtrace_dof_error(dof, "invalid args");
12863 			return (-1);
12864 		}
12865 
12866 		typeidx = probe->dofpr_nargv;
12867 		typestr = strtab + probe->dofpr_nargv;
12868 		for (k = 0; k < probe->dofpr_nargc; k++) {
12869 			if (typeidx >= str_sec->dofs_size) {
12870 				dtrace_dof_error(dof, "bad "
12871 				    "native argument type");
12872 				return (-1);
12873 			}
12874 
12875 			typesz = strlen(typestr) + 1;
12876 			if (typesz > DTRACE_ARGTYPELEN) {
12877 				dtrace_dof_error(dof, "native "
12878 				    "argument type too long");
12879 				return (-1);
12880 			}
12881 			typeidx += typesz;
12882 			typestr += typesz;
12883 		}
12884 
12885 		typeidx = probe->dofpr_xargv;
12886 		typestr = strtab + probe->dofpr_xargv;
12887 		for (k = 0; k < probe->dofpr_xargc; k++) {
12888 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
12889 				dtrace_dof_error(dof, "bad "
12890 				    "native argument index");
12891 				return (-1);
12892 			}
12893 
12894 			if (typeidx >= str_sec->dofs_size) {
12895 				dtrace_dof_error(dof, "bad "
12896 				    "translated argument type");
12897 				return (-1);
12898 			}
12899 
12900 			typesz = strlen(typestr) + 1;
12901 			if (typesz > DTRACE_ARGTYPELEN) {
12902 				dtrace_dof_error(dof, "translated argument "
12903 				    "type too long");
12904 				return (-1);
12905 			}
12906 
12907 			typeidx += typesz;
12908 			typestr += typesz;
12909 		}
12910 	}
12911 
12912 	return (0);
12913 }
12914 
12915 static int
12916 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
12917 {
12918 	dtrace_helpers_t *help;
12919 	dtrace_vstate_t *vstate;
12920 	dtrace_enabling_t *enab = NULL;
12921 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
12922 	uintptr_t daddr = (uintptr_t)dof;
12923 
12924 	ASSERT(MUTEX_HELD(&dtrace_lock));
12925 
12926 	if ((help = curproc->p_dtrace_helpers) == NULL)
12927 		help = dtrace_helpers_create(curproc);
12928 
12929 	vstate = &help->dthps_vstate;
12930 
12931 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
12932 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
12933 		dtrace_dof_destroy(dof);
12934 		return (rv);
12935 	}
12936 
12937 	/*
12938 	 * Look for helper providers and validate their descriptions.
12939 	 */
12940 	if (dhp != NULL) {
12941 		for (i = 0; i < dof->dofh_secnum; i++) {
12942 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
12943 			    dof->dofh_secoff + i * dof->dofh_secsize);
12944 
12945 			if (sec->dofs_type != DOF_SECT_PROVIDER)
12946 				continue;
12947 
12948 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
12949 				dtrace_enabling_destroy(enab);
12950 				dtrace_dof_destroy(dof);
12951 				return (-1);
12952 			}
12953 
12954 			nprovs++;
12955 		}
12956 	}
12957 
12958 	/*
12959 	 * Now we need to walk through the ECB descriptions in the enabling.
12960 	 */
12961 	for (i = 0; i < enab->dten_ndesc; i++) {
12962 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12963 		dtrace_probedesc_t *desc = &ep->dted_probe;
12964 
12965 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
12966 			continue;
12967 
12968 		if (strcmp(desc->dtpd_mod, "helper") != 0)
12969 			continue;
12970 
12971 		if (strcmp(desc->dtpd_func, "ustack") != 0)
12972 			continue;
12973 
12974 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
12975 		    ep)) != 0) {
12976 			/*
12977 			 * Adding this helper action failed -- we are now going
12978 			 * to rip out the entire generation and return failure.
12979 			 */
12980 			(void) dtrace_helper_destroygen(help->dthps_generation);
12981 			dtrace_enabling_destroy(enab);
12982 			dtrace_dof_destroy(dof);
12983 			return (-1);
12984 		}
12985 
12986 		nhelpers++;
12987 	}
12988 
12989 	if (nhelpers < enab->dten_ndesc)
12990 		dtrace_dof_error(dof, "unmatched helpers");
12991 
12992 	gen = help->dthps_generation++;
12993 	dtrace_enabling_destroy(enab);
12994 
12995 	if (dhp != NULL && nprovs > 0) {
12996 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
12997 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
12998 			mutex_exit(&dtrace_lock);
12999 			dtrace_helper_provider_register(curproc, help, dhp);
13000 			mutex_enter(&dtrace_lock);
13001 
13002 			destroy = 0;
13003 		}
13004 	}
13005 
13006 	if (destroy)
13007 		dtrace_dof_destroy(dof);
13008 
13009 	return (gen);
13010 }
13011 
13012 static dtrace_helpers_t *
13013 dtrace_helpers_create(proc_t *p)
13014 {
13015 	dtrace_helpers_t *help;
13016 
13017 	ASSERT(MUTEX_HELD(&dtrace_lock));
13018 	ASSERT(p->p_dtrace_helpers == NULL);
13019 
13020 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
13021 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
13022 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
13023 
13024 	p->p_dtrace_helpers = help;
13025 	dtrace_helpers++;
13026 
13027 	return (help);
13028 }
13029 
13030 static void
13031 dtrace_helpers_destroy(void)
13032 {
13033 	dtrace_helpers_t *help;
13034 	dtrace_vstate_t *vstate;
13035 	proc_t *p = curproc;
13036 	int i;
13037 
13038 	mutex_enter(&dtrace_lock);
13039 
13040 	ASSERT(p->p_dtrace_helpers != NULL);
13041 	ASSERT(dtrace_helpers > 0);
13042 
13043 	help = p->p_dtrace_helpers;
13044 	vstate = &help->dthps_vstate;
13045 
13046 	/*
13047 	 * We're now going to lose the help from this process.
13048 	 */
13049 	p->p_dtrace_helpers = NULL;
13050 	dtrace_sync();
13051 
13052 	/*
13053 	 * Destory the helper actions.
13054 	 */
13055 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13056 		dtrace_helper_action_t *h, *next;
13057 
13058 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13059 			next = h->dtha_next;
13060 			dtrace_helper_action_destroy(h, vstate);
13061 			h = next;
13062 		}
13063 	}
13064 
13065 	mutex_exit(&dtrace_lock);
13066 
13067 	/*
13068 	 * Destroy the helper providers.
13069 	 */
13070 	if (help->dthps_maxprovs > 0) {
13071 		mutex_enter(&dtrace_meta_lock);
13072 		if (dtrace_meta_pid != NULL) {
13073 			ASSERT(dtrace_deferred_pid == NULL);
13074 
13075 			for (i = 0; i < help->dthps_nprovs; i++) {
13076 				dtrace_helper_provider_remove(
13077 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
13078 			}
13079 		} else {
13080 			mutex_enter(&dtrace_lock);
13081 			ASSERT(help->dthps_deferred == 0 ||
13082 			    help->dthps_next != NULL ||
13083 			    help->dthps_prev != NULL ||
13084 			    help == dtrace_deferred_pid);
13085 
13086 			/*
13087 			 * Remove the helper from the deferred list.
13088 			 */
13089 			if (help->dthps_next != NULL)
13090 				help->dthps_next->dthps_prev = help->dthps_prev;
13091 			if (help->dthps_prev != NULL)
13092 				help->dthps_prev->dthps_next = help->dthps_next;
13093 			if (dtrace_deferred_pid == help) {
13094 				dtrace_deferred_pid = help->dthps_next;
13095 				ASSERT(help->dthps_prev == NULL);
13096 			}
13097 
13098 			mutex_exit(&dtrace_lock);
13099 		}
13100 
13101 		mutex_exit(&dtrace_meta_lock);
13102 
13103 		for (i = 0; i < help->dthps_nprovs; i++) {
13104 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
13105 		}
13106 
13107 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
13108 		    sizeof (dtrace_helper_provider_t *));
13109 	}
13110 
13111 	mutex_enter(&dtrace_lock);
13112 
13113 	dtrace_vstate_fini(&help->dthps_vstate);
13114 	kmem_free(help->dthps_actions,
13115 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
13116 	kmem_free(help, sizeof (dtrace_helpers_t));
13117 
13118 	--dtrace_helpers;
13119 	mutex_exit(&dtrace_lock);
13120 }
13121 
13122 static void
13123 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
13124 {
13125 	dtrace_helpers_t *help, *newhelp;
13126 	dtrace_helper_action_t *helper, *new, *last;
13127 	dtrace_difo_t *dp;
13128 	dtrace_vstate_t *vstate;
13129 	int i, j, sz, hasprovs = 0;
13130 
13131 	mutex_enter(&dtrace_lock);
13132 	ASSERT(from->p_dtrace_helpers != NULL);
13133 	ASSERT(dtrace_helpers > 0);
13134 
13135 	help = from->p_dtrace_helpers;
13136 	newhelp = dtrace_helpers_create(to);
13137 	ASSERT(to->p_dtrace_helpers != NULL);
13138 
13139 	newhelp->dthps_generation = help->dthps_generation;
13140 	vstate = &newhelp->dthps_vstate;
13141 
13142 	/*
13143 	 * Duplicate the helper actions.
13144 	 */
13145 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13146 		if ((helper = help->dthps_actions[i]) == NULL)
13147 			continue;
13148 
13149 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
13150 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
13151 			    KM_SLEEP);
13152 			new->dtha_generation = helper->dtha_generation;
13153 
13154 			if ((dp = helper->dtha_predicate) != NULL) {
13155 				dp = dtrace_difo_duplicate(dp, vstate);
13156 				new->dtha_predicate = dp;
13157 			}
13158 
13159 			new->dtha_nactions = helper->dtha_nactions;
13160 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
13161 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
13162 
13163 			for (j = 0; j < new->dtha_nactions; j++) {
13164 				dtrace_difo_t *dp = helper->dtha_actions[j];
13165 
13166 				ASSERT(dp != NULL);
13167 				dp = dtrace_difo_duplicate(dp, vstate);
13168 				new->dtha_actions[j] = dp;
13169 			}
13170 
13171 			if (last != NULL) {
13172 				last->dtha_next = new;
13173 			} else {
13174 				newhelp->dthps_actions[i] = new;
13175 			}
13176 
13177 			last = new;
13178 		}
13179 	}
13180 
13181 	/*
13182 	 * Duplicate the helper providers and register them with the
13183 	 * DTrace framework.
13184 	 */
13185 	if (help->dthps_nprovs > 0) {
13186 		newhelp->dthps_nprovs = help->dthps_nprovs;
13187 		newhelp->dthps_maxprovs = help->dthps_nprovs;
13188 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
13189 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13190 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
13191 			newhelp->dthps_provs[i] = help->dthps_provs[i];
13192 			newhelp->dthps_provs[i]->dthp_ref++;
13193 		}
13194 
13195 		hasprovs = 1;
13196 	}
13197 
13198 	mutex_exit(&dtrace_lock);
13199 
13200 	if (hasprovs)
13201 		dtrace_helper_provider_register(to, newhelp, NULL);
13202 }
13203 
13204 /*
13205  * DTrace Hook Functions
13206  */
13207 static void
13208 dtrace_module_loaded(struct modctl *ctl)
13209 {
13210 	dtrace_provider_t *prv;
13211 
13212 	mutex_enter(&dtrace_provider_lock);
13213 	mutex_enter(&mod_lock);
13214 
13215 	ASSERT(ctl->mod_busy);
13216 
13217 	/*
13218 	 * We're going to call each providers per-module provide operation
13219 	 * specifying only this module.
13220 	 */
13221 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
13222 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
13223 
13224 	mutex_exit(&mod_lock);
13225 	mutex_exit(&dtrace_provider_lock);
13226 
13227 	/*
13228 	 * If we have any retained enablings, we need to match against them.
13229 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
13230 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
13231 	 * module.  (In particular, this happens when loading scheduling
13232 	 * classes.)  So if we have any retained enablings, we need to dispatch
13233 	 * our task queue to do the match for us.
13234 	 */
13235 	mutex_enter(&dtrace_lock);
13236 
13237 	if (dtrace_retained == NULL) {
13238 		mutex_exit(&dtrace_lock);
13239 		return;
13240 	}
13241 
13242 	(void) taskq_dispatch(dtrace_taskq,
13243 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
13244 
13245 	mutex_exit(&dtrace_lock);
13246 
13247 	/*
13248 	 * And now, for a little heuristic sleaze:  in general, we want to
13249 	 * match modules as soon as they load.  However, we cannot guarantee
13250 	 * this, because it would lead us to the lock ordering violation
13251 	 * outlined above.  The common case, of course, is that cpu_lock is
13252 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
13253 	 * long enough for the task queue to do its work.  If it's not, it's
13254 	 * not a serious problem -- it just means that the module that we
13255 	 * just loaded may not be immediately instrumentable.
13256 	 */
13257 	delay(1);
13258 }
13259 
13260 static void
13261 dtrace_module_unloaded(struct modctl *ctl)
13262 {
13263 	dtrace_probe_t template, *probe, *first, *next;
13264 	dtrace_provider_t *prov;
13265 
13266 	template.dtpr_mod = ctl->mod_modname;
13267 
13268 	mutex_enter(&dtrace_provider_lock);
13269 	mutex_enter(&mod_lock);
13270 	mutex_enter(&dtrace_lock);
13271 
13272 	if (dtrace_bymod == NULL) {
13273 		/*
13274 		 * The DTrace module is loaded (obviously) but not attached;
13275 		 * we don't have any work to do.
13276 		 */
13277 		mutex_exit(&dtrace_provider_lock);
13278 		mutex_exit(&mod_lock);
13279 		mutex_exit(&dtrace_lock);
13280 		return;
13281 	}
13282 
13283 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
13284 	    probe != NULL; probe = probe->dtpr_nextmod) {
13285 		if (probe->dtpr_ecb != NULL) {
13286 			mutex_exit(&dtrace_provider_lock);
13287 			mutex_exit(&mod_lock);
13288 			mutex_exit(&dtrace_lock);
13289 
13290 			/*
13291 			 * This shouldn't _actually_ be possible -- we're
13292 			 * unloading a module that has an enabled probe in it.
13293 			 * (It's normally up to the provider to make sure that
13294 			 * this can't happen.)  However, because dtps_enable()
13295 			 * doesn't have a failure mode, there can be an
13296 			 * enable/unload race.  Upshot:  we don't want to
13297 			 * assert, but we're not going to disable the
13298 			 * probe, either.
13299 			 */
13300 			if (dtrace_err_verbose) {
13301 				cmn_err(CE_WARN, "unloaded module '%s' had "
13302 				    "enabled probes", ctl->mod_modname);
13303 			}
13304 
13305 			return;
13306 		}
13307 	}
13308 
13309 	probe = first;
13310 
13311 	for (first = NULL; probe != NULL; probe = next) {
13312 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
13313 
13314 		dtrace_probes[probe->dtpr_id - 1] = NULL;
13315 
13316 		next = probe->dtpr_nextmod;
13317 		dtrace_hash_remove(dtrace_bymod, probe);
13318 		dtrace_hash_remove(dtrace_byfunc, probe);
13319 		dtrace_hash_remove(dtrace_byname, probe);
13320 
13321 		if (first == NULL) {
13322 			first = probe;
13323 			probe->dtpr_nextmod = NULL;
13324 		} else {
13325 			probe->dtpr_nextmod = first;
13326 			first = probe;
13327 		}
13328 	}
13329 
13330 	/*
13331 	 * We've removed all of the module's probes from the hash chains and
13332 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
13333 	 * everyone has cleared out from any probe array processing.
13334 	 */
13335 	dtrace_sync();
13336 
13337 	for (probe = first; probe != NULL; probe = first) {
13338 		first = probe->dtpr_nextmod;
13339 		prov = probe->dtpr_provider;
13340 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
13341 		    probe->dtpr_arg);
13342 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
13343 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
13344 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
13345 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
13346 		kmem_free(probe, sizeof (dtrace_probe_t));
13347 	}
13348 
13349 	mutex_exit(&dtrace_lock);
13350 	mutex_exit(&mod_lock);
13351 	mutex_exit(&dtrace_provider_lock);
13352 }
13353 
13354 void
13355 dtrace_suspend(void)
13356 {
13357 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
13358 }
13359 
13360 void
13361 dtrace_resume(void)
13362 {
13363 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
13364 }
13365 
13366 static int
13367 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
13368 {
13369 	ASSERT(MUTEX_HELD(&cpu_lock));
13370 	mutex_enter(&dtrace_lock);
13371 
13372 	switch (what) {
13373 	case CPU_CONFIG: {
13374 		dtrace_state_t *state;
13375 		dtrace_optval_t *opt, rs, c;
13376 
13377 		/*
13378 		 * For now, we only allocate a new buffer for anonymous state.
13379 		 */
13380 		if ((state = dtrace_anon.dta_state) == NULL)
13381 			break;
13382 
13383 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13384 			break;
13385 
13386 		opt = state->dts_options;
13387 		c = opt[DTRACEOPT_CPU];
13388 
13389 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
13390 			break;
13391 
13392 		/*
13393 		 * Regardless of what the actual policy is, we're going to
13394 		 * temporarily set our resize policy to be manual.  We're
13395 		 * also going to temporarily set our CPU option to denote
13396 		 * the newly configured CPU.
13397 		 */
13398 		rs = opt[DTRACEOPT_BUFRESIZE];
13399 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
13400 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
13401 
13402 		(void) dtrace_state_buffers(state);
13403 
13404 		opt[DTRACEOPT_BUFRESIZE] = rs;
13405 		opt[DTRACEOPT_CPU] = c;
13406 
13407 		break;
13408 	}
13409 
13410 	case CPU_UNCONFIG:
13411 		/*
13412 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
13413 		 * buffer will be freed when the consumer exits.)
13414 		 */
13415 		break;
13416 
13417 	default:
13418 		break;
13419 	}
13420 
13421 	mutex_exit(&dtrace_lock);
13422 	return (0);
13423 }
13424 
13425 static void
13426 dtrace_cpu_setup_initial(processorid_t cpu)
13427 {
13428 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
13429 }
13430 
13431 static void
13432 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
13433 {
13434 	if (dtrace_toxranges >= dtrace_toxranges_max) {
13435 		int osize, nsize;
13436 		dtrace_toxrange_t *range;
13437 
13438 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
13439 
13440 		if (osize == 0) {
13441 			ASSERT(dtrace_toxrange == NULL);
13442 			ASSERT(dtrace_toxranges_max == 0);
13443 			dtrace_toxranges_max = 1;
13444 		} else {
13445 			dtrace_toxranges_max <<= 1;
13446 		}
13447 
13448 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
13449 		range = kmem_zalloc(nsize, KM_SLEEP);
13450 
13451 		if (dtrace_toxrange != NULL) {
13452 			ASSERT(osize != 0);
13453 			bcopy(dtrace_toxrange, range, osize);
13454 			kmem_free(dtrace_toxrange, osize);
13455 		}
13456 
13457 		dtrace_toxrange = range;
13458 	}
13459 
13460 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
13461 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
13462 
13463 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
13464 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
13465 	dtrace_toxranges++;
13466 }
13467 
13468 /*
13469  * DTrace Driver Cookbook Functions
13470  */
13471 /*ARGSUSED*/
13472 static int
13473 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
13474 {
13475 	dtrace_provider_id_t id;
13476 	dtrace_state_t *state = NULL;
13477 	dtrace_enabling_t *enab;
13478 
13479 	mutex_enter(&cpu_lock);
13480 	mutex_enter(&dtrace_provider_lock);
13481 	mutex_enter(&dtrace_lock);
13482 
13483 	if (ddi_soft_state_init(&dtrace_softstate,
13484 	    sizeof (dtrace_state_t), 0) != 0) {
13485 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
13486 		mutex_exit(&cpu_lock);
13487 		mutex_exit(&dtrace_provider_lock);
13488 		mutex_exit(&dtrace_lock);
13489 		return (DDI_FAILURE);
13490 	}
13491 
13492 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
13493 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
13494 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
13495 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
13496 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
13497 		ddi_remove_minor_node(devi, NULL);
13498 		ddi_soft_state_fini(&dtrace_softstate);
13499 		mutex_exit(&cpu_lock);
13500 		mutex_exit(&dtrace_provider_lock);
13501 		mutex_exit(&dtrace_lock);
13502 		return (DDI_FAILURE);
13503 	}
13504 
13505 	ddi_report_dev(devi);
13506 	dtrace_devi = devi;
13507 
13508 	dtrace_modload = dtrace_module_loaded;
13509 	dtrace_modunload = dtrace_module_unloaded;
13510 	dtrace_cpu_init = dtrace_cpu_setup_initial;
13511 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
13512 	dtrace_helpers_fork = dtrace_helpers_duplicate;
13513 	dtrace_cpustart_init = dtrace_suspend;
13514 	dtrace_cpustart_fini = dtrace_resume;
13515 	dtrace_debugger_init = dtrace_suspend;
13516 	dtrace_debugger_fini = dtrace_resume;
13517 	dtrace_kreloc_init = dtrace_suspend;
13518 	dtrace_kreloc_fini = dtrace_resume;
13519 
13520 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
13521 
13522 	ASSERT(MUTEX_HELD(&cpu_lock));
13523 
13524 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
13525 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13526 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
13527 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
13528 	    VM_SLEEP | VMC_IDENTIFIER);
13529 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
13530 	    1, INT_MAX, 0);
13531 
13532 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
13533 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
13534 	    NULL, NULL, NULL, NULL, NULL, 0);
13535 
13536 	ASSERT(MUTEX_HELD(&cpu_lock));
13537 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
13538 	    offsetof(dtrace_probe_t, dtpr_nextmod),
13539 	    offsetof(dtrace_probe_t, dtpr_prevmod));
13540 
13541 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
13542 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
13543 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
13544 
13545 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
13546 	    offsetof(dtrace_probe_t, dtpr_nextname),
13547 	    offsetof(dtrace_probe_t, dtpr_prevname));
13548 
13549 	if (dtrace_retain_max < 1) {
13550 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
13551 		    "setting to 1", dtrace_retain_max);
13552 		dtrace_retain_max = 1;
13553 	}
13554 
13555 	/*
13556 	 * Now discover our toxic ranges.
13557 	 */
13558 	dtrace_toxic_ranges(dtrace_toxrange_add);
13559 
13560 	/*
13561 	 * Before we register ourselves as a provider to our own framework,
13562 	 * we would like to assert that dtrace_provider is NULL -- but that's
13563 	 * not true if we were loaded as a dependency of a DTrace provider.
13564 	 * Once we've registered, we can assert that dtrace_provider is our
13565 	 * pseudo provider.
13566 	 */
13567 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
13568 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
13569 
13570 	ASSERT(dtrace_provider != NULL);
13571 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
13572 
13573 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
13574 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
13575 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
13576 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
13577 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
13578 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
13579 
13580 	dtrace_anon_property();
13581 	mutex_exit(&cpu_lock);
13582 
13583 	/*
13584 	 * If DTrace helper tracing is enabled, we need to allocate the
13585 	 * trace buffer and initialize the values.
13586 	 */
13587 	if (dtrace_helptrace_enabled) {
13588 		ASSERT(dtrace_helptrace_buffer == NULL);
13589 		dtrace_helptrace_buffer =
13590 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
13591 		dtrace_helptrace_next = 0;
13592 	}
13593 
13594 	/*
13595 	 * If there are already providers, we must ask them to provide their
13596 	 * probes, and then match any anonymous enabling against them.  Note
13597 	 * that there should be no other retained enablings at this time:
13598 	 * the only retained enablings at this time should be the anonymous
13599 	 * enabling.
13600 	 */
13601 	if (dtrace_anon.dta_enabling != NULL) {
13602 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
13603 
13604 		dtrace_enabling_provide(NULL);
13605 		state = dtrace_anon.dta_state;
13606 
13607 		/*
13608 		 * We couldn't hold cpu_lock across the above call to
13609 		 * dtrace_enabling_provide(), but we must hold it to actually
13610 		 * enable the probes.  We have to drop all of our locks, pick
13611 		 * up cpu_lock, and regain our locks before matching the
13612 		 * retained anonymous enabling.
13613 		 */
13614 		mutex_exit(&dtrace_lock);
13615 		mutex_exit(&dtrace_provider_lock);
13616 
13617 		mutex_enter(&cpu_lock);
13618 		mutex_enter(&dtrace_provider_lock);
13619 		mutex_enter(&dtrace_lock);
13620 
13621 		if ((enab = dtrace_anon.dta_enabling) != NULL)
13622 			(void) dtrace_enabling_match(enab, NULL);
13623 
13624 		mutex_exit(&cpu_lock);
13625 	}
13626 
13627 	mutex_exit(&dtrace_lock);
13628 	mutex_exit(&dtrace_provider_lock);
13629 
13630 	if (state != NULL) {
13631 		/*
13632 		 * If we created any anonymous state, set it going now.
13633 		 */
13634 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
13635 	}
13636 
13637 	return (DDI_SUCCESS);
13638 }
13639 
13640 /*ARGSUSED*/
13641 static int
13642 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
13643 {
13644 	dtrace_state_t *state;
13645 	uint32_t priv;
13646 	uid_t uid;
13647 	zoneid_t zoneid;
13648 
13649 	if (getminor(*devp) == DTRACEMNRN_HELPER)
13650 		return (0);
13651 
13652 	/*
13653 	 * If this wasn't an open with the "helper" minor, then it must be
13654 	 * the "dtrace" minor.
13655 	 */
13656 	ASSERT(getminor(*devp) == DTRACEMNRN_DTRACE);
13657 
13658 	/*
13659 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
13660 	 * caller lacks sufficient permission to do anything with DTrace.
13661 	 */
13662 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
13663 	if (priv == DTRACE_PRIV_NONE)
13664 		return (EACCES);
13665 
13666 	/*
13667 	 * Ask all providers to provide all their probes.
13668 	 */
13669 	mutex_enter(&dtrace_provider_lock);
13670 	dtrace_probe_provide(NULL, NULL);
13671 	mutex_exit(&dtrace_provider_lock);
13672 
13673 	mutex_enter(&cpu_lock);
13674 	mutex_enter(&dtrace_lock);
13675 	dtrace_opens++;
13676 	dtrace_membar_producer();
13677 
13678 	/*
13679 	 * If the kernel debugger is active (that is, if the kernel debugger
13680 	 * modified text in some way), we won't allow the open.
13681 	 */
13682 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
13683 		dtrace_opens--;
13684 		mutex_exit(&cpu_lock);
13685 		mutex_exit(&dtrace_lock);
13686 		return (EBUSY);
13687 	}
13688 
13689 	state = dtrace_state_create(devp, cred_p);
13690 	mutex_exit(&cpu_lock);
13691 
13692 	if (state == NULL) {
13693 		if (--dtrace_opens == 0)
13694 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
13695 		mutex_exit(&dtrace_lock);
13696 		return (EAGAIN);
13697 	}
13698 
13699 	mutex_exit(&dtrace_lock);
13700 
13701 	return (0);
13702 }
13703 
13704 /*ARGSUSED*/
13705 static int
13706 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
13707 {
13708 	minor_t minor = getminor(dev);
13709 	dtrace_state_t *state;
13710 
13711 	if (minor == DTRACEMNRN_HELPER)
13712 		return (0);
13713 
13714 	state = ddi_get_soft_state(dtrace_softstate, minor);
13715 
13716 	mutex_enter(&cpu_lock);
13717 	mutex_enter(&dtrace_lock);
13718 
13719 	if (state->dts_anon) {
13720 		/*
13721 		 * There is anonymous state. Destroy that first.
13722 		 */
13723 		ASSERT(dtrace_anon.dta_state == NULL);
13724 		dtrace_state_destroy(state->dts_anon);
13725 	}
13726 
13727 	dtrace_state_destroy(state);
13728 	ASSERT(dtrace_opens > 0);
13729 	if (--dtrace_opens == 0)
13730 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
13731 
13732 	mutex_exit(&dtrace_lock);
13733 	mutex_exit(&cpu_lock);
13734 
13735 	return (0);
13736 }
13737 
13738 /*ARGSUSED*/
13739 static int
13740 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
13741 {
13742 	int rval;
13743 	dof_helper_t help, *dhp = NULL;
13744 
13745 	switch (cmd) {
13746 	case DTRACEHIOC_ADDDOF:
13747 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
13748 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
13749 			return (EFAULT);
13750 		}
13751 
13752 		dhp = &help;
13753 		arg = (intptr_t)help.dofhp_dof;
13754 		/*FALLTHROUGH*/
13755 
13756 	case DTRACEHIOC_ADD: {
13757 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
13758 
13759 		if (dof == NULL)
13760 			return (rval);
13761 
13762 		mutex_enter(&dtrace_lock);
13763 
13764 		/*
13765 		 * dtrace_helper_slurp() takes responsibility for the dof --
13766 		 * it may free it now or it may save it and free it later.
13767 		 */
13768 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
13769 			*rv = rval;
13770 			rval = 0;
13771 		} else {
13772 			rval = EINVAL;
13773 		}
13774 
13775 		mutex_exit(&dtrace_lock);
13776 		return (rval);
13777 	}
13778 
13779 	case DTRACEHIOC_REMOVE: {
13780 		mutex_enter(&dtrace_lock);
13781 		rval = dtrace_helper_destroygen(arg);
13782 		mutex_exit(&dtrace_lock);
13783 
13784 		return (rval);
13785 	}
13786 
13787 	default:
13788 		break;
13789 	}
13790 
13791 	return (ENOTTY);
13792 }
13793 
13794 /*ARGSUSED*/
13795 static int
13796 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
13797 {
13798 	minor_t minor = getminor(dev);
13799 	dtrace_state_t *state;
13800 	int rval;
13801 
13802 	if (minor == DTRACEMNRN_HELPER)
13803 		return (dtrace_ioctl_helper(cmd, arg, rv));
13804 
13805 	state = ddi_get_soft_state(dtrace_softstate, minor);
13806 
13807 	if (state->dts_anon) {
13808 		ASSERT(dtrace_anon.dta_state == NULL);
13809 		state = state->dts_anon;
13810 	}
13811 
13812 	switch (cmd) {
13813 	case DTRACEIOC_PROVIDER: {
13814 		dtrace_providerdesc_t pvd;
13815 		dtrace_provider_t *pvp;
13816 
13817 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
13818 			return (EFAULT);
13819 
13820 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
13821 		mutex_enter(&dtrace_provider_lock);
13822 
13823 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
13824 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
13825 				break;
13826 		}
13827 
13828 		mutex_exit(&dtrace_provider_lock);
13829 
13830 		if (pvp == NULL)
13831 			return (ESRCH);
13832 
13833 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
13834 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
13835 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
13836 			return (EFAULT);
13837 
13838 		return (0);
13839 	}
13840 
13841 	case DTRACEIOC_EPROBE: {
13842 		dtrace_eprobedesc_t epdesc;
13843 		dtrace_ecb_t *ecb;
13844 		dtrace_action_t *act;
13845 		void *buf;
13846 		size_t size;
13847 		uintptr_t dest;
13848 		int nrecs;
13849 
13850 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
13851 			return (EFAULT);
13852 
13853 		mutex_enter(&dtrace_lock);
13854 
13855 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
13856 			mutex_exit(&dtrace_lock);
13857 			return (EINVAL);
13858 		}
13859 
13860 		if (ecb->dte_probe == NULL) {
13861 			mutex_exit(&dtrace_lock);
13862 			return (EINVAL);
13863 		}
13864 
13865 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
13866 		epdesc.dtepd_uarg = ecb->dte_uarg;
13867 		epdesc.dtepd_size = ecb->dte_size;
13868 
13869 		nrecs = epdesc.dtepd_nrecs;
13870 		epdesc.dtepd_nrecs = 0;
13871 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
13872 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
13873 				continue;
13874 
13875 			epdesc.dtepd_nrecs++;
13876 		}
13877 
13878 		/*
13879 		 * Now that we have the size, we need to allocate a temporary
13880 		 * buffer in which to store the complete description.  We need
13881 		 * the temporary buffer to be able to drop dtrace_lock()
13882 		 * across the copyout(), below.
13883 		 */
13884 		size = sizeof (dtrace_eprobedesc_t) +
13885 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
13886 
13887 		buf = kmem_alloc(size, KM_SLEEP);
13888 		dest = (uintptr_t)buf;
13889 
13890 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
13891 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
13892 
13893 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
13894 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
13895 				continue;
13896 
13897 			if (nrecs-- == 0)
13898 				break;
13899 
13900 			bcopy(&act->dta_rec, (void *)dest,
13901 			    sizeof (dtrace_recdesc_t));
13902 			dest += sizeof (dtrace_recdesc_t);
13903 		}
13904 
13905 		mutex_exit(&dtrace_lock);
13906 
13907 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
13908 			kmem_free(buf, size);
13909 			return (EFAULT);
13910 		}
13911 
13912 		kmem_free(buf, size);
13913 		return (0);
13914 	}
13915 
13916 	case DTRACEIOC_AGGDESC: {
13917 		dtrace_aggdesc_t aggdesc;
13918 		dtrace_action_t *act;
13919 		dtrace_aggregation_t *agg;
13920 		int nrecs;
13921 		uint32_t offs;
13922 		dtrace_recdesc_t *lrec;
13923 		void *buf;
13924 		size_t size;
13925 		uintptr_t dest;
13926 
13927 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
13928 			return (EFAULT);
13929 
13930 		mutex_enter(&dtrace_lock);
13931 
13932 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
13933 			mutex_exit(&dtrace_lock);
13934 			return (EINVAL);
13935 		}
13936 
13937 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
13938 
13939 		nrecs = aggdesc.dtagd_nrecs;
13940 		aggdesc.dtagd_nrecs = 0;
13941 
13942 		offs = agg->dtag_base;
13943 		lrec = &agg->dtag_action.dta_rec;
13944 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
13945 
13946 		for (act = agg->dtag_first; ; act = act->dta_next) {
13947 			ASSERT(act->dta_intuple ||
13948 			    DTRACEACT_ISAGG(act->dta_kind));
13949 
13950 			/*
13951 			 * If this action has a record size of zero, it
13952 			 * denotes an argument to the aggregating action.
13953 			 * Because the presence of this record doesn't (or
13954 			 * shouldn't) affect the way the data is interpreted,
13955 			 * we don't copy it out to save user-level the
13956 			 * confusion of dealing with a zero-length record.
13957 			 */
13958 			if (act->dta_rec.dtrd_size == 0) {
13959 				ASSERT(agg->dtag_hasarg);
13960 				continue;
13961 			}
13962 
13963 			aggdesc.dtagd_nrecs++;
13964 
13965 			if (act == &agg->dtag_action)
13966 				break;
13967 		}
13968 
13969 		/*
13970 		 * Now that we have the size, we need to allocate a temporary
13971 		 * buffer in which to store the complete description.  We need
13972 		 * the temporary buffer to be able to drop dtrace_lock()
13973 		 * across the copyout(), below.
13974 		 */
13975 		size = sizeof (dtrace_aggdesc_t) +
13976 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
13977 
13978 		buf = kmem_alloc(size, KM_SLEEP);
13979 		dest = (uintptr_t)buf;
13980 
13981 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
13982 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
13983 
13984 		for (act = agg->dtag_first; ; act = act->dta_next) {
13985 			dtrace_recdesc_t rec = act->dta_rec;
13986 
13987 			/*
13988 			 * See the comment in the above loop for why we pass
13989 			 * over zero-length records.
13990 			 */
13991 			if (rec.dtrd_size == 0) {
13992 				ASSERT(agg->dtag_hasarg);
13993 				continue;
13994 			}
13995 
13996 			if (nrecs-- == 0)
13997 				break;
13998 
13999 			rec.dtrd_offset -= offs;
14000 			bcopy(&rec, (void *)dest, sizeof (rec));
14001 			dest += sizeof (dtrace_recdesc_t);
14002 
14003 			if (act == &agg->dtag_action)
14004 				break;
14005 		}
14006 
14007 		mutex_exit(&dtrace_lock);
14008 
14009 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
14010 			kmem_free(buf, size);
14011 			return (EFAULT);
14012 		}
14013 
14014 		kmem_free(buf, size);
14015 		return (0);
14016 	}
14017 
14018 	case DTRACEIOC_ENABLE: {
14019 		dof_hdr_t *dof;
14020 		dtrace_enabling_t *enab = NULL;
14021 		dtrace_vstate_t *vstate;
14022 		int err = 0;
14023 
14024 		*rv = 0;
14025 
14026 		/*
14027 		 * If a NULL argument has been passed, we take this as our
14028 		 * cue to reevaluate our enablings.
14029 		 */
14030 		if (arg == NULL) {
14031 			mutex_enter(&cpu_lock);
14032 			mutex_enter(&dtrace_lock);
14033 			err = dtrace_enabling_matchstate(state, rv);
14034 			mutex_exit(&dtrace_lock);
14035 			mutex_exit(&cpu_lock);
14036 
14037 			return (err);
14038 		}
14039 
14040 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
14041 			return (rval);
14042 
14043 		mutex_enter(&cpu_lock);
14044 		mutex_enter(&dtrace_lock);
14045 		vstate = &state->dts_vstate;
14046 
14047 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14048 			mutex_exit(&dtrace_lock);
14049 			mutex_exit(&cpu_lock);
14050 			dtrace_dof_destroy(dof);
14051 			return (EBUSY);
14052 		}
14053 
14054 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
14055 			mutex_exit(&dtrace_lock);
14056 			mutex_exit(&cpu_lock);
14057 			dtrace_dof_destroy(dof);
14058 			return (EINVAL);
14059 		}
14060 
14061 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
14062 			dtrace_enabling_destroy(enab);
14063 			mutex_exit(&dtrace_lock);
14064 			mutex_exit(&cpu_lock);
14065 			dtrace_dof_destroy(dof);
14066 			return (rval);
14067 		}
14068 
14069 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
14070 			err = dtrace_enabling_retain(enab);
14071 		} else {
14072 			dtrace_enabling_destroy(enab);
14073 		}
14074 
14075 		mutex_exit(&cpu_lock);
14076 		mutex_exit(&dtrace_lock);
14077 		dtrace_dof_destroy(dof);
14078 
14079 		return (err);
14080 	}
14081 
14082 	case DTRACEIOC_REPLICATE: {
14083 		dtrace_repldesc_t desc;
14084 		dtrace_probedesc_t *match = &desc.dtrpd_match;
14085 		dtrace_probedesc_t *create = &desc.dtrpd_create;
14086 		int err;
14087 
14088 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14089 			return (EFAULT);
14090 
14091 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14092 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14093 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14094 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14095 
14096 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14097 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14098 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14099 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14100 
14101 		mutex_enter(&dtrace_lock);
14102 		err = dtrace_enabling_replicate(state, match, create);
14103 		mutex_exit(&dtrace_lock);
14104 
14105 		return (err);
14106 	}
14107 
14108 	case DTRACEIOC_PROBEMATCH:
14109 	case DTRACEIOC_PROBES: {
14110 		dtrace_probe_t *probe = NULL;
14111 		dtrace_probedesc_t desc;
14112 		dtrace_probekey_t pkey;
14113 		dtrace_id_t i;
14114 		int m = 0;
14115 		uint32_t priv;
14116 		uid_t uid;
14117 		zoneid_t zoneid;
14118 
14119 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14120 			return (EFAULT);
14121 
14122 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14123 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14124 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14125 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14126 
14127 		/*
14128 		 * Before we attempt to match this probe, we want to give
14129 		 * all providers the opportunity to provide it.
14130 		 */
14131 		if (desc.dtpd_id == DTRACE_IDNONE) {
14132 			mutex_enter(&dtrace_provider_lock);
14133 			dtrace_probe_provide(&desc, NULL);
14134 			mutex_exit(&dtrace_provider_lock);
14135 			desc.dtpd_id++;
14136 		}
14137 
14138 		if (cmd == DTRACEIOC_PROBEMATCH)  {
14139 			dtrace_probekey(&desc, &pkey);
14140 			pkey.dtpk_id = DTRACE_IDNONE;
14141 		}
14142 
14143 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
14144 
14145 		mutex_enter(&dtrace_lock);
14146 
14147 		if (cmd == DTRACEIOC_PROBEMATCH) {
14148 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14149 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14150 				    (m = dtrace_match_probe(probe, &pkey,
14151 				    priv, uid, zoneid)) != 0)
14152 					break;
14153 			}
14154 
14155 			if (m < 0) {
14156 				mutex_exit(&dtrace_lock);
14157 				return (EINVAL);
14158 			}
14159 
14160 		} else {
14161 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14162 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14163 				    dtrace_match_priv(probe, priv, uid, zoneid))
14164 					break;
14165 			}
14166 		}
14167 
14168 		if (probe == NULL) {
14169 			mutex_exit(&dtrace_lock);
14170 			return (ESRCH);
14171 		}
14172 
14173 		dtrace_probe_description(probe, &desc);
14174 		mutex_exit(&dtrace_lock);
14175 
14176 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14177 			return (EFAULT);
14178 
14179 		return (0);
14180 	}
14181 
14182 	case DTRACEIOC_PROBEARG: {
14183 		dtrace_argdesc_t desc;
14184 		dtrace_probe_t *probe;
14185 		dtrace_provider_t *prov;
14186 
14187 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14188 			return (EFAULT);
14189 
14190 		if (desc.dtargd_id == DTRACE_IDNONE)
14191 			return (EINVAL);
14192 
14193 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
14194 			return (EINVAL);
14195 
14196 		mutex_enter(&dtrace_provider_lock);
14197 		mutex_enter(&mod_lock);
14198 		mutex_enter(&dtrace_lock);
14199 
14200 		if (desc.dtargd_id > dtrace_nprobes) {
14201 			mutex_exit(&dtrace_lock);
14202 			mutex_exit(&mod_lock);
14203 			mutex_exit(&dtrace_provider_lock);
14204 			return (EINVAL);
14205 		}
14206 
14207 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
14208 			mutex_exit(&dtrace_lock);
14209 			mutex_exit(&mod_lock);
14210 			mutex_exit(&dtrace_provider_lock);
14211 			return (EINVAL);
14212 		}
14213 
14214 		mutex_exit(&dtrace_lock);
14215 
14216 		prov = probe->dtpr_provider;
14217 
14218 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
14219 			/*
14220 			 * There isn't any typed information for this probe.
14221 			 * Set the argument number to DTRACE_ARGNONE.
14222 			 */
14223 			desc.dtargd_ndx = DTRACE_ARGNONE;
14224 		} else {
14225 			desc.dtargd_native[0] = '\0';
14226 			desc.dtargd_xlate[0] = '\0';
14227 			desc.dtargd_mapping = desc.dtargd_ndx;
14228 
14229 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
14230 			    probe->dtpr_id, probe->dtpr_arg, &desc);
14231 		}
14232 
14233 		mutex_exit(&mod_lock);
14234 		mutex_exit(&dtrace_provider_lock);
14235 
14236 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14237 			return (EFAULT);
14238 
14239 		return (0);
14240 	}
14241 
14242 	case DTRACEIOC_GO: {
14243 		processorid_t cpuid;
14244 		rval = dtrace_state_go(state, &cpuid);
14245 
14246 		if (rval != 0)
14247 			return (rval);
14248 
14249 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14250 			return (EFAULT);
14251 
14252 		return (0);
14253 	}
14254 
14255 	case DTRACEIOC_STOP: {
14256 		processorid_t cpuid;
14257 
14258 		mutex_enter(&dtrace_lock);
14259 		rval = dtrace_state_stop(state, &cpuid);
14260 		mutex_exit(&dtrace_lock);
14261 
14262 		if (rval != 0)
14263 			return (rval);
14264 
14265 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14266 			return (EFAULT);
14267 
14268 		return (0);
14269 	}
14270 
14271 	case DTRACEIOC_DOFGET: {
14272 		dof_hdr_t hdr, *dof;
14273 		uint64_t len;
14274 
14275 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
14276 			return (EFAULT);
14277 
14278 		mutex_enter(&dtrace_lock);
14279 		dof = dtrace_dof_create(state);
14280 		mutex_exit(&dtrace_lock);
14281 
14282 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
14283 		rval = copyout(dof, (void *)arg, len);
14284 		dtrace_dof_destroy(dof);
14285 
14286 		return (rval == 0 ? 0 : EFAULT);
14287 	}
14288 
14289 	case DTRACEIOC_AGGSNAP:
14290 	case DTRACEIOC_BUFSNAP: {
14291 		dtrace_bufdesc_t desc;
14292 		caddr_t cached;
14293 		dtrace_buffer_t *buf;
14294 
14295 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14296 			return (EFAULT);
14297 
14298 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
14299 			return (EINVAL);
14300 
14301 		mutex_enter(&dtrace_lock);
14302 
14303 		if (cmd == DTRACEIOC_BUFSNAP) {
14304 			buf = &state->dts_buffer[desc.dtbd_cpu];
14305 		} else {
14306 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
14307 		}
14308 
14309 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
14310 			size_t sz = buf->dtb_offset;
14311 
14312 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
14313 				mutex_exit(&dtrace_lock);
14314 				return (EBUSY);
14315 			}
14316 
14317 			/*
14318 			 * If this buffer has already been consumed, we're
14319 			 * going to indicate that there's nothing left here
14320 			 * to consume.
14321 			 */
14322 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
14323 				mutex_exit(&dtrace_lock);
14324 
14325 				desc.dtbd_size = 0;
14326 				desc.dtbd_drops = 0;
14327 				desc.dtbd_errors = 0;
14328 				desc.dtbd_oldest = 0;
14329 				sz = sizeof (desc);
14330 
14331 				if (copyout(&desc, (void *)arg, sz) != 0)
14332 					return (EFAULT);
14333 
14334 				return (0);
14335 			}
14336 
14337 			/*
14338 			 * If this is a ring buffer that has wrapped, we want
14339 			 * to copy the whole thing out.
14340 			 */
14341 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
14342 				dtrace_buffer_polish(buf);
14343 				sz = buf->dtb_size;
14344 			}
14345 
14346 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
14347 				mutex_exit(&dtrace_lock);
14348 				return (EFAULT);
14349 			}
14350 
14351 			desc.dtbd_size = sz;
14352 			desc.dtbd_drops = buf->dtb_drops;
14353 			desc.dtbd_errors = buf->dtb_errors;
14354 			desc.dtbd_oldest = buf->dtb_xamot_offset;
14355 
14356 			mutex_exit(&dtrace_lock);
14357 
14358 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14359 				return (EFAULT);
14360 
14361 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
14362 
14363 			return (0);
14364 		}
14365 
14366 		if (buf->dtb_tomax == NULL) {
14367 			ASSERT(buf->dtb_xamot == NULL);
14368 			mutex_exit(&dtrace_lock);
14369 			return (ENOENT);
14370 		}
14371 
14372 		cached = buf->dtb_tomax;
14373 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
14374 
14375 		dtrace_xcall(desc.dtbd_cpu,
14376 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
14377 
14378 		state->dts_errors += buf->dtb_xamot_errors;
14379 
14380 		/*
14381 		 * If the buffers did not actually switch, then the cross call
14382 		 * did not take place -- presumably because the given CPU is
14383 		 * not in the ready set.  If this is the case, we'll return
14384 		 * ENOENT.
14385 		 */
14386 		if (buf->dtb_tomax == cached) {
14387 			ASSERT(buf->dtb_xamot != cached);
14388 			mutex_exit(&dtrace_lock);
14389 			return (ENOENT);
14390 		}
14391 
14392 		ASSERT(cached == buf->dtb_xamot);
14393 
14394 		/*
14395 		 * We have our snapshot; now copy it out.
14396 		 */
14397 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
14398 		    buf->dtb_xamot_offset) != 0) {
14399 			mutex_exit(&dtrace_lock);
14400 			return (EFAULT);
14401 		}
14402 
14403 		desc.dtbd_size = buf->dtb_xamot_offset;
14404 		desc.dtbd_drops = buf->dtb_xamot_drops;
14405 		desc.dtbd_errors = buf->dtb_xamot_errors;
14406 		desc.dtbd_oldest = 0;
14407 
14408 		mutex_exit(&dtrace_lock);
14409 
14410 		/*
14411 		 * Finally, copy out the buffer description.
14412 		 */
14413 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14414 			return (EFAULT);
14415 
14416 		return (0);
14417 	}
14418 
14419 	case DTRACEIOC_CONF: {
14420 		dtrace_conf_t conf;
14421 
14422 		bzero(&conf, sizeof (conf));
14423 		conf.dtc_difversion = DIF_VERSION;
14424 		conf.dtc_difintregs = DIF_DIR_NREGS;
14425 		conf.dtc_diftupregs = DIF_DTR_NREGS;
14426 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
14427 
14428 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
14429 			return (EFAULT);
14430 
14431 		return (0);
14432 	}
14433 
14434 	case DTRACEIOC_STATUS: {
14435 		dtrace_status_t stat;
14436 		dtrace_dstate_t *dstate;
14437 		int i, j;
14438 		uint64_t nerrs;
14439 
14440 		/*
14441 		 * See the comment in dtrace_state_deadman() for the reason
14442 		 * for setting dts_laststatus to INT64_MAX before setting
14443 		 * it to the correct value.
14444 		 */
14445 		state->dts_laststatus = INT64_MAX;
14446 		dtrace_membar_producer();
14447 		state->dts_laststatus = dtrace_gethrtime();
14448 
14449 		bzero(&stat, sizeof (stat));
14450 
14451 		mutex_enter(&dtrace_lock);
14452 
14453 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
14454 			mutex_exit(&dtrace_lock);
14455 			return (ENOENT);
14456 		}
14457 
14458 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
14459 			stat.dtst_exiting = 1;
14460 
14461 		nerrs = state->dts_errors;
14462 		dstate = &state->dts_vstate.dtvs_dynvars;
14463 
14464 		for (i = 0; i < NCPU; i++) {
14465 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
14466 
14467 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
14468 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
14469 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
14470 
14471 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
14472 				stat.dtst_filled++;
14473 
14474 			nerrs += state->dts_buffer[i].dtb_errors;
14475 
14476 			for (j = 0; j < state->dts_nspeculations; j++) {
14477 				dtrace_speculation_t *spec;
14478 				dtrace_buffer_t *buf;
14479 
14480 				spec = &state->dts_speculations[j];
14481 				buf = &spec->dtsp_buffer[i];
14482 				stat.dtst_specdrops += buf->dtb_xamot_drops;
14483 			}
14484 		}
14485 
14486 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
14487 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
14488 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
14489 		stat.dtst_dblerrors = state->dts_dblerrors;
14490 		stat.dtst_killed =
14491 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
14492 		stat.dtst_errors = nerrs;
14493 
14494 		mutex_exit(&dtrace_lock);
14495 
14496 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
14497 			return (EFAULT);
14498 
14499 		return (0);
14500 	}
14501 
14502 	case DTRACEIOC_FORMAT: {
14503 		dtrace_fmtdesc_t fmt;
14504 		char *str;
14505 		int len;
14506 
14507 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
14508 			return (EFAULT);
14509 
14510 		mutex_enter(&dtrace_lock);
14511 
14512 		if (fmt.dtfd_format == 0 ||
14513 		    fmt.dtfd_format > state->dts_nformats) {
14514 			mutex_exit(&dtrace_lock);
14515 			return (EINVAL);
14516 		}
14517 
14518 		/*
14519 		 * Format strings are allocated contiguously and they are
14520 		 * never freed; if a format index is less than the number
14521 		 * of formats, we can assert that the format map is non-NULL
14522 		 * and that the format for the specified index is non-NULL.
14523 		 */
14524 		ASSERT(state->dts_formats != NULL);
14525 		str = state->dts_formats[fmt.dtfd_format - 1];
14526 		ASSERT(str != NULL);
14527 
14528 		len = strlen(str) + 1;
14529 
14530 		if (len > fmt.dtfd_length) {
14531 			fmt.dtfd_length = len;
14532 
14533 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
14534 				mutex_exit(&dtrace_lock);
14535 				return (EINVAL);
14536 			}
14537 		} else {
14538 			if (copyout(str, fmt.dtfd_string, len) != 0) {
14539 				mutex_exit(&dtrace_lock);
14540 				return (EINVAL);
14541 			}
14542 		}
14543 
14544 		mutex_exit(&dtrace_lock);
14545 		return (0);
14546 	}
14547 
14548 	default:
14549 		break;
14550 	}
14551 
14552 	return (ENOTTY);
14553 }
14554 
14555 /*ARGSUSED*/
14556 static int
14557 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
14558 {
14559 	dtrace_state_t *state;
14560 
14561 	switch (cmd) {
14562 	case DDI_DETACH:
14563 		break;
14564 
14565 	case DDI_SUSPEND:
14566 		return (DDI_SUCCESS);
14567 
14568 	default:
14569 		return (DDI_FAILURE);
14570 	}
14571 
14572 	mutex_enter(&cpu_lock);
14573 	mutex_enter(&dtrace_provider_lock);
14574 	mutex_enter(&dtrace_lock);
14575 
14576 	ASSERT(dtrace_opens == 0);
14577 
14578 	if (dtrace_helpers > 0) {
14579 		mutex_exit(&dtrace_provider_lock);
14580 		mutex_exit(&dtrace_lock);
14581 		mutex_exit(&cpu_lock);
14582 		return (DDI_FAILURE);
14583 	}
14584 
14585 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
14586 		mutex_exit(&dtrace_provider_lock);
14587 		mutex_exit(&dtrace_lock);
14588 		mutex_exit(&cpu_lock);
14589 		return (DDI_FAILURE);
14590 	}
14591 
14592 	dtrace_provider = NULL;
14593 
14594 	if ((state = dtrace_anon_grab()) != NULL) {
14595 		/*
14596 		 * If there were ECBs on this state, the provider should
14597 		 * have not been allowed to detach; assert that there is
14598 		 * none.
14599 		 */
14600 		ASSERT(state->dts_necbs == 0);
14601 		dtrace_state_destroy(state);
14602 
14603 		/*
14604 		 * If we're being detached with anonymous state, we need to
14605 		 * indicate to the kernel debugger that DTrace is now inactive.
14606 		 */
14607 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14608 	}
14609 
14610 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
14611 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
14612 	dtrace_cpu_init = NULL;
14613 	dtrace_helpers_cleanup = NULL;
14614 	dtrace_helpers_fork = NULL;
14615 	dtrace_cpustart_init = NULL;
14616 	dtrace_cpustart_fini = NULL;
14617 	dtrace_debugger_init = NULL;
14618 	dtrace_debugger_fini = NULL;
14619 	dtrace_kreloc_init = NULL;
14620 	dtrace_kreloc_fini = NULL;
14621 	dtrace_modload = NULL;
14622 	dtrace_modunload = NULL;
14623 
14624 	mutex_exit(&cpu_lock);
14625 
14626 	if (dtrace_helptrace_enabled) {
14627 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
14628 		dtrace_helptrace_buffer = NULL;
14629 	}
14630 
14631 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
14632 	dtrace_probes = NULL;
14633 	dtrace_nprobes = 0;
14634 
14635 	dtrace_hash_destroy(dtrace_bymod);
14636 	dtrace_hash_destroy(dtrace_byfunc);
14637 	dtrace_hash_destroy(dtrace_byname);
14638 	dtrace_bymod = NULL;
14639 	dtrace_byfunc = NULL;
14640 	dtrace_byname = NULL;
14641 
14642 	kmem_cache_destroy(dtrace_state_cache);
14643 	vmem_destroy(dtrace_minor);
14644 	vmem_destroy(dtrace_arena);
14645 
14646 	if (dtrace_toxrange != NULL) {
14647 		kmem_free(dtrace_toxrange,
14648 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
14649 		dtrace_toxrange = NULL;
14650 		dtrace_toxranges = 0;
14651 		dtrace_toxranges_max = 0;
14652 	}
14653 
14654 	ddi_remove_minor_node(dtrace_devi, NULL);
14655 	dtrace_devi = NULL;
14656 
14657 	ddi_soft_state_fini(&dtrace_softstate);
14658 
14659 	ASSERT(dtrace_vtime_references == 0);
14660 	ASSERT(dtrace_opens == 0);
14661 	ASSERT(dtrace_retained == NULL);
14662 
14663 	mutex_exit(&dtrace_lock);
14664 	mutex_exit(&dtrace_provider_lock);
14665 
14666 	/*
14667 	 * We don't destroy the task queue until after we have dropped our
14668 	 * locks (taskq_destroy() may block on running tasks).  To prevent
14669 	 * attempting to do work after we have effectively detached but before
14670 	 * the task queue has been destroyed, all tasks dispatched via the
14671 	 * task queue must check that DTrace is still attached before
14672 	 * performing any operation.
14673 	 */
14674 	taskq_destroy(dtrace_taskq);
14675 	dtrace_taskq = NULL;
14676 
14677 	return (DDI_SUCCESS);
14678 }
14679 
14680 /*ARGSUSED*/
14681 static int
14682 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
14683 {
14684 	int error;
14685 
14686 	switch (infocmd) {
14687 	case DDI_INFO_DEVT2DEVINFO:
14688 		*result = (void *)dtrace_devi;
14689 		error = DDI_SUCCESS;
14690 		break;
14691 	case DDI_INFO_DEVT2INSTANCE:
14692 		*result = (void *)0;
14693 		error = DDI_SUCCESS;
14694 		break;
14695 	default:
14696 		error = DDI_FAILURE;
14697 	}
14698 	return (error);
14699 }
14700 
14701 static struct cb_ops dtrace_cb_ops = {
14702 	dtrace_open,		/* open */
14703 	dtrace_close,		/* close */
14704 	nulldev,		/* strategy */
14705 	nulldev,		/* print */
14706 	nodev,			/* dump */
14707 	nodev,			/* read */
14708 	nodev,			/* write */
14709 	dtrace_ioctl,		/* ioctl */
14710 	nodev,			/* devmap */
14711 	nodev,			/* mmap */
14712 	nodev,			/* segmap */
14713 	nochpoll,		/* poll */
14714 	ddi_prop_op,		/* cb_prop_op */
14715 	0,			/* streamtab  */
14716 	D_NEW | D_MP		/* Driver compatibility flag */
14717 };
14718 
14719 static struct dev_ops dtrace_ops = {
14720 	DEVO_REV,		/* devo_rev */
14721 	0,			/* refcnt */
14722 	dtrace_info,		/* get_dev_info */
14723 	nulldev,		/* identify */
14724 	nulldev,		/* probe */
14725 	dtrace_attach,		/* attach */
14726 	dtrace_detach,		/* detach */
14727 	nodev,			/* reset */
14728 	&dtrace_cb_ops,		/* driver operations */
14729 	NULL,			/* bus operations */
14730 	nodev			/* dev power */
14731 };
14732 
14733 static struct modldrv modldrv = {
14734 	&mod_driverops,		/* module type (this is a pseudo driver) */
14735 	"Dynamic Tracing",	/* name of module */
14736 	&dtrace_ops,		/* driver ops */
14737 };
14738 
14739 static struct modlinkage modlinkage = {
14740 	MODREV_1,
14741 	(void *)&modldrv,
14742 	NULL
14743 };
14744 
14745 int
14746 _init(void)
14747 {
14748 	return (mod_install(&modlinkage));
14749 }
14750 
14751 int
14752 _info(struct modinfo *modinfop)
14753 {
14754 	return (mod_info(&modlinkage, modinfop));
14755 }
14756 
14757 int
14758 _fini(void)
14759 {
14760 	return (mod_remove(&modlinkage));
14761 }
14762