xref: /titanic_50/usr/src/uts/common/dtrace/dtrace.c (revision ead1f93ee620d7580f7e53350fe5a884fc4f158a)
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 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * DTrace - Dynamic Tracing for Solaris
29  *
30  * This is the implementation of the Solaris Dynamic Tracing framework
31  * (DTrace).  The user-visible interface to DTrace is described at length in
32  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
33  * library, the in-kernel DTrace framework, and the DTrace providers are
34  * described in the block comments in the <sys/dtrace.h> header file.  The
35  * internal architecture of DTrace is described in the block comments in the
36  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
37  * implementation very much assume mastery of all of these sources; if one has
38  * an unanswered question about the implementation, one should consult them
39  * first.
40  *
41  * The functions here are ordered roughly as follows:
42  *
43  *   - Probe context functions
44  *   - Probe hashing functions
45  *   - Non-probe context utility functions
46  *   - Matching functions
47  *   - Provider-to-Framework API functions
48  *   - Probe management functions
49  *   - DIF object functions
50  *   - Format functions
51  *   - Predicate functions
52  *   - ECB functions
53  *   - Buffer functions
54  *   - Enabling functions
55  *   - DOF functions
56  *   - Anonymous enabling functions
57  *   - Consumer state functions
58  *   - Helper functions
59  *   - Hook functions
60  *   - Driver cookbook functions
61  *
62  * Each group of functions begins with a block comment labelled the "DTrace
63  * [Group] Functions", allowing one to find each block by searching forward
64  * on capital-f functions.
65  */
66 #include <sys/errno.h>
67 #include <sys/stat.h>
68 #include <sys/modctl.h>
69 #include <sys/conf.h>
70 #include <sys/systm.h>
71 #include <sys/ddi.h>
72 #include <sys/sunddi.h>
73 #include <sys/cpuvar.h>
74 #include <sys/kmem.h>
75 #include <sys/strsubr.h>
76 #include <sys/sysmacros.h>
77 #include <sys/dtrace_impl.h>
78 #include <sys/atomic.h>
79 #include <sys/cmn_err.h>
80 #include <sys/mutex_impl.h>
81 #include <sys/rwlock_impl.h>
82 #include <sys/ctf_api.h>
83 #include <sys/panic.h>
84 #include <sys/priv_impl.h>
85 #include <sys/policy.h>
86 #include <sys/cred_impl.h>
87 #include <sys/procfs_isa.h>
88 #include <sys/taskq.h>
89 #include <sys/mkdev.h>
90 #include <sys/kdi.h>
91 #include <sys/zone.h>
92 #include <sys/socket.h>
93 #include <netinet/in.h>
94 
95 /*
96  * DTrace Tunable Variables
97  *
98  * The following variables may be tuned by adding a line to /etc/system that
99  * includes both the name of the DTrace module ("dtrace") and the name of the
100  * variable.  For example:
101  *
102  *   set dtrace:dtrace_destructive_disallow = 1
103  *
104  * In general, the only variables that one should be tuning this way are those
105  * that affect system-wide DTrace behavior, and for which the default behavior
106  * is undesirable.  Most of these variables are tunable on a per-consumer
107  * basis using DTrace options, and need not be tuned on a system-wide basis.
108  * When tuning these variables, avoid pathological values; while some attempt
109  * is made to verify the integrity of these variables, they are not considered
110  * part of the supported interface to DTrace, and they are therefore not
111  * checked comprehensively.  Further, these variables should not be tuned
112  * dynamically via "mdb -kw" or other means; they should only be tuned via
113  * /etc/system.
114  */
115 int		dtrace_destructive_disallow = 0;
116 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
117 size_t		dtrace_difo_maxsize = (256 * 1024);
118 dtrace_optval_t	dtrace_dof_maxsize = (256 * 1024);
119 size_t		dtrace_global_maxsize = (16 * 1024);
120 size_t		dtrace_actions_max = (16 * 1024);
121 size_t		dtrace_retain_max = 1024;
122 dtrace_optval_t	dtrace_helper_actions_max = 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_genid_t	dtrace_retained_gen;	/* current retained enab gen */
188 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
189 
190 /*
191  * DTrace Locking
192  * DTrace is protected by three (relatively coarse-grained) locks:
193  *
194  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
195  *     including enabling state, probes, ECBs, consumer state, helper state,
196  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
197  *     probe context is lock-free -- synchronization is handled via the
198  *     dtrace_sync() cross call mechanism.
199  *
200  * (2) dtrace_provider_lock is required when manipulating provider state, or
201  *     when provider state must be held constant.
202  *
203  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
204  *     when meta provider state must be held constant.
205  *
206  * The lock ordering between these three locks is dtrace_meta_lock before
207  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
208  * several places where dtrace_provider_lock is held by the framework as it
209  * calls into the providers -- which then call back into the framework,
210  * grabbing dtrace_lock.)
211  *
212  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
213  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
214  * role as a coarse-grained lock; it is acquired before both of these locks.
215  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
216  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
217  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
218  * acquired _between_ dtrace_provider_lock and dtrace_lock.
219  */
220 static kmutex_t		dtrace_lock;		/* probe state lock */
221 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
222 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
223 
224 /*
225  * DTrace Provider Variables
226  *
227  * These are the variables relating to DTrace as a provider (that is, the
228  * provider of the BEGIN, END, and ERROR probes).
229  */
230 static dtrace_pattr_t	dtrace_provider_attr = {
231 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
232 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
233 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
234 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
235 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
236 };
237 
238 static void
239 dtrace_nullop(void)
240 {}
241 
242 static int
243 dtrace_enable_nullop(void)
244 {
245 	return (0);
246 }
247 
248 static dtrace_pops_t	dtrace_provider_ops = {
249 	(void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
250 	(void (*)(void *, struct modctl *))dtrace_nullop,
251 	(int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
252 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
253 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
254 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
255 	NULL,
256 	NULL,
257 	NULL,
258 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
259 };
260 
261 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
262 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
263 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
264 
265 /*
266  * DTrace Helper Tracing Variables
267  */
268 uint32_t dtrace_helptrace_next = 0;
269 uint32_t dtrace_helptrace_nlocals;
270 char	*dtrace_helptrace_buffer;
271 int	dtrace_helptrace_bufsize = 512 * 1024;
272 
273 #ifdef DEBUG
274 int	dtrace_helptrace_enabled = 1;
275 #else
276 int	dtrace_helptrace_enabled = 0;
277 #endif
278 
279 /*
280  * DTrace Error Hashing
281  *
282  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
283  * table.  This is very useful for checking coverage of tests that are
284  * expected to induce DIF or DOF processing errors, and may be useful for
285  * debugging problems in the DIF code generator or in DOF generation .  The
286  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
287  */
288 #ifdef DEBUG
289 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
290 static const char *dtrace_errlast;
291 static kthread_t *dtrace_errthread;
292 static kmutex_t dtrace_errlock;
293 #endif
294 
295 /*
296  * DTrace Macros and Constants
297  *
298  * These are various macros that are useful in various spots in the
299  * implementation, along with a few random constants that have no meaning
300  * outside of the implementation.  There is no real structure to this cpp
301  * mishmash -- but is there ever?
302  */
303 #define	DTRACE_HASHSTR(hash, probe)	\
304 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
305 
306 #define	DTRACE_HASHNEXT(hash, probe)	\
307 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
308 
309 #define	DTRACE_HASHPREV(hash, probe)	\
310 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
311 
312 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
313 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
314 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
315 
316 #define	DTRACE_AGGHASHSIZE_SLEW		17
317 
318 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
319 
320 /*
321  * The key for a thread-local variable consists of the lower 61 bits of the
322  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
323  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
324  * equal to a variable identifier.  This is necessary (but not sufficient) to
325  * assure that global associative arrays never collide with thread-local
326  * variables.  To guarantee that they cannot collide, we must also define the
327  * order for keying dynamic variables.  That order is:
328  *
329  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
330  *
331  * Because the variable-key and the tls-key are in orthogonal spaces, there is
332  * no way for a global variable key signature to match a thread-local key
333  * signature.
334  */
335 #define	DTRACE_TLS_THRKEY(where) { \
336 	uint_t intr = 0; \
337 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
338 	for (; actv; actv >>= 1) \
339 		intr++; \
340 	ASSERT(intr < (1 << 3)); \
341 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
342 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
343 }
344 
345 #define	DT_BSWAP_8(x)	((x) & 0xff)
346 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
347 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
348 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
349 
350 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
351 
352 #define	DTRACE_STORE(type, tomax, offset, what) \
353 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
354 
355 #ifndef __i386
356 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
357 	if (addr & (size - 1)) {					\
358 		*flags |= CPU_DTRACE_BADALIGN;				\
359 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
360 		return (0);						\
361 	}
362 #else
363 #define	DTRACE_ALIGNCHECK(addr, size, flags)
364 #endif
365 
366 /*
367  * Test whether a range of memory starting at testaddr of size testsz falls
368  * within the range of memory described by addr, sz.  We take care to avoid
369  * problems with overflow and underflow of the unsigned quantities, and
370  * disallow all negative sizes.  Ranges of size 0 are allowed.
371  */
372 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
373 	((testaddr) - (baseaddr) < (basesz) && \
374 	(testaddr) + (testsz) - (baseaddr) <= (basesz) && \
375 	(testaddr) + (testsz) >= (testaddr))
376 
377 /*
378  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
379  * alloc_sz on the righthand side of the comparison in order to avoid overflow
380  * or underflow in the comparison with it.  This is simpler than the INRANGE
381  * check above, because we know that the dtms_scratch_ptr is valid in the
382  * range.  Allocations of size zero are allowed.
383  */
384 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
385 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
386 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
387 
388 #define	DTRACE_LOADFUNC(bits)						\
389 /*CSTYLED*/								\
390 uint##bits##_t								\
391 dtrace_load##bits(uintptr_t addr)					\
392 {									\
393 	size_t size = bits / NBBY;					\
394 	/*CSTYLED*/							\
395 	uint##bits##_t rval;						\
396 	int i;								\
397 	volatile uint16_t *flags = (volatile uint16_t *)		\
398 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
399 									\
400 	DTRACE_ALIGNCHECK(addr, size, flags);				\
401 									\
402 	for (i = 0; i < dtrace_toxranges; i++) {			\
403 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
404 			continue;					\
405 									\
406 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
407 			continue;					\
408 									\
409 		/*							\
410 		 * This address falls within a toxic region; return 0.	\
411 		 */							\
412 		*flags |= CPU_DTRACE_BADADDR;				\
413 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
414 		return (0);						\
415 	}								\
416 									\
417 	*flags |= CPU_DTRACE_NOFAULT;					\
418 	/*CSTYLED*/							\
419 	rval = *((volatile uint##bits##_t *)addr);			\
420 	*flags &= ~CPU_DTRACE_NOFAULT;					\
421 									\
422 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
423 }
424 
425 #ifdef _LP64
426 #define	dtrace_loadptr	dtrace_load64
427 #else
428 #define	dtrace_loadptr	dtrace_load32
429 #endif
430 
431 #define	DTRACE_DYNHASH_FREE	0
432 #define	DTRACE_DYNHASH_SINK	1
433 #define	DTRACE_DYNHASH_VALID	2
434 
435 #define	DTRACE_MATCH_FAIL	-1
436 #define	DTRACE_MATCH_NEXT	0
437 #define	DTRACE_MATCH_DONE	1
438 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
439 #define	DTRACE_STATE_ALIGN	64
440 
441 #define	DTRACE_FLAGS2FLT(flags)						\
442 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
443 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
444 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
445 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
446 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
447 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
448 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
449 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
450 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
451 	DTRACEFLT_UNKNOWN)
452 
453 #define	DTRACEACT_ISSTRING(act)						\
454 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
455 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
456 
457 static size_t dtrace_strlen(const char *, size_t);
458 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
459 static void dtrace_enabling_provide(dtrace_provider_t *);
460 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
461 static void dtrace_enabling_matchall(void);
462 static dtrace_state_t *dtrace_anon_grab(void);
463 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
464     dtrace_state_t *, uint64_t, uint64_t);
465 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
466 static void dtrace_buffer_drop(dtrace_buffer_t *);
467 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
468     dtrace_state_t *, dtrace_mstate_t *);
469 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
470     dtrace_optval_t);
471 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
472 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
473 
474 /*
475  * DTrace Probe Context Functions
476  *
477  * These functions are called from probe context.  Because probe context is
478  * any context in which C may be called, arbitrarily locks may be held,
479  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
480  * As a result, functions called from probe context may only call other DTrace
481  * support functions -- they may not interact at all with the system at large.
482  * (Note that the ASSERT macro is made probe-context safe by redefining it in
483  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
484  * loads are to be performed from probe context, they _must_ be in terms of
485  * the safe dtrace_load*() variants.
486  *
487  * Some functions in this block are not actually called from probe context;
488  * for these functions, there will be a comment above the function reading
489  * "Note:  not called from probe context."
490  */
491 void
492 dtrace_panic(const char *format, ...)
493 {
494 	va_list alist;
495 
496 	va_start(alist, format);
497 	dtrace_vpanic(format, alist);
498 	va_end(alist);
499 }
500 
501 int
502 dtrace_assfail(const char *a, const char *f, int l)
503 {
504 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
505 
506 	/*
507 	 * We just need something here that even the most clever compiler
508 	 * cannot optimize away.
509 	 */
510 	return (a[(uintptr_t)f]);
511 }
512 
513 /*
514  * Atomically increment a specified error counter from probe context.
515  */
516 static void
517 dtrace_error(uint32_t *counter)
518 {
519 	/*
520 	 * Most counters stored to in probe context are per-CPU counters.
521 	 * However, there are some error conditions that are sufficiently
522 	 * arcane that they don't merit per-CPU storage.  If these counters
523 	 * are incremented concurrently on different CPUs, scalability will be
524 	 * adversely affected -- but we don't expect them to be white-hot in a
525 	 * correctly constructed enabling...
526 	 */
527 	uint32_t oval, nval;
528 
529 	do {
530 		oval = *counter;
531 
532 		if ((nval = oval + 1) == 0) {
533 			/*
534 			 * If the counter would wrap, set it to 1 -- assuring
535 			 * that the counter is never zero when we have seen
536 			 * errors.  (The counter must be 32-bits because we
537 			 * aren't guaranteed a 64-bit compare&swap operation.)
538 			 * To save this code both the infamy of being fingered
539 			 * by a priggish news story and the indignity of being
540 			 * the target of a neo-puritan witch trial, we're
541 			 * carefully avoiding any colorful description of the
542 			 * likelihood of this condition -- but suffice it to
543 			 * say that it is only slightly more likely than the
544 			 * overflow of predicate cache IDs, as discussed in
545 			 * dtrace_predicate_create().
546 			 */
547 			nval = 1;
548 		}
549 	} while (dtrace_cas32(counter, oval, nval) != oval);
550 }
551 
552 /*
553  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
554  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
555  */
556 DTRACE_LOADFUNC(8)
557 DTRACE_LOADFUNC(16)
558 DTRACE_LOADFUNC(32)
559 DTRACE_LOADFUNC(64)
560 
561 static int
562 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
563 {
564 	if (dest < mstate->dtms_scratch_base)
565 		return (0);
566 
567 	if (dest + size < dest)
568 		return (0);
569 
570 	if (dest + size > mstate->dtms_scratch_ptr)
571 		return (0);
572 
573 	return (1);
574 }
575 
576 static int
577 dtrace_canstore_statvar(uint64_t addr, size_t sz,
578     dtrace_statvar_t **svars, int nsvars)
579 {
580 	int i;
581 
582 	for (i = 0; i < nsvars; i++) {
583 		dtrace_statvar_t *svar = svars[i];
584 
585 		if (svar == NULL || svar->dtsv_size == 0)
586 			continue;
587 
588 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
589 			return (1);
590 	}
591 
592 	return (0);
593 }
594 
595 /*
596  * Check to see if the address is within a memory region to which a store may
597  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
598  * region.  The caller of dtrace_canstore() is responsible for performing any
599  * alignment checks that are needed before stores are actually executed.
600  */
601 static int
602 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
603     dtrace_vstate_t *vstate)
604 {
605 	/*
606 	 * First, check to see if the address is in scratch space...
607 	 */
608 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
609 	    mstate->dtms_scratch_size))
610 		return (1);
611 
612 	/*
613 	 * Now check to see if it's a dynamic variable.  This check will pick
614 	 * up both thread-local variables and any global dynamically-allocated
615 	 * variables.
616 	 */
617 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
618 	    vstate->dtvs_dynvars.dtds_size)) {
619 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
620 		uintptr_t base = (uintptr_t)dstate->dtds_base +
621 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
622 		uintptr_t chunkoffs;
623 
624 		/*
625 		 * Before we assume that we can store here, we need to make
626 		 * sure that it isn't in our metadata -- storing to our
627 		 * dynamic variable metadata would corrupt our state.  For
628 		 * the range to not include any dynamic variable metadata,
629 		 * it must:
630 		 *
631 		 *	(1) Start above the hash table that is at the base of
632 		 *	the dynamic variable space
633 		 *
634 		 *	(2) Have a starting chunk offset that is beyond the
635 		 *	dtrace_dynvar_t that is at the base of every chunk
636 		 *
637 		 *	(3) Not span a chunk boundary
638 		 *
639 		 */
640 		if (addr < base)
641 			return (0);
642 
643 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
644 
645 		if (chunkoffs < sizeof (dtrace_dynvar_t))
646 			return (0);
647 
648 		if (chunkoffs + sz > dstate->dtds_chunksize)
649 			return (0);
650 
651 		return (1);
652 	}
653 
654 	/*
655 	 * Finally, check the static local and global variables.  These checks
656 	 * take the longest, so we perform them last.
657 	 */
658 	if (dtrace_canstore_statvar(addr, sz,
659 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
660 		return (1);
661 
662 	if (dtrace_canstore_statvar(addr, sz,
663 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
664 		return (1);
665 
666 	return (0);
667 }
668 
669 
670 /*
671  * Convenience routine to check to see if the address is within a memory
672  * region in which a load may be issued given the user's privilege level;
673  * if not, it sets the appropriate error flags and loads 'addr' into the
674  * illegal value slot.
675  *
676  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
677  * appropriate memory access protection.
678  */
679 static int
680 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
681     dtrace_vstate_t *vstate)
682 {
683 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
684 
685 	/*
686 	 * If we hold the privilege to read from kernel memory, then
687 	 * everything is readable.
688 	 */
689 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
690 		return (1);
691 
692 	/*
693 	 * You can obviously read that which you can store.
694 	 */
695 	if (dtrace_canstore(addr, sz, mstate, vstate))
696 		return (1);
697 
698 	/*
699 	 * We're allowed to read from our own string table.
700 	 */
701 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
702 	    mstate->dtms_difo->dtdo_strlen))
703 		return (1);
704 
705 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
706 	*illval = addr;
707 	return (0);
708 }
709 
710 /*
711  * Convenience routine to check to see if a given string is within a memory
712  * region in which a load may be issued given the user's privilege level;
713  * this exists so that we don't need to issue unnecessary dtrace_strlen()
714  * calls in the event that the user has all privileges.
715  */
716 static int
717 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
718     dtrace_vstate_t *vstate)
719 {
720 	size_t strsz;
721 
722 	/*
723 	 * If we hold the privilege to read from kernel memory, then
724 	 * everything is readable.
725 	 */
726 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
727 		return (1);
728 
729 	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
730 	if (dtrace_canload(addr, strsz, mstate, vstate))
731 		return (1);
732 
733 	return (0);
734 }
735 
736 /*
737  * Convenience routine to check to see if a given variable is within a memory
738  * region in which a load may be issued given the user's privilege level.
739  */
740 static int
741 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
742     dtrace_vstate_t *vstate)
743 {
744 	size_t sz;
745 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
746 
747 	/*
748 	 * If we hold the privilege to read from kernel memory, then
749 	 * everything is readable.
750 	 */
751 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
752 		return (1);
753 
754 	if (type->dtdt_kind == DIF_TYPE_STRING)
755 		sz = dtrace_strlen(src,
756 		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
757 	else
758 		sz = type->dtdt_size;
759 
760 	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
761 }
762 
763 /*
764  * Compare two strings using safe loads.
765  */
766 static int
767 dtrace_strncmp(char *s1, char *s2, size_t limit)
768 {
769 	uint8_t c1, c2;
770 	volatile uint16_t *flags;
771 
772 	if (s1 == s2 || limit == 0)
773 		return (0);
774 
775 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
776 
777 	do {
778 		if (s1 == NULL) {
779 			c1 = '\0';
780 		} else {
781 			c1 = dtrace_load8((uintptr_t)s1++);
782 		}
783 
784 		if (s2 == NULL) {
785 			c2 = '\0';
786 		} else {
787 			c2 = dtrace_load8((uintptr_t)s2++);
788 		}
789 
790 		if (c1 != c2)
791 			return (c1 - c2);
792 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
793 
794 	return (0);
795 }
796 
797 /*
798  * Compute strlen(s) for a string using safe memory accesses.  The additional
799  * len parameter is used to specify a maximum length to ensure completion.
800  */
801 static size_t
802 dtrace_strlen(const char *s, size_t lim)
803 {
804 	uint_t len;
805 
806 	for (len = 0; len != lim; len++) {
807 		if (dtrace_load8((uintptr_t)s++) == '\0')
808 			break;
809 	}
810 
811 	return (len);
812 }
813 
814 /*
815  * Check if an address falls within a toxic region.
816  */
817 static int
818 dtrace_istoxic(uintptr_t kaddr, size_t size)
819 {
820 	uintptr_t taddr, tsize;
821 	int i;
822 
823 	for (i = 0; i < dtrace_toxranges; i++) {
824 		taddr = dtrace_toxrange[i].dtt_base;
825 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
826 
827 		if (kaddr - taddr < tsize) {
828 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
829 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
830 			return (1);
831 		}
832 
833 		if (taddr - kaddr < size) {
834 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
835 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
836 			return (1);
837 		}
838 	}
839 
840 	return (0);
841 }
842 
843 /*
844  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
845  * memory specified by the DIF program.  The dst is assumed to be safe memory
846  * that we can store to directly because it is managed by DTrace.  As with
847  * standard bcopy, overlapping copies are handled properly.
848  */
849 static void
850 dtrace_bcopy(const void *src, void *dst, size_t len)
851 {
852 	if (len != 0) {
853 		uint8_t *s1 = dst;
854 		const uint8_t *s2 = src;
855 
856 		if (s1 <= s2) {
857 			do {
858 				*s1++ = dtrace_load8((uintptr_t)s2++);
859 			} while (--len != 0);
860 		} else {
861 			s2 += len;
862 			s1 += len;
863 
864 			do {
865 				*--s1 = dtrace_load8((uintptr_t)--s2);
866 			} while (--len != 0);
867 		}
868 	}
869 }
870 
871 /*
872  * Copy src to dst using safe memory accesses, up to either the specified
873  * length, or the point that a nul byte is encountered.  The src is assumed to
874  * be unsafe memory specified by the DIF program.  The dst is assumed to be
875  * safe memory that we can store to directly because it is managed by DTrace.
876  * Unlike dtrace_bcopy(), overlapping regions are not handled.
877  */
878 static void
879 dtrace_strcpy(const void *src, void *dst, size_t len)
880 {
881 	if (len != 0) {
882 		uint8_t *s1 = dst, c;
883 		const uint8_t *s2 = src;
884 
885 		do {
886 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
887 		} while (--len != 0 && c != '\0');
888 	}
889 }
890 
891 /*
892  * Copy src to dst, deriving the size and type from the specified (BYREF)
893  * variable type.  The src is assumed to be unsafe memory specified by the DIF
894  * program.  The dst is assumed to be DTrace variable memory that is of the
895  * specified type; we assume that we can store to directly.
896  */
897 static void
898 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
899 {
900 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
901 
902 	if (type->dtdt_kind == DIF_TYPE_STRING) {
903 		dtrace_strcpy(src, dst, type->dtdt_size);
904 	} else {
905 		dtrace_bcopy(src, dst, type->dtdt_size);
906 	}
907 }
908 
909 /*
910  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
911  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
912  * safe memory that we can access directly because it is managed by DTrace.
913  */
914 static int
915 dtrace_bcmp(const void *s1, const void *s2, size_t len)
916 {
917 	volatile uint16_t *flags;
918 
919 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
920 
921 	if (s1 == s2)
922 		return (0);
923 
924 	if (s1 == NULL || s2 == NULL)
925 		return (1);
926 
927 	if (s1 != s2 && len != 0) {
928 		const uint8_t *ps1 = s1;
929 		const uint8_t *ps2 = s2;
930 
931 		do {
932 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
933 				return (1);
934 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
935 	}
936 	return (0);
937 }
938 
939 /*
940  * Zero the specified region using a simple byte-by-byte loop.  Note that this
941  * is for safe DTrace-managed memory only.
942  */
943 static void
944 dtrace_bzero(void *dst, size_t len)
945 {
946 	uchar_t *cp;
947 
948 	for (cp = dst; len != 0; len--)
949 		*cp++ = 0;
950 }
951 
952 static void
953 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
954 {
955 	uint64_t result[2];
956 
957 	result[0] = addend1[0] + addend2[0];
958 	result[1] = addend1[1] + addend2[1] +
959 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
960 
961 	sum[0] = result[0];
962 	sum[1] = result[1];
963 }
964 
965 /*
966  * Shift the 128-bit value in a by b. If b is positive, shift left.
967  * If b is negative, shift right.
968  */
969 static void
970 dtrace_shift_128(uint64_t *a, int b)
971 {
972 	uint64_t mask;
973 
974 	if (b == 0)
975 		return;
976 
977 	if (b < 0) {
978 		b = -b;
979 		if (b >= 64) {
980 			a[0] = a[1] >> (b - 64);
981 			a[1] = 0;
982 		} else {
983 			a[0] >>= b;
984 			mask = 1LL << (64 - b);
985 			mask -= 1;
986 			a[0] |= ((a[1] & mask) << (64 - b));
987 			a[1] >>= b;
988 		}
989 	} else {
990 		if (b >= 64) {
991 			a[1] = a[0] << (b - 64);
992 			a[0] = 0;
993 		} else {
994 			a[1] <<= b;
995 			mask = a[0] >> (64 - b);
996 			a[1] |= mask;
997 			a[0] <<= b;
998 		}
999 	}
1000 }
1001 
1002 /*
1003  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1004  * use native multiplication on those, and then re-combine into the
1005  * resulting 128-bit value.
1006  *
1007  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1008  *     hi1 * hi2 << 64 +
1009  *     hi1 * lo2 << 32 +
1010  *     hi2 * lo1 << 32 +
1011  *     lo1 * lo2
1012  */
1013 static void
1014 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1015 {
1016 	uint64_t hi1, hi2, lo1, lo2;
1017 	uint64_t tmp[2];
1018 
1019 	hi1 = factor1 >> 32;
1020 	hi2 = factor2 >> 32;
1021 
1022 	lo1 = factor1 & DT_MASK_LO;
1023 	lo2 = factor2 & DT_MASK_LO;
1024 
1025 	product[0] = lo1 * lo2;
1026 	product[1] = hi1 * hi2;
1027 
1028 	tmp[0] = hi1 * lo2;
1029 	tmp[1] = 0;
1030 	dtrace_shift_128(tmp, 32);
1031 	dtrace_add_128(product, tmp, product);
1032 
1033 	tmp[0] = hi2 * lo1;
1034 	tmp[1] = 0;
1035 	dtrace_shift_128(tmp, 32);
1036 	dtrace_add_128(product, tmp, product);
1037 }
1038 
1039 /*
1040  * This privilege check should be used by actions and subroutines to
1041  * verify that the user credentials of the process that enabled the
1042  * invoking ECB match the target credentials
1043  */
1044 static int
1045 dtrace_priv_proc_common_user(dtrace_state_t *state)
1046 {
1047 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1048 
1049 	/*
1050 	 * We should always have a non-NULL state cred here, since if cred
1051 	 * is null (anonymous tracing), we fast-path bypass this routine.
1052 	 */
1053 	ASSERT(s_cr != NULL);
1054 
1055 	if ((cr = CRED()) != NULL &&
1056 	    s_cr->cr_uid == cr->cr_uid &&
1057 	    s_cr->cr_uid == cr->cr_ruid &&
1058 	    s_cr->cr_uid == cr->cr_suid &&
1059 	    s_cr->cr_gid == cr->cr_gid &&
1060 	    s_cr->cr_gid == cr->cr_rgid &&
1061 	    s_cr->cr_gid == cr->cr_sgid)
1062 		return (1);
1063 
1064 	return (0);
1065 }
1066 
1067 /*
1068  * This privilege check should be used by actions and subroutines to
1069  * verify that the zone of the process that enabled the invoking ECB
1070  * matches the target credentials
1071  */
1072 static int
1073 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1074 {
1075 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1076 
1077 	/*
1078 	 * We should always have a non-NULL state cred here, since if cred
1079 	 * is null (anonymous tracing), we fast-path bypass this routine.
1080 	 */
1081 	ASSERT(s_cr != NULL);
1082 
1083 	if ((cr = CRED()) != NULL &&
1084 	    s_cr->cr_zone == cr->cr_zone)
1085 		return (1);
1086 
1087 	return (0);
1088 }
1089 
1090 /*
1091  * This privilege check should be used by actions and subroutines to
1092  * verify that the process has not setuid or changed credentials.
1093  */
1094 static int
1095 dtrace_priv_proc_common_nocd()
1096 {
1097 	proc_t *proc;
1098 
1099 	if ((proc = ttoproc(curthread)) != NULL &&
1100 	    !(proc->p_flag & SNOCD))
1101 		return (1);
1102 
1103 	return (0);
1104 }
1105 
1106 static int
1107 dtrace_priv_proc_destructive(dtrace_state_t *state)
1108 {
1109 	int action = state->dts_cred.dcr_action;
1110 
1111 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1112 	    dtrace_priv_proc_common_zone(state) == 0)
1113 		goto bad;
1114 
1115 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1116 	    dtrace_priv_proc_common_user(state) == 0)
1117 		goto bad;
1118 
1119 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1120 	    dtrace_priv_proc_common_nocd() == 0)
1121 		goto bad;
1122 
1123 	return (1);
1124 
1125 bad:
1126 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1127 
1128 	return (0);
1129 }
1130 
1131 static int
1132 dtrace_priv_proc_control(dtrace_state_t *state)
1133 {
1134 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1135 		return (1);
1136 
1137 	if (dtrace_priv_proc_common_zone(state) &&
1138 	    dtrace_priv_proc_common_user(state) &&
1139 	    dtrace_priv_proc_common_nocd())
1140 		return (1);
1141 
1142 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1143 
1144 	return (0);
1145 }
1146 
1147 static int
1148 dtrace_priv_proc(dtrace_state_t *state)
1149 {
1150 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1151 		return (1);
1152 
1153 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1154 
1155 	return (0);
1156 }
1157 
1158 static int
1159 dtrace_priv_kernel(dtrace_state_t *state)
1160 {
1161 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1162 		return (1);
1163 
1164 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1165 
1166 	return (0);
1167 }
1168 
1169 static int
1170 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1171 {
1172 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1173 		return (1);
1174 
1175 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1176 
1177 	return (0);
1178 }
1179 
1180 /*
1181  * Note:  not called from probe context.  This function is called
1182  * asynchronously (and at a regular interval) from outside of probe context to
1183  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1184  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1185  */
1186 void
1187 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1188 {
1189 	dtrace_dynvar_t *dirty;
1190 	dtrace_dstate_percpu_t *dcpu;
1191 	int i, work = 0;
1192 
1193 	for (i = 0; i < NCPU; i++) {
1194 		dcpu = &dstate->dtds_percpu[i];
1195 
1196 		ASSERT(dcpu->dtdsc_rinsing == NULL);
1197 
1198 		/*
1199 		 * If the dirty list is NULL, there is no dirty work to do.
1200 		 */
1201 		if (dcpu->dtdsc_dirty == NULL)
1202 			continue;
1203 
1204 		/*
1205 		 * If the clean list is non-NULL, then we're not going to do
1206 		 * any work for this CPU -- it means that there has not been
1207 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1208 		 * since the last time we cleaned house.
1209 		 */
1210 		if (dcpu->dtdsc_clean != NULL)
1211 			continue;
1212 
1213 		work = 1;
1214 
1215 		/*
1216 		 * Atomically move the dirty list aside.
1217 		 */
1218 		do {
1219 			dirty = dcpu->dtdsc_dirty;
1220 
1221 			/*
1222 			 * Before we zap the dirty list, set the rinsing list.
1223 			 * (This allows for a potential assertion in
1224 			 * dtrace_dynvar():  if a free dynamic variable appears
1225 			 * on a hash chain, either the dirty list or the
1226 			 * rinsing list for some CPU must be non-NULL.)
1227 			 */
1228 			dcpu->dtdsc_rinsing = dirty;
1229 			dtrace_membar_producer();
1230 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1231 		    dirty, NULL) != dirty);
1232 	}
1233 
1234 	if (!work) {
1235 		/*
1236 		 * We have no work to do; we can simply return.
1237 		 */
1238 		return;
1239 	}
1240 
1241 	dtrace_sync();
1242 
1243 	for (i = 0; i < NCPU; i++) {
1244 		dcpu = &dstate->dtds_percpu[i];
1245 
1246 		if (dcpu->dtdsc_rinsing == NULL)
1247 			continue;
1248 
1249 		/*
1250 		 * We are now guaranteed that no hash chain contains a pointer
1251 		 * into this dirty list; we can make it clean.
1252 		 */
1253 		ASSERT(dcpu->dtdsc_clean == NULL);
1254 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1255 		dcpu->dtdsc_rinsing = NULL;
1256 	}
1257 
1258 	/*
1259 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1260 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1261 	 * This prevents a race whereby a CPU incorrectly decides that
1262 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1263 	 * after dtrace_dynvar_clean() has completed.
1264 	 */
1265 	dtrace_sync();
1266 
1267 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1268 }
1269 
1270 /*
1271  * Depending on the value of the op parameter, this function looks-up,
1272  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1273  * allocation is requested, this function will return a pointer to a
1274  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1275  * variable can be allocated.  If NULL is returned, the appropriate counter
1276  * will be incremented.
1277  */
1278 dtrace_dynvar_t *
1279 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1280     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1281     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1282 {
1283 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1284 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1285 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1286 	processorid_t me = CPU->cpu_id, cpu = me;
1287 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1288 	size_t bucket, ksize;
1289 	size_t chunksize = dstate->dtds_chunksize;
1290 	uintptr_t kdata, lock, nstate;
1291 	uint_t i;
1292 
1293 	ASSERT(nkeys != 0);
1294 
1295 	/*
1296 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1297 	 * algorithm.  For the by-value portions, we perform the algorithm in
1298 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1299 	 * bit, and seems to have only a minute effect on distribution.  For
1300 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1301 	 * over each referenced byte.  It's painful to do this, but it's much
1302 	 * better than pathological hash distribution.  The efficacy of the
1303 	 * hashing algorithm (and a comparison with other algorithms) may be
1304 	 * found by running the ::dtrace_dynstat MDB dcmd.
1305 	 */
1306 	for (i = 0; i < nkeys; i++) {
1307 		if (key[i].dttk_size == 0) {
1308 			uint64_t val = key[i].dttk_value;
1309 
1310 			hashval += (val >> 48) & 0xffff;
1311 			hashval += (hashval << 10);
1312 			hashval ^= (hashval >> 6);
1313 
1314 			hashval += (val >> 32) & 0xffff;
1315 			hashval += (hashval << 10);
1316 			hashval ^= (hashval >> 6);
1317 
1318 			hashval += (val >> 16) & 0xffff;
1319 			hashval += (hashval << 10);
1320 			hashval ^= (hashval >> 6);
1321 
1322 			hashval += val & 0xffff;
1323 			hashval += (hashval << 10);
1324 			hashval ^= (hashval >> 6);
1325 		} else {
1326 			/*
1327 			 * This is incredibly painful, but it beats the hell
1328 			 * out of the alternative.
1329 			 */
1330 			uint64_t j, size = key[i].dttk_size;
1331 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1332 
1333 			if (!dtrace_canload(base, size, mstate, vstate))
1334 				break;
1335 
1336 			for (j = 0; j < size; j++) {
1337 				hashval += dtrace_load8(base + j);
1338 				hashval += (hashval << 10);
1339 				hashval ^= (hashval >> 6);
1340 			}
1341 		}
1342 	}
1343 
1344 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1345 		return (NULL);
1346 
1347 	hashval += (hashval << 3);
1348 	hashval ^= (hashval >> 11);
1349 	hashval += (hashval << 15);
1350 
1351 	/*
1352 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1353 	 * comes out to be one of our two sentinel hash values.  If this
1354 	 * actually happens, we set the hashval to be a value known to be a
1355 	 * non-sentinel value.
1356 	 */
1357 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1358 		hashval = DTRACE_DYNHASH_VALID;
1359 
1360 	/*
1361 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1362 	 * important here, tricks can be pulled to reduce it.  (However, it's
1363 	 * critical that hash collisions be kept to an absolute minimum;
1364 	 * they're much more painful than a divide.)  It's better to have a
1365 	 * solution that generates few collisions and still keeps things
1366 	 * relatively simple.
1367 	 */
1368 	bucket = hashval % dstate->dtds_hashsize;
1369 
1370 	if (op == DTRACE_DYNVAR_DEALLOC) {
1371 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1372 
1373 		for (;;) {
1374 			while ((lock = *lockp) & 1)
1375 				continue;
1376 
1377 			if (dtrace_casptr((void *)lockp,
1378 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1379 				break;
1380 		}
1381 
1382 		dtrace_membar_producer();
1383 	}
1384 
1385 top:
1386 	prev = NULL;
1387 	lock = hash[bucket].dtdh_lock;
1388 
1389 	dtrace_membar_consumer();
1390 
1391 	start = hash[bucket].dtdh_chain;
1392 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1393 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1394 	    op != DTRACE_DYNVAR_DEALLOC));
1395 
1396 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1397 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1398 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1399 
1400 		if (dvar->dtdv_hashval != hashval) {
1401 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1402 				/*
1403 				 * We've reached the sink, and therefore the
1404 				 * end of the hash chain; we can kick out of
1405 				 * the loop knowing that we have seen a valid
1406 				 * snapshot of state.
1407 				 */
1408 				ASSERT(dvar->dtdv_next == NULL);
1409 				ASSERT(dvar == &dtrace_dynhash_sink);
1410 				break;
1411 			}
1412 
1413 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1414 				/*
1415 				 * We've gone off the rails:  somewhere along
1416 				 * the line, one of the members of this hash
1417 				 * chain was deleted.  Note that we could also
1418 				 * detect this by simply letting this loop run
1419 				 * to completion, as we would eventually hit
1420 				 * the end of the dirty list.  However, we
1421 				 * want to avoid running the length of the
1422 				 * dirty list unnecessarily (it might be quite
1423 				 * long), so we catch this as early as
1424 				 * possible by detecting the hash marker.  In
1425 				 * this case, we simply set dvar to NULL and
1426 				 * break; the conditional after the loop will
1427 				 * send us back to top.
1428 				 */
1429 				dvar = NULL;
1430 				break;
1431 			}
1432 
1433 			goto next;
1434 		}
1435 
1436 		if (dtuple->dtt_nkeys != nkeys)
1437 			goto next;
1438 
1439 		for (i = 0; i < nkeys; i++, dkey++) {
1440 			if (dkey->dttk_size != key[i].dttk_size)
1441 				goto next; /* size or type mismatch */
1442 
1443 			if (dkey->dttk_size != 0) {
1444 				if (dtrace_bcmp(
1445 				    (void *)(uintptr_t)key[i].dttk_value,
1446 				    (void *)(uintptr_t)dkey->dttk_value,
1447 				    dkey->dttk_size))
1448 					goto next;
1449 			} else {
1450 				if (dkey->dttk_value != key[i].dttk_value)
1451 					goto next;
1452 			}
1453 		}
1454 
1455 		if (op != DTRACE_DYNVAR_DEALLOC)
1456 			return (dvar);
1457 
1458 		ASSERT(dvar->dtdv_next == NULL ||
1459 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1460 
1461 		if (prev != NULL) {
1462 			ASSERT(hash[bucket].dtdh_chain != dvar);
1463 			ASSERT(start != dvar);
1464 			ASSERT(prev->dtdv_next == dvar);
1465 			prev->dtdv_next = dvar->dtdv_next;
1466 		} else {
1467 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1468 			    start, dvar->dtdv_next) != start) {
1469 				/*
1470 				 * We have failed to atomically swing the
1471 				 * hash table head pointer, presumably because
1472 				 * of a conflicting allocation on another CPU.
1473 				 * We need to reread the hash chain and try
1474 				 * again.
1475 				 */
1476 				goto top;
1477 			}
1478 		}
1479 
1480 		dtrace_membar_producer();
1481 
1482 		/*
1483 		 * Now set the hash value to indicate that it's free.
1484 		 */
1485 		ASSERT(hash[bucket].dtdh_chain != dvar);
1486 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1487 
1488 		dtrace_membar_producer();
1489 
1490 		/*
1491 		 * Set the next pointer to point at the dirty list, and
1492 		 * atomically swing the dirty pointer to the newly freed dvar.
1493 		 */
1494 		do {
1495 			next = dcpu->dtdsc_dirty;
1496 			dvar->dtdv_next = next;
1497 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1498 
1499 		/*
1500 		 * Finally, unlock this hash bucket.
1501 		 */
1502 		ASSERT(hash[bucket].dtdh_lock == lock);
1503 		ASSERT(lock & 1);
1504 		hash[bucket].dtdh_lock++;
1505 
1506 		return (NULL);
1507 next:
1508 		prev = dvar;
1509 		continue;
1510 	}
1511 
1512 	if (dvar == NULL) {
1513 		/*
1514 		 * If dvar is NULL, it is because we went off the rails:
1515 		 * one of the elements that we traversed in the hash chain
1516 		 * was deleted while we were traversing it.  In this case,
1517 		 * we assert that we aren't doing a dealloc (deallocs lock
1518 		 * the hash bucket to prevent themselves from racing with
1519 		 * one another), and retry the hash chain traversal.
1520 		 */
1521 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1522 		goto top;
1523 	}
1524 
1525 	if (op != DTRACE_DYNVAR_ALLOC) {
1526 		/*
1527 		 * If we are not to allocate a new variable, we want to
1528 		 * return NULL now.  Before we return, check that the value
1529 		 * of the lock word hasn't changed.  If it has, we may have
1530 		 * seen an inconsistent snapshot.
1531 		 */
1532 		if (op == DTRACE_DYNVAR_NOALLOC) {
1533 			if (hash[bucket].dtdh_lock != lock)
1534 				goto top;
1535 		} else {
1536 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1537 			ASSERT(hash[bucket].dtdh_lock == lock);
1538 			ASSERT(lock & 1);
1539 			hash[bucket].dtdh_lock++;
1540 		}
1541 
1542 		return (NULL);
1543 	}
1544 
1545 	/*
1546 	 * We need to allocate a new dynamic variable.  The size we need is the
1547 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1548 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1549 	 * the size of any referred-to data (dsize).  We then round the final
1550 	 * size up to the chunksize for allocation.
1551 	 */
1552 	for (ksize = 0, i = 0; i < nkeys; i++)
1553 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1554 
1555 	/*
1556 	 * This should be pretty much impossible, but could happen if, say,
1557 	 * strange DIF specified the tuple.  Ideally, this should be an
1558 	 * assertion and not an error condition -- but that requires that the
1559 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1560 	 * bullet-proof.  (That is, it must not be able to be fooled by
1561 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1562 	 * solving this would presumably not amount to solving the Halting
1563 	 * Problem -- but it still seems awfully hard.
1564 	 */
1565 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1566 	    ksize + dsize > chunksize) {
1567 		dcpu->dtdsc_drops++;
1568 		return (NULL);
1569 	}
1570 
1571 	nstate = DTRACE_DSTATE_EMPTY;
1572 
1573 	do {
1574 retry:
1575 		free = dcpu->dtdsc_free;
1576 
1577 		if (free == NULL) {
1578 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1579 			void *rval;
1580 
1581 			if (clean == NULL) {
1582 				/*
1583 				 * We're out of dynamic variable space on
1584 				 * this CPU.  Unless we have tried all CPUs,
1585 				 * we'll try to allocate from a different
1586 				 * CPU.
1587 				 */
1588 				switch (dstate->dtds_state) {
1589 				case DTRACE_DSTATE_CLEAN: {
1590 					void *sp = &dstate->dtds_state;
1591 
1592 					if (++cpu >= NCPU)
1593 						cpu = 0;
1594 
1595 					if (dcpu->dtdsc_dirty != NULL &&
1596 					    nstate == DTRACE_DSTATE_EMPTY)
1597 						nstate = DTRACE_DSTATE_DIRTY;
1598 
1599 					if (dcpu->dtdsc_rinsing != NULL)
1600 						nstate = DTRACE_DSTATE_RINSING;
1601 
1602 					dcpu = &dstate->dtds_percpu[cpu];
1603 
1604 					if (cpu != me)
1605 						goto retry;
1606 
1607 					(void) dtrace_cas32(sp,
1608 					    DTRACE_DSTATE_CLEAN, nstate);
1609 
1610 					/*
1611 					 * To increment the correct bean
1612 					 * counter, take another lap.
1613 					 */
1614 					goto retry;
1615 				}
1616 
1617 				case DTRACE_DSTATE_DIRTY:
1618 					dcpu->dtdsc_dirty_drops++;
1619 					break;
1620 
1621 				case DTRACE_DSTATE_RINSING:
1622 					dcpu->dtdsc_rinsing_drops++;
1623 					break;
1624 
1625 				case DTRACE_DSTATE_EMPTY:
1626 					dcpu->dtdsc_drops++;
1627 					break;
1628 				}
1629 
1630 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1631 				return (NULL);
1632 			}
1633 
1634 			/*
1635 			 * The clean list appears to be non-empty.  We want to
1636 			 * move the clean list to the free list; we start by
1637 			 * moving the clean pointer aside.
1638 			 */
1639 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1640 			    clean, NULL) != clean) {
1641 				/*
1642 				 * We are in one of two situations:
1643 				 *
1644 				 *  (a)	The clean list was switched to the
1645 				 *	free list by another CPU.
1646 				 *
1647 				 *  (b)	The clean list was added to by the
1648 				 *	cleansing cyclic.
1649 				 *
1650 				 * In either of these situations, we can
1651 				 * just reattempt the free list allocation.
1652 				 */
1653 				goto retry;
1654 			}
1655 
1656 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1657 
1658 			/*
1659 			 * Now we'll move the clean list to the free list.
1660 			 * It's impossible for this to fail:  the only way
1661 			 * the free list can be updated is through this
1662 			 * code path, and only one CPU can own the clean list.
1663 			 * Thus, it would only be possible for this to fail if
1664 			 * this code were racing with dtrace_dynvar_clean().
1665 			 * (That is, if dtrace_dynvar_clean() updated the clean
1666 			 * list, and we ended up racing to update the free
1667 			 * list.)  This race is prevented by the dtrace_sync()
1668 			 * in dtrace_dynvar_clean() -- which flushes the
1669 			 * owners of the clean lists out before resetting
1670 			 * the clean lists.
1671 			 */
1672 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1673 			ASSERT(rval == NULL);
1674 			goto retry;
1675 		}
1676 
1677 		dvar = free;
1678 		new_free = dvar->dtdv_next;
1679 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1680 
1681 	/*
1682 	 * We have now allocated a new chunk.  We copy the tuple keys into the
1683 	 * tuple array and copy any referenced key data into the data space
1684 	 * following the tuple array.  As we do this, we relocate dttk_value
1685 	 * in the final tuple to point to the key data address in the chunk.
1686 	 */
1687 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1688 	dvar->dtdv_data = (void *)(kdata + ksize);
1689 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
1690 
1691 	for (i = 0; i < nkeys; i++) {
1692 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1693 		size_t kesize = key[i].dttk_size;
1694 
1695 		if (kesize != 0) {
1696 			dtrace_bcopy(
1697 			    (const void *)(uintptr_t)key[i].dttk_value,
1698 			    (void *)kdata, kesize);
1699 			dkey->dttk_value = kdata;
1700 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1701 		} else {
1702 			dkey->dttk_value = key[i].dttk_value;
1703 		}
1704 
1705 		dkey->dttk_size = kesize;
1706 	}
1707 
1708 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1709 	dvar->dtdv_hashval = hashval;
1710 	dvar->dtdv_next = start;
1711 
1712 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1713 		return (dvar);
1714 
1715 	/*
1716 	 * The cas has failed.  Either another CPU is adding an element to
1717 	 * this hash chain, or another CPU is deleting an element from this
1718 	 * hash chain.  The simplest way to deal with both of these cases
1719 	 * (though not necessarily the most efficient) is to free our
1720 	 * allocated block and tail-call ourselves.  Note that the free is
1721 	 * to the dirty list and _not_ to the free list.  This is to prevent
1722 	 * races with allocators, above.
1723 	 */
1724 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1725 
1726 	dtrace_membar_producer();
1727 
1728 	do {
1729 		free = dcpu->dtdsc_dirty;
1730 		dvar->dtdv_next = free;
1731 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1732 
1733 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1734 }
1735 
1736 /*ARGSUSED*/
1737 static void
1738 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1739 {
1740 	if ((int64_t)nval < (int64_t)*oval)
1741 		*oval = nval;
1742 }
1743 
1744 /*ARGSUSED*/
1745 static void
1746 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1747 {
1748 	if ((int64_t)nval > (int64_t)*oval)
1749 		*oval = nval;
1750 }
1751 
1752 static void
1753 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1754 {
1755 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1756 	int64_t val = (int64_t)nval;
1757 
1758 	if (val < 0) {
1759 		for (i = 0; i < zero; i++) {
1760 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1761 				quanta[i] += incr;
1762 				return;
1763 			}
1764 		}
1765 	} else {
1766 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1767 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1768 				quanta[i - 1] += incr;
1769 				return;
1770 			}
1771 		}
1772 
1773 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1774 		return;
1775 	}
1776 
1777 	ASSERT(0);
1778 }
1779 
1780 static void
1781 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1782 {
1783 	uint64_t arg = *lquanta++;
1784 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1785 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1786 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1787 	int32_t val = (int32_t)nval, level;
1788 
1789 	ASSERT(step != 0);
1790 	ASSERT(levels != 0);
1791 
1792 	if (val < base) {
1793 		/*
1794 		 * This is an underflow.
1795 		 */
1796 		lquanta[0] += incr;
1797 		return;
1798 	}
1799 
1800 	level = (val - base) / step;
1801 
1802 	if (level < levels) {
1803 		lquanta[level + 1] += incr;
1804 		return;
1805 	}
1806 
1807 	/*
1808 	 * This is an overflow.
1809 	 */
1810 	lquanta[levels + 1] += incr;
1811 }
1812 
1813 /*ARGSUSED*/
1814 static void
1815 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
1816 {
1817 	data[0]++;
1818 	data[1] += nval;
1819 }
1820 
1821 /*ARGSUSED*/
1822 static void
1823 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
1824 {
1825 	int64_t snval = (int64_t)nval;
1826 	uint64_t tmp[2];
1827 
1828 	data[0]++;
1829 	data[1] += nval;
1830 
1831 	/*
1832 	 * What we want to say here is:
1833 	 *
1834 	 * data[2] += nval * nval;
1835 	 *
1836 	 * But given that nval is 64-bit, we could easily overflow, so
1837 	 * we do this as 128-bit arithmetic.
1838 	 */
1839 	if (snval < 0)
1840 		snval = -snval;
1841 
1842 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
1843 	dtrace_add_128(data + 2, tmp, data + 2);
1844 }
1845 
1846 /*ARGSUSED*/
1847 static void
1848 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
1849 {
1850 	*oval = *oval + 1;
1851 }
1852 
1853 /*ARGSUSED*/
1854 static void
1855 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
1856 {
1857 	*oval += nval;
1858 }
1859 
1860 /*
1861  * Aggregate given the tuple in the principal data buffer, and the aggregating
1862  * action denoted by the specified dtrace_aggregation_t.  The aggregation
1863  * buffer is specified as the buf parameter.  This routine does not return
1864  * failure; if there is no space in the aggregation buffer, the data will be
1865  * dropped, and a corresponding counter incremented.
1866  */
1867 static void
1868 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
1869     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
1870 {
1871 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
1872 	uint32_t i, ndx, size, fsize;
1873 	uint32_t align = sizeof (uint64_t) - 1;
1874 	dtrace_aggbuffer_t *agb;
1875 	dtrace_aggkey_t *key;
1876 	uint32_t hashval = 0, limit, isstr;
1877 	caddr_t tomax, data, kdata;
1878 	dtrace_actkind_t action;
1879 	dtrace_action_t *act;
1880 	uintptr_t offs;
1881 
1882 	if (buf == NULL)
1883 		return;
1884 
1885 	if (!agg->dtag_hasarg) {
1886 		/*
1887 		 * Currently, only quantize() and lquantize() take additional
1888 		 * arguments, and they have the same semantics:  an increment
1889 		 * value that defaults to 1 when not present.  If additional
1890 		 * aggregating actions take arguments, the setting of the
1891 		 * default argument value will presumably have to become more
1892 		 * sophisticated...
1893 		 */
1894 		arg = 1;
1895 	}
1896 
1897 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
1898 	size = rec->dtrd_offset - agg->dtag_base;
1899 	fsize = size + rec->dtrd_size;
1900 
1901 	ASSERT(dbuf->dtb_tomax != NULL);
1902 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
1903 
1904 	if ((tomax = buf->dtb_tomax) == NULL) {
1905 		dtrace_buffer_drop(buf);
1906 		return;
1907 	}
1908 
1909 	/*
1910 	 * The metastructure is always at the bottom of the buffer.
1911 	 */
1912 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
1913 	    sizeof (dtrace_aggbuffer_t));
1914 
1915 	if (buf->dtb_offset == 0) {
1916 		/*
1917 		 * We just kludge up approximately 1/8th of the size to be
1918 		 * buckets.  If this guess ends up being routinely
1919 		 * off-the-mark, we may need to dynamically readjust this
1920 		 * based on past performance.
1921 		 */
1922 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
1923 
1924 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
1925 		    (uintptr_t)tomax || hashsize == 0) {
1926 			/*
1927 			 * We've been given a ludicrously small buffer;
1928 			 * increment our drop count and leave.
1929 			 */
1930 			dtrace_buffer_drop(buf);
1931 			return;
1932 		}
1933 
1934 		/*
1935 		 * And now, a pathetic attempt to try to get a an odd (or
1936 		 * perchance, a prime) hash size for better hash distribution.
1937 		 */
1938 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
1939 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
1940 
1941 		agb->dtagb_hashsize = hashsize;
1942 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
1943 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
1944 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
1945 
1946 		for (i = 0; i < agb->dtagb_hashsize; i++)
1947 			agb->dtagb_hash[i] = NULL;
1948 	}
1949 
1950 	ASSERT(agg->dtag_first != NULL);
1951 	ASSERT(agg->dtag_first->dta_intuple);
1952 
1953 	/*
1954 	 * Calculate the hash value based on the key.  Note that we _don't_
1955 	 * include the aggid in the hashing (but we will store it as part of
1956 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
1957 	 * algorithm: a simple, quick algorithm that has no known funnels, and
1958 	 * gets good distribution in practice.  The efficacy of the hashing
1959 	 * algorithm (and a comparison with other algorithms) may be found by
1960 	 * running the ::dtrace_aggstat MDB dcmd.
1961 	 */
1962 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1963 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1964 		limit = i + act->dta_rec.dtrd_size;
1965 		ASSERT(limit <= size);
1966 		isstr = DTRACEACT_ISSTRING(act);
1967 
1968 		for (; i < limit; i++) {
1969 			hashval += data[i];
1970 			hashval += (hashval << 10);
1971 			hashval ^= (hashval >> 6);
1972 
1973 			if (isstr && data[i] == '\0')
1974 				break;
1975 		}
1976 	}
1977 
1978 	hashval += (hashval << 3);
1979 	hashval ^= (hashval >> 11);
1980 	hashval += (hashval << 15);
1981 
1982 	/*
1983 	 * Yes, the divide here is expensive -- but it's generally the least
1984 	 * of the performance issues given the amount of data that we iterate
1985 	 * over to compute hash values, compare data, etc.
1986 	 */
1987 	ndx = hashval % agb->dtagb_hashsize;
1988 
1989 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
1990 		ASSERT((caddr_t)key >= tomax);
1991 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
1992 
1993 		if (hashval != key->dtak_hashval || key->dtak_size != size)
1994 			continue;
1995 
1996 		kdata = key->dtak_data;
1997 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
1998 
1999 		for (act = agg->dtag_first; act->dta_intuple;
2000 		    act = act->dta_next) {
2001 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2002 			limit = i + act->dta_rec.dtrd_size;
2003 			ASSERT(limit <= size);
2004 			isstr = DTRACEACT_ISSTRING(act);
2005 
2006 			for (; i < limit; i++) {
2007 				if (kdata[i] != data[i])
2008 					goto next;
2009 
2010 				if (isstr && data[i] == '\0')
2011 					break;
2012 			}
2013 		}
2014 
2015 		if (action != key->dtak_action) {
2016 			/*
2017 			 * We are aggregating on the same value in the same
2018 			 * aggregation with two different aggregating actions.
2019 			 * (This should have been picked up in the compiler,
2020 			 * so we may be dealing with errant or devious DIF.)
2021 			 * This is an error condition; we indicate as much,
2022 			 * and return.
2023 			 */
2024 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2025 			return;
2026 		}
2027 
2028 		/*
2029 		 * This is a hit:  we need to apply the aggregator to
2030 		 * the value at this key.
2031 		 */
2032 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2033 		return;
2034 next:
2035 		continue;
2036 	}
2037 
2038 	/*
2039 	 * We didn't find it.  We need to allocate some zero-filled space,
2040 	 * link it into the hash table appropriately, and apply the aggregator
2041 	 * to the (zero-filled) value.
2042 	 */
2043 	offs = buf->dtb_offset;
2044 	while (offs & (align - 1))
2045 		offs += sizeof (uint32_t);
2046 
2047 	/*
2048 	 * If we don't have enough room to both allocate a new key _and_
2049 	 * its associated data, increment the drop count and return.
2050 	 */
2051 	if ((uintptr_t)tomax + offs + fsize >
2052 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2053 		dtrace_buffer_drop(buf);
2054 		return;
2055 	}
2056 
2057 	/*CONSTCOND*/
2058 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2059 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2060 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2061 
2062 	key->dtak_data = kdata = tomax + offs;
2063 	buf->dtb_offset = offs + fsize;
2064 
2065 	/*
2066 	 * Now copy the data across.
2067 	 */
2068 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2069 
2070 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2071 		kdata[i] = data[i];
2072 
2073 	/*
2074 	 * Because strings are not zeroed out by default, we need to iterate
2075 	 * looking for actions that store strings, and we need to explicitly
2076 	 * pad these strings out with zeroes.
2077 	 */
2078 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2079 		int nul;
2080 
2081 		if (!DTRACEACT_ISSTRING(act))
2082 			continue;
2083 
2084 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2085 		limit = i + act->dta_rec.dtrd_size;
2086 		ASSERT(limit <= size);
2087 
2088 		for (nul = 0; i < limit; i++) {
2089 			if (nul) {
2090 				kdata[i] = '\0';
2091 				continue;
2092 			}
2093 
2094 			if (data[i] != '\0')
2095 				continue;
2096 
2097 			nul = 1;
2098 		}
2099 	}
2100 
2101 	for (i = size; i < fsize; i++)
2102 		kdata[i] = 0;
2103 
2104 	key->dtak_hashval = hashval;
2105 	key->dtak_size = size;
2106 	key->dtak_action = action;
2107 	key->dtak_next = agb->dtagb_hash[ndx];
2108 	agb->dtagb_hash[ndx] = key;
2109 
2110 	/*
2111 	 * Finally, apply the aggregator.
2112 	 */
2113 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2114 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2115 }
2116 
2117 /*
2118  * Given consumer state, this routine finds a speculation in the INACTIVE
2119  * state and transitions it into the ACTIVE state.  If there is no speculation
2120  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2121  * incremented -- it is up to the caller to take appropriate action.
2122  */
2123 static int
2124 dtrace_speculation(dtrace_state_t *state)
2125 {
2126 	int i = 0;
2127 	dtrace_speculation_state_t current;
2128 	uint32_t *stat = &state->dts_speculations_unavail, count;
2129 
2130 	while (i < state->dts_nspeculations) {
2131 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2132 
2133 		current = spec->dtsp_state;
2134 
2135 		if (current != DTRACESPEC_INACTIVE) {
2136 			if (current == DTRACESPEC_COMMITTINGMANY ||
2137 			    current == DTRACESPEC_COMMITTING ||
2138 			    current == DTRACESPEC_DISCARDING)
2139 				stat = &state->dts_speculations_busy;
2140 			i++;
2141 			continue;
2142 		}
2143 
2144 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2145 		    current, DTRACESPEC_ACTIVE) == current)
2146 			return (i + 1);
2147 	}
2148 
2149 	/*
2150 	 * We couldn't find a speculation.  If we found as much as a single
2151 	 * busy speculation buffer, we'll attribute this failure as "busy"
2152 	 * instead of "unavail".
2153 	 */
2154 	do {
2155 		count = *stat;
2156 	} while (dtrace_cas32(stat, count, count + 1) != count);
2157 
2158 	return (0);
2159 }
2160 
2161 /*
2162  * This routine commits an active speculation.  If the specified speculation
2163  * is not in a valid state to perform a commit(), this routine will silently do
2164  * nothing.  The state of the specified speculation is transitioned according
2165  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2166  */
2167 static void
2168 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2169     dtrace_specid_t which)
2170 {
2171 	dtrace_speculation_t *spec;
2172 	dtrace_buffer_t *src, *dest;
2173 	uintptr_t daddr, saddr, dlimit;
2174 	dtrace_speculation_state_t current, new;
2175 	intptr_t offs;
2176 
2177 	if (which == 0)
2178 		return;
2179 
2180 	if (which > state->dts_nspeculations) {
2181 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2182 		return;
2183 	}
2184 
2185 	spec = &state->dts_speculations[which - 1];
2186 	src = &spec->dtsp_buffer[cpu];
2187 	dest = &state->dts_buffer[cpu];
2188 
2189 	do {
2190 		current = spec->dtsp_state;
2191 
2192 		if (current == DTRACESPEC_COMMITTINGMANY)
2193 			break;
2194 
2195 		switch (current) {
2196 		case DTRACESPEC_INACTIVE:
2197 		case DTRACESPEC_DISCARDING:
2198 			return;
2199 
2200 		case DTRACESPEC_COMMITTING:
2201 			/*
2202 			 * This is only possible if we are (a) commit()'ing
2203 			 * without having done a prior speculate() on this CPU
2204 			 * and (b) racing with another commit() on a different
2205 			 * CPU.  There's nothing to do -- we just assert that
2206 			 * our offset is 0.
2207 			 */
2208 			ASSERT(src->dtb_offset == 0);
2209 			return;
2210 
2211 		case DTRACESPEC_ACTIVE:
2212 			new = DTRACESPEC_COMMITTING;
2213 			break;
2214 
2215 		case DTRACESPEC_ACTIVEONE:
2216 			/*
2217 			 * This speculation is active on one CPU.  If our
2218 			 * buffer offset is non-zero, we know that the one CPU
2219 			 * must be us.  Otherwise, we are committing on a
2220 			 * different CPU from the speculate(), and we must
2221 			 * rely on being asynchronously cleaned.
2222 			 */
2223 			if (src->dtb_offset != 0) {
2224 				new = DTRACESPEC_COMMITTING;
2225 				break;
2226 			}
2227 			/*FALLTHROUGH*/
2228 
2229 		case DTRACESPEC_ACTIVEMANY:
2230 			new = DTRACESPEC_COMMITTINGMANY;
2231 			break;
2232 
2233 		default:
2234 			ASSERT(0);
2235 		}
2236 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2237 	    current, new) != current);
2238 
2239 	/*
2240 	 * We have set the state to indicate that we are committing this
2241 	 * speculation.  Now reserve the necessary space in the destination
2242 	 * buffer.
2243 	 */
2244 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2245 	    sizeof (uint64_t), state, NULL)) < 0) {
2246 		dtrace_buffer_drop(dest);
2247 		goto out;
2248 	}
2249 
2250 	/*
2251 	 * We have the space; copy the buffer across.  (Note that this is a
2252 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2253 	 * a serious performance issue, a high-performance DTrace-specific
2254 	 * bcopy() should obviously be invented.)
2255 	 */
2256 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2257 	dlimit = daddr + src->dtb_offset;
2258 	saddr = (uintptr_t)src->dtb_tomax;
2259 
2260 	/*
2261 	 * First, the aligned portion.
2262 	 */
2263 	while (dlimit - daddr >= sizeof (uint64_t)) {
2264 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2265 
2266 		daddr += sizeof (uint64_t);
2267 		saddr += sizeof (uint64_t);
2268 	}
2269 
2270 	/*
2271 	 * Now any left-over bit...
2272 	 */
2273 	while (dlimit - daddr)
2274 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2275 
2276 	/*
2277 	 * Finally, commit the reserved space in the destination buffer.
2278 	 */
2279 	dest->dtb_offset = offs + src->dtb_offset;
2280 
2281 out:
2282 	/*
2283 	 * If we're lucky enough to be the only active CPU on this speculation
2284 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2285 	 */
2286 	if (current == DTRACESPEC_ACTIVE ||
2287 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2288 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2289 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2290 
2291 		ASSERT(rval == DTRACESPEC_COMMITTING);
2292 	}
2293 
2294 	src->dtb_offset = 0;
2295 	src->dtb_xamot_drops += src->dtb_drops;
2296 	src->dtb_drops = 0;
2297 }
2298 
2299 /*
2300  * This routine discards an active speculation.  If the specified speculation
2301  * is not in a valid state to perform a discard(), this routine will silently
2302  * do nothing.  The state of the specified speculation is transitioned
2303  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2304  */
2305 static void
2306 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2307     dtrace_specid_t which)
2308 {
2309 	dtrace_speculation_t *spec;
2310 	dtrace_speculation_state_t current, new;
2311 	dtrace_buffer_t *buf;
2312 
2313 	if (which == 0)
2314 		return;
2315 
2316 	if (which > state->dts_nspeculations) {
2317 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2318 		return;
2319 	}
2320 
2321 	spec = &state->dts_speculations[which - 1];
2322 	buf = &spec->dtsp_buffer[cpu];
2323 
2324 	do {
2325 		current = spec->dtsp_state;
2326 
2327 		switch (current) {
2328 		case DTRACESPEC_INACTIVE:
2329 		case DTRACESPEC_COMMITTINGMANY:
2330 		case DTRACESPEC_COMMITTING:
2331 		case DTRACESPEC_DISCARDING:
2332 			return;
2333 
2334 		case DTRACESPEC_ACTIVE:
2335 		case DTRACESPEC_ACTIVEMANY:
2336 			new = DTRACESPEC_DISCARDING;
2337 			break;
2338 
2339 		case DTRACESPEC_ACTIVEONE:
2340 			if (buf->dtb_offset != 0) {
2341 				new = DTRACESPEC_INACTIVE;
2342 			} else {
2343 				new = DTRACESPEC_DISCARDING;
2344 			}
2345 			break;
2346 
2347 		default:
2348 			ASSERT(0);
2349 		}
2350 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2351 	    current, new) != current);
2352 
2353 	buf->dtb_offset = 0;
2354 	buf->dtb_drops = 0;
2355 }
2356 
2357 /*
2358  * Note:  not called from probe context.  This function is called
2359  * asynchronously from cross call context to clean any speculations that are
2360  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2361  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2362  * speculation.
2363  */
2364 static void
2365 dtrace_speculation_clean_here(dtrace_state_t *state)
2366 {
2367 	dtrace_icookie_t cookie;
2368 	processorid_t cpu = CPU->cpu_id;
2369 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2370 	dtrace_specid_t i;
2371 
2372 	cookie = dtrace_interrupt_disable();
2373 
2374 	if (dest->dtb_tomax == NULL) {
2375 		dtrace_interrupt_enable(cookie);
2376 		return;
2377 	}
2378 
2379 	for (i = 0; i < state->dts_nspeculations; i++) {
2380 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2381 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2382 
2383 		if (src->dtb_tomax == NULL)
2384 			continue;
2385 
2386 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2387 			src->dtb_offset = 0;
2388 			continue;
2389 		}
2390 
2391 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2392 			continue;
2393 
2394 		if (src->dtb_offset == 0)
2395 			continue;
2396 
2397 		dtrace_speculation_commit(state, cpu, i + 1);
2398 	}
2399 
2400 	dtrace_interrupt_enable(cookie);
2401 }
2402 
2403 /*
2404  * Note:  not called from probe context.  This function is called
2405  * asynchronously (and at a regular interval) to clean any speculations that
2406  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2407  * is work to be done, it cross calls all CPUs to perform that work;
2408  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2409  * INACTIVE state until they have been cleaned by all CPUs.
2410  */
2411 static void
2412 dtrace_speculation_clean(dtrace_state_t *state)
2413 {
2414 	int work = 0, rv;
2415 	dtrace_specid_t i;
2416 
2417 	for (i = 0; i < state->dts_nspeculations; i++) {
2418 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2419 
2420 		ASSERT(!spec->dtsp_cleaning);
2421 
2422 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2423 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2424 			continue;
2425 
2426 		work++;
2427 		spec->dtsp_cleaning = 1;
2428 	}
2429 
2430 	if (!work)
2431 		return;
2432 
2433 	dtrace_xcall(DTRACE_CPUALL,
2434 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2435 
2436 	/*
2437 	 * We now know that all CPUs have committed or discarded their
2438 	 * speculation buffers, as appropriate.  We can now set the state
2439 	 * to inactive.
2440 	 */
2441 	for (i = 0; i < state->dts_nspeculations; i++) {
2442 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2443 		dtrace_speculation_state_t current, new;
2444 
2445 		if (!spec->dtsp_cleaning)
2446 			continue;
2447 
2448 		current = spec->dtsp_state;
2449 		ASSERT(current == DTRACESPEC_DISCARDING ||
2450 		    current == DTRACESPEC_COMMITTINGMANY);
2451 
2452 		new = DTRACESPEC_INACTIVE;
2453 
2454 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2455 		ASSERT(rv == current);
2456 		spec->dtsp_cleaning = 0;
2457 	}
2458 }
2459 
2460 /*
2461  * Called as part of a speculate() to get the speculative buffer associated
2462  * with a given speculation.  Returns NULL if the specified speculation is not
2463  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2464  * the active CPU is not the specified CPU -- the speculation will be
2465  * atomically transitioned into the ACTIVEMANY state.
2466  */
2467 static dtrace_buffer_t *
2468 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2469     dtrace_specid_t which)
2470 {
2471 	dtrace_speculation_t *spec;
2472 	dtrace_speculation_state_t current, new;
2473 	dtrace_buffer_t *buf;
2474 
2475 	if (which == 0)
2476 		return (NULL);
2477 
2478 	if (which > state->dts_nspeculations) {
2479 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2480 		return (NULL);
2481 	}
2482 
2483 	spec = &state->dts_speculations[which - 1];
2484 	buf = &spec->dtsp_buffer[cpuid];
2485 
2486 	do {
2487 		current = spec->dtsp_state;
2488 
2489 		switch (current) {
2490 		case DTRACESPEC_INACTIVE:
2491 		case DTRACESPEC_COMMITTINGMANY:
2492 		case DTRACESPEC_DISCARDING:
2493 			return (NULL);
2494 
2495 		case DTRACESPEC_COMMITTING:
2496 			ASSERT(buf->dtb_offset == 0);
2497 			return (NULL);
2498 
2499 		case DTRACESPEC_ACTIVEONE:
2500 			/*
2501 			 * This speculation is currently active on one CPU.
2502 			 * Check the offset in the buffer; if it's non-zero,
2503 			 * that CPU must be us (and we leave the state alone).
2504 			 * If it's zero, assume that we're starting on a new
2505 			 * CPU -- and change the state to indicate that the
2506 			 * speculation is active on more than one CPU.
2507 			 */
2508 			if (buf->dtb_offset != 0)
2509 				return (buf);
2510 
2511 			new = DTRACESPEC_ACTIVEMANY;
2512 			break;
2513 
2514 		case DTRACESPEC_ACTIVEMANY:
2515 			return (buf);
2516 
2517 		case DTRACESPEC_ACTIVE:
2518 			new = DTRACESPEC_ACTIVEONE;
2519 			break;
2520 
2521 		default:
2522 			ASSERT(0);
2523 		}
2524 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2525 	    current, new) != current);
2526 
2527 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2528 	return (buf);
2529 }
2530 
2531 /*
2532  * Return a string.  In the event that the user lacks the privilege to access
2533  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2534  * don't fail access checking.
2535  *
2536  * dtrace_dif_variable() uses this routine as a helper for various
2537  * builtin values such as 'execname' and 'probefunc.'
2538  */
2539 uintptr_t
2540 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2541     dtrace_mstate_t *mstate)
2542 {
2543 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2544 	uintptr_t ret;
2545 	size_t strsz;
2546 
2547 	/*
2548 	 * The easy case: this probe is allowed to read all of memory, so
2549 	 * we can just return this as a vanilla pointer.
2550 	 */
2551 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2552 		return (addr);
2553 
2554 	/*
2555 	 * This is the tougher case: we copy the string in question from
2556 	 * kernel memory into scratch memory and return it that way: this
2557 	 * ensures that we won't trip up when access checking tests the
2558 	 * BYREF return value.
2559 	 */
2560 	strsz = dtrace_strlen((char *)addr, size) + 1;
2561 
2562 	if (mstate->dtms_scratch_ptr + strsz >
2563 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2564 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2565 		return (NULL);
2566 	}
2567 
2568 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2569 	    strsz);
2570 	ret = mstate->dtms_scratch_ptr;
2571 	mstate->dtms_scratch_ptr += strsz;
2572 	return (ret);
2573 }
2574 
2575 /*
2576  * This function implements the DIF emulator's variable lookups.  The emulator
2577  * passes a reserved variable identifier and optional built-in array index.
2578  */
2579 static uint64_t
2580 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2581     uint64_t ndx)
2582 {
2583 	/*
2584 	 * If we're accessing one of the uncached arguments, we'll turn this
2585 	 * into a reference in the args array.
2586 	 */
2587 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2588 		ndx = v - DIF_VAR_ARG0;
2589 		v = DIF_VAR_ARGS;
2590 	}
2591 
2592 	switch (v) {
2593 	case DIF_VAR_ARGS:
2594 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2595 		if (ndx >= sizeof (mstate->dtms_arg) /
2596 		    sizeof (mstate->dtms_arg[0])) {
2597 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2598 			dtrace_provider_t *pv;
2599 			uint64_t val;
2600 
2601 			pv = mstate->dtms_probe->dtpr_provider;
2602 			if (pv->dtpv_pops.dtps_getargval != NULL)
2603 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2604 				    mstate->dtms_probe->dtpr_id,
2605 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
2606 			else
2607 				val = dtrace_getarg(ndx, aframes);
2608 
2609 			/*
2610 			 * This is regrettably required to keep the compiler
2611 			 * from tail-optimizing the call to dtrace_getarg().
2612 			 * The condition always evaluates to true, but the
2613 			 * compiler has no way of figuring that out a priori.
2614 			 * (None of this would be necessary if the compiler
2615 			 * could be relied upon to _always_ tail-optimize
2616 			 * the call to dtrace_getarg() -- but it can't.)
2617 			 */
2618 			if (mstate->dtms_probe != NULL)
2619 				return (val);
2620 
2621 			ASSERT(0);
2622 		}
2623 
2624 		return (mstate->dtms_arg[ndx]);
2625 
2626 	case DIF_VAR_UREGS: {
2627 		klwp_t *lwp;
2628 
2629 		if (!dtrace_priv_proc(state))
2630 			return (0);
2631 
2632 		if ((lwp = curthread->t_lwp) == NULL) {
2633 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2634 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
2635 			return (0);
2636 		}
2637 
2638 		return (dtrace_getreg(lwp->lwp_regs, ndx));
2639 	}
2640 
2641 	case DIF_VAR_CURTHREAD:
2642 		if (!dtrace_priv_kernel(state))
2643 			return (0);
2644 		return ((uint64_t)(uintptr_t)curthread);
2645 
2646 	case DIF_VAR_TIMESTAMP:
2647 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2648 			mstate->dtms_timestamp = dtrace_gethrtime();
2649 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2650 		}
2651 		return (mstate->dtms_timestamp);
2652 
2653 	case DIF_VAR_VTIMESTAMP:
2654 		ASSERT(dtrace_vtime_references != 0);
2655 		return (curthread->t_dtrace_vtime);
2656 
2657 	case DIF_VAR_WALLTIMESTAMP:
2658 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2659 			mstate->dtms_walltimestamp = dtrace_gethrestime();
2660 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2661 		}
2662 		return (mstate->dtms_walltimestamp);
2663 
2664 	case DIF_VAR_IPL:
2665 		if (!dtrace_priv_kernel(state))
2666 			return (0);
2667 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2668 			mstate->dtms_ipl = dtrace_getipl();
2669 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
2670 		}
2671 		return (mstate->dtms_ipl);
2672 
2673 	case DIF_VAR_EPID:
2674 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2675 		return (mstate->dtms_epid);
2676 
2677 	case DIF_VAR_ID:
2678 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2679 		return (mstate->dtms_probe->dtpr_id);
2680 
2681 	case DIF_VAR_STACKDEPTH:
2682 		if (!dtrace_priv_kernel(state))
2683 			return (0);
2684 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2685 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2686 
2687 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2688 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2689 		}
2690 		return (mstate->dtms_stackdepth);
2691 
2692 	case DIF_VAR_USTACKDEPTH:
2693 		if (!dtrace_priv_proc(state))
2694 			return (0);
2695 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2696 			/*
2697 			 * See comment in DIF_VAR_PID.
2698 			 */
2699 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2700 			    CPU_ON_INTR(CPU)) {
2701 				mstate->dtms_ustackdepth = 0;
2702 			} else {
2703 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2704 				mstate->dtms_ustackdepth =
2705 				    dtrace_getustackdepth();
2706 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2707 			}
2708 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2709 		}
2710 		return (mstate->dtms_ustackdepth);
2711 
2712 	case DIF_VAR_CALLER:
2713 		if (!dtrace_priv_kernel(state))
2714 			return (0);
2715 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2716 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2717 
2718 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2719 				/*
2720 				 * If this is an unanchored probe, we are
2721 				 * required to go through the slow path:
2722 				 * dtrace_caller() only guarantees correct
2723 				 * results for anchored probes.
2724 				 */
2725 				pc_t caller[2];
2726 
2727 				dtrace_getpcstack(caller, 2, aframes,
2728 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2729 				mstate->dtms_caller = caller[1];
2730 			} else if ((mstate->dtms_caller =
2731 			    dtrace_caller(aframes)) == -1) {
2732 				/*
2733 				 * We have failed to do this the quick way;
2734 				 * we must resort to the slower approach of
2735 				 * calling dtrace_getpcstack().
2736 				 */
2737 				pc_t caller;
2738 
2739 				dtrace_getpcstack(&caller, 1, aframes, NULL);
2740 				mstate->dtms_caller = caller;
2741 			}
2742 
2743 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
2744 		}
2745 		return (mstate->dtms_caller);
2746 
2747 	case DIF_VAR_UCALLER:
2748 		if (!dtrace_priv_proc(state))
2749 			return (0);
2750 
2751 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
2752 			uint64_t ustack[3];
2753 
2754 			/*
2755 			 * dtrace_getupcstack() fills in the first uint64_t
2756 			 * with the current PID.  The second uint64_t will
2757 			 * be the program counter at user-level.  The third
2758 			 * uint64_t will contain the caller, which is what
2759 			 * we're after.
2760 			 */
2761 			ustack[2] = NULL;
2762 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2763 			dtrace_getupcstack(ustack, 3);
2764 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2765 			mstate->dtms_ucaller = ustack[2];
2766 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
2767 		}
2768 
2769 		return (mstate->dtms_ucaller);
2770 
2771 	case DIF_VAR_PROBEPROV:
2772 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2773 		return (dtrace_dif_varstr(
2774 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
2775 		    state, mstate));
2776 
2777 	case DIF_VAR_PROBEMOD:
2778 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2779 		return (dtrace_dif_varstr(
2780 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
2781 		    state, mstate));
2782 
2783 	case DIF_VAR_PROBEFUNC:
2784 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2785 		return (dtrace_dif_varstr(
2786 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
2787 		    state, mstate));
2788 
2789 	case DIF_VAR_PROBENAME:
2790 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2791 		return (dtrace_dif_varstr(
2792 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
2793 		    state, mstate));
2794 
2795 	case DIF_VAR_PID:
2796 		if (!dtrace_priv_proc(state))
2797 			return (0);
2798 
2799 		/*
2800 		 * Note that we are assuming that an unanchored probe is
2801 		 * always due to a high-level interrupt.  (And we're assuming
2802 		 * that there is only a single high level interrupt.)
2803 		 */
2804 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2805 			return (pid0.pid_id);
2806 
2807 		/*
2808 		 * It is always safe to dereference one's own t_procp pointer:
2809 		 * it always points to a valid, allocated proc structure.
2810 		 * Further, it is always safe to dereference the p_pidp member
2811 		 * of one's own proc structure.  (These are truisms becuase
2812 		 * threads and processes don't clean up their own state --
2813 		 * they leave that task to whomever reaps them.)
2814 		 */
2815 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
2816 
2817 	case DIF_VAR_PPID:
2818 		if (!dtrace_priv_proc(state))
2819 			return (0);
2820 
2821 		/*
2822 		 * See comment in DIF_VAR_PID.
2823 		 */
2824 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2825 			return (pid0.pid_id);
2826 
2827 		/*
2828 		 * It is always safe to dereference one's own t_procp pointer:
2829 		 * it always points to a valid, allocated proc structure.
2830 		 * (This is true because threads don't clean up their own
2831 		 * state -- they leave that task to whomever reaps them.)
2832 		 */
2833 		return ((uint64_t)curthread->t_procp->p_ppid);
2834 
2835 	case DIF_VAR_TID:
2836 		/*
2837 		 * See comment in DIF_VAR_PID.
2838 		 */
2839 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2840 			return (0);
2841 
2842 		return ((uint64_t)curthread->t_tid);
2843 
2844 	case DIF_VAR_EXECNAME:
2845 		if (!dtrace_priv_proc(state))
2846 			return (0);
2847 
2848 		/*
2849 		 * See comment in DIF_VAR_PID.
2850 		 */
2851 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2852 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
2853 
2854 		/*
2855 		 * It is always safe to dereference one's own t_procp pointer:
2856 		 * it always points to a valid, allocated proc structure.
2857 		 * (This is true because threads don't clean up their own
2858 		 * state -- they leave that task to whomever reaps them.)
2859 		 */
2860 		return (dtrace_dif_varstr(
2861 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
2862 		    state, mstate));
2863 
2864 	case DIF_VAR_ZONENAME:
2865 		if (!dtrace_priv_proc(state))
2866 			return (0);
2867 
2868 		/*
2869 		 * See comment in DIF_VAR_PID.
2870 		 */
2871 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2872 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
2873 
2874 		/*
2875 		 * It is always safe to dereference one's own t_procp pointer:
2876 		 * it always points to a valid, allocated proc structure.
2877 		 * (This is true because threads don't clean up their own
2878 		 * state -- they leave that task to whomever reaps them.)
2879 		 */
2880 		return (dtrace_dif_varstr(
2881 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
2882 		    state, mstate));
2883 
2884 	case DIF_VAR_UID:
2885 		if (!dtrace_priv_proc(state))
2886 			return (0);
2887 
2888 		/*
2889 		 * See comment in DIF_VAR_PID.
2890 		 */
2891 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2892 			return ((uint64_t)p0.p_cred->cr_uid);
2893 
2894 		/*
2895 		 * It is always safe to dereference one's own t_procp pointer:
2896 		 * it always points to a valid, allocated proc structure.
2897 		 * (This is true because threads don't clean up their own
2898 		 * state -- they leave that task to whomever reaps them.)
2899 		 *
2900 		 * Additionally, it is safe to dereference one's own process
2901 		 * credential, since this is never NULL after process birth.
2902 		 */
2903 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
2904 
2905 	case DIF_VAR_GID:
2906 		if (!dtrace_priv_proc(state))
2907 			return (0);
2908 
2909 		/*
2910 		 * See comment in DIF_VAR_PID.
2911 		 */
2912 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2913 			return ((uint64_t)p0.p_cred->cr_gid);
2914 
2915 		/*
2916 		 * It is always safe to dereference one's own t_procp pointer:
2917 		 * it always points to a valid, allocated proc structure.
2918 		 * (This is true because threads don't clean up their own
2919 		 * state -- they leave that task to whomever reaps them.)
2920 		 *
2921 		 * Additionally, it is safe to dereference one's own process
2922 		 * credential, since this is never NULL after process birth.
2923 		 */
2924 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
2925 
2926 	case DIF_VAR_ERRNO: {
2927 		klwp_t *lwp;
2928 		if (!dtrace_priv_proc(state))
2929 			return (0);
2930 
2931 		/*
2932 		 * See comment in DIF_VAR_PID.
2933 		 */
2934 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2935 			return (0);
2936 
2937 		/*
2938 		 * It is always safe to dereference one's own t_lwp pointer in
2939 		 * the event that this pointer is non-NULL.  (This is true
2940 		 * because threads and lwps don't clean up their own state --
2941 		 * they leave that task to whomever reaps them.)
2942 		 */
2943 		if ((lwp = curthread->t_lwp) == NULL)
2944 			return (0);
2945 
2946 		return ((uint64_t)lwp->lwp_errno);
2947 	}
2948 	default:
2949 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2950 		return (0);
2951 	}
2952 }
2953 
2954 /*
2955  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
2956  * Notice that we don't bother validating the proper number of arguments or
2957  * their types in the tuple stack.  This isn't needed because all argument
2958  * interpretation is safe because of our load safety -- the worst that can
2959  * happen is that a bogus program can obtain bogus results.
2960  */
2961 static void
2962 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
2963     dtrace_key_t *tupregs, int nargs,
2964     dtrace_mstate_t *mstate, dtrace_state_t *state)
2965 {
2966 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
2967 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
2968 	dtrace_vstate_t *vstate = &state->dts_vstate;
2969 
2970 	union {
2971 		mutex_impl_t mi;
2972 		uint64_t mx;
2973 	} m;
2974 
2975 	union {
2976 		krwlock_t ri;
2977 		uintptr_t rw;
2978 	} r;
2979 
2980 	switch (subr) {
2981 	case DIF_SUBR_RAND:
2982 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
2983 		break;
2984 
2985 	case DIF_SUBR_MUTEX_OWNED:
2986 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2987 		    mstate, vstate)) {
2988 			regs[rd] = NULL;
2989 			break;
2990 		}
2991 
2992 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2993 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
2994 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
2995 		else
2996 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
2997 		break;
2998 
2999 	case DIF_SUBR_MUTEX_OWNER:
3000 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3001 		    mstate, vstate)) {
3002 			regs[rd] = NULL;
3003 			break;
3004 		}
3005 
3006 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3007 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
3008 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
3009 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
3010 		else
3011 			regs[rd] = 0;
3012 		break;
3013 
3014 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
3015 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3016 		    mstate, vstate)) {
3017 			regs[rd] = NULL;
3018 			break;
3019 		}
3020 
3021 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3022 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
3023 		break;
3024 
3025 	case DIF_SUBR_MUTEX_TYPE_SPIN:
3026 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
3027 		    mstate, vstate)) {
3028 			regs[rd] = NULL;
3029 			break;
3030 		}
3031 
3032 		m.mx = dtrace_load64(tupregs[0].dttk_value);
3033 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
3034 		break;
3035 
3036 	case DIF_SUBR_RW_READ_HELD: {
3037 		uintptr_t tmp;
3038 
3039 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
3040 		    mstate, vstate)) {
3041 			regs[rd] = NULL;
3042 			break;
3043 		}
3044 
3045 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3046 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
3047 		break;
3048 	}
3049 
3050 	case DIF_SUBR_RW_WRITE_HELD:
3051 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3052 		    mstate, vstate)) {
3053 			regs[rd] = NULL;
3054 			break;
3055 		}
3056 
3057 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3058 		regs[rd] = _RW_WRITE_HELD(&r.ri);
3059 		break;
3060 
3061 	case DIF_SUBR_RW_ISWRITER:
3062 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
3063 		    mstate, vstate)) {
3064 			regs[rd] = NULL;
3065 			break;
3066 		}
3067 
3068 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
3069 		regs[rd] = _RW_ISWRITER(&r.ri);
3070 		break;
3071 
3072 	case DIF_SUBR_BCOPY: {
3073 		/*
3074 		 * We need to be sure that the destination is in the scratch
3075 		 * region -- no other region is allowed.
3076 		 */
3077 		uintptr_t src = tupregs[0].dttk_value;
3078 		uintptr_t dest = tupregs[1].dttk_value;
3079 		size_t size = tupregs[2].dttk_value;
3080 
3081 		if (!dtrace_inscratch(dest, size, mstate)) {
3082 			*flags |= CPU_DTRACE_BADADDR;
3083 			*illval = regs[rd];
3084 			break;
3085 		}
3086 
3087 		if (!dtrace_canload(src, size, mstate, vstate)) {
3088 			regs[rd] = NULL;
3089 			break;
3090 		}
3091 
3092 		dtrace_bcopy((void *)src, (void *)dest, size);
3093 		break;
3094 	}
3095 
3096 	case DIF_SUBR_ALLOCA:
3097 	case DIF_SUBR_COPYIN: {
3098 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
3099 		uint64_t size =
3100 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
3101 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
3102 
3103 		/*
3104 		 * This action doesn't require any credential checks since
3105 		 * probes will not activate in user contexts to which the
3106 		 * enabling user does not have permissions.
3107 		 */
3108 
3109 		/*
3110 		 * Rounding up the user allocation size could have overflowed
3111 		 * a large, bogus allocation (like -1ULL) to 0.
3112 		 */
3113 		if (scratch_size < size ||
3114 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
3115 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3116 			regs[rd] = NULL;
3117 			break;
3118 		}
3119 
3120 		if (subr == DIF_SUBR_COPYIN) {
3121 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3122 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3123 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3124 		}
3125 
3126 		mstate->dtms_scratch_ptr += scratch_size;
3127 		regs[rd] = dest;
3128 		break;
3129 	}
3130 
3131 	case DIF_SUBR_COPYINTO: {
3132 		uint64_t size = tupregs[1].dttk_value;
3133 		uintptr_t dest = tupregs[2].dttk_value;
3134 
3135 		/*
3136 		 * This action doesn't require any credential checks since
3137 		 * probes will not activate in user contexts to which the
3138 		 * enabling user does not have permissions.
3139 		 */
3140 		if (!dtrace_inscratch(dest, size, mstate)) {
3141 			*flags |= CPU_DTRACE_BADADDR;
3142 			*illval = regs[rd];
3143 			break;
3144 		}
3145 
3146 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3147 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3148 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3149 		break;
3150 	}
3151 
3152 	case DIF_SUBR_COPYINSTR: {
3153 		uintptr_t dest = mstate->dtms_scratch_ptr;
3154 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3155 
3156 		if (nargs > 1 && tupregs[1].dttk_value < size)
3157 			size = tupregs[1].dttk_value + 1;
3158 
3159 		/*
3160 		 * This action doesn't require any credential checks since
3161 		 * probes will not activate in user contexts to which the
3162 		 * enabling user does not have permissions.
3163 		 */
3164 		if (!DTRACE_INSCRATCH(mstate, size)) {
3165 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3166 			regs[rd] = NULL;
3167 			break;
3168 		}
3169 
3170 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3171 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3172 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3173 
3174 		((char *)dest)[size - 1] = '\0';
3175 		mstate->dtms_scratch_ptr += size;
3176 		regs[rd] = dest;
3177 		break;
3178 	}
3179 
3180 	case DIF_SUBR_MSGSIZE:
3181 	case DIF_SUBR_MSGDSIZE: {
3182 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
3183 		uintptr_t wptr, rptr;
3184 		size_t count = 0;
3185 		int cont = 0;
3186 
3187 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3188 
3189 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3190 			    vstate)) {
3191 				regs[rd] = NULL;
3192 				break;
3193 			}
3194 
3195 			wptr = dtrace_loadptr(baddr +
3196 			    offsetof(mblk_t, b_wptr));
3197 
3198 			rptr = dtrace_loadptr(baddr +
3199 			    offsetof(mblk_t, b_rptr));
3200 
3201 			if (wptr < rptr) {
3202 				*flags |= CPU_DTRACE_BADADDR;
3203 				*illval = tupregs[0].dttk_value;
3204 				break;
3205 			}
3206 
3207 			daddr = dtrace_loadptr(baddr +
3208 			    offsetof(mblk_t, b_datap));
3209 
3210 			baddr = dtrace_loadptr(baddr +
3211 			    offsetof(mblk_t, b_cont));
3212 
3213 			/*
3214 			 * We want to prevent against denial-of-service here,
3215 			 * so we're only going to search the list for
3216 			 * dtrace_msgdsize_max mblks.
3217 			 */
3218 			if (cont++ > dtrace_msgdsize_max) {
3219 				*flags |= CPU_DTRACE_ILLOP;
3220 				break;
3221 			}
3222 
3223 			if (subr == DIF_SUBR_MSGDSIZE) {
3224 				if (dtrace_load8(daddr +
3225 				    offsetof(dblk_t, db_type)) != M_DATA)
3226 					continue;
3227 			}
3228 
3229 			count += wptr - rptr;
3230 		}
3231 
3232 		if (!(*flags & CPU_DTRACE_FAULT))
3233 			regs[rd] = count;
3234 
3235 		break;
3236 	}
3237 
3238 	case DIF_SUBR_PROGENYOF: {
3239 		pid_t pid = tupregs[0].dttk_value;
3240 		proc_t *p;
3241 		int rval = 0;
3242 
3243 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3244 
3245 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3246 			if (p->p_pidp->pid_id == pid) {
3247 				rval = 1;
3248 				break;
3249 			}
3250 		}
3251 
3252 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3253 
3254 		regs[rd] = rval;
3255 		break;
3256 	}
3257 
3258 	case DIF_SUBR_SPECULATION:
3259 		regs[rd] = dtrace_speculation(state);
3260 		break;
3261 
3262 	case DIF_SUBR_COPYOUT: {
3263 		uintptr_t kaddr = tupregs[0].dttk_value;
3264 		uintptr_t uaddr = tupregs[1].dttk_value;
3265 		uint64_t size = tupregs[2].dttk_value;
3266 
3267 		if (!dtrace_destructive_disallow &&
3268 		    dtrace_priv_proc_control(state) &&
3269 		    !dtrace_istoxic(kaddr, size)) {
3270 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3271 			dtrace_copyout(kaddr, uaddr, size, flags);
3272 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3273 		}
3274 		break;
3275 	}
3276 
3277 	case DIF_SUBR_COPYOUTSTR: {
3278 		uintptr_t kaddr = tupregs[0].dttk_value;
3279 		uintptr_t uaddr = tupregs[1].dttk_value;
3280 		uint64_t size = tupregs[2].dttk_value;
3281 
3282 		if (!dtrace_destructive_disallow &&
3283 		    dtrace_priv_proc_control(state) &&
3284 		    !dtrace_istoxic(kaddr, size)) {
3285 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3286 			dtrace_copyoutstr(kaddr, uaddr, size, flags);
3287 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3288 		}
3289 		break;
3290 	}
3291 
3292 	case DIF_SUBR_STRLEN: {
3293 		size_t sz;
3294 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3295 		sz = dtrace_strlen((char *)addr,
3296 		    state->dts_options[DTRACEOPT_STRSIZE]);
3297 
3298 		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3299 			regs[rd] = NULL;
3300 			break;
3301 		}
3302 
3303 		regs[rd] = sz;
3304 
3305 		break;
3306 	}
3307 
3308 	case DIF_SUBR_STRCHR:
3309 	case DIF_SUBR_STRRCHR: {
3310 		/*
3311 		 * We're going to iterate over the string looking for the
3312 		 * specified character.  We will iterate until we have reached
3313 		 * the string length or we have found the character.  If this
3314 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3315 		 * of the specified character instead of the first.
3316 		 */
3317 		uintptr_t saddr = tupregs[0].dttk_value;
3318 		uintptr_t addr = tupregs[0].dttk_value;
3319 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3320 		char c, target = (char)tupregs[1].dttk_value;
3321 
3322 		for (regs[rd] = NULL; addr < limit; addr++) {
3323 			if ((c = dtrace_load8(addr)) == target) {
3324 				regs[rd] = addr;
3325 
3326 				if (subr == DIF_SUBR_STRCHR)
3327 					break;
3328 			}
3329 
3330 			if (c == '\0')
3331 				break;
3332 		}
3333 
3334 		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3335 			regs[rd] = NULL;
3336 			break;
3337 		}
3338 
3339 		break;
3340 	}
3341 
3342 	case DIF_SUBR_STRSTR:
3343 	case DIF_SUBR_INDEX:
3344 	case DIF_SUBR_RINDEX: {
3345 		/*
3346 		 * We're going to iterate over the string looking for the
3347 		 * specified string.  We will iterate until we have reached
3348 		 * the string length or we have found the string.  (Yes, this
3349 		 * is done in the most naive way possible -- but considering
3350 		 * that the string we're searching for is likely to be
3351 		 * relatively short, the complexity of Rabin-Karp or similar
3352 		 * hardly seems merited.)
3353 		 */
3354 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3355 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3356 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3357 		size_t len = dtrace_strlen(addr, size);
3358 		size_t sublen = dtrace_strlen(substr, size);
3359 		char *limit = addr + len, *orig = addr;
3360 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3361 		int inc = 1;
3362 
3363 		regs[rd] = notfound;
3364 
3365 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3366 			regs[rd] = NULL;
3367 			break;
3368 		}
3369 
3370 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3371 		    vstate)) {
3372 			regs[rd] = NULL;
3373 			break;
3374 		}
3375 
3376 		/*
3377 		 * strstr() and index()/rindex() have similar semantics if
3378 		 * both strings are the empty string: strstr() returns a
3379 		 * pointer to the (empty) string, and index() and rindex()
3380 		 * both return index 0 (regardless of any position argument).
3381 		 */
3382 		if (sublen == 0 && len == 0) {
3383 			if (subr == DIF_SUBR_STRSTR)
3384 				regs[rd] = (uintptr_t)addr;
3385 			else
3386 				regs[rd] = 0;
3387 			break;
3388 		}
3389 
3390 		if (subr != DIF_SUBR_STRSTR) {
3391 			if (subr == DIF_SUBR_RINDEX) {
3392 				limit = orig - 1;
3393 				addr += len;
3394 				inc = -1;
3395 			}
3396 
3397 			/*
3398 			 * Both index() and rindex() take an optional position
3399 			 * argument that denotes the starting position.
3400 			 */
3401 			if (nargs == 3) {
3402 				int64_t pos = (int64_t)tupregs[2].dttk_value;
3403 
3404 				/*
3405 				 * If the position argument to index() is
3406 				 * negative, Perl implicitly clamps it at
3407 				 * zero.  This semantic is a little surprising
3408 				 * given the special meaning of negative
3409 				 * positions to similar Perl functions like
3410 				 * substr(), but it appears to reflect a
3411 				 * notion that index() can start from a
3412 				 * negative index and increment its way up to
3413 				 * the string.  Given this notion, Perl's
3414 				 * rindex() is at least self-consistent in
3415 				 * that it implicitly clamps positions greater
3416 				 * than the string length to be the string
3417 				 * length.  Where Perl completely loses
3418 				 * coherence, however, is when the specified
3419 				 * substring is the empty string ("").  In
3420 				 * this case, even if the position is
3421 				 * negative, rindex() returns 0 -- and even if
3422 				 * the position is greater than the length,
3423 				 * index() returns the string length.  These
3424 				 * semantics violate the notion that index()
3425 				 * should never return a value less than the
3426 				 * specified position and that rindex() should
3427 				 * never return a value greater than the
3428 				 * specified position.  (One assumes that
3429 				 * these semantics are artifacts of Perl's
3430 				 * implementation and not the results of
3431 				 * deliberate design -- it beggars belief that
3432 				 * even Larry Wall could desire such oddness.)
3433 				 * While in the abstract one would wish for
3434 				 * consistent position semantics across
3435 				 * substr(), index() and rindex() -- or at the
3436 				 * very least self-consistent position
3437 				 * semantics for index() and rindex() -- we
3438 				 * instead opt to keep with the extant Perl
3439 				 * semantics, in all their broken glory.  (Do
3440 				 * we have more desire to maintain Perl's
3441 				 * semantics than Perl does?  Probably.)
3442 				 */
3443 				if (subr == DIF_SUBR_RINDEX) {
3444 					if (pos < 0) {
3445 						if (sublen == 0)
3446 							regs[rd] = 0;
3447 						break;
3448 					}
3449 
3450 					if (pos > len)
3451 						pos = len;
3452 				} else {
3453 					if (pos < 0)
3454 						pos = 0;
3455 
3456 					if (pos >= len) {
3457 						if (sublen == 0)
3458 							regs[rd] = len;
3459 						break;
3460 					}
3461 				}
3462 
3463 				addr = orig + pos;
3464 			}
3465 		}
3466 
3467 		for (regs[rd] = notfound; addr != limit; addr += inc) {
3468 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
3469 				if (subr != DIF_SUBR_STRSTR) {
3470 					/*
3471 					 * As D index() and rindex() are
3472 					 * modeled on Perl (and not on awk),
3473 					 * we return a zero-based (and not a
3474 					 * one-based) index.  (For you Perl
3475 					 * weenies: no, we're not going to add
3476 					 * $[ -- and shouldn't you be at a con
3477 					 * or something?)
3478 					 */
3479 					regs[rd] = (uintptr_t)(addr - orig);
3480 					break;
3481 				}
3482 
3483 				ASSERT(subr == DIF_SUBR_STRSTR);
3484 				regs[rd] = (uintptr_t)addr;
3485 				break;
3486 			}
3487 		}
3488 
3489 		break;
3490 	}
3491 
3492 	case DIF_SUBR_STRTOK: {
3493 		uintptr_t addr = tupregs[0].dttk_value;
3494 		uintptr_t tokaddr = tupregs[1].dttk_value;
3495 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3496 		uintptr_t limit, toklimit = tokaddr + size;
3497 		uint8_t c, tokmap[32];	 /* 256 / 8 */
3498 		char *dest = (char *)mstate->dtms_scratch_ptr;
3499 		int i;
3500 
3501 		/*
3502 		 * Check both the token buffer and (later) the input buffer,
3503 		 * since both could be non-scratch addresses.
3504 		 */
3505 		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3506 			regs[rd] = NULL;
3507 			break;
3508 		}
3509 
3510 		if (!DTRACE_INSCRATCH(mstate, size)) {
3511 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3512 			regs[rd] = NULL;
3513 			break;
3514 		}
3515 
3516 		if (addr == NULL) {
3517 			/*
3518 			 * If the address specified is NULL, we use our saved
3519 			 * strtok pointer from the mstate.  Note that this
3520 			 * means that the saved strtok pointer is _only_
3521 			 * valid within multiple enablings of the same probe --
3522 			 * it behaves like an implicit clause-local variable.
3523 			 */
3524 			addr = mstate->dtms_strtok;
3525 		} else {
3526 			/*
3527 			 * If the user-specified address is non-NULL we must
3528 			 * access check it.  This is the only time we have
3529 			 * a chance to do so, since this address may reside
3530 			 * in the string table of this clause-- future calls
3531 			 * (when we fetch addr from mstate->dtms_strtok)
3532 			 * would fail this access check.
3533 			 */
3534 			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3535 				regs[rd] = NULL;
3536 				break;
3537 			}
3538 		}
3539 
3540 		/*
3541 		 * First, zero the token map, and then process the token
3542 		 * string -- setting a bit in the map for every character
3543 		 * found in the token string.
3544 		 */
3545 		for (i = 0; i < sizeof (tokmap); i++)
3546 			tokmap[i] = 0;
3547 
3548 		for (; tokaddr < toklimit; tokaddr++) {
3549 			if ((c = dtrace_load8(tokaddr)) == '\0')
3550 				break;
3551 
3552 			ASSERT((c >> 3) < sizeof (tokmap));
3553 			tokmap[c >> 3] |= (1 << (c & 0x7));
3554 		}
3555 
3556 		for (limit = addr + size; addr < limit; addr++) {
3557 			/*
3558 			 * We're looking for a character that is _not_ contained
3559 			 * in the token string.
3560 			 */
3561 			if ((c = dtrace_load8(addr)) == '\0')
3562 				break;
3563 
3564 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3565 				break;
3566 		}
3567 
3568 		if (c == '\0') {
3569 			/*
3570 			 * We reached the end of the string without finding
3571 			 * any character that was not in the token string.
3572 			 * We return NULL in this case, and we set the saved
3573 			 * address to NULL as well.
3574 			 */
3575 			regs[rd] = NULL;
3576 			mstate->dtms_strtok = NULL;
3577 			break;
3578 		}
3579 
3580 		/*
3581 		 * From here on, we're copying into the destination string.
3582 		 */
3583 		for (i = 0; addr < limit && i < size - 1; addr++) {
3584 			if ((c = dtrace_load8(addr)) == '\0')
3585 				break;
3586 
3587 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
3588 				break;
3589 
3590 			ASSERT(i < size);
3591 			dest[i++] = c;
3592 		}
3593 
3594 		ASSERT(i < size);
3595 		dest[i] = '\0';
3596 		regs[rd] = (uintptr_t)dest;
3597 		mstate->dtms_scratch_ptr += size;
3598 		mstate->dtms_strtok = addr;
3599 		break;
3600 	}
3601 
3602 	case DIF_SUBR_SUBSTR: {
3603 		uintptr_t s = tupregs[0].dttk_value;
3604 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3605 		char *d = (char *)mstate->dtms_scratch_ptr;
3606 		int64_t index = (int64_t)tupregs[1].dttk_value;
3607 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
3608 		size_t len = dtrace_strlen((char *)s, size);
3609 		int64_t i = 0;
3610 
3611 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
3612 			regs[rd] = NULL;
3613 			break;
3614 		}
3615 
3616 		if (!DTRACE_INSCRATCH(mstate, size)) {
3617 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3618 			regs[rd] = NULL;
3619 			break;
3620 		}
3621 
3622 		if (nargs <= 2)
3623 			remaining = (int64_t)size;
3624 
3625 		if (index < 0) {
3626 			index += len;
3627 
3628 			if (index < 0 && index + remaining > 0) {
3629 				remaining += index;
3630 				index = 0;
3631 			}
3632 		}
3633 
3634 		if (index >= len || index < 0) {
3635 			remaining = 0;
3636 		} else if (remaining < 0) {
3637 			remaining += len - index;
3638 		} else if (index + remaining > size) {
3639 			remaining = size - index;
3640 		}
3641 
3642 		for (i = 0; i < remaining; i++) {
3643 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
3644 				break;
3645 		}
3646 
3647 		d[i] = '\0';
3648 
3649 		mstate->dtms_scratch_ptr += size;
3650 		regs[rd] = (uintptr_t)d;
3651 		break;
3652 	}
3653 
3654 	case DIF_SUBR_GETMAJOR:
3655 #ifdef _LP64
3656 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
3657 #else
3658 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
3659 #endif
3660 		break;
3661 
3662 	case DIF_SUBR_GETMINOR:
3663 #ifdef _LP64
3664 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
3665 #else
3666 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
3667 #endif
3668 		break;
3669 
3670 	case DIF_SUBR_DDI_PATHNAME: {
3671 		/*
3672 		 * This one is a galactic mess.  We are going to roughly
3673 		 * emulate ddi_pathname(), but it's made more complicated
3674 		 * by the fact that we (a) want to include the minor name and
3675 		 * (b) must proceed iteratively instead of recursively.
3676 		 */
3677 		uintptr_t dest = mstate->dtms_scratch_ptr;
3678 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3679 		char *start = (char *)dest, *end = start + size - 1;
3680 		uintptr_t daddr = tupregs[0].dttk_value;
3681 		int64_t minor = (int64_t)tupregs[1].dttk_value;
3682 		char *s;
3683 		int i, len, depth = 0;
3684 
3685 		/*
3686 		 * Due to all the pointer jumping we do and context we must
3687 		 * rely upon, we just mandate that the user must have kernel
3688 		 * read privileges to use this routine.
3689 		 */
3690 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
3691 			*flags |= CPU_DTRACE_KPRIV;
3692 			*illval = daddr;
3693 			regs[rd] = NULL;
3694 		}
3695 
3696 		if (!DTRACE_INSCRATCH(mstate, size)) {
3697 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3698 			regs[rd] = NULL;
3699 			break;
3700 		}
3701 
3702 		*end = '\0';
3703 
3704 		/*
3705 		 * We want to have a name for the minor.  In order to do this,
3706 		 * we need to walk the minor list from the devinfo.  We want
3707 		 * to be sure that we don't infinitely walk a circular list,
3708 		 * so we check for circularity by sending a scout pointer
3709 		 * ahead two elements for every element that we iterate over;
3710 		 * if the list is circular, these will ultimately point to the
3711 		 * same element.  You may recognize this little trick as the
3712 		 * answer to a stupid interview question -- one that always
3713 		 * seems to be asked by those who had to have it laboriously
3714 		 * explained to them, and who can't even concisely describe
3715 		 * the conditions under which one would be forced to resort to
3716 		 * this technique.  Needless to say, those conditions are
3717 		 * found here -- and probably only here.  Is this the only use
3718 		 * of this infamous trick in shipping, production code?  If it
3719 		 * isn't, it probably should be...
3720 		 */
3721 		if (minor != -1) {
3722 			uintptr_t maddr = dtrace_loadptr(daddr +
3723 			    offsetof(struct dev_info, devi_minor));
3724 
3725 			uintptr_t next = offsetof(struct ddi_minor_data, next);
3726 			uintptr_t name = offsetof(struct ddi_minor_data,
3727 			    d_minor) + offsetof(struct ddi_minor, name);
3728 			uintptr_t dev = offsetof(struct ddi_minor_data,
3729 			    d_minor) + offsetof(struct ddi_minor, dev);
3730 			uintptr_t scout;
3731 
3732 			if (maddr != NULL)
3733 				scout = dtrace_loadptr(maddr + next);
3734 
3735 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3736 				uint64_t m;
3737 #ifdef _LP64
3738 				m = dtrace_load64(maddr + dev) & MAXMIN64;
3739 #else
3740 				m = dtrace_load32(maddr + dev) & MAXMIN;
3741 #endif
3742 				if (m != minor) {
3743 					maddr = dtrace_loadptr(maddr + next);
3744 
3745 					if (scout == NULL)
3746 						continue;
3747 
3748 					scout = dtrace_loadptr(scout + next);
3749 
3750 					if (scout == NULL)
3751 						continue;
3752 
3753 					scout = dtrace_loadptr(scout + next);
3754 
3755 					if (scout == NULL)
3756 						continue;
3757 
3758 					if (scout == maddr) {
3759 						*flags |= CPU_DTRACE_ILLOP;
3760 						break;
3761 					}
3762 
3763 					continue;
3764 				}
3765 
3766 				/*
3767 				 * We have the minor data.  Now we need to
3768 				 * copy the minor's name into the end of the
3769 				 * pathname.
3770 				 */
3771 				s = (char *)dtrace_loadptr(maddr + name);
3772 				len = dtrace_strlen(s, size);
3773 
3774 				if (*flags & CPU_DTRACE_FAULT)
3775 					break;
3776 
3777 				if (len != 0) {
3778 					if ((end -= (len + 1)) < start)
3779 						break;
3780 
3781 					*end = ':';
3782 				}
3783 
3784 				for (i = 1; i <= len; i++)
3785 					end[i] = dtrace_load8((uintptr_t)s++);
3786 				break;
3787 			}
3788 		}
3789 
3790 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3791 			ddi_node_state_t devi_state;
3792 
3793 			devi_state = dtrace_load32(daddr +
3794 			    offsetof(struct dev_info, devi_node_state));
3795 
3796 			if (*flags & CPU_DTRACE_FAULT)
3797 				break;
3798 
3799 			if (devi_state >= DS_INITIALIZED) {
3800 				s = (char *)dtrace_loadptr(daddr +
3801 				    offsetof(struct dev_info, devi_addr));
3802 				len = dtrace_strlen(s, size);
3803 
3804 				if (*flags & CPU_DTRACE_FAULT)
3805 					break;
3806 
3807 				if (len != 0) {
3808 					if ((end -= (len + 1)) < start)
3809 						break;
3810 
3811 					*end = '@';
3812 				}
3813 
3814 				for (i = 1; i <= len; i++)
3815 					end[i] = dtrace_load8((uintptr_t)s++);
3816 			}
3817 
3818 			/*
3819 			 * Now for the node name...
3820 			 */
3821 			s = (char *)dtrace_loadptr(daddr +
3822 			    offsetof(struct dev_info, devi_node_name));
3823 
3824 			daddr = dtrace_loadptr(daddr +
3825 			    offsetof(struct dev_info, devi_parent));
3826 
3827 			/*
3828 			 * If our parent is NULL (that is, if we're the root
3829 			 * node), we're going to use the special path
3830 			 * "devices".
3831 			 */
3832 			if (daddr == NULL)
3833 				s = "devices";
3834 
3835 			len = dtrace_strlen(s, size);
3836 			if (*flags & CPU_DTRACE_FAULT)
3837 				break;
3838 
3839 			if ((end -= (len + 1)) < start)
3840 				break;
3841 
3842 			for (i = 1; i <= len; i++)
3843 				end[i] = dtrace_load8((uintptr_t)s++);
3844 			*end = '/';
3845 
3846 			if (depth++ > dtrace_devdepth_max) {
3847 				*flags |= CPU_DTRACE_ILLOP;
3848 				break;
3849 			}
3850 		}
3851 
3852 		if (end < start)
3853 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3854 
3855 		if (daddr == NULL) {
3856 			regs[rd] = (uintptr_t)end;
3857 			mstate->dtms_scratch_ptr += size;
3858 		}
3859 
3860 		break;
3861 	}
3862 
3863 	case DIF_SUBR_STRJOIN: {
3864 		char *d = (char *)mstate->dtms_scratch_ptr;
3865 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3866 		uintptr_t s1 = tupregs[0].dttk_value;
3867 		uintptr_t s2 = tupregs[1].dttk_value;
3868 		int i = 0;
3869 
3870 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
3871 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
3872 			regs[rd] = NULL;
3873 			break;
3874 		}
3875 
3876 		if (!DTRACE_INSCRATCH(mstate, size)) {
3877 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3878 			regs[rd] = NULL;
3879 			break;
3880 		}
3881 
3882 		for (;;) {
3883 			if (i >= size) {
3884 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3885 				regs[rd] = NULL;
3886 				break;
3887 			}
3888 
3889 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
3890 				i--;
3891 				break;
3892 			}
3893 		}
3894 
3895 		for (;;) {
3896 			if (i >= size) {
3897 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3898 				regs[rd] = NULL;
3899 				break;
3900 			}
3901 
3902 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
3903 				break;
3904 		}
3905 
3906 		if (i < size) {
3907 			mstate->dtms_scratch_ptr += i;
3908 			regs[rd] = (uintptr_t)d;
3909 		}
3910 
3911 		break;
3912 	}
3913 
3914 	case DIF_SUBR_LLTOSTR: {
3915 		int64_t i = (int64_t)tupregs[0].dttk_value;
3916 		int64_t val = i < 0 ? i * -1 : i;
3917 		uint64_t size = 22;	/* enough room for 2^64 in decimal */
3918 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
3919 
3920 		if (!DTRACE_INSCRATCH(mstate, size)) {
3921 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3922 			regs[rd] = NULL;
3923 			break;
3924 		}
3925 
3926 		for (*end-- = '\0'; val; val /= 10)
3927 			*end-- = '0' + (val % 10);
3928 
3929 		if (i == 0)
3930 			*end-- = '0';
3931 
3932 		if (i < 0)
3933 			*end-- = '-';
3934 
3935 		regs[rd] = (uintptr_t)end + 1;
3936 		mstate->dtms_scratch_ptr += size;
3937 		break;
3938 	}
3939 
3940 	case DIF_SUBR_HTONS:
3941 	case DIF_SUBR_NTOHS:
3942 #ifdef _BIG_ENDIAN
3943 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
3944 #else
3945 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
3946 #endif
3947 		break;
3948 
3949 
3950 	case DIF_SUBR_HTONL:
3951 	case DIF_SUBR_NTOHL:
3952 #ifdef _BIG_ENDIAN
3953 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
3954 #else
3955 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
3956 #endif
3957 		break;
3958 
3959 
3960 	case DIF_SUBR_HTONLL:
3961 	case DIF_SUBR_NTOHLL:
3962 #ifdef _BIG_ENDIAN
3963 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
3964 #else
3965 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
3966 #endif
3967 		break;
3968 
3969 
3970 	case DIF_SUBR_DIRNAME:
3971 	case DIF_SUBR_BASENAME: {
3972 		char *dest = (char *)mstate->dtms_scratch_ptr;
3973 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3974 		uintptr_t src = tupregs[0].dttk_value;
3975 		int i, j, len = dtrace_strlen((char *)src, size);
3976 		int lastbase = -1, firstbase = -1, lastdir = -1;
3977 		int start, end;
3978 
3979 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
3980 			regs[rd] = NULL;
3981 			break;
3982 		}
3983 
3984 		if (!DTRACE_INSCRATCH(mstate, size)) {
3985 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3986 			regs[rd] = NULL;
3987 			break;
3988 		}
3989 
3990 		/*
3991 		 * The basename and dirname for a zero-length string is
3992 		 * defined to be "."
3993 		 */
3994 		if (len == 0) {
3995 			len = 1;
3996 			src = (uintptr_t)".";
3997 		}
3998 
3999 		/*
4000 		 * Start from the back of the string, moving back toward the
4001 		 * front until we see a character that isn't a slash.  That
4002 		 * character is the last character in the basename.
4003 		 */
4004 		for (i = len - 1; i >= 0; i--) {
4005 			if (dtrace_load8(src + i) != '/')
4006 				break;
4007 		}
4008 
4009 		if (i >= 0)
4010 			lastbase = i;
4011 
4012 		/*
4013 		 * Starting from the last character in the basename, move
4014 		 * towards the front until we find a slash.  The character
4015 		 * that we processed immediately before that is the first
4016 		 * character in the basename.
4017 		 */
4018 		for (; i >= 0; i--) {
4019 			if (dtrace_load8(src + i) == '/')
4020 				break;
4021 		}
4022 
4023 		if (i >= 0)
4024 			firstbase = i + 1;
4025 
4026 		/*
4027 		 * Now keep going until we find a non-slash character.  That
4028 		 * character is the last character in the dirname.
4029 		 */
4030 		for (; i >= 0; i--) {
4031 			if (dtrace_load8(src + i) != '/')
4032 				break;
4033 		}
4034 
4035 		if (i >= 0)
4036 			lastdir = i;
4037 
4038 		ASSERT(!(lastbase == -1 && firstbase != -1));
4039 		ASSERT(!(firstbase == -1 && lastdir != -1));
4040 
4041 		if (lastbase == -1) {
4042 			/*
4043 			 * We didn't find a non-slash character.  We know that
4044 			 * the length is non-zero, so the whole string must be
4045 			 * slashes.  In either the dirname or the basename
4046 			 * case, we return '/'.
4047 			 */
4048 			ASSERT(firstbase == -1);
4049 			firstbase = lastbase = lastdir = 0;
4050 		}
4051 
4052 		if (firstbase == -1) {
4053 			/*
4054 			 * The entire string consists only of a basename
4055 			 * component.  If we're looking for dirname, we need
4056 			 * to change our string to be just "."; if we're
4057 			 * looking for a basename, we'll just set the first
4058 			 * character of the basename to be 0.
4059 			 */
4060 			if (subr == DIF_SUBR_DIRNAME) {
4061 				ASSERT(lastdir == -1);
4062 				src = (uintptr_t)".";
4063 				lastdir = 0;
4064 			} else {
4065 				firstbase = 0;
4066 			}
4067 		}
4068 
4069 		if (subr == DIF_SUBR_DIRNAME) {
4070 			if (lastdir == -1) {
4071 				/*
4072 				 * We know that we have a slash in the name --
4073 				 * or lastdir would be set to 0, above.  And
4074 				 * because lastdir is -1, we know that this
4075 				 * slash must be the first character.  (That
4076 				 * is, the full string must be of the form
4077 				 * "/basename".)  In this case, the last
4078 				 * character of the directory name is 0.
4079 				 */
4080 				lastdir = 0;
4081 			}
4082 
4083 			start = 0;
4084 			end = lastdir;
4085 		} else {
4086 			ASSERT(subr == DIF_SUBR_BASENAME);
4087 			ASSERT(firstbase != -1 && lastbase != -1);
4088 			start = firstbase;
4089 			end = lastbase;
4090 		}
4091 
4092 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
4093 			dest[j] = dtrace_load8(src + i);
4094 
4095 		dest[j] = '\0';
4096 		regs[rd] = (uintptr_t)dest;
4097 		mstate->dtms_scratch_ptr += size;
4098 		break;
4099 	}
4100 
4101 	case DIF_SUBR_CLEANPATH: {
4102 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4103 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4104 		uintptr_t src = tupregs[0].dttk_value;
4105 		int i = 0, j = 0;
4106 
4107 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
4108 			regs[rd] = NULL;
4109 			break;
4110 		}
4111 
4112 		if (!DTRACE_INSCRATCH(mstate, size)) {
4113 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4114 			regs[rd] = NULL;
4115 			break;
4116 		}
4117 
4118 		/*
4119 		 * Move forward, loading each character.
4120 		 */
4121 		do {
4122 			c = dtrace_load8(src + i++);
4123 next:
4124 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
4125 				break;
4126 
4127 			if (c != '/') {
4128 				dest[j++] = c;
4129 				continue;
4130 			}
4131 
4132 			c = dtrace_load8(src + i++);
4133 
4134 			if (c == '/') {
4135 				/*
4136 				 * We have two slashes -- we can just advance
4137 				 * to the next character.
4138 				 */
4139 				goto next;
4140 			}
4141 
4142 			if (c != '.') {
4143 				/*
4144 				 * This is not "." and it's not ".." -- we can
4145 				 * just store the "/" and this character and
4146 				 * drive on.
4147 				 */
4148 				dest[j++] = '/';
4149 				dest[j++] = c;
4150 				continue;
4151 			}
4152 
4153 			c = dtrace_load8(src + i++);
4154 
4155 			if (c == '/') {
4156 				/*
4157 				 * This is a "/./" component.  We're not going
4158 				 * to store anything in the destination buffer;
4159 				 * we're just going to go to the next component.
4160 				 */
4161 				goto next;
4162 			}
4163 
4164 			if (c != '.') {
4165 				/*
4166 				 * This is not ".." -- we can just store the
4167 				 * "/." and this character and continue
4168 				 * processing.
4169 				 */
4170 				dest[j++] = '/';
4171 				dest[j++] = '.';
4172 				dest[j++] = c;
4173 				continue;
4174 			}
4175 
4176 			c = dtrace_load8(src + i++);
4177 
4178 			if (c != '/' && c != '\0') {
4179 				/*
4180 				 * This is not ".." -- it's "..[mumble]".
4181 				 * We'll store the "/.." and this character
4182 				 * and continue processing.
4183 				 */
4184 				dest[j++] = '/';
4185 				dest[j++] = '.';
4186 				dest[j++] = '.';
4187 				dest[j++] = c;
4188 				continue;
4189 			}
4190 
4191 			/*
4192 			 * This is "/../" or "/..\0".  We need to back up
4193 			 * our destination pointer until we find a "/".
4194 			 */
4195 			i--;
4196 			while (j != 0 && dest[--j] != '/')
4197 				continue;
4198 
4199 			if (c == '\0')
4200 				dest[++j] = '/';
4201 		} while (c != '\0');
4202 
4203 		dest[j] = '\0';
4204 		regs[rd] = (uintptr_t)dest;
4205 		mstate->dtms_scratch_ptr += size;
4206 		break;
4207 	}
4208 
4209 	case DIF_SUBR_INET_NTOA:
4210 	case DIF_SUBR_INET_NTOA6:
4211 	case DIF_SUBR_INET_NTOP: {
4212 		size_t size;
4213 		int af, argi, i;
4214 		char *base, *end;
4215 
4216 		if (subr == DIF_SUBR_INET_NTOP) {
4217 			af = (int)tupregs[0].dttk_value;
4218 			argi = 1;
4219 		} else {
4220 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4221 			argi = 0;
4222 		}
4223 
4224 		if (af == AF_INET) {
4225 			ipaddr_t ip4;
4226 			uint8_t *ptr8, val;
4227 
4228 			/*
4229 			 * Safely load the IPv4 address.
4230 			 */
4231 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
4232 
4233 			/*
4234 			 * Check an IPv4 string will fit in scratch.
4235 			 */
4236 			size = INET_ADDRSTRLEN;
4237 			if (!DTRACE_INSCRATCH(mstate, size)) {
4238 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4239 				regs[rd] = NULL;
4240 				break;
4241 			}
4242 			base = (char *)mstate->dtms_scratch_ptr;
4243 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4244 
4245 			/*
4246 			 * Stringify as a dotted decimal quad.
4247 			 */
4248 			*end-- = '\0';
4249 			ptr8 = (uint8_t *)&ip4;
4250 			for (i = 3; i >= 0; i--) {
4251 				val = ptr8[i];
4252 
4253 				if (val == 0) {
4254 					*end-- = '0';
4255 				} else {
4256 					for (; val; val /= 10) {
4257 						*end-- = '0' + (val % 10);
4258 					}
4259 				}
4260 
4261 				if (i > 0)
4262 					*end-- = '.';
4263 			}
4264 			ASSERT(end + 1 >= base);
4265 
4266 		} else if (af == AF_INET6) {
4267 			struct in6_addr ip6;
4268 			int firstzero, tryzero, numzero, v6end;
4269 			uint16_t val;
4270 			const char digits[] = "0123456789abcdef";
4271 
4272 			/*
4273 			 * Stringify using RFC 1884 convention 2 - 16 bit
4274 			 * hexadecimal values with a zero-run compression.
4275 			 * Lower case hexadecimal digits are used.
4276 			 * 	eg, fe80::214:4fff:fe0b:76c8.
4277 			 * The IPv4 embedded form is returned for inet_ntop,
4278 			 * just the IPv4 string is returned for inet_ntoa6.
4279 			 */
4280 
4281 			/*
4282 			 * Safely load the IPv6 address.
4283 			 */
4284 			dtrace_bcopy(
4285 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
4286 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4287 
4288 			/*
4289 			 * Check an IPv6 string will fit in scratch.
4290 			 */
4291 			size = INET6_ADDRSTRLEN;
4292 			if (!DTRACE_INSCRATCH(mstate, size)) {
4293 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4294 				regs[rd] = NULL;
4295 				break;
4296 			}
4297 			base = (char *)mstate->dtms_scratch_ptr;
4298 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4299 			*end-- = '\0';
4300 
4301 			/*
4302 			 * Find the longest run of 16 bit zero values
4303 			 * for the single allowed zero compression - "::".
4304 			 */
4305 			firstzero = -1;
4306 			tryzero = -1;
4307 			numzero = 1;
4308 			for (i = 0; i < sizeof (struct in6_addr); i++) {
4309 				if (ip6._S6_un._S6_u8[i] == 0 &&
4310 				    tryzero == -1 && i % 2 == 0) {
4311 					tryzero = i;
4312 					continue;
4313 				}
4314 
4315 				if (tryzero != -1 &&
4316 				    (ip6._S6_un._S6_u8[i] != 0 ||
4317 				    i == sizeof (struct in6_addr) - 1)) {
4318 
4319 					if (i - tryzero <= numzero) {
4320 						tryzero = -1;
4321 						continue;
4322 					}
4323 
4324 					firstzero = tryzero;
4325 					numzero = i - i % 2 - tryzero;
4326 					tryzero = -1;
4327 
4328 					if (ip6._S6_un._S6_u8[i] == 0 &&
4329 					    i == sizeof (struct in6_addr) - 1)
4330 						numzero += 2;
4331 				}
4332 			}
4333 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4334 
4335 			/*
4336 			 * Check for an IPv4 embedded address.
4337 			 */
4338 			v6end = sizeof (struct in6_addr) - 2;
4339 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4340 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
4341 				for (i = sizeof (struct in6_addr) - 1;
4342 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
4343 					ASSERT(end >= base);
4344 
4345 					val = ip6._S6_un._S6_u8[i];
4346 
4347 					if (val == 0) {
4348 						*end-- = '0';
4349 					} else {
4350 						for (; val; val /= 10) {
4351 							*end-- = '0' + val % 10;
4352 						}
4353 					}
4354 
4355 					if (i > DTRACE_V4MAPPED_OFFSET)
4356 						*end-- = '.';
4357 				}
4358 
4359 				if (subr == DIF_SUBR_INET_NTOA6)
4360 					goto inetout;
4361 
4362 				/*
4363 				 * Set v6end to skip the IPv4 address that
4364 				 * we have already stringified.
4365 				 */
4366 				v6end = 10;
4367 			}
4368 
4369 			/*
4370 			 * Build the IPv6 string by working through the
4371 			 * address in reverse.
4372 			 */
4373 			for (i = v6end; i >= 0; i -= 2) {
4374 				ASSERT(end >= base);
4375 
4376 				if (i == firstzero + numzero - 2) {
4377 					*end-- = ':';
4378 					*end-- = ':';
4379 					i -= numzero - 2;
4380 					continue;
4381 				}
4382 
4383 				if (i < 14 && i != firstzero - 2)
4384 					*end-- = ':';
4385 
4386 				val = (ip6._S6_un._S6_u8[i] << 8) +
4387 				    ip6._S6_un._S6_u8[i + 1];
4388 
4389 				if (val == 0) {
4390 					*end-- = '0';
4391 				} else {
4392 					for (; val; val /= 16) {
4393 						*end-- = digits[val % 16];
4394 					}
4395 				}
4396 			}
4397 			ASSERT(end + 1 >= base);
4398 
4399 		} else {
4400 			/*
4401 			 * The user didn't use AH_INET or AH_INET6.
4402 			 */
4403 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4404 			regs[rd] = NULL;
4405 			break;
4406 		}
4407 
4408 inetout:	regs[rd] = (uintptr_t)end + 1;
4409 		mstate->dtms_scratch_ptr += size;
4410 		break;
4411 	}
4412 
4413 	}
4414 }
4415 
4416 /*
4417  * Emulate the execution of DTrace IR instructions specified by the given
4418  * DIF object.  This function is deliberately void of assertions as all of
4419  * the necessary checks are handled by a call to dtrace_difo_validate().
4420  */
4421 static uint64_t
4422 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4423     dtrace_vstate_t *vstate, dtrace_state_t *state)
4424 {
4425 	const dif_instr_t *text = difo->dtdo_buf;
4426 	const uint_t textlen = difo->dtdo_len;
4427 	const char *strtab = difo->dtdo_strtab;
4428 	const uint64_t *inttab = difo->dtdo_inttab;
4429 
4430 	uint64_t rval = 0;
4431 	dtrace_statvar_t *svar;
4432 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4433 	dtrace_difv_t *v;
4434 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4435 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4436 
4437 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4438 	uint64_t regs[DIF_DIR_NREGS];
4439 	uint64_t *tmp;
4440 
4441 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4442 	int64_t cc_r;
4443 	uint_t pc = 0, id, opc;
4444 	uint8_t ttop = 0;
4445 	dif_instr_t instr;
4446 	uint_t r1, r2, rd;
4447 
4448 	/*
4449 	 * We stash the current DIF object into the machine state: we need it
4450 	 * for subsequent access checking.
4451 	 */
4452 	mstate->dtms_difo = difo;
4453 
4454 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
4455 
4456 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4457 		opc = pc;
4458 
4459 		instr = text[pc++];
4460 		r1 = DIF_INSTR_R1(instr);
4461 		r2 = DIF_INSTR_R2(instr);
4462 		rd = DIF_INSTR_RD(instr);
4463 
4464 		switch (DIF_INSTR_OP(instr)) {
4465 		case DIF_OP_OR:
4466 			regs[rd] = regs[r1] | regs[r2];
4467 			break;
4468 		case DIF_OP_XOR:
4469 			regs[rd] = regs[r1] ^ regs[r2];
4470 			break;
4471 		case DIF_OP_AND:
4472 			regs[rd] = regs[r1] & regs[r2];
4473 			break;
4474 		case DIF_OP_SLL:
4475 			regs[rd] = regs[r1] << regs[r2];
4476 			break;
4477 		case DIF_OP_SRL:
4478 			regs[rd] = regs[r1] >> regs[r2];
4479 			break;
4480 		case DIF_OP_SUB:
4481 			regs[rd] = regs[r1] - regs[r2];
4482 			break;
4483 		case DIF_OP_ADD:
4484 			regs[rd] = regs[r1] + regs[r2];
4485 			break;
4486 		case DIF_OP_MUL:
4487 			regs[rd] = regs[r1] * regs[r2];
4488 			break;
4489 		case DIF_OP_SDIV:
4490 			if (regs[r2] == 0) {
4491 				regs[rd] = 0;
4492 				*flags |= CPU_DTRACE_DIVZERO;
4493 			} else {
4494 				regs[rd] = (int64_t)regs[r1] /
4495 				    (int64_t)regs[r2];
4496 			}
4497 			break;
4498 
4499 		case DIF_OP_UDIV:
4500 			if (regs[r2] == 0) {
4501 				regs[rd] = 0;
4502 				*flags |= CPU_DTRACE_DIVZERO;
4503 			} else {
4504 				regs[rd] = regs[r1] / regs[r2];
4505 			}
4506 			break;
4507 
4508 		case DIF_OP_SREM:
4509 			if (regs[r2] == 0) {
4510 				regs[rd] = 0;
4511 				*flags |= CPU_DTRACE_DIVZERO;
4512 			} else {
4513 				regs[rd] = (int64_t)regs[r1] %
4514 				    (int64_t)regs[r2];
4515 			}
4516 			break;
4517 
4518 		case DIF_OP_UREM:
4519 			if (regs[r2] == 0) {
4520 				regs[rd] = 0;
4521 				*flags |= CPU_DTRACE_DIVZERO;
4522 			} else {
4523 				regs[rd] = regs[r1] % regs[r2];
4524 			}
4525 			break;
4526 
4527 		case DIF_OP_NOT:
4528 			regs[rd] = ~regs[r1];
4529 			break;
4530 		case DIF_OP_MOV:
4531 			regs[rd] = regs[r1];
4532 			break;
4533 		case DIF_OP_CMP:
4534 			cc_r = regs[r1] - regs[r2];
4535 			cc_n = cc_r < 0;
4536 			cc_z = cc_r == 0;
4537 			cc_v = 0;
4538 			cc_c = regs[r1] < regs[r2];
4539 			break;
4540 		case DIF_OP_TST:
4541 			cc_n = cc_v = cc_c = 0;
4542 			cc_z = regs[r1] == 0;
4543 			break;
4544 		case DIF_OP_BA:
4545 			pc = DIF_INSTR_LABEL(instr);
4546 			break;
4547 		case DIF_OP_BE:
4548 			if (cc_z)
4549 				pc = DIF_INSTR_LABEL(instr);
4550 			break;
4551 		case DIF_OP_BNE:
4552 			if (cc_z == 0)
4553 				pc = DIF_INSTR_LABEL(instr);
4554 			break;
4555 		case DIF_OP_BG:
4556 			if ((cc_z | (cc_n ^ cc_v)) == 0)
4557 				pc = DIF_INSTR_LABEL(instr);
4558 			break;
4559 		case DIF_OP_BGU:
4560 			if ((cc_c | cc_z) == 0)
4561 				pc = DIF_INSTR_LABEL(instr);
4562 			break;
4563 		case DIF_OP_BGE:
4564 			if ((cc_n ^ cc_v) == 0)
4565 				pc = DIF_INSTR_LABEL(instr);
4566 			break;
4567 		case DIF_OP_BGEU:
4568 			if (cc_c == 0)
4569 				pc = DIF_INSTR_LABEL(instr);
4570 			break;
4571 		case DIF_OP_BL:
4572 			if (cc_n ^ cc_v)
4573 				pc = DIF_INSTR_LABEL(instr);
4574 			break;
4575 		case DIF_OP_BLU:
4576 			if (cc_c)
4577 				pc = DIF_INSTR_LABEL(instr);
4578 			break;
4579 		case DIF_OP_BLE:
4580 			if (cc_z | (cc_n ^ cc_v))
4581 				pc = DIF_INSTR_LABEL(instr);
4582 			break;
4583 		case DIF_OP_BLEU:
4584 			if (cc_c | cc_z)
4585 				pc = DIF_INSTR_LABEL(instr);
4586 			break;
4587 		case DIF_OP_RLDSB:
4588 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4589 				*flags |= CPU_DTRACE_KPRIV;
4590 				*illval = regs[r1];
4591 				break;
4592 			}
4593 			/*FALLTHROUGH*/
4594 		case DIF_OP_LDSB:
4595 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
4596 			break;
4597 		case DIF_OP_RLDSH:
4598 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4599 				*flags |= CPU_DTRACE_KPRIV;
4600 				*illval = regs[r1];
4601 				break;
4602 			}
4603 			/*FALLTHROUGH*/
4604 		case DIF_OP_LDSH:
4605 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
4606 			break;
4607 		case DIF_OP_RLDSW:
4608 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4609 				*flags |= CPU_DTRACE_KPRIV;
4610 				*illval = regs[r1];
4611 				break;
4612 			}
4613 			/*FALLTHROUGH*/
4614 		case DIF_OP_LDSW:
4615 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
4616 			break;
4617 		case DIF_OP_RLDUB:
4618 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4619 				*flags |= CPU_DTRACE_KPRIV;
4620 				*illval = regs[r1];
4621 				break;
4622 			}
4623 			/*FALLTHROUGH*/
4624 		case DIF_OP_LDUB:
4625 			regs[rd] = dtrace_load8(regs[r1]);
4626 			break;
4627 		case DIF_OP_RLDUH:
4628 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4629 				*flags |= CPU_DTRACE_KPRIV;
4630 				*illval = regs[r1];
4631 				break;
4632 			}
4633 			/*FALLTHROUGH*/
4634 		case DIF_OP_LDUH:
4635 			regs[rd] = dtrace_load16(regs[r1]);
4636 			break;
4637 		case DIF_OP_RLDUW:
4638 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4639 				*flags |= CPU_DTRACE_KPRIV;
4640 				*illval = regs[r1];
4641 				break;
4642 			}
4643 			/*FALLTHROUGH*/
4644 		case DIF_OP_LDUW:
4645 			regs[rd] = dtrace_load32(regs[r1]);
4646 			break;
4647 		case DIF_OP_RLDX:
4648 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
4649 				*flags |= CPU_DTRACE_KPRIV;
4650 				*illval = regs[r1];
4651 				break;
4652 			}
4653 			/*FALLTHROUGH*/
4654 		case DIF_OP_LDX:
4655 			regs[rd] = dtrace_load64(regs[r1]);
4656 			break;
4657 		case DIF_OP_ULDSB:
4658 			regs[rd] = (int8_t)
4659 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4660 			break;
4661 		case DIF_OP_ULDSH:
4662 			regs[rd] = (int16_t)
4663 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4664 			break;
4665 		case DIF_OP_ULDSW:
4666 			regs[rd] = (int32_t)
4667 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4668 			break;
4669 		case DIF_OP_ULDUB:
4670 			regs[rd] =
4671 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4672 			break;
4673 		case DIF_OP_ULDUH:
4674 			regs[rd] =
4675 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4676 			break;
4677 		case DIF_OP_ULDUW:
4678 			regs[rd] =
4679 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4680 			break;
4681 		case DIF_OP_ULDX:
4682 			regs[rd] =
4683 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
4684 			break;
4685 		case DIF_OP_RET:
4686 			rval = regs[rd];
4687 			pc = textlen;
4688 			break;
4689 		case DIF_OP_NOP:
4690 			break;
4691 		case DIF_OP_SETX:
4692 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
4693 			break;
4694 		case DIF_OP_SETS:
4695 			regs[rd] = (uint64_t)(uintptr_t)
4696 			    (strtab + DIF_INSTR_STRING(instr));
4697 			break;
4698 		case DIF_OP_SCMP: {
4699 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
4700 			uintptr_t s1 = regs[r1];
4701 			uintptr_t s2 = regs[r2];
4702 
4703 			if (s1 != NULL &&
4704 			    !dtrace_strcanload(s1, sz, mstate, vstate))
4705 				break;
4706 			if (s2 != NULL &&
4707 			    !dtrace_strcanload(s2, sz, mstate, vstate))
4708 				break;
4709 
4710 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
4711 
4712 			cc_n = cc_r < 0;
4713 			cc_z = cc_r == 0;
4714 			cc_v = cc_c = 0;
4715 			break;
4716 		}
4717 		case DIF_OP_LDGA:
4718 			regs[rd] = dtrace_dif_variable(mstate, state,
4719 			    r1, regs[r2]);
4720 			break;
4721 		case DIF_OP_LDGS:
4722 			id = DIF_INSTR_VAR(instr);
4723 
4724 			if (id >= DIF_VAR_OTHER_UBASE) {
4725 				uintptr_t a;
4726 
4727 				id -= DIF_VAR_OTHER_UBASE;
4728 				svar = vstate->dtvs_globals[id];
4729 				ASSERT(svar != NULL);
4730 				v = &svar->dtsv_var;
4731 
4732 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
4733 					regs[rd] = svar->dtsv_data;
4734 					break;
4735 				}
4736 
4737 				a = (uintptr_t)svar->dtsv_data;
4738 
4739 				if (*(uint8_t *)a == UINT8_MAX) {
4740 					/*
4741 					 * If the 0th byte is set to UINT8_MAX
4742 					 * then this is to be treated as a
4743 					 * reference to a NULL variable.
4744 					 */
4745 					regs[rd] = NULL;
4746 				} else {
4747 					regs[rd] = a + sizeof (uint64_t);
4748 				}
4749 
4750 				break;
4751 			}
4752 
4753 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
4754 			break;
4755 
4756 		case DIF_OP_STGS:
4757 			id = DIF_INSTR_VAR(instr);
4758 
4759 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4760 			id -= DIF_VAR_OTHER_UBASE;
4761 
4762 			svar = vstate->dtvs_globals[id];
4763 			ASSERT(svar != NULL);
4764 			v = &svar->dtsv_var;
4765 
4766 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4767 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4768 
4769 				ASSERT(a != NULL);
4770 				ASSERT(svar->dtsv_size != 0);
4771 
4772 				if (regs[rd] == NULL) {
4773 					*(uint8_t *)a = UINT8_MAX;
4774 					break;
4775 				} else {
4776 					*(uint8_t *)a = 0;
4777 					a += sizeof (uint64_t);
4778 				}
4779 				if (!dtrace_vcanload(
4780 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4781 				    mstate, vstate))
4782 					break;
4783 
4784 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4785 				    (void *)a, &v->dtdv_type);
4786 				break;
4787 			}
4788 
4789 			svar->dtsv_data = regs[rd];
4790 			break;
4791 
4792 		case DIF_OP_LDTA:
4793 			/*
4794 			 * There are no DTrace built-in thread-local arrays at
4795 			 * present.  This opcode is saved for future work.
4796 			 */
4797 			*flags |= CPU_DTRACE_ILLOP;
4798 			regs[rd] = 0;
4799 			break;
4800 
4801 		case DIF_OP_LDLS:
4802 			id = DIF_INSTR_VAR(instr);
4803 
4804 			if (id < DIF_VAR_OTHER_UBASE) {
4805 				/*
4806 				 * For now, this has no meaning.
4807 				 */
4808 				regs[rd] = 0;
4809 				break;
4810 			}
4811 
4812 			id -= DIF_VAR_OTHER_UBASE;
4813 
4814 			ASSERT(id < vstate->dtvs_nlocals);
4815 			ASSERT(vstate->dtvs_locals != NULL);
4816 
4817 			svar = vstate->dtvs_locals[id];
4818 			ASSERT(svar != NULL);
4819 			v = &svar->dtsv_var;
4820 
4821 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4822 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4823 				size_t sz = v->dtdv_type.dtdt_size;
4824 
4825 				sz += sizeof (uint64_t);
4826 				ASSERT(svar->dtsv_size == NCPU * sz);
4827 				a += CPU->cpu_id * sz;
4828 
4829 				if (*(uint8_t *)a == UINT8_MAX) {
4830 					/*
4831 					 * If the 0th byte is set to UINT8_MAX
4832 					 * then this is to be treated as a
4833 					 * reference to a NULL variable.
4834 					 */
4835 					regs[rd] = NULL;
4836 				} else {
4837 					regs[rd] = a + sizeof (uint64_t);
4838 				}
4839 
4840 				break;
4841 			}
4842 
4843 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4844 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4845 			regs[rd] = tmp[CPU->cpu_id];
4846 			break;
4847 
4848 		case DIF_OP_STLS:
4849 			id = DIF_INSTR_VAR(instr);
4850 
4851 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4852 			id -= DIF_VAR_OTHER_UBASE;
4853 			ASSERT(id < vstate->dtvs_nlocals);
4854 
4855 			ASSERT(vstate->dtvs_locals != NULL);
4856 			svar = vstate->dtvs_locals[id];
4857 			ASSERT(svar != NULL);
4858 			v = &svar->dtsv_var;
4859 
4860 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4861 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4862 				size_t sz = v->dtdv_type.dtdt_size;
4863 
4864 				sz += sizeof (uint64_t);
4865 				ASSERT(svar->dtsv_size == NCPU * sz);
4866 				a += CPU->cpu_id * sz;
4867 
4868 				if (regs[rd] == NULL) {
4869 					*(uint8_t *)a = UINT8_MAX;
4870 					break;
4871 				} else {
4872 					*(uint8_t *)a = 0;
4873 					a += sizeof (uint64_t);
4874 				}
4875 
4876 				if (!dtrace_vcanload(
4877 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4878 				    mstate, vstate))
4879 					break;
4880 
4881 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4882 				    (void *)a, &v->dtdv_type);
4883 				break;
4884 			}
4885 
4886 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4887 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4888 			tmp[CPU->cpu_id] = regs[rd];
4889 			break;
4890 
4891 		case DIF_OP_LDTS: {
4892 			dtrace_dynvar_t *dvar;
4893 			dtrace_key_t *key;
4894 
4895 			id = DIF_INSTR_VAR(instr);
4896 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4897 			id -= DIF_VAR_OTHER_UBASE;
4898 			v = &vstate->dtvs_tlocals[id];
4899 
4900 			key = &tupregs[DIF_DTR_NREGS];
4901 			key[0].dttk_value = (uint64_t)id;
4902 			key[0].dttk_size = 0;
4903 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4904 			key[1].dttk_size = 0;
4905 
4906 			dvar = dtrace_dynvar(dstate, 2, key,
4907 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
4908 			    mstate, vstate);
4909 
4910 			if (dvar == NULL) {
4911 				regs[rd] = 0;
4912 				break;
4913 			}
4914 
4915 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4916 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4917 			} else {
4918 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4919 			}
4920 
4921 			break;
4922 		}
4923 
4924 		case DIF_OP_STTS: {
4925 			dtrace_dynvar_t *dvar;
4926 			dtrace_key_t *key;
4927 
4928 			id = DIF_INSTR_VAR(instr);
4929 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4930 			id -= DIF_VAR_OTHER_UBASE;
4931 
4932 			key = &tupregs[DIF_DTR_NREGS];
4933 			key[0].dttk_value = (uint64_t)id;
4934 			key[0].dttk_size = 0;
4935 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4936 			key[1].dttk_size = 0;
4937 			v = &vstate->dtvs_tlocals[id];
4938 
4939 			dvar = dtrace_dynvar(dstate, 2, key,
4940 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4941 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4942 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4943 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
4944 
4945 			/*
4946 			 * Given that we're storing to thread-local data,
4947 			 * we need to flush our predicate cache.
4948 			 */
4949 			curthread->t_predcache = NULL;
4950 
4951 			if (dvar == NULL)
4952 				break;
4953 
4954 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4955 				if (!dtrace_vcanload(
4956 				    (void *)(uintptr_t)regs[rd],
4957 				    &v->dtdv_type, mstate, vstate))
4958 					break;
4959 
4960 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4961 				    dvar->dtdv_data, &v->dtdv_type);
4962 			} else {
4963 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4964 			}
4965 
4966 			break;
4967 		}
4968 
4969 		case DIF_OP_SRA:
4970 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
4971 			break;
4972 
4973 		case DIF_OP_CALL:
4974 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
4975 			    regs, tupregs, ttop, mstate, state);
4976 			break;
4977 
4978 		case DIF_OP_PUSHTR:
4979 			if (ttop == DIF_DTR_NREGS) {
4980 				*flags |= CPU_DTRACE_TUPOFLOW;
4981 				break;
4982 			}
4983 
4984 			if (r1 == DIF_TYPE_STRING) {
4985 				/*
4986 				 * If this is a string type and the size is 0,
4987 				 * we'll use the system-wide default string
4988 				 * size.  Note that we are _not_ looking at
4989 				 * the value of the DTRACEOPT_STRSIZE option;
4990 				 * had this been set, we would expect to have
4991 				 * a non-zero size value in the "pushtr".
4992 				 */
4993 				tupregs[ttop].dttk_size =
4994 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
4995 				    regs[r2] ? regs[r2] :
4996 				    dtrace_strsize_default) + 1;
4997 			} else {
4998 				tupregs[ttop].dttk_size = regs[r2];
4999 			}
5000 
5001 			tupregs[ttop++].dttk_value = regs[rd];
5002 			break;
5003 
5004 		case DIF_OP_PUSHTV:
5005 			if (ttop == DIF_DTR_NREGS) {
5006 				*flags |= CPU_DTRACE_TUPOFLOW;
5007 				break;
5008 			}
5009 
5010 			tupregs[ttop].dttk_value = regs[rd];
5011 			tupregs[ttop++].dttk_size = 0;
5012 			break;
5013 
5014 		case DIF_OP_POPTS:
5015 			if (ttop != 0)
5016 				ttop--;
5017 			break;
5018 
5019 		case DIF_OP_FLUSHTS:
5020 			ttop = 0;
5021 			break;
5022 
5023 		case DIF_OP_LDGAA:
5024 		case DIF_OP_LDTAA: {
5025 			dtrace_dynvar_t *dvar;
5026 			dtrace_key_t *key = tupregs;
5027 			uint_t nkeys = ttop;
5028 
5029 			id = DIF_INSTR_VAR(instr);
5030 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5031 			id -= DIF_VAR_OTHER_UBASE;
5032 
5033 			key[nkeys].dttk_value = (uint64_t)id;
5034 			key[nkeys++].dttk_size = 0;
5035 
5036 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
5037 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5038 				key[nkeys++].dttk_size = 0;
5039 				v = &vstate->dtvs_tlocals[id];
5040 			} else {
5041 				v = &vstate->dtvs_globals[id]->dtsv_var;
5042 			}
5043 
5044 			dvar = dtrace_dynvar(dstate, nkeys, key,
5045 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5046 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5047 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
5048 
5049 			if (dvar == NULL) {
5050 				regs[rd] = 0;
5051 				break;
5052 			}
5053 
5054 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5055 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
5056 			} else {
5057 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
5058 			}
5059 
5060 			break;
5061 		}
5062 
5063 		case DIF_OP_STGAA:
5064 		case DIF_OP_STTAA: {
5065 			dtrace_dynvar_t *dvar;
5066 			dtrace_key_t *key = tupregs;
5067 			uint_t nkeys = ttop;
5068 
5069 			id = DIF_INSTR_VAR(instr);
5070 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
5071 			id -= DIF_VAR_OTHER_UBASE;
5072 
5073 			key[nkeys].dttk_value = (uint64_t)id;
5074 			key[nkeys++].dttk_size = 0;
5075 
5076 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
5077 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
5078 				key[nkeys++].dttk_size = 0;
5079 				v = &vstate->dtvs_tlocals[id];
5080 			} else {
5081 				v = &vstate->dtvs_globals[id]->dtsv_var;
5082 			}
5083 
5084 			dvar = dtrace_dynvar(dstate, nkeys, key,
5085 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
5086 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
5087 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
5088 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
5089 
5090 			if (dvar == NULL)
5091 				break;
5092 
5093 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
5094 				if (!dtrace_vcanload(
5095 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
5096 				    mstate, vstate))
5097 					break;
5098 
5099 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
5100 				    dvar->dtdv_data, &v->dtdv_type);
5101 			} else {
5102 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
5103 			}
5104 
5105 			break;
5106 		}
5107 
5108 		case DIF_OP_ALLOCS: {
5109 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5110 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
5111 
5112 			/*
5113 			 * Rounding up the user allocation size could have
5114 			 * overflowed large, bogus allocations (like -1ULL) to
5115 			 * 0.
5116 			 */
5117 			if (size < regs[r1] ||
5118 			    !DTRACE_INSCRATCH(mstate, size)) {
5119 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5120 				regs[rd] = NULL;
5121 				break;
5122 			}
5123 
5124 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5125 			mstate->dtms_scratch_ptr += size;
5126 			regs[rd] = ptr;
5127 			break;
5128 		}
5129 
5130 		case DIF_OP_COPYS:
5131 			if (!dtrace_canstore(regs[rd], regs[r2],
5132 			    mstate, vstate)) {
5133 				*flags |= CPU_DTRACE_BADADDR;
5134 				*illval = regs[rd];
5135 				break;
5136 			}
5137 
5138 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5139 				break;
5140 
5141 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
5142 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5143 			break;
5144 
5145 		case DIF_OP_STB:
5146 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5147 				*flags |= CPU_DTRACE_BADADDR;
5148 				*illval = regs[rd];
5149 				break;
5150 			}
5151 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5152 			break;
5153 
5154 		case DIF_OP_STH:
5155 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5156 				*flags |= CPU_DTRACE_BADADDR;
5157 				*illval = regs[rd];
5158 				break;
5159 			}
5160 			if (regs[rd] & 1) {
5161 				*flags |= CPU_DTRACE_BADALIGN;
5162 				*illval = regs[rd];
5163 				break;
5164 			}
5165 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5166 			break;
5167 
5168 		case DIF_OP_STW:
5169 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5170 				*flags |= CPU_DTRACE_BADADDR;
5171 				*illval = regs[rd];
5172 				break;
5173 			}
5174 			if (regs[rd] & 3) {
5175 				*flags |= CPU_DTRACE_BADALIGN;
5176 				*illval = regs[rd];
5177 				break;
5178 			}
5179 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5180 			break;
5181 
5182 		case DIF_OP_STX:
5183 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5184 				*flags |= CPU_DTRACE_BADADDR;
5185 				*illval = regs[rd];
5186 				break;
5187 			}
5188 			if (regs[rd] & 7) {
5189 				*flags |= CPU_DTRACE_BADALIGN;
5190 				*illval = regs[rd];
5191 				break;
5192 			}
5193 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5194 			break;
5195 		}
5196 	}
5197 
5198 	if (!(*flags & CPU_DTRACE_FAULT))
5199 		return (rval);
5200 
5201 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5202 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5203 
5204 	return (0);
5205 }
5206 
5207 static void
5208 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5209 {
5210 	dtrace_probe_t *probe = ecb->dte_probe;
5211 	dtrace_provider_t *prov = probe->dtpr_provider;
5212 	char c[DTRACE_FULLNAMELEN + 80], *str;
5213 	char *msg = "dtrace: breakpoint action at probe ";
5214 	char *ecbmsg = " (ecb ";
5215 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5216 	uintptr_t val = (uintptr_t)ecb;
5217 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5218 
5219 	if (dtrace_destructive_disallow)
5220 		return;
5221 
5222 	/*
5223 	 * It's impossible to be taking action on the NULL probe.
5224 	 */
5225 	ASSERT(probe != NULL);
5226 
5227 	/*
5228 	 * This is a poor man's (destitute man's?) sprintf():  we want to
5229 	 * print the provider name, module name, function name and name of
5230 	 * the probe, along with the hex address of the ECB with the breakpoint
5231 	 * action -- all of which we must place in the character buffer by
5232 	 * hand.
5233 	 */
5234 	while (*msg != '\0')
5235 		c[i++] = *msg++;
5236 
5237 	for (str = prov->dtpv_name; *str != '\0'; str++)
5238 		c[i++] = *str;
5239 	c[i++] = ':';
5240 
5241 	for (str = probe->dtpr_mod; *str != '\0'; str++)
5242 		c[i++] = *str;
5243 	c[i++] = ':';
5244 
5245 	for (str = probe->dtpr_func; *str != '\0'; str++)
5246 		c[i++] = *str;
5247 	c[i++] = ':';
5248 
5249 	for (str = probe->dtpr_name; *str != '\0'; str++)
5250 		c[i++] = *str;
5251 
5252 	while (*ecbmsg != '\0')
5253 		c[i++] = *ecbmsg++;
5254 
5255 	while (shift >= 0) {
5256 		mask = (uintptr_t)0xf << shift;
5257 
5258 		if (val >= ((uintptr_t)1 << shift))
5259 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5260 		shift -= 4;
5261 	}
5262 
5263 	c[i++] = ')';
5264 	c[i] = '\0';
5265 
5266 	debug_enter(c);
5267 }
5268 
5269 static void
5270 dtrace_action_panic(dtrace_ecb_t *ecb)
5271 {
5272 	dtrace_probe_t *probe = ecb->dte_probe;
5273 
5274 	/*
5275 	 * It's impossible to be taking action on the NULL probe.
5276 	 */
5277 	ASSERT(probe != NULL);
5278 
5279 	if (dtrace_destructive_disallow)
5280 		return;
5281 
5282 	if (dtrace_panicked != NULL)
5283 		return;
5284 
5285 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5286 		return;
5287 
5288 	/*
5289 	 * We won the right to panic.  (We want to be sure that only one
5290 	 * thread calls panic() from dtrace_probe(), and that panic() is
5291 	 * called exactly once.)
5292 	 */
5293 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5294 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5295 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5296 }
5297 
5298 static void
5299 dtrace_action_raise(uint64_t sig)
5300 {
5301 	if (dtrace_destructive_disallow)
5302 		return;
5303 
5304 	if (sig >= NSIG) {
5305 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5306 		return;
5307 	}
5308 
5309 	/*
5310 	 * raise() has a queue depth of 1 -- we ignore all subsequent
5311 	 * invocations of the raise() action.
5312 	 */
5313 	if (curthread->t_dtrace_sig == 0)
5314 		curthread->t_dtrace_sig = (uint8_t)sig;
5315 
5316 	curthread->t_sig_check = 1;
5317 	aston(curthread);
5318 }
5319 
5320 static void
5321 dtrace_action_stop(void)
5322 {
5323 	if (dtrace_destructive_disallow)
5324 		return;
5325 
5326 	if (!curthread->t_dtrace_stop) {
5327 		curthread->t_dtrace_stop = 1;
5328 		curthread->t_sig_check = 1;
5329 		aston(curthread);
5330 	}
5331 }
5332 
5333 static void
5334 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5335 {
5336 	hrtime_t now;
5337 	volatile uint16_t *flags;
5338 	cpu_t *cpu = CPU;
5339 
5340 	if (dtrace_destructive_disallow)
5341 		return;
5342 
5343 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5344 
5345 	now = dtrace_gethrtime();
5346 
5347 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5348 		/*
5349 		 * We need to advance the mark to the current time.
5350 		 */
5351 		cpu->cpu_dtrace_chillmark = now;
5352 		cpu->cpu_dtrace_chilled = 0;
5353 	}
5354 
5355 	/*
5356 	 * Now check to see if the requested chill time would take us over
5357 	 * the maximum amount of time allowed in the chill interval.  (Or
5358 	 * worse, if the calculation itself induces overflow.)
5359 	 */
5360 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5361 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5362 		*flags |= CPU_DTRACE_ILLOP;
5363 		return;
5364 	}
5365 
5366 	while (dtrace_gethrtime() - now < val)
5367 		continue;
5368 
5369 	/*
5370 	 * Normally, we assure that the value of the variable "timestamp" does
5371 	 * not change within an ECB.  The presence of chill() represents an
5372 	 * exception to this rule, however.
5373 	 */
5374 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5375 	cpu->cpu_dtrace_chilled += val;
5376 }
5377 
5378 static void
5379 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5380     uint64_t *buf, uint64_t arg)
5381 {
5382 	int nframes = DTRACE_USTACK_NFRAMES(arg);
5383 	int strsize = DTRACE_USTACK_STRSIZE(arg);
5384 	uint64_t *pcs = &buf[1], *fps;
5385 	char *str = (char *)&pcs[nframes];
5386 	int size, offs = 0, i, j;
5387 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
5388 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5389 	char *sym;
5390 
5391 	/*
5392 	 * Should be taking a faster path if string space has not been
5393 	 * allocated.
5394 	 */
5395 	ASSERT(strsize != 0);
5396 
5397 	/*
5398 	 * We will first allocate some temporary space for the frame pointers.
5399 	 */
5400 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5401 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5402 	    (nframes * sizeof (uint64_t));
5403 
5404 	if (!DTRACE_INSCRATCH(mstate, size)) {
5405 		/*
5406 		 * Not enough room for our frame pointers -- need to indicate
5407 		 * that we ran out of scratch space.
5408 		 */
5409 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5410 		return;
5411 	}
5412 
5413 	mstate->dtms_scratch_ptr += size;
5414 	saved = mstate->dtms_scratch_ptr;
5415 
5416 	/*
5417 	 * Now get a stack with both program counters and frame pointers.
5418 	 */
5419 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5420 	dtrace_getufpstack(buf, fps, nframes + 1);
5421 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5422 
5423 	/*
5424 	 * If that faulted, we're cooked.
5425 	 */
5426 	if (*flags & CPU_DTRACE_FAULT)
5427 		goto out;
5428 
5429 	/*
5430 	 * Now we want to walk up the stack, calling the USTACK helper.  For
5431 	 * each iteration, we restore the scratch pointer.
5432 	 */
5433 	for (i = 0; i < nframes; i++) {
5434 		mstate->dtms_scratch_ptr = saved;
5435 
5436 		if (offs >= strsize)
5437 			break;
5438 
5439 		sym = (char *)(uintptr_t)dtrace_helper(
5440 		    DTRACE_HELPER_ACTION_USTACK,
5441 		    mstate, state, pcs[i], fps[i]);
5442 
5443 		/*
5444 		 * If we faulted while running the helper, we're going to
5445 		 * clear the fault and null out the corresponding string.
5446 		 */
5447 		if (*flags & CPU_DTRACE_FAULT) {
5448 			*flags &= ~CPU_DTRACE_FAULT;
5449 			str[offs++] = '\0';
5450 			continue;
5451 		}
5452 
5453 		if (sym == NULL) {
5454 			str[offs++] = '\0';
5455 			continue;
5456 		}
5457 
5458 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5459 
5460 		/*
5461 		 * Now copy in the string that the helper returned to us.
5462 		 */
5463 		for (j = 0; offs + j < strsize; j++) {
5464 			if ((str[offs + j] = sym[j]) == '\0')
5465 				break;
5466 		}
5467 
5468 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5469 
5470 		offs += j + 1;
5471 	}
5472 
5473 	if (offs >= strsize) {
5474 		/*
5475 		 * If we didn't have room for all of the strings, we don't
5476 		 * abort processing -- this needn't be a fatal error -- but we
5477 		 * still want to increment a counter (dts_stkstroverflows) to
5478 		 * allow this condition to be warned about.  (If this is from
5479 		 * a jstack() action, it is easily tuned via jstackstrsize.)
5480 		 */
5481 		dtrace_error(&state->dts_stkstroverflows);
5482 	}
5483 
5484 	while (offs < strsize)
5485 		str[offs++] = '\0';
5486 
5487 out:
5488 	mstate->dtms_scratch_ptr = old;
5489 }
5490 
5491 /*
5492  * If you're looking for the epicenter of DTrace, you just found it.  This
5493  * is the function called by the provider to fire a probe -- from which all
5494  * subsequent probe-context DTrace activity emanates.
5495  */
5496 void
5497 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
5498     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
5499 {
5500 	processorid_t cpuid;
5501 	dtrace_icookie_t cookie;
5502 	dtrace_probe_t *probe;
5503 	dtrace_mstate_t mstate;
5504 	dtrace_ecb_t *ecb;
5505 	dtrace_action_t *act;
5506 	intptr_t offs;
5507 	size_t size;
5508 	int vtime, onintr;
5509 	volatile uint16_t *flags;
5510 	hrtime_t now;
5511 
5512 	/*
5513 	 * Kick out immediately if this CPU is still being born (in which case
5514 	 * curthread will be set to -1) or the current thread can't allow
5515 	 * probes in its current context.
5516 	 */
5517 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
5518 		return;
5519 
5520 	cookie = dtrace_interrupt_disable();
5521 	probe = dtrace_probes[id - 1];
5522 	cpuid = CPU->cpu_id;
5523 	onintr = CPU_ON_INTR(CPU);
5524 
5525 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
5526 	    probe->dtpr_predcache == curthread->t_predcache) {
5527 		/*
5528 		 * We have hit in the predicate cache; we know that
5529 		 * this predicate would evaluate to be false.
5530 		 */
5531 		dtrace_interrupt_enable(cookie);
5532 		return;
5533 	}
5534 
5535 	if (panic_quiesce) {
5536 		/*
5537 		 * We don't trace anything if we're panicking.
5538 		 */
5539 		dtrace_interrupt_enable(cookie);
5540 		return;
5541 	}
5542 
5543 	now = dtrace_gethrtime();
5544 	vtime = dtrace_vtime_references != 0;
5545 
5546 	if (vtime && curthread->t_dtrace_start)
5547 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
5548 
5549 	mstate.dtms_difo = NULL;
5550 	mstate.dtms_probe = probe;
5551 	mstate.dtms_strtok = NULL;
5552 	mstate.dtms_arg[0] = arg0;
5553 	mstate.dtms_arg[1] = arg1;
5554 	mstate.dtms_arg[2] = arg2;
5555 	mstate.dtms_arg[3] = arg3;
5556 	mstate.dtms_arg[4] = arg4;
5557 
5558 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
5559 
5560 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
5561 		dtrace_predicate_t *pred = ecb->dte_predicate;
5562 		dtrace_state_t *state = ecb->dte_state;
5563 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
5564 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
5565 		dtrace_vstate_t *vstate = &state->dts_vstate;
5566 		dtrace_provider_t *prov = probe->dtpr_provider;
5567 		int committed = 0;
5568 		caddr_t tomax;
5569 
5570 		/*
5571 		 * A little subtlety with the following (seemingly innocuous)
5572 		 * declaration of the automatic 'val':  by looking at the
5573 		 * code, you might think that it could be declared in the
5574 		 * action processing loop, below.  (That is, it's only used in
5575 		 * the action processing loop.)  However, it must be declared
5576 		 * out of that scope because in the case of DIF expression
5577 		 * arguments to aggregating actions, one iteration of the
5578 		 * action loop will use the last iteration's value.
5579 		 */
5580 #ifdef lint
5581 		uint64_t val = 0;
5582 #else
5583 		uint64_t val;
5584 #endif
5585 
5586 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
5587 		*flags &= ~CPU_DTRACE_ERROR;
5588 
5589 		if (prov == dtrace_provider) {
5590 			/*
5591 			 * If dtrace itself is the provider of this probe,
5592 			 * we're only going to continue processing the ECB if
5593 			 * arg0 (the dtrace_state_t) is equal to the ECB's
5594 			 * creating state.  (This prevents disjoint consumers
5595 			 * from seeing one another's metaprobes.)
5596 			 */
5597 			if (arg0 != (uint64_t)(uintptr_t)state)
5598 				continue;
5599 		}
5600 
5601 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
5602 			/*
5603 			 * We're not currently active.  If our provider isn't
5604 			 * the dtrace pseudo provider, we're not interested.
5605 			 */
5606 			if (prov != dtrace_provider)
5607 				continue;
5608 
5609 			/*
5610 			 * Now we must further check if we are in the BEGIN
5611 			 * probe.  If we are, we will only continue processing
5612 			 * if we're still in WARMUP -- if one BEGIN enabling
5613 			 * has invoked the exit() action, we don't want to
5614 			 * evaluate subsequent BEGIN enablings.
5615 			 */
5616 			if (probe->dtpr_id == dtrace_probeid_begin &&
5617 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
5618 				ASSERT(state->dts_activity ==
5619 				    DTRACE_ACTIVITY_DRAINING);
5620 				continue;
5621 			}
5622 		}
5623 
5624 		if (ecb->dte_cond) {
5625 			/*
5626 			 * If the dte_cond bits indicate that this
5627 			 * consumer is only allowed to see user-mode firings
5628 			 * of this probe, call the provider's dtps_usermode()
5629 			 * entry point to check that the probe was fired
5630 			 * while in a user context. Skip this ECB if that's
5631 			 * not the case.
5632 			 */
5633 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
5634 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
5635 			    probe->dtpr_id, probe->dtpr_arg) == 0)
5636 				continue;
5637 
5638 			/*
5639 			 * This is more subtle than it looks. We have to be
5640 			 * absolutely certain that CRED() isn't going to
5641 			 * change out from under us so it's only legit to
5642 			 * examine that structure if we're in constrained
5643 			 * situations. Currently, the only times we'll this
5644 			 * check is if a non-super-user has enabled the
5645 			 * profile or syscall providers -- providers that
5646 			 * allow visibility of all processes. For the
5647 			 * profile case, the check above will ensure that
5648 			 * we're examining a user context.
5649 			 */
5650 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
5651 				cred_t *cr;
5652 				cred_t *s_cr =
5653 				    ecb->dte_state->dts_cred.dcr_cred;
5654 				proc_t *proc;
5655 
5656 				ASSERT(s_cr != NULL);
5657 
5658 				if ((cr = CRED()) == NULL ||
5659 				    s_cr->cr_uid != cr->cr_uid ||
5660 				    s_cr->cr_uid != cr->cr_ruid ||
5661 				    s_cr->cr_uid != cr->cr_suid ||
5662 				    s_cr->cr_gid != cr->cr_gid ||
5663 				    s_cr->cr_gid != cr->cr_rgid ||
5664 				    s_cr->cr_gid != cr->cr_sgid ||
5665 				    (proc = ttoproc(curthread)) == NULL ||
5666 				    (proc->p_flag & SNOCD))
5667 					continue;
5668 			}
5669 
5670 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
5671 				cred_t *cr;
5672 				cred_t *s_cr =
5673 				    ecb->dte_state->dts_cred.dcr_cred;
5674 
5675 				ASSERT(s_cr != NULL);
5676 
5677 				if ((cr = CRED()) == NULL ||
5678 				    s_cr->cr_zone->zone_id !=
5679 				    cr->cr_zone->zone_id)
5680 					continue;
5681 			}
5682 		}
5683 
5684 		if (now - state->dts_alive > dtrace_deadman_timeout) {
5685 			/*
5686 			 * We seem to be dead.  Unless we (a) have kernel
5687 			 * destructive permissions (b) have expicitly enabled
5688 			 * destructive actions and (c) destructive actions have
5689 			 * not been disabled, we're going to transition into
5690 			 * the KILLED state, from which no further processing
5691 			 * on this state will be performed.
5692 			 */
5693 			if (!dtrace_priv_kernel_destructive(state) ||
5694 			    !state->dts_cred.dcr_destructive ||
5695 			    dtrace_destructive_disallow) {
5696 				void *activity = &state->dts_activity;
5697 				dtrace_activity_t current;
5698 
5699 				do {
5700 					current = state->dts_activity;
5701 				} while (dtrace_cas32(activity, current,
5702 				    DTRACE_ACTIVITY_KILLED) != current);
5703 
5704 				continue;
5705 			}
5706 		}
5707 
5708 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
5709 		    ecb->dte_alignment, state, &mstate)) < 0)
5710 			continue;
5711 
5712 		tomax = buf->dtb_tomax;
5713 		ASSERT(tomax != NULL);
5714 
5715 		if (ecb->dte_size != 0)
5716 			DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
5717 
5718 		mstate.dtms_epid = ecb->dte_epid;
5719 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
5720 
5721 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
5722 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
5723 		else
5724 			mstate.dtms_access = 0;
5725 
5726 		if (pred != NULL) {
5727 			dtrace_difo_t *dp = pred->dtp_difo;
5728 			int rval;
5729 
5730 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
5731 
5732 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
5733 				dtrace_cacheid_t cid = probe->dtpr_predcache;
5734 
5735 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
5736 					/*
5737 					 * Update the predicate cache...
5738 					 */
5739 					ASSERT(cid == pred->dtp_cacheid);
5740 					curthread->t_predcache = cid;
5741 				}
5742 
5743 				continue;
5744 			}
5745 		}
5746 
5747 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
5748 		    act != NULL; act = act->dta_next) {
5749 			size_t valoffs;
5750 			dtrace_difo_t *dp;
5751 			dtrace_recdesc_t *rec = &act->dta_rec;
5752 
5753 			size = rec->dtrd_size;
5754 			valoffs = offs + rec->dtrd_offset;
5755 
5756 			if (DTRACEACT_ISAGG(act->dta_kind)) {
5757 				uint64_t v = 0xbad;
5758 				dtrace_aggregation_t *agg;
5759 
5760 				agg = (dtrace_aggregation_t *)act;
5761 
5762 				if ((dp = act->dta_difo) != NULL)
5763 					v = dtrace_dif_emulate(dp,
5764 					    &mstate, vstate, state);
5765 
5766 				if (*flags & CPU_DTRACE_ERROR)
5767 					continue;
5768 
5769 				/*
5770 				 * Note that we always pass the expression
5771 				 * value from the previous iteration of the
5772 				 * action loop.  This value will only be used
5773 				 * if there is an expression argument to the
5774 				 * aggregating action, denoted by the
5775 				 * dtag_hasarg field.
5776 				 */
5777 				dtrace_aggregate(agg, buf,
5778 				    offs, aggbuf, v, val);
5779 				continue;
5780 			}
5781 
5782 			switch (act->dta_kind) {
5783 			case DTRACEACT_STOP:
5784 				if (dtrace_priv_proc_destructive(state))
5785 					dtrace_action_stop();
5786 				continue;
5787 
5788 			case DTRACEACT_BREAKPOINT:
5789 				if (dtrace_priv_kernel_destructive(state))
5790 					dtrace_action_breakpoint(ecb);
5791 				continue;
5792 
5793 			case DTRACEACT_PANIC:
5794 				if (dtrace_priv_kernel_destructive(state))
5795 					dtrace_action_panic(ecb);
5796 				continue;
5797 
5798 			case DTRACEACT_STACK:
5799 				if (!dtrace_priv_kernel(state))
5800 					continue;
5801 
5802 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
5803 				    size / sizeof (pc_t), probe->dtpr_aframes,
5804 				    DTRACE_ANCHORED(probe) ? NULL :
5805 				    (uint32_t *)arg0);
5806 
5807 				continue;
5808 
5809 			case DTRACEACT_JSTACK:
5810 			case DTRACEACT_USTACK:
5811 				if (!dtrace_priv_proc(state))
5812 					continue;
5813 
5814 				/*
5815 				 * See comment in DIF_VAR_PID.
5816 				 */
5817 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
5818 				    CPU_ON_INTR(CPU)) {
5819 					int depth = DTRACE_USTACK_NFRAMES(
5820 					    rec->dtrd_arg) + 1;
5821 
5822 					dtrace_bzero((void *)(tomax + valoffs),
5823 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
5824 					    + depth * sizeof (uint64_t));
5825 
5826 					continue;
5827 				}
5828 
5829 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
5830 				    curproc->p_dtrace_helpers != NULL) {
5831 					/*
5832 					 * This is the slow path -- we have
5833 					 * allocated string space, and we're
5834 					 * getting the stack of a process that
5835 					 * has helpers.  Call into a separate
5836 					 * routine to perform this processing.
5837 					 */
5838 					dtrace_action_ustack(&mstate, state,
5839 					    (uint64_t *)(tomax + valoffs),
5840 					    rec->dtrd_arg);
5841 					continue;
5842 				}
5843 
5844 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5845 				dtrace_getupcstack((uint64_t *)
5846 				    (tomax + valoffs),
5847 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
5848 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5849 				continue;
5850 
5851 			default:
5852 				break;
5853 			}
5854 
5855 			dp = act->dta_difo;
5856 			ASSERT(dp != NULL);
5857 
5858 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
5859 
5860 			if (*flags & CPU_DTRACE_ERROR)
5861 				continue;
5862 
5863 			switch (act->dta_kind) {
5864 			case DTRACEACT_SPECULATE:
5865 				ASSERT(buf == &state->dts_buffer[cpuid]);
5866 				buf = dtrace_speculation_buffer(state,
5867 				    cpuid, val);
5868 
5869 				if (buf == NULL) {
5870 					*flags |= CPU_DTRACE_DROP;
5871 					continue;
5872 				}
5873 
5874 				offs = dtrace_buffer_reserve(buf,
5875 				    ecb->dte_needed, ecb->dte_alignment,
5876 				    state, NULL);
5877 
5878 				if (offs < 0) {
5879 					*flags |= CPU_DTRACE_DROP;
5880 					continue;
5881 				}
5882 
5883 				tomax = buf->dtb_tomax;
5884 				ASSERT(tomax != NULL);
5885 
5886 				if (ecb->dte_size != 0)
5887 					DTRACE_STORE(uint32_t, tomax, offs,
5888 					    ecb->dte_epid);
5889 				continue;
5890 
5891 			case DTRACEACT_CHILL:
5892 				if (dtrace_priv_kernel_destructive(state))
5893 					dtrace_action_chill(&mstate, val);
5894 				continue;
5895 
5896 			case DTRACEACT_RAISE:
5897 				if (dtrace_priv_proc_destructive(state))
5898 					dtrace_action_raise(val);
5899 				continue;
5900 
5901 			case DTRACEACT_COMMIT:
5902 				ASSERT(!committed);
5903 
5904 				/*
5905 				 * We need to commit our buffer state.
5906 				 */
5907 				if (ecb->dte_size)
5908 					buf->dtb_offset = offs + ecb->dte_size;
5909 				buf = &state->dts_buffer[cpuid];
5910 				dtrace_speculation_commit(state, cpuid, val);
5911 				committed = 1;
5912 				continue;
5913 
5914 			case DTRACEACT_DISCARD:
5915 				dtrace_speculation_discard(state, cpuid, val);
5916 				continue;
5917 
5918 			case DTRACEACT_DIFEXPR:
5919 			case DTRACEACT_LIBACT:
5920 			case DTRACEACT_PRINTF:
5921 			case DTRACEACT_PRINTA:
5922 			case DTRACEACT_SYSTEM:
5923 			case DTRACEACT_FREOPEN:
5924 				break;
5925 
5926 			case DTRACEACT_SYM:
5927 			case DTRACEACT_MOD:
5928 				if (!dtrace_priv_kernel(state))
5929 					continue;
5930 				break;
5931 
5932 			case DTRACEACT_USYM:
5933 			case DTRACEACT_UMOD:
5934 			case DTRACEACT_UADDR: {
5935 				struct pid *pid = curthread->t_procp->p_pidp;
5936 
5937 				if (!dtrace_priv_proc(state))
5938 					continue;
5939 
5940 				DTRACE_STORE(uint64_t, tomax,
5941 				    valoffs, (uint64_t)pid->pid_id);
5942 				DTRACE_STORE(uint64_t, tomax,
5943 				    valoffs + sizeof (uint64_t), val);
5944 
5945 				continue;
5946 			}
5947 
5948 			case DTRACEACT_EXIT: {
5949 				/*
5950 				 * For the exit action, we are going to attempt
5951 				 * to atomically set our activity to be
5952 				 * draining.  If this fails (either because
5953 				 * another CPU has beat us to the exit action,
5954 				 * or because our current activity is something
5955 				 * other than ACTIVE or WARMUP), we will
5956 				 * continue.  This assures that the exit action
5957 				 * can be successfully recorded at most once
5958 				 * when we're in the ACTIVE state.  If we're
5959 				 * encountering the exit() action while in
5960 				 * COOLDOWN, however, we want to honor the new
5961 				 * status code.  (We know that we're the only
5962 				 * thread in COOLDOWN, so there is no race.)
5963 				 */
5964 				void *activity = &state->dts_activity;
5965 				dtrace_activity_t current = state->dts_activity;
5966 
5967 				if (current == DTRACE_ACTIVITY_COOLDOWN)
5968 					break;
5969 
5970 				if (current != DTRACE_ACTIVITY_WARMUP)
5971 					current = DTRACE_ACTIVITY_ACTIVE;
5972 
5973 				if (dtrace_cas32(activity, current,
5974 				    DTRACE_ACTIVITY_DRAINING) != current) {
5975 					*flags |= CPU_DTRACE_DROP;
5976 					continue;
5977 				}
5978 
5979 				break;
5980 			}
5981 
5982 			default:
5983 				ASSERT(0);
5984 			}
5985 
5986 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
5987 				uintptr_t end = valoffs + size;
5988 
5989 				if (!dtrace_vcanload((void *)(uintptr_t)val,
5990 				    &dp->dtdo_rtype, &mstate, vstate))
5991 					continue;
5992 
5993 				/*
5994 				 * If this is a string, we're going to only
5995 				 * load until we find the zero byte -- after
5996 				 * which we'll store zero bytes.
5997 				 */
5998 				if (dp->dtdo_rtype.dtdt_kind ==
5999 				    DIF_TYPE_STRING) {
6000 					char c = '\0' + 1;
6001 					int intuple = act->dta_intuple;
6002 					size_t s;
6003 
6004 					for (s = 0; s < size; s++) {
6005 						if (c != '\0')
6006 							c = dtrace_load8(val++);
6007 
6008 						DTRACE_STORE(uint8_t, tomax,
6009 						    valoffs++, c);
6010 
6011 						if (c == '\0' && intuple)
6012 							break;
6013 					}
6014 
6015 					continue;
6016 				}
6017 
6018 				while (valoffs < end) {
6019 					DTRACE_STORE(uint8_t, tomax, valoffs++,
6020 					    dtrace_load8(val++));
6021 				}
6022 
6023 				continue;
6024 			}
6025 
6026 			switch (size) {
6027 			case 0:
6028 				break;
6029 
6030 			case sizeof (uint8_t):
6031 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
6032 				break;
6033 			case sizeof (uint16_t):
6034 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
6035 				break;
6036 			case sizeof (uint32_t):
6037 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
6038 				break;
6039 			case sizeof (uint64_t):
6040 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
6041 				break;
6042 			default:
6043 				/*
6044 				 * Any other size should have been returned by
6045 				 * reference, not by value.
6046 				 */
6047 				ASSERT(0);
6048 				break;
6049 			}
6050 		}
6051 
6052 		if (*flags & CPU_DTRACE_DROP)
6053 			continue;
6054 
6055 		if (*flags & CPU_DTRACE_FAULT) {
6056 			int ndx;
6057 			dtrace_action_t *err;
6058 
6059 			buf->dtb_errors++;
6060 
6061 			if (probe->dtpr_id == dtrace_probeid_error) {
6062 				/*
6063 				 * There's nothing we can do -- we had an
6064 				 * error on the error probe.  We bump an
6065 				 * error counter to at least indicate that
6066 				 * this condition happened.
6067 				 */
6068 				dtrace_error(&state->dts_dblerrors);
6069 				continue;
6070 			}
6071 
6072 			if (vtime) {
6073 				/*
6074 				 * Before recursing on dtrace_probe(), we
6075 				 * need to explicitly clear out our start
6076 				 * time to prevent it from being accumulated
6077 				 * into t_dtrace_vtime.
6078 				 */
6079 				curthread->t_dtrace_start = 0;
6080 			}
6081 
6082 			/*
6083 			 * Iterate over the actions to figure out which action
6084 			 * we were processing when we experienced the error.
6085 			 * Note that act points _past_ the faulting action; if
6086 			 * act is ecb->dte_action, the fault was in the
6087 			 * predicate, if it's ecb->dte_action->dta_next it's
6088 			 * in action #1, and so on.
6089 			 */
6090 			for (err = ecb->dte_action, ndx = 0;
6091 			    err != act; err = err->dta_next, ndx++)
6092 				continue;
6093 
6094 			dtrace_probe_error(state, ecb->dte_epid, ndx,
6095 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
6096 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
6097 			    cpu_core[cpuid].cpuc_dtrace_illval);
6098 
6099 			continue;
6100 		}
6101 
6102 		if (!committed)
6103 			buf->dtb_offset = offs + ecb->dte_size;
6104 	}
6105 
6106 	if (vtime)
6107 		curthread->t_dtrace_start = dtrace_gethrtime();
6108 
6109 	dtrace_interrupt_enable(cookie);
6110 }
6111 
6112 /*
6113  * DTrace Probe Hashing Functions
6114  *
6115  * The functions in this section (and indeed, the functions in remaining
6116  * sections) are not _called_ from probe context.  (Any exceptions to this are
6117  * marked with a "Note:".)  Rather, they are called from elsewhere in the
6118  * DTrace framework to look-up probes in, add probes to and remove probes from
6119  * the DTrace probe hashes.  (Each probe is hashed by each element of the
6120  * probe tuple -- allowing for fast lookups, regardless of what was
6121  * specified.)
6122  */
6123 static uint_t
6124 dtrace_hash_str(char *p)
6125 {
6126 	unsigned int g;
6127 	uint_t hval = 0;
6128 
6129 	while (*p) {
6130 		hval = (hval << 4) + *p++;
6131 		if ((g = (hval & 0xf0000000)) != 0)
6132 			hval ^= g >> 24;
6133 		hval &= ~g;
6134 	}
6135 	return (hval);
6136 }
6137 
6138 static dtrace_hash_t *
6139 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6140 {
6141 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6142 
6143 	hash->dth_stroffs = stroffs;
6144 	hash->dth_nextoffs = nextoffs;
6145 	hash->dth_prevoffs = prevoffs;
6146 
6147 	hash->dth_size = 1;
6148 	hash->dth_mask = hash->dth_size - 1;
6149 
6150 	hash->dth_tab = kmem_zalloc(hash->dth_size *
6151 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6152 
6153 	return (hash);
6154 }
6155 
6156 static void
6157 dtrace_hash_destroy(dtrace_hash_t *hash)
6158 {
6159 #ifdef DEBUG
6160 	int i;
6161 
6162 	for (i = 0; i < hash->dth_size; i++)
6163 		ASSERT(hash->dth_tab[i] == NULL);
6164 #endif
6165 
6166 	kmem_free(hash->dth_tab,
6167 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
6168 	kmem_free(hash, sizeof (dtrace_hash_t));
6169 }
6170 
6171 static void
6172 dtrace_hash_resize(dtrace_hash_t *hash)
6173 {
6174 	int size = hash->dth_size, i, ndx;
6175 	int new_size = hash->dth_size << 1;
6176 	int new_mask = new_size - 1;
6177 	dtrace_hashbucket_t **new_tab, *bucket, *next;
6178 
6179 	ASSERT((new_size & new_mask) == 0);
6180 
6181 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6182 
6183 	for (i = 0; i < size; i++) {
6184 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6185 			dtrace_probe_t *probe = bucket->dthb_chain;
6186 
6187 			ASSERT(probe != NULL);
6188 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6189 
6190 			next = bucket->dthb_next;
6191 			bucket->dthb_next = new_tab[ndx];
6192 			new_tab[ndx] = bucket;
6193 		}
6194 	}
6195 
6196 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6197 	hash->dth_tab = new_tab;
6198 	hash->dth_size = new_size;
6199 	hash->dth_mask = new_mask;
6200 }
6201 
6202 static void
6203 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6204 {
6205 	int hashval = DTRACE_HASHSTR(hash, new);
6206 	int ndx = hashval & hash->dth_mask;
6207 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6208 	dtrace_probe_t **nextp, **prevp;
6209 
6210 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6211 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6212 			goto add;
6213 	}
6214 
6215 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6216 		dtrace_hash_resize(hash);
6217 		dtrace_hash_add(hash, new);
6218 		return;
6219 	}
6220 
6221 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6222 	bucket->dthb_next = hash->dth_tab[ndx];
6223 	hash->dth_tab[ndx] = bucket;
6224 	hash->dth_nbuckets++;
6225 
6226 add:
6227 	nextp = DTRACE_HASHNEXT(hash, new);
6228 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6229 	*nextp = bucket->dthb_chain;
6230 
6231 	if (bucket->dthb_chain != NULL) {
6232 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6233 		ASSERT(*prevp == NULL);
6234 		*prevp = new;
6235 	}
6236 
6237 	bucket->dthb_chain = new;
6238 	bucket->dthb_len++;
6239 }
6240 
6241 static dtrace_probe_t *
6242 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6243 {
6244 	int hashval = DTRACE_HASHSTR(hash, template);
6245 	int ndx = hashval & hash->dth_mask;
6246 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6247 
6248 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6249 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6250 			return (bucket->dthb_chain);
6251 	}
6252 
6253 	return (NULL);
6254 }
6255 
6256 static int
6257 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6258 {
6259 	int hashval = DTRACE_HASHSTR(hash, template);
6260 	int ndx = hashval & hash->dth_mask;
6261 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6262 
6263 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6264 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6265 			return (bucket->dthb_len);
6266 	}
6267 
6268 	return (NULL);
6269 }
6270 
6271 static void
6272 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6273 {
6274 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6275 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6276 
6277 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6278 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6279 
6280 	/*
6281 	 * Find the bucket that we're removing this probe from.
6282 	 */
6283 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6284 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6285 			break;
6286 	}
6287 
6288 	ASSERT(bucket != NULL);
6289 
6290 	if (*prevp == NULL) {
6291 		if (*nextp == NULL) {
6292 			/*
6293 			 * The removed probe was the only probe on this
6294 			 * bucket; we need to remove the bucket.
6295 			 */
6296 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6297 
6298 			ASSERT(bucket->dthb_chain == probe);
6299 			ASSERT(b != NULL);
6300 
6301 			if (b == bucket) {
6302 				hash->dth_tab[ndx] = bucket->dthb_next;
6303 			} else {
6304 				while (b->dthb_next != bucket)
6305 					b = b->dthb_next;
6306 				b->dthb_next = bucket->dthb_next;
6307 			}
6308 
6309 			ASSERT(hash->dth_nbuckets > 0);
6310 			hash->dth_nbuckets--;
6311 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
6312 			return;
6313 		}
6314 
6315 		bucket->dthb_chain = *nextp;
6316 	} else {
6317 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
6318 	}
6319 
6320 	if (*nextp != NULL)
6321 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
6322 }
6323 
6324 /*
6325  * DTrace Utility Functions
6326  *
6327  * These are random utility functions that are _not_ called from probe context.
6328  */
6329 static int
6330 dtrace_badattr(const dtrace_attribute_t *a)
6331 {
6332 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
6333 	    a->dtat_data > DTRACE_STABILITY_MAX ||
6334 	    a->dtat_class > DTRACE_CLASS_MAX);
6335 }
6336 
6337 /*
6338  * Return a duplicate copy of a string.  If the specified string is NULL,
6339  * this function returns a zero-length string.
6340  */
6341 static char *
6342 dtrace_strdup(const char *str)
6343 {
6344 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
6345 
6346 	if (str != NULL)
6347 		(void) strcpy(new, str);
6348 
6349 	return (new);
6350 }
6351 
6352 #define	DTRACE_ISALPHA(c)	\
6353 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
6354 
6355 static int
6356 dtrace_badname(const char *s)
6357 {
6358 	char c;
6359 
6360 	if (s == NULL || (c = *s++) == '\0')
6361 		return (0);
6362 
6363 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
6364 		return (1);
6365 
6366 	while ((c = *s++) != '\0') {
6367 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
6368 		    c != '-' && c != '_' && c != '.' && c != '`')
6369 			return (1);
6370 	}
6371 
6372 	return (0);
6373 }
6374 
6375 static void
6376 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
6377 {
6378 	uint32_t priv;
6379 
6380 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
6381 		/*
6382 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
6383 		 */
6384 		priv = DTRACE_PRIV_ALL;
6385 	} else {
6386 		*uidp = crgetuid(cr);
6387 		*zoneidp = crgetzoneid(cr);
6388 
6389 		priv = 0;
6390 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
6391 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
6392 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
6393 			priv |= DTRACE_PRIV_USER;
6394 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
6395 			priv |= DTRACE_PRIV_PROC;
6396 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
6397 			priv |= DTRACE_PRIV_OWNER;
6398 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
6399 			priv |= DTRACE_PRIV_ZONEOWNER;
6400 	}
6401 
6402 	*privp = priv;
6403 }
6404 
6405 #ifdef DTRACE_ERRDEBUG
6406 static void
6407 dtrace_errdebug(const char *str)
6408 {
6409 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
6410 	int occupied = 0;
6411 
6412 	mutex_enter(&dtrace_errlock);
6413 	dtrace_errlast = str;
6414 	dtrace_errthread = curthread;
6415 
6416 	while (occupied++ < DTRACE_ERRHASHSZ) {
6417 		if (dtrace_errhash[hval].dter_msg == str) {
6418 			dtrace_errhash[hval].dter_count++;
6419 			goto out;
6420 		}
6421 
6422 		if (dtrace_errhash[hval].dter_msg != NULL) {
6423 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
6424 			continue;
6425 		}
6426 
6427 		dtrace_errhash[hval].dter_msg = str;
6428 		dtrace_errhash[hval].dter_count = 1;
6429 		goto out;
6430 	}
6431 
6432 	panic("dtrace: undersized error hash");
6433 out:
6434 	mutex_exit(&dtrace_errlock);
6435 }
6436 #endif
6437 
6438 /*
6439  * DTrace Matching Functions
6440  *
6441  * These functions are used to match groups of probes, given some elements of
6442  * a probe tuple, or some globbed expressions for elements of a probe tuple.
6443  */
6444 static int
6445 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
6446     zoneid_t zoneid)
6447 {
6448 	if (priv != DTRACE_PRIV_ALL) {
6449 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
6450 		uint32_t match = priv & ppriv;
6451 
6452 		/*
6453 		 * No PRIV_DTRACE_* privileges...
6454 		 */
6455 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
6456 		    DTRACE_PRIV_KERNEL)) == 0)
6457 			return (0);
6458 
6459 		/*
6460 		 * No matching bits, but there were bits to match...
6461 		 */
6462 		if (match == 0 && ppriv != 0)
6463 			return (0);
6464 
6465 		/*
6466 		 * Need to have permissions to the process, but don't...
6467 		 */
6468 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
6469 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
6470 			return (0);
6471 		}
6472 
6473 		/*
6474 		 * Need to be in the same zone unless we possess the
6475 		 * privilege to examine all zones.
6476 		 */
6477 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
6478 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
6479 			return (0);
6480 		}
6481 	}
6482 
6483 	return (1);
6484 }
6485 
6486 /*
6487  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
6488  * consists of input pattern strings and an ops-vector to evaluate them.
6489  * This function returns >0 for match, 0 for no match, and <0 for error.
6490  */
6491 static int
6492 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
6493     uint32_t priv, uid_t uid, zoneid_t zoneid)
6494 {
6495 	dtrace_provider_t *pvp = prp->dtpr_provider;
6496 	int rv;
6497 
6498 	if (pvp->dtpv_defunct)
6499 		return (0);
6500 
6501 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
6502 		return (rv);
6503 
6504 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
6505 		return (rv);
6506 
6507 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
6508 		return (rv);
6509 
6510 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
6511 		return (rv);
6512 
6513 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
6514 		return (0);
6515 
6516 	return (rv);
6517 }
6518 
6519 /*
6520  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
6521  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
6522  * libc's version, the kernel version only applies to 8-bit ASCII strings.
6523  * In addition, all of the recursion cases except for '*' matching have been
6524  * unwound.  For '*', we still implement recursive evaluation, but a depth
6525  * counter is maintained and matching is aborted if we recurse too deep.
6526  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
6527  */
6528 static int
6529 dtrace_match_glob(const char *s, const char *p, int depth)
6530 {
6531 	const char *olds;
6532 	char s1, c;
6533 	int gs;
6534 
6535 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
6536 		return (-1);
6537 
6538 	if (s == NULL)
6539 		s = ""; /* treat NULL as empty string */
6540 
6541 top:
6542 	olds = s;
6543 	s1 = *s++;
6544 
6545 	if (p == NULL)
6546 		return (0);
6547 
6548 	if ((c = *p++) == '\0')
6549 		return (s1 == '\0');
6550 
6551 	switch (c) {
6552 	case '[': {
6553 		int ok = 0, notflag = 0;
6554 		char lc = '\0';
6555 
6556 		if (s1 == '\0')
6557 			return (0);
6558 
6559 		if (*p == '!') {
6560 			notflag = 1;
6561 			p++;
6562 		}
6563 
6564 		if ((c = *p++) == '\0')
6565 			return (0);
6566 
6567 		do {
6568 			if (c == '-' && lc != '\0' && *p != ']') {
6569 				if ((c = *p++) == '\0')
6570 					return (0);
6571 				if (c == '\\' && (c = *p++) == '\0')
6572 					return (0);
6573 
6574 				if (notflag) {
6575 					if (s1 < lc || s1 > c)
6576 						ok++;
6577 					else
6578 						return (0);
6579 				} else if (lc <= s1 && s1 <= c)
6580 					ok++;
6581 
6582 			} else if (c == '\\' && (c = *p++) == '\0')
6583 				return (0);
6584 
6585 			lc = c; /* save left-hand 'c' for next iteration */
6586 
6587 			if (notflag) {
6588 				if (s1 != c)
6589 					ok++;
6590 				else
6591 					return (0);
6592 			} else if (s1 == c)
6593 				ok++;
6594 
6595 			if ((c = *p++) == '\0')
6596 				return (0);
6597 
6598 		} while (c != ']');
6599 
6600 		if (ok)
6601 			goto top;
6602 
6603 		return (0);
6604 	}
6605 
6606 	case '\\':
6607 		if ((c = *p++) == '\0')
6608 			return (0);
6609 		/*FALLTHRU*/
6610 
6611 	default:
6612 		if (c != s1)
6613 			return (0);
6614 		/*FALLTHRU*/
6615 
6616 	case '?':
6617 		if (s1 != '\0')
6618 			goto top;
6619 		return (0);
6620 
6621 	case '*':
6622 		while (*p == '*')
6623 			p++; /* consecutive *'s are identical to a single one */
6624 
6625 		if (*p == '\0')
6626 			return (1);
6627 
6628 		for (s = olds; *s != '\0'; s++) {
6629 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
6630 				return (gs);
6631 		}
6632 
6633 		return (0);
6634 	}
6635 }
6636 
6637 /*ARGSUSED*/
6638 static int
6639 dtrace_match_string(const char *s, const char *p, int depth)
6640 {
6641 	return (s != NULL && strcmp(s, p) == 0);
6642 }
6643 
6644 /*ARGSUSED*/
6645 static int
6646 dtrace_match_nul(const char *s, const char *p, int depth)
6647 {
6648 	return (1); /* always match the empty pattern */
6649 }
6650 
6651 /*ARGSUSED*/
6652 static int
6653 dtrace_match_nonzero(const char *s, const char *p, int depth)
6654 {
6655 	return (s != NULL && s[0] != '\0');
6656 }
6657 
6658 static int
6659 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
6660     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
6661 {
6662 	dtrace_probe_t template, *probe;
6663 	dtrace_hash_t *hash = NULL;
6664 	int len, rc, best = INT_MAX, nmatched = 0;
6665 	dtrace_id_t i;
6666 
6667 	ASSERT(MUTEX_HELD(&dtrace_lock));
6668 
6669 	/*
6670 	 * If the probe ID is specified in the key, just lookup by ID and
6671 	 * invoke the match callback once if a matching probe is found.
6672 	 */
6673 	if (pkp->dtpk_id != DTRACE_IDNONE) {
6674 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
6675 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
6676 			if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
6677 				return (DTRACE_MATCH_FAIL);
6678 			nmatched++;
6679 		}
6680 		return (nmatched);
6681 	}
6682 
6683 	template.dtpr_mod = (char *)pkp->dtpk_mod;
6684 	template.dtpr_func = (char *)pkp->dtpk_func;
6685 	template.dtpr_name = (char *)pkp->dtpk_name;
6686 
6687 	/*
6688 	 * We want to find the most distinct of the module name, function
6689 	 * name, and name.  So for each one that is not a glob pattern or
6690 	 * empty string, we perform a lookup in the corresponding hash and
6691 	 * use the hash table with the fewest collisions to do our search.
6692 	 */
6693 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
6694 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
6695 		best = len;
6696 		hash = dtrace_bymod;
6697 	}
6698 
6699 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
6700 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
6701 		best = len;
6702 		hash = dtrace_byfunc;
6703 	}
6704 
6705 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
6706 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
6707 		best = len;
6708 		hash = dtrace_byname;
6709 	}
6710 
6711 	/*
6712 	 * If we did not select a hash table, iterate over every probe and
6713 	 * invoke our callback for each one that matches our input probe key.
6714 	 */
6715 	if (hash == NULL) {
6716 		for (i = 0; i < dtrace_nprobes; i++) {
6717 			if ((probe = dtrace_probes[i]) == NULL ||
6718 			    dtrace_match_probe(probe, pkp, priv, uid,
6719 			    zoneid) <= 0)
6720 				continue;
6721 
6722 			nmatched++;
6723 
6724 			if ((rc = (*matched)(probe, arg)) !=
6725 			    DTRACE_MATCH_NEXT) {
6726 				if (rc == DTRACE_MATCH_FAIL)
6727 					return (DTRACE_MATCH_FAIL);
6728 				break;
6729 			}
6730 		}
6731 
6732 		return (nmatched);
6733 	}
6734 
6735 	/*
6736 	 * If we selected a hash table, iterate over each probe of the same key
6737 	 * name and invoke the callback for every probe that matches the other
6738 	 * attributes of our input probe key.
6739 	 */
6740 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
6741 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
6742 
6743 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
6744 			continue;
6745 
6746 		nmatched++;
6747 
6748 		if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
6749 			if (rc == DTRACE_MATCH_FAIL)
6750 				return (DTRACE_MATCH_FAIL);
6751 			break;
6752 		}
6753 	}
6754 
6755 	return (nmatched);
6756 }
6757 
6758 /*
6759  * Return the function pointer dtrace_probecmp() should use to compare the
6760  * specified pattern with a string.  For NULL or empty patterns, we select
6761  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
6762  * For non-empty non-glob strings, we use dtrace_match_string().
6763  */
6764 static dtrace_probekey_f *
6765 dtrace_probekey_func(const char *p)
6766 {
6767 	char c;
6768 
6769 	if (p == NULL || *p == '\0')
6770 		return (&dtrace_match_nul);
6771 
6772 	while ((c = *p++) != '\0') {
6773 		if (c == '[' || c == '?' || c == '*' || c == '\\')
6774 			return (&dtrace_match_glob);
6775 	}
6776 
6777 	return (&dtrace_match_string);
6778 }
6779 
6780 /*
6781  * Build a probe comparison key for use with dtrace_match_probe() from the
6782  * given probe description.  By convention, a null key only matches anchored
6783  * probes: if each field is the empty string, reset dtpk_fmatch to
6784  * dtrace_match_nonzero().
6785  */
6786 static void
6787 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
6788 {
6789 	pkp->dtpk_prov = pdp->dtpd_provider;
6790 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
6791 
6792 	pkp->dtpk_mod = pdp->dtpd_mod;
6793 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
6794 
6795 	pkp->dtpk_func = pdp->dtpd_func;
6796 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
6797 
6798 	pkp->dtpk_name = pdp->dtpd_name;
6799 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
6800 
6801 	pkp->dtpk_id = pdp->dtpd_id;
6802 
6803 	if (pkp->dtpk_id == DTRACE_IDNONE &&
6804 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
6805 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
6806 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
6807 	    pkp->dtpk_nmatch == &dtrace_match_nul)
6808 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
6809 }
6810 
6811 /*
6812  * DTrace Provider-to-Framework API Functions
6813  *
6814  * These functions implement much of the Provider-to-Framework API, as
6815  * described in <sys/dtrace.h>.  The parts of the API not in this section are
6816  * the functions in the API for probe management (found below), and
6817  * dtrace_probe() itself (found above).
6818  */
6819 
6820 /*
6821  * Register the calling provider with the DTrace framework.  This should
6822  * generally be called by DTrace providers in their attach(9E) entry point.
6823  */
6824 int
6825 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
6826     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
6827 {
6828 	dtrace_provider_t *provider;
6829 
6830 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
6831 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6832 		    "arguments", name ? name : "<NULL>");
6833 		return (EINVAL);
6834 	}
6835 
6836 	if (name[0] == '\0' || dtrace_badname(name)) {
6837 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6838 		    "provider name", name);
6839 		return (EINVAL);
6840 	}
6841 
6842 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
6843 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
6844 	    pops->dtps_destroy == NULL ||
6845 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
6846 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6847 		    "provider ops", name);
6848 		return (EINVAL);
6849 	}
6850 
6851 	if (dtrace_badattr(&pap->dtpa_provider) ||
6852 	    dtrace_badattr(&pap->dtpa_mod) ||
6853 	    dtrace_badattr(&pap->dtpa_func) ||
6854 	    dtrace_badattr(&pap->dtpa_name) ||
6855 	    dtrace_badattr(&pap->dtpa_args)) {
6856 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6857 		    "provider attributes", name);
6858 		return (EINVAL);
6859 	}
6860 
6861 	if (priv & ~DTRACE_PRIV_ALL) {
6862 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6863 		    "privilege attributes", name);
6864 		return (EINVAL);
6865 	}
6866 
6867 	if ((priv & DTRACE_PRIV_KERNEL) &&
6868 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
6869 	    pops->dtps_usermode == NULL) {
6870 		cmn_err(CE_WARN, "failed to register provider '%s': need "
6871 		    "dtps_usermode() op for given privilege attributes", name);
6872 		return (EINVAL);
6873 	}
6874 
6875 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
6876 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
6877 	(void) strcpy(provider->dtpv_name, name);
6878 
6879 	provider->dtpv_attr = *pap;
6880 	provider->dtpv_priv.dtpp_flags = priv;
6881 	if (cr != NULL) {
6882 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
6883 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
6884 	}
6885 	provider->dtpv_pops = *pops;
6886 
6887 	if (pops->dtps_provide == NULL) {
6888 		ASSERT(pops->dtps_provide_module != NULL);
6889 		provider->dtpv_pops.dtps_provide =
6890 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
6891 	}
6892 
6893 	if (pops->dtps_provide_module == NULL) {
6894 		ASSERT(pops->dtps_provide != NULL);
6895 		provider->dtpv_pops.dtps_provide_module =
6896 		    (void (*)(void *, struct modctl *))dtrace_nullop;
6897 	}
6898 
6899 	if (pops->dtps_suspend == NULL) {
6900 		ASSERT(pops->dtps_resume == NULL);
6901 		provider->dtpv_pops.dtps_suspend =
6902 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6903 		provider->dtpv_pops.dtps_resume =
6904 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6905 	}
6906 
6907 	provider->dtpv_arg = arg;
6908 	*idp = (dtrace_provider_id_t)provider;
6909 
6910 	if (pops == &dtrace_provider_ops) {
6911 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6912 		ASSERT(MUTEX_HELD(&dtrace_lock));
6913 		ASSERT(dtrace_anon.dta_enabling == NULL);
6914 
6915 		/*
6916 		 * We make sure that the DTrace provider is at the head of
6917 		 * the provider chain.
6918 		 */
6919 		provider->dtpv_next = dtrace_provider;
6920 		dtrace_provider = provider;
6921 		return (0);
6922 	}
6923 
6924 	mutex_enter(&dtrace_provider_lock);
6925 	mutex_enter(&dtrace_lock);
6926 
6927 	/*
6928 	 * If there is at least one provider registered, we'll add this
6929 	 * provider after the first provider.
6930 	 */
6931 	if (dtrace_provider != NULL) {
6932 		provider->dtpv_next = dtrace_provider->dtpv_next;
6933 		dtrace_provider->dtpv_next = provider;
6934 	} else {
6935 		dtrace_provider = provider;
6936 	}
6937 
6938 	if (dtrace_retained != NULL) {
6939 		dtrace_enabling_provide(provider);
6940 
6941 		/*
6942 		 * Now we need to call dtrace_enabling_matchall() -- which
6943 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
6944 		 * to drop all of our locks before calling into it...
6945 		 */
6946 		mutex_exit(&dtrace_lock);
6947 		mutex_exit(&dtrace_provider_lock);
6948 		dtrace_enabling_matchall();
6949 
6950 		return (0);
6951 	}
6952 
6953 	mutex_exit(&dtrace_lock);
6954 	mutex_exit(&dtrace_provider_lock);
6955 
6956 	return (0);
6957 }
6958 
6959 /*
6960  * Unregister the specified provider from the DTrace framework.  This should
6961  * generally be called by DTrace providers in their detach(9E) entry point.
6962  */
6963 int
6964 dtrace_unregister(dtrace_provider_id_t id)
6965 {
6966 	dtrace_provider_t *old = (dtrace_provider_t *)id;
6967 	dtrace_provider_t *prev = NULL;
6968 	int i, self = 0;
6969 	dtrace_probe_t *probe, *first = NULL;
6970 
6971 	if (old->dtpv_pops.dtps_enable ==
6972 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
6973 		/*
6974 		 * If DTrace itself is the provider, we're called with locks
6975 		 * already held.
6976 		 */
6977 		ASSERT(old == dtrace_provider);
6978 		ASSERT(dtrace_devi != NULL);
6979 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6980 		ASSERT(MUTEX_HELD(&dtrace_lock));
6981 		self = 1;
6982 
6983 		if (dtrace_provider->dtpv_next != NULL) {
6984 			/*
6985 			 * There's another provider here; return failure.
6986 			 */
6987 			return (EBUSY);
6988 		}
6989 	} else {
6990 		mutex_enter(&dtrace_provider_lock);
6991 		mutex_enter(&mod_lock);
6992 		mutex_enter(&dtrace_lock);
6993 	}
6994 
6995 	/*
6996 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
6997 	 * probes, we refuse to let providers slither away, unless this
6998 	 * provider has already been explicitly invalidated.
6999 	 */
7000 	if (!old->dtpv_defunct &&
7001 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
7002 	    dtrace_anon.dta_state->dts_necbs > 0))) {
7003 		if (!self) {
7004 			mutex_exit(&dtrace_lock);
7005 			mutex_exit(&mod_lock);
7006 			mutex_exit(&dtrace_provider_lock);
7007 		}
7008 		return (EBUSY);
7009 	}
7010 
7011 	/*
7012 	 * Attempt to destroy the probes associated with this provider.
7013 	 */
7014 	for (i = 0; i < dtrace_nprobes; i++) {
7015 		if ((probe = dtrace_probes[i]) == NULL)
7016 			continue;
7017 
7018 		if (probe->dtpr_provider != old)
7019 			continue;
7020 
7021 		if (probe->dtpr_ecb == NULL)
7022 			continue;
7023 
7024 		/*
7025 		 * We have at least one ECB; we can't remove this provider.
7026 		 */
7027 		if (!self) {
7028 			mutex_exit(&dtrace_lock);
7029 			mutex_exit(&mod_lock);
7030 			mutex_exit(&dtrace_provider_lock);
7031 		}
7032 		return (EBUSY);
7033 	}
7034 
7035 	/*
7036 	 * All of the probes for this provider are disabled; we can safely
7037 	 * remove all of them from their hash chains and from the probe array.
7038 	 */
7039 	for (i = 0; i < dtrace_nprobes; i++) {
7040 		if ((probe = dtrace_probes[i]) == NULL)
7041 			continue;
7042 
7043 		if (probe->dtpr_provider != old)
7044 			continue;
7045 
7046 		dtrace_probes[i] = NULL;
7047 
7048 		dtrace_hash_remove(dtrace_bymod, probe);
7049 		dtrace_hash_remove(dtrace_byfunc, probe);
7050 		dtrace_hash_remove(dtrace_byname, probe);
7051 
7052 		if (first == NULL) {
7053 			first = probe;
7054 			probe->dtpr_nextmod = NULL;
7055 		} else {
7056 			probe->dtpr_nextmod = first;
7057 			first = probe;
7058 		}
7059 	}
7060 
7061 	/*
7062 	 * The provider's probes have been removed from the hash chains and
7063 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
7064 	 * everyone has cleared out from any probe array processing.
7065 	 */
7066 	dtrace_sync();
7067 
7068 	for (probe = first; probe != NULL; probe = first) {
7069 		first = probe->dtpr_nextmod;
7070 
7071 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
7072 		    probe->dtpr_arg);
7073 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7074 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7075 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7076 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
7077 		kmem_free(probe, sizeof (dtrace_probe_t));
7078 	}
7079 
7080 	if ((prev = dtrace_provider) == old) {
7081 		ASSERT(self || dtrace_devi == NULL);
7082 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
7083 		dtrace_provider = old->dtpv_next;
7084 	} else {
7085 		while (prev != NULL && prev->dtpv_next != old)
7086 			prev = prev->dtpv_next;
7087 
7088 		if (prev == NULL) {
7089 			panic("attempt to unregister non-existent "
7090 			    "dtrace provider %p\n", (void *)id);
7091 		}
7092 
7093 		prev->dtpv_next = old->dtpv_next;
7094 	}
7095 
7096 	if (!self) {
7097 		mutex_exit(&dtrace_lock);
7098 		mutex_exit(&mod_lock);
7099 		mutex_exit(&dtrace_provider_lock);
7100 	}
7101 
7102 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
7103 	kmem_free(old, sizeof (dtrace_provider_t));
7104 
7105 	return (0);
7106 }
7107 
7108 /*
7109  * Invalidate the specified provider.  All subsequent probe lookups for the
7110  * specified provider will fail, but its probes will not be removed.
7111  */
7112 void
7113 dtrace_invalidate(dtrace_provider_id_t id)
7114 {
7115 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
7116 
7117 	ASSERT(pvp->dtpv_pops.dtps_enable !=
7118 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7119 
7120 	mutex_enter(&dtrace_provider_lock);
7121 	mutex_enter(&dtrace_lock);
7122 
7123 	pvp->dtpv_defunct = 1;
7124 
7125 	mutex_exit(&dtrace_lock);
7126 	mutex_exit(&dtrace_provider_lock);
7127 }
7128 
7129 /*
7130  * Indicate whether or not DTrace has attached.
7131  */
7132 int
7133 dtrace_attached(void)
7134 {
7135 	/*
7136 	 * dtrace_provider will be non-NULL iff the DTrace driver has
7137 	 * attached.  (It's non-NULL because DTrace is always itself a
7138 	 * provider.)
7139 	 */
7140 	return (dtrace_provider != NULL);
7141 }
7142 
7143 /*
7144  * Remove all the unenabled probes for the given provider.  This function is
7145  * not unlike dtrace_unregister(), except that it doesn't remove the provider
7146  * -- just as many of its associated probes as it can.
7147  */
7148 int
7149 dtrace_condense(dtrace_provider_id_t id)
7150 {
7151 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
7152 	int i;
7153 	dtrace_probe_t *probe;
7154 
7155 	/*
7156 	 * Make sure this isn't the dtrace provider itself.
7157 	 */
7158 	ASSERT(prov->dtpv_pops.dtps_enable !=
7159 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
7160 
7161 	mutex_enter(&dtrace_provider_lock);
7162 	mutex_enter(&dtrace_lock);
7163 
7164 	/*
7165 	 * Attempt to destroy the probes associated with this provider.
7166 	 */
7167 	for (i = 0; i < dtrace_nprobes; i++) {
7168 		if ((probe = dtrace_probes[i]) == NULL)
7169 			continue;
7170 
7171 		if (probe->dtpr_provider != prov)
7172 			continue;
7173 
7174 		if (probe->dtpr_ecb != NULL)
7175 			continue;
7176 
7177 		dtrace_probes[i] = NULL;
7178 
7179 		dtrace_hash_remove(dtrace_bymod, probe);
7180 		dtrace_hash_remove(dtrace_byfunc, probe);
7181 		dtrace_hash_remove(dtrace_byname, probe);
7182 
7183 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7184 		    probe->dtpr_arg);
7185 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7186 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7187 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7188 		kmem_free(probe, sizeof (dtrace_probe_t));
7189 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7190 	}
7191 
7192 	mutex_exit(&dtrace_lock);
7193 	mutex_exit(&dtrace_provider_lock);
7194 
7195 	return (0);
7196 }
7197 
7198 /*
7199  * DTrace Probe Management Functions
7200  *
7201  * The functions in this section perform the DTrace probe management,
7202  * including functions to create probes, look-up probes, and call into the
7203  * providers to request that probes be provided.  Some of these functions are
7204  * in the Provider-to-Framework API; these functions can be identified by the
7205  * fact that they are not declared "static".
7206  */
7207 
7208 /*
7209  * Create a probe with the specified module name, function name, and name.
7210  */
7211 dtrace_id_t
7212 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7213     const char *func, const char *name, int aframes, void *arg)
7214 {
7215 	dtrace_probe_t *probe, **probes;
7216 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7217 	dtrace_id_t id;
7218 
7219 	if (provider == dtrace_provider) {
7220 		ASSERT(MUTEX_HELD(&dtrace_lock));
7221 	} else {
7222 		mutex_enter(&dtrace_lock);
7223 	}
7224 
7225 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7226 	    VM_BESTFIT | VM_SLEEP);
7227 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
7228 
7229 	probe->dtpr_id = id;
7230 	probe->dtpr_gen = dtrace_probegen++;
7231 	probe->dtpr_mod = dtrace_strdup(mod);
7232 	probe->dtpr_func = dtrace_strdup(func);
7233 	probe->dtpr_name = dtrace_strdup(name);
7234 	probe->dtpr_arg = arg;
7235 	probe->dtpr_aframes = aframes;
7236 	probe->dtpr_provider = provider;
7237 
7238 	dtrace_hash_add(dtrace_bymod, probe);
7239 	dtrace_hash_add(dtrace_byfunc, probe);
7240 	dtrace_hash_add(dtrace_byname, probe);
7241 
7242 	if (id - 1 >= dtrace_nprobes) {
7243 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7244 		size_t nsize = osize << 1;
7245 
7246 		if (nsize == 0) {
7247 			ASSERT(osize == 0);
7248 			ASSERT(dtrace_probes == NULL);
7249 			nsize = sizeof (dtrace_probe_t *);
7250 		}
7251 
7252 		probes = kmem_zalloc(nsize, KM_SLEEP);
7253 
7254 		if (dtrace_probes == NULL) {
7255 			ASSERT(osize == 0);
7256 			dtrace_probes = probes;
7257 			dtrace_nprobes = 1;
7258 		} else {
7259 			dtrace_probe_t **oprobes = dtrace_probes;
7260 
7261 			bcopy(oprobes, probes, osize);
7262 			dtrace_membar_producer();
7263 			dtrace_probes = probes;
7264 
7265 			dtrace_sync();
7266 
7267 			/*
7268 			 * All CPUs are now seeing the new probes array; we can
7269 			 * safely free the old array.
7270 			 */
7271 			kmem_free(oprobes, osize);
7272 			dtrace_nprobes <<= 1;
7273 		}
7274 
7275 		ASSERT(id - 1 < dtrace_nprobes);
7276 	}
7277 
7278 	ASSERT(dtrace_probes[id - 1] == NULL);
7279 	dtrace_probes[id - 1] = probe;
7280 
7281 	if (provider != dtrace_provider)
7282 		mutex_exit(&dtrace_lock);
7283 
7284 	return (id);
7285 }
7286 
7287 static dtrace_probe_t *
7288 dtrace_probe_lookup_id(dtrace_id_t id)
7289 {
7290 	ASSERT(MUTEX_HELD(&dtrace_lock));
7291 
7292 	if (id == 0 || id > dtrace_nprobes)
7293 		return (NULL);
7294 
7295 	return (dtrace_probes[id - 1]);
7296 }
7297 
7298 static int
7299 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
7300 {
7301 	*((dtrace_id_t *)arg) = probe->dtpr_id;
7302 
7303 	return (DTRACE_MATCH_DONE);
7304 }
7305 
7306 /*
7307  * Look up a probe based on provider and one or more of module name, function
7308  * name and probe name.
7309  */
7310 dtrace_id_t
7311 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
7312     const char *func, const char *name)
7313 {
7314 	dtrace_probekey_t pkey;
7315 	dtrace_id_t id;
7316 	int match;
7317 
7318 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
7319 	pkey.dtpk_pmatch = &dtrace_match_string;
7320 	pkey.dtpk_mod = mod;
7321 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
7322 	pkey.dtpk_func = func;
7323 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
7324 	pkey.dtpk_name = name;
7325 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
7326 	pkey.dtpk_id = DTRACE_IDNONE;
7327 
7328 	mutex_enter(&dtrace_lock);
7329 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
7330 	    dtrace_probe_lookup_match, &id);
7331 	mutex_exit(&dtrace_lock);
7332 
7333 	ASSERT(match == 1 || match == 0);
7334 	return (match ? id : 0);
7335 }
7336 
7337 /*
7338  * Returns the probe argument associated with the specified probe.
7339  */
7340 void *
7341 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
7342 {
7343 	dtrace_probe_t *probe;
7344 	void *rval = NULL;
7345 
7346 	mutex_enter(&dtrace_lock);
7347 
7348 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
7349 	    probe->dtpr_provider == (dtrace_provider_t *)id)
7350 		rval = probe->dtpr_arg;
7351 
7352 	mutex_exit(&dtrace_lock);
7353 
7354 	return (rval);
7355 }
7356 
7357 /*
7358  * Copy a probe into a probe description.
7359  */
7360 static void
7361 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
7362 {
7363 	bzero(pdp, sizeof (dtrace_probedesc_t));
7364 	pdp->dtpd_id = prp->dtpr_id;
7365 
7366 	(void) strncpy(pdp->dtpd_provider,
7367 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
7368 
7369 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
7370 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
7371 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
7372 }
7373 
7374 /*
7375  * Called to indicate that a probe -- or probes -- should be provided by a
7376  * specfied provider.  If the specified description is NULL, the provider will
7377  * be told to provide all of its probes.  (This is done whenever a new
7378  * consumer comes along, or whenever a retained enabling is to be matched.) If
7379  * the specified description is non-NULL, the provider is given the
7380  * opportunity to dynamically provide the specified probe, allowing providers
7381  * to support the creation of probes on-the-fly.  (So-called _autocreated_
7382  * probes.)  If the provider is NULL, the operations will be applied to all
7383  * providers; if the provider is non-NULL the operations will only be applied
7384  * to the specified provider.  The dtrace_provider_lock must be held, and the
7385  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
7386  * will need to grab the dtrace_lock when it reenters the framework through
7387  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
7388  */
7389 static void
7390 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
7391 {
7392 	struct modctl *ctl;
7393 	int all = 0;
7394 
7395 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7396 
7397 	if (prv == NULL) {
7398 		all = 1;
7399 		prv = dtrace_provider;
7400 	}
7401 
7402 	do {
7403 		/*
7404 		 * First, call the blanket provide operation.
7405 		 */
7406 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
7407 
7408 		/*
7409 		 * Now call the per-module provide operation.  We will grab
7410 		 * mod_lock to prevent the list from being modified.  Note
7411 		 * that this also prevents the mod_busy bits from changing.
7412 		 * (mod_busy can only be changed with mod_lock held.)
7413 		 */
7414 		mutex_enter(&mod_lock);
7415 
7416 		ctl = &modules;
7417 		do {
7418 			if (ctl->mod_busy || ctl->mod_mp == NULL)
7419 				continue;
7420 
7421 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
7422 
7423 		} while ((ctl = ctl->mod_next) != &modules);
7424 
7425 		mutex_exit(&mod_lock);
7426 	} while (all && (prv = prv->dtpv_next) != NULL);
7427 }
7428 
7429 /*
7430  * Iterate over each probe, and call the Framework-to-Provider API function
7431  * denoted by offs.
7432  */
7433 static void
7434 dtrace_probe_foreach(uintptr_t offs)
7435 {
7436 	dtrace_provider_t *prov;
7437 	void (*func)(void *, dtrace_id_t, void *);
7438 	dtrace_probe_t *probe;
7439 	dtrace_icookie_t cookie;
7440 	int i;
7441 
7442 	/*
7443 	 * We disable interrupts to walk through the probe array.  This is
7444 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
7445 	 * won't see stale data.
7446 	 */
7447 	cookie = dtrace_interrupt_disable();
7448 
7449 	for (i = 0; i < dtrace_nprobes; i++) {
7450 		if ((probe = dtrace_probes[i]) == NULL)
7451 			continue;
7452 
7453 		if (probe->dtpr_ecb == NULL) {
7454 			/*
7455 			 * This probe isn't enabled -- don't call the function.
7456 			 */
7457 			continue;
7458 		}
7459 
7460 		prov = probe->dtpr_provider;
7461 		func = *((void(**)(void *, dtrace_id_t, void *))
7462 		    ((uintptr_t)&prov->dtpv_pops + offs));
7463 
7464 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
7465 	}
7466 
7467 	dtrace_interrupt_enable(cookie);
7468 }
7469 
7470 static int
7471 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
7472 {
7473 	dtrace_probekey_t pkey;
7474 	uint32_t priv;
7475 	uid_t uid;
7476 	zoneid_t zoneid;
7477 
7478 	ASSERT(MUTEX_HELD(&dtrace_lock));
7479 	dtrace_ecb_create_cache = NULL;
7480 
7481 	if (desc == NULL) {
7482 		/*
7483 		 * If we're passed a NULL description, we're being asked to
7484 		 * create an ECB with a NULL probe.
7485 		 */
7486 		(void) dtrace_ecb_create_enable(NULL, enab);
7487 		return (0);
7488 	}
7489 
7490 	dtrace_probekey(desc, &pkey);
7491 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
7492 	    &priv, &uid, &zoneid);
7493 
7494 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
7495 	    enab));
7496 }
7497 
7498 /*
7499  * DTrace Helper Provider Functions
7500  */
7501 static void
7502 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
7503 {
7504 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
7505 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
7506 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
7507 }
7508 
7509 static void
7510 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
7511     const dof_provider_t *dofprov, char *strtab)
7512 {
7513 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
7514 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
7515 	    dofprov->dofpv_provattr);
7516 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
7517 	    dofprov->dofpv_modattr);
7518 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
7519 	    dofprov->dofpv_funcattr);
7520 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
7521 	    dofprov->dofpv_nameattr);
7522 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
7523 	    dofprov->dofpv_argsattr);
7524 }
7525 
7526 static void
7527 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7528 {
7529 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7530 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7531 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
7532 	dof_provider_t *provider;
7533 	dof_probe_t *probe;
7534 	uint32_t *off, *enoff;
7535 	uint8_t *arg;
7536 	char *strtab;
7537 	uint_t i, nprobes;
7538 	dtrace_helper_provdesc_t dhpv;
7539 	dtrace_helper_probedesc_t dhpb;
7540 	dtrace_meta_t *meta = dtrace_meta_pid;
7541 	dtrace_mops_t *mops = &meta->dtm_mops;
7542 	void *parg;
7543 
7544 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7545 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7546 	    provider->dofpv_strtab * dof->dofh_secsize);
7547 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7548 	    provider->dofpv_probes * dof->dofh_secsize);
7549 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7550 	    provider->dofpv_prargs * dof->dofh_secsize);
7551 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7552 	    provider->dofpv_proffs * dof->dofh_secsize);
7553 
7554 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7555 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
7556 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
7557 	enoff = NULL;
7558 
7559 	/*
7560 	 * See dtrace_helper_provider_validate().
7561 	 */
7562 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
7563 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
7564 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7565 		    provider->dofpv_prenoffs * dof->dofh_secsize);
7566 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
7567 	}
7568 
7569 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
7570 
7571 	/*
7572 	 * Create the provider.
7573 	 */
7574 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7575 
7576 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
7577 		return;
7578 
7579 	meta->dtm_count++;
7580 
7581 	/*
7582 	 * Create the probes.
7583 	 */
7584 	for (i = 0; i < nprobes; i++) {
7585 		probe = (dof_probe_t *)(uintptr_t)(daddr +
7586 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
7587 
7588 		dhpb.dthpb_mod = dhp->dofhp_mod;
7589 		dhpb.dthpb_func = strtab + probe->dofpr_func;
7590 		dhpb.dthpb_name = strtab + probe->dofpr_name;
7591 		dhpb.dthpb_base = probe->dofpr_addr;
7592 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
7593 		dhpb.dthpb_noffs = probe->dofpr_noffs;
7594 		if (enoff != NULL) {
7595 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
7596 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
7597 		} else {
7598 			dhpb.dthpb_enoffs = NULL;
7599 			dhpb.dthpb_nenoffs = 0;
7600 		}
7601 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
7602 		dhpb.dthpb_nargc = probe->dofpr_nargc;
7603 		dhpb.dthpb_xargc = probe->dofpr_xargc;
7604 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
7605 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
7606 
7607 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
7608 	}
7609 }
7610 
7611 static void
7612 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
7613 {
7614 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7615 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7616 	int i;
7617 
7618 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7619 
7620 	for (i = 0; i < dof->dofh_secnum; i++) {
7621 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7622 		    dof->dofh_secoff + i * dof->dofh_secsize);
7623 
7624 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7625 			continue;
7626 
7627 		dtrace_helper_provide_one(dhp, sec, pid);
7628 	}
7629 
7630 	/*
7631 	 * We may have just created probes, so we must now rematch against
7632 	 * any retained enablings.  Note that this call will acquire both
7633 	 * cpu_lock and dtrace_lock; the fact that we are holding
7634 	 * dtrace_meta_lock now is what defines the ordering with respect to
7635 	 * these three locks.
7636 	 */
7637 	dtrace_enabling_matchall();
7638 }
7639 
7640 static void
7641 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7642 {
7643 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7644 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7645 	dof_sec_t *str_sec;
7646 	dof_provider_t *provider;
7647 	char *strtab;
7648 	dtrace_helper_provdesc_t dhpv;
7649 	dtrace_meta_t *meta = dtrace_meta_pid;
7650 	dtrace_mops_t *mops = &meta->dtm_mops;
7651 
7652 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7653 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7654 	    provider->dofpv_strtab * dof->dofh_secsize);
7655 
7656 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7657 
7658 	/*
7659 	 * Create the provider.
7660 	 */
7661 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7662 
7663 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
7664 
7665 	meta->dtm_count--;
7666 }
7667 
7668 static void
7669 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
7670 {
7671 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7672 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7673 	int i;
7674 
7675 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7676 
7677 	for (i = 0; i < dof->dofh_secnum; i++) {
7678 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7679 		    dof->dofh_secoff + i * dof->dofh_secsize);
7680 
7681 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7682 			continue;
7683 
7684 		dtrace_helper_provider_remove_one(dhp, sec, pid);
7685 	}
7686 }
7687 
7688 /*
7689  * DTrace Meta Provider-to-Framework API Functions
7690  *
7691  * These functions implement the Meta Provider-to-Framework API, as described
7692  * in <sys/dtrace.h>.
7693  */
7694 int
7695 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
7696     dtrace_meta_provider_id_t *idp)
7697 {
7698 	dtrace_meta_t *meta;
7699 	dtrace_helpers_t *help, *next;
7700 	int i;
7701 
7702 	*idp = DTRACE_METAPROVNONE;
7703 
7704 	/*
7705 	 * We strictly don't need the name, but we hold onto it for
7706 	 * debuggability. All hail error queues!
7707 	 */
7708 	if (name == NULL) {
7709 		cmn_err(CE_WARN, "failed to register meta-provider: "
7710 		    "invalid name");
7711 		return (EINVAL);
7712 	}
7713 
7714 	if (mops == NULL ||
7715 	    mops->dtms_create_probe == NULL ||
7716 	    mops->dtms_provide_pid == NULL ||
7717 	    mops->dtms_remove_pid == NULL) {
7718 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7719 		    "invalid ops", name);
7720 		return (EINVAL);
7721 	}
7722 
7723 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
7724 	meta->dtm_mops = *mops;
7725 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7726 	(void) strcpy(meta->dtm_name, name);
7727 	meta->dtm_arg = arg;
7728 
7729 	mutex_enter(&dtrace_meta_lock);
7730 	mutex_enter(&dtrace_lock);
7731 
7732 	if (dtrace_meta_pid != NULL) {
7733 		mutex_exit(&dtrace_lock);
7734 		mutex_exit(&dtrace_meta_lock);
7735 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7736 		    "user-land meta-provider exists", name);
7737 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
7738 		kmem_free(meta, sizeof (dtrace_meta_t));
7739 		return (EINVAL);
7740 	}
7741 
7742 	dtrace_meta_pid = meta;
7743 	*idp = (dtrace_meta_provider_id_t)meta;
7744 
7745 	/*
7746 	 * If there are providers and probes ready to go, pass them
7747 	 * off to the new meta provider now.
7748 	 */
7749 
7750 	help = dtrace_deferred_pid;
7751 	dtrace_deferred_pid = NULL;
7752 
7753 	mutex_exit(&dtrace_lock);
7754 
7755 	while (help != NULL) {
7756 		for (i = 0; i < help->dthps_nprovs; i++) {
7757 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
7758 			    help->dthps_pid);
7759 		}
7760 
7761 		next = help->dthps_next;
7762 		help->dthps_next = NULL;
7763 		help->dthps_prev = NULL;
7764 		help->dthps_deferred = 0;
7765 		help = next;
7766 	}
7767 
7768 	mutex_exit(&dtrace_meta_lock);
7769 
7770 	return (0);
7771 }
7772 
7773 int
7774 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
7775 {
7776 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
7777 
7778 	mutex_enter(&dtrace_meta_lock);
7779 	mutex_enter(&dtrace_lock);
7780 
7781 	if (old == dtrace_meta_pid) {
7782 		pp = &dtrace_meta_pid;
7783 	} else {
7784 		panic("attempt to unregister non-existent "
7785 		    "dtrace meta-provider %p\n", (void *)old);
7786 	}
7787 
7788 	if (old->dtm_count != 0) {
7789 		mutex_exit(&dtrace_lock);
7790 		mutex_exit(&dtrace_meta_lock);
7791 		return (EBUSY);
7792 	}
7793 
7794 	*pp = NULL;
7795 
7796 	mutex_exit(&dtrace_lock);
7797 	mutex_exit(&dtrace_meta_lock);
7798 
7799 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
7800 	kmem_free(old, sizeof (dtrace_meta_t));
7801 
7802 	return (0);
7803 }
7804 
7805 
7806 /*
7807  * DTrace DIF Object Functions
7808  */
7809 static int
7810 dtrace_difo_err(uint_t pc, const char *format, ...)
7811 {
7812 	if (dtrace_err_verbose) {
7813 		va_list alist;
7814 
7815 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
7816 		va_start(alist, format);
7817 		(void) vuprintf(format, alist);
7818 		va_end(alist);
7819 	}
7820 
7821 #ifdef DTRACE_ERRDEBUG
7822 	dtrace_errdebug(format);
7823 #endif
7824 	return (1);
7825 }
7826 
7827 /*
7828  * Validate a DTrace DIF object by checking the IR instructions.  The following
7829  * rules are currently enforced by dtrace_difo_validate():
7830  *
7831  * 1. Each instruction must have a valid opcode
7832  * 2. Each register, string, variable, or subroutine reference must be valid
7833  * 3. No instruction can modify register %r0 (must be zero)
7834  * 4. All instruction reserved bits must be set to zero
7835  * 5. The last instruction must be a "ret" instruction
7836  * 6. All branch targets must reference a valid instruction _after_ the branch
7837  */
7838 static int
7839 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
7840     cred_t *cr)
7841 {
7842 	int err = 0, i;
7843 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
7844 	int kcheckload;
7845 	uint_t pc;
7846 
7847 	kcheckload = cr == NULL ||
7848 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
7849 
7850 	dp->dtdo_destructive = 0;
7851 
7852 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
7853 		dif_instr_t instr = dp->dtdo_buf[pc];
7854 
7855 		uint_t r1 = DIF_INSTR_R1(instr);
7856 		uint_t r2 = DIF_INSTR_R2(instr);
7857 		uint_t rd = DIF_INSTR_RD(instr);
7858 		uint_t rs = DIF_INSTR_RS(instr);
7859 		uint_t label = DIF_INSTR_LABEL(instr);
7860 		uint_t v = DIF_INSTR_VAR(instr);
7861 		uint_t subr = DIF_INSTR_SUBR(instr);
7862 		uint_t type = DIF_INSTR_TYPE(instr);
7863 		uint_t op = DIF_INSTR_OP(instr);
7864 
7865 		switch (op) {
7866 		case DIF_OP_OR:
7867 		case DIF_OP_XOR:
7868 		case DIF_OP_AND:
7869 		case DIF_OP_SLL:
7870 		case DIF_OP_SRL:
7871 		case DIF_OP_SRA:
7872 		case DIF_OP_SUB:
7873 		case DIF_OP_ADD:
7874 		case DIF_OP_MUL:
7875 		case DIF_OP_SDIV:
7876 		case DIF_OP_UDIV:
7877 		case DIF_OP_SREM:
7878 		case DIF_OP_UREM:
7879 		case DIF_OP_COPYS:
7880 			if (r1 >= nregs)
7881 				err += efunc(pc, "invalid register %u\n", r1);
7882 			if (r2 >= nregs)
7883 				err += efunc(pc, "invalid register %u\n", r2);
7884 			if (rd >= nregs)
7885 				err += efunc(pc, "invalid register %u\n", rd);
7886 			if (rd == 0)
7887 				err += efunc(pc, "cannot write to %r0\n");
7888 			break;
7889 		case DIF_OP_NOT:
7890 		case DIF_OP_MOV:
7891 		case DIF_OP_ALLOCS:
7892 			if (r1 >= nregs)
7893 				err += efunc(pc, "invalid register %u\n", r1);
7894 			if (r2 != 0)
7895 				err += efunc(pc, "non-zero reserved bits\n");
7896 			if (rd >= nregs)
7897 				err += efunc(pc, "invalid register %u\n", rd);
7898 			if (rd == 0)
7899 				err += efunc(pc, "cannot write to %r0\n");
7900 			break;
7901 		case DIF_OP_LDSB:
7902 		case DIF_OP_LDSH:
7903 		case DIF_OP_LDSW:
7904 		case DIF_OP_LDUB:
7905 		case DIF_OP_LDUH:
7906 		case DIF_OP_LDUW:
7907 		case DIF_OP_LDX:
7908 			if (r1 >= nregs)
7909 				err += efunc(pc, "invalid register %u\n", r1);
7910 			if (r2 != 0)
7911 				err += efunc(pc, "non-zero reserved bits\n");
7912 			if (rd >= nregs)
7913 				err += efunc(pc, "invalid register %u\n", rd);
7914 			if (rd == 0)
7915 				err += efunc(pc, "cannot write to %r0\n");
7916 			if (kcheckload)
7917 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
7918 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
7919 			break;
7920 		case DIF_OP_RLDSB:
7921 		case DIF_OP_RLDSH:
7922 		case DIF_OP_RLDSW:
7923 		case DIF_OP_RLDUB:
7924 		case DIF_OP_RLDUH:
7925 		case DIF_OP_RLDUW:
7926 		case DIF_OP_RLDX:
7927 			if (r1 >= nregs)
7928 				err += efunc(pc, "invalid register %u\n", r1);
7929 			if (r2 != 0)
7930 				err += efunc(pc, "non-zero reserved bits\n");
7931 			if (rd >= nregs)
7932 				err += efunc(pc, "invalid register %u\n", rd);
7933 			if (rd == 0)
7934 				err += efunc(pc, "cannot write to %r0\n");
7935 			break;
7936 		case DIF_OP_ULDSB:
7937 		case DIF_OP_ULDSH:
7938 		case DIF_OP_ULDSW:
7939 		case DIF_OP_ULDUB:
7940 		case DIF_OP_ULDUH:
7941 		case DIF_OP_ULDUW:
7942 		case DIF_OP_ULDX:
7943 			if (r1 >= nregs)
7944 				err += efunc(pc, "invalid register %u\n", r1);
7945 			if (r2 != 0)
7946 				err += efunc(pc, "non-zero reserved bits\n");
7947 			if (rd >= nregs)
7948 				err += efunc(pc, "invalid register %u\n", rd);
7949 			if (rd == 0)
7950 				err += efunc(pc, "cannot write to %r0\n");
7951 			break;
7952 		case DIF_OP_STB:
7953 		case DIF_OP_STH:
7954 		case DIF_OP_STW:
7955 		case DIF_OP_STX:
7956 			if (r1 >= nregs)
7957 				err += efunc(pc, "invalid register %u\n", r1);
7958 			if (r2 != 0)
7959 				err += efunc(pc, "non-zero reserved bits\n");
7960 			if (rd >= nregs)
7961 				err += efunc(pc, "invalid register %u\n", rd);
7962 			if (rd == 0)
7963 				err += efunc(pc, "cannot write to 0 address\n");
7964 			break;
7965 		case DIF_OP_CMP:
7966 		case DIF_OP_SCMP:
7967 			if (r1 >= nregs)
7968 				err += efunc(pc, "invalid register %u\n", r1);
7969 			if (r2 >= nregs)
7970 				err += efunc(pc, "invalid register %u\n", r2);
7971 			if (rd != 0)
7972 				err += efunc(pc, "non-zero reserved bits\n");
7973 			break;
7974 		case DIF_OP_TST:
7975 			if (r1 >= nregs)
7976 				err += efunc(pc, "invalid register %u\n", r1);
7977 			if (r2 != 0 || rd != 0)
7978 				err += efunc(pc, "non-zero reserved bits\n");
7979 			break;
7980 		case DIF_OP_BA:
7981 		case DIF_OP_BE:
7982 		case DIF_OP_BNE:
7983 		case DIF_OP_BG:
7984 		case DIF_OP_BGU:
7985 		case DIF_OP_BGE:
7986 		case DIF_OP_BGEU:
7987 		case DIF_OP_BL:
7988 		case DIF_OP_BLU:
7989 		case DIF_OP_BLE:
7990 		case DIF_OP_BLEU:
7991 			if (label >= dp->dtdo_len) {
7992 				err += efunc(pc, "invalid branch target %u\n",
7993 				    label);
7994 			}
7995 			if (label <= pc) {
7996 				err += efunc(pc, "backward branch to %u\n",
7997 				    label);
7998 			}
7999 			break;
8000 		case DIF_OP_RET:
8001 			if (r1 != 0 || r2 != 0)
8002 				err += efunc(pc, "non-zero reserved bits\n");
8003 			if (rd >= nregs)
8004 				err += efunc(pc, "invalid register %u\n", rd);
8005 			break;
8006 		case DIF_OP_NOP:
8007 		case DIF_OP_POPTS:
8008 		case DIF_OP_FLUSHTS:
8009 			if (r1 != 0 || r2 != 0 || rd != 0)
8010 				err += efunc(pc, "non-zero reserved bits\n");
8011 			break;
8012 		case DIF_OP_SETX:
8013 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
8014 				err += efunc(pc, "invalid integer ref %u\n",
8015 				    DIF_INSTR_INTEGER(instr));
8016 			}
8017 			if (rd >= nregs)
8018 				err += efunc(pc, "invalid register %u\n", rd);
8019 			if (rd == 0)
8020 				err += efunc(pc, "cannot write to %r0\n");
8021 			break;
8022 		case DIF_OP_SETS:
8023 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
8024 				err += efunc(pc, "invalid string ref %u\n",
8025 				    DIF_INSTR_STRING(instr));
8026 			}
8027 			if (rd >= nregs)
8028 				err += efunc(pc, "invalid register %u\n", rd);
8029 			if (rd == 0)
8030 				err += efunc(pc, "cannot write to %r0\n");
8031 			break;
8032 		case DIF_OP_LDGA:
8033 		case DIF_OP_LDTA:
8034 			if (r1 > DIF_VAR_ARRAY_MAX)
8035 				err += efunc(pc, "invalid array %u\n", r1);
8036 			if (r2 >= nregs)
8037 				err += efunc(pc, "invalid register %u\n", r2);
8038 			if (rd >= nregs)
8039 				err += efunc(pc, "invalid register %u\n", rd);
8040 			if (rd == 0)
8041 				err += efunc(pc, "cannot write to %r0\n");
8042 			break;
8043 		case DIF_OP_LDGS:
8044 		case DIF_OP_LDTS:
8045 		case DIF_OP_LDLS:
8046 		case DIF_OP_LDGAA:
8047 		case DIF_OP_LDTAA:
8048 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
8049 				err += efunc(pc, "invalid variable %u\n", v);
8050 			if (rd >= nregs)
8051 				err += efunc(pc, "invalid register %u\n", rd);
8052 			if (rd == 0)
8053 				err += efunc(pc, "cannot write to %r0\n");
8054 			break;
8055 		case DIF_OP_STGS:
8056 		case DIF_OP_STTS:
8057 		case DIF_OP_STLS:
8058 		case DIF_OP_STGAA:
8059 		case DIF_OP_STTAA:
8060 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
8061 				err += efunc(pc, "invalid variable %u\n", v);
8062 			if (rs >= nregs)
8063 				err += efunc(pc, "invalid register %u\n", rd);
8064 			break;
8065 		case DIF_OP_CALL:
8066 			if (subr > DIF_SUBR_MAX)
8067 				err += efunc(pc, "invalid subr %u\n", subr);
8068 			if (rd >= nregs)
8069 				err += efunc(pc, "invalid register %u\n", rd);
8070 			if (rd == 0)
8071 				err += efunc(pc, "cannot write to %r0\n");
8072 
8073 			if (subr == DIF_SUBR_COPYOUT ||
8074 			    subr == DIF_SUBR_COPYOUTSTR) {
8075 				dp->dtdo_destructive = 1;
8076 			}
8077 			break;
8078 		case DIF_OP_PUSHTR:
8079 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
8080 				err += efunc(pc, "invalid ref type %u\n", type);
8081 			if (r2 >= nregs)
8082 				err += efunc(pc, "invalid register %u\n", r2);
8083 			if (rs >= nregs)
8084 				err += efunc(pc, "invalid register %u\n", rs);
8085 			break;
8086 		case DIF_OP_PUSHTV:
8087 			if (type != DIF_TYPE_CTF)
8088 				err += efunc(pc, "invalid val type %u\n", type);
8089 			if (r2 >= nregs)
8090 				err += efunc(pc, "invalid register %u\n", r2);
8091 			if (rs >= nregs)
8092 				err += efunc(pc, "invalid register %u\n", rs);
8093 			break;
8094 		default:
8095 			err += efunc(pc, "invalid opcode %u\n",
8096 			    DIF_INSTR_OP(instr));
8097 		}
8098 	}
8099 
8100 	if (dp->dtdo_len != 0 &&
8101 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
8102 		err += efunc(dp->dtdo_len - 1,
8103 		    "expected 'ret' as last DIF instruction\n");
8104 	}
8105 
8106 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
8107 		/*
8108 		 * If we're not returning by reference, the size must be either
8109 		 * 0 or the size of one of the base types.
8110 		 */
8111 		switch (dp->dtdo_rtype.dtdt_size) {
8112 		case 0:
8113 		case sizeof (uint8_t):
8114 		case sizeof (uint16_t):
8115 		case sizeof (uint32_t):
8116 		case sizeof (uint64_t):
8117 			break;
8118 
8119 		default:
8120 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
8121 		}
8122 	}
8123 
8124 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
8125 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
8126 		dtrace_diftype_t *vt, *et;
8127 		uint_t id, ndx;
8128 
8129 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
8130 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
8131 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8132 			err += efunc(i, "unrecognized variable scope %d\n",
8133 			    v->dtdv_scope);
8134 			break;
8135 		}
8136 
8137 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8138 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
8139 			err += efunc(i, "unrecognized variable type %d\n",
8140 			    v->dtdv_kind);
8141 			break;
8142 		}
8143 
8144 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8145 			err += efunc(i, "%d exceeds variable id limit\n", id);
8146 			break;
8147 		}
8148 
8149 		if (id < DIF_VAR_OTHER_UBASE)
8150 			continue;
8151 
8152 		/*
8153 		 * For user-defined variables, we need to check that this
8154 		 * definition is identical to any previous definition that we
8155 		 * encountered.
8156 		 */
8157 		ndx = id - DIF_VAR_OTHER_UBASE;
8158 
8159 		switch (v->dtdv_scope) {
8160 		case DIFV_SCOPE_GLOBAL:
8161 			if (ndx < vstate->dtvs_nglobals) {
8162 				dtrace_statvar_t *svar;
8163 
8164 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8165 					existing = &svar->dtsv_var;
8166 			}
8167 
8168 			break;
8169 
8170 		case DIFV_SCOPE_THREAD:
8171 			if (ndx < vstate->dtvs_ntlocals)
8172 				existing = &vstate->dtvs_tlocals[ndx];
8173 			break;
8174 
8175 		case DIFV_SCOPE_LOCAL:
8176 			if (ndx < vstate->dtvs_nlocals) {
8177 				dtrace_statvar_t *svar;
8178 
8179 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8180 					existing = &svar->dtsv_var;
8181 			}
8182 
8183 			break;
8184 		}
8185 
8186 		vt = &v->dtdv_type;
8187 
8188 		if (vt->dtdt_flags & DIF_TF_BYREF) {
8189 			if (vt->dtdt_size == 0) {
8190 				err += efunc(i, "zero-sized variable\n");
8191 				break;
8192 			}
8193 
8194 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8195 			    vt->dtdt_size > dtrace_global_maxsize) {
8196 				err += efunc(i, "oversized by-ref global\n");
8197 				break;
8198 			}
8199 		}
8200 
8201 		if (existing == NULL || existing->dtdv_id == 0)
8202 			continue;
8203 
8204 		ASSERT(existing->dtdv_id == v->dtdv_id);
8205 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
8206 
8207 		if (existing->dtdv_kind != v->dtdv_kind)
8208 			err += efunc(i, "%d changed variable kind\n", id);
8209 
8210 		et = &existing->dtdv_type;
8211 
8212 		if (vt->dtdt_flags != et->dtdt_flags) {
8213 			err += efunc(i, "%d changed variable type flags\n", id);
8214 			break;
8215 		}
8216 
8217 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8218 			err += efunc(i, "%d changed variable type size\n", id);
8219 			break;
8220 		}
8221 	}
8222 
8223 	return (err);
8224 }
8225 
8226 /*
8227  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
8228  * are much more constrained than normal DIFOs.  Specifically, they may
8229  * not:
8230  *
8231  * 1. Make calls to subroutines other than copyin(), copyinstr() or
8232  *    miscellaneous string routines
8233  * 2. Access DTrace variables other than the args[] array, and the
8234  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8235  * 3. Have thread-local variables.
8236  * 4. Have dynamic variables.
8237  */
8238 static int
8239 dtrace_difo_validate_helper(dtrace_difo_t *dp)
8240 {
8241 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8242 	int err = 0;
8243 	uint_t pc;
8244 
8245 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8246 		dif_instr_t instr = dp->dtdo_buf[pc];
8247 
8248 		uint_t v = DIF_INSTR_VAR(instr);
8249 		uint_t subr = DIF_INSTR_SUBR(instr);
8250 		uint_t op = DIF_INSTR_OP(instr);
8251 
8252 		switch (op) {
8253 		case DIF_OP_OR:
8254 		case DIF_OP_XOR:
8255 		case DIF_OP_AND:
8256 		case DIF_OP_SLL:
8257 		case DIF_OP_SRL:
8258 		case DIF_OP_SRA:
8259 		case DIF_OP_SUB:
8260 		case DIF_OP_ADD:
8261 		case DIF_OP_MUL:
8262 		case DIF_OP_SDIV:
8263 		case DIF_OP_UDIV:
8264 		case DIF_OP_SREM:
8265 		case DIF_OP_UREM:
8266 		case DIF_OP_COPYS:
8267 		case DIF_OP_NOT:
8268 		case DIF_OP_MOV:
8269 		case DIF_OP_RLDSB:
8270 		case DIF_OP_RLDSH:
8271 		case DIF_OP_RLDSW:
8272 		case DIF_OP_RLDUB:
8273 		case DIF_OP_RLDUH:
8274 		case DIF_OP_RLDUW:
8275 		case DIF_OP_RLDX:
8276 		case DIF_OP_ULDSB:
8277 		case DIF_OP_ULDSH:
8278 		case DIF_OP_ULDSW:
8279 		case DIF_OP_ULDUB:
8280 		case DIF_OP_ULDUH:
8281 		case DIF_OP_ULDUW:
8282 		case DIF_OP_ULDX:
8283 		case DIF_OP_STB:
8284 		case DIF_OP_STH:
8285 		case DIF_OP_STW:
8286 		case DIF_OP_STX:
8287 		case DIF_OP_ALLOCS:
8288 		case DIF_OP_CMP:
8289 		case DIF_OP_SCMP:
8290 		case DIF_OP_TST:
8291 		case DIF_OP_BA:
8292 		case DIF_OP_BE:
8293 		case DIF_OP_BNE:
8294 		case DIF_OP_BG:
8295 		case DIF_OP_BGU:
8296 		case DIF_OP_BGE:
8297 		case DIF_OP_BGEU:
8298 		case DIF_OP_BL:
8299 		case DIF_OP_BLU:
8300 		case DIF_OP_BLE:
8301 		case DIF_OP_BLEU:
8302 		case DIF_OP_RET:
8303 		case DIF_OP_NOP:
8304 		case DIF_OP_POPTS:
8305 		case DIF_OP_FLUSHTS:
8306 		case DIF_OP_SETX:
8307 		case DIF_OP_SETS:
8308 		case DIF_OP_LDGA:
8309 		case DIF_OP_LDLS:
8310 		case DIF_OP_STGS:
8311 		case DIF_OP_STLS:
8312 		case DIF_OP_PUSHTR:
8313 		case DIF_OP_PUSHTV:
8314 			break;
8315 
8316 		case DIF_OP_LDGS:
8317 			if (v >= DIF_VAR_OTHER_UBASE)
8318 				break;
8319 
8320 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
8321 				break;
8322 
8323 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
8324 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
8325 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
8326 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
8327 				break;
8328 
8329 			err += efunc(pc, "illegal variable %u\n", v);
8330 			break;
8331 
8332 		case DIF_OP_LDTA:
8333 		case DIF_OP_LDTS:
8334 		case DIF_OP_LDGAA:
8335 		case DIF_OP_LDTAA:
8336 			err += efunc(pc, "illegal dynamic variable load\n");
8337 			break;
8338 
8339 		case DIF_OP_STTS:
8340 		case DIF_OP_STGAA:
8341 		case DIF_OP_STTAA:
8342 			err += efunc(pc, "illegal dynamic variable store\n");
8343 			break;
8344 
8345 		case DIF_OP_CALL:
8346 			if (subr == DIF_SUBR_ALLOCA ||
8347 			    subr == DIF_SUBR_BCOPY ||
8348 			    subr == DIF_SUBR_COPYIN ||
8349 			    subr == DIF_SUBR_COPYINTO ||
8350 			    subr == DIF_SUBR_COPYINSTR ||
8351 			    subr == DIF_SUBR_INDEX ||
8352 			    subr == DIF_SUBR_INET_NTOA ||
8353 			    subr == DIF_SUBR_INET_NTOA6 ||
8354 			    subr == DIF_SUBR_INET_NTOP ||
8355 			    subr == DIF_SUBR_LLTOSTR ||
8356 			    subr == DIF_SUBR_RINDEX ||
8357 			    subr == DIF_SUBR_STRCHR ||
8358 			    subr == DIF_SUBR_STRJOIN ||
8359 			    subr == DIF_SUBR_STRRCHR ||
8360 			    subr == DIF_SUBR_STRSTR ||
8361 			    subr == DIF_SUBR_HTONS ||
8362 			    subr == DIF_SUBR_HTONL ||
8363 			    subr == DIF_SUBR_HTONLL ||
8364 			    subr == DIF_SUBR_NTOHS ||
8365 			    subr == DIF_SUBR_NTOHL ||
8366 			    subr == DIF_SUBR_NTOHLL)
8367 				break;
8368 
8369 			err += efunc(pc, "invalid subr %u\n", subr);
8370 			break;
8371 
8372 		default:
8373 			err += efunc(pc, "invalid opcode %u\n",
8374 			    DIF_INSTR_OP(instr));
8375 		}
8376 	}
8377 
8378 	return (err);
8379 }
8380 
8381 /*
8382  * Returns 1 if the expression in the DIF object can be cached on a per-thread
8383  * basis; 0 if not.
8384  */
8385 static int
8386 dtrace_difo_cacheable(dtrace_difo_t *dp)
8387 {
8388 	int i;
8389 
8390 	if (dp == NULL)
8391 		return (0);
8392 
8393 	for (i = 0; i < dp->dtdo_varlen; i++) {
8394 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8395 
8396 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
8397 			continue;
8398 
8399 		switch (v->dtdv_id) {
8400 		case DIF_VAR_CURTHREAD:
8401 		case DIF_VAR_PID:
8402 		case DIF_VAR_TID:
8403 		case DIF_VAR_EXECNAME:
8404 		case DIF_VAR_ZONENAME:
8405 			break;
8406 
8407 		default:
8408 			return (0);
8409 		}
8410 	}
8411 
8412 	/*
8413 	 * This DIF object may be cacheable.  Now we need to look for any
8414 	 * array loading instructions, any memory loading instructions, or
8415 	 * any stores to thread-local variables.
8416 	 */
8417 	for (i = 0; i < dp->dtdo_len; i++) {
8418 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
8419 
8420 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
8421 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
8422 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
8423 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
8424 			return (0);
8425 	}
8426 
8427 	return (1);
8428 }
8429 
8430 static void
8431 dtrace_difo_hold(dtrace_difo_t *dp)
8432 {
8433 	int i;
8434 
8435 	ASSERT(MUTEX_HELD(&dtrace_lock));
8436 
8437 	dp->dtdo_refcnt++;
8438 	ASSERT(dp->dtdo_refcnt != 0);
8439 
8440 	/*
8441 	 * We need to check this DIF object for references to the variable
8442 	 * DIF_VAR_VTIMESTAMP.
8443 	 */
8444 	for (i = 0; i < dp->dtdo_varlen; i++) {
8445 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8446 
8447 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8448 			continue;
8449 
8450 		if (dtrace_vtime_references++ == 0)
8451 			dtrace_vtime_enable();
8452 	}
8453 }
8454 
8455 /*
8456  * This routine calculates the dynamic variable chunksize for a given DIF
8457  * object.  The calculation is not fool-proof, and can probably be tricked by
8458  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
8459  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
8460  * if a dynamic variable size exceeds the chunksize.
8461  */
8462 static void
8463 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8464 {
8465 	uint64_t sval;
8466 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
8467 	const dif_instr_t *text = dp->dtdo_buf;
8468 	uint_t pc, srd = 0;
8469 	uint_t ttop = 0;
8470 	size_t size, ksize;
8471 	uint_t id, i;
8472 
8473 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8474 		dif_instr_t instr = text[pc];
8475 		uint_t op = DIF_INSTR_OP(instr);
8476 		uint_t rd = DIF_INSTR_RD(instr);
8477 		uint_t r1 = DIF_INSTR_R1(instr);
8478 		uint_t nkeys = 0;
8479 		uchar_t scope;
8480 
8481 		dtrace_key_t *key = tupregs;
8482 
8483 		switch (op) {
8484 		case DIF_OP_SETX:
8485 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
8486 			srd = rd;
8487 			continue;
8488 
8489 		case DIF_OP_STTS:
8490 			key = &tupregs[DIF_DTR_NREGS];
8491 			key[0].dttk_size = 0;
8492 			key[1].dttk_size = 0;
8493 			nkeys = 2;
8494 			scope = DIFV_SCOPE_THREAD;
8495 			break;
8496 
8497 		case DIF_OP_STGAA:
8498 		case DIF_OP_STTAA:
8499 			nkeys = ttop;
8500 
8501 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
8502 				key[nkeys++].dttk_size = 0;
8503 
8504 			key[nkeys++].dttk_size = 0;
8505 
8506 			if (op == DIF_OP_STTAA) {
8507 				scope = DIFV_SCOPE_THREAD;
8508 			} else {
8509 				scope = DIFV_SCOPE_GLOBAL;
8510 			}
8511 
8512 			break;
8513 
8514 		case DIF_OP_PUSHTR:
8515 			if (ttop == DIF_DTR_NREGS)
8516 				return;
8517 
8518 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
8519 				/*
8520 				 * If the register for the size of the "pushtr"
8521 				 * is %r0 (or the value is 0) and the type is
8522 				 * a string, we'll use the system-wide default
8523 				 * string size.
8524 				 */
8525 				tupregs[ttop++].dttk_size =
8526 				    dtrace_strsize_default;
8527 			} else {
8528 				if (srd == 0)
8529 					return;
8530 
8531 				tupregs[ttop++].dttk_size = sval;
8532 			}
8533 
8534 			break;
8535 
8536 		case DIF_OP_PUSHTV:
8537 			if (ttop == DIF_DTR_NREGS)
8538 				return;
8539 
8540 			tupregs[ttop++].dttk_size = 0;
8541 			break;
8542 
8543 		case DIF_OP_FLUSHTS:
8544 			ttop = 0;
8545 			break;
8546 
8547 		case DIF_OP_POPTS:
8548 			if (ttop != 0)
8549 				ttop--;
8550 			break;
8551 		}
8552 
8553 		sval = 0;
8554 		srd = 0;
8555 
8556 		if (nkeys == 0)
8557 			continue;
8558 
8559 		/*
8560 		 * We have a dynamic variable allocation; calculate its size.
8561 		 */
8562 		for (ksize = 0, i = 0; i < nkeys; i++)
8563 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
8564 
8565 		size = sizeof (dtrace_dynvar_t);
8566 		size += sizeof (dtrace_key_t) * (nkeys - 1);
8567 		size += ksize;
8568 
8569 		/*
8570 		 * Now we need to determine the size of the stored data.
8571 		 */
8572 		id = DIF_INSTR_VAR(instr);
8573 
8574 		for (i = 0; i < dp->dtdo_varlen; i++) {
8575 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
8576 
8577 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
8578 				size += v->dtdv_type.dtdt_size;
8579 				break;
8580 			}
8581 		}
8582 
8583 		if (i == dp->dtdo_varlen)
8584 			return;
8585 
8586 		/*
8587 		 * We have the size.  If this is larger than the chunk size
8588 		 * for our dynamic variable state, reset the chunk size.
8589 		 */
8590 		size = P2ROUNDUP(size, sizeof (uint64_t));
8591 
8592 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
8593 			vstate->dtvs_dynvars.dtds_chunksize = size;
8594 	}
8595 }
8596 
8597 static void
8598 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8599 {
8600 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
8601 	uint_t id;
8602 
8603 	ASSERT(MUTEX_HELD(&dtrace_lock));
8604 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
8605 
8606 	for (i = 0; i < dp->dtdo_varlen; i++) {
8607 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8608 		dtrace_statvar_t *svar, ***svarp;
8609 		size_t dsize = 0;
8610 		uint8_t scope = v->dtdv_scope;
8611 		int *np;
8612 
8613 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8614 			continue;
8615 
8616 		id -= DIF_VAR_OTHER_UBASE;
8617 
8618 		switch (scope) {
8619 		case DIFV_SCOPE_THREAD:
8620 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
8621 				dtrace_difv_t *tlocals;
8622 
8623 				if ((ntlocals = (otlocals << 1)) == 0)
8624 					ntlocals = 1;
8625 
8626 				osz = otlocals * sizeof (dtrace_difv_t);
8627 				nsz = ntlocals * sizeof (dtrace_difv_t);
8628 
8629 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
8630 
8631 				if (osz != 0) {
8632 					bcopy(vstate->dtvs_tlocals,
8633 					    tlocals, osz);
8634 					kmem_free(vstate->dtvs_tlocals, osz);
8635 				}
8636 
8637 				vstate->dtvs_tlocals = tlocals;
8638 				vstate->dtvs_ntlocals = ntlocals;
8639 			}
8640 
8641 			vstate->dtvs_tlocals[id] = *v;
8642 			continue;
8643 
8644 		case DIFV_SCOPE_LOCAL:
8645 			np = &vstate->dtvs_nlocals;
8646 			svarp = &vstate->dtvs_locals;
8647 
8648 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8649 				dsize = NCPU * (v->dtdv_type.dtdt_size +
8650 				    sizeof (uint64_t));
8651 			else
8652 				dsize = NCPU * sizeof (uint64_t);
8653 
8654 			break;
8655 
8656 		case DIFV_SCOPE_GLOBAL:
8657 			np = &vstate->dtvs_nglobals;
8658 			svarp = &vstate->dtvs_globals;
8659 
8660 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8661 				dsize = v->dtdv_type.dtdt_size +
8662 				    sizeof (uint64_t);
8663 
8664 			break;
8665 
8666 		default:
8667 			ASSERT(0);
8668 		}
8669 
8670 		while (id >= (oldsvars = *np)) {
8671 			dtrace_statvar_t **statics;
8672 			int newsvars, oldsize, newsize;
8673 
8674 			if ((newsvars = (oldsvars << 1)) == 0)
8675 				newsvars = 1;
8676 
8677 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
8678 			newsize = newsvars * sizeof (dtrace_statvar_t *);
8679 
8680 			statics = kmem_zalloc(newsize, KM_SLEEP);
8681 
8682 			if (oldsize != 0) {
8683 				bcopy(*svarp, statics, oldsize);
8684 				kmem_free(*svarp, oldsize);
8685 			}
8686 
8687 			*svarp = statics;
8688 			*np = newsvars;
8689 		}
8690 
8691 		if ((svar = (*svarp)[id]) == NULL) {
8692 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
8693 			svar->dtsv_var = *v;
8694 
8695 			if ((svar->dtsv_size = dsize) != 0) {
8696 				svar->dtsv_data = (uint64_t)(uintptr_t)
8697 				    kmem_zalloc(dsize, KM_SLEEP);
8698 			}
8699 
8700 			(*svarp)[id] = svar;
8701 		}
8702 
8703 		svar->dtsv_refcnt++;
8704 	}
8705 
8706 	dtrace_difo_chunksize(dp, vstate);
8707 	dtrace_difo_hold(dp);
8708 }
8709 
8710 static dtrace_difo_t *
8711 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8712 {
8713 	dtrace_difo_t *new;
8714 	size_t sz;
8715 
8716 	ASSERT(dp->dtdo_buf != NULL);
8717 	ASSERT(dp->dtdo_refcnt != 0);
8718 
8719 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
8720 
8721 	ASSERT(dp->dtdo_buf != NULL);
8722 	sz = dp->dtdo_len * sizeof (dif_instr_t);
8723 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
8724 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
8725 	new->dtdo_len = dp->dtdo_len;
8726 
8727 	if (dp->dtdo_strtab != NULL) {
8728 		ASSERT(dp->dtdo_strlen != 0);
8729 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
8730 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
8731 		new->dtdo_strlen = dp->dtdo_strlen;
8732 	}
8733 
8734 	if (dp->dtdo_inttab != NULL) {
8735 		ASSERT(dp->dtdo_intlen != 0);
8736 		sz = dp->dtdo_intlen * sizeof (uint64_t);
8737 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
8738 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
8739 		new->dtdo_intlen = dp->dtdo_intlen;
8740 	}
8741 
8742 	if (dp->dtdo_vartab != NULL) {
8743 		ASSERT(dp->dtdo_varlen != 0);
8744 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
8745 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
8746 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
8747 		new->dtdo_varlen = dp->dtdo_varlen;
8748 	}
8749 
8750 	dtrace_difo_init(new, vstate);
8751 	return (new);
8752 }
8753 
8754 static void
8755 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8756 {
8757 	int i;
8758 
8759 	ASSERT(dp->dtdo_refcnt == 0);
8760 
8761 	for (i = 0; i < dp->dtdo_varlen; i++) {
8762 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8763 		dtrace_statvar_t *svar, **svarp;
8764 		uint_t id;
8765 		uint8_t scope = v->dtdv_scope;
8766 		int *np;
8767 
8768 		switch (scope) {
8769 		case DIFV_SCOPE_THREAD:
8770 			continue;
8771 
8772 		case DIFV_SCOPE_LOCAL:
8773 			np = &vstate->dtvs_nlocals;
8774 			svarp = vstate->dtvs_locals;
8775 			break;
8776 
8777 		case DIFV_SCOPE_GLOBAL:
8778 			np = &vstate->dtvs_nglobals;
8779 			svarp = vstate->dtvs_globals;
8780 			break;
8781 
8782 		default:
8783 			ASSERT(0);
8784 		}
8785 
8786 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8787 			continue;
8788 
8789 		id -= DIF_VAR_OTHER_UBASE;
8790 		ASSERT(id < *np);
8791 
8792 		svar = svarp[id];
8793 		ASSERT(svar != NULL);
8794 		ASSERT(svar->dtsv_refcnt > 0);
8795 
8796 		if (--svar->dtsv_refcnt > 0)
8797 			continue;
8798 
8799 		if (svar->dtsv_size != 0) {
8800 			ASSERT(svar->dtsv_data != NULL);
8801 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
8802 			    svar->dtsv_size);
8803 		}
8804 
8805 		kmem_free(svar, sizeof (dtrace_statvar_t));
8806 		svarp[id] = NULL;
8807 	}
8808 
8809 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
8810 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
8811 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
8812 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
8813 
8814 	kmem_free(dp, sizeof (dtrace_difo_t));
8815 }
8816 
8817 static void
8818 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8819 {
8820 	int i;
8821 
8822 	ASSERT(MUTEX_HELD(&dtrace_lock));
8823 	ASSERT(dp->dtdo_refcnt != 0);
8824 
8825 	for (i = 0; i < dp->dtdo_varlen; i++) {
8826 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8827 
8828 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8829 			continue;
8830 
8831 		ASSERT(dtrace_vtime_references > 0);
8832 		if (--dtrace_vtime_references == 0)
8833 			dtrace_vtime_disable();
8834 	}
8835 
8836 	if (--dp->dtdo_refcnt == 0)
8837 		dtrace_difo_destroy(dp, vstate);
8838 }
8839 
8840 /*
8841  * DTrace Format Functions
8842  */
8843 static uint16_t
8844 dtrace_format_add(dtrace_state_t *state, char *str)
8845 {
8846 	char *fmt, **new;
8847 	uint16_t ndx, len = strlen(str) + 1;
8848 
8849 	fmt = kmem_zalloc(len, KM_SLEEP);
8850 	bcopy(str, fmt, len);
8851 
8852 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
8853 		if (state->dts_formats[ndx] == NULL) {
8854 			state->dts_formats[ndx] = fmt;
8855 			return (ndx + 1);
8856 		}
8857 	}
8858 
8859 	if (state->dts_nformats == USHRT_MAX) {
8860 		/*
8861 		 * This is only likely if a denial-of-service attack is being
8862 		 * attempted.  As such, it's okay to fail silently here.
8863 		 */
8864 		kmem_free(fmt, len);
8865 		return (0);
8866 	}
8867 
8868 	/*
8869 	 * For simplicity, we always resize the formats array to be exactly the
8870 	 * number of formats.
8871 	 */
8872 	ndx = state->dts_nformats++;
8873 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
8874 
8875 	if (state->dts_formats != NULL) {
8876 		ASSERT(ndx != 0);
8877 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
8878 		kmem_free(state->dts_formats, ndx * sizeof (char *));
8879 	}
8880 
8881 	state->dts_formats = new;
8882 	state->dts_formats[ndx] = fmt;
8883 
8884 	return (ndx + 1);
8885 }
8886 
8887 static void
8888 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
8889 {
8890 	char *fmt;
8891 
8892 	ASSERT(state->dts_formats != NULL);
8893 	ASSERT(format <= state->dts_nformats);
8894 	ASSERT(state->dts_formats[format - 1] != NULL);
8895 
8896 	fmt = state->dts_formats[format - 1];
8897 	kmem_free(fmt, strlen(fmt) + 1);
8898 	state->dts_formats[format - 1] = NULL;
8899 }
8900 
8901 static void
8902 dtrace_format_destroy(dtrace_state_t *state)
8903 {
8904 	int i;
8905 
8906 	if (state->dts_nformats == 0) {
8907 		ASSERT(state->dts_formats == NULL);
8908 		return;
8909 	}
8910 
8911 	ASSERT(state->dts_formats != NULL);
8912 
8913 	for (i = 0; i < state->dts_nformats; i++) {
8914 		char *fmt = state->dts_formats[i];
8915 
8916 		if (fmt == NULL)
8917 			continue;
8918 
8919 		kmem_free(fmt, strlen(fmt) + 1);
8920 	}
8921 
8922 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
8923 	state->dts_nformats = 0;
8924 	state->dts_formats = NULL;
8925 }
8926 
8927 /*
8928  * DTrace Predicate Functions
8929  */
8930 static dtrace_predicate_t *
8931 dtrace_predicate_create(dtrace_difo_t *dp)
8932 {
8933 	dtrace_predicate_t *pred;
8934 
8935 	ASSERT(MUTEX_HELD(&dtrace_lock));
8936 	ASSERT(dp->dtdo_refcnt != 0);
8937 
8938 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
8939 	pred->dtp_difo = dp;
8940 	pred->dtp_refcnt = 1;
8941 
8942 	if (!dtrace_difo_cacheable(dp))
8943 		return (pred);
8944 
8945 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
8946 		/*
8947 		 * This is only theoretically possible -- we have had 2^32
8948 		 * cacheable predicates on this machine.  We cannot allow any
8949 		 * more predicates to become cacheable:  as unlikely as it is,
8950 		 * there may be a thread caching a (now stale) predicate cache
8951 		 * ID. (N.B.: the temptation is being successfully resisted to
8952 		 * have this cmn_err() "Holy shit -- we executed this code!")
8953 		 */
8954 		return (pred);
8955 	}
8956 
8957 	pred->dtp_cacheid = dtrace_predcache_id++;
8958 
8959 	return (pred);
8960 }
8961 
8962 static void
8963 dtrace_predicate_hold(dtrace_predicate_t *pred)
8964 {
8965 	ASSERT(MUTEX_HELD(&dtrace_lock));
8966 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
8967 	ASSERT(pred->dtp_refcnt > 0);
8968 
8969 	pred->dtp_refcnt++;
8970 }
8971 
8972 static void
8973 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
8974 {
8975 	dtrace_difo_t *dp = pred->dtp_difo;
8976 
8977 	ASSERT(MUTEX_HELD(&dtrace_lock));
8978 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
8979 	ASSERT(pred->dtp_refcnt > 0);
8980 
8981 	if (--pred->dtp_refcnt == 0) {
8982 		dtrace_difo_release(pred->dtp_difo, vstate);
8983 		kmem_free(pred, sizeof (dtrace_predicate_t));
8984 	}
8985 }
8986 
8987 /*
8988  * DTrace Action Description Functions
8989  */
8990 static dtrace_actdesc_t *
8991 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
8992     uint64_t uarg, uint64_t arg)
8993 {
8994 	dtrace_actdesc_t *act;
8995 
8996 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
8997 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
8998 
8999 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
9000 	act->dtad_kind = kind;
9001 	act->dtad_ntuple = ntuple;
9002 	act->dtad_uarg = uarg;
9003 	act->dtad_arg = arg;
9004 	act->dtad_refcnt = 1;
9005 
9006 	return (act);
9007 }
9008 
9009 static void
9010 dtrace_actdesc_hold(dtrace_actdesc_t *act)
9011 {
9012 	ASSERT(act->dtad_refcnt >= 1);
9013 	act->dtad_refcnt++;
9014 }
9015 
9016 static void
9017 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
9018 {
9019 	dtrace_actkind_t kind = act->dtad_kind;
9020 	dtrace_difo_t *dp;
9021 
9022 	ASSERT(act->dtad_refcnt >= 1);
9023 
9024 	if (--act->dtad_refcnt != 0)
9025 		return;
9026 
9027 	if ((dp = act->dtad_difo) != NULL)
9028 		dtrace_difo_release(dp, vstate);
9029 
9030 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
9031 		char *str = (char *)(uintptr_t)act->dtad_arg;
9032 
9033 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
9034 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
9035 
9036 		if (str != NULL)
9037 			kmem_free(str, strlen(str) + 1);
9038 	}
9039 
9040 	kmem_free(act, sizeof (dtrace_actdesc_t));
9041 }
9042 
9043 /*
9044  * DTrace ECB Functions
9045  */
9046 static dtrace_ecb_t *
9047 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
9048 {
9049 	dtrace_ecb_t *ecb;
9050 	dtrace_epid_t epid;
9051 
9052 	ASSERT(MUTEX_HELD(&dtrace_lock));
9053 
9054 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
9055 	ecb->dte_predicate = NULL;
9056 	ecb->dte_probe = probe;
9057 
9058 	/*
9059 	 * The default size is the size of the default action: recording
9060 	 * the epid.
9061 	 */
9062 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
9063 	ecb->dte_alignment = sizeof (dtrace_epid_t);
9064 
9065 	epid = state->dts_epid++;
9066 
9067 	if (epid - 1 >= state->dts_necbs) {
9068 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
9069 		int necbs = state->dts_necbs << 1;
9070 
9071 		ASSERT(epid == state->dts_necbs + 1);
9072 
9073 		if (necbs == 0) {
9074 			ASSERT(oecbs == NULL);
9075 			necbs = 1;
9076 		}
9077 
9078 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
9079 
9080 		if (oecbs != NULL)
9081 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
9082 
9083 		dtrace_membar_producer();
9084 		state->dts_ecbs = ecbs;
9085 
9086 		if (oecbs != NULL) {
9087 			/*
9088 			 * If this state is active, we must dtrace_sync()
9089 			 * before we can free the old dts_ecbs array:  we're
9090 			 * coming in hot, and there may be active ring
9091 			 * buffer processing (which indexes into the dts_ecbs
9092 			 * array) on another CPU.
9093 			 */
9094 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
9095 				dtrace_sync();
9096 
9097 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
9098 		}
9099 
9100 		dtrace_membar_producer();
9101 		state->dts_necbs = necbs;
9102 	}
9103 
9104 	ecb->dte_state = state;
9105 
9106 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
9107 	dtrace_membar_producer();
9108 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
9109 
9110 	return (ecb);
9111 }
9112 
9113 static int
9114 dtrace_ecb_enable(dtrace_ecb_t *ecb)
9115 {
9116 	dtrace_probe_t *probe = ecb->dte_probe;
9117 
9118 	ASSERT(MUTEX_HELD(&cpu_lock));
9119 	ASSERT(MUTEX_HELD(&dtrace_lock));
9120 	ASSERT(ecb->dte_next == NULL);
9121 
9122 	if (probe == NULL) {
9123 		/*
9124 		 * This is the NULL probe -- there's nothing to do.
9125 		 */
9126 		return (0);
9127 	}
9128 
9129 	if (probe->dtpr_ecb == NULL) {
9130 		dtrace_provider_t *prov = probe->dtpr_provider;
9131 
9132 		/*
9133 		 * We're the first ECB on this probe.
9134 		 */
9135 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9136 
9137 		if (ecb->dte_predicate != NULL)
9138 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9139 
9140 		return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9141 		    probe->dtpr_id, probe->dtpr_arg));
9142 	} else {
9143 		/*
9144 		 * This probe is already active.  Swing the last pointer to
9145 		 * point to the new ECB, and issue a dtrace_sync() to assure
9146 		 * that all CPUs have seen the change.
9147 		 */
9148 		ASSERT(probe->dtpr_ecb_last != NULL);
9149 		probe->dtpr_ecb_last->dte_next = ecb;
9150 		probe->dtpr_ecb_last = ecb;
9151 		probe->dtpr_predcache = 0;
9152 
9153 		dtrace_sync();
9154 		return (0);
9155 	}
9156 }
9157 
9158 static void
9159 dtrace_ecb_resize(dtrace_ecb_t *ecb)
9160 {
9161 	uint32_t maxalign = sizeof (dtrace_epid_t);
9162 	uint32_t align = sizeof (uint8_t), offs, diff;
9163 	dtrace_action_t *act;
9164 	int wastuple = 0;
9165 	uint32_t aggbase = UINT32_MAX;
9166 	dtrace_state_t *state = ecb->dte_state;
9167 
9168 	/*
9169 	 * If we record anything, we always record the epid.  (And we always
9170 	 * record it first.)
9171 	 */
9172 	offs = sizeof (dtrace_epid_t);
9173 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
9174 
9175 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9176 		dtrace_recdesc_t *rec = &act->dta_rec;
9177 
9178 		if ((align = rec->dtrd_alignment) > maxalign)
9179 			maxalign = align;
9180 
9181 		if (!wastuple && act->dta_intuple) {
9182 			/*
9183 			 * This is the first record in a tuple.  Align the
9184 			 * offset to be at offset 4 in an 8-byte aligned
9185 			 * block.
9186 			 */
9187 			diff = offs + sizeof (dtrace_aggid_t);
9188 
9189 			if (diff = (diff & (sizeof (uint64_t) - 1)))
9190 				offs += sizeof (uint64_t) - diff;
9191 
9192 			aggbase = offs - sizeof (dtrace_aggid_t);
9193 			ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
9194 		}
9195 
9196 		/*LINTED*/
9197 		if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
9198 			/*
9199 			 * The current offset is not properly aligned; align it.
9200 			 */
9201 			offs += align - diff;
9202 		}
9203 
9204 		rec->dtrd_offset = offs;
9205 
9206 		if (offs + rec->dtrd_size > ecb->dte_needed) {
9207 			ecb->dte_needed = offs + rec->dtrd_size;
9208 
9209 			if (ecb->dte_needed > state->dts_needed)
9210 				state->dts_needed = ecb->dte_needed;
9211 		}
9212 
9213 		if (DTRACEACT_ISAGG(act->dta_kind)) {
9214 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9215 			dtrace_action_t *first = agg->dtag_first, *prev;
9216 
9217 			ASSERT(rec->dtrd_size != 0 && first != NULL);
9218 			ASSERT(wastuple);
9219 			ASSERT(aggbase != UINT32_MAX);
9220 
9221 			agg->dtag_base = aggbase;
9222 
9223 			while ((prev = first->dta_prev) != NULL &&
9224 			    DTRACEACT_ISAGG(prev->dta_kind)) {
9225 				agg = (dtrace_aggregation_t *)prev;
9226 				first = agg->dtag_first;
9227 			}
9228 
9229 			if (prev != NULL) {
9230 				offs = prev->dta_rec.dtrd_offset +
9231 				    prev->dta_rec.dtrd_size;
9232 			} else {
9233 				offs = sizeof (dtrace_epid_t);
9234 			}
9235 			wastuple = 0;
9236 		} else {
9237 			if (!act->dta_intuple)
9238 				ecb->dte_size = offs + rec->dtrd_size;
9239 
9240 			offs += rec->dtrd_size;
9241 		}
9242 
9243 		wastuple = act->dta_intuple;
9244 	}
9245 
9246 	if ((act = ecb->dte_action) != NULL &&
9247 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9248 	    ecb->dte_size == sizeof (dtrace_epid_t)) {
9249 		/*
9250 		 * If the size is still sizeof (dtrace_epid_t), then all
9251 		 * actions store no data; set the size to 0.
9252 		 */
9253 		ecb->dte_alignment = maxalign;
9254 		ecb->dte_size = 0;
9255 
9256 		/*
9257 		 * If the needed space is still sizeof (dtrace_epid_t), then
9258 		 * all actions need no additional space; set the needed
9259 		 * size to 0.
9260 		 */
9261 		if (ecb->dte_needed == sizeof (dtrace_epid_t))
9262 			ecb->dte_needed = 0;
9263 
9264 		return;
9265 	}
9266 
9267 	/*
9268 	 * Set our alignment, and make sure that the dte_size and dte_needed
9269 	 * are aligned to the size of an EPID.
9270 	 */
9271 	ecb->dte_alignment = maxalign;
9272 	ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
9273 	    ~(sizeof (dtrace_epid_t) - 1);
9274 	ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
9275 	    ~(sizeof (dtrace_epid_t) - 1);
9276 	ASSERT(ecb->dte_size <= ecb->dte_needed);
9277 }
9278 
9279 static dtrace_action_t *
9280 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9281 {
9282 	dtrace_aggregation_t *agg;
9283 	size_t size = sizeof (uint64_t);
9284 	int ntuple = desc->dtad_ntuple;
9285 	dtrace_action_t *act;
9286 	dtrace_recdesc_t *frec;
9287 	dtrace_aggid_t aggid;
9288 	dtrace_state_t *state = ecb->dte_state;
9289 
9290 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
9291 	agg->dtag_ecb = ecb;
9292 
9293 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
9294 
9295 	switch (desc->dtad_kind) {
9296 	case DTRACEAGG_MIN:
9297 		agg->dtag_initial = INT64_MAX;
9298 		agg->dtag_aggregate = dtrace_aggregate_min;
9299 		break;
9300 
9301 	case DTRACEAGG_MAX:
9302 		agg->dtag_initial = INT64_MIN;
9303 		agg->dtag_aggregate = dtrace_aggregate_max;
9304 		break;
9305 
9306 	case DTRACEAGG_COUNT:
9307 		agg->dtag_aggregate = dtrace_aggregate_count;
9308 		break;
9309 
9310 	case DTRACEAGG_QUANTIZE:
9311 		agg->dtag_aggregate = dtrace_aggregate_quantize;
9312 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
9313 		    sizeof (uint64_t);
9314 		break;
9315 
9316 	case DTRACEAGG_LQUANTIZE: {
9317 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
9318 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
9319 
9320 		agg->dtag_initial = desc->dtad_arg;
9321 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
9322 
9323 		if (step == 0 || levels == 0)
9324 			goto err;
9325 
9326 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
9327 		break;
9328 	}
9329 
9330 	case DTRACEAGG_AVG:
9331 		agg->dtag_aggregate = dtrace_aggregate_avg;
9332 		size = sizeof (uint64_t) * 2;
9333 		break;
9334 
9335 	case DTRACEAGG_STDDEV:
9336 		agg->dtag_aggregate = dtrace_aggregate_stddev;
9337 		size = sizeof (uint64_t) * 4;
9338 		break;
9339 
9340 	case DTRACEAGG_SUM:
9341 		agg->dtag_aggregate = dtrace_aggregate_sum;
9342 		break;
9343 
9344 	default:
9345 		goto err;
9346 	}
9347 
9348 	agg->dtag_action.dta_rec.dtrd_size = size;
9349 
9350 	if (ntuple == 0)
9351 		goto err;
9352 
9353 	/*
9354 	 * We must make sure that we have enough actions for the n-tuple.
9355 	 */
9356 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
9357 		if (DTRACEACT_ISAGG(act->dta_kind))
9358 			break;
9359 
9360 		if (--ntuple == 0) {
9361 			/*
9362 			 * This is the action with which our n-tuple begins.
9363 			 */
9364 			agg->dtag_first = act;
9365 			goto success;
9366 		}
9367 	}
9368 
9369 	/*
9370 	 * This n-tuple is short by ntuple elements.  Return failure.
9371 	 */
9372 	ASSERT(ntuple != 0);
9373 err:
9374 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9375 	return (NULL);
9376 
9377 success:
9378 	/*
9379 	 * If the last action in the tuple has a size of zero, it's actually
9380 	 * an expression argument for the aggregating action.
9381 	 */
9382 	ASSERT(ecb->dte_action_last != NULL);
9383 	act = ecb->dte_action_last;
9384 
9385 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
9386 		ASSERT(act->dta_difo != NULL);
9387 
9388 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
9389 			agg->dtag_hasarg = 1;
9390 	}
9391 
9392 	/*
9393 	 * We need to allocate an id for this aggregation.
9394 	 */
9395 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
9396 	    VM_BESTFIT | VM_SLEEP);
9397 
9398 	if (aggid - 1 >= state->dts_naggregations) {
9399 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
9400 		dtrace_aggregation_t **aggs;
9401 		int naggs = state->dts_naggregations << 1;
9402 		int onaggs = state->dts_naggregations;
9403 
9404 		ASSERT(aggid == state->dts_naggregations + 1);
9405 
9406 		if (naggs == 0) {
9407 			ASSERT(oaggs == NULL);
9408 			naggs = 1;
9409 		}
9410 
9411 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
9412 
9413 		if (oaggs != NULL) {
9414 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
9415 			kmem_free(oaggs, onaggs * sizeof (*aggs));
9416 		}
9417 
9418 		state->dts_aggregations = aggs;
9419 		state->dts_naggregations = naggs;
9420 	}
9421 
9422 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
9423 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
9424 
9425 	frec = &agg->dtag_first->dta_rec;
9426 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
9427 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
9428 
9429 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
9430 		ASSERT(!act->dta_intuple);
9431 		act->dta_intuple = 1;
9432 	}
9433 
9434 	return (&agg->dtag_action);
9435 }
9436 
9437 static void
9438 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
9439 {
9440 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9441 	dtrace_state_t *state = ecb->dte_state;
9442 	dtrace_aggid_t aggid = agg->dtag_id;
9443 
9444 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
9445 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
9446 
9447 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
9448 	state->dts_aggregations[aggid - 1] = NULL;
9449 
9450 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9451 }
9452 
9453 static int
9454 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9455 {
9456 	dtrace_action_t *action, *last;
9457 	dtrace_difo_t *dp = desc->dtad_difo;
9458 	uint32_t size = 0, align = sizeof (uint8_t), mask;
9459 	uint16_t format = 0;
9460 	dtrace_recdesc_t *rec;
9461 	dtrace_state_t *state = ecb->dte_state;
9462 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
9463 	uint64_t arg = desc->dtad_arg;
9464 
9465 	ASSERT(MUTEX_HELD(&dtrace_lock));
9466 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
9467 
9468 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
9469 		/*
9470 		 * If this is an aggregating action, there must be neither
9471 		 * a speculate nor a commit on the action chain.
9472 		 */
9473 		dtrace_action_t *act;
9474 
9475 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9476 			if (act->dta_kind == DTRACEACT_COMMIT)
9477 				return (EINVAL);
9478 
9479 			if (act->dta_kind == DTRACEACT_SPECULATE)
9480 				return (EINVAL);
9481 		}
9482 
9483 		action = dtrace_ecb_aggregation_create(ecb, desc);
9484 
9485 		if (action == NULL)
9486 			return (EINVAL);
9487 	} else {
9488 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
9489 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
9490 		    dp != NULL && dp->dtdo_destructive)) {
9491 			state->dts_destructive = 1;
9492 		}
9493 
9494 		switch (desc->dtad_kind) {
9495 		case DTRACEACT_PRINTF:
9496 		case DTRACEACT_PRINTA:
9497 		case DTRACEACT_SYSTEM:
9498 		case DTRACEACT_FREOPEN:
9499 			/*
9500 			 * We know that our arg is a string -- turn it into a
9501 			 * format.
9502 			 */
9503 			if (arg == NULL) {
9504 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
9505 				format = 0;
9506 			} else {
9507 				ASSERT(arg != NULL);
9508 				ASSERT(arg > KERNELBASE);
9509 				format = dtrace_format_add(state,
9510 				    (char *)(uintptr_t)arg);
9511 			}
9512 
9513 			/*FALLTHROUGH*/
9514 		case DTRACEACT_LIBACT:
9515 		case DTRACEACT_DIFEXPR:
9516 			if (dp == NULL)
9517 				return (EINVAL);
9518 
9519 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
9520 				break;
9521 
9522 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
9523 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9524 					return (EINVAL);
9525 
9526 				size = opt[DTRACEOPT_STRSIZE];
9527 			}
9528 
9529 			break;
9530 
9531 		case DTRACEACT_STACK:
9532 			if ((nframes = arg) == 0) {
9533 				nframes = opt[DTRACEOPT_STACKFRAMES];
9534 				ASSERT(nframes > 0);
9535 				arg = nframes;
9536 			}
9537 
9538 			size = nframes * sizeof (pc_t);
9539 			break;
9540 
9541 		case DTRACEACT_JSTACK:
9542 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
9543 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
9544 
9545 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
9546 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
9547 
9548 			arg = DTRACE_USTACK_ARG(nframes, strsize);
9549 
9550 			/*FALLTHROUGH*/
9551 		case DTRACEACT_USTACK:
9552 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
9553 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
9554 				strsize = DTRACE_USTACK_STRSIZE(arg);
9555 				nframes = opt[DTRACEOPT_USTACKFRAMES];
9556 				ASSERT(nframes > 0);
9557 				arg = DTRACE_USTACK_ARG(nframes, strsize);
9558 			}
9559 
9560 			/*
9561 			 * Save a slot for the pid.
9562 			 */
9563 			size = (nframes + 1) * sizeof (uint64_t);
9564 			size += DTRACE_USTACK_STRSIZE(arg);
9565 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
9566 
9567 			break;
9568 
9569 		case DTRACEACT_SYM:
9570 		case DTRACEACT_MOD:
9571 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
9572 			    sizeof (uint64_t)) ||
9573 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9574 				return (EINVAL);
9575 			break;
9576 
9577 		case DTRACEACT_USYM:
9578 		case DTRACEACT_UMOD:
9579 		case DTRACEACT_UADDR:
9580 			if (dp == NULL ||
9581 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
9582 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9583 				return (EINVAL);
9584 
9585 			/*
9586 			 * We have a slot for the pid, plus a slot for the
9587 			 * argument.  To keep things simple (aligned with
9588 			 * bitness-neutral sizing), we store each as a 64-bit
9589 			 * quantity.
9590 			 */
9591 			size = 2 * sizeof (uint64_t);
9592 			break;
9593 
9594 		case DTRACEACT_STOP:
9595 		case DTRACEACT_BREAKPOINT:
9596 		case DTRACEACT_PANIC:
9597 			break;
9598 
9599 		case DTRACEACT_CHILL:
9600 		case DTRACEACT_DISCARD:
9601 		case DTRACEACT_RAISE:
9602 			if (dp == NULL)
9603 				return (EINVAL);
9604 			break;
9605 
9606 		case DTRACEACT_EXIT:
9607 			if (dp == NULL ||
9608 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
9609 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9610 				return (EINVAL);
9611 			break;
9612 
9613 		case DTRACEACT_SPECULATE:
9614 			if (ecb->dte_size > sizeof (dtrace_epid_t))
9615 				return (EINVAL);
9616 
9617 			if (dp == NULL)
9618 				return (EINVAL);
9619 
9620 			state->dts_speculates = 1;
9621 			break;
9622 
9623 		case DTRACEACT_COMMIT: {
9624 			dtrace_action_t *act = ecb->dte_action;
9625 
9626 			for (; act != NULL; act = act->dta_next) {
9627 				if (act->dta_kind == DTRACEACT_COMMIT)
9628 					return (EINVAL);
9629 			}
9630 
9631 			if (dp == NULL)
9632 				return (EINVAL);
9633 			break;
9634 		}
9635 
9636 		default:
9637 			return (EINVAL);
9638 		}
9639 
9640 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
9641 			/*
9642 			 * If this is a data-storing action or a speculate,
9643 			 * we must be sure that there isn't a commit on the
9644 			 * action chain.
9645 			 */
9646 			dtrace_action_t *act = ecb->dte_action;
9647 
9648 			for (; act != NULL; act = act->dta_next) {
9649 				if (act->dta_kind == DTRACEACT_COMMIT)
9650 					return (EINVAL);
9651 			}
9652 		}
9653 
9654 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
9655 		action->dta_rec.dtrd_size = size;
9656 	}
9657 
9658 	action->dta_refcnt = 1;
9659 	rec = &action->dta_rec;
9660 	size = rec->dtrd_size;
9661 
9662 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
9663 		if (!(size & mask)) {
9664 			align = mask + 1;
9665 			break;
9666 		}
9667 	}
9668 
9669 	action->dta_kind = desc->dtad_kind;
9670 
9671 	if ((action->dta_difo = dp) != NULL)
9672 		dtrace_difo_hold(dp);
9673 
9674 	rec->dtrd_action = action->dta_kind;
9675 	rec->dtrd_arg = arg;
9676 	rec->dtrd_uarg = desc->dtad_uarg;
9677 	rec->dtrd_alignment = (uint16_t)align;
9678 	rec->dtrd_format = format;
9679 
9680 	if ((last = ecb->dte_action_last) != NULL) {
9681 		ASSERT(ecb->dte_action != NULL);
9682 		action->dta_prev = last;
9683 		last->dta_next = action;
9684 	} else {
9685 		ASSERT(ecb->dte_action == NULL);
9686 		ecb->dte_action = action;
9687 	}
9688 
9689 	ecb->dte_action_last = action;
9690 
9691 	return (0);
9692 }
9693 
9694 static void
9695 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
9696 {
9697 	dtrace_action_t *act = ecb->dte_action, *next;
9698 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
9699 	dtrace_difo_t *dp;
9700 	uint16_t format;
9701 
9702 	if (act != NULL && act->dta_refcnt > 1) {
9703 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
9704 		act->dta_refcnt--;
9705 	} else {
9706 		for (; act != NULL; act = next) {
9707 			next = act->dta_next;
9708 			ASSERT(next != NULL || act == ecb->dte_action_last);
9709 			ASSERT(act->dta_refcnt == 1);
9710 
9711 			if ((format = act->dta_rec.dtrd_format) != 0)
9712 				dtrace_format_remove(ecb->dte_state, format);
9713 
9714 			if ((dp = act->dta_difo) != NULL)
9715 				dtrace_difo_release(dp, vstate);
9716 
9717 			if (DTRACEACT_ISAGG(act->dta_kind)) {
9718 				dtrace_ecb_aggregation_destroy(ecb, act);
9719 			} else {
9720 				kmem_free(act, sizeof (dtrace_action_t));
9721 			}
9722 		}
9723 	}
9724 
9725 	ecb->dte_action = NULL;
9726 	ecb->dte_action_last = NULL;
9727 	ecb->dte_size = sizeof (dtrace_epid_t);
9728 }
9729 
9730 static void
9731 dtrace_ecb_disable(dtrace_ecb_t *ecb)
9732 {
9733 	/*
9734 	 * We disable the ECB by removing it from its probe.
9735 	 */
9736 	dtrace_ecb_t *pecb, *prev = NULL;
9737 	dtrace_probe_t *probe = ecb->dte_probe;
9738 
9739 	ASSERT(MUTEX_HELD(&dtrace_lock));
9740 
9741 	if (probe == NULL) {
9742 		/*
9743 		 * This is the NULL probe; there is nothing to disable.
9744 		 */
9745 		return;
9746 	}
9747 
9748 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
9749 		if (pecb == ecb)
9750 			break;
9751 		prev = pecb;
9752 	}
9753 
9754 	ASSERT(pecb != NULL);
9755 
9756 	if (prev == NULL) {
9757 		probe->dtpr_ecb = ecb->dte_next;
9758 	} else {
9759 		prev->dte_next = ecb->dte_next;
9760 	}
9761 
9762 	if (ecb == probe->dtpr_ecb_last) {
9763 		ASSERT(ecb->dte_next == NULL);
9764 		probe->dtpr_ecb_last = prev;
9765 	}
9766 
9767 	/*
9768 	 * The ECB has been disconnected from the probe; now sync to assure
9769 	 * that all CPUs have seen the change before returning.
9770 	 */
9771 	dtrace_sync();
9772 
9773 	if (probe->dtpr_ecb == NULL) {
9774 		/*
9775 		 * That was the last ECB on the probe; clear the predicate
9776 		 * cache ID for the probe, disable it and sync one more time
9777 		 * to assure that we'll never hit it again.
9778 		 */
9779 		dtrace_provider_t *prov = probe->dtpr_provider;
9780 
9781 		ASSERT(ecb->dte_next == NULL);
9782 		ASSERT(probe->dtpr_ecb_last == NULL);
9783 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
9784 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
9785 		    probe->dtpr_id, probe->dtpr_arg);
9786 		dtrace_sync();
9787 	} else {
9788 		/*
9789 		 * There is at least one ECB remaining on the probe.  If there
9790 		 * is _exactly_ one, set the probe's predicate cache ID to be
9791 		 * the predicate cache ID of the remaining ECB.
9792 		 */
9793 		ASSERT(probe->dtpr_ecb_last != NULL);
9794 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
9795 
9796 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
9797 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
9798 
9799 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
9800 
9801 			if (p != NULL)
9802 				probe->dtpr_predcache = p->dtp_cacheid;
9803 		}
9804 
9805 		ecb->dte_next = NULL;
9806 	}
9807 }
9808 
9809 static void
9810 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
9811 {
9812 	dtrace_state_t *state = ecb->dte_state;
9813 	dtrace_vstate_t *vstate = &state->dts_vstate;
9814 	dtrace_predicate_t *pred;
9815 	dtrace_epid_t epid = ecb->dte_epid;
9816 
9817 	ASSERT(MUTEX_HELD(&dtrace_lock));
9818 	ASSERT(ecb->dte_next == NULL);
9819 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
9820 
9821 	if ((pred = ecb->dte_predicate) != NULL)
9822 		dtrace_predicate_release(pred, vstate);
9823 
9824 	dtrace_ecb_action_remove(ecb);
9825 
9826 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
9827 	state->dts_ecbs[epid - 1] = NULL;
9828 
9829 	kmem_free(ecb, sizeof (dtrace_ecb_t));
9830 }
9831 
9832 static dtrace_ecb_t *
9833 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
9834     dtrace_enabling_t *enab)
9835 {
9836 	dtrace_ecb_t *ecb;
9837 	dtrace_predicate_t *pred;
9838 	dtrace_actdesc_t *act;
9839 	dtrace_provider_t *prov;
9840 	dtrace_ecbdesc_t *desc = enab->dten_current;
9841 
9842 	ASSERT(MUTEX_HELD(&dtrace_lock));
9843 	ASSERT(state != NULL);
9844 
9845 	ecb = dtrace_ecb_add(state, probe);
9846 	ecb->dte_uarg = desc->dted_uarg;
9847 
9848 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
9849 		dtrace_predicate_hold(pred);
9850 		ecb->dte_predicate = pred;
9851 	}
9852 
9853 	if (probe != NULL) {
9854 		/*
9855 		 * If the provider shows more leg than the consumer is old
9856 		 * enough to see, we need to enable the appropriate implicit
9857 		 * predicate bits to prevent the ecb from activating at
9858 		 * revealing times.
9859 		 *
9860 		 * Providers specifying DTRACE_PRIV_USER at register time
9861 		 * are stating that they need the /proc-style privilege
9862 		 * model to be enforced, and this is what DTRACE_COND_OWNER
9863 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
9864 		 */
9865 		prov = probe->dtpr_provider;
9866 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
9867 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9868 			ecb->dte_cond |= DTRACE_COND_OWNER;
9869 
9870 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
9871 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9872 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
9873 
9874 		/*
9875 		 * If the provider shows us kernel innards and the user
9876 		 * is lacking sufficient privilege, enable the
9877 		 * DTRACE_COND_USERMODE implicit predicate.
9878 		 */
9879 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
9880 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
9881 			ecb->dte_cond |= DTRACE_COND_USERMODE;
9882 	}
9883 
9884 	if (dtrace_ecb_create_cache != NULL) {
9885 		/*
9886 		 * If we have a cached ecb, we'll use its action list instead
9887 		 * of creating our own (saving both time and space).
9888 		 */
9889 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
9890 		dtrace_action_t *act = cached->dte_action;
9891 
9892 		if (act != NULL) {
9893 			ASSERT(act->dta_refcnt > 0);
9894 			act->dta_refcnt++;
9895 			ecb->dte_action = act;
9896 			ecb->dte_action_last = cached->dte_action_last;
9897 			ecb->dte_needed = cached->dte_needed;
9898 			ecb->dte_size = cached->dte_size;
9899 			ecb->dte_alignment = cached->dte_alignment;
9900 		}
9901 
9902 		return (ecb);
9903 	}
9904 
9905 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
9906 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
9907 			dtrace_ecb_destroy(ecb);
9908 			return (NULL);
9909 		}
9910 	}
9911 
9912 	dtrace_ecb_resize(ecb);
9913 
9914 	return (dtrace_ecb_create_cache = ecb);
9915 }
9916 
9917 static int
9918 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
9919 {
9920 	dtrace_ecb_t *ecb;
9921 	dtrace_enabling_t *enab = arg;
9922 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
9923 
9924 	ASSERT(state != NULL);
9925 
9926 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
9927 		/*
9928 		 * This probe was created in a generation for which this
9929 		 * enabling has previously created ECBs; we don't want to
9930 		 * enable it again, so just kick out.
9931 		 */
9932 		return (DTRACE_MATCH_NEXT);
9933 	}
9934 
9935 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
9936 		return (DTRACE_MATCH_DONE);
9937 
9938 	if (dtrace_ecb_enable(ecb) < 0)
9939 		return (DTRACE_MATCH_FAIL);
9940 
9941 	return (DTRACE_MATCH_NEXT);
9942 }
9943 
9944 static dtrace_ecb_t *
9945 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
9946 {
9947 	dtrace_ecb_t *ecb;
9948 
9949 	ASSERT(MUTEX_HELD(&dtrace_lock));
9950 
9951 	if (id == 0 || id > state->dts_necbs)
9952 		return (NULL);
9953 
9954 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
9955 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
9956 
9957 	return (state->dts_ecbs[id - 1]);
9958 }
9959 
9960 static dtrace_aggregation_t *
9961 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
9962 {
9963 	dtrace_aggregation_t *agg;
9964 
9965 	ASSERT(MUTEX_HELD(&dtrace_lock));
9966 
9967 	if (id == 0 || id > state->dts_naggregations)
9968 		return (NULL);
9969 
9970 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
9971 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
9972 	    agg->dtag_id == id);
9973 
9974 	return (state->dts_aggregations[id - 1]);
9975 }
9976 
9977 /*
9978  * DTrace Buffer Functions
9979  *
9980  * The following functions manipulate DTrace buffers.  Most of these functions
9981  * are called in the context of establishing or processing consumer state;
9982  * exceptions are explicitly noted.
9983  */
9984 
9985 /*
9986  * Note:  called from cross call context.  This function switches the two
9987  * buffers on a given CPU.  The atomicity of this operation is assured by
9988  * disabling interrupts while the actual switch takes place; the disabling of
9989  * interrupts serializes the execution with any execution of dtrace_probe() on
9990  * the same CPU.
9991  */
9992 static void
9993 dtrace_buffer_switch(dtrace_buffer_t *buf)
9994 {
9995 	caddr_t tomax = buf->dtb_tomax;
9996 	caddr_t xamot = buf->dtb_xamot;
9997 	dtrace_icookie_t cookie;
9998 
9999 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10000 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
10001 
10002 	cookie = dtrace_interrupt_disable();
10003 	buf->dtb_tomax = xamot;
10004 	buf->dtb_xamot = tomax;
10005 	buf->dtb_xamot_drops = buf->dtb_drops;
10006 	buf->dtb_xamot_offset = buf->dtb_offset;
10007 	buf->dtb_xamot_errors = buf->dtb_errors;
10008 	buf->dtb_xamot_flags = buf->dtb_flags;
10009 	buf->dtb_offset = 0;
10010 	buf->dtb_drops = 0;
10011 	buf->dtb_errors = 0;
10012 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
10013 	dtrace_interrupt_enable(cookie);
10014 }
10015 
10016 /*
10017  * Note:  called from cross call context.  This function activates a buffer
10018  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
10019  * is guaranteed by the disabling of interrupts.
10020  */
10021 static void
10022 dtrace_buffer_activate(dtrace_state_t *state)
10023 {
10024 	dtrace_buffer_t *buf;
10025 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
10026 
10027 	buf = &state->dts_buffer[CPU->cpu_id];
10028 
10029 	if (buf->dtb_tomax != NULL) {
10030 		/*
10031 		 * We might like to assert that the buffer is marked inactive,
10032 		 * but this isn't necessarily true:  the buffer for the CPU
10033 		 * that processes the BEGIN probe has its buffer activated
10034 		 * manually.  In this case, we take the (harmless) action
10035 		 * re-clearing the bit INACTIVE bit.
10036 		 */
10037 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
10038 	}
10039 
10040 	dtrace_interrupt_enable(cookie);
10041 }
10042 
10043 static int
10044 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
10045     processorid_t cpu)
10046 {
10047 	cpu_t *cp;
10048 	dtrace_buffer_t *buf;
10049 
10050 	ASSERT(MUTEX_HELD(&cpu_lock));
10051 	ASSERT(MUTEX_HELD(&dtrace_lock));
10052 
10053 	if (size > dtrace_nonroot_maxsize &&
10054 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
10055 		return (EFBIG);
10056 
10057 	cp = cpu_list;
10058 
10059 	do {
10060 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10061 			continue;
10062 
10063 		buf = &bufs[cp->cpu_id];
10064 
10065 		/*
10066 		 * If there is already a buffer allocated for this CPU, it
10067 		 * is only possible that this is a DR event.  In this case,
10068 		 * the buffer size must match our specified size.
10069 		 */
10070 		if (buf->dtb_tomax != NULL) {
10071 			ASSERT(buf->dtb_size == size);
10072 			continue;
10073 		}
10074 
10075 		ASSERT(buf->dtb_xamot == NULL);
10076 
10077 		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10078 			goto err;
10079 
10080 		buf->dtb_size = size;
10081 		buf->dtb_flags = flags;
10082 		buf->dtb_offset = 0;
10083 		buf->dtb_drops = 0;
10084 
10085 		if (flags & DTRACEBUF_NOSWITCH)
10086 			continue;
10087 
10088 		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
10089 			goto err;
10090 	} while ((cp = cp->cpu_next) != cpu_list);
10091 
10092 	return (0);
10093 
10094 err:
10095 	cp = cpu_list;
10096 
10097 	do {
10098 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
10099 			continue;
10100 
10101 		buf = &bufs[cp->cpu_id];
10102 
10103 		if (buf->dtb_xamot != NULL) {
10104 			ASSERT(buf->dtb_tomax != NULL);
10105 			ASSERT(buf->dtb_size == size);
10106 			kmem_free(buf->dtb_xamot, size);
10107 		}
10108 
10109 		if (buf->dtb_tomax != NULL) {
10110 			ASSERT(buf->dtb_size == size);
10111 			kmem_free(buf->dtb_tomax, size);
10112 		}
10113 
10114 		buf->dtb_tomax = NULL;
10115 		buf->dtb_xamot = NULL;
10116 		buf->dtb_size = 0;
10117 	} while ((cp = cp->cpu_next) != cpu_list);
10118 
10119 	return (ENOMEM);
10120 }
10121 
10122 /*
10123  * Note:  called from probe context.  This function just increments the drop
10124  * count on a buffer.  It has been made a function to allow for the
10125  * possibility of understanding the source of mysterious drop counts.  (A
10126  * problem for which one may be particularly disappointed that DTrace cannot
10127  * be used to understand DTrace.)
10128  */
10129 static void
10130 dtrace_buffer_drop(dtrace_buffer_t *buf)
10131 {
10132 	buf->dtb_drops++;
10133 }
10134 
10135 /*
10136  * Note:  called from probe context.  This function is called to reserve space
10137  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
10138  * mstate.  Returns the new offset in the buffer, or a negative value if an
10139  * error has occurred.
10140  */
10141 static intptr_t
10142 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
10143     dtrace_state_t *state, dtrace_mstate_t *mstate)
10144 {
10145 	intptr_t offs = buf->dtb_offset, soffs;
10146 	intptr_t woffs;
10147 	caddr_t tomax;
10148 	size_t total;
10149 
10150 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
10151 		return (-1);
10152 
10153 	if ((tomax = buf->dtb_tomax) == NULL) {
10154 		dtrace_buffer_drop(buf);
10155 		return (-1);
10156 	}
10157 
10158 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
10159 		while (offs & (align - 1)) {
10160 			/*
10161 			 * Assert that our alignment is off by a number which
10162 			 * is itself sizeof (uint32_t) aligned.
10163 			 */
10164 			ASSERT(!((align - (offs & (align - 1))) &
10165 			    (sizeof (uint32_t) - 1)));
10166 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10167 			offs += sizeof (uint32_t);
10168 		}
10169 
10170 		if ((soffs = offs + needed) > buf->dtb_size) {
10171 			dtrace_buffer_drop(buf);
10172 			return (-1);
10173 		}
10174 
10175 		if (mstate == NULL)
10176 			return (offs);
10177 
10178 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
10179 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
10180 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10181 
10182 		return (offs);
10183 	}
10184 
10185 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10186 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
10187 		    (buf->dtb_flags & DTRACEBUF_FULL))
10188 			return (-1);
10189 		goto out;
10190 	}
10191 
10192 	total = needed + (offs & (align - 1));
10193 
10194 	/*
10195 	 * For a ring buffer, life is quite a bit more complicated.  Before
10196 	 * we can store any padding, we need to adjust our wrapping offset.
10197 	 * (If we've never before wrapped or we're not about to, no adjustment
10198 	 * is required.)
10199 	 */
10200 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
10201 	    offs + total > buf->dtb_size) {
10202 		woffs = buf->dtb_xamot_offset;
10203 
10204 		if (offs + total > buf->dtb_size) {
10205 			/*
10206 			 * We can't fit in the end of the buffer.  First, a
10207 			 * sanity check that we can fit in the buffer at all.
10208 			 */
10209 			if (total > buf->dtb_size) {
10210 				dtrace_buffer_drop(buf);
10211 				return (-1);
10212 			}
10213 
10214 			/*
10215 			 * We're going to be storing at the top of the buffer,
10216 			 * so now we need to deal with the wrapped offset.  We
10217 			 * only reset our wrapped offset to 0 if it is
10218 			 * currently greater than the current offset.  If it
10219 			 * is less than the current offset, it is because a
10220 			 * previous allocation induced a wrap -- but the
10221 			 * allocation didn't subsequently take the space due
10222 			 * to an error or false predicate evaluation.  In this
10223 			 * case, we'll just leave the wrapped offset alone: if
10224 			 * the wrapped offset hasn't been advanced far enough
10225 			 * for this allocation, it will be adjusted in the
10226 			 * lower loop.
10227 			 */
10228 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
10229 				if (woffs >= offs)
10230 					woffs = 0;
10231 			} else {
10232 				woffs = 0;
10233 			}
10234 
10235 			/*
10236 			 * Now we know that we're going to be storing to the
10237 			 * top of the buffer and that there is room for us
10238 			 * there.  We need to clear the buffer from the current
10239 			 * offset to the end (there may be old gunk there).
10240 			 */
10241 			while (offs < buf->dtb_size)
10242 				tomax[offs++] = 0;
10243 
10244 			/*
10245 			 * We need to set our offset to zero.  And because we
10246 			 * are wrapping, we need to set the bit indicating as
10247 			 * much.  We can also adjust our needed space back
10248 			 * down to the space required by the ECB -- we know
10249 			 * that the top of the buffer is aligned.
10250 			 */
10251 			offs = 0;
10252 			total = needed;
10253 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
10254 		} else {
10255 			/*
10256 			 * There is room for us in the buffer, so we simply
10257 			 * need to check the wrapped offset.
10258 			 */
10259 			if (woffs < offs) {
10260 				/*
10261 				 * The wrapped offset is less than the offset.
10262 				 * This can happen if we allocated buffer space
10263 				 * that induced a wrap, but then we didn't
10264 				 * subsequently take the space due to an error
10265 				 * or false predicate evaluation.  This is
10266 				 * okay; we know that _this_ allocation isn't
10267 				 * going to induce a wrap.  We still can't
10268 				 * reset the wrapped offset to be zero,
10269 				 * however: the space may have been trashed in
10270 				 * the previous failed probe attempt.  But at
10271 				 * least the wrapped offset doesn't need to
10272 				 * be adjusted at all...
10273 				 */
10274 				goto out;
10275 			}
10276 		}
10277 
10278 		while (offs + total > woffs) {
10279 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
10280 			size_t size;
10281 
10282 			if (epid == DTRACE_EPIDNONE) {
10283 				size = sizeof (uint32_t);
10284 			} else {
10285 				ASSERT(epid <= state->dts_necbs);
10286 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
10287 
10288 				size = state->dts_ecbs[epid - 1]->dte_size;
10289 			}
10290 
10291 			ASSERT(woffs + size <= buf->dtb_size);
10292 			ASSERT(size != 0);
10293 
10294 			if (woffs + size == buf->dtb_size) {
10295 				/*
10296 				 * We've reached the end of the buffer; we want
10297 				 * to set the wrapped offset to 0 and break
10298 				 * out.  However, if the offs is 0, then we're
10299 				 * in a strange edge-condition:  the amount of
10300 				 * space that we want to reserve plus the size
10301 				 * of the record that we're overwriting is
10302 				 * greater than the size of the buffer.  This
10303 				 * is problematic because if we reserve the
10304 				 * space but subsequently don't consume it (due
10305 				 * to a failed predicate or error) the wrapped
10306 				 * offset will be 0 -- yet the EPID at offset 0
10307 				 * will not be committed.  This situation is
10308 				 * relatively easy to deal with:  if we're in
10309 				 * this case, the buffer is indistinguishable
10310 				 * from one that hasn't wrapped; we need only
10311 				 * finish the job by clearing the wrapped bit,
10312 				 * explicitly setting the offset to be 0, and
10313 				 * zero'ing out the old data in the buffer.
10314 				 */
10315 				if (offs == 0) {
10316 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
10317 					buf->dtb_offset = 0;
10318 					woffs = total;
10319 
10320 					while (woffs < buf->dtb_size)
10321 						tomax[woffs++] = 0;
10322 				}
10323 
10324 				woffs = 0;
10325 				break;
10326 			}
10327 
10328 			woffs += size;
10329 		}
10330 
10331 		/*
10332 		 * We have a wrapped offset.  It may be that the wrapped offset
10333 		 * has become zero -- that's okay.
10334 		 */
10335 		buf->dtb_xamot_offset = woffs;
10336 	}
10337 
10338 out:
10339 	/*
10340 	 * Now we can plow the buffer with any necessary padding.
10341 	 */
10342 	while (offs & (align - 1)) {
10343 		/*
10344 		 * Assert that our alignment is off by a number which
10345 		 * is itself sizeof (uint32_t) aligned.
10346 		 */
10347 		ASSERT(!((align - (offs & (align - 1))) &
10348 		    (sizeof (uint32_t) - 1)));
10349 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10350 		offs += sizeof (uint32_t);
10351 	}
10352 
10353 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10354 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
10355 			buf->dtb_flags |= DTRACEBUF_FULL;
10356 			return (-1);
10357 		}
10358 	}
10359 
10360 	if (mstate == NULL)
10361 		return (offs);
10362 
10363 	/*
10364 	 * For ring buffers and fill buffers, the scratch space is always
10365 	 * the inactive buffer.
10366 	 */
10367 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
10368 	mstate->dtms_scratch_size = buf->dtb_size;
10369 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10370 
10371 	return (offs);
10372 }
10373 
10374 static void
10375 dtrace_buffer_polish(dtrace_buffer_t *buf)
10376 {
10377 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
10378 	ASSERT(MUTEX_HELD(&dtrace_lock));
10379 
10380 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
10381 		return;
10382 
10383 	/*
10384 	 * We need to polish the ring buffer.  There are three cases:
10385 	 *
10386 	 * - The first (and presumably most common) is that there is no gap
10387 	 *   between the buffer offset and the wrapped offset.  In this case,
10388 	 *   there is nothing in the buffer that isn't valid data; we can
10389 	 *   mark the buffer as polished and return.
10390 	 *
10391 	 * - The second (less common than the first but still more common
10392 	 *   than the third) is that there is a gap between the buffer offset
10393 	 *   and the wrapped offset, and the wrapped offset is larger than the
10394 	 *   buffer offset.  This can happen because of an alignment issue, or
10395 	 *   can happen because of a call to dtrace_buffer_reserve() that
10396 	 *   didn't subsequently consume the buffer space.  In this case,
10397 	 *   we need to zero the data from the buffer offset to the wrapped
10398 	 *   offset.
10399 	 *
10400 	 * - The third (and least common) is that there is a gap between the
10401 	 *   buffer offset and the wrapped offset, but the wrapped offset is
10402 	 *   _less_ than the buffer offset.  This can only happen because a
10403 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
10404 	 *   was not subsequently consumed.  In this case, we need to zero the
10405 	 *   space from the offset to the end of the buffer _and_ from the
10406 	 *   top of the buffer to the wrapped offset.
10407 	 */
10408 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
10409 		bzero(buf->dtb_tomax + buf->dtb_offset,
10410 		    buf->dtb_xamot_offset - buf->dtb_offset);
10411 	}
10412 
10413 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
10414 		bzero(buf->dtb_tomax + buf->dtb_offset,
10415 		    buf->dtb_size - buf->dtb_offset);
10416 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
10417 	}
10418 }
10419 
10420 static void
10421 dtrace_buffer_free(dtrace_buffer_t *bufs)
10422 {
10423 	int i;
10424 
10425 	for (i = 0; i < NCPU; i++) {
10426 		dtrace_buffer_t *buf = &bufs[i];
10427 
10428 		if (buf->dtb_tomax == NULL) {
10429 			ASSERT(buf->dtb_xamot == NULL);
10430 			ASSERT(buf->dtb_size == 0);
10431 			continue;
10432 		}
10433 
10434 		if (buf->dtb_xamot != NULL) {
10435 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10436 			kmem_free(buf->dtb_xamot, buf->dtb_size);
10437 		}
10438 
10439 		kmem_free(buf->dtb_tomax, buf->dtb_size);
10440 		buf->dtb_size = 0;
10441 		buf->dtb_tomax = NULL;
10442 		buf->dtb_xamot = NULL;
10443 	}
10444 }
10445 
10446 /*
10447  * DTrace Enabling Functions
10448  */
10449 static dtrace_enabling_t *
10450 dtrace_enabling_create(dtrace_vstate_t *vstate)
10451 {
10452 	dtrace_enabling_t *enab;
10453 
10454 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
10455 	enab->dten_vstate = vstate;
10456 
10457 	return (enab);
10458 }
10459 
10460 static void
10461 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
10462 {
10463 	dtrace_ecbdesc_t **ndesc;
10464 	size_t osize, nsize;
10465 
10466 	/*
10467 	 * We can't add to enablings after we've enabled them, or after we've
10468 	 * retained them.
10469 	 */
10470 	ASSERT(enab->dten_probegen == 0);
10471 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10472 
10473 	if (enab->dten_ndesc < enab->dten_maxdesc) {
10474 		enab->dten_desc[enab->dten_ndesc++] = ecb;
10475 		return;
10476 	}
10477 
10478 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10479 
10480 	if (enab->dten_maxdesc == 0) {
10481 		enab->dten_maxdesc = 1;
10482 	} else {
10483 		enab->dten_maxdesc <<= 1;
10484 	}
10485 
10486 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
10487 
10488 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10489 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
10490 	bcopy(enab->dten_desc, ndesc, osize);
10491 	kmem_free(enab->dten_desc, osize);
10492 
10493 	enab->dten_desc = ndesc;
10494 	enab->dten_desc[enab->dten_ndesc++] = ecb;
10495 }
10496 
10497 static void
10498 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
10499     dtrace_probedesc_t *pd)
10500 {
10501 	dtrace_ecbdesc_t *new;
10502 	dtrace_predicate_t *pred;
10503 	dtrace_actdesc_t *act;
10504 
10505 	/*
10506 	 * We're going to create a new ECB description that matches the
10507 	 * specified ECB in every way, but has the specified probe description.
10508 	 */
10509 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
10510 
10511 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
10512 		dtrace_predicate_hold(pred);
10513 
10514 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
10515 		dtrace_actdesc_hold(act);
10516 
10517 	new->dted_action = ecb->dted_action;
10518 	new->dted_pred = ecb->dted_pred;
10519 	new->dted_probe = *pd;
10520 	new->dted_uarg = ecb->dted_uarg;
10521 
10522 	dtrace_enabling_add(enab, new);
10523 }
10524 
10525 static void
10526 dtrace_enabling_dump(dtrace_enabling_t *enab)
10527 {
10528 	int i;
10529 
10530 	for (i = 0; i < enab->dten_ndesc; i++) {
10531 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
10532 
10533 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
10534 		    desc->dtpd_provider, desc->dtpd_mod,
10535 		    desc->dtpd_func, desc->dtpd_name);
10536 	}
10537 }
10538 
10539 static void
10540 dtrace_enabling_destroy(dtrace_enabling_t *enab)
10541 {
10542 	int i;
10543 	dtrace_ecbdesc_t *ep;
10544 	dtrace_vstate_t *vstate = enab->dten_vstate;
10545 
10546 	ASSERT(MUTEX_HELD(&dtrace_lock));
10547 
10548 	for (i = 0; i < enab->dten_ndesc; i++) {
10549 		dtrace_actdesc_t *act, *next;
10550 		dtrace_predicate_t *pred;
10551 
10552 		ep = enab->dten_desc[i];
10553 
10554 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
10555 			dtrace_predicate_release(pred, vstate);
10556 
10557 		for (act = ep->dted_action; act != NULL; act = next) {
10558 			next = act->dtad_next;
10559 			dtrace_actdesc_release(act, vstate);
10560 		}
10561 
10562 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
10563 	}
10564 
10565 	kmem_free(enab->dten_desc,
10566 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
10567 
10568 	/*
10569 	 * If this was a retained enabling, decrement the dts_nretained count
10570 	 * and take it off of the dtrace_retained list.
10571 	 */
10572 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
10573 	    dtrace_retained == enab) {
10574 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10575 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
10576 		enab->dten_vstate->dtvs_state->dts_nretained--;
10577 		dtrace_retained_gen++;
10578 	}
10579 
10580 	if (enab->dten_prev == NULL) {
10581 		if (dtrace_retained == enab) {
10582 			dtrace_retained = enab->dten_next;
10583 
10584 			if (dtrace_retained != NULL)
10585 				dtrace_retained->dten_prev = NULL;
10586 		}
10587 	} else {
10588 		ASSERT(enab != dtrace_retained);
10589 		ASSERT(dtrace_retained != NULL);
10590 		enab->dten_prev->dten_next = enab->dten_next;
10591 	}
10592 
10593 	if (enab->dten_next != NULL) {
10594 		ASSERT(dtrace_retained != NULL);
10595 		enab->dten_next->dten_prev = enab->dten_prev;
10596 	}
10597 
10598 	kmem_free(enab, sizeof (dtrace_enabling_t));
10599 }
10600 
10601 static int
10602 dtrace_enabling_retain(dtrace_enabling_t *enab)
10603 {
10604 	dtrace_state_t *state;
10605 
10606 	ASSERT(MUTEX_HELD(&dtrace_lock));
10607 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10608 	ASSERT(enab->dten_vstate != NULL);
10609 
10610 	state = enab->dten_vstate->dtvs_state;
10611 	ASSERT(state != NULL);
10612 
10613 	/*
10614 	 * We only allow each state to retain dtrace_retain_max enablings.
10615 	 */
10616 	if (state->dts_nretained >= dtrace_retain_max)
10617 		return (ENOSPC);
10618 
10619 	state->dts_nretained++;
10620 	dtrace_retained_gen++;
10621 
10622 	if (dtrace_retained == NULL) {
10623 		dtrace_retained = enab;
10624 		return (0);
10625 	}
10626 
10627 	enab->dten_next = dtrace_retained;
10628 	dtrace_retained->dten_prev = enab;
10629 	dtrace_retained = enab;
10630 
10631 	return (0);
10632 }
10633 
10634 static int
10635 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
10636     dtrace_probedesc_t *create)
10637 {
10638 	dtrace_enabling_t *new, *enab;
10639 	int found = 0, err = ENOENT;
10640 
10641 	ASSERT(MUTEX_HELD(&dtrace_lock));
10642 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
10643 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
10644 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
10645 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
10646 
10647 	new = dtrace_enabling_create(&state->dts_vstate);
10648 
10649 	/*
10650 	 * Iterate over all retained enablings, looking for enablings that
10651 	 * match the specified state.
10652 	 */
10653 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10654 		int i;
10655 
10656 		/*
10657 		 * dtvs_state can only be NULL for helper enablings -- and
10658 		 * helper enablings can't be retained.
10659 		 */
10660 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10661 
10662 		if (enab->dten_vstate->dtvs_state != state)
10663 			continue;
10664 
10665 		/*
10666 		 * Now iterate over each probe description; we're looking for
10667 		 * an exact match to the specified probe description.
10668 		 */
10669 		for (i = 0; i < enab->dten_ndesc; i++) {
10670 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
10671 			dtrace_probedesc_t *pd = &ep->dted_probe;
10672 
10673 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
10674 				continue;
10675 
10676 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
10677 				continue;
10678 
10679 			if (strcmp(pd->dtpd_func, match->dtpd_func))
10680 				continue;
10681 
10682 			if (strcmp(pd->dtpd_name, match->dtpd_name))
10683 				continue;
10684 
10685 			/*
10686 			 * We have a winning probe!  Add it to our growing
10687 			 * enabling.
10688 			 */
10689 			found = 1;
10690 			dtrace_enabling_addlike(new, ep, create);
10691 		}
10692 	}
10693 
10694 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
10695 		dtrace_enabling_destroy(new);
10696 		return (err);
10697 	}
10698 
10699 	return (0);
10700 }
10701 
10702 static void
10703 dtrace_enabling_retract(dtrace_state_t *state)
10704 {
10705 	dtrace_enabling_t *enab, *next;
10706 
10707 	ASSERT(MUTEX_HELD(&dtrace_lock));
10708 
10709 	/*
10710 	 * Iterate over all retained enablings, destroy the enablings retained
10711 	 * for the specified state.
10712 	 */
10713 	for (enab = dtrace_retained; enab != NULL; enab = next) {
10714 		next = enab->dten_next;
10715 
10716 		/*
10717 		 * dtvs_state can only be NULL for helper enablings -- and
10718 		 * helper enablings can't be retained.
10719 		 */
10720 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10721 
10722 		if (enab->dten_vstate->dtvs_state == state) {
10723 			ASSERT(state->dts_nretained > 0);
10724 			dtrace_enabling_destroy(enab);
10725 		}
10726 	}
10727 
10728 	ASSERT(state->dts_nretained == 0);
10729 }
10730 
10731 static int
10732 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
10733 {
10734 	int i = 0;
10735 	int total_matched = 0, matched = 0;
10736 
10737 	ASSERT(MUTEX_HELD(&cpu_lock));
10738 	ASSERT(MUTEX_HELD(&dtrace_lock));
10739 
10740 	for (i = 0; i < enab->dten_ndesc; i++) {
10741 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
10742 
10743 		enab->dten_current = ep;
10744 		enab->dten_error = 0;
10745 
10746 		/*
10747 		 * If a provider failed to enable a probe then get out and
10748 		 * let the consumer know we failed.
10749 		 */
10750 		if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
10751 			return (EBUSY);
10752 
10753 		total_matched += matched;
10754 
10755 		if (enab->dten_error != 0) {
10756 			/*
10757 			 * If we get an error half-way through enabling the
10758 			 * probes, we kick out -- perhaps with some number of
10759 			 * them enabled.  Leaving enabled probes enabled may
10760 			 * be slightly confusing for user-level, but we expect
10761 			 * that no one will attempt to actually drive on in
10762 			 * the face of such errors.  If this is an anonymous
10763 			 * enabling (indicated with a NULL nmatched pointer),
10764 			 * we cmn_err() a message.  We aren't expecting to
10765 			 * get such an error -- such as it can exist at all,
10766 			 * it would be a result of corrupted DOF in the driver
10767 			 * properties.
10768 			 */
10769 			if (nmatched == NULL) {
10770 				cmn_err(CE_WARN, "dtrace_enabling_match() "
10771 				    "error on %p: %d", (void *)ep,
10772 				    enab->dten_error);
10773 			}
10774 
10775 			return (enab->dten_error);
10776 		}
10777 	}
10778 
10779 	enab->dten_probegen = dtrace_probegen;
10780 	if (nmatched != NULL)
10781 		*nmatched = total_matched;
10782 
10783 	return (0);
10784 }
10785 
10786 static void
10787 dtrace_enabling_matchall(void)
10788 {
10789 	dtrace_enabling_t *enab;
10790 
10791 	mutex_enter(&cpu_lock);
10792 	mutex_enter(&dtrace_lock);
10793 
10794 	/*
10795 	 * Iterate over all retained enablings to see if any probes match
10796 	 * against them.  We only perform this operation on enablings for which
10797 	 * we have sufficient permissions by virtue of being in the global zone
10798 	 * or in the same zone as the DTrace client.  Because we can be called
10799 	 * after dtrace_detach() has been called, we cannot assert that there
10800 	 * are retained enablings.  We can safely load from dtrace_retained,
10801 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
10802 	 * block pending our completion.
10803 	 */
10804 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10805 		cred_t *cr = enab->dten_vstate->dtvs_state->dts_cred.dcr_cred;
10806 
10807 		if (INGLOBALZONE(curproc) ||
10808 		    cr != NULL && getzoneid() == crgetzoneid(cr))
10809 			(void) dtrace_enabling_match(enab, NULL);
10810 	}
10811 
10812 	mutex_exit(&dtrace_lock);
10813 	mutex_exit(&cpu_lock);
10814 }
10815 
10816 /*
10817  * If an enabling is to be enabled without having matched probes (that is, if
10818  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
10819  * enabling must be _primed_ by creating an ECB for every ECB description.
10820  * This must be done to assure that we know the number of speculations, the
10821  * number of aggregations, the minimum buffer size needed, etc. before we
10822  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
10823  * enabling any probes, we create ECBs for every ECB decription, but with a
10824  * NULL probe -- which is exactly what this function does.
10825  */
10826 static void
10827 dtrace_enabling_prime(dtrace_state_t *state)
10828 {
10829 	dtrace_enabling_t *enab;
10830 	int i;
10831 
10832 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10833 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10834 
10835 		if (enab->dten_vstate->dtvs_state != state)
10836 			continue;
10837 
10838 		/*
10839 		 * We don't want to prime an enabling more than once, lest
10840 		 * we allow a malicious user to induce resource exhaustion.
10841 		 * (The ECBs that result from priming an enabling aren't
10842 		 * leaked -- but they also aren't deallocated until the
10843 		 * consumer state is destroyed.)
10844 		 */
10845 		if (enab->dten_primed)
10846 			continue;
10847 
10848 		for (i = 0; i < enab->dten_ndesc; i++) {
10849 			enab->dten_current = enab->dten_desc[i];
10850 			(void) dtrace_probe_enable(NULL, enab);
10851 		}
10852 
10853 		enab->dten_primed = 1;
10854 	}
10855 }
10856 
10857 /*
10858  * Called to indicate that probes should be provided due to retained
10859  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
10860  * must take an initial lap through the enabling calling the dtps_provide()
10861  * entry point explicitly to allow for autocreated probes.
10862  */
10863 static void
10864 dtrace_enabling_provide(dtrace_provider_t *prv)
10865 {
10866 	int i, all = 0;
10867 	dtrace_probedesc_t desc;
10868 	dtrace_genid_t gen;
10869 
10870 	ASSERT(MUTEX_HELD(&dtrace_lock));
10871 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
10872 
10873 	if (prv == NULL) {
10874 		all = 1;
10875 		prv = dtrace_provider;
10876 	}
10877 
10878 	do {
10879 		dtrace_enabling_t *enab;
10880 		void *parg = prv->dtpv_arg;
10881 
10882 retry:
10883 		gen = dtrace_retained_gen;
10884 		for (enab = dtrace_retained; enab != NULL;
10885 		    enab = enab->dten_next) {
10886 			for (i = 0; i < enab->dten_ndesc; i++) {
10887 				desc = enab->dten_desc[i]->dted_probe;
10888 				mutex_exit(&dtrace_lock);
10889 				prv->dtpv_pops.dtps_provide(parg, &desc);
10890 				mutex_enter(&dtrace_lock);
10891 				/*
10892 				 * Process the retained enablings again if
10893 				 * they have changed while we weren't holding
10894 				 * dtrace_lock.
10895 				 */
10896 				if (gen != dtrace_retained_gen)
10897 					goto retry;
10898 			}
10899 		}
10900 	} while (all && (prv = prv->dtpv_next) != NULL);
10901 
10902 	mutex_exit(&dtrace_lock);
10903 	dtrace_probe_provide(NULL, all ? NULL : prv);
10904 	mutex_enter(&dtrace_lock);
10905 }
10906 
10907 /*
10908  * DTrace DOF Functions
10909  */
10910 /*ARGSUSED*/
10911 static void
10912 dtrace_dof_error(dof_hdr_t *dof, const char *str)
10913 {
10914 	if (dtrace_err_verbose)
10915 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
10916 
10917 #ifdef DTRACE_ERRDEBUG
10918 	dtrace_errdebug(str);
10919 #endif
10920 }
10921 
10922 /*
10923  * Create DOF out of a currently enabled state.  Right now, we only create
10924  * DOF containing the run-time options -- but this could be expanded to create
10925  * complete DOF representing the enabled state.
10926  */
10927 static dof_hdr_t *
10928 dtrace_dof_create(dtrace_state_t *state)
10929 {
10930 	dof_hdr_t *dof;
10931 	dof_sec_t *sec;
10932 	dof_optdesc_t *opt;
10933 	int i, len = sizeof (dof_hdr_t) +
10934 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
10935 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10936 
10937 	ASSERT(MUTEX_HELD(&dtrace_lock));
10938 
10939 	dof = kmem_zalloc(len, KM_SLEEP);
10940 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
10941 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
10942 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
10943 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
10944 
10945 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
10946 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
10947 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
10948 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
10949 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
10950 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
10951 
10952 	dof->dofh_flags = 0;
10953 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
10954 	dof->dofh_secsize = sizeof (dof_sec_t);
10955 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
10956 	dof->dofh_secoff = sizeof (dof_hdr_t);
10957 	dof->dofh_loadsz = len;
10958 	dof->dofh_filesz = len;
10959 	dof->dofh_pad = 0;
10960 
10961 	/*
10962 	 * Fill in the option section header...
10963 	 */
10964 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
10965 	sec->dofs_type = DOF_SECT_OPTDESC;
10966 	sec->dofs_align = sizeof (uint64_t);
10967 	sec->dofs_flags = DOF_SECF_LOAD;
10968 	sec->dofs_entsize = sizeof (dof_optdesc_t);
10969 
10970 	opt = (dof_optdesc_t *)((uintptr_t)sec +
10971 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
10972 
10973 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
10974 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10975 
10976 	for (i = 0; i < DTRACEOPT_MAX; i++) {
10977 		opt[i].dofo_option = i;
10978 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
10979 		opt[i].dofo_value = state->dts_options[i];
10980 	}
10981 
10982 	return (dof);
10983 }
10984 
10985 static dof_hdr_t *
10986 dtrace_dof_copyin(uintptr_t uarg, int *errp)
10987 {
10988 	dof_hdr_t hdr, *dof;
10989 
10990 	ASSERT(!MUTEX_HELD(&dtrace_lock));
10991 
10992 	/*
10993 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
10994 	 */
10995 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
10996 		dtrace_dof_error(NULL, "failed to copyin DOF header");
10997 		*errp = EFAULT;
10998 		return (NULL);
10999 	}
11000 
11001 	/*
11002 	 * Now we'll allocate the entire DOF and copy it in -- provided
11003 	 * that the length isn't outrageous.
11004 	 */
11005 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
11006 		dtrace_dof_error(&hdr, "load size exceeds maximum");
11007 		*errp = E2BIG;
11008 		return (NULL);
11009 	}
11010 
11011 	if (hdr.dofh_loadsz < sizeof (hdr)) {
11012 		dtrace_dof_error(&hdr, "invalid load size");
11013 		*errp = EINVAL;
11014 		return (NULL);
11015 	}
11016 
11017 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
11018 
11019 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
11020 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
11021 		kmem_free(dof, hdr.dofh_loadsz);
11022 		*errp = EFAULT;
11023 		return (NULL);
11024 	}
11025 
11026 	return (dof);
11027 }
11028 
11029 static dof_hdr_t *
11030 dtrace_dof_property(const char *name)
11031 {
11032 	uchar_t *buf;
11033 	uint64_t loadsz;
11034 	unsigned int len, i;
11035 	dof_hdr_t *dof;
11036 
11037 	/*
11038 	 * Unfortunately, array of values in .conf files are always (and
11039 	 * only) interpreted to be integer arrays.  We must read our DOF
11040 	 * as an integer array, and then squeeze it into a byte array.
11041 	 */
11042 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
11043 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
11044 		return (NULL);
11045 
11046 	for (i = 0; i < len; i++)
11047 		buf[i] = (uchar_t)(((int *)buf)[i]);
11048 
11049 	if (len < sizeof (dof_hdr_t)) {
11050 		ddi_prop_free(buf);
11051 		dtrace_dof_error(NULL, "truncated header");
11052 		return (NULL);
11053 	}
11054 
11055 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
11056 		ddi_prop_free(buf);
11057 		dtrace_dof_error(NULL, "truncated DOF");
11058 		return (NULL);
11059 	}
11060 
11061 	if (loadsz >= dtrace_dof_maxsize) {
11062 		ddi_prop_free(buf);
11063 		dtrace_dof_error(NULL, "oversized DOF");
11064 		return (NULL);
11065 	}
11066 
11067 	dof = kmem_alloc(loadsz, KM_SLEEP);
11068 	bcopy(buf, dof, loadsz);
11069 	ddi_prop_free(buf);
11070 
11071 	return (dof);
11072 }
11073 
11074 static void
11075 dtrace_dof_destroy(dof_hdr_t *dof)
11076 {
11077 	kmem_free(dof, dof->dofh_loadsz);
11078 }
11079 
11080 /*
11081  * Return the dof_sec_t pointer corresponding to a given section index.  If the
11082  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
11083  * a type other than DOF_SECT_NONE is specified, the header is checked against
11084  * this type and NULL is returned if the types do not match.
11085  */
11086 static dof_sec_t *
11087 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
11088 {
11089 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
11090 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
11091 
11092 	if (i >= dof->dofh_secnum) {
11093 		dtrace_dof_error(dof, "referenced section index is invalid");
11094 		return (NULL);
11095 	}
11096 
11097 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
11098 		dtrace_dof_error(dof, "referenced section is not loadable");
11099 		return (NULL);
11100 	}
11101 
11102 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
11103 		dtrace_dof_error(dof, "referenced section is the wrong type");
11104 		return (NULL);
11105 	}
11106 
11107 	return (sec);
11108 }
11109 
11110 static dtrace_probedesc_t *
11111 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
11112 {
11113 	dof_probedesc_t *probe;
11114 	dof_sec_t *strtab;
11115 	uintptr_t daddr = (uintptr_t)dof;
11116 	uintptr_t str;
11117 	size_t size;
11118 
11119 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
11120 		dtrace_dof_error(dof, "invalid probe section");
11121 		return (NULL);
11122 	}
11123 
11124 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
11125 		dtrace_dof_error(dof, "bad alignment in probe description");
11126 		return (NULL);
11127 	}
11128 
11129 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
11130 		dtrace_dof_error(dof, "truncated probe description");
11131 		return (NULL);
11132 	}
11133 
11134 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
11135 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
11136 
11137 	if (strtab == NULL)
11138 		return (NULL);
11139 
11140 	str = daddr + strtab->dofs_offset;
11141 	size = strtab->dofs_size;
11142 
11143 	if (probe->dofp_provider >= strtab->dofs_size) {
11144 		dtrace_dof_error(dof, "corrupt probe provider");
11145 		return (NULL);
11146 	}
11147 
11148 	(void) strncpy(desc->dtpd_provider,
11149 	    (char *)(str + probe->dofp_provider),
11150 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
11151 
11152 	if (probe->dofp_mod >= strtab->dofs_size) {
11153 		dtrace_dof_error(dof, "corrupt probe module");
11154 		return (NULL);
11155 	}
11156 
11157 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
11158 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
11159 
11160 	if (probe->dofp_func >= strtab->dofs_size) {
11161 		dtrace_dof_error(dof, "corrupt probe function");
11162 		return (NULL);
11163 	}
11164 
11165 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
11166 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
11167 
11168 	if (probe->dofp_name >= strtab->dofs_size) {
11169 		dtrace_dof_error(dof, "corrupt probe name");
11170 		return (NULL);
11171 	}
11172 
11173 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
11174 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
11175 
11176 	return (desc);
11177 }
11178 
11179 static dtrace_difo_t *
11180 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11181     cred_t *cr)
11182 {
11183 	dtrace_difo_t *dp;
11184 	size_t ttl = 0;
11185 	dof_difohdr_t *dofd;
11186 	uintptr_t daddr = (uintptr_t)dof;
11187 	size_t max = dtrace_difo_maxsize;
11188 	int i, l, n;
11189 
11190 	static const struct {
11191 		int section;
11192 		int bufoffs;
11193 		int lenoffs;
11194 		int entsize;
11195 		int align;
11196 		const char *msg;
11197 	} difo[] = {
11198 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
11199 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
11200 		sizeof (dif_instr_t), "multiple DIF sections" },
11201 
11202 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
11203 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
11204 		sizeof (uint64_t), "multiple integer tables" },
11205 
11206 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
11207 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
11208 		sizeof (char), "multiple string tables" },
11209 
11210 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
11211 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
11212 		sizeof (uint_t), "multiple variable tables" },
11213 
11214 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
11215 	};
11216 
11217 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
11218 		dtrace_dof_error(dof, "invalid DIFO header section");
11219 		return (NULL);
11220 	}
11221 
11222 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
11223 		dtrace_dof_error(dof, "bad alignment in DIFO header");
11224 		return (NULL);
11225 	}
11226 
11227 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
11228 	    sec->dofs_size % sizeof (dof_secidx_t)) {
11229 		dtrace_dof_error(dof, "bad size in DIFO header");
11230 		return (NULL);
11231 	}
11232 
11233 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11234 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
11235 
11236 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
11237 	dp->dtdo_rtype = dofd->dofd_rtype;
11238 
11239 	for (l = 0; l < n; l++) {
11240 		dof_sec_t *subsec;
11241 		void **bufp;
11242 		uint32_t *lenp;
11243 
11244 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
11245 		    dofd->dofd_links[l])) == NULL)
11246 			goto err; /* invalid section link */
11247 
11248 		if (ttl + subsec->dofs_size > max) {
11249 			dtrace_dof_error(dof, "exceeds maximum size");
11250 			goto err;
11251 		}
11252 
11253 		ttl += subsec->dofs_size;
11254 
11255 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
11256 			if (subsec->dofs_type != difo[i].section)
11257 				continue;
11258 
11259 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
11260 				dtrace_dof_error(dof, "section not loaded");
11261 				goto err;
11262 			}
11263 
11264 			if (subsec->dofs_align != difo[i].align) {
11265 				dtrace_dof_error(dof, "bad alignment");
11266 				goto err;
11267 			}
11268 
11269 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
11270 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
11271 
11272 			if (*bufp != NULL) {
11273 				dtrace_dof_error(dof, difo[i].msg);
11274 				goto err;
11275 			}
11276 
11277 			if (difo[i].entsize != subsec->dofs_entsize) {
11278 				dtrace_dof_error(dof, "entry size mismatch");
11279 				goto err;
11280 			}
11281 
11282 			if (subsec->dofs_entsize != 0 &&
11283 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
11284 				dtrace_dof_error(dof, "corrupt entry size");
11285 				goto err;
11286 			}
11287 
11288 			*lenp = subsec->dofs_size;
11289 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
11290 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
11291 			    *bufp, subsec->dofs_size);
11292 
11293 			if (subsec->dofs_entsize != 0)
11294 				*lenp /= subsec->dofs_entsize;
11295 
11296 			break;
11297 		}
11298 
11299 		/*
11300 		 * If we encounter a loadable DIFO sub-section that is not
11301 		 * known to us, assume this is a broken program and fail.
11302 		 */
11303 		if (difo[i].section == DOF_SECT_NONE &&
11304 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
11305 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
11306 			goto err;
11307 		}
11308 	}
11309 
11310 	if (dp->dtdo_buf == NULL) {
11311 		/*
11312 		 * We can't have a DIF object without DIF text.
11313 		 */
11314 		dtrace_dof_error(dof, "missing DIF text");
11315 		goto err;
11316 	}
11317 
11318 	/*
11319 	 * Before we validate the DIF object, run through the variable table
11320 	 * looking for the strings -- if any of their size are under, we'll set
11321 	 * their size to be the system-wide default string size.  Note that
11322 	 * this should _not_ happen if the "strsize" option has been set --
11323 	 * in this case, the compiler should have set the size to reflect the
11324 	 * setting of the option.
11325 	 */
11326 	for (i = 0; i < dp->dtdo_varlen; i++) {
11327 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
11328 		dtrace_diftype_t *t = &v->dtdv_type;
11329 
11330 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
11331 			continue;
11332 
11333 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
11334 			t->dtdt_size = dtrace_strsize_default;
11335 	}
11336 
11337 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
11338 		goto err;
11339 
11340 	dtrace_difo_init(dp, vstate);
11341 	return (dp);
11342 
11343 err:
11344 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
11345 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
11346 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
11347 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
11348 
11349 	kmem_free(dp, sizeof (dtrace_difo_t));
11350 	return (NULL);
11351 }
11352 
11353 static dtrace_predicate_t *
11354 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11355     cred_t *cr)
11356 {
11357 	dtrace_difo_t *dp;
11358 
11359 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
11360 		return (NULL);
11361 
11362 	return (dtrace_predicate_create(dp));
11363 }
11364 
11365 static dtrace_actdesc_t *
11366 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11367     cred_t *cr)
11368 {
11369 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
11370 	dof_actdesc_t *desc;
11371 	dof_sec_t *difosec;
11372 	size_t offs;
11373 	uintptr_t daddr = (uintptr_t)dof;
11374 	uint64_t arg;
11375 	dtrace_actkind_t kind;
11376 
11377 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
11378 		dtrace_dof_error(dof, "invalid action section");
11379 		return (NULL);
11380 	}
11381 
11382 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
11383 		dtrace_dof_error(dof, "truncated action description");
11384 		return (NULL);
11385 	}
11386 
11387 	if (sec->dofs_align != sizeof (uint64_t)) {
11388 		dtrace_dof_error(dof, "bad alignment in action description");
11389 		return (NULL);
11390 	}
11391 
11392 	if (sec->dofs_size < sec->dofs_entsize) {
11393 		dtrace_dof_error(dof, "section entry size exceeds total size");
11394 		return (NULL);
11395 	}
11396 
11397 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
11398 		dtrace_dof_error(dof, "bad entry size in action description");
11399 		return (NULL);
11400 	}
11401 
11402 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
11403 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
11404 		return (NULL);
11405 	}
11406 
11407 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
11408 		desc = (dof_actdesc_t *)(daddr +
11409 		    (uintptr_t)sec->dofs_offset + offs);
11410 		kind = (dtrace_actkind_t)desc->dofa_kind;
11411 
11412 		if (DTRACEACT_ISPRINTFLIKE(kind) &&
11413 		    (kind != DTRACEACT_PRINTA ||
11414 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
11415 			dof_sec_t *strtab;
11416 			char *str, *fmt;
11417 			uint64_t i;
11418 
11419 			/*
11420 			 * printf()-like actions must have a format string.
11421 			 */
11422 			if ((strtab = dtrace_dof_sect(dof,
11423 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
11424 				goto err;
11425 
11426 			str = (char *)((uintptr_t)dof +
11427 			    (uintptr_t)strtab->dofs_offset);
11428 
11429 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
11430 				if (str[i] == '\0')
11431 					break;
11432 			}
11433 
11434 			if (i >= strtab->dofs_size) {
11435 				dtrace_dof_error(dof, "bogus format string");
11436 				goto err;
11437 			}
11438 
11439 			if (i == desc->dofa_arg) {
11440 				dtrace_dof_error(dof, "empty format string");
11441 				goto err;
11442 			}
11443 
11444 			i -= desc->dofa_arg;
11445 			fmt = kmem_alloc(i + 1, KM_SLEEP);
11446 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
11447 			arg = (uint64_t)(uintptr_t)fmt;
11448 		} else {
11449 			if (kind == DTRACEACT_PRINTA) {
11450 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
11451 				arg = 0;
11452 			} else {
11453 				arg = desc->dofa_arg;
11454 			}
11455 		}
11456 
11457 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
11458 		    desc->dofa_uarg, arg);
11459 
11460 		if (last != NULL) {
11461 			last->dtad_next = act;
11462 		} else {
11463 			first = act;
11464 		}
11465 
11466 		last = act;
11467 
11468 		if (desc->dofa_difo == DOF_SECIDX_NONE)
11469 			continue;
11470 
11471 		if ((difosec = dtrace_dof_sect(dof,
11472 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
11473 			goto err;
11474 
11475 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
11476 
11477 		if (act->dtad_difo == NULL)
11478 			goto err;
11479 	}
11480 
11481 	ASSERT(first != NULL);
11482 	return (first);
11483 
11484 err:
11485 	for (act = first; act != NULL; act = next) {
11486 		next = act->dtad_next;
11487 		dtrace_actdesc_release(act, vstate);
11488 	}
11489 
11490 	return (NULL);
11491 }
11492 
11493 static dtrace_ecbdesc_t *
11494 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11495     cred_t *cr)
11496 {
11497 	dtrace_ecbdesc_t *ep;
11498 	dof_ecbdesc_t *ecb;
11499 	dtrace_probedesc_t *desc;
11500 	dtrace_predicate_t *pred = NULL;
11501 
11502 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
11503 		dtrace_dof_error(dof, "truncated ECB description");
11504 		return (NULL);
11505 	}
11506 
11507 	if (sec->dofs_align != sizeof (uint64_t)) {
11508 		dtrace_dof_error(dof, "bad alignment in ECB description");
11509 		return (NULL);
11510 	}
11511 
11512 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
11513 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
11514 
11515 	if (sec == NULL)
11516 		return (NULL);
11517 
11518 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11519 	ep->dted_uarg = ecb->dofe_uarg;
11520 	desc = &ep->dted_probe;
11521 
11522 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
11523 		goto err;
11524 
11525 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
11526 		if ((sec = dtrace_dof_sect(dof,
11527 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
11528 			goto err;
11529 
11530 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
11531 			goto err;
11532 
11533 		ep->dted_pred.dtpdd_predicate = pred;
11534 	}
11535 
11536 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
11537 		if ((sec = dtrace_dof_sect(dof,
11538 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
11539 			goto err;
11540 
11541 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
11542 
11543 		if (ep->dted_action == NULL)
11544 			goto err;
11545 	}
11546 
11547 	return (ep);
11548 
11549 err:
11550 	if (pred != NULL)
11551 		dtrace_predicate_release(pred, vstate);
11552 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11553 	return (NULL);
11554 }
11555 
11556 /*
11557  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
11558  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
11559  * site of any user SETX relocations to account for load object base address.
11560  * In the future, if we need other relocations, this function can be extended.
11561  */
11562 static int
11563 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
11564 {
11565 	uintptr_t daddr = (uintptr_t)dof;
11566 	dof_relohdr_t *dofr =
11567 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11568 	dof_sec_t *ss, *rs, *ts;
11569 	dof_relodesc_t *r;
11570 	uint_t i, n;
11571 
11572 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
11573 	    sec->dofs_align != sizeof (dof_secidx_t)) {
11574 		dtrace_dof_error(dof, "invalid relocation header");
11575 		return (-1);
11576 	}
11577 
11578 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
11579 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
11580 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
11581 
11582 	if (ss == NULL || rs == NULL || ts == NULL)
11583 		return (-1); /* dtrace_dof_error() has been called already */
11584 
11585 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
11586 	    rs->dofs_align != sizeof (uint64_t)) {
11587 		dtrace_dof_error(dof, "invalid relocation section");
11588 		return (-1);
11589 	}
11590 
11591 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
11592 	n = rs->dofs_size / rs->dofs_entsize;
11593 
11594 	for (i = 0; i < n; i++) {
11595 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
11596 
11597 		switch (r->dofr_type) {
11598 		case DOF_RELO_NONE:
11599 			break;
11600 		case DOF_RELO_SETX:
11601 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
11602 			    sizeof (uint64_t) > ts->dofs_size) {
11603 				dtrace_dof_error(dof, "bad relocation offset");
11604 				return (-1);
11605 			}
11606 
11607 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
11608 				dtrace_dof_error(dof, "misaligned setx relo");
11609 				return (-1);
11610 			}
11611 
11612 			*(uint64_t *)taddr += ubase;
11613 			break;
11614 		default:
11615 			dtrace_dof_error(dof, "invalid relocation type");
11616 			return (-1);
11617 		}
11618 
11619 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
11620 	}
11621 
11622 	return (0);
11623 }
11624 
11625 /*
11626  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
11627  * header:  it should be at the front of a memory region that is at least
11628  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
11629  * size.  It need not be validated in any other way.
11630  */
11631 static int
11632 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
11633     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
11634 {
11635 	uint64_t len = dof->dofh_loadsz, seclen;
11636 	uintptr_t daddr = (uintptr_t)dof;
11637 	dtrace_ecbdesc_t *ep;
11638 	dtrace_enabling_t *enab;
11639 	uint_t i;
11640 
11641 	ASSERT(MUTEX_HELD(&dtrace_lock));
11642 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
11643 
11644 	/*
11645 	 * Check the DOF header identification bytes.  In addition to checking
11646 	 * valid settings, we also verify that unused bits/bytes are zeroed so
11647 	 * we can use them later without fear of regressing existing binaries.
11648 	 */
11649 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
11650 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
11651 		dtrace_dof_error(dof, "DOF magic string mismatch");
11652 		return (-1);
11653 	}
11654 
11655 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
11656 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
11657 		dtrace_dof_error(dof, "DOF has invalid data model");
11658 		return (-1);
11659 	}
11660 
11661 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
11662 		dtrace_dof_error(dof, "DOF encoding mismatch");
11663 		return (-1);
11664 	}
11665 
11666 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
11667 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
11668 		dtrace_dof_error(dof, "DOF version mismatch");
11669 		return (-1);
11670 	}
11671 
11672 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
11673 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
11674 		return (-1);
11675 	}
11676 
11677 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
11678 		dtrace_dof_error(dof, "DOF uses too many integer registers");
11679 		return (-1);
11680 	}
11681 
11682 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
11683 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
11684 		return (-1);
11685 	}
11686 
11687 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
11688 		if (dof->dofh_ident[i] != 0) {
11689 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
11690 			return (-1);
11691 		}
11692 	}
11693 
11694 	if (dof->dofh_flags & ~DOF_FL_VALID) {
11695 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
11696 		return (-1);
11697 	}
11698 
11699 	if (dof->dofh_secsize == 0) {
11700 		dtrace_dof_error(dof, "zero section header size");
11701 		return (-1);
11702 	}
11703 
11704 	/*
11705 	 * Check that the section headers don't exceed the amount of DOF
11706 	 * data.  Note that we cast the section size and number of sections
11707 	 * to uint64_t's to prevent possible overflow in the multiplication.
11708 	 */
11709 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
11710 
11711 	if (dof->dofh_secoff > len || seclen > len ||
11712 	    dof->dofh_secoff + seclen > len) {
11713 		dtrace_dof_error(dof, "truncated section headers");
11714 		return (-1);
11715 	}
11716 
11717 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
11718 		dtrace_dof_error(dof, "misaligned section headers");
11719 		return (-1);
11720 	}
11721 
11722 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
11723 		dtrace_dof_error(dof, "misaligned section size");
11724 		return (-1);
11725 	}
11726 
11727 	/*
11728 	 * Take an initial pass through the section headers to be sure that
11729 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
11730 	 * set, do not permit sections relating to providers, probes, or args.
11731 	 */
11732 	for (i = 0; i < dof->dofh_secnum; i++) {
11733 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11734 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11735 
11736 		if (noprobes) {
11737 			switch (sec->dofs_type) {
11738 			case DOF_SECT_PROVIDER:
11739 			case DOF_SECT_PROBES:
11740 			case DOF_SECT_PRARGS:
11741 			case DOF_SECT_PROFFS:
11742 				dtrace_dof_error(dof, "illegal sections "
11743 				    "for enabling");
11744 				return (-1);
11745 			}
11746 		}
11747 
11748 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
11749 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
11750 			dtrace_dof_error(dof, "loadable section with load "
11751 			    "flag unset");
11752 			return (-1);
11753 		}
11754 
11755 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
11756 			continue; /* just ignore non-loadable sections */
11757 
11758 		if (sec->dofs_align & (sec->dofs_align - 1)) {
11759 			dtrace_dof_error(dof, "bad section alignment");
11760 			return (-1);
11761 		}
11762 
11763 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
11764 			dtrace_dof_error(dof, "misaligned section");
11765 			return (-1);
11766 		}
11767 
11768 		if (sec->dofs_offset > len || sec->dofs_size > len ||
11769 		    sec->dofs_offset + sec->dofs_size > len) {
11770 			dtrace_dof_error(dof, "corrupt section header");
11771 			return (-1);
11772 		}
11773 
11774 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
11775 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
11776 			dtrace_dof_error(dof, "non-terminating string table");
11777 			return (-1);
11778 		}
11779 	}
11780 
11781 	/*
11782 	 * Take a second pass through the sections and locate and perform any
11783 	 * relocations that are present.  We do this after the first pass to
11784 	 * be sure that all sections have had their headers validated.
11785 	 */
11786 	for (i = 0; i < dof->dofh_secnum; i++) {
11787 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11788 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11789 
11790 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
11791 			continue; /* skip sections that are not loadable */
11792 
11793 		switch (sec->dofs_type) {
11794 		case DOF_SECT_URELHDR:
11795 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
11796 				return (-1);
11797 			break;
11798 		}
11799 	}
11800 
11801 	if ((enab = *enabp) == NULL)
11802 		enab = *enabp = dtrace_enabling_create(vstate);
11803 
11804 	for (i = 0; i < dof->dofh_secnum; i++) {
11805 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11806 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11807 
11808 		if (sec->dofs_type != DOF_SECT_ECBDESC)
11809 			continue;
11810 
11811 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
11812 			dtrace_enabling_destroy(enab);
11813 			*enabp = NULL;
11814 			return (-1);
11815 		}
11816 
11817 		dtrace_enabling_add(enab, ep);
11818 	}
11819 
11820 	return (0);
11821 }
11822 
11823 /*
11824  * Process DOF for any options.  This routine assumes that the DOF has been
11825  * at least processed by dtrace_dof_slurp().
11826  */
11827 static int
11828 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
11829 {
11830 	int i, rval;
11831 	uint32_t entsize;
11832 	size_t offs;
11833 	dof_optdesc_t *desc;
11834 
11835 	for (i = 0; i < dof->dofh_secnum; i++) {
11836 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
11837 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11838 
11839 		if (sec->dofs_type != DOF_SECT_OPTDESC)
11840 			continue;
11841 
11842 		if (sec->dofs_align != sizeof (uint64_t)) {
11843 			dtrace_dof_error(dof, "bad alignment in "
11844 			    "option description");
11845 			return (EINVAL);
11846 		}
11847 
11848 		if ((entsize = sec->dofs_entsize) == 0) {
11849 			dtrace_dof_error(dof, "zeroed option entry size");
11850 			return (EINVAL);
11851 		}
11852 
11853 		if (entsize < sizeof (dof_optdesc_t)) {
11854 			dtrace_dof_error(dof, "bad option entry size");
11855 			return (EINVAL);
11856 		}
11857 
11858 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
11859 			desc = (dof_optdesc_t *)((uintptr_t)dof +
11860 			    (uintptr_t)sec->dofs_offset + offs);
11861 
11862 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
11863 				dtrace_dof_error(dof, "non-zero option string");
11864 				return (EINVAL);
11865 			}
11866 
11867 			if (desc->dofo_value == DTRACEOPT_UNSET) {
11868 				dtrace_dof_error(dof, "unset option");
11869 				return (EINVAL);
11870 			}
11871 
11872 			if ((rval = dtrace_state_option(state,
11873 			    desc->dofo_option, desc->dofo_value)) != 0) {
11874 				dtrace_dof_error(dof, "rejected option");
11875 				return (rval);
11876 			}
11877 		}
11878 	}
11879 
11880 	return (0);
11881 }
11882 
11883 /*
11884  * DTrace Consumer State Functions
11885  */
11886 int
11887 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
11888 {
11889 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
11890 	void *base;
11891 	uintptr_t limit;
11892 	dtrace_dynvar_t *dvar, *next, *start;
11893 	int i;
11894 
11895 	ASSERT(MUTEX_HELD(&dtrace_lock));
11896 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
11897 
11898 	bzero(dstate, sizeof (dtrace_dstate_t));
11899 
11900 	if ((dstate->dtds_chunksize = chunksize) == 0)
11901 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
11902 
11903 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
11904 		size = min;
11905 
11906 	if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11907 		return (ENOMEM);
11908 
11909 	dstate->dtds_size = size;
11910 	dstate->dtds_base = base;
11911 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
11912 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
11913 
11914 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
11915 
11916 	if (hashsize != 1 && (hashsize & 1))
11917 		hashsize--;
11918 
11919 	dstate->dtds_hashsize = hashsize;
11920 	dstate->dtds_hash = dstate->dtds_base;
11921 
11922 	/*
11923 	 * Set all of our hash buckets to point to the single sink, and (if
11924 	 * it hasn't already been set), set the sink's hash value to be the
11925 	 * sink sentinel value.  The sink is needed for dynamic variable
11926 	 * lookups to know that they have iterated over an entire, valid hash
11927 	 * chain.
11928 	 */
11929 	for (i = 0; i < hashsize; i++)
11930 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
11931 
11932 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
11933 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
11934 
11935 	/*
11936 	 * Determine number of active CPUs.  Divide free list evenly among
11937 	 * active CPUs.
11938 	 */
11939 	start = (dtrace_dynvar_t *)
11940 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
11941 	limit = (uintptr_t)base + size;
11942 
11943 	maxper = (limit - (uintptr_t)start) / NCPU;
11944 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
11945 
11946 	for (i = 0; i < NCPU; i++) {
11947 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
11948 
11949 		/*
11950 		 * If we don't even have enough chunks to make it once through
11951 		 * NCPUs, we're just going to allocate everything to the first
11952 		 * CPU.  And if we're on the last CPU, we're going to allocate
11953 		 * whatever is left over.  In either case, we set the limit to
11954 		 * be the limit of the dynamic variable space.
11955 		 */
11956 		if (maxper == 0 || i == NCPU - 1) {
11957 			limit = (uintptr_t)base + size;
11958 			start = NULL;
11959 		} else {
11960 			limit = (uintptr_t)start + maxper;
11961 			start = (dtrace_dynvar_t *)limit;
11962 		}
11963 
11964 		ASSERT(limit <= (uintptr_t)base + size);
11965 
11966 		for (;;) {
11967 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
11968 			    dstate->dtds_chunksize);
11969 
11970 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
11971 				break;
11972 
11973 			dvar->dtdv_next = next;
11974 			dvar = next;
11975 		}
11976 
11977 		if (maxper == 0)
11978 			break;
11979 	}
11980 
11981 	return (0);
11982 }
11983 
11984 void
11985 dtrace_dstate_fini(dtrace_dstate_t *dstate)
11986 {
11987 	ASSERT(MUTEX_HELD(&cpu_lock));
11988 
11989 	if (dstate->dtds_base == NULL)
11990 		return;
11991 
11992 	kmem_free(dstate->dtds_base, dstate->dtds_size);
11993 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
11994 }
11995 
11996 static void
11997 dtrace_vstate_fini(dtrace_vstate_t *vstate)
11998 {
11999 	/*
12000 	 * Logical XOR, where are you?
12001 	 */
12002 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
12003 
12004 	if (vstate->dtvs_nglobals > 0) {
12005 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
12006 		    sizeof (dtrace_statvar_t *));
12007 	}
12008 
12009 	if (vstate->dtvs_ntlocals > 0) {
12010 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
12011 		    sizeof (dtrace_difv_t));
12012 	}
12013 
12014 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
12015 
12016 	if (vstate->dtvs_nlocals > 0) {
12017 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
12018 		    sizeof (dtrace_statvar_t *));
12019 	}
12020 }
12021 
12022 static void
12023 dtrace_state_clean(dtrace_state_t *state)
12024 {
12025 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
12026 		return;
12027 
12028 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
12029 	dtrace_speculation_clean(state);
12030 }
12031 
12032 static void
12033 dtrace_state_deadman(dtrace_state_t *state)
12034 {
12035 	hrtime_t now;
12036 
12037 	dtrace_sync();
12038 
12039 	now = dtrace_gethrtime();
12040 
12041 	if (state != dtrace_anon.dta_state &&
12042 	    now - state->dts_laststatus >= dtrace_deadman_user)
12043 		return;
12044 
12045 	/*
12046 	 * We must be sure that dts_alive never appears to be less than the
12047 	 * value upon entry to dtrace_state_deadman(), and because we lack a
12048 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
12049 	 * store INT64_MAX to it, followed by a memory barrier, followed by
12050 	 * the new value.  This assures that dts_alive never appears to be
12051 	 * less than its true value, regardless of the order in which the
12052 	 * stores to the underlying storage are issued.
12053 	 */
12054 	state->dts_alive = INT64_MAX;
12055 	dtrace_membar_producer();
12056 	state->dts_alive = now;
12057 }
12058 
12059 dtrace_state_t *
12060 dtrace_state_create(dev_t *devp, cred_t *cr)
12061 {
12062 	minor_t minor;
12063 	major_t major;
12064 	char c[30];
12065 	dtrace_state_t *state;
12066 	dtrace_optval_t *opt;
12067 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
12068 
12069 	ASSERT(MUTEX_HELD(&dtrace_lock));
12070 	ASSERT(MUTEX_HELD(&cpu_lock));
12071 
12072 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
12073 	    VM_BESTFIT | VM_SLEEP);
12074 
12075 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
12076 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12077 		return (NULL);
12078 	}
12079 
12080 	state = ddi_get_soft_state(dtrace_softstate, minor);
12081 	state->dts_epid = DTRACE_EPIDNONE + 1;
12082 
12083 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
12084 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
12085 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
12086 
12087 	if (devp != NULL) {
12088 		major = getemajor(*devp);
12089 	} else {
12090 		major = ddi_driver_major(dtrace_devi);
12091 	}
12092 
12093 	state->dts_dev = makedevice(major, minor);
12094 
12095 	if (devp != NULL)
12096 		*devp = state->dts_dev;
12097 
12098 	/*
12099 	 * We allocate NCPU buffers.  On the one hand, this can be quite
12100 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
12101 	 * other hand, it saves an additional memory reference in the probe
12102 	 * path.
12103 	 */
12104 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
12105 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
12106 	state->dts_cleaner = CYCLIC_NONE;
12107 	state->dts_deadman = CYCLIC_NONE;
12108 	state->dts_vstate.dtvs_state = state;
12109 
12110 	for (i = 0; i < DTRACEOPT_MAX; i++)
12111 		state->dts_options[i] = DTRACEOPT_UNSET;
12112 
12113 	/*
12114 	 * Set the default options.
12115 	 */
12116 	opt = state->dts_options;
12117 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
12118 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
12119 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
12120 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
12121 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
12122 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
12123 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
12124 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
12125 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
12126 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
12127 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
12128 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
12129 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
12130 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
12131 
12132 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
12133 
12134 	/*
12135 	 * Depending on the user credentials, we set flag bits which alter probe
12136 	 * visibility or the amount of destructiveness allowed.  In the case of
12137 	 * actual anonymous tracing, or the possession of all privileges, all of
12138 	 * the normal checks are bypassed.
12139 	 */
12140 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
12141 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
12142 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
12143 	} else {
12144 		/*
12145 		 * Set up the credentials for this instantiation.  We take a
12146 		 * hold on the credential to prevent it from disappearing on
12147 		 * us; this in turn prevents the zone_t referenced by this
12148 		 * credential from disappearing.  This means that we can
12149 		 * examine the credential and the zone from probe context.
12150 		 */
12151 		crhold(cr);
12152 		state->dts_cred.dcr_cred = cr;
12153 
12154 		/*
12155 		 * CRA_PROC means "we have *some* privilege for dtrace" and
12156 		 * unlocks the use of variables like pid, zonename, etc.
12157 		 */
12158 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
12159 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12160 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
12161 		}
12162 
12163 		/*
12164 		 * dtrace_user allows use of syscall and profile providers.
12165 		 * If the user also has proc_owner and/or proc_zone, we
12166 		 * extend the scope to include additional visibility and
12167 		 * destructive power.
12168 		 */
12169 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
12170 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
12171 				state->dts_cred.dcr_visible |=
12172 				    DTRACE_CRV_ALLPROC;
12173 
12174 				state->dts_cred.dcr_action |=
12175 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12176 			}
12177 
12178 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
12179 				state->dts_cred.dcr_visible |=
12180 				    DTRACE_CRV_ALLZONE;
12181 
12182 				state->dts_cred.dcr_action |=
12183 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12184 			}
12185 
12186 			/*
12187 			 * If we have all privs in whatever zone this is,
12188 			 * we can do destructive things to processes which
12189 			 * have altered credentials.
12190 			 */
12191 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12192 			    cr->cr_zone->zone_privset)) {
12193 				state->dts_cred.dcr_action |=
12194 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12195 			}
12196 		}
12197 
12198 		/*
12199 		 * Holding the dtrace_kernel privilege also implies that
12200 		 * the user has the dtrace_user privilege from a visibility
12201 		 * perspective.  But without further privileges, some
12202 		 * destructive actions are not available.
12203 		 */
12204 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
12205 			/*
12206 			 * Make all probes in all zones visible.  However,
12207 			 * this doesn't mean that all actions become available
12208 			 * to all zones.
12209 			 */
12210 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
12211 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
12212 
12213 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
12214 			    DTRACE_CRA_PROC;
12215 			/*
12216 			 * Holding proc_owner means that destructive actions
12217 			 * for *this* zone are allowed.
12218 			 */
12219 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12220 				state->dts_cred.dcr_action |=
12221 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12222 
12223 			/*
12224 			 * Holding proc_zone means that destructive actions
12225 			 * for this user/group ID in all zones is allowed.
12226 			 */
12227 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12228 				state->dts_cred.dcr_action |=
12229 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12230 
12231 			/*
12232 			 * If we have all privs in whatever zone this is,
12233 			 * we can do destructive things to processes which
12234 			 * have altered credentials.
12235 			 */
12236 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12237 			    cr->cr_zone->zone_privset)) {
12238 				state->dts_cred.dcr_action |=
12239 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12240 			}
12241 		}
12242 
12243 		/*
12244 		 * Holding the dtrace_proc privilege gives control over fasttrap
12245 		 * and pid providers.  We need to grant wider destructive
12246 		 * privileges in the event that the user has proc_owner and/or
12247 		 * proc_zone.
12248 		 */
12249 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12250 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12251 				state->dts_cred.dcr_action |=
12252 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12253 
12254 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12255 				state->dts_cred.dcr_action |=
12256 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12257 		}
12258 	}
12259 
12260 	return (state);
12261 }
12262 
12263 static int
12264 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
12265 {
12266 	dtrace_optval_t *opt = state->dts_options, size;
12267 	processorid_t cpu;
12268 	int flags = 0, rval;
12269 
12270 	ASSERT(MUTEX_HELD(&dtrace_lock));
12271 	ASSERT(MUTEX_HELD(&cpu_lock));
12272 	ASSERT(which < DTRACEOPT_MAX);
12273 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
12274 	    (state == dtrace_anon.dta_state &&
12275 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
12276 
12277 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
12278 		return (0);
12279 
12280 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
12281 		cpu = opt[DTRACEOPT_CPU];
12282 
12283 	if (which == DTRACEOPT_SPECSIZE)
12284 		flags |= DTRACEBUF_NOSWITCH;
12285 
12286 	if (which == DTRACEOPT_BUFSIZE) {
12287 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
12288 			flags |= DTRACEBUF_RING;
12289 
12290 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
12291 			flags |= DTRACEBUF_FILL;
12292 
12293 		if (state != dtrace_anon.dta_state ||
12294 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
12295 			flags |= DTRACEBUF_INACTIVE;
12296 	}
12297 
12298 	for (size = opt[which]; size >= sizeof (uint64_t); size >>= 1) {
12299 		/*
12300 		 * The size must be 8-byte aligned.  If the size is not 8-byte
12301 		 * aligned, drop it down by the difference.
12302 		 */
12303 		if (size & (sizeof (uint64_t) - 1))
12304 			size -= size & (sizeof (uint64_t) - 1);
12305 
12306 		if (size < state->dts_reserve) {
12307 			/*
12308 			 * Buffers always must be large enough to accommodate
12309 			 * their prereserved space.  We return E2BIG instead
12310 			 * of ENOMEM in this case to allow for user-level
12311 			 * software to differentiate the cases.
12312 			 */
12313 			return (E2BIG);
12314 		}
12315 
12316 		rval = dtrace_buffer_alloc(buf, size, flags, cpu);
12317 
12318 		if (rval != ENOMEM) {
12319 			opt[which] = size;
12320 			return (rval);
12321 		}
12322 
12323 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12324 			return (rval);
12325 	}
12326 
12327 	return (ENOMEM);
12328 }
12329 
12330 static int
12331 dtrace_state_buffers(dtrace_state_t *state)
12332 {
12333 	dtrace_speculation_t *spec = state->dts_speculations;
12334 	int rval, i;
12335 
12336 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
12337 	    DTRACEOPT_BUFSIZE)) != 0)
12338 		return (rval);
12339 
12340 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
12341 	    DTRACEOPT_AGGSIZE)) != 0)
12342 		return (rval);
12343 
12344 	for (i = 0; i < state->dts_nspeculations; i++) {
12345 		if ((rval = dtrace_state_buffer(state,
12346 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
12347 			return (rval);
12348 	}
12349 
12350 	return (0);
12351 }
12352 
12353 static void
12354 dtrace_state_prereserve(dtrace_state_t *state)
12355 {
12356 	dtrace_ecb_t *ecb;
12357 	dtrace_probe_t *probe;
12358 
12359 	state->dts_reserve = 0;
12360 
12361 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
12362 		return;
12363 
12364 	/*
12365 	 * If our buffer policy is a "fill" buffer policy, we need to set the
12366 	 * prereserved space to be the space required by the END probes.
12367 	 */
12368 	probe = dtrace_probes[dtrace_probeid_end - 1];
12369 	ASSERT(probe != NULL);
12370 
12371 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
12372 		if (ecb->dte_state != state)
12373 			continue;
12374 
12375 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
12376 	}
12377 }
12378 
12379 static int
12380 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
12381 {
12382 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
12383 	dtrace_speculation_t *spec;
12384 	dtrace_buffer_t *buf;
12385 	cyc_handler_t hdlr;
12386 	cyc_time_t when;
12387 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12388 	dtrace_icookie_t cookie;
12389 
12390 	mutex_enter(&cpu_lock);
12391 	mutex_enter(&dtrace_lock);
12392 
12393 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
12394 		rval = EBUSY;
12395 		goto out;
12396 	}
12397 
12398 	/*
12399 	 * Before we can perform any checks, we must prime all of the
12400 	 * retained enablings that correspond to this state.
12401 	 */
12402 	dtrace_enabling_prime(state);
12403 
12404 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
12405 		rval = EACCES;
12406 		goto out;
12407 	}
12408 
12409 	dtrace_state_prereserve(state);
12410 
12411 	/*
12412 	 * Now we want to do is try to allocate our speculations.
12413 	 * We do not automatically resize the number of speculations; if
12414 	 * this fails, we will fail the operation.
12415 	 */
12416 	nspec = opt[DTRACEOPT_NSPEC];
12417 	ASSERT(nspec != DTRACEOPT_UNSET);
12418 
12419 	if (nspec > INT_MAX) {
12420 		rval = ENOMEM;
12421 		goto out;
12422 	}
12423 
12424 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
12425 
12426 	if (spec == NULL) {
12427 		rval = ENOMEM;
12428 		goto out;
12429 	}
12430 
12431 	state->dts_speculations = spec;
12432 	state->dts_nspeculations = (int)nspec;
12433 
12434 	for (i = 0; i < nspec; i++) {
12435 		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
12436 			rval = ENOMEM;
12437 			goto err;
12438 		}
12439 
12440 		spec[i].dtsp_buffer = buf;
12441 	}
12442 
12443 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
12444 		if (dtrace_anon.dta_state == NULL) {
12445 			rval = ENOENT;
12446 			goto out;
12447 		}
12448 
12449 		if (state->dts_necbs != 0) {
12450 			rval = EALREADY;
12451 			goto out;
12452 		}
12453 
12454 		state->dts_anon = dtrace_anon_grab();
12455 		ASSERT(state->dts_anon != NULL);
12456 		state = state->dts_anon;
12457 
12458 		/*
12459 		 * We want "grabanon" to be set in the grabbed state, so we'll
12460 		 * copy that option value from the grabbing state into the
12461 		 * grabbed state.
12462 		 */
12463 		state->dts_options[DTRACEOPT_GRABANON] =
12464 		    opt[DTRACEOPT_GRABANON];
12465 
12466 		*cpu = dtrace_anon.dta_beganon;
12467 
12468 		/*
12469 		 * If the anonymous state is active (as it almost certainly
12470 		 * is if the anonymous enabling ultimately matched anything),
12471 		 * we don't allow any further option processing -- but we
12472 		 * don't return failure.
12473 		 */
12474 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12475 			goto out;
12476 	}
12477 
12478 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
12479 	    opt[DTRACEOPT_AGGSIZE] != 0) {
12480 		if (state->dts_aggregations == NULL) {
12481 			/*
12482 			 * We're not going to create an aggregation buffer
12483 			 * because we don't have any ECBs that contain
12484 			 * aggregations -- set this option to 0.
12485 			 */
12486 			opt[DTRACEOPT_AGGSIZE] = 0;
12487 		} else {
12488 			/*
12489 			 * If we have an aggregation buffer, we must also have
12490 			 * a buffer to use as scratch.
12491 			 */
12492 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
12493 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
12494 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
12495 			}
12496 		}
12497 	}
12498 
12499 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
12500 	    opt[DTRACEOPT_SPECSIZE] != 0) {
12501 		if (!state->dts_speculates) {
12502 			/*
12503 			 * We're not going to create speculation buffers
12504 			 * because we don't have any ECBs that actually
12505 			 * speculate -- set the speculation size to 0.
12506 			 */
12507 			opt[DTRACEOPT_SPECSIZE] = 0;
12508 		}
12509 	}
12510 
12511 	/*
12512 	 * The bare minimum size for any buffer that we're actually going to
12513 	 * do anything to is sizeof (uint64_t).
12514 	 */
12515 	sz = sizeof (uint64_t);
12516 
12517 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
12518 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
12519 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
12520 		/*
12521 		 * A buffer size has been explicitly set to 0 (or to a size
12522 		 * that will be adjusted to 0) and we need the space -- we
12523 		 * need to return failure.  We return ENOSPC to differentiate
12524 		 * it from failing to allocate a buffer due to failure to meet
12525 		 * the reserve (for which we return E2BIG).
12526 		 */
12527 		rval = ENOSPC;
12528 		goto out;
12529 	}
12530 
12531 	if ((rval = dtrace_state_buffers(state)) != 0)
12532 		goto err;
12533 
12534 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
12535 		sz = dtrace_dstate_defsize;
12536 
12537 	do {
12538 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
12539 
12540 		if (rval == 0)
12541 			break;
12542 
12543 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12544 			goto err;
12545 	} while (sz >>= 1);
12546 
12547 	opt[DTRACEOPT_DYNVARSIZE] = sz;
12548 
12549 	if (rval != 0)
12550 		goto err;
12551 
12552 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
12553 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
12554 
12555 	if (opt[DTRACEOPT_CLEANRATE] == 0)
12556 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12557 
12558 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
12559 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
12560 
12561 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
12562 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12563 
12564 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
12565 	hdlr.cyh_arg = state;
12566 	hdlr.cyh_level = CY_LOW_LEVEL;
12567 
12568 	when.cyt_when = 0;
12569 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
12570 
12571 	state->dts_cleaner = cyclic_add(&hdlr, &when);
12572 
12573 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
12574 	hdlr.cyh_arg = state;
12575 	hdlr.cyh_level = CY_LOW_LEVEL;
12576 
12577 	when.cyt_when = 0;
12578 	when.cyt_interval = dtrace_deadman_interval;
12579 
12580 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
12581 	state->dts_deadman = cyclic_add(&hdlr, &when);
12582 
12583 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
12584 
12585 	/*
12586 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
12587 	 * interrupts here both to record the CPU on which we fired the BEGIN
12588 	 * probe (the data from this CPU will be processed first at user
12589 	 * level) and to manually activate the buffer for this CPU.
12590 	 */
12591 	cookie = dtrace_interrupt_disable();
12592 	*cpu = CPU->cpu_id;
12593 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
12594 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12595 
12596 	dtrace_probe(dtrace_probeid_begin,
12597 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
12598 	dtrace_interrupt_enable(cookie);
12599 	/*
12600 	 * We may have had an exit action from a BEGIN probe; only change our
12601 	 * state to ACTIVE if we're still in WARMUP.
12602 	 */
12603 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
12604 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
12605 
12606 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
12607 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
12608 
12609 	/*
12610 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
12611 	 * want each CPU to transition its principal buffer out of the
12612 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
12613 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
12614 	 * atomically transition from processing none of a state's ECBs to
12615 	 * processing all of them.
12616 	 */
12617 	dtrace_xcall(DTRACE_CPUALL,
12618 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
12619 	goto out;
12620 
12621 err:
12622 	dtrace_buffer_free(state->dts_buffer);
12623 	dtrace_buffer_free(state->dts_aggbuffer);
12624 
12625 	if ((nspec = state->dts_nspeculations) == 0) {
12626 		ASSERT(state->dts_speculations == NULL);
12627 		goto out;
12628 	}
12629 
12630 	spec = state->dts_speculations;
12631 	ASSERT(spec != NULL);
12632 
12633 	for (i = 0; i < state->dts_nspeculations; i++) {
12634 		if ((buf = spec[i].dtsp_buffer) == NULL)
12635 			break;
12636 
12637 		dtrace_buffer_free(buf);
12638 		kmem_free(buf, bufsize);
12639 	}
12640 
12641 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
12642 	state->dts_nspeculations = 0;
12643 	state->dts_speculations = NULL;
12644 
12645 out:
12646 	mutex_exit(&dtrace_lock);
12647 	mutex_exit(&cpu_lock);
12648 
12649 	return (rval);
12650 }
12651 
12652 static int
12653 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
12654 {
12655 	dtrace_icookie_t cookie;
12656 
12657 	ASSERT(MUTEX_HELD(&dtrace_lock));
12658 
12659 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
12660 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
12661 		return (EINVAL);
12662 
12663 	/*
12664 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
12665 	 * to be sure that every CPU has seen it.  See below for the details
12666 	 * on why this is done.
12667 	 */
12668 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
12669 	dtrace_sync();
12670 
12671 	/*
12672 	 * By this point, it is impossible for any CPU to be still processing
12673 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
12674 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
12675 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
12676 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
12677 	 * iff we're in the END probe.
12678 	 */
12679 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
12680 	dtrace_sync();
12681 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
12682 
12683 	/*
12684 	 * Finally, we can release the reserve and call the END probe.  We
12685 	 * disable interrupts across calling the END probe to allow us to
12686 	 * return the CPU on which we actually called the END probe.  This
12687 	 * allows user-land to be sure that this CPU's principal buffer is
12688 	 * processed last.
12689 	 */
12690 	state->dts_reserve = 0;
12691 
12692 	cookie = dtrace_interrupt_disable();
12693 	*cpu = CPU->cpu_id;
12694 	dtrace_probe(dtrace_probeid_end,
12695 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
12696 	dtrace_interrupt_enable(cookie);
12697 
12698 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
12699 	dtrace_sync();
12700 
12701 	return (0);
12702 }
12703 
12704 static int
12705 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
12706     dtrace_optval_t val)
12707 {
12708 	ASSERT(MUTEX_HELD(&dtrace_lock));
12709 
12710 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12711 		return (EBUSY);
12712 
12713 	if (option >= DTRACEOPT_MAX)
12714 		return (EINVAL);
12715 
12716 	if (option != DTRACEOPT_CPU && val < 0)
12717 		return (EINVAL);
12718 
12719 	switch (option) {
12720 	case DTRACEOPT_DESTRUCTIVE:
12721 		if (dtrace_destructive_disallow)
12722 			return (EACCES);
12723 
12724 		state->dts_cred.dcr_destructive = 1;
12725 		break;
12726 
12727 	case DTRACEOPT_BUFSIZE:
12728 	case DTRACEOPT_DYNVARSIZE:
12729 	case DTRACEOPT_AGGSIZE:
12730 	case DTRACEOPT_SPECSIZE:
12731 	case DTRACEOPT_STRSIZE:
12732 		if (val < 0)
12733 			return (EINVAL);
12734 
12735 		if (val >= LONG_MAX) {
12736 			/*
12737 			 * If this is an otherwise negative value, set it to
12738 			 * the highest multiple of 128m less than LONG_MAX.
12739 			 * Technically, we're adjusting the size without
12740 			 * regard to the buffer resizing policy, but in fact,
12741 			 * this has no effect -- if we set the buffer size to
12742 			 * ~LONG_MAX and the buffer policy is ultimately set to
12743 			 * be "manual", the buffer allocation is guaranteed to
12744 			 * fail, if only because the allocation requires two
12745 			 * buffers.  (We set the the size to the highest
12746 			 * multiple of 128m because it ensures that the size
12747 			 * will remain a multiple of a megabyte when
12748 			 * repeatedly halved -- all the way down to 15m.)
12749 			 */
12750 			val = LONG_MAX - (1 << 27) + 1;
12751 		}
12752 	}
12753 
12754 	state->dts_options[option] = val;
12755 
12756 	return (0);
12757 }
12758 
12759 static void
12760 dtrace_state_destroy(dtrace_state_t *state)
12761 {
12762 	dtrace_ecb_t *ecb;
12763 	dtrace_vstate_t *vstate = &state->dts_vstate;
12764 	minor_t minor = getminor(state->dts_dev);
12765 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12766 	dtrace_speculation_t *spec = state->dts_speculations;
12767 	int nspec = state->dts_nspeculations;
12768 	uint32_t match;
12769 
12770 	ASSERT(MUTEX_HELD(&dtrace_lock));
12771 	ASSERT(MUTEX_HELD(&cpu_lock));
12772 
12773 	/*
12774 	 * First, retract any retained enablings for this state.
12775 	 */
12776 	dtrace_enabling_retract(state);
12777 	ASSERT(state->dts_nretained == 0);
12778 
12779 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
12780 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
12781 		/*
12782 		 * We have managed to come into dtrace_state_destroy() on a
12783 		 * hot enabling -- almost certainly because of a disorderly
12784 		 * shutdown of a consumer.  (That is, a consumer that is
12785 		 * exiting without having called dtrace_stop().) In this case,
12786 		 * we're going to set our activity to be KILLED, and then
12787 		 * issue a sync to be sure that everyone is out of probe
12788 		 * context before we start blowing away ECBs.
12789 		 */
12790 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
12791 		dtrace_sync();
12792 	}
12793 
12794 	/*
12795 	 * Release the credential hold we took in dtrace_state_create().
12796 	 */
12797 	if (state->dts_cred.dcr_cred != NULL)
12798 		crfree(state->dts_cred.dcr_cred);
12799 
12800 	/*
12801 	 * Now we can safely disable and destroy any enabled probes.  Because
12802 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
12803 	 * (especially if they're all enabled), we take two passes through the
12804 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
12805 	 * in the second we disable whatever is left over.
12806 	 */
12807 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
12808 		for (i = 0; i < state->dts_necbs; i++) {
12809 			if ((ecb = state->dts_ecbs[i]) == NULL)
12810 				continue;
12811 
12812 			if (match && ecb->dte_probe != NULL) {
12813 				dtrace_probe_t *probe = ecb->dte_probe;
12814 				dtrace_provider_t *prov = probe->dtpr_provider;
12815 
12816 				if (!(prov->dtpv_priv.dtpp_flags & match))
12817 					continue;
12818 			}
12819 
12820 			dtrace_ecb_disable(ecb);
12821 			dtrace_ecb_destroy(ecb);
12822 		}
12823 
12824 		if (!match)
12825 			break;
12826 	}
12827 
12828 	/*
12829 	 * Before we free the buffers, perform one more sync to assure that
12830 	 * every CPU is out of probe context.
12831 	 */
12832 	dtrace_sync();
12833 
12834 	dtrace_buffer_free(state->dts_buffer);
12835 	dtrace_buffer_free(state->dts_aggbuffer);
12836 
12837 	for (i = 0; i < nspec; i++)
12838 		dtrace_buffer_free(spec[i].dtsp_buffer);
12839 
12840 	if (state->dts_cleaner != CYCLIC_NONE)
12841 		cyclic_remove(state->dts_cleaner);
12842 
12843 	if (state->dts_deadman != CYCLIC_NONE)
12844 		cyclic_remove(state->dts_deadman);
12845 
12846 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
12847 	dtrace_vstate_fini(vstate);
12848 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
12849 
12850 	if (state->dts_aggregations != NULL) {
12851 #ifdef DEBUG
12852 		for (i = 0; i < state->dts_naggregations; i++)
12853 			ASSERT(state->dts_aggregations[i] == NULL);
12854 #endif
12855 		ASSERT(state->dts_naggregations > 0);
12856 		kmem_free(state->dts_aggregations,
12857 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
12858 	}
12859 
12860 	kmem_free(state->dts_buffer, bufsize);
12861 	kmem_free(state->dts_aggbuffer, bufsize);
12862 
12863 	for (i = 0; i < nspec; i++)
12864 		kmem_free(spec[i].dtsp_buffer, bufsize);
12865 
12866 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
12867 
12868 	dtrace_format_destroy(state);
12869 
12870 	vmem_destroy(state->dts_aggid_arena);
12871 	ddi_soft_state_free(dtrace_softstate, minor);
12872 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12873 }
12874 
12875 /*
12876  * DTrace Anonymous Enabling Functions
12877  */
12878 static dtrace_state_t *
12879 dtrace_anon_grab(void)
12880 {
12881 	dtrace_state_t *state;
12882 
12883 	ASSERT(MUTEX_HELD(&dtrace_lock));
12884 
12885 	if ((state = dtrace_anon.dta_state) == NULL) {
12886 		ASSERT(dtrace_anon.dta_enabling == NULL);
12887 		return (NULL);
12888 	}
12889 
12890 	ASSERT(dtrace_anon.dta_enabling != NULL);
12891 	ASSERT(dtrace_retained != NULL);
12892 
12893 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
12894 	dtrace_anon.dta_enabling = NULL;
12895 	dtrace_anon.dta_state = NULL;
12896 
12897 	return (state);
12898 }
12899 
12900 static void
12901 dtrace_anon_property(void)
12902 {
12903 	int i, rv;
12904 	dtrace_state_t *state;
12905 	dof_hdr_t *dof;
12906 	char c[32];		/* enough for "dof-data-" + digits */
12907 
12908 	ASSERT(MUTEX_HELD(&dtrace_lock));
12909 	ASSERT(MUTEX_HELD(&cpu_lock));
12910 
12911 	for (i = 0; ; i++) {
12912 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
12913 
12914 		dtrace_err_verbose = 1;
12915 
12916 		if ((dof = dtrace_dof_property(c)) == NULL) {
12917 			dtrace_err_verbose = 0;
12918 			break;
12919 		}
12920 
12921 		/*
12922 		 * We want to create anonymous state, so we need to transition
12923 		 * the kernel debugger to indicate that DTrace is active.  If
12924 		 * this fails (e.g. because the debugger has modified text in
12925 		 * some way), we won't continue with the processing.
12926 		 */
12927 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
12928 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
12929 			    "enabling ignored.");
12930 			dtrace_dof_destroy(dof);
12931 			break;
12932 		}
12933 
12934 		/*
12935 		 * If we haven't allocated an anonymous state, we'll do so now.
12936 		 */
12937 		if ((state = dtrace_anon.dta_state) == NULL) {
12938 			state = dtrace_state_create(NULL, NULL);
12939 			dtrace_anon.dta_state = state;
12940 
12941 			if (state == NULL) {
12942 				/*
12943 				 * This basically shouldn't happen:  the only
12944 				 * failure mode from dtrace_state_create() is a
12945 				 * failure of ddi_soft_state_zalloc() that
12946 				 * itself should never happen.  Still, the
12947 				 * interface allows for a failure mode, and
12948 				 * we want to fail as gracefully as possible:
12949 				 * we'll emit an error message and cease
12950 				 * processing anonymous state in this case.
12951 				 */
12952 				cmn_err(CE_WARN, "failed to create "
12953 				    "anonymous state");
12954 				dtrace_dof_destroy(dof);
12955 				break;
12956 			}
12957 		}
12958 
12959 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
12960 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
12961 
12962 		if (rv == 0)
12963 			rv = dtrace_dof_options(dof, state);
12964 
12965 		dtrace_err_verbose = 0;
12966 		dtrace_dof_destroy(dof);
12967 
12968 		if (rv != 0) {
12969 			/*
12970 			 * This is malformed DOF; chuck any anonymous state
12971 			 * that we created.
12972 			 */
12973 			ASSERT(dtrace_anon.dta_enabling == NULL);
12974 			dtrace_state_destroy(state);
12975 			dtrace_anon.dta_state = NULL;
12976 			break;
12977 		}
12978 
12979 		ASSERT(dtrace_anon.dta_enabling != NULL);
12980 	}
12981 
12982 	if (dtrace_anon.dta_enabling != NULL) {
12983 		int rval;
12984 
12985 		/*
12986 		 * dtrace_enabling_retain() can only fail because we are
12987 		 * trying to retain more enablings than are allowed -- but
12988 		 * we only have one anonymous enabling, and we are guaranteed
12989 		 * to be allowed at least one retained enabling; we assert
12990 		 * that dtrace_enabling_retain() returns success.
12991 		 */
12992 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
12993 		ASSERT(rval == 0);
12994 
12995 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
12996 	}
12997 }
12998 
12999 /*
13000  * DTrace Helper Functions
13001  */
13002 static void
13003 dtrace_helper_trace(dtrace_helper_action_t *helper,
13004     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
13005 {
13006 	uint32_t size, next, nnext, i;
13007 	dtrace_helptrace_t *ent;
13008 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13009 
13010 	if (!dtrace_helptrace_enabled)
13011 		return;
13012 
13013 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
13014 
13015 	/*
13016 	 * What would a tracing framework be without its own tracing
13017 	 * framework?  (Well, a hell of a lot simpler, for starters...)
13018 	 */
13019 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
13020 	    sizeof (uint64_t) - sizeof (uint64_t);
13021 
13022 	/*
13023 	 * Iterate until we can allocate a slot in the trace buffer.
13024 	 */
13025 	do {
13026 		next = dtrace_helptrace_next;
13027 
13028 		if (next + size < dtrace_helptrace_bufsize) {
13029 			nnext = next + size;
13030 		} else {
13031 			nnext = size;
13032 		}
13033 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
13034 
13035 	/*
13036 	 * We have our slot; fill it in.
13037 	 */
13038 	if (nnext == size)
13039 		next = 0;
13040 
13041 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
13042 	ent->dtht_helper = helper;
13043 	ent->dtht_where = where;
13044 	ent->dtht_nlocals = vstate->dtvs_nlocals;
13045 
13046 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
13047 	    mstate->dtms_fltoffs : -1;
13048 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
13049 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
13050 
13051 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
13052 		dtrace_statvar_t *svar;
13053 
13054 		if ((svar = vstate->dtvs_locals[i]) == NULL)
13055 			continue;
13056 
13057 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
13058 		ent->dtht_locals[i] =
13059 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
13060 	}
13061 }
13062 
13063 static uint64_t
13064 dtrace_helper(int which, dtrace_mstate_t *mstate,
13065     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
13066 {
13067 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
13068 	uint64_t sarg0 = mstate->dtms_arg[0];
13069 	uint64_t sarg1 = mstate->dtms_arg[1];
13070 	uint64_t rval;
13071 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
13072 	dtrace_helper_action_t *helper;
13073 	dtrace_vstate_t *vstate;
13074 	dtrace_difo_t *pred;
13075 	int i, trace = dtrace_helptrace_enabled;
13076 
13077 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
13078 
13079 	if (helpers == NULL)
13080 		return (0);
13081 
13082 	if ((helper = helpers->dthps_actions[which]) == NULL)
13083 		return (0);
13084 
13085 	vstate = &helpers->dthps_vstate;
13086 	mstate->dtms_arg[0] = arg0;
13087 	mstate->dtms_arg[1] = arg1;
13088 
13089 	/*
13090 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
13091 	 * we'll call the corresponding actions.  Note that the below calls
13092 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
13093 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
13094 	 * the stored DIF offset with its own (which is the desired behavior).
13095 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
13096 	 * from machine state; this is okay, too.
13097 	 */
13098 	for (; helper != NULL; helper = helper->dtha_next) {
13099 		if ((pred = helper->dtha_predicate) != NULL) {
13100 			if (trace)
13101 				dtrace_helper_trace(helper, mstate, vstate, 0);
13102 
13103 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
13104 				goto next;
13105 
13106 			if (*flags & CPU_DTRACE_FAULT)
13107 				goto err;
13108 		}
13109 
13110 		for (i = 0; i < helper->dtha_nactions; i++) {
13111 			if (trace)
13112 				dtrace_helper_trace(helper,
13113 				    mstate, vstate, i + 1);
13114 
13115 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
13116 			    mstate, vstate, state);
13117 
13118 			if (*flags & CPU_DTRACE_FAULT)
13119 				goto err;
13120 		}
13121 
13122 next:
13123 		if (trace)
13124 			dtrace_helper_trace(helper, mstate, vstate,
13125 			    DTRACE_HELPTRACE_NEXT);
13126 	}
13127 
13128 	if (trace)
13129 		dtrace_helper_trace(helper, mstate, vstate,
13130 		    DTRACE_HELPTRACE_DONE);
13131 
13132 	/*
13133 	 * Restore the arg0 that we saved upon entry.
13134 	 */
13135 	mstate->dtms_arg[0] = sarg0;
13136 	mstate->dtms_arg[1] = sarg1;
13137 
13138 	return (rval);
13139 
13140 err:
13141 	if (trace)
13142 		dtrace_helper_trace(helper, mstate, vstate,
13143 		    DTRACE_HELPTRACE_ERR);
13144 
13145 	/*
13146 	 * Restore the arg0 that we saved upon entry.
13147 	 */
13148 	mstate->dtms_arg[0] = sarg0;
13149 	mstate->dtms_arg[1] = sarg1;
13150 
13151 	return (NULL);
13152 }
13153 
13154 static void
13155 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
13156     dtrace_vstate_t *vstate)
13157 {
13158 	int i;
13159 
13160 	if (helper->dtha_predicate != NULL)
13161 		dtrace_difo_release(helper->dtha_predicate, vstate);
13162 
13163 	for (i = 0; i < helper->dtha_nactions; i++) {
13164 		ASSERT(helper->dtha_actions[i] != NULL);
13165 		dtrace_difo_release(helper->dtha_actions[i], vstate);
13166 	}
13167 
13168 	kmem_free(helper->dtha_actions,
13169 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
13170 	kmem_free(helper, sizeof (dtrace_helper_action_t));
13171 }
13172 
13173 static int
13174 dtrace_helper_destroygen(int gen)
13175 {
13176 	proc_t *p = curproc;
13177 	dtrace_helpers_t *help = p->p_dtrace_helpers;
13178 	dtrace_vstate_t *vstate;
13179 	int i;
13180 
13181 	ASSERT(MUTEX_HELD(&dtrace_lock));
13182 
13183 	if (help == NULL || gen > help->dthps_generation)
13184 		return (EINVAL);
13185 
13186 	vstate = &help->dthps_vstate;
13187 
13188 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13189 		dtrace_helper_action_t *last = NULL, *h, *next;
13190 
13191 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13192 			next = h->dtha_next;
13193 
13194 			if (h->dtha_generation == gen) {
13195 				if (last != NULL) {
13196 					last->dtha_next = next;
13197 				} else {
13198 					help->dthps_actions[i] = next;
13199 				}
13200 
13201 				dtrace_helper_action_destroy(h, vstate);
13202 			} else {
13203 				last = h;
13204 			}
13205 		}
13206 	}
13207 
13208 	/*
13209 	 * Interate until we've cleared out all helper providers with the
13210 	 * given generation number.
13211 	 */
13212 	for (;;) {
13213 		dtrace_helper_provider_t *prov;
13214 
13215 		/*
13216 		 * Look for a helper provider with the right generation. We
13217 		 * have to start back at the beginning of the list each time
13218 		 * because we drop dtrace_lock. It's unlikely that we'll make
13219 		 * more than two passes.
13220 		 */
13221 		for (i = 0; i < help->dthps_nprovs; i++) {
13222 			prov = help->dthps_provs[i];
13223 
13224 			if (prov->dthp_generation == gen)
13225 				break;
13226 		}
13227 
13228 		/*
13229 		 * If there were no matches, we're done.
13230 		 */
13231 		if (i == help->dthps_nprovs)
13232 			break;
13233 
13234 		/*
13235 		 * Move the last helper provider into this slot.
13236 		 */
13237 		help->dthps_nprovs--;
13238 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
13239 		help->dthps_provs[help->dthps_nprovs] = NULL;
13240 
13241 		mutex_exit(&dtrace_lock);
13242 
13243 		/*
13244 		 * If we have a meta provider, remove this helper provider.
13245 		 */
13246 		mutex_enter(&dtrace_meta_lock);
13247 		if (dtrace_meta_pid != NULL) {
13248 			ASSERT(dtrace_deferred_pid == NULL);
13249 			dtrace_helper_provider_remove(&prov->dthp_prov,
13250 			    p->p_pid);
13251 		}
13252 		mutex_exit(&dtrace_meta_lock);
13253 
13254 		dtrace_helper_provider_destroy(prov);
13255 
13256 		mutex_enter(&dtrace_lock);
13257 	}
13258 
13259 	return (0);
13260 }
13261 
13262 static int
13263 dtrace_helper_validate(dtrace_helper_action_t *helper)
13264 {
13265 	int err = 0, i;
13266 	dtrace_difo_t *dp;
13267 
13268 	if ((dp = helper->dtha_predicate) != NULL)
13269 		err += dtrace_difo_validate_helper(dp);
13270 
13271 	for (i = 0; i < helper->dtha_nactions; i++)
13272 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
13273 
13274 	return (err == 0);
13275 }
13276 
13277 static int
13278 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
13279 {
13280 	dtrace_helpers_t *help;
13281 	dtrace_helper_action_t *helper, *last;
13282 	dtrace_actdesc_t *act;
13283 	dtrace_vstate_t *vstate;
13284 	dtrace_predicate_t *pred;
13285 	int count = 0, nactions = 0, i;
13286 
13287 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
13288 		return (EINVAL);
13289 
13290 	help = curproc->p_dtrace_helpers;
13291 	last = help->dthps_actions[which];
13292 	vstate = &help->dthps_vstate;
13293 
13294 	for (count = 0; last != NULL; last = last->dtha_next) {
13295 		count++;
13296 		if (last->dtha_next == NULL)
13297 			break;
13298 	}
13299 
13300 	/*
13301 	 * If we already have dtrace_helper_actions_max helper actions for this
13302 	 * helper action type, we'll refuse to add a new one.
13303 	 */
13304 	if (count >= dtrace_helper_actions_max)
13305 		return (ENOSPC);
13306 
13307 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
13308 	helper->dtha_generation = help->dthps_generation;
13309 
13310 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
13311 		ASSERT(pred->dtp_difo != NULL);
13312 		dtrace_difo_hold(pred->dtp_difo);
13313 		helper->dtha_predicate = pred->dtp_difo;
13314 	}
13315 
13316 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
13317 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
13318 			goto err;
13319 
13320 		if (act->dtad_difo == NULL)
13321 			goto err;
13322 
13323 		nactions++;
13324 	}
13325 
13326 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
13327 	    (helper->dtha_nactions = nactions), KM_SLEEP);
13328 
13329 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
13330 		dtrace_difo_hold(act->dtad_difo);
13331 		helper->dtha_actions[i++] = act->dtad_difo;
13332 	}
13333 
13334 	if (!dtrace_helper_validate(helper))
13335 		goto err;
13336 
13337 	if (last == NULL) {
13338 		help->dthps_actions[which] = helper;
13339 	} else {
13340 		last->dtha_next = helper;
13341 	}
13342 
13343 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
13344 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
13345 		dtrace_helptrace_next = 0;
13346 	}
13347 
13348 	return (0);
13349 err:
13350 	dtrace_helper_action_destroy(helper, vstate);
13351 	return (EINVAL);
13352 }
13353 
13354 static void
13355 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
13356     dof_helper_t *dofhp)
13357 {
13358 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
13359 
13360 	mutex_enter(&dtrace_meta_lock);
13361 	mutex_enter(&dtrace_lock);
13362 
13363 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
13364 		/*
13365 		 * If the dtrace module is loaded but not attached, or if
13366 		 * there aren't isn't a meta provider registered to deal with
13367 		 * these provider descriptions, we need to postpone creating
13368 		 * the actual providers until later.
13369 		 */
13370 
13371 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
13372 		    dtrace_deferred_pid != help) {
13373 			help->dthps_deferred = 1;
13374 			help->dthps_pid = p->p_pid;
13375 			help->dthps_next = dtrace_deferred_pid;
13376 			help->dthps_prev = NULL;
13377 			if (dtrace_deferred_pid != NULL)
13378 				dtrace_deferred_pid->dthps_prev = help;
13379 			dtrace_deferred_pid = help;
13380 		}
13381 
13382 		mutex_exit(&dtrace_lock);
13383 
13384 	} else if (dofhp != NULL) {
13385 		/*
13386 		 * If the dtrace module is loaded and we have a particular
13387 		 * helper provider description, pass that off to the
13388 		 * meta provider.
13389 		 */
13390 
13391 		mutex_exit(&dtrace_lock);
13392 
13393 		dtrace_helper_provide(dofhp, p->p_pid);
13394 
13395 	} else {
13396 		/*
13397 		 * Otherwise, just pass all the helper provider descriptions
13398 		 * off to the meta provider.
13399 		 */
13400 
13401 		int i;
13402 		mutex_exit(&dtrace_lock);
13403 
13404 		for (i = 0; i < help->dthps_nprovs; i++) {
13405 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
13406 			    p->p_pid);
13407 		}
13408 	}
13409 
13410 	mutex_exit(&dtrace_meta_lock);
13411 }
13412 
13413 static int
13414 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
13415 {
13416 	dtrace_helpers_t *help;
13417 	dtrace_helper_provider_t *hprov, **tmp_provs;
13418 	uint_t tmp_maxprovs, i;
13419 
13420 	ASSERT(MUTEX_HELD(&dtrace_lock));
13421 
13422 	help = curproc->p_dtrace_helpers;
13423 	ASSERT(help != NULL);
13424 
13425 	/*
13426 	 * If we already have dtrace_helper_providers_max helper providers,
13427 	 * we're refuse to add a new one.
13428 	 */
13429 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
13430 		return (ENOSPC);
13431 
13432 	/*
13433 	 * Check to make sure this isn't a duplicate.
13434 	 */
13435 	for (i = 0; i < help->dthps_nprovs; i++) {
13436 		if (dofhp->dofhp_addr ==
13437 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
13438 			return (EALREADY);
13439 	}
13440 
13441 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
13442 	hprov->dthp_prov = *dofhp;
13443 	hprov->dthp_ref = 1;
13444 	hprov->dthp_generation = gen;
13445 
13446 	/*
13447 	 * Allocate a bigger table for helper providers if it's already full.
13448 	 */
13449 	if (help->dthps_maxprovs == help->dthps_nprovs) {
13450 		tmp_maxprovs = help->dthps_maxprovs;
13451 		tmp_provs = help->dthps_provs;
13452 
13453 		if (help->dthps_maxprovs == 0)
13454 			help->dthps_maxprovs = 2;
13455 		else
13456 			help->dthps_maxprovs *= 2;
13457 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
13458 			help->dthps_maxprovs = dtrace_helper_providers_max;
13459 
13460 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
13461 
13462 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
13463 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13464 
13465 		if (tmp_provs != NULL) {
13466 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
13467 			    sizeof (dtrace_helper_provider_t *));
13468 			kmem_free(tmp_provs, tmp_maxprovs *
13469 			    sizeof (dtrace_helper_provider_t *));
13470 		}
13471 	}
13472 
13473 	help->dthps_provs[help->dthps_nprovs] = hprov;
13474 	help->dthps_nprovs++;
13475 
13476 	return (0);
13477 }
13478 
13479 static void
13480 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
13481 {
13482 	mutex_enter(&dtrace_lock);
13483 
13484 	if (--hprov->dthp_ref == 0) {
13485 		dof_hdr_t *dof;
13486 		mutex_exit(&dtrace_lock);
13487 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
13488 		dtrace_dof_destroy(dof);
13489 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
13490 	} else {
13491 		mutex_exit(&dtrace_lock);
13492 	}
13493 }
13494 
13495 static int
13496 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
13497 {
13498 	uintptr_t daddr = (uintptr_t)dof;
13499 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
13500 	dof_provider_t *provider;
13501 	dof_probe_t *probe;
13502 	uint8_t *arg;
13503 	char *strtab, *typestr;
13504 	dof_stridx_t typeidx;
13505 	size_t typesz;
13506 	uint_t nprobes, j, k;
13507 
13508 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
13509 
13510 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
13511 		dtrace_dof_error(dof, "misaligned section offset");
13512 		return (-1);
13513 	}
13514 
13515 	/*
13516 	 * The section needs to be large enough to contain the DOF provider
13517 	 * structure appropriate for the given version.
13518 	 */
13519 	if (sec->dofs_size <
13520 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
13521 	    offsetof(dof_provider_t, dofpv_prenoffs) :
13522 	    sizeof (dof_provider_t))) {
13523 		dtrace_dof_error(dof, "provider section too small");
13524 		return (-1);
13525 	}
13526 
13527 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
13528 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
13529 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
13530 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
13531 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
13532 
13533 	if (str_sec == NULL || prb_sec == NULL ||
13534 	    arg_sec == NULL || off_sec == NULL)
13535 		return (-1);
13536 
13537 	enoff_sec = NULL;
13538 
13539 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13540 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
13541 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
13542 	    provider->dofpv_prenoffs)) == NULL)
13543 		return (-1);
13544 
13545 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
13546 
13547 	if (provider->dofpv_name >= str_sec->dofs_size ||
13548 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
13549 		dtrace_dof_error(dof, "invalid provider name");
13550 		return (-1);
13551 	}
13552 
13553 	if (prb_sec->dofs_entsize == 0 ||
13554 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
13555 		dtrace_dof_error(dof, "invalid entry size");
13556 		return (-1);
13557 	}
13558 
13559 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
13560 		dtrace_dof_error(dof, "misaligned entry size");
13561 		return (-1);
13562 	}
13563 
13564 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
13565 		dtrace_dof_error(dof, "invalid entry size");
13566 		return (-1);
13567 	}
13568 
13569 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
13570 		dtrace_dof_error(dof, "misaligned section offset");
13571 		return (-1);
13572 	}
13573 
13574 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
13575 		dtrace_dof_error(dof, "invalid entry size");
13576 		return (-1);
13577 	}
13578 
13579 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
13580 
13581 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
13582 
13583 	/*
13584 	 * Take a pass through the probes to check for errors.
13585 	 */
13586 	for (j = 0; j < nprobes; j++) {
13587 		probe = (dof_probe_t *)(uintptr_t)(daddr +
13588 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
13589 
13590 		if (probe->dofpr_func >= str_sec->dofs_size) {
13591 			dtrace_dof_error(dof, "invalid function name");
13592 			return (-1);
13593 		}
13594 
13595 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
13596 			dtrace_dof_error(dof, "function name too long");
13597 			return (-1);
13598 		}
13599 
13600 		if (probe->dofpr_name >= str_sec->dofs_size ||
13601 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
13602 			dtrace_dof_error(dof, "invalid probe name");
13603 			return (-1);
13604 		}
13605 
13606 		/*
13607 		 * The offset count must not wrap the index, and the offsets
13608 		 * must also not overflow the section's data.
13609 		 */
13610 		if (probe->dofpr_offidx + probe->dofpr_noffs <
13611 		    probe->dofpr_offidx ||
13612 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
13613 		    off_sec->dofs_entsize > off_sec->dofs_size) {
13614 			dtrace_dof_error(dof, "invalid probe offset");
13615 			return (-1);
13616 		}
13617 
13618 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
13619 			/*
13620 			 * If there's no is-enabled offset section, make sure
13621 			 * there aren't any is-enabled offsets. Otherwise
13622 			 * perform the same checks as for probe offsets
13623 			 * (immediately above).
13624 			 */
13625 			if (enoff_sec == NULL) {
13626 				if (probe->dofpr_enoffidx != 0 ||
13627 				    probe->dofpr_nenoffs != 0) {
13628 					dtrace_dof_error(dof, "is-enabled "
13629 					    "offsets with null section");
13630 					return (-1);
13631 				}
13632 			} else if (probe->dofpr_enoffidx +
13633 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
13634 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
13635 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
13636 				dtrace_dof_error(dof, "invalid is-enabled "
13637 				    "offset");
13638 				return (-1);
13639 			}
13640 
13641 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
13642 				dtrace_dof_error(dof, "zero probe and "
13643 				    "is-enabled offsets");
13644 				return (-1);
13645 			}
13646 		} else if (probe->dofpr_noffs == 0) {
13647 			dtrace_dof_error(dof, "zero probe offsets");
13648 			return (-1);
13649 		}
13650 
13651 		if (probe->dofpr_argidx + probe->dofpr_xargc <
13652 		    probe->dofpr_argidx ||
13653 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
13654 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
13655 			dtrace_dof_error(dof, "invalid args");
13656 			return (-1);
13657 		}
13658 
13659 		typeidx = probe->dofpr_nargv;
13660 		typestr = strtab + probe->dofpr_nargv;
13661 		for (k = 0; k < probe->dofpr_nargc; k++) {
13662 			if (typeidx >= str_sec->dofs_size) {
13663 				dtrace_dof_error(dof, "bad "
13664 				    "native argument type");
13665 				return (-1);
13666 			}
13667 
13668 			typesz = strlen(typestr) + 1;
13669 			if (typesz > DTRACE_ARGTYPELEN) {
13670 				dtrace_dof_error(dof, "native "
13671 				    "argument type too long");
13672 				return (-1);
13673 			}
13674 			typeidx += typesz;
13675 			typestr += typesz;
13676 		}
13677 
13678 		typeidx = probe->dofpr_xargv;
13679 		typestr = strtab + probe->dofpr_xargv;
13680 		for (k = 0; k < probe->dofpr_xargc; k++) {
13681 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
13682 				dtrace_dof_error(dof, "bad "
13683 				    "native argument index");
13684 				return (-1);
13685 			}
13686 
13687 			if (typeidx >= str_sec->dofs_size) {
13688 				dtrace_dof_error(dof, "bad "
13689 				    "translated argument type");
13690 				return (-1);
13691 			}
13692 
13693 			typesz = strlen(typestr) + 1;
13694 			if (typesz > DTRACE_ARGTYPELEN) {
13695 				dtrace_dof_error(dof, "translated argument "
13696 				    "type too long");
13697 				return (-1);
13698 			}
13699 
13700 			typeidx += typesz;
13701 			typestr += typesz;
13702 		}
13703 	}
13704 
13705 	return (0);
13706 }
13707 
13708 static int
13709 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
13710 {
13711 	dtrace_helpers_t *help;
13712 	dtrace_vstate_t *vstate;
13713 	dtrace_enabling_t *enab = NULL;
13714 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
13715 	uintptr_t daddr = (uintptr_t)dof;
13716 
13717 	ASSERT(MUTEX_HELD(&dtrace_lock));
13718 
13719 	if ((help = curproc->p_dtrace_helpers) == NULL)
13720 		help = dtrace_helpers_create(curproc);
13721 
13722 	vstate = &help->dthps_vstate;
13723 
13724 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
13725 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
13726 		dtrace_dof_destroy(dof);
13727 		return (rv);
13728 	}
13729 
13730 	/*
13731 	 * Look for helper providers and validate their descriptions.
13732 	 */
13733 	if (dhp != NULL) {
13734 		for (i = 0; i < dof->dofh_secnum; i++) {
13735 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
13736 			    dof->dofh_secoff + i * dof->dofh_secsize);
13737 
13738 			if (sec->dofs_type != DOF_SECT_PROVIDER)
13739 				continue;
13740 
13741 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
13742 				dtrace_enabling_destroy(enab);
13743 				dtrace_dof_destroy(dof);
13744 				return (-1);
13745 			}
13746 
13747 			nprovs++;
13748 		}
13749 	}
13750 
13751 	/*
13752 	 * Now we need to walk through the ECB descriptions in the enabling.
13753 	 */
13754 	for (i = 0; i < enab->dten_ndesc; i++) {
13755 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
13756 		dtrace_probedesc_t *desc = &ep->dted_probe;
13757 
13758 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
13759 			continue;
13760 
13761 		if (strcmp(desc->dtpd_mod, "helper") != 0)
13762 			continue;
13763 
13764 		if (strcmp(desc->dtpd_func, "ustack") != 0)
13765 			continue;
13766 
13767 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
13768 		    ep)) != 0) {
13769 			/*
13770 			 * Adding this helper action failed -- we are now going
13771 			 * to rip out the entire generation and return failure.
13772 			 */
13773 			(void) dtrace_helper_destroygen(help->dthps_generation);
13774 			dtrace_enabling_destroy(enab);
13775 			dtrace_dof_destroy(dof);
13776 			return (-1);
13777 		}
13778 
13779 		nhelpers++;
13780 	}
13781 
13782 	if (nhelpers < enab->dten_ndesc)
13783 		dtrace_dof_error(dof, "unmatched helpers");
13784 
13785 	gen = help->dthps_generation++;
13786 	dtrace_enabling_destroy(enab);
13787 
13788 	if (dhp != NULL && nprovs > 0) {
13789 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
13790 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
13791 			mutex_exit(&dtrace_lock);
13792 			dtrace_helper_provider_register(curproc, help, dhp);
13793 			mutex_enter(&dtrace_lock);
13794 
13795 			destroy = 0;
13796 		}
13797 	}
13798 
13799 	if (destroy)
13800 		dtrace_dof_destroy(dof);
13801 
13802 	return (gen);
13803 }
13804 
13805 static dtrace_helpers_t *
13806 dtrace_helpers_create(proc_t *p)
13807 {
13808 	dtrace_helpers_t *help;
13809 
13810 	ASSERT(MUTEX_HELD(&dtrace_lock));
13811 	ASSERT(p->p_dtrace_helpers == NULL);
13812 
13813 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
13814 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
13815 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
13816 
13817 	p->p_dtrace_helpers = help;
13818 	dtrace_helpers++;
13819 
13820 	return (help);
13821 }
13822 
13823 static void
13824 dtrace_helpers_destroy(void)
13825 {
13826 	dtrace_helpers_t *help;
13827 	dtrace_vstate_t *vstate;
13828 	proc_t *p = curproc;
13829 	int i;
13830 
13831 	mutex_enter(&dtrace_lock);
13832 
13833 	ASSERT(p->p_dtrace_helpers != NULL);
13834 	ASSERT(dtrace_helpers > 0);
13835 
13836 	help = p->p_dtrace_helpers;
13837 	vstate = &help->dthps_vstate;
13838 
13839 	/*
13840 	 * We're now going to lose the help from this process.
13841 	 */
13842 	p->p_dtrace_helpers = NULL;
13843 	dtrace_sync();
13844 
13845 	/*
13846 	 * Destory the helper actions.
13847 	 */
13848 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13849 		dtrace_helper_action_t *h, *next;
13850 
13851 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13852 			next = h->dtha_next;
13853 			dtrace_helper_action_destroy(h, vstate);
13854 			h = next;
13855 		}
13856 	}
13857 
13858 	mutex_exit(&dtrace_lock);
13859 
13860 	/*
13861 	 * Destroy the helper providers.
13862 	 */
13863 	if (help->dthps_maxprovs > 0) {
13864 		mutex_enter(&dtrace_meta_lock);
13865 		if (dtrace_meta_pid != NULL) {
13866 			ASSERT(dtrace_deferred_pid == NULL);
13867 
13868 			for (i = 0; i < help->dthps_nprovs; i++) {
13869 				dtrace_helper_provider_remove(
13870 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
13871 			}
13872 		} else {
13873 			mutex_enter(&dtrace_lock);
13874 			ASSERT(help->dthps_deferred == 0 ||
13875 			    help->dthps_next != NULL ||
13876 			    help->dthps_prev != NULL ||
13877 			    help == dtrace_deferred_pid);
13878 
13879 			/*
13880 			 * Remove the helper from the deferred list.
13881 			 */
13882 			if (help->dthps_next != NULL)
13883 				help->dthps_next->dthps_prev = help->dthps_prev;
13884 			if (help->dthps_prev != NULL)
13885 				help->dthps_prev->dthps_next = help->dthps_next;
13886 			if (dtrace_deferred_pid == help) {
13887 				dtrace_deferred_pid = help->dthps_next;
13888 				ASSERT(help->dthps_prev == NULL);
13889 			}
13890 
13891 			mutex_exit(&dtrace_lock);
13892 		}
13893 
13894 		mutex_exit(&dtrace_meta_lock);
13895 
13896 		for (i = 0; i < help->dthps_nprovs; i++) {
13897 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
13898 		}
13899 
13900 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
13901 		    sizeof (dtrace_helper_provider_t *));
13902 	}
13903 
13904 	mutex_enter(&dtrace_lock);
13905 
13906 	dtrace_vstate_fini(&help->dthps_vstate);
13907 	kmem_free(help->dthps_actions,
13908 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
13909 	kmem_free(help, sizeof (dtrace_helpers_t));
13910 
13911 	--dtrace_helpers;
13912 	mutex_exit(&dtrace_lock);
13913 }
13914 
13915 static void
13916 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
13917 {
13918 	dtrace_helpers_t *help, *newhelp;
13919 	dtrace_helper_action_t *helper, *new, *last;
13920 	dtrace_difo_t *dp;
13921 	dtrace_vstate_t *vstate;
13922 	int i, j, sz, hasprovs = 0;
13923 
13924 	mutex_enter(&dtrace_lock);
13925 	ASSERT(from->p_dtrace_helpers != NULL);
13926 	ASSERT(dtrace_helpers > 0);
13927 
13928 	help = from->p_dtrace_helpers;
13929 	newhelp = dtrace_helpers_create(to);
13930 	ASSERT(to->p_dtrace_helpers != NULL);
13931 
13932 	newhelp->dthps_generation = help->dthps_generation;
13933 	vstate = &newhelp->dthps_vstate;
13934 
13935 	/*
13936 	 * Duplicate the helper actions.
13937 	 */
13938 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13939 		if ((helper = help->dthps_actions[i]) == NULL)
13940 			continue;
13941 
13942 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
13943 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
13944 			    KM_SLEEP);
13945 			new->dtha_generation = helper->dtha_generation;
13946 
13947 			if ((dp = helper->dtha_predicate) != NULL) {
13948 				dp = dtrace_difo_duplicate(dp, vstate);
13949 				new->dtha_predicate = dp;
13950 			}
13951 
13952 			new->dtha_nactions = helper->dtha_nactions;
13953 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
13954 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
13955 
13956 			for (j = 0; j < new->dtha_nactions; j++) {
13957 				dtrace_difo_t *dp = helper->dtha_actions[j];
13958 
13959 				ASSERT(dp != NULL);
13960 				dp = dtrace_difo_duplicate(dp, vstate);
13961 				new->dtha_actions[j] = dp;
13962 			}
13963 
13964 			if (last != NULL) {
13965 				last->dtha_next = new;
13966 			} else {
13967 				newhelp->dthps_actions[i] = new;
13968 			}
13969 
13970 			last = new;
13971 		}
13972 	}
13973 
13974 	/*
13975 	 * Duplicate the helper providers and register them with the
13976 	 * DTrace framework.
13977 	 */
13978 	if (help->dthps_nprovs > 0) {
13979 		newhelp->dthps_nprovs = help->dthps_nprovs;
13980 		newhelp->dthps_maxprovs = help->dthps_nprovs;
13981 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
13982 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13983 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
13984 			newhelp->dthps_provs[i] = help->dthps_provs[i];
13985 			newhelp->dthps_provs[i]->dthp_ref++;
13986 		}
13987 
13988 		hasprovs = 1;
13989 	}
13990 
13991 	mutex_exit(&dtrace_lock);
13992 
13993 	if (hasprovs)
13994 		dtrace_helper_provider_register(to, newhelp, NULL);
13995 }
13996 
13997 /*
13998  * DTrace Hook Functions
13999  */
14000 static void
14001 dtrace_module_loaded(struct modctl *ctl)
14002 {
14003 	dtrace_provider_t *prv;
14004 
14005 	mutex_enter(&dtrace_provider_lock);
14006 	mutex_enter(&mod_lock);
14007 
14008 	ASSERT(ctl->mod_busy);
14009 
14010 	/*
14011 	 * We're going to call each providers per-module provide operation
14012 	 * specifying only this module.
14013 	 */
14014 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
14015 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
14016 
14017 	mutex_exit(&mod_lock);
14018 	mutex_exit(&dtrace_provider_lock);
14019 
14020 	/*
14021 	 * If we have any retained enablings, we need to match against them.
14022 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
14023 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
14024 	 * module.  (In particular, this happens when loading scheduling
14025 	 * classes.)  So if we have any retained enablings, we need to dispatch
14026 	 * our task queue to do the match for us.
14027 	 */
14028 	mutex_enter(&dtrace_lock);
14029 
14030 	if (dtrace_retained == NULL) {
14031 		mutex_exit(&dtrace_lock);
14032 		return;
14033 	}
14034 
14035 	(void) taskq_dispatch(dtrace_taskq,
14036 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
14037 
14038 	mutex_exit(&dtrace_lock);
14039 
14040 	/*
14041 	 * And now, for a little heuristic sleaze:  in general, we want to
14042 	 * match modules as soon as they load.  However, we cannot guarantee
14043 	 * this, because it would lead us to the lock ordering violation
14044 	 * outlined above.  The common case, of course, is that cpu_lock is
14045 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
14046 	 * long enough for the task queue to do its work.  If it's not, it's
14047 	 * not a serious problem -- it just means that the module that we
14048 	 * just loaded may not be immediately instrumentable.
14049 	 */
14050 	delay(1);
14051 }
14052 
14053 static void
14054 dtrace_module_unloaded(struct modctl *ctl)
14055 {
14056 	dtrace_probe_t template, *probe, *first, *next;
14057 	dtrace_provider_t *prov;
14058 
14059 	template.dtpr_mod = ctl->mod_modname;
14060 
14061 	mutex_enter(&dtrace_provider_lock);
14062 	mutex_enter(&mod_lock);
14063 	mutex_enter(&dtrace_lock);
14064 
14065 	if (dtrace_bymod == NULL) {
14066 		/*
14067 		 * The DTrace module is loaded (obviously) but not attached;
14068 		 * we don't have any work to do.
14069 		 */
14070 		mutex_exit(&dtrace_provider_lock);
14071 		mutex_exit(&mod_lock);
14072 		mutex_exit(&dtrace_lock);
14073 		return;
14074 	}
14075 
14076 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
14077 	    probe != NULL; probe = probe->dtpr_nextmod) {
14078 		if (probe->dtpr_ecb != NULL) {
14079 			mutex_exit(&dtrace_provider_lock);
14080 			mutex_exit(&mod_lock);
14081 			mutex_exit(&dtrace_lock);
14082 
14083 			/*
14084 			 * This shouldn't _actually_ be possible -- we're
14085 			 * unloading a module that has an enabled probe in it.
14086 			 * (It's normally up to the provider to make sure that
14087 			 * this can't happen.)  However, because dtps_enable()
14088 			 * doesn't have a failure mode, there can be an
14089 			 * enable/unload race.  Upshot:  we don't want to
14090 			 * assert, but we're not going to disable the
14091 			 * probe, either.
14092 			 */
14093 			if (dtrace_err_verbose) {
14094 				cmn_err(CE_WARN, "unloaded module '%s' had "
14095 				    "enabled probes", ctl->mod_modname);
14096 			}
14097 
14098 			return;
14099 		}
14100 	}
14101 
14102 	probe = first;
14103 
14104 	for (first = NULL; probe != NULL; probe = next) {
14105 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
14106 
14107 		dtrace_probes[probe->dtpr_id - 1] = NULL;
14108 
14109 		next = probe->dtpr_nextmod;
14110 		dtrace_hash_remove(dtrace_bymod, probe);
14111 		dtrace_hash_remove(dtrace_byfunc, probe);
14112 		dtrace_hash_remove(dtrace_byname, probe);
14113 
14114 		if (first == NULL) {
14115 			first = probe;
14116 			probe->dtpr_nextmod = NULL;
14117 		} else {
14118 			probe->dtpr_nextmod = first;
14119 			first = probe;
14120 		}
14121 	}
14122 
14123 	/*
14124 	 * We've removed all of the module's probes from the hash chains and
14125 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
14126 	 * everyone has cleared out from any probe array processing.
14127 	 */
14128 	dtrace_sync();
14129 
14130 	for (probe = first; probe != NULL; probe = first) {
14131 		first = probe->dtpr_nextmod;
14132 		prov = probe->dtpr_provider;
14133 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
14134 		    probe->dtpr_arg);
14135 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
14136 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
14137 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
14138 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
14139 		kmem_free(probe, sizeof (dtrace_probe_t));
14140 	}
14141 
14142 	mutex_exit(&dtrace_lock);
14143 	mutex_exit(&mod_lock);
14144 	mutex_exit(&dtrace_provider_lock);
14145 }
14146 
14147 void
14148 dtrace_suspend(void)
14149 {
14150 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
14151 }
14152 
14153 void
14154 dtrace_resume(void)
14155 {
14156 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
14157 }
14158 
14159 static int
14160 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
14161 {
14162 	ASSERT(MUTEX_HELD(&cpu_lock));
14163 	mutex_enter(&dtrace_lock);
14164 
14165 	switch (what) {
14166 	case CPU_CONFIG: {
14167 		dtrace_state_t *state;
14168 		dtrace_optval_t *opt, rs, c;
14169 
14170 		/*
14171 		 * For now, we only allocate a new buffer for anonymous state.
14172 		 */
14173 		if ((state = dtrace_anon.dta_state) == NULL)
14174 			break;
14175 
14176 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14177 			break;
14178 
14179 		opt = state->dts_options;
14180 		c = opt[DTRACEOPT_CPU];
14181 
14182 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
14183 			break;
14184 
14185 		/*
14186 		 * Regardless of what the actual policy is, we're going to
14187 		 * temporarily set our resize policy to be manual.  We're
14188 		 * also going to temporarily set our CPU option to denote
14189 		 * the newly configured CPU.
14190 		 */
14191 		rs = opt[DTRACEOPT_BUFRESIZE];
14192 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
14193 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
14194 
14195 		(void) dtrace_state_buffers(state);
14196 
14197 		opt[DTRACEOPT_BUFRESIZE] = rs;
14198 		opt[DTRACEOPT_CPU] = c;
14199 
14200 		break;
14201 	}
14202 
14203 	case CPU_UNCONFIG:
14204 		/*
14205 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
14206 		 * buffer will be freed when the consumer exits.)
14207 		 */
14208 		break;
14209 
14210 	default:
14211 		break;
14212 	}
14213 
14214 	mutex_exit(&dtrace_lock);
14215 	return (0);
14216 }
14217 
14218 static void
14219 dtrace_cpu_setup_initial(processorid_t cpu)
14220 {
14221 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
14222 }
14223 
14224 static void
14225 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
14226 {
14227 	if (dtrace_toxranges >= dtrace_toxranges_max) {
14228 		int osize, nsize;
14229 		dtrace_toxrange_t *range;
14230 
14231 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14232 
14233 		if (osize == 0) {
14234 			ASSERT(dtrace_toxrange == NULL);
14235 			ASSERT(dtrace_toxranges_max == 0);
14236 			dtrace_toxranges_max = 1;
14237 		} else {
14238 			dtrace_toxranges_max <<= 1;
14239 		}
14240 
14241 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14242 		range = kmem_zalloc(nsize, KM_SLEEP);
14243 
14244 		if (dtrace_toxrange != NULL) {
14245 			ASSERT(osize != 0);
14246 			bcopy(dtrace_toxrange, range, osize);
14247 			kmem_free(dtrace_toxrange, osize);
14248 		}
14249 
14250 		dtrace_toxrange = range;
14251 	}
14252 
14253 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
14254 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
14255 
14256 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
14257 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
14258 	dtrace_toxranges++;
14259 }
14260 
14261 /*
14262  * DTrace Driver Cookbook Functions
14263  */
14264 /*ARGSUSED*/
14265 static int
14266 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
14267 {
14268 	dtrace_provider_id_t id;
14269 	dtrace_state_t *state = NULL;
14270 	dtrace_enabling_t *enab;
14271 
14272 	mutex_enter(&cpu_lock);
14273 	mutex_enter(&dtrace_provider_lock);
14274 	mutex_enter(&dtrace_lock);
14275 
14276 	if (ddi_soft_state_init(&dtrace_softstate,
14277 	    sizeof (dtrace_state_t), 0) != 0) {
14278 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
14279 		mutex_exit(&cpu_lock);
14280 		mutex_exit(&dtrace_provider_lock);
14281 		mutex_exit(&dtrace_lock);
14282 		return (DDI_FAILURE);
14283 	}
14284 
14285 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
14286 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
14287 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
14288 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
14289 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
14290 		ddi_remove_minor_node(devi, NULL);
14291 		ddi_soft_state_fini(&dtrace_softstate);
14292 		mutex_exit(&cpu_lock);
14293 		mutex_exit(&dtrace_provider_lock);
14294 		mutex_exit(&dtrace_lock);
14295 		return (DDI_FAILURE);
14296 	}
14297 
14298 	ddi_report_dev(devi);
14299 	dtrace_devi = devi;
14300 
14301 	dtrace_modload = dtrace_module_loaded;
14302 	dtrace_modunload = dtrace_module_unloaded;
14303 	dtrace_cpu_init = dtrace_cpu_setup_initial;
14304 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
14305 	dtrace_helpers_fork = dtrace_helpers_duplicate;
14306 	dtrace_cpustart_init = dtrace_suspend;
14307 	dtrace_cpustart_fini = dtrace_resume;
14308 	dtrace_debugger_init = dtrace_suspend;
14309 	dtrace_debugger_fini = dtrace_resume;
14310 
14311 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
14312 
14313 	ASSERT(MUTEX_HELD(&cpu_lock));
14314 
14315 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
14316 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14317 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
14318 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
14319 	    VM_SLEEP | VMC_IDENTIFIER);
14320 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
14321 	    1, INT_MAX, 0);
14322 
14323 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
14324 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
14325 	    NULL, NULL, NULL, NULL, NULL, 0);
14326 
14327 	ASSERT(MUTEX_HELD(&cpu_lock));
14328 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
14329 	    offsetof(dtrace_probe_t, dtpr_nextmod),
14330 	    offsetof(dtrace_probe_t, dtpr_prevmod));
14331 
14332 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
14333 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
14334 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
14335 
14336 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
14337 	    offsetof(dtrace_probe_t, dtpr_nextname),
14338 	    offsetof(dtrace_probe_t, dtpr_prevname));
14339 
14340 	if (dtrace_retain_max < 1) {
14341 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
14342 		    "setting to 1", dtrace_retain_max);
14343 		dtrace_retain_max = 1;
14344 	}
14345 
14346 	/*
14347 	 * Now discover our toxic ranges.
14348 	 */
14349 	dtrace_toxic_ranges(dtrace_toxrange_add);
14350 
14351 	/*
14352 	 * Before we register ourselves as a provider to our own framework,
14353 	 * we would like to assert that dtrace_provider is NULL -- but that's
14354 	 * not true if we were loaded as a dependency of a DTrace provider.
14355 	 * Once we've registered, we can assert that dtrace_provider is our
14356 	 * pseudo provider.
14357 	 */
14358 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
14359 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
14360 
14361 	ASSERT(dtrace_provider != NULL);
14362 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
14363 
14364 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
14365 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
14366 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
14367 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
14368 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
14369 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
14370 
14371 	dtrace_anon_property();
14372 	mutex_exit(&cpu_lock);
14373 
14374 	/*
14375 	 * If DTrace helper tracing is enabled, we need to allocate the
14376 	 * trace buffer and initialize the values.
14377 	 */
14378 	if (dtrace_helptrace_enabled) {
14379 		ASSERT(dtrace_helptrace_buffer == NULL);
14380 		dtrace_helptrace_buffer =
14381 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
14382 		dtrace_helptrace_next = 0;
14383 	}
14384 
14385 	/*
14386 	 * If there are already providers, we must ask them to provide their
14387 	 * probes, and then match any anonymous enabling against them.  Note
14388 	 * that there should be no other retained enablings at this time:
14389 	 * the only retained enablings at this time should be the anonymous
14390 	 * enabling.
14391 	 */
14392 	if (dtrace_anon.dta_enabling != NULL) {
14393 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
14394 
14395 		dtrace_enabling_provide(NULL);
14396 		state = dtrace_anon.dta_state;
14397 
14398 		/*
14399 		 * We couldn't hold cpu_lock across the above call to
14400 		 * dtrace_enabling_provide(), but we must hold it to actually
14401 		 * enable the probes.  We have to drop all of our locks, pick
14402 		 * up cpu_lock, and regain our locks before matching the
14403 		 * retained anonymous enabling.
14404 		 */
14405 		mutex_exit(&dtrace_lock);
14406 		mutex_exit(&dtrace_provider_lock);
14407 
14408 		mutex_enter(&cpu_lock);
14409 		mutex_enter(&dtrace_provider_lock);
14410 		mutex_enter(&dtrace_lock);
14411 
14412 		if ((enab = dtrace_anon.dta_enabling) != NULL)
14413 			(void) dtrace_enabling_match(enab, NULL);
14414 
14415 		mutex_exit(&cpu_lock);
14416 	}
14417 
14418 	mutex_exit(&dtrace_lock);
14419 	mutex_exit(&dtrace_provider_lock);
14420 
14421 	if (state != NULL) {
14422 		/*
14423 		 * If we created any anonymous state, set it going now.
14424 		 */
14425 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
14426 	}
14427 
14428 	return (DDI_SUCCESS);
14429 }
14430 
14431 /*ARGSUSED*/
14432 static int
14433 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
14434 {
14435 	dtrace_state_t *state;
14436 	uint32_t priv;
14437 	uid_t uid;
14438 	zoneid_t zoneid;
14439 
14440 	if (getminor(*devp) == DTRACEMNRN_HELPER)
14441 		return (0);
14442 
14443 	/*
14444 	 * If this wasn't an open with the "helper" minor, then it must be
14445 	 * the "dtrace" minor.
14446 	 */
14447 	if (getminor(*devp) != DTRACEMNRN_DTRACE)
14448 		return (ENXIO);
14449 
14450 	/*
14451 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
14452 	 * caller lacks sufficient permission to do anything with DTrace.
14453 	 */
14454 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
14455 	if (priv == DTRACE_PRIV_NONE)
14456 		return (EACCES);
14457 
14458 	/*
14459 	 * Ask all providers to provide all their probes.
14460 	 */
14461 	mutex_enter(&dtrace_provider_lock);
14462 	dtrace_probe_provide(NULL, NULL);
14463 	mutex_exit(&dtrace_provider_lock);
14464 
14465 	mutex_enter(&cpu_lock);
14466 	mutex_enter(&dtrace_lock);
14467 	dtrace_opens++;
14468 	dtrace_membar_producer();
14469 
14470 	/*
14471 	 * If the kernel debugger is active (that is, if the kernel debugger
14472 	 * modified text in some way), we won't allow the open.
14473 	 */
14474 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14475 		dtrace_opens--;
14476 		mutex_exit(&cpu_lock);
14477 		mutex_exit(&dtrace_lock);
14478 		return (EBUSY);
14479 	}
14480 
14481 	state = dtrace_state_create(devp, cred_p);
14482 	mutex_exit(&cpu_lock);
14483 
14484 	if (state == NULL) {
14485 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
14486 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14487 		mutex_exit(&dtrace_lock);
14488 		return (EAGAIN);
14489 	}
14490 
14491 	mutex_exit(&dtrace_lock);
14492 
14493 	return (0);
14494 }
14495 
14496 /*ARGSUSED*/
14497 static int
14498 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
14499 {
14500 	minor_t minor = getminor(dev);
14501 	dtrace_state_t *state;
14502 
14503 	if (minor == DTRACEMNRN_HELPER)
14504 		return (0);
14505 
14506 	state = ddi_get_soft_state(dtrace_softstate, minor);
14507 
14508 	mutex_enter(&cpu_lock);
14509 	mutex_enter(&dtrace_lock);
14510 
14511 	if (state->dts_anon) {
14512 		/*
14513 		 * There is anonymous state. Destroy that first.
14514 		 */
14515 		ASSERT(dtrace_anon.dta_state == NULL);
14516 		dtrace_state_destroy(state->dts_anon);
14517 	}
14518 
14519 	dtrace_state_destroy(state);
14520 	ASSERT(dtrace_opens > 0);
14521 
14522 	/*
14523 	 * Only relinquish control of the kernel debugger interface when there
14524 	 * are no consumers and no anonymous enablings.
14525 	 */
14526 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
14527 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14528 
14529 	mutex_exit(&dtrace_lock);
14530 	mutex_exit(&cpu_lock);
14531 
14532 	return (0);
14533 }
14534 
14535 /*ARGSUSED*/
14536 static int
14537 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
14538 {
14539 	int rval;
14540 	dof_helper_t help, *dhp = NULL;
14541 
14542 	switch (cmd) {
14543 	case DTRACEHIOC_ADDDOF:
14544 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
14545 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
14546 			return (EFAULT);
14547 		}
14548 
14549 		dhp = &help;
14550 		arg = (intptr_t)help.dofhp_dof;
14551 		/*FALLTHROUGH*/
14552 
14553 	case DTRACEHIOC_ADD: {
14554 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
14555 
14556 		if (dof == NULL)
14557 			return (rval);
14558 
14559 		mutex_enter(&dtrace_lock);
14560 
14561 		/*
14562 		 * dtrace_helper_slurp() takes responsibility for the dof --
14563 		 * it may free it now or it may save it and free it later.
14564 		 */
14565 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
14566 			*rv = rval;
14567 			rval = 0;
14568 		} else {
14569 			rval = EINVAL;
14570 		}
14571 
14572 		mutex_exit(&dtrace_lock);
14573 		return (rval);
14574 	}
14575 
14576 	case DTRACEHIOC_REMOVE: {
14577 		mutex_enter(&dtrace_lock);
14578 		rval = dtrace_helper_destroygen(arg);
14579 		mutex_exit(&dtrace_lock);
14580 
14581 		return (rval);
14582 	}
14583 
14584 	default:
14585 		break;
14586 	}
14587 
14588 	return (ENOTTY);
14589 }
14590 
14591 /*ARGSUSED*/
14592 static int
14593 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
14594 {
14595 	minor_t minor = getminor(dev);
14596 	dtrace_state_t *state;
14597 	int rval;
14598 
14599 	if (minor == DTRACEMNRN_HELPER)
14600 		return (dtrace_ioctl_helper(cmd, arg, rv));
14601 
14602 	state = ddi_get_soft_state(dtrace_softstate, minor);
14603 
14604 	if (state->dts_anon) {
14605 		ASSERT(dtrace_anon.dta_state == NULL);
14606 		state = state->dts_anon;
14607 	}
14608 
14609 	switch (cmd) {
14610 	case DTRACEIOC_PROVIDER: {
14611 		dtrace_providerdesc_t pvd;
14612 		dtrace_provider_t *pvp;
14613 
14614 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
14615 			return (EFAULT);
14616 
14617 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
14618 		mutex_enter(&dtrace_provider_lock);
14619 
14620 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
14621 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
14622 				break;
14623 		}
14624 
14625 		mutex_exit(&dtrace_provider_lock);
14626 
14627 		if (pvp == NULL)
14628 			return (ESRCH);
14629 
14630 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
14631 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
14632 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
14633 			return (EFAULT);
14634 
14635 		return (0);
14636 	}
14637 
14638 	case DTRACEIOC_EPROBE: {
14639 		dtrace_eprobedesc_t epdesc;
14640 		dtrace_ecb_t *ecb;
14641 		dtrace_action_t *act;
14642 		void *buf;
14643 		size_t size;
14644 		uintptr_t dest;
14645 		int nrecs;
14646 
14647 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
14648 			return (EFAULT);
14649 
14650 		mutex_enter(&dtrace_lock);
14651 
14652 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
14653 			mutex_exit(&dtrace_lock);
14654 			return (EINVAL);
14655 		}
14656 
14657 		if (ecb->dte_probe == NULL) {
14658 			mutex_exit(&dtrace_lock);
14659 			return (EINVAL);
14660 		}
14661 
14662 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
14663 		epdesc.dtepd_uarg = ecb->dte_uarg;
14664 		epdesc.dtepd_size = ecb->dte_size;
14665 
14666 		nrecs = epdesc.dtepd_nrecs;
14667 		epdesc.dtepd_nrecs = 0;
14668 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
14669 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
14670 				continue;
14671 
14672 			epdesc.dtepd_nrecs++;
14673 		}
14674 
14675 		/*
14676 		 * Now that we have the size, we need to allocate a temporary
14677 		 * buffer in which to store the complete description.  We need
14678 		 * the temporary buffer to be able to drop dtrace_lock()
14679 		 * across the copyout(), below.
14680 		 */
14681 		size = sizeof (dtrace_eprobedesc_t) +
14682 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
14683 
14684 		buf = kmem_alloc(size, KM_SLEEP);
14685 		dest = (uintptr_t)buf;
14686 
14687 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
14688 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
14689 
14690 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
14691 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
14692 				continue;
14693 
14694 			if (nrecs-- == 0)
14695 				break;
14696 
14697 			bcopy(&act->dta_rec, (void *)dest,
14698 			    sizeof (dtrace_recdesc_t));
14699 			dest += sizeof (dtrace_recdesc_t);
14700 		}
14701 
14702 		mutex_exit(&dtrace_lock);
14703 
14704 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
14705 			kmem_free(buf, size);
14706 			return (EFAULT);
14707 		}
14708 
14709 		kmem_free(buf, size);
14710 		return (0);
14711 	}
14712 
14713 	case DTRACEIOC_AGGDESC: {
14714 		dtrace_aggdesc_t aggdesc;
14715 		dtrace_action_t *act;
14716 		dtrace_aggregation_t *agg;
14717 		int nrecs;
14718 		uint32_t offs;
14719 		dtrace_recdesc_t *lrec;
14720 		void *buf;
14721 		size_t size;
14722 		uintptr_t dest;
14723 
14724 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
14725 			return (EFAULT);
14726 
14727 		mutex_enter(&dtrace_lock);
14728 
14729 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
14730 			mutex_exit(&dtrace_lock);
14731 			return (EINVAL);
14732 		}
14733 
14734 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
14735 
14736 		nrecs = aggdesc.dtagd_nrecs;
14737 		aggdesc.dtagd_nrecs = 0;
14738 
14739 		offs = agg->dtag_base;
14740 		lrec = &agg->dtag_action.dta_rec;
14741 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
14742 
14743 		for (act = agg->dtag_first; ; act = act->dta_next) {
14744 			ASSERT(act->dta_intuple ||
14745 			    DTRACEACT_ISAGG(act->dta_kind));
14746 
14747 			/*
14748 			 * If this action has a record size of zero, it
14749 			 * denotes an argument to the aggregating action.
14750 			 * Because the presence of this record doesn't (or
14751 			 * shouldn't) affect the way the data is interpreted,
14752 			 * we don't copy it out to save user-level the
14753 			 * confusion of dealing with a zero-length record.
14754 			 */
14755 			if (act->dta_rec.dtrd_size == 0) {
14756 				ASSERT(agg->dtag_hasarg);
14757 				continue;
14758 			}
14759 
14760 			aggdesc.dtagd_nrecs++;
14761 
14762 			if (act == &agg->dtag_action)
14763 				break;
14764 		}
14765 
14766 		/*
14767 		 * Now that we have the size, we need to allocate a temporary
14768 		 * buffer in which to store the complete description.  We need
14769 		 * the temporary buffer to be able to drop dtrace_lock()
14770 		 * across the copyout(), below.
14771 		 */
14772 		size = sizeof (dtrace_aggdesc_t) +
14773 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
14774 
14775 		buf = kmem_alloc(size, KM_SLEEP);
14776 		dest = (uintptr_t)buf;
14777 
14778 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
14779 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
14780 
14781 		for (act = agg->dtag_first; ; act = act->dta_next) {
14782 			dtrace_recdesc_t rec = act->dta_rec;
14783 
14784 			/*
14785 			 * See the comment in the above loop for why we pass
14786 			 * over zero-length records.
14787 			 */
14788 			if (rec.dtrd_size == 0) {
14789 				ASSERT(agg->dtag_hasarg);
14790 				continue;
14791 			}
14792 
14793 			if (nrecs-- == 0)
14794 				break;
14795 
14796 			rec.dtrd_offset -= offs;
14797 			bcopy(&rec, (void *)dest, sizeof (rec));
14798 			dest += sizeof (dtrace_recdesc_t);
14799 
14800 			if (act == &agg->dtag_action)
14801 				break;
14802 		}
14803 
14804 		mutex_exit(&dtrace_lock);
14805 
14806 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
14807 			kmem_free(buf, size);
14808 			return (EFAULT);
14809 		}
14810 
14811 		kmem_free(buf, size);
14812 		return (0);
14813 	}
14814 
14815 	case DTRACEIOC_ENABLE: {
14816 		dof_hdr_t *dof;
14817 		dtrace_enabling_t *enab = NULL;
14818 		dtrace_vstate_t *vstate;
14819 		int err = 0;
14820 
14821 		*rv = 0;
14822 
14823 		/*
14824 		 * If a NULL argument has been passed, we take this as our
14825 		 * cue to reevaluate our enablings.
14826 		 */
14827 		if (arg == NULL) {
14828 			dtrace_enabling_matchall();
14829 
14830 			return (0);
14831 		}
14832 
14833 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
14834 			return (rval);
14835 
14836 		mutex_enter(&cpu_lock);
14837 		mutex_enter(&dtrace_lock);
14838 		vstate = &state->dts_vstate;
14839 
14840 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14841 			mutex_exit(&dtrace_lock);
14842 			mutex_exit(&cpu_lock);
14843 			dtrace_dof_destroy(dof);
14844 			return (EBUSY);
14845 		}
14846 
14847 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
14848 			mutex_exit(&dtrace_lock);
14849 			mutex_exit(&cpu_lock);
14850 			dtrace_dof_destroy(dof);
14851 			return (EINVAL);
14852 		}
14853 
14854 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
14855 			dtrace_enabling_destroy(enab);
14856 			mutex_exit(&dtrace_lock);
14857 			mutex_exit(&cpu_lock);
14858 			dtrace_dof_destroy(dof);
14859 			return (rval);
14860 		}
14861 
14862 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
14863 			err = dtrace_enabling_retain(enab);
14864 		} else {
14865 			dtrace_enabling_destroy(enab);
14866 		}
14867 
14868 		mutex_exit(&cpu_lock);
14869 		mutex_exit(&dtrace_lock);
14870 		dtrace_dof_destroy(dof);
14871 
14872 		return (err);
14873 	}
14874 
14875 	case DTRACEIOC_REPLICATE: {
14876 		dtrace_repldesc_t desc;
14877 		dtrace_probedesc_t *match = &desc.dtrpd_match;
14878 		dtrace_probedesc_t *create = &desc.dtrpd_create;
14879 		int err;
14880 
14881 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14882 			return (EFAULT);
14883 
14884 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14885 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14886 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14887 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14888 
14889 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14890 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14891 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14892 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14893 
14894 		mutex_enter(&dtrace_lock);
14895 		err = dtrace_enabling_replicate(state, match, create);
14896 		mutex_exit(&dtrace_lock);
14897 
14898 		return (err);
14899 	}
14900 
14901 	case DTRACEIOC_PROBEMATCH:
14902 	case DTRACEIOC_PROBES: {
14903 		dtrace_probe_t *probe = NULL;
14904 		dtrace_probedesc_t desc;
14905 		dtrace_probekey_t pkey;
14906 		dtrace_id_t i;
14907 		int m = 0;
14908 		uint32_t priv;
14909 		uid_t uid;
14910 		zoneid_t zoneid;
14911 
14912 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14913 			return (EFAULT);
14914 
14915 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14916 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14917 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14918 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14919 
14920 		/*
14921 		 * Before we attempt to match this probe, we want to give
14922 		 * all providers the opportunity to provide it.
14923 		 */
14924 		if (desc.dtpd_id == DTRACE_IDNONE) {
14925 			mutex_enter(&dtrace_provider_lock);
14926 			dtrace_probe_provide(&desc, NULL);
14927 			mutex_exit(&dtrace_provider_lock);
14928 			desc.dtpd_id++;
14929 		}
14930 
14931 		if (cmd == DTRACEIOC_PROBEMATCH)  {
14932 			dtrace_probekey(&desc, &pkey);
14933 			pkey.dtpk_id = DTRACE_IDNONE;
14934 		}
14935 
14936 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
14937 
14938 		mutex_enter(&dtrace_lock);
14939 
14940 		if (cmd == DTRACEIOC_PROBEMATCH) {
14941 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14942 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14943 				    (m = dtrace_match_probe(probe, &pkey,
14944 				    priv, uid, zoneid)) != 0)
14945 					break;
14946 			}
14947 
14948 			if (m < 0) {
14949 				mutex_exit(&dtrace_lock);
14950 				return (EINVAL);
14951 			}
14952 
14953 		} else {
14954 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14955 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14956 				    dtrace_match_priv(probe, priv, uid, zoneid))
14957 					break;
14958 			}
14959 		}
14960 
14961 		if (probe == NULL) {
14962 			mutex_exit(&dtrace_lock);
14963 			return (ESRCH);
14964 		}
14965 
14966 		dtrace_probe_description(probe, &desc);
14967 		mutex_exit(&dtrace_lock);
14968 
14969 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14970 			return (EFAULT);
14971 
14972 		return (0);
14973 	}
14974 
14975 	case DTRACEIOC_PROBEARG: {
14976 		dtrace_argdesc_t desc;
14977 		dtrace_probe_t *probe;
14978 		dtrace_provider_t *prov;
14979 
14980 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14981 			return (EFAULT);
14982 
14983 		if (desc.dtargd_id == DTRACE_IDNONE)
14984 			return (EINVAL);
14985 
14986 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
14987 			return (EINVAL);
14988 
14989 		mutex_enter(&dtrace_provider_lock);
14990 		mutex_enter(&mod_lock);
14991 		mutex_enter(&dtrace_lock);
14992 
14993 		if (desc.dtargd_id > dtrace_nprobes) {
14994 			mutex_exit(&dtrace_lock);
14995 			mutex_exit(&mod_lock);
14996 			mutex_exit(&dtrace_provider_lock);
14997 			return (EINVAL);
14998 		}
14999 
15000 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
15001 			mutex_exit(&dtrace_lock);
15002 			mutex_exit(&mod_lock);
15003 			mutex_exit(&dtrace_provider_lock);
15004 			return (EINVAL);
15005 		}
15006 
15007 		mutex_exit(&dtrace_lock);
15008 
15009 		prov = probe->dtpr_provider;
15010 
15011 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
15012 			/*
15013 			 * There isn't any typed information for this probe.
15014 			 * Set the argument number to DTRACE_ARGNONE.
15015 			 */
15016 			desc.dtargd_ndx = DTRACE_ARGNONE;
15017 		} else {
15018 			desc.dtargd_native[0] = '\0';
15019 			desc.dtargd_xlate[0] = '\0';
15020 			desc.dtargd_mapping = desc.dtargd_ndx;
15021 
15022 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
15023 			    probe->dtpr_id, probe->dtpr_arg, &desc);
15024 		}
15025 
15026 		mutex_exit(&mod_lock);
15027 		mutex_exit(&dtrace_provider_lock);
15028 
15029 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15030 			return (EFAULT);
15031 
15032 		return (0);
15033 	}
15034 
15035 	case DTRACEIOC_GO: {
15036 		processorid_t cpuid;
15037 		rval = dtrace_state_go(state, &cpuid);
15038 
15039 		if (rval != 0)
15040 			return (rval);
15041 
15042 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
15043 			return (EFAULT);
15044 
15045 		return (0);
15046 	}
15047 
15048 	case DTRACEIOC_STOP: {
15049 		processorid_t cpuid;
15050 
15051 		mutex_enter(&dtrace_lock);
15052 		rval = dtrace_state_stop(state, &cpuid);
15053 		mutex_exit(&dtrace_lock);
15054 
15055 		if (rval != 0)
15056 			return (rval);
15057 
15058 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
15059 			return (EFAULT);
15060 
15061 		return (0);
15062 	}
15063 
15064 	case DTRACEIOC_DOFGET: {
15065 		dof_hdr_t hdr, *dof;
15066 		uint64_t len;
15067 
15068 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
15069 			return (EFAULT);
15070 
15071 		mutex_enter(&dtrace_lock);
15072 		dof = dtrace_dof_create(state);
15073 		mutex_exit(&dtrace_lock);
15074 
15075 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
15076 		rval = copyout(dof, (void *)arg, len);
15077 		dtrace_dof_destroy(dof);
15078 
15079 		return (rval == 0 ? 0 : EFAULT);
15080 	}
15081 
15082 	case DTRACEIOC_AGGSNAP:
15083 	case DTRACEIOC_BUFSNAP: {
15084 		dtrace_bufdesc_t desc;
15085 		caddr_t cached;
15086 		dtrace_buffer_t *buf;
15087 
15088 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
15089 			return (EFAULT);
15090 
15091 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
15092 			return (EINVAL);
15093 
15094 		mutex_enter(&dtrace_lock);
15095 
15096 		if (cmd == DTRACEIOC_BUFSNAP) {
15097 			buf = &state->dts_buffer[desc.dtbd_cpu];
15098 		} else {
15099 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
15100 		}
15101 
15102 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
15103 			size_t sz = buf->dtb_offset;
15104 
15105 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
15106 				mutex_exit(&dtrace_lock);
15107 				return (EBUSY);
15108 			}
15109 
15110 			/*
15111 			 * If this buffer has already been consumed, we're
15112 			 * going to indicate that there's nothing left here
15113 			 * to consume.
15114 			 */
15115 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
15116 				mutex_exit(&dtrace_lock);
15117 
15118 				desc.dtbd_size = 0;
15119 				desc.dtbd_drops = 0;
15120 				desc.dtbd_errors = 0;
15121 				desc.dtbd_oldest = 0;
15122 				sz = sizeof (desc);
15123 
15124 				if (copyout(&desc, (void *)arg, sz) != 0)
15125 					return (EFAULT);
15126 
15127 				return (0);
15128 			}
15129 
15130 			/*
15131 			 * If this is a ring buffer that has wrapped, we want
15132 			 * to copy the whole thing out.
15133 			 */
15134 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
15135 				dtrace_buffer_polish(buf);
15136 				sz = buf->dtb_size;
15137 			}
15138 
15139 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
15140 				mutex_exit(&dtrace_lock);
15141 				return (EFAULT);
15142 			}
15143 
15144 			desc.dtbd_size = sz;
15145 			desc.dtbd_drops = buf->dtb_drops;
15146 			desc.dtbd_errors = buf->dtb_errors;
15147 			desc.dtbd_oldest = buf->dtb_xamot_offset;
15148 
15149 			mutex_exit(&dtrace_lock);
15150 
15151 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15152 				return (EFAULT);
15153 
15154 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
15155 
15156 			return (0);
15157 		}
15158 
15159 		if (buf->dtb_tomax == NULL) {
15160 			ASSERT(buf->dtb_xamot == NULL);
15161 			mutex_exit(&dtrace_lock);
15162 			return (ENOENT);
15163 		}
15164 
15165 		cached = buf->dtb_tomax;
15166 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
15167 
15168 		dtrace_xcall(desc.dtbd_cpu,
15169 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
15170 
15171 		state->dts_errors += buf->dtb_xamot_errors;
15172 
15173 		/*
15174 		 * If the buffers did not actually switch, then the cross call
15175 		 * did not take place -- presumably because the given CPU is
15176 		 * not in the ready set.  If this is the case, we'll return
15177 		 * ENOENT.
15178 		 */
15179 		if (buf->dtb_tomax == cached) {
15180 			ASSERT(buf->dtb_xamot != cached);
15181 			mutex_exit(&dtrace_lock);
15182 			return (ENOENT);
15183 		}
15184 
15185 		ASSERT(cached == buf->dtb_xamot);
15186 
15187 		/*
15188 		 * We have our snapshot; now copy it out.
15189 		 */
15190 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
15191 		    buf->dtb_xamot_offset) != 0) {
15192 			mutex_exit(&dtrace_lock);
15193 			return (EFAULT);
15194 		}
15195 
15196 		desc.dtbd_size = buf->dtb_xamot_offset;
15197 		desc.dtbd_drops = buf->dtb_xamot_drops;
15198 		desc.dtbd_errors = buf->dtb_xamot_errors;
15199 		desc.dtbd_oldest = 0;
15200 
15201 		mutex_exit(&dtrace_lock);
15202 
15203 		/*
15204 		 * Finally, copy out the buffer description.
15205 		 */
15206 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15207 			return (EFAULT);
15208 
15209 		return (0);
15210 	}
15211 
15212 	case DTRACEIOC_CONF: {
15213 		dtrace_conf_t conf;
15214 
15215 		bzero(&conf, sizeof (conf));
15216 		conf.dtc_difversion = DIF_VERSION;
15217 		conf.dtc_difintregs = DIF_DIR_NREGS;
15218 		conf.dtc_diftupregs = DIF_DTR_NREGS;
15219 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
15220 
15221 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
15222 			return (EFAULT);
15223 
15224 		return (0);
15225 	}
15226 
15227 	case DTRACEIOC_STATUS: {
15228 		dtrace_status_t stat;
15229 		dtrace_dstate_t *dstate;
15230 		int i, j;
15231 		uint64_t nerrs;
15232 
15233 		/*
15234 		 * See the comment in dtrace_state_deadman() for the reason
15235 		 * for setting dts_laststatus to INT64_MAX before setting
15236 		 * it to the correct value.
15237 		 */
15238 		state->dts_laststatus = INT64_MAX;
15239 		dtrace_membar_producer();
15240 		state->dts_laststatus = dtrace_gethrtime();
15241 
15242 		bzero(&stat, sizeof (stat));
15243 
15244 		mutex_enter(&dtrace_lock);
15245 
15246 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
15247 			mutex_exit(&dtrace_lock);
15248 			return (ENOENT);
15249 		}
15250 
15251 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
15252 			stat.dtst_exiting = 1;
15253 
15254 		nerrs = state->dts_errors;
15255 		dstate = &state->dts_vstate.dtvs_dynvars;
15256 
15257 		for (i = 0; i < NCPU; i++) {
15258 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
15259 
15260 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
15261 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
15262 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
15263 
15264 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
15265 				stat.dtst_filled++;
15266 
15267 			nerrs += state->dts_buffer[i].dtb_errors;
15268 
15269 			for (j = 0; j < state->dts_nspeculations; j++) {
15270 				dtrace_speculation_t *spec;
15271 				dtrace_buffer_t *buf;
15272 
15273 				spec = &state->dts_speculations[j];
15274 				buf = &spec->dtsp_buffer[i];
15275 				stat.dtst_specdrops += buf->dtb_xamot_drops;
15276 			}
15277 		}
15278 
15279 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
15280 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
15281 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
15282 		stat.dtst_dblerrors = state->dts_dblerrors;
15283 		stat.dtst_killed =
15284 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
15285 		stat.dtst_errors = nerrs;
15286 
15287 		mutex_exit(&dtrace_lock);
15288 
15289 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
15290 			return (EFAULT);
15291 
15292 		return (0);
15293 	}
15294 
15295 	case DTRACEIOC_FORMAT: {
15296 		dtrace_fmtdesc_t fmt;
15297 		char *str;
15298 		int len;
15299 
15300 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
15301 			return (EFAULT);
15302 
15303 		mutex_enter(&dtrace_lock);
15304 
15305 		if (fmt.dtfd_format == 0 ||
15306 		    fmt.dtfd_format > state->dts_nformats) {
15307 			mutex_exit(&dtrace_lock);
15308 			return (EINVAL);
15309 		}
15310 
15311 		/*
15312 		 * Format strings are allocated contiguously and they are
15313 		 * never freed; if a format index is less than the number
15314 		 * of formats, we can assert that the format map is non-NULL
15315 		 * and that the format for the specified index is non-NULL.
15316 		 */
15317 		ASSERT(state->dts_formats != NULL);
15318 		str = state->dts_formats[fmt.dtfd_format - 1];
15319 		ASSERT(str != NULL);
15320 
15321 		len = strlen(str) + 1;
15322 
15323 		if (len > fmt.dtfd_length) {
15324 			fmt.dtfd_length = len;
15325 
15326 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
15327 				mutex_exit(&dtrace_lock);
15328 				return (EINVAL);
15329 			}
15330 		} else {
15331 			if (copyout(str, fmt.dtfd_string, len) != 0) {
15332 				mutex_exit(&dtrace_lock);
15333 				return (EINVAL);
15334 			}
15335 		}
15336 
15337 		mutex_exit(&dtrace_lock);
15338 		return (0);
15339 	}
15340 
15341 	default:
15342 		break;
15343 	}
15344 
15345 	return (ENOTTY);
15346 }
15347 
15348 /*ARGSUSED*/
15349 static int
15350 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
15351 {
15352 	dtrace_state_t *state;
15353 
15354 	switch (cmd) {
15355 	case DDI_DETACH:
15356 		break;
15357 
15358 	case DDI_SUSPEND:
15359 		return (DDI_SUCCESS);
15360 
15361 	default:
15362 		return (DDI_FAILURE);
15363 	}
15364 
15365 	mutex_enter(&cpu_lock);
15366 	mutex_enter(&dtrace_provider_lock);
15367 	mutex_enter(&dtrace_lock);
15368 
15369 	ASSERT(dtrace_opens == 0);
15370 
15371 	if (dtrace_helpers > 0) {
15372 		mutex_exit(&dtrace_provider_lock);
15373 		mutex_exit(&dtrace_lock);
15374 		mutex_exit(&cpu_lock);
15375 		return (DDI_FAILURE);
15376 	}
15377 
15378 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
15379 		mutex_exit(&dtrace_provider_lock);
15380 		mutex_exit(&dtrace_lock);
15381 		mutex_exit(&cpu_lock);
15382 		return (DDI_FAILURE);
15383 	}
15384 
15385 	dtrace_provider = NULL;
15386 
15387 	if ((state = dtrace_anon_grab()) != NULL) {
15388 		/*
15389 		 * If there were ECBs on this state, the provider should
15390 		 * have not been allowed to detach; assert that there is
15391 		 * none.
15392 		 */
15393 		ASSERT(state->dts_necbs == 0);
15394 		dtrace_state_destroy(state);
15395 
15396 		/*
15397 		 * If we're being detached with anonymous state, we need to
15398 		 * indicate to the kernel debugger that DTrace is now inactive.
15399 		 */
15400 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15401 	}
15402 
15403 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
15404 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15405 	dtrace_cpu_init = NULL;
15406 	dtrace_helpers_cleanup = NULL;
15407 	dtrace_helpers_fork = NULL;
15408 	dtrace_cpustart_init = NULL;
15409 	dtrace_cpustart_fini = NULL;
15410 	dtrace_debugger_init = NULL;
15411 	dtrace_debugger_fini = NULL;
15412 	dtrace_modload = NULL;
15413 	dtrace_modunload = NULL;
15414 
15415 	mutex_exit(&cpu_lock);
15416 
15417 	if (dtrace_helptrace_enabled) {
15418 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
15419 		dtrace_helptrace_buffer = NULL;
15420 	}
15421 
15422 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
15423 	dtrace_probes = NULL;
15424 	dtrace_nprobes = 0;
15425 
15426 	dtrace_hash_destroy(dtrace_bymod);
15427 	dtrace_hash_destroy(dtrace_byfunc);
15428 	dtrace_hash_destroy(dtrace_byname);
15429 	dtrace_bymod = NULL;
15430 	dtrace_byfunc = NULL;
15431 	dtrace_byname = NULL;
15432 
15433 	kmem_cache_destroy(dtrace_state_cache);
15434 	vmem_destroy(dtrace_minor);
15435 	vmem_destroy(dtrace_arena);
15436 
15437 	if (dtrace_toxrange != NULL) {
15438 		kmem_free(dtrace_toxrange,
15439 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
15440 		dtrace_toxrange = NULL;
15441 		dtrace_toxranges = 0;
15442 		dtrace_toxranges_max = 0;
15443 	}
15444 
15445 	ddi_remove_minor_node(dtrace_devi, NULL);
15446 	dtrace_devi = NULL;
15447 
15448 	ddi_soft_state_fini(&dtrace_softstate);
15449 
15450 	ASSERT(dtrace_vtime_references == 0);
15451 	ASSERT(dtrace_opens == 0);
15452 	ASSERT(dtrace_retained == NULL);
15453 
15454 	mutex_exit(&dtrace_lock);
15455 	mutex_exit(&dtrace_provider_lock);
15456 
15457 	/*
15458 	 * We don't destroy the task queue until after we have dropped our
15459 	 * locks (taskq_destroy() may block on running tasks).  To prevent
15460 	 * attempting to do work after we have effectively detached but before
15461 	 * the task queue has been destroyed, all tasks dispatched via the
15462 	 * task queue must check that DTrace is still attached before
15463 	 * performing any operation.
15464 	 */
15465 	taskq_destroy(dtrace_taskq);
15466 	dtrace_taskq = NULL;
15467 
15468 	return (DDI_SUCCESS);
15469 }
15470 
15471 /*ARGSUSED*/
15472 static int
15473 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
15474 {
15475 	int error;
15476 
15477 	switch (infocmd) {
15478 	case DDI_INFO_DEVT2DEVINFO:
15479 		*result = (void *)dtrace_devi;
15480 		error = DDI_SUCCESS;
15481 		break;
15482 	case DDI_INFO_DEVT2INSTANCE:
15483 		*result = (void *)0;
15484 		error = DDI_SUCCESS;
15485 		break;
15486 	default:
15487 		error = DDI_FAILURE;
15488 	}
15489 	return (error);
15490 }
15491 
15492 static struct cb_ops dtrace_cb_ops = {
15493 	dtrace_open,		/* open */
15494 	dtrace_close,		/* close */
15495 	nulldev,		/* strategy */
15496 	nulldev,		/* print */
15497 	nodev,			/* dump */
15498 	nodev,			/* read */
15499 	nodev,			/* write */
15500 	dtrace_ioctl,		/* ioctl */
15501 	nodev,			/* devmap */
15502 	nodev,			/* mmap */
15503 	nodev,			/* segmap */
15504 	nochpoll,		/* poll */
15505 	ddi_prop_op,		/* cb_prop_op */
15506 	0,			/* streamtab  */
15507 	D_NEW | D_MP		/* Driver compatibility flag */
15508 };
15509 
15510 static struct dev_ops dtrace_ops = {
15511 	DEVO_REV,		/* devo_rev */
15512 	0,			/* refcnt */
15513 	dtrace_info,		/* get_dev_info */
15514 	nulldev,		/* identify */
15515 	nulldev,		/* probe */
15516 	dtrace_attach,		/* attach */
15517 	dtrace_detach,		/* detach */
15518 	nodev,			/* reset */
15519 	&dtrace_cb_ops,		/* driver operations */
15520 	NULL,			/* bus operations */
15521 	nodev,			/* dev power */
15522 	ddi_quiesce_not_needed,		/* quiesce */
15523 };
15524 
15525 static struct modldrv modldrv = {
15526 	&mod_driverops,		/* module type (this is a pseudo driver) */
15527 	"Dynamic Tracing",	/* name of module */
15528 	&dtrace_ops,		/* driver ops */
15529 };
15530 
15531 static struct modlinkage modlinkage = {
15532 	MODREV_1,
15533 	(void *)&modldrv,
15534 	NULL
15535 };
15536 
15537 int
15538 _init(void)
15539 {
15540 	return (mod_install(&modlinkage));
15541 }
15542 
15543 int
15544 _info(struct modinfo *modinfop)
15545 {
15546 	return (mod_info(&modlinkage, modinfop));
15547 }
15548 
15549 int
15550 _fini(void)
15551 {
15552 	return (mod_remove(&modlinkage));
15553 }
15554