xref: /titanic_51/usr/src/uts/common/dtrace/dtrace.c (revision c8e880c1386b032ac975c61826ba3bc0d8dce5ac)
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 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * DTrace - Dynamic Tracing for Solaris
31  *
32  * This is the implementation of the Solaris Dynamic Tracing framework
33  * (DTrace).  The user-visible interface to DTrace is described at length in
34  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
35  * library, the in-kernel DTrace framework, and the DTrace providers are
36  * described in the block comments in the <sys/dtrace.h> header file.  The
37  * internal architecture of DTrace is described in the block comments in the
38  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
39  * implementation very much assume mastery of all of these sources; if one has
40  * an unanswered question about the implementation, one should consult them
41  * first.
42  *
43  * The functions here are ordered roughly as follows:
44  *
45  *   - Probe context functions
46  *   - Probe hashing functions
47  *   - Non-probe context utility functions
48  *   - Matching functions
49  *   - Provider-to-Framework API functions
50  *   - Probe management functions
51  *   - DIF object functions
52  *   - Format functions
53  *   - Predicate functions
54  *   - ECB functions
55  *   - Buffer functions
56  *   - Enabling functions
57  *   - DOF functions
58  *   - Anonymous enabling functions
59  *   - Consumer state functions
60  *   - Helper functions
61  *   - Hook functions
62  *   - Driver cookbook functions
63  *
64  * Each group of functions begins with a block comment labelled the "DTrace
65  * [Group] Functions", allowing one to find each block by searching forward
66  * on capital-f functions.
67  */
68 #include <sys/errno.h>
69 #include <sys/stat.h>
70 #include <sys/modctl.h>
71 #include <sys/conf.h>
72 #include <sys/systm.h>
73 #include <sys/ddi.h>
74 #include <sys/sunddi.h>
75 #include <sys/cpuvar.h>
76 #include <sys/kmem.h>
77 #include <sys/strsubr.h>
78 #include <sys/sysmacros.h>
79 #include <sys/dtrace_impl.h>
80 #include <sys/atomic.h>
81 #include <sys/cmn_err.h>
82 #include <sys/mutex_impl.h>
83 #include <sys/rwlock_impl.h>
84 #include <sys/ctf_api.h>
85 #include <sys/panic.h>
86 #include <sys/priv_impl.h>
87 #include <sys/policy.h>
88 #include <sys/cred_impl.h>
89 #include <sys/procfs_isa.h>
90 #include <sys/taskq.h>
91 #include <sys/mkdev.h>
92 #include <sys/kdi.h>
93 #include <sys/zone.h>
94 #include <sys/socket.h>
95 #include <netinet/in.h>
96 
97 /*
98  * DTrace Tunable Variables
99  *
100  * The following variables may be tuned by adding a line to /etc/system that
101  * includes both the name of the DTrace module ("dtrace") and the name of the
102  * variable.  For example:
103  *
104  *   set dtrace:dtrace_destructive_disallow = 1
105  *
106  * In general, the only variables that one should be tuning this way are those
107  * that affect system-wide DTrace behavior, and for which the default behavior
108  * is undesirable.  Most of these variables are tunable on a per-consumer
109  * basis using DTrace options, and need not be tuned on a system-wide basis.
110  * When tuning these variables, avoid pathological values; while some attempt
111  * is made to verify the integrity of these variables, they are not considered
112  * part of the supported interface to DTrace, and they are therefore not
113  * checked comprehensively.  Further, these variables should not be tuned
114  * dynamically via "mdb -kw" or other means; they should only be tuned via
115  * /etc/system.
116  */
117 int		dtrace_destructive_disallow = 0;
118 dtrace_optval_t	dtrace_nonroot_maxsize = (16 * 1024 * 1024);
119 size_t		dtrace_difo_maxsize = (256 * 1024);
120 dtrace_optval_t	dtrace_dof_maxsize = (256 * 1024);
121 size_t		dtrace_global_maxsize = (16 * 1024);
122 size_t		dtrace_actions_max = (16 * 1024);
123 size_t		dtrace_retain_max = 1024;
124 dtrace_optval_t	dtrace_helper_actions_max = 32;
125 dtrace_optval_t	dtrace_helper_providers_max = 32;
126 dtrace_optval_t	dtrace_dstate_defsize = (1 * 1024 * 1024);
127 size_t		dtrace_strsize_default = 256;
128 dtrace_optval_t	dtrace_cleanrate_default = 9900990;		/* 101 hz */
129 dtrace_optval_t	dtrace_cleanrate_min = 200000;			/* 5000 hz */
130 dtrace_optval_t	dtrace_cleanrate_max = (uint64_t)60 * NANOSEC;	/* 1/minute */
131 dtrace_optval_t	dtrace_aggrate_default = NANOSEC;		/* 1 hz */
132 dtrace_optval_t	dtrace_statusrate_default = NANOSEC;		/* 1 hz */
133 dtrace_optval_t dtrace_statusrate_max = (hrtime_t)10 * NANOSEC;	 /* 6/minute */
134 dtrace_optval_t	dtrace_switchrate_default = NANOSEC;		/* 1 hz */
135 dtrace_optval_t	dtrace_nspec_default = 1;
136 dtrace_optval_t	dtrace_specsize_default = 32 * 1024;
137 dtrace_optval_t dtrace_stackframes_default = 20;
138 dtrace_optval_t dtrace_ustackframes_default = 20;
139 dtrace_optval_t dtrace_jstackframes_default = 50;
140 dtrace_optval_t dtrace_jstackstrsize_default = 512;
141 int		dtrace_msgdsize_max = 128;
142 hrtime_t	dtrace_chill_max = 500 * (NANOSEC / MILLISEC);	/* 500 ms */
143 hrtime_t	dtrace_chill_interval = NANOSEC;		/* 1000 ms */
144 int		dtrace_devdepth_max = 32;
145 int		dtrace_err_verbose;
146 hrtime_t	dtrace_deadman_interval = NANOSEC;
147 hrtime_t	dtrace_deadman_timeout = (hrtime_t)10 * NANOSEC;
148 hrtime_t	dtrace_deadman_user = (hrtime_t)30 * NANOSEC;
149 
150 /*
151  * DTrace External Variables
152  *
153  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
154  * available to DTrace consumers via the backtick (`) syntax.  One of these,
155  * dtrace_zero, is made deliberately so:  it is provided as a source of
156  * well-known, zero-filled memory.  While this variable is not documented,
157  * it is used by some translators as an implementation detail.
158  */
159 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
160 
161 /*
162  * DTrace Internal Variables
163  */
164 static dev_info_t	*dtrace_devi;		/* device info */
165 static vmem_t		*dtrace_arena;		/* probe ID arena */
166 static vmem_t		*dtrace_minor;		/* minor number arena */
167 static taskq_t		*dtrace_taskq;		/* task queue */
168 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
169 static int		dtrace_nprobes;		/* number of probes */
170 static dtrace_provider_t *dtrace_provider;	/* provider list */
171 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
172 static int		dtrace_opens;		/* number of opens */
173 static int		dtrace_helpers;		/* number of helpers */
174 static void		*dtrace_softstate;	/* softstate pointer */
175 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
176 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
177 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
178 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
179 static int		dtrace_toxranges;	/* number of toxic ranges */
180 static int		dtrace_toxranges_max;	/* size of toxic range array */
181 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
182 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
183 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
184 static kthread_t	*dtrace_panicked;	/* panicking thread */
185 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
186 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
187 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
188 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
189 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
190 
191 /*
192  * DTrace Locking
193  * DTrace is protected by three (relatively coarse-grained) locks:
194  *
195  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
196  *     including enabling state, probes, ECBs, consumer state, helper state,
197  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
198  *     probe context is lock-free -- synchronization is handled via the
199  *     dtrace_sync() cross call mechanism.
200  *
201  * (2) dtrace_provider_lock is required when manipulating provider state, or
202  *     when provider state must be held constant.
203  *
204  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
205  *     when meta provider state must be held constant.
206  *
207  * The lock ordering between these three locks is dtrace_meta_lock before
208  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
209  * several places where dtrace_provider_lock is held by the framework as it
210  * calls into the providers -- which then call back into the framework,
211  * grabbing dtrace_lock.)
212  *
213  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
214  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
215  * role as a coarse-grained lock; it is acquired before both of these locks.
216  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
217  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
218  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
219  * acquired _between_ dtrace_provider_lock and dtrace_lock.
220  */
221 static kmutex_t		dtrace_lock;		/* probe state lock */
222 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
223 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
224 
225 /*
226  * DTrace Provider Variables
227  *
228  * These are the variables relating to DTrace as a provider (that is, the
229  * provider of the BEGIN, END, and ERROR probes).
230  */
231 static dtrace_pattr_t	dtrace_provider_attr = {
232 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
233 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
234 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
235 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
236 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
237 };
238 
239 static void
240 dtrace_nullop(void)
241 {}
242 
243 static dtrace_pops_t	dtrace_provider_ops = {
244 	(void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
245 	(void (*)(void *, struct modctl *))dtrace_nullop,
246 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
247 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
248 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
249 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
250 	NULL,
251 	NULL,
252 	NULL,
253 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
254 };
255 
256 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
257 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
258 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
259 
260 /*
261  * DTrace Helper Tracing Variables
262  */
263 uint32_t dtrace_helptrace_next = 0;
264 uint32_t dtrace_helptrace_nlocals;
265 char	*dtrace_helptrace_buffer;
266 int	dtrace_helptrace_bufsize = 512 * 1024;
267 
268 #ifdef DEBUG
269 int	dtrace_helptrace_enabled = 1;
270 #else
271 int	dtrace_helptrace_enabled = 0;
272 #endif
273 
274 /*
275  * DTrace Error Hashing
276  *
277  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
278  * table.  This is very useful for checking coverage of tests that are
279  * expected to induce DIF or DOF processing errors, and may be useful for
280  * debugging problems in the DIF code generator or in DOF generation .  The
281  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
282  */
283 #ifdef DEBUG
284 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
285 static const char *dtrace_errlast;
286 static kthread_t *dtrace_errthread;
287 static kmutex_t dtrace_errlock;
288 #endif
289 
290 /*
291  * DTrace Macros and Constants
292  *
293  * These are various macros that are useful in various spots in the
294  * implementation, along with a few random constants that have no meaning
295  * outside of the implementation.  There is no real structure to this cpp
296  * mishmash -- but is there ever?
297  */
298 #define	DTRACE_HASHSTR(hash, probe)	\
299 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
300 
301 #define	DTRACE_HASHNEXT(hash, probe)	\
302 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
303 
304 #define	DTRACE_HASHPREV(hash, probe)	\
305 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
306 
307 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
308 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
309 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
310 
311 #define	DTRACE_AGGHASHSIZE_SLEW		17
312 
313 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
314 
315 /*
316  * The key for a thread-local variable consists of the lower 61 bits of the
317  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
318  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
319  * equal to a variable identifier.  This is necessary (but not sufficient) to
320  * assure that global associative arrays never collide with thread-local
321  * variables.  To guarantee that they cannot collide, we must also define the
322  * order for keying dynamic variables.  That order is:
323  *
324  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
325  *
326  * Because the variable-key and the tls-key are in orthogonal spaces, there is
327  * no way for a global variable key signature to match a thread-local key
328  * signature.
329  */
330 #define	DTRACE_TLS_THRKEY(where) { \
331 	uint_t intr = 0; \
332 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
333 	for (; actv; actv >>= 1) \
334 		intr++; \
335 	ASSERT(intr < (1 << 3)); \
336 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
337 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
338 }
339 
340 #define	DT_BSWAP_8(x)	((x) & 0xff)
341 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
342 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
343 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
344 
345 #define	DTRACE_STORE(type, tomax, offset, what) \
346 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
347 
348 #ifndef __i386
349 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
350 	if (addr & (size - 1)) {					\
351 		*flags |= CPU_DTRACE_BADALIGN;				\
352 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
353 		return (0);						\
354 	}
355 #else
356 #define	DTRACE_ALIGNCHECK(addr, size, flags)
357 #endif
358 
359 /*
360  * Test whether a range of memory starting at testaddr of size testsz falls
361  * within the range of memory described by addr, sz.  We take care to avoid
362  * problems with overflow and underflow of the unsigned quantities, and
363  * disallow all negative sizes.  Ranges of size 0 are allowed.
364  */
365 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
366 	((testaddr) - (baseaddr) < (basesz) && \
367 	(testaddr) + (testsz) - (baseaddr) <= (basesz) && \
368 	(testaddr) + (testsz) >= (testaddr))
369 
370 /*
371  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
372  * alloc_sz on the righthand side of the comparison in order to avoid overflow
373  * or underflow in the comparison with it.  This is simpler than the INRANGE
374  * check above, because we know that the dtms_scratch_ptr is valid in the
375  * range.  Allocations of size zero are allowed.
376  */
377 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
378 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
379 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
380 
381 #define	DTRACE_LOADFUNC(bits)						\
382 /*CSTYLED*/								\
383 uint##bits##_t								\
384 dtrace_load##bits(uintptr_t addr)					\
385 {									\
386 	size_t size = bits / NBBY;					\
387 	/*CSTYLED*/							\
388 	uint##bits##_t rval;						\
389 	int i;								\
390 	volatile uint16_t *flags = (volatile uint16_t *)		\
391 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
392 									\
393 	DTRACE_ALIGNCHECK(addr, size, flags);				\
394 									\
395 	for (i = 0; i < dtrace_toxranges; i++) {			\
396 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
397 			continue;					\
398 									\
399 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
400 			continue;					\
401 									\
402 		/*							\
403 		 * This address falls within a toxic region; return 0.	\
404 		 */							\
405 		*flags |= CPU_DTRACE_BADADDR;				\
406 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
407 		return (0);						\
408 	}								\
409 									\
410 	*flags |= CPU_DTRACE_NOFAULT;					\
411 	/*CSTYLED*/							\
412 	rval = *((volatile uint##bits##_t *)addr);			\
413 	*flags &= ~CPU_DTRACE_NOFAULT;					\
414 									\
415 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
416 }
417 
418 #ifdef _LP64
419 #define	dtrace_loadptr	dtrace_load64
420 #else
421 #define	dtrace_loadptr	dtrace_load32
422 #endif
423 
424 #define	DTRACE_DYNHASH_FREE	0
425 #define	DTRACE_DYNHASH_SINK	1
426 #define	DTRACE_DYNHASH_VALID	2
427 
428 #define	DTRACE_MATCH_NEXT	0
429 #define	DTRACE_MATCH_DONE	1
430 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
431 #define	DTRACE_STATE_ALIGN	64
432 
433 #define	DTRACE_FLAGS2FLT(flags)						\
434 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
435 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
436 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
437 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
438 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
439 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
440 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
441 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
442 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
443 	DTRACEFLT_UNKNOWN)
444 
445 #define	DTRACEACT_ISSTRING(act)						\
446 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
447 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
448 
449 static size_t dtrace_strlen(const char *, size_t);
450 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
451 static void dtrace_enabling_provide(dtrace_provider_t *);
452 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
453 static void dtrace_enabling_matchall(void);
454 static dtrace_state_t *dtrace_anon_grab(void);
455 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
456     dtrace_state_t *, uint64_t, uint64_t);
457 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
458 static void dtrace_buffer_drop(dtrace_buffer_t *);
459 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
460     dtrace_state_t *, dtrace_mstate_t *);
461 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
462     dtrace_optval_t);
463 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
464 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
465 
466 /*
467  * DTrace Probe Context Functions
468  *
469  * These functions are called from probe context.  Because probe context is
470  * any context in which C may be called, arbitrarily locks may be held,
471  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
472  * As a result, functions called from probe context may only call other DTrace
473  * support functions -- they may not interact at all with the system at large.
474  * (Note that the ASSERT macro is made probe-context safe by redefining it in
475  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
476  * loads are to be performed from probe context, they _must_ be in terms of
477  * the safe dtrace_load*() variants.
478  *
479  * Some functions in this block are not actually called from probe context;
480  * for these functions, there will be a comment above the function reading
481  * "Note:  not called from probe context."
482  */
483 void
484 dtrace_panic(const char *format, ...)
485 {
486 	va_list alist;
487 
488 	va_start(alist, format);
489 	dtrace_vpanic(format, alist);
490 	va_end(alist);
491 }
492 
493 int
494 dtrace_assfail(const char *a, const char *f, int l)
495 {
496 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
497 
498 	/*
499 	 * We just need something here that even the most clever compiler
500 	 * cannot optimize away.
501 	 */
502 	return (a[(uintptr_t)f]);
503 }
504 
505 /*
506  * Atomically increment a specified error counter from probe context.
507  */
508 static void
509 dtrace_error(uint32_t *counter)
510 {
511 	/*
512 	 * Most counters stored to in probe context are per-CPU counters.
513 	 * However, there are some error conditions that are sufficiently
514 	 * arcane that they don't merit per-CPU storage.  If these counters
515 	 * are incremented concurrently on different CPUs, scalability will be
516 	 * adversely affected -- but we don't expect them to be white-hot in a
517 	 * correctly constructed enabling...
518 	 */
519 	uint32_t oval, nval;
520 
521 	do {
522 		oval = *counter;
523 
524 		if ((nval = oval + 1) == 0) {
525 			/*
526 			 * If the counter would wrap, set it to 1 -- assuring
527 			 * that the counter is never zero when we have seen
528 			 * errors.  (The counter must be 32-bits because we
529 			 * aren't guaranteed a 64-bit compare&swap operation.)
530 			 * To save this code both the infamy of being fingered
531 			 * by a priggish news story and the indignity of being
532 			 * the target of a neo-puritan witch trial, we're
533 			 * carefully avoiding any colorful description of the
534 			 * likelihood of this condition -- but suffice it to
535 			 * say that it is only slightly more likely than the
536 			 * overflow of predicate cache IDs, as discussed in
537 			 * dtrace_predicate_create().
538 			 */
539 			nval = 1;
540 		}
541 	} while (dtrace_cas32(counter, oval, nval) != oval);
542 }
543 
544 /*
545  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
546  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
547  */
548 DTRACE_LOADFUNC(8)
549 DTRACE_LOADFUNC(16)
550 DTRACE_LOADFUNC(32)
551 DTRACE_LOADFUNC(64)
552 
553 static int
554 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
555 {
556 	if (dest < mstate->dtms_scratch_base)
557 		return (0);
558 
559 	if (dest + size < dest)
560 		return (0);
561 
562 	if (dest + size > mstate->dtms_scratch_ptr)
563 		return (0);
564 
565 	return (1);
566 }
567 
568 static int
569 dtrace_canstore_statvar(uint64_t addr, size_t sz,
570     dtrace_statvar_t **svars, int nsvars)
571 {
572 	int i;
573 
574 	for (i = 0; i < nsvars; i++) {
575 		dtrace_statvar_t *svar = svars[i];
576 
577 		if (svar == NULL || svar->dtsv_size == 0)
578 			continue;
579 
580 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data, svar->dtsv_size))
581 			return (1);
582 	}
583 
584 	return (0);
585 }
586 
587 /*
588  * Check to see if the address is within a memory region to which a store may
589  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
590  * region.  The caller of dtrace_canstore() is responsible for performing any
591  * alignment checks that are needed before stores are actually executed.
592  */
593 static int
594 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
595     dtrace_vstate_t *vstate)
596 {
597 	/*
598 	 * First, check to see if the address is in scratch space...
599 	 */
600 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
601 	    mstate->dtms_scratch_size))
602 		return (1);
603 
604 	/*
605 	 * Now check to see if it's a dynamic variable.  This check will pick
606 	 * up both thread-local variables and any global dynamically-allocated
607 	 * variables.
608 	 */
609 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)vstate->dtvs_dynvars.dtds_base,
610 	    vstate->dtvs_dynvars.dtds_size)) {
611 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
612 		uintptr_t base = (uintptr_t)dstate->dtds_base +
613 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
614 		uintptr_t chunkoffs;
615 
616 		/*
617 		 * Before we assume that we can store here, we need to make
618 		 * sure that it isn't in our metadata -- storing to our
619 		 * dynamic variable metadata would corrupt our state.  For
620 		 * the range to not include any dynamic variable metadata,
621 		 * it must:
622 		 *
623 		 *	(1) Start above the hash table that is at the base of
624 		 *	the dynamic variable space
625 		 *
626 		 *	(2) Have a starting chunk offset that is beyond the
627 		 *	dtrace_dynvar_t that is at the base of every chunk
628 		 *
629 		 *	(3) Not span a chunk boundary
630 		 *
631 		 */
632 		if (addr < base)
633 			return (0);
634 
635 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
636 
637 		if (chunkoffs < sizeof (dtrace_dynvar_t))
638 			return (0);
639 
640 		if (chunkoffs + sz > dstate->dtds_chunksize)
641 			return (0);
642 
643 		return (1);
644 	}
645 
646 	/*
647 	 * Finally, check the static local and global variables.  These checks
648 	 * take the longest, so we perform them last.
649 	 */
650 	if (dtrace_canstore_statvar(addr, sz,
651 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
652 		return (1);
653 
654 	if (dtrace_canstore_statvar(addr, sz,
655 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
656 		return (1);
657 
658 	return (0);
659 }
660 
661 
662 /*
663  * Convenience routine to check to see if the address is within a memory
664  * region in which a load may be issued given the user's privilege level;
665  * if not, it sets the appropriate error flags and loads 'addr' into the
666  * illegal value slot.
667  *
668  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
669  * appropriate memory access protection.
670  */
671 static int
672 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
673     dtrace_vstate_t *vstate)
674 {
675 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
676 
677 	/*
678 	 * If we hold the privilege to read from kernel memory, then
679 	 * everything is readable.
680 	 */
681 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
682 		return (1);
683 
684 	/*
685 	 * You can obviously read that which you can store.
686 	 */
687 	if (dtrace_canstore(addr, sz, mstate, vstate))
688 		return (1);
689 
690 	/*
691 	 * We're allowed to read from our own string table.
692 	 */
693 	if (DTRACE_INRANGE(addr, sz, (uintptr_t)mstate->dtms_difo->dtdo_strtab,
694 	    mstate->dtms_difo->dtdo_strlen))
695 		return (1);
696 
697 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
698 	*illval = addr;
699 	return (0);
700 }
701 
702 /*
703  * Convenience routine to check to see if a given string is within a memory
704  * region in which a load may be issued given the user's privilege level;
705  * this exists so that we don't need to issue unnecessary dtrace_strlen()
706  * calls in the event that the user has all privileges.
707  */
708 static int
709 dtrace_strcanload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
710     dtrace_vstate_t *vstate)
711 {
712 	size_t strsz;
713 
714 	/*
715 	 * If we hold the privilege to read from kernel memory, then
716 	 * everything is readable.
717 	 */
718 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
719 		return (1);
720 
721 	strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr, sz);
722 	if (dtrace_canload(addr, strsz, mstate, vstate))
723 		return (1);
724 
725 	return (0);
726 }
727 
728 /*
729  * Convenience routine to check to see if a given variable is within a memory
730  * region in which a load may be issued given the user's privilege level.
731  */
732 static int
733 dtrace_vcanload(void *src, dtrace_diftype_t *type, dtrace_mstate_t *mstate,
734     dtrace_vstate_t *vstate)
735 {
736 	size_t sz;
737 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
738 
739 	/*
740 	 * If we hold the privilege to read from kernel memory, then
741 	 * everything is readable.
742 	 */
743 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
744 		return (1);
745 
746 	if (type->dtdt_kind == DIF_TYPE_STRING)
747 		sz = dtrace_strlen(src,
748 		    vstate->dtvs_state->dts_options[DTRACEOPT_STRSIZE]) + 1;
749 	else
750 		sz = type->dtdt_size;
751 
752 	return (dtrace_canload((uintptr_t)src, sz, mstate, vstate));
753 }
754 
755 /*
756  * Compare two strings using safe loads.
757  */
758 static int
759 dtrace_strncmp(char *s1, char *s2, size_t limit)
760 {
761 	uint8_t c1, c2;
762 	volatile uint16_t *flags;
763 
764 	if (s1 == s2 || limit == 0)
765 		return (0);
766 
767 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
768 
769 	do {
770 		if (s1 == NULL) {
771 			c1 = '\0';
772 		} else {
773 			c1 = dtrace_load8((uintptr_t)s1++);
774 		}
775 
776 		if (s2 == NULL) {
777 			c2 = '\0';
778 		} else {
779 			c2 = dtrace_load8((uintptr_t)s2++);
780 		}
781 
782 		if (c1 != c2)
783 			return (c1 - c2);
784 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
785 
786 	return (0);
787 }
788 
789 /*
790  * Compute strlen(s) for a string using safe memory accesses.  The additional
791  * len parameter is used to specify a maximum length to ensure completion.
792  */
793 static size_t
794 dtrace_strlen(const char *s, size_t lim)
795 {
796 	uint_t len;
797 
798 	for (len = 0; len != lim; len++) {
799 		if (dtrace_load8((uintptr_t)s++) == '\0')
800 			break;
801 	}
802 
803 	return (len);
804 }
805 
806 /*
807  * Check if an address falls within a toxic region.
808  */
809 static int
810 dtrace_istoxic(uintptr_t kaddr, size_t size)
811 {
812 	uintptr_t taddr, tsize;
813 	int i;
814 
815 	for (i = 0; i < dtrace_toxranges; i++) {
816 		taddr = dtrace_toxrange[i].dtt_base;
817 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
818 
819 		if (kaddr - taddr < tsize) {
820 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
821 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
822 			return (1);
823 		}
824 
825 		if (taddr - kaddr < size) {
826 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
827 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
828 			return (1);
829 		}
830 	}
831 
832 	return (0);
833 }
834 
835 /*
836  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
837  * memory specified by the DIF program.  The dst is assumed to be safe memory
838  * that we can store to directly because it is managed by DTrace.  As with
839  * standard bcopy, overlapping copies are handled properly.
840  */
841 static void
842 dtrace_bcopy(const void *src, void *dst, size_t len)
843 {
844 	if (len != 0) {
845 		uint8_t *s1 = dst;
846 		const uint8_t *s2 = src;
847 
848 		if (s1 <= s2) {
849 			do {
850 				*s1++ = dtrace_load8((uintptr_t)s2++);
851 			} while (--len != 0);
852 		} else {
853 			s2 += len;
854 			s1 += len;
855 
856 			do {
857 				*--s1 = dtrace_load8((uintptr_t)--s2);
858 			} while (--len != 0);
859 		}
860 	}
861 }
862 
863 /*
864  * Copy src to dst using safe memory accesses, up to either the specified
865  * length, or the point that a nul byte is encountered.  The src is assumed to
866  * be unsafe memory specified by the DIF program.  The dst is assumed to be
867  * safe memory that we can store to directly because it is managed by DTrace.
868  * Unlike dtrace_bcopy(), overlapping regions are not handled.
869  */
870 static void
871 dtrace_strcpy(const void *src, void *dst, size_t len)
872 {
873 	if (len != 0) {
874 		uint8_t *s1 = dst, c;
875 		const uint8_t *s2 = src;
876 
877 		do {
878 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
879 		} while (--len != 0 && c != '\0');
880 	}
881 }
882 
883 /*
884  * Copy src to dst, deriving the size and type from the specified (BYREF)
885  * variable type.  The src is assumed to be unsafe memory specified by the DIF
886  * program.  The dst is assumed to be DTrace variable memory that is of the
887  * specified type; we assume that we can store to directly.
888  */
889 static void
890 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type)
891 {
892 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
893 
894 	if (type->dtdt_kind == DIF_TYPE_STRING) {
895 		dtrace_strcpy(src, dst, type->dtdt_size);
896 	} else {
897 		dtrace_bcopy(src, dst, type->dtdt_size);
898 	}
899 }
900 
901 /*
902  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
903  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
904  * safe memory that we can access directly because it is managed by DTrace.
905  */
906 static int
907 dtrace_bcmp(const void *s1, const void *s2, size_t len)
908 {
909 	volatile uint16_t *flags;
910 
911 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
912 
913 	if (s1 == s2)
914 		return (0);
915 
916 	if (s1 == NULL || s2 == NULL)
917 		return (1);
918 
919 	if (s1 != s2 && len != 0) {
920 		const uint8_t *ps1 = s1;
921 		const uint8_t *ps2 = s2;
922 
923 		do {
924 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
925 				return (1);
926 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
927 	}
928 	return (0);
929 }
930 
931 /*
932  * Zero the specified region using a simple byte-by-byte loop.  Note that this
933  * is for safe DTrace-managed memory only.
934  */
935 static void
936 dtrace_bzero(void *dst, size_t len)
937 {
938 	uchar_t *cp;
939 
940 	for (cp = dst; len != 0; len--)
941 		*cp++ = 0;
942 }
943 
944 /*
945  * This privilege check should be used by actions and subroutines to
946  * verify that the user credentials of the process that enabled the
947  * invoking ECB match the target credentials
948  */
949 static int
950 dtrace_priv_proc_common_user(dtrace_state_t *state)
951 {
952 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
953 
954 	/*
955 	 * We should always have a non-NULL state cred here, since if cred
956 	 * is null (anonymous tracing), we fast-path bypass this routine.
957 	 */
958 	ASSERT(s_cr != NULL);
959 
960 	if ((cr = CRED()) != NULL &&
961 	    s_cr->cr_uid == cr->cr_uid &&
962 	    s_cr->cr_uid == cr->cr_ruid &&
963 	    s_cr->cr_uid == cr->cr_suid &&
964 	    s_cr->cr_gid == cr->cr_gid &&
965 	    s_cr->cr_gid == cr->cr_rgid &&
966 	    s_cr->cr_gid == cr->cr_sgid)
967 		return (1);
968 
969 	return (0);
970 }
971 
972 /*
973  * This privilege check should be used by actions and subroutines to
974  * verify that the zone of the process that enabled the invoking ECB
975  * matches the target credentials
976  */
977 static int
978 dtrace_priv_proc_common_zone(dtrace_state_t *state)
979 {
980 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
981 
982 	/*
983 	 * We should always have a non-NULL state cred here, since if cred
984 	 * is null (anonymous tracing), we fast-path bypass this routine.
985 	 */
986 	ASSERT(s_cr != NULL);
987 
988 	if ((cr = CRED()) != NULL &&
989 	    s_cr->cr_zone == cr->cr_zone)
990 		return (1);
991 
992 	return (0);
993 }
994 
995 /*
996  * This privilege check should be used by actions and subroutines to
997  * verify that the process has not setuid or changed credentials.
998  */
999 static int
1000 dtrace_priv_proc_common_nocd()
1001 {
1002 	proc_t *proc;
1003 
1004 	if ((proc = ttoproc(curthread)) != NULL &&
1005 	    !(proc->p_flag & SNOCD))
1006 		return (1);
1007 
1008 	return (0);
1009 }
1010 
1011 static int
1012 dtrace_priv_proc_destructive(dtrace_state_t *state)
1013 {
1014 	int action = state->dts_cred.dcr_action;
1015 
1016 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1017 	    dtrace_priv_proc_common_zone(state) == 0)
1018 		goto bad;
1019 
1020 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1021 	    dtrace_priv_proc_common_user(state) == 0)
1022 		goto bad;
1023 
1024 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1025 	    dtrace_priv_proc_common_nocd() == 0)
1026 		goto bad;
1027 
1028 	return (1);
1029 
1030 bad:
1031 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1032 
1033 	return (0);
1034 }
1035 
1036 static int
1037 dtrace_priv_proc_control(dtrace_state_t *state)
1038 {
1039 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1040 		return (1);
1041 
1042 	if (dtrace_priv_proc_common_zone(state) &&
1043 	    dtrace_priv_proc_common_user(state) &&
1044 	    dtrace_priv_proc_common_nocd())
1045 		return (1);
1046 
1047 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1048 
1049 	return (0);
1050 }
1051 
1052 static int
1053 dtrace_priv_proc(dtrace_state_t *state)
1054 {
1055 	if (state->dts_cred.dcr_action & DTRACE_CRA_PROC)
1056 		return (1);
1057 
1058 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1059 
1060 	return (0);
1061 }
1062 
1063 static int
1064 dtrace_priv_kernel(dtrace_state_t *state)
1065 {
1066 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1067 		return (1);
1068 
1069 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1070 
1071 	return (0);
1072 }
1073 
1074 static int
1075 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1076 {
1077 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1078 		return (1);
1079 
1080 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1081 
1082 	return (0);
1083 }
1084 
1085 /*
1086  * Note:  not called from probe context.  This function is called
1087  * asynchronously (and at a regular interval) from outside of probe context to
1088  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1089  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1090  */
1091 void
1092 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1093 {
1094 	dtrace_dynvar_t *dirty;
1095 	dtrace_dstate_percpu_t *dcpu;
1096 	int i, work = 0;
1097 
1098 	for (i = 0; i < NCPU; i++) {
1099 		dcpu = &dstate->dtds_percpu[i];
1100 
1101 		ASSERT(dcpu->dtdsc_rinsing == NULL);
1102 
1103 		/*
1104 		 * If the dirty list is NULL, there is no dirty work to do.
1105 		 */
1106 		if (dcpu->dtdsc_dirty == NULL)
1107 			continue;
1108 
1109 		/*
1110 		 * If the clean list is non-NULL, then we're not going to do
1111 		 * any work for this CPU -- it means that there has not been
1112 		 * a dtrace_dynvar() allocation on this CPU (or from this CPU)
1113 		 * since the last time we cleaned house.
1114 		 */
1115 		if (dcpu->dtdsc_clean != NULL)
1116 			continue;
1117 
1118 		work = 1;
1119 
1120 		/*
1121 		 * Atomically move the dirty list aside.
1122 		 */
1123 		do {
1124 			dirty = dcpu->dtdsc_dirty;
1125 
1126 			/*
1127 			 * Before we zap the dirty list, set the rinsing list.
1128 			 * (This allows for a potential assertion in
1129 			 * dtrace_dynvar():  if a free dynamic variable appears
1130 			 * on a hash chain, either the dirty list or the
1131 			 * rinsing list for some CPU must be non-NULL.)
1132 			 */
1133 			dcpu->dtdsc_rinsing = dirty;
1134 			dtrace_membar_producer();
1135 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1136 		    dirty, NULL) != dirty);
1137 	}
1138 
1139 	if (!work) {
1140 		/*
1141 		 * We have no work to do; we can simply return.
1142 		 */
1143 		return;
1144 	}
1145 
1146 	dtrace_sync();
1147 
1148 	for (i = 0; i < NCPU; i++) {
1149 		dcpu = &dstate->dtds_percpu[i];
1150 
1151 		if (dcpu->dtdsc_rinsing == NULL)
1152 			continue;
1153 
1154 		/*
1155 		 * We are now guaranteed that no hash chain contains a pointer
1156 		 * into this dirty list; we can make it clean.
1157 		 */
1158 		ASSERT(dcpu->dtdsc_clean == NULL);
1159 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1160 		dcpu->dtdsc_rinsing = NULL;
1161 	}
1162 
1163 	/*
1164 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1165 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1166 	 * This prevents a race whereby a CPU incorrectly decides that
1167 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1168 	 * after dtrace_dynvar_clean() has completed.
1169 	 */
1170 	dtrace_sync();
1171 
1172 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1173 }
1174 
1175 /*
1176  * Depending on the value of the op parameter, this function looks-up,
1177  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1178  * allocation is requested, this function will return a pointer to a
1179  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1180  * variable can be allocated.  If NULL is returned, the appropriate counter
1181  * will be incremented.
1182  */
1183 dtrace_dynvar_t *
1184 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1185     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1186     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1187 {
1188 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1189 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1190 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1191 	processorid_t me = CPU->cpu_id, cpu = me;
1192 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1193 	size_t bucket, ksize;
1194 	size_t chunksize = dstate->dtds_chunksize;
1195 	uintptr_t kdata, lock, nstate;
1196 	uint_t i;
1197 
1198 	ASSERT(nkeys != 0);
1199 
1200 	/*
1201 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1202 	 * algorithm.  For the by-value portions, we perform the algorithm in
1203 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1204 	 * bit, and seems to have only a minute effect on distribution.  For
1205 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1206 	 * over each referenced byte.  It's painful to do this, but it's much
1207 	 * better than pathological hash distribution.  The efficacy of the
1208 	 * hashing algorithm (and a comparison with other algorithms) may be
1209 	 * found by running the ::dtrace_dynstat MDB dcmd.
1210 	 */
1211 	for (i = 0; i < nkeys; i++) {
1212 		if (key[i].dttk_size == 0) {
1213 			uint64_t val = key[i].dttk_value;
1214 
1215 			hashval += (val >> 48) & 0xffff;
1216 			hashval += (hashval << 10);
1217 			hashval ^= (hashval >> 6);
1218 
1219 			hashval += (val >> 32) & 0xffff;
1220 			hashval += (hashval << 10);
1221 			hashval ^= (hashval >> 6);
1222 
1223 			hashval += (val >> 16) & 0xffff;
1224 			hashval += (hashval << 10);
1225 			hashval ^= (hashval >> 6);
1226 
1227 			hashval += val & 0xffff;
1228 			hashval += (hashval << 10);
1229 			hashval ^= (hashval >> 6);
1230 		} else {
1231 			/*
1232 			 * This is incredibly painful, but it beats the hell
1233 			 * out of the alternative.
1234 			 */
1235 			uint64_t j, size = key[i].dttk_size;
1236 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1237 
1238 			if (!dtrace_canload(base, size, mstate, vstate))
1239 				break;
1240 
1241 			for (j = 0; j < size; j++) {
1242 				hashval += dtrace_load8(base + j);
1243 				hashval += (hashval << 10);
1244 				hashval ^= (hashval >> 6);
1245 			}
1246 		}
1247 	}
1248 
1249 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1250 		return (NULL);
1251 
1252 	hashval += (hashval << 3);
1253 	hashval ^= (hashval >> 11);
1254 	hashval += (hashval << 15);
1255 
1256 	/*
1257 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1258 	 * comes out to be one of our two sentinel hash values.  If this
1259 	 * actually happens, we set the hashval to be a value known to be a
1260 	 * non-sentinel value.
1261 	 */
1262 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1263 		hashval = DTRACE_DYNHASH_VALID;
1264 
1265 	/*
1266 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1267 	 * important here, tricks can be pulled to reduce it.  (However, it's
1268 	 * critical that hash collisions be kept to an absolute minimum;
1269 	 * they're much more painful than a divide.)  It's better to have a
1270 	 * solution that generates few collisions and still keeps things
1271 	 * relatively simple.
1272 	 */
1273 	bucket = hashval % dstate->dtds_hashsize;
1274 
1275 	if (op == DTRACE_DYNVAR_DEALLOC) {
1276 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1277 
1278 		for (;;) {
1279 			while ((lock = *lockp) & 1)
1280 				continue;
1281 
1282 			if (dtrace_casptr((void *)lockp,
1283 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1284 				break;
1285 		}
1286 
1287 		dtrace_membar_producer();
1288 	}
1289 
1290 top:
1291 	prev = NULL;
1292 	lock = hash[bucket].dtdh_lock;
1293 
1294 	dtrace_membar_consumer();
1295 
1296 	start = hash[bucket].dtdh_chain;
1297 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1298 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1299 	    op != DTRACE_DYNVAR_DEALLOC));
1300 
1301 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1302 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1303 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1304 
1305 		if (dvar->dtdv_hashval != hashval) {
1306 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1307 				/*
1308 				 * We've reached the sink, and therefore the
1309 				 * end of the hash chain; we can kick out of
1310 				 * the loop knowing that we have seen a valid
1311 				 * snapshot of state.
1312 				 */
1313 				ASSERT(dvar->dtdv_next == NULL);
1314 				ASSERT(dvar == &dtrace_dynhash_sink);
1315 				break;
1316 			}
1317 
1318 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1319 				/*
1320 				 * We've gone off the rails:  somewhere along
1321 				 * the line, one of the members of this hash
1322 				 * chain was deleted.  Note that we could also
1323 				 * detect this by simply letting this loop run
1324 				 * to completion, as we would eventually hit
1325 				 * the end of the dirty list.  However, we
1326 				 * want to avoid running the length of the
1327 				 * dirty list unnecessarily (it might be quite
1328 				 * long), so we catch this as early as
1329 				 * possible by detecting the hash marker.  In
1330 				 * this case, we simply set dvar to NULL and
1331 				 * break; the conditional after the loop will
1332 				 * send us back to top.
1333 				 */
1334 				dvar = NULL;
1335 				break;
1336 			}
1337 
1338 			goto next;
1339 		}
1340 
1341 		if (dtuple->dtt_nkeys != nkeys)
1342 			goto next;
1343 
1344 		for (i = 0; i < nkeys; i++, dkey++) {
1345 			if (dkey->dttk_size != key[i].dttk_size)
1346 				goto next; /* size or type mismatch */
1347 
1348 			if (dkey->dttk_size != 0) {
1349 				if (dtrace_bcmp(
1350 				    (void *)(uintptr_t)key[i].dttk_value,
1351 				    (void *)(uintptr_t)dkey->dttk_value,
1352 				    dkey->dttk_size))
1353 					goto next;
1354 			} else {
1355 				if (dkey->dttk_value != key[i].dttk_value)
1356 					goto next;
1357 			}
1358 		}
1359 
1360 		if (op != DTRACE_DYNVAR_DEALLOC)
1361 			return (dvar);
1362 
1363 		ASSERT(dvar->dtdv_next == NULL ||
1364 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1365 
1366 		if (prev != NULL) {
1367 			ASSERT(hash[bucket].dtdh_chain != dvar);
1368 			ASSERT(start != dvar);
1369 			ASSERT(prev->dtdv_next == dvar);
1370 			prev->dtdv_next = dvar->dtdv_next;
1371 		} else {
1372 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1373 			    start, dvar->dtdv_next) != start) {
1374 				/*
1375 				 * We have failed to atomically swing the
1376 				 * hash table head pointer, presumably because
1377 				 * of a conflicting allocation on another CPU.
1378 				 * We need to reread the hash chain and try
1379 				 * again.
1380 				 */
1381 				goto top;
1382 			}
1383 		}
1384 
1385 		dtrace_membar_producer();
1386 
1387 		/*
1388 		 * Now set the hash value to indicate that it's free.
1389 		 */
1390 		ASSERT(hash[bucket].dtdh_chain != dvar);
1391 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1392 
1393 		dtrace_membar_producer();
1394 
1395 		/*
1396 		 * Set the next pointer to point at the dirty list, and
1397 		 * atomically swing the dirty pointer to the newly freed dvar.
1398 		 */
1399 		do {
1400 			next = dcpu->dtdsc_dirty;
1401 			dvar->dtdv_next = next;
1402 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1403 
1404 		/*
1405 		 * Finally, unlock this hash bucket.
1406 		 */
1407 		ASSERT(hash[bucket].dtdh_lock == lock);
1408 		ASSERT(lock & 1);
1409 		hash[bucket].dtdh_lock++;
1410 
1411 		return (NULL);
1412 next:
1413 		prev = dvar;
1414 		continue;
1415 	}
1416 
1417 	if (dvar == NULL) {
1418 		/*
1419 		 * If dvar is NULL, it is because we went off the rails:
1420 		 * one of the elements that we traversed in the hash chain
1421 		 * was deleted while we were traversing it.  In this case,
1422 		 * we assert that we aren't doing a dealloc (deallocs lock
1423 		 * the hash bucket to prevent themselves from racing with
1424 		 * one another), and retry the hash chain traversal.
1425 		 */
1426 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1427 		goto top;
1428 	}
1429 
1430 	if (op != DTRACE_DYNVAR_ALLOC) {
1431 		/*
1432 		 * If we are not to allocate a new variable, we want to
1433 		 * return NULL now.  Before we return, check that the value
1434 		 * of the lock word hasn't changed.  If it has, we may have
1435 		 * seen an inconsistent snapshot.
1436 		 */
1437 		if (op == DTRACE_DYNVAR_NOALLOC) {
1438 			if (hash[bucket].dtdh_lock != lock)
1439 				goto top;
1440 		} else {
1441 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
1442 			ASSERT(hash[bucket].dtdh_lock == lock);
1443 			ASSERT(lock & 1);
1444 			hash[bucket].dtdh_lock++;
1445 		}
1446 
1447 		return (NULL);
1448 	}
1449 
1450 	/*
1451 	 * We need to allocate a new dynamic variable.  The size we need is the
1452 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
1453 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
1454 	 * the size of any referred-to data (dsize).  We then round the final
1455 	 * size up to the chunksize for allocation.
1456 	 */
1457 	for (ksize = 0, i = 0; i < nkeys; i++)
1458 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
1459 
1460 	/*
1461 	 * This should be pretty much impossible, but could happen if, say,
1462 	 * strange DIF specified the tuple.  Ideally, this should be an
1463 	 * assertion and not an error condition -- but that requires that the
1464 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
1465 	 * bullet-proof.  (That is, it must not be able to be fooled by
1466 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
1467 	 * solving this would presumably not amount to solving the Halting
1468 	 * Problem -- but it still seems awfully hard.
1469 	 */
1470 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
1471 	    ksize + dsize > chunksize) {
1472 		dcpu->dtdsc_drops++;
1473 		return (NULL);
1474 	}
1475 
1476 	nstate = DTRACE_DSTATE_EMPTY;
1477 
1478 	do {
1479 retry:
1480 		free = dcpu->dtdsc_free;
1481 
1482 		if (free == NULL) {
1483 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
1484 			void *rval;
1485 
1486 			if (clean == NULL) {
1487 				/*
1488 				 * We're out of dynamic variable space on
1489 				 * this CPU.  Unless we have tried all CPUs,
1490 				 * we'll try to allocate from a different
1491 				 * CPU.
1492 				 */
1493 				switch (dstate->dtds_state) {
1494 				case DTRACE_DSTATE_CLEAN: {
1495 					void *sp = &dstate->dtds_state;
1496 
1497 					if (++cpu >= NCPU)
1498 						cpu = 0;
1499 
1500 					if (dcpu->dtdsc_dirty != NULL &&
1501 					    nstate == DTRACE_DSTATE_EMPTY)
1502 						nstate = DTRACE_DSTATE_DIRTY;
1503 
1504 					if (dcpu->dtdsc_rinsing != NULL)
1505 						nstate = DTRACE_DSTATE_RINSING;
1506 
1507 					dcpu = &dstate->dtds_percpu[cpu];
1508 
1509 					if (cpu != me)
1510 						goto retry;
1511 
1512 					(void) dtrace_cas32(sp,
1513 					    DTRACE_DSTATE_CLEAN, nstate);
1514 
1515 					/*
1516 					 * To increment the correct bean
1517 					 * counter, take another lap.
1518 					 */
1519 					goto retry;
1520 				}
1521 
1522 				case DTRACE_DSTATE_DIRTY:
1523 					dcpu->dtdsc_dirty_drops++;
1524 					break;
1525 
1526 				case DTRACE_DSTATE_RINSING:
1527 					dcpu->dtdsc_rinsing_drops++;
1528 					break;
1529 
1530 				case DTRACE_DSTATE_EMPTY:
1531 					dcpu->dtdsc_drops++;
1532 					break;
1533 				}
1534 
1535 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
1536 				return (NULL);
1537 			}
1538 
1539 			/*
1540 			 * The clean list appears to be non-empty.  We want to
1541 			 * move the clean list to the free list; we start by
1542 			 * moving the clean pointer aside.
1543 			 */
1544 			if (dtrace_casptr(&dcpu->dtdsc_clean,
1545 			    clean, NULL) != clean) {
1546 				/*
1547 				 * We are in one of two situations:
1548 				 *
1549 				 *  (a)	The clean list was switched to the
1550 				 *	free list by another CPU.
1551 				 *
1552 				 *  (b)	The clean list was added to by the
1553 				 *	cleansing cyclic.
1554 				 *
1555 				 * In either of these situations, we can
1556 				 * just reattempt the free list allocation.
1557 				 */
1558 				goto retry;
1559 			}
1560 
1561 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
1562 
1563 			/*
1564 			 * Now we'll move the clean list to the free list.
1565 			 * It's impossible for this to fail:  the only way
1566 			 * the free list can be updated is through this
1567 			 * code path, and only one CPU can own the clean list.
1568 			 * Thus, it would only be possible for this to fail if
1569 			 * this code were racing with dtrace_dynvar_clean().
1570 			 * (That is, if dtrace_dynvar_clean() updated the clean
1571 			 * list, and we ended up racing to update the free
1572 			 * list.)  This race is prevented by the dtrace_sync()
1573 			 * in dtrace_dynvar_clean() -- which flushes the
1574 			 * owners of the clean lists out before resetting
1575 			 * the clean lists.
1576 			 */
1577 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
1578 			ASSERT(rval == NULL);
1579 			goto retry;
1580 		}
1581 
1582 		dvar = free;
1583 		new_free = dvar->dtdv_next;
1584 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
1585 
1586 	/*
1587 	 * We have now allocated a new chunk.  We copy the tuple keys into the
1588 	 * tuple array and copy any referenced key data into the data space
1589 	 * following the tuple array.  As we do this, we relocate dttk_value
1590 	 * in the final tuple to point to the key data address in the chunk.
1591 	 */
1592 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
1593 	dvar->dtdv_data = (void *)(kdata + ksize);
1594 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
1595 
1596 	for (i = 0; i < nkeys; i++) {
1597 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
1598 		size_t kesize = key[i].dttk_size;
1599 
1600 		if (kesize != 0) {
1601 			dtrace_bcopy(
1602 			    (const void *)(uintptr_t)key[i].dttk_value,
1603 			    (void *)kdata, kesize);
1604 			dkey->dttk_value = kdata;
1605 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
1606 		} else {
1607 			dkey->dttk_value = key[i].dttk_value;
1608 		}
1609 
1610 		dkey->dttk_size = kesize;
1611 	}
1612 
1613 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
1614 	dvar->dtdv_hashval = hashval;
1615 	dvar->dtdv_next = start;
1616 
1617 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
1618 		return (dvar);
1619 
1620 	/*
1621 	 * The cas has failed.  Either another CPU is adding an element to
1622 	 * this hash chain, or another CPU is deleting an element from this
1623 	 * hash chain.  The simplest way to deal with both of these cases
1624 	 * (though not necessarily the most efficient) is to free our
1625 	 * allocated block and tail-call ourselves.  Note that the free is
1626 	 * to the dirty list and _not_ to the free list.  This is to prevent
1627 	 * races with allocators, above.
1628 	 */
1629 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1630 
1631 	dtrace_membar_producer();
1632 
1633 	do {
1634 		free = dcpu->dtdsc_dirty;
1635 		dvar->dtdv_next = free;
1636 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
1637 
1638 	return (dtrace_dynvar(dstate, nkeys, key, dsize, op, mstate, vstate));
1639 }
1640 
1641 /*ARGSUSED*/
1642 static void
1643 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
1644 {
1645 	if (nval < *oval)
1646 		*oval = nval;
1647 }
1648 
1649 /*ARGSUSED*/
1650 static void
1651 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
1652 {
1653 	if (nval > *oval)
1654 		*oval = nval;
1655 }
1656 
1657 static void
1658 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
1659 {
1660 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
1661 	int64_t val = (int64_t)nval;
1662 
1663 	if (val < 0) {
1664 		for (i = 0; i < zero; i++) {
1665 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
1666 				quanta[i] += incr;
1667 				return;
1668 			}
1669 		}
1670 	} else {
1671 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
1672 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
1673 				quanta[i - 1] += incr;
1674 				return;
1675 			}
1676 		}
1677 
1678 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
1679 		return;
1680 	}
1681 
1682 	ASSERT(0);
1683 }
1684 
1685 static void
1686 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
1687 {
1688 	uint64_t arg = *lquanta++;
1689 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
1690 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
1691 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
1692 	int32_t val = (int32_t)nval, level;
1693 
1694 	ASSERT(step != 0);
1695 	ASSERT(levels != 0);
1696 
1697 	if (val < base) {
1698 		/*
1699 		 * This is an underflow.
1700 		 */
1701 		lquanta[0] += incr;
1702 		return;
1703 	}
1704 
1705 	level = (val - base) / step;
1706 
1707 	if (level < levels) {
1708 		lquanta[level + 1] += incr;
1709 		return;
1710 	}
1711 
1712 	/*
1713 	 * This is an overflow.
1714 	 */
1715 	lquanta[levels + 1] += incr;
1716 }
1717 
1718 /*ARGSUSED*/
1719 static void
1720 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
1721 {
1722 	data[0]++;
1723 	data[1] += nval;
1724 }
1725 
1726 /*ARGSUSED*/
1727 static void
1728 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
1729 {
1730 	*oval = *oval + 1;
1731 }
1732 
1733 /*ARGSUSED*/
1734 static void
1735 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
1736 {
1737 	*oval += nval;
1738 }
1739 
1740 /*
1741  * Aggregate given the tuple in the principal data buffer, and the aggregating
1742  * action denoted by the specified dtrace_aggregation_t.  The aggregation
1743  * buffer is specified as the buf parameter.  This routine does not return
1744  * failure; if there is no space in the aggregation buffer, the data will be
1745  * dropped, and a corresponding counter incremented.
1746  */
1747 static void
1748 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
1749     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
1750 {
1751 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
1752 	uint32_t i, ndx, size, fsize;
1753 	uint32_t align = sizeof (uint64_t) - 1;
1754 	dtrace_aggbuffer_t *agb;
1755 	dtrace_aggkey_t *key;
1756 	uint32_t hashval = 0, limit, isstr;
1757 	caddr_t tomax, data, kdata;
1758 	dtrace_actkind_t action;
1759 	dtrace_action_t *act;
1760 	uintptr_t offs;
1761 
1762 	if (buf == NULL)
1763 		return;
1764 
1765 	if (!agg->dtag_hasarg) {
1766 		/*
1767 		 * Currently, only quantize() and lquantize() take additional
1768 		 * arguments, and they have the same semantics:  an increment
1769 		 * value that defaults to 1 when not present.  If additional
1770 		 * aggregating actions take arguments, the setting of the
1771 		 * default argument value will presumably have to become more
1772 		 * sophisticated...
1773 		 */
1774 		arg = 1;
1775 	}
1776 
1777 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
1778 	size = rec->dtrd_offset - agg->dtag_base;
1779 	fsize = size + rec->dtrd_size;
1780 
1781 	ASSERT(dbuf->dtb_tomax != NULL);
1782 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
1783 
1784 	if ((tomax = buf->dtb_tomax) == NULL) {
1785 		dtrace_buffer_drop(buf);
1786 		return;
1787 	}
1788 
1789 	/*
1790 	 * The metastructure is always at the bottom of the buffer.
1791 	 */
1792 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
1793 	    sizeof (dtrace_aggbuffer_t));
1794 
1795 	if (buf->dtb_offset == 0) {
1796 		/*
1797 		 * We just kludge up approximately 1/8th of the size to be
1798 		 * buckets.  If this guess ends up being routinely
1799 		 * off-the-mark, we may need to dynamically readjust this
1800 		 * based on past performance.
1801 		 */
1802 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
1803 
1804 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
1805 		    (uintptr_t)tomax || hashsize == 0) {
1806 			/*
1807 			 * We've been given a ludicrously small buffer;
1808 			 * increment our drop count and leave.
1809 			 */
1810 			dtrace_buffer_drop(buf);
1811 			return;
1812 		}
1813 
1814 		/*
1815 		 * And now, a pathetic attempt to try to get a an odd (or
1816 		 * perchance, a prime) hash size for better hash distribution.
1817 		 */
1818 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
1819 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
1820 
1821 		agb->dtagb_hashsize = hashsize;
1822 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
1823 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
1824 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
1825 
1826 		for (i = 0; i < agb->dtagb_hashsize; i++)
1827 			agb->dtagb_hash[i] = NULL;
1828 	}
1829 
1830 	ASSERT(agg->dtag_first != NULL);
1831 	ASSERT(agg->dtag_first->dta_intuple);
1832 
1833 	/*
1834 	 * Calculate the hash value based on the key.  Note that we _don't_
1835 	 * include the aggid in the hashing (but we will store it as part of
1836 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
1837 	 * algorithm: a simple, quick algorithm that has no known funnels, and
1838 	 * gets good distribution in practice.  The efficacy of the hashing
1839 	 * algorithm (and a comparison with other algorithms) may be found by
1840 	 * running the ::dtrace_aggstat MDB dcmd.
1841 	 */
1842 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1843 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1844 		limit = i + act->dta_rec.dtrd_size;
1845 		ASSERT(limit <= size);
1846 		isstr = DTRACEACT_ISSTRING(act);
1847 
1848 		for (; i < limit; i++) {
1849 			hashval += data[i];
1850 			hashval += (hashval << 10);
1851 			hashval ^= (hashval >> 6);
1852 
1853 			if (isstr && data[i] == '\0')
1854 				break;
1855 		}
1856 	}
1857 
1858 	hashval += (hashval << 3);
1859 	hashval ^= (hashval >> 11);
1860 	hashval += (hashval << 15);
1861 
1862 	/*
1863 	 * Yes, the divide here is expensive -- but it's generally the least
1864 	 * of the performance issues given the amount of data that we iterate
1865 	 * over to compute hash values, compare data, etc.
1866 	 */
1867 	ndx = hashval % agb->dtagb_hashsize;
1868 
1869 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
1870 		ASSERT((caddr_t)key >= tomax);
1871 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
1872 
1873 		if (hashval != key->dtak_hashval || key->dtak_size != size)
1874 			continue;
1875 
1876 		kdata = key->dtak_data;
1877 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
1878 
1879 		for (act = agg->dtag_first; act->dta_intuple;
1880 		    act = act->dta_next) {
1881 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
1882 			limit = i + act->dta_rec.dtrd_size;
1883 			ASSERT(limit <= size);
1884 			isstr = DTRACEACT_ISSTRING(act);
1885 
1886 			for (; i < limit; i++) {
1887 				if (kdata[i] != data[i])
1888 					goto next;
1889 
1890 				if (isstr && data[i] == '\0')
1891 					break;
1892 			}
1893 		}
1894 
1895 		if (action != key->dtak_action) {
1896 			/*
1897 			 * We are aggregating on the same value in the same
1898 			 * aggregation with two different aggregating actions.
1899 			 * (This should have been picked up in the compiler,
1900 			 * so we may be dealing with errant or devious DIF.)
1901 			 * This is an error condition; we indicate as much,
1902 			 * and return.
1903 			 */
1904 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
1905 			return;
1906 		}
1907 
1908 		/*
1909 		 * This is a hit:  we need to apply the aggregator to
1910 		 * the value at this key.
1911 		 */
1912 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
1913 		return;
1914 next:
1915 		continue;
1916 	}
1917 
1918 	/*
1919 	 * We didn't find it.  We need to allocate some zero-filled space,
1920 	 * link it into the hash table appropriately, and apply the aggregator
1921 	 * to the (zero-filled) value.
1922 	 */
1923 	offs = buf->dtb_offset;
1924 	while (offs & (align - 1))
1925 		offs += sizeof (uint32_t);
1926 
1927 	/*
1928 	 * If we don't have enough room to both allocate a new key _and_
1929 	 * its associated data, increment the drop count and return.
1930 	 */
1931 	if ((uintptr_t)tomax + offs + fsize >
1932 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
1933 		dtrace_buffer_drop(buf);
1934 		return;
1935 	}
1936 
1937 	/*CONSTCOND*/
1938 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
1939 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
1940 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
1941 
1942 	key->dtak_data = kdata = tomax + offs;
1943 	buf->dtb_offset = offs + fsize;
1944 
1945 	/*
1946 	 * Now copy the data across.
1947 	 */
1948 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
1949 
1950 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
1951 		kdata[i] = data[i];
1952 
1953 	/*
1954 	 * Because strings are not zeroed out by default, we need to iterate
1955 	 * looking for actions that store strings, and we need to explicitly
1956 	 * pad these strings out with zeroes.
1957 	 */
1958 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
1959 		int nul;
1960 
1961 		if (!DTRACEACT_ISSTRING(act))
1962 			continue;
1963 
1964 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
1965 		limit = i + act->dta_rec.dtrd_size;
1966 		ASSERT(limit <= size);
1967 
1968 		for (nul = 0; i < limit; i++) {
1969 			if (nul) {
1970 				kdata[i] = '\0';
1971 				continue;
1972 			}
1973 
1974 			if (data[i] != '\0')
1975 				continue;
1976 
1977 			nul = 1;
1978 		}
1979 	}
1980 
1981 	for (i = size; i < fsize; i++)
1982 		kdata[i] = 0;
1983 
1984 	key->dtak_hashval = hashval;
1985 	key->dtak_size = size;
1986 	key->dtak_action = action;
1987 	key->dtak_next = agb->dtagb_hash[ndx];
1988 	agb->dtagb_hash[ndx] = key;
1989 
1990 	/*
1991 	 * Finally, apply the aggregator.
1992 	 */
1993 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
1994 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
1995 }
1996 
1997 /*
1998  * Given consumer state, this routine finds a speculation in the INACTIVE
1999  * state and transitions it into the ACTIVE state.  If there is no speculation
2000  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2001  * incremented -- it is up to the caller to take appropriate action.
2002  */
2003 static int
2004 dtrace_speculation(dtrace_state_t *state)
2005 {
2006 	int i = 0;
2007 	dtrace_speculation_state_t current;
2008 	uint32_t *stat = &state->dts_speculations_unavail, count;
2009 
2010 	while (i < state->dts_nspeculations) {
2011 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2012 
2013 		current = spec->dtsp_state;
2014 
2015 		if (current != DTRACESPEC_INACTIVE) {
2016 			if (current == DTRACESPEC_COMMITTINGMANY ||
2017 			    current == DTRACESPEC_COMMITTING ||
2018 			    current == DTRACESPEC_DISCARDING)
2019 				stat = &state->dts_speculations_busy;
2020 			i++;
2021 			continue;
2022 		}
2023 
2024 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2025 		    current, DTRACESPEC_ACTIVE) == current)
2026 			return (i + 1);
2027 	}
2028 
2029 	/*
2030 	 * We couldn't find a speculation.  If we found as much as a single
2031 	 * busy speculation buffer, we'll attribute this failure as "busy"
2032 	 * instead of "unavail".
2033 	 */
2034 	do {
2035 		count = *stat;
2036 	} while (dtrace_cas32(stat, count, count + 1) != count);
2037 
2038 	return (0);
2039 }
2040 
2041 /*
2042  * This routine commits an active speculation.  If the specified speculation
2043  * is not in a valid state to perform a commit(), this routine will silently do
2044  * nothing.  The state of the specified speculation is transitioned according
2045  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2046  */
2047 static void
2048 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2049     dtrace_specid_t which)
2050 {
2051 	dtrace_speculation_t *spec;
2052 	dtrace_buffer_t *src, *dest;
2053 	uintptr_t daddr, saddr, dlimit;
2054 	dtrace_speculation_state_t current, new;
2055 	intptr_t offs;
2056 
2057 	if (which == 0)
2058 		return;
2059 
2060 	if (which > state->dts_nspeculations) {
2061 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2062 		return;
2063 	}
2064 
2065 	spec = &state->dts_speculations[which - 1];
2066 	src = &spec->dtsp_buffer[cpu];
2067 	dest = &state->dts_buffer[cpu];
2068 
2069 	do {
2070 		current = spec->dtsp_state;
2071 
2072 		if (current == DTRACESPEC_COMMITTINGMANY)
2073 			break;
2074 
2075 		switch (current) {
2076 		case DTRACESPEC_INACTIVE:
2077 		case DTRACESPEC_DISCARDING:
2078 			return;
2079 
2080 		case DTRACESPEC_COMMITTING:
2081 			/*
2082 			 * This is only possible if we are (a) commit()'ing
2083 			 * without having done a prior speculate() on this CPU
2084 			 * and (b) racing with another commit() on a different
2085 			 * CPU.  There's nothing to do -- we just assert that
2086 			 * our offset is 0.
2087 			 */
2088 			ASSERT(src->dtb_offset == 0);
2089 			return;
2090 
2091 		case DTRACESPEC_ACTIVE:
2092 			new = DTRACESPEC_COMMITTING;
2093 			break;
2094 
2095 		case DTRACESPEC_ACTIVEONE:
2096 			/*
2097 			 * This speculation is active on one CPU.  If our
2098 			 * buffer offset is non-zero, we know that the one CPU
2099 			 * must be us.  Otherwise, we are committing on a
2100 			 * different CPU from the speculate(), and we must
2101 			 * rely on being asynchronously cleaned.
2102 			 */
2103 			if (src->dtb_offset != 0) {
2104 				new = DTRACESPEC_COMMITTING;
2105 				break;
2106 			}
2107 			/*FALLTHROUGH*/
2108 
2109 		case DTRACESPEC_ACTIVEMANY:
2110 			new = DTRACESPEC_COMMITTINGMANY;
2111 			break;
2112 
2113 		default:
2114 			ASSERT(0);
2115 		}
2116 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2117 	    current, new) != current);
2118 
2119 	/*
2120 	 * We have set the state to indicate that we are committing this
2121 	 * speculation.  Now reserve the necessary space in the destination
2122 	 * buffer.
2123 	 */
2124 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2125 	    sizeof (uint64_t), state, NULL)) < 0) {
2126 		dtrace_buffer_drop(dest);
2127 		goto out;
2128 	}
2129 
2130 	/*
2131 	 * We have the space; copy the buffer across.  (Note that this is a
2132 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2133 	 * a serious performance issue, a high-performance DTrace-specific
2134 	 * bcopy() should obviously be invented.)
2135 	 */
2136 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2137 	dlimit = daddr + src->dtb_offset;
2138 	saddr = (uintptr_t)src->dtb_tomax;
2139 
2140 	/*
2141 	 * First, the aligned portion.
2142 	 */
2143 	while (dlimit - daddr >= sizeof (uint64_t)) {
2144 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2145 
2146 		daddr += sizeof (uint64_t);
2147 		saddr += sizeof (uint64_t);
2148 	}
2149 
2150 	/*
2151 	 * Now any left-over bit...
2152 	 */
2153 	while (dlimit - daddr)
2154 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2155 
2156 	/*
2157 	 * Finally, commit the reserved space in the destination buffer.
2158 	 */
2159 	dest->dtb_offset = offs + src->dtb_offset;
2160 
2161 out:
2162 	/*
2163 	 * If we're lucky enough to be the only active CPU on this speculation
2164 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2165 	 */
2166 	if (current == DTRACESPEC_ACTIVE ||
2167 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2168 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2169 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2170 
2171 		ASSERT(rval == DTRACESPEC_COMMITTING);
2172 	}
2173 
2174 	src->dtb_offset = 0;
2175 	src->dtb_xamot_drops += src->dtb_drops;
2176 	src->dtb_drops = 0;
2177 }
2178 
2179 /*
2180  * This routine discards an active speculation.  If the specified speculation
2181  * is not in a valid state to perform a discard(), this routine will silently
2182  * do nothing.  The state of the specified speculation is transitioned
2183  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2184  */
2185 static void
2186 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2187     dtrace_specid_t which)
2188 {
2189 	dtrace_speculation_t *spec;
2190 	dtrace_speculation_state_t current, new;
2191 	dtrace_buffer_t *buf;
2192 
2193 	if (which == 0)
2194 		return;
2195 
2196 	if (which > state->dts_nspeculations) {
2197 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2198 		return;
2199 	}
2200 
2201 	spec = &state->dts_speculations[which - 1];
2202 	buf = &spec->dtsp_buffer[cpu];
2203 
2204 	do {
2205 		current = spec->dtsp_state;
2206 
2207 		switch (current) {
2208 		case DTRACESPEC_INACTIVE:
2209 		case DTRACESPEC_COMMITTINGMANY:
2210 		case DTRACESPEC_COMMITTING:
2211 		case DTRACESPEC_DISCARDING:
2212 			return;
2213 
2214 		case DTRACESPEC_ACTIVE:
2215 		case DTRACESPEC_ACTIVEMANY:
2216 			new = DTRACESPEC_DISCARDING;
2217 			break;
2218 
2219 		case DTRACESPEC_ACTIVEONE:
2220 			if (buf->dtb_offset != 0) {
2221 				new = DTRACESPEC_INACTIVE;
2222 			} else {
2223 				new = DTRACESPEC_DISCARDING;
2224 			}
2225 			break;
2226 
2227 		default:
2228 			ASSERT(0);
2229 		}
2230 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2231 	    current, new) != current);
2232 
2233 	buf->dtb_offset = 0;
2234 	buf->dtb_drops = 0;
2235 }
2236 
2237 /*
2238  * Note:  not called from probe context.  This function is called
2239  * asynchronously from cross call context to clean any speculations that are
2240  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2241  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2242  * speculation.
2243  */
2244 static void
2245 dtrace_speculation_clean_here(dtrace_state_t *state)
2246 {
2247 	dtrace_icookie_t cookie;
2248 	processorid_t cpu = CPU->cpu_id;
2249 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2250 	dtrace_specid_t i;
2251 
2252 	cookie = dtrace_interrupt_disable();
2253 
2254 	if (dest->dtb_tomax == NULL) {
2255 		dtrace_interrupt_enable(cookie);
2256 		return;
2257 	}
2258 
2259 	for (i = 0; i < state->dts_nspeculations; i++) {
2260 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2261 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2262 
2263 		if (src->dtb_tomax == NULL)
2264 			continue;
2265 
2266 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2267 			src->dtb_offset = 0;
2268 			continue;
2269 		}
2270 
2271 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2272 			continue;
2273 
2274 		if (src->dtb_offset == 0)
2275 			continue;
2276 
2277 		dtrace_speculation_commit(state, cpu, i + 1);
2278 	}
2279 
2280 	dtrace_interrupt_enable(cookie);
2281 }
2282 
2283 /*
2284  * Note:  not called from probe context.  This function is called
2285  * asynchronously (and at a regular interval) to clean any speculations that
2286  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2287  * is work to be done, it cross calls all CPUs to perform that work;
2288  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2289  * INACTIVE state until they have been cleaned by all CPUs.
2290  */
2291 static void
2292 dtrace_speculation_clean(dtrace_state_t *state)
2293 {
2294 	int work = 0, rv;
2295 	dtrace_specid_t i;
2296 
2297 	for (i = 0; i < state->dts_nspeculations; i++) {
2298 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2299 
2300 		ASSERT(!spec->dtsp_cleaning);
2301 
2302 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2303 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2304 			continue;
2305 
2306 		work++;
2307 		spec->dtsp_cleaning = 1;
2308 	}
2309 
2310 	if (!work)
2311 		return;
2312 
2313 	dtrace_xcall(DTRACE_CPUALL,
2314 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
2315 
2316 	/*
2317 	 * We now know that all CPUs have committed or discarded their
2318 	 * speculation buffers, as appropriate.  We can now set the state
2319 	 * to inactive.
2320 	 */
2321 	for (i = 0; i < state->dts_nspeculations; i++) {
2322 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2323 		dtrace_speculation_state_t current, new;
2324 
2325 		if (!spec->dtsp_cleaning)
2326 			continue;
2327 
2328 		current = spec->dtsp_state;
2329 		ASSERT(current == DTRACESPEC_DISCARDING ||
2330 		    current == DTRACESPEC_COMMITTINGMANY);
2331 
2332 		new = DTRACESPEC_INACTIVE;
2333 
2334 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
2335 		ASSERT(rv == current);
2336 		spec->dtsp_cleaning = 0;
2337 	}
2338 }
2339 
2340 /*
2341  * Called as part of a speculate() to get the speculative buffer associated
2342  * with a given speculation.  Returns NULL if the specified speculation is not
2343  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
2344  * the active CPU is not the specified CPU -- the speculation will be
2345  * atomically transitioned into the ACTIVEMANY state.
2346  */
2347 static dtrace_buffer_t *
2348 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
2349     dtrace_specid_t which)
2350 {
2351 	dtrace_speculation_t *spec;
2352 	dtrace_speculation_state_t current, new;
2353 	dtrace_buffer_t *buf;
2354 
2355 	if (which == 0)
2356 		return (NULL);
2357 
2358 	if (which > state->dts_nspeculations) {
2359 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2360 		return (NULL);
2361 	}
2362 
2363 	spec = &state->dts_speculations[which - 1];
2364 	buf = &spec->dtsp_buffer[cpuid];
2365 
2366 	do {
2367 		current = spec->dtsp_state;
2368 
2369 		switch (current) {
2370 		case DTRACESPEC_INACTIVE:
2371 		case DTRACESPEC_COMMITTINGMANY:
2372 		case DTRACESPEC_DISCARDING:
2373 			return (NULL);
2374 
2375 		case DTRACESPEC_COMMITTING:
2376 			ASSERT(buf->dtb_offset == 0);
2377 			return (NULL);
2378 
2379 		case DTRACESPEC_ACTIVEONE:
2380 			/*
2381 			 * This speculation is currently active on one CPU.
2382 			 * Check the offset in the buffer; if it's non-zero,
2383 			 * that CPU must be us (and we leave the state alone).
2384 			 * If it's zero, assume that we're starting on a new
2385 			 * CPU -- and change the state to indicate that the
2386 			 * speculation is active on more than one CPU.
2387 			 */
2388 			if (buf->dtb_offset != 0)
2389 				return (buf);
2390 
2391 			new = DTRACESPEC_ACTIVEMANY;
2392 			break;
2393 
2394 		case DTRACESPEC_ACTIVEMANY:
2395 			return (buf);
2396 
2397 		case DTRACESPEC_ACTIVE:
2398 			new = DTRACESPEC_ACTIVEONE;
2399 			break;
2400 
2401 		default:
2402 			ASSERT(0);
2403 		}
2404 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2405 	    current, new) != current);
2406 
2407 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
2408 	return (buf);
2409 }
2410 
2411 /*
2412  * Return a string.  In the event that the user lacks the privilege to access
2413  * arbitrary kernel memory, we copy the string out to scratch memory so that we
2414  * don't fail access checking.
2415  *
2416  * dtrace_dif_variable() uses this routine as a helper for various
2417  * builtin values such as 'execname' and 'probefunc.'
2418  */
2419 uintptr_t
2420 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
2421     dtrace_mstate_t *mstate)
2422 {
2423 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
2424 	uintptr_t ret;
2425 	size_t strsz;
2426 
2427 	/*
2428 	 * The easy case: this probe is allowed to read all of memory, so
2429 	 * we can just return this as a vanilla pointer.
2430 	 */
2431 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
2432 		return (addr);
2433 
2434 	/*
2435 	 * This is the tougher case: we copy the string in question from
2436 	 * kernel memory into scratch memory and return it that way: this
2437 	 * ensures that we won't trip up when access checking tests the
2438 	 * BYREF return value.
2439 	 */
2440 	strsz = dtrace_strlen((char *)addr, size) + 1;
2441 
2442 	if (mstate->dtms_scratch_ptr + strsz >
2443 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
2444 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2445 		return (NULL);
2446 	}
2447 
2448 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
2449 	    strsz);
2450 	ret = mstate->dtms_scratch_ptr;
2451 	mstate->dtms_scratch_ptr += strsz;
2452 	return (ret);
2453 }
2454 
2455 /*
2456  * This function implements the DIF emulator's variable lookups.  The emulator
2457  * passes a reserved variable identifier and optional built-in array index.
2458  */
2459 static uint64_t
2460 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
2461     uint64_t ndx)
2462 {
2463 	/*
2464 	 * If we're accessing one of the uncached arguments, we'll turn this
2465 	 * into a reference in the args array.
2466 	 */
2467 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
2468 		ndx = v - DIF_VAR_ARG0;
2469 		v = DIF_VAR_ARGS;
2470 	}
2471 
2472 	switch (v) {
2473 	case DIF_VAR_ARGS:
2474 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
2475 		if (ndx >= sizeof (mstate->dtms_arg) /
2476 		    sizeof (mstate->dtms_arg[0])) {
2477 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2478 			dtrace_provider_t *pv;
2479 			uint64_t val;
2480 
2481 			pv = mstate->dtms_probe->dtpr_provider;
2482 			if (pv->dtpv_pops.dtps_getargval != NULL)
2483 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
2484 				    mstate->dtms_probe->dtpr_id,
2485 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
2486 			else
2487 				val = dtrace_getarg(ndx, aframes);
2488 
2489 			/*
2490 			 * This is regrettably required to keep the compiler
2491 			 * from tail-optimizing the call to dtrace_getarg().
2492 			 * The condition always evaluates to true, but the
2493 			 * compiler has no way of figuring that out a priori.
2494 			 * (None of this would be necessary if the compiler
2495 			 * could be relied upon to _always_ tail-optimize
2496 			 * the call to dtrace_getarg() -- but it can't.)
2497 			 */
2498 			if (mstate->dtms_probe != NULL)
2499 				return (val);
2500 
2501 			ASSERT(0);
2502 		}
2503 
2504 		return (mstate->dtms_arg[ndx]);
2505 
2506 	case DIF_VAR_UREGS: {
2507 		klwp_t *lwp;
2508 
2509 		if (!dtrace_priv_proc(state))
2510 			return (0);
2511 
2512 		if ((lwp = curthread->t_lwp) == NULL) {
2513 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
2514 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = NULL;
2515 			return (0);
2516 		}
2517 
2518 		return (dtrace_getreg(lwp->lwp_regs, ndx));
2519 	}
2520 
2521 	case DIF_VAR_CURTHREAD:
2522 		if (!dtrace_priv_kernel(state))
2523 			return (0);
2524 		return ((uint64_t)(uintptr_t)curthread);
2525 
2526 	case DIF_VAR_TIMESTAMP:
2527 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
2528 			mstate->dtms_timestamp = dtrace_gethrtime();
2529 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
2530 		}
2531 		return (mstate->dtms_timestamp);
2532 
2533 	case DIF_VAR_VTIMESTAMP:
2534 		ASSERT(dtrace_vtime_references != 0);
2535 		return (curthread->t_dtrace_vtime);
2536 
2537 	case DIF_VAR_WALLTIMESTAMP:
2538 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
2539 			mstate->dtms_walltimestamp = dtrace_gethrestime();
2540 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
2541 		}
2542 		return (mstate->dtms_walltimestamp);
2543 
2544 	case DIF_VAR_IPL:
2545 		if (!dtrace_priv_kernel(state))
2546 			return (0);
2547 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
2548 			mstate->dtms_ipl = dtrace_getipl();
2549 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
2550 		}
2551 		return (mstate->dtms_ipl);
2552 
2553 	case DIF_VAR_EPID:
2554 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
2555 		return (mstate->dtms_epid);
2556 
2557 	case DIF_VAR_ID:
2558 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2559 		return (mstate->dtms_probe->dtpr_id);
2560 
2561 	case DIF_VAR_STACKDEPTH:
2562 		if (!dtrace_priv_kernel(state))
2563 			return (0);
2564 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
2565 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2566 
2567 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
2568 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
2569 		}
2570 		return (mstate->dtms_stackdepth);
2571 
2572 	case DIF_VAR_USTACKDEPTH:
2573 		if (!dtrace_priv_proc(state))
2574 			return (0);
2575 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
2576 			/*
2577 			 * See comment in DIF_VAR_PID.
2578 			 */
2579 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
2580 			    CPU_ON_INTR(CPU)) {
2581 				mstate->dtms_ustackdepth = 0;
2582 			} else {
2583 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
2584 				mstate->dtms_ustackdepth =
2585 				    dtrace_getustackdepth();
2586 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
2587 			}
2588 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
2589 		}
2590 		return (mstate->dtms_ustackdepth);
2591 
2592 	case DIF_VAR_CALLER:
2593 		if (!dtrace_priv_kernel(state))
2594 			return (0);
2595 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
2596 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
2597 
2598 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
2599 				/*
2600 				 * If this is an unanchored probe, we are
2601 				 * required to go through the slow path:
2602 				 * dtrace_caller() only guarantees correct
2603 				 * results for anchored probes.
2604 				 */
2605 				pc_t caller[2];
2606 
2607 				dtrace_getpcstack(caller, 2, aframes,
2608 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
2609 				mstate->dtms_caller = caller[1];
2610 			} else if ((mstate->dtms_caller =
2611 			    dtrace_caller(aframes)) == -1) {
2612 				/*
2613 				 * We have failed to do this the quick way;
2614 				 * we must resort to the slower approach of
2615 				 * calling dtrace_getpcstack().
2616 				 */
2617 				pc_t caller;
2618 
2619 				dtrace_getpcstack(&caller, 1, aframes, NULL);
2620 				mstate->dtms_caller = caller;
2621 			}
2622 
2623 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
2624 		}
2625 		return (mstate->dtms_caller);
2626 
2627 	case DIF_VAR_UCALLER:
2628 		if (!dtrace_priv_proc(state))
2629 			return (0);
2630 
2631 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
2632 			uint64_t ustack[3];
2633 
2634 			/*
2635 			 * dtrace_getupcstack() fills in the first uint64_t
2636 			 * with the current PID.  The second uint64_t will
2637 			 * be the program counter at user-level.  The third
2638 			 * uint64_t will contain the caller, which is what
2639 			 * we're after.
2640 			 */
2641 			ustack[2] = NULL;
2642 			dtrace_getupcstack(ustack, 3);
2643 			mstate->dtms_ucaller = ustack[2];
2644 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
2645 		}
2646 
2647 		return (mstate->dtms_ucaller);
2648 
2649 	case DIF_VAR_PROBEPROV:
2650 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2651 		return (dtrace_dif_varstr(
2652 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
2653 		    state, mstate));
2654 
2655 	case DIF_VAR_PROBEMOD:
2656 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2657 		return (dtrace_dif_varstr(
2658 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
2659 		    state, mstate));
2660 
2661 	case DIF_VAR_PROBEFUNC:
2662 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2663 		return (dtrace_dif_varstr(
2664 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
2665 		    state, mstate));
2666 
2667 	case DIF_VAR_PROBENAME:
2668 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
2669 		return (dtrace_dif_varstr(
2670 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
2671 		    state, mstate));
2672 
2673 	case DIF_VAR_PID:
2674 		if (!dtrace_priv_proc(state))
2675 			return (0);
2676 
2677 		/*
2678 		 * Note that we are assuming that an unanchored probe is
2679 		 * always due to a high-level interrupt.  (And we're assuming
2680 		 * that there is only a single high level interrupt.)
2681 		 */
2682 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2683 			return (pid0.pid_id);
2684 
2685 		/*
2686 		 * It is always safe to dereference one's own t_procp pointer:
2687 		 * it always points to a valid, allocated proc structure.
2688 		 * Further, it is always safe to dereference the p_pidp member
2689 		 * of one's own proc structure.  (These are truisms becuase
2690 		 * threads and processes don't clean up their own state --
2691 		 * they leave that task to whomever reaps them.)
2692 		 */
2693 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
2694 
2695 	case DIF_VAR_PPID:
2696 		if (!dtrace_priv_proc(state))
2697 			return (0);
2698 
2699 		/*
2700 		 * See comment in DIF_VAR_PID.
2701 		 */
2702 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2703 			return (pid0.pid_id);
2704 
2705 		/*
2706 		 * It is always safe to dereference one's own t_procp pointer:
2707 		 * it always points to a valid, allocated proc structure.
2708 		 * (This is true because threads don't clean up their own
2709 		 * state -- they leave that task to whomever reaps them.)
2710 		 */
2711 		return ((uint64_t)curthread->t_procp->p_ppid);
2712 
2713 	case DIF_VAR_TID:
2714 		/*
2715 		 * See comment in DIF_VAR_PID.
2716 		 */
2717 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2718 			return (0);
2719 
2720 		return ((uint64_t)curthread->t_tid);
2721 
2722 	case DIF_VAR_EXECNAME:
2723 		if (!dtrace_priv_proc(state))
2724 			return (0);
2725 
2726 		/*
2727 		 * See comment in DIF_VAR_PID.
2728 		 */
2729 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2730 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
2731 
2732 		/*
2733 		 * It is always safe to dereference one's own t_procp pointer:
2734 		 * it always points to a valid, allocated proc structure.
2735 		 * (This is true because threads don't clean up their own
2736 		 * state -- they leave that task to whomever reaps them.)
2737 		 */
2738 		return (dtrace_dif_varstr(
2739 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
2740 		    state, mstate));
2741 
2742 	case DIF_VAR_ZONENAME:
2743 		if (!dtrace_priv_proc(state))
2744 			return (0);
2745 
2746 		/*
2747 		 * See comment in DIF_VAR_PID.
2748 		 */
2749 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2750 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
2751 
2752 		/*
2753 		 * It is always safe to dereference one's own t_procp pointer:
2754 		 * it always points to a valid, allocated proc structure.
2755 		 * (This is true because threads don't clean up their own
2756 		 * state -- they leave that task to whomever reaps them.)
2757 		 */
2758 		return (dtrace_dif_varstr(
2759 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
2760 		    state, mstate));
2761 
2762 	case DIF_VAR_UID:
2763 		if (!dtrace_priv_proc(state))
2764 			return (0);
2765 
2766 		/*
2767 		 * See comment in DIF_VAR_PID.
2768 		 */
2769 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2770 			return ((uint64_t)p0.p_cred->cr_uid);
2771 
2772 		/*
2773 		 * It is always safe to dereference one's own t_procp pointer:
2774 		 * it always points to a valid, allocated proc structure.
2775 		 * (This is true because threads don't clean up their own
2776 		 * state -- they leave that task to whomever reaps them.)
2777 		 *
2778 		 * Additionally, it is safe to dereference one's own process
2779 		 * credential, since this is never NULL after process birth.
2780 		 */
2781 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
2782 
2783 	case DIF_VAR_GID:
2784 		if (!dtrace_priv_proc(state))
2785 			return (0);
2786 
2787 		/*
2788 		 * See comment in DIF_VAR_PID.
2789 		 */
2790 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2791 			return ((uint64_t)p0.p_cred->cr_gid);
2792 
2793 		/*
2794 		 * It is always safe to dereference one's own t_procp pointer:
2795 		 * it always points to a valid, allocated proc structure.
2796 		 * (This is true because threads don't clean up their own
2797 		 * state -- they leave that task to whomever reaps them.)
2798 		 *
2799 		 * Additionally, it is safe to dereference one's own process
2800 		 * credential, since this is never NULL after process birth.
2801 		 */
2802 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
2803 
2804 	case DIF_VAR_ERRNO: {
2805 		klwp_t *lwp;
2806 		if (!dtrace_priv_proc(state))
2807 			return (0);
2808 
2809 		/*
2810 		 * See comment in DIF_VAR_PID.
2811 		 */
2812 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
2813 			return (0);
2814 
2815 		/*
2816 		 * It is always safe to dereference one's own t_lwp pointer in
2817 		 * the event that this pointer is non-NULL.  (This is true
2818 		 * because threads and lwps don't clean up their own state --
2819 		 * they leave that task to whomever reaps them.)
2820 		 */
2821 		if ((lwp = curthread->t_lwp) == NULL)
2822 			return (0);
2823 
2824 		return ((uint64_t)lwp->lwp_errno);
2825 	}
2826 	default:
2827 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2828 		return (0);
2829 	}
2830 }
2831 
2832 /*
2833  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
2834  * Notice that we don't bother validating the proper number of arguments or
2835  * their types in the tuple stack.  This isn't needed because all argument
2836  * interpretation is safe because of our load safety -- the worst that can
2837  * happen is that a bogus program can obtain bogus results.
2838  */
2839 static void
2840 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
2841     dtrace_key_t *tupregs, int nargs,
2842     dtrace_mstate_t *mstate, dtrace_state_t *state)
2843 {
2844 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
2845 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
2846 	dtrace_vstate_t *vstate = &state->dts_vstate;
2847 
2848 	union {
2849 		mutex_impl_t mi;
2850 		uint64_t mx;
2851 	} m;
2852 
2853 	union {
2854 		krwlock_t ri;
2855 		uintptr_t rw;
2856 	} r;
2857 
2858 	switch (subr) {
2859 	case DIF_SUBR_RAND:
2860 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
2861 		break;
2862 
2863 	case DIF_SUBR_MUTEX_OWNED:
2864 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2865 		    mstate, vstate)) {
2866 			regs[rd] = NULL;
2867 			break;
2868 		}
2869 
2870 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2871 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
2872 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
2873 		else
2874 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
2875 		break;
2876 
2877 	case DIF_SUBR_MUTEX_OWNER:
2878 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2879 		    mstate, vstate)) {
2880 			regs[rd] = NULL;
2881 			break;
2882 		}
2883 
2884 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2885 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
2886 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
2887 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
2888 		else
2889 			regs[rd] = 0;
2890 		break;
2891 
2892 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
2893 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2894 		    mstate, vstate)) {
2895 			regs[rd] = NULL;
2896 			break;
2897 		}
2898 
2899 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2900 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
2901 		break;
2902 
2903 	case DIF_SUBR_MUTEX_TYPE_SPIN:
2904 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
2905 		    mstate, vstate)) {
2906 			regs[rd] = NULL;
2907 			break;
2908 		}
2909 
2910 		m.mx = dtrace_load64(tupregs[0].dttk_value);
2911 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
2912 		break;
2913 
2914 	case DIF_SUBR_RW_READ_HELD: {
2915 		uintptr_t tmp;
2916 
2917 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
2918 		    mstate, vstate)) {
2919 			regs[rd] = NULL;
2920 			break;
2921 		}
2922 
2923 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2924 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
2925 		break;
2926 	}
2927 
2928 	case DIF_SUBR_RW_WRITE_HELD:
2929 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
2930 		    mstate, vstate)) {
2931 			regs[rd] = NULL;
2932 			break;
2933 		}
2934 
2935 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2936 		regs[rd] = _RW_WRITE_HELD(&r.ri);
2937 		break;
2938 
2939 	case DIF_SUBR_RW_ISWRITER:
2940 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
2941 		    mstate, vstate)) {
2942 			regs[rd] = NULL;
2943 			break;
2944 		}
2945 
2946 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
2947 		regs[rd] = _RW_ISWRITER(&r.ri);
2948 		break;
2949 
2950 	case DIF_SUBR_BCOPY: {
2951 		/*
2952 		 * We need to be sure that the destination is in the scratch
2953 		 * region -- no other region is allowed.
2954 		 */
2955 		uintptr_t src = tupregs[0].dttk_value;
2956 		uintptr_t dest = tupregs[1].dttk_value;
2957 		size_t size = tupregs[2].dttk_value;
2958 
2959 		if (!dtrace_inscratch(dest, size, mstate)) {
2960 			*flags |= CPU_DTRACE_BADADDR;
2961 			*illval = regs[rd];
2962 			break;
2963 		}
2964 
2965 		if (!dtrace_canload(src, size, mstate, vstate)) {
2966 			regs[rd] = NULL;
2967 			break;
2968 		}
2969 
2970 		dtrace_bcopy((void *)src, (void *)dest, size);
2971 		break;
2972 	}
2973 
2974 	case DIF_SUBR_ALLOCA:
2975 	case DIF_SUBR_COPYIN: {
2976 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
2977 		uint64_t size =
2978 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
2979 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
2980 
2981 		/*
2982 		 * This action doesn't require any credential checks since
2983 		 * probes will not activate in user contexts to which the
2984 		 * enabling user does not have permissions.
2985 		 */
2986 
2987 		/*
2988 		 * Rounding up the user allocation size could have overflowed
2989 		 * a large, bogus allocation (like -1ULL) to 0.
2990 		 */
2991 		if (scratch_size < size ||
2992 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
2993 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
2994 			regs[rd] = NULL;
2995 			break;
2996 		}
2997 
2998 		if (subr == DIF_SUBR_COPYIN) {
2999 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3000 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3001 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3002 		}
3003 
3004 		mstate->dtms_scratch_ptr += scratch_size;
3005 		regs[rd] = dest;
3006 		break;
3007 	}
3008 
3009 	case DIF_SUBR_COPYINTO: {
3010 		uint64_t size = tupregs[1].dttk_value;
3011 		uintptr_t dest = tupregs[2].dttk_value;
3012 
3013 		/*
3014 		 * This action doesn't require any credential checks since
3015 		 * probes will not activate in user contexts to which the
3016 		 * enabling user does not have permissions.
3017 		 */
3018 		if (!dtrace_inscratch(dest, size, mstate)) {
3019 			*flags |= CPU_DTRACE_BADADDR;
3020 			*illval = regs[rd];
3021 			break;
3022 		}
3023 
3024 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3025 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
3026 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3027 		break;
3028 	}
3029 
3030 	case DIF_SUBR_COPYINSTR: {
3031 		uintptr_t dest = mstate->dtms_scratch_ptr;
3032 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3033 
3034 		if (nargs > 1 && tupregs[1].dttk_value < size)
3035 			size = tupregs[1].dttk_value + 1;
3036 
3037 		/*
3038 		 * This action doesn't require any credential checks since
3039 		 * probes will not activate in user contexts to which the
3040 		 * enabling user does not have permissions.
3041 		 */
3042 		if (!DTRACE_INSCRATCH(mstate, size)) {
3043 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3044 			regs[rd] = NULL;
3045 			break;
3046 		}
3047 
3048 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3049 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
3050 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3051 
3052 		((char *)dest)[size - 1] = '\0';
3053 		mstate->dtms_scratch_ptr += size;
3054 		regs[rd] = dest;
3055 		break;
3056 	}
3057 
3058 	case DIF_SUBR_MSGSIZE:
3059 	case DIF_SUBR_MSGDSIZE: {
3060 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
3061 		uintptr_t wptr, rptr;
3062 		size_t count = 0;
3063 		int cont = 0;
3064 
3065 		while (baddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3066 
3067 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
3068 			    vstate)) {
3069 				regs[rd] = NULL;
3070 				break;
3071 			}
3072 
3073 			wptr = dtrace_loadptr(baddr +
3074 			    offsetof(mblk_t, b_wptr));
3075 
3076 			rptr = dtrace_loadptr(baddr +
3077 			    offsetof(mblk_t, b_rptr));
3078 
3079 			if (wptr < rptr) {
3080 				*flags |= CPU_DTRACE_BADADDR;
3081 				*illval = tupregs[0].dttk_value;
3082 				break;
3083 			}
3084 
3085 			daddr = dtrace_loadptr(baddr +
3086 			    offsetof(mblk_t, b_datap));
3087 
3088 			baddr = dtrace_loadptr(baddr +
3089 			    offsetof(mblk_t, b_cont));
3090 
3091 			/*
3092 			 * We want to prevent against denial-of-service here,
3093 			 * so we're only going to search the list for
3094 			 * dtrace_msgdsize_max mblks.
3095 			 */
3096 			if (cont++ > dtrace_msgdsize_max) {
3097 				*flags |= CPU_DTRACE_ILLOP;
3098 				break;
3099 			}
3100 
3101 			if (subr == DIF_SUBR_MSGDSIZE) {
3102 				if (dtrace_load8(daddr +
3103 				    offsetof(dblk_t, db_type)) != M_DATA)
3104 					continue;
3105 			}
3106 
3107 			count += wptr - rptr;
3108 		}
3109 
3110 		if (!(*flags & CPU_DTRACE_FAULT))
3111 			regs[rd] = count;
3112 
3113 		break;
3114 	}
3115 
3116 	case DIF_SUBR_PROGENYOF: {
3117 		pid_t pid = tupregs[0].dttk_value;
3118 		proc_t *p;
3119 		int rval = 0;
3120 
3121 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3122 
3123 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
3124 			if (p->p_pidp->pid_id == pid) {
3125 				rval = 1;
3126 				break;
3127 			}
3128 		}
3129 
3130 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3131 
3132 		regs[rd] = rval;
3133 		break;
3134 	}
3135 
3136 	case DIF_SUBR_SPECULATION:
3137 		regs[rd] = dtrace_speculation(state);
3138 		break;
3139 
3140 	case DIF_SUBR_COPYOUT: {
3141 		uintptr_t kaddr = tupregs[0].dttk_value;
3142 		uintptr_t uaddr = tupregs[1].dttk_value;
3143 		uint64_t size = tupregs[2].dttk_value;
3144 
3145 		if (!dtrace_destructive_disallow &&
3146 		    dtrace_priv_proc_control(state) &&
3147 		    !dtrace_istoxic(kaddr, size)) {
3148 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3149 			dtrace_copyout(kaddr, uaddr, size, flags);
3150 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3151 		}
3152 		break;
3153 	}
3154 
3155 	case DIF_SUBR_COPYOUTSTR: {
3156 		uintptr_t kaddr = tupregs[0].dttk_value;
3157 		uintptr_t uaddr = tupregs[1].dttk_value;
3158 		uint64_t size = tupregs[2].dttk_value;
3159 
3160 		if (!dtrace_destructive_disallow &&
3161 		    dtrace_priv_proc_control(state) &&
3162 		    !dtrace_istoxic(kaddr, size)) {
3163 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3164 			dtrace_copyoutstr(kaddr, uaddr, size, flags);
3165 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3166 		}
3167 		break;
3168 	}
3169 
3170 	case DIF_SUBR_STRLEN: {
3171 		size_t sz;
3172 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
3173 		sz = dtrace_strlen((char *)addr,
3174 		    state->dts_options[DTRACEOPT_STRSIZE]);
3175 
3176 		if (!dtrace_canload(addr, sz + 1, mstate, vstate)) {
3177 			regs[rd] = NULL;
3178 			break;
3179 		}
3180 
3181 		regs[rd] = sz;
3182 
3183 		break;
3184 	}
3185 
3186 	case DIF_SUBR_STRCHR:
3187 	case DIF_SUBR_STRRCHR: {
3188 		/*
3189 		 * We're going to iterate over the string looking for the
3190 		 * specified character.  We will iterate until we have reached
3191 		 * the string length or we have found the character.  If this
3192 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
3193 		 * of the specified character instead of the first.
3194 		 */
3195 		uintptr_t saddr = tupregs[0].dttk_value;
3196 		uintptr_t addr = tupregs[0].dttk_value;
3197 		uintptr_t limit = addr + state->dts_options[DTRACEOPT_STRSIZE];
3198 		char c, target = (char)tupregs[1].dttk_value;
3199 
3200 		for (regs[rd] = NULL; addr < limit; addr++) {
3201 			if ((c = dtrace_load8(addr)) == target) {
3202 				regs[rd] = addr;
3203 
3204 				if (subr == DIF_SUBR_STRCHR)
3205 					break;
3206 			}
3207 
3208 			if (c == '\0')
3209 				break;
3210 		}
3211 
3212 		if (!dtrace_canload(saddr, addr - saddr, mstate, vstate)) {
3213 			regs[rd] = NULL;
3214 			break;
3215 		}
3216 
3217 		break;
3218 	}
3219 
3220 	case DIF_SUBR_STRSTR:
3221 	case DIF_SUBR_INDEX:
3222 	case DIF_SUBR_RINDEX: {
3223 		/*
3224 		 * We're going to iterate over the string looking for the
3225 		 * specified string.  We will iterate until we have reached
3226 		 * the string length or we have found the string.  (Yes, this
3227 		 * is done in the most naive way possible -- but considering
3228 		 * that the string we're searching for is likely to be
3229 		 * relatively short, the complexity of Rabin-Karp or similar
3230 		 * hardly seems merited.)
3231 		 */
3232 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
3233 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
3234 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3235 		size_t len = dtrace_strlen(addr, size);
3236 		size_t sublen = dtrace_strlen(substr, size);
3237 		char *limit = addr + len, *orig = addr;
3238 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
3239 		int inc = 1;
3240 
3241 		regs[rd] = notfound;
3242 
3243 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
3244 			regs[rd] = NULL;
3245 			break;
3246 		}
3247 
3248 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
3249 		    vstate)) {
3250 			regs[rd] = NULL;
3251 			break;
3252 		}
3253 
3254 		/*
3255 		 * strstr() and index()/rindex() have similar semantics if
3256 		 * both strings are the empty string: strstr() returns a
3257 		 * pointer to the (empty) string, and index() and rindex()
3258 		 * both return index 0 (regardless of any position argument).
3259 		 */
3260 		if (sublen == 0 && len == 0) {
3261 			if (subr == DIF_SUBR_STRSTR)
3262 				regs[rd] = (uintptr_t)addr;
3263 			else
3264 				regs[rd] = 0;
3265 			break;
3266 		}
3267 
3268 		if (subr != DIF_SUBR_STRSTR) {
3269 			if (subr == DIF_SUBR_RINDEX) {
3270 				limit = orig - 1;
3271 				addr += len;
3272 				inc = -1;
3273 			}
3274 
3275 			/*
3276 			 * Both index() and rindex() take an optional position
3277 			 * argument that denotes the starting position.
3278 			 */
3279 			if (nargs == 3) {
3280 				int64_t pos = (int64_t)tupregs[2].dttk_value;
3281 
3282 				/*
3283 				 * If the position argument to index() is
3284 				 * negative, Perl implicitly clamps it at
3285 				 * zero.  This semantic is a little surprising
3286 				 * given the special meaning of negative
3287 				 * positions to similar Perl functions like
3288 				 * substr(), but it appears to reflect a
3289 				 * notion that index() can start from a
3290 				 * negative index and increment its way up to
3291 				 * the string.  Given this notion, Perl's
3292 				 * rindex() is at least self-consistent in
3293 				 * that it implicitly clamps positions greater
3294 				 * than the string length to be the string
3295 				 * length.  Where Perl completely loses
3296 				 * coherence, however, is when the specified
3297 				 * substring is the empty string ("").  In
3298 				 * this case, even if the position is
3299 				 * negative, rindex() returns 0 -- and even if
3300 				 * the position is greater than the length,
3301 				 * index() returns the string length.  These
3302 				 * semantics violate the notion that index()
3303 				 * should never return a value less than the
3304 				 * specified position and that rindex() should
3305 				 * never return a value greater than the
3306 				 * specified position.  (One assumes that
3307 				 * these semantics are artifacts of Perl's
3308 				 * implementation and not the results of
3309 				 * deliberate design -- it beggars belief that
3310 				 * even Larry Wall could desire such oddness.)
3311 				 * While in the abstract one would wish for
3312 				 * consistent position semantics across
3313 				 * substr(), index() and rindex() -- or at the
3314 				 * very least self-consistent position
3315 				 * semantics for index() and rindex() -- we
3316 				 * instead opt to keep with the extant Perl
3317 				 * semantics, in all their broken glory.  (Do
3318 				 * we have more desire to maintain Perl's
3319 				 * semantics than Perl does?  Probably.)
3320 				 */
3321 				if (subr == DIF_SUBR_RINDEX) {
3322 					if (pos < 0) {
3323 						if (sublen == 0)
3324 							regs[rd] = 0;
3325 						break;
3326 					}
3327 
3328 					if (pos > len)
3329 						pos = len;
3330 				} else {
3331 					if (pos < 0)
3332 						pos = 0;
3333 
3334 					if (pos >= len) {
3335 						if (sublen == 0)
3336 							regs[rd] = len;
3337 						break;
3338 					}
3339 				}
3340 
3341 				addr = orig + pos;
3342 			}
3343 		}
3344 
3345 		for (regs[rd] = notfound; addr != limit; addr += inc) {
3346 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
3347 				if (subr != DIF_SUBR_STRSTR) {
3348 					/*
3349 					 * As D index() and rindex() are
3350 					 * modeled on Perl (and not on awk),
3351 					 * we return a zero-based (and not a
3352 					 * one-based) index.  (For you Perl
3353 					 * weenies: no, we're not going to add
3354 					 * $[ -- and shouldn't you be at a con
3355 					 * or something?)
3356 					 */
3357 					regs[rd] = (uintptr_t)(addr - orig);
3358 					break;
3359 				}
3360 
3361 				ASSERT(subr == DIF_SUBR_STRSTR);
3362 				regs[rd] = (uintptr_t)addr;
3363 				break;
3364 			}
3365 		}
3366 
3367 		break;
3368 	}
3369 
3370 	case DIF_SUBR_STRTOK: {
3371 		uintptr_t addr = tupregs[0].dttk_value;
3372 		uintptr_t tokaddr = tupregs[1].dttk_value;
3373 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3374 		uintptr_t limit, toklimit = tokaddr + size;
3375 		uint8_t c, tokmap[32];	 /* 256 / 8 */
3376 		char *dest = (char *)mstate->dtms_scratch_ptr;
3377 		int i;
3378 
3379 		/*
3380 		 * Check both the token buffer and (later) the input buffer,
3381 		 * since both could be non-scratch addresses.
3382 		 */
3383 		if (!dtrace_strcanload(tokaddr, size, mstate, vstate)) {
3384 			regs[rd] = NULL;
3385 			break;
3386 		}
3387 
3388 		if (!DTRACE_INSCRATCH(mstate, size)) {
3389 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3390 			regs[rd] = NULL;
3391 			break;
3392 		}
3393 
3394 		if (addr == NULL) {
3395 			/*
3396 			 * If the address specified is NULL, we use our saved
3397 			 * strtok pointer from the mstate.  Note that this
3398 			 * means that the saved strtok pointer is _only_
3399 			 * valid within multiple enablings of the same probe --
3400 			 * it behaves like an implicit clause-local variable.
3401 			 */
3402 			addr = mstate->dtms_strtok;
3403 		} else {
3404 			/*
3405 			 * If the user-specified address is non-NULL we must
3406 			 * access check it.  This is the only time we have
3407 			 * a chance to do so, since this address may reside
3408 			 * in the string table of this clause-- future calls
3409 			 * (when we fetch addr from mstate->dtms_strtok)
3410 			 * would fail this access check.
3411 			 */
3412 			if (!dtrace_strcanload(addr, size, mstate, vstate)) {
3413 				regs[rd] = NULL;
3414 				break;
3415 			}
3416 		}
3417 
3418 		/*
3419 		 * First, zero the token map, and then process the token
3420 		 * string -- setting a bit in the map for every character
3421 		 * found in the token string.
3422 		 */
3423 		for (i = 0; i < sizeof (tokmap); i++)
3424 			tokmap[i] = 0;
3425 
3426 		for (; tokaddr < toklimit; tokaddr++) {
3427 			if ((c = dtrace_load8(tokaddr)) == '\0')
3428 				break;
3429 
3430 			ASSERT((c >> 3) < sizeof (tokmap));
3431 			tokmap[c >> 3] |= (1 << (c & 0x7));
3432 		}
3433 
3434 		for (limit = addr + size; addr < limit; addr++) {
3435 			/*
3436 			 * We're looking for a character that is _not_ contained
3437 			 * in the token string.
3438 			 */
3439 			if ((c = dtrace_load8(addr)) == '\0')
3440 				break;
3441 
3442 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
3443 				break;
3444 		}
3445 
3446 		if (c == '\0') {
3447 			/*
3448 			 * We reached the end of the string without finding
3449 			 * any character that was not in the token string.
3450 			 * We return NULL in this case, and we set the saved
3451 			 * address to NULL as well.
3452 			 */
3453 			regs[rd] = NULL;
3454 			mstate->dtms_strtok = NULL;
3455 			break;
3456 		}
3457 
3458 		/*
3459 		 * From here on, we're copying into the destination string.
3460 		 */
3461 		for (i = 0; addr < limit && i < size - 1; addr++) {
3462 			if ((c = dtrace_load8(addr)) == '\0')
3463 				break;
3464 
3465 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
3466 				break;
3467 
3468 			ASSERT(i < size);
3469 			dest[i++] = c;
3470 		}
3471 
3472 		ASSERT(i < size);
3473 		dest[i] = '\0';
3474 		regs[rd] = (uintptr_t)dest;
3475 		mstate->dtms_scratch_ptr += size;
3476 		mstate->dtms_strtok = addr;
3477 		break;
3478 	}
3479 
3480 	case DIF_SUBR_SUBSTR: {
3481 		uintptr_t s = tupregs[0].dttk_value;
3482 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3483 		char *d = (char *)mstate->dtms_scratch_ptr;
3484 		int64_t index = (int64_t)tupregs[1].dttk_value;
3485 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
3486 		size_t len = dtrace_strlen((char *)s, size);
3487 		int64_t i = 0;
3488 
3489 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
3490 			regs[rd] = NULL;
3491 			break;
3492 		}
3493 
3494 		if (nargs <= 2)
3495 			remaining = (int64_t)size;
3496 
3497 		if (!DTRACE_INSCRATCH(mstate, size)) {
3498 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3499 			regs[rd] = NULL;
3500 			break;
3501 		}
3502 
3503 		if (index < 0) {
3504 			index += len;
3505 
3506 			if (index < 0 && index + remaining > 0) {
3507 				remaining += index;
3508 				index = 0;
3509 			}
3510 		}
3511 
3512 		if (index >= len || index < 0)
3513 			index = len;
3514 
3515 		for (d[0] = '\0'; remaining > 0; remaining--) {
3516 			if ((d[i++] = dtrace_load8(s++ + index)) == '\0')
3517 				break;
3518 
3519 			if (i == size) {
3520 				d[i - 1] = '\0';
3521 				break;
3522 			}
3523 		}
3524 
3525 		mstate->dtms_scratch_ptr += size;
3526 		regs[rd] = (uintptr_t)d;
3527 		break;
3528 	}
3529 
3530 	case DIF_SUBR_GETMAJOR:
3531 #ifdef _LP64
3532 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
3533 #else
3534 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
3535 #endif
3536 		break;
3537 
3538 	case DIF_SUBR_GETMINOR:
3539 #ifdef _LP64
3540 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
3541 #else
3542 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
3543 #endif
3544 		break;
3545 
3546 	case DIF_SUBR_DDI_PATHNAME: {
3547 		/*
3548 		 * This one is a galactic mess.  We are going to roughly
3549 		 * emulate ddi_pathname(), but it's made more complicated
3550 		 * by the fact that we (a) want to include the minor name and
3551 		 * (b) must proceed iteratively instead of recursively.
3552 		 */
3553 		uintptr_t dest = mstate->dtms_scratch_ptr;
3554 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3555 		char *start = (char *)dest, *end = start + size - 1;
3556 		uintptr_t daddr = tupregs[0].dttk_value;
3557 		int64_t minor = (int64_t)tupregs[1].dttk_value;
3558 		char *s;
3559 		int i, len, depth = 0;
3560 
3561 		/*
3562 		 * Due to all the pointer jumping we do and context we must
3563 		 * rely upon, we just mandate that the user must have kernel
3564 		 * read privileges to use this routine.
3565 		 */
3566 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
3567 			*flags |= CPU_DTRACE_KPRIV;
3568 			*illval = daddr;
3569 			regs[rd] = NULL;
3570 		}
3571 
3572 		if (!DTRACE_INSCRATCH(mstate, size)) {
3573 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3574 			regs[rd] = NULL;
3575 			break;
3576 		}
3577 
3578 		*end = '\0';
3579 
3580 		/*
3581 		 * We want to have a name for the minor.  In order to do this,
3582 		 * we need to walk the minor list from the devinfo.  We want
3583 		 * to be sure that we don't infinitely walk a circular list,
3584 		 * so we check for circularity by sending a scout pointer
3585 		 * ahead two elements for every element that we iterate over;
3586 		 * if the list is circular, these will ultimately point to the
3587 		 * same element.  You may recognize this little trick as the
3588 		 * answer to a stupid interview question -- one that always
3589 		 * seems to be asked by those who had to have it laboriously
3590 		 * explained to them, and who can't even concisely describe
3591 		 * the conditions under which one would be forced to resort to
3592 		 * this technique.  Needless to say, those conditions are
3593 		 * found here -- and probably only here.  Is this is the only
3594 		 * use of this infamous trick in shipping, production code?
3595 		 * If it isn't, it probably should be...
3596 		 */
3597 		if (minor != -1) {
3598 			uintptr_t maddr = dtrace_loadptr(daddr +
3599 			    offsetof(struct dev_info, devi_minor));
3600 
3601 			uintptr_t next = offsetof(struct ddi_minor_data, next);
3602 			uintptr_t name = offsetof(struct ddi_minor_data,
3603 			    d_minor) + offsetof(struct ddi_minor, name);
3604 			uintptr_t dev = offsetof(struct ddi_minor_data,
3605 			    d_minor) + offsetof(struct ddi_minor, dev);
3606 			uintptr_t scout;
3607 
3608 			if (maddr != NULL)
3609 				scout = dtrace_loadptr(maddr + next);
3610 
3611 			while (maddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3612 				uint64_t m;
3613 #ifdef _LP64
3614 				m = dtrace_load64(maddr + dev) & MAXMIN64;
3615 #else
3616 				m = dtrace_load32(maddr + dev) & MAXMIN;
3617 #endif
3618 				if (m != minor) {
3619 					maddr = dtrace_loadptr(maddr + next);
3620 
3621 					if (scout == NULL)
3622 						continue;
3623 
3624 					scout = dtrace_loadptr(scout + next);
3625 
3626 					if (scout == NULL)
3627 						continue;
3628 
3629 					scout = dtrace_loadptr(scout + next);
3630 
3631 					if (scout == NULL)
3632 						continue;
3633 
3634 					if (scout == maddr) {
3635 						*flags |= CPU_DTRACE_ILLOP;
3636 						break;
3637 					}
3638 
3639 					continue;
3640 				}
3641 
3642 				/*
3643 				 * We have the minor data.  Now we need to
3644 				 * copy the minor's name into the end of the
3645 				 * pathname.
3646 				 */
3647 				s = (char *)dtrace_loadptr(maddr + name);
3648 				len = dtrace_strlen(s, size);
3649 
3650 				if (*flags & CPU_DTRACE_FAULT)
3651 					break;
3652 
3653 				if (len != 0) {
3654 					if ((end -= (len + 1)) < start)
3655 						break;
3656 
3657 					*end = ':';
3658 				}
3659 
3660 				for (i = 1; i <= len; i++)
3661 					end[i] = dtrace_load8((uintptr_t)s++);
3662 				break;
3663 			}
3664 		}
3665 
3666 		while (daddr != NULL && !(*flags & CPU_DTRACE_FAULT)) {
3667 			ddi_node_state_t devi_state;
3668 
3669 			devi_state = dtrace_load32(daddr +
3670 			    offsetof(struct dev_info, devi_node_state));
3671 
3672 			if (*flags & CPU_DTRACE_FAULT)
3673 				break;
3674 
3675 			if (devi_state >= DS_INITIALIZED) {
3676 				s = (char *)dtrace_loadptr(daddr +
3677 				    offsetof(struct dev_info, devi_addr));
3678 				len = dtrace_strlen(s, size);
3679 
3680 				if (*flags & CPU_DTRACE_FAULT)
3681 					break;
3682 
3683 				if (len != 0) {
3684 					if ((end -= (len + 1)) < start)
3685 						break;
3686 
3687 					*end = '@';
3688 				}
3689 
3690 				for (i = 1; i <= len; i++)
3691 					end[i] = dtrace_load8((uintptr_t)s++);
3692 			}
3693 
3694 			/*
3695 			 * Now for the node name...
3696 			 */
3697 			s = (char *)dtrace_loadptr(daddr +
3698 			    offsetof(struct dev_info, devi_node_name));
3699 
3700 			daddr = dtrace_loadptr(daddr +
3701 			    offsetof(struct dev_info, devi_parent));
3702 
3703 			/*
3704 			 * If our parent is NULL (that is, if we're the root
3705 			 * node), we're going to use the special path
3706 			 * "devices".
3707 			 */
3708 			if (daddr == NULL)
3709 				s = "devices";
3710 
3711 			len = dtrace_strlen(s, size);
3712 			if (*flags & CPU_DTRACE_FAULT)
3713 				break;
3714 
3715 			if ((end -= (len + 1)) < start)
3716 				break;
3717 
3718 			for (i = 1; i <= len; i++)
3719 				end[i] = dtrace_load8((uintptr_t)s++);
3720 			*end = '/';
3721 
3722 			if (depth++ > dtrace_devdepth_max) {
3723 				*flags |= CPU_DTRACE_ILLOP;
3724 				break;
3725 			}
3726 		}
3727 
3728 		if (end < start)
3729 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3730 
3731 		if (daddr == NULL) {
3732 			regs[rd] = (uintptr_t)end;
3733 			mstate->dtms_scratch_ptr += size;
3734 		}
3735 
3736 		break;
3737 	}
3738 
3739 	case DIF_SUBR_STRJOIN: {
3740 		char *d = (char *)mstate->dtms_scratch_ptr;
3741 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3742 		uintptr_t s1 = tupregs[0].dttk_value;
3743 		uintptr_t s2 = tupregs[1].dttk_value;
3744 		int i = 0;
3745 
3746 		if (!dtrace_strcanload(s1, size, mstate, vstate) ||
3747 		    !dtrace_strcanload(s2, size, mstate, vstate)) {
3748 			regs[rd] = NULL;
3749 			break;
3750 		}
3751 
3752 		if (!DTRACE_INSCRATCH(mstate, size)) {
3753 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3754 			regs[rd] = NULL;
3755 			break;
3756 		}
3757 
3758 		for (;;) {
3759 			if (i >= size) {
3760 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3761 				regs[rd] = NULL;
3762 				break;
3763 			}
3764 
3765 			if ((d[i++] = dtrace_load8(s1++)) == '\0') {
3766 				i--;
3767 				break;
3768 			}
3769 		}
3770 
3771 		for (;;) {
3772 			if (i >= size) {
3773 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3774 				regs[rd] = NULL;
3775 				break;
3776 			}
3777 
3778 			if ((d[i++] = dtrace_load8(s2++)) == '\0')
3779 				break;
3780 		}
3781 
3782 		if (i < size) {
3783 			mstate->dtms_scratch_ptr += i;
3784 			regs[rd] = (uintptr_t)d;
3785 		}
3786 
3787 		break;
3788 	}
3789 
3790 	case DIF_SUBR_LLTOSTR: {
3791 		int64_t i = (int64_t)tupregs[0].dttk_value;
3792 		int64_t val = i < 0 ? i * -1 : i;
3793 		uint64_t size = 22;	/* enough room for 2^64 in decimal */
3794 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
3795 
3796 		if (!DTRACE_INSCRATCH(mstate, size)) {
3797 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3798 			regs[rd] = NULL;
3799 			break;
3800 		}
3801 
3802 		for (*end-- = '\0'; val; val /= 10)
3803 			*end-- = '0' + (val % 10);
3804 
3805 		if (i == 0)
3806 			*end-- = '0';
3807 
3808 		if (i < 0)
3809 			*end-- = '-';
3810 
3811 		regs[rd] = (uintptr_t)end + 1;
3812 		mstate->dtms_scratch_ptr += size;
3813 		break;
3814 	}
3815 
3816 	case DIF_SUBR_HTONS:
3817 	case DIF_SUBR_NTOHS:
3818 #ifdef _BIG_ENDIAN
3819 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
3820 #else
3821 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
3822 #endif
3823 		break;
3824 
3825 
3826 	case DIF_SUBR_HTONL:
3827 	case DIF_SUBR_NTOHL:
3828 #ifdef _BIG_ENDIAN
3829 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
3830 #else
3831 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
3832 #endif
3833 		break;
3834 
3835 
3836 	case DIF_SUBR_HTONLL:
3837 	case DIF_SUBR_NTOHLL:
3838 #ifdef _BIG_ENDIAN
3839 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
3840 #else
3841 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
3842 #endif
3843 		break;
3844 
3845 
3846 	case DIF_SUBR_DIRNAME:
3847 	case DIF_SUBR_BASENAME: {
3848 		char *dest = (char *)mstate->dtms_scratch_ptr;
3849 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3850 		uintptr_t src = tupregs[0].dttk_value;
3851 		int i, j, len = dtrace_strlen((char *)src, size);
3852 		int lastbase = -1, firstbase = -1, lastdir = -1;
3853 		int start, end;
3854 
3855 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
3856 			regs[rd] = NULL;
3857 			break;
3858 		}
3859 
3860 		if (!DTRACE_INSCRATCH(mstate, size)) {
3861 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3862 			regs[rd] = NULL;
3863 			break;
3864 		}
3865 
3866 		/*
3867 		 * The basename and dirname for a zero-length string is
3868 		 * defined to be "."
3869 		 */
3870 		if (len == 0) {
3871 			len = 1;
3872 			src = (uintptr_t)".";
3873 		}
3874 
3875 		/*
3876 		 * Start from the back of the string, moving back toward the
3877 		 * front until we see a character that isn't a slash.  That
3878 		 * character is the last character in the basename.
3879 		 */
3880 		for (i = len - 1; i >= 0; i--) {
3881 			if (dtrace_load8(src + i) != '/')
3882 				break;
3883 		}
3884 
3885 		if (i >= 0)
3886 			lastbase = i;
3887 
3888 		/*
3889 		 * Starting from the last character in the basename, move
3890 		 * towards the front until we find a slash.  The character
3891 		 * that we processed immediately before that is the first
3892 		 * character in the basename.
3893 		 */
3894 		for (; i >= 0; i--) {
3895 			if (dtrace_load8(src + i) == '/')
3896 				break;
3897 		}
3898 
3899 		if (i >= 0)
3900 			firstbase = i + 1;
3901 
3902 		/*
3903 		 * Now keep going until we find a non-slash character.  That
3904 		 * character is the last character in the dirname.
3905 		 */
3906 		for (; i >= 0; i--) {
3907 			if (dtrace_load8(src + i) != '/')
3908 				break;
3909 		}
3910 
3911 		if (i >= 0)
3912 			lastdir = i;
3913 
3914 		ASSERT(!(lastbase == -1 && firstbase != -1));
3915 		ASSERT(!(firstbase == -1 && lastdir != -1));
3916 
3917 		if (lastbase == -1) {
3918 			/*
3919 			 * We didn't find a non-slash character.  We know that
3920 			 * the length is non-zero, so the whole string must be
3921 			 * slashes.  In either the dirname or the basename
3922 			 * case, we return '/'.
3923 			 */
3924 			ASSERT(firstbase == -1);
3925 			firstbase = lastbase = lastdir = 0;
3926 		}
3927 
3928 		if (firstbase == -1) {
3929 			/*
3930 			 * The entire string consists only of a basename
3931 			 * component.  If we're looking for dirname, we need
3932 			 * to change our string to be just "."; if we're
3933 			 * looking for a basename, we'll just set the first
3934 			 * character of the basename to be 0.
3935 			 */
3936 			if (subr == DIF_SUBR_DIRNAME) {
3937 				ASSERT(lastdir == -1);
3938 				src = (uintptr_t)".";
3939 				lastdir = 0;
3940 			} else {
3941 				firstbase = 0;
3942 			}
3943 		}
3944 
3945 		if (subr == DIF_SUBR_DIRNAME) {
3946 			if (lastdir == -1) {
3947 				/*
3948 				 * We know that we have a slash in the name --
3949 				 * or lastdir would be set to 0, above.  And
3950 				 * because lastdir is -1, we know that this
3951 				 * slash must be the first character.  (That
3952 				 * is, the full string must be of the form
3953 				 * "/basename".)  In this case, the last
3954 				 * character of the directory name is 0.
3955 				 */
3956 				lastdir = 0;
3957 			}
3958 
3959 			start = 0;
3960 			end = lastdir;
3961 		} else {
3962 			ASSERT(subr == DIF_SUBR_BASENAME);
3963 			ASSERT(firstbase != -1 && lastbase != -1);
3964 			start = firstbase;
3965 			end = lastbase;
3966 		}
3967 
3968 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
3969 			dest[j] = dtrace_load8(src + i);
3970 
3971 		dest[j] = '\0';
3972 		regs[rd] = (uintptr_t)dest;
3973 		mstate->dtms_scratch_ptr += size;
3974 		break;
3975 	}
3976 
3977 	case DIF_SUBR_CLEANPATH: {
3978 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
3979 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3980 		uintptr_t src = tupregs[0].dttk_value;
3981 		int i = 0, j = 0;
3982 
3983 		if (!dtrace_strcanload(src, size, mstate, vstate)) {
3984 			regs[rd] = NULL;
3985 			break;
3986 		}
3987 
3988 		if (!DTRACE_INSCRATCH(mstate, size)) {
3989 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3990 			regs[rd] = NULL;
3991 			break;
3992 		}
3993 
3994 		/*
3995 		 * Move forward, loading each character.
3996 		 */
3997 		do {
3998 			c = dtrace_load8(src + i++);
3999 next:
4000 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
4001 				break;
4002 
4003 			if (c != '/') {
4004 				dest[j++] = c;
4005 				continue;
4006 			}
4007 
4008 			c = dtrace_load8(src + i++);
4009 
4010 			if (c == '/') {
4011 				/*
4012 				 * We have two slashes -- we can just advance
4013 				 * to the next character.
4014 				 */
4015 				goto next;
4016 			}
4017 
4018 			if (c != '.') {
4019 				/*
4020 				 * This is not "." and it's not ".." -- we can
4021 				 * just store the "/" and this character and
4022 				 * drive on.
4023 				 */
4024 				dest[j++] = '/';
4025 				dest[j++] = c;
4026 				continue;
4027 			}
4028 
4029 			c = dtrace_load8(src + i++);
4030 
4031 			if (c == '/') {
4032 				/*
4033 				 * This is a "/./" component.  We're not going
4034 				 * to store anything in the destination buffer;
4035 				 * we're just going to go to the next component.
4036 				 */
4037 				goto next;
4038 			}
4039 
4040 			if (c != '.') {
4041 				/*
4042 				 * This is not ".." -- we can just store the
4043 				 * "/." and this character and continue
4044 				 * processing.
4045 				 */
4046 				dest[j++] = '/';
4047 				dest[j++] = '.';
4048 				dest[j++] = c;
4049 				continue;
4050 			}
4051 
4052 			c = dtrace_load8(src + i++);
4053 
4054 			if (c != '/' && c != '\0') {
4055 				/*
4056 				 * This is not ".." -- it's "..[mumble]".
4057 				 * We'll store the "/.." and this character
4058 				 * and continue processing.
4059 				 */
4060 				dest[j++] = '/';
4061 				dest[j++] = '.';
4062 				dest[j++] = '.';
4063 				dest[j++] = c;
4064 				continue;
4065 			}
4066 
4067 			/*
4068 			 * This is "/../" or "/..\0".  We need to back up
4069 			 * our destination pointer until we find a "/".
4070 			 */
4071 			i--;
4072 			while (j != 0 && dest[--j] != '/')
4073 				continue;
4074 
4075 			if (c == '\0')
4076 				dest[++j] = '/';
4077 		} while (c != '\0');
4078 
4079 		dest[j] = '\0';
4080 		regs[rd] = (uintptr_t)dest;
4081 		mstate->dtms_scratch_ptr += size;
4082 		break;
4083 	}
4084 
4085 	case DIF_SUBR_INET_NTOA:
4086 	case DIF_SUBR_INET_NTOA6:
4087 	case DIF_SUBR_INET_NTOP: {
4088 		size_t size;
4089 		int af, argi, i;
4090 		char *base, *end;
4091 
4092 		if (subr == DIF_SUBR_INET_NTOP) {
4093 			af = (int)tupregs[0].dttk_value;
4094 			argi = 1;
4095 		} else {
4096 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
4097 			argi = 0;
4098 		}
4099 
4100 		if (af == AF_INET) {
4101 			ipaddr_t ip4;
4102 			uint8_t *ptr8, val;
4103 
4104 			/*
4105 			 * Safely load the IPv4 address.
4106 			 */
4107 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
4108 
4109 			/*
4110 			 * Check an IPv4 string will fit in scratch.
4111 			 */
4112 			size = INET_ADDRSTRLEN;
4113 			if (!DTRACE_INSCRATCH(mstate, size)) {
4114 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4115 				regs[rd] = NULL;
4116 				break;
4117 			}
4118 			base = (char *)mstate->dtms_scratch_ptr;
4119 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4120 
4121 			/*
4122 			 * Stringify as a dotted decimal quad.
4123 			 */
4124 			*end-- = '\0';
4125 			ptr8 = (uint8_t *)&ip4;
4126 			for (i = 3; i >= 0; i--) {
4127 				val = ptr8[i];
4128 
4129 				if (val == 0) {
4130 					*end-- = '0';
4131 				} else {
4132 					for (; val; val /= 10) {
4133 						*end-- = '0' + (val % 10);
4134 					}
4135 				}
4136 
4137 				if (i > 0)
4138 					*end-- = '.';
4139 			}
4140 			ASSERT(end + 1 >= base);
4141 
4142 		} else if (af == AF_INET6) {
4143 			struct in6_addr ip6;
4144 			int firstzero, tryzero, numzero, v6end;
4145 			uint16_t val;
4146 			const char digits[] = "0123456789abcdef";
4147 
4148 			/*
4149 			 * Stringify using RFC 1884 convention 2 - 16 bit
4150 			 * hexadecimal values with a zero-run compression.
4151 			 * Lower case hexadecimal digits are used.
4152 			 * 	eg, fe80::214:4fff:fe0b:76c8.
4153 			 * The IPv4 embedded form is returned for inet_ntop,
4154 			 * just the IPv4 string is returned for inet_ntoa6.
4155 			 */
4156 
4157 			/*
4158 			 * Safely load the IPv6 address.
4159 			 */
4160 			dtrace_bcopy(
4161 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
4162 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
4163 
4164 			/*
4165 			 * Check an IPv6 string will fit in scratch.
4166 			 */
4167 			size = INET6_ADDRSTRLEN;
4168 			if (!DTRACE_INSCRATCH(mstate, size)) {
4169 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4170 				regs[rd] = NULL;
4171 				break;
4172 			}
4173 			base = (char *)mstate->dtms_scratch_ptr;
4174 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
4175 			*end-- = '\0';
4176 
4177 			/*
4178 			 * Find the longest run of 16 bit zero values
4179 			 * for the single allowed zero compression - "::".
4180 			 */
4181 			firstzero = -1;
4182 			tryzero = -1;
4183 			numzero = 1;
4184 			for (i = 0; i < sizeof (struct in6_addr); i++) {
4185 				if (ip6._S6_un._S6_u8[i] == 0 &&
4186 				    tryzero == -1 && i % 2 == 0) {
4187 					tryzero = i;
4188 					continue;
4189 				}
4190 
4191 				if (tryzero != -1 &&
4192 				    (ip6._S6_un._S6_u8[i] != 0 ||
4193 				    i == sizeof (struct in6_addr) - 1)) {
4194 
4195 					if (i - tryzero <= numzero) {
4196 						tryzero = -1;
4197 						continue;
4198 					}
4199 
4200 					firstzero = tryzero;
4201 					numzero = i - i % 2 - tryzero;
4202 					tryzero = -1;
4203 
4204 					if (ip6._S6_un._S6_u8[i] == 0 &&
4205 					    i == sizeof (struct in6_addr) - 1)
4206 						numzero += 2;
4207 				}
4208 			}
4209 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
4210 
4211 			/*
4212 			 * Check for an IPv4 embedded address.
4213 			 */
4214 			v6end = sizeof (struct in6_addr) - 2;
4215 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
4216 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
4217 				for (i = sizeof (struct in6_addr) - 1;
4218 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
4219 					ASSERT(end >= base);
4220 
4221 					val = ip6._S6_un._S6_u8[i];
4222 
4223 					if (val == 0) {
4224 						*end-- = '0';
4225 					} else {
4226 						for (; val; val /= 10) {
4227 							*end-- = '0' + val % 10;
4228 						}
4229 					}
4230 
4231 					if (i > DTRACE_V4MAPPED_OFFSET)
4232 						*end-- = '.';
4233 				}
4234 
4235 				if (subr == DIF_SUBR_INET_NTOA6)
4236 					goto inetout;
4237 
4238 				/*
4239 				 * Set v6end to skip the IPv4 address that
4240 				 * we have already stringified.
4241 				 */
4242 				v6end = 10;
4243 			}
4244 
4245 			/*
4246 			 * Build the IPv6 string by working through the
4247 			 * address in reverse.
4248 			 */
4249 			for (i = v6end; i >= 0; i -= 2) {
4250 				ASSERT(end >= base);
4251 
4252 				if (i == firstzero + numzero - 2) {
4253 					*end-- = ':';
4254 					*end-- = ':';
4255 					i -= numzero - 2;
4256 					continue;
4257 				}
4258 
4259 				if (i < 14 && i != firstzero - 2)
4260 					*end-- = ':';
4261 
4262 				val = (ip6._S6_un._S6_u8[i] << 8) +
4263 				    ip6._S6_un._S6_u8[i + 1];
4264 
4265 				if (val == 0) {
4266 					*end-- = '0';
4267 				} else {
4268 					for (; val; val /= 16) {
4269 						*end-- = digits[val % 16];
4270 					}
4271 				}
4272 			}
4273 			ASSERT(end + 1 >= base);
4274 
4275 		} else {
4276 			/*
4277 			 * The user didn't use AH_INET or AH_INET6.
4278 			 */
4279 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
4280 			regs[rd] = NULL;
4281 			break;
4282 		}
4283 
4284 inetout:	regs[rd] = (uintptr_t)end + 1;
4285 		mstate->dtms_scratch_ptr += size;
4286 		break;
4287 	}
4288 
4289 	}
4290 }
4291 
4292 /*
4293  * Emulate the execution of DTrace IR instructions specified by the given
4294  * DIF object.  This function is deliberately void of assertions as all of
4295  * the necessary checks are handled by a call to dtrace_difo_validate().
4296  */
4297 static uint64_t
4298 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
4299     dtrace_vstate_t *vstate, dtrace_state_t *state)
4300 {
4301 	const dif_instr_t *text = difo->dtdo_buf;
4302 	const uint_t textlen = difo->dtdo_len;
4303 	const char *strtab = difo->dtdo_strtab;
4304 	const uint64_t *inttab = difo->dtdo_inttab;
4305 
4306 	uint64_t rval = 0;
4307 	dtrace_statvar_t *svar;
4308 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
4309 	dtrace_difv_t *v;
4310 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4311 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4312 
4313 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
4314 	uint64_t regs[DIF_DIR_NREGS];
4315 	uint64_t *tmp;
4316 
4317 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
4318 	int64_t cc_r;
4319 	uint_t pc = 0, id, opc;
4320 	uint8_t ttop = 0;
4321 	dif_instr_t instr;
4322 	uint_t r1, r2, rd;
4323 
4324 	/*
4325 	 * We stash the current DIF object into the machine state: we need it
4326 	 * for subsequent access checking.
4327 	 */
4328 	mstate->dtms_difo = difo;
4329 
4330 	regs[DIF_REG_R0] = 0; 		/* %r0 is fixed at zero */
4331 
4332 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
4333 		opc = pc;
4334 
4335 		instr = text[pc++];
4336 		r1 = DIF_INSTR_R1(instr);
4337 		r2 = DIF_INSTR_R2(instr);
4338 		rd = DIF_INSTR_RD(instr);
4339 
4340 		switch (DIF_INSTR_OP(instr)) {
4341 		case DIF_OP_OR:
4342 			regs[rd] = regs[r1] | regs[r2];
4343 			break;
4344 		case DIF_OP_XOR:
4345 			regs[rd] = regs[r1] ^ regs[r2];
4346 			break;
4347 		case DIF_OP_AND:
4348 			regs[rd] = regs[r1] & regs[r2];
4349 			break;
4350 		case DIF_OP_SLL:
4351 			regs[rd] = regs[r1] << regs[r2];
4352 			break;
4353 		case DIF_OP_SRL:
4354 			regs[rd] = regs[r1] >> regs[r2];
4355 			break;
4356 		case DIF_OP_SUB:
4357 			regs[rd] = regs[r1] - regs[r2];
4358 			break;
4359 		case DIF_OP_ADD:
4360 			regs[rd] = regs[r1] + regs[r2];
4361 			break;
4362 		case DIF_OP_MUL:
4363 			regs[rd] = regs[r1] * regs[r2];
4364 			break;
4365 		case DIF_OP_SDIV:
4366 			if (regs[r2] == 0) {
4367 				regs[rd] = 0;
4368 				*flags |= CPU_DTRACE_DIVZERO;
4369 			} else {
4370 				regs[rd] = (int64_t)regs[r1] /
4371 				    (int64_t)regs[r2];
4372 			}
4373 			break;
4374 
4375 		case DIF_OP_UDIV:
4376 			if (regs[r2] == 0) {
4377 				regs[rd] = 0;
4378 				*flags |= CPU_DTRACE_DIVZERO;
4379 			} else {
4380 				regs[rd] = regs[r1] / regs[r2];
4381 			}
4382 			break;
4383 
4384 		case DIF_OP_SREM:
4385 			if (regs[r2] == 0) {
4386 				regs[rd] = 0;
4387 				*flags |= CPU_DTRACE_DIVZERO;
4388 			} else {
4389 				regs[rd] = (int64_t)regs[r1] %
4390 				    (int64_t)regs[r2];
4391 			}
4392 			break;
4393 
4394 		case DIF_OP_UREM:
4395 			if (regs[r2] == 0) {
4396 				regs[rd] = 0;
4397 				*flags |= CPU_DTRACE_DIVZERO;
4398 			} else {
4399 				regs[rd] = regs[r1] % regs[r2];
4400 			}
4401 			break;
4402 
4403 		case DIF_OP_NOT:
4404 			regs[rd] = ~regs[r1];
4405 			break;
4406 		case DIF_OP_MOV:
4407 			regs[rd] = regs[r1];
4408 			break;
4409 		case DIF_OP_CMP:
4410 			cc_r = regs[r1] - regs[r2];
4411 			cc_n = cc_r < 0;
4412 			cc_z = cc_r == 0;
4413 			cc_v = 0;
4414 			cc_c = regs[r1] < regs[r2];
4415 			break;
4416 		case DIF_OP_TST:
4417 			cc_n = cc_v = cc_c = 0;
4418 			cc_z = regs[r1] == 0;
4419 			break;
4420 		case DIF_OP_BA:
4421 			pc = DIF_INSTR_LABEL(instr);
4422 			break;
4423 		case DIF_OP_BE:
4424 			if (cc_z)
4425 				pc = DIF_INSTR_LABEL(instr);
4426 			break;
4427 		case DIF_OP_BNE:
4428 			if (cc_z == 0)
4429 				pc = DIF_INSTR_LABEL(instr);
4430 			break;
4431 		case DIF_OP_BG:
4432 			if ((cc_z | (cc_n ^ cc_v)) == 0)
4433 				pc = DIF_INSTR_LABEL(instr);
4434 			break;
4435 		case DIF_OP_BGU:
4436 			if ((cc_c | cc_z) == 0)
4437 				pc = DIF_INSTR_LABEL(instr);
4438 			break;
4439 		case DIF_OP_BGE:
4440 			if ((cc_n ^ cc_v) == 0)
4441 				pc = DIF_INSTR_LABEL(instr);
4442 			break;
4443 		case DIF_OP_BGEU:
4444 			if (cc_c == 0)
4445 				pc = DIF_INSTR_LABEL(instr);
4446 			break;
4447 		case DIF_OP_BL:
4448 			if (cc_n ^ cc_v)
4449 				pc = DIF_INSTR_LABEL(instr);
4450 			break;
4451 		case DIF_OP_BLU:
4452 			if (cc_c)
4453 				pc = DIF_INSTR_LABEL(instr);
4454 			break;
4455 		case DIF_OP_BLE:
4456 			if (cc_z | (cc_n ^ cc_v))
4457 				pc = DIF_INSTR_LABEL(instr);
4458 			break;
4459 		case DIF_OP_BLEU:
4460 			if (cc_c | cc_z)
4461 				pc = DIF_INSTR_LABEL(instr);
4462 			break;
4463 		case DIF_OP_RLDSB:
4464 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4465 				*flags |= CPU_DTRACE_KPRIV;
4466 				*illval = regs[r1];
4467 				break;
4468 			}
4469 			/*FALLTHROUGH*/
4470 		case DIF_OP_LDSB:
4471 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
4472 			break;
4473 		case DIF_OP_RLDSH:
4474 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4475 				*flags |= CPU_DTRACE_KPRIV;
4476 				*illval = regs[r1];
4477 				break;
4478 			}
4479 			/*FALLTHROUGH*/
4480 		case DIF_OP_LDSH:
4481 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
4482 			break;
4483 		case DIF_OP_RLDSW:
4484 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4485 				*flags |= CPU_DTRACE_KPRIV;
4486 				*illval = regs[r1];
4487 				break;
4488 			}
4489 			/*FALLTHROUGH*/
4490 		case DIF_OP_LDSW:
4491 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
4492 			break;
4493 		case DIF_OP_RLDUB:
4494 			if (!dtrace_canstore(regs[r1], 1, mstate, vstate)) {
4495 				*flags |= CPU_DTRACE_KPRIV;
4496 				*illval = regs[r1];
4497 				break;
4498 			}
4499 			/*FALLTHROUGH*/
4500 		case DIF_OP_LDUB:
4501 			regs[rd] = dtrace_load8(regs[r1]);
4502 			break;
4503 		case DIF_OP_RLDUH:
4504 			if (!dtrace_canstore(regs[r1], 2, mstate, vstate)) {
4505 				*flags |= CPU_DTRACE_KPRIV;
4506 				*illval = regs[r1];
4507 				break;
4508 			}
4509 			/*FALLTHROUGH*/
4510 		case DIF_OP_LDUH:
4511 			regs[rd] = dtrace_load16(regs[r1]);
4512 			break;
4513 		case DIF_OP_RLDUW:
4514 			if (!dtrace_canstore(regs[r1], 4, mstate, vstate)) {
4515 				*flags |= CPU_DTRACE_KPRIV;
4516 				*illval = regs[r1];
4517 				break;
4518 			}
4519 			/*FALLTHROUGH*/
4520 		case DIF_OP_LDUW:
4521 			regs[rd] = dtrace_load32(regs[r1]);
4522 			break;
4523 		case DIF_OP_RLDX:
4524 			if (!dtrace_canstore(regs[r1], 8, mstate, vstate)) {
4525 				*flags |= CPU_DTRACE_KPRIV;
4526 				*illval = regs[r1];
4527 				break;
4528 			}
4529 			/*FALLTHROUGH*/
4530 		case DIF_OP_LDX:
4531 			regs[rd] = dtrace_load64(regs[r1]);
4532 			break;
4533 		case DIF_OP_ULDSB:
4534 			regs[rd] = (int8_t)
4535 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4536 			break;
4537 		case DIF_OP_ULDSH:
4538 			regs[rd] = (int16_t)
4539 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4540 			break;
4541 		case DIF_OP_ULDSW:
4542 			regs[rd] = (int32_t)
4543 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4544 			break;
4545 		case DIF_OP_ULDUB:
4546 			regs[rd] =
4547 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
4548 			break;
4549 		case DIF_OP_ULDUH:
4550 			regs[rd] =
4551 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
4552 			break;
4553 		case DIF_OP_ULDUW:
4554 			regs[rd] =
4555 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
4556 			break;
4557 		case DIF_OP_ULDX:
4558 			regs[rd] =
4559 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
4560 			break;
4561 		case DIF_OP_RET:
4562 			rval = regs[rd];
4563 			pc = textlen;
4564 			break;
4565 		case DIF_OP_NOP:
4566 			break;
4567 		case DIF_OP_SETX:
4568 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
4569 			break;
4570 		case DIF_OP_SETS:
4571 			regs[rd] = (uint64_t)(uintptr_t)
4572 			    (strtab + DIF_INSTR_STRING(instr));
4573 			break;
4574 		case DIF_OP_SCMP: {
4575 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
4576 			uintptr_t s1 = regs[r1];
4577 			uintptr_t s2 = regs[r2];
4578 
4579 			if (s1 != NULL &&
4580 			    !dtrace_strcanload(s1, sz, mstate, vstate))
4581 				break;
4582 			if (s2 != NULL &&
4583 			    !dtrace_strcanload(s2, sz, mstate, vstate))
4584 				break;
4585 
4586 			cc_r = dtrace_strncmp((char *)s1, (char *)s2, sz);
4587 
4588 			cc_n = cc_r < 0;
4589 			cc_z = cc_r == 0;
4590 			cc_v = cc_c = 0;
4591 			break;
4592 		}
4593 		case DIF_OP_LDGA:
4594 			regs[rd] = dtrace_dif_variable(mstate, state,
4595 			    r1, regs[r2]);
4596 			break;
4597 		case DIF_OP_LDGS:
4598 			id = DIF_INSTR_VAR(instr);
4599 
4600 			if (id >= DIF_VAR_OTHER_UBASE) {
4601 				uintptr_t a;
4602 
4603 				id -= DIF_VAR_OTHER_UBASE;
4604 				svar = vstate->dtvs_globals[id];
4605 				ASSERT(svar != NULL);
4606 				v = &svar->dtsv_var;
4607 
4608 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
4609 					regs[rd] = svar->dtsv_data;
4610 					break;
4611 				}
4612 
4613 				a = (uintptr_t)svar->dtsv_data;
4614 
4615 				if (*(uint8_t *)a == UINT8_MAX) {
4616 					/*
4617 					 * If the 0th byte is set to UINT8_MAX
4618 					 * then this is to be treated as a
4619 					 * reference to a NULL variable.
4620 					 */
4621 					regs[rd] = NULL;
4622 				} else {
4623 					regs[rd] = a + sizeof (uint64_t);
4624 				}
4625 
4626 				break;
4627 			}
4628 
4629 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
4630 			break;
4631 
4632 		case DIF_OP_STGS:
4633 			id = DIF_INSTR_VAR(instr);
4634 
4635 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4636 			id -= DIF_VAR_OTHER_UBASE;
4637 
4638 			svar = vstate->dtvs_globals[id];
4639 			ASSERT(svar != NULL);
4640 			v = &svar->dtsv_var;
4641 
4642 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4643 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4644 
4645 				ASSERT(a != NULL);
4646 				ASSERT(svar->dtsv_size != 0);
4647 
4648 				if (regs[rd] == NULL) {
4649 					*(uint8_t *)a = UINT8_MAX;
4650 					break;
4651 				} else {
4652 					*(uint8_t *)a = 0;
4653 					a += sizeof (uint64_t);
4654 				}
4655 				if (!dtrace_vcanload(
4656 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4657 				    mstate, vstate))
4658 					break;
4659 
4660 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4661 				    (void *)a, &v->dtdv_type);
4662 				break;
4663 			}
4664 
4665 			svar->dtsv_data = regs[rd];
4666 			break;
4667 
4668 		case DIF_OP_LDTA:
4669 			/*
4670 			 * There are no DTrace built-in thread-local arrays at
4671 			 * present.  This opcode is saved for future work.
4672 			 */
4673 			*flags |= CPU_DTRACE_ILLOP;
4674 			regs[rd] = 0;
4675 			break;
4676 
4677 		case DIF_OP_LDLS:
4678 			id = DIF_INSTR_VAR(instr);
4679 
4680 			if (id < DIF_VAR_OTHER_UBASE) {
4681 				/*
4682 				 * For now, this has no meaning.
4683 				 */
4684 				regs[rd] = 0;
4685 				break;
4686 			}
4687 
4688 			id -= DIF_VAR_OTHER_UBASE;
4689 
4690 			ASSERT(id < vstate->dtvs_nlocals);
4691 			ASSERT(vstate->dtvs_locals != NULL);
4692 
4693 			svar = vstate->dtvs_locals[id];
4694 			ASSERT(svar != NULL);
4695 			v = &svar->dtsv_var;
4696 
4697 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4698 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4699 				size_t sz = v->dtdv_type.dtdt_size;
4700 
4701 				sz += sizeof (uint64_t);
4702 				ASSERT(svar->dtsv_size == NCPU * sz);
4703 				a += CPU->cpu_id * sz;
4704 
4705 				if (*(uint8_t *)a == UINT8_MAX) {
4706 					/*
4707 					 * If the 0th byte is set to UINT8_MAX
4708 					 * then this is to be treated as a
4709 					 * reference to a NULL variable.
4710 					 */
4711 					regs[rd] = NULL;
4712 				} else {
4713 					regs[rd] = a + sizeof (uint64_t);
4714 				}
4715 
4716 				break;
4717 			}
4718 
4719 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4720 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4721 			regs[rd] = tmp[CPU->cpu_id];
4722 			break;
4723 
4724 		case DIF_OP_STLS:
4725 			id = DIF_INSTR_VAR(instr);
4726 
4727 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4728 			id -= DIF_VAR_OTHER_UBASE;
4729 			ASSERT(id < vstate->dtvs_nlocals);
4730 
4731 			ASSERT(vstate->dtvs_locals != NULL);
4732 			svar = vstate->dtvs_locals[id];
4733 			ASSERT(svar != NULL);
4734 			v = &svar->dtsv_var;
4735 
4736 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4737 				uintptr_t a = (uintptr_t)svar->dtsv_data;
4738 				size_t sz = v->dtdv_type.dtdt_size;
4739 
4740 				sz += sizeof (uint64_t);
4741 				ASSERT(svar->dtsv_size == NCPU * sz);
4742 				a += CPU->cpu_id * sz;
4743 
4744 				if (regs[rd] == NULL) {
4745 					*(uint8_t *)a = UINT8_MAX;
4746 					break;
4747 				} else {
4748 					*(uint8_t *)a = 0;
4749 					a += sizeof (uint64_t);
4750 				}
4751 
4752 				if (!dtrace_vcanload(
4753 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4754 				    mstate, vstate))
4755 					break;
4756 
4757 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4758 				    (void *)a, &v->dtdv_type);
4759 				break;
4760 			}
4761 
4762 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
4763 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
4764 			tmp[CPU->cpu_id] = regs[rd];
4765 			break;
4766 
4767 		case DIF_OP_LDTS: {
4768 			dtrace_dynvar_t *dvar;
4769 			dtrace_key_t *key;
4770 
4771 			id = DIF_INSTR_VAR(instr);
4772 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4773 			id -= DIF_VAR_OTHER_UBASE;
4774 			v = &vstate->dtvs_tlocals[id];
4775 
4776 			key = &tupregs[DIF_DTR_NREGS];
4777 			key[0].dttk_value = (uint64_t)id;
4778 			key[0].dttk_size = 0;
4779 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4780 			key[1].dttk_size = 0;
4781 
4782 			dvar = dtrace_dynvar(dstate, 2, key,
4783 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
4784 			    mstate, vstate);
4785 
4786 			if (dvar == NULL) {
4787 				regs[rd] = 0;
4788 				break;
4789 			}
4790 
4791 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4792 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4793 			} else {
4794 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4795 			}
4796 
4797 			break;
4798 		}
4799 
4800 		case DIF_OP_STTS: {
4801 			dtrace_dynvar_t *dvar;
4802 			dtrace_key_t *key;
4803 
4804 			id = DIF_INSTR_VAR(instr);
4805 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4806 			id -= DIF_VAR_OTHER_UBASE;
4807 
4808 			key = &tupregs[DIF_DTR_NREGS];
4809 			key[0].dttk_value = (uint64_t)id;
4810 			key[0].dttk_size = 0;
4811 			DTRACE_TLS_THRKEY(key[1].dttk_value);
4812 			key[1].dttk_size = 0;
4813 			v = &vstate->dtvs_tlocals[id];
4814 
4815 			dvar = dtrace_dynvar(dstate, 2, key,
4816 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4817 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4818 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4819 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
4820 
4821 			/*
4822 			 * Given that we're storing to thread-local data,
4823 			 * we need to flush our predicate cache.
4824 			 */
4825 			curthread->t_predcache = NULL;
4826 
4827 			if (dvar == NULL)
4828 				break;
4829 
4830 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4831 				if (!dtrace_vcanload(
4832 				    (void *)(uintptr_t)regs[rd],
4833 				    &v->dtdv_type, mstate, vstate))
4834 					break;
4835 
4836 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4837 				    dvar->dtdv_data, &v->dtdv_type);
4838 			} else {
4839 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4840 			}
4841 
4842 			break;
4843 		}
4844 
4845 		case DIF_OP_SRA:
4846 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
4847 			break;
4848 
4849 		case DIF_OP_CALL:
4850 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
4851 			    regs, tupregs, ttop, mstate, state);
4852 			break;
4853 
4854 		case DIF_OP_PUSHTR:
4855 			if (ttop == DIF_DTR_NREGS) {
4856 				*flags |= CPU_DTRACE_TUPOFLOW;
4857 				break;
4858 			}
4859 
4860 			if (r1 == DIF_TYPE_STRING) {
4861 				/*
4862 				 * If this is a string type and the size is 0,
4863 				 * we'll use the system-wide default string
4864 				 * size.  Note that we are _not_ looking at
4865 				 * the value of the DTRACEOPT_STRSIZE option;
4866 				 * had this been set, we would expect to have
4867 				 * a non-zero size value in the "pushtr".
4868 				 */
4869 				tupregs[ttop].dttk_size =
4870 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
4871 				    regs[r2] ? regs[r2] :
4872 				    dtrace_strsize_default) + 1;
4873 			} else {
4874 				tupregs[ttop].dttk_size = regs[r2];
4875 			}
4876 
4877 			tupregs[ttop++].dttk_value = regs[rd];
4878 			break;
4879 
4880 		case DIF_OP_PUSHTV:
4881 			if (ttop == DIF_DTR_NREGS) {
4882 				*flags |= CPU_DTRACE_TUPOFLOW;
4883 				break;
4884 			}
4885 
4886 			tupregs[ttop].dttk_value = regs[rd];
4887 			tupregs[ttop++].dttk_size = 0;
4888 			break;
4889 
4890 		case DIF_OP_POPTS:
4891 			if (ttop != 0)
4892 				ttop--;
4893 			break;
4894 
4895 		case DIF_OP_FLUSHTS:
4896 			ttop = 0;
4897 			break;
4898 
4899 		case DIF_OP_LDGAA:
4900 		case DIF_OP_LDTAA: {
4901 			dtrace_dynvar_t *dvar;
4902 			dtrace_key_t *key = tupregs;
4903 			uint_t nkeys = ttop;
4904 
4905 			id = DIF_INSTR_VAR(instr);
4906 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4907 			id -= DIF_VAR_OTHER_UBASE;
4908 
4909 			key[nkeys].dttk_value = (uint64_t)id;
4910 			key[nkeys++].dttk_size = 0;
4911 
4912 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
4913 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4914 				key[nkeys++].dttk_size = 0;
4915 				v = &vstate->dtvs_tlocals[id];
4916 			} else {
4917 				v = &vstate->dtvs_globals[id]->dtsv_var;
4918 			}
4919 
4920 			dvar = dtrace_dynvar(dstate, nkeys, key,
4921 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4922 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4923 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
4924 
4925 			if (dvar == NULL) {
4926 				regs[rd] = 0;
4927 				break;
4928 			}
4929 
4930 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4931 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
4932 			} else {
4933 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
4934 			}
4935 
4936 			break;
4937 		}
4938 
4939 		case DIF_OP_STGAA:
4940 		case DIF_OP_STTAA: {
4941 			dtrace_dynvar_t *dvar;
4942 			dtrace_key_t *key = tupregs;
4943 			uint_t nkeys = ttop;
4944 
4945 			id = DIF_INSTR_VAR(instr);
4946 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
4947 			id -= DIF_VAR_OTHER_UBASE;
4948 
4949 			key[nkeys].dttk_value = (uint64_t)id;
4950 			key[nkeys++].dttk_size = 0;
4951 
4952 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
4953 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
4954 				key[nkeys++].dttk_size = 0;
4955 				v = &vstate->dtvs_tlocals[id];
4956 			} else {
4957 				v = &vstate->dtvs_globals[id]->dtsv_var;
4958 			}
4959 
4960 			dvar = dtrace_dynvar(dstate, nkeys, key,
4961 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
4962 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
4963 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
4964 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
4965 
4966 			if (dvar == NULL)
4967 				break;
4968 
4969 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
4970 				if (!dtrace_vcanload(
4971 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
4972 				    mstate, vstate))
4973 					break;
4974 
4975 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
4976 				    dvar->dtdv_data, &v->dtdv_type);
4977 			} else {
4978 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
4979 			}
4980 
4981 			break;
4982 		}
4983 
4984 		case DIF_OP_ALLOCS: {
4985 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4986 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
4987 
4988 			/*
4989 			 * Rounding up the user allocation size could have
4990 			 * overflowed large, bogus allocations (like -1ULL) to
4991 			 * 0.
4992 			 */
4993 			if (size < regs[r1] ||
4994 			    !DTRACE_INSCRATCH(mstate, size)) {
4995 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4996 				regs[rd] = NULL;
4997 				break;
4998 			}
4999 
5000 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
5001 			mstate->dtms_scratch_ptr += size;
5002 			regs[rd] = ptr;
5003 			break;
5004 		}
5005 
5006 		case DIF_OP_COPYS:
5007 			if (!dtrace_canstore(regs[rd], regs[r2],
5008 			    mstate, vstate)) {
5009 				*flags |= CPU_DTRACE_BADADDR;
5010 				*illval = regs[rd];
5011 				break;
5012 			}
5013 
5014 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
5015 				break;
5016 
5017 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
5018 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
5019 			break;
5020 
5021 		case DIF_OP_STB:
5022 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
5023 				*flags |= CPU_DTRACE_BADADDR;
5024 				*illval = regs[rd];
5025 				break;
5026 			}
5027 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
5028 			break;
5029 
5030 		case DIF_OP_STH:
5031 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
5032 				*flags |= CPU_DTRACE_BADADDR;
5033 				*illval = regs[rd];
5034 				break;
5035 			}
5036 			if (regs[rd] & 1) {
5037 				*flags |= CPU_DTRACE_BADALIGN;
5038 				*illval = regs[rd];
5039 				break;
5040 			}
5041 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
5042 			break;
5043 
5044 		case DIF_OP_STW:
5045 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
5046 				*flags |= CPU_DTRACE_BADADDR;
5047 				*illval = regs[rd];
5048 				break;
5049 			}
5050 			if (regs[rd] & 3) {
5051 				*flags |= CPU_DTRACE_BADALIGN;
5052 				*illval = regs[rd];
5053 				break;
5054 			}
5055 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
5056 			break;
5057 
5058 		case DIF_OP_STX:
5059 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
5060 				*flags |= CPU_DTRACE_BADADDR;
5061 				*illval = regs[rd];
5062 				break;
5063 			}
5064 			if (regs[rd] & 7) {
5065 				*flags |= CPU_DTRACE_BADALIGN;
5066 				*illval = regs[rd];
5067 				break;
5068 			}
5069 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
5070 			break;
5071 		}
5072 	}
5073 
5074 	if (!(*flags & CPU_DTRACE_FAULT))
5075 		return (rval);
5076 
5077 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
5078 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
5079 
5080 	return (0);
5081 }
5082 
5083 static void
5084 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
5085 {
5086 	dtrace_probe_t *probe = ecb->dte_probe;
5087 	dtrace_provider_t *prov = probe->dtpr_provider;
5088 	char c[DTRACE_FULLNAMELEN + 80], *str;
5089 	char *msg = "dtrace: breakpoint action at probe ";
5090 	char *ecbmsg = " (ecb ";
5091 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
5092 	uintptr_t val = (uintptr_t)ecb;
5093 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
5094 
5095 	if (dtrace_destructive_disallow)
5096 		return;
5097 
5098 	/*
5099 	 * It's impossible to be taking action on the NULL probe.
5100 	 */
5101 	ASSERT(probe != NULL);
5102 
5103 	/*
5104 	 * This is a poor man's (destitute man's?) sprintf():  we want to
5105 	 * print the provider name, module name, function name and name of
5106 	 * the probe, along with the hex address of the ECB with the breakpoint
5107 	 * action -- all of which we must place in the character buffer by
5108 	 * hand.
5109 	 */
5110 	while (*msg != '\0')
5111 		c[i++] = *msg++;
5112 
5113 	for (str = prov->dtpv_name; *str != '\0'; str++)
5114 		c[i++] = *str;
5115 	c[i++] = ':';
5116 
5117 	for (str = probe->dtpr_mod; *str != '\0'; str++)
5118 		c[i++] = *str;
5119 	c[i++] = ':';
5120 
5121 	for (str = probe->dtpr_func; *str != '\0'; str++)
5122 		c[i++] = *str;
5123 	c[i++] = ':';
5124 
5125 	for (str = probe->dtpr_name; *str != '\0'; str++)
5126 		c[i++] = *str;
5127 
5128 	while (*ecbmsg != '\0')
5129 		c[i++] = *ecbmsg++;
5130 
5131 	while (shift >= 0) {
5132 		mask = (uintptr_t)0xf << shift;
5133 
5134 		if (val >= ((uintptr_t)1 << shift))
5135 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
5136 		shift -= 4;
5137 	}
5138 
5139 	c[i++] = ')';
5140 	c[i] = '\0';
5141 
5142 	debug_enter(c);
5143 }
5144 
5145 static void
5146 dtrace_action_panic(dtrace_ecb_t *ecb)
5147 {
5148 	dtrace_probe_t *probe = ecb->dte_probe;
5149 
5150 	/*
5151 	 * It's impossible to be taking action on the NULL probe.
5152 	 */
5153 	ASSERT(probe != NULL);
5154 
5155 	if (dtrace_destructive_disallow)
5156 		return;
5157 
5158 	if (dtrace_panicked != NULL)
5159 		return;
5160 
5161 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
5162 		return;
5163 
5164 	/*
5165 	 * We won the right to panic.  (We want to be sure that only one
5166 	 * thread calls panic() from dtrace_probe(), and that panic() is
5167 	 * called exactly once.)
5168 	 */
5169 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
5170 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
5171 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
5172 }
5173 
5174 static void
5175 dtrace_action_raise(uint64_t sig)
5176 {
5177 	if (dtrace_destructive_disallow)
5178 		return;
5179 
5180 	if (sig >= NSIG) {
5181 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5182 		return;
5183 	}
5184 
5185 	/*
5186 	 * raise() has a queue depth of 1 -- we ignore all subsequent
5187 	 * invocations of the raise() action.
5188 	 */
5189 	if (curthread->t_dtrace_sig == 0)
5190 		curthread->t_dtrace_sig = (uint8_t)sig;
5191 
5192 	curthread->t_sig_check = 1;
5193 	aston(curthread);
5194 }
5195 
5196 static void
5197 dtrace_action_stop(void)
5198 {
5199 	if (dtrace_destructive_disallow)
5200 		return;
5201 
5202 	if (!curthread->t_dtrace_stop) {
5203 		curthread->t_dtrace_stop = 1;
5204 		curthread->t_sig_check = 1;
5205 		aston(curthread);
5206 	}
5207 }
5208 
5209 static void
5210 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
5211 {
5212 	hrtime_t now;
5213 	volatile uint16_t *flags;
5214 	cpu_t *cpu = CPU;
5215 
5216 	if (dtrace_destructive_disallow)
5217 		return;
5218 
5219 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
5220 
5221 	now = dtrace_gethrtime();
5222 
5223 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
5224 		/*
5225 		 * We need to advance the mark to the current time.
5226 		 */
5227 		cpu->cpu_dtrace_chillmark = now;
5228 		cpu->cpu_dtrace_chilled = 0;
5229 	}
5230 
5231 	/*
5232 	 * Now check to see if the requested chill time would take us over
5233 	 * the maximum amount of time allowed in the chill interval.  (Or
5234 	 * worse, if the calculation itself induces overflow.)
5235 	 */
5236 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
5237 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
5238 		*flags |= CPU_DTRACE_ILLOP;
5239 		return;
5240 	}
5241 
5242 	while (dtrace_gethrtime() - now < val)
5243 		continue;
5244 
5245 	/*
5246 	 * Normally, we assure that the value of the variable "timestamp" does
5247 	 * not change within an ECB.  The presence of chill() represents an
5248 	 * exception to this rule, however.
5249 	 */
5250 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
5251 	cpu->cpu_dtrace_chilled += val;
5252 }
5253 
5254 static void
5255 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
5256     uint64_t *buf, uint64_t arg)
5257 {
5258 	int nframes = DTRACE_USTACK_NFRAMES(arg);
5259 	int strsize = DTRACE_USTACK_STRSIZE(arg);
5260 	uint64_t *pcs = &buf[1], *fps;
5261 	char *str = (char *)&pcs[nframes];
5262 	int size, offs = 0, i, j;
5263 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
5264 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5265 	char *sym;
5266 
5267 	/*
5268 	 * Should be taking a faster path if string space has not been
5269 	 * allocated.
5270 	 */
5271 	ASSERT(strsize != 0);
5272 
5273 	/*
5274 	 * We will first allocate some temporary space for the frame pointers.
5275 	 */
5276 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
5277 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
5278 	    (nframes * sizeof (uint64_t));
5279 
5280 	if (!DTRACE_INSCRATCH(mstate, size)) {
5281 		/*
5282 		 * Not enough room for our frame pointers -- need to indicate
5283 		 * that we ran out of scratch space.
5284 		 */
5285 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5286 		return;
5287 	}
5288 
5289 	mstate->dtms_scratch_ptr += size;
5290 	saved = mstate->dtms_scratch_ptr;
5291 
5292 	/*
5293 	 * Now get a stack with both program counters and frame pointers.
5294 	 */
5295 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5296 	dtrace_getufpstack(buf, fps, nframes + 1);
5297 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5298 
5299 	/*
5300 	 * If that faulted, we're cooked.
5301 	 */
5302 	if (*flags & CPU_DTRACE_FAULT)
5303 		goto out;
5304 
5305 	/*
5306 	 * Now we want to walk up the stack, calling the USTACK helper.  For
5307 	 * each iteration, we restore the scratch pointer.
5308 	 */
5309 	for (i = 0; i < nframes; i++) {
5310 		mstate->dtms_scratch_ptr = saved;
5311 
5312 		if (offs >= strsize)
5313 			break;
5314 
5315 		sym = (char *)(uintptr_t)dtrace_helper(
5316 		    DTRACE_HELPER_ACTION_USTACK,
5317 		    mstate, state, pcs[i], fps[i]);
5318 
5319 		/*
5320 		 * If we faulted while running the helper, we're going to
5321 		 * clear the fault and null out the corresponding string.
5322 		 */
5323 		if (*flags & CPU_DTRACE_FAULT) {
5324 			*flags &= ~CPU_DTRACE_FAULT;
5325 			str[offs++] = '\0';
5326 			continue;
5327 		}
5328 
5329 		if (sym == NULL) {
5330 			str[offs++] = '\0';
5331 			continue;
5332 		}
5333 
5334 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5335 
5336 		/*
5337 		 * Now copy in the string that the helper returned to us.
5338 		 */
5339 		for (j = 0; offs + j < strsize; j++) {
5340 			if ((str[offs + j] = sym[j]) == '\0')
5341 				break;
5342 		}
5343 
5344 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5345 
5346 		offs += j + 1;
5347 	}
5348 
5349 	if (offs >= strsize) {
5350 		/*
5351 		 * If we didn't have room for all of the strings, we don't
5352 		 * abort processing -- this needn't be a fatal error -- but we
5353 		 * still want to increment a counter (dts_stkstroverflows) to
5354 		 * allow this condition to be warned about.  (If this is from
5355 		 * a jstack() action, it is easily tuned via jstackstrsize.)
5356 		 */
5357 		dtrace_error(&state->dts_stkstroverflows);
5358 	}
5359 
5360 	while (offs < strsize)
5361 		str[offs++] = '\0';
5362 
5363 out:
5364 	mstate->dtms_scratch_ptr = old;
5365 }
5366 
5367 /*
5368  * If you're looking for the epicenter of DTrace, you just found it.  This
5369  * is the function called by the provider to fire a probe -- from which all
5370  * subsequent probe-context DTrace activity emanates.
5371  */
5372 void
5373 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
5374     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
5375 {
5376 	processorid_t cpuid;
5377 	dtrace_icookie_t cookie;
5378 	dtrace_probe_t *probe;
5379 	dtrace_mstate_t mstate;
5380 	dtrace_ecb_t *ecb;
5381 	dtrace_action_t *act;
5382 	intptr_t offs;
5383 	size_t size;
5384 	int vtime, onintr;
5385 	volatile uint16_t *flags;
5386 	hrtime_t now;
5387 
5388 	/*
5389 	 * Kick out immediately if this CPU is still being born (in which case
5390 	 * curthread will be set to -1) or the current thread can't allow
5391 	 * probes in its current context.
5392 	 */
5393 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
5394 		return;
5395 
5396 	cookie = dtrace_interrupt_disable();
5397 	probe = dtrace_probes[id - 1];
5398 	cpuid = CPU->cpu_id;
5399 	onintr = CPU_ON_INTR(CPU);
5400 
5401 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
5402 	    probe->dtpr_predcache == curthread->t_predcache) {
5403 		/*
5404 		 * We have hit in the predicate cache; we know that
5405 		 * this predicate would evaluate to be false.
5406 		 */
5407 		dtrace_interrupt_enable(cookie);
5408 		return;
5409 	}
5410 
5411 	if (panic_quiesce) {
5412 		/*
5413 		 * We don't trace anything if we're panicking.
5414 		 */
5415 		dtrace_interrupt_enable(cookie);
5416 		return;
5417 	}
5418 
5419 	now = dtrace_gethrtime();
5420 	vtime = dtrace_vtime_references != 0;
5421 
5422 	if (vtime && curthread->t_dtrace_start)
5423 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
5424 
5425 	mstate.dtms_difo = NULL;
5426 	mstate.dtms_probe = probe;
5427 	mstate.dtms_strtok = NULL;
5428 	mstate.dtms_arg[0] = arg0;
5429 	mstate.dtms_arg[1] = arg1;
5430 	mstate.dtms_arg[2] = arg2;
5431 	mstate.dtms_arg[3] = arg3;
5432 	mstate.dtms_arg[4] = arg4;
5433 
5434 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
5435 
5436 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
5437 		dtrace_predicate_t *pred = ecb->dte_predicate;
5438 		dtrace_state_t *state = ecb->dte_state;
5439 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
5440 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
5441 		dtrace_vstate_t *vstate = &state->dts_vstate;
5442 		dtrace_provider_t *prov = probe->dtpr_provider;
5443 		int committed = 0;
5444 		caddr_t tomax;
5445 
5446 		/*
5447 		 * A little subtlety with the following (seemingly innocuous)
5448 		 * declaration of the automatic 'val':  by looking at the
5449 		 * code, you might think that it could be declared in the
5450 		 * action processing loop, below.  (That is, it's only used in
5451 		 * the action processing loop.)  However, it must be declared
5452 		 * out of that scope because in the case of DIF expression
5453 		 * arguments to aggregating actions, one iteration of the
5454 		 * action loop will use the last iteration's value.
5455 		 */
5456 #ifdef lint
5457 		uint64_t val = 0;
5458 #else
5459 		uint64_t val;
5460 #endif
5461 
5462 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
5463 		*flags &= ~CPU_DTRACE_ERROR;
5464 
5465 		if (prov == dtrace_provider) {
5466 			/*
5467 			 * If dtrace itself is the provider of this probe,
5468 			 * we're only going to continue processing the ECB if
5469 			 * arg0 (the dtrace_state_t) is equal to the ECB's
5470 			 * creating state.  (This prevents disjoint consumers
5471 			 * from seeing one another's metaprobes.)
5472 			 */
5473 			if (arg0 != (uint64_t)(uintptr_t)state)
5474 				continue;
5475 		}
5476 
5477 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
5478 			/*
5479 			 * We're not currently active.  If our provider isn't
5480 			 * the dtrace pseudo provider, we're not interested.
5481 			 */
5482 			if (prov != dtrace_provider)
5483 				continue;
5484 
5485 			/*
5486 			 * Now we must further check if we are in the BEGIN
5487 			 * probe.  If we are, we will only continue processing
5488 			 * if we're still in WARMUP -- if one BEGIN enabling
5489 			 * has invoked the exit() action, we don't want to
5490 			 * evaluate subsequent BEGIN enablings.
5491 			 */
5492 			if (probe->dtpr_id == dtrace_probeid_begin &&
5493 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
5494 				ASSERT(state->dts_activity ==
5495 				    DTRACE_ACTIVITY_DRAINING);
5496 				continue;
5497 			}
5498 		}
5499 
5500 		if (ecb->dte_cond) {
5501 			/*
5502 			 * If the dte_cond bits indicate that this
5503 			 * consumer is only allowed to see user-mode firings
5504 			 * of this probe, call the provider's dtps_usermode()
5505 			 * entry point to check that the probe was fired
5506 			 * while in a user context. Skip this ECB if that's
5507 			 * not the case.
5508 			 */
5509 			if ((ecb->dte_cond & DTRACE_COND_USERMODE) &&
5510 			    prov->dtpv_pops.dtps_usermode(prov->dtpv_arg,
5511 			    probe->dtpr_id, probe->dtpr_arg) == 0)
5512 				continue;
5513 
5514 			/*
5515 			 * This is more subtle than it looks. We have to be
5516 			 * absolutely certain that CRED() isn't going to
5517 			 * change out from under us so it's only legit to
5518 			 * examine that structure if we're in constrained
5519 			 * situations. Currently, the only times we'll this
5520 			 * check is if a non-super-user has enabled the
5521 			 * profile or syscall providers -- providers that
5522 			 * allow visibility of all processes. For the
5523 			 * profile case, the check above will ensure that
5524 			 * we're examining a user context.
5525 			 */
5526 			if (ecb->dte_cond & DTRACE_COND_OWNER) {
5527 				cred_t *cr;
5528 				cred_t *s_cr =
5529 				    ecb->dte_state->dts_cred.dcr_cred;
5530 				proc_t *proc;
5531 
5532 				ASSERT(s_cr != NULL);
5533 
5534 				if ((cr = CRED()) == NULL ||
5535 				    s_cr->cr_uid != cr->cr_uid ||
5536 				    s_cr->cr_uid != cr->cr_ruid ||
5537 				    s_cr->cr_uid != cr->cr_suid ||
5538 				    s_cr->cr_gid != cr->cr_gid ||
5539 				    s_cr->cr_gid != cr->cr_rgid ||
5540 				    s_cr->cr_gid != cr->cr_sgid ||
5541 				    (proc = ttoproc(curthread)) == NULL ||
5542 				    (proc->p_flag & SNOCD))
5543 					continue;
5544 			}
5545 
5546 			if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
5547 				cred_t *cr;
5548 				cred_t *s_cr =
5549 				    ecb->dte_state->dts_cred.dcr_cred;
5550 
5551 				ASSERT(s_cr != NULL);
5552 
5553 				if ((cr = CRED()) == NULL ||
5554 				    s_cr->cr_zone->zone_id !=
5555 				    cr->cr_zone->zone_id)
5556 					continue;
5557 			}
5558 		}
5559 
5560 		if (now - state->dts_alive > dtrace_deadman_timeout) {
5561 			/*
5562 			 * We seem to be dead.  Unless we (a) have kernel
5563 			 * destructive permissions (b) have expicitly enabled
5564 			 * destructive actions and (c) destructive actions have
5565 			 * not been disabled, we're going to transition into
5566 			 * the KILLED state, from which no further processing
5567 			 * on this state will be performed.
5568 			 */
5569 			if (!dtrace_priv_kernel_destructive(state) ||
5570 			    !state->dts_cred.dcr_destructive ||
5571 			    dtrace_destructive_disallow) {
5572 				void *activity = &state->dts_activity;
5573 				dtrace_activity_t current;
5574 
5575 				do {
5576 					current = state->dts_activity;
5577 				} while (dtrace_cas32(activity, current,
5578 				    DTRACE_ACTIVITY_KILLED) != current);
5579 
5580 				continue;
5581 			}
5582 		}
5583 
5584 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
5585 		    ecb->dte_alignment, state, &mstate)) < 0)
5586 			continue;
5587 
5588 		tomax = buf->dtb_tomax;
5589 		ASSERT(tomax != NULL);
5590 
5591 		if (ecb->dte_size != 0)
5592 			DTRACE_STORE(uint32_t, tomax, offs, ecb->dte_epid);
5593 
5594 		mstate.dtms_epid = ecb->dte_epid;
5595 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
5596 
5597 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
5598 			mstate.dtms_access = DTRACE_ACCESS_KERNEL;
5599 		else
5600 			mstate.dtms_access = 0;
5601 
5602 		if (pred != NULL) {
5603 			dtrace_difo_t *dp = pred->dtp_difo;
5604 			int rval;
5605 
5606 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
5607 
5608 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
5609 				dtrace_cacheid_t cid = probe->dtpr_predcache;
5610 
5611 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
5612 					/*
5613 					 * Update the predicate cache...
5614 					 */
5615 					ASSERT(cid == pred->dtp_cacheid);
5616 					curthread->t_predcache = cid;
5617 				}
5618 
5619 				continue;
5620 			}
5621 		}
5622 
5623 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
5624 		    act != NULL; act = act->dta_next) {
5625 			size_t valoffs;
5626 			dtrace_difo_t *dp;
5627 			dtrace_recdesc_t *rec = &act->dta_rec;
5628 
5629 			size = rec->dtrd_size;
5630 			valoffs = offs + rec->dtrd_offset;
5631 
5632 			if (DTRACEACT_ISAGG(act->dta_kind)) {
5633 				uint64_t v = 0xbad;
5634 				dtrace_aggregation_t *agg;
5635 
5636 				agg = (dtrace_aggregation_t *)act;
5637 
5638 				if ((dp = act->dta_difo) != NULL)
5639 					v = dtrace_dif_emulate(dp,
5640 					    &mstate, vstate, state);
5641 
5642 				if (*flags & CPU_DTRACE_ERROR)
5643 					continue;
5644 
5645 				/*
5646 				 * Note that we always pass the expression
5647 				 * value from the previous iteration of the
5648 				 * action loop.  This value will only be used
5649 				 * if there is an expression argument to the
5650 				 * aggregating action, denoted by the
5651 				 * dtag_hasarg field.
5652 				 */
5653 				dtrace_aggregate(agg, buf,
5654 				    offs, aggbuf, v, val);
5655 				continue;
5656 			}
5657 
5658 			switch (act->dta_kind) {
5659 			case DTRACEACT_STOP:
5660 				if (dtrace_priv_proc_destructive(state))
5661 					dtrace_action_stop();
5662 				continue;
5663 
5664 			case DTRACEACT_BREAKPOINT:
5665 				if (dtrace_priv_kernel_destructive(state))
5666 					dtrace_action_breakpoint(ecb);
5667 				continue;
5668 
5669 			case DTRACEACT_PANIC:
5670 				if (dtrace_priv_kernel_destructive(state))
5671 					dtrace_action_panic(ecb);
5672 				continue;
5673 
5674 			case DTRACEACT_STACK:
5675 				if (!dtrace_priv_kernel(state))
5676 					continue;
5677 
5678 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
5679 				    size / sizeof (pc_t), probe->dtpr_aframes,
5680 				    DTRACE_ANCHORED(probe) ? NULL :
5681 				    (uint32_t *)arg0);
5682 
5683 				continue;
5684 
5685 			case DTRACEACT_JSTACK:
5686 			case DTRACEACT_USTACK:
5687 				if (!dtrace_priv_proc(state))
5688 					continue;
5689 
5690 				/*
5691 				 * See comment in DIF_VAR_PID.
5692 				 */
5693 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
5694 				    CPU_ON_INTR(CPU)) {
5695 					int depth = DTRACE_USTACK_NFRAMES(
5696 					    rec->dtrd_arg) + 1;
5697 
5698 					dtrace_bzero((void *)(tomax + valoffs),
5699 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
5700 					    + depth * sizeof (uint64_t));
5701 
5702 					continue;
5703 				}
5704 
5705 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
5706 				    curproc->p_dtrace_helpers != NULL) {
5707 					/*
5708 					 * This is the slow path -- we have
5709 					 * allocated string space, and we're
5710 					 * getting the stack of a process that
5711 					 * has helpers.  Call into a separate
5712 					 * routine to perform this processing.
5713 					 */
5714 					dtrace_action_ustack(&mstate, state,
5715 					    (uint64_t *)(tomax + valoffs),
5716 					    rec->dtrd_arg);
5717 					continue;
5718 				}
5719 
5720 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5721 				dtrace_getupcstack((uint64_t *)
5722 				    (tomax + valoffs),
5723 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
5724 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5725 				continue;
5726 
5727 			default:
5728 				break;
5729 			}
5730 
5731 			dp = act->dta_difo;
5732 			ASSERT(dp != NULL);
5733 
5734 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
5735 
5736 			if (*flags & CPU_DTRACE_ERROR)
5737 				continue;
5738 
5739 			switch (act->dta_kind) {
5740 			case DTRACEACT_SPECULATE:
5741 				ASSERT(buf == &state->dts_buffer[cpuid]);
5742 				buf = dtrace_speculation_buffer(state,
5743 				    cpuid, val);
5744 
5745 				if (buf == NULL) {
5746 					*flags |= CPU_DTRACE_DROP;
5747 					continue;
5748 				}
5749 
5750 				offs = dtrace_buffer_reserve(buf,
5751 				    ecb->dte_needed, ecb->dte_alignment,
5752 				    state, NULL);
5753 
5754 				if (offs < 0) {
5755 					*flags |= CPU_DTRACE_DROP;
5756 					continue;
5757 				}
5758 
5759 				tomax = buf->dtb_tomax;
5760 				ASSERT(tomax != NULL);
5761 
5762 				if (ecb->dte_size != 0)
5763 					DTRACE_STORE(uint32_t, tomax, offs,
5764 					    ecb->dte_epid);
5765 				continue;
5766 
5767 			case DTRACEACT_CHILL:
5768 				if (dtrace_priv_kernel_destructive(state))
5769 					dtrace_action_chill(&mstate, val);
5770 				continue;
5771 
5772 			case DTRACEACT_RAISE:
5773 				if (dtrace_priv_proc_destructive(state))
5774 					dtrace_action_raise(val);
5775 				continue;
5776 
5777 			case DTRACEACT_COMMIT:
5778 				ASSERT(!committed);
5779 
5780 				/*
5781 				 * We need to commit our buffer state.
5782 				 */
5783 				if (ecb->dte_size)
5784 					buf->dtb_offset = offs + ecb->dte_size;
5785 				buf = &state->dts_buffer[cpuid];
5786 				dtrace_speculation_commit(state, cpuid, val);
5787 				committed = 1;
5788 				continue;
5789 
5790 			case DTRACEACT_DISCARD:
5791 				dtrace_speculation_discard(state, cpuid, val);
5792 				continue;
5793 
5794 			case DTRACEACT_DIFEXPR:
5795 			case DTRACEACT_LIBACT:
5796 			case DTRACEACT_PRINTF:
5797 			case DTRACEACT_PRINTA:
5798 			case DTRACEACT_SYSTEM:
5799 			case DTRACEACT_FREOPEN:
5800 				break;
5801 
5802 			case DTRACEACT_SYM:
5803 			case DTRACEACT_MOD:
5804 				if (!dtrace_priv_kernel(state))
5805 					continue;
5806 				break;
5807 
5808 			case DTRACEACT_USYM:
5809 			case DTRACEACT_UMOD:
5810 			case DTRACEACT_UADDR: {
5811 				struct pid *pid = curthread->t_procp->p_pidp;
5812 
5813 				if (!dtrace_priv_proc(state))
5814 					continue;
5815 
5816 				DTRACE_STORE(uint64_t, tomax,
5817 				    valoffs, (uint64_t)pid->pid_id);
5818 				DTRACE_STORE(uint64_t, tomax,
5819 				    valoffs + sizeof (uint64_t), val);
5820 
5821 				continue;
5822 			}
5823 
5824 			case DTRACEACT_EXIT: {
5825 				/*
5826 				 * For the exit action, we are going to attempt
5827 				 * to atomically set our activity to be
5828 				 * draining.  If this fails (either because
5829 				 * another CPU has beat us to the exit action,
5830 				 * or because our current activity is something
5831 				 * other than ACTIVE or WARMUP), we will
5832 				 * continue.  This assures that the exit action
5833 				 * can be successfully recorded at most once
5834 				 * when we're in the ACTIVE state.  If we're
5835 				 * encountering the exit() action while in
5836 				 * COOLDOWN, however, we want to honor the new
5837 				 * status code.  (We know that we're the only
5838 				 * thread in COOLDOWN, so there is no race.)
5839 				 */
5840 				void *activity = &state->dts_activity;
5841 				dtrace_activity_t current = state->dts_activity;
5842 
5843 				if (current == DTRACE_ACTIVITY_COOLDOWN)
5844 					break;
5845 
5846 				if (current != DTRACE_ACTIVITY_WARMUP)
5847 					current = DTRACE_ACTIVITY_ACTIVE;
5848 
5849 				if (dtrace_cas32(activity, current,
5850 				    DTRACE_ACTIVITY_DRAINING) != current) {
5851 					*flags |= CPU_DTRACE_DROP;
5852 					continue;
5853 				}
5854 
5855 				break;
5856 			}
5857 
5858 			default:
5859 				ASSERT(0);
5860 			}
5861 
5862 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF) {
5863 				uintptr_t end = valoffs + size;
5864 
5865 				if (!dtrace_vcanload((void *)(uintptr_t)val,
5866 				    &dp->dtdo_rtype, &mstate, vstate))
5867 					continue;
5868 
5869 				/*
5870 				 * If this is a string, we're going to only
5871 				 * load until we find the zero byte -- after
5872 				 * which we'll store zero bytes.
5873 				 */
5874 				if (dp->dtdo_rtype.dtdt_kind ==
5875 				    DIF_TYPE_STRING) {
5876 					char c = '\0' + 1;
5877 					int intuple = act->dta_intuple;
5878 					size_t s;
5879 
5880 					for (s = 0; s < size; s++) {
5881 						if (c != '\0')
5882 							c = dtrace_load8(val++);
5883 
5884 						DTRACE_STORE(uint8_t, tomax,
5885 						    valoffs++, c);
5886 
5887 						if (c == '\0' && intuple)
5888 							break;
5889 					}
5890 
5891 					continue;
5892 				}
5893 
5894 				while (valoffs < end) {
5895 					DTRACE_STORE(uint8_t, tomax, valoffs++,
5896 					    dtrace_load8(val++));
5897 				}
5898 
5899 				continue;
5900 			}
5901 
5902 			switch (size) {
5903 			case 0:
5904 				break;
5905 
5906 			case sizeof (uint8_t):
5907 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
5908 				break;
5909 			case sizeof (uint16_t):
5910 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
5911 				break;
5912 			case sizeof (uint32_t):
5913 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
5914 				break;
5915 			case sizeof (uint64_t):
5916 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
5917 				break;
5918 			default:
5919 				/*
5920 				 * Any other size should have been returned by
5921 				 * reference, not by value.
5922 				 */
5923 				ASSERT(0);
5924 				break;
5925 			}
5926 		}
5927 
5928 		if (*flags & CPU_DTRACE_DROP)
5929 			continue;
5930 
5931 		if (*flags & CPU_DTRACE_FAULT) {
5932 			int ndx;
5933 			dtrace_action_t *err;
5934 
5935 			buf->dtb_errors++;
5936 
5937 			if (probe->dtpr_id == dtrace_probeid_error) {
5938 				/*
5939 				 * There's nothing we can do -- we had an
5940 				 * error on the error probe.  We bump an
5941 				 * error counter to at least indicate that
5942 				 * this condition happened.
5943 				 */
5944 				dtrace_error(&state->dts_dblerrors);
5945 				continue;
5946 			}
5947 
5948 			if (vtime) {
5949 				/*
5950 				 * Before recursing on dtrace_probe(), we
5951 				 * need to explicitly clear out our start
5952 				 * time to prevent it from being accumulated
5953 				 * into t_dtrace_vtime.
5954 				 */
5955 				curthread->t_dtrace_start = 0;
5956 			}
5957 
5958 			/*
5959 			 * Iterate over the actions to figure out which action
5960 			 * we were processing when we experienced the error.
5961 			 * Note that act points _past_ the faulting action; if
5962 			 * act is ecb->dte_action, the fault was in the
5963 			 * predicate, if it's ecb->dte_action->dta_next it's
5964 			 * in action #1, and so on.
5965 			 */
5966 			for (err = ecb->dte_action, ndx = 0;
5967 			    err != act; err = err->dta_next, ndx++)
5968 				continue;
5969 
5970 			dtrace_probe_error(state, ecb->dte_epid, ndx,
5971 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
5972 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
5973 			    cpu_core[cpuid].cpuc_dtrace_illval);
5974 
5975 			continue;
5976 		}
5977 
5978 		if (!committed)
5979 			buf->dtb_offset = offs + ecb->dte_size;
5980 	}
5981 
5982 	if (vtime)
5983 		curthread->t_dtrace_start = dtrace_gethrtime();
5984 
5985 	dtrace_interrupt_enable(cookie);
5986 }
5987 
5988 /*
5989  * DTrace Probe Hashing Functions
5990  *
5991  * The functions in this section (and indeed, the functions in remaining
5992  * sections) are not _called_ from probe context.  (Any exceptions to this are
5993  * marked with a "Note:".)  Rather, they are called from elsewhere in the
5994  * DTrace framework to look-up probes in, add probes to and remove probes from
5995  * the DTrace probe hashes.  (Each probe is hashed by each element of the
5996  * probe tuple -- allowing for fast lookups, regardless of what was
5997  * specified.)
5998  */
5999 static uint_t
6000 dtrace_hash_str(char *p)
6001 {
6002 	unsigned int g;
6003 	uint_t hval = 0;
6004 
6005 	while (*p) {
6006 		hval = (hval << 4) + *p++;
6007 		if ((g = (hval & 0xf0000000)) != 0)
6008 			hval ^= g >> 24;
6009 		hval &= ~g;
6010 	}
6011 	return (hval);
6012 }
6013 
6014 static dtrace_hash_t *
6015 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
6016 {
6017 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
6018 
6019 	hash->dth_stroffs = stroffs;
6020 	hash->dth_nextoffs = nextoffs;
6021 	hash->dth_prevoffs = prevoffs;
6022 
6023 	hash->dth_size = 1;
6024 	hash->dth_mask = hash->dth_size - 1;
6025 
6026 	hash->dth_tab = kmem_zalloc(hash->dth_size *
6027 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
6028 
6029 	return (hash);
6030 }
6031 
6032 static void
6033 dtrace_hash_destroy(dtrace_hash_t *hash)
6034 {
6035 #ifdef DEBUG
6036 	int i;
6037 
6038 	for (i = 0; i < hash->dth_size; i++)
6039 		ASSERT(hash->dth_tab[i] == NULL);
6040 #endif
6041 
6042 	kmem_free(hash->dth_tab,
6043 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
6044 	kmem_free(hash, sizeof (dtrace_hash_t));
6045 }
6046 
6047 static void
6048 dtrace_hash_resize(dtrace_hash_t *hash)
6049 {
6050 	int size = hash->dth_size, i, ndx;
6051 	int new_size = hash->dth_size << 1;
6052 	int new_mask = new_size - 1;
6053 	dtrace_hashbucket_t **new_tab, *bucket, *next;
6054 
6055 	ASSERT((new_size & new_mask) == 0);
6056 
6057 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
6058 
6059 	for (i = 0; i < size; i++) {
6060 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
6061 			dtrace_probe_t *probe = bucket->dthb_chain;
6062 
6063 			ASSERT(probe != NULL);
6064 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
6065 
6066 			next = bucket->dthb_next;
6067 			bucket->dthb_next = new_tab[ndx];
6068 			new_tab[ndx] = bucket;
6069 		}
6070 	}
6071 
6072 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
6073 	hash->dth_tab = new_tab;
6074 	hash->dth_size = new_size;
6075 	hash->dth_mask = new_mask;
6076 }
6077 
6078 static void
6079 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
6080 {
6081 	int hashval = DTRACE_HASHSTR(hash, new);
6082 	int ndx = hashval & hash->dth_mask;
6083 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6084 	dtrace_probe_t **nextp, **prevp;
6085 
6086 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6087 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
6088 			goto add;
6089 	}
6090 
6091 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
6092 		dtrace_hash_resize(hash);
6093 		dtrace_hash_add(hash, new);
6094 		return;
6095 	}
6096 
6097 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
6098 	bucket->dthb_next = hash->dth_tab[ndx];
6099 	hash->dth_tab[ndx] = bucket;
6100 	hash->dth_nbuckets++;
6101 
6102 add:
6103 	nextp = DTRACE_HASHNEXT(hash, new);
6104 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
6105 	*nextp = bucket->dthb_chain;
6106 
6107 	if (bucket->dthb_chain != NULL) {
6108 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
6109 		ASSERT(*prevp == NULL);
6110 		*prevp = new;
6111 	}
6112 
6113 	bucket->dthb_chain = new;
6114 	bucket->dthb_len++;
6115 }
6116 
6117 static dtrace_probe_t *
6118 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
6119 {
6120 	int hashval = DTRACE_HASHSTR(hash, template);
6121 	int ndx = hashval & hash->dth_mask;
6122 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6123 
6124 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6125 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6126 			return (bucket->dthb_chain);
6127 	}
6128 
6129 	return (NULL);
6130 }
6131 
6132 static int
6133 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
6134 {
6135 	int hashval = DTRACE_HASHSTR(hash, template);
6136 	int ndx = hashval & hash->dth_mask;
6137 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6138 
6139 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6140 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
6141 			return (bucket->dthb_len);
6142 	}
6143 
6144 	return (NULL);
6145 }
6146 
6147 static void
6148 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
6149 {
6150 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
6151 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
6152 
6153 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
6154 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
6155 
6156 	/*
6157 	 * Find the bucket that we're removing this probe from.
6158 	 */
6159 	for (; bucket != NULL; bucket = bucket->dthb_next) {
6160 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
6161 			break;
6162 	}
6163 
6164 	ASSERT(bucket != NULL);
6165 
6166 	if (*prevp == NULL) {
6167 		if (*nextp == NULL) {
6168 			/*
6169 			 * The removed probe was the only probe on this
6170 			 * bucket; we need to remove the bucket.
6171 			 */
6172 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
6173 
6174 			ASSERT(bucket->dthb_chain == probe);
6175 			ASSERT(b != NULL);
6176 
6177 			if (b == bucket) {
6178 				hash->dth_tab[ndx] = bucket->dthb_next;
6179 			} else {
6180 				while (b->dthb_next != bucket)
6181 					b = b->dthb_next;
6182 				b->dthb_next = bucket->dthb_next;
6183 			}
6184 
6185 			ASSERT(hash->dth_nbuckets > 0);
6186 			hash->dth_nbuckets--;
6187 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
6188 			return;
6189 		}
6190 
6191 		bucket->dthb_chain = *nextp;
6192 	} else {
6193 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
6194 	}
6195 
6196 	if (*nextp != NULL)
6197 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
6198 }
6199 
6200 /*
6201  * DTrace Utility Functions
6202  *
6203  * These are random utility functions that are _not_ called from probe context.
6204  */
6205 static int
6206 dtrace_badattr(const dtrace_attribute_t *a)
6207 {
6208 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
6209 	    a->dtat_data > DTRACE_STABILITY_MAX ||
6210 	    a->dtat_class > DTRACE_CLASS_MAX);
6211 }
6212 
6213 /*
6214  * Return a duplicate copy of a string.  If the specified string is NULL,
6215  * this function returns a zero-length string.
6216  */
6217 static char *
6218 dtrace_strdup(const char *str)
6219 {
6220 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
6221 
6222 	if (str != NULL)
6223 		(void) strcpy(new, str);
6224 
6225 	return (new);
6226 }
6227 
6228 #define	DTRACE_ISALPHA(c)	\
6229 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
6230 
6231 static int
6232 dtrace_badname(const char *s)
6233 {
6234 	char c;
6235 
6236 	if (s == NULL || (c = *s++) == '\0')
6237 		return (0);
6238 
6239 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
6240 		return (1);
6241 
6242 	while ((c = *s++) != '\0') {
6243 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
6244 		    c != '-' && c != '_' && c != '.' && c != '`')
6245 			return (1);
6246 	}
6247 
6248 	return (0);
6249 }
6250 
6251 static void
6252 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
6253 {
6254 	uint32_t priv;
6255 
6256 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
6257 		/*
6258 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
6259 		 */
6260 		priv = DTRACE_PRIV_ALL;
6261 	} else {
6262 		*uidp = crgetuid(cr);
6263 		*zoneidp = crgetzoneid(cr);
6264 
6265 		priv = 0;
6266 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
6267 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
6268 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
6269 			priv |= DTRACE_PRIV_USER;
6270 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
6271 			priv |= DTRACE_PRIV_PROC;
6272 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
6273 			priv |= DTRACE_PRIV_OWNER;
6274 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
6275 			priv |= DTRACE_PRIV_ZONEOWNER;
6276 	}
6277 
6278 	*privp = priv;
6279 }
6280 
6281 #ifdef DTRACE_ERRDEBUG
6282 static void
6283 dtrace_errdebug(const char *str)
6284 {
6285 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
6286 	int occupied = 0;
6287 
6288 	mutex_enter(&dtrace_errlock);
6289 	dtrace_errlast = str;
6290 	dtrace_errthread = curthread;
6291 
6292 	while (occupied++ < DTRACE_ERRHASHSZ) {
6293 		if (dtrace_errhash[hval].dter_msg == str) {
6294 			dtrace_errhash[hval].dter_count++;
6295 			goto out;
6296 		}
6297 
6298 		if (dtrace_errhash[hval].dter_msg != NULL) {
6299 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
6300 			continue;
6301 		}
6302 
6303 		dtrace_errhash[hval].dter_msg = str;
6304 		dtrace_errhash[hval].dter_count = 1;
6305 		goto out;
6306 	}
6307 
6308 	panic("dtrace: undersized error hash");
6309 out:
6310 	mutex_exit(&dtrace_errlock);
6311 }
6312 #endif
6313 
6314 /*
6315  * DTrace Matching Functions
6316  *
6317  * These functions are used to match groups of probes, given some elements of
6318  * a probe tuple, or some globbed expressions for elements of a probe tuple.
6319  */
6320 static int
6321 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
6322     zoneid_t zoneid)
6323 {
6324 	if (priv != DTRACE_PRIV_ALL) {
6325 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
6326 		uint32_t match = priv & ppriv;
6327 
6328 		/*
6329 		 * No PRIV_DTRACE_* privileges...
6330 		 */
6331 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
6332 		    DTRACE_PRIV_KERNEL)) == 0)
6333 			return (0);
6334 
6335 		/*
6336 		 * No matching bits, but there were bits to match...
6337 		 */
6338 		if (match == 0 && ppriv != 0)
6339 			return (0);
6340 
6341 		/*
6342 		 * Need to have permissions to the process, but don't...
6343 		 */
6344 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
6345 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
6346 			return (0);
6347 		}
6348 
6349 		/*
6350 		 * Need to be in the same zone unless we possess the
6351 		 * privilege to examine all zones.
6352 		 */
6353 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
6354 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
6355 			return (0);
6356 		}
6357 	}
6358 
6359 	return (1);
6360 }
6361 
6362 /*
6363  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
6364  * consists of input pattern strings and an ops-vector to evaluate them.
6365  * This function returns >0 for match, 0 for no match, and <0 for error.
6366  */
6367 static int
6368 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
6369     uint32_t priv, uid_t uid, zoneid_t zoneid)
6370 {
6371 	dtrace_provider_t *pvp = prp->dtpr_provider;
6372 	int rv;
6373 
6374 	if (pvp->dtpv_defunct)
6375 		return (0);
6376 
6377 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
6378 		return (rv);
6379 
6380 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
6381 		return (rv);
6382 
6383 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
6384 		return (rv);
6385 
6386 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
6387 		return (rv);
6388 
6389 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
6390 		return (0);
6391 
6392 	return (rv);
6393 }
6394 
6395 /*
6396  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
6397  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
6398  * libc's version, the kernel version only applies to 8-bit ASCII strings.
6399  * In addition, all of the recursion cases except for '*' matching have been
6400  * unwound.  For '*', we still implement recursive evaluation, but a depth
6401  * counter is maintained and matching is aborted if we recurse too deep.
6402  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
6403  */
6404 static int
6405 dtrace_match_glob(const char *s, const char *p, int depth)
6406 {
6407 	const char *olds;
6408 	char s1, c;
6409 	int gs;
6410 
6411 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
6412 		return (-1);
6413 
6414 	if (s == NULL)
6415 		s = ""; /* treat NULL as empty string */
6416 
6417 top:
6418 	olds = s;
6419 	s1 = *s++;
6420 
6421 	if (p == NULL)
6422 		return (0);
6423 
6424 	if ((c = *p++) == '\0')
6425 		return (s1 == '\0');
6426 
6427 	switch (c) {
6428 	case '[': {
6429 		int ok = 0, notflag = 0;
6430 		char lc = '\0';
6431 
6432 		if (s1 == '\0')
6433 			return (0);
6434 
6435 		if (*p == '!') {
6436 			notflag = 1;
6437 			p++;
6438 		}
6439 
6440 		if ((c = *p++) == '\0')
6441 			return (0);
6442 
6443 		do {
6444 			if (c == '-' && lc != '\0' && *p != ']') {
6445 				if ((c = *p++) == '\0')
6446 					return (0);
6447 				if (c == '\\' && (c = *p++) == '\0')
6448 					return (0);
6449 
6450 				if (notflag) {
6451 					if (s1 < lc || s1 > c)
6452 						ok++;
6453 					else
6454 						return (0);
6455 				} else if (lc <= s1 && s1 <= c)
6456 					ok++;
6457 
6458 			} else if (c == '\\' && (c = *p++) == '\0')
6459 				return (0);
6460 
6461 			lc = c; /* save left-hand 'c' for next iteration */
6462 
6463 			if (notflag) {
6464 				if (s1 != c)
6465 					ok++;
6466 				else
6467 					return (0);
6468 			} else if (s1 == c)
6469 				ok++;
6470 
6471 			if ((c = *p++) == '\0')
6472 				return (0);
6473 
6474 		} while (c != ']');
6475 
6476 		if (ok)
6477 			goto top;
6478 
6479 		return (0);
6480 	}
6481 
6482 	case '\\':
6483 		if ((c = *p++) == '\0')
6484 			return (0);
6485 		/*FALLTHRU*/
6486 
6487 	default:
6488 		if (c != s1)
6489 			return (0);
6490 		/*FALLTHRU*/
6491 
6492 	case '?':
6493 		if (s1 != '\0')
6494 			goto top;
6495 		return (0);
6496 
6497 	case '*':
6498 		while (*p == '*')
6499 			p++; /* consecutive *'s are identical to a single one */
6500 
6501 		if (*p == '\0')
6502 			return (1);
6503 
6504 		for (s = olds; *s != '\0'; s++) {
6505 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
6506 				return (gs);
6507 		}
6508 
6509 		return (0);
6510 	}
6511 }
6512 
6513 /*ARGSUSED*/
6514 static int
6515 dtrace_match_string(const char *s, const char *p, int depth)
6516 {
6517 	return (s != NULL && strcmp(s, p) == 0);
6518 }
6519 
6520 /*ARGSUSED*/
6521 static int
6522 dtrace_match_nul(const char *s, const char *p, int depth)
6523 {
6524 	return (1); /* always match the empty pattern */
6525 }
6526 
6527 /*ARGSUSED*/
6528 static int
6529 dtrace_match_nonzero(const char *s, const char *p, int depth)
6530 {
6531 	return (s != NULL && s[0] != '\0');
6532 }
6533 
6534 static int
6535 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
6536     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
6537 {
6538 	dtrace_probe_t template, *probe;
6539 	dtrace_hash_t *hash = NULL;
6540 	int len, best = INT_MAX, nmatched = 0;
6541 	dtrace_id_t i;
6542 
6543 	ASSERT(MUTEX_HELD(&dtrace_lock));
6544 
6545 	/*
6546 	 * If the probe ID is specified in the key, just lookup by ID and
6547 	 * invoke the match callback once if a matching probe is found.
6548 	 */
6549 	if (pkp->dtpk_id != DTRACE_IDNONE) {
6550 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
6551 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
6552 			(void) (*matched)(probe, arg);
6553 			nmatched++;
6554 		}
6555 		return (nmatched);
6556 	}
6557 
6558 	template.dtpr_mod = (char *)pkp->dtpk_mod;
6559 	template.dtpr_func = (char *)pkp->dtpk_func;
6560 	template.dtpr_name = (char *)pkp->dtpk_name;
6561 
6562 	/*
6563 	 * We want to find the most distinct of the module name, function
6564 	 * name, and name.  So for each one that is not a glob pattern or
6565 	 * empty string, we perform a lookup in the corresponding hash and
6566 	 * use the hash table with the fewest collisions to do our search.
6567 	 */
6568 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
6569 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
6570 		best = len;
6571 		hash = dtrace_bymod;
6572 	}
6573 
6574 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
6575 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
6576 		best = len;
6577 		hash = dtrace_byfunc;
6578 	}
6579 
6580 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
6581 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
6582 		best = len;
6583 		hash = dtrace_byname;
6584 	}
6585 
6586 	/*
6587 	 * If we did not select a hash table, iterate over every probe and
6588 	 * invoke our callback for each one that matches our input probe key.
6589 	 */
6590 	if (hash == NULL) {
6591 		for (i = 0; i < dtrace_nprobes; i++) {
6592 			if ((probe = dtrace_probes[i]) == NULL ||
6593 			    dtrace_match_probe(probe, pkp, priv, uid,
6594 			    zoneid) <= 0)
6595 				continue;
6596 
6597 			nmatched++;
6598 
6599 			if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
6600 				break;
6601 		}
6602 
6603 		return (nmatched);
6604 	}
6605 
6606 	/*
6607 	 * If we selected a hash table, iterate over each probe of the same key
6608 	 * name and invoke the callback for every probe that matches the other
6609 	 * attributes of our input probe key.
6610 	 */
6611 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
6612 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
6613 
6614 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
6615 			continue;
6616 
6617 		nmatched++;
6618 
6619 		if ((*matched)(probe, arg) != DTRACE_MATCH_NEXT)
6620 			break;
6621 	}
6622 
6623 	return (nmatched);
6624 }
6625 
6626 /*
6627  * Return the function pointer dtrace_probecmp() should use to compare the
6628  * specified pattern with a string.  For NULL or empty patterns, we select
6629  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
6630  * For non-empty non-glob strings, we use dtrace_match_string().
6631  */
6632 static dtrace_probekey_f *
6633 dtrace_probekey_func(const char *p)
6634 {
6635 	char c;
6636 
6637 	if (p == NULL || *p == '\0')
6638 		return (&dtrace_match_nul);
6639 
6640 	while ((c = *p++) != '\0') {
6641 		if (c == '[' || c == '?' || c == '*' || c == '\\')
6642 			return (&dtrace_match_glob);
6643 	}
6644 
6645 	return (&dtrace_match_string);
6646 }
6647 
6648 /*
6649  * Build a probe comparison key for use with dtrace_match_probe() from the
6650  * given probe description.  By convention, a null key only matches anchored
6651  * probes: if each field is the empty string, reset dtpk_fmatch to
6652  * dtrace_match_nonzero().
6653  */
6654 static void
6655 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
6656 {
6657 	pkp->dtpk_prov = pdp->dtpd_provider;
6658 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
6659 
6660 	pkp->dtpk_mod = pdp->dtpd_mod;
6661 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
6662 
6663 	pkp->dtpk_func = pdp->dtpd_func;
6664 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
6665 
6666 	pkp->dtpk_name = pdp->dtpd_name;
6667 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
6668 
6669 	pkp->dtpk_id = pdp->dtpd_id;
6670 
6671 	if (pkp->dtpk_id == DTRACE_IDNONE &&
6672 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
6673 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
6674 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
6675 	    pkp->dtpk_nmatch == &dtrace_match_nul)
6676 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
6677 }
6678 
6679 /*
6680  * DTrace Provider-to-Framework API Functions
6681  *
6682  * These functions implement much of the Provider-to-Framework API, as
6683  * described in <sys/dtrace.h>.  The parts of the API not in this section are
6684  * the functions in the API for probe management (found below), and
6685  * dtrace_probe() itself (found above).
6686  */
6687 
6688 /*
6689  * Register the calling provider with the DTrace framework.  This should
6690  * generally be called by DTrace providers in their attach(9E) entry point.
6691  */
6692 int
6693 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
6694     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
6695 {
6696 	dtrace_provider_t *provider;
6697 
6698 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
6699 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6700 		    "arguments", name ? name : "<NULL>");
6701 		return (EINVAL);
6702 	}
6703 
6704 	if (name[0] == '\0' || dtrace_badname(name)) {
6705 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6706 		    "provider name", name);
6707 		return (EINVAL);
6708 	}
6709 
6710 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
6711 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
6712 	    pops->dtps_destroy == NULL ||
6713 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
6714 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6715 		    "provider ops", name);
6716 		return (EINVAL);
6717 	}
6718 
6719 	if (dtrace_badattr(&pap->dtpa_provider) ||
6720 	    dtrace_badattr(&pap->dtpa_mod) ||
6721 	    dtrace_badattr(&pap->dtpa_func) ||
6722 	    dtrace_badattr(&pap->dtpa_name) ||
6723 	    dtrace_badattr(&pap->dtpa_args)) {
6724 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6725 		    "provider attributes", name);
6726 		return (EINVAL);
6727 	}
6728 
6729 	if (priv & ~DTRACE_PRIV_ALL) {
6730 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
6731 		    "privilege attributes", name);
6732 		return (EINVAL);
6733 	}
6734 
6735 	if ((priv & DTRACE_PRIV_KERNEL) &&
6736 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
6737 	    pops->dtps_usermode == NULL) {
6738 		cmn_err(CE_WARN, "failed to register provider '%s': need "
6739 		    "dtps_usermode() op for given privilege attributes", name);
6740 		return (EINVAL);
6741 	}
6742 
6743 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
6744 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
6745 	(void) strcpy(provider->dtpv_name, name);
6746 
6747 	provider->dtpv_attr = *pap;
6748 	provider->dtpv_priv.dtpp_flags = priv;
6749 	if (cr != NULL) {
6750 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
6751 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
6752 	}
6753 	provider->dtpv_pops = *pops;
6754 
6755 	if (pops->dtps_provide == NULL) {
6756 		ASSERT(pops->dtps_provide_module != NULL);
6757 		provider->dtpv_pops.dtps_provide =
6758 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
6759 	}
6760 
6761 	if (pops->dtps_provide_module == NULL) {
6762 		ASSERT(pops->dtps_provide != NULL);
6763 		provider->dtpv_pops.dtps_provide_module =
6764 		    (void (*)(void *, struct modctl *))dtrace_nullop;
6765 	}
6766 
6767 	if (pops->dtps_suspend == NULL) {
6768 		ASSERT(pops->dtps_resume == NULL);
6769 		provider->dtpv_pops.dtps_suspend =
6770 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6771 		provider->dtpv_pops.dtps_resume =
6772 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
6773 	}
6774 
6775 	provider->dtpv_arg = arg;
6776 	*idp = (dtrace_provider_id_t)provider;
6777 
6778 	if (pops == &dtrace_provider_ops) {
6779 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6780 		ASSERT(MUTEX_HELD(&dtrace_lock));
6781 		ASSERT(dtrace_anon.dta_enabling == NULL);
6782 
6783 		/*
6784 		 * We make sure that the DTrace provider is at the head of
6785 		 * the provider chain.
6786 		 */
6787 		provider->dtpv_next = dtrace_provider;
6788 		dtrace_provider = provider;
6789 		return (0);
6790 	}
6791 
6792 	mutex_enter(&dtrace_provider_lock);
6793 	mutex_enter(&dtrace_lock);
6794 
6795 	/*
6796 	 * If there is at least one provider registered, we'll add this
6797 	 * provider after the first provider.
6798 	 */
6799 	if (dtrace_provider != NULL) {
6800 		provider->dtpv_next = dtrace_provider->dtpv_next;
6801 		dtrace_provider->dtpv_next = provider;
6802 	} else {
6803 		dtrace_provider = provider;
6804 	}
6805 
6806 	if (dtrace_retained != NULL) {
6807 		dtrace_enabling_provide(provider);
6808 
6809 		/*
6810 		 * Now we need to call dtrace_enabling_matchall() -- which
6811 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
6812 		 * to drop all of our locks before calling into it...
6813 		 */
6814 		mutex_exit(&dtrace_lock);
6815 		mutex_exit(&dtrace_provider_lock);
6816 		dtrace_enabling_matchall();
6817 
6818 		return (0);
6819 	}
6820 
6821 	mutex_exit(&dtrace_lock);
6822 	mutex_exit(&dtrace_provider_lock);
6823 
6824 	return (0);
6825 }
6826 
6827 /*
6828  * Unregister the specified provider from the DTrace framework.  This should
6829  * generally be called by DTrace providers in their detach(9E) entry point.
6830  */
6831 int
6832 dtrace_unregister(dtrace_provider_id_t id)
6833 {
6834 	dtrace_provider_t *old = (dtrace_provider_t *)id;
6835 	dtrace_provider_t *prev = NULL;
6836 	int i, self = 0;
6837 	dtrace_probe_t *probe, *first = NULL;
6838 
6839 	if (old->dtpv_pops.dtps_enable ==
6840 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop) {
6841 		/*
6842 		 * If DTrace itself is the provider, we're called with locks
6843 		 * already held.
6844 		 */
6845 		ASSERT(old == dtrace_provider);
6846 		ASSERT(dtrace_devi != NULL);
6847 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
6848 		ASSERT(MUTEX_HELD(&dtrace_lock));
6849 		self = 1;
6850 
6851 		if (dtrace_provider->dtpv_next != NULL) {
6852 			/*
6853 			 * There's another provider here; return failure.
6854 			 */
6855 			return (EBUSY);
6856 		}
6857 	} else {
6858 		mutex_enter(&dtrace_provider_lock);
6859 		mutex_enter(&mod_lock);
6860 		mutex_enter(&dtrace_lock);
6861 	}
6862 
6863 	/*
6864 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
6865 	 * probes, we refuse to let providers slither away, unless this
6866 	 * provider has already been explicitly invalidated.
6867 	 */
6868 	if (!old->dtpv_defunct &&
6869 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
6870 	    dtrace_anon.dta_state->dts_necbs > 0))) {
6871 		if (!self) {
6872 			mutex_exit(&dtrace_lock);
6873 			mutex_exit(&mod_lock);
6874 			mutex_exit(&dtrace_provider_lock);
6875 		}
6876 		return (EBUSY);
6877 	}
6878 
6879 	/*
6880 	 * Attempt to destroy the probes associated with this provider.
6881 	 */
6882 	for (i = 0; i < dtrace_nprobes; i++) {
6883 		if ((probe = dtrace_probes[i]) == NULL)
6884 			continue;
6885 
6886 		if (probe->dtpr_provider != old)
6887 			continue;
6888 
6889 		if (probe->dtpr_ecb == NULL)
6890 			continue;
6891 
6892 		/*
6893 		 * We have at least one ECB; we can't remove this provider.
6894 		 */
6895 		if (!self) {
6896 			mutex_exit(&dtrace_lock);
6897 			mutex_exit(&mod_lock);
6898 			mutex_exit(&dtrace_provider_lock);
6899 		}
6900 		return (EBUSY);
6901 	}
6902 
6903 	/*
6904 	 * All of the probes for this provider are disabled; we can safely
6905 	 * remove all of them from their hash chains and from the probe array.
6906 	 */
6907 	for (i = 0; i < dtrace_nprobes; i++) {
6908 		if ((probe = dtrace_probes[i]) == NULL)
6909 			continue;
6910 
6911 		if (probe->dtpr_provider != old)
6912 			continue;
6913 
6914 		dtrace_probes[i] = NULL;
6915 
6916 		dtrace_hash_remove(dtrace_bymod, probe);
6917 		dtrace_hash_remove(dtrace_byfunc, probe);
6918 		dtrace_hash_remove(dtrace_byname, probe);
6919 
6920 		if (first == NULL) {
6921 			first = probe;
6922 			probe->dtpr_nextmod = NULL;
6923 		} else {
6924 			probe->dtpr_nextmod = first;
6925 			first = probe;
6926 		}
6927 	}
6928 
6929 	/*
6930 	 * The provider's probes have been removed from the hash chains and
6931 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
6932 	 * everyone has cleared out from any probe array processing.
6933 	 */
6934 	dtrace_sync();
6935 
6936 	for (probe = first; probe != NULL; probe = first) {
6937 		first = probe->dtpr_nextmod;
6938 
6939 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
6940 		    probe->dtpr_arg);
6941 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
6942 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
6943 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
6944 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
6945 		kmem_free(probe, sizeof (dtrace_probe_t));
6946 	}
6947 
6948 	if ((prev = dtrace_provider) == old) {
6949 		ASSERT(self || dtrace_devi == NULL);
6950 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
6951 		dtrace_provider = old->dtpv_next;
6952 	} else {
6953 		while (prev != NULL && prev->dtpv_next != old)
6954 			prev = prev->dtpv_next;
6955 
6956 		if (prev == NULL) {
6957 			panic("attempt to unregister non-existent "
6958 			    "dtrace provider %p\n", (void *)id);
6959 		}
6960 
6961 		prev->dtpv_next = old->dtpv_next;
6962 	}
6963 
6964 	if (!self) {
6965 		mutex_exit(&dtrace_lock);
6966 		mutex_exit(&mod_lock);
6967 		mutex_exit(&dtrace_provider_lock);
6968 	}
6969 
6970 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
6971 	kmem_free(old, sizeof (dtrace_provider_t));
6972 
6973 	return (0);
6974 }
6975 
6976 /*
6977  * Invalidate the specified provider.  All subsequent probe lookups for the
6978  * specified provider will fail, but its probes will not be removed.
6979  */
6980 void
6981 dtrace_invalidate(dtrace_provider_id_t id)
6982 {
6983 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
6984 
6985 	ASSERT(pvp->dtpv_pops.dtps_enable !=
6986 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
6987 
6988 	mutex_enter(&dtrace_provider_lock);
6989 	mutex_enter(&dtrace_lock);
6990 
6991 	pvp->dtpv_defunct = 1;
6992 
6993 	mutex_exit(&dtrace_lock);
6994 	mutex_exit(&dtrace_provider_lock);
6995 }
6996 
6997 /*
6998  * Indicate whether or not DTrace has attached.
6999  */
7000 int
7001 dtrace_attached(void)
7002 {
7003 	/*
7004 	 * dtrace_provider will be non-NULL iff the DTrace driver has
7005 	 * attached.  (It's non-NULL because DTrace is always itself a
7006 	 * provider.)
7007 	 */
7008 	return (dtrace_provider != NULL);
7009 }
7010 
7011 /*
7012  * Remove all the unenabled probes for the given provider.  This function is
7013  * not unlike dtrace_unregister(), except that it doesn't remove the provider
7014  * -- just as many of its associated probes as it can.
7015  */
7016 int
7017 dtrace_condense(dtrace_provider_id_t id)
7018 {
7019 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
7020 	int i;
7021 	dtrace_probe_t *probe;
7022 
7023 	/*
7024 	 * Make sure this isn't the dtrace provider itself.
7025 	 */
7026 	ASSERT(prov->dtpv_pops.dtps_enable !=
7027 	    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop);
7028 
7029 	mutex_enter(&dtrace_provider_lock);
7030 	mutex_enter(&dtrace_lock);
7031 
7032 	/*
7033 	 * Attempt to destroy the probes associated with this provider.
7034 	 */
7035 	for (i = 0; i < dtrace_nprobes; i++) {
7036 		if ((probe = dtrace_probes[i]) == NULL)
7037 			continue;
7038 
7039 		if (probe->dtpr_provider != prov)
7040 			continue;
7041 
7042 		if (probe->dtpr_ecb != NULL)
7043 			continue;
7044 
7045 		dtrace_probes[i] = NULL;
7046 
7047 		dtrace_hash_remove(dtrace_bymod, probe);
7048 		dtrace_hash_remove(dtrace_byfunc, probe);
7049 		dtrace_hash_remove(dtrace_byname, probe);
7050 
7051 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
7052 		    probe->dtpr_arg);
7053 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
7054 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
7055 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
7056 		kmem_free(probe, sizeof (dtrace_probe_t));
7057 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
7058 	}
7059 
7060 	mutex_exit(&dtrace_lock);
7061 	mutex_exit(&dtrace_provider_lock);
7062 
7063 	return (0);
7064 }
7065 
7066 /*
7067  * DTrace Probe Management Functions
7068  *
7069  * The functions in this section perform the DTrace probe management,
7070  * including functions to create probes, look-up probes, and call into the
7071  * providers to request that probes be provided.  Some of these functions are
7072  * in the Provider-to-Framework API; these functions can be identified by the
7073  * fact that they are not declared "static".
7074  */
7075 
7076 /*
7077  * Create a probe with the specified module name, function name, and name.
7078  */
7079 dtrace_id_t
7080 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
7081     const char *func, const char *name, int aframes, void *arg)
7082 {
7083 	dtrace_probe_t *probe, **probes;
7084 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
7085 	dtrace_id_t id;
7086 
7087 	if (provider == dtrace_provider) {
7088 		ASSERT(MUTEX_HELD(&dtrace_lock));
7089 	} else {
7090 		mutex_enter(&dtrace_lock);
7091 	}
7092 
7093 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
7094 	    VM_BESTFIT | VM_SLEEP);
7095 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
7096 
7097 	probe->dtpr_id = id;
7098 	probe->dtpr_gen = dtrace_probegen++;
7099 	probe->dtpr_mod = dtrace_strdup(mod);
7100 	probe->dtpr_func = dtrace_strdup(func);
7101 	probe->dtpr_name = dtrace_strdup(name);
7102 	probe->dtpr_arg = arg;
7103 	probe->dtpr_aframes = aframes;
7104 	probe->dtpr_provider = provider;
7105 
7106 	dtrace_hash_add(dtrace_bymod, probe);
7107 	dtrace_hash_add(dtrace_byfunc, probe);
7108 	dtrace_hash_add(dtrace_byname, probe);
7109 
7110 	if (id - 1 >= dtrace_nprobes) {
7111 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
7112 		size_t nsize = osize << 1;
7113 
7114 		if (nsize == 0) {
7115 			ASSERT(osize == 0);
7116 			ASSERT(dtrace_probes == NULL);
7117 			nsize = sizeof (dtrace_probe_t *);
7118 		}
7119 
7120 		probes = kmem_zalloc(nsize, KM_SLEEP);
7121 
7122 		if (dtrace_probes == NULL) {
7123 			ASSERT(osize == 0);
7124 			dtrace_probes = probes;
7125 			dtrace_nprobes = 1;
7126 		} else {
7127 			dtrace_probe_t **oprobes = dtrace_probes;
7128 
7129 			bcopy(oprobes, probes, osize);
7130 			dtrace_membar_producer();
7131 			dtrace_probes = probes;
7132 
7133 			dtrace_sync();
7134 
7135 			/*
7136 			 * All CPUs are now seeing the new probes array; we can
7137 			 * safely free the old array.
7138 			 */
7139 			kmem_free(oprobes, osize);
7140 			dtrace_nprobes <<= 1;
7141 		}
7142 
7143 		ASSERT(id - 1 < dtrace_nprobes);
7144 	}
7145 
7146 	ASSERT(dtrace_probes[id - 1] == NULL);
7147 	dtrace_probes[id - 1] = probe;
7148 
7149 	if (provider != dtrace_provider)
7150 		mutex_exit(&dtrace_lock);
7151 
7152 	return (id);
7153 }
7154 
7155 static dtrace_probe_t *
7156 dtrace_probe_lookup_id(dtrace_id_t id)
7157 {
7158 	ASSERT(MUTEX_HELD(&dtrace_lock));
7159 
7160 	if (id == 0 || id > dtrace_nprobes)
7161 		return (NULL);
7162 
7163 	return (dtrace_probes[id - 1]);
7164 }
7165 
7166 static int
7167 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
7168 {
7169 	*((dtrace_id_t *)arg) = probe->dtpr_id;
7170 
7171 	return (DTRACE_MATCH_DONE);
7172 }
7173 
7174 /*
7175  * Look up a probe based on provider and one or more of module name, function
7176  * name and probe name.
7177  */
7178 dtrace_id_t
7179 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
7180     const char *func, const char *name)
7181 {
7182 	dtrace_probekey_t pkey;
7183 	dtrace_id_t id;
7184 	int match;
7185 
7186 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
7187 	pkey.dtpk_pmatch = &dtrace_match_string;
7188 	pkey.dtpk_mod = mod;
7189 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
7190 	pkey.dtpk_func = func;
7191 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
7192 	pkey.dtpk_name = name;
7193 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
7194 	pkey.dtpk_id = DTRACE_IDNONE;
7195 
7196 	mutex_enter(&dtrace_lock);
7197 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
7198 	    dtrace_probe_lookup_match, &id);
7199 	mutex_exit(&dtrace_lock);
7200 
7201 	ASSERT(match == 1 || match == 0);
7202 	return (match ? id : 0);
7203 }
7204 
7205 /*
7206  * Returns the probe argument associated with the specified probe.
7207  */
7208 void *
7209 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
7210 {
7211 	dtrace_probe_t *probe;
7212 	void *rval = NULL;
7213 
7214 	mutex_enter(&dtrace_lock);
7215 
7216 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
7217 	    probe->dtpr_provider == (dtrace_provider_t *)id)
7218 		rval = probe->dtpr_arg;
7219 
7220 	mutex_exit(&dtrace_lock);
7221 
7222 	return (rval);
7223 }
7224 
7225 /*
7226  * Copy a probe into a probe description.
7227  */
7228 static void
7229 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
7230 {
7231 	bzero(pdp, sizeof (dtrace_probedesc_t));
7232 	pdp->dtpd_id = prp->dtpr_id;
7233 
7234 	(void) strncpy(pdp->dtpd_provider,
7235 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
7236 
7237 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
7238 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
7239 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
7240 }
7241 
7242 /*
7243  * Called to indicate that a probe -- or probes -- should be provided by a
7244  * specfied provider.  If the specified description is NULL, the provider will
7245  * be told to provide all of its probes.  (This is done whenever a new
7246  * consumer comes along, or whenever a retained enabling is to be matched.) If
7247  * the specified description is non-NULL, the provider is given the
7248  * opportunity to dynamically provide the specified probe, allowing providers
7249  * to support the creation of probes on-the-fly.  (So-called _autocreated_
7250  * probes.)  If the provider is NULL, the operations will be applied to all
7251  * providers; if the provider is non-NULL the operations will only be applied
7252  * to the specified provider.  The dtrace_provider_lock must be held, and the
7253  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
7254  * will need to grab the dtrace_lock when it reenters the framework through
7255  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
7256  */
7257 static void
7258 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
7259 {
7260 	struct modctl *ctl;
7261 	int all = 0;
7262 
7263 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
7264 
7265 	if (prv == NULL) {
7266 		all = 1;
7267 		prv = dtrace_provider;
7268 	}
7269 
7270 	do {
7271 		/*
7272 		 * First, call the blanket provide operation.
7273 		 */
7274 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
7275 
7276 		/*
7277 		 * Now call the per-module provide operation.  We will grab
7278 		 * mod_lock to prevent the list from being modified.  Note
7279 		 * that this also prevents the mod_busy bits from changing.
7280 		 * (mod_busy can only be changed with mod_lock held.)
7281 		 */
7282 		mutex_enter(&mod_lock);
7283 
7284 		ctl = &modules;
7285 		do {
7286 			if (ctl->mod_busy || ctl->mod_mp == NULL)
7287 				continue;
7288 
7289 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
7290 
7291 		} while ((ctl = ctl->mod_next) != &modules);
7292 
7293 		mutex_exit(&mod_lock);
7294 	} while (all && (prv = prv->dtpv_next) != NULL);
7295 }
7296 
7297 /*
7298  * Iterate over each probe, and call the Framework-to-Provider API function
7299  * denoted by offs.
7300  */
7301 static void
7302 dtrace_probe_foreach(uintptr_t offs)
7303 {
7304 	dtrace_provider_t *prov;
7305 	void (*func)(void *, dtrace_id_t, void *);
7306 	dtrace_probe_t *probe;
7307 	dtrace_icookie_t cookie;
7308 	int i;
7309 
7310 	/*
7311 	 * We disable interrupts to walk through the probe array.  This is
7312 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
7313 	 * won't see stale data.
7314 	 */
7315 	cookie = dtrace_interrupt_disable();
7316 
7317 	for (i = 0; i < dtrace_nprobes; i++) {
7318 		if ((probe = dtrace_probes[i]) == NULL)
7319 			continue;
7320 
7321 		if (probe->dtpr_ecb == NULL) {
7322 			/*
7323 			 * This probe isn't enabled -- don't call the function.
7324 			 */
7325 			continue;
7326 		}
7327 
7328 		prov = probe->dtpr_provider;
7329 		func = *((void(**)(void *, dtrace_id_t, void *))
7330 		    ((uintptr_t)&prov->dtpv_pops + offs));
7331 
7332 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
7333 	}
7334 
7335 	dtrace_interrupt_enable(cookie);
7336 }
7337 
7338 static int
7339 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
7340 {
7341 	dtrace_probekey_t pkey;
7342 	uint32_t priv;
7343 	uid_t uid;
7344 	zoneid_t zoneid;
7345 
7346 	ASSERT(MUTEX_HELD(&dtrace_lock));
7347 	dtrace_ecb_create_cache = NULL;
7348 
7349 	if (desc == NULL) {
7350 		/*
7351 		 * If we're passed a NULL description, we're being asked to
7352 		 * create an ECB with a NULL probe.
7353 		 */
7354 		(void) dtrace_ecb_create_enable(NULL, enab);
7355 		return (0);
7356 	}
7357 
7358 	dtrace_probekey(desc, &pkey);
7359 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
7360 	    &priv, &uid, &zoneid);
7361 
7362 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
7363 	    enab));
7364 }
7365 
7366 /*
7367  * DTrace Helper Provider Functions
7368  */
7369 static void
7370 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
7371 {
7372 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
7373 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
7374 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
7375 }
7376 
7377 static void
7378 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
7379     const dof_provider_t *dofprov, char *strtab)
7380 {
7381 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
7382 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
7383 	    dofprov->dofpv_provattr);
7384 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
7385 	    dofprov->dofpv_modattr);
7386 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
7387 	    dofprov->dofpv_funcattr);
7388 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
7389 	    dofprov->dofpv_nameattr);
7390 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
7391 	    dofprov->dofpv_argsattr);
7392 }
7393 
7394 static void
7395 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7396 {
7397 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7398 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7399 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
7400 	dof_provider_t *provider;
7401 	dof_probe_t *probe;
7402 	uint32_t *off, *enoff;
7403 	uint8_t *arg;
7404 	char *strtab;
7405 	uint_t i, nprobes;
7406 	dtrace_helper_provdesc_t dhpv;
7407 	dtrace_helper_probedesc_t dhpb;
7408 	dtrace_meta_t *meta = dtrace_meta_pid;
7409 	dtrace_mops_t *mops = &meta->dtm_mops;
7410 	void *parg;
7411 
7412 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7413 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7414 	    provider->dofpv_strtab * dof->dofh_secsize);
7415 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7416 	    provider->dofpv_probes * dof->dofh_secsize);
7417 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7418 	    provider->dofpv_prargs * dof->dofh_secsize);
7419 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7420 	    provider->dofpv_proffs * dof->dofh_secsize);
7421 
7422 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7423 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
7424 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
7425 	enoff = NULL;
7426 
7427 	/*
7428 	 * See dtrace_helper_provider_validate().
7429 	 */
7430 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
7431 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
7432 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7433 		    provider->dofpv_prenoffs * dof->dofh_secsize);
7434 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
7435 	}
7436 
7437 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
7438 
7439 	/*
7440 	 * Create the provider.
7441 	 */
7442 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7443 
7444 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
7445 		return;
7446 
7447 	meta->dtm_count++;
7448 
7449 	/*
7450 	 * Create the probes.
7451 	 */
7452 	for (i = 0; i < nprobes; i++) {
7453 		probe = (dof_probe_t *)(uintptr_t)(daddr +
7454 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
7455 
7456 		dhpb.dthpb_mod = dhp->dofhp_mod;
7457 		dhpb.dthpb_func = strtab + probe->dofpr_func;
7458 		dhpb.dthpb_name = strtab + probe->dofpr_name;
7459 		dhpb.dthpb_base = probe->dofpr_addr;
7460 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
7461 		dhpb.dthpb_noffs = probe->dofpr_noffs;
7462 		if (enoff != NULL) {
7463 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
7464 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
7465 		} else {
7466 			dhpb.dthpb_enoffs = NULL;
7467 			dhpb.dthpb_nenoffs = 0;
7468 		}
7469 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
7470 		dhpb.dthpb_nargc = probe->dofpr_nargc;
7471 		dhpb.dthpb_xargc = probe->dofpr_xargc;
7472 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
7473 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
7474 
7475 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
7476 	}
7477 }
7478 
7479 static void
7480 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
7481 {
7482 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7483 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7484 	int i;
7485 
7486 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7487 
7488 	for (i = 0; i < dof->dofh_secnum; i++) {
7489 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7490 		    dof->dofh_secoff + i * dof->dofh_secsize);
7491 
7492 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7493 			continue;
7494 
7495 		dtrace_helper_provide_one(dhp, sec, pid);
7496 	}
7497 
7498 	/*
7499 	 * We may have just created probes, so we must now rematch against
7500 	 * any retained enablings.  Note that this call will acquire both
7501 	 * cpu_lock and dtrace_lock; the fact that we are holding
7502 	 * dtrace_meta_lock now is what defines the ordering with respect to
7503 	 * these three locks.
7504 	 */
7505 	dtrace_enabling_matchall();
7506 }
7507 
7508 static void
7509 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
7510 {
7511 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7512 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7513 	dof_sec_t *str_sec;
7514 	dof_provider_t *provider;
7515 	char *strtab;
7516 	dtrace_helper_provdesc_t dhpv;
7517 	dtrace_meta_t *meta = dtrace_meta_pid;
7518 	dtrace_mops_t *mops = &meta->dtm_mops;
7519 
7520 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
7521 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
7522 	    provider->dofpv_strtab * dof->dofh_secsize);
7523 
7524 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
7525 
7526 	/*
7527 	 * Create the provider.
7528 	 */
7529 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
7530 
7531 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
7532 
7533 	meta->dtm_count--;
7534 }
7535 
7536 static void
7537 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
7538 {
7539 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
7540 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
7541 	int i;
7542 
7543 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
7544 
7545 	for (i = 0; i < dof->dofh_secnum; i++) {
7546 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
7547 		    dof->dofh_secoff + i * dof->dofh_secsize);
7548 
7549 		if (sec->dofs_type != DOF_SECT_PROVIDER)
7550 			continue;
7551 
7552 		dtrace_helper_provider_remove_one(dhp, sec, pid);
7553 	}
7554 }
7555 
7556 /*
7557  * DTrace Meta Provider-to-Framework API Functions
7558  *
7559  * These functions implement the Meta Provider-to-Framework API, as described
7560  * in <sys/dtrace.h>.
7561  */
7562 int
7563 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
7564     dtrace_meta_provider_id_t *idp)
7565 {
7566 	dtrace_meta_t *meta;
7567 	dtrace_helpers_t *help, *next;
7568 	int i;
7569 
7570 	*idp = DTRACE_METAPROVNONE;
7571 
7572 	/*
7573 	 * We strictly don't need the name, but we hold onto it for
7574 	 * debuggability. All hail error queues!
7575 	 */
7576 	if (name == NULL) {
7577 		cmn_err(CE_WARN, "failed to register meta-provider: "
7578 		    "invalid name");
7579 		return (EINVAL);
7580 	}
7581 
7582 	if (mops == NULL ||
7583 	    mops->dtms_create_probe == NULL ||
7584 	    mops->dtms_provide_pid == NULL ||
7585 	    mops->dtms_remove_pid == NULL) {
7586 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7587 		    "invalid ops", name);
7588 		return (EINVAL);
7589 	}
7590 
7591 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
7592 	meta->dtm_mops = *mops;
7593 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
7594 	(void) strcpy(meta->dtm_name, name);
7595 	meta->dtm_arg = arg;
7596 
7597 	mutex_enter(&dtrace_meta_lock);
7598 	mutex_enter(&dtrace_lock);
7599 
7600 	if (dtrace_meta_pid != NULL) {
7601 		mutex_exit(&dtrace_lock);
7602 		mutex_exit(&dtrace_meta_lock);
7603 		cmn_err(CE_WARN, "failed to register meta-register %s: "
7604 		    "user-land meta-provider exists", name);
7605 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
7606 		kmem_free(meta, sizeof (dtrace_meta_t));
7607 		return (EINVAL);
7608 	}
7609 
7610 	dtrace_meta_pid = meta;
7611 	*idp = (dtrace_meta_provider_id_t)meta;
7612 
7613 	/*
7614 	 * If there are providers and probes ready to go, pass them
7615 	 * off to the new meta provider now.
7616 	 */
7617 
7618 	help = dtrace_deferred_pid;
7619 	dtrace_deferred_pid = NULL;
7620 
7621 	mutex_exit(&dtrace_lock);
7622 
7623 	while (help != NULL) {
7624 		for (i = 0; i < help->dthps_nprovs; i++) {
7625 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
7626 			    help->dthps_pid);
7627 		}
7628 
7629 		next = help->dthps_next;
7630 		help->dthps_next = NULL;
7631 		help->dthps_prev = NULL;
7632 		help->dthps_deferred = 0;
7633 		help = next;
7634 	}
7635 
7636 	mutex_exit(&dtrace_meta_lock);
7637 
7638 	return (0);
7639 }
7640 
7641 int
7642 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
7643 {
7644 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
7645 
7646 	mutex_enter(&dtrace_meta_lock);
7647 	mutex_enter(&dtrace_lock);
7648 
7649 	if (old == dtrace_meta_pid) {
7650 		pp = &dtrace_meta_pid;
7651 	} else {
7652 		panic("attempt to unregister non-existent "
7653 		    "dtrace meta-provider %p\n", (void *)old);
7654 	}
7655 
7656 	if (old->dtm_count != 0) {
7657 		mutex_exit(&dtrace_lock);
7658 		mutex_exit(&dtrace_meta_lock);
7659 		return (EBUSY);
7660 	}
7661 
7662 	*pp = NULL;
7663 
7664 	mutex_exit(&dtrace_lock);
7665 	mutex_exit(&dtrace_meta_lock);
7666 
7667 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
7668 	kmem_free(old, sizeof (dtrace_meta_t));
7669 
7670 	return (0);
7671 }
7672 
7673 
7674 /*
7675  * DTrace DIF Object Functions
7676  */
7677 static int
7678 dtrace_difo_err(uint_t pc, const char *format, ...)
7679 {
7680 	if (dtrace_err_verbose) {
7681 		va_list alist;
7682 
7683 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
7684 		va_start(alist, format);
7685 		(void) vuprintf(format, alist);
7686 		va_end(alist);
7687 	}
7688 
7689 #ifdef DTRACE_ERRDEBUG
7690 	dtrace_errdebug(format);
7691 #endif
7692 	return (1);
7693 }
7694 
7695 /*
7696  * Validate a DTrace DIF object by checking the IR instructions.  The following
7697  * rules are currently enforced by dtrace_difo_validate():
7698  *
7699  * 1. Each instruction must have a valid opcode
7700  * 2. Each register, string, variable, or subroutine reference must be valid
7701  * 3. No instruction can modify register %r0 (must be zero)
7702  * 4. All instruction reserved bits must be set to zero
7703  * 5. The last instruction must be a "ret" instruction
7704  * 6. All branch targets must reference a valid instruction _after_ the branch
7705  */
7706 static int
7707 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
7708     cred_t *cr)
7709 {
7710 	int err = 0, i;
7711 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
7712 	int kcheckload;
7713 	uint_t pc;
7714 
7715 	kcheckload = cr == NULL ||
7716 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
7717 
7718 	dp->dtdo_destructive = 0;
7719 
7720 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
7721 		dif_instr_t instr = dp->dtdo_buf[pc];
7722 
7723 		uint_t r1 = DIF_INSTR_R1(instr);
7724 		uint_t r2 = DIF_INSTR_R2(instr);
7725 		uint_t rd = DIF_INSTR_RD(instr);
7726 		uint_t rs = DIF_INSTR_RS(instr);
7727 		uint_t label = DIF_INSTR_LABEL(instr);
7728 		uint_t v = DIF_INSTR_VAR(instr);
7729 		uint_t subr = DIF_INSTR_SUBR(instr);
7730 		uint_t type = DIF_INSTR_TYPE(instr);
7731 		uint_t op = DIF_INSTR_OP(instr);
7732 
7733 		switch (op) {
7734 		case DIF_OP_OR:
7735 		case DIF_OP_XOR:
7736 		case DIF_OP_AND:
7737 		case DIF_OP_SLL:
7738 		case DIF_OP_SRL:
7739 		case DIF_OP_SRA:
7740 		case DIF_OP_SUB:
7741 		case DIF_OP_ADD:
7742 		case DIF_OP_MUL:
7743 		case DIF_OP_SDIV:
7744 		case DIF_OP_UDIV:
7745 		case DIF_OP_SREM:
7746 		case DIF_OP_UREM:
7747 		case DIF_OP_COPYS:
7748 			if (r1 >= nregs)
7749 				err += efunc(pc, "invalid register %u\n", r1);
7750 			if (r2 >= nregs)
7751 				err += efunc(pc, "invalid register %u\n", r2);
7752 			if (rd >= nregs)
7753 				err += efunc(pc, "invalid register %u\n", rd);
7754 			if (rd == 0)
7755 				err += efunc(pc, "cannot write to %r0\n");
7756 			break;
7757 		case DIF_OP_NOT:
7758 		case DIF_OP_MOV:
7759 		case DIF_OP_ALLOCS:
7760 			if (r1 >= nregs)
7761 				err += efunc(pc, "invalid register %u\n", r1);
7762 			if (r2 != 0)
7763 				err += efunc(pc, "non-zero reserved bits\n");
7764 			if (rd >= nregs)
7765 				err += efunc(pc, "invalid register %u\n", rd);
7766 			if (rd == 0)
7767 				err += efunc(pc, "cannot write to %r0\n");
7768 			break;
7769 		case DIF_OP_LDSB:
7770 		case DIF_OP_LDSH:
7771 		case DIF_OP_LDSW:
7772 		case DIF_OP_LDUB:
7773 		case DIF_OP_LDUH:
7774 		case DIF_OP_LDUW:
7775 		case DIF_OP_LDX:
7776 			if (r1 >= nregs)
7777 				err += efunc(pc, "invalid register %u\n", r1);
7778 			if (r2 != 0)
7779 				err += efunc(pc, "non-zero reserved bits\n");
7780 			if (rd >= nregs)
7781 				err += efunc(pc, "invalid register %u\n", rd);
7782 			if (rd == 0)
7783 				err += efunc(pc, "cannot write to %r0\n");
7784 			if (kcheckload)
7785 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
7786 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
7787 			break;
7788 		case DIF_OP_RLDSB:
7789 		case DIF_OP_RLDSH:
7790 		case DIF_OP_RLDSW:
7791 		case DIF_OP_RLDUB:
7792 		case DIF_OP_RLDUH:
7793 		case DIF_OP_RLDUW:
7794 		case DIF_OP_RLDX:
7795 			if (r1 >= nregs)
7796 				err += efunc(pc, "invalid register %u\n", r1);
7797 			if (r2 != 0)
7798 				err += efunc(pc, "non-zero reserved bits\n");
7799 			if (rd >= nregs)
7800 				err += efunc(pc, "invalid register %u\n", rd);
7801 			if (rd == 0)
7802 				err += efunc(pc, "cannot write to %r0\n");
7803 			break;
7804 		case DIF_OP_ULDSB:
7805 		case DIF_OP_ULDSH:
7806 		case DIF_OP_ULDSW:
7807 		case DIF_OP_ULDUB:
7808 		case DIF_OP_ULDUH:
7809 		case DIF_OP_ULDUW:
7810 		case DIF_OP_ULDX:
7811 			if (r1 >= nregs)
7812 				err += efunc(pc, "invalid register %u\n", r1);
7813 			if (r2 != 0)
7814 				err += efunc(pc, "non-zero reserved bits\n");
7815 			if (rd >= nregs)
7816 				err += efunc(pc, "invalid register %u\n", rd);
7817 			if (rd == 0)
7818 				err += efunc(pc, "cannot write to %r0\n");
7819 			break;
7820 		case DIF_OP_STB:
7821 		case DIF_OP_STH:
7822 		case DIF_OP_STW:
7823 		case DIF_OP_STX:
7824 			if (r1 >= nregs)
7825 				err += efunc(pc, "invalid register %u\n", r1);
7826 			if (r2 != 0)
7827 				err += efunc(pc, "non-zero reserved bits\n");
7828 			if (rd >= nregs)
7829 				err += efunc(pc, "invalid register %u\n", rd);
7830 			if (rd == 0)
7831 				err += efunc(pc, "cannot write to 0 address\n");
7832 			break;
7833 		case DIF_OP_CMP:
7834 		case DIF_OP_SCMP:
7835 			if (r1 >= nregs)
7836 				err += efunc(pc, "invalid register %u\n", r1);
7837 			if (r2 >= nregs)
7838 				err += efunc(pc, "invalid register %u\n", r2);
7839 			if (rd != 0)
7840 				err += efunc(pc, "non-zero reserved bits\n");
7841 			break;
7842 		case DIF_OP_TST:
7843 			if (r1 >= nregs)
7844 				err += efunc(pc, "invalid register %u\n", r1);
7845 			if (r2 != 0 || rd != 0)
7846 				err += efunc(pc, "non-zero reserved bits\n");
7847 			break;
7848 		case DIF_OP_BA:
7849 		case DIF_OP_BE:
7850 		case DIF_OP_BNE:
7851 		case DIF_OP_BG:
7852 		case DIF_OP_BGU:
7853 		case DIF_OP_BGE:
7854 		case DIF_OP_BGEU:
7855 		case DIF_OP_BL:
7856 		case DIF_OP_BLU:
7857 		case DIF_OP_BLE:
7858 		case DIF_OP_BLEU:
7859 			if (label >= dp->dtdo_len) {
7860 				err += efunc(pc, "invalid branch target %u\n",
7861 				    label);
7862 			}
7863 			if (label <= pc) {
7864 				err += efunc(pc, "backward branch to %u\n",
7865 				    label);
7866 			}
7867 			break;
7868 		case DIF_OP_RET:
7869 			if (r1 != 0 || r2 != 0)
7870 				err += efunc(pc, "non-zero reserved bits\n");
7871 			if (rd >= nregs)
7872 				err += efunc(pc, "invalid register %u\n", rd);
7873 			break;
7874 		case DIF_OP_NOP:
7875 		case DIF_OP_POPTS:
7876 		case DIF_OP_FLUSHTS:
7877 			if (r1 != 0 || r2 != 0 || rd != 0)
7878 				err += efunc(pc, "non-zero reserved bits\n");
7879 			break;
7880 		case DIF_OP_SETX:
7881 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
7882 				err += efunc(pc, "invalid integer ref %u\n",
7883 				    DIF_INSTR_INTEGER(instr));
7884 			}
7885 			if (rd >= nregs)
7886 				err += efunc(pc, "invalid register %u\n", rd);
7887 			if (rd == 0)
7888 				err += efunc(pc, "cannot write to %r0\n");
7889 			break;
7890 		case DIF_OP_SETS:
7891 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
7892 				err += efunc(pc, "invalid string ref %u\n",
7893 				    DIF_INSTR_STRING(instr));
7894 			}
7895 			if (rd >= nregs)
7896 				err += efunc(pc, "invalid register %u\n", rd);
7897 			if (rd == 0)
7898 				err += efunc(pc, "cannot write to %r0\n");
7899 			break;
7900 		case DIF_OP_LDGA:
7901 		case DIF_OP_LDTA:
7902 			if (r1 > DIF_VAR_ARRAY_MAX)
7903 				err += efunc(pc, "invalid array %u\n", r1);
7904 			if (r2 >= nregs)
7905 				err += efunc(pc, "invalid register %u\n", r2);
7906 			if (rd >= nregs)
7907 				err += efunc(pc, "invalid register %u\n", rd);
7908 			if (rd == 0)
7909 				err += efunc(pc, "cannot write to %r0\n");
7910 			break;
7911 		case DIF_OP_LDGS:
7912 		case DIF_OP_LDTS:
7913 		case DIF_OP_LDLS:
7914 		case DIF_OP_LDGAA:
7915 		case DIF_OP_LDTAA:
7916 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
7917 				err += efunc(pc, "invalid variable %u\n", v);
7918 			if (rd >= nregs)
7919 				err += efunc(pc, "invalid register %u\n", rd);
7920 			if (rd == 0)
7921 				err += efunc(pc, "cannot write to %r0\n");
7922 			break;
7923 		case DIF_OP_STGS:
7924 		case DIF_OP_STTS:
7925 		case DIF_OP_STLS:
7926 		case DIF_OP_STGAA:
7927 		case DIF_OP_STTAA:
7928 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
7929 				err += efunc(pc, "invalid variable %u\n", v);
7930 			if (rs >= nregs)
7931 				err += efunc(pc, "invalid register %u\n", rd);
7932 			break;
7933 		case DIF_OP_CALL:
7934 			if (subr > DIF_SUBR_MAX)
7935 				err += efunc(pc, "invalid subr %u\n", subr);
7936 			if (rd >= nregs)
7937 				err += efunc(pc, "invalid register %u\n", rd);
7938 			if (rd == 0)
7939 				err += efunc(pc, "cannot write to %r0\n");
7940 
7941 			if (subr == DIF_SUBR_COPYOUT ||
7942 			    subr == DIF_SUBR_COPYOUTSTR) {
7943 				dp->dtdo_destructive = 1;
7944 			}
7945 			break;
7946 		case DIF_OP_PUSHTR:
7947 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
7948 				err += efunc(pc, "invalid ref type %u\n", type);
7949 			if (r2 >= nregs)
7950 				err += efunc(pc, "invalid register %u\n", r2);
7951 			if (rs >= nregs)
7952 				err += efunc(pc, "invalid register %u\n", rs);
7953 			break;
7954 		case DIF_OP_PUSHTV:
7955 			if (type != DIF_TYPE_CTF)
7956 				err += efunc(pc, "invalid val type %u\n", type);
7957 			if (r2 >= nregs)
7958 				err += efunc(pc, "invalid register %u\n", r2);
7959 			if (rs >= nregs)
7960 				err += efunc(pc, "invalid register %u\n", rs);
7961 			break;
7962 		default:
7963 			err += efunc(pc, "invalid opcode %u\n",
7964 			    DIF_INSTR_OP(instr));
7965 		}
7966 	}
7967 
7968 	if (dp->dtdo_len != 0 &&
7969 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
7970 		err += efunc(dp->dtdo_len - 1,
7971 		    "expected 'ret' as last DIF instruction\n");
7972 	}
7973 
7974 	if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF)) {
7975 		/*
7976 		 * If we're not returning by reference, the size must be either
7977 		 * 0 or the size of one of the base types.
7978 		 */
7979 		switch (dp->dtdo_rtype.dtdt_size) {
7980 		case 0:
7981 		case sizeof (uint8_t):
7982 		case sizeof (uint16_t):
7983 		case sizeof (uint32_t):
7984 		case sizeof (uint64_t):
7985 			break;
7986 
7987 		default:
7988 			err += efunc(dp->dtdo_len - 1, "bad return size");
7989 		}
7990 	}
7991 
7992 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
7993 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
7994 		dtrace_diftype_t *vt, *et;
7995 		uint_t id, ndx;
7996 
7997 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
7998 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
7999 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
8000 			err += efunc(i, "unrecognized variable scope %d\n",
8001 			    v->dtdv_scope);
8002 			break;
8003 		}
8004 
8005 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
8006 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
8007 			err += efunc(i, "unrecognized variable type %d\n",
8008 			    v->dtdv_kind);
8009 			break;
8010 		}
8011 
8012 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
8013 			err += efunc(i, "%d exceeds variable id limit\n", id);
8014 			break;
8015 		}
8016 
8017 		if (id < DIF_VAR_OTHER_UBASE)
8018 			continue;
8019 
8020 		/*
8021 		 * For user-defined variables, we need to check that this
8022 		 * definition is identical to any previous definition that we
8023 		 * encountered.
8024 		 */
8025 		ndx = id - DIF_VAR_OTHER_UBASE;
8026 
8027 		switch (v->dtdv_scope) {
8028 		case DIFV_SCOPE_GLOBAL:
8029 			if (ndx < vstate->dtvs_nglobals) {
8030 				dtrace_statvar_t *svar;
8031 
8032 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
8033 					existing = &svar->dtsv_var;
8034 			}
8035 
8036 			break;
8037 
8038 		case DIFV_SCOPE_THREAD:
8039 			if (ndx < vstate->dtvs_ntlocals)
8040 				existing = &vstate->dtvs_tlocals[ndx];
8041 			break;
8042 
8043 		case DIFV_SCOPE_LOCAL:
8044 			if (ndx < vstate->dtvs_nlocals) {
8045 				dtrace_statvar_t *svar;
8046 
8047 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
8048 					existing = &svar->dtsv_var;
8049 			}
8050 
8051 			break;
8052 		}
8053 
8054 		vt = &v->dtdv_type;
8055 
8056 		if (vt->dtdt_flags & DIF_TF_BYREF) {
8057 			if (vt->dtdt_size == 0) {
8058 				err += efunc(i, "zero-sized variable\n");
8059 				break;
8060 			}
8061 
8062 			if (v->dtdv_scope == DIFV_SCOPE_GLOBAL &&
8063 			    vt->dtdt_size > dtrace_global_maxsize) {
8064 				err += efunc(i, "oversized by-ref global\n");
8065 				break;
8066 			}
8067 		}
8068 
8069 		if (existing == NULL || existing->dtdv_id == 0)
8070 			continue;
8071 
8072 		ASSERT(existing->dtdv_id == v->dtdv_id);
8073 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
8074 
8075 		if (existing->dtdv_kind != v->dtdv_kind)
8076 			err += efunc(i, "%d changed variable kind\n", id);
8077 
8078 		et = &existing->dtdv_type;
8079 
8080 		if (vt->dtdt_flags != et->dtdt_flags) {
8081 			err += efunc(i, "%d changed variable type flags\n", id);
8082 			break;
8083 		}
8084 
8085 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
8086 			err += efunc(i, "%d changed variable type size\n", id);
8087 			break;
8088 		}
8089 	}
8090 
8091 	return (err);
8092 }
8093 
8094 /*
8095  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
8096  * are much more constrained than normal DIFOs.  Specifically, they may
8097  * not:
8098  *
8099  * 1. Make calls to subroutines other than copyin(), copyinstr() or
8100  *    miscellaneous string routines
8101  * 2. Access DTrace variables other than the args[] array, and the
8102  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
8103  * 3. Have thread-local variables.
8104  * 4. Have dynamic variables.
8105  */
8106 static int
8107 dtrace_difo_validate_helper(dtrace_difo_t *dp)
8108 {
8109 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
8110 	int err = 0;
8111 	uint_t pc;
8112 
8113 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8114 		dif_instr_t instr = dp->dtdo_buf[pc];
8115 
8116 		uint_t v = DIF_INSTR_VAR(instr);
8117 		uint_t subr = DIF_INSTR_SUBR(instr);
8118 		uint_t op = DIF_INSTR_OP(instr);
8119 
8120 		switch (op) {
8121 		case DIF_OP_OR:
8122 		case DIF_OP_XOR:
8123 		case DIF_OP_AND:
8124 		case DIF_OP_SLL:
8125 		case DIF_OP_SRL:
8126 		case DIF_OP_SRA:
8127 		case DIF_OP_SUB:
8128 		case DIF_OP_ADD:
8129 		case DIF_OP_MUL:
8130 		case DIF_OP_SDIV:
8131 		case DIF_OP_UDIV:
8132 		case DIF_OP_SREM:
8133 		case DIF_OP_UREM:
8134 		case DIF_OP_COPYS:
8135 		case DIF_OP_NOT:
8136 		case DIF_OP_MOV:
8137 		case DIF_OP_RLDSB:
8138 		case DIF_OP_RLDSH:
8139 		case DIF_OP_RLDSW:
8140 		case DIF_OP_RLDUB:
8141 		case DIF_OP_RLDUH:
8142 		case DIF_OP_RLDUW:
8143 		case DIF_OP_RLDX:
8144 		case DIF_OP_ULDSB:
8145 		case DIF_OP_ULDSH:
8146 		case DIF_OP_ULDSW:
8147 		case DIF_OP_ULDUB:
8148 		case DIF_OP_ULDUH:
8149 		case DIF_OP_ULDUW:
8150 		case DIF_OP_ULDX:
8151 		case DIF_OP_STB:
8152 		case DIF_OP_STH:
8153 		case DIF_OP_STW:
8154 		case DIF_OP_STX:
8155 		case DIF_OP_ALLOCS:
8156 		case DIF_OP_CMP:
8157 		case DIF_OP_SCMP:
8158 		case DIF_OP_TST:
8159 		case DIF_OP_BA:
8160 		case DIF_OP_BE:
8161 		case DIF_OP_BNE:
8162 		case DIF_OP_BG:
8163 		case DIF_OP_BGU:
8164 		case DIF_OP_BGE:
8165 		case DIF_OP_BGEU:
8166 		case DIF_OP_BL:
8167 		case DIF_OP_BLU:
8168 		case DIF_OP_BLE:
8169 		case DIF_OP_BLEU:
8170 		case DIF_OP_RET:
8171 		case DIF_OP_NOP:
8172 		case DIF_OP_POPTS:
8173 		case DIF_OP_FLUSHTS:
8174 		case DIF_OP_SETX:
8175 		case DIF_OP_SETS:
8176 		case DIF_OP_LDGA:
8177 		case DIF_OP_LDLS:
8178 		case DIF_OP_STGS:
8179 		case DIF_OP_STLS:
8180 		case DIF_OP_PUSHTR:
8181 		case DIF_OP_PUSHTV:
8182 			break;
8183 
8184 		case DIF_OP_LDGS:
8185 			if (v >= DIF_VAR_OTHER_UBASE)
8186 				break;
8187 
8188 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
8189 				break;
8190 
8191 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
8192 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
8193 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
8194 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
8195 				break;
8196 
8197 			err += efunc(pc, "illegal variable %u\n", v);
8198 			break;
8199 
8200 		case DIF_OP_LDTA:
8201 		case DIF_OP_LDTS:
8202 		case DIF_OP_LDGAA:
8203 		case DIF_OP_LDTAA:
8204 			err += efunc(pc, "illegal dynamic variable load\n");
8205 			break;
8206 
8207 		case DIF_OP_STTS:
8208 		case DIF_OP_STGAA:
8209 		case DIF_OP_STTAA:
8210 			err += efunc(pc, "illegal dynamic variable store\n");
8211 			break;
8212 
8213 		case DIF_OP_CALL:
8214 			if (subr == DIF_SUBR_ALLOCA ||
8215 			    subr == DIF_SUBR_BCOPY ||
8216 			    subr == DIF_SUBR_COPYIN ||
8217 			    subr == DIF_SUBR_COPYINTO ||
8218 			    subr == DIF_SUBR_COPYINSTR ||
8219 			    subr == DIF_SUBR_INDEX ||
8220 			    subr == DIF_SUBR_INET_NTOA ||
8221 			    subr == DIF_SUBR_INET_NTOA6 ||
8222 			    subr == DIF_SUBR_INET_NTOP ||
8223 			    subr == DIF_SUBR_LLTOSTR ||
8224 			    subr == DIF_SUBR_RINDEX ||
8225 			    subr == DIF_SUBR_STRCHR ||
8226 			    subr == DIF_SUBR_STRJOIN ||
8227 			    subr == DIF_SUBR_STRRCHR ||
8228 			    subr == DIF_SUBR_STRSTR ||
8229 			    subr == DIF_SUBR_HTONS ||
8230 			    subr == DIF_SUBR_HTONL ||
8231 			    subr == DIF_SUBR_HTONLL ||
8232 			    subr == DIF_SUBR_NTOHS ||
8233 			    subr == DIF_SUBR_NTOHL ||
8234 			    subr == DIF_SUBR_NTOHLL)
8235 				break;
8236 
8237 			err += efunc(pc, "invalid subr %u\n", subr);
8238 			break;
8239 
8240 		default:
8241 			err += efunc(pc, "invalid opcode %u\n",
8242 			    DIF_INSTR_OP(instr));
8243 		}
8244 	}
8245 
8246 	return (err);
8247 }
8248 
8249 /*
8250  * Returns 1 if the expression in the DIF object can be cached on a per-thread
8251  * basis; 0 if not.
8252  */
8253 static int
8254 dtrace_difo_cacheable(dtrace_difo_t *dp)
8255 {
8256 	int i;
8257 
8258 	if (dp == NULL)
8259 		return (0);
8260 
8261 	for (i = 0; i < dp->dtdo_varlen; i++) {
8262 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8263 
8264 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
8265 			continue;
8266 
8267 		switch (v->dtdv_id) {
8268 		case DIF_VAR_CURTHREAD:
8269 		case DIF_VAR_PID:
8270 		case DIF_VAR_TID:
8271 		case DIF_VAR_EXECNAME:
8272 		case DIF_VAR_ZONENAME:
8273 			break;
8274 
8275 		default:
8276 			return (0);
8277 		}
8278 	}
8279 
8280 	/*
8281 	 * This DIF object may be cacheable.  Now we need to look for any
8282 	 * array loading instructions, any memory loading instructions, or
8283 	 * any stores to thread-local variables.
8284 	 */
8285 	for (i = 0; i < dp->dtdo_len; i++) {
8286 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
8287 
8288 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
8289 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
8290 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
8291 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
8292 			return (0);
8293 	}
8294 
8295 	return (1);
8296 }
8297 
8298 static void
8299 dtrace_difo_hold(dtrace_difo_t *dp)
8300 {
8301 	int i;
8302 
8303 	ASSERT(MUTEX_HELD(&dtrace_lock));
8304 
8305 	dp->dtdo_refcnt++;
8306 	ASSERT(dp->dtdo_refcnt != 0);
8307 
8308 	/*
8309 	 * We need to check this DIF object for references to the variable
8310 	 * DIF_VAR_VTIMESTAMP.
8311 	 */
8312 	for (i = 0; i < dp->dtdo_varlen; i++) {
8313 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8314 
8315 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8316 			continue;
8317 
8318 		if (dtrace_vtime_references++ == 0)
8319 			dtrace_vtime_enable();
8320 	}
8321 }
8322 
8323 /*
8324  * This routine calculates the dynamic variable chunksize for a given DIF
8325  * object.  The calculation is not fool-proof, and can probably be tricked by
8326  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
8327  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
8328  * if a dynamic variable size exceeds the chunksize.
8329  */
8330 static void
8331 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8332 {
8333 	uint64_t sval;
8334 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
8335 	const dif_instr_t *text = dp->dtdo_buf;
8336 	uint_t pc, srd = 0;
8337 	uint_t ttop = 0;
8338 	size_t size, ksize;
8339 	uint_t id, i;
8340 
8341 	for (pc = 0; pc < dp->dtdo_len; pc++) {
8342 		dif_instr_t instr = text[pc];
8343 		uint_t op = DIF_INSTR_OP(instr);
8344 		uint_t rd = DIF_INSTR_RD(instr);
8345 		uint_t r1 = DIF_INSTR_R1(instr);
8346 		uint_t nkeys = 0;
8347 		uchar_t scope;
8348 
8349 		dtrace_key_t *key = tupregs;
8350 
8351 		switch (op) {
8352 		case DIF_OP_SETX:
8353 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
8354 			srd = rd;
8355 			continue;
8356 
8357 		case DIF_OP_STTS:
8358 			key = &tupregs[DIF_DTR_NREGS];
8359 			key[0].dttk_size = 0;
8360 			key[1].dttk_size = 0;
8361 			nkeys = 2;
8362 			scope = DIFV_SCOPE_THREAD;
8363 			break;
8364 
8365 		case DIF_OP_STGAA:
8366 		case DIF_OP_STTAA:
8367 			nkeys = ttop;
8368 
8369 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
8370 				key[nkeys++].dttk_size = 0;
8371 
8372 			key[nkeys++].dttk_size = 0;
8373 
8374 			if (op == DIF_OP_STTAA) {
8375 				scope = DIFV_SCOPE_THREAD;
8376 			} else {
8377 				scope = DIFV_SCOPE_GLOBAL;
8378 			}
8379 
8380 			break;
8381 
8382 		case DIF_OP_PUSHTR:
8383 			if (ttop == DIF_DTR_NREGS)
8384 				return;
8385 
8386 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
8387 				/*
8388 				 * If the register for the size of the "pushtr"
8389 				 * is %r0 (or the value is 0) and the type is
8390 				 * a string, we'll use the system-wide default
8391 				 * string size.
8392 				 */
8393 				tupregs[ttop++].dttk_size =
8394 				    dtrace_strsize_default;
8395 			} else {
8396 				if (srd == 0)
8397 					return;
8398 
8399 				tupregs[ttop++].dttk_size = sval;
8400 			}
8401 
8402 			break;
8403 
8404 		case DIF_OP_PUSHTV:
8405 			if (ttop == DIF_DTR_NREGS)
8406 				return;
8407 
8408 			tupregs[ttop++].dttk_size = 0;
8409 			break;
8410 
8411 		case DIF_OP_FLUSHTS:
8412 			ttop = 0;
8413 			break;
8414 
8415 		case DIF_OP_POPTS:
8416 			if (ttop != 0)
8417 				ttop--;
8418 			break;
8419 		}
8420 
8421 		sval = 0;
8422 		srd = 0;
8423 
8424 		if (nkeys == 0)
8425 			continue;
8426 
8427 		/*
8428 		 * We have a dynamic variable allocation; calculate its size.
8429 		 */
8430 		for (ksize = 0, i = 0; i < nkeys; i++)
8431 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
8432 
8433 		size = sizeof (dtrace_dynvar_t);
8434 		size += sizeof (dtrace_key_t) * (nkeys - 1);
8435 		size += ksize;
8436 
8437 		/*
8438 		 * Now we need to determine the size of the stored data.
8439 		 */
8440 		id = DIF_INSTR_VAR(instr);
8441 
8442 		for (i = 0; i < dp->dtdo_varlen; i++) {
8443 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
8444 
8445 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
8446 				size += v->dtdv_type.dtdt_size;
8447 				break;
8448 			}
8449 		}
8450 
8451 		if (i == dp->dtdo_varlen)
8452 			return;
8453 
8454 		/*
8455 		 * We have the size.  If this is larger than the chunk size
8456 		 * for our dynamic variable state, reset the chunk size.
8457 		 */
8458 		size = P2ROUNDUP(size, sizeof (uint64_t));
8459 
8460 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
8461 			vstate->dtvs_dynvars.dtds_chunksize = size;
8462 	}
8463 }
8464 
8465 static void
8466 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8467 {
8468 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
8469 	uint_t id;
8470 
8471 	ASSERT(MUTEX_HELD(&dtrace_lock));
8472 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
8473 
8474 	for (i = 0; i < dp->dtdo_varlen; i++) {
8475 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8476 		dtrace_statvar_t *svar, ***svarp;
8477 		size_t dsize = 0;
8478 		uint8_t scope = v->dtdv_scope;
8479 		int *np;
8480 
8481 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8482 			continue;
8483 
8484 		id -= DIF_VAR_OTHER_UBASE;
8485 
8486 		switch (scope) {
8487 		case DIFV_SCOPE_THREAD:
8488 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
8489 				dtrace_difv_t *tlocals;
8490 
8491 				if ((ntlocals = (otlocals << 1)) == 0)
8492 					ntlocals = 1;
8493 
8494 				osz = otlocals * sizeof (dtrace_difv_t);
8495 				nsz = ntlocals * sizeof (dtrace_difv_t);
8496 
8497 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
8498 
8499 				if (osz != 0) {
8500 					bcopy(vstate->dtvs_tlocals,
8501 					    tlocals, osz);
8502 					kmem_free(vstate->dtvs_tlocals, osz);
8503 				}
8504 
8505 				vstate->dtvs_tlocals = tlocals;
8506 				vstate->dtvs_ntlocals = ntlocals;
8507 			}
8508 
8509 			vstate->dtvs_tlocals[id] = *v;
8510 			continue;
8511 
8512 		case DIFV_SCOPE_LOCAL:
8513 			np = &vstate->dtvs_nlocals;
8514 			svarp = &vstate->dtvs_locals;
8515 
8516 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8517 				dsize = NCPU * (v->dtdv_type.dtdt_size +
8518 				    sizeof (uint64_t));
8519 			else
8520 				dsize = NCPU * sizeof (uint64_t);
8521 
8522 			break;
8523 
8524 		case DIFV_SCOPE_GLOBAL:
8525 			np = &vstate->dtvs_nglobals;
8526 			svarp = &vstate->dtvs_globals;
8527 
8528 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
8529 				dsize = v->dtdv_type.dtdt_size +
8530 				    sizeof (uint64_t);
8531 
8532 			break;
8533 
8534 		default:
8535 			ASSERT(0);
8536 		}
8537 
8538 		while (id >= (oldsvars = *np)) {
8539 			dtrace_statvar_t **statics;
8540 			int newsvars, oldsize, newsize;
8541 
8542 			if ((newsvars = (oldsvars << 1)) == 0)
8543 				newsvars = 1;
8544 
8545 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
8546 			newsize = newsvars * sizeof (dtrace_statvar_t *);
8547 
8548 			statics = kmem_zalloc(newsize, KM_SLEEP);
8549 
8550 			if (oldsize != 0) {
8551 				bcopy(*svarp, statics, oldsize);
8552 				kmem_free(*svarp, oldsize);
8553 			}
8554 
8555 			*svarp = statics;
8556 			*np = newsvars;
8557 		}
8558 
8559 		if ((svar = (*svarp)[id]) == NULL) {
8560 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
8561 			svar->dtsv_var = *v;
8562 
8563 			if ((svar->dtsv_size = dsize) != 0) {
8564 				svar->dtsv_data = (uint64_t)(uintptr_t)
8565 				    kmem_zalloc(dsize, KM_SLEEP);
8566 			}
8567 
8568 			(*svarp)[id] = svar;
8569 		}
8570 
8571 		svar->dtsv_refcnt++;
8572 	}
8573 
8574 	dtrace_difo_chunksize(dp, vstate);
8575 	dtrace_difo_hold(dp);
8576 }
8577 
8578 static dtrace_difo_t *
8579 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8580 {
8581 	dtrace_difo_t *new;
8582 	size_t sz;
8583 
8584 	ASSERT(dp->dtdo_buf != NULL);
8585 	ASSERT(dp->dtdo_refcnt != 0);
8586 
8587 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
8588 
8589 	ASSERT(dp->dtdo_buf != NULL);
8590 	sz = dp->dtdo_len * sizeof (dif_instr_t);
8591 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
8592 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
8593 	new->dtdo_len = dp->dtdo_len;
8594 
8595 	if (dp->dtdo_strtab != NULL) {
8596 		ASSERT(dp->dtdo_strlen != 0);
8597 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
8598 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
8599 		new->dtdo_strlen = dp->dtdo_strlen;
8600 	}
8601 
8602 	if (dp->dtdo_inttab != NULL) {
8603 		ASSERT(dp->dtdo_intlen != 0);
8604 		sz = dp->dtdo_intlen * sizeof (uint64_t);
8605 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
8606 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
8607 		new->dtdo_intlen = dp->dtdo_intlen;
8608 	}
8609 
8610 	if (dp->dtdo_vartab != NULL) {
8611 		ASSERT(dp->dtdo_varlen != 0);
8612 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
8613 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
8614 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
8615 		new->dtdo_varlen = dp->dtdo_varlen;
8616 	}
8617 
8618 	dtrace_difo_init(new, vstate);
8619 	return (new);
8620 }
8621 
8622 static void
8623 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8624 {
8625 	int i;
8626 
8627 	ASSERT(dp->dtdo_refcnt == 0);
8628 
8629 	for (i = 0; i < dp->dtdo_varlen; i++) {
8630 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8631 		dtrace_statvar_t *svar, **svarp;
8632 		uint_t id;
8633 		uint8_t scope = v->dtdv_scope;
8634 		int *np;
8635 
8636 		switch (scope) {
8637 		case DIFV_SCOPE_THREAD:
8638 			continue;
8639 
8640 		case DIFV_SCOPE_LOCAL:
8641 			np = &vstate->dtvs_nlocals;
8642 			svarp = vstate->dtvs_locals;
8643 			break;
8644 
8645 		case DIFV_SCOPE_GLOBAL:
8646 			np = &vstate->dtvs_nglobals;
8647 			svarp = vstate->dtvs_globals;
8648 			break;
8649 
8650 		default:
8651 			ASSERT(0);
8652 		}
8653 
8654 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
8655 			continue;
8656 
8657 		id -= DIF_VAR_OTHER_UBASE;
8658 		ASSERT(id < *np);
8659 
8660 		svar = svarp[id];
8661 		ASSERT(svar != NULL);
8662 		ASSERT(svar->dtsv_refcnt > 0);
8663 
8664 		if (--svar->dtsv_refcnt > 0)
8665 			continue;
8666 
8667 		if (svar->dtsv_size != 0) {
8668 			ASSERT(svar->dtsv_data != NULL);
8669 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
8670 			    svar->dtsv_size);
8671 		}
8672 
8673 		kmem_free(svar, sizeof (dtrace_statvar_t));
8674 		svarp[id] = NULL;
8675 	}
8676 
8677 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
8678 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
8679 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
8680 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
8681 
8682 	kmem_free(dp, sizeof (dtrace_difo_t));
8683 }
8684 
8685 static void
8686 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
8687 {
8688 	int i;
8689 
8690 	ASSERT(MUTEX_HELD(&dtrace_lock));
8691 	ASSERT(dp->dtdo_refcnt != 0);
8692 
8693 	for (i = 0; i < dp->dtdo_varlen; i++) {
8694 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
8695 
8696 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
8697 			continue;
8698 
8699 		ASSERT(dtrace_vtime_references > 0);
8700 		if (--dtrace_vtime_references == 0)
8701 			dtrace_vtime_disable();
8702 	}
8703 
8704 	if (--dp->dtdo_refcnt == 0)
8705 		dtrace_difo_destroy(dp, vstate);
8706 }
8707 
8708 /*
8709  * DTrace Format Functions
8710  */
8711 static uint16_t
8712 dtrace_format_add(dtrace_state_t *state, char *str)
8713 {
8714 	char *fmt, **new;
8715 	uint16_t ndx, len = strlen(str) + 1;
8716 
8717 	fmt = kmem_zalloc(len, KM_SLEEP);
8718 	bcopy(str, fmt, len);
8719 
8720 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
8721 		if (state->dts_formats[ndx] == NULL) {
8722 			state->dts_formats[ndx] = fmt;
8723 			return (ndx + 1);
8724 		}
8725 	}
8726 
8727 	if (state->dts_nformats == USHRT_MAX) {
8728 		/*
8729 		 * This is only likely if a denial-of-service attack is being
8730 		 * attempted.  As such, it's okay to fail silently here.
8731 		 */
8732 		kmem_free(fmt, len);
8733 		return (0);
8734 	}
8735 
8736 	/*
8737 	 * For simplicity, we always resize the formats array to be exactly the
8738 	 * number of formats.
8739 	 */
8740 	ndx = state->dts_nformats++;
8741 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
8742 
8743 	if (state->dts_formats != NULL) {
8744 		ASSERT(ndx != 0);
8745 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
8746 		kmem_free(state->dts_formats, ndx * sizeof (char *));
8747 	}
8748 
8749 	state->dts_formats = new;
8750 	state->dts_formats[ndx] = fmt;
8751 
8752 	return (ndx + 1);
8753 }
8754 
8755 static void
8756 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
8757 {
8758 	char *fmt;
8759 
8760 	ASSERT(state->dts_formats != NULL);
8761 	ASSERT(format <= state->dts_nformats);
8762 	ASSERT(state->dts_formats[format - 1] != NULL);
8763 
8764 	fmt = state->dts_formats[format - 1];
8765 	kmem_free(fmt, strlen(fmt) + 1);
8766 	state->dts_formats[format - 1] = NULL;
8767 }
8768 
8769 static void
8770 dtrace_format_destroy(dtrace_state_t *state)
8771 {
8772 	int i;
8773 
8774 	if (state->dts_nformats == 0) {
8775 		ASSERT(state->dts_formats == NULL);
8776 		return;
8777 	}
8778 
8779 	ASSERT(state->dts_formats != NULL);
8780 
8781 	for (i = 0; i < state->dts_nformats; i++) {
8782 		char *fmt = state->dts_formats[i];
8783 
8784 		if (fmt == NULL)
8785 			continue;
8786 
8787 		kmem_free(fmt, strlen(fmt) + 1);
8788 	}
8789 
8790 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
8791 	state->dts_nformats = 0;
8792 	state->dts_formats = NULL;
8793 }
8794 
8795 /*
8796  * DTrace Predicate Functions
8797  */
8798 static dtrace_predicate_t *
8799 dtrace_predicate_create(dtrace_difo_t *dp)
8800 {
8801 	dtrace_predicate_t *pred;
8802 
8803 	ASSERT(MUTEX_HELD(&dtrace_lock));
8804 	ASSERT(dp->dtdo_refcnt != 0);
8805 
8806 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
8807 	pred->dtp_difo = dp;
8808 	pred->dtp_refcnt = 1;
8809 
8810 	if (!dtrace_difo_cacheable(dp))
8811 		return (pred);
8812 
8813 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
8814 		/*
8815 		 * This is only theoretically possible -- we have had 2^32
8816 		 * cacheable predicates on this machine.  We cannot allow any
8817 		 * more predicates to become cacheable:  as unlikely as it is,
8818 		 * there may be a thread caching a (now stale) predicate cache
8819 		 * ID. (N.B.: the temptation is being successfully resisted to
8820 		 * have this cmn_err() "Holy shit -- we executed this code!")
8821 		 */
8822 		return (pred);
8823 	}
8824 
8825 	pred->dtp_cacheid = dtrace_predcache_id++;
8826 
8827 	return (pred);
8828 }
8829 
8830 static void
8831 dtrace_predicate_hold(dtrace_predicate_t *pred)
8832 {
8833 	ASSERT(MUTEX_HELD(&dtrace_lock));
8834 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
8835 	ASSERT(pred->dtp_refcnt > 0);
8836 
8837 	pred->dtp_refcnt++;
8838 }
8839 
8840 static void
8841 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
8842 {
8843 	dtrace_difo_t *dp = pred->dtp_difo;
8844 
8845 	ASSERT(MUTEX_HELD(&dtrace_lock));
8846 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
8847 	ASSERT(pred->dtp_refcnt > 0);
8848 
8849 	if (--pred->dtp_refcnt == 0) {
8850 		dtrace_difo_release(pred->dtp_difo, vstate);
8851 		kmem_free(pred, sizeof (dtrace_predicate_t));
8852 	}
8853 }
8854 
8855 /*
8856  * DTrace Action Description Functions
8857  */
8858 static dtrace_actdesc_t *
8859 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
8860     uint64_t uarg, uint64_t arg)
8861 {
8862 	dtrace_actdesc_t *act;
8863 
8864 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != NULL &&
8865 	    arg >= KERNELBASE) || (arg == NULL && kind == DTRACEACT_PRINTA));
8866 
8867 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
8868 	act->dtad_kind = kind;
8869 	act->dtad_ntuple = ntuple;
8870 	act->dtad_uarg = uarg;
8871 	act->dtad_arg = arg;
8872 	act->dtad_refcnt = 1;
8873 
8874 	return (act);
8875 }
8876 
8877 static void
8878 dtrace_actdesc_hold(dtrace_actdesc_t *act)
8879 {
8880 	ASSERT(act->dtad_refcnt >= 1);
8881 	act->dtad_refcnt++;
8882 }
8883 
8884 static void
8885 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
8886 {
8887 	dtrace_actkind_t kind = act->dtad_kind;
8888 	dtrace_difo_t *dp;
8889 
8890 	ASSERT(act->dtad_refcnt >= 1);
8891 
8892 	if (--act->dtad_refcnt != 0)
8893 		return;
8894 
8895 	if ((dp = act->dtad_difo) != NULL)
8896 		dtrace_difo_release(dp, vstate);
8897 
8898 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
8899 		char *str = (char *)(uintptr_t)act->dtad_arg;
8900 
8901 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
8902 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
8903 
8904 		if (str != NULL)
8905 			kmem_free(str, strlen(str) + 1);
8906 	}
8907 
8908 	kmem_free(act, sizeof (dtrace_actdesc_t));
8909 }
8910 
8911 /*
8912  * DTrace ECB Functions
8913  */
8914 static dtrace_ecb_t *
8915 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
8916 {
8917 	dtrace_ecb_t *ecb;
8918 	dtrace_epid_t epid;
8919 
8920 	ASSERT(MUTEX_HELD(&dtrace_lock));
8921 
8922 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
8923 	ecb->dte_predicate = NULL;
8924 	ecb->dte_probe = probe;
8925 
8926 	/*
8927 	 * The default size is the size of the default action: recording
8928 	 * the epid.
8929 	 */
8930 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
8931 	ecb->dte_alignment = sizeof (dtrace_epid_t);
8932 
8933 	epid = state->dts_epid++;
8934 
8935 	if (epid - 1 >= state->dts_necbs) {
8936 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
8937 		int necbs = state->dts_necbs << 1;
8938 
8939 		ASSERT(epid == state->dts_necbs + 1);
8940 
8941 		if (necbs == 0) {
8942 			ASSERT(oecbs == NULL);
8943 			necbs = 1;
8944 		}
8945 
8946 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
8947 
8948 		if (oecbs != NULL)
8949 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
8950 
8951 		dtrace_membar_producer();
8952 		state->dts_ecbs = ecbs;
8953 
8954 		if (oecbs != NULL) {
8955 			/*
8956 			 * If this state is active, we must dtrace_sync()
8957 			 * before we can free the old dts_ecbs array:  we're
8958 			 * coming in hot, and there may be active ring
8959 			 * buffer processing (which indexes into the dts_ecbs
8960 			 * array) on another CPU.
8961 			 */
8962 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
8963 				dtrace_sync();
8964 
8965 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
8966 		}
8967 
8968 		dtrace_membar_producer();
8969 		state->dts_necbs = necbs;
8970 	}
8971 
8972 	ecb->dte_state = state;
8973 
8974 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
8975 	dtrace_membar_producer();
8976 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
8977 
8978 	return (ecb);
8979 }
8980 
8981 static void
8982 dtrace_ecb_enable(dtrace_ecb_t *ecb)
8983 {
8984 	dtrace_probe_t *probe = ecb->dte_probe;
8985 
8986 	ASSERT(MUTEX_HELD(&cpu_lock));
8987 	ASSERT(MUTEX_HELD(&dtrace_lock));
8988 	ASSERT(ecb->dte_next == NULL);
8989 
8990 	if (probe == NULL) {
8991 		/*
8992 		 * This is the NULL probe -- there's nothing to do.
8993 		 */
8994 		return;
8995 	}
8996 
8997 	if (probe->dtpr_ecb == NULL) {
8998 		dtrace_provider_t *prov = probe->dtpr_provider;
8999 
9000 		/*
9001 		 * We're the first ECB on this probe.
9002 		 */
9003 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
9004 
9005 		if (ecb->dte_predicate != NULL)
9006 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
9007 
9008 		prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
9009 		    probe->dtpr_id, probe->dtpr_arg);
9010 	} else {
9011 		/*
9012 		 * This probe is already active.  Swing the last pointer to
9013 		 * point to the new ECB, and issue a dtrace_sync() to assure
9014 		 * that all CPUs have seen the change.
9015 		 */
9016 		ASSERT(probe->dtpr_ecb_last != NULL);
9017 		probe->dtpr_ecb_last->dte_next = ecb;
9018 		probe->dtpr_ecb_last = ecb;
9019 		probe->dtpr_predcache = 0;
9020 
9021 		dtrace_sync();
9022 	}
9023 }
9024 
9025 static void
9026 dtrace_ecb_resize(dtrace_ecb_t *ecb)
9027 {
9028 	uint32_t maxalign = sizeof (dtrace_epid_t);
9029 	uint32_t align = sizeof (uint8_t), offs, diff;
9030 	dtrace_action_t *act;
9031 	int wastuple = 0;
9032 	uint32_t aggbase = UINT32_MAX;
9033 	dtrace_state_t *state = ecb->dte_state;
9034 
9035 	/*
9036 	 * If we record anything, we always record the epid.  (And we always
9037 	 * record it first.)
9038 	 */
9039 	offs = sizeof (dtrace_epid_t);
9040 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_epid_t);
9041 
9042 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9043 		dtrace_recdesc_t *rec = &act->dta_rec;
9044 
9045 		if ((align = rec->dtrd_alignment) > maxalign)
9046 			maxalign = align;
9047 
9048 		if (!wastuple && act->dta_intuple) {
9049 			/*
9050 			 * This is the first record in a tuple.  Align the
9051 			 * offset to be at offset 4 in an 8-byte aligned
9052 			 * block.
9053 			 */
9054 			diff = offs + sizeof (dtrace_aggid_t);
9055 
9056 			if (diff = (diff & (sizeof (uint64_t) - 1)))
9057 				offs += sizeof (uint64_t) - diff;
9058 
9059 			aggbase = offs - sizeof (dtrace_aggid_t);
9060 			ASSERT(!(aggbase & (sizeof (uint64_t) - 1)));
9061 		}
9062 
9063 		/*LINTED*/
9064 		if (rec->dtrd_size != 0 && (diff = (offs & (align - 1)))) {
9065 			/*
9066 			 * The current offset is not properly aligned; align it.
9067 			 */
9068 			offs += align - diff;
9069 		}
9070 
9071 		rec->dtrd_offset = offs;
9072 
9073 		if (offs + rec->dtrd_size > ecb->dte_needed) {
9074 			ecb->dte_needed = offs + rec->dtrd_size;
9075 
9076 			if (ecb->dte_needed > state->dts_needed)
9077 				state->dts_needed = ecb->dte_needed;
9078 		}
9079 
9080 		if (DTRACEACT_ISAGG(act->dta_kind)) {
9081 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9082 			dtrace_action_t *first = agg->dtag_first, *prev;
9083 
9084 			ASSERT(rec->dtrd_size != 0 && first != NULL);
9085 			ASSERT(wastuple);
9086 			ASSERT(aggbase != UINT32_MAX);
9087 
9088 			agg->dtag_base = aggbase;
9089 
9090 			while ((prev = first->dta_prev) != NULL &&
9091 			    DTRACEACT_ISAGG(prev->dta_kind)) {
9092 				agg = (dtrace_aggregation_t *)prev;
9093 				first = agg->dtag_first;
9094 			}
9095 
9096 			if (prev != NULL) {
9097 				offs = prev->dta_rec.dtrd_offset +
9098 				    prev->dta_rec.dtrd_size;
9099 			} else {
9100 				offs = sizeof (dtrace_epid_t);
9101 			}
9102 			wastuple = 0;
9103 		} else {
9104 			if (!act->dta_intuple)
9105 				ecb->dte_size = offs + rec->dtrd_size;
9106 
9107 			offs += rec->dtrd_size;
9108 		}
9109 
9110 		wastuple = act->dta_intuple;
9111 	}
9112 
9113 	if ((act = ecb->dte_action) != NULL &&
9114 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
9115 	    ecb->dte_size == sizeof (dtrace_epid_t)) {
9116 		/*
9117 		 * If the size is still sizeof (dtrace_epid_t), then all
9118 		 * actions store no data; set the size to 0.
9119 		 */
9120 		ecb->dte_alignment = maxalign;
9121 		ecb->dte_size = 0;
9122 
9123 		/*
9124 		 * If the needed space is still sizeof (dtrace_epid_t), then
9125 		 * all actions need no additional space; set the needed
9126 		 * size to 0.
9127 		 */
9128 		if (ecb->dte_needed == sizeof (dtrace_epid_t))
9129 			ecb->dte_needed = 0;
9130 
9131 		return;
9132 	}
9133 
9134 	/*
9135 	 * Set our alignment, and make sure that the dte_size and dte_needed
9136 	 * are aligned to the size of an EPID.
9137 	 */
9138 	ecb->dte_alignment = maxalign;
9139 	ecb->dte_size = (ecb->dte_size + (sizeof (dtrace_epid_t) - 1)) &
9140 	    ~(sizeof (dtrace_epid_t) - 1);
9141 	ecb->dte_needed = (ecb->dte_needed + (sizeof (dtrace_epid_t) - 1)) &
9142 	    ~(sizeof (dtrace_epid_t) - 1);
9143 	ASSERT(ecb->dte_size <= ecb->dte_needed);
9144 }
9145 
9146 static dtrace_action_t *
9147 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9148 {
9149 	dtrace_aggregation_t *agg;
9150 	size_t size = sizeof (uint64_t);
9151 	int ntuple = desc->dtad_ntuple;
9152 	dtrace_action_t *act;
9153 	dtrace_recdesc_t *frec;
9154 	dtrace_aggid_t aggid;
9155 	dtrace_state_t *state = ecb->dte_state;
9156 
9157 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
9158 	agg->dtag_ecb = ecb;
9159 
9160 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
9161 
9162 	switch (desc->dtad_kind) {
9163 	case DTRACEAGG_MIN:
9164 		agg->dtag_initial = UINT64_MAX;
9165 		agg->dtag_aggregate = dtrace_aggregate_min;
9166 		break;
9167 
9168 	case DTRACEAGG_MAX:
9169 		agg->dtag_aggregate = dtrace_aggregate_max;
9170 		break;
9171 
9172 	case DTRACEAGG_COUNT:
9173 		agg->dtag_aggregate = dtrace_aggregate_count;
9174 		break;
9175 
9176 	case DTRACEAGG_QUANTIZE:
9177 		agg->dtag_aggregate = dtrace_aggregate_quantize;
9178 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
9179 		    sizeof (uint64_t);
9180 		break;
9181 
9182 	case DTRACEAGG_LQUANTIZE: {
9183 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
9184 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
9185 
9186 		agg->dtag_initial = desc->dtad_arg;
9187 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
9188 
9189 		if (step == 0 || levels == 0)
9190 			goto err;
9191 
9192 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
9193 		break;
9194 	}
9195 
9196 	case DTRACEAGG_AVG:
9197 		agg->dtag_aggregate = dtrace_aggregate_avg;
9198 		size = sizeof (uint64_t) * 2;
9199 		break;
9200 
9201 	case DTRACEAGG_SUM:
9202 		agg->dtag_aggregate = dtrace_aggregate_sum;
9203 		break;
9204 
9205 	default:
9206 		goto err;
9207 	}
9208 
9209 	agg->dtag_action.dta_rec.dtrd_size = size;
9210 
9211 	if (ntuple == 0)
9212 		goto err;
9213 
9214 	/*
9215 	 * We must make sure that we have enough actions for the n-tuple.
9216 	 */
9217 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
9218 		if (DTRACEACT_ISAGG(act->dta_kind))
9219 			break;
9220 
9221 		if (--ntuple == 0) {
9222 			/*
9223 			 * This is the action with which our n-tuple begins.
9224 			 */
9225 			agg->dtag_first = act;
9226 			goto success;
9227 		}
9228 	}
9229 
9230 	/*
9231 	 * This n-tuple is short by ntuple elements.  Return failure.
9232 	 */
9233 	ASSERT(ntuple != 0);
9234 err:
9235 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9236 	return (NULL);
9237 
9238 success:
9239 	/*
9240 	 * If the last action in the tuple has a size of zero, it's actually
9241 	 * an expression argument for the aggregating action.
9242 	 */
9243 	ASSERT(ecb->dte_action_last != NULL);
9244 	act = ecb->dte_action_last;
9245 
9246 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
9247 		ASSERT(act->dta_difo != NULL);
9248 
9249 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
9250 			agg->dtag_hasarg = 1;
9251 	}
9252 
9253 	/*
9254 	 * We need to allocate an id for this aggregation.
9255 	 */
9256 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
9257 	    VM_BESTFIT | VM_SLEEP);
9258 
9259 	if (aggid - 1 >= state->dts_naggregations) {
9260 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
9261 		dtrace_aggregation_t **aggs;
9262 		int naggs = state->dts_naggregations << 1;
9263 		int onaggs = state->dts_naggregations;
9264 
9265 		ASSERT(aggid == state->dts_naggregations + 1);
9266 
9267 		if (naggs == 0) {
9268 			ASSERT(oaggs == NULL);
9269 			naggs = 1;
9270 		}
9271 
9272 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
9273 
9274 		if (oaggs != NULL) {
9275 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
9276 			kmem_free(oaggs, onaggs * sizeof (*aggs));
9277 		}
9278 
9279 		state->dts_aggregations = aggs;
9280 		state->dts_naggregations = naggs;
9281 	}
9282 
9283 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
9284 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
9285 
9286 	frec = &agg->dtag_first->dta_rec;
9287 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
9288 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
9289 
9290 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
9291 		ASSERT(!act->dta_intuple);
9292 		act->dta_intuple = 1;
9293 	}
9294 
9295 	return (&agg->dtag_action);
9296 }
9297 
9298 static void
9299 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
9300 {
9301 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
9302 	dtrace_state_t *state = ecb->dte_state;
9303 	dtrace_aggid_t aggid = agg->dtag_id;
9304 
9305 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
9306 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
9307 
9308 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
9309 	state->dts_aggregations[aggid - 1] = NULL;
9310 
9311 	kmem_free(agg, sizeof (dtrace_aggregation_t));
9312 }
9313 
9314 static int
9315 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
9316 {
9317 	dtrace_action_t *action, *last;
9318 	dtrace_difo_t *dp = desc->dtad_difo;
9319 	uint32_t size = 0, align = sizeof (uint8_t), mask;
9320 	uint16_t format = 0;
9321 	dtrace_recdesc_t *rec;
9322 	dtrace_state_t *state = ecb->dte_state;
9323 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
9324 	uint64_t arg = desc->dtad_arg;
9325 
9326 	ASSERT(MUTEX_HELD(&dtrace_lock));
9327 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
9328 
9329 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
9330 		/*
9331 		 * If this is an aggregating action, there must be neither
9332 		 * a speculate nor a commit on the action chain.
9333 		 */
9334 		dtrace_action_t *act;
9335 
9336 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
9337 			if (act->dta_kind == DTRACEACT_COMMIT)
9338 				return (EINVAL);
9339 
9340 			if (act->dta_kind == DTRACEACT_SPECULATE)
9341 				return (EINVAL);
9342 		}
9343 
9344 		action = dtrace_ecb_aggregation_create(ecb, desc);
9345 
9346 		if (action == NULL)
9347 			return (EINVAL);
9348 	} else {
9349 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
9350 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
9351 		    dp != NULL && dp->dtdo_destructive)) {
9352 			state->dts_destructive = 1;
9353 		}
9354 
9355 		switch (desc->dtad_kind) {
9356 		case DTRACEACT_PRINTF:
9357 		case DTRACEACT_PRINTA:
9358 		case DTRACEACT_SYSTEM:
9359 		case DTRACEACT_FREOPEN:
9360 			/*
9361 			 * We know that our arg is a string -- turn it into a
9362 			 * format.
9363 			 */
9364 			if (arg == NULL) {
9365 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA);
9366 				format = 0;
9367 			} else {
9368 				ASSERT(arg != NULL);
9369 				ASSERT(arg > KERNELBASE);
9370 				format = dtrace_format_add(state,
9371 				    (char *)(uintptr_t)arg);
9372 			}
9373 
9374 			/*FALLTHROUGH*/
9375 		case DTRACEACT_LIBACT:
9376 		case DTRACEACT_DIFEXPR:
9377 			if (dp == NULL)
9378 				return (EINVAL);
9379 
9380 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
9381 				break;
9382 
9383 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
9384 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9385 					return (EINVAL);
9386 
9387 				size = opt[DTRACEOPT_STRSIZE];
9388 			}
9389 
9390 			break;
9391 
9392 		case DTRACEACT_STACK:
9393 			if ((nframes = arg) == 0) {
9394 				nframes = opt[DTRACEOPT_STACKFRAMES];
9395 				ASSERT(nframes > 0);
9396 				arg = nframes;
9397 			}
9398 
9399 			size = nframes * sizeof (pc_t);
9400 			break;
9401 
9402 		case DTRACEACT_JSTACK:
9403 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
9404 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
9405 
9406 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
9407 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
9408 
9409 			arg = DTRACE_USTACK_ARG(nframes, strsize);
9410 
9411 			/*FALLTHROUGH*/
9412 		case DTRACEACT_USTACK:
9413 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
9414 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
9415 				strsize = DTRACE_USTACK_STRSIZE(arg);
9416 				nframes = opt[DTRACEOPT_USTACKFRAMES];
9417 				ASSERT(nframes > 0);
9418 				arg = DTRACE_USTACK_ARG(nframes, strsize);
9419 			}
9420 
9421 			/*
9422 			 * Save a slot for the pid.
9423 			 */
9424 			size = (nframes + 1) * sizeof (uint64_t);
9425 			size += DTRACE_USTACK_STRSIZE(arg);
9426 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
9427 
9428 			break;
9429 
9430 		case DTRACEACT_SYM:
9431 		case DTRACEACT_MOD:
9432 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
9433 			    sizeof (uint64_t)) ||
9434 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9435 				return (EINVAL);
9436 			break;
9437 
9438 		case DTRACEACT_USYM:
9439 		case DTRACEACT_UMOD:
9440 		case DTRACEACT_UADDR:
9441 			if (dp == NULL ||
9442 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
9443 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9444 				return (EINVAL);
9445 
9446 			/*
9447 			 * We have a slot for the pid, plus a slot for the
9448 			 * argument.  To keep things simple (aligned with
9449 			 * bitness-neutral sizing), we store each as a 64-bit
9450 			 * quantity.
9451 			 */
9452 			size = 2 * sizeof (uint64_t);
9453 			break;
9454 
9455 		case DTRACEACT_STOP:
9456 		case DTRACEACT_BREAKPOINT:
9457 		case DTRACEACT_PANIC:
9458 			break;
9459 
9460 		case DTRACEACT_CHILL:
9461 		case DTRACEACT_DISCARD:
9462 		case DTRACEACT_RAISE:
9463 			if (dp == NULL)
9464 				return (EINVAL);
9465 			break;
9466 
9467 		case DTRACEACT_EXIT:
9468 			if (dp == NULL ||
9469 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
9470 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
9471 				return (EINVAL);
9472 			break;
9473 
9474 		case DTRACEACT_SPECULATE:
9475 			if (ecb->dte_size > sizeof (dtrace_epid_t))
9476 				return (EINVAL);
9477 
9478 			if (dp == NULL)
9479 				return (EINVAL);
9480 
9481 			state->dts_speculates = 1;
9482 			break;
9483 
9484 		case DTRACEACT_COMMIT: {
9485 			dtrace_action_t *act = ecb->dte_action;
9486 
9487 			for (; act != NULL; act = act->dta_next) {
9488 				if (act->dta_kind == DTRACEACT_COMMIT)
9489 					return (EINVAL);
9490 			}
9491 
9492 			if (dp == NULL)
9493 				return (EINVAL);
9494 			break;
9495 		}
9496 
9497 		default:
9498 			return (EINVAL);
9499 		}
9500 
9501 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
9502 			/*
9503 			 * If this is a data-storing action or a speculate,
9504 			 * we must be sure that there isn't a commit on the
9505 			 * action chain.
9506 			 */
9507 			dtrace_action_t *act = ecb->dte_action;
9508 
9509 			for (; act != NULL; act = act->dta_next) {
9510 				if (act->dta_kind == DTRACEACT_COMMIT)
9511 					return (EINVAL);
9512 			}
9513 		}
9514 
9515 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
9516 		action->dta_rec.dtrd_size = size;
9517 	}
9518 
9519 	action->dta_refcnt = 1;
9520 	rec = &action->dta_rec;
9521 	size = rec->dtrd_size;
9522 
9523 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
9524 		if (!(size & mask)) {
9525 			align = mask + 1;
9526 			break;
9527 		}
9528 	}
9529 
9530 	action->dta_kind = desc->dtad_kind;
9531 
9532 	if ((action->dta_difo = dp) != NULL)
9533 		dtrace_difo_hold(dp);
9534 
9535 	rec->dtrd_action = action->dta_kind;
9536 	rec->dtrd_arg = arg;
9537 	rec->dtrd_uarg = desc->dtad_uarg;
9538 	rec->dtrd_alignment = (uint16_t)align;
9539 	rec->dtrd_format = format;
9540 
9541 	if ((last = ecb->dte_action_last) != NULL) {
9542 		ASSERT(ecb->dte_action != NULL);
9543 		action->dta_prev = last;
9544 		last->dta_next = action;
9545 	} else {
9546 		ASSERT(ecb->dte_action == NULL);
9547 		ecb->dte_action = action;
9548 	}
9549 
9550 	ecb->dte_action_last = action;
9551 
9552 	return (0);
9553 }
9554 
9555 static void
9556 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
9557 {
9558 	dtrace_action_t *act = ecb->dte_action, *next;
9559 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
9560 	dtrace_difo_t *dp;
9561 	uint16_t format;
9562 
9563 	if (act != NULL && act->dta_refcnt > 1) {
9564 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
9565 		act->dta_refcnt--;
9566 	} else {
9567 		for (; act != NULL; act = next) {
9568 			next = act->dta_next;
9569 			ASSERT(next != NULL || act == ecb->dte_action_last);
9570 			ASSERT(act->dta_refcnt == 1);
9571 
9572 			if ((format = act->dta_rec.dtrd_format) != 0)
9573 				dtrace_format_remove(ecb->dte_state, format);
9574 
9575 			if ((dp = act->dta_difo) != NULL)
9576 				dtrace_difo_release(dp, vstate);
9577 
9578 			if (DTRACEACT_ISAGG(act->dta_kind)) {
9579 				dtrace_ecb_aggregation_destroy(ecb, act);
9580 			} else {
9581 				kmem_free(act, sizeof (dtrace_action_t));
9582 			}
9583 		}
9584 	}
9585 
9586 	ecb->dte_action = NULL;
9587 	ecb->dte_action_last = NULL;
9588 	ecb->dte_size = sizeof (dtrace_epid_t);
9589 }
9590 
9591 static void
9592 dtrace_ecb_disable(dtrace_ecb_t *ecb)
9593 {
9594 	/*
9595 	 * We disable the ECB by removing it from its probe.
9596 	 */
9597 	dtrace_ecb_t *pecb, *prev = NULL;
9598 	dtrace_probe_t *probe = ecb->dte_probe;
9599 
9600 	ASSERT(MUTEX_HELD(&dtrace_lock));
9601 
9602 	if (probe == NULL) {
9603 		/*
9604 		 * This is the NULL probe; there is nothing to disable.
9605 		 */
9606 		return;
9607 	}
9608 
9609 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
9610 		if (pecb == ecb)
9611 			break;
9612 		prev = pecb;
9613 	}
9614 
9615 	ASSERT(pecb != NULL);
9616 
9617 	if (prev == NULL) {
9618 		probe->dtpr_ecb = ecb->dte_next;
9619 	} else {
9620 		prev->dte_next = ecb->dte_next;
9621 	}
9622 
9623 	if (ecb == probe->dtpr_ecb_last) {
9624 		ASSERT(ecb->dte_next == NULL);
9625 		probe->dtpr_ecb_last = prev;
9626 	}
9627 
9628 	/*
9629 	 * The ECB has been disconnected from the probe; now sync to assure
9630 	 * that all CPUs have seen the change before returning.
9631 	 */
9632 	dtrace_sync();
9633 
9634 	if (probe->dtpr_ecb == NULL) {
9635 		/*
9636 		 * That was the last ECB on the probe; clear the predicate
9637 		 * cache ID for the probe, disable it and sync one more time
9638 		 * to assure that we'll never hit it again.
9639 		 */
9640 		dtrace_provider_t *prov = probe->dtpr_provider;
9641 
9642 		ASSERT(ecb->dte_next == NULL);
9643 		ASSERT(probe->dtpr_ecb_last == NULL);
9644 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
9645 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
9646 		    probe->dtpr_id, probe->dtpr_arg);
9647 		dtrace_sync();
9648 	} else {
9649 		/*
9650 		 * There is at least one ECB remaining on the probe.  If there
9651 		 * is _exactly_ one, set the probe's predicate cache ID to be
9652 		 * the predicate cache ID of the remaining ECB.
9653 		 */
9654 		ASSERT(probe->dtpr_ecb_last != NULL);
9655 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
9656 
9657 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
9658 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
9659 
9660 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
9661 
9662 			if (p != NULL)
9663 				probe->dtpr_predcache = p->dtp_cacheid;
9664 		}
9665 
9666 		ecb->dte_next = NULL;
9667 	}
9668 }
9669 
9670 static void
9671 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
9672 {
9673 	dtrace_state_t *state = ecb->dte_state;
9674 	dtrace_vstate_t *vstate = &state->dts_vstate;
9675 	dtrace_predicate_t *pred;
9676 	dtrace_epid_t epid = ecb->dte_epid;
9677 
9678 	ASSERT(MUTEX_HELD(&dtrace_lock));
9679 	ASSERT(ecb->dte_next == NULL);
9680 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
9681 
9682 	if ((pred = ecb->dte_predicate) != NULL)
9683 		dtrace_predicate_release(pred, vstate);
9684 
9685 	dtrace_ecb_action_remove(ecb);
9686 
9687 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
9688 	state->dts_ecbs[epid - 1] = NULL;
9689 
9690 	kmem_free(ecb, sizeof (dtrace_ecb_t));
9691 }
9692 
9693 static dtrace_ecb_t *
9694 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
9695     dtrace_enabling_t *enab)
9696 {
9697 	dtrace_ecb_t *ecb;
9698 	dtrace_predicate_t *pred;
9699 	dtrace_actdesc_t *act;
9700 	dtrace_provider_t *prov;
9701 	dtrace_ecbdesc_t *desc = enab->dten_current;
9702 
9703 	ASSERT(MUTEX_HELD(&dtrace_lock));
9704 	ASSERT(state != NULL);
9705 
9706 	ecb = dtrace_ecb_add(state, probe);
9707 	ecb->dte_uarg = desc->dted_uarg;
9708 
9709 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
9710 		dtrace_predicate_hold(pred);
9711 		ecb->dte_predicate = pred;
9712 	}
9713 
9714 	if (probe != NULL) {
9715 		/*
9716 		 * If the provider shows more leg than the consumer is old
9717 		 * enough to see, we need to enable the appropriate implicit
9718 		 * predicate bits to prevent the ecb from activating at
9719 		 * revealing times.
9720 		 *
9721 		 * Providers specifying DTRACE_PRIV_USER at register time
9722 		 * are stating that they need the /proc-style privilege
9723 		 * model to be enforced, and this is what DTRACE_COND_OWNER
9724 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
9725 		 */
9726 		prov = probe->dtpr_provider;
9727 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
9728 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9729 			ecb->dte_cond |= DTRACE_COND_OWNER;
9730 
9731 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
9732 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
9733 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
9734 
9735 		/*
9736 		 * If the provider shows us kernel innards and the user
9737 		 * is lacking sufficient privilege, enable the
9738 		 * DTRACE_COND_USERMODE implicit predicate.
9739 		 */
9740 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
9741 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
9742 			ecb->dte_cond |= DTRACE_COND_USERMODE;
9743 	}
9744 
9745 	if (dtrace_ecb_create_cache != NULL) {
9746 		/*
9747 		 * If we have a cached ecb, we'll use its action list instead
9748 		 * of creating our own (saving both time and space).
9749 		 */
9750 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
9751 		dtrace_action_t *act = cached->dte_action;
9752 
9753 		if (act != NULL) {
9754 			ASSERT(act->dta_refcnt > 0);
9755 			act->dta_refcnt++;
9756 			ecb->dte_action = act;
9757 			ecb->dte_action_last = cached->dte_action_last;
9758 			ecb->dte_needed = cached->dte_needed;
9759 			ecb->dte_size = cached->dte_size;
9760 			ecb->dte_alignment = cached->dte_alignment;
9761 		}
9762 
9763 		return (ecb);
9764 	}
9765 
9766 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
9767 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
9768 			dtrace_ecb_destroy(ecb);
9769 			return (NULL);
9770 		}
9771 	}
9772 
9773 	dtrace_ecb_resize(ecb);
9774 
9775 	return (dtrace_ecb_create_cache = ecb);
9776 }
9777 
9778 static int
9779 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
9780 {
9781 	dtrace_ecb_t *ecb;
9782 	dtrace_enabling_t *enab = arg;
9783 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
9784 
9785 	ASSERT(state != NULL);
9786 
9787 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
9788 		/*
9789 		 * This probe was created in a generation for which this
9790 		 * enabling has previously created ECBs; we don't want to
9791 		 * enable it again, so just kick out.
9792 		 */
9793 		return (DTRACE_MATCH_NEXT);
9794 	}
9795 
9796 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
9797 		return (DTRACE_MATCH_DONE);
9798 
9799 	dtrace_ecb_enable(ecb);
9800 	return (DTRACE_MATCH_NEXT);
9801 }
9802 
9803 static dtrace_ecb_t *
9804 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
9805 {
9806 	dtrace_ecb_t *ecb;
9807 
9808 	ASSERT(MUTEX_HELD(&dtrace_lock));
9809 
9810 	if (id == 0 || id > state->dts_necbs)
9811 		return (NULL);
9812 
9813 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
9814 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
9815 
9816 	return (state->dts_ecbs[id - 1]);
9817 }
9818 
9819 static dtrace_aggregation_t *
9820 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
9821 {
9822 	dtrace_aggregation_t *agg;
9823 
9824 	ASSERT(MUTEX_HELD(&dtrace_lock));
9825 
9826 	if (id == 0 || id > state->dts_naggregations)
9827 		return (NULL);
9828 
9829 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
9830 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
9831 	    agg->dtag_id == id);
9832 
9833 	return (state->dts_aggregations[id - 1]);
9834 }
9835 
9836 /*
9837  * DTrace Buffer Functions
9838  *
9839  * The following functions manipulate DTrace buffers.  Most of these functions
9840  * are called in the context of establishing or processing consumer state;
9841  * exceptions are explicitly noted.
9842  */
9843 
9844 /*
9845  * Note:  called from cross call context.  This function switches the two
9846  * buffers on a given CPU.  The atomicity of this operation is assured by
9847  * disabling interrupts while the actual switch takes place; the disabling of
9848  * interrupts serializes the execution with any execution of dtrace_probe() on
9849  * the same CPU.
9850  */
9851 static void
9852 dtrace_buffer_switch(dtrace_buffer_t *buf)
9853 {
9854 	caddr_t tomax = buf->dtb_tomax;
9855 	caddr_t xamot = buf->dtb_xamot;
9856 	dtrace_icookie_t cookie;
9857 
9858 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
9859 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
9860 
9861 	cookie = dtrace_interrupt_disable();
9862 	buf->dtb_tomax = xamot;
9863 	buf->dtb_xamot = tomax;
9864 	buf->dtb_xamot_drops = buf->dtb_drops;
9865 	buf->dtb_xamot_offset = buf->dtb_offset;
9866 	buf->dtb_xamot_errors = buf->dtb_errors;
9867 	buf->dtb_xamot_flags = buf->dtb_flags;
9868 	buf->dtb_offset = 0;
9869 	buf->dtb_drops = 0;
9870 	buf->dtb_errors = 0;
9871 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
9872 	dtrace_interrupt_enable(cookie);
9873 }
9874 
9875 /*
9876  * Note:  called from cross call context.  This function activates a buffer
9877  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
9878  * is guaranteed by the disabling of interrupts.
9879  */
9880 static void
9881 dtrace_buffer_activate(dtrace_state_t *state)
9882 {
9883 	dtrace_buffer_t *buf;
9884 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
9885 
9886 	buf = &state->dts_buffer[CPU->cpu_id];
9887 
9888 	if (buf->dtb_tomax != NULL) {
9889 		/*
9890 		 * We might like to assert that the buffer is marked inactive,
9891 		 * but this isn't necessarily true:  the buffer for the CPU
9892 		 * that processes the BEGIN probe has its buffer activated
9893 		 * manually.  In this case, we take the (harmless) action
9894 		 * re-clearing the bit INACTIVE bit.
9895 		 */
9896 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
9897 	}
9898 
9899 	dtrace_interrupt_enable(cookie);
9900 }
9901 
9902 static int
9903 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
9904     processorid_t cpu)
9905 {
9906 	cpu_t *cp;
9907 	dtrace_buffer_t *buf;
9908 
9909 	ASSERT(MUTEX_HELD(&cpu_lock));
9910 	ASSERT(MUTEX_HELD(&dtrace_lock));
9911 
9912 	if (size > dtrace_nonroot_maxsize &&
9913 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
9914 		return (EFBIG);
9915 
9916 	cp = cpu_list;
9917 
9918 	do {
9919 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9920 			continue;
9921 
9922 		buf = &bufs[cp->cpu_id];
9923 
9924 		/*
9925 		 * If there is already a buffer allocated for this CPU, it
9926 		 * is only possible that this is a DR event.  In this case,
9927 		 * the buffer size must match our specified size.
9928 		 */
9929 		if (buf->dtb_tomax != NULL) {
9930 			ASSERT(buf->dtb_size == size);
9931 			continue;
9932 		}
9933 
9934 		ASSERT(buf->dtb_xamot == NULL);
9935 
9936 		if ((buf->dtb_tomax = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9937 			goto err;
9938 
9939 		buf->dtb_size = size;
9940 		buf->dtb_flags = flags;
9941 		buf->dtb_offset = 0;
9942 		buf->dtb_drops = 0;
9943 
9944 		if (flags & DTRACEBUF_NOSWITCH)
9945 			continue;
9946 
9947 		if ((buf->dtb_xamot = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
9948 			goto err;
9949 	} while ((cp = cp->cpu_next) != cpu_list);
9950 
9951 	return (0);
9952 
9953 err:
9954 	cp = cpu_list;
9955 
9956 	do {
9957 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
9958 			continue;
9959 
9960 		buf = &bufs[cp->cpu_id];
9961 
9962 		if (buf->dtb_xamot != NULL) {
9963 			ASSERT(buf->dtb_tomax != NULL);
9964 			ASSERT(buf->dtb_size == size);
9965 			kmem_free(buf->dtb_xamot, size);
9966 		}
9967 
9968 		if (buf->dtb_tomax != NULL) {
9969 			ASSERT(buf->dtb_size == size);
9970 			kmem_free(buf->dtb_tomax, size);
9971 		}
9972 
9973 		buf->dtb_tomax = NULL;
9974 		buf->dtb_xamot = NULL;
9975 		buf->dtb_size = 0;
9976 	} while ((cp = cp->cpu_next) != cpu_list);
9977 
9978 	return (ENOMEM);
9979 }
9980 
9981 /*
9982  * Note:  called from probe context.  This function just increments the drop
9983  * count on a buffer.  It has been made a function to allow for the
9984  * possibility of understanding the source of mysterious drop counts.  (A
9985  * problem for which one may be particularly disappointed that DTrace cannot
9986  * be used to understand DTrace.)
9987  */
9988 static void
9989 dtrace_buffer_drop(dtrace_buffer_t *buf)
9990 {
9991 	buf->dtb_drops++;
9992 }
9993 
9994 /*
9995  * Note:  called from probe context.  This function is called to reserve space
9996  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
9997  * mstate.  Returns the new offset in the buffer, or a negative value if an
9998  * error has occurred.
9999  */
10000 static intptr_t
10001 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
10002     dtrace_state_t *state, dtrace_mstate_t *mstate)
10003 {
10004 	intptr_t offs = buf->dtb_offset, soffs;
10005 	intptr_t woffs;
10006 	caddr_t tomax;
10007 	size_t total;
10008 
10009 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
10010 		return (-1);
10011 
10012 	if ((tomax = buf->dtb_tomax) == NULL) {
10013 		dtrace_buffer_drop(buf);
10014 		return (-1);
10015 	}
10016 
10017 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
10018 		while (offs & (align - 1)) {
10019 			/*
10020 			 * Assert that our alignment is off by a number which
10021 			 * is itself sizeof (uint32_t) aligned.
10022 			 */
10023 			ASSERT(!((align - (offs & (align - 1))) &
10024 			    (sizeof (uint32_t) - 1)));
10025 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10026 			offs += sizeof (uint32_t);
10027 		}
10028 
10029 		if ((soffs = offs + needed) > buf->dtb_size) {
10030 			dtrace_buffer_drop(buf);
10031 			return (-1);
10032 		}
10033 
10034 		if (mstate == NULL)
10035 			return (offs);
10036 
10037 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
10038 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
10039 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10040 
10041 		return (offs);
10042 	}
10043 
10044 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10045 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
10046 		    (buf->dtb_flags & DTRACEBUF_FULL))
10047 			return (-1);
10048 		goto out;
10049 	}
10050 
10051 	total = needed + (offs & (align - 1));
10052 
10053 	/*
10054 	 * For a ring buffer, life is quite a bit more complicated.  Before
10055 	 * we can store any padding, we need to adjust our wrapping offset.
10056 	 * (If we've never before wrapped or we're not about to, no adjustment
10057 	 * is required.)
10058 	 */
10059 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
10060 	    offs + total > buf->dtb_size) {
10061 		woffs = buf->dtb_xamot_offset;
10062 
10063 		if (offs + total > buf->dtb_size) {
10064 			/*
10065 			 * We can't fit in the end of the buffer.  First, a
10066 			 * sanity check that we can fit in the buffer at all.
10067 			 */
10068 			if (total > buf->dtb_size) {
10069 				dtrace_buffer_drop(buf);
10070 				return (-1);
10071 			}
10072 
10073 			/*
10074 			 * We're going to be storing at the top of the buffer,
10075 			 * so now we need to deal with the wrapped offset.  We
10076 			 * only reset our wrapped offset to 0 if it is
10077 			 * currently greater than the current offset.  If it
10078 			 * is less than the current offset, it is because a
10079 			 * previous allocation induced a wrap -- but the
10080 			 * allocation didn't subsequently take the space due
10081 			 * to an error or false predicate evaluation.  In this
10082 			 * case, we'll just leave the wrapped offset alone: if
10083 			 * the wrapped offset hasn't been advanced far enough
10084 			 * for this allocation, it will be adjusted in the
10085 			 * lower loop.
10086 			 */
10087 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
10088 				if (woffs >= offs)
10089 					woffs = 0;
10090 			} else {
10091 				woffs = 0;
10092 			}
10093 
10094 			/*
10095 			 * Now we know that we're going to be storing to the
10096 			 * top of the buffer and that there is room for us
10097 			 * there.  We need to clear the buffer from the current
10098 			 * offset to the end (there may be old gunk there).
10099 			 */
10100 			while (offs < buf->dtb_size)
10101 				tomax[offs++] = 0;
10102 
10103 			/*
10104 			 * We need to set our offset to zero.  And because we
10105 			 * are wrapping, we need to set the bit indicating as
10106 			 * much.  We can also adjust our needed space back
10107 			 * down to the space required by the ECB -- we know
10108 			 * that the top of the buffer is aligned.
10109 			 */
10110 			offs = 0;
10111 			total = needed;
10112 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
10113 		} else {
10114 			/*
10115 			 * There is room for us in the buffer, so we simply
10116 			 * need to check the wrapped offset.
10117 			 */
10118 			if (woffs < offs) {
10119 				/*
10120 				 * The wrapped offset is less than the offset.
10121 				 * This can happen if we allocated buffer space
10122 				 * that induced a wrap, but then we didn't
10123 				 * subsequently take the space due to an error
10124 				 * or false predicate evaluation.  This is
10125 				 * okay; we know that _this_ allocation isn't
10126 				 * going to induce a wrap.  We still can't
10127 				 * reset the wrapped offset to be zero,
10128 				 * however: the space may have been trashed in
10129 				 * the previous failed probe attempt.  But at
10130 				 * least the wrapped offset doesn't need to
10131 				 * be adjusted at all...
10132 				 */
10133 				goto out;
10134 			}
10135 		}
10136 
10137 		while (offs + total > woffs) {
10138 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
10139 			size_t size;
10140 
10141 			if (epid == DTRACE_EPIDNONE) {
10142 				size = sizeof (uint32_t);
10143 			} else {
10144 				ASSERT(epid <= state->dts_necbs);
10145 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
10146 
10147 				size = state->dts_ecbs[epid - 1]->dte_size;
10148 			}
10149 
10150 			ASSERT(woffs + size <= buf->dtb_size);
10151 			ASSERT(size != 0);
10152 
10153 			if (woffs + size == buf->dtb_size) {
10154 				/*
10155 				 * We've reached the end of the buffer; we want
10156 				 * to set the wrapped offset to 0 and break
10157 				 * out.  However, if the offs is 0, then we're
10158 				 * in a strange edge-condition:  the amount of
10159 				 * space that we want to reserve plus the size
10160 				 * of the record that we're overwriting is
10161 				 * greater than the size of the buffer.  This
10162 				 * is problematic because if we reserve the
10163 				 * space but subsequently don't consume it (due
10164 				 * to a failed predicate or error) the wrapped
10165 				 * offset will be 0 -- yet the EPID at offset 0
10166 				 * will not be committed.  This situation is
10167 				 * relatively easy to deal with:  if we're in
10168 				 * this case, the buffer is indistinguishable
10169 				 * from one that hasn't wrapped; we need only
10170 				 * finish the job by clearing the wrapped bit,
10171 				 * explicitly setting the offset to be 0, and
10172 				 * zero'ing out the old data in the buffer.
10173 				 */
10174 				if (offs == 0) {
10175 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
10176 					buf->dtb_offset = 0;
10177 					woffs = total;
10178 
10179 					while (woffs < buf->dtb_size)
10180 						tomax[woffs++] = 0;
10181 				}
10182 
10183 				woffs = 0;
10184 				break;
10185 			}
10186 
10187 			woffs += size;
10188 		}
10189 
10190 		/*
10191 		 * We have a wrapped offset.  It may be that the wrapped offset
10192 		 * has become zero -- that's okay.
10193 		 */
10194 		buf->dtb_xamot_offset = woffs;
10195 	}
10196 
10197 out:
10198 	/*
10199 	 * Now we can plow the buffer with any necessary padding.
10200 	 */
10201 	while (offs & (align - 1)) {
10202 		/*
10203 		 * Assert that our alignment is off by a number which
10204 		 * is itself sizeof (uint32_t) aligned.
10205 		 */
10206 		ASSERT(!((align - (offs & (align - 1))) &
10207 		    (sizeof (uint32_t) - 1)));
10208 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
10209 		offs += sizeof (uint32_t);
10210 	}
10211 
10212 	if (buf->dtb_flags & DTRACEBUF_FILL) {
10213 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
10214 			buf->dtb_flags |= DTRACEBUF_FULL;
10215 			return (-1);
10216 		}
10217 	}
10218 
10219 	if (mstate == NULL)
10220 		return (offs);
10221 
10222 	/*
10223 	 * For ring buffers and fill buffers, the scratch space is always
10224 	 * the inactive buffer.
10225 	 */
10226 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
10227 	mstate->dtms_scratch_size = buf->dtb_size;
10228 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
10229 
10230 	return (offs);
10231 }
10232 
10233 static void
10234 dtrace_buffer_polish(dtrace_buffer_t *buf)
10235 {
10236 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
10237 	ASSERT(MUTEX_HELD(&dtrace_lock));
10238 
10239 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
10240 		return;
10241 
10242 	/*
10243 	 * We need to polish the ring buffer.  There are three cases:
10244 	 *
10245 	 * - The first (and presumably most common) is that there is no gap
10246 	 *   between the buffer offset and the wrapped offset.  In this case,
10247 	 *   there is nothing in the buffer that isn't valid data; we can
10248 	 *   mark the buffer as polished and return.
10249 	 *
10250 	 * - The second (less common than the first but still more common
10251 	 *   than the third) is that there is a gap between the buffer offset
10252 	 *   and the wrapped offset, and the wrapped offset is larger than the
10253 	 *   buffer offset.  This can happen because of an alignment issue, or
10254 	 *   can happen because of a call to dtrace_buffer_reserve() that
10255 	 *   didn't subsequently consume the buffer space.  In this case,
10256 	 *   we need to zero the data from the buffer offset to the wrapped
10257 	 *   offset.
10258 	 *
10259 	 * - The third (and least common) is that there is a gap between the
10260 	 *   buffer offset and the wrapped offset, but the wrapped offset is
10261 	 *   _less_ than the buffer offset.  This can only happen because a
10262 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
10263 	 *   was not subsequently consumed.  In this case, we need to zero the
10264 	 *   space from the offset to the end of the buffer _and_ from the
10265 	 *   top of the buffer to the wrapped offset.
10266 	 */
10267 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
10268 		bzero(buf->dtb_tomax + buf->dtb_offset,
10269 		    buf->dtb_xamot_offset - buf->dtb_offset);
10270 	}
10271 
10272 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
10273 		bzero(buf->dtb_tomax + buf->dtb_offset,
10274 		    buf->dtb_size - buf->dtb_offset);
10275 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
10276 	}
10277 }
10278 
10279 static void
10280 dtrace_buffer_free(dtrace_buffer_t *bufs)
10281 {
10282 	int i;
10283 
10284 	for (i = 0; i < NCPU; i++) {
10285 		dtrace_buffer_t *buf = &bufs[i];
10286 
10287 		if (buf->dtb_tomax == NULL) {
10288 			ASSERT(buf->dtb_xamot == NULL);
10289 			ASSERT(buf->dtb_size == 0);
10290 			continue;
10291 		}
10292 
10293 		if (buf->dtb_xamot != NULL) {
10294 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
10295 			kmem_free(buf->dtb_xamot, buf->dtb_size);
10296 		}
10297 
10298 		kmem_free(buf->dtb_tomax, buf->dtb_size);
10299 		buf->dtb_size = 0;
10300 		buf->dtb_tomax = NULL;
10301 		buf->dtb_xamot = NULL;
10302 	}
10303 }
10304 
10305 /*
10306  * DTrace Enabling Functions
10307  */
10308 static dtrace_enabling_t *
10309 dtrace_enabling_create(dtrace_vstate_t *vstate)
10310 {
10311 	dtrace_enabling_t *enab;
10312 
10313 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
10314 	enab->dten_vstate = vstate;
10315 
10316 	return (enab);
10317 }
10318 
10319 static void
10320 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
10321 {
10322 	dtrace_ecbdesc_t **ndesc;
10323 	size_t osize, nsize;
10324 
10325 	/*
10326 	 * We can't add to enablings after we've enabled them, or after we've
10327 	 * retained them.
10328 	 */
10329 	ASSERT(enab->dten_probegen == 0);
10330 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10331 
10332 	if (enab->dten_ndesc < enab->dten_maxdesc) {
10333 		enab->dten_desc[enab->dten_ndesc++] = ecb;
10334 		return;
10335 	}
10336 
10337 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10338 
10339 	if (enab->dten_maxdesc == 0) {
10340 		enab->dten_maxdesc = 1;
10341 	} else {
10342 		enab->dten_maxdesc <<= 1;
10343 	}
10344 
10345 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
10346 
10347 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
10348 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
10349 	bcopy(enab->dten_desc, ndesc, osize);
10350 	kmem_free(enab->dten_desc, osize);
10351 
10352 	enab->dten_desc = ndesc;
10353 	enab->dten_desc[enab->dten_ndesc++] = ecb;
10354 }
10355 
10356 static void
10357 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
10358     dtrace_probedesc_t *pd)
10359 {
10360 	dtrace_ecbdesc_t *new;
10361 	dtrace_predicate_t *pred;
10362 	dtrace_actdesc_t *act;
10363 
10364 	/*
10365 	 * We're going to create a new ECB description that matches the
10366 	 * specified ECB in every way, but has the specified probe description.
10367 	 */
10368 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
10369 
10370 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
10371 		dtrace_predicate_hold(pred);
10372 
10373 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
10374 		dtrace_actdesc_hold(act);
10375 
10376 	new->dted_action = ecb->dted_action;
10377 	new->dted_pred = ecb->dted_pred;
10378 	new->dted_probe = *pd;
10379 	new->dted_uarg = ecb->dted_uarg;
10380 
10381 	dtrace_enabling_add(enab, new);
10382 }
10383 
10384 static void
10385 dtrace_enabling_dump(dtrace_enabling_t *enab)
10386 {
10387 	int i;
10388 
10389 	for (i = 0; i < enab->dten_ndesc; i++) {
10390 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
10391 
10392 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
10393 		    desc->dtpd_provider, desc->dtpd_mod,
10394 		    desc->dtpd_func, desc->dtpd_name);
10395 	}
10396 }
10397 
10398 static void
10399 dtrace_enabling_destroy(dtrace_enabling_t *enab)
10400 {
10401 	int i;
10402 	dtrace_ecbdesc_t *ep;
10403 	dtrace_vstate_t *vstate = enab->dten_vstate;
10404 
10405 	ASSERT(MUTEX_HELD(&dtrace_lock));
10406 
10407 	for (i = 0; i < enab->dten_ndesc; i++) {
10408 		dtrace_actdesc_t *act, *next;
10409 		dtrace_predicate_t *pred;
10410 
10411 		ep = enab->dten_desc[i];
10412 
10413 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
10414 			dtrace_predicate_release(pred, vstate);
10415 
10416 		for (act = ep->dted_action; act != NULL; act = next) {
10417 			next = act->dtad_next;
10418 			dtrace_actdesc_release(act, vstate);
10419 		}
10420 
10421 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
10422 	}
10423 
10424 	kmem_free(enab->dten_desc,
10425 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
10426 
10427 	/*
10428 	 * If this was a retained enabling, decrement the dts_nretained count
10429 	 * and take it off of the dtrace_retained list.
10430 	 */
10431 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
10432 	    dtrace_retained == enab) {
10433 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10434 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
10435 		enab->dten_vstate->dtvs_state->dts_nretained--;
10436 	}
10437 
10438 	if (enab->dten_prev == NULL) {
10439 		if (dtrace_retained == enab) {
10440 			dtrace_retained = enab->dten_next;
10441 
10442 			if (dtrace_retained != NULL)
10443 				dtrace_retained->dten_prev = NULL;
10444 		}
10445 	} else {
10446 		ASSERT(enab != dtrace_retained);
10447 		ASSERT(dtrace_retained != NULL);
10448 		enab->dten_prev->dten_next = enab->dten_next;
10449 	}
10450 
10451 	if (enab->dten_next != NULL) {
10452 		ASSERT(dtrace_retained != NULL);
10453 		enab->dten_next->dten_prev = enab->dten_prev;
10454 	}
10455 
10456 	kmem_free(enab, sizeof (dtrace_enabling_t));
10457 }
10458 
10459 static int
10460 dtrace_enabling_retain(dtrace_enabling_t *enab)
10461 {
10462 	dtrace_state_t *state;
10463 
10464 	ASSERT(MUTEX_HELD(&dtrace_lock));
10465 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
10466 	ASSERT(enab->dten_vstate != NULL);
10467 
10468 	state = enab->dten_vstate->dtvs_state;
10469 	ASSERT(state != NULL);
10470 
10471 	/*
10472 	 * We only allow each state to retain dtrace_retain_max enablings.
10473 	 */
10474 	if (state->dts_nretained >= dtrace_retain_max)
10475 		return (ENOSPC);
10476 
10477 	state->dts_nretained++;
10478 
10479 	if (dtrace_retained == NULL) {
10480 		dtrace_retained = enab;
10481 		return (0);
10482 	}
10483 
10484 	enab->dten_next = dtrace_retained;
10485 	dtrace_retained->dten_prev = enab;
10486 	dtrace_retained = enab;
10487 
10488 	return (0);
10489 }
10490 
10491 static int
10492 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
10493     dtrace_probedesc_t *create)
10494 {
10495 	dtrace_enabling_t *new, *enab;
10496 	int found = 0, err = ENOENT;
10497 
10498 	ASSERT(MUTEX_HELD(&dtrace_lock));
10499 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
10500 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
10501 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
10502 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
10503 
10504 	new = dtrace_enabling_create(&state->dts_vstate);
10505 
10506 	/*
10507 	 * Iterate over all retained enablings, looking for enablings that
10508 	 * match the specified state.
10509 	 */
10510 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10511 		int i;
10512 
10513 		/*
10514 		 * dtvs_state can only be NULL for helper enablings -- and
10515 		 * helper enablings can't be retained.
10516 		 */
10517 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10518 
10519 		if (enab->dten_vstate->dtvs_state != state)
10520 			continue;
10521 
10522 		/*
10523 		 * Now iterate over each probe description; we're looking for
10524 		 * an exact match to the specified probe description.
10525 		 */
10526 		for (i = 0; i < enab->dten_ndesc; i++) {
10527 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
10528 			dtrace_probedesc_t *pd = &ep->dted_probe;
10529 
10530 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
10531 				continue;
10532 
10533 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
10534 				continue;
10535 
10536 			if (strcmp(pd->dtpd_func, match->dtpd_func))
10537 				continue;
10538 
10539 			if (strcmp(pd->dtpd_name, match->dtpd_name))
10540 				continue;
10541 
10542 			/*
10543 			 * We have a winning probe!  Add it to our growing
10544 			 * enabling.
10545 			 */
10546 			found = 1;
10547 			dtrace_enabling_addlike(new, ep, create);
10548 		}
10549 	}
10550 
10551 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
10552 		dtrace_enabling_destroy(new);
10553 		return (err);
10554 	}
10555 
10556 	return (0);
10557 }
10558 
10559 static void
10560 dtrace_enabling_retract(dtrace_state_t *state)
10561 {
10562 	dtrace_enabling_t *enab, *next;
10563 
10564 	ASSERT(MUTEX_HELD(&dtrace_lock));
10565 
10566 	/*
10567 	 * Iterate over all retained enablings, destroy the enablings retained
10568 	 * for the specified state.
10569 	 */
10570 	for (enab = dtrace_retained; enab != NULL; enab = next) {
10571 		next = enab->dten_next;
10572 
10573 		/*
10574 		 * dtvs_state can only be NULL for helper enablings -- and
10575 		 * helper enablings can't be retained.
10576 		 */
10577 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10578 
10579 		if (enab->dten_vstate->dtvs_state == state) {
10580 			ASSERT(state->dts_nretained > 0);
10581 			dtrace_enabling_destroy(enab);
10582 		}
10583 	}
10584 
10585 	ASSERT(state->dts_nretained == 0);
10586 }
10587 
10588 static int
10589 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
10590 {
10591 	int i = 0;
10592 	int matched = 0;
10593 
10594 	ASSERT(MUTEX_HELD(&cpu_lock));
10595 	ASSERT(MUTEX_HELD(&dtrace_lock));
10596 
10597 	for (i = 0; i < enab->dten_ndesc; i++) {
10598 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
10599 
10600 		enab->dten_current = ep;
10601 		enab->dten_error = 0;
10602 
10603 		matched += dtrace_probe_enable(&ep->dted_probe, enab);
10604 
10605 		if (enab->dten_error != 0) {
10606 			/*
10607 			 * If we get an error half-way through enabling the
10608 			 * probes, we kick out -- perhaps with some number of
10609 			 * them enabled.  Leaving enabled probes enabled may
10610 			 * be slightly confusing for user-level, but we expect
10611 			 * that no one will attempt to actually drive on in
10612 			 * the face of such errors.  If this is an anonymous
10613 			 * enabling (indicated with a NULL nmatched pointer),
10614 			 * we cmn_err() a message.  We aren't expecting to
10615 			 * get such an error -- such as it can exist at all,
10616 			 * it would be a result of corrupted DOF in the driver
10617 			 * properties.
10618 			 */
10619 			if (nmatched == NULL) {
10620 				cmn_err(CE_WARN, "dtrace_enabling_match() "
10621 				    "error on %p: %d", (void *)ep,
10622 				    enab->dten_error);
10623 			}
10624 
10625 			return (enab->dten_error);
10626 		}
10627 	}
10628 
10629 	enab->dten_probegen = dtrace_probegen;
10630 	if (nmatched != NULL)
10631 		*nmatched = matched;
10632 
10633 	return (0);
10634 }
10635 
10636 static void
10637 dtrace_enabling_matchall(void)
10638 {
10639 	dtrace_enabling_t *enab;
10640 
10641 	mutex_enter(&cpu_lock);
10642 	mutex_enter(&dtrace_lock);
10643 
10644 	/*
10645 	 * Because we can be called after dtrace_detach() has been called, we
10646 	 * cannot assert that there are retained enablings.  We can safely
10647 	 * load from dtrace_retained, however:  the taskq_destroy() at the
10648 	 * end of dtrace_detach() will block pending our completion.
10649 	 */
10650 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next)
10651 		(void) dtrace_enabling_match(enab, NULL);
10652 
10653 	mutex_exit(&dtrace_lock);
10654 	mutex_exit(&cpu_lock);
10655 }
10656 
10657 static int
10658 dtrace_enabling_matchstate(dtrace_state_t *state, int *nmatched)
10659 {
10660 	dtrace_enabling_t *enab;
10661 	int matched, total = 0, err;
10662 
10663 	ASSERT(MUTEX_HELD(&cpu_lock));
10664 	ASSERT(MUTEX_HELD(&dtrace_lock));
10665 
10666 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10667 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10668 
10669 		if (enab->dten_vstate->dtvs_state != state)
10670 			continue;
10671 
10672 		if ((err = dtrace_enabling_match(enab, &matched)) != 0)
10673 			return (err);
10674 
10675 		total += matched;
10676 	}
10677 
10678 	if (nmatched != NULL)
10679 		*nmatched = total;
10680 
10681 	return (0);
10682 }
10683 
10684 /*
10685  * If an enabling is to be enabled without having matched probes (that is, if
10686  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
10687  * enabling must be _primed_ by creating an ECB for every ECB description.
10688  * This must be done to assure that we know the number of speculations, the
10689  * number of aggregations, the minimum buffer size needed, etc. before we
10690  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
10691  * enabling any probes, we create ECBs for every ECB decription, but with a
10692  * NULL probe -- which is exactly what this function does.
10693  */
10694 static void
10695 dtrace_enabling_prime(dtrace_state_t *state)
10696 {
10697 	dtrace_enabling_t *enab;
10698 	int i;
10699 
10700 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
10701 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
10702 
10703 		if (enab->dten_vstate->dtvs_state != state)
10704 			continue;
10705 
10706 		/*
10707 		 * We don't want to prime an enabling more than once, lest
10708 		 * we allow a malicious user to induce resource exhaustion.
10709 		 * (The ECBs that result from priming an enabling aren't
10710 		 * leaked -- but they also aren't deallocated until the
10711 		 * consumer state is destroyed.)
10712 		 */
10713 		if (enab->dten_primed)
10714 			continue;
10715 
10716 		for (i = 0; i < enab->dten_ndesc; i++) {
10717 			enab->dten_current = enab->dten_desc[i];
10718 			(void) dtrace_probe_enable(NULL, enab);
10719 		}
10720 
10721 		enab->dten_primed = 1;
10722 	}
10723 }
10724 
10725 /*
10726  * Called to indicate that probes should be provided due to retained
10727  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
10728  * must take an initial lap through the enabling calling the dtps_provide()
10729  * entry point explicitly to allow for autocreated probes.
10730  */
10731 static void
10732 dtrace_enabling_provide(dtrace_provider_t *prv)
10733 {
10734 	int i, all = 0;
10735 	dtrace_probedesc_t desc;
10736 
10737 	ASSERT(MUTEX_HELD(&dtrace_lock));
10738 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
10739 
10740 	if (prv == NULL) {
10741 		all = 1;
10742 		prv = dtrace_provider;
10743 	}
10744 
10745 	do {
10746 		dtrace_enabling_t *enab = dtrace_retained;
10747 		void *parg = prv->dtpv_arg;
10748 
10749 		for (; enab != NULL; enab = enab->dten_next) {
10750 			for (i = 0; i < enab->dten_ndesc; i++) {
10751 				desc = enab->dten_desc[i]->dted_probe;
10752 				mutex_exit(&dtrace_lock);
10753 				prv->dtpv_pops.dtps_provide(parg, &desc);
10754 				mutex_enter(&dtrace_lock);
10755 			}
10756 		}
10757 	} while (all && (prv = prv->dtpv_next) != NULL);
10758 
10759 	mutex_exit(&dtrace_lock);
10760 	dtrace_probe_provide(NULL, all ? NULL : prv);
10761 	mutex_enter(&dtrace_lock);
10762 }
10763 
10764 /*
10765  * DTrace DOF Functions
10766  */
10767 /*ARGSUSED*/
10768 static void
10769 dtrace_dof_error(dof_hdr_t *dof, const char *str)
10770 {
10771 	if (dtrace_err_verbose)
10772 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
10773 
10774 #ifdef DTRACE_ERRDEBUG
10775 	dtrace_errdebug(str);
10776 #endif
10777 }
10778 
10779 /*
10780  * Create DOF out of a currently enabled state.  Right now, we only create
10781  * DOF containing the run-time options -- but this could be expanded to create
10782  * complete DOF representing the enabled state.
10783  */
10784 static dof_hdr_t *
10785 dtrace_dof_create(dtrace_state_t *state)
10786 {
10787 	dof_hdr_t *dof;
10788 	dof_sec_t *sec;
10789 	dof_optdesc_t *opt;
10790 	int i, len = sizeof (dof_hdr_t) +
10791 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
10792 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10793 
10794 	ASSERT(MUTEX_HELD(&dtrace_lock));
10795 
10796 	dof = kmem_zalloc(len, KM_SLEEP);
10797 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
10798 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
10799 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
10800 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
10801 
10802 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
10803 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
10804 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
10805 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
10806 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
10807 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
10808 
10809 	dof->dofh_flags = 0;
10810 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
10811 	dof->dofh_secsize = sizeof (dof_sec_t);
10812 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
10813 	dof->dofh_secoff = sizeof (dof_hdr_t);
10814 	dof->dofh_loadsz = len;
10815 	dof->dofh_filesz = len;
10816 	dof->dofh_pad = 0;
10817 
10818 	/*
10819 	 * Fill in the option section header...
10820 	 */
10821 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
10822 	sec->dofs_type = DOF_SECT_OPTDESC;
10823 	sec->dofs_align = sizeof (uint64_t);
10824 	sec->dofs_flags = DOF_SECF_LOAD;
10825 	sec->dofs_entsize = sizeof (dof_optdesc_t);
10826 
10827 	opt = (dof_optdesc_t *)((uintptr_t)sec +
10828 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
10829 
10830 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
10831 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
10832 
10833 	for (i = 0; i < DTRACEOPT_MAX; i++) {
10834 		opt[i].dofo_option = i;
10835 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
10836 		opt[i].dofo_value = state->dts_options[i];
10837 	}
10838 
10839 	return (dof);
10840 }
10841 
10842 static dof_hdr_t *
10843 dtrace_dof_copyin(uintptr_t uarg, int *errp)
10844 {
10845 	dof_hdr_t hdr, *dof;
10846 
10847 	ASSERT(!MUTEX_HELD(&dtrace_lock));
10848 
10849 	/*
10850 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
10851 	 */
10852 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
10853 		dtrace_dof_error(NULL, "failed to copyin DOF header");
10854 		*errp = EFAULT;
10855 		return (NULL);
10856 	}
10857 
10858 	/*
10859 	 * Now we'll allocate the entire DOF and copy it in -- provided
10860 	 * that the length isn't outrageous.
10861 	 */
10862 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
10863 		dtrace_dof_error(&hdr, "load size exceeds maximum");
10864 		*errp = E2BIG;
10865 		return (NULL);
10866 	}
10867 
10868 	if (hdr.dofh_loadsz < sizeof (hdr)) {
10869 		dtrace_dof_error(&hdr, "invalid load size");
10870 		*errp = EINVAL;
10871 		return (NULL);
10872 	}
10873 
10874 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
10875 
10876 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0) {
10877 		kmem_free(dof, hdr.dofh_loadsz);
10878 		*errp = EFAULT;
10879 		return (NULL);
10880 	}
10881 
10882 	return (dof);
10883 }
10884 
10885 static dof_hdr_t *
10886 dtrace_dof_property(const char *name)
10887 {
10888 	uchar_t *buf;
10889 	uint64_t loadsz;
10890 	unsigned int len, i;
10891 	dof_hdr_t *dof;
10892 
10893 	/*
10894 	 * Unfortunately, array of values in .conf files are always (and
10895 	 * only) interpreted to be integer arrays.  We must read our DOF
10896 	 * as an integer array, and then squeeze it into a byte array.
10897 	 */
10898 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
10899 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
10900 		return (NULL);
10901 
10902 	for (i = 0; i < len; i++)
10903 		buf[i] = (uchar_t)(((int *)buf)[i]);
10904 
10905 	if (len < sizeof (dof_hdr_t)) {
10906 		ddi_prop_free(buf);
10907 		dtrace_dof_error(NULL, "truncated header");
10908 		return (NULL);
10909 	}
10910 
10911 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
10912 		ddi_prop_free(buf);
10913 		dtrace_dof_error(NULL, "truncated DOF");
10914 		return (NULL);
10915 	}
10916 
10917 	if (loadsz >= dtrace_dof_maxsize) {
10918 		ddi_prop_free(buf);
10919 		dtrace_dof_error(NULL, "oversized DOF");
10920 		return (NULL);
10921 	}
10922 
10923 	dof = kmem_alloc(loadsz, KM_SLEEP);
10924 	bcopy(buf, dof, loadsz);
10925 	ddi_prop_free(buf);
10926 
10927 	return (dof);
10928 }
10929 
10930 static void
10931 dtrace_dof_destroy(dof_hdr_t *dof)
10932 {
10933 	kmem_free(dof, dof->dofh_loadsz);
10934 }
10935 
10936 /*
10937  * Return the dof_sec_t pointer corresponding to a given section index.  If the
10938  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
10939  * a type other than DOF_SECT_NONE is specified, the header is checked against
10940  * this type and NULL is returned if the types do not match.
10941  */
10942 static dof_sec_t *
10943 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
10944 {
10945 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
10946 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
10947 
10948 	if (i >= dof->dofh_secnum) {
10949 		dtrace_dof_error(dof, "referenced section index is invalid");
10950 		return (NULL);
10951 	}
10952 
10953 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
10954 		dtrace_dof_error(dof, "referenced section is not loadable");
10955 		return (NULL);
10956 	}
10957 
10958 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
10959 		dtrace_dof_error(dof, "referenced section is the wrong type");
10960 		return (NULL);
10961 	}
10962 
10963 	return (sec);
10964 }
10965 
10966 static dtrace_probedesc_t *
10967 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
10968 {
10969 	dof_probedesc_t *probe;
10970 	dof_sec_t *strtab;
10971 	uintptr_t daddr = (uintptr_t)dof;
10972 	uintptr_t str;
10973 	size_t size;
10974 
10975 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
10976 		dtrace_dof_error(dof, "invalid probe section");
10977 		return (NULL);
10978 	}
10979 
10980 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
10981 		dtrace_dof_error(dof, "bad alignment in probe description");
10982 		return (NULL);
10983 	}
10984 
10985 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
10986 		dtrace_dof_error(dof, "truncated probe description");
10987 		return (NULL);
10988 	}
10989 
10990 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
10991 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
10992 
10993 	if (strtab == NULL)
10994 		return (NULL);
10995 
10996 	str = daddr + strtab->dofs_offset;
10997 	size = strtab->dofs_size;
10998 
10999 	if (probe->dofp_provider >= strtab->dofs_size) {
11000 		dtrace_dof_error(dof, "corrupt probe provider");
11001 		return (NULL);
11002 	}
11003 
11004 	(void) strncpy(desc->dtpd_provider,
11005 	    (char *)(str + probe->dofp_provider),
11006 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
11007 
11008 	if (probe->dofp_mod >= strtab->dofs_size) {
11009 		dtrace_dof_error(dof, "corrupt probe module");
11010 		return (NULL);
11011 	}
11012 
11013 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
11014 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
11015 
11016 	if (probe->dofp_func >= strtab->dofs_size) {
11017 		dtrace_dof_error(dof, "corrupt probe function");
11018 		return (NULL);
11019 	}
11020 
11021 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
11022 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
11023 
11024 	if (probe->dofp_name >= strtab->dofs_size) {
11025 		dtrace_dof_error(dof, "corrupt probe name");
11026 		return (NULL);
11027 	}
11028 
11029 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
11030 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
11031 
11032 	return (desc);
11033 }
11034 
11035 static dtrace_difo_t *
11036 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11037     cred_t *cr)
11038 {
11039 	dtrace_difo_t *dp;
11040 	size_t ttl = 0;
11041 	dof_difohdr_t *dofd;
11042 	uintptr_t daddr = (uintptr_t)dof;
11043 	size_t max = dtrace_difo_maxsize;
11044 	int i, l, n;
11045 
11046 	static const struct {
11047 		int section;
11048 		int bufoffs;
11049 		int lenoffs;
11050 		int entsize;
11051 		int align;
11052 		const char *msg;
11053 	} difo[] = {
11054 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
11055 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
11056 		sizeof (dif_instr_t), "multiple DIF sections" },
11057 
11058 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
11059 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
11060 		sizeof (uint64_t), "multiple integer tables" },
11061 
11062 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
11063 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
11064 		sizeof (char), "multiple string tables" },
11065 
11066 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
11067 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
11068 		sizeof (uint_t), "multiple variable tables" },
11069 
11070 		{ DOF_SECT_NONE, 0, 0, 0, NULL }
11071 	};
11072 
11073 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
11074 		dtrace_dof_error(dof, "invalid DIFO header section");
11075 		return (NULL);
11076 	}
11077 
11078 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
11079 		dtrace_dof_error(dof, "bad alignment in DIFO header");
11080 		return (NULL);
11081 	}
11082 
11083 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
11084 	    sec->dofs_size % sizeof (dof_secidx_t)) {
11085 		dtrace_dof_error(dof, "bad size in DIFO header");
11086 		return (NULL);
11087 	}
11088 
11089 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11090 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
11091 
11092 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
11093 	dp->dtdo_rtype = dofd->dofd_rtype;
11094 
11095 	for (l = 0; l < n; l++) {
11096 		dof_sec_t *subsec;
11097 		void **bufp;
11098 		uint32_t *lenp;
11099 
11100 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
11101 		    dofd->dofd_links[l])) == NULL)
11102 			goto err; /* invalid section link */
11103 
11104 		if (ttl + subsec->dofs_size > max) {
11105 			dtrace_dof_error(dof, "exceeds maximum size");
11106 			goto err;
11107 		}
11108 
11109 		ttl += subsec->dofs_size;
11110 
11111 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
11112 			if (subsec->dofs_type != difo[i].section)
11113 				continue;
11114 
11115 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
11116 				dtrace_dof_error(dof, "section not loaded");
11117 				goto err;
11118 			}
11119 
11120 			if (subsec->dofs_align != difo[i].align) {
11121 				dtrace_dof_error(dof, "bad alignment");
11122 				goto err;
11123 			}
11124 
11125 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
11126 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
11127 
11128 			if (*bufp != NULL) {
11129 				dtrace_dof_error(dof, difo[i].msg);
11130 				goto err;
11131 			}
11132 
11133 			if (difo[i].entsize != subsec->dofs_entsize) {
11134 				dtrace_dof_error(dof, "entry size mismatch");
11135 				goto err;
11136 			}
11137 
11138 			if (subsec->dofs_entsize != 0 &&
11139 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
11140 				dtrace_dof_error(dof, "corrupt entry size");
11141 				goto err;
11142 			}
11143 
11144 			*lenp = subsec->dofs_size;
11145 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
11146 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
11147 			    *bufp, subsec->dofs_size);
11148 
11149 			if (subsec->dofs_entsize != 0)
11150 				*lenp /= subsec->dofs_entsize;
11151 
11152 			break;
11153 		}
11154 
11155 		/*
11156 		 * If we encounter a loadable DIFO sub-section that is not
11157 		 * known to us, assume this is a broken program and fail.
11158 		 */
11159 		if (difo[i].section == DOF_SECT_NONE &&
11160 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
11161 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
11162 			goto err;
11163 		}
11164 	}
11165 
11166 	if (dp->dtdo_buf == NULL) {
11167 		/*
11168 		 * We can't have a DIF object without DIF text.
11169 		 */
11170 		dtrace_dof_error(dof, "missing DIF text");
11171 		goto err;
11172 	}
11173 
11174 	/*
11175 	 * Before we validate the DIF object, run through the variable table
11176 	 * looking for the strings -- if any of their size are under, we'll set
11177 	 * their size to be the system-wide default string size.  Note that
11178 	 * this should _not_ happen if the "strsize" option has been set --
11179 	 * in this case, the compiler should have set the size to reflect the
11180 	 * setting of the option.
11181 	 */
11182 	for (i = 0; i < dp->dtdo_varlen; i++) {
11183 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
11184 		dtrace_diftype_t *t = &v->dtdv_type;
11185 
11186 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
11187 			continue;
11188 
11189 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
11190 			t->dtdt_size = dtrace_strsize_default;
11191 	}
11192 
11193 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
11194 		goto err;
11195 
11196 	dtrace_difo_init(dp, vstate);
11197 	return (dp);
11198 
11199 err:
11200 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
11201 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
11202 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
11203 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
11204 
11205 	kmem_free(dp, sizeof (dtrace_difo_t));
11206 	return (NULL);
11207 }
11208 
11209 static dtrace_predicate_t *
11210 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11211     cred_t *cr)
11212 {
11213 	dtrace_difo_t *dp;
11214 
11215 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
11216 		return (NULL);
11217 
11218 	return (dtrace_predicate_create(dp));
11219 }
11220 
11221 static dtrace_actdesc_t *
11222 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11223     cred_t *cr)
11224 {
11225 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
11226 	dof_actdesc_t *desc;
11227 	dof_sec_t *difosec;
11228 	size_t offs;
11229 	uintptr_t daddr = (uintptr_t)dof;
11230 	uint64_t arg;
11231 	dtrace_actkind_t kind;
11232 
11233 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
11234 		dtrace_dof_error(dof, "invalid action section");
11235 		return (NULL);
11236 	}
11237 
11238 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
11239 		dtrace_dof_error(dof, "truncated action description");
11240 		return (NULL);
11241 	}
11242 
11243 	if (sec->dofs_align != sizeof (uint64_t)) {
11244 		dtrace_dof_error(dof, "bad alignment in action description");
11245 		return (NULL);
11246 	}
11247 
11248 	if (sec->dofs_size < sec->dofs_entsize) {
11249 		dtrace_dof_error(dof, "section entry size exceeds total size");
11250 		return (NULL);
11251 	}
11252 
11253 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
11254 		dtrace_dof_error(dof, "bad entry size in action description");
11255 		return (NULL);
11256 	}
11257 
11258 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
11259 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
11260 		return (NULL);
11261 	}
11262 
11263 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
11264 		desc = (dof_actdesc_t *)(daddr +
11265 		    (uintptr_t)sec->dofs_offset + offs);
11266 		kind = (dtrace_actkind_t)desc->dofa_kind;
11267 
11268 		if (DTRACEACT_ISPRINTFLIKE(kind) &&
11269 		    (kind != DTRACEACT_PRINTA ||
11270 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
11271 			dof_sec_t *strtab;
11272 			char *str, *fmt;
11273 			uint64_t i;
11274 
11275 			/*
11276 			 * printf()-like actions must have a format string.
11277 			 */
11278 			if ((strtab = dtrace_dof_sect(dof,
11279 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
11280 				goto err;
11281 
11282 			str = (char *)((uintptr_t)dof +
11283 			    (uintptr_t)strtab->dofs_offset);
11284 
11285 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
11286 				if (str[i] == '\0')
11287 					break;
11288 			}
11289 
11290 			if (i >= strtab->dofs_size) {
11291 				dtrace_dof_error(dof, "bogus format string");
11292 				goto err;
11293 			}
11294 
11295 			if (i == desc->dofa_arg) {
11296 				dtrace_dof_error(dof, "empty format string");
11297 				goto err;
11298 			}
11299 
11300 			i -= desc->dofa_arg;
11301 			fmt = kmem_alloc(i + 1, KM_SLEEP);
11302 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
11303 			arg = (uint64_t)(uintptr_t)fmt;
11304 		} else {
11305 			if (kind == DTRACEACT_PRINTA) {
11306 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
11307 				arg = 0;
11308 			} else {
11309 				arg = desc->dofa_arg;
11310 			}
11311 		}
11312 
11313 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
11314 		    desc->dofa_uarg, arg);
11315 
11316 		if (last != NULL) {
11317 			last->dtad_next = act;
11318 		} else {
11319 			first = act;
11320 		}
11321 
11322 		last = act;
11323 
11324 		if (desc->dofa_difo == DOF_SECIDX_NONE)
11325 			continue;
11326 
11327 		if ((difosec = dtrace_dof_sect(dof,
11328 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
11329 			goto err;
11330 
11331 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
11332 
11333 		if (act->dtad_difo == NULL)
11334 			goto err;
11335 	}
11336 
11337 	ASSERT(first != NULL);
11338 	return (first);
11339 
11340 err:
11341 	for (act = first; act != NULL; act = next) {
11342 		next = act->dtad_next;
11343 		dtrace_actdesc_release(act, vstate);
11344 	}
11345 
11346 	return (NULL);
11347 }
11348 
11349 static dtrace_ecbdesc_t *
11350 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
11351     cred_t *cr)
11352 {
11353 	dtrace_ecbdesc_t *ep;
11354 	dof_ecbdesc_t *ecb;
11355 	dtrace_probedesc_t *desc;
11356 	dtrace_predicate_t *pred = NULL;
11357 
11358 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
11359 		dtrace_dof_error(dof, "truncated ECB description");
11360 		return (NULL);
11361 	}
11362 
11363 	if (sec->dofs_align != sizeof (uint64_t)) {
11364 		dtrace_dof_error(dof, "bad alignment in ECB description");
11365 		return (NULL);
11366 	}
11367 
11368 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
11369 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
11370 
11371 	if (sec == NULL)
11372 		return (NULL);
11373 
11374 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
11375 	ep->dted_uarg = ecb->dofe_uarg;
11376 	desc = &ep->dted_probe;
11377 
11378 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
11379 		goto err;
11380 
11381 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
11382 		if ((sec = dtrace_dof_sect(dof,
11383 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
11384 			goto err;
11385 
11386 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
11387 			goto err;
11388 
11389 		ep->dted_pred.dtpdd_predicate = pred;
11390 	}
11391 
11392 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
11393 		if ((sec = dtrace_dof_sect(dof,
11394 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
11395 			goto err;
11396 
11397 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
11398 
11399 		if (ep->dted_action == NULL)
11400 			goto err;
11401 	}
11402 
11403 	return (ep);
11404 
11405 err:
11406 	if (pred != NULL)
11407 		dtrace_predicate_release(pred, vstate);
11408 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
11409 	return (NULL);
11410 }
11411 
11412 /*
11413  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
11414  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
11415  * site of any user SETX relocations to account for load object base address.
11416  * In the future, if we need other relocations, this function can be extended.
11417  */
11418 static int
11419 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
11420 {
11421 	uintptr_t daddr = (uintptr_t)dof;
11422 	dof_relohdr_t *dofr =
11423 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
11424 	dof_sec_t *ss, *rs, *ts;
11425 	dof_relodesc_t *r;
11426 	uint_t i, n;
11427 
11428 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
11429 	    sec->dofs_align != sizeof (dof_secidx_t)) {
11430 		dtrace_dof_error(dof, "invalid relocation header");
11431 		return (-1);
11432 	}
11433 
11434 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
11435 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
11436 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
11437 
11438 	if (ss == NULL || rs == NULL || ts == NULL)
11439 		return (-1); /* dtrace_dof_error() has been called already */
11440 
11441 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
11442 	    rs->dofs_align != sizeof (uint64_t)) {
11443 		dtrace_dof_error(dof, "invalid relocation section");
11444 		return (-1);
11445 	}
11446 
11447 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
11448 	n = rs->dofs_size / rs->dofs_entsize;
11449 
11450 	for (i = 0; i < n; i++) {
11451 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
11452 
11453 		switch (r->dofr_type) {
11454 		case DOF_RELO_NONE:
11455 			break;
11456 		case DOF_RELO_SETX:
11457 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
11458 			    sizeof (uint64_t) > ts->dofs_size) {
11459 				dtrace_dof_error(dof, "bad relocation offset");
11460 				return (-1);
11461 			}
11462 
11463 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
11464 				dtrace_dof_error(dof, "misaligned setx relo");
11465 				return (-1);
11466 			}
11467 
11468 			*(uint64_t *)taddr += ubase;
11469 			break;
11470 		default:
11471 			dtrace_dof_error(dof, "invalid relocation type");
11472 			return (-1);
11473 		}
11474 
11475 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
11476 	}
11477 
11478 	return (0);
11479 }
11480 
11481 /*
11482  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
11483  * header:  it should be at the front of a memory region that is at least
11484  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
11485  * size.  It need not be validated in any other way.
11486  */
11487 static int
11488 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
11489     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
11490 {
11491 	uint64_t len = dof->dofh_loadsz, seclen;
11492 	uintptr_t daddr = (uintptr_t)dof;
11493 	dtrace_ecbdesc_t *ep;
11494 	dtrace_enabling_t *enab;
11495 	uint_t i;
11496 
11497 	ASSERT(MUTEX_HELD(&dtrace_lock));
11498 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
11499 
11500 	/*
11501 	 * Check the DOF header identification bytes.  In addition to checking
11502 	 * valid settings, we also verify that unused bits/bytes are zeroed so
11503 	 * we can use them later without fear of regressing existing binaries.
11504 	 */
11505 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
11506 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
11507 		dtrace_dof_error(dof, "DOF magic string mismatch");
11508 		return (-1);
11509 	}
11510 
11511 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
11512 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
11513 		dtrace_dof_error(dof, "DOF has invalid data model");
11514 		return (-1);
11515 	}
11516 
11517 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
11518 		dtrace_dof_error(dof, "DOF encoding mismatch");
11519 		return (-1);
11520 	}
11521 
11522 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
11523 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
11524 		dtrace_dof_error(dof, "DOF version mismatch");
11525 		return (-1);
11526 	}
11527 
11528 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
11529 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
11530 		return (-1);
11531 	}
11532 
11533 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
11534 		dtrace_dof_error(dof, "DOF uses too many integer registers");
11535 		return (-1);
11536 	}
11537 
11538 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
11539 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
11540 		return (-1);
11541 	}
11542 
11543 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
11544 		if (dof->dofh_ident[i] != 0) {
11545 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
11546 			return (-1);
11547 		}
11548 	}
11549 
11550 	if (dof->dofh_flags & ~DOF_FL_VALID) {
11551 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
11552 		return (-1);
11553 	}
11554 
11555 	if (dof->dofh_secsize == 0) {
11556 		dtrace_dof_error(dof, "zero section header size");
11557 		return (-1);
11558 	}
11559 
11560 	/*
11561 	 * Check that the section headers don't exceed the amount of DOF
11562 	 * data.  Note that we cast the section size and number of sections
11563 	 * to uint64_t's to prevent possible overflow in the multiplication.
11564 	 */
11565 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
11566 
11567 	if (dof->dofh_secoff > len || seclen > len ||
11568 	    dof->dofh_secoff + seclen > len) {
11569 		dtrace_dof_error(dof, "truncated section headers");
11570 		return (-1);
11571 	}
11572 
11573 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
11574 		dtrace_dof_error(dof, "misaligned section headers");
11575 		return (-1);
11576 	}
11577 
11578 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
11579 		dtrace_dof_error(dof, "misaligned section size");
11580 		return (-1);
11581 	}
11582 
11583 	/*
11584 	 * Take an initial pass through the section headers to be sure that
11585 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
11586 	 * set, do not permit sections relating to providers, probes, or args.
11587 	 */
11588 	for (i = 0; i < dof->dofh_secnum; i++) {
11589 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11590 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11591 
11592 		if (noprobes) {
11593 			switch (sec->dofs_type) {
11594 			case DOF_SECT_PROVIDER:
11595 			case DOF_SECT_PROBES:
11596 			case DOF_SECT_PRARGS:
11597 			case DOF_SECT_PROFFS:
11598 				dtrace_dof_error(dof, "illegal sections "
11599 				    "for enabling");
11600 				return (-1);
11601 			}
11602 		}
11603 
11604 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
11605 			continue; /* just ignore non-loadable sections */
11606 
11607 		if (sec->dofs_align & (sec->dofs_align - 1)) {
11608 			dtrace_dof_error(dof, "bad section alignment");
11609 			return (-1);
11610 		}
11611 
11612 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
11613 			dtrace_dof_error(dof, "misaligned section");
11614 			return (-1);
11615 		}
11616 
11617 		if (sec->dofs_offset > len || sec->dofs_size > len ||
11618 		    sec->dofs_offset + sec->dofs_size > len) {
11619 			dtrace_dof_error(dof, "corrupt section header");
11620 			return (-1);
11621 		}
11622 
11623 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
11624 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
11625 			dtrace_dof_error(dof, "non-terminating string table");
11626 			return (-1);
11627 		}
11628 	}
11629 
11630 	/*
11631 	 * Take a second pass through the sections and locate and perform any
11632 	 * relocations that are present.  We do this after the first pass to
11633 	 * be sure that all sections have had their headers validated.
11634 	 */
11635 	for (i = 0; i < dof->dofh_secnum; i++) {
11636 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11637 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11638 
11639 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
11640 			continue; /* skip sections that are not loadable */
11641 
11642 		switch (sec->dofs_type) {
11643 		case DOF_SECT_URELHDR:
11644 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
11645 				return (-1);
11646 			break;
11647 		}
11648 	}
11649 
11650 	if ((enab = *enabp) == NULL)
11651 		enab = *enabp = dtrace_enabling_create(vstate);
11652 
11653 	for (i = 0; i < dof->dofh_secnum; i++) {
11654 		dof_sec_t *sec = (dof_sec_t *)(daddr +
11655 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11656 
11657 		if (sec->dofs_type != DOF_SECT_ECBDESC)
11658 			continue;
11659 
11660 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
11661 			dtrace_enabling_destroy(enab);
11662 			*enabp = NULL;
11663 			return (-1);
11664 		}
11665 
11666 		dtrace_enabling_add(enab, ep);
11667 	}
11668 
11669 	return (0);
11670 }
11671 
11672 /*
11673  * Process DOF for any options.  This routine assumes that the DOF has been
11674  * at least processed by dtrace_dof_slurp().
11675  */
11676 static int
11677 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
11678 {
11679 	int i, rval;
11680 	uint32_t entsize;
11681 	size_t offs;
11682 	dof_optdesc_t *desc;
11683 
11684 	for (i = 0; i < dof->dofh_secnum; i++) {
11685 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
11686 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
11687 
11688 		if (sec->dofs_type != DOF_SECT_OPTDESC)
11689 			continue;
11690 
11691 		if (sec->dofs_align != sizeof (uint64_t)) {
11692 			dtrace_dof_error(dof, "bad alignment in "
11693 			    "option description");
11694 			return (EINVAL);
11695 		}
11696 
11697 		if ((entsize = sec->dofs_entsize) == 0) {
11698 			dtrace_dof_error(dof, "zeroed option entry size");
11699 			return (EINVAL);
11700 		}
11701 
11702 		if (entsize < sizeof (dof_optdesc_t)) {
11703 			dtrace_dof_error(dof, "bad option entry size");
11704 			return (EINVAL);
11705 		}
11706 
11707 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
11708 			desc = (dof_optdesc_t *)((uintptr_t)dof +
11709 			    (uintptr_t)sec->dofs_offset + offs);
11710 
11711 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
11712 				dtrace_dof_error(dof, "non-zero option string");
11713 				return (EINVAL);
11714 			}
11715 
11716 			if (desc->dofo_value == DTRACEOPT_UNSET) {
11717 				dtrace_dof_error(dof, "unset option");
11718 				return (EINVAL);
11719 			}
11720 
11721 			if ((rval = dtrace_state_option(state,
11722 			    desc->dofo_option, desc->dofo_value)) != 0) {
11723 				dtrace_dof_error(dof, "rejected option");
11724 				return (rval);
11725 			}
11726 		}
11727 	}
11728 
11729 	return (0);
11730 }
11731 
11732 /*
11733  * DTrace Consumer State Functions
11734  */
11735 int
11736 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
11737 {
11738 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
11739 	void *base;
11740 	uintptr_t limit;
11741 	dtrace_dynvar_t *dvar, *next, *start;
11742 	int i;
11743 
11744 	ASSERT(MUTEX_HELD(&dtrace_lock));
11745 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
11746 
11747 	bzero(dstate, sizeof (dtrace_dstate_t));
11748 
11749 	if ((dstate->dtds_chunksize = chunksize) == 0)
11750 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
11751 
11752 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
11753 		size = min;
11754 
11755 	if ((base = kmem_zalloc(size, KM_NOSLEEP)) == NULL)
11756 		return (ENOMEM);
11757 
11758 	dstate->dtds_size = size;
11759 	dstate->dtds_base = base;
11760 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
11761 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
11762 
11763 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
11764 
11765 	if (hashsize != 1 && (hashsize & 1))
11766 		hashsize--;
11767 
11768 	dstate->dtds_hashsize = hashsize;
11769 	dstate->dtds_hash = dstate->dtds_base;
11770 
11771 	/*
11772 	 * Set all of our hash buckets to point to the single sink, and (if
11773 	 * it hasn't already been set), set the sink's hash value to be the
11774 	 * sink sentinel value.  The sink is needed for dynamic variable
11775 	 * lookups to know that they have iterated over an entire, valid hash
11776 	 * chain.
11777 	 */
11778 	for (i = 0; i < hashsize; i++)
11779 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
11780 
11781 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
11782 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
11783 
11784 	/*
11785 	 * Determine number of active CPUs.  Divide free list evenly among
11786 	 * active CPUs.
11787 	 */
11788 	start = (dtrace_dynvar_t *)
11789 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
11790 	limit = (uintptr_t)base + size;
11791 
11792 	maxper = (limit - (uintptr_t)start) / NCPU;
11793 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
11794 
11795 	for (i = 0; i < NCPU; i++) {
11796 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
11797 
11798 		/*
11799 		 * If we don't even have enough chunks to make it once through
11800 		 * NCPUs, we're just going to allocate everything to the first
11801 		 * CPU.  And if we're on the last CPU, we're going to allocate
11802 		 * whatever is left over.  In either case, we set the limit to
11803 		 * be the limit of the dynamic variable space.
11804 		 */
11805 		if (maxper == 0 || i == NCPU - 1) {
11806 			limit = (uintptr_t)base + size;
11807 			start = NULL;
11808 		} else {
11809 			limit = (uintptr_t)start + maxper;
11810 			start = (dtrace_dynvar_t *)limit;
11811 		}
11812 
11813 		ASSERT(limit <= (uintptr_t)base + size);
11814 
11815 		for (;;) {
11816 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
11817 			    dstate->dtds_chunksize);
11818 
11819 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
11820 				break;
11821 
11822 			dvar->dtdv_next = next;
11823 			dvar = next;
11824 		}
11825 
11826 		if (maxper == 0)
11827 			break;
11828 	}
11829 
11830 	return (0);
11831 }
11832 
11833 void
11834 dtrace_dstate_fini(dtrace_dstate_t *dstate)
11835 {
11836 	ASSERT(MUTEX_HELD(&cpu_lock));
11837 
11838 	if (dstate->dtds_base == NULL)
11839 		return;
11840 
11841 	kmem_free(dstate->dtds_base, dstate->dtds_size);
11842 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
11843 }
11844 
11845 static void
11846 dtrace_vstate_fini(dtrace_vstate_t *vstate)
11847 {
11848 	/*
11849 	 * Logical XOR, where are you?
11850 	 */
11851 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
11852 
11853 	if (vstate->dtvs_nglobals > 0) {
11854 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
11855 		    sizeof (dtrace_statvar_t *));
11856 	}
11857 
11858 	if (vstate->dtvs_ntlocals > 0) {
11859 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
11860 		    sizeof (dtrace_difv_t));
11861 	}
11862 
11863 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
11864 
11865 	if (vstate->dtvs_nlocals > 0) {
11866 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
11867 		    sizeof (dtrace_statvar_t *));
11868 	}
11869 }
11870 
11871 static void
11872 dtrace_state_clean(dtrace_state_t *state)
11873 {
11874 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
11875 		return;
11876 
11877 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
11878 	dtrace_speculation_clean(state);
11879 }
11880 
11881 static void
11882 dtrace_state_deadman(dtrace_state_t *state)
11883 {
11884 	hrtime_t now;
11885 
11886 	dtrace_sync();
11887 
11888 	now = dtrace_gethrtime();
11889 
11890 	if (state != dtrace_anon.dta_state &&
11891 	    now - state->dts_laststatus >= dtrace_deadman_user)
11892 		return;
11893 
11894 	/*
11895 	 * We must be sure that dts_alive never appears to be less than the
11896 	 * value upon entry to dtrace_state_deadman(), and because we lack a
11897 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
11898 	 * store INT64_MAX to it, followed by a memory barrier, followed by
11899 	 * the new value.  This assures that dts_alive never appears to be
11900 	 * less than its true value, regardless of the order in which the
11901 	 * stores to the underlying storage are issued.
11902 	 */
11903 	state->dts_alive = INT64_MAX;
11904 	dtrace_membar_producer();
11905 	state->dts_alive = now;
11906 }
11907 
11908 dtrace_state_t *
11909 dtrace_state_create(dev_t *devp, cred_t *cr)
11910 {
11911 	minor_t minor;
11912 	major_t major;
11913 	char c[30];
11914 	dtrace_state_t *state;
11915 	dtrace_optval_t *opt;
11916 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
11917 
11918 	ASSERT(MUTEX_HELD(&dtrace_lock));
11919 	ASSERT(MUTEX_HELD(&cpu_lock));
11920 
11921 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
11922 	    VM_BESTFIT | VM_SLEEP);
11923 
11924 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
11925 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
11926 		return (NULL);
11927 	}
11928 
11929 	state = ddi_get_soft_state(dtrace_softstate, minor);
11930 	state->dts_epid = DTRACE_EPIDNONE + 1;
11931 
11932 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
11933 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
11934 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
11935 
11936 	if (devp != NULL) {
11937 		major = getemajor(*devp);
11938 	} else {
11939 		major = ddi_driver_major(dtrace_devi);
11940 	}
11941 
11942 	state->dts_dev = makedevice(major, minor);
11943 
11944 	if (devp != NULL)
11945 		*devp = state->dts_dev;
11946 
11947 	/*
11948 	 * We allocate NCPU buffers.  On the one hand, this can be quite
11949 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
11950 	 * other hand, it saves an additional memory reference in the probe
11951 	 * path.
11952 	 */
11953 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
11954 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
11955 	state->dts_cleaner = CYCLIC_NONE;
11956 	state->dts_deadman = CYCLIC_NONE;
11957 	state->dts_vstate.dtvs_state = state;
11958 
11959 	for (i = 0; i < DTRACEOPT_MAX; i++)
11960 		state->dts_options[i] = DTRACEOPT_UNSET;
11961 
11962 	/*
11963 	 * Set the default options.
11964 	 */
11965 	opt = state->dts_options;
11966 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
11967 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
11968 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
11969 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
11970 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
11971 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
11972 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
11973 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
11974 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
11975 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
11976 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
11977 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
11978 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
11979 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
11980 
11981 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
11982 
11983 	/*
11984 	 * Depending on the user credentials, we set flag bits which alter probe
11985 	 * visibility or the amount of destructiveness allowed.  In the case of
11986 	 * actual anonymous tracing, or the possession of all privileges, all of
11987 	 * the normal checks are bypassed.
11988 	 */
11989 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
11990 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
11991 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
11992 	} else {
11993 		/*
11994 		 * Set up the credentials for this instantiation.  We take a
11995 		 * hold on the credential to prevent it from disappearing on
11996 		 * us; this in turn prevents the zone_t referenced by this
11997 		 * credential from disappearing.  This means that we can
11998 		 * examine the credential and the zone from probe context.
11999 		 */
12000 		crhold(cr);
12001 		state->dts_cred.dcr_cred = cr;
12002 
12003 		/*
12004 		 * CRA_PROC means "we have *some* privilege for dtrace" and
12005 		 * unlocks the use of variables like pid, zonename, etc.
12006 		 */
12007 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
12008 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12009 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
12010 		}
12011 
12012 		/*
12013 		 * dtrace_user allows use of syscall and profile providers.
12014 		 * If the user also has proc_owner and/or proc_zone, we
12015 		 * extend the scope to include additional visibility and
12016 		 * destructive power.
12017 		 */
12018 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
12019 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
12020 				state->dts_cred.dcr_visible |=
12021 				    DTRACE_CRV_ALLPROC;
12022 
12023 				state->dts_cred.dcr_action |=
12024 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12025 			}
12026 
12027 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
12028 				state->dts_cred.dcr_visible |=
12029 				    DTRACE_CRV_ALLZONE;
12030 
12031 				state->dts_cred.dcr_action |=
12032 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12033 			}
12034 
12035 			/*
12036 			 * If we have all privs in whatever zone this is,
12037 			 * we can do destructive things to processes which
12038 			 * have altered credentials.
12039 			 */
12040 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12041 			    cr->cr_zone->zone_privset)) {
12042 				state->dts_cred.dcr_action |=
12043 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12044 			}
12045 		}
12046 
12047 		/*
12048 		 * Holding the dtrace_kernel privilege also implies that
12049 		 * the user has the dtrace_user privilege from a visibility
12050 		 * perspective.  But without further privileges, some
12051 		 * destructive actions are not available.
12052 		 */
12053 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
12054 			/*
12055 			 * Make all probes in all zones visible.  However,
12056 			 * this doesn't mean that all actions become available
12057 			 * to all zones.
12058 			 */
12059 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
12060 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
12061 
12062 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
12063 			    DTRACE_CRA_PROC;
12064 			/*
12065 			 * Holding proc_owner means that destructive actions
12066 			 * for *this* zone are allowed.
12067 			 */
12068 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12069 				state->dts_cred.dcr_action |=
12070 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12071 
12072 			/*
12073 			 * Holding proc_zone means that destructive actions
12074 			 * for this user/group ID in all zones is allowed.
12075 			 */
12076 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12077 				state->dts_cred.dcr_action |=
12078 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12079 
12080 			/*
12081 			 * If we have all privs in whatever zone this is,
12082 			 * we can do destructive things to processes which
12083 			 * have altered credentials.
12084 			 */
12085 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
12086 			    cr->cr_zone->zone_privset)) {
12087 				state->dts_cred.dcr_action |=
12088 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
12089 			}
12090 		}
12091 
12092 		/*
12093 		 * Holding the dtrace_proc privilege gives control over fasttrap
12094 		 * and pid providers.  We need to grant wider destructive
12095 		 * privileges in the event that the user has proc_owner and/or
12096 		 * proc_zone.
12097 		 */
12098 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
12099 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
12100 				state->dts_cred.dcr_action |=
12101 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
12102 
12103 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
12104 				state->dts_cred.dcr_action |=
12105 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
12106 		}
12107 	}
12108 
12109 	return (state);
12110 }
12111 
12112 static int
12113 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
12114 {
12115 	dtrace_optval_t *opt = state->dts_options, size;
12116 	processorid_t cpu;
12117 	int flags = 0, rval;
12118 
12119 	ASSERT(MUTEX_HELD(&dtrace_lock));
12120 	ASSERT(MUTEX_HELD(&cpu_lock));
12121 	ASSERT(which < DTRACEOPT_MAX);
12122 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
12123 	    (state == dtrace_anon.dta_state &&
12124 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
12125 
12126 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
12127 		return (0);
12128 
12129 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
12130 		cpu = opt[DTRACEOPT_CPU];
12131 
12132 	if (which == DTRACEOPT_SPECSIZE)
12133 		flags |= DTRACEBUF_NOSWITCH;
12134 
12135 	if (which == DTRACEOPT_BUFSIZE) {
12136 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
12137 			flags |= DTRACEBUF_RING;
12138 
12139 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
12140 			flags |= DTRACEBUF_FILL;
12141 
12142 		if (state != dtrace_anon.dta_state ||
12143 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
12144 			flags |= DTRACEBUF_INACTIVE;
12145 	}
12146 
12147 	for (size = opt[which]; size >= sizeof (uint64_t); size >>= 1) {
12148 		/*
12149 		 * The size must be 8-byte aligned.  If the size is not 8-byte
12150 		 * aligned, drop it down by the difference.
12151 		 */
12152 		if (size & (sizeof (uint64_t) - 1))
12153 			size -= size & (sizeof (uint64_t) - 1);
12154 
12155 		if (size < state->dts_reserve) {
12156 			/*
12157 			 * Buffers always must be large enough to accommodate
12158 			 * their prereserved space.  We return E2BIG instead
12159 			 * of ENOMEM in this case to allow for user-level
12160 			 * software to differentiate the cases.
12161 			 */
12162 			return (E2BIG);
12163 		}
12164 
12165 		rval = dtrace_buffer_alloc(buf, size, flags, cpu);
12166 
12167 		if (rval != ENOMEM) {
12168 			opt[which] = size;
12169 			return (rval);
12170 		}
12171 
12172 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12173 			return (rval);
12174 	}
12175 
12176 	return (ENOMEM);
12177 }
12178 
12179 static int
12180 dtrace_state_buffers(dtrace_state_t *state)
12181 {
12182 	dtrace_speculation_t *spec = state->dts_speculations;
12183 	int rval, i;
12184 
12185 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
12186 	    DTRACEOPT_BUFSIZE)) != 0)
12187 		return (rval);
12188 
12189 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
12190 	    DTRACEOPT_AGGSIZE)) != 0)
12191 		return (rval);
12192 
12193 	for (i = 0; i < state->dts_nspeculations; i++) {
12194 		if ((rval = dtrace_state_buffer(state,
12195 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
12196 			return (rval);
12197 	}
12198 
12199 	return (0);
12200 }
12201 
12202 static void
12203 dtrace_state_prereserve(dtrace_state_t *state)
12204 {
12205 	dtrace_ecb_t *ecb;
12206 	dtrace_probe_t *probe;
12207 
12208 	state->dts_reserve = 0;
12209 
12210 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
12211 		return;
12212 
12213 	/*
12214 	 * If our buffer policy is a "fill" buffer policy, we need to set the
12215 	 * prereserved space to be the space required by the END probes.
12216 	 */
12217 	probe = dtrace_probes[dtrace_probeid_end - 1];
12218 	ASSERT(probe != NULL);
12219 
12220 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
12221 		if (ecb->dte_state != state)
12222 			continue;
12223 
12224 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
12225 	}
12226 }
12227 
12228 static int
12229 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
12230 {
12231 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
12232 	dtrace_speculation_t *spec;
12233 	dtrace_buffer_t *buf;
12234 	cyc_handler_t hdlr;
12235 	cyc_time_t when;
12236 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12237 	dtrace_icookie_t cookie;
12238 
12239 	mutex_enter(&cpu_lock);
12240 	mutex_enter(&dtrace_lock);
12241 
12242 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
12243 		rval = EBUSY;
12244 		goto out;
12245 	}
12246 
12247 	/*
12248 	 * Before we can perform any checks, we must prime all of the
12249 	 * retained enablings that correspond to this state.
12250 	 */
12251 	dtrace_enabling_prime(state);
12252 
12253 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
12254 		rval = EACCES;
12255 		goto out;
12256 	}
12257 
12258 	dtrace_state_prereserve(state);
12259 
12260 	/*
12261 	 * Now we want to do is try to allocate our speculations.
12262 	 * We do not automatically resize the number of speculations; if
12263 	 * this fails, we will fail the operation.
12264 	 */
12265 	nspec = opt[DTRACEOPT_NSPEC];
12266 	ASSERT(nspec != DTRACEOPT_UNSET);
12267 
12268 	if (nspec > INT_MAX) {
12269 		rval = ENOMEM;
12270 		goto out;
12271 	}
12272 
12273 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t), KM_NOSLEEP);
12274 
12275 	if (spec == NULL) {
12276 		rval = ENOMEM;
12277 		goto out;
12278 	}
12279 
12280 	state->dts_speculations = spec;
12281 	state->dts_nspeculations = (int)nspec;
12282 
12283 	for (i = 0; i < nspec; i++) {
12284 		if ((buf = kmem_zalloc(bufsize, KM_NOSLEEP)) == NULL) {
12285 			rval = ENOMEM;
12286 			goto err;
12287 		}
12288 
12289 		spec[i].dtsp_buffer = buf;
12290 	}
12291 
12292 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
12293 		if (dtrace_anon.dta_state == NULL) {
12294 			rval = ENOENT;
12295 			goto out;
12296 		}
12297 
12298 		if (state->dts_necbs != 0) {
12299 			rval = EALREADY;
12300 			goto out;
12301 		}
12302 
12303 		state->dts_anon = dtrace_anon_grab();
12304 		ASSERT(state->dts_anon != NULL);
12305 		state = state->dts_anon;
12306 
12307 		/*
12308 		 * We want "grabanon" to be set in the grabbed state, so we'll
12309 		 * copy that option value from the grabbing state into the
12310 		 * grabbed state.
12311 		 */
12312 		state->dts_options[DTRACEOPT_GRABANON] =
12313 		    opt[DTRACEOPT_GRABANON];
12314 
12315 		*cpu = dtrace_anon.dta_beganon;
12316 
12317 		/*
12318 		 * If the anonymous state is active (as it almost certainly
12319 		 * is if the anonymous enabling ultimately matched anything),
12320 		 * we don't allow any further option processing -- but we
12321 		 * don't return failure.
12322 		 */
12323 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12324 			goto out;
12325 	}
12326 
12327 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
12328 	    opt[DTRACEOPT_AGGSIZE] != 0) {
12329 		if (state->dts_aggregations == NULL) {
12330 			/*
12331 			 * We're not going to create an aggregation buffer
12332 			 * because we don't have any ECBs that contain
12333 			 * aggregations -- set this option to 0.
12334 			 */
12335 			opt[DTRACEOPT_AGGSIZE] = 0;
12336 		} else {
12337 			/*
12338 			 * If we have an aggregation buffer, we must also have
12339 			 * a buffer to use as scratch.
12340 			 */
12341 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
12342 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
12343 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
12344 			}
12345 		}
12346 	}
12347 
12348 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
12349 	    opt[DTRACEOPT_SPECSIZE] != 0) {
12350 		if (!state->dts_speculates) {
12351 			/*
12352 			 * We're not going to create speculation buffers
12353 			 * because we don't have any ECBs that actually
12354 			 * speculate -- set the speculation size to 0.
12355 			 */
12356 			opt[DTRACEOPT_SPECSIZE] = 0;
12357 		}
12358 	}
12359 
12360 	/*
12361 	 * The bare minimum size for any buffer that we're actually going to
12362 	 * do anything to is sizeof (uint64_t).
12363 	 */
12364 	sz = sizeof (uint64_t);
12365 
12366 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
12367 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
12368 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
12369 		/*
12370 		 * A buffer size has been explicitly set to 0 (or to a size
12371 		 * that will be adjusted to 0) and we need the space -- we
12372 		 * need to return failure.  We return ENOSPC to differentiate
12373 		 * it from failing to allocate a buffer due to failure to meet
12374 		 * the reserve (for which we return E2BIG).
12375 		 */
12376 		rval = ENOSPC;
12377 		goto out;
12378 	}
12379 
12380 	if ((rval = dtrace_state_buffers(state)) != 0)
12381 		goto err;
12382 
12383 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
12384 		sz = dtrace_dstate_defsize;
12385 
12386 	do {
12387 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
12388 
12389 		if (rval == 0)
12390 			break;
12391 
12392 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
12393 			goto err;
12394 	} while (sz >>= 1);
12395 
12396 	opt[DTRACEOPT_DYNVARSIZE] = sz;
12397 
12398 	if (rval != 0)
12399 		goto err;
12400 
12401 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
12402 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
12403 
12404 	if (opt[DTRACEOPT_CLEANRATE] == 0)
12405 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12406 
12407 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
12408 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
12409 
12410 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
12411 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
12412 
12413 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
12414 	hdlr.cyh_arg = state;
12415 	hdlr.cyh_level = CY_LOW_LEVEL;
12416 
12417 	when.cyt_when = 0;
12418 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
12419 
12420 	state->dts_cleaner = cyclic_add(&hdlr, &when);
12421 
12422 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
12423 	hdlr.cyh_arg = state;
12424 	hdlr.cyh_level = CY_LOW_LEVEL;
12425 
12426 	when.cyt_when = 0;
12427 	when.cyt_interval = dtrace_deadman_interval;
12428 
12429 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
12430 	state->dts_deadman = cyclic_add(&hdlr, &when);
12431 
12432 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
12433 
12434 	/*
12435 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
12436 	 * interrupts here both to record the CPU on which we fired the BEGIN
12437 	 * probe (the data from this CPU will be processed first at user
12438 	 * level) and to manually activate the buffer for this CPU.
12439 	 */
12440 	cookie = dtrace_interrupt_disable();
12441 	*cpu = CPU->cpu_id;
12442 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
12443 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
12444 
12445 	dtrace_probe(dtrace_probeid_begin,
12446 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
12447 	dtrace_interrupt_enable(cookie);
12448 	/*
12449 	 * We may have had an exit action from a BEGIN probe; only change our
12450 	 * state to ACTIVE if we're still in WARMUP.
12451 	 */
12452 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
12453 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
12454 
12455 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
12456 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
12457 
12458 	/*
12459 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
12460 	 * want each CPU to transition its principal buffer out of the
12461 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
12462 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
12463 	 * atomically transition from processing none of a state's ECBs to
12464 	 * processing all of them.
12465 	 */
12466 	dtrace_xcall(DTRACE_CPUALL,
12467 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
12468 	goto out;
12469 
12470 err:
12471 	dtrace_buffer_free(state->dts_buffer);
12472 	dtrace_buffer_free(state->dts_aggbuffer);
12473 
12474 	if ((nspec = state->dts_nspeculations) == 0) {
12475 		ASSERT(state->dts_speculations == NULL);
12476 		goto out;
12477 	}
12478 
12479 	spec = state->dts_speculations;
12480 	ASSERT(spec != NULL);
12481 
12482 	for (i = 0; i < state->dts_nspeculations; i++) {
12483 		if ((buf = spec[i].dtsp_buffer) == NULL)
12484 			break;
12485 
12486 		dtrace_buffer_free(buf);
12487 		kmem_free(buf, bufsize);
12488 	}
12489 
12490 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
12491 	state->dts_nspeculations = 0;
12492 	state->dts_speculations = NULL;
12493 
12494 out:
12495 	mutex_exit(&dtrace_lock);
12496 	mutex_exit(&cpu_lock);
12497 
12498 	return (rval);
12499 }
12500 
12501 static int
12502 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
12503 {
12504 	dtrace_icookie_t cookie;
12505 
12506 	ASSERT(MUTEX_HELD(&dtrace_lock));
12507 
12508 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
12509 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
12510 		return (EINVAL);
12511 
12512 	/*
12513 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
12514 	 * to be sure that every CPU has seen it.  See below for the details
12515 	 * on why this is done.
12516 	 */
12517 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
12518 	dtrace_sync();
12519 
12520 	/*
12521 	 * By this point, it is impossible for any CPU to be still processing
12522 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
12523 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
12524 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
12525 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
12526 	 * iff we're in the END probe.
12527 	 */
12528 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
12529 	dtrace_sync();
12530 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
12531 
12532 	/*
12533 	 * Finally, we can release the reserve and call the END probe.  We
12534 	 * disable interrupts across calling the END probe to allow us to
12535 	 * return the CPU on which we actually called the END probe.  This
12536 	 * allows user-land to be sure that this CPU's principal buffer is
12537 	 * processed last.
12538 	 */
12539 	state->dts_reserve = 0;
12540 
12541 	cookie = dtrace_interrupt_disable();
12542 	*cpu = CPU->cpu_id;
12543 	dtrace_probe(dtrace_probeid_end,
12544 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
12545 	dtrace_interrupt_enable(cookie);
12546 
12547 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
12548 	dtrace_sync();
12549 
12550 	return (0);
12551 }
12552 
12553 static int
12554 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
12555     dtrace_optval_t val)
12556 {
12557 	ASSERT(MUTEX_HELD(&dtrace_lock));
12558 
12559 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
12560 		return (EBUSY);
12561 
12562 	if (option >= DTRACEOPT_MAX)
12563 		return (EINVAL);
12564 
12565 	if (option != DTRACEOPT_CPU && val < 0)
12566 		return (EINVAL);
12567 
12568 	switch (option) {
12569 	case DTRACEOPT_DESTRUCTIVE:
12570 		if (dtrace_destructive_disallow)
12571 			return (EACCES);
12572 
12573 		state->dts_cred.dcr_destructive = 1;
12574 		break;
12575 
12576 	case DTRACEOPT_BUFSIZE:
12577 	case DTRACEOPT_DYNVARSIZE:
12578 	case DTRACEOPT_AGGSIZE:
12579 	case DTRACEOPT_SPECSIZE:
12580 	case DTRACEOPT_STRSIZE:
12581 		if (val < 0)
12582 			return (EINVAL);
12583 
12584 		if (val >= LONG_MAX) {
12585 			/*
12586 			 * If this is an otherwise negative value, set it to
12587 			 * the highest multiple of 128m less than LONG_MAX.
12588 			 * Technically, we're adjusting the size without
12589 			 * regard to the buffer resizing policy, but in fact,
12590 			 * this has no effect -- if we set the buffer size to
12591 			 * ~LONG_MAX and the buffer policy is ultimately set to
12592 			 * be "manual", the buffer allocation is guaranteed to
12593 			 * fail, if only because the allocation requires two
12594 			 * buffers.  (We set the the size to the highest
12595 			 * multiple of 128m because it ensures that the size
12596 			 * will remain a multiple of a megabyte when
12597 			 * repeatedly halved -- all the way down to 15m.)
12598 			 */
12599 			val = LONG_MAX - (1 << 27) + 1;
12600 		}
12601 	}
12602 
12603 	state->dts_options[option] = val;
12604 
12605 	return (0);
12606 }
12607 
12608 static void
12609 dtrace_state_destroy(dtrace_state_t *state)
12610 {
12611 	dtrace_ecb_t *ecb;
12612 	dtrace_vstate_t *vstate = &state->dts_vstate;
12613 	minor_t minor = getminor(state->dts_dev);
12614 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
12615 	dtrace_speculation_t *spec = state->dts_speculations;
12616 	int nspec = state->dts_nspeculations;
12617 	uint32_t match;
12618 
12619 	ASSERT(MUTEX_HELD(&dtrace_lock));
12620 	ASSERT(MUTEX_HELD(&cpu_lock));
12621 
12622 	/*
12623 	 * First, retract any retained enablings for this state.
12624 	 */
12625 	dtrace_enabling_retract(state);
12626 	ASSERT(state->dts_nretained == 0);
12627 
12628 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
12629 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
12630 		/*
12631 		 * We have managed to come into dtrace_state_destroy() on a
12632 		 * hot enabling -- almost certainly because of a disorderly
12633 		 * shutdown of a consumer.  (That is, a consumer that is
12634 		 * exiting without having called dtrace_stop().) In this case,
12635 		 * we're going to set our activity to be KILLED, and then
12636 		 * issue a sync to be sure that everyone is out of probe
12637 		 * context before we start blowing away ECBs.
12638 		 */
12639 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
12640 		dtrace_sync();
12641 	}
12642 
12643 	/*
12644 	 * Release the credential hold we took in dtrace_state_create().
12645 	 */
12646 	if (state->dts_cred.dcr_cred != NULL)
12647 		crfree(state->dts_cred.dcr_cred);
12648 
12649 	/*
12650 	 * Now we can safely disable and destroy any enabled probes.  Because
12651 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
12652 	 * (especially if they're all enabled), we take two passes through the
12653 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
12654 	 * in the second we disable whatever is left over.
12655 	 */
12656 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
12657 		for (i = 0; i < state->dts_necbs; i++) {
12658 			if ((ecb = state->dts_ecbs[i]) == NULL)
12659 				continue;
12660 
12661 			if (match && ecb->dte_probe != NULL) {
12662 				dtrace_probe_t *probe = ecb->dte_probe;
12663 				dtrace_provider_t *prov = probe->dtpr_provider;
12664 
12665 				if (!(prov->dtpv_priv.dtpp_flags & match))
12666 					continue;
12667 			}
12668 
12669 			dtrace_ecb_disable(ecb);
12670 			dtrace_ecb_destroy(ecb);
12671 		}
12672 
12673 		if (!match)
12674 			break;
12675 	}
12676 
12677 	/*
12678 	 * Before we free the buffers, perform one more sync to assure that
12679 	 * every CPU is out of probe context.
12680 	 */
12681 	dtrace_sync();
12682 
12683 	dtrace_buffer_free(state->dts_buffer);
12684 	dtrace_buffer_free(state->dts_aggbuffer);
12685 
12686 	for (i = 0; i < nspec; i++)
12687 		dtrace_buffer_free(spec[i].dtsp_buffer);
12688 
12689 	if (state->dts_cleaner != CYCLIC_NONE)
12690 		cyclic_remove(state->dts_cleaner);
12691 
12692 	if (state->dts_deadman != CYCLIC_NONE)
12693 		cyclic_remove(state->dts_deadman);
12694 
12695 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
12696 	dtrace_vstate_fini(vstate);
12697 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
12698 
12699 	if (state->dts_aggregations != NULL) {
12700 #ifdef DEBUG
12701 		for (i = 0; i < state->dts_naggregations; i++)
12702 			ASSERT(state->dts_aggregations[i] == NULL);
12703 #endif
12704 		ASSERT(state->dts_naggregations > 0);
12705 		kmem_free(state->dts_aggregations,
12706 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
12707 	}
12708 
12709 	kmem_free(state->dts_buffer, bufsize);
12710 	kmem_free(state->dts_aggbuffer, bufsize);
12711 
12712 	for (i = 0; i < nspec; i++)
12713 		kmem_free(spec[i].dtsp_buffer, bufsize);
12714 
12715 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
12716 
12717 	dtrace_format_destroy(state);
12718 
12719 	vmem_destroy(state->dts_aggid_arena);
12720 	ddi_soft_state_free(dtrace_softstate, minor);
12721 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
12722 }
12723 
12724 /*
12725  * DTrace Anonymous Enabling Functions
12726  */
12727 static dtrace_state_t *
12728 dtrace_anon_grab(void)
12729 {
12730 	dtrace_state_t *state;
12731 
12732 	ASSERT(MUTEX_HELD(&dtrace_lock));
12733 
12734 	if ((state = dtrace_anon.dta_state) == NULL) {
12735 		ASSERT(dtrace_anon.dta_enabling == NULL);
12736 		return (NULL);
12737 	}
12738 
12739 	ASSERT(dtrace_anon.dta_enabling != NULL);
12740 	ASSERT(dtrace_retained != NULL);
12741 
12742 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
12743 	dtrace_anon.dta_enabling = NULL;
12744 	dtrace_anon.dta_state = NULL;
12745 
12746 	return (state);
12747 }
12748 
12749 static void
12750 dtrace_anon_property(void)
12751 {
12752 	int i, rv;
12753 	dtrace_state_t *state;
12754 	dof_hdr_t *dof;
12755 	char c[32];		/* enough for "dof-data-" + digits */
12756 
12757 	ASSERT(MUTEX_HELD(&dtrace_lock));
12758 	ASSERT(MUTEX_HELD(&cpu_lock));
12759 
12760 	for (i = 0; ; i++) {
12761 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
12762 
12763 		dtrace_err_verbose = 1;
12764 
12765 		if ((dof = dtrace_dof_property(c)) == NULL) {
12766 			dtrace_err_verbose = 0;
12767 			break;
12768 		}
12769 
12770 		/*
12771 		 * We want to create anonymous state, so we need to transition
12772 		 * the kernel debugger to indicate that DTrace is active.  If
12773 		 * this fails (e.g. because the debugger has modified text in
12774 		 * some way), we won't continue with the processing.
12775 		 */
12776 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
12777 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
12778 			    "enabling ignored.");
12779 			dtrace_dof_destroy(dof);
12780 			break;
12781 		}
12782 
12783 		/*
12784 		 * If we haven't allocated an anonymous state, we'll do so now.
12785 		 */
12786 		if ((state = dtrace_anon.dta_state) == NULL) {
12787 			state = dtrace_state_create(NULL, NULL);
12788 			dtrace_anon.dta_state = state;
12789 
12790 			if (state == NULL) {
12791 				/*
12792 				 * This basically shouldn't happen:  the only
12793 				 * failure mode from dtrace_state_create() is a
12794 				 * failure of ddi_soft_state_zalloc() that
12795 				 * itself should never happen.  Still, the
12796 				 * interface allows for a failure mode, and
12797 				 * we want to fail as gracefully as possible:
12798 				 * we'll emit an error message and cease
12799 				 * processing anonymous state in this case.
12800 				 */
12801 				cmn_err(CE_WARN, "failed to create "
12802 				    "anonymous state");
12803 				dtrace_dof_destroy(dof);
12804 				break;
12805 			}
12806 		}
12807 
12808 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
12809 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
12810 
12811 		if (rv == 0)
12812 			rv = dtrace_dof_options(dof, state);
12813 
12814 		dtrace_err_verbose = 0;
12815 		dtrace_dof_destroy(dof);
12816 
12817 		if (rv != 0) {
12818 			/*
12819 			 * This is malformed DOF; chuck any anonymous state
12820 			 * that we created.
12821 			 */
12822 			ASSERT(dtrace_anon.dta_enabling == NULL);
12823 			dtrace_state_destroy(state);
12824 			dtrace_anon.dta_state = NULL;
12825 			break;
12826 		}
12827 
12828 		ASSERT(dtrace_anon.dta_enabling != NULL);
12829 	}
12830 
12831 	if (dtrace_anon.dta_enabling != NULL) {
12832 		int rval;
12833 
12834 		/*
12835 		 * dtrace_enabling_retain() can only fail because we are
12836 		 * trying to retain more enablings than are allowed -- but
12837 		 * we only have one anonymous enabling, and we are guaranteed
12838 		 * to be allowed at least one retained enabling; we assert
12839 		 * that dtrace_enabling_retain() returns success.
12840 		 */
12841 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
12842 		ASSERT(rval == 0);
12843 
12844 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
12845 	}
12846 }
12847 
12848 /*
12849  * DTrace Helper Functions
12850  */
12851 static void
12852 dtrace_helper_trace(dtrace_helper_action_t *helper,
12853     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
12854 {
12855 	uint32_t size, next, nnext, i;
12856 	dtrace_helptrace_t *ent;
12857 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12858 
12859 	if (!dtrace_helptrace_enabled)
12860 		return;
12861 
12862 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
12863 
12864 	/*
12865 	 * What would a tracing framework be without its own tracing
12866 	 * framework?  (Well, a hell of a lot simpler, for starters...)
12867 	 */
12868 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
12869 	    sizeof (uint64_t) - sizeof (uint64_t);
12870 
12871 	/*
12872 	 * Iterate until we can allocate a slot in the trace buffer.
12873 	 */
12874 	do {
12875 		next = dtrace_helptrace_next;
12876 
12877 		if (next + size < dtrace_helptrace_bufsize) {
12878 			nnext = next + size;
12879 		} else {
12880 			nnext = size;
12881 		}
12882 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
12883 
12884 	/*
12885 	 * We have our slot; fill it in.
12886 	 */
12887 	if (nnext == size)
12888 		next = 0;
12889 
12890 	ent = (dtrace_helptrace_t *)&dtrace_helptrace_buffer[next];
12891 	ent->dtht_helper = helper;
12892 	ent->dtht_where = where;
12893 	ent->dtht_nlocals = vstate->dtvs_nlocals;
12894 
12895 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
12896 	    mstate->dtms_fltoffs : -1;
12897 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
12898 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
12899 
12900 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
12901 		dtrace_statvar_t *svar;
12902 
12903 		if ((svar = vstate->dtvs_locals[i]) == NULL)
12904 			continue;
12905 
12906 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
12907 		ent->dtht_locals[i] =
12908 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
12909 	}
12910 }
12911 
12912 static uint64_t
12913 dtrace_helper(int which, dtrace_mstate_t *mstate,
12914     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
12915 {
12916 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
12917 	uint64_t sarg0 = mstate->dtms_arg[0];
12918 	uint64_t sarg1 = mstate->dtms_arg[1];
12919 	uint64_t rval;
12920 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
12921 	dtrace_helper_action_t *helper;
12922 	dtrace_vstate_t *vstate;
12923 	dtrace_difo_t *pred;
12924 	int i, trace = dtrace_helptrace_enabled;
12925 
12926 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
12927 
12928 	if (helpers == NULL)
12929 		return (0);
12930 
12931 	if ((helper = helpers->dthps_actions[which]) == NULL)
12932 		return (0);
12933 
12934 	vstate = &helpers->dthps_vstate;
12935 	mstate->dtms_arg[0] = arg0;
12936 	mstate->dtms_arg[1] = arg1;
12937 
12938 	/*
12939 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
12940 	 * we'll call the corresponding actions.  Note that the below calls
12941 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
12942 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
12943 	 * the stored DIF offset with its own (which is the desired behavior).
12944 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
12945 	 * from machine state; this is okay, too.
12946 	 */
12947 	for (; helper != NULL; helper = helper->dtha_next) {
12948 		if ((pred = helper->dtha_predicate) != NULL) {
12949 			if (trace)
12950 				dtrace_helper_trace(helper, mstate, vstate, 0);
12951 
12952 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
12953 				goto next;
12954 
12955 			if (*flags & CPU_DTRACE_FAULT)
12956 				goto err;
12957 		}
12958 
12959 		for (i = 0; i < helper->dtha_nactions; i++) {
12960 			if (trace)
12961 				dtrace_helper_trace(helper,
12962 				    mstate, vstate, i + 1);
12963 
12964 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
12965 			    mstate, vstate, state);
12966 
12967 			if (*flags & CPU_DTRACE_FAULT)
12968 				goto err;
12969 		}
12970 
12971 next:
12972 		if (trace)
12973 			dtrace_helper_trace(helper, mstate, vstate,
12974 			    DTRACE_HELPTRACE_NEXT);
12975 	}
12976 
12977 	if (trace)
12978 		dtrace_helper_trace(helper, mstate, vstate,
12979 		    DTRACE_HELPTRACE_DONE);
12980 
12981 	/*
12982 	 * Restore the arg0 that we saved upon entry.
12983 	 */
12984 	mstate->dtms_arg[0] = sarg0;
12985 	mstate->dtms_arg[1] = sarg1;
12986 
12987 	return (rval);
12988 
12989 err:
12990 	if (trace)
12991 		dtrace_helper_trace(helper, mstate, vstate,
12992 		    DTRACE_HELPTRACE_ERR);
12993 
12994 	/*
12995 	 * Restore the arg0 that we saved upon entry.
12996 	 */
12997 	mstate->dtms_arg[0] = sarg0;
12998 	mstate->dtms_arg[1] = sarg1;
12999 
13000 	return (NULL);
13001 }
13002 
13003 static void
13004 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
13005     dtrace_vstate_t *vstate)
13006 {
13007 	int i;
13008 
13009 	if (helper->dtha_predicate != NULL)
13010 		dtrace_difo_release(helper->dtha_predicate, vstate);
13011 
13012 	for (i = 0; i < helper->dtha_nactions; i++) {
13013 		ASSERT(helper->dtha_actions[i] != NULL);
13014 		dtrace_difo_release(helper->dtha_actions[i], vstate);
13015 	}
13016 
13017 	kmem_free(helper->dtha_actions,
13018 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
13019 	kmem_free(helper, sizeof (dtrace_helper_action_t));
13020 }
13021 
13022 static int
13023 dtrace_helper_destroygen(int gen)
13024 {
13025 	proc_t *p = curproc;
13026 	dtrace_helpers_t *help = p->p_dtrace_helpers;
13027 	dtrace_vstate_t *vstate;
13028 	int i;
13029 
13030 	ASSERT(MUTEX_HELD(&dtrace_lock));
13031 
13032 	if (help == NULL || gen > help->dthps_generation)
13033 		return (EINVAL);
13034 
13035 	vstate = &help->dthps_vstate;
13036 
13037 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13038 		dtrace_helper_action_t *last = NULL, *h, *next;
13039 
13040 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13041 			next = h->dtha_next;
13042 
13043 			if (h->dtha_generation == gen) {
13044 				if (last != NULL) {
13045 					last->dtha_next = next;
13046 				} else {
13047 					help->dthps_actions[i] = next;
13048 				}
13049 
13050 				dtrace_helper_action_destroy(h, vstate);
13051 			} else {
13052 				last = h;
13053 			}
13054 		}
13055 	}
13056 
13057 	/*
13058 	 * Interate until we've cleared out all helper providers with the
13059 	 * given generation number.
13060 	 */
13061 	for (;;) {
13062 		dtrace_helper_provider_t *prov;
13063 
13064 		/*
13065 		 * Look for a helper provider with the right generation. We
13066 		 * have to start back at the beginning of the list each time
13067 		 * because we drop dtrace_lock. It's unlikely that we'll make
13068 		 * more than two passes.
13069 		 */
13070 		for (i = 0; i < help->dthps_nprovs; i++) {
13071 			prov = help->dthps_provs[i];
13072 
13073 			if (prov->dthp_generation == gen)
13074 				break;
13075 		}
13076 
13077 		/*
13078 		 * If there were no matches, we're done.
13079 		 */
13080 		if (i == help->dthps_nprovs)
13081 			break;
13082 
13083 		/*
13084 		 * Move the last helper provider into this slot.
13085 		 */
13086 		help->dthps_nprovs--;
13087 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
13088 		help->dthps_provs[help->dthps_nprovs] = NULL;
13089 
13090 		mutex_exit(&dtrace_lock);
13091 
13092 		/*
13093 		 * If we have a meta provider, remove this helper provider.
13094 		 */
13095 		mutex_enter(&dtrace_meta_lock);
13096 		if (dtrace_meta_pid != NULL) {
13097 			ASSERT(dtrace_deferred_pid == NULL);
13098 			dtrace_helper_provider_remove(&prov->dthp_prov,
13099 			    p->p_pid);
13100 		}
13101 		mutex_exit(&dtrace_meta_lock);
13102 
13103 		dtrace_helper_provider_destroy(prov);
13104 
13105 		mutex_enter(&dtrace_lock);
13106 	}
13107 
13108 	return (0);
13109 }
13110 
13111 static int
13112 dtrace_helper_validate(dtrace_helper_action_t *helper)
13113 {
13114 	int err = 0, i;
13115 	dtrace_difo_t *dp;
13116 
13117 	if ((dp = helper->dtha_predicate) != NULL)
13118 		err += dtrace_difo_validate_helper(dp);
13119 
13120 	for (i = 0; i < helper->dtha_nactions; i++)
13121 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
13122 
13123 	return (err == 0);
13124 }
13125 
13126 static int
13127 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
13128 {
13129 	dtrace_helpers_t *help;
13130 	dtrace_helper_action_t *helper, *last;
13131 	dtrace_actdesc_t *act;
13132 	dtrace_vstate_t *vstate;
13133 	dtrace_predicate_t *pred;
13134 	int count = 0, nactions = 0, i;
13135 
13136 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
13137 		return (EINVAL);
13138 
13139 	help = curproc->p_dtrace_helpers;
13140 	last = help->dthps_actions[which];
13141 	vstate = &help->dthps_vstate;
13142 
13143 	for (count = 0; last != NULL; last = last->dtha_next) {
13144 		count++;
13145 		if (last->dtha_next == NULL)
13146 			break;
13147 	}
13148 
13149 	/*
13150 	 * If we already have dtrace_helper_actions_max helper actions for this
13151 	 * helper action type, we'll refuse to add a new one.
13152 	 */
13153 	if (count >= dtrace_helper_actions_max)
13154 		return (ENOSPC);
13155 
13156 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
13157 	helper->dtha_generation = help->dthps_generation;
13158 
13159 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
13160 		ASSERT(pred->dtp_difo != NULL);
13161 		dtrace_difo_hold(pred->dtp_difo);
13162 		helper->dtha_predicate = pred->dtp_difo;
13163 	}
13164 
13165 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
13166 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
13167 			goto err;
13168 
13169 		if (act->dtad_difo == NULL)
13170 			goto err;
13171 
13172 		nactions++;
13173 	}
13174 
13175 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
13176 	    (helper->dtha_nactions = nactions), KM_SLEEP);
13177 
13178 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
13179 		dtrace_difo_hold(act->dtad_difo);
13180 		helper->dtha_actions[i++] = act->dtad_difo;
13181 	}
13182 
13183 	if (!dtrace_helper_validate(helper))
13184 		goto err;
13185 
13186 	if (last == NULL) {
13187 		help->dthps_actions[which] = helper;
13188 	} else {
13189 		last->dtha_next = helper;
13190 	}
13191 
13192 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
13193 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
13194 		dtrace_helptrace_next = 0;
13195 	}
13196 
13197 	return (0);
13198 err:
13199 	dtrace_helper_action_destroy(helper, vstate);
13200 	return (EINVAL);
13201 }
13202 
13203 static void
13204 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
13205     dof_helper_t *dofhp)
13206 {
13207 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
13208 
13209 	mutex_enter(&dtrace_meta_lock);
13210 	mutex_enter(&dtrace_lock);
13211 
13212 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
13213 		/*
13214 		 * If the dtrace module is loaded but not attached, or if
13215 		 * there aren't isn't a meta provider registered to deal with
13216 		 * these provider descriptions, we need to postpone creating
13217 		 * the actual providers until later.
13218 		 */
13219 
13220 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
13221 		    dtrace_deferred_pid != help) {
13222 			help->dthps_deferred = 1;
13223 			help->dthps_pid = p->p_pid;
13224 			help->dthps_next = dtrace_deferred_pid;
13225 			help->dthps_prev = NULL;
13226 			if (dtrace_deferred_pid != NULL)
13227 				dtrace_deferred_pid->dthps_prev = help;
13228 			dtrace_deferred_pid = help;
13229 		}
13230 
13231 		mutex_exit(&dtrace_lock);
13232 
13233 	} else if (dofhp != NULL) {
13234 		/*
13235 		 * If the dtrace module is loaded and we have a particular
13236 		 * helper provider description, pass that off to the
13237 		 * meta provider.
13238 		 */
13239 
13240 		mutex_exit(&dtrace_lock);
13241 
13242 		dtrace_helper_provide(dofhp, p->p_pid);
13243 
13244 	} else {
13245 		/*
13246 		 * Otherwise, just pass all the helper provider descriptions
13247 		 * off to the meta provider.
13248 		 */
13249 
13250 		int i;
13251 		mutex_exit(&dtrace_lock);
13252 
13253 		for (i = 0; i < help->dthps_nprovs; i++) {
13254 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
13255 			    p->p_pid);
13256 		}
13257 	}
13258 
13259 	mutex_exit(&dtrace_meta_lock);
13260 }
13261 
13262 static int
13263 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
13264 {
13265 	dtrace_helpers_t *help;
13266 	dtrace_helper_provider_t *hprov, **tmp_provs;
13267 	uint_t tmp_maxprovs, i;
13268 
13269 	ASSERT(MUTEX_HELD(&dtrace_lock));
13270 
13271 	help = curproc->p_dtrace_helpers;
13272 	ASSERT(help != NULL);
13273 
13274 	/*
13275 	 * If we already have dtrace_helper_providers_max helper providers,
13276 	 * we're refuse to add a new one.
13277 	 */
13278 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
13279 		return (ENOSPC);
13280 
13281 	/*
13282 	 * Check to make sure this isn't a duplicate.
13283 	 */
13284 	for (i = 0; i < help->dthps_nprovs; i++) {
13285 		if (dofhp->dofhp_addr ==
13286 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
13287 			return (EALREADY);
13288 	}
13289 
13290 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
13291 	hprov->dthp_prov = *dofhp;
13292 	hprov->dthp_ref = 1;
13293 	hprov->dthp_generation = gen;
13294 
13295 	/*
13296 	 * Allocate a bigger table for helper providers if it's already full.
13297 	 */
13298 	if (help->dthps_maxprovs == help->dthps_nprovs) {
13299 		tmp_maxprovs = help->dthps_maxprovs;
13300 		tmp_provs = help->dthps_provs;
13301 
13302 		if (help->dthps_maxprovs == 0)
13303 			help->dthps_maxprovs = 2;
13304 		else
13305 			help->dthps_maxprovs *= 2;
13306 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
13307 			help->dthps_maxprovs = dtrace_helper_providers_max;
13308 
13309 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
13310 
13311 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
13312 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13313 
13314 		if (tmp_provs != NULL) {
13315 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
13316 			    sizeof (dtrace_helper_provider_t *));
13317 			kmem_free(tmp_provs, tmp_maxprovs *
13318 			    sizeof (dtrace_helper_provider_t *));
13319 		}
13320 	}
13321 
13322 	help->dthps_provs[help->dthps_nprovs] = hprov;
13323 	help->dthps_nprovs++;
13324 
13325 	return (0);
13326 }
13327 
13328 static void
13329 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
13330 {
13331 	mutex_enter(&dtrace_lock);
13332 
13333 	if (--hprov->dthp_ref == 0) {
13334 		dof_hdr_t *dof;
13335 		mutex_exit(&dtrace_lock);
13336 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
13337 		dtrace_dof_destroy(dof);
13338 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
13339 	} else {
13340 		mutex_exit(&dtrace_lock);
13341 	}
13342 }
13343 
13344 static int
13345 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
13346 {
13347 	uintptr_t daddr = (uintptr_t)dof;
13348 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
13349 	dof_provider_t *provider;
13350 	dof_probe_t *probe;
13351 	uint8_t *arg;
13352 	char *strtab, *typestr;
13353 	dof_stridx_t typeidx;
13354 	size_t typesz;
13355 	uint_t nprobes, j, k;
13356 
13357 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
13358 
13359 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
13360 		dtrace_dof_error(dof, "misaligned section offset");
13361 		return (-1);
13362 	}
13363 
13364 	/*
13365 	 * The section needs to be large enough to contain the DOF provider
13366 	 * structure appropriate for the given version.
13367 	 */
13368 	if (sec->dofs_size <
13369 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
13370 	    offsetof(dof_provider_t, dofpv_prenoffs) :
13371 	    sizeof (dof_provider_t))) {
13372 		dtrace_dof_error(dof, "provider section too small");
13373 		return (-1);
13374 	}
13375 
13376 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
13377 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
13378 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
13379 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
13380 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
13381 
13382 	if (str_sec == NULL || prb_sec == NULL ||
13383 	    arg_sec == NULL || off_sec == NULL)
13384 		return (-1);
13385 
13386 	enoff_sec = NULL;
13387 
13388 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13389 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
13390 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
13391 	    provider->dofpv_prenoffs)) == NULL)
13392 		return (-1);
13393 
13394 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
13395 
13396 	if (provider->dofpv_name >= str_sec->dofs_size ||
13397 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
13398 		dtrace_dof_error(dof, "invalid provider name");
13399 		return (-1);
13400 	}
13401 
13402 	if (prb_sec->dofs_entsize == 0 ||
13403 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
13404 		dtrace_dof_error(dof, "invalid entry size");
13405 		return (-1);
13406 	}
13407 
13408 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
13409 		dtrace_dof_error(dof, "misaligned entry size");
13410 		return (-1);
13411 	}
13412 
13413 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
13414 		dtrace_dof_error(dof, "invalid entry size");
13415 		return (-1);
13416 	}
13417 
13418 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
13419 		dtrace_dof_error(dof, "misaligned section offset");
13420 		return (-1);
13421 	}
13422 
13423 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
13424 		dtrace_dof_error(dof, "invalid entry size");
13425 		return (-1);
13426 	}
13427 
13428 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
13429 
13430 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
13431 
13432 	/*
13433 	 * Take a pass through the probes to check for errors.
13434 	 */
13435 	for (j = 0; j < nprobes; j++) {
13436 		probe = (dof_probe_t *)(uintptr_t)(daddr +
13437 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
13438 
13439 		if (probe->dofpr_func >= str_sec->dofs_size) {
13440 			dtrace_dof_error(dof, "invalid function name");
13441 			return (-1);
13442 		}
13443 
13444 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
13445 			dtrace_dof_error(dof, "function name too long");
13446 			return (-1);
13447 		}
13448 
13449 		if (probe->dofpr_name >= str_sec->dofs_size ||
13450 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
13451 			dtrace_dof_error(dof, "invalid probe name");
13452 			return (-1);
13453 		}
13454 
13455 		/*
13456 		 * The offset count must not wrap the index, and the offsets
13457 		 * must also not overflow the section's data.
13458 		 */
13459 		if (probe->dofpr_offidx + probe->dofpr_noffs <
13460 		    probe->dofpr_offidx ||
13461 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
13462 		    off_sec->dofs_entsize > off_sec->dofs_size) {
13463 			dtrace_dof_error(dof, "invalid probe offset");
13464 			return (-1);
13465 		}
13466 
13467 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
13468 			/*
13469 			 * If there's no is-enabled offset section, make sure
13470 			 * there aren't any is-enabled offsets. Otherwise
13471 			 * perform the same checks as for probe offsets
13472 			 * (immediately above).
13473 			 */
13474 			if (enoff_sec == NULL) {
13475 				if (probe->dofpr_enoffidx != 0 ||
13476 				    probe->dofpr_nenoffs != 0) {
13477 					dtrace_dof_error(dof, "is-enabled "
13478 					    "offsets with null section");
13479 					return (-1);
13480 				}
13481 			} else if (probe->dofpr_enoffidx +
13482 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
13483 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
13484 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
13485 				dtrace_dof_error(dof, "invalid is-enabled "
13486 				    "offset");
13487 				return (-1);
13488 			}
13489 
13490 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
13491 				dtrace_dof_error(dof, "zero probe and "
13492 				    "is-enabled offsets");
13493 				return (-1);
13494 			}
13495 		} else if (probe->dofpr_noffs == 0) {
13496 			dtrace_dof_error(dof, "zero probe offsets");
13497 			return (-1);
13498 		}
13499 
13500 		if (probe->dofpr_argidx + probe->dofpr_xargc <
13501 		    probe->dofpr_argidx ||
13502 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
13503 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
13504 			dtrace_dof_error(dof, "invalid args");
13505 			return (-1);
13506 		}
13507 
13508 		typeidx = probe->dofpr_nargv;
13509 		typestr = strtab + probe->dofpr_nargv;
13510 		for (k = 0; k < probe->dofpr_nargc; k++) {
13511 			if (typeidx >= str_sec->dofs_size) {
13512 				dtrace_dof_error(dof, "bad "
13513 				    "native argument type");
13514 				return (-1);
13515 			}
13516 
13517 			typesz = strlen(typestr) + 1;
13518 			if (typesz > DTRACE_ARGTYPELEN) {
13519 				dtrace_dof_error(dof, "native "
13520 				    "argument type too long");
13521 				return (-1);
13522 			}
13523 			typeidx += typesz;
13524 			typestr += typesz;
13525 		}
13526 
13527 		typeidx = probe->dofpr_xargv;
13528 		typestr = strtab + probe->dofpr_xargv;
13529 		for (k = 0; k < probe->dofpr_xargc; k++) {
13530 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
13531 				dtrace_dof_error(dof, "bad "
13532 				    "native argument index");
13533 				return (-1);
13534 			}
13535 
13536 			if (typeidx >= str_sec->dofs_size) {
13537 				dtrace_dof_error(dof, "bad "
13538 				    "translated argument type");
13539 				return (-1);
13540 			}
13541 
13542 			typesz = strlen(typestr) + 1;
13543 			if (typesz > DTRACE_ARGTYPELEN) {
13544 				dtrace_dof_error(dof, "translated argument "
13545 				    "type too long");
13546 				return (-1);
13547 			}
13548 
13549 			typeidx += typesz;
13550 			typestr += typesz;
13551 		}
13552 	}
13553 
13554 	return (0);
13555 }
13556 
13557 static int
13558 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
13559 {
13560 	dtrace_helpers_t *help;
13561 	dtrace_vstate_t *vstate;
13562 	dtrace_enabling_t *enab = NULL;
13563 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
13564 	uintptr_t daddr = (uintptr_t)dof;
13565 
13566 	ASSERT(MUTEX_HELD(&dtrace_lock));
13567 
13568 	if ((help = curproc->p_dtrace_helpers) == NULL)
13569 		help = dtrace_helpers_create(curproc);
13570 
13571 	vstate = &help->dthps_vstate;
13572 
13573 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
13574 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
13575 		dtrace_dof_destroy(dof);
13576 		return (rv);
13577 	}
13578 
13579 	/*
13580 	 * Look for helper providers and validate their descriptions.
13581 	 */
13582 	if (dhp != NULL) {
13583 		for (i = 0; i < dof->dofh_secnum; i++) {
13584 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
13585 			    dof->dofh_secoff + i * dof->dofh_secsize);
13586 
13587 			if (sec->dofs_type != DOF_SECT_PROVIDER)
13588 				continue;
13589 
13590 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
13591 				dtrace_enabling_destroy(enab);
13592 				dtrace_dof_destroy(dof);
13593 				return (-1);
13594 			}
13595 
13596 			nprovs++;
13597 		}
13598 	}
13599 
13600 	/*
13601 	 * Now we need to walk through the ECB descriptions in the enabling.
13602 	 */
13603 	for (i = 0; i < enab->dten_ndesc; i++) {
13604 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
13605 		dtrace_probedesc_t *desc = &ep->dted_probe;
13606 
13607 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
13608 			continue;
13609 
13610 		if (strcmp(desc->dtpd_mod, "helper") != 0)
13611 			continue;
13612 
13613 		if (strcmp(desc->dtpd_func, "ustack") != 0)
13614 			continue;
13615 
13616 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
13617 		    ep)) != 0) {
13618 			/*
13619 			 * Adding this helper action failed -- we are now going
13620 			 * to rip out the entire generation and return failure.
13621 			 */
13622 			(void) dtrace_helper_destroygen(help->dthps_generation);
13623 			dtrace_enabling_destroy(enab);
13624 			dtrace_dof_destroy(dof);
13625 			return (-1);
13626 		}
13627 
13628 		nhelpers++;
13629 	}
13630 
13631 	if (nhelpers < enab->dten_ndesc)
13632 		dtrace_dof_error(dof, "unmatched helpers");
13633 
13634 	gen = help->dthps_generation++;
13635 	dtrace_enabling_destroy(enab);
13636 
13637 	if (dhp != NULL && nprovs > 0) {
13638 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
13639 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
13640 			mutex_exit(&dtrace_lock);
13641 			dtrace_helper_provider_register(curproc, help, dhp);
13642 			mutex_enter(&dtrace_lock);
13643 
13644 			destroy = 0;
13645 		}
13646 	}
13647 
13648 	if (destroy)
13649 		dtrace_dof_destroy(dof);
13650 
13651 	return (gen);
13652 }
13653 
13654 static dtrace_helpers_t *
13655 dtrace_helpers_create(proc_t *p)
13656 {
13657 	dtrace_helpers_t *help;
13658 
13659 	ASSERT(MUTEX_HELD(&dtrace_lock));
13660 	ASSERT(p->p_dtrace_helpers == NULL);
13661 
13662 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
13663 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
13664 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
13665 
13666 	p->p_dtrace_helpers = help;
13667 	dtrace_helpers++;
13668 
13669 	return (help);
13670 }
13671 
13672 static void
13673 dtrace_helpers_destroy(void)
13674 {
13675 	dtrace_helpers_t *help;
13676 	dtrace_vstate_t *vstate;
13677 	proc_t *p = curproc;
13678 	int i;
13679 
13680 	mutex_enter(&dtrace_lock);
13681 
13682 	ASSERT(p->p_dtrace_helpers != NULL);
13683 	ASSERT(dtrace_helpers > 0);
13684 
13685 	help = p->p_dtrace_helpers;
13686 	vstate = &help->dthps_vstate;
13687 
13688 	/*
13689 	 * We're now going to lose the help from this process.
13690 	 */
13691 	p->p_dtrace_helpers = NULL;
13692 	dtrace_sync();
13693 
13694 	/*
13695 	 * Destory the helper actions.
13696 	 */
13697 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13698 		dtrace_helper_action_t *h, *next;
13699 
13700 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
13701 			next = h->dtha_next;
13702 			dtrace_helper_action_destroy(h, vstate);
13703 			h = next;
13704 		}
13705 	}
13706 
13707 	mutex_exit(&dtrace_lock);
13708 
13709 	/*
13710 	 * Destroy the helper providers.
13711 	 */
13712 	if (help->dthps_maxprovs > 0) {
13713 		mutex_enter(&dtrace_meta_lock);
13714 		if (dtrace_meta_pid != NULL) {
13715 			ASSERT(dtrace_deferred_pid == NULL);
13716 
13717 			for (i = 0; i < help->dthps_nprovs; i++) {
13718 				dtrace_helper_provider_remove(
13719 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
13720 			}
13721 		} else {
13722 			mutex_enter(&dtrace_lock);
13723 			ASSERT(help->dthps_deferred == 0 ||
13724 			    help->dthps_next != NULL ||
13725 			    help->dthps_prev != NULL ||
13726 			    help == dtrace_deferred_pid);
13727 
13728 			/*
13729 			 * Remove the helper from the deferred list.
13730 			 */
13731 			if (help->dthps_next != NULL)
13732 				help->dthps_next->dthps_prev = help->dthps_prev;
13733 			if (help->dthps_prev != NULL)
13734 				help->dthps_prev->dthps_next = help->dthps_next;
13735 			if (dtrace_deferred_pid == help) {
13736 				dtrace_deferred_pid = help->dthps_next;
13737 				ASSERT(help->dthps_prev == NULL);
13738 			}
13739 
13740 			mutex_exit(&dtrace_lock);
13741 		}
13742 
13743 		mutex_exit(&dtrace_meta_lock);
13744 
13745 		for (i = 0; i < help->dthps_nprovs; i++) {
13746 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
13747 		}
13748 
13749 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
13750 		    sizeof (dtrace_helper_provider_t *));
13751 	}
13752 
13753 	mutex_enter(&dtrace_lock);
13754 
13755 	dtrace_vstate_fini(&help->dthps_vstate);
13756 	kmem_free(help->dthps_actions,
13757 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
13758 	kmem_free(help, sizeof (dtrace_helpers_t));
13759 
13760 	--dtrace_helpers;
13761 	mutex_exit(&dtrace_lock);
13762 }
13763 
13764 static void
13765 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
13766 {
13767 	dtrace_helpers_t *help, *newhelp;
13768 	dtrace_helper_action_t *helper, *new, *last;
13769 	dtrace_difo_t *dp;
13770 	dtrace_vstate_t *vstate;
13771 	int i, j, sz, hasprovs = 0;
13772 
13773 	mutex_enter(&dtrace_lock);
13774 	ASSERT(from->p_dtrace_helpers != NULL);
13775 	ASSERT(dtrace_helpers > 0);
13776 
13777 	help = from->p_dtrace_helpers;
13778 	newhelp = dtrace_helpers_create(to);
13779 	ASSERT(to->p_dtrace_helpers != NULL);
13780 
13781 	newhelp->dthps_generation = help->dthps_generation;
13782 	vstate = &newhelp->dthps_vstate;
13783 
13784 	/*
13785 	 * Duplicate the helper actions.
13786 	 */
13787 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
13788 		if ((helper = help->dthps_actions[i]) == NULL)
13789 			continue;
13790 
13791 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
13792 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
13793 			    KM_SLEEP);
13794 			new->dtha_generation = helper->dtha_generation;
13795 
13796 			if ((dp = helper->dtha_predicate) != NULL) {
13797 				dp = dtrace_difo_duplicate(dp, vstate);
13798 				new->dtha_predicate = dp;
13799 			}
13800 
13801 			new->dtha_nactions = helper->dtha_nactions;
13802 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
13803 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
13804 
13805 			for (j = 0; j < new->dtha_nactions; j++) {
13806 				dtrace_difo_t *dp = helper->dtha_actions[j];
13807 
13808 				ASSERT(dp != NULL);
13809 				dp = dtrace_difo_duplicate(dp, vstate);
13810 				new->dtha_actions[j] = dp;
13811 			}
13812 
13813 			if (last != NULL) {
13814 				last->dtha_next = new;
13815 			} else {
13816 				newhelp->dthps_actions[i] = new;
13817 			}
13818 
13819 			last = new;
13820 		}
13821 	}
13822 
13823 	/*
13824 	 * Duplicate the helper providers and register them with the
13825 	 * DTrace framework.
13826 	 */
13827 	if (help->dthps_nprovs > 0) {
13828 		newhelp->dthps_nprovs = help->dthps_nprovs;
13829 		newhelp->dthps_maxprovs = help->dthps_nprovs;
13830 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
13831 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
13832 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
13833 			newhelp->dthps_provs[i] = help->dthps_provs[i];
13834 			newhelp->dthps_provs[i]->dthp_ref++;
13835 		}
13836 
13837 		hasprovs = 1;
13838 	}
13839 
13840 	mutex_exit(&dtrace_lock);
13841 
13842 	if (hasprovs)
13843 		dtrace_helper_provider_register(to, newhelp, NULL);
13844 }
13845 
13846 /*
13847  * DTrace Hook Functions
13848  */
13849 static void
13850 dtrace_module_loaded(struct modctl *ctl)
13851 {
13852 	dtrace_provider_t *prv;
13853 
13854 	mutex_enter(&dtrace_provider_lock);
13855 	mutex_enter(&mod_lock);
13856 
13857 	ASSERT(ctl->mod_busy);
13858 
13859 	/*
13860 	 * We're going to call each providers per-module provide operation
13861 	 * specifying only this module.
13862 	 */
13863 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
13864 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
13865 
13866 	mutex_exit(&mod_lock);
13867 	mutex_exit(&dtrace_provider_lock);
13868 
13869 	/*
13870 	 * If we have any retained enablings, we need to match against them.
13871 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
13872 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
13873 	 * module.  (In particular, this happens when loading scheduling
13874 	 * classes.)  So if we have any retained enablings, we need to dispatch
13875 	 * our task queue to do the match for us.
13876 	 */
13877 	mutex_enter(&dtrace_lock);
13878 
13879 	if (dtrace_retained == NULL) {
13880 		mutex_exit(&dtrace_lock);
13881 		return;
13882 	}
13883 
13884 	(void) taskq_dispatch(dtrace_taskq,
13885 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
13886 
13887 	mutex_exit(&dtrace_lock);
13888 
13889 	/*
13890 	 * And now, for a little heuristic sleaze:  in general, we want to
13891 	 * match modules as soon as they load.  However, we cannot guarantee
13892 	 * this, because it would lead us to the lock ordering violation
13893 	 * outlined above.  The common case, of course, is that cpu_lock is
13894 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
13895 	 * long enough for the task queue to do its work.  If it's not, it's
13896 	 * not a serious problem -- it just means that the module that we
13897 	 * just loaded may not be immediately instrumentable.
13898 	 */
13899 	delay(1);
13900 }
13901 
13902 static void
13903 dtrace_module_unloaded(struct modctl *ctl)
13904 {
13905 	dtrace_probe_t template, *probe, *first, *next;
13906 	dtrace_provider_t *prov;
13907 
13908 	template.dtpr_mod = ctl->mod_modname;
13909 
13910 	mutex_enter(&dtrace_provider_lock);
13911 	mutex_enter(&mod_lock);
13912 	mutex_enter(&dtrace_lock);
13913 
13914 	if (dtrace_bymod == NULL) {
13915 		/*
13916 		 * The DTrace module is loaded (obviously) but not attached;
13917 		 * we don't have any work to do.
13918 		 */
13919 		mutex_exit(&dtrace_provider_lock);
13920 		mutex_exit(&mod_lock);
13921 		mutex_exit(&dtrace_lock);
13922 		return;
13923 	}
13924 
13925 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
13926 	    probe != NULL; probe = probe->dtpr_nextmod) {
13927 		if (probe->dtpr_ecb != NULL) {
13928 			mutex_exit(&dtrace_provider_lock);
13929 			mutex_exit(&mod_lock);
13930 			mutex_exit(&dtrace_lock);
13931 
13932 			/*
13933 			 * This shouldn't _actually_ be possible -- we're
13934 			 * unloading a module that has an enabled probe in it.
13935 			 * (It's normally up to the provider to make sure that
13936 			 * this can't happen.)  However, because dtps_enable()
13937 			 * doesn't have a failure mode, there can be an
13938 			 * enable/unload race.  Upshot:  we don't want to
13939 			 * assert, but we're not going to disable the
13940 			 * probe, either.
13941 			 */
13942 			if (dtrace_err_verbose) {
13943 				cmn_err(CE_WARN, "unloaded module '%s' had "
13944 				    "enabled probes", ctl->mod_modname);
13945 			}
13946 
13947 			return;
13948 		}
13949 	}
13950 
13951 	probe = first;
13952 
13953 	for (first = NULL; probe != NULL; probe = next) {
13954 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
13955 
13956 		dtrace_probes[probe->dtpr_id - 1] = NULL;
13957 
13958 		next = probe->dtpr_nextmod;
13959 		dtrace_hash_remove(dtrace_bymod, probe);
13960 		dtrace_hash_remove(dtrace_byfunc, probe);
13961 		dtrace_hash_remove(dtrace_byname, probe);
13962 
13963 		if (first == NULL) {
13964 			first = probe;
13965 			probe->dtpr_nextmod = NULL;
13966 		} else {
13967 			probe->dtpr_nextmod = first;
13968 			first = probe;
13969 		}
13970 	}
13971 
13972 	/*
13973 	 * We've removed all of the module's probes from the hash chains and
13974 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
13975 	 * everyone has cleared out from any probe array processing.
13976 	 */
13977 	dtrace_sync();
13978 
13979 	for (probe = first; probe != NULL; probe = first) {
13980 		first = probe->dtpr_nextmod;
13981 		prov = probe->dtpr_provider;
13982 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
13983 		    probe->dtpr_arg);
13984 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
13985 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
13986 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
13987 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
13988 		kmem_free(probe, sizeof (dtrace_probe_t));
13989 	}
13990 
13991 	mutex_exit(&dtrace_lock);
13992 	mutex_exit(&mod_lock);
13993 	mutex_exit(&dtrace_provider_lock);
13994 }
13995 
13996 void
13997 dtrace_suspend(void)
13998 {
13999 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
14000 }
14001 
14002 void
14003 dtrace_resume(void)
14004 {
14005 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
14006 }
14007 
14008 static int
14009 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
14010 {
14011 	ASSERT(MUTEX_HELD(&cpu_lock));
14012 	mutex_enter(&dtrace_lock);
14013 
14014 	switch (what) {
14015 	case CPU_CONFIG: {
14016 		dtrace_state_t *state;
14017 		dtrace_optval_t *opt, rs, c;
14018 
14019 		/*
14020 		 * For now, we only allocate a new buffer for anonymous state.
14021 		 */
14022 		if ((state = dtrace_anon.dta_state) == NULL)
14023 			break;
14024 
14025 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
14026 			break;
14027 
14028 		opt = state->dts_options;
14029 		c = opt[DTRACEOPT_CPU];
14030 
14031 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
14032 			break;
14033 
14034 		/*
14035 		 * Regardless of what the actual policy is, we're going to
14036 		 * temporarily set our resize policy to be manual.  We're
14037 		 * also going to temporarily set our CPU option to denote
14038 		 * the newly configured CPU.
14039 		 */
14040 		rs = opt[DTRACEOPT_BUFRESIZE];
14041 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
14042 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
14043 
14044 		(void) dtrace_state_buffers(state);
14045 
14046 		opt[DTRACEOPT_BUFRESIZE] = rs;
14047 		opt[DTRACEOPT_CPU] = c;
14048 
14049 		break;
14050 	}
14051 
14052 	case CPU_UNCONFIG:
14053 		/*
14054 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
14055 		 * buffer will be freed when the consumer exits.)
14056 		 */
14057 		break;
14058 
14059 	default:
14060 		break;
14061 	}
14062 
14063 	mutex_exit(&dtrace_lock);
14064 	return (0);
14065 }
14066 
14067 static void
14068 dtrace_cpu_setup_initial(processorid_t cpu)
14069 {
14070 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
14071 }
14072 
14073 static void
14074 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
14075 {
14076 	if (dtrace_toxranges >= dtrace_toxranges_max) {
14077 		int osize, nsize;
14078 		dtrace_toxrange_t *range;
14079 
14080 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14081 
14082 		if (osize == 0) {
14083 			ASSERT(dtrace_toxrange == NULL);
14084 			ASSERT(dtrace_toxranges_max == 0);
14085 			dtrace_toxranges_max = 1;
14086 		} else {
14087 			dtrace_toxranges_max <<= 1;
14088 		}
14089 
14090 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
14091 		range = kmem_zalloc(nsize, KM_SLEEP);
14092 
14093 		if (dtrace_toxrange != NULL) {
14094 			ASSERT(osize != 0);
14095 			bcopy(dtrace_toxrange, range, osize);
14096 			kmem_free(dtrace_toxrange, osize);
14097 		}
14098 
14099 		dtrace_toxrange = range;
14100 	}
14101 
14102 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == NULL);
14103 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == NULL);
14104 
14105 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
14106 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
14107 	dtrace_toxranges++;
14108 }
14109 
14110 /*
14111  * DTrace Driver Cookbook Functions
14112  */
14113 /*ARGSUSED*/
14114 static int
14115 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
14116 {
14117 	dtrace_provider_id_t id;
14118 	dtrace_state_t *state = NULL;
14119 	dtrace_enabling_t *enab;
14120 
14121 	mutex_enter(&cpu_lock);
14122 	mutex_enter(&dtrace_provider_lock);
14123 	mutex_enter(&dtrace_lock);
14124 
14125 	if (ddi_soft_state_init(&dtrace_softstate,
14126 	    sizeof (dtrace_state_t), 0) != 0) {
14127 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
14128 		mutex_exit(&cpu_lock);
14129 		mutex_exit(&dtrace_provider_lock);
14130 		mutex_exit(&dtrace_lock);
14131 		return (DDI_FAILURE);
14132 	}
14133 
14134 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
14135 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, NULL) == DDI_FAILURE ||
14136 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
14137 	    DTRACEMNRN_HELPER, DDI_PSEUDO, NULL) == DDI_FAILURE) {
14138 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
14139 		ddi_remove_minor_node(devi, NULL);
14140 		ddi_soft_state_fini(&dtrace_softstate);
14141 		mutex_exit(&cpu_lock);
14142 		mutex_exit(&dtrace_provider_lock);
14143 		mutex_exit(&dtrace_lock);
14144 		return (DDI_FAILURE);
14145 	}
14146 
14147 	ddi_report_dev(devi);
14148 	dtrace_devi = devi;
14149 
14150 	dtrace_modload = dtrace_module_loaded;
14151 	dtrace_modunload = dtrace_module_unloaded;
14152 	dtrace_cpu_init = dtrace_cpu_setup_initial;
14153 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
14154 	dtrace_helpers_fork = dtrace_helpers_duplicate;
14155 	dtrace_cpustart_init = dtrace_suspend;
14156 	dtrace_cpustart_fini = dtrace_resume;
14157 	dtrace_debugger_init = dtrace_suspend;
14158 	dtrace_debugger_fini = dtrace_resume;
14159 
14160 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
14161 
14162 	ASSERT(MUTEX_HELD(&cpu_lock));
14163 
14164 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
14165 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
14166 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
14167 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
14168 	    VM_SLEEP | VMC_IDENTIFIER);
14169 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
14170 	    1, INT_MAX, 0);
14171 
14172 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
14173 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
14174 	    NULL, NULL, NULL, NULL, NULL, 0);
14175 
14176 	ASSERT(MUTEX_HELD(&cpu_lock));
14177 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
14178 	    offsetof(dtrace_probe_t, dtpr_nextmod),
14179 	    offsetof(dtrace_probe_t, dtpr_prevmod));
14180 
14181 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
14182 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
14183 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
14184 
14185 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
14186 	    offsetof(dtrace_probe_t, dtpr_nextname),
14187 	    offsetof(dtrace_probe_t, dtpr_prevname));
14188 
14189 	if (dtrace_retain_max < 1) {
14190 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
14191 		    "setting to 1", dtrace_retain_max);
14192 		dtrace_retain_max = 1;
14193 	}
14194 
14195 	/*
14196 	 * Now discover our toxic ranges.
14197 	 */
14198 	dtrace_toxic_ranges(dtrace_toxrange_add);
14199 
14200 	/*
14201 	 * Before we register ourselves as a provider to our own framework,
14202 	 * we would like to assert that dtrace_provider is NULL -- but that's
14203 	 * not true if we were loaded as a dependency of a DTrace provider.
14204 	 * Once we've registered, we can assert that dtrace_provider is our
14205 	 * pseudo provider.
14206 	 */
14207 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
14208 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
14209 
14210 	ASSERT(dtrace_provider != NULL);
14211 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
14212 
14213 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
14214 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
14215 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
14216 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
14217 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
14218 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
14219 
14220 	dtrace_anon_property();
14221 	mutex_exit(&cpu_lock);
14222 
14223 	/*
14224 	 * If DTrace helper tracing is enabled, we need to allocate the
14225 	 * trace buffer and initialize the values.
14226 	 */
14227 	if (dtrace_helptrace_enabled) {
14228 		ASSERT(dtrace_helptrace_buffer == NULL);
14229 		dtrace_helptrace_buffer =
14230 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
14231 		dtrace_helptrace_next = 0;
14232 	}
14233 
14234 	/*
14235 	 * If there are already providers, we must ask them to provide their
14236 	 * probes, and then match any anonymous enabling against them.  Note
14237 	 * that there should be no other retained enablings at this time:
14238 	 * the only retained enablings at this time should be the anonymous
14239 	 * enabling.
14240 	 */
14241 	if (dtrace_anon.dta_enabling != NULL) {
14242 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
14243 
14244 		dtrace_enabling_provide(NULL);
14245 		state = dtrace_anon.dta_state;
14246 
14247 		/*
14248 		 * We couldn't hold cpu_lock across the above call to
14249 		 * dtrace_enabling_provide(), but we must hold it to actually
14250 		 * enable the probes.  We have to drop all of our locks, pick
14251 		 * up cpu_lock, and regain our locks before matching the
14252 		 * retained anonymous enabling.
14253 		 */
14254 		mutex_exit(&dtrace_lock);
14255 		mutex_exit(&dtrace_provider_lock);
14256 
14257 		mutex_enter(&cpu_lock);
14258 		mutex_enter(&dtrace_provider_lock);
14259 		mutex_enter(&dtrace_lock);
14260 
14261 		if ((enab = dtrace_anon.dta_enabling) != NULL)
14262 			(void) dtrace_enabling_match(enab, NULL);
14263 
14264 		mutex_exit(&cpu_lock);
14265 	}
14266 
14267 	mutex_exit(&dtrace_lock);
14268 	mutex_exit(&dtrace_provider_lock);
14269 
14270 	if (state != NULL) {
14271 		/*
14272 		 * If we created any anonymous state, set it going now.
14273 		 */
14274 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
14275 	}
14276 
14277 	return (DDI_SUCCESS);
14278 }
14279 
14280 /*ARGSUSED*/
14281 static int
14282 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
14283 {
14284 	dtrace_state_t *state;
14285 	uint32_t priv;
14286 	uid_t uid;
14287 	zoneid_t zoneid;
14288 
14289 	if (getminor(*devp) == DTRACEMNRN_HELPER)
14290 		return (0);
14291 
14292 	/*
14293 	 * If this wasn't an open with the "helper" minor, then it must be
14294 	 * the "dtrace" minor.
14295 	 */
14296 	ASSERT(getminor(*devp) == DTRACEMNRN_DTRACE);
14297 
14298 	/*
14299 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
14300 	 * caller lacks sufficient permission to do anything with DTrace.
14301 	 */
14302 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
14303 	if (priv == DTRACE_PRIV_NONE)
14304 		return (EACCES);
14305 
14306 	/*
14307 	 * Ask all providers to provide all their probes.
14308 	 */
14309 	mutex_enter(&dtrace_provider_lock);
14310 	dtrace_probe_provide(NULL, NULL);
14311 	mutex_exit(&dtrace_provider_lock);
14312 
14313 	mutex_enter(&cpu_lock);
14314 	mutex_enter(&dtrace_lock);
14315 	dtrace_opens++;
14316 	dtrace_membar_producer();
14317 
14318 	/*
14319 	 * If the kernel debugger is active (that is, if the kernel debugger
14320 	 * modified text in some way), we won't allow the open.
14321 	 */
14322 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14323 		dtrace_opens--;
14324 		mutex_exit(&cpu_lock);
14325 		mutex_exit(&dtrace_lock);
14326 		return (EBUSY);
14327 	}
14328 
14329 	state = dtrace_state_create(devp, cred_p);
14330 	mutex_exit(&cpu_lock);
14331 
14332 	if (state == NULL) {
14333 		if (--dtrace_opens == 0)
14334 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14335 		mutex_exit(&dtrace_lock);
14336 		return (EAGAIN);
14337 	}
14338 
14339 	mutex_exit(&dtrace_lock);
14340 
14341 	return (0);
14342 }
14343 
14344 /*ARGSUSED*/
14345 static int
14346 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
14347 {
14348 	minor_t minor = getminor(dev);
14349 	dtrace_state_t *state;
14350 
14351 	if (minor == DTRACEMNRN_HELPER)
14352 		return (0);
14353 
14354 	state = ddi_get_soft_state(dtrace_softstate, minor);
14355 
14356 	mutex_enter(&cpu_lock);
14357 	mutex_enter(&dtrace_lock);
14358 
14359 	if (state->dts_anon) {
14360 		/*
14361 		 * There is anonymous state. Destroy that first.
14362 		 */
14363 		ASSERT(dtrace_anon.dta_state == NULL);
14364 		dtrace_state_destroy(state->dts_anon);
14365 	}
14366 
14367 	dtrace_state_destroy(state);
14368 	ASSERT(dtrace_opens > 0);
14369 	if (--dtrace_opens == 0)
14370 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
14371 
14372 	mutex_exit(&dtrace_lock);
14373 	mutex_exit(&cpu_lock);
14374 
14375 	return (0);
14376 }
14377 
14378 /*ARGSUSED*/
14379 static int
14380 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
14381 {
14382 	int rval;
14383 	dof_helper_t help, *dhp = NULL;
14384 
14385 	switch (cmd) {
14386 	case DTRACEHIOC_ADDDOF:
14387 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
14388 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
14389 			return (EFAULT);
14390 		}
14391 
14392 		dhp = &help;
14393 		arg = (intptr_t)help.dofhp_dof;
14394 		/*FALLTHROUGH*/
14395 
14396 	case DTRACEHIOC_ADD: {
14397 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
14398 
14399 		if (dof == NULL)
14400 			return (rval);
14401 
14402 		mutex_enter(&dtrace_lock);
14403 
14404 		/*
14405 		 * dtrace_helper_slurp() takes responsibility for the dof --
14406 		 * it may free it now or it may save it and free it later.
14407 		 */
14408 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
14409 			*rv = rval;
14410 			rval = 0;
14411 		} else {
14412 			rval = EINVAL;
14413 		}
14414 
14415 		mutex_exit(&dtrace_lock);
14416 		return (rval);
14417 	}
14418 
14419 	case DTRACEHIOC_REMOVE: {
14420 		mutex_enter(&dtrace_lock);
14421 		rval = dtrace_helper_destroygen(arg);
14422 		mutex_exit(&dtrace_lock);
14423 
14424 		return (rval);
14425 	}
14426 
14427 	default:
14428 		break;
14429 	}
14430 
14431 	return (ENOTTY);
14432 }
14433 
14434 /*ARGSUSED*/
14435 static int
14436 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
14437 {
14438 	minor_t minor = getminor(dev);
14439 	dtrace_state_t *state;
14440 	int rval;
14441 
14442 	if (minor == DTRACEMNRN_HELPER)
14443 		return (dtrace_ioctl_helper(cmd, arg, rv));
14444 
14445 	state = ddi_get_soft_state(dtrace_softstate, minor);
14446 
14447 	if (state->dts_anon) {
14448 		ASSERT(dtrace_anon.dta_state == NULL);
14449 		state = state->dts_anon;
14450 	}
14451 
14452 	switch (cmd) {
14453 	case DTRACEIOC_PROVIDER: {
14454 		dtrace_providerdesc_t pvd;
14455 		dtrace_provider_t *pvp;
14456 
14457 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
14458 			return (EFAULT);
14459 
14460 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
14461 		mutex_enter(&dtrace_provider_lock);
14462 
14463 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
14464 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
14465 				break;
14466 		}
14467 
14468 		mutex_exit(&dtrace_provider_lock);
14469 
14470 		if (pvp == NULL)
14471 			return (ESRCH);
14472 
14473 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
14474 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
14475 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
14476 			return (EFAULT);
14477 
14478 		return (0);
14479 	}
14480 
14481 	case DTRACEIOC_EPROBE: {
14482 		dtrace_eprobedesc_t epdesc;
14483 		dtrace_ecb_t *ecb;
14484 		dtrace_action_t *act;
14485 		void *buf;
14486 		size_t size;
14487 		uintptr_t dest;
14488 		int nrecs;
14489 
14490 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
14491 			return (EFAULT);
14492 
14493 		mutex_enter(&dtrace_lock);
14494 
14495 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
14496 			mutex_exit(&dtrace_lock);
14497 			return (EINVAL);
14498 		}
14499 
14500 		if (ecb->dte_probe == NULL) {
14501 			mutex_exit(&dtrace_lock);
14502 			return (EINVAL);
14503 		}
14504 
14505 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
14506 		epdesc.dtepd_uarg = ecb->dte_uarg;
14507 		epdesc.dtepd_size = ecb->dte_size;
14508 
14509 		nrecs = epdesc.dtepd_nrecs;
14510 		epdesc.dtepd_nrecs = 0;
14511 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
14512 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
14513 				continue;
14514 
14515 			epdesc.dtepd_nrecs++;
14516 		}
14517 
14518 		/*
14519 		 * Now that we have the size, we need to allocate a temporary
14520 		 * buffer in which to store the complete description.  We need
14521 		 * the temporary buffer to be able to drop dtrace_lock()
14522 		 * across the copyout(), below.
14523 		 */
14524 		size = sizeof (dtrace_eprobedesc_t) +
14525 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
14526 
14527 		buf = kmem_alloc(size, KM_SLEEP);
14528 		dest = (uintptr_t)buf;
14529 
14530 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
14531 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
14532 
14533 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
14534 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
14535 				continue;
14536 
14537 			if (nrecs-- == 0)
14538 				break;
14539 
14540 			bcopy(&act->dta_rec, (void *)dest,
14541 			    sizeof (dtrace_recdesc_t));
14542 			dest += sizeof (dtrace_recdesc_t);
14543 		}
14544 
14545 		mutex_exit(&dtrace_lock);
14546 
14547 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
14548 			kmem_free(buf, size);
14549 			return (EFAULT);
14550 		}
14551 
14552 		kmem_free(buf, size);
14553 		return (0);
14554 	}
14555 
14556 	case DTRACEIOC_AGGDESC: {
14557 		dtrace_aggdesc_t aggdesc;
14558 		dtrace_action_t *act;
14559 		dtrace_aggregation_t *agg;
14560 		int nrecs;
14561 		uint32_t offs;
14562 		dtrace_recdesc_t *lrec;
14563 		void *buf;
14564 		size_t size;
14565 		uintptr_t dest;
14566 
14567 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
14568 			return (EFAULT);
14569 
14570 		mutex_enter(&dtrace_lock);
14571 
14572 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
14573 			mutex_exit(&dtrace_lock);
14574 			return (EINVAL);
14575 		}
14576 
14577 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
14578 
14579 		nrecs = aggdesc.dtagd_nrecs;
14580 		aggdesc.dtagd_nrecs = 0;
14581 
14582 		offs = agg->dtag_base;
14583 		lrec = &agg->dtag_action.dta_rec;
14584 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
14585 
14586 		for (act = agg->dtag_first; ; act = act->dta_next) {
14587 			ASSERT(act->dta_intuple ||
14588 			    DTRACEACT_ISAGG(act->dta_kind));
14589 
14590 			/*
14591 			 * If this action has a record size of zero, it
14592 			 * denotes an argument to the aggregating action.
14593 			 * Because the presence of this record doesn't (or
14594 			 * shouldn't) affect the way the data is interpreted,
14595 			 * we don't copy it out to save user-level the
14596 			 * confusion of dealing with a zero-length record.
14597 			 */
14598 			if (act->dta_rec.dtrd_size == 0) {
14599 				ASSERT(agg->dtag_hasarg);
14600 				continue;
14601 			}
14602 
14603 			aggdesc.dtagd_nrecs++;
14604 
14605 			if (act == &agg->dtag_action)
14606 				break;
14607 		}
14608 
14609 		/*
14610 		 * Now that we have the size, we need to allocate a temporary
14611 		 * buffer in which to store the complete description.  We need
14612 		 * the temporary buffer to be able to drop dtrace_lock()
14613 		 * across the copyout(), below.
14614 		 */
14615 		size = sizeof (dtrace_aggdesc_t) +
14616 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
14617 
14618 		buf = kmem_alloc(size, KM_SLEEP);
14619 		dest = (uintptr_t)buf;
14620 
14621 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
14622 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
14623 
14624 		for (act = agg->dtag_first; ; act = act->dta_next) {
14625 			dtrace_recdesc_t rec = act->dta_rec;
14626 
14627 			/*
14628 			 * See the comment in the above loop for why we pass
14629 			 * over zero-length records.
14630 			 */
14631 			if (rec.dtrd_size == 0) {
14632 				ASSERT(agg->dtag_hasarg);
14633 				continue;
14634 			}
14635 
14636 			if (nrecs-- == 0)
14637 				break;
14638 
14639 			rec.dtrd_offset -= offs;
14640 			bcopy(&rec, (void *)dest, sizeof (rec));
14641 			dest += sizeof (dtrace_recdesc_t);
14642 
14643 			if (act == &agg->dtag_action)
14644 				break;
14645 		}
14646 
14647 		mutex_exit(&dtrace_lock);
14648 
14649 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
14650 			kmem_free(buf, size);
14651 			return (EFAULT);
14652 		}
14653 
14654 		kmem_free(buf, size);
14655 		return (0);
14656 	}
14657 
14658 	case DTRACEIOC_ENABLE: {
14659 		dof_hdr_t *dof;
14660 		dtrace_enabling_t *enab = NULL;
14661 		dtrace_vstate_t *vstate;
14662 		int err = 0;
14663 
14664 		*rv = 0;
14665 
14666 		/*
14667 		 * If a NULL argument has been passed, we take this as our
14668 		 * cue to reevaluate our enablings.
14669 		 */
14670 		if (arg == NULL) {
14671 			mutex_enter(&cpu_lock);
14672 			mutex_enter(&dtrace_lock);
14673 			err = dtrace_enabling_matchstate(state, rv);
14674 			mutex_exit(&dtrace_lock);
14675 			mutex_exit(&cpu_lock);
14676 
14677 			return (err);
14678 		}
14679 
14680 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
14681 			return (rval);
14682 
14683 		mutex_enter(&cpu_lock);
14684 		mutex_enter(&dtrace_lock);
14685 		vstate = &state->dts_vstate;
14686 
14687 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14688 			mutex_exit(&dtrace_lock);
14689 			mutex_exit(&cpu_lock);
14690 			dtrace_dof_destroy(dof);
14691 			return (EBUSY);
14692 		}
14693 
14694 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
14695 			mutex_exit(&dtrace_lock);
14696 			mutex_exit(&cpu_lock);
14697 			dtrace_dof_destroy(dof);
14698 			return (EINVAL);
14699 		}
14700 
14701 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
14702 			dtrace_enabling_destroy(enab);
14703 			mutex_exit(&dtrace_lock);
14704 			mutex_exit(&cpu_lock);
14705 			dtrace_dof_destroy(dof);
14706 			return (rval);
14707 		}
14708 
14709 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
14710 			err = dtrace_enabling_retain(enab);
14711 		} else {
14712 			dtrace_enabling_destroy(enab);
14713 		}
14714 
14715 		mutex_exit(&cpu_lock);
14716 		mutex_exit(&dtrace_lock);
14717 		dtrace_dof_destroy(dof);
14718 
14719 		return (err);
14720 	}
14721 
14722 	case DTRACEIOC_REPLICATE: {
14723 		dtrace_repldesc_t desc;
14724 		dtrace_probedesc_t *match = &desc.dtrpd_match;
14725 		dtrace_probedesc_t *create = &desc.dtrpd_create;
14726 		int err;
14727 
14728 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14729 			return (EFAULT);
14730 
14731 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14732 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14733 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14734 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14735 
14736 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14737 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14738 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14739 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14740 
14741 		mutex_enter(&dtrace_lock);
14742 		err = dtrace_enabling_replicate(state, match, create);
14743 		mutex_exit(&dtrace_lock);
14744 
14745 		return (err);
14746 	}
14747 
14748 	case DTRACEIOC_PROBEMATCH:
14749 	case DTRACEIOC_PROBES: {
14750 		dtrace_probe_t *probe = NULL;
14751 		dtrace_probedesc_t desc;
14752 		dtrace_probekey_t pkey;
14753 		dtrace_id_t i;
14754 		int m = 0;
14755 		uint32_t priv;
14756 		uid_t uid;
14757 		zoneid_t zoneid;
14758 
14759 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14760 			return (EFAULT);
14761 
14762 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
14763 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
14764 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
14765 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
14766 
14767 		/*
14768 		 * Before we attempt to match this probe, we want to give
14769 		 * all providers the opportunity to provide it.
14770 		 */
14771 		if (desc.dtpd_id == DTRACE_IDNONE) {
14772 			mutex_enter(&dtrace_provider_lock);
14773 			dtrace_probe_provide(&desc, NULL);
14774 			mutex_exit(&dtrace_provider_lock);
14775 			desc.dtpd_id++;
14776 		}
14777 
14778 		if (cmd == DTRACEIOC_PROBEMATCH)  {
14779 			dtrace_probekey(&desc, &pkey);
14780 			pkey.dtpk_id = DTRACE_IDNONE;
14781 		}
14782 
14783 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
14784 
14785 		mutex_enter(&dtrace_lock);
14786 
14787 		if (cmd == DTRACEIOC_PROBEMATCH) {
14788 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14789 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14790 				    (m = dtrace_match_probe(probe, &pkey,
14791 				    priv, uid, zoneid)) != 0)
14792 					break;
14793 			}
14794 
14795 			if (m < 0) {
14796 				mutex_exit(&dtrace_lock);
14797 				return (EINVAL);
14798 			}
14799 
14800 		} else {
14801 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
14802 				if ((probe = dtrace_probes[i - 1]) != NULL &&
14803 				    dtrace_match_priv(probe, priv, uid, zoneid))
14804 					break;
14805 			}
14806 		}
14807 
14808 		if (probe == NULL) {
14809 			mutex_exit(&dtrace_lock);
14810 			return (ESRCH);
14811 		}
14812 
14813 		dtrace_probe_description(probe, &desc);
14814 		mutex_exit(&dtrace_lock);
14815 
14816 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14817 			return (EFAULT);
14818 
14819 		return (0);
14820 	}
14821 
14822 	case DTRACEIOC_PROBEARG: {
14823 		dtrace_argdesc_t desc;
14824 		dtrace_probe_t *probe;
14825 		dtrace_provider_t *prov;
14826 
14827 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14828 			return (EFAULT);
14829 
14830 		if (desc.dtargd_id == DTRACE_IDNONE)
14831 			return (EINVAL);
14832 
14833 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
14834 			return (EINVAL);
14835 
14836 		mutex_enter(&dtrace_provider_lock);
14837 		mutex_enter(&mod_lock);
14838 		mutex_enter(&dtrace_lock);
14839 
14840 		if (desc.dtargd_id > dtrace_nprobes) {
14841 			mutex_exit(&dtrace_lock);
14842 			mutex_exit(&mod_lock);
14843 			mutex_exit(&dtrace_provider_lock);
14844 			return (EINVAL);
14845 		}
14846 
14847 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
14848 			mutex_exit(&dtrace_lock);
14849 			mutex_exit(&mod_lock);
14850 			mutex_exit(&dtrace_provider_lock);
14851 			return (EINVAL);
14852 		}
14853 
14854 		mutex_exit(&dtrace_lock);
14855 
14856 		prov = probe->dtpr_provider;
14857 
14858 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
14859 			/*
14860 			 * There isn't any typed information for this probe.
14861 			 * Set the argument number to DTRACE_ARGNONE.
14862 			 */
14863 			desc.dtargd_ndx = DTRACE_ARGNONE;
14864 		} else {
14865 			desc.dtargd_native[0] = '\0';
14866 			desc.dtargd_xlate[0] = '\0';
14867 			desc.dtargd_mapping = desc.dtargd_ndx;
14868 
14869 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
14870 			    probe->dtpr_id, probe->dtpr_arg, &desc);
14871 		}
14872 
14873 		mutex_exit(&mod_lock);
14874 		mutex_exit(&dtrace_provider_lock);
14875 
14876 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14877 			return (EFAULT);
14878 
14879 		return (0);
14880 	}
14881 
14882 	case DTRACEIOC_GO: {
14883 		processorid_t cpuid;
14884 		rval = dtrace_state_go(state, &cpuid);
14885 
14886 		if (rval != 0)
14887 			return (rval);
14888 
14889 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14890 			return (EFAULT);
14891 
14892 		return (0);
14893 	}
14894 
14895 	case DTRACEIOC_STOP: {
14896 		processorid_t cpuid;
14897 
14898 		mutex_enter(&dtrace_lock);
14899 		rval = dtrace_state_stop(state, &cpuid);
14900 		mutex_exit(&dtrace_lock);
14901 
14902 		if (rval != 0)
14903 			return (rval);
14904 
14905 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
14906 			return (EFAULT);
14907 
14908 		return (0);
14909 	}
14910 
14911 	case DTRACEIOC_DOFGET: {
14912 		dof_hdr_t hdr, *dof;
14913 		uint64_t len;
14914 
14915 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
14916 			return (EFAULT);
14917 
14918 		mutex_enter(&dtrace_lock);
14919 		dof = dtrace_dof_create(state);
14920 		mutex_exit(&dtrace_lock);
14921 
14922 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
14923 		rval = copyout(dof, (void *)arg, len);
14924 		dtrace_dof_destroy(dof);
14925 
14926 		return (rval == 0 ? 0 : EFAULT);
14927 	}
14928 
14929 	case DTRACEIOC_AGGSNAP:
14930 	case DTRACEIOC_BUFSNAP: {
14931 		dtrace_bufdesc_t desc;
14932 		caddr_t cached;
14933 		dtrace_buffer_t *buf;
14934 
14935 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
14936 			return (EFAULT);
14937 
14938 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
14939 			return (EINVAL);
14940 
14941 		mutex_enter(&dtrace_lock);
14942 
14943 		if (cmd == DTRACEIOC_BUFSNAP) {
14944 			buf = &state->dts_buffer[desc.dtbd_cpu];
14945 		} else {
14946 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
14947 		}
14948 
14949 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
14950 			size_t sz = buf->dtb_offset;
14951 
14952 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
14953 				mutex_exit(&dtrace_lock);
14954 				return (EBUSY);
14955 			}
14956 
14957 			/*
14958 			 * If this buffer has already been consumed, we're
14959 			 * going to indicate that there's nothing left here
14960 			 * to consume.
14961 			 */
14962 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
14963 				mutex_exit(&dtrace_lock);
14964 
14965 				desc.dtbd_size = 0;
14966 				desc.dtbd_drops = 0;
14967 				desc.dtbd_errors = 0;
14968 				desc.dtbd_oldest = 0;
14969 				sz = sizeof (desc);
14970 
14971 				if (copyout(&desc, (void *)arg, sz) != 0)
14972 					return (EFAULT);
14973 
14974 				return (0);
14975 			}
14976 
14977 			/*
14978 			 * If this is a ring buffer that has wrapped, we want
14979 			 * to copy the whole thing out.
14980 			 */
14981 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
14982 				dtrace_buffer_polish(buf);
14983 				sz = buf->dtb_size;
14984 			}
14985 
14986 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
14987 				mutex_exit(&dtrace_lock);
14988 				return (EFAULT);
14989 			}
14990 
14991 			desc.dtbd_size = sz;
14992 			desc.dtbd_drops = buf->dtb_drops;
14993 			desc.dtbd_errors = buf->dtb_errors;
14994 			desc.dtbd_oldest = buf->dtb_xamot_offset;
14995 
14996 			mutex_exit(&dtrace_lock);
14997 
14998 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
14999 				return (EFAULT);
15000 
15001 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
15002 
15003 			return (0);
15004 		}
15005 
15006 		if (buf->dtb_tomax == NULL) {
15007 			ASSERT(buf->dtb_xamot == NULL);
15008 			mutex_exit(&dtrace_lock);
15009 			return (ENOENT);
15010 		}
15011 
15012 		cached = buf->dtb_tomax;
15013 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
15014 
15015 		dtrace_xcall(desc.dtbd_cpu,
15016 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
15017 
15018 		state->dts_errors += buf->dtb_xamot_errors;
15019 
15020 		/*
15021 		 * If the buffers did not actually switch, then the cross call
15022 		 * did not take place -- presumably because the given CPU is
15023 		 * not in the ready set.  If this is the case, we'll return
15024 		 * ENOENT.
15025 		 */
15026 		if (buf->dtb_tomax == cached) {
15027 			ASSERT(buf->dtb_xamot != cached);
15028 			mutex_exit(&dtrace_lock);
15029 			return (ENOENT);
15030 		}
15031 
15032 		ASSERT(cached == buf->dtb_xamot);
15033 
15034 		/*
15035 		 * We have our snapshot; now copy it out.
15036 		 */
15037 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
15038 		    buf->dtb_xamot_offset) != 0) {
15039 			mutex_exit(&dtrace_lock);
15040 			return (EFAULT);
15041 		}
15042 
15043 		desc.dtbd_size = buf->dtb_xamot_offset;
15044 		desc.dtbd_drops = buf->dtb_xamot_drops;
15045 		desc.dtbd_errors = buf->dtb_xamot_errors;
15046 		desc.dtbd_oldest = 0;
15047 
15048 		mutex_exit(&dtrace_lock);
15049 
15050 		/*
15051 		 * Finally, copy out the buffer description.
15052 		 */
15053 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
15054 			return (EFAULT);
15055 
15056 		return (0);
15057 	}
15058 
15059 	case DTRACEIOC_CONF: {
15060 		dtrace_conf_t conf;
15061 
15062 		bzero(&conf, sizeof (conf));
15063 		conf.dtc_difversion = DIF_VERSION;
15064 		conf.dtc_difintregs = DIF_DIR_NREGS;
15065 		conf.dtc_diftupregs = DIF_DTR_NREGS;
15066 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
15067 
15068 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
15069 			return (EFAULT);
15070 
15071 		return (0);
15072 	}
15073 
15074 	case DTRACEIOC_STATUS: {
15075 		dtrace_status_t stat;
15076 		dtrace_dstate_t *dstate;
15077 		int i, j;
15078 		uint64_t nerrs;
15079 
15080 		/*
15081 		 * See the comment in dtrace_state_deadman() for the reason
15082 		 * for setting dts_laststatus to INT64_MAX before setting
15083 		 * it to the correct value.
15084 		 */
15085 		state->dts_laststatus = INT64_MAX;
15086 		dtrace_membar_producer();
15087 		state->dts_laststatus = dtrace_gethrtime();
15088 
15089 		bzero(&stat, sizeof (stat));
15090 
15091 		mutex_enter(&dtrace_lock);
15092 
15093 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
15094 			mutex_exit(&dtrace_lock);
15095 			return (ENOENT);
15096 		}
15097 
15098 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
15099 			stat.dtst_exiting = 1;
15100 
15101 		nerrs = state->dts_errors;
15102 		dstate = &state->dts_vstate.dtvs_dynvars;
15103 
15104 		for (i = 0; i < NCPU; i++) {
15105 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
15106 
15107 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
15108 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
15109 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
15110 
15111 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
15112 				stat.dtst_filled++;
15113 
15114 			nerrs += state->dts_buffer[i].dtb_errors;
15115 
15116 			for (j = 0; j < state->dts_nspeculations; j++) {
15117 				dtrace_speculation_t *spec;
15118 				dtrace_buffer_t *buf;
15119 
15120 				spec = &state->dts_speculations[j];
15121 				buf = &spec->dtsp_buffer[i];
15122 				stat.dtst_specdrops += buf->dtb_xamot_drops;
15123 			}
15124 		}
15125 
15126 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
15127 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
15128 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
15129 		stat.dtst_dblerrors = state->dts_dblerrors;
15130 		stat.dtst_killed =
15131 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
15132 		stat.dtst_errors = nerrs;
15133 
15134 		mutex_exit(&dtrace_lock);
15135 
15136 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
15137 			return (EFAULT);
15138 
15139 		return (0);
15140 	}
15141 
15142 	case DTRACEIOC_FORMAT: {
15143 		dtrace_fmtdesc_t fmt;
15144 		char *str;
15145 		int len;
15146 
15147 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
15148 			return (EFAULT);
15149 
15150 		mutex_enter(&dtrace_lock);
15151 
15152 		if (fmt.dtfd_format == 0 ||
15153 		    fmt.dtfd_format > state->dts_nformats) {
15154 			mutex_exit(&dtrace_lock);
15155 			return (EINVAL);
15156 		}
15157 
15158 		/*
15159 		 * Format strings are allocated contiguously and they are
15160 		 * never freed; if a format index is less than the number
15161 		 * of formats, we can assert that the format map is non-NULL
15162 		 * and that the format for the specified index is non-NULL.
15163 		 */
15164 		ASSERT(state->dts_formats != NULL);
15165 		str = state->dts_formats[fmt.dtfd_format - 1];
15166 		ASSERT(str != NULL);
15167 
15168 		len = strlen(str) + 1;
15169 
15170 		if (len > fmt.dtfd_length) {
15171 			fmt.dtfd_length = len;
15172 
15173 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
15174 				mutex_exit(&dtrace_lock);
15175 				return (EINVAL);
15176 			}
15177 		} else {
15178 			if (copyout(str, fmt.dtfd_string, len) != 0) {
15179 				mutex_exit(&dtrace_lock);
15180 				return (EINVAL);
15181 			}
15182 		}
15183 
15184 		mutex_exit(&dtrace_lock);
15185 		return (0);
15186 	}
15187 
15188 	default:
15189 		break;
15190 	}
15191 
15192 	return (ENOTTY);
15193 }
15194 
15195 /*ARGSUSED*/
15196 static int
15197 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
15198 {
15199 	dtrace_state_t *state;
15200 
15201 	switch (cmd) {
15202 	case DDI_DETACH:
15203 		break;
15204 
15205 	case DDI_SUSPEND:
15206 		return (DDI_SUCCESS);
15207 
15208 	default:
15209 		return (DDI_FAILURE);
15210 	}
15211 
15212 	mutex_enter(&cpu_lock);
15213 	mutex_enter(&dtrace_provider_lock);
15214 	mutex_enter(&dtrace_lock);
15215 
15216 	ASSERT(dtrace_opens == 0);
15217 
15218 	if (dtrace_helpers > 0) {
15219 		mutex_exit(&dtrace_provider_lock);
15220 		mutex_exit(&dtrace_lock);
15221 		mutex_exit(&cpu_lock);
15222 		return (DDI_FAILURE);
15223 	}
15224 
15225 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
15226 		mutex_exit(&dtrace_provider_lock);
15227 		mutex_exit(&dtrace_lock);
15228 		mutex_exit(&cpu_lock);
15229 		return (DDI_FAILURE);
15230 	}
15231 
15232 	dtrace_provider = NULL;
15233 
15234 	if ((state = dtrace_anon_grab()) != NULL) {
15235 		/*
15236 		 * If there were ECBs on this state, the provider should
15237 		 * have not been allowed to detach; assert that there is
15238 		 * none.
15239 		 */
15240 		ASSERT(state->dts_necbs == 0);
15241 		dtrace_state_destroy(state);
15242 
15243 		/*
15244 		 * If we're being detached with anonymous state, we need to
15245 		 * indicate to the kernel debugger that DTrace is now inactive.
15246 		 */
15247 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
15248 	}
15249 
15250 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
15251 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
15252 	dtrace_cpu_init = NULL;
15253 	dtrace_helpers_cleanup = NULL;
15254 	dtrace_helpers_fork = NULL;
15255 	dtrace_cpustart_init = NULL;
15256 	dtrace_cpustart_fini = NULL;
15257 	dtrace_debugger_init = NULL;
15258 	dtrace_debugger_fini = NULL;
15259 	dtrace_modload = NULL;
15260 	dtrace_modunload = NULL;
15261 
15262 	mutex_exit(&cpu_lock);
15263 
15264 	if (dtrace_helptrace_enabled) {
15265 		kmem_free(dtrace_helptrace_buffer, dtrace_helptrace_bufsize);
15266 		dtrace_helptrace_buffer = NULL;
15267 	}
15268 
15269 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
15270 	dtrace_probes = NULL;
15271 	dtrace_nprobes = 0;
15272 
15273 	dtrace_hash_destroy(dtrace_bymod);
15274 	dtrace_hash_destroy(dtrace_byfunc);
15275 	dtrace_hash_destroy(dtrace_byname);
15276 	dtrace_bymod = NULL;
15277 	dtrace_byfunc = NULL;
15278 	dtrace_byname = NULL;
15279 
15280 	kmem_cache_destroy(dtrace_state_cache);
15281 	vmem_destroy(dtrace_minor);
15282 	vmem_destroy(dtrace_arena);
15283 
15284 	if (dtrace_toxrange != NULL) {
15285 		kmem_free(dtrace_toxrange,
15286 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
15287 		dtrace_toxrange = NULL;
15288 		dtrace_toxranges = 0;
15289 		dtrace_toxranges_max = 0;
15290 	}
15291 
15292 	ddi_remove_minor_node(dtrace_devi, NULL);
15293 	dtrace_devi = NULL;
15294 
15295 	ddi_soft_state_fini(&dtrace_softstate);
15296 
15297 	ASSERT(dtrace_vtime_references == 0);
15298 	ASSERT(dtrace_opens == 0);
15299 	ASSERT(dtrace_retained == NULL);
15300 
15301 	mutex_exit(&dtrace_lock);
15302 	mutex_exit(&dtrace_provider_lock);
15303 
15304 	/*
15305 	 * We don't destroy the task queue until after we have dropped our
15306 	 * locks (taskq_destroy() may block on running tasks).  To prevent
15307 	 * attempting to do work after we have effectively detached but before
15308 	 * the task queue has been destroyed, all tasks dispatched via the
15309 	 * task queue must check that DTrace is still attached before
15310 	 * performing any operation.
15311 	 */
15312 	taskq_destroy(dtrace_taskq);
15313 	dtrace_taskq = NULL;
15314 
15315 	return (DDI_SUCCESS);
15316 }
15317 
15318 /*ARGSUSED*/
15319 static int
15320 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
15321 {
15322 	int error;
15323 
15324 	switch (infocmd) {
15325 	case DDI_INFO_DEVT2DEVINFO:
15326 		*result = (void *)dtrace_devi;
15327 		error = DDI_SUCCESS;
15328 		break;
15329 	case DDI_INFO_DEVT2INSTANCE:
15330 		*result = (void *)0;
15331 		error = DDI_SUCCESS;
15332 		break;
15333 	default:
15334 		error = DDI_FAILURE;
15335 	}
15336 	return (error);
15337 }
15338 
15339 static struct cb_ops dtrace_cb_ops = {
15340 	dtrace_open,		/* open */
15341 	dtrace_close,		/* close */
15342 	nulldev,		/* strategy */
15343 	nulldev,		/* print */
15344 	nodev,			/* dump */
15345 	nodev,			/* read */
15346 	nodev,			/* write */
15347 	dtrace_ioctl,		/* ioctl */
15348 	nodev,			/* devmap */
15349 	nodev,			/* mmap */
15350 	nodev,			/* segmap */
15351 	nochpoll,		/* poll */
15352 	ddi_prop_op,		/* cb_prop_op */
15353 	0,			/* streamtab  */
15354 	D_NEW | D_MP		/* Driver compatibility flag */
15355 };
15356 
15357 static struct dev_ops dtrace_ops = {
15358 	DEVO_REV,		/* devo_rev */
15359 	0,			/* refcnt */
15360 	dtrace_info,		/* get_dev_info */
15361 	nulldev,		/* identify */
15362 	nulldev,		/* probe */
15363 	dtrace_attach,		/* attach */
15364 	dtrace_detach,		/* detach */
15365 	nodev,			/* reset */
15366 	&dtrace_cb_ops,		/* driver operations */
15367 	NULL,			/* bus operations */
15368 	nodev			/* dev power */
15369 };
15370 
15371 static struct modldrv modldrv = {
15372 	&mod_driverops,		/* module type (this is a pseudo driver) */
15373 	"Dynamic Tracing",	/* name of module */
15374 	&dtrace_ops,		/* driver ops */
15375 };
15376 
15377 static struct modlinkage modlinkage = {
15378 	MODREV_1,
15379 	(void *)&modldrv,
15380 	NULL
15381 };
15382 
15383 int
15384 _init(void)
15385 {
15386 	return (mod_install(&modlinkage));
15387 }
15388 
15389 int
15390 _info(struct modinfo *modinfop)
15391 {
15392 	return (mod_info(&modlinkage, modinfop));
15393 }
15394 
15395 int
15396 _fini(void)
15397 {
15398 	return (mod_remove(&modlinkage));
15399 }
15400