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