xref: /illumos-gate/usr/src/uts/common/dtrace/dtrace.c (revision b73ccab0)
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 (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2019 Joyent, Inc.
25  * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
26  */
27 
28 /*
29  * DTrace - Dynamic Tracing for Solaris
30  *
31  * This is the implementation of the Solaris Dynamic Tracing framework
32  * (DTrace).  The user-visible interface to DTrace is described at length in
33  * the "Solaris Dynamic Tracing Guide".  The interfaces between the libdtrace
34  * library, the in-kernel DTrace framework, and the DTrace providers are
35  * described in the block comments in the <sys/dtrace.h> header file.  The
36  * internal architecture of DTrace is described in the block comments in the
37  * <sys/dtrace_impl.h> header file.  The comments contained within the DTrace
38  * implementation very much assume mastery of all of these sources; if one has
39  * an unanswered question about the implementation, one should consult them
40  * first.
41  *
42  * The functions here are ordered roughly as follows:
43  *
44  *   - Probe context functions
45  *   - Probe hashing functions
46  *   - Non-probe context utility functions
47  *   - Matching functions
48  *   - Provider-to-Framework API functions
49  *   - Probe management functions
50  *   - DIF object functions
51  *   - Format functions
52  *   - Predicate functions
53  *   - ECB functions
54  *   - Buffer functions
55  *   - Enabling functions
56  *   - DOF functions
57  *   - Anonymous enabling functions
58  *   - Consumer state functions
59  *   - Helper functions
60  *   - Hook functions
61  *   - Driver cookbook functions
62  *
63  * Each group of functions begins with a block comment labelled the "DTrace
64  * [Group] Functions", allowing one to find each block by searching forward
65  * on capital-f functions.
66  */
67 #include <sys/errno.h>
68 #include <sys/stat.h>
69 #include <sys/modctl.h>
70 #include <sys/conf.h>
71 #include <sys/systm.h>
72 #include <sys/ddi.h>
73 #include <sys/sunddi.h>
74 #include <sys/cpuvar.h>
75 #include <sys/kmem.h>
76 #include <sys/strsubr.h>
77 #include <sys/sysmacros.h>
78 #include <sys/dtrace_impl.h>
79 #include <sys/atomic.h>
80 #include <sys/cmn_err.h>
81 #include <sys/mutex_impl.h>
82 #include <sys/rwlock_impl.h>
83 #include <sys/ctf_api.h>
84 #include <sys/panic.h>
85 #include <sys/priv_impl.h>
86 #include <sys/policy.h>
87 #include <sys/cred_impl.h>
88 #include <sys/procfs_isa.h>
89 #include <sys/taskq.h>
90 #include <sys/mkdev.h>
91 #include <sys/kdi.h>
92 #include <sys/zone.h>
93 #include <sys/socket.h>
94 #include <netinet/in.h>
95 #include "strtolctype.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 = (8 * 1024 * 1024);
121 size_t		dtrace_statvar_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 = 1024;
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 = MSEC2NSEC(500);		/* 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 hrtime_t	dtrace_unregister_defunct_reap = (hrtime_t)60 * NANOSEC;
150 
151 /*
152  * DTrace External Variables
153  *
154  * As dtrace(7D) is a kernel module, any DTrace variables are obviously
155  * available to DTrace consumers via the backtick (`) syntax.  One of these,
156  * dtrace_zero, is made deliberately so:  it is provided as a source of
157  * well-known, zero-filled memory.  While this variable is not documented,
158  * it is used by some translators as an implementation detail.
159  */
160 const char	dtrace_zero[256] = { 0 };	/* zero-filled memory */
161 
162 /*
163  * DTrace Internal Variables
164  */
165 static dev_info_t	*dtrace_devi;		/* device info */
166 static vmem_t		*dtrace_arena;		/* probe ID arena */
167 static vmem_t		*dtrace_minor;		/* minor number arena */
168 static taskq_t		*dtrace_taskq;		/* task queue */
169 static dtrace_probe_t	**dtrace_probes;	/* array of all probes */
170 static int		dtrace_nprobes;		/* number of probes */
171 static dtrace_provider_t *dtrace_provider;	/* provider list */
172 static dtrace_meta_t	*dtrace_meta_pid;	/* user-land meta provider */
173 static int		dtrace_opens;		/* number of opens */
174 static int		dtrace_helpers;		/* number of helpers */
175 static int		dtrace_getf;		/* number of unpriv getf()s */
176 static void		*dtrace_softstate;	/* softstate pointer */
177 static dtrace_hash_t	*dtrace_bymod;		/* probes hashed by module */
178 static dtrace_hash_t	*dtrace_byfunc;		/* probes hashed by function */
179 static dtrace_hash_t	*dtrace_byname;		/* probes hashed by name */
180 static dtrace_toxrange_t *dtrace_toxrange;	/* toxic range array */
181 static int		dtrace_toxranges;	/* number of toxic ranges */
182 static int		dtrace_toxranges_max;	/* size of toxic range array */
183 static dtrace_anon_t	dtrace_anon;		/* anonymous enabling */
184 static kmem_cache_t	*dtrace_state_cache;	/* cache for dynamic state */
185 static uint64_t		dtrace_vtime_references; /* number of vtimestamp refs */
186 static kthread_t	*dtrace_panicked;	/* panicking thread */
187 static dtrace_ecb_t	*dtrace_ecb_create_cache; /* cached created ECB */
188 static dtrace_genid_t	dtrace_probegen;	/* current probe generation */
189 static dtrace_helpers_t *dtrace_deferred_pid;	/* deferred helper list */
190 static dtrace_enabling_t *dtrace_retained;	/* list of retained enablings */
191 static dtrace_genid_t	dtrace_retained_gen;	/* current retained enab gen */
192 static dtrace_dynvar_t	dtrace_dynhash_sink;	/* end of dynamic hash chains */
193 static int		dtrace_dynvar_failclean; /* dynvars failed to clean */
194 
195 /*
196  * DTrace Locking
197  * DTrace is protected by three (relatively coarse-grained) locks:
198  *
199  * (1) dtrace_lock is required to manipulate essentially any DTrace state,
200  *     including enabling state, probes, ECBs, consumer state, helper state,
201  *     etc.  Importantly, dtrace_lock is _not_ required when in probe context;
202  *     probe context is lock-free -- synchronization is handled via the
203  *     dtrace_sync() cross call mechanism.
204  *
205  * (2) dtrace_provider_lock is required when manipulating provider state, or
206  *     when provider state must be held constant.
207  *
208  * (3) dtrace_meta_lock is required when manipulating meta provider state, or
209  *     when meta provider state must be held constant.
210  *
211  * The lock ordering between these three locks is dtrace_meta_lock before
212  * dtrace_provider_lock before dtrace_lock.  (In particular, there are
213  * several places where dtrace_provider_lock is held by the framework as it
214  * calls into the providers -- which then call back into the framework,
215  * grabbing dtrace_lock.)
216  *
217  * There are two other locks in the mix:  mod_lock and cpu_lock.  With respect
218  * to dtrace_provider_lock and dtrace_lock, cpu_lock continues its historical
219  * role as a coarse-grained lock; it is acquired before both of these locks.
220  * With respect to dtrace_meta_lock, its behavior is stranger:  cpu_lock must
221  * be acquired _between_ dtrace_meta_lock and any other DTrace locks.
222  * mod_lock is similar with respect to dtrace_provider_lock in that it must be
223  * acquired _between_ dtrace_provider_lock and dtrace_lock.
224  */
225 static kmutex_t		dtrace_lock;		/* probe state lock */
226 static kmutex_t		dtrace_provider_lock;	/* provider state lock */
227 static kmutex_t		dtrace_meta_lock;	/* meta-provider state lock */
228 
229 /*
230  * DTrace Provider Variables
231  *
232  * These are the variables relating to DTrace as a provider (that is, the
233  * provider of the BEGIN, END, and ERROR probes).
234  */
235 static dtrace_pattr_t	dtrace_provider_attr = {
236 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
237 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
238 { DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
239 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
240 { DTRACE_STABILITY_STABLE, DTRACE_STABILITY_STABLE, DTRACE_CLASS_COMMON },
241 };
242 
243 static void
244 dtrace_nullop(void)
245 {}
246 
247 static int
248 dtrace_enable_nullop(void)
249 {
250 	return (0);
251 }
252 
253 static dtrace_pops_t	dtrace_provider_ops = {
254 	(void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop,
255 	(void (*)(void *, struct modctl *))dtrace_nullop,
256 	(int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop,
257 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
258 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
259 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop,
260 	NULL,
261 	NULL,
262 	NULL,
263 	(void (*)(void *, dtrace_id_t, void *))dtrace_nullop
264 };
265 
266 static dtrace_id_t	dtrace_probeid_begin;	/* special BEGIN probe */
267 static dtrace_id_t	dtrace_probeid_end;	/* special END probe */
268 dtrace_id_t		dtrace_probeid_error;	/* special ERROR probe */
269 
270 /*
271  * DTrace Helper Tracing Variables
272  *
273  * These variables should be set dynamically to enable helper tracing.  The
274  * only variables that should be set are dtrace_helptrace_enable (which should
275  * be set to a non-zero value to allocate helper tracing buffers on the next
276  * open of /dev/dtrace) and dtrace_helptrace_disable (which should be set to a
277  * non-zero value to deallocate helper tracing buffers on the next close of
278  * /dev/dtrace).  When (and only when) helper tracing is disabled, the
279  * buffer size may also be set via dtrace_helptrace_bufsize.
280  */
281 int			dtrace_helptrace_enable = 0;
282 int			dtrace_helptrace_disable = 0;
283 int			dtrace_helptrace_bufsize = 16 * 1024 * 1024;
284 uint32_t		dtrace_helptrace_nlocals;
285 static dtrace_helptrace_t *dtrace_helptrace_buffer;
286 static uint32_t		dtrace_helptrace_next = 0;
287 static int		dtrace_helptrace_wrapped = 0;
288 
289 /*
290  * DTrace Error Hashing
291  *
292  * On DEBUG kernels, DTrace will track the errors that has seen in a hash
293  * table.  This is very useful for checking coverage of tests that are
294  * expected to induce DIF or DOF processing errors, and may be useful for
295  * debugging problems in the DIF code generator or in DOF generation .  The
296  * error hash may be examined with the ::dtrace_errhash MDB dcmd.
297  */
298 #ifdef DEBUG
299 static dtrace_errhash_t	dtrace_errhash[DTRACE_ERRHASHSZ];
300 static const char *dtrace_errlast;
301 static kthread_t *dtrace_errthread;
302 static kmutex_t dtrace_errlock;
303 #endif
304 
305 /*
306  * DTrace Macros and Constants
307  *
308  * These are various macros that are useful in various spots in the
309  * implementation, along with a few random constants that have no meaning
310  * outside of the implementation.  There is no real structure to this cpp
311  * mishmash -- but is there ever?
312  */
313 #define	DTRACE_HASHSTR(hash, probe)	\
314 	dtrace_hash_str(*((char **)((uintptr_t)(probe) + (hash)->dth_stroffs)))
315 
316 #define	DTRACE_HASHNEXT(hash, probe)	\
317 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_nextoffs)
318 
319 #define	DTRACE_HASHPREV(hash, probe)	\
320 	(dtrace_probe_t **)((uintptr_t)(probe) + (hash)->dth_prevoffs)
321 
322 #define	DTRACE_HASHEQ(hash, lhs, rhs)	\
323 	(strcmp(*((char **)((uintptr_t)(lhs) + (hash)->dth_stroffs)), \
324 	    *((char **)((uintptr_t)(rhs) + (hash)->dth_stroffs))) == 0)
325 
326 #define	DTRACE_AGGHASHSIZE_SLEW		17
327 
328 #define	DTRACE_V4MAPPED_OFFSET		(sizeof (uint32_t) * 3)
329 
330 /*
331  * The key for a thread-local variable consists of the lower 61 bits of the
332  * t_did, plus the 3 bits of the highest active interrupt above LOCK_LEVEL.
333  * We add DIF_VARIABLE_MAX to t_did to assure that the thread key is never
334  * equal to a variable identifier.  This is necessary (but not sufficient) to
335  * assure that global associative arrays never collide with thread-local
336  * variables.  To guarantee that they cannot collide, we must also define the
337  * order for keying dynamic variables.  That order is:
338  *
339  *   [ key0 ] ... [ keyn ] [ variable-key ] [ tls-key ]
340  *
341  * Because the variable-key and the tls-key are in orthogonal spaces, there is
342  * no way for a global variable key signature to match a thread-local key
343  * signature.
344  */
345 #define	DTRACE_TLS_THRKEY(where) { \
346 	uint_t intr = 0; \
347 	uint_t actv = CPU->cpu_intr_actv >> (LOCK_LEVEL + 1); \
348 	for (; actv; actv >>= 1) \
349 		intr++; \
350 	ASSERT(intr < (1 << 3)); \
351 	(where) = ((curthread->t_did + DIF_VARIABLE_MAX) & \
352 	    (((uint64_t)1 << 61) - 1)) | ((uint64_t)intr << 61); \
353 }
354 
355 #define	DT_BSWAP_8(x)	((x) & 0xff)
356 #define	DT_BSWAP_16(x)	((DT_BSWAP_8(x) << 8) | DT_BSWAP_8((x) >> 8))
357 #define	DT_BSWAP_32(x)	((DT_BSWAP_16(x) << 16) | DT_BSWAP_16((x) >> 16))
358 #define	DT_BSWAP_64(x)	((DT_BSWAP_32(x) << 32) | DT_BSWAP_32((x) >> 32))
359 
360 #define	DT_MASK_LO 0x00000000FFFFFFFFULL
361 
362 #define	DTRACE_STORE(type, tomax, offset, what) \
363 	*((type *)((uintptr_t)(tomax) + (uintptr_t)offset)) = (type)(what);
364 
365 #ifndef __x86
366 #define	DTRACE_ALIGNCHECK(addr, size, flags)				\
367 	if (addr & (size - 1)) {					\
368 		*flags |= CPU_DTRACE_BADALIGN;				\
369 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
370 		return (0);						\
371 	}
372 #else
373 #define	DTRACE_ALIGNCHECK(addr, size, flags)
374 #endif
375 
376 /*
377  * Test whether a range of memory starting at testaddr of size testsz falls
378  * within the range of memory described by addr, sz.  We take care to avoid
379  * problems with overflow and underflow of the unsigned quantities, and
380  * disallow all negative sizes.  Ranges of size 0 are allowed.
381  */
382 #define	DTRACE_INRANGE(testaddr, testsz, baseaddr, basesz) \
383 	((testaddr) - (uintptr_t)(baseaddr) < (basesz) && \
384 	(testaddr) + (testsz) - (uintptr_t)(baseaddr) <= (basesz) && \
385 	(testaddr) + (testsz) >= (testaddr))
386 
387 #define	DTRACE_RANGE_REMAIN(remp, addr, baseaddr, basesz)		\
388 do {									\
389 	if ((remp) != NULL) {						\
390 		*(remp) = (uintptr_t)(baseaddr) + (basesz) - (addr);	\
391 	}								\
392 _NOTE(CONSTCOND) } while (0)
393 
394 
395 /*
396  * Test whether alloc_sz bytes will fit in the scratch region.  We isolate
397  * alloc_sz on the righthand side of the comparison in order to avoid overflow
398  * or underflow in the comparison with it.  This is simpler than the INRANGE
399  * check above, because we know that the dtms_scratch_ptr is valid in the
400  * range.  Allocations of size zero are allowed.
401  */
402 #define	DTRACE_INSCRATCH(mstate, alloc_sz) \
403 	((mstate)->dtms_scratch_base + (mstate)->dtms_scratch_size - \
404 	(mstate)->dtms_scratch_ptr >= (alloc_sz))
405 
406 #define	DTRACE_LOADFUNC(bits)						\
407 /*CSTYLED*/								\
408 uint##bits##_t								\
409 dtrace_load##bits(uintptr_t addr)					\
410 {									\
411 	size_t size = bits / NBBY;					\
412 	/*CSTYLED*/							\
413 	uint##bits##_t rval;						\
414 	int i;								\
415 	volatile uint16_t *flags = (volatile uint16_t *)		\
416 	    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;			\
417 									\
418 	DTRACE_ALIGNCHECK(addr, size, flags);				\
419 									\
420 	for (i = 0; i < dtrace_toxranges; i++) {			\
421 		if (addr >= dtrace_toxrange[i].dtt_limit)		\
422 			continue;					\
423 									\
424 		if (addr + size <= dtrace_toxrange[i].dtt_base)		\
425 			continue;					\
426 									\
427 		/*							\
428 		 * This address falls within a toxic region; return 0.	\
429 		 */							\
430 		*flags |= CPU_DTRACE_BADADDR;				\
431 		cpu_core[CPU->cpu_id].cpuc_dtrace_illval = addr;	\
432 		return (0);						\
433 	}								\
434 									\
435 	*flags |= CPU_DTRACE_NOFAULT;					\
436 	/*CSTYLED*/							\
437 	rval = *((volatile uint##bits##_t *)addr);			\
438 	*flags &= ~CPU_DTRACE_NOFAULT;					\
439 									\
440 	return (!(*flags & CPU_DTRACE_FAULT) ? rval : 0);		\
441 }
442 
443 #ifdef _LP64
444 #define	dtrace_loadptr	dtrace_load64
445 #else
446 #define	dtrace_loadptr	dtrace_load32
447 #endif
448 
449 #define	DTRACE_DYNHASH_FREE	0
450 #define	DTRACE_DYNHASH_SINK	1
451 #define	DTRACE_DYNHASH_VALID	2
452 
453 #define	DTRACE_MATCH_FAIL	-1
454 #define	DTRACE_MATCH_NEXT	0
455 #define	DTRACE_MATCH_DONE	1
456 #define	DTRACE_ANCHORED(probe)	((probe)->dtpr_func[0] != '\0')
457 #define	DTRACE_STATE_ALIGN	64
458 
459 #define	DTRACE_FLAGS2FLT(flags)						\
460 	(((flags) & CPU_DTRACE_BADADDR) ? DTRACEFLT_BADADDR :		\
461 	((flags) & CPU_DTRACE_ILLOP) ? DTRACEFLT_ILLOP :		\
462 	((flags) & CPU_DTRACE_DIVZERO) ? DTRACEFLT_DIVZERO :		\
463 	((flags) & CPU_DTRACE_KPRIV) ? DTRACEFLT_KPRIV :		\
464 	((flags) & CPU_DTRACE_UPRIV) ? DTRACEFLT_UPRIV :		\
465 	((flags) & CPU_DTRACE_TUPOFLOW) ?  DTRACEFLT_TUPOFLOW :		\
466 	((flags) & CPU_DTRACE_BADALIGN) ?  DTRACEFLT_BADALIGN :		\
467 	((flags) & CPU_DTRACE_NOSCRATCH) ?  DTRACEFLT_NOSCRATCH :	\
468 	((flags) & CPU_DTRACE_BADSTACK) ?  DTRACEFLT_BADSTACK :		\
469 	DTRACEFLT_UNKNOWN)
470 
471 #define	DTRACEACT_ISSTRING(act)						\
472 	((act)->dta_kind == DTRACEACT_DIFEXPR &&			\
473 	(act)->dta_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING)
474 
475 static size_t dtrace_strlen(const char *, size_t);
476 static dtrace_probe_t *dtrace_probe_lookup_id(dtrace_id_t id);
477 static void dtrace_enabling_provide(dtrace_provider_t *);
478 static int dtrace_enabling_match(dtrace_enabling_t *, int *);
479 static void dtrace_enabling_matchall(void);
480 static void dtrace_enabling_reap(void);
481 static dtrace_state_t *dtrace_anon_grab(void);
482 static uint64_t dtrace_helper(int, dtrace_mstate_t *,
483     dtrace_state_t *, uint64_t, uint64_t);
484 static dtrace_helpers_t *dtrace_helpers_create(proc_t *);
485 static void dtrace_buffer_drop(dtrace_buffer_t *);
486 static int dtrace_buffer_consumed(dtrace_buffer_t *, hrtime_t when);
487 static intptr_t dtrace_buffer_reserve(dtrace_buffer_t *, size_t, size_t,
488     dtrace_state_t *, dtrace_mstate_t *);
489 static int dtrace_state_option(dtrace_state_t *, dtrace_optid_t,
490     dtrace_optval_t);
491 static int dtrace_ecb_create_enable(dtrace_probe_t *, void *);
492 static void dtrace_helper_provider_destroy(dtrace_helper_provider_t *);
493 static int dtrace_priv_proc(dtrace_state_t *, dtrace_mstate_t *);
494 static void dtrace_getf_barrier(void);
495 static int dtrace_canload_remains(uint64_t, size_t, size_t *,
496     dtrace_mstate_t *, dtrace_vstate_t *);
497 static int dtrace_canstore_remains(uint64_t, size_t, size_t *,
498     dtrace_mstate_t *, dtrace_vstate_t *);
499 
500 /*
501  * DTrace Probe Context Functions
502  *
503  * These functions are called from probe context.  Because probe context is
504  * any context in which C may be called, arbitrarily locks may be held,
505  * interrupts may be disabled, we may be in arbitrary dispatched state, etc.
506  * As a result, functions called from probe context may only call other DTrace
507  * support functions -- they may not interact at all with the system at large.
508  * (Note that the ASSERT macro is made probe-context safe by redefining it in
509  * terms of dtrace_assfail(), a probe-context safe function.) If arbitrary
510  * loads are to be performed from probe context, they _must_ be in terms of
511  * the safe dtrace_load*() variants.
512  *
513  * Some functions in this block are not actually called from probe context;
514  * for these functions, there will be a comment above the function reading
515  * "Note:  not called from probe context."
516  */
517 void
518 dtrace_panic(const char *format, ...)
519 {
520 	va_list alist;
521 
522 	va_start(alist, format);
523 	dtrace_vpanic(format, alist);
524 	va_end(alist);
525 }
526 
527 int
528 dtrace_assfail(const char *a, const char *f, int l)
529 {
530 	dtrace_panic("assertion failed: %s, file: %s, line: %d", a, f, l);
531 
532 	/*
533 	 * We just need something here that even the most clever compiler
534 	 * cannot optimize away.
535 	 */
536 	return (a[(uintptr_t)f]);
537 }
538 
539 /*
540  * Atomically increment a specified error counter from probe context.
541  */
542 static void
543 dtrace_error(uint32_t *counter)
544 {
545 	/*
546 	 * Most counters stored to in probe context are per-CPU counters.
547 	 * However, there are some error conditions that are sufficiently
548 	 * arcane that they don't merit per-CPU storage.  If these counters
549 	 * are incremented concurrently on different CPUs, scalability will be
550 	 * adversely affected -- but we don't expect them to be white-hot in a
551 	 * correctly constructed enabling...
552 	 */
553 	uint32_t oval, nval;
554 
555 	do {
556 		oval = *counter;
557 
558 		if ((nval = oval + 1) == 0) {
559 			/*
560 			 * If the counter would wrap, set it to 1 -- assuring
561 			 * that the counter is never zero when we have seen
562 			 * errors.  (The counter must be 32-bits because we
563 			 * aren't guaranteed a 64-bit compare&swap operation.)
564 			 * To save this code both the infamy of being fingered
565 			 * by a priggish news story and the indignity of being
566 			 * the target of a neo-puritan witch trial, we're
567 			 * carefully avoiding any colorful description of the
568 			 * likelihood of this condition -- but suffice it to
569 			 * say that it is only slightly more likely than the
570 			 * overflow of predicate cache IDs, as discussed in
571 			 * dtrace_predicate_create().
572 			 */
573 			nval = 1;
574 		}
575 	} while (dtrace_cas32(counter, oval, nval) != oval);
576 }
577 
578 /*
579  * Use the DTRACE_LOADFUNC macro to define functions for each of loading a
580  * uint8_t, a uint16_t, a uint32_t and a uint64_t.
581  */
582 /* BEGIN CSTYLED */
583 DTRACE_LOADFUNC(8)
584 DTRACE_LOADFUNC(16)
585 DTRACE_LOADFUNC(32)
586 DTRACE_LOADFUNC(64)
587 /* END CSTYLED */
588 
589 static int
590 dtrace_inscratch(uintptr_t dest, size_t size, dtrace_mstate_t *mstate)
591 {
592 	if (dest < mstate->dtms_scratch_base)
593 		return (0);
594 
595 	if (dest + size < dest)
596 		return (0);
597 
598 	if (dest + size > mstate->dtms_scratch_ptr)
599 		return (0);
600 
601 	return (1);
602 }
603 
604 static int
605 dtrace_canstore_statvar(uint64_t addr, size_t sz, size_t *remain,
606     dtrace_statvar_t **svars, int nsvars)
607 {
608 	int i;
609 	size_t maxglobalsize, maxlocalsize;
610 
611 	if (nsvars == 0)
612 		return (0);
613 
614 	maxglobalsize = dtrace_statvar_maxsize + sizeof (uint64_t);
615 	maxlocalsize = maxglobalsize * NCPU;
616 
617 	for (i = 0; i < nsvars; i++) {
618 		dtrace_statvar_t *svar = svars[i];
619 		uint8_t scope;
620 		size_t size;
621 
622 		if (svar == NULL || (size = svar->dtsv_size) == 0)
623 			continue;
624 
625 		scope = svar->dtsv_var.dtdv_scope;
626 
627 		/*
628 		 * We verify that our size is valid in the spirit of providing
629 		 * defense in depth:  we want to prevent attackers from using
630 		 * DTrace to escalate an orthogonal kernel heap corruption bug
631 		 * into the ability to store to arbitrary locations in memory.
632 		 */
633 		VERIFY((scope == DIFV_SCOPE_GLOBAL && size <= maxglobalsize) ||
634 		    (scope == DIFV_SCOPE_LOCAL && size <= maxlocalsize));
635 
636 		if (DTRACE_INRANGE(addr, sz, svar->dtsv_data,
637 		    svar->dtsv_size)) {
638 			DTRACE_RANGE_REMAIN(remain, addr, svar->dtsv_data,
639 			    svar->dtsv_size);
640 			return (1);
641 		}
642 	}
643 
644 	return (0);
645 }
646 
647 /*
648  * Check to see if the address is within a memory region to which a store may
649  * be issued.  This includes the DTrace scratch areas, and any DTrace variable
650  * region.  The caller of dtrace_canstore() is responsible for performing any
651  * alignment checks that are needed before stores are actually executed.
652  */
653 static int
654 dtrace_canstore(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
655     dtrace_vstate_t *vstate)
656 {
657 	return (dtrace_canstore_remains(addr, sz, NULL, mstate, vstate));
658 }
659 
660 /*
661  * Implementation of dtrace_canstore which communicates the upper bound of the
662  * allowed memory region.
663  */
664 static int
665 dtrace_canstore_remains(uint64_t addr, size_t sz, size_t *remain,
666     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
667 {
668 	/*
669 	 * First, check to see if the address is in scratch space...
670 	 */
671 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_scratch_base,
672 	    mstate->dtms_scratch_size)) {
673 		DTRACE_RANGE_REMAIN(remain, addr, mstate->dtms_scratch_base,
674 		    mstate->dtms_scratch_size);
675 		return (1);
676 	}
677 
678 	/*
679 	 * Now check to see if it's a dynamic variable.  This check will pick
680 	 * up both thread-local variables and any global dynamically-allocated
681 	 * variables.
682 	 */
683 	if (DTRACE_INRANGE(addr, sz, vstate->dtvs_dynvars.dtds_base,
684 	    vstate->dtvs_dynvars.dtds_size)) {
685 		dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
686 		uintptr_t base = (uintptr_t)dstate->dtds_base +
687 		    (dstate->dtds_hashsize * sizeof (dtrace_dynhash_t));
688 		uintptr_t chunkoffs;
689 		dtrace_dynvar_t *dvar;
690 
691 		/*
692 		 * Before we assume that we can store here, we need to make
693 		 * sure that it isn't in our metadata -- storing to our
694 		 * dynamic variable metadata would corrupt our state.  For
695 		 * the range to not include any dynamic variable metadata,
696 		 * it must:
697 		 *
698 		 *	(1) Start above the hash table that is at the base of
699 		 *	the dynamic variable space
700 		 *
701 		 *	(2) Have a starting chunk offset that is beyond the
702 		 *	dtrace_dynvar_t that is at the base of every chunk
703 		 *
704 		 *	(3) Not span a chunk boundary
705 		 *
706 		 *	(4) Not be in the tuple space of a dynamic variable
707 		 *
708 		 */
709 		if (addr < base)
710 			return (0);
711 
712 		chunkoffs = (addr - base) % dstate->dtds_chunksize;
713 
714 		if (chunkoffs < sizeof (dtrace_dynvar_t))
715 			return (0);
716 
717 		if (chunkoffs + sz > dstate->dtds_chunksize)
718 			return (0);
719 
720 		dvar = (dtrace_dynvar_t *)((uintptr_t)addr - chunkoffs);
721 
722 		if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE)
723 			return (0);
724 
725 		if (chunkoffs < sizeof (dtrace_dynvar_t) +
726 		    ((dvar->dtdv_tuple.dtt_nkeys - 1) * sizeof (dtrace_key_t)))
727 			return (0);
728 
729 		DTRACE_RANGE_REMAIN(remain, addr, dvar, dstate->dtds_chunksize);
730 		return (1);
731 	}
732 
733 	/*
734 	 * Finally, check the static local and global variables.  These checks
735 	 * take the longest, so we perform them last.
736 	 */
737 	if (dtrace_canstore_statvar(addr, sz, remain,
738 	    vstate->dtvs_locals, vstate->dtvs_nlocals))
739 		return (1);
740 
741 	if (dtrace_canstore_statvar(addr, sz, remain,
742 	    vstate->dtvs_globals, vstate->dtvs_nglobals))
743 		return (1);
744 
745 	return (0);
746 }
747 
748 
749 /*
750  * Convenience routine to check to see if the address is within a memory
751  * region in which a load may be issued given the user's privilege level;
752  * if not, it sets the appropriate error flags and loads 'addr' into the
753  * illegal value slot.
754  *
755  * DTrace subroutines (DIF_SUBR_*) should use this helper to implement
756  * appropriate memory access protection.
757  */
758 static int
759 dtrace_canload(uint64_t addr, size_t sz, dtrace_mstate_t *mstate,
760     dtrace_vstate_t *vstate)
761 {
762 	return (dtrace_canload_remains(addr, sz, NULL, mstate, vstate));
763 }
764 
765 /*
766  * Implementation of dtrace_canload which communicates the upper bound of the
767  * allowed memory region.
768  */
769 static int
770 dtrace_canload_remains(uint64_t addr, size_t sz, size_t *remain,
771     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
772 {
773 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
774 	file_t *fp;
775 
776 	/*
777 	 * If we hold the privilege to read from kernel memory, then
778 	 * everything is readable.
779 	 */
780 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
781 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
782 		return (1);
783 	}
784 
785 	/*
786 	 * You can obviously read that which you can store.
787 	 */
788 	if (dtrace_canstore_remains(addr, sz, remain, mstate, vstate))
789 		return (1);
790 
791 	/*
792 	 * We're allowed to read from our own string table.
793 	 */
794 	if (DTRACE_INRANGE(addr, sz, mstate->dtms_difo->dtdo_strtab,
795 	    mstate->dtms_difo->dtdo_strlen)) {
796 		DTRACE_RANGE_REMAIN(remain, addr,
797 		    mstate->dtms_difo->dtdo_strtab,
798 		    mstate->dtms_difo->dtdo_strlen);
799 		return (1);
800 	}
801 
802 	if (vstate->dtvs_state != NULL &&
803 	    dtrace_priv_proc(vstate->dtvs_state, mstate)) {
804 		proc_t *p;
805 
806 		/*
807 		 * When we have privileges to the current process, there are
808 		 * several context-related kernel structures that are safe to
809 		 * read, even absent the privilege to read from kernel memory.
810 		 * These reads are safe because these structures contain only
811 		 * state that (1) we're permitted to read, (2) is harmless or
812 		 * (3) contains pointers to additional kernel state that we're
813 		 * not permitted to read (and as such, do not present an
814 		 * opportunity for privilege escalation).  Finally (and
815 		 * critically), because of the nature of their relation with
816 		 * the current thread context, the memory associated with these
817 		 * structures cannot change over the duration of probe context,
818 		 * and it is therefore impossible for this memory to be
819 		 * deallocated and reallocated as something else while it's
820 		 * being operated upon.
821 		 */
822 		if (DTRACE_INRANGE(addr, sz, curthread, sizeof (kthread_t))) {
823 			DTRACE_RANGE_REMAIN(remain, addr, curthread,
824 			    sizeof (kthread_t));
825 			return (1);
826 		}
827 
828 		if ((p = curthread->t_procp) != NULL && DTRACE_INRANGE(addr,
829 		    sz, curthread->t_procp, sizeof (proc_t))) {
830 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_procp,
831 			    sizeof (proc_t));
832 			return (1);
833 		}
834 
835 		if (curthread->t_cred != NULL && DTRACE_INRANGE(addr, sz,
836 		    curthread->t_cred, sizeof (cred_t))) {
837 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cred,
838 			    sizeof (cred_t));
839 			return (1);
840 		}
841 
842 		if (p != NULL && p->p_pidp != NULL && DTRACE_INRANGE(addr, sz,
843 		    &(p->p_pidp->pid_id), sizeof (pid_t))) {
844 			DTRACE_RANGE_REMAIN(remain, addr, &(p->p_pidp->pid_id),
845 			    sizeof (pid_t));
846 			return (1);
847 		}
848 
849 		if (curthread->t_cpu != NULL && DTRACE_INRANGE(addr, sz,
850 		    curthread->t_cpu, offsetof(cpu_t, cpu_pause_thread))) {
851 			DTRACE_RANGE_REMAIN(remain, addr, curthread->t_cpu,
852 			    offsetof(cpu_t, cpu_pause_thread));
853 			return (1);
854 		}
855 	}
856 
857 	if ((fp = mstate->dtms_getf) != NULL) {
858 		uintptr_t psz = sizeof (void *);
859 		vnode_t *vp;
860 		vnodeops_t *op;
861 
862 		/*
863 		 * When getf() returns a file_t, the enabling is implicitly
864 		 * granted the (transient) right to read the returned file_t
865 		 * as well as the v_path and v_op->vnop_name of the underlying
866 		 * vnode.  These accesses are allowed after a successful
867 		 * getf() because the members that they refer to cannot change
868 		 * once set -- and the barrier logic in the kernel's closef()
869 		 * path assures that the file_t and its referenced vode_t
870 		 * cannot themselves be stale (that is, it impossible for
871 		 * either dtms_getf itself or its f_vnode member to reference
872 		 * freed memory).
873 		 */
874 		if (DTRACE_INRANGE(addr, sz, fp, sizeof (file_t))) {
875 			DTRACE_RANGE_REMAIN(remain, addr, fp, sizeof (file_t));
876 			return (1);
877 		}
878 
879 		if ((vp = fp->f_vnode) != NULL) {
880 			size_t slen;
881 
882 			if (DTRACE_INRANGE(addr, sz, &vp->v_path, psz)) {
883 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_path,
884 				    psz);
885 				return (1);
886 			}
887 
888 			slen = strlen(vp->v_path) + 1;
889 			if (DTRACE_INRANGE(addr, sz, vp->v_path, slen)) {
890 				DTRACE_RANGE_REMAIN(remain, addr, vp->v_path,
891 				    slen);
892 				return (1);
893 			}
894 
895 			if (DTRACE_INRANGE(addr, sz, &vp->v_op, psz)) {
896 				DTRACE_RANGE_REMAIN(remain, addr, &vp->v_op,
897 				    psz);
898 				return (1);
899 			}
900 
901 			if ((op = vp->v_op) != NULL &&
902 			    DTRACE_INRANGE(addr, sz, &op->vnop_name, psz)) {
903 				DTRACE_RANGE_REMAIN(remain, addr,
904 				    &op->vnop_name, psz);
905 				return (1);
906 			}
907 
908 			if (op != NULL && op->vnop_name != NULL &&
909 			    DTRACE_INRANGE(addr, sz, op->vnop_name,
910 			    (slen = strlen(op->vnop_name) + 1))) {
911 				DTRACE_RANGE_REMAIN(remain, addr,
912 				    op->vnop_name, slen);
913 				return (1);
914 			}
915 		}
916 	}
917 
918 	DTRACE_CPUFLAG_SET(CPU_DTRACE_KPRIV);
919 	*illval = addr;
920 	return (0);
921 }
922 
923 /*
924  * Convenience routine to check to see if a given string is within a memory
925  * region in which a load may be issued given the user's privilege level;
926  * this exists so that we don't need to issue unnecessary dtrace_strlen()
927  * calls in the event that the user has all privileges.
928  */
929 static int
930 dtrace_strcanload(uint64_t addr, size_t sz, size_t *remain,
931     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
932 {
933 	size_t rsize;
934 
935 	/*
936 	 * If we hold the privilege to read from kernel memory, then
937 	 * everything is readable.
938 	 */
939 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
940 		DTRACE_RANGE_REMAIN(remain, addr, addr, sz);
941 		return (1);
942 	}
943 
944 	/*
945 	 * Even if the caller is uninterested in querying the remaining valid
946 	 * range, it is required to ensure that the access is allowed.
947 	 */
948 	if (remain == NULL) {
949 		remain = &rsize;
950 	}
951 	if (dtrace_canload_remains(addr, 0, remain, mstate, vstate)) {
952 		size_t strsz;
953 		/*
954 		 * Perform the strlen after determining the length of the
955 		 * memory region which is accessible.  This prevents timing
956 		 * information from being used to find NULs in memory which is
957 		 * not accessible to the caller.
958 		 */
959 		strsz = 1 + dtrace_strlen((char *)(uintptr_t)addr,
960 		    MIN(sz, *remain));
961 		if (strsz <= *remain) {
962 			return (1);
963 		}
964 	}
965 
966 	return (0);
967 }
968 
969 /*
970  * Convenience routine to check to see if a given variable is within a memory
971  * region in which a load may be issued given the user's privilege level.
972  */
973 static int
974 dtrace_vcanload(void *src, dtrace_diftype_t *type, size_t *remain,
975     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
976 {
977 	size_t sz;
978 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
979 
980 	/*
981 	 * Calculate the max size before performing any checks since even
982 	 * DTRACE_ACCESS_KERNEL-credentialed callers expect that this function
983 	 * return the max length via 'remain'.
984 	 */
985 	if (type->dtdt_kind == DIF_TYPE_STRING) {
986 		dtrace_state_t *state = vstate->dtvs_state;
987 
988 		if (state != NULL) {
989 			sz = state->dts_options[DTRACEOPT_STRSIZE];
990 		} else {
991 			/*
992 			 * In helper context, we have a NULL state; fall back
993 			 * to using the system-wide default for the string size
994 			 * in this case.
995 			 */
996 			sz = dtrace_strsize_default;
997 		}
998 	} else {
999 		sz = type->dtdt_size;
1000 	}
1001 
1002 	/*
1003 	 * If we hold the privilege to read from kernel memory, then
1004 	 * everything is readable.
1005 	 */
1006 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0) {
1007 		DTRACE_RANGE_REMAIN(remain, (uintptr_t)src, src, sz);
1008 		return (1);
1009 	}
1010 
1011 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1012 		return (dtrace_strcanload((uintptr_t)src, sz, remain, mstate,
1013 		    vstate));
1014 	}
1015 	return (dtrace_canload_remains((uintptr_t)src, sz, remain, mstate,
1016 	    vstate));
1017 }
1018 
1019 /*
1020  * Convert a string to a signed integer using safe loads.
1021  *
1022  * NOTE: This function uses various macros from strtolctype.h to manipulate
1023  * digit values, etc -- these have all been checked to ensure they make
1024  * no additional function calls.
1025  */
1026 static int64_t
1027 dtrace_strtoll(char *input, int base, size_t limit)
1028 {
1029 	uintptr_t pos = (uintptr_t)input;
1030 	int64_t val = 0;
1031 	int x;
1032 	boolean_t neg = B_FALSE;
1033 	char c, cc, ccc;
1034 	uintptr_t end = pos + limit;
1035 
1036 	/*
1037 	 * Consume any whitespace preceding digits.
1038 	 */
1039 	while ((c = dtrace_load8(pos)) == ' ' || c == '\t')
1040 		pos++;
1041 
1042 	/*
1043 	 * Handle an explicit sign if one is present.
1044 	 */
1045 	if (c == '-' || c == '+') {
1046 		if (c == '-')
1047 			neg = B_TRUE;
1048 		c = dtrace_load8(++pos);
1049 	}
1050 
1051 	/*
1052 	 * Check for an explicit hexadecimal prefix ("0x" or "0X") and skip it
1053 	 * if present.
1054 	 */
1055 	if (base == 16 && c == '0' && ((cc = dtrace_load8(pos + 1)) == 'x' ||
1056 	    cc == 'X') && isxdigit(ccc = dtrace_load8(pos + 2))) {
1057 		pos += 2;
1058 		c = ccc;
1059 	}
1060 
1061 	/*
1062 	 * Read in contiguous digits until the first non-digit character.
1063 	 */
1064 	for (; pos < end && c != '\0' && lisalnum(c) && (x = DIGIT(c)) < base;
1065 	    c = dtrace_load8(++pos))
1066 		val = val * base + x;
1067 
1068 	return (neg ? -val : val);
1069 }
1070 
1071 /*
1072  * Compare two strings using safe loads.
1073  */
1074 static int
1075 dtrace_strncmp(char *s1, char *s2, size_t limit)
1076 {
1077 	uint8_t c1, c2;
1078 	volatile uint16_t *flags;
1079 
1080 	if (s1 == s2 || limit == 0)
1081 		return (0);
1082 
1083 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1084 
1085 	do {
1086 		if (s1 == NULL) {
1087 			c1 = '\0';
1088 		} else {
1089 			c1 = dtrace_load8((uintptr_t)s1++);
1090 		}
1091 
1092 		if (s2 == NULL) {
1093 			c2 = '\0';
1094 		} else {
1095 			c2 = dtrace_load8((uintptr_t)s2++);
1096 		}
1097 
1098 		if (c1 != c2)
1099 			return (c1 - c2);
1100 	} while (--limit && c1 != '\0' && !(*flags & CPU_DTRACE_FAULT));
1101 
1102 	return (0);
1103 }
1104 
1105 /*
1106  * Compute strlen(s) for a string using safe memory accesses.  The additional
1107  * len parameter is used to specify a maximum length to ensure completion.
1108  */
1109 static size_t
1110 dtrace_strlen(const char *s, size_t lim)
1111 {
1112 	uint_t len;
1113 
1114 	for (len = 0; len != lim; len++) {
1115 		if (dtrace_load8((uintptr_t)s++) == '\0')
1116 			break;
1117 	}
1118 
1119 	return (len);
1120 }
1121 
1122 /*
1123  * Check if an address falls within a toxic region.
1124  */
1125 static int
1126 dtrace_istoxic(uintptr_t kaddr, size_t size)
1127 {
1128 	uintptr_t taddr, tsize;
1129 	int i;
1130 
1131 	for (i = 0; i < dtrace_toxranges; i++) {
1132 		taddr = dtrace_toxrange[i].dtt_base;
1133 		tsize = dtrace_toxrange[i].dtt_limit - taddr;
1134 
1135 		if (kaddr - taddr < tsize) {
1136 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1137 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = kaddr;
1138 			return (1);
1139 		}
1140 
1141 		if (taddr - kaddr < size) {
1142 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
1143 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = taddr;
1144 			return (1);
1145 		}
1146 	}
1147 
1148 	return (0);
1149 }
1150 
1151 /*
1152  * Copy src to dst using safe memory accesses.  The src is assumed to be unsafe
1153  * memory specified by the DIF program.  The dst is assumed to be safe memory
1154  * that we can store to directly because it is managed by DTrace.  As with
1155  * standard bcopy, overlapping copies are handled properly.
1156  */
1157 static void
1158 dtrace_bcopy(const void *src, void *dst, size_t len)
1159 {
1160 	if (len != 0) {
1161 		uint8_t *s1 = dst;
1162 		const uint8_t *s2 = src;
1163 
1164 		if (s1 <= s2) {
1165 			do {
1166 				*s1++ = dtrace_load8((uintptr_t)s2++);
1167 			} while (--len != 0);
1168 		} else {
1169 			s2 += len;
1170 			s1 += len;
1171 
1172 			do {
1173 				*--s1 = dtrace_load8((uintptr_t)--s2);
1174 			} while (--len != 0);
1175 		}
1176 	}
1177 }
1178 
1179 /*
1180  * Copy src to dst using safe memory accesses, up to either the specified
1181  * length, or the point that a nul byte is encountered.  The src is assumed to
1182  * be unsafe memory specified by the DIF program.  The dst is assumed to be
1183  * safe memory that we can store to directly because it is managed by DTrace.
1184  * Unlike dtrace_bcopy(), overlapping regions are not handled.
1185  */
1186 static void
1187 dtrace_strcpy(const void *src, void *dst, size_t len)
1188 {
1189 	if (len != 0) {
1190 		uint8_t *s1 = dst, c;
1191 		const uint8_t *s2 = src;
1192 
1193 		do {
1194 			*s1++ = c = dtrace_load8((uintptr_t)s2++);
1195 		} while (--len != 0 && c != '\0');
1196 	}
1197 }
1198 
1199 /*
1200  * Copy src to dst, deriving the size and type from the specified (BYREF)
1201  * variable type.  The src is assumed to be unsafe memory specified by the DIF
1202  * program.  The dst is assumed to be DTrace variable memory that is of the
1203  * specified type; we assume that we can store to directly.
1204  */
1205 static void
1206 dtrace_vcopy(void *src, void *dst, dtrace_diftype_t *type, size_t limit)
1207 {
1208 	ASSERT(type->dtdt_flags & DIF_TF_BYREF);
1209 
1210 	if (type->dtdt_kind == DIF_TYPE_STRING) {
1211 		dtrace_strcpy(src, dst, MIN(type->dtdt_size, limit));
1212 	} else {
1213 		dtrace_bcopy(src, dst, MIN(type->dtdt_size, limit));
1214 	}
1215 }
1216 
1217 /*
1218  * Compare s1 to s2 using safe memory accesses.  The s1 data is assumed to be
1219  * unsafe memory specified by the DIF program.  The s2 data is assumed to be
1220  * safe memory that we can access directly because it is managed by DTrace.
1221  */
1222 static int
1223 dtrace_bcmp(const void *s1, const void *s2, size_t len)
1224 {
1225 	volatile uint16_t *flags;
1226 
1227 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
1228 
1229 	if (s1 == s2)
1230 		return (0);
1231 
1232 	if (s1 == NULL || s2 == NULL)
1233 		return (1);
1234 
1235 	if (s1 != s2 && len != 0) {
1236 		const uint8_t *ps1 = s1;
1237 		const uint8_t *ps2 = s2;
1238 
1239 		do {
1240 			if (dtrace_load8((uintptr_t)ps1++) != *ps2++)
1241 				return (1);
1242 		} while (--len != 0 && !(*flags & CPU_DTRACE_FAULT));
1243 	}
1244 	return (0);
1245 }
1246 
1247 /*
1248  * Zero the specified region using a simple byte-by-byte loop.  Note that this
1249  * is for safe DTrace-managed memory only.
1250  */
1251 static void
1252 dtrace_bzero(void *dst, size_t len)
1253 {
1254 	uchar_t *cp;
1255 
1256 	for (cp = dst; len != 0; len--)
1257 		*cp++ = 0;
1258 }
1259 
1260 static void
1261 dtrace_add_128(uint64_t *addend1, uint64_t *addend2, uint64_t *sum)
1262 {
1263 	uint64_t result[2];
1264 
1265 	result[0] = addend1[0] + addend2[0];
1266 	result[1] = addend1[1] + addend2[1] +
1267 	    (result[0] < addend1[0] || result[0] < addend2[0] ? 1 : 0);
1268 
1269 	sum[0] = result[0];
1270 	sum[1] = result[1];
1271 }
1272 
1273 /*
1274  * Shift the 128-bit value in a by b. If b is positive, shift left.
1275  * If b is negative, shift right.
1276  */
1277 static void
1278 dtrace_shift_128(uint64_t *a, int b)
1279 {
1280 	uint64_t mask;
1281 
1282 	if (b == 0)
1283 		return;
1284 
1285 	if (b < 0) {
1286 		b = -b;
1287 		if (b >= 64) {
1288 			a[0] = a[1] >> (b - 64);
1289 			a[1] = 0;
1290 		} else {
1291 			a[0] >>= b;
1292 			mask = 1LL << (64 - b);
1293 			mask -= 1;
1294 			a[0] |= ((a[1] & mask) << (64 - b));
1295 			a[1] >>= b;
1296 		}
1297 	} else {
1298 		if (b >= 64) {
1299 			a[1] = a[0] << (b - 64);
1300 			a[0] = 0;
1301 		} else {
1302 			a[1] <<= b;
1303 			mask = a[0] >> (64 - b);
1304 			a[1] |= mask;
1305 			a[0] <<= b;
1306 		}
1307 	}
1308 }
1309 
1310 /*
1311  * The basic idea is to break the 2 64-bit values into 4 32-bit values,
1312  * use native multiplication on those, and then re-combine into the
1313  * resulting 128-bit value.
1314  *
1315  * (hi1 << 32 + lo1) * (hi2 << 32 + lo2) =
1316  *     hi1 * hi2 << 64 +
1317  *     hi1 * lo2 << 32 +
1318  *     hi2 * lo1 << 32 +
1319  *     lo1 * lo2
1320  */
1321 static void
1322 dtrace_multiply_128(uint64_t factor1, uint64_t factor2, uint64_t *product)
1323 {
1324 	uint64_t hi1, hi2, lo1, lo2;
1325 	uint64_t tmp[2];
1326 
1327 	hi1 = factor1 >> 32;
1328 	hi2 = factor2 >> 32;
1329 
1330 	lo1 = factor1 & DT_MASK_LO;
1331 	lo2 = factor2 & DT_MASK_LO;
1332 
1333 	product[0] = lo1 * lo2;
1334 	product[1] = hi1 * hi2;
1335 
1336 	tmp[0] = hi1 * lo2;
1337 	tmp[1] = 0;
1338 	dtrace_shift_128(tmp, 32);
1339 	dtrace_add_128(product, tmp, product);
1340 
1341 	tmp[0] = hi2 * lo1;
1342 	tmp[1] = 0;
1343 	dtrace_shift_128(tmp, 32);
1344 	dtrace_add_128(product, tmp, product);
1345 }
1346 
1347 /*
1348  * This privilege check should be used by actions and subroutines to
1349  * verify that the user credentials of the process that enabled the
1350  * invoking ECB match the target credentials
1351  */
1352 static int
1353 dtrace_priv_proc_common_user(dtrace_state_t *state)
1354 {
1355 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1356 
1357 	/*
1358 	 * We should always have a non-NULL state cred here, since if cred
1359 	 * is null (anonymous tracing), we fast-path bypass this routine.
1360 	 */
1361 	ASSERT(s_cr != NULL);
1362 
1363 	if ((cr = CRED()) != NULL &&
1364 	    s_cr->cr_uid == cr->cr_uid &&
1365 	    s_cr->cr_uid == cr->cr_ruid &&
1366 	    s_cr->cr_uid == cr->cr_suid &&
1367 	    s_cr->cr_gid == cr->cr_gid &&
1368 	    s_cr->cr_gid == cr->cr_rgid &&
1369 	    s_cr->cr_gid == cr->cr_sgid)
1370 		return (1);
1371 
1372 	return (0);
1373 }
1374 
1375 /*
1376  * This privilege check should be used by actions and subroutines to
1377  * verify that the zone of the process that enabled the invoking ECB
1378  * matches the target credentials
1379  */
1380 static int
1381 dtrace_priv_proc_common_zone(dtrace_state_t *state)
1382 {
1383 	cred_t *cr, *s_cr = state->dts_cred.dcr_cred;
1384 
1385 	/*
1386 	 * We should always have a non-NULL state cred here, since if cred
1387 	 * is null (anonymous tracing), we fast-path bypass this routine.
1388 	 */
1389 	ASSERT(s_cr != NULL);
1390 
1391 	if ((cr = CRED()) != NULL && s_cr->cr_zone == cr->cr_zone)
1392 		return (1);
1393 
1394 	return (0);
1395 }
1396 
1397 /*
1398  * This privilege check should be used by actions and subroutines to
1399  * verify that the process has not setuid or changed credentials.
1400  */
1401 static int
1402 dtrace_priv_proc_common_nocd()
1403 {
1404 	proc_t *proc;
1405 
1406 	if ((proc = ttoproc(curthread)) != NULL &&
1407 	    !(proc->p_flag & SNOCD))
1408 		return (1);
1409 
1410 	return (0);
1411 }
1412 
1413 static int
1414 dtrace_priv_proc_destructive(dtrace_state_t *state, dtrace_mstate_t *mstate)
1415 {
1416 	int action = state->dts_cred.dcr_action;
1417 
1418 	if (!(mstate->dtms_access & DTRACE_ACCESS_PROC))
1419 		goto bad;
1420 
1421 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE) == 0) &&
1422 	    dtrace_priv_proc_common_zone(state) == 0)
1423 		goto bad;
1424 
1425 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER) == 0) &&
1426 	    dtrace_priv_proc_common_user(state) == 0)
1427 		goto bad;
1428 
1429 	if (((action & DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG) == 0) &&
1430 	    dtrace_priv_proc_common_nocd() == 0)
1431 		goto bad;
1432 
1433 	return (1);
1434 
1435 bad:
1436 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1437 
1438 	return (0);
1439 }
1440 
1441 static int
1442 dtrace_priv_proc_control(dtrace_state_t *state, dtrace_mstate_t *mstate)
1443 {
1444 	if (mstate->dtms_access & DTRACE_ACCESS_PROC) {
1445 		if (state->dts_cred.dcr_action & DTRACE_CRA_PROC_CONTROL)
1446 			return (1);
1447 
1448 		if (dtrace_priv_proc_common_zone(state) &&
1449 		    dtrace_priv_proc_common_user(state) &&
1450 		    dtrace_priv_proc_common_nocd())
1451 			return (1);
1452 	}
1453 
1454 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1455 
1456 	return (0);
1457 }
1458 
1459 static int
1460 dtrace_priv_proc(dtrace_state_t *state, dtrace_mstate_t *mstate)
1461 {
1462 	if ((mstate->dtms_access & DTRACE_ACCESS_PROC) &&
1463 	    (state->dts_cred.dcr_action & DTRACE_CRA_PROC))
1464 		return (1);
1465 
1466 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_UPRIV;
1467 
1468 	return (0);
1469 }
1470 
1471 static int
1472 dtrace_priv_kernel(dtrace_state_t *state)
1473 {
1474 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL)
1475 		return (1);
1476 
1477 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1478 
1479 	return (0);
1480 }
1481 
1482 static int
1483 dtrace_priv_kernel_destructive(dtrace_state_t *state)
1484 {
1485 	if (state->dts_cred.dcr_action & DTRACE_CRA_KERNEL_DESTRUCTIVE)
1486 		return (1);
1487 
1488 	cpu_core[CPU->cpu_id].cpuc_dtrace_flags |= CPU_DTRACE_KPRIV;
1489 
1490 	return (0);
1491 }
1492 
1493 /*
1494  * Determine if the dte_cond of the specified ECB allows for processing of
1495  * the current probe to continue.  Note that this routine may allow continued
1496  * processing, but with access(es) stripped from the mstate's dtms_access
1497  * field.
1498  */
1499 static int
1500 dtrace_priv_probe(dtrace_state_t *state, dtrace_mstate_t *mstate,
1501     dtrace_ecb_t *ecb)
1502 {
1503 	dtrace_probe_t *probe = ecb->dte_probe;
1504 	dtrace_provider_t *prov = probe->dtpr_provider;
1505 	dtrace_pops_t *pops = &prov->dtpv_pops;
1506 	int mode = DTRACE_MODE_NOPRIV_DROP;
1507 
1508 	ASSERT(ecb->dte_cond);
1509 
1510 	if (pops->dtps_mode != NULL) {
1511 		mode = pops->dtps_mode(prov->dtpv_arg,
1512 		    probe->dtpr_id, probe->dtpr_arg);
1513 
1514 		ASSERT(mode & (DTRACE_MODE_USER | DTRACE_MODE_KERNEL));
1515 		ASSERT(mode & (DTRACE_MODE_NOPRIV_RESTRICT |
1516 		    DTRACE_MODE_NOPRIV_DROP));
1517 	}
1518 
1519 	/*
1520 	 * If the dte_cond bits indicate that this consumer is only allowed to
1521 	 * see user-mode firings of this probe, check that the probe was fired
1522 	 * while in a user context.  If that's not the case, use the policy
1523 	 * specified by the provider to determine if we drop the probe or
1524 	 * merely restrict operation.
1525 	 */
1526 	if (ecb->dte_cond & DTRACE_COND_USERMODE) {
1527 		ASSERT(mode != DTRACE_MODE_NOPRIV_DROP);
1528 
1529 		if (!(mode & DTRACE_MODE_USER)) {
1530 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1531 				return (0);
1532 
1533 			mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1534 		}
1535 	}
1536 
1537 	/*
1538 	 * This is more subtle than it looks. We have to be absolutely certain
1539 	 * that CRED() isn't going to change out from under us so it's only
1540 	 * legit to examine that structure if we're in constrained situations.
1541 	 * Currently, the only times we'll this check is if a non-super-user
1542 	 * has enabled the profile or syscall providers -- providers that
1543 	 * allow visibility of all processes. For the profile case, the check
1544 	 * above will ensure that we're examining a user context.
1545 	 */
1546 	if (ecb->dte_cond & DTRACE_COND_OWNER) {
1547 		cred_t *cr;
1548 		cred_t *s_cr = state->dts_cred.dcr_cred;
1549 		proc_t *proc;
1550 
1551 		ASSERT(s_cr != NULL);
1552 
1553 		if ((cr = CRED()) == NULL ||
1554 		    s_cr->cr_uid != cr->cr_uid ||
1555 		    s_cr->cr_uid != cr->cr_ruid ||
1556 		    s_cr->cr_uid != cr->cr_suid ||
1557 		    s_cr->cr_gid != cr->cr_gid ||
1558 		    s_cr->cr_gid != cr->cr_rgid ||
1559 		    s_cr->cr_gid != cr->cr_sgid ||
1560 		    (proc = ttoproc(curthread)) == NULL ||
1561 		    (proc->p_flag & SNOCD)) {
1562 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1563 				return (0);
1564 
1565 			mstate->dtms_access &= ~DTRACE_ACCESS_PROC;
1566 		}
1567 	}
1568 
1569 	/*
1570 	 * If our dte_cond is set to DTRACE_COND_ZONEOWNER and we are not
1571 	 * in our zone, check to see if our mode policy is to restrict rather
1572 	 * than to drop; if to restrict, strip away both DTRACE_ACCESS_PROC
1573 	 * and DTRACE_ACCESS_ARGS
1574 	 */
1575 	if (ecb->dte_cond & DTRACE_COND_ZONEOWNER) {
1576 		cred_t *cr;
1577 		cred_t *s_cr = state->dts_cred.dcr_cred;
1578 
1579 		ASSERT(s_cr != NULL);
1580 
1581 		if ((cr = CRED()) == NULL ||
1582 		    s_cr->cr_zone->zone_id != cr->cr_zone->zone_id) {
1583 			if (mode & DTRACE_MODE_NOPRIV_DROP)
1584 				return (0);
1585 
1586 			mstate->dtms_access &=
1587 			    ~(DTRACE_ACCESS_PROC | DTRACE_ACCESS_ARGS);
1588 		}
1589 	}
1590 
1591 	/*
1592 	 * By merits of being in this code path at all, we have limited
1593 	 * privileges.  If the provider has indicated that limited privileges
1594 	 * are to denote restricted operation, strip off the ability to access
1595 	 * arguments.
1596 	 */
1597 	if (mode & DTRACE_MODE_LIMITEDPRIV_RESTRICT)
1598 		mstate->dtms_access &= ~DTRACE_ACCESS_ARGS;
1599 
1600 	return (1);
1601 }
1602 
1603 /*
1604  * Note:  not called from probe context.  This function is called
1605  * asynchronously (and at a regular interval) from outside of probe context to
1606  * clean the dirty dynamic variable lists on all CPUs.  Dynamic variable
1607  * cleaning is explained in detail in <sys/dtrace_impl.h>.
1608  */
1609 void
1610 dtrace_dynvar_clean(dtrace_dstate_t *dstate)
1611 {
1612 	dtrace_dynvar_t *dirty;
1613 	dtrace_dstate_percpu_t *dcpu;
1614 	dtrace_dynvar_t **rinsep;
1615 	int i, j, work = 0;
1616 
1617 	for (i = 0; i < NCPU; i++) {
1618 		dcpu = &dstate->dtds_percpu[i];
1619 		rinsep = &dcpu->dtdsc_rinsing;
1620 
1621 		/*
1622 		 * If the dirty list is NULL, there is no dirty work to do.
1623 		 */
1624 		if (dcpu->dtdsc_dirty == NULL)
1625 			continue;
1626 
1627 		if (dcpu->dtdsc_rinsing != NULL) {
1628 			/*
1629 			 * If the rinsing list is non-NULL, then it is because
1630 			 * this CPU was selected to accept another CPU's
1631 			 * dirty list -- and since that time, dirty buffers
1632 			 * have accumulated.  This is a highly unlikely
1633 			 * condition, but we choose to ignore the dirty
1634 			 * buffers -- they'll be picked up a future cleanse.
1635 			 */
1636 			continue;
1637 		}
1638 
1639 		if (dcpu->dtdsc_clean != NULL) {
1640 			/*
1641 			 * If the clean list is non-NULL, then we're in a
1642 			 * situation where a CPU has done deallocations (we
1643 			 * have a non-NULL dirty list) but no allocations (we
1644 			 * also have a non-NULL clean list).  We can't simply
1645 			 * move the dirty list into the clean list on this
1646 			 * CPU, yet we also don't want to allow this condition
1647 			 * to persist, lest a short clean list prevent a
1648 			 * massive dirty list from being cleaned (which in
1649 			 * turn could lead to otherwise avoidable dynamic
1650 			 * drops).  To deal with this, we look for some CPU
1651 			 * with a NULL clean list, NULL dirty list, and NULL
1652 			 * rinsing list -- and then we borrow this CPU to
1653 			 * rinse our dirty list.
1654 			 */
1655 			for (j = 0; j < NCPU; j++) {
1656 				dtrace_dstate_percpu_t *rinser;
1657 
1658 				rinser = &dstate->dtds_percpu[j];
1659 
1660 				if (rinser->dtdsc_rinsing != NULL)
1661 					continue;
1662 
1663 				if (rinser->dtdsc_dirty != NULL)
1664 					continue;
1665 
1666 				if (rinser->dtdsc_clean != NULL)
1667 					continue;
1668 
1669 				rinsep = &rinser->dtdsc_rinsing;
1670 				break;
1671 			}
1672 
1673 			if (j == NCPU) {
1674 				/*
1675 				 * We were unable to find another CPU that
1676 				 * could accept this dirty list -- we are
1677 				 * therefore unable to clean it now.
1678 				 */
1679 				dtrace_dynvar_failclean++;
1680 				continue;
1681 			}
1682 		}
1683 
1684 		work = 1;
1685 
1686 		/*
1687 		 * Atomically move the dirty list aside.
1688 		 */
1689 		do {
1690 			dirty = dcpu->dtdsc_dirty;
1691 
1692 			/*
1693 			 * Before we zap the dirty list, set the rinsing list.
1694 			 * (This allows for a potential assertion in
1695 			 * dtrace_dynvar():  if a free dynamic variable appears
1696 			 * on a hash chain, either the dirty list or the
1697 			 * rinsing list for some CPU must be non-NULL.)
1698 			 */
1699 			*rinsep = dirty;
1700 			dtrace_membar_producer();
1701 		} while (dtrace_casptr(&dcpu->dtdsc_dirty,
1702 		    dirty, NULL) != dirty);
1703 	}
1704 
1705 	if (!work) {
1706 		/*
1707 		 * We have no work to do; we can simply return.
1708 		 */
1709 		return;
1710 	}
1711 
1712 	dtrace_sync();
1713 
1714 	for (i = 0; i < NCPU; i++) {
1715 		dcpu = &dstate->dtds_percpu[i];
1716 
1717 		if (dcpu->dtdsc_rinsing == NULL)
1718 			continue;
1719 
1720 		/*
1721 		 * We are now guaranteed that no hash chain contains a pointer
1722 		 * into this dirty list; we can make it clean.
1723 		 */
1724 		ASSERT(dcpu->dtdsc_clean == NULL);
1725 		dcpu->dtdsc_clean = dcpu->dtdsc_rinsing;
1726 		dcpu->dtdsc_rinsing = NULL;
1727 	}
1728 
1729 	/*
1730 	 * Before we actually set the state to be DTRACE_DSTATE_CLEAN, make
1731 	 * sure that all CPUs have seen all of the dtdsc_clean pointers.
1732 	 * This prevents a race whereby a CPU incorrectly decides that
1733 	 * the state should be something other than DTRACE_DSTATE_CLEAN
1734 	 * after dtrace_dynvar_clean() has completed.
1735 	 */
1736 	dtrace_sync();
1737 
1738 	dstate->dtds_state = DTRACE_DSTATE_CLEAN;
1739 }
1740 
1741 /*
1742  * Depending on the value of the op parameter, this function looks-up,
1743  * allocates or deallocates an arbitrarily-keyed dynamic variable.  If an
1744  * allocation is requested, this function will return a pointer to a
1745  * dtrace_dynvar_t corresponding to the allocated variable -- or NULL if no
1746  * variable can be allocated.  If NULL is returned, the appropriate counter
1747  * will be incremented.
1748  */
1749 dtrace_dynvar_t *
1750 dtrace_dynvar(dtrace_dstate_t *dstate, uint_t nkeys,
1751     dtrace_key_t *key, size_t dsize, dtrace_dynvar_op_t op,
1752     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate)
1753 {
1754 	uint64_t hashval = DTRACE_DYNHASH_VALID;
1755 	dtrace_dynhash_t *hash = dstate->dtds_hash;
1756 	dtrace_dynvar_t *free, *new_free, *next, *dvar, *start, *prev = NULL;
1757 	processorid_t me = CPU->cpu_id, cpu = me;
1758 	dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[me];
1759 	size_t bucket, ksize;
1760 	size_t chunksize = dstate->dtds_chunksize;
1761 	uintptr_t kdata, lock, nstate;
1762 	uint_t i;
1763 
1764 	ASSERT(nkeys != 0);
1765 
1766 	/*
1767 	 * Hash the key.  As with aggregations, we use Jenkins' "One-at-a-time"
1768 	 * algorithm.  For the by-value portions, we perform the algorithm in
1769 	 * 16-bit chunks (as opposed to 8-bit chunks).  This speeds things up a
1770 	 * bit, and seems to have only a minute effect on distribution.  For
1771 	 * the by-reference data, we perform "One-at-a-time" iterating (safely)
1772 	 * over each referenced byte.  It's painful to do this, but it's much
1773 	 * better than pathological hash distribution.  The efficacy of the
1774 	 * hashing algorithm (and a comparison with other algorithms) may be
1775 	 * found by running the ::dtrace_dynstat MDB dcmd.
1776 	 */
1777 	for (i = 0; i < nkeys; i++) {
1778 		if (key[i].dttk_size == 0) {
1779 			uint64_t val = key[i].dttk_value;
1780 
1781 			hashval += (val >> 48) & 0xffff;
1782 			hashval += (hashval << 10);
1783 			hashval ^= (hashval >> 6);
1784 
1785 			hashval += (val >> 32) & 0xffff;
1786 			hashval += (hashval << 10);
1787 			hashval ^= (hashval >> 6);
1788 
1789 			hashval += (val >> 16) & 0xffff;
1790 			hashval += (hashval << 10);
1791 			hashval ^= (hashval >> 6);
1792 
1793 			hashval += val & 0xffff;
1794 			hashval += (hashval << 10);
1795 			hashval ^= (hashval >> 6);
1796 		} else {
1797 			/*
1798 			 * This is incredibly painful, but it beats the hell
1799 			 * out of the alternative.
1800 			 */
1801 			uint64_t j, size = key[i].dttk_size;
1802 			uintptr_t base = (uintptr_t)key[i].dttk_value;
1803 
1804 			if (!dtrace_canload(base, size, mstate, vstate))
1805 				break;
1806 
1807 			for (j = 0; j < size; j++) {
1808 				hashval += dtrace_load8(base + j);
1809 				hashval += (hashval << 10);
1810 				hashval ^= (hashval >> 6);
1811 			}
1812 		}
1813 	}
1814 
1815 	if (DTRACE_CPUFLAG_ISSET(CPU_DTRACE_FAULT))
1816 		return (NULL);
1817 
1818 	hashval += (hashval << 3);
1819 	hashval ^= (hashval >> 11);
1820 	hashval += (hashval << 15);
1821 
1822 	/*
1823 	 * There is a remote chance (ideally, 1 in 2^31) that our hashval
1824 	 * comes out to be one of our two sentinel hash values.  If this
1825 	 * actually happens, we set the hashval to be a value known to be a
1826 	 * non-sentinel value.
1827 	 */
1828 	if (hashval == DTRACE_DYNHASH_FREE || hashval == DTRACE_DYNHASH_SINK)
1829 		hashval = DTRACE_DYNHASH_VALID;
1830 
1831 	/*
1832 	 * Yes, it's painful to do a divide here.  If the cycle count becomes
1833 	 * important here, tricks can be pulled to reduce it.  (However, it's
1834 	 * critical that hash collisions be kept to an absolute minimum;
1835 	 * they're much more painful than a divide.)  It's better to have a
1836 	 * solution that generates few collisions and still keeps things
1837 	 * relatively simple.
1838 	 */
1839 	bucket = hashval % dstate->dtds_hashsize;
1840 
1841 	if (op == DTRACE_DYNVAR_DEALLOC) {
1842 		volatile uintptr_t *lockp = &hash[bucket].dtdh_lock;
1843 
1844 		for (;;) {
1845 			while ((lock = *lockp) & 1)
1846 				continue;
1847 
1848 			if (dtrace_casptr((void *)lockp,
1849 			    (void *)lock, (void *)(lock + 1)) == (void *)lock)
1850 				break;
1851 		}
1852 
1853 		dtrace_membar_producer();
1854 	}
1855 
1856 top:
1857 	prev = NULL;
1858 	lock = hash[bucket].dtdh_lock;
1859 
1860 	dtrace_membar_consumer();
1861 
1862 	start = hash[bucket].dtdh_chain;
1863 	ASSERT(start != NULL && (start->dtdv_hashval == DTRACE_DYNHASH_SINK ||
1864 	    start->dtdv_hashval != DTRACE_DYNHASH_FREE ||
1865 	    op != DTRACE_DYNVAR_DEALLOC));
1866 
1867 	for (dvar = start; dvar != NULL; dvar = dvar->dtdv_next) {
1868 		dtrace_tuple_t *dtuple = &dvar->dtdv_tuple;
1869 		dtrace_key_t *dkey = &dtuple->dtt_key[0];
1870 
1871 		if (dvar->dtdv_hashval != hashval) {
1872 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_SINK) {
1873 				/*
1874 				 * We've reached the sink, and therefore the
1875 				 * end of the hash chain; we can kick out of
1876 				 * the loop knowing that we have seen a valid
1877 				 * snapshot of state.
1878 				 */
1879 				ASSERT(dvar->dtdv_next == NULL);
1880 				ASSERT(dvar == &dtrace_dynhash_sink);
1881 				break;
1882 			}
1883 
1884 			if (dvar->dtdv_hashval == DTRACE_DYNHASH_FREE) {
1885 				/*
1886 				 * We've gone off the rails:  somewhere along
1887 				 * the line, one of the members of this hash
1888 				 * chain was deleted.  Note that we could also
1889 				 * detect this by simply letting this loop run
1890 				 * to completion, as we would eventually hit
1891 				 * the end of the dirty list.  However, we
1892 				 * want to avoid running the length of the
1893 				 * dirty list unnecessarily (it might be quite
1894 				 * long), so we catch this as early as
1895 				 * possible by detecting the hash marker.  In
1896 				 * this case, we simply set dvar to NULL and
1897 				 * break; the conditional after the loop will
1898 				 * send us back to top.
1899 				 */
1900 				dvar = NULL;
1901 				break;
1902 			}
1903 
1904 			goto next;
1905 		}
1906 
1907 		if (dtuple->dtt_nkeys != nkeys)
1908 			goto next;
1909 
1910 		for (i = 0; i < nkeys; i++, dkey++) {
1911 			if (dkey->dttk_size != key[i].dttk_size)
1912 				goto next; /* size or type mismatch */
1913 
1914 			if (dkey->dttk_size != 0) {
1915 				if (dtrace_bcmp(
1916 				    (void *)(uintptr_t)key[i].dttk_value,
1917 				    (void *)(uintptr_t)dkey->dttk_value,
1918 				    dkey->dttk_size))
1919 					goto next;
1920 			} else {
1921 				if (dkey->dttk_value != key[i].dttk_value)
1922 					goto next;
1923 			}
1924 		}
1925 
1926 		if (op != DTRACE_DYNVAR_DEALLOC)
1927 			return (dvar);
1928 
1929 		ASSERT(dvar->dtdv_next == NULL ||
1930 		    dvar->dtdv_next->dtdv_hashval != DTRACE_DYNHASH_FREE);
1931 
1932 		if (prev != NULL) {
1933 			ASSERT(hash[bucket].dtdh_chain != dvar);
1934 			ASSERT(start != dvar);
1935 			ASSERT(prev->dtdv_next == dvar);
1936 			prev->dtdv_next = dvar->dtdv_next;
1937 		} else {
1938 			if (dtrace_casptr(&hash[bucket].dtdh_chain,
1939 			    start, dvar->dtdv_next) != start) {
1940 				/*
1941 				 * We have failed to atomically swing the
1942 				 * hash table head pointer, presumably because
1943 				 * of a conflicting allocation on another CPU.
1944 				 * We need to reread the hash chain and try
1945 				 * again.
1946 				 */
1947 				goto top;
1948 			}
1949 		}
1950 
1951 		dtrace_membar_producer();
1952 
1953 		/*
1954 		 * Now set the hash value to indicate that it's free.
1955 		 */
1956 		ASSERT(hash[bucket].dtdh_chain != dvar);
1957 		dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
1958 
1959 		dtrace_membar_producer();
1960 
1961 		/*
1962 		 * Set the next pointer to point at the dirty list, and
1963 		 * atomically swing the dirty pointer to the newly freed dvar.
1964 		 */
1965 		do {
1966 			next = dcpu->dtdsc_dirty;
1967 			dvar->dtdv_next = next;
1968 		} while (dtrace_casptr(&dcpu->dtdsc_dirty, next, dvar) != next);
1969 
1970 		/*
1971 		 * Finally, unlock this hash bucket.
1972 		 */
1973 		ASSERT(hash[bucket].dtdh_lock == lock);
1974 		ASSERT(lock & 1);
1975 		hash[bucket].dtdh_lock++;
1976 
1977 		return (NULL);
1978 next:
1979 		prev = dvar;
1980 		continue;
1981 	}
1982 
1983 	if (dvar == NULL) {
1984 		/*
1985 		 * If dvar is NULL, it is because we went off the rails:
1986 		 * one of the elements that we traversed in the hash chain
1987 		 * was deleted while we were traversing it.  In this case,
1988 		 * we assert that we aren't doing a dealloc (deallocs lock
1989 		 * the hash bucket to prevent themselves from racing with
1990 		 * one another), and retry the hash chain traversal.
1991 		 */
1992 		ASSERT(op != DTRACE_DYNVAR_DEALLOC);
1993 		goto top;
1994 	}
1995 
1996 	if (op != DTRACE_DYNVAR_ALLOC) {
1997 		/*
1998 		 * If we are not to allocate a new variable, we want to
1999 		 * return NULL now.  Before we return, check that the value
2000 		 * of the lock word hasn't changed.  If it has, we may have
2001 		 * seen an inconsistent snapshot.
2002 		 */
2003 		if (op == DTRACE_DYNVAR_NOALLOC) {
2004 			if (hash[bucket].dtdh_lock != lock)
2005 				goto top;
2006 		} else {
2007 			ASSERT(op == DTRACE_DYNVAR_DEALLOC);
2008 			ASSERT(hash[bucket].dtdh_lock == lock);
2009 			ASSERT(lock & 1);
2010 			hash[bucket].dtdh_lock++;
2011 		}
2012 
2013 		return (NULL);
2014 	}
2015 
2016 	/*
2017 	 * We need to allocate a new dynamic variable.  The size we need is the
2018 	 * size of dtrace_dynvar plus the size of nkeys dtrace_key_t's plus the
2019 	 * size of any auxiliary key data (rounded up to 8-byte alignment) plus
2020 	 * the size of any referred-to data (dsize).  We then round the final
2021 	 * size up to the chunksize for allocation.
2022 	 */
2023 	for (ksize = 0, i = 0; i < nkeys; i++)
2024 		ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
2025 
2026 	/*
2027 	 * This should be pretty much impossible, but could happen if, say,
2028 	 * strange DIF specified the tuple.  Ideally, this should be an
2029 	 * assertion and not an error condition -- but that requires that the
2030 	 * chunksize calculation in dtrace_difo_chunksize() be absolutely
2031 	 * bullet-proof.  (That is, it must not be able to be fooled by
2032 	 * malicious DIF.)  Given the lack of backwards branches in DIF,
2033 	 * solving this would presumably not amount to solving the Halting
2034 	 * Problem -- but it still seems awfully hard.
2035 	 */
2036 	if (sizeof (dtrace_dynvar_t) + sizeof (dtrace_key_t) * (nkeys - 1) +
2037 	    ksize + dsize > chunksize) {
2038 		dcpu->dtdsc_drops++;
2039 		return (NULL);
2040 	}
2041 
2042 	nstate = DTRACE_DSTATE_EMPTY;
2043 
2044 	do {
2045 retry:
2046 		free = dcpu->dtdsc_free;
2047 
2048 		if (free == NULL) {
2049 			dtrace_dynvar_t *clean = dcpu->dtdsc_clean;
2050 			void *rval;
2051 
2052 			if (clean == NULL) {
2053 				/*
2054 				 * We're out of dynamic variable space on
2055 				 * this CPU.  Unless we have tried all CPUs,
2056 				 * we'll try to allocate from a different
2057 				 * CPU.
2058 				 */
2059 				switch (dstate->dtds_state) {
2060 				case DTRACE_DSTATE_CLEAN: {
2061 					void *sp = &dstate->dtds_state;
2062 
2063 					if (++cpu >= NCPU)
2064 						cpu = 0;
2065 
2066 					if (dcpu->dtdsc_dirty != NULL &&
2067 					    nstate == DTRACE_DSTATE_EMPTY)
2068 						nstate = DTRACE_DSTATE_DIRTY;
2069 
2070 					if (dcpu->dtdsc_rinsing != NULL)
2071 						nstate = DTRACE_DSTATE_RINSING;
2072 
2073 					dcpu = &dstate->dtds_percpu[cpu];
2074 
2075 					if (cpu != me)
2076 						goto retry;
2077 
2078 					(void) dtrace_cas32(sp,
2079 					    DTRACE_DSTATE_CLEAN, nstate);
2080 
2081 					/*
2082 					 * To increment the correct bean
2083 					 * counter, take another lap.
2084 					 */
2085 					goto retry;
2086 				}
2087 
2088 				case DTRACE_DSTATE_DIRTY:
2089 					dcpu->dtdsc_dirty_drops++;
2090 					break;
2091 
2092 				case DTRACE_DSTATE_RINSING:
2093 					dcpu->dtdsc_rinsing_drops++;
2094 					break;
2095 
2096 				case DTRACE_DSTATE_EMPTY:
2097 					dcpu->dtdsc_drops++;
2098 					break;
2099 				}
2100 
2101 				DTRACE_CPUFLAG_SET(CPU_DTRACE_DROP);
2102 				return (NULL);
2103 			}
2104 
2105 			/*
2106 			 * The clean list appears to be non-empty.  We want to
2107 			 * move the clean list to the free list; we start by
2108 			 * moving the clean pointer aside.
2109 			 */
2110 			if (dtrace_casptr(&dcpu->dtdsc_clean,
2111 			    clean, NULL) != clean) {
2112 				/*
2113 				 * We are in one of two situations:
2114 				 *
2115 				 *  (a)	The clean list was switched to the
2116 				 *	free list by another CPU.
2117 				 *
2118 				 *  (b)	The clean list was added to by the
2119 				 *	cleansing cyclic.
2120 				 *
2121 				 * In either of these situations, we can
2122 				 * just reattempt the free list allocation.
2123 				 */
2124 				goto retry;
2125 			}
2126 
2127 			ASSERT(clean->dtdv_hashval == DTRACE_DYNHASH_FREE);
2128 
2129 			/*
2130 			 * Now we'll move the clean list to our free list.
2131 			 * It's impossible for this to fail:  the only way
2132 			 * the free list can be updated is through this
2133 			 * code path, and only one CPU can own the clean list.
2134 			 * Thus, it would only be possible for this to fail if
2135 			 * this code were racing with dtrace_dynvar_clean().
2136 			 * (That is, if dtrace_dynvar_clean() updated the clean
2137 			 * list, and we ended up racing to update the free
2138 			 * list.)  This race is prevented by the dtrace_sync()
2139 			 * in dtrace_dynvar_clean() -- which flushes the
2140 			 * owners of the clean lists out before resetting
2141 			 * the clean lists.
2142 			 */
2143 			dcpu = &dstate->dtds_percpu[me];
2144 			rval = dtrace_casptr(&dcpu->dtdsc_free, NULL, clean);
2145 			ASSERT(rval == NULL);
2146 			goto retry;
2147 		}
2148 
2149 		dvar = free;
2150 		new_free = dvar->dtdv_next;
2151 	} while (dtrace_casptr(&dcpu->dtdsc_free, free, new_free) != free);
2152 
2153 	/*
2154 	 * We have now allocated a new chunk.  We copy the tuple keys into the
2155 	 * tuple array and copy any referenced key data into the data space
2156 	 * following the tuple array.  As we do this, we relocate dttk_value
2157 	 * in the final tuple to point to the key data address in the chunk.
2158 	 */
2159 	kdata = (uintptr_t)&dvar->dtdv_tuple.dtt_key[nkeys];
2160 	dvar->dtdv_data = (void *)(kdata + ksize);
2161 	dvar->dtdv_tuple.dtt_nkeys = nkeys;
2162 
2163 	for (i = 0; i < nkeys; i++) {
2164 		dtrace_key_t *dkey = &dvar->dtdv_tuple.dtt_key[i];
2165 		size_t kesize = key[i].dttk_size;
2166 
2167 		if (kesize != 0) {
2168 			dtrace_bcopy(
2169 			    (const void *)(uintptr_t)key[i].dttk_value,
2170 			    (void *)kdata, kesize);
2171 			dkey->dttk_value = kdata;
2172 			kdata += P2ROUNDUP(kesize, sizeof (uint64_t));
2173 		} else {
2174 			dkey->dttk_value = key[i].dttk_value;
2175 		}
2176 
2177 		dkey->dttk_size = kesize;
2178 	}
2179 
2180 	ASSERT(dvar->dtdv_hashval == DTRACE_DYNHASH_FREE);
2181 	dvar->dtdv_hashval = hashval;
2182 	dvar->dtdv_next = start;
2183 
2184 	if (dtrace_casptr(&hash[bucket].dtdh_chain, start, dvar) == start)
2185 		return (dvar);
2186 
2187 	/*
2188 	 * The cas has failed.  Either another CPU is adding an element to
2189 	 * this hash chain, or another CPU is deleting an element from this
2190 	 * hash chain.  The simplest way to deal with both of these cases
2191 	 * (though not necessarily the most efficient) is to free our
2192 	 * allocated block and re-attempt it all.  Note that the free is
2193 	 * to the dirty list and _not_ to the free list.  This is to prevent
2194 	 * races with allocators, above.
2195 	 */
2196 	dvar->dtdv_hashval = DTRACE_DYNHASH_FREE;
2197 
2198 	dtrace_membar_producer();
2199 
2200 	do {
2201 		free = dcpu->dtdsc_dirty;
2202 		dvar->dtdv_next = free;
2203 	} while (dtrace_casptr(&dcpu->dtdsc_dirty, free, dvar) != free);
2204 
2205 	goto top;
2206 }
2207 
2208 /*ARGSUSED*/
2209 static void
2210 dtrace_aggregate_min(uint64_t *oval, uint64_t nval, uint64_t arg)
2211 {
2212 	if ((int64_t)nval < (int64_t)*oval)
2213 		*oval = nval;
2214 }
2215 
2216 /*ARGSUSED*/
2217 static void
2218 dtrace_aggregate_max(uint64_t *oval, uint64_t nval, uint64_t arg)
2219 {
2220 	if ((int64_t)nval > (int64_t)*oval)
2221 		*oval = nval;
2222 }
2223 
2224 static void
2225 dtrace_aggregate_quantize(uint64_t *quanta, uint64_t nval, uint64_t incr)
2226 {
2227 	int i, zero = DTRACE_QUANTIZE_ZEROBUCKET;
2228 	int64_t val = (int64_t)nval;
2229 
2230 	if (val < 0) {
2231 		for (i = 0; i < zero; i++) {
2232 			if (val <= DTRACE_QUANTIZE_BUCKETVAL(i)) {
2233 				quanta[i] += incr;
2234 				return;
2235 			}
2236 		}
2237 	} else {
2238 		for (i = zero + 1; i < DTRACE_QUANTIZE_NBUCKETS; i++) {
2239 			if (val < DTRACE_QUANTIZE_BUCKETVAL(i)) {
2240 				quanta[i - 1] += incr;
2241 				return;
2242 			}
2243 		}
2244 
2245 		quanta[DTRACE_QUANTIZE_NBUCKETS - 1] += incr;
2246 		return;
2247 	}
2248 
2249 	ASSERT(0);
2250 }
2251 
2252 static void
2253 dtrace_aggregate_lquantize(uint64_t *lquanta, uint64_t nval, uint64_t incr)
2254 {
2255 	uint64_t arg = *lquanta++;
2256 	int32_t base = DTRACE_LQUANTIZE_BASE(arg);
2257 	uint16_t step = DTRACE_LQUANTIZE_STEP(arg);
2258 	uint16_t levels = DTRACE_LQUANTIZE_LEVELS(arg);
2259 	int32_t val = (int32_t)nval, level;
2260 
2261 	ASSERT(step != 0);
2262 	ASSERT(levels != 0);
2263 
2264 	if (val < base) {
2265 		/*
2266 		 * This is an underflow.
2267 		 */
2268 		lquanta[0] += incr;
2269 		return;
2270 	}
2271 
2272 	level = (val - base) / step;
2273 
2274 	if (level < levels) {
2275 		lquanta[level + 1] += incr;
2276 		return;
2277 	}
2278 
2279 	/*
2280 	 * This is an overflow.
2281 	 */
2282 	lquanta[levels + 1] += incr;
2283 }
2284 
2285 static int
2286 dtrace_aggregate_llquantize_bucket(uint16_t factor, uint16_t low,
2287     uint16_t high, uint16_t nsteps, int64_t value)
2288 {
2289 	int64_t this = 1, last, next;
2290 	int base = 1, order;
2291 
2292 	ASSERT(factor <= nsteps);
2293 	ASSERT(nsteps % factor == 0);
2294 
2295 	for (order = 0; order < low; order++)
2296 		this *= factor;
2297 
2298 	/*
2299 	 * If our value is less than our factor taken to the power of the
2300 	 * low order of magnitude, it goes into the zeroth bucket.
2301 	 */
2302 	if (value < (last = this))
2303 		return (0);
2304 
2305 	for (this *= factor; order <= high; order++) {
2306 		int nbuckets = this > nsteps ? nsteps : this;
2307 
2308 		if ((next = this * factor) < this) {
2309 			/*
2310 			 * We should not generally get log/linear quantizations
2311 			 * with a high magnitude that allows 64-bits to
2312 			 * overflow, but we nonetheless protect against this
2313 			 * by explicitly checking for overflow, and clamping
2314 			 * our value accordingly.
2315 			 */
2316 			value = this - 1;
2317 		}
2318 
2319 		if (value < this) {
2320 			/*
2321 			 * If our value lies within this order of magnitude,
2322 			 * determine its position by taking the offset within
2323 			 * the order of magnitude, dividing by the bucket
2324 			 * width, and adding to our (accumulated) base.
2325 			 */
2326 			return (base + (value - last) / (this / nbuckets));
2327 		}
2328 
2329 		base += nbuckets - (nbuckets / factor);
2330 		last = this;
2331 		this = next;
2332 	}
2333 
2334 	/*
2335 	 * Our value is greater than or equal to our factor taken to the
2336 	 * power of one plus the high magnitude -- return the top bucket.
2337 	 */
2338 	return (base);
2339 }
2340 
2341 static void
2342 dtrace_aggregate_llquantize(uint64_t *llquanta, uint64_t nval, uint64_t incr)
2343 {
2344 	uint64_t arg = *llquanta++;
2345 	uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(arg);
2346 	uint16_t low = DTRACE_LLQUANTIZE_LOW(arg);
2347 	uint16_t high = DTRACE_LLQUANTIZE_HIGH(arg);
2348 	uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(arg);
2349 
2350 	llquanta[dtrace_aggregate_llquantize_bucket(factor,
2351 	    low, high, nsteps, nval)] += incr;
2352 }
2353 
2354 /*ARGSUSED*/
2355 static void
2356 dtrace_aggregate_avg(uint64_t *data, uint64_t nval, uint64_t arg)
2357 {
2358 	data[0]++;
2359 	data[1] += nval;
2360 }
2361 
2362 /*ARGSUSED*/
2363 static void
2364 dtrace_aggregate_stddev(uint64_t *data, uint64_t nval, uint64_t arg)
2365 {
2366 	int64_t snval = (int64_t)nval;
2367 	uint64_t tmp[2];
2368 
2369 	data[0]++;
2370 	data[1] += nval;
2371 
2372 	/*
2373 	 * What we want to say here is:
2374 	 *
2375 	 * data[2] += nval * nval;
2376 	 *
2377 	 * But given that nval is 64-bit, we could easily overflow, so
2378 	 * we do this as 128-bit arithmetic.
2379 	 */
2380 	if (snval < 0)
2381 		snval = -snval;
2382 
2383 	dtrace_multiply_128((uint64_t)snval, (uint64_t)snval, tmp);
2384 	dtrace_add_128(data + 2, tmp, data + 2);
2385 }
2386 
2387 /*ARGSUSED*/
2388 static void
2389 dtrace_aggregate_count(uint64_t *oval, uint64_t nval, uint64_t arg)
2390 {
2391 	*oval = *oval + 1;
2392 }
2393 
2394 /*ARGSUSED*/
2395 static void
2396 dtrace_aggregate_sum(uint64_t *oval, uint64_t nval, uint64_t arg)
2397 {
2398 	*oval += nval;
2399 }
2400 
2401 /*
2402  * Aggregate given the tuple in the principal data buffer, and the aggregating
2403  * action denoted by the specified dtrace_aggregation_t.  The aggregation
2404  * buffer is specified as the buf parameter.  This routine does not return
2405  * failure; if there is no space in the aggregation buffer, the data will be
2406  * dropped, and a corresponding counter incremented.
2407  */
2408 static void
2409 dtrace_aggregate(dtrace_aggregation_t *agg, dtrace_buffer_t *dbuf,
2410     intptr_t offset, dtrace_buffer_t *buf, uint64_t expr, uint64_t arg)
2411 {
2412 	dtrace_recdesc_t *rec = &agg->dtag_action.dta_rec;
2413 	uint32_t i, ndx, size, fsize;
2414 	uint32_t align = sizeof (uint64_t) - 1;
2415 	dtrace_aggbuffer_t *agb;
2416 	dtrace_aggkey_t *key;
2417 	uint32_t hashval = 0, limit, isstr;
2418 	caddr_t tomax, data, kdata;
2419 	dtrace_actkind_t action;
2420 	dtrace_action_t *act;
2421 	uintptr_t offs;
2422 
2423 	if (buf == NULL)
2424 		return;
2425 
2426 	if (!agg->dtag_hasarg) {
2427 		/*
2428 		 * Currently, only quantize() and lquantize() take additional
2429 		 * arguments, and they have the same semantics:  an increment
2430 		 * value that defaults to 1 when not present.  If additional
2431 		 * aggregating actions take arguments, the setting of the
2432 		 * default argument value will presumably have to become more
2433 		 * sophisticated...
2434 		 */
2435 		arg = 1;
2436 	}
2437 
2438 	action = agg->dtag_action.dta_kind - DTRACEACT_AGGREGATION;
2439 	size = rec->dtrd_offset - agg->dtag_base;
2440 	fsize = size + rec->dtrd_size;
2441 
2442 	ASSERT(dbuf->dtb_tomax != NULL);
2443 	data = dbuf->dtb_tomax + offset + agg->dtag_base;
2444 
2445 	if ((tomax = buf->dtb_tomax) == NULL) {
2446 		dtrace_buffer_drop(buf);
2447 		return;
2448 	}
2449 
2450 	/*
2451 	 * The metastructure is always at the bottom of the buffer.
2452 	 */
2453 	agb = (dtrace_aggbuffer_t *)(tomax + buf->dtb_size -
2454 	    sizeof (dtrace_aggbuffer_t));
2455 
2456 	if (buf->dtb_offset == 0) {
2457 		/*
2458 		 * We just kludge up approximately 1/8th of the size to be
2459 		 * buckets.  If this guess ends up being routinely
2460 		 * off-the-mark, we may need to dynamically readjust this
2461 		 * based on past performance.
2462 		 */
2463 		uintptr_t hashsize = (buf->dtb_size >> 3) / sizeof (uintptr_t);
2464 
2465 		if ((uintptr_t)agb - hashsize * sizeof (dtrace_aggkey_t *) <
2466 		    (uintptr_t)tomax || hashsize == 0) {
2467 			/*
2468 			 * We've been given a ludicrously small buffer;
2469 			 * increment our drop count and leave.
2470 			 */
2471 			dtrace_buffer_drop(buf);
2472 			return;
2473 		}
2474 
2475 		/*
2476 		 * And now, a pathetic attempt to try to get a an odd (or
2477 		 * perchance, a prime) hash size for better hash distribution.
2478 		 */
2479 		if (hashsize > (DTRACE_AGGHASHSIZE_SLEW << 3))
2480 			hashsize -= DTRACE_AGGHASHSIZE_SLEW;
2481 
2482 		agb->dtagb_hashsize = hashsize;
2483 		agb->dtagb_hash = (dtrace_aggkey_t **)((uintptr_t)agb -
2484 		    agb->dtagb_hashsize * sizeof (dtrace_aggkey_t *));
2485 		agb->dtagb_free = (uintptr_t)agb->dtagb_hash;
2486 
2487 		for (i = 0; i < agb->dtagb_hashsize; i++)
2488 			agb->dtagb_hash[i] = NULL;
2489 	}
2490 
2491 	ASSERT(agg->dtag_first != NULL);
2492 	ASSERT(agg->dtag_first->dta_intuple);
2493 
2494 	/*
2495 	 * Calculate the hash value based on the key.  Note that we _don't_
2496 	 * include the aggid in the hashing (but we will store it as part of
2497 	 * the key).  The hashing algorithm is Bob Jenkins' "One-at-a-time"
2498 	 * algorithm: a simple, quick algorithm that has no known funnels, and
2499 	 * gets good distribution in practice.  The efficacy of the hashing
2500 	 * algorithm (and a comparison with other algorithms) may be found by
2501 	 * running the ::dtrace_aggstat MDB dcmd.
2502 	 */
2503 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2504 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2505 		limit = i + act->dta_rec.dtrd_size;
2506 		ASSERT(limit <= size);
2507 		isstr = DTRACEACT_ISSTRING(act);
2508 
2509 		for (; i < limit; i++) {
2510 			hashval += data[i];
2511 			hashval += (hashval << 10);
2512 			hashval ^= (hashval >> 6);
2513 
2514 			if (isstr && data[i] == '\0')
2515 				break;
2516 		}
2517 	}
2518 
2519 	hashval += (hashval << 3);
2520 	hashval ^= (hashval >> 11);
2521 	hashval += (hashval << 15);
2522 
2523 	/*
2524 	 * Yes, the divide here is expensive -- but it's generally the least
2525 	 * of the performance issues given the amount of data that we iterate
2526 	 * over to compute hash values, compare data, etc.
2527 	 */
2528 	ndx = hashval % agb->dtagb_hashsize;
2529 
2530 	for (key = agb->dtagb_hash[ndx]; key != NULL; key = key->dtak_next) {
2531 		ASSERT((caddr_t)key >= tomax);
2532 		ASSERT((caddr_t)key < tomax + buf->dtb_size);
2533 
2534 		if (hashval != key->dtak_hashval || key->dtak_size != size)
2535 			continue;
2536 
2537 		kdata = key->dtak_data;
2538 		ASSERT(kdata >= tomax && kdata < tomax + buf->dtb_size);
2539 
2540 		for (act = agg->dtag_first; act->dta_intuple;
2541 		    act = act->dta_next) {
2542 			i = act->dta_rec.dtrd_offset - agg->dtag_base;
2543 			limit = i + act->dta_rec.dtrd_size;
2544 			ASSERT(limit <= size);
2545 			isstr = DTRACEACT_ISSTRING(act);
2546 
2547 			for (; i < limit; i++) {
2548 				if (kdata[i] != data[i])
2549 					goto next;
2550 
2551 				if (isstr && data[i] == '\0')
2552 					break;
2553 			}
2554 		}
2555 
2556 		if (action != key->dtak_action) {
2557 			/*
2558 			 * We are aggregating on the same value in the same
2559 			 * aggregation with two different aggregating actions.
2560 			 * (This should have been picked up in the compiler,
2561 			 * so we may be dealing with errant or devious DIF.)
2562 			 * This is an error condition; we indicate as much,
2563 			 * and return.
2564 			 */
2565 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
2566 			return;
2567 		}
2568 
2569 		/*
2570 		 * This is a hit:  we need to apply the aggregator to
2571 		 * the value at this key.
2572 		 */
2573 		agg->dtag_aggregate((uint64_t *)(kdata + size), expr, arg);
2574 		return;
2575 next:
2576 		continue;
2577 	}
2578 
2579 	/*
2580 	 * We didn't find it.  We need to allocate some zero-filled space,
2581 	 * link it into the hash table appropriately, and apply the aggregator
2582 	 * to the (zero-filled) value.
2583 	 */
2584 	offs = buf->dtb_offset;
2585 	while (offs & (align - 1))
2586 		offs += sizeof (uint32_t);
2587 
2588 	/*
2589 	 * If we don't have enough room to both allocate a new key _and_
2590 	 * its associated data, increment the drop count and return.
2591 	 */
2592 	if ((uintptr_t)tomax + offs + fsize >
2593 	    agb->dtagb_free - sizeof (dtrace_aggkey_t)) {
2594 		dtrace_buffer_drop(buf);
2595 		return;
2596 	}
2597 
2598 	/*CONSTCOND*/
2599 	ASSERT(!(sizeof (dtrace_aggkey_t) & (sizeof (uintptr_t) - 1)));
2600 	key = (dtrace_aggkey_t *)(agb->dtagb_free - sizeof (dtrace_aggkey_t));
2601 	agb->dtagb_free -= sizeof (dtrace_aggkey_t);
2602 
2603 	key->dtak_data = kdata = tomax + offs;
2604 	buf->dtb_offset = offs + fsize;
2605 
2606 	/*
2607 	 * Now copy the data across.
2608 	 */
2609 	*((dtrace_aggid_t *)kdata) = agg->dtag_id;
2610 
2611 	for (i = sizeof (dtrace_aggid_t); i < size; i++)
2612 		kdata[i] = data[i];
2613 
2614 	/*
2615 	 * Because strings are not zeroed out by default, we need to iterate
2616 	 * looking for actions that store strings, and we need to explicitly
2617 	 * pad these strings out with zeroes.
2618 	 */
2619 	for (act = agg->dtag_first; act->dta_intuple; act = act->dta_next) {
2620 		int nul;
2621 
2622 		if (!DTRACEACT_ISSTRING(act))
2623 			continue;
2624 
2625 		i = act->dta_rec.dtrd_offset - agg->dtag_base;
2626 		limit = i + act->dta_rec.dtrd_size;
2627 		ASSERT(limit <= size);
2628 
2629 		for (nul = 0; i < limit; i++) {
2630 			if (nul) {
2631 				kdata[i] = '\0';
2632 				continue;
2633 			}
2634 
2635 			if (data[i] != '\0')
2636 				continue;
2637 
2638 			nul = 1;
2639 		}
2640 	}
2641 
2642 	for (i = size; i < fsize; i++)
2643 		kdata[i] = 0;
2644 
2645 	key->dtak_hashval = hashval;
2646 	key->dtak_size = size;
2647 	key->dtak_action = action;
2648 	key->dtak_next = agb->dtagb_hash[ndx];
2649 	agb->dtagb_hash[ndx] = key;
2650 
2651 	/*
2652 	 * Finally, apply the aggregator.
2653 	 */
2654 	*((uint64_t *)(key->dtak_data + size)) = agg->dtag_initial;
2655 	agg->dtag_aggregate((uint64_t *)(key->dtak_data + size), expr, arg);
2656 }
2657 
2658 /*
2659  * Given consumer state, this routine finds a speculation in the INACTIVE
2660  * state and transitions it into the ACTIVE state.  If there is no speculation
2661  * in the INACTIVE state, 0 is returned.  In this case, no error counter is
2662  * incremented -- it is up to the caller to take appropriate action.
2663  */
2664 static int
2665 dtrace_speculation(dtrace_state_t *state)
2666 {
2667 	int i = 0;
2668 	dtrace_speculation_state_t current;
2669 	uint32_t *stat = &state->dts_speculations_unavail, count;
2670 
2671 	while (i < state->dts_nspeculations) {
2672 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2673 
2674 		current = spec->dtsp_state;
2675 
2676 		if (current != DTRACESPEC_INACTIVE) {
2677 			if (current == DTRACESPEC_COMMITTINGMANY ||
2678 			    current == DTRACESPEC_COMMITTING ||
2679 			    current == DTRACESPEC_DISCARDING)
2680 				stat = &state->dts_speculations_busy;
2681 			i++;
2682 			continue;
2683 		}
2684 
2685 		if (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2686 		    current, DTRACESPEC_ACTIVE) == current)
2687 			return (i + 1);
2688 	}
2689 
2690 	/*
2691 	 * We couldn't find a speculation.  If we found as much as a single
2692 	 * busy speculation buffer, we'll attribute this failure as "busy"
2693 	 * instead of "unavail".
2694 	 */
2695 	do {
2696 		count = *stat;
2697 	} while (dtrace_cas32(stat, count, count + 1) != count);
2698 
2699 	return (0);
2700 }
2701 
2702 /*
2703  * This routine commits an active speculation.  If the specified speculation
2704  * is not in a valid state to perform a commit(), this routine will silently do
2705  * nothing.  The state of the specified speculation is transitioned according
2706  * to the state transition diagram outlined in <sys/dtrace_impl.h>
2707  */
2708 static void
2709 dtrace_speculation_commit(dtrace_state_t *state, processorid_t cpu,
2710     dtrace_specid_t which)
2711 {
2712 	dtrace_speculation_t *spec;
2713 	dtrace_buffer_t *src, *dest;
2714 	uintptr_t daddr, saddr, dlimit, slimit;
2715 	dtrace_speculation_state_t current, new;
2716 	intptr_t offs;
2717 	uint64_t timestamp;
2718 
2719 	if (which == 0)
2720 		return;
2721 
2722 	if (which > state->dts_nspeculations) {
2723 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2724 		return;
2725 	}
2726 
2727 	spec = &state->dts_speculations[which - 1];
2728 	src = &spec->dtsp_buffer[cpu];
2729 	dest = &state->dts_buffer[cpu];
2730 
2731 	do {
2732 		current = spec->dtsp_state;
2733 
2734 		if (current == DTRACESPEC_COMMITTINGMANY)
2735 			break;
2736 
2737 		switch (current) {
2738 		case DTRACESPEC_INACTIVE:
2739 		case DTRACESPEC_DISCARDING:
2740 			return;
2741 
2742 		case DTRACESPEC_COMMITTING:
2743 			/*
2744 			 * This is only possible if we are (a) commit()'ing
2745 			 * without having done a prior speculate() on this CPU
2746 			 * and (b) racing with another commit() on a different
2747 			 * CPU.  There's nothing to do -- we just assert that
2748 			 * our offset is 0.
2749 			 */
2750 			ASSERT(src->dtb_offset == 0);
2751 			return;
2752 
2753 		case DTRACESPEC_ACTIVE:
2754 			new = DTRACESPEC_COMMITTING;
2755 			break;
2756 
2757 		case DTRACESPEC_ACTIVEONE:
2758 			/*
2759 			 * This speculation is active on one CPU.  If our
2760 			 * buffer offset is non-zero, we know that the one CPU
2761 			 * must be us.  Otherwise, we are committing on a
2762 			 * different CPU from the speculate(), and we must
2763 			 * rely on being asynchronously cleaned.
2764 			 */
2765 			if (src->dtb_offset != 0) {
2766 				new = DTRACESPEC_COMMITTING;
2767 				break;
2768 			}
2769 			/*FALLTHROUGH*/
2770 
2771 		case DTRACESPEC_ACTIVEMANY:
2772 			new = DTRACESPEC_COMMITTINGMANY;
2773 			break;
2774 
2775 		default:
2776 			ASSERT(0);
2777 		}
2778 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2779 	    current, new) != current);
2780 
2781 	/*
2782 	 * We have set the state to indicate that we are committing this
2783 	 * speculation.  Now reserve the necessary space in the destination
2784 	 * buffer.
2785 	 */
2786 	if ((offs = dtrace_buffer_reserve(dest, src->dtb_offset,
2787 	    sizeof (uint64_t), state, NULL)) < 0) {
2788 		dtrace_buffer_drop(dest);
2789 		goto out;
2790 	}
2791 
2792 	/*
2793 	 * We have sufficient space to copy the speculative buffer into the
2794 	 * primary buffer.  First, modify the speculative buffer, filling
2795 	 * in the timestamp of all entries with the current time.  The data
2796 	 * must have the commit() time rather than the time it was traced,
2797 	 * so that all entries in the primary buffer are in timestamp order.
2798 	 */
2799 	timestamp = dtrace_gethrtime();
2800 	saddr = (uintptr_t)src->dtb_tomax;
2801 	slimit = saddr + src->dtb_offset;
2802 	while (saddr < slimit) {
2803 		size_t size;
2804 		dtrace_rechdr_t *dtrh = (dtrace_rechdr_t *)saddr;
2805 
2806 		if (dtrh->dtrh_epid == DTRACE_EPIDNONE) {
2807 			saddr += sizeof (dtrace_epid_t);
2808 			continue;
2809 		}
2810 		ASSERT3U(dtrh->dtrh_epid, <=, state->dts_necbs);
2811 		size = state->dts_ecbs[dtrh->dtrh_epid - 1]->dte_size;
2812 
2813 		ASSERT3U(saddr + size, <=, slimit);
2814 		ASSERT3U(size, >=, sizeof (dtrace_rechdr_t));
2815 		ASSERT3U(DTRACE_RECORD_LOAD_TIMESTAMP(dtrh), ==, UINT64_MAX);
2816 
2817 		DTRACE_RECORD_STORE_TIMESTAMP(dtrh, timestamp);
2818 
2819 		saddr += size;
2820 	}
2821 
2822 	/*
2823 	 * Copy the buffer across.  (Note that this is a
2824 	 * highly subobtimal bcopy(); in the unlikely event that this becomes
2825 	 * a serious performance issue, a high-performance DTrace-specific
2826 	 * bcopy() should obviously be invented.)
2827 	 */
2828 	daddr = (uintptr_t)dest->dtb_tomax + offs;
2829 	dlimit = daddr + src->dtb_offset;
2830 	saddr = (uintptr_t)src->dtb_tomax;
2831 
2832 	/*
2833 	 * First, the aligned portion.
2834 	 */
2835 	while (dlimit - daddr >= sizeof (uint64_t)) {
2836 		*((uint64_t *)daddr) = *((uint64_t *)saddr);
2837 
2838 		daddr += sizeof (uint64_t);
2839 		saddr += sizeof (uint64_t);
2840 	}
2841 
2842 	/*
2843 	 * Now any left-over bit...
2844 	 */
2845 	while (dlimit - daddr)
2846 		*((uint8_t *)daddr++) = *((uint8_t *)saddr++);
2847 
2848 	/*
2849 	 * Finally, commit the reserved space in the destination buffer.
2850 	 */
2851 	dest->dtb_offset = offs + src->dtb_offset;
2852 
2853 out:
2854 	/*
2855 	 * If we're lucky enough to be the only active CPU on this speculation
2856 	 * buffer, we can just set the state back to DTRACESPEC_INACTIVE.
2857 	 */
2858 	if (current == DTRACESPEC_ACTIVE ||
2859 	    (current == DTRACESPEC_ACTIVEONE && new == DTRACESPEC_COMMITTING)) {
2860 		uint32_t rval = dtrace_cas32((uint32_t *)&spec->dtsp_state,
2861 		    DTRACESPEC_COMMITTING, DTRACESPEC_INACTIVE);
2862 
2863 		ASSERT(rval == DTRACESPEC_COMMITTING);
2864 	}
2865 
2866 	src->dtb_offset = 0;
2867 	src->dtb_xamot_drops += src->dtb_drops;
2868 	src->dtb_drops = 0;
2869 }
2870 
2871 /*
2872  * This routine discards an active speculation.  If the specified speculation
2873  * is not in a valid state to perform a discard(), this routine will silently
2874  * do nothing.  The state of the specified speculation is transitioned
2875  * according to the state transition diagram outlined in <sys/dtrace_impl.h>
2876  */
2877 static void
2878 dtrace_speculation_discard(dtrace_state_t *state, processorid_t cpu,
2879     dtrace_specid_t which)
2880 {
2881 	dtrace_speculation_t *spec;
2882 	dtrace_speculation_state_t current, new;
2883 	dtrace_buffer_t *buf;
2884 
2885 	if (which == 0)
2886 		return;
2887 
2888 	if (which > state->dts_nspeculations) {
2889 		cpu_core[cpu].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
2890 		return;
2891 	}
2892 
2893 	spec = &state->dts_speculations[which - 1];
2894 	buf = &spec->dtsp_buffer[cpu];
2895 
2896 	do {
2897 		current = spec->dtsp_state;
2898 
2899 		switch (current) {
2900 		case DTRACESPEC_INACTIVE:
2901 		case DTRACESPEC_COMMITTINGMANY:
2902 		case DTRACESPEC_COMMITTING:
2903 		case DTRACESPEC_DISCARDING:
2904 			return;
2905 
2906 		case DTRACESPEC_ACTIVE:
2907 		case DTRACESPEC_ACTIVEMANY:
2908 			new = DTRACESPEC_DISCARDING;
2909 			break;
2910 
2911 		case DTRACESPEC_ACTIVEONE:
2912 			if (buf->dtb_offset != 0) {
2913 				new = DTRACESPEC_INACTIVE;
2914 			} else {
2915 				new = DTRACESPEC_DISCARDING;
2916 			}
2917 			break;
2918 
2919 		default:
2920 			ASSERT(0);
2921 		}
2922 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
2923 	    current, new) != current);
2924 
2925 	buf->dtb_offset = 0;
2926 	buf->dtb_drops = 0;
2927 }
2928 
2929 /*
2930  * Note:  not called from probe context.  This function is called
2931  * asynchronously from cross call context to clean any speculations that are
2932  * in the COMMITTINGMANY or DISCARDING states.  These speculations may not be
2933  * transitioned back to the INACTIVE state until all CPUs have cleaned the
2934  * speculation.
2935  */
2936 static void
2937 dtrace_speculation_clean_here(dtrace_state_t *state)
2938 {
2939 	dtrace_icookie_t cookie;
2940 	processorid_t cpu = CPU->cpu_id;
2941 	dtrace_buffer_t *dest = &state->dts_buffer[cpu];
2942 	dtrace_specid_t i;
2943 
2944 	cookie = dtrace_interrupt_disable();
2945 
2946 	if (dest->dtb_tomax == NULL) {
2947 		dtrace_interrupt_enable(cookie);
2948 		return;
2949 	}
2950 
2951 	for (i = 0; i < state->dts_nspeculations; i++) {
2952 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2953 		dtrace_buffer_t *src = &spec->dtsp_buffer[cpu];
2954 
2955 		if (src->dtb_tomax == NULL)
2956 			continue;
2957 
2958 		if (spec->dtsp_state == DTRACESPEC_DISCARDING) {
2959 			src->dtb_offset = 0;
2960 			continue;
2961 		}
2962 
2963 		if (spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2964 			continue;
2965 
2966 		if (src->dtb_offset == 0)
2967 			continue;
2968 
2969 		dtrace_speculation_commit(state, cpu, i + 1);
2970 	}
2971 
2972 	dtrace_interrupt_enable(cookie);
2973 }
2974 
2975 /*
2976  * Note:  not called from probe context.  This function is called
2977  * asynchronously (and at a regular interval) to clean any speculations that
2978  * are in the COMMITTINGMANY or DISCARDING states.  If it discovers that there
2979  * is work to be done, it cross calls all CPUs to perform that work;
2980  * COMMITMANY and DISCARDING speculations may not be transitioned back to the
2981  * INACTIVE state until they have been cleaned by all CPUs.
2982  */
2983 static void
2984 dtrace_speculation_clean(dtrace_state_t *state)
2985 {
2986 	int work = 0, rv;
2987 	dtrace_specid_t i;
2988 
2989 	for (i = 0; i < state->dts_nspeculations; i++) {
2990 		dtrace_speculation_t *spec = &state->dts_speculations[i];
2991 
2992 		ASSERT(!spec->dtsp_cleaning);
2993 
2994 		if (spec->dtsp_state != DTRACESPEC_DISCARDING &&
2995 		    spec->dtsp_state != DTRACESPEC_COMMITTINGMANY)
2996 			continue;
2997 
2998 		work++;
2999 		spec->dtsp_cleaning = 1;
3000 	}
3001 
3002 	if (!work)
3003 		return;
3004 
3005 	dtrace_xcall(DTRACE_CPUALL,
3006 	    (dtrace_xcall_t)dtrace_speculation_clean_here, state);
3007 
3008 	/*
3009 	 * We now know that all CPUs have committed or discarded their
3010 	 * speculation buffers, as appropriate.  We can now set the state
3011 	 * to inactive.
3012 	 */
3013 	for (i = 0; i < state->dts_nspeculations; i++) {
3014 		dtrace_speculation_t *spec = &state->dts_speculations[i];
3015 		dtrace_speculation_state_t current, new;
3016 
3017 		if (!spec->dtsp_cleaning)
3018 			continue;
3019 
3020 		current = spec->dtsp_state;
3021 		ASSERT(current == DTRACESPEC_DISCARDING ||
3022 		    current == DTRACESPEC_COMMITTINGMANY);
3023 
3024 		new = DTRACESPEC_INACTIVE;
3025 
3026 		rv = dtrace_cas32((uint32_t *)&spec->dtsp_state, current, new);
3027 		ASSERT(rv == current);
3028 		spec->dtsp_cleaning = 0;
3029 	}
3030 }
3031 
3032 /*
3033  * Called as part of a speculate() to get the speculative buffer associated
3034  * with a given speculation.  Returns NULL if the specified speculation is not
3035  * in an ACTIVE state.  If the speculation is in the ACTIVEONE state -- and
3036  * the active CPU is not the specified CPU -- the speculation will be
3037  * atomically transitioned into the ACTIVEMANY state.
3038  */
3039 static dtrace_buffer_t *
3040 dtrace_speculation_buffer(dtrace_state_t *state, processorid_t cpuid,
3041     dtrace_specid_t which)
3042 {
3043 	dtrace_speculation_t *spec;
3044 	dtrace_speculation_state_t current, new;
3045 	dtrace_buffer_t *buf;
3046 
3047 	if (which == 0)
3048 		return (NULL);
3049 
3050 	if (which > state->dts_nspeculations) {
3051 		cpu_core[cpuid].cpuc_dtrace_flags |= CPU_DTRACE_ILLOP;
3052 		return (NULL);
3053 	}
3054 
3055 	spec = &state->dts_speculations[which - 1];
3056 	buf = &spec->dtsp_buffer[cpuid];
3057 
3058 	do {
3059 		current = spec->dtsp_state;
3060 
3061 		switch (current) {
3062 		case DTRACESPEC_INACTIVE:
3063 		case DTRACESPEC_COMMITTINGMANY:
3064 		case DTRACESPEC_DISCARDING:
3065 			return (NULL);
3066 
3067 		case DTRACESPEC_COMMITTING:
3068 			ASSERT(buf->dtb_offset == 0);
3069 			return (NULL);
3070 
3071 		case DTRACESPEC_ACTIVEONE:
3072 			/*
3073 			 * This speculation is currently active on one CPU.
3074 			 * Check the offset in the buffer; if it's non-zero,
3075 			 * that CPU must be us (and we leave the state alone).
3076 			 * If it's zero, assume that we're starting on a new
3077 			 * CPU -- and change the state to indicate that the
3078 			 * speculation is active on more than one CPU.
3079 			 */
3080 			if (buf->dtb_offset != 0)
3081 				return (buf);
3082 
3083 			new = DTRACESPEC_ACTIVEMANY;
3084 			break;
3085 
3086 		case DTRACESPEC_ACTIVEMANY:
3087 			return (buf);
3088 
3089 		case DTRACESPEC_ACTIVE:
3090 			new = DTRACESPEC_ACTIVEONE;
3091 			break;
3092 
3093 		default:
3094 			ASSERT(0);
3095 		}
3096 	} while (dtrace_cas32((uint32_t *)&spec->dtsp_state,
3097 	    current, new) != current);
3098 
3099 	ASSERT(new == DTRACESPEC_ACTIVEONE || new == DTRACESPEC_ACTIVEMANY);
3100 	return (buf);
3101 }
3102 
3103 /*
3104  * Return a string.  In the event that the user lacks the privilege to access
3105  * arbitrary kernel memory, we copy the string out to scratch memory so that we
3106  * don't fail access checking.
3107  *
3108  * dtrace_dif_variable() uses this routine as a helper for various
3109  * builtin values such as 'execname' and 'probefunc.'
3110  */
3111 uintptr_t
3112 dtrace_dif_varstr(uintptr_t addr, dtrace_state_t *state,
3113     dtrace_mstate_t *mstate)
3114 {
3115 	uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
3116 	uintptr_t ret;
3117 	size_t strsz;
3118 
3119 	/*
3120 	 * The easy case: this probe is allowed to read all of memory, so
3121 	 * we can just return this as a vanilla pointer.
3122 	 */
3123 	if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) != 0)
3124 		return (addr);
3125 
3126 	/*
3127 	 * This is the tougher case: we copy the string in question from
3128 	 * kernel memory into scratch memory and return it that way: this
3129 	 * ensures that we won't trip up when access checking tests the
3130 	 * BYREF return value.
3131 	 */
3132 	strsz = dtrace_strlen((char *)addr, size) + 1;
3133 
3134 	if (mstate->dtms_scratch_ptr + strsz >
3135 	    mstate->dtms_scratch_base + mstate->dtms_scratch_size) {
3136 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
3137 		return (0);
3138 	}
3139 
3140 	dtrace_strcpy((const void *)addr, (void *)mstate->dtms_scratch_ptr,
3141 	    strsz);
3142 	ret = mstate->dtms_scratch_ptr;
3143 	mstate->dtms_scratch_ptr += strsz;
3144 	return (ret);
3145 }
3146 
3147 /*
3148  * This function implements the DIF emulator's variable lookups.  The emulator
3149  * passes a reserved variable identifier and optional built-in array index.
3150  */
3151 static uint64_t
3152 dtrace_dif_variable(dtrace_mstate_t *mstate, dtrace_state_t *state, uint64_t v,
3153     uint64_t ndx)
3154 {
3155 	/*
3156 	 * If we're accessing one of the uncached arguments, we'll turn this
3157 	 * into a reference in the args array.
3158 	 */
3159 	if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9) {
3160 		ndx = v - DIF_VAR_ARG0;
3161 		v = DIF_VAR_ARGS;
3162 	}
3163 
3164 	switch (v) {
3165 	case DIF_VAR_ARGS:
3166 		if (!(mstate->dtms_access & DTRACE_ACCESS_ARGS)) {
3167 			cpu_core[CPU->cpu_id].cpuc_dtrace_flags |=
3168 			    CPU_DTRACE_KPRIV;
3169 			return (0);
3170 		}
3171 
3172 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_ARGS);
3173 		if (ndx >= sizeof (mstate->dtms_arg) /
3174 		    sizeof (mstate->dtms_arg[0])) {
3175 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3176 			dtrace_provider_t *pv;
3177 			uint64_t val;
3178 
3179 			pv = mstate->dtms_probe->dtpr_provider;
3180 			if (pv->dtpv_pops.dtps_getargval != NULL)
3181 				val = pv->dtpv_pops.dtps_getargval(pv->dtpv_arg,
3182 				    mstate->dtms_probe->dtpr_id,
3183 				    mstate->dtms_probe->dtpr_arg, ndx, aframes);
3184 			else
3185 				val = dtrace_getarg(ndx, aframes);
3186 
3187 			/*
3188 			 * This is regrettably required to keep the compiler
3189 			 * from tail-optimizing the call to dtrace_getarg().
3190 			 * The condition always evaluates to true, but the
3191 			 * compiler has no way of figuring that out a priori.
3192 			 * (None of this would be necessary if the compiler
3193 			 * could be relied upon to _always_ tail-optimize
3194 			 * the call to dtrace_getarg() -- but it can't.)
3195 			 */
3196 			if (mstate->dtms_probe != NULL)
3197 				return (val);
3198 
3199 			ASSERT(0);
3200 		}
3201 
3202 		return (mstate->dtms_arg[ndx]);
3203 
3204 	case DIF_VAR_UREGS: {
3205 		klwp_t *lwp;
3206 
3207 		if (!dtrace_priv_proc(state, mstate))
3208 			return (0);
3209 
3210 		if ((lwp = curthread->t_lwp) == NULL) {
3211 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3212 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = 0;
3213 			return (0);
3214 		}
3215 
3216 		return (dtrace_getreg(lwp->lwp_regs, ndx));
3217 	}
3218 
3219 	case DIF_VAR_VMREGS: {
3220 		uint64_t rval;
3221 
3222 		if (!dtrace_priv_kernel(state))
3223 			return (0);
3224 
3225 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3226 
3227 		rval = dtrace_getvmreg(ndx,
3228 		    &cpu_core[CPU->cpu_id].cpuc_dtrace_flags);
3229 
3230 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3231 
3232 		return (rval);
3233 	}
3234 
3235 	case DIF_VAR_CURTHREAD:
3236 		if (!dtrace_priv_proc(state, mstate))
3237 			return (0);
3238 		return ((uint64_t)(uintptr_t)curthread);
3239 
3240 	case DIF_VAR_TIMESTAMP:
3241 		if (!(mstate->dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
3242 			mstate->dtms_timestamp = dtrace_gethrtime();
3243 			mstate->dtms_present |= DTRACE_MSTATE_TIMESTAMP;
3244 		}
3245 		return (mstate->dtms_timestamp);
3246 
3247 	case DIF_VAR_VTIMESTAMP:
3248 		ASSERT(dtrace_vtime_references != 0);
3249 		return (curthread->t_dtrace_vtime);
3250 
3251 	case DIF_VAR_WALLTIMESTAMP:
3252 		if (!(mstate->dtms_present & DTRACE_MSTATE_WALLTIMESTAMP)) {
3253 			mstate->dtms_walltimestamp = dtrace_gethrestime();
3254 			mstate->dtms_present |= DTRACE_MSTATE_WALLTIMESTAMP;
3255 		}
3256 		return (mstate->dtms_walltimestamp);
3257 
3258 	case DIF_VAR_IPL:
3259 		if (!dtrace_priv_kernel(state))
3260 			return (0);
3261 		if (!(mstate->dtms_present & DTRACE_MSTATE_IPL)) {
3262 			mstate->dtms_ipl = dtrace_getipl();
3263 			mstate->dtms_present |= DTRACE_MSTATE_IPL;
3264 		}
3265 		return (mstate->dtms_ipl);
3266 
3267 	case DIF_VAR_EPID:
3268 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_EPID);
3269 		return (mstate->dtms_epid);
3270 
3271 	case DIF_VAR_ID:
3272 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3273 		return (mstate->dtms_probe->dtpr_id);
3274 
3275 	case DIF_VAR_STACKDEPTH:
3276 		if (!dtrace_priv_kernel(state))
3277 			return (0);
3278 		if (!(mstate->dtms_present & DTRACE_MSTATE_STACKDEPTH)) {
3279 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3280 
3281 			mstate->dtms_stackdepth = dtrace_getstackdepth(aframes);
3282 			mstate->dtms_present |= DTRACE_MSTATE_STACKDEPTH;
3283 		}
3284 		return (mstate->dtms_stackdepth);
3285 
3286 	case DIF_VAR_USTACKDEPTH:
3287 		if (!dtrace_priv_proc(state, mstate))
3288 			return (0);
3289 		if (!(mstate->dtms_present & DTRACE_MSTATE_USTACKDEPTH)) {
3290 			/*
3291 			 * See comment in DIF_VAR_PID.
3292 			 */
3293 			if (DTRACE_ANCHORED(mstate->dtms_probe) &&
3294 			    CPU_ON_INTR(CPU)) {
3295 				mstate->dtms_ustackdepth = 0;
3296 			} else {
3297 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3298 				mstate->dtms_ustackdepth =
3299 				    dtrace_getustackdepth();
3300 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3301 			}
3302 			mstate->dtms_present |= DTRACE_MSTATE_USTACKDEPTH;
3303 		}
3304 		return (mstate->dtms_ustackdepth);
3305 
3306 	case DIF_VAR_CALLER:
3307 		if (!dtrace_priv_kernel(state))
3308 			return (0);
3309 		if (!(mstate->dtms_present & DTRACE_MSTATE_CALLER)) {
3310 			int aframes = mstate->dtms_probe->dtpr_aframes + 2;
3311 
3312 			if (!DTRACE_ANCHORED(mstate->dtms_probe)) {
3313 				/*
3314 				 * If this is an unanchored probe, we are
3315 				 * required to go through the slow path:
3316 				 * dtrace_caller() only guarantees correct
3317 				 * results for anchored probes.
3318 				 */
3319 				pc_t caller[2];
3320 
3321 				dtrace_getpcstack(caller, 2, aframes,
3322 				    (uint32_t *)(uintptr_t)mstate->dtms_arg[0]);
3323 				mstate->dtms_caller = caller[1];
3324 			} else if ((mstate->dtms_caller =
3325 			    dtrace_caller(aframes)) == -1) {
3326 				/*
3327 				 * We have failed to do this the quick way;
3328 				 * we must resort to the slower approach of
3329 				 * calling dtrace_getpcstack().
3330 				 */
3331 				pc_t caller;
3332 
3333 				dtrace_getpcstack(&caller, 1, aframes, NULL);
3334 				mstate->dtms_caller = caller;
3335 			}
3336 
3337 			mstate->dtms_present |= DTRACE_MSTATE_CALLER;
3338 		}
3339 		return (mstate->dtms_caller);
3340 
3341 	case DIF_VAR_UCALLER:
3342 		if (!dtrace_priv_proc(state, mstate))
3343 			return (0);
3344 
3345 		if (!(mstate->dtms_present & DTRACE_MSTATE_UCALLER)) {
3346 			uint64_t ustack[3];
3347 
3348 			/*
3349 			 * dtrace_getupcstack() fills in the first uint64_t
3350 			 * with the current PID.  The second uint64_t will
3351 			 * be the program counter at user-level.  The third
3352 			 * uint64_t will contain the caller, which is what
3353 			 * we're after.
3354 			 */
3355 			ustack[2] = 0;
3356 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
3357 			dtrace_getupcstack(ustack, 3);
3358 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
3359 			mstate->dtms_ucaller = ustack[2];
3360 			mstate->dtms_present |= DTRACE_MSTATE_UCALLER;
3361 		}
3362 
3363 		return (mstate->dtms_ucaller);
3364 
3365 	case DIF_VAR_PROBEPROV:
3366 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3367 		return (dtrace_dif_varstr(
3368 		    (uintptr_t)mstate->dtms_probe->dtpr_provider->dtpv_name,
3369 		    state, mstate));
3370 
3371 	case DIF_VAR_PROBEMOD:
3372 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3373 		return (dtrace_dif_varstr(
3374 		    (uintptr_t)mstate->dtms_probe->dtpr_mod,
3375 		    state, mstate));
3376 
3377 	case DIF_VAR_PROBEFUNC:
3378 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3379 		return (dtrace_dif_varstr(
3380 		    (uintptr_t)mstate->dtms_probe->dtpr_func,
3381 		    state, mstate));
3382 
3383 	case DIF_VAR_PROBENAME:
3384 		ASSERT(mstate->dtms_present & DTRACE_MSTATE_PROBE);
3385 		return (dtrace_dif_varstr(
3386 		    (uintptr_t)mstate->dtms_probe->dtpr_name,
3387 		    state, mstate));
3388 
3389 	case DIF_VAR_PID:
3390 		if (!dtrace_priv_proc(state, mstate))
3391 			return (0);
3392 
3393 		/*
3394 		 * Note that we are assuming that an unanchored probe is
3395 		 * always due to a high-level interrupt.  (And we're assuming
3396 		 * that there is only a single high level interrupt.)
3397 		 */
3398 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3399 			return (pid0.pid_id);
3400 
3401 		/*
3402 		 * It is always safe to dereference one's own t_procp pointer:
3403 		 * it always points to a valid, allocated proc structure.
3404 		 * Further, it is always safe to dereference the p_pidp member
3405 		 * of one's own proc structure.  (These are truisms becuase
3406 		 * threads and processes don't clean up their own state --
3407 		 * they leave that task to whomever reaps them.)
3408 		 */
3409 		return ((uint64_t)curthread->t_procp->p_pidp->pid_id);
3410 
3411 	case DIF_VAR_PPID:
3412 		if (!dtrace_priv_proc(state, mstate))
3413 			return (0);
3414 
3415 		/*
3416 		 * See comment in DIF_VAR_PID.
3417 		 */
3418 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3419 			return (pid0.pid_id);
3420 
3421 		/*
3422 		 * It is always safe to dereference one's own t_procp pointer:
3423 		 * it always points to a valid, allocated proc structure.
3424 		 * (This is true because threads don't clean up their own
3425 		 * state -- they leave that task to whomever reaps them.)
3426 		 */
3427 		return ((uint64_t)curthread->t_procp->p_ppid);
3428 
3429 	case DIF_VAR_TID:
3430 		/*
3431 		 * See comment in DIF_VAR_PID.
3432 		 */
3433 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3434 			return (0);
3435 
3436 		return ((uint64_t)curthread->t_tid);
3437 
3438 	case DIF_VAR_EXECNAME:
3439 		if (!dtrace_priv_proc(state, mstate))
3440 			return (0);
3441 
3442 		/*
3443 		 * See comment in DIF_VAR_PID.
3444 		 */
3445 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3446 			return ((uint64_t)(uintptr_t)p0.p_user.u_comm);
3447 
3448 		/*
3449 		 * It is always safe to dereference one's own t_procp pointer:
3450 		 * it always points to a valid, allocated proc structure.
3451 		 * (This is true because threads don't clean up their own
3452 		 * state -- they leave that task to whomever reaps them.)
3453 		 */
3454 		return (dtrace_dif_varstr(
3455 		    (uintptr_t)curthread->t_procp->p_user.u_comm,
3456 		    state, mstate));
3457 
3458 	case DIF_VAR_ZONENAME:
3459 		if (!dtrace_priv_proc(state, mstate))
3460 			return (0);
3461 
3462 		/*
3463 		 * See comment in DIF_VAR_PID.
3464 		 */
3465 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3466 			return ((uint64_t)(uintptr_t)p0.p_zone->zone_name);
3467 
3468 		/*
3469 		 * It is always safe to dereference one's own t_procp pointer:
3470 		 * it always points to a valid, allocated proc structure.
3471 		 * (This is true because threads don't clean up their own
3472 		 * state -- they leave that task to whomever reaps them.)
3473 		 */
3474 		return (dtrace_dif_varstr(
3475 		    (uintptr_t)curthread->t_procp->p_zone->zone_name,
3476 		    state, mstate));
3477 
3478 	case DIF_VAR_UID:
3479 		if (!dtrace_priv_proc(state, mstate))
3480 			return (0);
3481 
3482 		/*
3483 		 * See comment in DIF_VAR_PID.
3484 		 */
3485 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3486 			return ((uint64_t)p0.p_cred->cr_uid);
3487 
3488 		/*
3489 		 * It is always safe to dereference one's own t_procp pointer:
3490 		 * it always points to a valid, allocated proc structure.
3491 		 * (This is true because threads don't clean up their own
3492 		 * state -- they leave that task to whomever reaps them.)
3493 		 *
3494 		 * Additionally, it is safe to dereference one's own process
3495 		 * credential, since this is never NULL after process birth.
3496 		 */
3497 		return ((uint64_t)curthread->t_procp->p_cred->cr_uid);
3498 
3499 	case DIF_VAR_GID:
3500 		if (!dtrace_priv_proc(state, mstate))
3501 			return (0);
3502 
3503 		/*
3504 		 * See comment in DIF_VAR_PID.
3505 		 */
3506 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3507 			return ((uint64_t)p0.p_cred->cr_gid);
3508 
3509 		/*
3510 		 * It is always safe to dereference one's own t_procp pointer:
3511 		 * it always points to a valid, allocated proc structure.
3512 		 * (This is true because threads don't clean up their own
3513 		 * state -- they leave that task to whomever reaps them.)
3514 		 *
3515 		 * Additionally, it is safe to dereference one's own process
3516 		 * credential, since this is never NULL after process birth.
3517 		 */
3518 		return ((uint64_t)curthread->t_procp->p_cred->cr_gid);
3519 
3520 	case DIF_VAR_ERRNO: {
3521 		klwp_t *lwp;
3522 		if (!dtrace_priv_proc(state, mstate))
3523 			return (0);
3524 
3525 		/*
3526 		 * See comment in DIF_VAR_PID.
3527 		 */
3528 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3529 			return (0);
3530 
3531 		/*
3532 		 * It is always safe to dereference one's own t_lwp pointer in
3533 		 * the event that this pointer is non-NULL.  (This is true
3534 		 * because threads and lwps don't clean up their own state --
3535 		 * they leave that task to whomever reaps them.)
3536 		 */
3537 		if ((lwp = curthread->t_lwp) == NULL)
3538 			return (0);
3539 
3540 		return ((uint64_t)lwp->lwp_errno);
3541 	}
3542 
3543 	case DIF_VAR_THREADNAME:
3544 		/*
3545 		 * See comment in DIF_VAR_PID.
3546 		 */
3547 		if (DTRACE_ANCHORED(mstate->dtms_probe) && CPU_ON_INTR(CPU))
3548 			return (0);
3549 
3550 		if (curthread->t_name == NULL)
3551 			return (0);
3552 
3553 		/*
3554 		 * Once set, ->t_name itself is never changed: any updates are
3555 		 * made to the same buffer that we are pointing out.  So we are
3556 		 * safe to dereference it here.
3557 		 */
3558 		return (dtrace_dif_varstr((uintptr_t)curthread->t_name,
3559 		    state, mstate));
3560 
3561 	default:
3562 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3563 		return (0);
3564 	}
3565 }
3566 
3567 static void
3568 dtrace_dif_variable_write(dtrace_mstate_t *mstate, dtrace_state_t *state,
3569     uint64_t v, uint64_t ndx, uint64_t data)
3570 {
3571 	switch (v) {
3572 	case DIF_VAR_UREGS: {
3573 		klwp_t *lwp;
3574 
3575 		if (dtrace_destructive_disallow ||
3576 		    !dtrace_priv_proc_control(state, mstate)) {
3577 			return;
3578 		}
3579 
3580 		if ((lwp = curthread->t_lwp) == NULL) {
3581 			DTRACE_CPUFLAG_SET(CPU_DTRACE_BADADDR);
3582 			cpu_core[CPU->cpu_id].cpuc_dtrace_illval = 0;
3583 			return;
3584 		}
3585 
3586 		dtrace_setreg(lwp->lwp_regs, ndx, data);
3587 		return;
3588 	}
3589 
3590 	default:
3591 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
3592 		return;
3593 	}
3594 }
3595 
3596 typedef enum dtrace_json_state {
3597 	DTRACE_JSON_REST = 1,
3598 	DTRACE_JSON_OBJECT,
3599 	DTRACE_JSON_STRING,
3600 	DTRACE_JSON_STRING_ESCAPE,
3601 	DTRACE_JSON_STRING_ESCAPE_UNICODE,
3602 	DTRACE_JSON_COLON,
3603 	DTRACE_JSON_COMMA,
3604 	DTRACE_JSON_VALUE,
3605 	DTRACE_JSON_IDENTIFIER,
3606 	DTRACE_JSON_NUMBER,
3607 	DTRACE_JSON_NUMBER_FRAC,
3608 	DTRACE_JSON_NUMBER_EXP,
3609 	DTRACE_JSON_COLLECT_OBJECT
3610 } dtrace_json_state_t;
3611 
3612 /*
3613  * This function possesses just enough knowledge about JSON to extract a single
3614  * value from a JSON string and store it in the scratch buffer.  It is able
3615  * to extract nested object values, and members of arrays by index.
3616  *
3617  * elemlist is a list of JSON keys, stored as packed NUL-terminated strings, to
3618  * be looked up as we descend into the object tree.  e.g.
3619  *
3620  *    foo[0].bar.baz[32] --> "foo" NUL "0" NUL "bar" NUL "baz" NUL "32" NUL
3621  *       with nelems = 5.
3622  *
3623  * The run time of this function must be bounded above by strsize to limit the
3624  * amount of work done in probe context.  As such, it is implemented as a
3625  * simple state machine, reading one character at a time using safe loads
3626  * until we find the requested element, hit a parsing error or run off the
3627  * end of the object or string.
3628  *
3629  * As there is no way for a subroutine to return an error without interrupting
3630  * clause execution, we simply return NULL in the event of a missing key or any
3631  * other error condition.  Each NULL return in this function is commented with
3632  * the error condition it represents -- parsing or otherwise.
3633  *
3634  * The set of states for the state machine closely matches the JSON
3635  * specification (http://json.org/).  Briefly:
3636  *
3637  *   DTRACE_JSON_REST:
3638  *     Skip whitespace until we find either a top-level Object, moving
3639  *     to DTRACE_JSON_OBJECT; or an Array, moving to DTRACE_JSON_VALUE.
3640  *
3641  *   DTRACE_JSON_OBJECT:
3642  *     Locate the next key String in an Object.  Sets a flag to denote
3643  *     the next String as a key string and moves to DTRACE_JSON_STRING.
3644  *
3645  *   DTRACE_JSON_COLON:
3646  *     Skip whitespace until we find the colon that separates key Strings
3647  *     from their values.  Once found, move to DTRACE_JSON_VALUE.
3648  *
3649  *   DTRACE_JSON_VALUE:
3650  *     Detects the type of the next value (String, Number, Identifier, Object
3651  *     or Array) and routes to the states that process that type.  Here we also
3652  *     deal with the element selector list if we are requested to traverse down
3653  *     into the object tree.
3654  *
3655  *   DTRACE_JSON_COMMA:
3656  *     Skip whitespace until we find the comma that separates key-value pairs
3657  *     in Objects (returning to DTRACE_JSON_OBJECT) or values in Arrays
3658  *     (similarly DTRACE_JSON_VALUE).  All following literal value processing
3659  *     states return to this state at the end of their value, unless otherwise
3660  *     noted.
3661  *
3662  *   DTRACE_JSON_NUMBER, DTRACE_JSON_NUMBER_FRAC, DTRACE_JSON_NUMBER_EXP:
3663  *     Processes a Number literal from the JSON, including any exponent
3664  *     component that may be present.  Numbers are returned as strings, which
3665  *     may be passed to strtoll() if an integer is required.
3666  *
3667  *   DTRACE_JSON_IDENTIFIER:
3668  *     Processes a "true", "false" or "null" literal in the JSON.
3669  *
3670  *   DTRACE_JSON_STRING, DTRACE_JSON_STRING_ESCAPE,
3671  *   DTRACE_JSON_STRING_ESCAPE_UNICODE:
3672  *     Processes a String literal from the JSON, whether the String denotes
3673  *     a key, a value or part of a larger Object.  Handles all escape sequences
3674  *     present in the specification, including four-digit unicode characters,
3675  *     but merely includes the escape sequence without converting it to the
3676  *     actual escaped character.  If the String is flagged as a key, we
3677  *     move to DTRACE_JSON_COLON rather than DTRACE_JSON_COMMA.
3678  *
3679  *   DTRACE_JSON_COLLECT_OBJECT:
3680  *     This state collects an entire Object (or Array), correctly handling
3681  *     embedded strings.  If the full element selector list matches this nested
3682  *     object, we return the Object in full as a string.  If not, we use this
3683  *     state to skip to the next value at this level and continue processing.
3684  *
3685  * NOTE: This function uses various macros from strtolctype.h to manipulate
3686  * digit values, etc -- these have all been checked to ensure they make
3687  * no additional function calls.
3688  */
3689 static char *
3690 dtrace_json(uint64_t size, uintptr_t json, char *elemlist, int nelems,
3691     char *dest)
3692 {
3693 	dtrace_json_state_t state = DTRACE_JSON_REST;
3694 	int64_t array_elem = INT64_MIN;
3695 	int64_t array_pos = 0;
3696 	uint8_t escape_unicount = 0;
3697 	boolean_t string_is_key = B_FALSE;
3698 	boolean_t collect_object = B_FALSE;
3699 	boolean_t found_key = B_FALSE;
3700 	boolean_t in_array = B_FALSE;
3701 	uint32_t braces = 0, brackets = 0;
3702 	char *elem = elemlist;
3703 	char *dd = dest;
3704 	uintptr_t cur;
3705 
3706 	for (cur = json; cur < json + size; cur++) {
3707 		char cc = dtrace_load8(cur);
3708 		if (cc == '\0')
3709 			return (NULL);
3710 
3711 		switch (state) {
3712 		case DTRACE_JSON_REST:
3713 			if (isspace(cc))
3714 				break;
3715 
3716 			if (cc == '{') {
3717 				state = DTRACE_JSON_OBJECT;
3718 				break;
3719 			}
3720 
3721 			if (cc == '[') {
3722 				in_array = B_TRUE;
3723 				array_pos = 0;
3724 				array_elem = dtrace_strtoll(elem, 10, size);
3725 				found_key = array_elem == 0 ? B_TRUE : B_FALSE;
3726 				state = DTRACE_JSON_VALUE;
3727 				break;
3728 			}
3729 
3730 			/*
3731 			 * ERROR: expected to find a top-level object or array.
3732 			 */
3733 			return (NULL);
3734 		case DTRACE_JSON_OBJECT:
3735 			if (isspace(cc))
3736 				break;
3737 
3738 			if (cc == '"') {
3739 				state = DTRACE_JSON_STRING;
3740 				string_is_key = B_TRUE;
3741 				break;
3742 			}
3743 
3744 			/*
3745 			 * ERROR: either the object did not start with a key
3746 			 * string, or we've run off the end of the object
3747 			 * without finding the requested key.
3748 			 */
3749 			return (NULL);
3750 		case DTRACE_JSON_STRING:
3751 			if (cc == '\\') {
3752 				*dd++ = '\\';
3753 				state = DTRACE_JSON_STRING_ESCAPE;
3754 				break;
3755 			}
3756 
3757 			if (cc == '"') {
3758 				if (collect_object) {
3759 					/*
3760 					 * We don't reset the dest here, as
3761 					 * the string is part of a larger
3762 					 * object being collected.
3763 					 */
3764 					*dd++ = cc;
3765 					collect_object = B_FALSE;
3766 					state = DTRACE_JSON_COLLECT_OBJECT;
3767 					break;
3768 				}
3769 				*dd = '\0';
3770 				dd = dest; /* reset string buffer */
3771 				if (string_is_key) {
3772 					if (dtrace_strncmp(dest, elem,
3773 					    size) == 0)
3774 						found_key = B_TRUE;
3775 				} else if (found_key) {
3776 					if (nelems > 1) {
3777 						/*
3778 						 * We expected an object, not
3779 						 * this string.
3780 						 */
3781 						return (NULL);
3782 					}
3783 					return (dest);
3784 				}
3785 				state = string_is_key ? DTRACE_JSON_COLON :
3786 				    DTRACE_JSON_COMMA;
3787 				string_is_key = B_FALSE;
3788 				break;
3789 			}
3790 
3791 			*dd++ = cc;
3792 			break;
3793 		case DTRACE_JSON_STRING_ESCAPE:
3794 			*dd++ = cc;
3795 			if (cc == 'u') {
3796 				escape_unicount = 0;
3797 				state = DTRACE_JSON_STRING_ESCAPE_UNICODE;
3798 			} else {
3799 				state = DTRACE_JSON_STRING;
3800 			}
3801 			break;
3802 		case DTRACE_JSON_STRING_ESCAPE_UNICODE:
3803 			if (!isxdigit(cc)) {
3804 				/*
3805 				 * ERROR: invalid unicode escape, expected
3806 				 * four valid hexidecimal digits.
3807 				 */
3808 				return (NULL);
3809 			}
3810 
3811 			*dd++ = cc;
3812 			if (++escape_unicount == 4)
3813 				state = DTRACE_JSON_STRING;
3814 			break;
3815 		case DTRACE_JSON_COLON:
3816 			if (isspace(cc))
3817 				break;
3818 
3819 			if (cc == ':') {
3820 				state = DTRACE_JSON_VALUE;
3821 				break;
3822 			}
3823 
3824 			/*
3825 			 * ERROR: expected a colon.
3826 			 */
3827 			return (NULL);
3828 		case DTRACE_JSON_COMMA:
3829 			if (isspace(cc))
3830 				break;
3831 
3832 			if (cc == ',') {
3833 				if (in_array) {
3834 					state = DTRACE_JSON_VALUE;
3835 					if (++array_pos == array_elem)
3836 						found_key = B_TRUE;
3837 				} else {
3838 					state = DTRACE_JSON_OBJECT;
3839 				}
3840 				break;
3841 			}
3842 
3843 			/*
3844 			 * ERROR: either we hit an unexpected character, or
3845 			 * we reached the end of the object or array without
3846 			 * finding the requested key.
3847 			 */
3848 			return (NULL);
3849 		case DTRACE_JSON_IDENTIFIER:
3850 			if (islower(cc)) {
3851 				*dd++ = cc;
3852 				break;
3853 			}
3854 
3855 			*dd = '\0';
3856 			dd = dest; /* reset string buffer */
3857 
3858 			if (dtrace_strncmp(dest, "true", 5) == 0 ||
3859 			    dtrace_strncmp(dest, "false", 6) == 0 ||
3860 			    dtrace_strncmp(dest, "null", 5) == 0) {
3861 				if (found_key) {
3862 					if (nelems > 1) {
3863 						/*
3864 						 * ERROR: We expected an object,
3865 						 * not this identifier.
3866 						 */
3867 						return (NULL);
3868 					}
3869 					return (dest);
3870 				} else {
3871 					cur--;
3872 					state = DTRACE_JSON_COMMA;
3873 					break;
3874 				}
3875 			}
3876 
3877 			/*
3878 			 * ERROR: we did not recognise the identifier as one
3879 			 * of those in the JSON specification.
3880 			 */
3881 			return (NULL);
3882 		case DTRACE_JSON_NUMBER:
3883 			if (cc == '.') {
3884 				*dd++ = cc;
3885 				state = DTRACE_JSON_NUMBER_FRAC;
3886 				break;
3887 			}
3888 
3889 			if (cc == 'x' || cc == 'X') {
3890 				/*
3891 				 * ERROR: specification explicitly excludes
3892 				 * hexidecimal or octal numbers.
3893 				 */
3894 				return (NULL);
3895 			}
3896 
3897 			/* FALLTHRU */
3898 		case DTRACE_JSON_NUMBER_FRAC:
3899 			if (cc == 'e' || cc == 'E') {
3900 				*dd++ = cc;
3901 				state = DTRACE_JSON_NUMBER_EXP;
3902 				break;
3903 			}
3904 
3905 			if (cc == '+' || cc == '-') {
3906 				/*
3907 				 * ERROR: expect sign as part of exponent only.
3908 				 */
3909 				return (NULL);
3910 			}
3911 			/* FALLTHRU */
3912 		case DTRACE_JSON_NUMBER_EXP:
3913 			if (isdigit(cc) || cc == '+' || cc == '-') {
3914 				*dd++ = cc;
3915 				break;
3916 			}
3917 
3918 			*dd = '\0';
3919 			dd = dest; /* reset string buffer */
3920 			if (found_key) {
3921 				if (nelems > 1) {
3922 					/*
3923 					 * ERROR: We expected an object, not
3924 					 * this number.
3925 					 */
3926 					return (NULL);
3927 				}
3928 				return (dest);
3929 			}
3930 
3931 			cur--;
3932 			state = DTRACE_JSON_COMMA;
3933 			break;
3934 		case DTRACE_JSON_VALUE:
3935 			if (isspace(cc))
3936 				break;
3937 
3938 			if (cc == '{' || cc == '[') {
3939 				if (nelems > 1 && found_key) {
3940 					in_array = cc == '[' ? B_TRUE : B_FALSE;
3941 					/*
3942 					 * If our element selector directs us
3943 					 * to descend into this nested object,
3944 					 * then move to the next selector
3945 					 * element in the list and restart the
3946 					 * state machine.
3947 					 */
3948 					while (*elem != '\0')
3949 						elem++;
3950 					elem++; /* skip the inter-element NUL */
3951 					nelems--;
3952 					dd = dest;
3953 					if (in_array) {
3954 						state = DTRACE_JSON_VALUE;
3955 						array_pos = 0;
3956 						array_elem = dtrace_strtoll(
3957 						    elem, 10, size);
3958 						found_key = array_elem == 0 ?
3959 						    B_TRUE : B_FALSE;
3960 					} else {
3961 						found_key = B_FALSE;
3962 						state = DTRACE_JSON_OBJECT;
3963 					}
3964 					break;
3965 				}
3966 
3967 				/*
3968 				 * Otherwise, we wish to either skip this
3969 				 * nested object or return it in full.
3970 				 */
3971 				if (cc == '[')
3972 					brackets = 1;
3973 				else
3974 					braces = 1;
3975 				*dd++ = cc;
3976 				state = DTRACE_JSON_COLLECT_OBJECT;
3977 				break;
3978 			}
3979 
3980 			if (cc == '"') {
3981 				state = DTRACE_JSON_STRING;
3982 				break;
3983 			}
3984 
3985 			if (islower(cc)) {
3986 				/*
3987 				 * Here we deal with true, false and null.
3988 				 */
3989 				*dd++ = cc;
3990 				state = DTRACE_JSON_IDENTIFIER;
3991 				break;
3992 			}
3993 
3994 			if (cc == '-' || isdigit(cc)) {
3995 				*dd++ = cc;
3996 				state = DTRACE_JSON_NUMBER;
3997 				break;
3998 			}
3999 
4000 			/*
4001 			 * ERROR: unexpected character at start of value.
4002 			 */
4003 			return (NULL);
4004 		case DTRACE_JSON_COLLECT_OBJECT:
4005 			if (cc == '\0')
4006 				/*
4007 				 * ERROR: unexpected end of input.
4008 				 */
4009 				return (NULL);
4010 
4011 			*dd++ = cc;
4012 			if (cc == '"') {
4013 				collect_object = B_TRUE;
4014 				state = DTRACE_JSON_STRING;
4015 				break;
4016 			}
4017 
4018 			if (cc == ']') {
4019 				if (brackets-- == 0) {
4020 					/*
4021 					 * ERROR: unbalanced brackets.
4022 					 */
4023 					return (NULL);
4024 				}
4025 			} else if (cc == '}') {
4026 				if (braces-- == 0) {
4027 					/*
4028 					 * ERROR: unbalanced braces.
4029 					 */
4030 					return (NULL);
4031 				}
4032 			} else if (cc == '{') {
4033 				braces++;
4034 			} else if (cc == '[') {
4035 				brackets++;
4036 			}
4037 
4038 			if (brackets == 0 && braces == 0) {
4039 				if (found_key) {
4040 					*dd = '\0';
4041 					return (dest);
4042 				}
4043 				dd = dest; /* reset string buffer */
4044 				state = DTRACE_JSON_COMMA;
4045 			}
4046 			break;
4047 		}
4048 	}
4049 	return (NULL);
4050 }
4051 
4052 /*
4053  * Emulate the execution of DTrace ID subroutines invoked by the call opcode.
4054  * Notice that we don't bother validating the proper number of arguments or
4055  * their types in the tuple stack.  This isn't needed because all argument
4056  * interpretation is safe because of our load safety -- the worst that can
4057  * happen is that a bogus program can obtain bogus results.
4058  */
4059 static void
4060 dtrace_dif_subr(uint_t subr, uint_t rd, uint64_t *regs,
4061     dtrace_key_t *tupregs, int nargs,
4062     dtrace_mstate_t *mstate, dtrace_state_t *state)
4063 {
4064 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
4065 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
4066 	dtrace_vstate_t *vstate = &state->dts_vstate;
4067 
4068 	union {
4069 		mutex_impl_t mi;
4070 		uint64_t mx;
4071 	} m;
4072 
4073 	union {
4074 		krwlock_t ri;
4075 		uintptr_t rw;
4076 	} r;
4077 
4078 	switch (subr) {
4079 	case DIF_SUBR_RAND:
4080 		regs[rd] = (dtrace_gethrtime() * 2416 + 374441) % 1771875;
4081 		break;
4082 
4083 	case DIF_SUBR_MUTEX_OWNED:
4084 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4085 		    mstate, vstate)) {
4086 			regs[rd] = 0;
4087 			break;
4088 		}
4089 
4090 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4091 		if (MUTEX_TYPE_ADAPTIVE(&m.mi))
4092 			regs[rd] = MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER;
4093 		else
4094 			regs[rd] = LOCK_HELD(&m.mi.m_spin.m_spinlock);
4095 		break;
4096 
4097 	case DIF_SUBR_MUTEX_OWNER:
4098 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4099 		    mstate, vstate)) {
4100 			regs[rd] = 0;
4101 			break;
4102 		}
4103 
4104 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4105 		if (MUTEX_TYPE_ADAPTIVE(&m.mi) &&
4106 		    MUTEX_OWNER(&m.mi) != MUTEX_NO_OWNER)
4107 			regs[rd] = (uintptr_t)MUTEX_OWNER(&m.mi);
4108 		else
4109 			regs[rd] = 0;
4110 		break;
4111 
4112 	case DIF_SUBR_MUTEX_TYPE_ADAPTIVE:
4113 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4114 		    mstate, vstate)) {
4115 			regs[rd] = 0;
4116 			break;
4117 		}
4118 
4119 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4120 		regs[rd] = MUTEX_TYPE_ADAPTIVE(&m.mi);
4121 		break;
4122 
4123 	case DIF_SUBR_MUTEX_TYPE_SPIN:
4124 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (kmutex_t),
4125 		    mstate, vstate)) {
4126 			regs[rd] = 0;
4127 			break;
4128 		}
4129 
4130 		m.mx = dtrace_load64(tupregs[0].dttk_value);
4131 		regs[rd] = MUTEX_TYPE_SPIN(&m.mi);
4132 		break;
4133 
4134 	case DIF_SUBR_RW_READ_HELD: {
4135 		uintptr_t tmp;
4136 
4137 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (uintptr_t),
4138 		    mstate, vstate)) {
4139 			regs[rd] = 0;
4140 			break;
4141 		}
4142 
4143 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4144 		regs[rd] = _RW_READ_HELD(&r.ri, tmp);
4145 		break;
4146 	}
4147 
4148 	case DIF_SUBR_RW_WRITE_HELD:
4149 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4150 		    mstate, vstate)) {
4151 			regs[rd] = 0;
4152 			break;
4153 		}
4154 
4155 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4156 		regs[rd] = _RW_WRITE_HELD(&r.ri);
4157 		break;
4158 
4159 	case DIF_SUBR_RW_ISWRITER:
4160 		if (!dtrace_canload(tupregs[0].dttk_value, sizeof (krwlock_t),
4161 		    mstate, vstate)) {
4162 			regs[rd] = 0;
4163 			break;
4164 		}
4165 
4166 		r.rw = dtrace_loadptr(tupregs[0].dttk_value);
4167 		regs[rd] = _RW_ISWRITER(&r.ri);
4168 		break;
4169 
4170 	case DIF_SUBR_BCOPY: {
4171 		/*
4172 		 * We need to be sure that the destination is in the scratch
4173 		 * region -- no other region is allowed.
4174 		 */
4175 		uintptr_t src = tupregs[0].dttk_value;
4176 		uintptr_t dest = tupregs[1].dttk_value;
4177 		size_t size = tupregs[2].dttk_value;
4178 
4179 		if (!dtrace_inscratch(dest, size, mstate)) {
4180 			*flags |= CPU_DTRACE_BADADDR;
4181 			*illval = regs[rd];
4182 			break;
4183 		}
4184 
4185 		if (!dtrace_canload(src, size, mstate, vstate)) {
4186 			regs[rd] = 0;
4187 			break;
4188 		}
4189 
4190 		dtrace_bcopy((void *)src, (void *)dest, size);
4191 		break;
4192 	}
4193 
4194 	case DIF_SUBR_ALLOCA:
4195 	case DIF_SUBR_COPYIN: {
4196 		uintptr_t dest = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
4197 		uint64_t size =
4198 		    tupregs[subr == DIF_SUBR_ALLOCA ? 0 : 1].dttk_value;
4199 		size_t scratch_size = (dest - mstate->dtms_scratch_ptr) + size;
4200 
4201 		/*
4202 		 * This action doesn't require any credential checks since
4203 		 * probes will not activate in user contexts to which the
4204 		 * enabling user does not have permissions.
4205 		 */
4206 
4207 		/*
4208 		 * Rounding up the user allocation size could have overflowed
4209 		 * a large, bogus allocation (like -1ULL) to 0.
4210 		 */
4211 		if (scratch_size < size ||
4212 		    !DTRACE_INSCRATCH(mstate, scratch_size)) {
4213 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4214 			regs[rd] = 0;
4215 			break;
4216 		}
4217 
4218 		if (subr == DIF_SUBR_COPYIN) {
4219 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4220 			dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4221 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4222 		}
4223 
4224 		mstate->dtms_scratch_ptr += scratch_size;
4225 		regs[rd] = dest;
4226 		break;
4227 	}
4228 
4229 	case DIF_SUBR_COPYINTO: {
4230 		uint64_t size = tupregs[1].dttk_value;
4231 		uintptr_t dest = tupregs[2].dttk_value;
4232 
4233 		/*
4234 		 * This action doesn't require any credential checks since
4235 		 * probes will not activate in user contexts to which the
4236 		 * enabling user does not have permissions.
4237 		 */
4238 		if (!dtrace_inscratch(dest, size, mstate)) {
4239 			*flags |= CPU_DTRACE_BADADDR;
4240 			*illval = regs[rd];
4241 			break;
4242 		}
4243 
4244 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4245 		dtrace_copyin(tupregs[0].dttk_value, dest, size, flags);
4246 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4247 		break;
4248 	}
4249 
4250 	case DIF_SUBR_COPYINSTR: {
4251 		uintptr_t dest = mstate->dtms_scratch_ptr;
4252 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4253 
4254 		if (nargs > 1 && tupregs[1].dttk_value < size)
4255 			size = tupregs[1].dttk_value + 1;
4256 
4257 		/*
4258 		 * This action doesn't require any credential checks since
4259 		 * probes will not activate in user contexts to which the
4260 		 * enabling user does not have permissions.
4261 		 */
4262 		if (!DTRACE_INSCRATCH(mstate, size)) {
4263 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4264 			regs[rd] = 0;
4265 			break;
4266 		}
4267 
4268 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4269 		dtrace_copyinstr(tupregs[0].dttk_value, dest, size, flags);
4270 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4271 
4272 		((char *)dest)[size - 1] = '\0';
4273 		mstate->dtms_scratch_ptr += size;
4274 		regs[rd] = dest;
4275 		break;
4276 	}
4277 
4278 	case DIF_SUBR_MSGSIZE:
4279 	case DIF_SUBR_MSGDSIZE: {
4280 		uintptr_t baddr = tupregs[0].dttk_value, daddr;
4281 		uintptr_t wptr, rptr;
4282 		size_t count = 0;
4283 		int cont = 0;
4284 
4285 		while (baddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4286 
4287 			if (!dtrace_canload(baddr, sizeof (mblk_t), mstate,
4288 			    vstate)) {
4289 				regs[rd] = 0;
4290 				break;
4291 			}
4292 
4293 			wptr = dtrace_loadptr(baddr +
4294 			    offsetof(mblk_t, b_wptr));
4295 
4296 			rptr = dtrace_loadptr(baddr +
4297 			    offsetof(mblk_t, b_rptr));
4298 
4299 			if (wptr < rptr) {
4300 				*flags |= CPU_DTRACE_BADADDR;
4301 				*illval = tupregs[0].dttk_value;
4302 				break;
4303 			}
4304 
4305 			daddr = dtrace_loadptr(baddr +
4306 			    offsetof(mblk_t, b_datap));
4307 
4308 			baddr = dtrace_loadptr(baddr +
4309 			    offsetof(mblk_t, b_cont));
4310 
4311 			/*
4312 			 * We want to prevent against denial-of-service here,
4313 			 * so we're only going to search the list for
4314 			 * dtrace_msgdsize_max mblks.
4315 			 */
4316 			if (cont++ > dtrace_msgdsize_max) {
4317 				*flags |= CPU_DTRACE_ILLOP;
4318 				break;
4319 			}
4320 
4321 			if (subr == DIF_SUBR_MSGDSIZE) {
4322 				if (dtrace_load8(daddr +
4323 				    offsetof(dblk_t, db_type)) != M_DATA)
4324 					continue;
4325 			}
4326 
4327 			count += wptr - rptr;
4328 		}
4329 
4330 		if (!(*flags & CPU_DTRACE_FAULT))
4331 			regs[rd] = count;
4332 
4333 		break;
4334 	}
4335 
4336 	case DIF_SUBR_PROGENYOF: {
4337 		pid_t pid = tupregs[0].dttk_value;
4338 		proc_t *p;
4339 		int rval = 0;
4340 
4341 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4342 
4343 		for (p = curthread->t_procp; p != NULL; p = p->p_parent) {
4344 			if (p->p_pidp->pid_id == pid) {
4345 				rval = 1;
4346 				break;
4347 			}
4348 		}
4349 
4350 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4351 
4352 		regs[rd] = rval;
4353 		break;
4354 	}
4355 
4356 	case DIF_SUBR_SPECULATION:
4357 		regs[rd] = dtrace_speculation(state);
4358 		break;
4359 
4360 	case DIF_SUBR_COPYOUT: {
4361 		uintptr_t kaddr = tupregs[0].dttk_value;
4362 		uintptr_t uaddr = tupregs[1].dttk_value;
4363 		uint64_t size = tupregs[2].dttk_value;
4364 
4365 		if (!dtrace_destructive_disallow &&
4366 		    dtrace_priv_proc_control(state, mstate) &&
4367 		    !dtrace_istoxic(kaddr, size) &&
4368 		    dtrace_canload(kaddr, size, mstate, vstate)) {
4369 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4370 			dtrace_copyout(kaddr, uaddr, size, flags);
4371 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4372 		}
4373 		break;
4374 	}
4375 
4376 	case DIF_SUBR_COPYOUTSTR: {
4377 		uintptr_t kaddr = tupregs[0].dttk_value;
4378 		uintptr_t uaddr = tupregs[1].dttk_value;
4379 		uint64_t size = tupregs[2].dttk_value;
4380 		size_t lim;
4381 
4382 		if (!dtrace_destructive_disallow &&
4383 		    dtrace_priv_proc_control(state, mstate) &&
4384 		    !dtrace_istoxic(kaddr, size) &&
4385 		    dtrace_strcanload(kaddr, size, &lim, mstate, vstate)) {
4386 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
4387 			dtrace_copyoutstr(kaddr, uaddr, lim, flags);
4388 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
4389 		}
4390 		break;
4391 	}
4392 
4393 	case DIF_SUBR_STRLEN: {
4394 		size_t size = state->dts_options[DTRACEOPT_STRSIZE];
4395 		uintptr_t addr = (uintptr_t)tupregs[0].dttk_value;
4396 		size_t lim;
4397 
4398 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4399 			regs[rd] = 0;
4400 			break;
4401 		}
4402 		regs[rd] = dtrace_strlen((char *)addr, lim);
4403 
4404 		break;
4405 	}
4406 
4407 	case DIF_SUBR_STRCHR:
4408 	case DIF_SUBR_STRRCHR: {
4409 		/*
4410 		 * We're going to iterate over the string looking for the
4411 		 * specified character.  We will iterate until we have reached
4412 		 * the string length or we have found the character.  If this
4413 		 * is DIF_SUBR_STRRCHR, we will look for the last occurrence
4414 		 * of the specified character instead of the first.
4415 		 */
4416 		uintptr_t addr = tupregs[0].dttk_value;
4417 		uintptr_t addr_limit;
4418 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4419 		size_t lim;
4420 		char c, target = (char)tupregs[1].dttk_value;
4421 
4422 		if (!dtrace_strcanload(addr, size, &lim, mstate, vstate)) {
4423 			regs[rd] = 0;
4424 			break;
4425 		}
4426 		addr_limit = addr + lim;
4427 
4428 		for (regs[rd] = 0; addr < addr_limit; addr++) {
4429 			if ((c = dtrace_load8(addr)) == target) {
4430 				regs[rd] = addr;
4431 
4432 				if (subr == DIF_SUBR_STRCHR)
4433 					break;
4434 			}
4435 			if (c == '\0')
4436 				break;
4437 		}
4438 
4439 		break;
4440 	}
4441 
4442 	case DIF_SUBR_STRSTR:
4443 	case DIF_SUBR_INDEX:
4444 	case DIF_SUBR_RINDEX: {
4445 		/*
4446 		 * We're going to iterate over the string looking for the
4447 		 * specified string.  We will iterate until we have reached
4448 		 * the string length or we have found the string.  (Yes, this
4449 		 * is done in the most naive way possible -- but considering
4450 		 * that the string we're searching for is likely to be
4451 		 * relatively short, the complexity of Rabin-Karp or similar
4452 		 * hardly seems merited.)
4453 		 */
4454 		char *addr = (char *)(uintptr_t)tupregs[0].dttk_value;
4455 		char *substr = (char *)(uintptr_t)tupregs[1].dttk_value;
4456 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4457 		size_t len = dtrace_strlen(addr, size);
4458 		size_t sublen = dtrace_strlen(substr, size);
4459 		char *limit = addr + len, *orig = addr;
4460 		int notfound = subr == DIF_SUBR_STRSTR ? 0 : -1;
4461 		int inc = 1;
4462 
4463 		regs[rd] = notfound;
4464 
4465 		if (!dtrace_canload((uintptr_t)addr, len + 1, mstate, vstate)) {
4466 			regs[rd] = 0;
4467 			break;
4468 		}
4469 
4470 		if (!dtrace_canload((uintptr_t)substr, sublen + 1, mstate,
4471 		    vstate)) {
4472 			regs[rd] = 0;
4473 			break;
4474 		}
4475 
4476 		/*
4477 		 * strstr() and index()/rindex() have similar semantics if
4478 		 * both strings are the empty string: strstr() returns a
4479 		 * pointer to the (empty) string, and index() and rindex()
4480 		 * both return index 0 (regardless of any position argument).
4481 		 */
4482 		if (sublen == 0 && len == 0) {
4483 			if (subr == DIF_SUBR_STRSTR)
4484 				regs[rd] = (uintptr_t)addr;
4485 			else
4486 				regs[rd] = 0;
4487 			break;
4488 		}
4489 
4490 		if (subr != DIF_SUBR_STRSTR) {
4491 			if (subr == DIF_SUBR_RINDEX) {
4492 				limit = orig - 1;
4493 				addr += len;
4494 				inc = -1;
4495 			}
4496 
4497 			/*
4498 			 * Both index() and rindex() take an optional position
4499 			 * argument that denotes the starting position.
4500 			 */
4501 			if (nargs == 3) {
4502 				int64_t pos = (int64_t)tupregs[2].dttk_value;
4503 
4504 				/*
4505 				 * If the position argument to index() is
4506 				 * negative, Perl implicitly clamps it at
4507 				 * zero.  This semantic is a little surprising
4508 				 * given the special meaning of negative
4509 				 * positions to similar Perl functions like
4510 				 * substr(), but it appears to reflect a
4511 				 * notion that index() can start from a
4512 				 * negative index and increment its way up to
4513 				 * the string.  Given this notion, Perl's
4514 				 * rindex() is at least self-consistent in
4515 				 * that it implicitly clamps positions greater
4516 				 * than the string length to be the string
4517 				 * length.  Where Perl completely loses
4518 				 * coherence, however, is when the specified
4519 				 * substring is the empty string ("").  In
4520 				 * this case, even if the position is
4521 				 * negative, rindex() returns 0 -- and even if
4522 				 * the position is greater than the length,
4523 				 * index() returns the string length.  These
4524 				 * semantics violate the notion that index()
4525 				 * should never return a value less than the
4526 				 * specified position and that rindex() should
4527 				 * never return a value greater than the
4528 				 * specified position.  (One assumes that
4529 				 * these semantics are artifacts of Perl's
4530 				 * implementation and not the results of
4531 				 * deliberate design -- it beggars belief that
4532 				 * even Larry Wall could desire such oddness.)
4533 				 * While in the abstract one would wish for
4534 				 * consistent position semantics across
4535 				 * substr(), index() and rindex() -- or at the
4536 				 * very least self-consistent position
4537 				 * semantics for index() and rindex() -- we
4538 				 * instead opt to keep with the extant Perl
4539 				 * semantics, in all their broken glory.  (Do
4540 				 * we have more desire to maintain Perl's
4541 				 * semantics than Perl does?  Probably.)
4542 				 */
4543 				if (subr == DIF_SUBR_RINDEX) {
4544 					if (pos < 0) {
4545 						if (sublen == 0)
4546 							regs[rd] = 0;
4547 						break;
4548 					}
4549 
4550 					if (pos > len)
4551 						pos = len;
4552 				} else {
4553 					if (pos < 0)
4554 						pos = 0;
4555 
4556 					if (pos >= len) {
4557 						if (sublen == 0)
4558 							regs[rd] = len;
4559 						break;
4560 					}
4561 				}
4562 
4563 				addr = orig + pos;
4564 			}
4565 		}
4566 
4567 		for (regs[rd] = notfound; addr != limit; addr += inc) {
4568 			if (dtrace_strncmp(addr, substr, sublen) == 0) {
4569 				if (subr != DIF_SUBR_STRSTR) {
4570 					/*
4571 					 * As D index() and rindex() are
4572 					 * modeled on Perl (and not on awk),
4573 					 * we return a zero-based (and not a
4574 					 * one-based) index.  (For you Perl
4575 					 * weenies: no, we're not going to add
4576 					 * $[ -- and shouldn't you be at a con
4577 					 * or something?)
4578 					 */
4579 					regs[rd] = (uintptr_t)(addr - orig);
4580 					break;
4581 				}
4582 
4583 				ASSERT(subr == DIF_SUBR_STRSTR);
4584 				regs[rd] = (uintptr_t)addr;
4585 				break;
4586 			}
4587 		}
4588 
4589 		break;
4590 	}
4591 
4592 	case DIF_SUBR_STRTOK: {
4593 		uintptr_t addr = tupregs[0].dttk_value;
4594 		uintptr_t tokaddr = tupregs[1].dttk_value;
4595 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4596 		uintptr_t limit, toklimit;
4597 		size_t clim;
4598 		uint8_t c, tokmap[32];	 /* 256 / 8 */
4599 		char *dest = (char *)mstate->dtms_scratch_ptr;
4600 		int i;
4601 
4602 		/*
4603 		 * Check both the token buffer and (later) the input buffer,
4604 		 * since both could be non-scratch addresses.
4605 		 */
4606 		if (!dtrace_strcanload(tokaddr, size, &clim, mstate, vstate)) {
4607 			regs[rd] = 0;
4608 			break;
4609 		}
4610 		toklimit = tokaddr + clim;
4611 
4612 		if (!DTRACE_INSCRATCH(mstate, size)) {
4613 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4614 			regs[rd] = 0;
4615 			break;
4616 		}
4617 
4618 		if (addr == 0) {
4619 			/*
4620 			 * If the address specified is NULL, we use our saved
4621 			 * strtok pointer from the mstate.  Note that this
4622 			 * means that the saved strtok pointer is _only_
4623 			 * valid within multiple enablings of the same probe --
4624 			 * it behaves like an implicit clause-local variable.
4625 			 */
4626 			addr = mstate->dtms_strtok;
4627 			limit = mstate->dtms_strtok_limit;
4628 		} else {
4629 			/*
4630 			 * If the user-specified address is non-NULL we must
4631 			 * access check it.  This is the only time we have
4632 			 * a chance to do so, since this address may reside
4633 			 * in the string table of this clause-- future calls
4634 			 * (when we fetch addr from mstate->dtms_strtok)
4635 			 * would fail this access check.
4636 			 */
4637 			if (!dtrace_strcanload(addr, size, &clim, mstate,
4638 			    vstate)) {
4639 				regs[rd] = 0;
4640 				break;
4641 			}
4642 			limit = addr + clim;
4643 		}
4644 
4645 		/*
4646 		 * First, zero the token map, and then process the token
4647 		 * string -- setting a bit in the map for every character
4648 		 * found in the token string.
4649 		 */
4650 		for (i = 0; i < sizeof (tokmap); i++)
4651 			tokmap[i] = 0;
4652 
4653 		for (; tokaddr < toklimit; tokaddr++) {
4654 			if ((c = dtrace_load8(tokaddr)) == '\0')
4655 				break;
4656 
4657 			ASSERT((c >> 3) < sizeof (tokmap));
4658 			tokmap[c >> 3] |= (1 << (c & 0x7));
4659 		}
4660 
4661 		for (; addr < limit; addr++) {
4662 			/*
4663 			 * We're looking for a character that is _not_
4664 			 * contained in the token string.
4665 			 */
4666 			if ((c = dtrace_load8(addr)) == '\0')
4667 				break;
4668 
4669 			if (!(tokmap[c >> 3] & (1 << (c & 0x7))))
4670 				break;
4671 		}
4672 
4673 		if (c == '\0') {
4674 			/*
4675 			 * We reached the end of the string without finding
4676 			 * any character that was not in the token string.
4677 			 * We return NULL in this case, and we set the saved
4678 			 * address to NULL as well.
4679 			 */
4680 			regs[rd] = 0;
4681 			mstate->dtms_strtok = 0;
4682 			mstate->dtms_strtok_limit = 0;
4683 			break;
4684 		}
4685 
4686 		/*
4687 		 * From here on, we're copying into the destination string.
4688 		 */
4689 		for (i = 0; addr < limit && i < size - 1; addr++) {
4690 			if ((c = dtrace_load8(addr)) == '\0')
4691 				break;
4692 
4693 			if (tokmap[c >> 3] & (1 << (c & 0x7)))
4694 				break;
4695 
4696 			ASSERT(i < size);
4697 			dest[i++] = c;
4698 		}
4699 
4700 		ASSERT(i < size);
4701 		dest[i] = '\0';
4702 		regs[rd] = (uintptr_t)dest;
4703 		mstate->dtms_scratch_ptr += size;
4704 		mstate->dtms_strtok = addr;
4705 		mstate->dtms_strtok_limit = limit;
4706 		break;
4707 	}
4708 
4709 	case DIF_SUBR_SUBSTR: {
4710 		uintptr_t s = tupregs[0].dttk_value;
4711 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4712 		char *d = (char *)mstate->dtms_scratch_ptr;
4713 		int64_t index = (int64_t)tupregs[1].dttk_value;
4714 		int64_t remaining = (int64_t)tupregs[2].dttk_value;
4715 		size_t len = dtrace_strlen((char *)s, size);
4716 		int64_t i;
4717 
4718 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4719 			regs[rd] = 0;
4720 			break;
4721 		}
4722 
4723 		if (!DTRACE_INSCRATCH(mstate, size)) {
4724 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4725 			regs[rd] = 0;
4726 			break;
4727 		}
4728 
4729 		if (nargs <= 2)
4730 			remaining = (int64_t)size;
4731 
4732 		if (index < 0) {
4733 			index += len;
4734 
4735 			if (index < 0 && index + remaining > 0) {
4736 				remaining += index;
4737 				index = 0;
4738 			}
4739 		}
4740 
4741 		if (index >= len || index < 0) {
4742 			remaining = 0;
4743 		} else if (remaining < 0) {
4744 			remaining += len - index;
4745 		} else if (index + remaining > size) {
4746 			remaining = size - index;
4747 		}
4748 
4749 		for (i = 0; i < remaining; i++) {
4750 			if ((d[i] = dtrace_load8(s + index + i)) == '\0')
4751 				break;
4752 		}
4753 
4754 		d[i] = '\0';
4755 
4756 		mstate->dtms_scratch_ptr += size;
4757 		regs[rd] = (uintptr_t)d;
4758 		break;
4759 	}
4760 
4761 	case DIF_SUBR_JSON: {
4762 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4763 		uintptr_t json = tupregs[0].dttk_value;
4764 		size_t jsonlen = dtrace_strlen((char *)json, size);
4765 		uintptr_t elem = tupregs[1].dttk_value;
4766 		size_t elemlen = dtrace_strlen((char *)elem, size);
4767 
4768 		char *dest = (char *)mstate->dtms_scratch_ptr;
4769 		char *elemlist = (char *)mstate->dtms_scratch_ptr + jsonlen + 1;
4770 		char *ee = elemlist;
4771 		int nelems = 1;
4772 		uintptr_t cur;
4773 
4774 		if (!dtrace_canload(json, jsonlen + 1, mstate, vstate) ||
4775 		    !dtrace_canload(elem, elemlen + 1, mstate, vstate)) {
4776 			regs[rd] = 0;
4777 			break;
4778 		}
4779 
4780 		if (!DTRACE_INSCRATCH(mstate, jsonlen + 1 + elemlen + 1)) {
4781 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4782 			regs[rd] = 0;
4783 			break;
4784 		}
4785 
4786 		/*
4787 		 * Read the element selector and split it up into a packed list
4788 		 * of strings.
4789 		 */
4790 		for (cur = elem; cur < elem + elemlen; cur++) {
4791 			char cc = dtrace_load8(cur);
4792 
4793 			if (cur == elem && cc == '[') {
4794 				/*
4795 				 * If the first element selector key is
4796 				 * actually an array index then ignore the
4797 				 * bracket.
4798 				 */
4799 				continue;
4800 			}
4801 
4802 			if (cc == ']')
4803 				continue;
4804 
4805 			if (cc == '.' || cc == '[') {
4806 				nelems++;
4807 				cc = '\0';
4808 			}
4809 
4810 			*ee++ = cc;
4811 		}
4812 		*ee++ = '\0';
4813 
4814 		if ((regs[rd] = (uintptr_t)dtrace_json(size, json, elemlist,
4815 		    nelems, dest)) != 0)
4816 			mstate->dtms_scratch_ptr += jsonlen + 1;
4817 		break;
4818 	}
4819 
4820 	case DIF_SUBR_TOUPPER:
4821 	case DIF_SUBR_TOLOWER: {
4822 		uintptr_t s = tupregs[0].dttk_value;
4823 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4824 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
4825 		size_t len = dtrace_strlen((char *)s, size);
4826 		char lower, upper, convert;
4827 		int64_t i;
4828 
4829 		if (subr == DIF_SUBR_TOUPPER) {
4830 			lower = 'a';
4831 			upper = 'z';
4832 			convert = 'A';
4833 		} else {
4834 			lower = 'A';
4835 			upper = 'Z';
4836 			convert = 'a';
4837 		}
4838 
4839 		if (!dtrace_canload(s, len + 1, mstate, vstate)) {
4840 			regs[rd] = 0;
4841 			break;
4842 		}
4843 
4844 		if (!DTRACE_INSCRATCH(mstate, size)) {
4845 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4846 			regs[rd] = 0;
4847 			break;
4848 		}
4849 
4850 		for (i = 0; i < size - 1; i++) {
4851 			if ((c = dtrace_load8(s + i)) == '\0')
4852 				break;
4853 
4854 			if (c >= lower && c <= upper)
4855 				c = convert + (c - lower);
4856 
4857 			dest[i] = c;
4858 		}
4859 
4860 		ASSERT(i < size);
4861 		dest[i] = '\0';
4862 		regs[rd] = (uintptr_t)dest;
4863 		mstate->dtms_scratch_ptr += size;
4864 		break;
4865 	}
4866 
4867 case DIF_SUBR_GETMAJOR:
4868 #ifdef _LP64
4869 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR64) & MAXMAJ64;
4870 #else
4871 		regs[rd] = (tupregs[0].dttk_value >> NBITSMINOR) & MAXMAJ;
4872 #endif
4873 		break;
4874 
4875 	case DIF_SUBR_GETMINOR:
4876 #ifdef _LP64
4877 		regs[rd] = tupregs[0].dttk_value & MAXMIN64;
4878 #else
4879 		regs[rd] = tupregs[0].dttk_value & MAXMIN;
4880 #endif
4881 		break;
4882 
4883 	case DIF_SUBR_DDI_PATHNAME: {
4884 		/*
4885 		 * This one is a galactic mess.  We are going to roughly
4886 		 * emulate ddi_pathname(), but it's made more complicated
4887 		 * by the fact that we (a) want to include the minor name and
4888 		 * (b) must proceed iteratively instead of recursively.
4889 		 */
4890 		uintptr_t dest = mstate->dtms_scratch_ptr;
4891 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
4892 		char *start = (char *)dest, *end = start + size - 1;
4893 		uintptr_t daddr = tupregs[0].dttk_value;
4894 		int64_t minor = (int64_t)tupregs[1].dttk_value;
4895 		char *s;
4896 		int i, len, depth = 0;
4897 
4898 		/*
4899 		 * Due to all the pointer jumping we do and context we must
4900 		 * rely upon, we just mandate that the user must have kernel
4901 		 * read privileges to use this routine.
4902 		 */
4903 		if ((mstate->dtms_access & DTRACE_ACCESS_KERNEL) == 0) {
4904 			*flags |= CPU_DTRACE_KPRIV;
4905 			*illval = daddr;
4906 			regs[rd] = 0;
4907 		}
4908 
4909 		if (!DTRACE_INSCRATCH(mstate, size)) {
4910 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
4911 			regs[rd] = 0;
4912 			break;
4913 		}
4914 
4915 		*end = '\0';
4916 
4917 		/*
4918 		 * We want to have a name for the minor.  In order to do this,
4919 		 * we need to walk the minor list from the devinfo.  We want
4920 		 * to be sure that we don't infinitely walk a circular list,
4921 		 * so we check for circularity by sending a scout pointer
4922 		 * ahead two elements for every element that we iterate over;
4923 		 * if the list is circular, these will ultimately point to the
4924 		 * same element.  You may recognize this little trick as the
4925 		 * answer to a stupid interview question -- one that always
4926 		 * seems to be asked by those who had to have it laboriously
4927 		 * explained to them, and who can't even concisely describe
4928 		 * the conditions under which one would be forced to resort to
4929 		 * this technique.  Needless to say, those conditions are
4930 		 * found here -- and probably only here.  Is this the only use
4931 		 * of this infamous trick in shipping, production code?  If it
4932 		 * isn't, it probably should be...
4933 		 */
4934 		if (minor != -1) {
4935 			uintptr_t maddr = dtrace_loadptr(daddr +
4936 			    offsetof(struct dev_info, devi_minor));
4937 
4938 			uintptr_t next = offsetof(struct ddi_minor_data, next);
4939 			uintptr_t name = offsetof(struct ddi_minor_data,
4940 			    d_minor) + offsetof(struct ddi_minor, name);
4941 			uintptr_t dev = offsetof(struct ddi_minor_data,
4942 			    d_minor) + offsetof(struct ddi_minor, dev);
4943 			uintptr_t scout;
4944 
4945 			if (maddr != 0)
4946 				scout = dtrace_loadptr(maddr + next);
4947 
4948 			while (maddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
4949 				uint64_t m;
4950 #ifdef _LP64
4951 				m = dtrace_load64(maddr + dev) & MAXMIN64;
4952 #else
4953 				m = dtrace_load32(maddr + dev) & MAXMIN;
4954 #endif
4955 				if (m != minor) {
4956 					maddr = dtrace_loadptr(maddr + next);
4957 
4958 					if (scout == 0)
4959 						continue;
4960 
4961 					scout = dtrace_loadptr(scout + next);
4962 
4963 					if (scout == 0)
4964 						continue;
4965 
4966 					scout = dtrace_loadptr(scout + next);
4967 
4968 					if (scout == 0)
4969 						continue;
4970 
4971 					if (scout == maddr) {
4972 						*flags |= CPU_DTRACE_ILLOP;
4973 						break;
4974 					}
4975 
4976 					continue;
4977 				}
4978 
4979 				/*
4980 				 * We have the minor data.  Now we need to
4981 				 * copy the minor's name into the end of the
4982 				 * pathname.
4983 				 */
4984 				s = (char *)dtrace_loadptr(maddr + name);
4985 				len = dtrace_strlen(s, size);
4986 
4987 				if (*flags & CPU_DTRACE_FAULT)
4988 					break;
4989 
4990 				if (len != 0) {
4991 					if ((end -= (len + 1)) < start)
4992 						break;
4993 
4994 					*end = ':';
4995 				}
4996 
4997 				for (i = 1; i <= len; i++)
4998 					end[i] = dtrace_load8((uintptr_t)s++);
4999 				break;
5000 			}
5001 		}
5002 
5003 		while (daddr != 0 && !(*flags & CPU_DTRACE_FAULT)) {
5004 			ddi_node_state_t devi_state;
5005 
5006 			devi_state = dtrace_load32(daddr +
5007 			    offsetof(struct dev_info, devi_node_state));
5008 
5009 			if (*flags & CPU_DTRACE_FAULT)
5010 				break;
5011 
5012 			if (devi_state >= DS_INITIALIZED) {
5013 				s = (char *)dtrace_loadptr(daddr +
5014 				    offsetof(struct dev_info, devi_addr));
5015 				len = dtrace_strlen(s, size);
5016 
5017 				if (*flags & CPU_DTRACE_FAULT)
5018 					break;
5019 
5020 				if (len != 0) {
5021 					if ((end -= (len + 1)) < start)
5022 						break;
5023 
5024 					*end = '@';
5025 				}
5026 
5027 				for (i = 1; i <= len; i++)
5028 					end[i] = dtrace_load8((uintptr_t)s++);
5029 			}
5030 
5031 			/*
5032 			 * Now for the node name...
5033 			 */
5034 			s = (char *)dtrace_loadptr(daddr +
5035 			    offsetof(struct dev_info, devi_node_name));
5036 
5037 			daddr = dtrace_loadptr(daddr +
5038 			    offsetof(struct dev_info, devi_parent));
5039 
5040 			/*
5041 			 * If our parent is NULL (that is, if we're the root
5042 			 * node), we're going to use the special path
5043 			 * "devices".
5044 			 */
5045 			if (daddr == 0)
5046 				s = "devices";
5047 
5048 			len = dtrace_strlen(s, size);
5049 			if (*flags & CPU_DTRACE_FAULT)
5050 				break;
5051 
5052 			if ((end -= (len + 1)) < start)
5053 				break;
5054 
5055 			for (i = 1; i <= len; i++)
5056 				end[i] = dtrace_load8((uintptr_t)s++);
5057 			*end = '/';
5058 
5059 			if (depth++ > dtrace_devdepth_max) {
5060 				*flags |= CPU_DTRACE_ILLOP;
5061 				break;
5062 			}
5063 		}
5064 
5065 		if (end < start)
5066 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5067 
5068 		if (daddr == 0) {
5069 			regs[rd] = (uintptr_t)end;
5070 			mstate->dtms_scratch_ptr += size;
5071 		}
5072 
5073 		break;
5074 	}
5075 
5076 	case DIF_SUBR_STRJOIN: {
5077 		char *d = (char *)mstate->dtms_scratch_ptr;
5078 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5079 		uintptr_t s1 = tupregs[0].dttk_value;
5080 		uintptr_t s2 = tupregs[1].dttk_value;
5081 		int i = 0, j = 0;
5082 		size_t lim1, lim2;
5083 		char c;
5084 
5085 		if (!dtrace_strcanload(s1, size, &lim1, mstate, vstate) ||
5086 		    !dtrace_strcanload(s2, size, &lim2, mstate, vstate)) {
5087 			regs[rd] = 0;
5088 			break;
5089 		}
5090 
5091 		if (!DTRACE_INSCRATCH(mstate, size)) {
5092 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5093 			regs[rd] = 0;
5094 			break;
5095 		}
5096 
5097 		for (;;) {
5098 			if (i >= size) {
5099 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5100 				regs[rd] = 0;
5101 				break;
5102 			}
5103 			c = (i >= lim1) ? '\0' : dtrace_load8(s1++);
5104 			if ((d[i++] = c) == '\0') {
5105 				i--;
5106 				break;
5107 			}
5108 		}
5109 
5110 		for (;;) {
5111 			if (i >= size) {
5112 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5113 				regs[rd] = 0;
5114 				break;
5115 			}
5116 
5117 			c = (j++ >= lim2) ? '\0' : dtrace_load8(s2++);
5118 			if ((d[i++] = c) == '\0')
5119 				break;
5120 		}
5121 
5122 		if (i < size) {
5123 			mstate->dtms_scratch_ptr += i;
5124 			regs[rd] = (uintptr_t)d;
5125 		}
5126 
5127 		break;
5128 	}
5129 
5130 	case DIF_SUBR_STRTOLL: {
5131 		uintptr_t s = tupregs[0].dttk_value;
5132 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5133 		size_t lim;
5134 		int base = 10;
5135 
5136 		if (nargs > 1) {
5137 			if ((base = tupregs[1].dttk_value) <= 1 ||
5138 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5139 				*flags |= CPU_DTRACE_ILLOP;
5140 				break;
5141 			}
5142 		}
5143 
5144 		if (!dtrace_strcanload(s, size, &lim, mstate, vstate)) {
5145 			regs[rd] = INT64_MIN;
5146 			break;
5147 		}
5148 
5149 		regs[rd] = dtrace_strtoll((char *)s, base, lim);
5150 		break;
5151 	}
5152 
5153 	case DIF_SUBR_LLTOSTR: {
5154 		int64_t i = (int64_t)tupregs[0].dttk_value;
5155 		uint64_t val, digit;
5156 		uint64_t size = 65;	/* enough room for 2^64 in binary */
5157 		char *end = (char *)mstate->dtms_scratch_ptr + size - 1;
5158 		int base = 10;
5159 
5160 		if (nargs > 1) {
5161 			if ((base = tupregs[1].dttk_value) <= 1 ||
5162 			    base > ('z' - 'a' + 1) + ('9' - '0' + 1)) {
5163 				*flags |= CPU_DTRACE_ILLOP;
5164 				break;
5165 			}
5166 		}
5167 
5168 		val = (base == 10 && i < 0) ? i * -1 : i;
5169 
5170 		if (!DTRACE_INSCRATCH(mstate, size)) {
5171 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5172 			regs[rd] = 0;
5173 			break;
5174 		}
5175 
5176 		for (*end-- = '\0'; val; val /= base) {
5177 			if ((digit = val % base) <= '9' - '0') {
5178 				*end-- = '0' + digit;
5179 			} else {
5180 				*end-- = 'a' + (digit - ('9' - '0') - 1);
5181 			}
5182 		}
5183 
5184 		if (i == 0 && base == 16)
5185 			*end-- = '0';
5186 
5187 		if (base == 16)
5188 			*end-- = 'x';
5189 
5190 		if (i == 0 || base == 8 || base == 16)
5191 			*end-- = '0';
5192 
5193 		if (i < 0 && base == 10)
5194 			*end-- = '-';
5195 
5196 		regs[rd] = (uintptr_t)end + 1;
5197 		mstate->dtms_scratch_ptr += size;
5198 		break;
5199 	}
5200 
5201 	case DIF_SUBR_HTONS:
5202 	case DIF_SUBR_NTOHS:
5203 #ifdef _BIG_ENDIAN
5204 		regs[rd] = (uint16_t)tupregs[0].dttk_value;
5205 #else
5206 		regs[rd] = DT_BSWAP_16((uint16_t)tupregs[0].dttk_value);
5207 #endif
5208 		break;
5209 
5210 
5211 	case DIF_SUBR_HTONL:
5212 	case DIF_SUBR_NTOHL:
5213 #ifdef _BIG_ENDIAN
5214 		regs[rd] = (uint32_t)tupregs[0].dttk_value;
5215 #else
5216 		regs[rd] = DT_BSWAP_32((uint32_t)tupregs[0].dttk_value);
5217 #endif
5218 		break;
5219 
5220 
5221 	case DIF_SUBR_HTONLL:
5222 	case DIF_SUBR_NTOHLL:
5223 #ifdef _BIG_ENDIAN
5224 		regs[rd] = (uint64_t)tupregs[0].dttk_value;
5225 #else
5226 		regs[rd] = DT_BSWAP_64((uint64_t)tupregs[0].dttk_value);
5227 #endif
5228 		break;
5229 
5230 
5231 	case DIF_SUBR_DIRNAME:
5232 	case DIF_SUBR_BASENAME: {
5233 		char *dest = (char *)mstate->dtms_scratch_ptr;
5234 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5235 		uintptr_t src = tupregs[0].dttk_value;
5236 		int i, j, len = dtrace_strlen((char *)src, size);
5237 		int lastbase = -1, firstbase = -1, lastdir = -1;
5238 		int start, end;
5239 
5240 		if (!dtrace_canload(src, len + 1, mstate, vstate)) {
5241 			regs[rd] = 0;
5242 			break;
5243 		}
5244 
5245 		if (!DTRACE_INSCRATCH(mstate, size)) {
5246 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5247 			regs[rd] = 0;
5248 			break;
5249 		}
5250 
5251 		/*
5252 		 * The basename and dirname for a zero-length string is
5253 		 * defined to be "."
5254 		 */
5255 		if (len == 0) {
5256 			len = 1;
5257 			src = (uintptr_t)".";
5258 		}
5259 
5260 		/*
5261 		 * Start from the back of the string, moving back toward the
5262 		 * front until we see a character that isn't a slash.  That
5263 		 * character is the last character in the basename.
5264 		 */
5265 		for (i = len - 1; i >= 0; i--) {
5266 			if (dtrace_load8(src + i) != '/')
5267 				break;
5268 		}
5269 
5270 		if (i >= 0)
5271 			lastbase = i;
5272 
5273 		/*
5274 		 * Starting from the last character in the basename, move
5275 		 * towards the front until we find a slash.  The character
5276 		 * that we processed immediately before that is the first
5277 		 * character in the basename.
5278 		 */
5279 		for (; i >= 0; i--) {
5280 			if (dtrace_load8(src + i) == '/')
5281 				break;
5282 		}
5283 
5284 		if (i >= 0)
5285 			firstbase = i + 1;
5286 
5287 		/*
5288 		 * Now keep going until we find a non-slash character.  That
5289 		 * character is the last character in the dirname.
5290 		 */
5291 		for (; i >= 0; i--) {
5292 			if (dtrace_load8(src + i) != '/')
5293 				break;
5294 		}
5295 
5296 		if (i >= 0)
5297 			lastdir = i;
5298 
5299 		ASSERT(!(lastbase == -1 && firstbase != -1));
5300 		ASSERT(!(firstbase == -1 && lastdir != -1));
5301 
5302 		if (lastbase == -1) {
5303 			/*
5304 			 * We didn't find a non-slash character.  We know that
5305 			 * the length is non-zero, so the whole string must be
5306 			 * slashes.  In either the dirname or the basename
5307 			 * case, we return '/'.
5308 			 */
5309 			ASSERT(firstbase == -1);
5310 			firstbase = lastbase = lastdir = 0;
5311 		}
5312 
5313 		if (firstbase == -1) {
5314 			/*
5315 			 * The entire string consists only of a basename
5316 			 * component.  If we're looking for dirname, we need
5317 			 * to change our string to be just "."; if we're
5318 			 * looking for a basename, we'll just set the first
5319 			 * character of the basename to be 0.
5320 			 */
5321 			if (subr == DIF_SUBR_DIRNAME) {
5322 				ASSERT(lastdir == -1);
5323 				src = (uintptr_t)".";
5324 				lastdir = 0;
5325 			} else {
5326 				firstbase = 0;
5327 			}
5328 		}
5329 
5330 		if (subr == DIF_SUBR_DIRNAME) {
5331 			if (lastdir == -1) {
5332 				/*
5333 				 * We know that we have a slash in the name --
5334 				 * or lastdir would be set to 0, above.  And
5335 				 * because lastdir is -1, we know that this
5336 				 * slash must be the first character.  (That
5337 				 * is, the full string must be of the form
5338 				 * "/basename".)  In this case, the last
5339 				 * character of the directory name is 0.
5340 				 */
5341 				lastdir = 0;
5342 			}
5343 
5344 			start = 0;
5345 			end = lastdir;
5346 		} else {
5347 			ASSERT(subr == DIF_SUBR_BASENAME);
5348 			ASSERT(firstbase != -1 && lastbase != -1);
5349 			start = firstbase;
5350 			end = lastbase;
5351 		}
5352 
5353 		for (i = start, j = 0; i <= end && j < size - 1; i++, j++)
5354 			dest[j] = dtrace_load8(src + i);
5355 
5356 		dest[j] = '\0';
5357 		regs[rd] = (uintptr_t)dest;
5358 		mstate->dtms_scratch_ptr += size;
5359 		break;
5360 	}
5361 
5362 	case DIF_SUBR_GETF: {
5363 		uintptr_t fd = tupregs[0].dttk_value;
5364 		uf_info_t *finfo = &curthread->t_procp->p_user.u_finfo;
5365 		file_t *fp;
5366 
5367 		if (!dtrace_priv_proc(state, mstate)) {
5368 			regs[rd] = 0;
5369 			break;
5370 		}
5371 
5372 		/*
5373 		 * This is safe because fi_nfiles only increases, and the
5374 		 * fi_list array is not freed when the array size doubles.
5375 		 * (See the comment in flist_grow() for details on the
5376 		 * management of the u_finfo structure.)
5377 		 */
5378 		fp = fd < finfo->fi_nfiles ? finfo->fi_list[fd].uf_file : NULL;
5379 
5380 		mstate->dtms_getf = fp;
5381 		regs[rd] = (uintptr_t)fp;
5382 		break;
5383 	}
5384 
5385 	case DIF_SUBR_CLEANPATH: {
5386 		char *dest = (char *)mstate->dtms_scratch_ptr, c;
5387 		uint64_t size = state->dts_options[DTRACEOPT_STRSIZE];
5388 		uintptr_t src = tupregs[0].dttk_value;
5389 		size_t lim;
5390 		int i = 0, j = 0;
5391 		zone_t *z;
5392 
5393 		if (!dtrace_strcanload(src, size, &lim, mstate, vstate)) {
5394 			regs[rd] = 0;
5395 			break;
5396 		}
5397 
5398 		if (!DTRACE_INSCRATCH(mstate, size)) {
5399 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5400 			regs[rd] = 0;
5401 			break;
5402 		}
5403 
5404 		/*
5405 		 * Move forward, loading each character.
5406 		 */
5407 		do {
5408 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5409 next:
5410 			if (j + 5 >= size)	/* 5 = strlen("/..c\0") */
5411 				break;
5412 
5413 			if (c != '/') {
5414 				dest[j++] = c;
5415 				continue;
5416 			}
5417 
5418 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5419 
5420 			if (c == '/') {
5421 				/*
5422 				 * We have two slashes -- we can just advance
5423 				 * to the next character.
5424 				 */
5425 				goto next;
5426 			}
5427 
5428 			if (c != '.') {
5429 				/*
5430 				 * This is not "." and it's not ".." -- we can
5431 				 * just store the "/" and this character and
5432 				 * drive on.
5433 				 */
5434 				dest[j++] = '/';
5435 				dest[j++] = c;
5436 				continue;
5437 			}
5438 
5439 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5440 
5441 			if (c == '/') {
5442 				/*
5443 				 * This is a "/./" component.  We're not going
5444 				 * to store anything in the destination buffer;
5445 				 * we're just going to go to the next component.
5446 				 */
5447 				goto next;
5448 			}
5449 
5450 			if (c != '.') {
5451 				/*
5452 				 * This is not ".." -- we can just store the
5453 				 * "/." and this character and continue
5454 				 * processing.
5455 				 */
5456 				dest[j++] = '/';
5457 				dest[j++] = '.';
5458 				dest[j++] = c;
5459 				continue;
5460 			}
5461 
5462 			c = (i >= lim) ? '\0' : dtrace_load8(src + i++);
5463 
5464 			if (c != '/' && c != '\0') {
5465 				/*
5466 				 * This is not ".." -- it's "..[mumble]".
5467 				 * We'll store the "/.." and this character
5468 				 * and continue processing.
5469 				 */
5470 				dest[j++] = '/';
5471 				dest[j++] = '.';
5472 				dest[j++] = '.';
5473 				dest[j++] = c;
5474 				continue;
5475 			}
5476 
5477 			/*
5478 			 * This is "/../" or "/..\0".  We need to back up
5479 			 * our destination pointer until we find a "/".
5480 			 */
5481 			i--;
5482 			while (j != 0 && dest[--j] != '/')
5483 				continue;
5484 
5485 			if (c == '\0')
5486 				dest[++j] = '/';
5487 		} while (c != '\0');
5488 
5489 		dest[j] = '\0';
5490 
5491 		if (mstate->dtms_getf != NULL &&
5492 		    !(mstate->dtms_access & DTRACE_ACCESS_KERNEL) &&
5493 		    (z = state->dts_cred.dcr_cred->cr_zone) != kcred->cr_zone) {
5494 			/*
5495 			 * If we've done a getf() as a part of this ECB and we
5496 			 * don't have kernel access (and we're not in the global
5497 			 * zone), check if the path we cleaned up begins with
5498 			 * the zone's root path, and trim it off if so.  Note
5499 			 * that this is an output cleanliness issue, not a
5500 			 * security issue: knowing one's zone root path does
5501 			 * not enable privilege escalation.
5502 			 */
5503 			if (strstr(dest, z->zone_rootpath) == dest)
5504 				dest += strlen(z->zone_rootpath) - 1;
5505 		}
5506 
5507 		regs[rd] = (uintptr_t)dest;
5508 		mstate->dtms_scratch_ptr += size;
5509 		break;
5510 	}
5511 
5512 	case DIF_SUBR_INET_NTOA:
5513 	case DIF_SUBR_INET_NTOA6:
5514 	case DIF_SUBR_INET_NTOP: {
5515 		size_t size;
5516 		int af, argi, i;
5517 		char *base, *end;
5518 
5519 		if (subr == DIF_SUBR_INET_NTOP) {
5520 			af = (int)tupregs[0].dttk_value;
5521 			argi = 1;
5522 		} else {
5523 			af = subr == DIF_SUBR_INET_NTOA ? AF_INET: AF_INET6;
5524 			argi = 0;
5525 		}
5526 
5527 		if (af == AF_INET) {
5528 			ipaddr_t ip4;
5529 			uint8_t *ptr8, val;
5530 
5531 			if (!dtrace_canload(tupregs[argi].dttk_value,
5532 			    sizeof (ipaddr_t), mstate, vstate)) {
5533 				regs[rd] = 0;
5534 				break;
5535 			}
5536 
5537 			/*
5538 			 * Safely load the IPv4 address.
5539 			 */
5540 			ip4 = dtrace_load32(tupregs[argi].dttk_value);
5541 
5542 			/*
5543 			 * Check an IPv4 string will fit in scratch.
5544 			 */
5545 			size = INET_ADDRSTRLEN;
5546 			if (!DTRACE_INSCRATCH(mstate, size)) {
5547 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5548 				regs[rd] = 0;
5549 				break;
5550 			}
5551 			base = (char *)mstate->dtms_scratch_ptr;
5552 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5553 
5554 			/*
5555 			 * Stringify as a dotted decimal quad.
5556 			 */
5557 			*end-- = '\0';
5558 			ptr8 = (uint8_t *)&ip4;
5559 			for (i = 3; i >= 0; i--) {
5560 				val = ptr8[i];
5561 
5562 				if (val == 0) {
5563 					*end-- = '0';
5564 				} else {
5565 					for (; val; val /= 10) {
5566 						*end-- = '0' + (val % 10);
5567 					}
5568 				}
5569 
5570 				if (i > 0)
5571 					*end-- = '.';
5572 			}
5573 			ASSERT(end + 1 >= base);
5574 
5575 		} else if (af == AF_INET6) {
5576 			struct in6_addr ip6;
5577 			int firstzero, tryzero, numzero, v6end;
5578 			uint16_t val;
5579 			const char digits[] = "0123456789abcdef";
5580 
5581 			/*
5582 			 * Stringify using RFC 1884 convention 2 - 16 bit
5583 			 * hexadecimal values with a zero-run compression.
5584 			 * Lower case hexadecimal digits are used.
5585 			 *	eg, fe80::214:4fff:fe0b:76c8.
5586 			 * The IPv4 embedded form is returned for inet_ntop,
5587 			 * just the IPv4 string is returned for inet_ntoa6.
5588 			 */
5589 
5590 			if (!dtrace_canload(tupregs[argi].dttk_value,
5591 			    sizeof (struct in6_addr), mstate, vstate)) {
5592 				regs[rd] = 0;
5593 				break;
5594 			}
5595 
5596 			/*
5597 			 * Safely load the IPv6 address.
5598 			 */
5599 			dtrace_bcopy(
5600 			    (void *)(uintptr_t)tupregs[argi].dttk_value,
5601 			    (void *)(uintptr_t)&ip6, sizeof (struct in6_addr));
5602 
5603 			/*
5604 			 * Check an IPv6 string will fit in scratch.
5605 			 */
5606 			size = INET6_ADDRSTRLEN;
5607 			if (!DTRACE_INSCRATCH(mstate, size)) {
5608 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
5609 				regs[rd] = 0;
5610 				break;
5611 			}
5612 			base = (char *)mstate->dtms_scratch_ptr;
5613 			end = (char *)mstate->dtms_scratch_ptr + size - 1;
5614 			*end-- = '\0';
5615 
5616 			/*
5617 			 * Find the longest run of 16 bit zero values
5618 			 * for the single allowed zero compression - "::".
5619 			 */
5620 			firstzero = -1;
5621 			tryzero = -1;
5622 			numzero = 1;
5623 			for (i = 0; i < sizeof (struct in6_addr); i++) {
5624 				if (ip6._S6_un._S6_u8[i] == 0 &&
5625 				    tryzero == -1 && i % 2 == 0) {
5626 					tryzero = i;
5627 					continue;
5628 				}
5629 
5630 				if (tryzero != -1 &&
5631 				    (ip6._S6_un._S6_u8[i] != 0 ||
5632 				    i == sizeof (struct in6_addr) - 1)) {
5633 
5634 					if (i - tryzero <= numzero) {
5635 						tryzero = -1;
5636 						continue;
5637 					}
5638 
5639 					firstzero = tryzero;
5640 					numzero = i - i % 2 - tryzero;
5641 					tryzero = -1;
5642 
5643 					if (ip6._S6_un._S6_u8[i] == 0 &&
5644 					    i == sizeof (struct in6_addr) - 1)
5645 						numzero += 2;
5646 				}
5647 			}
5648 			ASSERT(firstzero + numzero <= sizeof (struct in6_addr));
5649 
5650 			/*
5651 			 * Check for an IPv4 embedded address.
5652 			 */
5653 			v6end = sizeof (struct in6_addr) - 2;
5654 			if (IN6_IS_ADDR_V4MAPPED(&ip6) ||
5655 			    IN6_IS_ADDR_V4COMPAT(&ip6)) {
5656 				for (i = sizeof (struct in6_addr) - 1;
5657 				    i >= DTRACE_V4MAPPED_OFFSET; i--) {
5658 					ASSERT(end >= base);
5659 
5660 					val = ip6._S6_un._S6_u8[i];
5661 
5662 					if (val == 0) {
5663 						*end-- = '0';
5664 					} else {
5665 						for (; val; val /= 10) {
5666 							*end-- = '0' + val % 10;
5667 						}
5668 					}
5669 
5670 					if (i > DTRACE_V4MAPPED_OFFSET)
5671 						*end-- = '.';
5672 				}
5673 
5674 				if (subr == DIF_SUBR_INET_NTOA6)
5675 					goto inetout;
5676 
5677 				/*
5678 				 * Set v6end to skip the IPv4 address that
5679 				 * we have already stringified.
5680 				 */
5681 				v6end = 10;
5682 			}
5683 
5684 			/*
5685 			 * Build the IPv6 string by working through the
5686 			 * address in reverse.
5687 			 */
5688 			for (i = v6end; i >= 0; i -= 2) {
5689 				ASSERT(end >= base);
5690 
5691 				if (i == firstzero + numzero - 2) {
5692 					*end-- = ':';
5693 					*end-- = ':';
5694 					i -= numzero - 2;
5695 					continue;
5696 				}
5697 
5698 				if (i < 14 && i != firstzero - 2)
5699 					*end-- = ':';
5700 
5701 				val = (ip6._S6_un._S6_u8[i] << 8) +
5702 				    ip6._S6_un._S6_u8[i + 1];
5703 
5704 				if (val == 0) {
5705 					*end-- = '0';
5706 				} else {
5707 					for (; val; val /= 16) {
5708 						*end-- = digits[val % 16];
5709 					}
5710 				}
5711 			}
5712 			ASSERT(end + 1 >= base);
5713 
5714 		} else {
5715 			/*
5716 			 * The user didn't use AH_INET or AH_INET6.
5717 			 */
5718 			DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
5719 			regs[rd] = 0;
5720 			break;
5721 		}
5722 
5723 inetout:	regs[rd] = (uintptr_t)end + 1;
5724 		mstate->dtms_scratch_ptr += size;
5725 		break;
5726 	}
5727 
5728 	}
5729 }
5730 
5731 /*
5732  * Emulate the execution of DTrace IR instructions specified by the given
5733  * DIF object.  This function is deliberately void of assertions as all of
5734  * the necessary checks are handled by a call to dtrace_difo_validate().
5735  */
5736 static uint64_t
5737 dtrace_dif_emulate(dtrace_difo_t *difo, dtrace_mstate_t *mstate,
5738     dtrace_vstate_t *vstate, dtrace_state_t *state)
5739 {
5740 	const dif_instr_t *text = difo->dtdo_buf;
5741 	const uint_t textlen = difo->dtdo_len;
5742 	const char *strtab = difo->dtdo_strtab;
5743 	const uint64_t *inttab = difo->dtdo_inttab;
5744 
5745 	uint64_t rval = 0;
5746 	dtrace_statvar_t *svar;
5747 	dtrace_dstate_t *dstate = &vstate->dtvs_dynvars;
5748 	dtrace_difv_t *v;
5749 	volatile uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
5750 	volatile uintptr_t *illval = &cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
5751 
5752 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
5753 	uint64_t regs[DIF_DIR_NREGS];
5754 	uint64_t *tmp;
5755 
5756 	uint8_t cc_n = 0, cc_z = 0, cc_v = 0, cc_c = 0;
5757 	int64_t cc_r;
5758 	uint_t pc = 0, id, opc;
5759 	uint8_t ttop = 0;
5760 	dif_instr_t instr;
5761 	uint_t r1, r2, rd;
5762 
5763 	/*
5764 	 * We stash the current DIF object into the machine state: we need it
5765 	 * for subsequent access checking.
5766 	 */
5767 	mstate->dtms_difo = difo;
5768 
5769 	regs[DIF_REG_R0] = 0;		/* %r0 is fixed at zero */
5770 
5771 	while (pc < textlen && !(*flags & CPU_DTRACE_FAULT)) {
5772 		opc = pc;
5773 
5774 		instr = text[pc++];
5775 		r1 = DIF_INSTR_R1(instr);
5776 		r2 = DIF_INSTR_R2(instr);
5777 		rd = DIF_INSTR_RD(instr);
5778 
5779 		switch (DIF_INSTR_OP(instr)) {
5780 		case DIF_OP_OR:
5781 			regs[rd] = regs[r1] | regs[r2];
5782 			break;
5783 		case DIF_OP_XOR:
5784 			regs[rd] = regs[r1] ^ regs[r2];
5785 			break;
5786 		case DIF_OP_AND:
5787 			regs[rd] = regs[r1] & regs[r2];
5788 			break;
5789 		case DIF_OP_SLL:
5790 			regs[rd] = regs[r1] << regs[r2];
5791 			break;
5792 		case DIF_OP_SRL:
5793 			regs[rd] = regs[r1] >> regs[r2];
5794 			break;
5795 		case DIF_OP_SUB:
5796 			regs[rd] = regs[r1] - regs[r2];
5797 			break;
5798 		case DIF_OP_ADD:
5799 			regs[rd] = regs[r1] + regs[r2];
5800 			break;
5801 		case DIF_OP_MUL:
5802 			regs[rd] = regs[r1] * regs[r2];
5803 			break;
5804 		case DIF_OP_SDIV:
5805 			if (regs[r2] == 0) {
5806 				regs[rd] = 0;
5807 				*flags |= CPU_DTRACE_DIVZERO;
5808 			} else {
5809 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5810 				regs[rd] = (int64_t)regs[r1] /
5811 				    (int64_t)regs[r2];
5812 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5813 			}
5814 			break;
5815 
5816 		case DIF_OP_UDIV:
5817 			if (regs[r2] == 0) {
5818 				regs[rd] = 0;
5819 				*flags |= CPU_DTRACE_DIVZERO;
5820 			} else {
5821 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5822 				regs[rd] = regs[r1] / regs[r2];
5823 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5824 			}
5825 			break;
5826 
5827 		case DIF_OP_SREM:
5828 			if (regs[r2] == 0) {
5829 				regs[rd] = 0;
5830 				*flags |= CPU_DTRACE_DIVZERO;
5831 			} else {
5832 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5833 				regs[rd] = (int64_t)regs[r1] %
5834 				    (int64_t)regs[r2];
5835 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5836 			}
5837 			break;
5838 
5839 		case DIF_OP_UREM:
5840 			if (regs[r2] == 0) {
5841 				regs[rd] = 0;
5842 				*flags |= CPU_DTRACE_DIVZERO;
5843 			} else {
5844 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5845 				regs[rd] = regs[r1] % regs[r2];
5846 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5847 			}
5848 			break;
5849 
5850 		case DIF_OP_NOT:
5851 			regs[rd] = ~regs[r1];
5852 			break;
5853 		case DIF_OP_MOV:
5854 			regs[rd] = regs[r1];
5855 			break;
5856 		case DIF_OP_CMP:
5857 			cc_r = regs[r1] - regs[r2];
5858 			cc_n = cc_r < 0;
5859 			cc_z = cc_r == 0;
5860 			cc_v = 0;
5861 			cc_c = regs[r1] < regs[r2];
5862 			break;
5863 		case DIF_OP_TST:
5864 			cc_n = cc_v = cc_c = 0;
5865 			cc_z = regs[r1] == 0;
5866 			break;
5867 		case DIF_OP_BA:
5868 			pc = DIF_INSTR_LABEL(instr);
5869 			break;
5870 		case DIF_OP_BE:
5871 			if (cc_z)
5872 				pc = DIF_INSTR_LABEL(instr);
5873 			break;
5874 		case DIF_OP_BNE:
5875 			if (cc_z == 0)
5876 				pc = DIF_INSTR_LABEL(instr);
5877 			break;
5878 		case DIF_OP_BG:
5879 			if ((cc_z | (cc_n ^ cc_v)) == 0)
5880 				pc = DIF_INSTR_LABEL(instr);
5881 			break;
5882 		case DIF_OP_BGU:
5883 			if ((cc_c | cc_z) == 0)
5884 				pc = DIF_INSTR_LABEL(instr);
5885 			break;
5886 		case DIF_OP_BGE:
5887 			if ((cc_n ^ cc_v) == 0)
5888 				pc = DIF_INSTR_LABEL(instr);
5889 			break;
5890 		case DIF_OP_BGEU:
5891 			if (cc_c == 0)
5892 				pc = DIF_INSTR_LABEL(instr);
5893 			break;
5894 		case DIF_OP_BL:
5895 			if (cc_n ^ cc_v)
5896 				pc = DIF_INSTR_LABEL(instr);
5897 			break;
5898 		case DIF_OP_BLU:
5899 			if (cc_c)
5900 				pc = DIF_INSTR_LABEL(instr);
5901 			break;
5902 		case DIF_OP_BLE:
5903 			if (cc_z | (cc_n ^ cc_v))
5904 				pc = DIF_INSTR_LABEL(instr);
5905 			break;
5906 		case DIF_OP_BLEU:
5907 			if (cc_c | cc_z)
5908 				pc = DIF_INSTR_LABEL(instr);
5909 			break;
5910 		case DIF_OP_RLDSB:
5911 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5912 				break;
5913 			/*FALLTHROUGH*/
5914 		case DIF_OP_LDSB:
5915 			regs[rd] = (int8_t)dtrace_load8(regs[r1]);
5916 			break;
5917 		case DIF_OP_RLDSH:
5918 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5919 				break;
5920 			/*FALLTHROUGH*/
5921 		case DIF_OP_LDSH:
5922 			regs[rd] = (int16_t)dtrace_load16(regs[r1]);
5923 			break;
5924 		case DIF_OP_RLDSW:
5925 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5926 				break;
5927 			/*FALLTHROUGH*/
5928 		case DIF_OP_LDSW:
5929 			regs[rd] = (int32_t)dtrace_load32(regs[r1]);
5930 			break;
5931 		case DIF_OP_RLDUB:
5932 			if (!dtrace_canload(regs[r1], 1, mstate, vstate))
5933 				break;
5934 			/*FALLTHROUGH*/
5935 		case DIF_OP_LDUB:
5936 			regs[rd] = dtrace_load8(regs[r1]);
5937 			break;
5938 		case DIF_OP_RLDUH:
5939 			if (!dtrace_canload(regs[r1], 2, mstate, vstate))
5940 				break;
5941 			/*FALLTHROUGH*/
5942 		case DIF_OP_LDUH:
5943 			regs[rd] = dtrace_load16(regs[r1]);
5944 			break;
5945 		case DIF_OP_RLDUW:
5946 			if (!dtrace_canload(regs[r1], 4, mstate, vstate))
5947 				break;
5948 			/*FALLTHROUGH*/
5949 		case DIF_OP_LDUW:
5950 			regs[rd] = dtrace_load32(regs[r1]);
5951 			break;
5952 		case DIF_OP_RLDX:
5953 			if (!dtrace_canload(regs[r1], 8, mstate, vstate))
5954 				break;
5955 			/*FALLTHROUGH*/
5956 		case DIF_OP_LDX:
5957 			regs[rd] = dtrace_load64(regs[r1]);
5958 			break;
5959 		case DIF_OP_ULDSB:
5960 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5961 			regs[rd] = (int8_t)
5962 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5963 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5964 			break;
5965 		case DIF_OP_ULDSH:
5966 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5967 			regs[rd] = (int16_t)
5968 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5969 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5970 			break;
5971 		case DIF_OP_ULDSW:
5972 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5973 			regs[rd] = (int32_t)
5974 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5975 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5976 			break;
5977 		case DIF_OP_ULDUB:
5978 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5979 			regs[rd] =
5980 			    dtrace_fuword8((void *)(uintptr_t)regs[r1]);
5981 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5982 			break;
5983 		case DIF_OP_ULDUH:
5984 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5985 			regs[rd] =
5986 			    dtrace_fuword16((void *)(uintptr_t)regs[r1]);
5987 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5988 			break;
5989 		case DIF_OP_ULDUW:
5990 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5991 			regs[rd] =
5992 			    dtrace_fuword32((void *)(uintptr_t)regs[r1]);
5993 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
5994 			break;
5995 		case DIF_OP_ULDX:
5996 			DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
5997 			regs[rd] =
5998 			    dtrace_fuword64((void *)(uintptr_t)regs[r1]);
5999 			DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6000 			break;
6001 		case DIF_OP_RET:
6002 			rval = regs[rd];
6003 			pc = textlen;
6004 			break;
6005 		case DIF_OP_NOP:
6006 			break;
6007 		case DIF_OP_SETX:
6008 			regs[rd] = inttab[DIF_INSTR_INTEGER(instr)];
6009 			break;
6010 		case DIF_OP_SETS:
6011 			regs[rd] = (uint64_t)(uintptr_t)
6012 			    (strtab + DIF_INSTR_STRING(instr));
6013 			break;
6014 		case DIF_OP_SCMP: {
6015 			size_t sz = state->dts_options[DTRACEOPT_STRSIZE];
6016 			uintptr_t s1 = regs[r1];
6017 			uintptr_t s2 = regs[r2];
6018 			size_t lim1, lim2;
6019 
6020 			if (s1 != 0 &&
6021 			    !dtrace_strcanload(s1, sz, &lim1, mstate, vstate))
6022 				break;
6023 			if (s2 != 0 &&
6024 			    !dtrace_strcanload(s2, sz, &lim2, mstate, vstate))
6025 				break;
6026 
6027 			cc_r = dtrace_strncmp((char *)s1, (char *)s2,
6028 			    MIN(lim1, lim2));
6029 
6030 			cc_n = cc_r < 0;
6031 			cc_z = cc_r == 0;
6032 			cc_v = cc_c = 0;
6033 			break;
6034 		}
6035 		case DIF_OP_LDGA:
6036 			regs[rd] = dtrace_dif_variable(mstate, state,
6037 			    r1, regs[r2]);
6038 			break;
6039 		case DIF_OP_LDGS:
6040 			id = DIF_INSTR_VAR(instr);
6041 
6042 			if (id >= DIF_VAR_OTHER_UBASE) {
6043 				uintptr_t a;
6044 
6045 				id -= DIF_VAR_OTHER_UBASE;
6046 				svar = vstate->dtvs_globals[id];
6047 				ASSERT(svar != NULL);
6048 				v = &svar->dtsv_var;
6049 
6050 				if (!(v->dtdv_type.dtdt_flags & DIF_TF_BYREF)) {
6051 					regs[rd] = svar->dtsv_data;
6052 					break;
6053 				}
6054 
6055 				a = (uintptr_t)svar->dtsv_data;
6056 
6057 				if (*(uint8_t *)a == UINT8_MAX) {
6058 					/*
6059 					 * If the 0th byte is set to UINT8_MAX
6060 					 * then this is to be treated as a
6061 					 * reference to a NULL variable.
6062 					 */
6063 					regs[rd] = 0;
6064 				} else {
6065 					regs[rd] = a + sizeof (uint64_t);
6066 				}
6067 
6068 				break;
6069 			}
6070 
6071 			regs[rd] = dtrace_dif_variable(mstate, state, id, 0);
6072 			break;
6073 
6074 		case DIF_OP_STGA:
6075 			dtrace_dif_variable_write(mstate, state, r1, regs[r2],
6076 			    regs[rd]);
6077 			break;
6078 
6079 		case DIF_OP_STGS:
6080 			id = DIF_INSTR_VAR(instr);
6081 
6082 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6083 			id -= DIF_VAR_OTHER_UBASE;
6084 
6085 			VERIFY(id < vstate->dtvs_nglobals);
6086 			svar = vstate->dtvs_globals[id];
6087 			ASSERT(svar != NULL);
6088 			v = &svar->dtsv_var;
6089 
6090 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6091 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6092 				size_t lim;
6093 
6094 				ASSERT(a != (uintptr_t)NULL);
6095 				ASSERT(svar->dtsv_size != 0);
6096 
6097 				if (regs[rd] == 0) {
6098 					*(uint8_t *)a = UINT8_MAX;
6099 					break;
6100 				} else {
6101 					*(uint8_t *)a = 0;
6102 					a += sizeof (uint64_t);
6103 				}
6104 				if (!dtrace_vcanload(
6105 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6106 				    &lim, mstate, vstate))
6107 					break;
6108 
6109 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6110 				    (void *)a, &v->dtdv_type, lim);
6111 				break;
6112 			}
6113 
6114 			svar->dtsv_data = regs[rd];
6115 			break;
6116 
6117 		case DIF_OP_LDTA:
6118 			/*
6119 			 * There are no DTrace built-in thread-local arrays at
6120 			 * present.  This opcode is saved for future work.
6121 			 */
6122 			*flags |= CPU_DTRACE_ILLOP;
6123 			regs[rd] = 0;
6124 			break;
6125 
6126 		case DIF_OP_LDLS:
6127 			id = DIF_INSTR_VAR(instr);
6128 
6129 			if (id < DIF_VAR_OTHER_UBASE) {
6130 				/*
6131 				 * For now, this has no meaning.
6132 				 */
6133 				regs[rd] = 0;
6134 				break;
6135 			}
6136 
6137 			id -= DIF_VAR_OTHER_UBASE;
6138 
6139 			ASSERT(id < vstate->dtvs_nlocals);
6140 			ASSERT(vstate->dtvs_locals != NULL);
6141 
6142 			svar = vstate->dtvs_locals[id];
6143 			ASSERT(svar != NULL);
6144 			v = &svar->dtsv_var;
6145 
6146 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6147 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6148 				size_t sz = v->dtdv_type.dtdt_size;
6149 
6150 				sz += sizeof (uint64_t);
6151 				ASSERT(svar->dtsv_size == NCPU * sz);
6152 				a += CPU->cpu_id * sz;
6153 
6154 				if (*(uint8_t *)a == UINT8_MAX) {
6155 					/*
6156 					 * If the 0th byte is set to UINT8_MAX
6157 					 * then this is to be treated as a
6158 					 * reference to a NULL variable.
6159 					 */
6160 					regs[rd] = 0;
6161 				} else {
6162 					regs[rd] = a + sizeof (uint64_t);
6163 				}
6164 
6165 				break;
6166 			}
6167 
6168 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6169 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6170 			regs[rd] = tmp[CPU->cpu_id];
6171 			break;
6172 
6173 		case DIF_OP_STLS:
6174 			id = DIF_INSTR_VAR(instr);
6175 
6176 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6177 			id -= DIF_VAR_OTHER_UBASE;
6178 			VERIFY(id < vstate->dtvs_nlocals);
6179 
6180 			ASSERT(vstate->dtvs_locals != NULL);
6181 			svar = vstate->dtvs_locals[id];
6182 			ASSERT(svar != NULL);
6183 			v = &svar->dtsv_var;
6184 
6185 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6186 				uintptr_t a = (uintptr_t)svar->dtsv_data;
6187 				size_t sz = v->dtdv_type.dtdt_size;
6188 				size_t lim;
6189 
6190 				sz += sizeof (uint64_t);
6191 				ASSERT(svar->dtsv_size == NCPU * sz);
6192 				a += CPU->cpu_id * sz;
6193 
6194 				if (regs[rd] == 0) {
6195 					*(uint8_t *)a = UINT8_MAX;
6196 					break;
6197 				} else {
6198 					*(uint8_t *)a = 0;
6199 					a += sizeof (uint64_t);
6200 				}
6201 
6202 				if (!dtrace_vcanload(
6203 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6204 				    &lim, mstate, vstate))
6205 					break;
6206 
6207 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6208 				    (void *)a, &v->dtdv_type, lim);
6209 				break;
6210 			}
6211 
6212 			ASSERT(svar->dtsv_size == NCPU * sizeof (uint64_t));
6213 			tmp = (uint64_t *)(uintptr_t)svar->dtsv_data;
6214 			tmp[CPU->cpu_id] = regs[rd];
6215 			break;
6216 
6217 		case DIF_OP_LDTS: {
6218 			dtrace_dynvar_t *dvar;
6219 			dtrace_key_t *key;
6220 
6221 			id = DIF_INSTR_VAR(instr);
6222 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6223 			id -= DIF_VAR_OTHER_UBASE;
6224 			v = &vstate->dtvs_tlocals[id];
6225 
6226 			key = &tupregs[DIF_DTR_NREGS];
6227 			key[0].dttk_value = (uint64_t)id;
6228 			key[0].dttk_size = 0;
6229 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6230 			key[1].dttk_size = 0;
6231 
6232 			dvar = dtrace_dynvar(dstate, 2, key,
6233 			    sizeof (uint64_t), DTRACE_DYNVAR_NOALLOC,
6234 			    mstate, vstate);
6235 
6236 			if (dvar == NULL) {
6237 				regs[rd] = 0;
6238 				break;
6239 			}
6240 
6241 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6242 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6243 			} else {
6244 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6245 			}
6246 
6247 			break;
6248 		}
6249 
6250 		case DIF_OP_STTS: {
6251 			dtrace_dynvar_t *dvar;
6252 			dtrace_key_t *key;
6253 
6254 			id = DIF_INSTR_VAR(instr);
6255 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6256 			id -= DIF_VAR_OTHER_UBASE;
6257 			VERIFY(id < vstate->dtvs_ntlocals);
6258 
6259 			key = &tupregs[DIF_DTR_NREGS];
6260 			key[0].dttk_value = (uint64_t)id;
6261 			key[0].dttk_size = 0;
6262 			DTRACE_TLS_THRKEY(key[1].dttk_value);
6263 			key[1].dttk_size = 0;
6264 			v = &vstate->dtvs_tlocals[id];
6265 
6266 			dvar = dtrace_dynvar(dstate, 2, key,
6267 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6268 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6269 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6270 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6271 
6272 			/*
6273 			 * Given that we're storing to thread-local data,
6274 			 * we need to flush our predicate cache.
6275 			 */
6276 			curthread->t_predcache = DTRACE_CACHEIDNONE;
6277 
6278 			if (dvar == NULL)
6279 				break;
6280 
6281 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6282 				size_t lim;
6283 
6284 				if (!dtrace_vcanload(
6285 				    (void *)(uintptr_t)regs[rd],
6286 				    &v->dtdv_type, &lim, mstate, vstate))
6287 					break;
6288 
6289 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6290 				    dvar->dtdv_data, &v->dtdv_type, lim);
6291 			} else {
6292 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6293 			}
6294 
6295 			break;
6296 		}
6297 
6298 		case DIF_OP_SRA:
6299 			regs[rd] = (int64_t)regs[r1] >> regs[r2];
6300 			break;
6301 
6302 		case DIF_OP_CALL:
6303 			dtrace_dif_subr(DIF_INSTR_SUBR(instr), rd,
6304 			    regs, tupregs, ttop, mstate, state);
6305 			break;
6306 
6307 		case DIF_OP_PUSHTR:
6308 			if (ttop == DIF_DTR_NREGS) {
6309 				*flags |= CPU_DTRACE_TUPOFLOW;
6310 				break;
6311 			}
6312 
6313 			if (r1 == DIF_TYPE_STRING) {
6314 				/*
6315 				 * If this is a string type and the size is 0,
6316 				 * we'll use the system-wide default string
6317 				 * size.  Note that we are _not_ looking at
6318 				 * the value of the DTRACEOPT_STRSIZE option;
6319 				 * had this been set, we would expect to have
6320 				 * a non-zero size value in the "pushtr".
6321 				 */
6322 				tupregs[ttop].dttk_size =
6323 				    dtrace_strlen((char *)(uintptr_t)regs[rd],
6324 				    regs[r2] ? regs[r2] :
6325 				    dtrace_strsize_default) + 1;
6326 			} else {
6327 				if (regs[r2] > LONG_MAX) {
6328 					*flags |= CPU_DTRACE_ILLOP;
6329 					break;
6330 				}
6331 
6332 				tupregs[ttop].dttk_size = regs[r2];
6333 			}
6334 
6335 			tupregs[ttop++].dttk_value = regs[rd];
6336 			break;
6337 
6338 		case DIF_OP_PUSHTV:
6339 			if (ttop == DIF_DTR_NREGS) {
6340 				*flags |= CPU_DTRACE_TUPOFLOW;
6341 				break;
6342 			}
6343 
6344 			tupregs[ttop].dttk_value = regs[rd];
6345 			tupregs[ttop++].dttk_size = 0;
6346 			break;
6347 
6348 		case DIF_OP_POPTS:
6349 			if (ttop != 0)
6350 				ttop--;
6351 			break;
6352 
6353 		case DIF_OP_FLUSHTS:
6354 			ttop = 0;
6355 			break;
6356 
6357 		case DIF_OP_LDGAA:
6358 		case DIF_OP_LDTAA: {
6359 			dtrace_dynvar_t *dvar;
6360 			dtrace_key_t *key = tupregs;
6361 			uint_t nkeys = ttop;
6362 
6363 			id = DIF_INSTR_VAR(instr);
6364 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6365 			id -= DIF_VAR_OTHER_UBASE;
6366 
6367 			key[nkeys].dttk_value = (uint64_t)id;
6368 			key[nkeys++].dttk_size = 0;
6369 
6370 			if (DIF_INSTR_OP(instr) == DIF_OP_LDTAA) {
6371 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6372 				key[nkeys++].dttk_size = 0;
6373 				VERIFY(id < vstate->dtvs_ntlocals);
6374 				v = &vstate->dtvs_tlocals[id];
6375 			} else {
6376 				VERIFY(id < vstate->dtvs_nglobals);
6377 				v = &vstate->dtvs_globals[id]->dtsv_var;
6378 			}
6379 
6380 			dvar = dtrace_dynvar(dstate, nkeys, key,
6381 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6382 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6383 			    DTRACE_DYNVAR_NOALLOC, mstate, vstate);
6384 
6385 			if (dvar == NULL) {
6386 				regs[rd] = 0;
6387 				break;
6388 			}
6389 
6390 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6391 				regs[rd] = (uint64_t)(uintptr_t)dvar->dtdv_data;
6392 			} else {
6393 				regs[rd] = *((uint64_t *)dvar->dtdv_data);
6394 			}
6395 
6396 			break;
6397 		}
6398 
6399 		case DIF_OP_STGAA:
6400 		case DIF_OP_STTAA: {
6401 			dtrace_dynvar_t *dvar;
6402 			dtrace_key_t *key = tupregs;
6403 			uint_t nkeys = ttop;
6404 
6405 			id = DIF_INSTR_VAR(instr);
6406 			ASSERT(id >= DIF_VAR_OTHER_UBASE);
6407 			id -= DIF_VAR_OTHER_UBASE;
6408 
6409 			key[nkeys].dttk_value = (uint64_t)id;
6410 			key[nkeys++].dttk_size = 0;
6411 
6412 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA) {
6413 				DTRACE_TLS_THRKEY(key[nkeys].dttk_value);
6414 				key[nkeys++].dttk_size = 0;
6415 				VERIFY(id < vstate->dtvs_ntlocals);
6416 				v = &vstate->dtvs_tlocals[id];
6417 			} else {
6418 				VERIFY(id < vstate->dtvs_nglobals);
6419 				v = &vstate->dtvs_globals[id]->dtsv_var;
6420 			}
6421 
6422 			dvar = dtrace_dynvar(dstate, nkeys, key,
6423 			    v->dtdv_type.dtdt_size > sizeof (uint64_t) ?
6424 			    v->dtdv_type.dtdt_size : sizeof (uint64_t),
6425 			    regs[rd] ? DTRACE_DYNVAR_ALLOC :
6426 			    DTRACE_DYNVAR_DEALLOC, mstate, vstate);
6427 
6428 			if (dvar == NULL)
6429 				break;
6430 
6431 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF) {
6432 				size_t lim;
6433 
6434 				if (!dtrace_vcanload(
6435 				    (void *)(uintptr_t)regs[rd], &v->dtdv_type,
6436 				    &lim, mstate, vstate))
6437 					break;
6438 
6439 				dtrace_vcopy((void *)(uintptr_t)regs[rd],
6440 				    dvar->dtdv_data, &v->dtdv_type, lim);
6441 			} else {
6442 				*((uint64_t *)dvar->dtdv_data) = regs[rd];
6443 			}
6444 
6445 			break;
6446 		}
6447 
6448 		case DIF_OP_ALLOCS: {
6449 			uintptr_t ptr = P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6450 			size_t size = ptr - mstate->dtms_scratch_ptr + regs[r1];
6451 
6452 			/*
6453 			 * Rounding up the user allocation size could have
6454 			 * overflowed large, bogus allocations (like -1ULL) to
6455 			 * 0.
6456 			 */
6457 			if (size < regs[r1] ||
6458 			    !DTRACE_INSCRATCH(mstate, size)) {
6459 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6460 				regs[rd] = 0;
6461 				break;
6462 			}
6463 
6464 			dtrace_bzero((void *) mstate->dtms_scratch_ptr, size);
6465 			mstate->dtms_scratch_ptr += size;
6466 			regs[rd] = ptr;
6467 			break;
6468 		}
6469 
6470 		case DIF_OP_COPYS:
6471 			if (!dtrace_canstore(regs[rd], regs[r2],
6472 			    mstate, vstate)) {
6473 				*flags |= CPU_DTRACE_BADADDR;
6474 				*illval = regs[rd];
6475 				break;
6476 			}
6477 
6478 			if (!dtrace_canload(regs[r1], regs[r2], mstate, vstate))
6479 				break;
6480 
6481 			dtrace_bcopy((void *)(uintptr_t)regs[r1],
6482 			    (void *)(uintptr_t)regs[rd], (size_t)regs[r2]);
6483 			break;
6484 
6485 		case DIF_OP_STB:
6486 			if (!dtrace_canstore(regs[rd], 1, mstate, vstate)) {
6487 				*flags |= CPU_DTRACE_BADADDR;
6488 				*illval = regs[rd];
6489 				break;
6490 			}
6491 			*((uint8_t *)(uintptr_t)regs[rd]) = (uint8_t)regs[r1];
6492 			break;
6493 
6494 		case DIF_OP_STH:
6495 			if (!dtrace_canstore(regs[rd], 2, mstate, vstate)) {
6496 				*flags |= CPU_DTRACE_BADADDR;
6497 				*illval = regs[rd];
6498 				break;
6499 			}
6500 			if (regs[rd] & 1) {
6501 				*flags |= CPU_DTRACE_BADALIGN;
6502 				*illval = regs[rd];
6503 				break;
6504 			}
6505 			*((uint16_t *)(uintptr_t)regs[rd]) = (uint16_t)regs[r1];
6506 			break;
6507 
6508 		case DIF_OP_STW:
6509 			if (!dtrace_canstore(regs[rd], 4, mstate, vstate)) {
6510 				*flags |= CPU_DTRACE_BADADDR;
6511 				*illval = regs[rd];
6512 				break;
6513 			}
6514 			if (regs[rd] & 3) {
6515 				*flags |= CPU_DTRACE_BADALIGN;
6516 				*illval = regs[rd];
6517 				break;
6518 			}
6519 			*((uint32_t *)(uintptr_t)regs[rd]) = (uint32_t)regs[r1];
6520 			break;
6521 
6522 		case DIF_OP_STX:
6523 			if (!dtrace_canstore(regs[rd], 8, mstate, vstate)) {
6524 				*flags |= CPU_DTRACE_BADADDR;
6525 				*illval = regs[rd];
6526 				break;
6527 			}
6528 			if (regs[rd] & 7) {
6529 				*flags |= CPU_DTRACE_BADALIGN;
6530 				*illval = regs[rd];
6531 				break;
6532 			}
6533 			*((uint64_t *)(uintptr_t)regs[rd]) = regs[r1];
6534 			break;
6535 		}
6536 	}
6537 
6538 	if (!(*flags & CPU_DTRACE_FAULT))
6539 		return (rval);
6540 
6541 	mstate->dtms_fltoffs = opc * sizeof (dif_instr_t);
6542 	mstate->dtms_present |= DTRACE_MSTATE_FLTOFFS;
6543 
6544 	return (0);
6545 }
6546 
6547 static void
6548 dtrace_action_breakpoint(dtrace_ecb_t *ecb)
6549 {
6550 	dtrace_probe_t *probe = ecb->dte_probe;
6551 	dtrace_provider_t *prov = probe->dtpr_provider;
6552 	char c[DTRACE_FULLNAMELEN + 80], *str;
6553 	char *msg = "dtrace: breakpoint action at probe ";
6554 	char *ecbmsg = " (ecb ";
6555 	uintptr_t mask = (0xf << (sizeof (uintptr_t) * NBBY / 4));
6556 	uintptr_t val = (uintptr_t)ecb;
6557 	int shift = (sizeof (uintptr_t) * NBBY) - 4, i = 0;
6558 
6559 	if (dtrace_destructive_disallow)
6560 		return;
6561 
6562 	/*
6563 	 * It's impossible to be taking action on the NULL probe.
6564 	 */
6565 	ASSERT(probe != NULL);
6566 
6567 	/*
6568 	 * This is a poor man's (destitute man's?) sprintf():  we want to
6569 	 * print the provider name, module name, function name and name of
6570 	 * the probe, along with the hex address of the ECB with the breakpoint
6571 	 * action -- all of which we must place in the character buffer by
6572 	 * hand.
6573 	 */
6574 	while (*msg != '\0')
6575 		c[i++] = *msg++;
6576 
6577 	for (str = prov->dtpv_name; *str != '\0'; str++)
6578 		c[i++] = *str;
6579 	c[i++] = ':';
6580 
6581 	for (str = probe->dtpr_mod; *str != '\0'; str++)
6582 		c[i++] = *str;
6583 	c[i++] = ':';
6584 
6585 	for (str = probe->dtpr_func; *str != '\0'; str++)
6586 		c[i++] = *str;
6587 	c[i++] = ':';
6588 
6589 	for (str = probe->dtpr_name; *str != '\0'; str++)
6590 		c[i++] = *str;
6591 
6592 	while (*ecbmsg != '\0')
6593 		c[i++] = *ecbmsg++;
6594 
6595 	while (shift >= 0) {
6596 		mask = (uintptr_t)0xf << shift;
6597 
6598 		if (val >= ((uintptr_t)1 << shift))
6599 			c[i++] = "0123456789abcdef"[(val & mask) >> shift];
6600 		shift -= 4;
6601 	}
6602 
6603 	c[i++] = ')';
6604 	c[i] = '\0';
6605 
6606 	debug_enter(c);
6607 }
6608 
6609 static void
6610 dtrace_action_panic(dtrace_ecb_t *ecb)
6611 {
6612 	dtrace_probe_t *probe = ecb->dte_probe;
6613 
6614 	/*
6615 	 * It's impossible to be taking action on the NULL probe.
6616 	 */
6617 	ASSERT(probe != NULL);
6618 
6619 	if (dtrace_destructive_disallow)
6620 		return;
6621 
6622 	if (dtrace_panicked != NULL)
6623 		return;
6624 
6625 	if (dtrace_casptr(&dtrace_panicked, NULL, curthread) != NULL)
6626 		return;
6627 
6628 	/*
6629 	 * We won the right to panic.  (We want to be sure that only one
6630 	 * thread calls panic() from dtrace_probe(), and that panic() is
6631 	 * called exactly once.)
6632 	 */
6633 	dtrace_panic("dtrace: panic action at probe %s:%s:%s:%s (ecb %p)",
6634 	    probe->dtpr_provider->dtpv_name, probe->dtpr_mod,
6635 	    probe->dtpr_func, probe->dtpr_name, (void *)ecb);
6636 }
6637 
6638 static void
6639 dtrace_action_raise(uint64_t sig)
6640 {
6641 	if (dtrace_destructive_disallow)
6642 		return;
6643 
6644 	if (sig >= NSIG) {
6645 		DTRACE_CPUFLAG_SET(CPU_DTRACE_ILLOP);
6646 		return;
6647 	}
6648 
6649 	/*
6650 	 * raise() has a queue depth of 1 -- we ignore all subsequent
6651 	 * invocations of the raise() action.
6652 	 */
6653 	if (curthread->t_dtrace_sig == 0)
6654 		curthread->t_dtrace_sig = (uint8_t)sig;
6655 
6656 	curthread->t_sig_check = 1;
6657 	aston(curthread);
6658 }
6659 
6660 static void
6661 dtrace_action_stop(void)
6662 {
6663 	if (dtrace_destructive_disallow)
6664 		return;
6665 
6666 	if (!curthread->t_dtrace_stop) {
6667 		curthread->t_dtrace_stop = 1;
6668 		curthread->t_sig_check = 1;
6669 		aston(curthread);
6670 	}
6671 }
6672 
6673 static void
6674 dtrace_action_chill(dtrace_mstate_t *mstate, hrtime_t val)
6675 {
6676 	hrtime_t now;
6677 	volatile uint16_t *flags;
6678 	cpu_t *cpu = CPU;
6679 
6680 	if (dtrace_destructive_disallow)
6681 		return;
6682 
6683 	flags = (volatile uint16_t *)&cpu_core[cpu->cpu_id].cpuc_dtrace_flags;
6684 
6685 	now = dtrace_gethrtime();
6686 
6687 	if (now - cpu->cpu_dtrace_chillmark > dtrace_chill_interval) {
6688 		/*
6689 		 * We need to advance the mark to the current time.
6690 		 */
6691 		cpu->cpu_dtrace_chillmark = now;
6692 		cpu->cpu_dtrace_chilled = 0;
6693 	}
6694 
6695 	/*
6696 	 * Now check to see if the requested chill time would take us over
6697 	 * the maximum amount of time allowed in the chill interval.  (Or
6698 	 * worse, if the calculation itself induces overflow.)
6699 	 */
6700 	if (cpu->cpu_dtrace_chilled + val > dtrace_chill_max ||
6701 	    cpu->cpu_dtrace_chilled + val < cpu->cpu_dtrace_chilled) {
6702 		*flags |= CPU_DTRACE_ILLOP;
6703 		return;
6704 	}
6705 
6706 	while (dtrace_gethrtime() - now < val)
6707 		continue;
6708 
6709 	/*
6710 	 * Normally, we assure that the value of the variable "timestamp" does
6711 	 * not change within an ECB.  The presence of chill() represents an
6712 	 * exception to this rule, however.
6713 	 */
6714 	mstate->dtms_present &= ~DTRACE_MSTATE_TIMESTAMP;
6715 	cpu->cpu_dtrace_chilled += val;
6716 }
6717 
6718 static void
6719 dtrace_action_ustack(dtrace_mstate_t *mstate, dtrace_state_t *state,
6720     uint64_t *buf, uint64_t arg)
6721 {
6722 	int nframes = DTRACE_USTACK_NFRAMES(arg);
6723 	int strsize = DTRACE_USTACK_STRSIZE(arg);
6724 	uint64_t *pcs = &buf[1], *fps;
6725 	char *str = (char *)&pcs[nframes];
6726 	int size, offs = 0, i, j;
6727 	size_t rem;
6728 	uintptr_t old = mstate->dtms_scratch_ptr, saved;
6729 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6730 	char *sym;
6731 
6732 	/*
6733 	 * Should be taking a faster path if string space has not been
6734 	 * allocated.
6735 	 */
6736 	ASSERT(strsize != 0);
6737 
6738 	/*
6739 	 * We will first allocate some temporary space for the frame pointers.
6740 	 */
6741 	fps = (uint64_t *)P2ROUNDUP(mstate->dtms_scratch_ptr, 8);
6742 	size = (uintptr_t)fps - mstate->dtms_scratch_ptr +
6743 	    (nframes * sizeof (uint64_t));
6744 
6745 	if (!DTRACE_INSCRATCH(mstate, size)) {
6746 		/*
6747 		 * Not enough room for our frame pointers -- need to indicate
6748 		 * that we ran out of scratch space.
6749 		 */
6750 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOSCRATCH);
6751 		return;
6752 	}
6753 
6754 	mstate->dtms_scratch_ptr += size;
6755 	saved = mstate->dtms_scratch_ptr;
6756 
6757 	/*
6758 	 * Now get a stack with both program counters and frame pointers.
6759 	 */
6760 	DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6761 	dtrace_getufpstack(buf, fps, nframes + 1);
6762 	DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6763 
6764 	/*
6765 	 * If that faulted, we're cooked.
6766 	 */
6767 	if (*flags & CPU_DTRACE_FAULT)
6768 		goto out;
6769 
6770 	/*
6771 	 * Now we want to walk up the stack, calling the USTACK helper.  For
6772 	 * each iteration, we restore the scratch pointer.
6773 	 */
6774 	for (i = 0; i < nframes; i++) {
6775 		mstate->dtms_scratch_ptr = saved;
6776 
6777 		if (offs >= strsize)
6778 			break;
6779 
6780 		sym = (char *)(uintptr_t)dtrace_helper(
6781 		    DTRACE_HELPER_ACTION_USTACK,
6782 		    mstate, state, pcs[i], fps[i]);
6783 
6784 		/*
6785 		 * If we faulted while running the helper, we're going to
6786 		 * clear the fault and null out the corresponding string.
6787 		 */
6788 		if (*flags & CPU_DTRACE_FAULT) {
6789 			*flags &= ~CPU_DTRACE_FAULT;
6790 			str[offs++] = '\0';
6791 			continue;
6792 		}
6793 
6794 		if (sym == NULL) {
6795 			str[offs++] = '\0';
6796 			continue;
6797 		}
6798 
6799 		if (!dtrace_strcanload((uintptr_t)sym, strsize, &rem, mstate,
6800 		    &(state->dts_vstate))) {
6801 			str[offs++] = '\0';
6802 			continue;
6803 		}
6804 
6805 		DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6806 
6807 		/*
6808 		 * Now copy in the string that the helper returned to us.
6809 		 */
6810 		for (j = 0; offs + j < strsize && j < rem; j++) {
6811 			if ((str[offs + j] = sym[j]) == '\0')
6812 				break;
6813 		}
6814 
6815 		DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6816 
6817 		offs += j + 1;
6818 	}
6819 
6820 	if (offs >= strsize) {
6821 		/*
6822 		 * If we didn't have room for all of the strings, we don't
6823 		 * abort processing -- this needn't be a fatal error -- but we
6824 		 * still want to increment a counter (dts_stkstroverflows) to
6825 		 * allow this condition to be warned about.  (If this is from
6826 		 * a jstack() action, it is easily tuned via jstackstrsize.)
6827 		 */
6828 		dtrace_error(&state->dts_stkstroverflows);
6829 	}
6830 
6831 	while (offs < strsize)
6832 		str[offs++] = '\0';
6833 
6834 out:
6835 	mstate->dtms_scratch_ptr = old;
6836 }
6837 
6838 static void
6839 dtrace_store_by_ref(dtrace_difo_t *dp, caddr_t tomax, size_t size,
6840     size_t *valoffsp, uint64_t *valp, uint64_t end, int intuple, int dtkind)
6841 {
6842 	volatile uint16_t *flags;
6843 	uint64_t val = *valp;
6844 	size_t valoffs = *valoffsp;
6845 
6846 	flags = (volatile uint16_t *)&cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
6847 	ASSERT(dtkind == DIF_TF_BYREF || dtkind == DIF_TF_BYUREF);
6848 
6849 	/*
6850 	 * If this is a string, we're going to only load until we find the zero
6851 	 * byte -- after which we'll store zero bytes.
6852 	 */
6853 	if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
6854 		char c = '\0' + 1;
6855 		size_t s;
6856 
6857 		for (s = 0; s < size; s++) {
6858 			if (c != '\0' && dtkind == DIF_TF_BYREF) {
6859 				c = dtrace_load8(val++);
6860 			} else if (c != '\0' && dtkind == DIF_TF_BYUREF) {
6861 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6862 				c = dtrace_fuword8((void *)(uintptr_t)val++);
6863 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6864 				if (*flags & CPU_DTRACE_FAULT)
6865 					break;
6866 			}
6867 
6868 			DTRACE_STORE(uint8_t, tomax, valoffs++, c);
6869 
6870 			if (c == '\0' && intuple)
6871 				break;
6872 		}
6873 	} else {
6874 		uint8_t c;
6875 		while (valoffs < end) {
6876 			if (dtkind == DIF_TF_BYREF) {
6877 				c = dtrace_load8(val++);
6878 			} else if (dtkind == DIF_TF_BYUREF) {
6879 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
6880 				c = dtrace_fuword8((void *)(uintptr_t)val++);
6881 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
6882 				if (*flags & CPU_DTRACE_FAULT)
6883 					break;
6884 			}
6885 
6886 			DTRACE_STORE(uint8_t, tomax,
6887 			    valoffs++, c);
6888 		}
6889 	}
6890 
6891 	*valp = val;
6892 	*valoffsp = valoffs;
6893 }
6894 
6895 /*
6896  * If you're looking for the epicenter of DTrace, you just found it.  This
6897  * is the function called by the provider to fire a probe -- from which all
6898  * subsequent probe-context DTrace activity emanates.
6899  */
6900 void
6901 dtrace_probe(dtrace_id_t id, uintptr_t arg0, uintptr_t arg1,
6902     uintptr_t arg2, uintptr_t arg3, uintptr_t arg4)
6903 {
6904 	processorid_t cpuid;
6905 	dtrace_icookie_t cookie;
6906 	dtrace_probe_t *probe;
6907 	dtrace_mstate_t mstate;
6908 	dtrace_ecb_t *ecb;
6909 	dtrace_action_t *act;
6910 	intptr_t offs;
6911 	size_t size;
6912 	int vtime, onintr;
6913 	volatile uint16_t *flags;
6914 	hrtime_t now, end;
6915 
6916 	/*
6917 	 * Kick out immediately if this CPU is still being born (in which case
6918 	 * curthread will be set to -1) or the current thread can't allow
6919 	 * probes in its current context.
6920 	 */
6921 	if (((uintptr_t)curthread & 1) || (curthread->t_flag & T_DONTDTRACE))
6922 		return;
6923 
6924 	cookie = dtrace_interrupt_disable();
6925 
6926 	/*
6927 	 * Also refuse to process any probe firings that might happen on a
6928 	 * disabled CPU.
6929 	 */
6930 	if (CPU->cpu_flags & CPU_DISABLED) {
6931 		dtrace_interrupt_enable(cookie);
6932 		return;
6933 	}
6934 
6935 	probe = dtrace_probes[id - 1];
6936 	cpuid = CPU->cpu_id;
6937 	onintr = CPU_ON_INTR(CPU);
6938 
6939 	CPU->cpu_dtrace_probes++;
6940 
6941 	if (!onintr && probe->dtpr_predcache != DTRACE_CACHEIDNONE &&
6942 	    probe->dtpr_predcache == curthread->t_predcache) {
6943 		/*
6944 		 * We have hit in the predicate cache; we know that
6945 		 * this predicate would evaluate to be false.
6946 		 */
6947 		dtrace_interrupt_enable(cookie);
6948 		return;
6949 	}
6950 
6951 	if (panic_quiesce) {
6952 		/*
6953 		 * We don't trace anything if we're panicking.
6954 		 */
6955 		dtrace_interrupt_enable(cookie);
6956 		return;
6957 	}
6958 
6959 	now = mstate.dtms_timestamp = dtrace_gethrtime();
6960 	mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
6961 	vtime = dtrace_vtime_references != 0;
6962 
6963 	if (vtime && curthread->t_dtrace_start)
6964 		curthread->t_dtrace_vtime += now - curthread->t_dtrace_start;
6965 
6966 	mstate.dtms_difo = NULL;
6967 	mstate.dtms_probe = probe;
6968 	mstate.dtms_strtok = 0;
6969 	mstate.dtms_arg[0] = arg0;
6970 	mstate.dtms_arg[1] = arg1;
6971 	mstate.dtms_arg[2] = arg2;
6972 	mstate.dtms_arg[3] = arg3;
6973 	mstate.dtms_arg[4] = arg4;
6974 
6975 	flags = (volatile uint16_t *)&cpu_core[cpuid].cpuc_dtrace_flags;
6976 
6977 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
6978 		dtrace_predicate_t *pred = ecb->dte_predicate;
6979 		dtrace_state_t *state = ecb->dte_state;
6980 		dtrace_buffer_t *buf = &state->dts_buffer[cpuid];
6981 		dtrace_buffer_t *aggbuf = &state->dts_aggbuffer[cpuid];
6982 		dtrace_vstate_t *vstate = &state->dts_vstate;
6983 		dtrace_provider_t *prov = probe->dtpr_provider;
6984 		uint64_t tracememsize = 0;
6985 		int committed = 0;
6986 		caddr_t tomax;
6987 
6988 		/*
6989 		 * A little subtlety with the following (seemingly innocuous)
6990 		 * declaration of the automatic 'val':  by looking at the
6991 		 * code, you might think that it could be declared in the
6992 		 * action processing loop, below.  (That is, it's only used in
6993 		 * the action processing loop.)  However, it must be declared
6994 		 * out of that scope because in the case of DIF expression
6995 		 * arguments to aggregating actions, one iteration of the
6996 		 * action loop will use the last iteration's value.
6997 		 */
6998 #ifdef lint
6999 		uint64_t val = 0;
7000 #else
7001 		uint64_t val;
7002 #endif
7003 
7004 		mstate.dtms_present = DTRACE_MSTATE_ARGS | DTRACE_MSTATE_PROBE;
7005 		mstate.dtms_access = DTRACE_ACCESS_ARGS | DTRACE_ACCESS_PROC;
7006 		mstate.dtms_getf = NULL;
7007 
7008 		*flags &= ~CPU_DTRACE_ERROR;
7009 
7010 		if (prov == dtrace_provider) {
7011 			/*
7012 			 * If dtrace itself is the provider of this probe,
7013 			 * we're only going to continue processing the ECB if
7014 			 * arg0 (the dtrace_state_t) is equal to the ECB's
7015 			 * creating state.  (This prevents disjoint consumers
7016 			 * from seeing one another's metaprobes.)
7017 			 */
7018 			if (arg0 != (uint64_t)(uintptr_t)state)
7019 				continue;
7020 		}
7021 
7022 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE) {
7023 			/*
7024 			 * We're not currently active.  If our provider isn't
7025 			 * the dtrace pseudo provider, we're not interested.
7026 			 */
7027 			if (prov != dtrace_provider)
7028 				continue;
7029 
7030 			/*
7031 			 * Now we must further check if we are in the BEGIN
7032 			 * probe.  If we are, we will only continue processing
7033 			 * if we're still in WARMUP -- if one BEGIN enabling
7034 			 * has invoked the exit() action, we don't want to
7035 			 * evaluate subsequent BEGIN enablings.
7036 			 */
7037 			if (probe->dtpr_id == dtrace_probeid_begin &&
7038 			    state->dts_activity != DTRACE_ACTIVITY_WARMUP) {
7039 				ASSERT(state->dts_activity ==
7040 				    DTRACE_ACTIVITY_DRAINING);
7041 				continue;
7042 			}
7043 		}
7044 
7045 		if (ecb->dte_cond && !dtrace_priv_probe(state, &mstate, ecb))
7046 			continue;
7047 
7048 		if (now - state->dts_alive > dtrace_deadman_timeout) {
7049 			/*
7050 			 * We seem to be dead.  Unless we (a) have kernel
7051 			 * destructive permissions (b) have explicitly enabled
7052 			 * destructive actions and (c) destructive actions have
7053 			 * not been disabled, we're going to transition into
7054 			 * the KILLED state, from which no further processing
7055 			 * on this state will be performed.
7056 			 */
7057 			if (!dtrace_priv_kernel_destructive(state) ||
7058 			    !state->dts_cred.dcr_destructive ||
7059 			    dtrace_destructive_disallow) {
7060 				void *activity = &state->dts_activity;
7061 				dtrace_activity_t current;
7062 
7063 				do {
7064 					current = state->dts_activity;
7065 				} while (dtrace_cas32(activity, current,
7066 				    DTRACE_ACTIVITY_KILLED) != current);
7067 
7068 				continue;
7069 			}
7070 		}
7071 
7072 		if ((offs = dtrace_buffer_reserve(buf, ecb->dte_needed,
7073 		    ecb->dte_alignment, state, &mstate)) < 0)
7074 			continue;
7075 
7076 		tomax = buf->dtb_tomax;
7077 		ASSERT(tomax != NULL);
7078 
7079 		if (ecb->dte_size != 0) {
7080 			dtrace_rechdr_t dtrh;
7081 			if (!(mstate.dtms_present & DTRACE_MSTATE_TIMESTAMP)) {
7082 				mstate.dtms_timestamp = dtrace_gethrtime();
7083 				mstate.dtms_present |= DTRACE_MSTATE_TIMESTAMP;
7084 			}
7085 			ASSERT3U(ecb->dte_size, >=, sizeof (dtrace_rechdr_t));
7086 			dtrh.dtrh_epid = ecb->dte_epid;
7087 			DTRACE_RECORD_STORE_TIMESTAMP(&dtrh,
7088 			    mstate.dtms_timestamp);
7089 			*((dtrace_rechdr_t *)(tomax + offs)) = dtrh;
7090 		}
7091 
7092 		mstate.dtms_epid = ecb->dte_epid;
7093 		mstate.dtms_present |= DTRACE_MSTATE_EPID;
7094 
7095 		if (state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)
7096 			mstate.dtms_access |= DTRACE_ACCESS_KERNEL;
7097 
7098 		if (pred != NULL) {
7099 			dtrace_difo_t *dp = pred->dtp_difo;
7100 			int rval;
7101 
7102 			rval = dtrace_dif_emulate(dp, &mstate, vstate, state);
7103 
7104 			if (!(*flags & CPU_DTRACE_ERROR) && !rval) {
7105 				dtrace_cacheid_t cid = probe->dtpr_predcache;
7106 
7107 				if (cid != DTRACE_CACHEIDNONE && !onintr) {
7108 					/*
7109 					 * Update the predicate cache...
7110 					 */
7111 					ASSERT(cid == pred->dtp_cacheid);
7112 					curthread->t_predcache = cid;
7113 				}
7114 
7115 				continue;
7116 			}
7117 		}
7118 
7119 		for (act = ecb->dte_action; !(*flags & CPU_DTRACE_ERROR) &&
7120 		    act != NULL; act = act->dta_next) {
7121 			size_t valoffs;
7122 			dtrace_difo_t *dp;
7123 			dtrace_recdesc_t *rec = &act->dta_rec;
7124 
7125 			size = rec->dtrd_size;
7126 			valoffs = offs + rec->dtrd_offset;
7127 
7128 			if (DTRACEACT_ISAGG(act->dta_kind)) {
7129 				uint64_t v = 0xbad;
7130 				dtrace_aggregation_t *agg;
7131 
7132 				agg = (dtrace_aggregation_t *)act;
7133 
7134 				if ((dp = act->dta_difo) != NULL)
7135 					v = dtrace_dif_emulate(dp,
7136 					    &mstate, vstate, state);
7137 
7138 				if (*flags & CPU_DTRACE_ERROR)
7139 					continue;
7140 
7141 				/*
7142 				 * Note that we always pass the expression
7143 				 * value from the previous iteration of the
7144 				 * action loop.  This value will only be used
7145 				 * if there is an expression argument to the
7146 				 * aggregating action, denoted by the
7147 				 * dtag_hasarg field.
7148 				 */
7149 				dtrace_aggregate(agg, buf,
7150 				    offs, aggbuf, v, val);
7151 				continue;
7152 			}
7153 
7154 			switch (act->dta_kind) {
7155 			case DTRACEACT_STOP:
7156 				if (dtrace_priv_proc_destructive(state,
7157 				    &mstate))
7158 					dtrace_action_stop();
7159 				continue;
7160 
7161 			case DTRACEACT_BREAKPOINT:
7162 				if (dtrace_priv_kernel_destructive(state))
7163 					dtrace_action_breakpoint(ecb);
7164 				continue;
7165 
7166 			case DTRACEACT_PANIC:
7167 				if (dtrace_priv_kernel_destructive(state))
7168 					dtrace_action_panic(ecb);
7169 				continue;
7170 
7171 			case DTRACEACT_STACK:
7172 				if (!dtrace_priv_kernel(state))
7173 					continue;
7174 
7175 				dtrace_getpcstack((pc_t *)(tomax + valoffs),
7176 				    size / sizeof (pc_t), probe->dtpr_aframes,
7177 				    DTRACE_ANCHORED(probe) ? NULL :
7178 				    (uint32_t *)arg0);
7179 
7180 				continue;
7181 
7182 			case DTRACEACT_JSTACK:
7183 			case DTRACEACT_USTACK:
7184 				if (!dtrace_priv_proc(state, &mstate))
7185 					continue;
7186 
7187 				/*
7188 				 * See comment in DIF_VAR_PID.
7189 				 */
7190 				if (DTRACE_ANCHORED(mstate.dtms_probe) &&
7191 				    CPU_ON_INTR(CPU)) {
7192 					int depth = DTRACE_USTACK_NFRAMES(
7193 					    rec->dtrd_arg) + 1;
7194 
7195 					dtrace_bzero((void *)(tomax + valoffs),
7196 					    DTRACE_USTACK_STRSIZE(rec->dtrd_arg)
7197 					    + depth * sizeof (uint64_t));
7198 
7199 					continue;
7200 				}
7201 
7202 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0 &&
7203 				    curproc->p_dtrace_helpers != NULL) {
7204 					/*
7205 					 * This is the slow path -- we have
7206 					 * allocated string space, and we're
7207 					 * getting the stack of a process that
7208 					 * has helpers.  Call into a separate
7209 					 * routine to perform this processing.
7210 					 */
7211 					dtrace_action_ustack(&mstate, state,
7212 					    (uint64_t *)(tomax + valoffs),
7213 					    rec->dtrd_arg);
7214 					continue;
7215 				}
7216 
7217 				/*
7218 				 * Clear the string space, since there's no
7219 				 * helper to do it for us.
7220 				 */
7221 				if (DTRACE_USTACK_STRSIZE(rec->dtrd_arg) != 0) {
7222 					int depth = DTRACE_USTACK_NFRAMES(
7223 					    rec->dtrd_arg);
7224 					size_t strsize = DTRACE_USTACK_STRSIZE(
7225 					    rec->dtrd_arg);
7226 					uint64_t *buf = (uint64_t *)(tomax +
7227 					    valoffs);
7228 					void *strspace = &buf[depth + 1];
7229 
7230 					dtrace_bzero(strspace,
7231 					    MIN(depth, strsize));
7232 				}
7233 
7234 				DTRACE_CPUFLAG_SET(CPU_DTRACE_NOFAULT);
7235 				dtrace_getupcstack((uint64_t *)
7236 				    (tomax + valoffs),
7237 				    DTRACE_USTACK_NFRAMES(rec->dtrd_arg) + 1);
7238 				DTRACE_CPUFLAG_CLEAR(CPU_DTRACE_NOFAULT);
7239 				continue;
7240 
7241 			default:
7242 				break;
7243 			}
7244 
7245 			dp = act->dta_difo;
7246 			ASSERT(dp != NULL);
7247 
7248 			val = dtrace_dif_emulate(dp, &mstate, vstate, state);
7249 
7250 			if (*flags & CPU_DTRACE_ERROR)
7251 				continue;
7252 
7253 			switch (act->dta_kind) {
7254 			case DTRACEACT_SPECULATE: {
7255 				dtrace_rechdr_t *dtrh;
7256 
7257 				ASSERT(buf == &state->dts_buffer[cpuid]);
7258 				buf = dtrace_speculation_buffer(state,
7259 				    cpuid, val);
7260 
7261 				if (buf == NULL) {
7262 					*flags |= CPU_DTRACE_DROP;
7263 					continue;
7264 				}
7265 
7266 				offs = dtrace_buffer_reserve(buf,
7267 				    ecb->dte_needed, ecb->dte_alignment,
7268 				    state, NULL);
7269 
7270 				if (offs < 0) {
7271 					*flags |= CPU_DTRACE_DROP;
7272 					continue;
7273 				}
7274 
7275 				tomax = buf->dtb_tomax;
7276 				ASSERT(tomax != NULL);
7277 
7278 				if (ecb->dte_size == 0)
7279 					continue;
7280 
7281 				ASSERT3U(ecb->dte_size, >=,
7282 				    sizeof (dtrace_rechdr_t));
7283 				dtrh = ((void *)(tomax + offs));
7284 				dtrh->dtrh_epid = ecb->dte_epid;
7285 				/*
7286 				 * When the speculation is committed, all of
7287 				 * the records in the speculative buffer will
7288 				 * have their timestamps set to the commit
7289 				 * time.  Until then, it is set to a sentinel
7290 				 * value, for debugability.
7291 				 */
7292 				DTRACE_RECORD_STORE_TIMESTAMP(dtrh, UINT64_MAX);
7293 				continue;
7294 			}
7295 
7296 			case DTRACEACT_CHILL:
7297 				if (dtrace_priv_kernel_destructive(state))
7298 					dtrace_action_chill(&mstate, val);
7299 				continue;
7300 
7301 			case DTRACEACT_RAISE:
7302 				if (dtrace_priv_proc_destructive(state,
7303 				    &mstate))
7304 					dtrace_action_raise(val);
7305 				continue;
7306 
7307 			case DTRACEACT_COMMIT:
7308 				ASSERT(!committed);
7309 
7310 				/*
7311 				 * We need to commit our buffer state.
7312 				 */
7313 				if (ecb->dte_size)
7314 					buf->dtb_offset = offs + ecb->dte_size;
7315 				buf = &state->dts_buffer[cpuid];
7316 				dtrace_speculation_commit(state, cpuid, val);
7317 				committed = 1;
7318 				continue;
7319 
7320 			case DTRACEACT_DISCARD:
7321 				dtrace_speculation_discard(state, cpuid, val);
7322 				continue;
7323 
7324 			case DTRACEACT_DIFEXPR:
7325 			case DTRACEACT_LIBACT:
7326 			case DTRACEACT_PRINTF:
7327 			case DTRACEACT_PRINTA:
7328 			case DTRACEACT_SYSTEM:
7329 			case DTRACEACT_FREOPEN:
7330 			case DTRACEACT_TRACEMEM:
7331 				break;
7332 
7333 			case DTRACEACT_TRACEMEM_DYNSIZE:
7334 				tracememsize = val;
7335 				break;
7336 
7337 			case DTRACEACT_SYM:
7338 			case DTRACEACT_MOD:
7339 				if (!dtrace_priv_kernel(state))
7340 					continue;
7341 				break;
7342 
7343 			case DTRACEACT_USYM:
7344 			case DTRACEACT_UMOD:
7345 			case DTRACEACT_UADDR: {
7346 				struct pid *pid = curthread->t_procp->p_pidp;
7347 
7348 				if (!dtrace_priv_proc(state, &mstate))
7349 					continue;
7350 
7351 				DTRACE_STORE(uint64_t, tomax,
7352 				    valoffs, (uint64_t)pid->pid_id);
7353 				DTRACE_STORE(uint64_t, tomax,
7354 				    valoffs + sizeof (uint64_t), val);
7355 
7356 				continue;
7357 			}
7358 
7359 			case DTRACEACT_EXIT: {
7360 				/*
7361 				 * For the exit action, we are going to attempt
7362 				 * to atomically set our activity to be
7363 				 * draining.  If this fails (either because
7364 				 * another CPU has beat us to the exit action,
7365 				 * or because our current activity is something
7366 				 * other than ACTIVE or WARMUP), we will
7367 				 * continue.  This assures that the exit action
7368 				 * can be successfully recorded at most once
7369 				 * when we're in the ACTIVE state.  If we're
7370 				 * encountering the exit() action while in
7371 				 * COOLDOWN, however, we want to honor the new
7372 				 * status code.  (We know that we're the only
7373 				 * thread in COOLDOWN, so there is no race.)
7374 				 */
7375 				void *activity = &state->dts_activity;
7376 				dtrace_activity_t current = state->dts_activity;
7377 
7378 				if (current == DTRACE_ACTIVITY_COOLDOWN)
7379 					break;
7380 
7381 				if (current != DTRACE_ACTIVITY_WARMUP)
7382 					current = DTRACE_ACTIVITY_ACTIVE;
7383 
7384 				if (dtrace_cas32(activity, current,
7385 				    DTRACE_ACTIVITY_DRAINING) != current) {
7386 					*flags |= CPU_DTRACE_DROP;
7387 					continue;
7388 				}
7389 
7390 				break;
7391 			}
7392 
7393 			default:
7394 				ASSERT(0);
7395 			}
7396 
7397 			if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ||
7398 			    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYUREF) {
7399 				uintptr_t end = valoffs + size;
7400 
7401 				if (tracememsize != 0 &&
7402 				    valoffs + tracememsize < end) {
7403 					end = valoffs + tracememsize;
7404 					tracememsize = 0;
7405 				}
7406 
7407 				if (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF &&
7408 				    !dtrace_vcanload((void *)(uintptr_t)val,
7409 				    &dp->dtdo_rtype, NULL, &mstate, vstate))
7410 					continue;
7411 
7412 				dtrace_store_by_ref(dp, tomax, size, &valoffs,
7413 				    &val, end, act->dta_intuple,
7414 				    dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF ?
7415 				    DIF_TF_BYREF: DIF_TF_BYUREF);
7416 				continue;
7417 			}
7418 
7419 			switch (size) {
7420 			case 0:
7421 				break;
7422 
7423 			case sizeof (uint8_t):
7424 				DTRACE_STORE(uint8_t, tomax, valoffs, val);
7425 				break;
7426 			case sizeof (uint16_t):
7427 				DTRACE_STORE(uint16_t, tomax, valoffs, val);
7428 				break;
7429 			case sizeof (uint32_t):
7430 				DTRACE_STORE(uint32_t, tomax, valoffs, val);
7431 				break;
7432 			case sizeof (uint64_t):
7433 				DTRACE_STORE(uint64_t, tomax, valoffs, val);
7434 				break;
7435 			default:
7436 				/*
7437 				 * Any other size should have been returned by
7438 				 * reference, not by value.
7439 				 */
7440 				ASSERT(0);
7441 				break;
7442 			}
7443 		}
7444 
7445 		if (*flags & CPU_DTRACE_DROP)
7446 			continue;
7447 
7448 		if (*flags & CPU_DTRACE_FAULT) {
7449 			int ndx;
7450 			dtrace_action_t *err;
7451 
7452 			buf->dtb_errors++;
7453 
7454 			if (probe->dtpr_id == dtrace_probeid_error) {
7455 				/*
7456 				 * There's nothing we can do -- we had an
7457 				 * error on the error probe.  We bump an
7458 				 * error counter to at least indicate that
7459 				 * this condition happened.
7460 				 */
7461 				dtrace_error(&state->dts_dblerrors);
7462 				continue;
7463 			}
7464 
7465 			if (vtime) {
7466 				/*
7467 				 * Before recursing on dtrace_probe(), we
7468 				 * need to explicitly clear out our start
7469 				 * time to prevent it from being accumulated
7470 				 * into t_dtrace_vtime.
7471 				 */
7472 				curthread->t_dtrace_start = 0;
7473 			}
7474 
7475 			/*
7476 			 * Iterate over the actions to figure out which action
7477 			 * we were processing when we experienced the error.
7478 			 * Note that act points _past_ the faulting action; if
7479 			 * act is ecb->dte_action, the fault was in the
7480 			 * predicate, if it's ecb->dte_action->dta_next it's
7481 			 * in action #1, and so on.
7482 			 */
7483 			for (err = ecb->dte_action, ndx = 0;
7484 			    err != act; err = err->dta_next, ndx++)
7485 				continue;
7486 
7487 			dtrace_probe_error(state, ecb->dte_epid, ndx,
7488 			    (mstate.dtms_present & DTRACE_MSTATE_FLTOFFS) ?
7489 			    mstate.dtms_fltoffs : -1, DTRACE_FLAGS2FLT(*flags),
7490 			    cpu_core[cpuid].cpuc_dtrace_illval);
7491 
7492 			continue;
7493 		}
7494 
7495 		if (!committed)
7496 			buf->dtb_offset = offs + ecb->dte_size;
7497 	}
7498 
7499 	end = dtrace_gethrtime();
7500 	if (vtime)
7501 		curthread->t_dtrace_start = end;
7502 
7503 	CPU->cpu_dtrace_nsec += end - now;
7504 
7505 	dtrace_interrupt_enable(cookie);
7506 }
7507 
7508 /*
7509  * DTrace Probe Hashing Functions
7510  *
7511  * The functions in this section (and indeed, the functions in remaining
7512  * sections) are not _called_ from probe context.  (Any exceptions to this are
7513  * marked with a "Note:".)  Rather, they are called from elsewhere in the
7514  * DTrace framework to look-up probes in, add probes to and remove probes from
7515  * the DTrace probe hashes.  (Each probe is hashed by each element of the
7516  * probe tuple -- allowing for fast lookups, regardless of what was
7517  * specified.)
7518  */
7519 static uint_t
7520 dtrace_hash_str(char *p)
7521 {
7522 	unsigned int g;
7523 	uint_t hval = 0;
7524 
7525 	while (*p) {
7526 		hval = (hval << 4) + *p++;
7527 		if ((g = (hval & 0xf0000000)) != 0)
7528 			hval ^= g >> 24;
7529 		hval &= ~g;
7530 	}
7531 	return (hval);
7532 }
7533 
7534 static dtrace_hash_t *
7535 dtrace_hash_create(uintptr_t stroffs, uintptr_t nextoffs, uintptr_t prevoffs)
7536 {
7537 	dtrace_hash_t *hash = kmem_zalloc(sizeof (dtrace_hash_t), KM_SLEEP);
7538 
7539 	hash->dth_stroffs = stroffs;
7540 	hash->dth_nextoffs = nextoffs;
7541 	hash->dth_prevoffs = prevoffs;
7542 
7543 	hash->dth_size = 1;
7544 	hash->dth_mask = hash->dth_size - 1;
7545 
7546 	hash->dth_tab = kmem_zalloc(hash->dth_size *
7547 	    sizeof (dtrace_hashbucket_t *), KM_SLEEP);
7548 
7549 	return (hash);
7550 }
7551 
7552 static void
7553 dtrace_hash_destroy(dtrace_hash_t *hash)
7554 {
7555 #ifdef DEBUG
7556 	int i;
7557 
7558 	for (i = 0; i < hash->dth_size; i++)
7559 		ASSERT(hash->dth_tab[i] == NULL);
7560 #endif
7561 
7562 	kmem_free(hash->dth_tab,
7563 	    hash->dth_size * sizeof (dtrace_hashbucket_t *));
7564 	kmem_free(hash, sizeof (dtrace_hash_t));
7565 }
7566 
7567 static void
7568 dtrace_hash_resize(dtrace_hash_t *hash)
7569 {
7570 	int size = hash->dth_size, i, ndx;
7571 	int new_size = hash->dth_size << 1;
7572 	int new_mask = new_size - 1;
7573 	dtrace_hashbucket_t **new_tab, *bucket, *next;
7574 
7575 	ASSERT((new_size & new_mask) == 0);
7576 
7577 	new_tab = kmem_zalloc(new_size * sizeof (void *), KM_SLEEP);
7578 
7579 	for (i = 0; i < size; i++) {
7580 		for (bucket = hash->dth_tab[i]; bucket != NULL; bucket = next) {
7581 			dtrace_probe_t *probe = bucket->dthb_chain;
7582 
7583 			ASSERT(probe != NULL);
7584 			ndx = DTRACE_HASHSTR(hash, probe) & new_mask;
7585 
7586 			next = bucket->dthb_next;
7587 			bucket->dthb_next = new_tab[ndx];
7588 			new_tab[ndx] = bucket;
7589 		}
7590 	}
7591 
7592 	kmem_free(hash->dth_tab, hash->dth_size * sizeof (void *));
7593 	hash->dth_tab = new_tab;
7594 	hash->dth_size = new_size;
7595 	hash->dth_mask = new_mask;
7596 }
7597 
7598 static void
7599 dtrace_hash_add(dtrace_hash_t *hash, dtrace_probe_t *new)
7600 {
7601 	int hashval = DTRACE_HASHSTR(hash, new);
7602 	int ndx = hashval & hash->dth_mask;
7603 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7604 	dtrace_probe_t **nextp, **prevp;
7605 
7606 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7607 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, new))
7608 			goto add;
7609 	}
7610 
7611 	if ((hash->dth_nbuckets >> 1) > hash->dth_size) {
7612 		dtrace_hash_resize(hash);
7613 		dtrace_hash_add(hash, new);
7614 		return;
7615 	}
7616 
7617 	bucket = kmem_zalloc(sizeof (dtrace_hashbucket_t), KM_SLEEP);
7618 	bucket->dthb_next = hash->dth_tab[ndx];
7619 	hash->dth_tab[ndx] = bucket;
7620 	hash->dth_nbuckets++;
7621 
7622 add:
7623 	nextp = DTRACE_HASHNEXT(hash, new);
7624 	ASSERT(*nextp == NULL && *(DTRACE_HASHPREV(hash, new)) == NULL);
7625 	*nextp = bucket->dthb_chain;
7626 
7627 	if (bucket->dthb_chain != NULL) {
7628 		prevp = DTRACE_HASHPREV(hash, bucket->dthb_chain);
7629 		ASSERT(*prevp == NULL);
7630 		*prevp = new;
7631 	}
7632 
7633 	bucket->dthb_chain = new;
7634 	bucket->dthb_len++;
7635 }
7636 
7637 static dtrace_probe_t *
7638 dtrace_hash_lookup(dtrace_hash_t *hash, dtrace_probe_t *template)
7639 {
7640 	int hashval = DTRACE_HASHSTR(hash, template);
7641 	int ndx = hashval & hash->dth_mask;
7642 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7643 
7644 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7645 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7646 			return (bucket->dthb_chain);
7647 	}
7648 
7649 	return (NULL);
7650 }
7651 
7652 static int
7653 dtrace_hash_collisions(dtrace_hash_t *hash, dtrace_probe_t *template)
7654 {
7655 	int hashval = DTRACE_HASHSTR(hash, template);
7656 	int ndx = hashval & hash->dth_mask;
7657 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7658 
7659 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7660 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, template))
7661 			return (bucket->dthb_len);
7662 	}
7663 
7664 	return (0);
7665 }
7666 
7667 static void
7668 dtrace_hash_remove(dtrace_hash_t *hash, dtrace_probe_t *probe)
7669 {
7670 	int ndx = DTRACE_HASHSTR(hash, probe) & hash->dth_mask;
7671 	dtrace_hashbucket_t *bucket = hash->dth_tab[ndx];
7672 
7673 	dtrace_probe_t **prevp = DTRACE_HASHPREV(hash, probe);
7674 	dtrace_probe_t **nextp = DTRACE_HASHNEXT(hash, probe);
7675 
7676 	/*
7677 	 * Find the bucket that we're removing this probe from.
7678 	 */
7679 	for (; bucket != NULL; bucket = bucket->dthb_next) {
7680 		if (DTRACE_HASHEQ(hash, bucket->dthb_chain, probe))
7681 			break;
7682 	}
7683 
7684 	ASSERT(bucket != NULL);
7685 
7686 	if (*prevp == NULL) {
7687 		if (*nextp == NULL) {
7688 			/*
7689 			 * The removed probe was the only probe on this
7690 			 * bucket; we need to remove the bucket.
7691 			 */
7692 			dtrace_hashbucket_t *b = hash->dth_tab[ndx];
7693 
7694 			ASSERT(bucket->dthb_chain == probe);
7695 			ASSERT(b != NULL);
7696 
7697 			if (b == bucket) {
7698 				hash->dth_tab[ndx] = bucket->dthb_next;
7699 			} else {
7700 				while (b->dthb_next != bucket)
7701 					b = b->dthb_next;
7702 				b->dthb_next = bucket->dthb_next;
7703 			}
7704 
7705 			ASSERT(hash->dth_nbuckets > 0);
7706 			hash->dth_nbuckets--;
7707 			kmem_free(bucket, sizeof (dtrace_hashbucket_t));
7708 			return;
7709 		}
7710 
7711 		bucket->dthb_chain = *nextp;
7712 	} else {
7713 		*(DTRACE_HASHNEXT(hash, *prevp)) = *nextp;
7714 	}
7715 
7716 	if (*nextp != NULL)
7717 		*(DTRACE_HASHPREV(hash, *nextp)) = *prevp;
7718 }
7719 
7720 /*
7721  * DTrace Utility Functions
7722  *
7723  * These are random utility functions that are _not_ called from probe context.
7724  */
7725 static int
7726 dtrace_badattr(const dtrace_attribute_t *a)
7727 {
7728 	return (a->dtat_name > DTRACE_STABILITY_MAX ||
7729 	    a->dtat_data > DTRACE_STABILITY_MAX ||
7730 	    a->dtat_class > DTRACE_CLASS_MAX);
7731 }
7732 
7733 /*
7734  * Return a duplicate copy of a string.  If the specified string is NULL,
7735  * this function returns a zero-length string.
7736  */
7737 static char *
7738 dtrace_strdup(const char *str)
7739 {
7740 	char *new = kmem_zalloc((str != NULL ? strlen(str) : 0) + 1, KM_SLEEP);
7741 
7742 	if (str != NULL)
7743 		(void) strcpy(new, str);
7744 
7745 	return (new);
7746 }
7747 
7748 #define	DTRACE_ISALPHA(c)	\
7749 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
7750 
7751 static int
7752 dtrace_badname(const char *s)
7753 {
7754 	char c;
7755 
7756 	if (s == NULL || (c = *s++) == '\0')
7757 		return (0);
7758 
7759 	if (!DTRACE_ISALPHA(c) && c != '-' && c != '_' && c != '.')
7760 		return (1);
7761 
7762 	while ((c = *s++) != '\0') {
7763 		if (!DTRACE_ISALPHA(c) && (c < '0' || c > '9') &&
7764 		    c != '-' && c != '_' && c != '.' && c != '`')
7765 			return (1);
7766 	}
7767 
7768 	return (0);
7769 }
7770 
7771 static void
7772 dtrace_cred2priv(cred_t *cr, uint32_t *privp, uid_t *uidp, zoneid_t *zoneidp)
7773 {
7774 	uint32_t priv;
7775 
7776 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
7777 		/*
7778 		 * For DTRACE_PRIV_ALL, the uid and zoneid don't matter.
7779 		 */
7780 		priv = DTRACE_PRIV_ALL;
7781 	} else {
7782 		*uidp = crgetuid(cr);
7783 		*zoneidp = crgetzoneid(cr);
7784 
7785 		priv = 0;
7786 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE))
7787 			priv |= DTRACE_PRIV_KERNEL | DTRACE_PRIV_USER;
7788 		else if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE))
7789 			priv |= DTRACE_PRIV_USER;
7790 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE))
7791 			priv |= DTRACE_PRIV_PROC;
7792 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
7793 			priv |= DTRACE_PRIV_OWNER;
7794 		if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
7795 			priv |= DTRACE_PRIV_ZONEOWNER;
7796 	}
7797 
7798 	*privp = priv;
7799 }
7800 
7801 #ifdef DTRACE_ERRDEBUG
7802 static void
7803 dtrace_errdebug(const char *str)
7804 {
7805 	int hval = dtrace_hash_str((char *)str) % DTRACE_ERRHASHSZ;
7806 	int occupied = 0;
7807 
7808 	mutex_enter(&dtrace_errlock);
7809 	dtrace_errlast = str;
7810 	dtrace_errthread = curthread;
7811 
7812 	while (occupied++ < DTRACE_ERRHASHSZ) {
7813 		if (dtrace_errhash[hval].dter_msg == str) {
7814 			dtrace_errhash[hval].dter_count++;
7815 			goto out;
7816 		}
7817 
7818 		if (dtrace_errhash[hval].dter_msg != NULL) {
7819 			hval = (hval + 1) % DTRACE_ERRHASHSZ;
7820 			continue;
7821 		}
7822 
7823 		dtrace_errhash[hval].dter_msg = str;
7824 		dtrace_errhash[hval].dter_count = 1;
7825 		goto out;
7826 	}
7827 
7828 	panic("dtrace: undersized error hash");
7829 out:
7830 	mutex_exit(&dtrace_errlock);
7831 }
7832 #endif
7833 
7834 /*
7835  * DTrace Matching Functions
7836  *
7837  * These functions are used to match groups of probes, given some elements of
7838  * a probe tuple, or some globbed expressions for elements of a probe tuple.
7839  */
7840 static int
7841 dtrace_match_priv(const dtrace_probe_t *prp, uint32_t priv, uid_t uid,
7842     zoneid_t zoneid)
7843 {
7844 	if (priv != DTRACE_PRIV_ALL) {
7845 		uint32_t ppriv = prp->dtpr_provider->dtpv_priv.dtpp_flags;
7846 		uint32_t match = priv & ppriv;
7847 
7848 		/*
7849 		 * No PRIV_DTRACE_* privileges...
7850 		 */
7851 		if ((priv & (DTRACE_PRIV_PROC | DTRACE_PRIV_USER |
7852 		    DTRACE_PRIV_KERNEL)) == 0)
7853 			return (0);
7854 
7855 		/*
7856 		 * No matching bits, but there were bits to match...
7857 		 */
7858 		if (match == 0 && ppriv != 0)
7859 			return (0);
7860 
7861 		/*
7862 		 * Need to have permissions to the process, but don't...
7863 		 */
7864 		if (((ppriv & ~match) & DTRACE_PRIV_OWNER) != 0 &&
7865 		    uid != prp->dtpr_provider->dtpv_priv.dtpp_uid) {
7866 			return (0);
7867 		}
7868 
7869 		/*
7870 		 * Need to be in the same zone unless we possess the
7871 		 * privilege to examine all zones.
7872 		 */
7873 		if (((ppriv & ~match) & DTRACE_PRIV_ZONEOWNER) != 0 &&
7874 		    zoneid != prp->dtpr_provider->dtpv_priv.dtpp_zoneid) {
7875 			return (0);
7876 		}
7877 	}
7878 
7879 	return (1);
7880 }
7881 
7882 /*
7883  * dtrace_match_probe compares a dtrace_probe_t to a pre-compiled key, which
7884  * consists of input pattern strings and an ops-vector to evaluate them.
7885  * This function returns >0 for match, 0 for no match, and <0 for error.
7886  */
7887 static int
7888 dtrace_match_probe(const dtrace_probe_t *prp, const dtrace_probekey_t *pkp,
7889     uint32_t priv, uid_t uid, zoneid_t zoneid)
7890 {
7891 	dtrace_provider_t *pvp = prp->dtpr_provider;
7892 	int rv;
7893 
7894 	if (pvp->dtpv_defunct)
7895 		return (0);
7896 
7897 	if ((rv = pkp->dtpk_pmatch(pvp->dtpv_name, pkp->dtpk_prov, 0)) <= 0)
7898 		return (rv);
7899 
7900 	if ((rv = pkp->dtpk_mmatch(prp->dtpr_mod, pkp->dtpk_mod, 0)) <= 0)
7901 		return (rv);
7902 
7903 	if ((rv = pkp->dtpk_fmatch(prp->dtpr_func, pkp->dtpk_func, 0)) <= 0)
7904 		return (rv);
7905 
7906 	if ((rv = pkp->dtpk_nmatch(prp->dtpr_name, pkp->dtpk_name, 0)) <= 0)
7907 		return (rv);
7908 
7909 	if (dtrace_match_priv(prp, priv, uid, zoneid) == 0)
7910 		return (0);
7911 
7912 	return (rv);
7913 }
7914 
7915 /*
7916  * dtrace_match_glob() is a safe kernel implementation of the gmatch(3GEN)
7917  * interface for matching a glob pattern 'p' to an input string 's'.  Unlike
7918  * libc's version, the kernel version only applies to 8-bit ASCII strings.
7919  * In addition, all of the recursion cases except for '*' matching have been
7920  * unwound.  For '*', we still implement recursive evaluation, but a depth
7921  * counter is maintained and matching is aborted if we recurse too deep.
7922  * The function returns 0 if no match, >0 if match, and <0 if recursion error.
7923  */
7924 static int
7925 dtrace_match_glob(const char *s, const char *p, int depth)
7926 {
7927 	const char *olds;
7928 	char s1, c;
7929 	int gs;
7930 
7931 	if (depth > DTRACE_PROBEKEY_MAXDEPTH)
7932 		return (-1);
7933 
7934 	if (s == NULL)
7935 		s = ""; /* treat NULL as empty string */
7936 
7937 top:
7938 	olds = s;
7939 	s1 = *s++;
7940 
7941 	if (p == NULL)
7942 		return (0);
7943 
7944 	if ((c = *p++) == '\0')
7945 		return (s1 == '\0');
7946 
7947 	switch (c) {
7948 	case '[': {
7949 		int ok = 0, notflag = 0;
7950 		char lc = '\0';
7951 
7952 		if (s1 == '\0')
7953 			return (0);
7954 
7955 		if (*p == '!') {
7956 			notflag = 1;
7957 			p++;
7958 		}
7959 
7960 		if ((c = *p++) == '\0')
7961 			return (0);
7962 
7963 		do {
7964 			if (c == '-' && lc != '\0' && *p != ']') {
7965 				if ((c = *p++) == '\0')
7966 					return (0);
7967 				if (c == '\\' && (c = *p++) == '\0')
7968 					return (0);
7969 
7970 				if (notflag) {
7971 					if (s1 < lc || s1 > c)
7972 						ok++;
7973 					else
7974 						return (0);
7975 				} else if (lc <= s1 && s1 <= c)
7976 					ok++;
7977 
7978 			} else if (c == '\\' && (c = *p++) == '\0')
7979 				return (0);
7980 
7981 			lc = c; /* save left-hand 'c' for next iteration */
7982 
7983 			if (notflag) {
7984 				if (s1 != c)
7985 					ok++;
7986 				else
7987 					return (0);
7988 			} else if (s1 == c)
7989 				ok++;
7990 
7991 			if ((c = *p++) == '\0')
7992 				return (0);
7993 
7994 		} while (c != ']');
7995 
7996 		if (ok)
7997 			goto top;
7998 
7999 		return (0);
8000 	}
8001 
8002 	case '\\':
8003 		if ((c = *p++) == '\0')
8004 			return (0);
8005 		/*FALLTHRU*/
8006 
8007 	default:
8008 		if (c != s1)
8009 			return (0);
8010 		/*FALLTHRU*/
8011 
8012 	case '?':
8013 		if (s1 != '\0')
8014 			goto top;
8015 		return (0);
8016 
8017 	case '*':
8018 		while (*p == '*')
8019 			p++; /* consecutive *'s are identical to a single one */
8020 
8021 		if (*p == '\0')
8022 			return (1);
8023 
8024 		for (s = olds; *s != '\0'; s++) {
8025 			if ((gs = dtrace_match_glob(s, p, depth + 1)) != 0)
8026 				return (gs);
8027 		}
8028 
8029 		return (0);
8030 	}
8031 }
8032 
8033 /*ARGSUSED*/
8034 static int
8035 dtrace_match_string(const char *s, const char *p, int depth)
8036 {
8037 	return (s != NULL && strcmp(s, p) == 0);
8038 }
8039 
8040 /*ARGSUSED*/
8041 static int
8042 dtrace_match_nul(const char *s, const char *p, int depth)
8043 {
8044 	return (1); /* always match the empty pattern */
8045 }
8046 
8047 /*ARGSUSED*/
8048 static int
8049 dtrace_match_nonzero(const char *s, const char *p, int depth)
8050 {
8051 	return (s != NULL && s[0] != '\0');
8052 }
8053 
8054 static int
8055 dtrace_match(const dtrace_probekey_t *pkp, uint32_t priv, uid_t uid,
8056     zoneid_t zoneid, int (*matched)(dtrace_probe_t *, void *), void *arg)
8057 {
8058 	dtrace_probe_t template, *probe;
8059 	dtrace_hash_t *hash = NULL;
8060 	int len, rc, best = INT_MAX, nmatched = 0;
8061 	dtrace_id_t i;
8062 
8063 	ASSERT(MUTEX_HELD(&dtrace_lock));
8064 
8065 	/*
8066 	 * If the probe ID is specified in the key, just lookup by ID and
8067 	 * invoke the match callback once if a matching probe is found.
8068 	 */
8069 	if (pkp->dtpk_id != DTRACE_IDNONE) {
8070 		if ((probe = dtrace_probe_lookup_id(pkp->dtpk_id)) != NULL &&
8071 		    dtrace_match_probe(probe, pkp, priv, uid, zoneid) > 0) {
8072 			if ((*matched)(probe, arg) == DTRACE_MATCH_FAIL)
8073 				return (DTRACE_MATCH_FAIL);
8074 			nmatched++;
8075 		}
8076 		return (nmatched);
8077 	}
8078 
8079 	template.dtpr_mod = (char *)pkp->dtpk_mod;
8080 	template.dtpr_func = (char *)pkp->dtpk_func;
8081 	template.dtpr_name = (char *)pkp->dtpk_name;
8082 
8083 	/*
8084 	 * We want to find the most distinct of the module name, function
8085 	 * name, and name.  So for each one that is not a glob pattern or
8086 	 * empty string, we perform a lookup in the corresponding hash and
8087 	 * use the hash table with the fewest collisions to do our search.
8088 	 */
8089 	if (pkp->dtpk_mmatch == &dtrace_match_string &&
8090 	    (len = dtrace_hash_collisions(dtrace_bymod, &template)) < best) {
8091 		best = len;
8092 		hash = dtrace_bymod;
8093 	}
8094 
8095 	if (pkp->dtpk_fmatch == &dtrace_match_string &&
8096 	    (len = dtrace_hash_collisions(dtrace_byfunc, &template)) < best) {
8097 		best = len;
8098 		hash = dtrace_byfunc;
8099 	}
8100 
8101 	if (pkp->dtpk_nmatch == &dtrace_match_string &&
8102 	    (len = dtrace_hash_collisions(dtrace_byname, &template)) < best) {
8103 		best = len;
8104 		hash = dtrace_byname;
8105 	}
8106 
8107 	/*
8108 	 * If we did not select a hash table, iterate over every probe and
8109 	 * invoke our callback for each one that matches our input probe key.
8110 	 */
8111 	if (hash == NULL) {
8112 		for (i = 0; i < dtrace_nprobes; i++) {
8113 			if ((probe = dtrace_probes[i]) == NULL ||
8114 			    dtrace_match_probe(probe, pkp, priv, uid,
8115 			    zoneid) <= 0)
8116 				continue;
8117 
8118 			nmatched++;
8119 
8120 			if ((rc = (*matched)(probe, arg)) !=
8121 			    DTRACE_MATCH_NEXT) {
8122 				if (rc == DTRACE_MATCH_FAIL)
8123 					return (DTRACE_MATCH_FAIL);
8124 				break;
8125 			}
8126 		}
8127 
8128 		return (nmatched);
8129 	}
8130 
8131 	/*
8132 	 * If we selected a hash table, iterate over each probe of the same key
8133 	 * name and invoke the callback for every probe that matches the other
8134 	 * attributes of our input probe key.
8135 	 */
8136 	for (probe = dtrace_hash_lookup(hash, &template); probe != NULL;
8137 	    probe = *(DTRACE_HASHNEXT(hash, probe))) {
8138 
8139 		if (dtrace_match_probe(probe, pkp, priv, uid, zoneid) <= 0)
8140 			continue;
8141 
8142 		nmatched++;
8143 
8144 		if ((rc = (*matched)(probe, arg)) != DTRACE_MATCH_NEXT) {
8145 			if (rc == DTRACE_MATCH_FAIL)
8146 				return (DTRACE_MATCH_FAIL);
8147 			break;
8148 		}
8149 	}
8150 
8151 	return (nmatched);
8152 }
8153 
8154 /*
8155  * Return the function pointer dtrace_probecmp() should use to compare the
8156  * specified pattern with a string.  For NULL or empty patterns, we select
8157  * dtrace_match_nul().  For glob pattern strings, we use dtrace_match_glob().
8158  * For non-empty non-glob strings, we use dtrace_match_string().
8159  */
8160 static dtrace_probekey_f *
8161 dtrace_probekey_func(const char *p)
8162 {
8163 	char c;
8164 
8165 	if (p == NULL || *p == '\0')
8166 		return (&dtrace_match_nul);
8167 
8168 	while ((c = *p++) != '\0') {
8169 		if (c == '[' || c == '?' || c == '*' || c == '\\')
8170 			return (&dtrace_match_glob);
8171 	}
8172 
8173 	return (&dtrace_match_string);
8174 }
8175 
8176 /*
8177  * Build a probe comparison key for use with dtrace_match_probe() from the
8178  * given probe description.  By convention, a null key only matches anchored
8179  * probes: if each field is the empty string, reset dtpk_fmatch to
8180  * dtrace_match_nonzero().
8181  */
8182 static void
8183 dtrace_probekey(const dtrace_probedesc_t *pdp, dtrace_probekey_t *pkp)
8184 {
8185 	pkp->dtpk_prov = pdp->dtpd_provider;
8186 	pkp->dtpk_pmatch = dtrace_probekey_func(pdp->dtpd_provider);
8187 
8188 	pkp->dtpk_mod = pdp->dtpd_mod;
8189 	pkp->dtpk_mmatch = dtrace_probekey_func(pdp->dtpd_mod);
8190 
8191 	pkp->dtpk_func = pdp->dtpd_func;
8192 	pkp->dtpk_fmatch = dtrace_probekey_func(pdp->dtpd_func);
8193 
8194 	pkp->dtpk_name = pdp->dtpd_name;
8195 	pkp->dtpk_nmatch = dtrace_probekey_func(pdp->dtpd_name);
8196 
8197 	pkp->dtpk_id = pdp->dtpd_id;
8198 
8199 	if (pkp->dtpk_id == DTRACE_IDNONE &&
8200 	    pkp->dtpk_pmatch == &dtrace_match_nul &&
8201 	    pkp->dtpk_mmatch == &dtrace_match_nul &&
8202 	    pkp->dtpk_fmatch == &dtrace_match_nul &&
8203 	    pkp->dtpk_nmatch == &dtrace_match_nul)
8204 		pkp->dtpk_fmatch = &dtrace_match_nonzero;
8205 }
8206 
8207 /*
8208  * DTrace Provider-to-Framework API Functions
8209  *
8210  * These functions implement much of the Provider-to-Framework API, as
8211  * described in <sys/dtrace.h>.  The parts of the API not in this section are
8212  * the functions in the API for probe management (found below), and
8213  * dtrace_probe() itself (found above).
8214  */
8215 
8216 /*
8217  * Register the calling provider with the DTrace framework.  This should
8218  * generally be called by DTrace providers in their attach(9E) entry point.
8219  */
8220 int
8221 dtrace_register(const char *name, const dtrace_pattr_t *pap, uint32_t priv,
8222     cred_t *cr, const dtrace_pops_t *pops, void *arg, dtrace_provider_id_t *idp)
8223 {
8224 	dtrace_provider_t *provider;
8225 
8226 	if (name == NULL || pap == NULL || pops == NULL || idp == NULL) {
8227 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8228 		    "arguments", name ? name : "<NULL>");
8229 		return (EINVAL);
8230 	}
8231 
8232 	if (name[0] == '\0' || dtrace_badname(name)) {
8233 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8234 		    "provider name", name);
8235 		return (EINVAL);
8236 	}
8237 
8238 	if ((pops->dtps_provide == NULL && pops->dtps_provide_module == NULL) ||
8239 	    pops->dtps_enable == NULL || pops->dtps_disable == NULL ||
8240 	    pops->dtps_destroy == NULL ||
8241 	    ((pops->dtps_resume == NULL) != (pops->dtps_suspend == NULL))) {
8242 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8243 		    "provider ops", name);
8244 		return (EINVAL);
8245 	}
8246 
8247 	if (dtrace_badattr(&pap->dtpa_provider) ||
8248 	    dtrace_badattr(&pap->dtpa_mod) ||
8249 	    dtrace_badattr(&pap->dtpa_func) ||
8250 	    dtrace_badattr(&pap->dtpa_name) ||
8251 	    dtrace_badattr(&pap->dtpa_args)) {
8252 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8253 		    "provider attributes", name);
8254 		return (EINVAL);
8255 	}
8256 
8257 	if (priv & ~DTRACE_PRIV_ALL) {
8258 		cmn_err(CE_WARN, "failed to register provider '%s': invalid "
8259 		    "privilege attributes", name);
8260 		return (EINVAL);
8261 	}
8262 
8263 	if ((priv & DTRACE_PRIV_KERNEL) &&
8264 	    (priv & (DTRACE_PRIV_USER | DTRACE_PRIV_OWNER)) &&
8265 	    pops->dtps_mode == NULL) {
8266 		cmn_err(CE_WARN, "failed to register provider '%s': need "
8267 		    "dtps_mode() op for given privilege attributes", name);
8268 		return (EINVAL);
8269 	}
8270 
8271 	provider = kmem_zalloc(sizeof (dtrace_provider_t), KM_SLEEP);
8272 	provider->dtpv_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
8273 	(void) strcpy(provider->dtpv_name, name);
8274 
8275 	provider->dtpv_attr = *pap;
8276 	provider->dtpv_priv.dtpp_flags = priv;
8277 	if (cr != NULL) {
8278 		provider->dtpv_priv.dtpp_uid = crgetuid(cr);
8279 		provider->dtpv_priv.dtpp_zoneid = crgetzoneid(cr);
8280 	}
8281 	provider->dtpv_pops = *pops;
8282 
8283 	if (pops->dtps_provide == NULL) {
8284 		ASSERT(pops->dtps_provide_module != NULL);
8285 		provider->dtpv_pops.dtps_provide =
8286 		    (void (*)(void *, const dtrace_probedesc_t *))dtrace_nullop;
8287 	}
8288 
8289 	if (pops->dtps_provide_module == NULL) {
8290 		ASSERT(pops->dtps_provide != NULL);
8291 		provider->dtpv_pops.dtps_provide_module =
8292 		    (void (*)(void *, struct modctl *))dtrace_nullop;
8293 	}
8294 
8295 	if (pops->dtps_suspend == NULL) {
8296 		ASSERT(pops->dtps_resume == NULL);
8297 		provider->dtpv_pops.dtps_suspend =
8298 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8299 		provider->dtpv_pops.dtps_resume =
8300 		    (void (*)(void *, dtrace_id_t, void *))dtrace_nullop;
8301 	}
8302 
8303 	provider->dtpv_arg = arg;
8304 	*idp = (dtrace_provider_id_t)provider;
8305 
8306 	if (pops == &dtrace_provider_ops) {
8307 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8308 		ASSERT(MUTEX_HELD(&dtrace_lock));
8309 		ASSERT(dtrace_anon.dta_enabling == NULL);
8310 
8311 		/*
8312 		 * We make sure that the DTrace provider is at the head of
8313 		 * the provider chain.
8314 		 */
8315 		provider->dtpv_next = dtrace_provider;
8316 		dtrace_provider = provider;
8317 		return (0);
8318 	}
8319 
8320 	mutex_enter(&dtrace_provider_lock);
8321 	mutex_enter(&dtrace_lock);
8322 
8323 	/*
8324 	 * If there is at least one provider registered, we'll add this
8325 	 * provider after the first provider.
8326 	 */
8327 	if (dtrace_provider != NULL) {
8328 		provider->dtpv_next = dtrace_provider->dtpv_next;
8329 		dtrace_provider->dtpv_next = provider;
8330 	} else {
8331 		dtrace_provider = provider;
8332 	}
8333 
8334 	if (dtrace_retained != NULL) {
8335 		dtrace_enabling_provide(provider);
8336 
8337 		/*
8338 		 * Now we need to call dtrace_enabling_matchall() -- which
8339 		 * will acquire cpu_lock and dtrace_lock.  We therefore need
8340 		 * to drop all of our locks before calling into it...
8341 		 */
8342 		mutex_exit(&dtrace_lock);
8343 		mutex_exit(&dtrace_provider_lock);
8344 		dtrace_enabling_matchall();
8345 
8346 		return (0);
8347 	}
8348 
8349 	mutex_exit(&dtrace_lock);
8350 	mutex_exit(&dtrace_provider_lock);
8351 
8352 	return (0);
8353 }
8354 
8355 /*
8356  * Unregister the specified provider from the DTrace framework.  This should
8357  * generally be called by DTrace providers in their detach(9E) entry point.
8358  */
8359 int
8360 dtrace_unregister(dtrace_provider_id_t id)
8361 {
8362 	dtrace_provider_t *old = (dtrace_provider_t *)id;
8363 	dtrace_provider_t *prev = NULL;
8364 	int i, self = 0, noreap = 0;
8365 	dtrace_probe_t *probe, *first = NULL;
8366 
8367 	if (old->dtpv_pops.dtps_enable ==
8368 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop) {
8369 		/*
8370 		 * If DTrace itself is the provider, we're called with locks
8371 		 * already held.
8372 		 */
8373 		ASSERT(old == dtrace_provider);
8374 		ASSERT(dtrace_devi != NULL);
8375 		ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8376 		ASSERT(MUTEX_HELD(&dtrace_lock));
8377 		self = 1;
8378 
8379 		if (dtrace_provider->dtpv_next != NULL) {
8380 			/*
8381 			 * There's another provider here; return failure.
8382 			 */
8383 			return (EBUSY);
8384 		}
8385 	} else {
8386 		mutex_enter(&dtrace_provider_lock);
8387 		mutex_enter(&mod_lock);
8388 		mutex_enter(&dtrace_lock);
8389 	}
8390 
8391 	/*
8392 	 * If anyone has /dev/dtrace open, or if there are anonymous enabled
8393 	 * probes, we refuse to let providers slither away, unless this
8394 	 * provider has already been explicitly invalidated.
8395 	 */
8396 	if (!old->dtpv_defunct &&
8397 	    (dtrace_opens || (dtrace_anon.dta_state != NULL &&
8398 	    dtrace_anon.dta_state->dts_necbs > 0))) {
8399 		if (!self) {
8400 			mutex_exit(&dtrace_lock);
8401 			mutex_exit(&mod_lock);
8402 			mutex_exit(&dtrace_provider_lock);
8403 		}
8404 		return (EBUSY);
8405 	}
8406 
8407 	/*
8408 	 * Attempt to destroy the probes associated with this provider.
8409 	 */
8410 	for (i = 0; i < dtrace_nprobes; i++) {
8411 		if ((probe = dtrace_probes[i]) == NULL)
8412 			continue;
8413 
8414 		if (probe->dtpr_provider != old)
8415 			continue;
8416 
8417 		if (probe->dtpr_ecb == NULL)
8418 			continue;
8419 
8420 		/*
8421 		 * If we are trying to unregister a defunct provider, and the
8422 		 * provider was made defunct within the interval dictated by
8423 		 * dtrace_unregister_defunct_reap, we'll (asynchronously)
8424 		 * attempt to reap our enablings.  To denote that the provider
8425 		 * should reattempt to unregister itself at some point in the
8426 		 * future, we will return a differentiable error code (EAGAIN
8427 		 * instead of EBUSY) in this case.
8428 		 */
8429 		if (dtrace_gethrtime() - old->dtpv_defunct >
8430 		    dtrace_unregister_defunct_reap)
8431 			noreap = 1;
8432 
8433 		if (!self) {
8434 			mutex_exit(&dtrace_lock);
8435 			mutex_exit(&mod_lock);
8436 			mutex_exit(&dtrace_provider_lock);
8437 		}
8438 
8439 		if (noreap)
8440 			return (EBUSY);
8441 
8442 		(void) taskq_dispatch(dtrace_taskq,
8443 		    (task_func_t *)dtrace_enabling_reap, NULL, TQ_SLEEP);
8444 
8445 		return (EAGAIN);
8446 	}
8447 
8448 	/*
8449 	 * All of the probes for this provider are disabled; we can safely
8450 	 * remove all of them from their hash chains and from the probe array.
8451 	 */
8452 	for (i = 0; i < dtrace_nprobes; i++) {
8453 		if ((probe = dtrace_probes[i]) == NULL)
8454 			continue;
8455 
8456 		if (probe->dtpr_provider != old)
8457 			continue;
8458 
8459 		dtrace_probes[i] = NULL;
8460 
8461 		dtrace_hash_remove(dtrace_bymod, probe);
8462 		dtrace_hash_remove(dtrace_byfunc, probe);
8463 		dtrace_hash_remove(dtrace_byname, probe);
8464 
8465 		if (first == NULL) {
8466 			first = probe;
8467 			probe->dtpr_nextmod = NULL;
8468 		} else {
8469 			probe->dtpr_nextmod = first;
8470 			first = probe;
8471 		}
8472 	}
8473 
8474 	/*
8475 	 * The provider's probes have been removed from the hash chains and
8476 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
8477 	 * everyone has cleared out from any probe array processing.
8478 	 */
8479 	dtrace_sync();
8480 
8481 	for (probe = first; probe != NULL; probe = first) {
8482 		first = probe->dtpr_nextmod;
8483 
8484 		old->dtpv_pops.dtps_destroy(old->dtpv_arg, probe->dtpr_id,
8485 		    probe->dtpr_arg);
8486 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8487 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8488 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8489 		vmem_free(dtrace_arena, (void *)(uintptr_t)(probe->dtpr_id), 1);
8490 		kmem_free(probe, sizeof (dtrace_probe_t));
8491 	}
8492 
8493 	if ((prev = dtrace_provider) == old) {
8494 		ASSERT(self || dtrace_devi == NULL);
8495 		ASSERT(old->dtpv_next == NULL || dtrace_devi == NULL);
8496 		dtrace_provider = old->dtpv_next;
8497 	} else {
8498 		while (prev != NULL && prev->dtpv_next != old)
8499 			prev = prev->dtpv_next;
8500 
8501 		if (prev == NULL) {
8502 			panic("attempt to unregister non-existent "
8503 			    "dtrace provider %p\n", (void *)id);
8504 		}
8505 
8506 		prev->dtpv_next = old->dtpv_next;
8507 	}
8508 
8509 	if (!self) {
8510 		mutex_exit(&dtrace_lock);
8511 		mutex_exit(&mod_lock);
8512 		mutex_exit(&dtrace_provider_lock);
8513 	}
8514 
8515 	kmem_free(old->dtpv_name, strlen(old->dtpv_name) + 1);
8516 	kmem_free(old, sizeof (dtrace_provider_t));
8517 
8518 	return (0);
8519 }
8520 
8521 /*
8522  * Invalidate the specified provider.  All subsequent probe lookups for the
8523  * specified provider will fail, but its probes will not be removed.
8524  */
8525 void
8526 dtrace_invalidate(dtrace_provider_id_t id)
8527 {
8528 	dtrace_provider_t *pvp = (dtrace_provider_t *)id;
8529 
8530 	ASSERT(pvp->dtpv_pops.dtps_enable !=
8531 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8532 
8533 	mutex_enter(&dtrace_provider_lock);
8534 	mutex_enter(&dtrace_lock);
8535 
8536 	pvp->dtpv_defunct = dtrace_gethrtime();
8537 
8538 	mutex_exit(&dtrace_lock);
8539 	mutex_exit(&dtrace_provider_lock);
8540 }
8541 
8542 /*
8543  * Indicate whether or not DTrace has attached.
8544  */
8545 int
8546 dtrace_attached(void)
8547 {
8548 	/*
8549 	 * dtrace_provider will be non-NULL iff the DTrace driver has
8550 	 * attached.  (It's non-NULL because DTrace is always itself a
8551 	 * provider.)
8552 	 */
8553 	return (dtrace_provider != NULL);
8554 }
8555 
8556 /*
8557  * Remove all the unenabled probes for the given provider.  This function is
8558  * not unlike dtrace_unregister(), except that it doesn't remove the provider
8559  * -- just as many of its associated probes as it can.
8560  */
8561 int
8562 dtrace_condense(dtrace_provider_id_t id)
8563 {
8564 	dtrace_provider_t *prov = (dtrace_provider_t *)id;
8565 	int i;
8566 	dtrace_probe_t *probe;
8567 
8568 	/*
8569 	 * Make sure this isn't the dtrace provider itself.
8570 	 */
8571 	ASSERT(prov->dtpv_pops.dtps_enable !=
8572 	    (int (*)(void *, dtrace_id_t, void *))dtrace_enable_nullop);
8573 
8574 	mutex_enter(&dtrace_provider_lock);
8575 	mutex_enter(&dtrace_lock);
8576 
8577 	/*
8578 	 * Attempt to destroy the probes associated with this provider.
8579 	 */
8580 	for (i = 0; i < dtrace_nprobes; i++) {
8581 		if ((probe = dtrace_probes[i]) == NULL)
8582 			continue;
8583 
8584 		if (probe->dtpr_provider != prov)
8585 			continue;
8586 
8587 		if (probe->dtpr_ecb != NULL)
8588 			continue;
8589 
8590 		dtrace_probes[i] = NULL;
8591 
8592 		dtrace_hash_remove(dtrace_bymod, probe);
8593 		dtrace_hash_remove(dtrace_byfunc, probe);
8594 		dtrace_hash_remove(dtrace_byname, probe);
8595 
8596 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, i + 1,
8597 		    probe->dtpr_arg);
8598 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
8599 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
8600 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
8601 		kmem_free(probe, sizeof (dtrace_probe_t));
8602 		vmem_free(dtrace_arena, (void *)((uintptr_t)i + 1), 1);
8603 	}
8604 
8605 	mutex_exit(&dtrace_lock);
8606 	mutex_exit(&dtrace_provider_lock);
8607 
8608 	return (0);
8609 }
8610 
8611 /*
8612  * DTrace Probe Management Functions
8613  *
8614  * The functions in this section perform the DTrace probe management,
8615  * including functions to create probes, look-up probes, and call into the
8616  * providers to request that probes be provided.  Some of these functions are
8617  * in the Provider-to-Framework API; these functions can be identified by the
8618  * fact that they are not declared "static".
8619  */
8620 
8621 /*
8622  * Create a probe with the specified module name, function name, and name.
8623  */
8624 dtrace_id_t
8625 dtrace_probe_create(dtrace_provider_id_t prov, const char *mod,
8626     const char *func, const char *name, int aframes, void *arg)
8627 {
8628 	dtrace_probe_t *probe, **probes;
8629 	dtrace_provider_t *provider = (dtrace_provider_t *)prov;
8630 	dtrace_id_t id;
8631 
8632 	if (provider == dtrace_provider) {
8633 		ASSERT(MUTEX_HELD(&dtrace_lock));
8634 	} else {
8635 		mutex_enter(&dtrace_lock);
8636 	}
8637 
8638 	id = (dtrace_id_t)(uintptr_t)vmem_alloc(dtrace_arena, 1,
8639 	    VM_BESTFIT | VM_SLEEP);
8640 	probe = kmem_zalloc(sizeof (dtrace_probe_t), KM_SLEEP);
8641 
8642 	probe->dtpr_id = id;
8643 	probe->dtpr_gen = dtrace_probegen++;
8644 	probe->dtpr_mod = dtrace_strdup(mod);
8645 	probe->dtpr_func = dtrace_strdup(func);
8646 	probe->dtpr_name = dtrace_strdup(name);
8647 	probe->dtpr_arg = arg;
8648 	probe->dtpr_aframes = aframes;
8649 	probe->dtpr_provider = provider;
8650 
8651 	dtrace_hash_add(dtrace_bymod, probe);
8652 	dtrace_hash_add(dtrace_byfunc, probe);
8653 	dtrace_hash_add(dtrace_byname, probe);
8654 
8655 	if (id - 1 >= dtrace_nprobes) {
8656 		size_t osize = dtrace_nprobes * sizeof (dtrace_probe_t *);
8657 		size_t nsize = osize << 1;
8658 
8659 		if (nsize == 0) {
8660 			ASSERT(osize == 0);
8661 			ASSERT(dtrace_probes == NULL);
8662 			nsize = sizeof (dtrace_probe_t *);
8663 		}
8664 
8665 		probes = kmem_zalloc(nsize, KM_SLEEP);
8666 
8667 		if (dtrace_probes == NULL) {
8668 			ASSERT(osize == 0);
8669 			dtrace_probes = probes;
8670 			dtrace_nprobes = 1;
8671 		} else {
8672 			dtrace_probe_t **oprobes = dtrace_probes;
8673 
8674 			bcopy(oprobes, probes, osize);
8675 			dtrace_membar_producer();
8676 			dtrace_probes = probes;
8677 
8678 			dtrace_sync();
8679 
8680 			/*
8681 			 * All CPUs are now seeing the new probes array; we can
8682 			 * safely free the old array.
8683 			 */
8684 			kmem_free(oprobes, osize);
8685 			dtrace_nprobes <<= 1;
8686 		}
8687 
8688 		ASSERT(id - 1 < dtrace_nprobes);
8689 	}
8690 
8691 	ASSERT(dtrace_probes[id - 1] == NULL);
8692 	dtrace_probes[id - 1] = probe;
8693 
8694 	if (provider != dtrace_provider)
8695 		mutex_exit(&dtrace_lock);
8696 
8697 	return (id);
8698 }
8699 
8700 static dtrace_probe_t *
8701 dtrace_probe_lookup_id(dtrace_id_t id)
8702 {
8703 	ASSERT(MUTEX_HELD(&dtrace_lock));
8704 
8705 	if (id == 0 || id > dtrace_nprobes)
8706 		return (NULL);
8707 
8708 	return (dtrace_probes[id - 1]);
8709 }
8710 
8711 static int
8712 dtrace_probe_lookup_match(dtrace_probe_t *probe, void *arg)
8713 {
8714 	*((dtrace_id_t *)arg) = probe->dtpr_id;
8715 
8716 	return (DTRACE_MATCH_DONE);
8717 }
8718 
8719 /*
8720  * Look up a probe based on provider and one or more of module name, function
8721  * name and probe name.
8722  */
8723 dtrace_id_t
8724 dtrace_probe_lookup(dtrace_provider_id_t prid, const char *mod,
8725     const char *func, const char *name)
8726 {
8727 	dtrace_probekey_t pkey;
8728 	dtrace_id_t id;
8729 	int match;
8730 
8731 	pkey.dtpk_prov = ((dtrace_provider_t *)prid)->dtpv_name;
8732 	pkey.dtpk_pmatch = &dtrace_match_string;
8733 	pkey.dtpk_mod = mod;
8734 	pkey.dtpk_mmatch = mod ? &dtrace_match_string : &dtrace_match_nul;
8735 	pkey.dtpk_func = func;
8736 	pkey.dtpk_fmatch = func ? &dtrace_match_string : &dtrace_match_nul;
8737 	pkey.dtpk_name = name;
8738 	pkey.dtpk_nmatch = name ? &dtrace_match_string : &dtrace_match_nul;
8739 	pkey.dtpk_id = DTRACE_IDNONE;
8740 
8741 	mutex_enter(&dtrace_lock);
8742 	match = dtrace_match(&pkey, DTRACE_PRIV_ALL, 0, 0,
8743 	    dtrace_probe_lookup_match, &id);
8744 	mutex_exit(&dtrace_lock);
8745 
8746 	ASSERT(match == 1 || match == 0);
8747 	return (match ? id : 0);
8748 }
8749 
8750 /*
8751  * Returns the probe argument associated with the specified probe.
8752  */
8753 void *
8754 dtrace_probe_arg(dtrace_provider_id_t id, dtrace_id_t pid)
8755 {
8756 	dtrace_probe_t *probe;
8757 	void *rval = NULL;
8758 
8759 	mutex_enter(&dtrace_lock);
8760 
8761 	if ((probe = dtrace_probe_lookup_id(pid)) != NULL &&
8762 	    probe->dtpr_provider == (dtrace_provider_t *)id)
8763 		rval = probe->dtpr_arg;
8764 
8765 	mutex_exit(&dtrace_lock);
8766 
8767 	return (rval);
8768 }
8769 
8770 /*
8771  * Copy a probe into a probe description.
8772  */
8773 static void
8774 dtrace_probe_description(const dtrace_probe_t *prp, dtrace_probedesc_t *pdp)
8775 {
8776 	bzero(pdp, sizeof (dtrace_probedesc_t));
8777 	pdp->dtpd_id = prp->dtpr_id;
8778 
8779 	(void) strncpy(pdp->dtpd_provider,
8780 	    prp->dtpr_provider->dtpv_name, DTRACE_PROVNAMELEN - 1);
8781 
8782 	(void) strncpy(pdp->dtpd_mod, prp->dtpr_mod, DTRACE_MODNAMELEN - 1);
8783 	(void) strncpy(pdp->dtpd_func, prp->dtpr_func, DTRACE_FUNCNAMELEN - 1);
8784 	(void) strncpy(pdp->dtpd_name, prp->dtpr_name, DTRACE_NAMELEN - 1);
8785 }
8786 
8787 /*
8788  * Called to indicate that a probe -- or probes -- should be provided by a
8789  * specfied provider.  If the specified description is NULL, the provider will
8790  * be told to provide all of its probes.  (This is done whenever a new
8791  * consumer comes along, or whenever a retained enabling is to be matched.) If
8792  * the specified description is non-NULL, the provider is given the
8793  * opportunity to dynamically provide the specified probe, allowing providers
8794  * to support the creation of probes on-the-fly.  (So-called _autocreated_
8795  * probes.)  If the provider is NULL, the operations will be applied to all
8796  * providers; if the provider is non-NULL the operations will only be applied
8797  * to the specified provider.  The dtrace_provider_lock must be held, and the
8798  * dtrace_lock must _not_ be held -- the provider's dtps_provide() operation
8799  * will need to grab the dtrace_lock when it reenters the framework through
8800  * dtrace_probe_lookup(), dtrace_probe_create(), etc.
8801  */
8802 static void
8803 dtrace_probe_provide(dtrace_probedesc_t *desc, dtrace_provider_t *prv)
8804 {
8805 	struct modctl *ctl;
8806 	int all = 0;
8807 
8808 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
8809 
8810 	if (prv == NULL) {
8811 		all = 1;
8812 		prv = dtrace_provider;
8813 	}
8814 
8815 	do {
8816 		/*
8817 		 * First, call the blanket provide operation.
8818 		 */
8819 		prv->dtpv_pops.dtps_provide(prv->dtpv_arg, desc);
8820 
8821 		/*
8822 		 * Now call the per-module provide operation.  We will grab
8823 		 * mod_lock to prevent the list from being modified.  Note
8824 		 * that this also prevents the mod_busy bits from changing.
8825 		 * (mod_busy can only be changed with mod_lock held.)
8826 		 */
8827 		mutex_enter(&mod_lock);
8828 
8829 		ctl = &modules;
8830 		do {
8831 			if (ctl->mod_busy || ctl->mod_mp == NULL)
8832 				continue;
8833 
8834 			prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
8835 
8836 		} while ((ctl = ctl->mod_next) != &modules);
8837 
8838 		mutex_exit(&mod_lock);
8839 	} while (all && (prv = prv->dtpv_next) != NULL);
8840 }
8841 
8842 /*
8843  * Iterate over each probe, and call the Framework-to-Provider API function
8844  * denoted by offs.
8845  */
8846 static void
8847 dtrace_probe_foreach(uintptr_t offs)
8848 {
8849 	dtrace_provider_t *prov;
8850 	void (*func)(void *, dtrace_id_t, void *);
8851 	dtrace_probe_t *probe;
8852 	dtrace_icookie_t cookie;
8853 	int i;
8854 
8855 	/*
8856 	 * We disable interrupts to walk through the probe array.  This is
8857 	 * safe -- the dtrace_sync() in dtrace_unregister() assures that we
8858 	 * won't see stale data.
8859 	 */
8860 	cookie = dtrace_interrupt_disable();
8861 
8862 	for (i = 0; i < dtrace_nprobes; i++) {
8863 		if ((probe = dtrace_probes[i]) == NULL)
8864 			continue;
8865 
8866 		if (probe->dtpr_ecb == NULL) {
8867 			/*
8868 			 * This probe isn't enabled -- don't call the function.
8869 			 */
8870 			continue;
8871 		}
8872 
8873 		prov = probe->dtpr_provider;
8874 		func = *((void(**)(void *, dtrace_id_t, void *))
8875 		    ((uintptr_t)&prov->dtpv_pops + offs));
8876 
8877 		func(prov->dtpv_arg, i + 1, probe->dtpr_arg);
8878 	}
8879 
8880 	dtrace_interrupt_enable(cookie);
8881 }
8882 
8883 static int
8884 dtrace_probe_enable(const dtrace_probedesc_t *desc, dtrace_enabling_t *enab)
8885 {
8886 	dtrace_probekey_t pkey;
8887 	uint32_t priv;
8888 	uid_t uid;
8889 	zoneid_t zoneid;
8890 
8891 	ASSERT(MUTEX_HELD(&dtrace_lock));
8892 	dtrace_ecb_create_cache = NULL;
8893 
8894 	if (desc == NULL) {
8895 		/*
8896 		 * If we're passed a NULL description, we're being asked to
8897 		 * create an ECB with a NULL probe.
8898 		 */
8899 		(void) dtrace_ecb_create_enable(NULL, enab);
8900 		return (0);
8901 	}
8902 
8903 	dtrace_probekey(desc, &pkey);
8904 	dtrace_cred2priv(enab->dten_vstate->dtvs_state->dts_cred.dcr_cred,
8905 	    &priv, &uid, &zoneid);
8906 
8907 	return (dtrace_match(&pkey, priv, uid, zoneid, dtrace_ecb_create_enable,
8908 	    enab));
8909 }
8910 
8911 /*
8912  * DTrace Helper Provider Functions
8913  */
8914 static void
8915 dtrace_dofattr2attr(dtrace_attribute_t *attr, const dof_attr_t dofattr)
8916 {
8917 	attr->dtat_name = DOF_ATTR_NAME(dofattr);
8918 	attr->dtat_data = DOF_ATTR_DATA(dofattr);
8919 	attr->dtat_class = DOF_ATTR_CLASS(dofattr);
8920 }
8921 
8922 static void
8923 dtrace_dofprov2hprov(dtrace_helper_provdesc_t *hprov,
8924     const dof_provider_t *dofprov, char *strtab)
8925 {
8926 	hprov->dthpv_provname = strtab + dofprov->dofpv_name;
8927 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_provider,
8928 	    dofprov->dofpv_provattr);
8929 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_mod,
8930 	    dofprov->dofpv_modattr);
8931 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_func,
8932 	    dofprov->dofpv_funcattr);
8933 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_name,
8934 	    dofprov->dofpv_nameattr);
8935 	dtrace_dofattr2attr(&hprov->dthpv_pattr.dtpa_args,
8936 	    dofprov->dofpv_argsattr);
8937 }
8938 
8939 static void
8940 dtrace_helper_provide_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
8941 {
8942 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
8943 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
8944 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
8945 	dof_provider_t *provider;
8946 	dof_probe_t *probe;
8947 	uint32_t *off, *enoff;
8948 	uint8_t *arg;
8949 	char *strtab;
8950 	uint_t i, nprobes;
8951 	dtrace_helper_provdesc_t dhpv;
8952 	dtrace_helper_probedesc_t dhpb;
8953 	dtrace_meta_t *meta = dtrace_meta_pid;
8954 	dtrace_mops_t *mops = &meta->dtm_mops;
8955 	void *parg;
8956 
8957 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
8958 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8959 	    provider->dofpv_strtab * dof->dofh_secsize);
8960 	prb_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8961 	    provider->dofpv_probes * dof->dofh_secsize);
8962 	arg_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8963 	    provider->dofpv_prargs * dof->dofh_secsize);
8964 	off_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8965 	    provider->dofpv_proffs * dof->dofh_secsize);
8966 
8967 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
8968 	off = (uint32_t *)(uintptr_t)(daddr + off_sec->dofs_offset);
8969 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
8970 	enoff = NULL;
8971 
8972 	/*
8973 	 * See dtrace_helper_provider_validate().
8974 	 */
8975 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
8976 	    provider->dofpv_prenoffs != DOF_SECT_NONE) {
8977 		enoff_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
8978 		    provider->dofpv_prenoffs * dof->dofh_secsize);
8979 		enoff = (uint32_t *)(uintptr_t)(daddr + enoff_sec->dofs_offset);
8980 	}
8981 
8982 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
8983 
8984 	/*
8985 	 * Create the provider.
8986 	 */
8987 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
8988 
8989 	if ((parg = mops->dtms_provide_pid(meta->dtm_arg, &dhpv, pid)) == NULL)
8990 		return;
8991 
8992 	meta->dtm_count++;
8993 
8994 	/*
8995 	 * Create the probes.
8996 	 */
8997 	for (i = 0; i < nprobes; i++) {
8998 		probe = (dof_probe_t *)(uintptr_t)(daddr +
8999 		    prb_sec->dofs_offset + i * prb_sec->dofs_entsize);
9000 
9001 		dhpb.dthpb_mod = dhp->dofhp_mod;
9002 		dhpb.dthpb_func = strtab + probe->dofpr_func;
9003 		dhpb.dthpb_name = strtab + probe->dofpr_name;
9004 		dhpb.dthpb_base = probe->dofpr_addr;
9005 		dhpb.dthpb_offs = off + probe->dofpr_offidx;
9006 		dhpb.dthpb_noffs = probe->dofpr_noffs;
9007 		if (enoff != NULL) {
9008 			dhpb.dthpb_enoffs = enoff + probe->dofpr_enoffidx;
9009 			dhpb.dthpb_nenoffs = probe->dofpr_nenoffs;
9010 		} else {
9011 			dhpb.dthpb_enoffs = NULL;
9012 			dhpb.dthpb_nenoffs = 0;
9013 		}
9014 		dhpb.dthpb_args = arg + probe->dofpr_argidx;
9015 		dhpb.dthpb_nargc = probe->dofpr_nargc;
9016 		dhpb.dthpb_xargc = probe->dofpr_xargc;
9017 		dhpb.dthpb_ntypes = strtab + probe->dofpr_nargv;
9018 		dhpb.dthpb_xtypes = strtab + probe->dofpr_xargv;
9019 
9020 		mops->dtms_create_probe(meta->dtm_arg, parg, &dhpb);
9021 	}
9022 }
9023 
9024 static void
9025 dtrace_helper_provide(dof_helper_t *dhp, pid_t pid)
9026 {
9027 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9028 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9029 	int i;
9030 
9031 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9032 
9033 	for (i = 0; i < dof->dofh_secnum; i++) {
9034 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9035 		    dof->dofh_secoff + i * dof->dofh_secsize);
9036 
9037 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9038 			continue;
9039 
9040 		dtrace_helper_provide_one(dhp, sec, pid);
9041 	}
9042 
9043 	/*
9044 	 * We may have just created probes, so we must now rematch against
9045 	 * any retained enablings.  Note that this call will acquire both
9046 	 * cpu_lock and dtrace_lock; the fact that we are holding
9047 	 * dtrace_meta_lock now is what defines the ordering with respect to
9048 	 * these three locks.
9049 	 */
9050 	dtrace_enabling_matchall();
9051 }
9052 
9053 static void
9054 dtrace_helper_provider_remove_one(dof_helper_t *dhp, dof_sec_t *sec, pid_t pid)
9055 {
9056 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9057 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9058 	dof_sec_t *str_sec;
9059 	dof_provider_t *provider;
9060 	char *strtab;
9061 	dtrace_helper_provdesc_t dhpv;
9062 	dtrace_meta_t *meta = dtrace_meta_pid;
9063 	dtrace_mops_t *mops = &meta->dtm_mops;
9064 
9065 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
9066 	str_sec = (dof_sec_t *)(uintptr_t)(daddr + dof->dofh_secoff +
9067 	    provider->dofpv_strtab * dof->dofh_secsize);
9068 
9069 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
9070 
9071 	/*
9072 	 * Create the provider.
9073 	 */
9074 	dtrace_dofprov2hprov(&dhpv, provider, strtab);
9075 
9076 	mops->dtms_remove_pid(meta->dtm_arg, &dhpv, pid);
9077 
9078 	meta->dtm_count--;
9079 }
9080 
9081 static void
9082 dtrace_helper_provider_remove(dof_helper_t *dhp, pid_t pid)
9083 {
9084 	uintptr_t daddr = (uintptr_t)dhp->dofhp_dof;
9085 	dof_hdr_t *dof = (dof_hdr_t *)daddr;
9086 	int i;
9087 
9088 	ASSERT(MUTEX_HELD(&dtrace_meta_lock));
9089 
9090 	for (i = 0; i < dof->dofh_secnum; i++) {
9091 		dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
9092 		    dof->dofh_secoff + i * dof->dofh_secsize);
9093 
9094 		if (sec->dofs_type != DOF_SECT_PROVIDER)
9095 			continue;
9096 
9097 		dtrace_helper_provider_remove_one(dhp, sec, pid);
9098 	}
9099 }
9100 
9101 /*
9102  * DTrace Meta Provider-to-Framework API Functions
9103  *
9104  * These functions implement the Meta Provider-to-Framework API, as described
9105  * in <sys/dtrace.h>.
9106  */
9107 int
9108 dtrace_meta_register(const char *name, const dtrace_mops_t *mops, void *arg,
9109     dtrace_meta_provider_id_t *idp)
9110 {
9111 	dtrace_meta_t *meta;
9112 	dtrace_helpers_t *help, *next;
9113 	int i;
9114 
9115 	*idp = DTRACE_METAPROVNONE;
9116 
9117 	/*
9118 	 * We strictly don't need the name, but we hold onto it for
9119 	 * debuggability. All hail error queues!
9120 	 */
9121 	if (name == NULL) {
9122 		cmn_err(CE_WARN, "failed to register meta-provider: "
9123 		    "invalid name");
9124 		return (EINVAL);
9125 	}
9126 
9127 	if (mops == NULL ||
9128 	    mops->dtms_create_probe == NULL ||
9129 	    mops->dtms_provide_pid == NULL ||
9130 	    mops->dtms_remove_pid == NULL) {
9131 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9132 		    "invalid ops", name);
9133 		return (EINVAL);
9134 	}
9135 
9136 	meta = kmem_zalloc(sizeof (dtrace_meta_t), KM_SLEEP);
9137 	meta->dtm_mops = *mops;
9138 	meta->dtm_name = kmem_alloc(strlen(name) + 1, KM_SLEEP);
9139 	(void) strcpy(meta->dtm_name, name);
9140 	meta->dtm_arg = arg;
9141 
9142 	mutex_enter(&dtrace_meta_lock);
9143 	mutex_enter(&dtrace_lock);
9144 
9145 	if (dtrace_meta_pid != NULL) {
9146 		mutex_exit(&dtrace_lock);
9147 		mutex_exit(&dtrace_meta_lock);
9148 		cmn_err(CE_WARN, "failed to register meta-register %s: "
9149 		    "user-land meta-provider exists", name);
9150 		kmem_free(meta->dtm_name, strlen(meta->dtm_name) + 1);
9151 		kmem_free(meta, sizeof (dtrace_meta_t));
9152 		return (EINVAL);
9153 	}
9154 
9155 	dtrace_meta_pid = meta;
9156 	*idp = (dtrace_meta_provider_id_t)meta;
9157 
9158 	/*
9159 	 * If there are providers and probes ready to go, pass them
9160 	 * off to the new meta provider now.
9161 	 */
9162 
9163 	help = dtrace_deferred_pid;
9164 	dtrace_deferred_pid = NULL;
9165 
9166 	mutex_exit(&dtrace_lock);
9167 
9168 	while (help != NULL) {
9169 		for (i = 0; i < help->dthps_nprovs; i++) {
9170 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
9171 			    help->dthps_pid);
9172 		}
9173 
9174 		next = help->dthps_next;
9175 		help->dthps_next = NULL;
9176 		help->dthps_prev = NULL;
9177 		help->dthps_deferred = 0;
9178 		help = next;
9179 	}
9180 
9181 	mutex_exit(&dtrace_meta_lock);
9182 
9183 	return (0);
9184 }
9185 
9186 int
9187 dtrace_meta_unregister(dtrace_meta_provider_id_t id)
9188 {
9189 	dtrace_meta_t **pp, *old = (dtrace_meta_t *)id;
9190 
9191 	mutex_enter(&dtrace_meta_lock);
9192 	mutex_enter(&dtrace_lock);
9193 
9194 	if (old == dtrace_meta_pid) {
9195 		pp = &dtrace_meta_pid;
9196 	} else {
9197 		panic("attempt to unregister non-existent "
9198 		    "dtrace meta-provider %p\n", (void *)old);
9199 	}
9200 
9201 	if (old->dtm_count != 0) {
9202 		mutex_exit(&dtrace_lock);
9203 		mutex_exit(&dtrace_meta_lock);
9204 		return (EBUSY);
9205 	}
9206 
9207 	*pp = NULL;
9208 
9209 	mutex_exit(&dtrace_lock);
9210 	mutex_exit(&dtrace_meta_lock);
9211 
9212 	kmem_free(old->dtm_name, strlen(old->dtm_name) + 1);
9213 	kmem_free(old, sizeof (dtrace_meta_t));
9214 
9215 	return (0);
9216 }
9217 
9218 
9219 /*
9220  * DTrace DIF Object Functions
9221  */
9222 static int
9223 dtrace_difo_err(uint_t pc, const char *format, ...)
9224 {
9225 	if (dtrace_err_verbose) {
9226 		va_list alist;
9227 
9228 		(void) uprintf("dtrace DIF object error: [%u]: ", pc);
9229 		va_start(alist, format);
9230 		(void) vuprintf(format, alist);
9231 		va_end(alist);
9232 	}
9233 
9234 #ifdef DTRACE_ERRDEBUG
9235 	dtrace_errdebug(format);
9236 #endif
9237 	return (1);
9238 }
9239 
9240 /*
9241  * Validate a DTrace DIF object by checking the IR instructions.  The following
9242  * rules are currently enforced by dtrace_difo_validate():
9243  *
9244  * 1. Each instruction must have a valid opcode
9245  * 2. Each register, string, variable, or subroutine reference must be valid
9246  * 3. No instruction can modify register %r0 (must be zero)
9247  * 4. All instruction reserved bits must be set to zero
9248  * 5. The last instruction must be a "ret" instruction
9249  * 6. All branch targets must reference a valid instruction _after_ the branch
9250  */
9251 static int
9252 dtrace_difo_validate(dtrace_difo_t *dp, dtrace_vstate_t *vstate, uint_t nregs,
9253     cred_t *cr)
9254 {
9255 	int err = 0, i;
9256 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9257 	int kcheckload;
9258 	uint_t pc;
9259 	int maxglobal = -1, maxlocal = -1, maxtlocal = -1;
9260 
9261 	kcheckload = cr == NULL ||
9262 	    (vstate->dtvs_state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) == 0;
9263 
9264 	dp->dtdo_destructive = 0;
9265 
9266 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9267 		dif_instr_t instr = dp->dtdo_buf[pc];
9268 
9269 		uint_t r1 = DIF_INSTR_R1(instr);
9270 		uint_t r2 = DIF_INSTR_R2(instr);
9271 		uint_t rd = DIF_INSTR_RD(instr);
9272 		uint_t rs = DIF_INSTR_RS(instr);
9273 		uint_t label = DIF_INSTR_LABEL(instr);
9274 		uint_t v = DIF_INSTR_VAR(instr);
9275 		uint_t subr = DIF_INSTR_SUBR(instr);
9276 		uint_t type = DIF_INSTR_TYPE(instr);
9277 		uint_t op = DIF_INSTR_OP(instr);
9278 
9279 		switch (op) {
9280 		case DIF_OP_OR:
9281 		case DIF_OP_XOR:
9282 		case DIF_OP_AND:
9283 		case DIF_OP_SLL:
9284 		case DIF_OP_SRL:
9285 		case DIF_OP_SRA:
9286 		case DIF_OP_SUB:
9287 		case DIF_OP_ADD:
9288 		case DIF_OP_MUL:
9289 		case DIF_OP_SDIV:
9290 		case DIF_OP_UDIV:
9291 		case DIF_OP_SREM:
9292 		case DIF_OP_UREM:
9293 		case DIF_OP_COPYS:
9294 			if (r1 >= nregs)
9295 				err += efunc(pc, "invalid register %u\n", r1);
9296 			if (r2 >= nregs)
9297 				err += efunc(pc, "invalid register %u\n", r2);
9298 			if (rd >= nregs)
9299 				err += efunc(pc, "invalid register %u\n", rd);
9300 			if (rd == 0)
9301 				err += efunc(pc, "cannot write to %r0\n");
9302 			break;
9303 		case DIF_OP_NOT:
9304 		case DIF_OP_MOV:
9305 		case DIF_OP_ALLOCS:
9306 			if (r1 >= nregs)
9307 				err += efunc(pc, "invalid register %u\n", r1);
9308 			if (r2 != 0)
9309 				err += efunc(pc, "non-zero reserved bits\n");
9310 			if (rd >= nregs)
9311 				err += efunc(pc, "invalid register %u\n", rd);
9312 			if (rd == 0)
9313 				err += efunc(pc, "cannot write to %r0\n");
9314 			break;
9315 		case DIF_OP_LDSB:
9316 		case DIF_OP_LDSH:
9317 		case DIF_OP_LDSW:
9318 		case DIF_OP_LDUB:
9319 		case DIF_OP_LDUH:
9320 		case DIF_OP_LDUW:
9321 		case DIF_OP_LDX:
9322 			if (r1 >= nregs)
9323 				err += efunc(pc, "invalid register %u\n", r1);
9324 			if (r2 != 0)
9325 				err += efunc(pc, "non-zero reserved bits\n");
9326 			if (rd >= nregs)
9327 				err += efunc(pc, "invalid register %u\n", rd);
9328 			if (rd == 0)
9329 				err += efunc(pc, "cannot write to %r0\n");
9330 			if (kcheckload)
9331 				dp->dtdo_buf[pc] = DIF_INSTR_LOAD(op +
9332 				    DIF_OP_RLDSB - DIF_OP_LDSB, r1, rd);
9333 			break;
9334 		case DIF_OP_RLDSB:
9335 		case DIF_OP_RLDSH:
9336 		case DIF_OP_RLDSW:
9337 		case DIF_OP_RLDUB:
9338 		case DIF_OP_RLDUH:
9339 		case DIF_OP_RLDUW:
9340 		case DIF_OP_RLDX:
9341 			if (r1 >= nregs)
9342 				err += efunc(pc, "invalid register %u\n", r1);
9343 			if (r2 != 0)
9344 				err += efunc(pc, "non-zero reserved bits\n");
9345 			if (rd >= nregs)
9346 				err += efunc(pc, "invalid register %u\n", rd);
9347 			if (rd == 0)
9348 				err += efunc(pc, "cannot write to %r0\n");
9349 			break;
9350 		case DIF_OP_ULDSB:
9351 		case DIF_OP_ULDSH:
9352 		case DIF_OP_ULDSW:
9353 		case DIF_OP_ULDUB:
9354 		case DIF_OP_ULDUH:
9355 		case DIF_OP_ULDUW:
9356 		case DIF_OP_ULDX:
9357 			if (r1 >= nregs)
9358 				err += efunc(pc, "invalid register %u\n", r1);
9359 			if (r2 != 0)
9360 				err += efunc(pc, "non-zero reserved bits\n");
9361 			if (rd >= nregs)
9362 				err += efunc(pc, "invalid register %u\n", rd);
9363 			if (rd == 0)
9364 				err += efunc(pc, "cannot write to %r0\n");
9365 			break;
9366 		case DIF_OP_STB:
9367 		case DIF_OP_STH:
9368 		case DIF_OP_STW:
9369 		case DIF_OP_STX:
9370 			if (r1 >= nregs)
9371 				err += efunc(pc, "invalid register %u\n", r1);
9372 			if (r2 != 0)
9373 				err += efunc(pc, "non-zero reserved bits\n");
9374 			if (rd >= nregs)
9375 				err += efunc(pc, "invalid register %u\n", rd);
9376 			if (rd == 0)
9377 				err += efunc(pc, "cannot write to 0 address\n");
9378 			break;
9379 		case DIF_OP_CMP:
9380 		case DIF_OP_SCMP:
9381 			if (r1 >= nregs)
9382 				err += efunc(pc, "invalid register %u\n", r1);
9383 			if (r2 >= nregs)
9384 				err += efunc(pc, "invalid register %u\n", r2);
9385 			if (rd != 0)
9386 				err += efunc(pc, "non-zero reserved bits\n");
9387 			break;
9388 		case DIF_OP_TST:
9389 			if (r1 >= nregs)
9390 				err += efunc(pc, "invalid register %u\n", r1);
9391 			if (r2 != 0 || rd != 0)
9392 				err += efunc(pc, "non-zero reserved bits\n");
9393 			break;
9394 		case DIF_OP_BA:
9395 		case DIF_OP_BE:
9396 		case DIF_OP_BNE:
9397 		case DIF_OP_BG:
9398 		case DIF_OP_BGU:
9399 		case DIF_OP_BGE:
9400 		case DIF_OP_BGEU:
9401 		case DIF_OP_BL:
9402 		case DIF_OP_BLU:
9403 		case DIF_OP_BLE:
9404 		case DIF_OP_BLEU:
9405 			if (label >= dp->dtdo_len) {
9406 				err += efunc(pc, "invalid branch target %u\n",
9407 				    label);
9408 			}
9409 			if (label <= pc) {
9410 				err += efunc(pc, "backward branch to %u\n",
9411 				    label);
9412 			}
9413 			break;
9414 		case DIF_OP_RET:
9415 			if (r1 != 0 || r2 != 0)
9416 				err += efunc(pc, "non-zero reserved bits\n");
9417 			if (rd >= nregs)
9418 				err += efunc(pc, "invalid register %u\n", rd);
9419 			break;
9420 		case DIF_OP_NOP:
9421 		case DIF_OP_POPTS:
9422 		case DIF_OP_FLUSHTS:
9423 			if (r1 != 0 || r2 != 0 || rd != 0)
9424 				err += efunc(pc, "non-zero reserved bits\n");
9425 			break;
9426 		case DIF_OP_SETX:
9427 			if (DIF_INSTR_INTEGER(instr) >= dp->dtdo_intlen) {
9428 				err += efunc(pc, "invalid integer ref %u\n",
9429 				    DIF_INSTR_INTEGER(instr));
9430 			}
9431 			if (rd >= nregs)
9432 				err += efunc(pc, "invalid register %u\n", rd);
9433 			if (rd == 0)
9434 				err += efunc(pc, "cannot write to %r0\n");
9435 			break;
9436 		case DIF_OP_SETS:
9437 			if (DIF_INSTR_STRING(instr) >= dp->dtdo_strlen) {
9438 				err += efunc(pc, "invalid string ref %u\n",
9439 				    DIF_INSTR_STRING(instr));
9440 			}
9441 			if (rd >= nregs)
9442 				err += efunc(pc, "invalid register %u\n", rd);
9443 			if (rd == 0)
9444 				err += efunc(pc, "cannot write to %r0\n");
9445 			break;
9446 		case DIF_OP_LDGA:
9447 		case DIF_OP_LDTA:
9448 			if (r1 > DIF_VAR_ARRAY_MAX)
9449 				err += efunc(pc, "invalid array %u\n", r1);
9450 			if (r2 >= nregs)
9451 				err += efunc(pc, "invalid register %u\n", r2);
9452 			if (rd >= nregs)
9453 				err += efunc(pc, "invalid register %u\n", rd);
9454 			if (rd == 0)
9455 				err += efunc(pc, "cannot write to %r0\n");
9456 			break;
9457 		case DIF_OP_STGA:
9458 			if (r1 > DIF_VAR_ARRAY_MAX)
9459 				err += efunc(pc, "invalid array %u\n", r1);
9460 			if (r2 >= nregs)
9461 				err += efunc(pc, "invalid register %u\n", r2);
9462 			if (rd >= nregs)
9463 				err += efunc(pc, "invalid register %u\n", rd);
9464 			dp->dtdo_destructive = 1;
9465 			break;
9466 		case DIF_OP_LDGS:
9467 		case DIF_OP_LDTS:
9468 		case DIF_OP_LDLS:
9469 		case DIF_OP_LDGAA:
9470 		case DIF_OP_LDTAA:
9471 			if (v < DIF_VAR_OTHER_MIN || v > DIF_VAR_OTHER_MAX)
9472 				err += efunc(pc, "invalid variable %u\n", v);
9473 			if (rd >= nregs)
9474 				err += efunc(pc, "invalid register %u\n", rd);
9475 			if (rd == 0)
9476 				err += efunc(pc, "cannot write to %r0\n");
9477 			break;
9478 		case DIF_OP_STGS:
9479 		case DIF_OP_STTS:
9480 		case DIF_OP_STLS:
9481 		case DIF_OP_STGAA:
9482 		case DIF_OP_STTAA:
9483 			if (v < DIF_VAR_OTHER_UBASE || v > DIF_VAR_OTHER_MAX)
9484 				err += efunc(pc, "invalid variable %u\n", v);
9485 			if (rs >= nregs)
9486 				err += efunc(pc, "invalid register %u\n", rd);
9487 			break;
9488 		case DIF_OP_CALL:
9489 			if (subr > DIF_SUBR_MAX)
9490 				err += efunc(pc, "invalid subr %u\n", subr);
9491 			if (rd >= nregs)
9492 				err += efunc(pc, "invalid register %u\n", rd);
9493 			if (rd == 0)
9494 				err += efunc(pc, "cannot write to %r0\n");
9495 
9496 			if (subr == DIF_SUBR_COPYOUT ||
9497 			    subr == DIF_SUBR_COPYOUTSTR) {
9498 				dp->dtdo_destructive = 1;
9499 			}
9500 
9501 			if (subr == DIF_SUBR_GETF) {
9502 				/*
9503 				 * If we have a getf() we need to record that
9504 				 * in our state.  Note that our state can be
9505 				 * NULL if this is a helper -- but in that
9506 				 * case, the call to getf() is itself illegal,
9507 				 * and will be caught (slightly later) when
9508 				 * the helper is validated.
9509 				 */
9510 				if (vstate->dtvs_state != NULL)
9511 					vstate->dtvs_state->dts_getf++;
9512 			}
9513 
9514 			break;
9515 		case DIF_OP_PUSHTR:
9516 			if (type != DIF_TYPE_STRING && type != DIF_TYPE_CTF)
9517 				err += efunc(pc, "invalid ref type %u\n", type);
9518 			if (r2 >= nregs)
9519 				err += efunc(pc, "invalid register %u\n", r2);
9520 			if (rs >= nregs)
9521 				err += efunc(pc, "invalid register %u\n", rs);
9522 			break;
9523 		case DIF_OP_PUSHTV:
9524 			if (type != DIF_TYPE_CTF)
9525 				err += efunc(pc, "invalid val type %u\n", type);
9526 			if (r2 >= nregs)
9527 				err += efunc(pc, "invalid register %u\n", r2);
9528 			if (rs >= nregs)
9529 				err += efunc(pc, "invalid register %u\n", rs);
9530 			break;
9531 		default:
9532 			err += efunc(pc, "invalid opcode %u\n",
9533 			    DIF_INSTR_OP(instr));
9534 		}
9535 	}
9536 
9537 	if (dp->dtdo_len != 0 &&
9538 	    DIF_INSTR_OP(dp->dtdo_buf[dp->dtdo_len - 1]) != DIF_OP_RET) {
9539 		err += efunc(dp->dtdo_len - 1,
9540 		    "expected 'ret' as last DIF instruction\n");
9541 	}
9542 
9543 	if (!(dp->dtdo_rtype.dtdt_flags & (DIF_TF_BYREF | DIF_TF_BYUREF))) {
9544 		/*
9545 		 * If we're not returning by reference, the size must be either
9546 		 * 0 or the size of one of the base types.
9547 		 */
9548 		switch (dp->dtdo_rtype.dtdt_size) {
9549 		case 0:
9550 		case sizeof (uint8_t):
9551 		case sizeof (uint16_t):
9552 		case sizeof (uint32_t):
9553 		case sizeof (uint64_t):
9554 			break;
9555 
9556 		default:
9557 			err += efunc(dp->dtdo_len - 1, "bad return size\n");
9558 		}
9559 	}
9560 
9561 	for (i = 0; i < dp->dtdo_varlen && err == 0; i++) {
9562 		dtrace_difv_t *v = &dp->dtdo_vartab[i], *existing = NULL;
9563 		dtrace_diftype_t *vt, *et;
9564 		uint_t id, ndx;
9565 
9566 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL &&
9567 		    v->dtdv_scope != DIFV_SCOPE_THREAD &&
9568 		    v->dtdv_scope != DIFV_SCOPE_LOCAL) {
9569 			err += efunc(i, "unrecognized variable scope %d\n",
9570 			    v->dtdv_scope);
9571 			break;
9572 		}
9573 
9574 		if (v->dtdv_kind != DIFV_KIND_ARRAY &&
9575 		    v->dtdv_kind != DIFV_KIND_SCALAR) {
9576 			err += efunc(i, "unrecognized variable type %d\n",
9577 			    v->dtdv_kind);
9578 			break;
9579 		}
9580 
9581 		if ((id = v->dtdv_id) > DIF_VARIABLE_MAX) {
9582 			err += efunc(i, "%d exceeds variable id limit\n", id);
9583 			break;
9584 		}
9585 
9586 		if (id < DIF_VAR_OTHER_UBASE)
9587 			continue;
9588 
9589 		/*
9590 		 * For user-defined variables, we need to check that this
9591 		 * definition is identical to any previous definition that we
9592 		 * encountered.
9593 		 */
9594 		ndx = id - DIF_VAR_OTHER_UBASE;
9595 
9596 		switch (v->dtdv_scope) {
9597 		case DIFV_SCOPE_GLOBAL:
9598 			if (maxglobal == -1 || ndx > maxglobal)
9599 				maxglobal = ndx;
9600 
9601 			if (ndx < vstate->dtvs_nglobals) {
9602 				dtrace_statvar_t *svar;
9603 
9604 				if ((svar = vstate->dtvs_globals[ndx]) != NULL)
9605 					existing = &svar->dtsv_var;
9606 			}
9607 
9608 			break;
9609 
9610 		case DIFV_SCOPE_THREAD:
9611 			if (maxtlocal == -1 || ndx > maxtlocal)
9612 				maxtlocal = ndx;
9613 
9614 			if (ndx < vstate->dtvs_ntlocals)
9615 				existing = &vstate->dtvs_tlocals[ndx];
9616 			break;
9617 
9618 		case DIFV_SCOPE_LOCAL:
9619 			if (maxlocal == -1 || ndx > maxlocal)
9620 				maxlocal = ndx;
9621 
9622 			if (ndx < vstate->dtvs_nlocals) {
9623 				dtrace_statvar_t *svar;
9624 
9625 				if ((svar = vstate->dtvs_locals[ndx]) != NULL)
9626 					existing = &svar->dtsv_var;
9627 			}
9628 
9629 			break;
9630 		}
9631 
9632 		vt = &v->dtdv_type;
9633 
9634 		if (vt->dtdt_flags & DIF_TF_BYREF) {
9635 			if (vt->dtdt_size == 0) {
9636 				err += efunc(i, "zero-sized variable\n");
9637 				break;
9638 			}
9639 
9640 			if ((v->dtdv_scope == DIFV_SCOPE_GLOBAL ||
9641 			    v->dtdv_scope == DIFV_SCOPE_LOCAL) &&
9642 			    vt->dtdt_size > dtrace_statvar_maxsize) {
9643 				err += efunc(i, "oversized by-ref static\n");
9644 				break;
9645 			}
9646 		}
9647 
9648 		if (existing == NULL || existing->dtdv_id == 0)
9649 			continue;
9650 
9651 		ASSERT(existing->dtdv_id == v->dtdv_id);
9652 		ASSERT(existing->dtdv_scope == v->dtdv_scope);
9653 
9654 		if (existing->dtdv_kind != v->dtdv_kind)
9655 			err += efunc(i, "%d changed variable kind\n", id);
9656 
9657 		et = &existing->dtdv_type;
9658 
9659 		if (vt->dtdt_flags != et->dtdt_flags) {
9660 			err += efunc(i, "%d changed variable type flags\n", id);
9661 			break;
9662 		}
9663 
9664 		if (vt->dtdt_size != 0 && vt->dtdt_size != et->dtdt_size) {
9665 			err += efunc(i, "%d changed variable type size\n", id);
9666 			break;
9667 		}
9668 	}
9669 
9670 	for (pc = 0; pc < dp->dtdo_len && err == 0; pc++) {
9671 		dif_instr_t instr = dp->dtdo_buf[pc];
9672 
9673 		uint_t v = DIF_INSTR_VAR(instr);
9674 		uint_t op = DIF_INSTR_OP(instr);
9675 
9676 		switch (op) {
9677 		case DIF_OP_LDGS:
9678 		case DIF_OP_LDGAA:
9679 		case DIF_OP_STGS:
9680 		case DIF_OP_STGAA:
9681 			if (v > DIF_VAR_OTHER_UBASE + maxglobal)
9682 				err += efunc(pc, "invalid variable %u\n", v);
9683 			break;
9684 		case DIF_OP_LDTS:
9685 		case DIF_OP_LDTAA:
9686 		case DIF_OP_STTS:
9687 		case DIF_OP_STTAA:
9688 			if (v > DIF_VAR_OTHER_UBASE + maxtlocal)
9689 				err += efunc(pc, "invalid variable %u\n", v);
9690 			break;
9691 		case DIF_OP_LDLS:
9692 		case DIF_OP_STLS:
9693 			if (v > DIF_VAR_OTHER_UBASE + maxlocal)
9694 				err += efunc(pc, "invalid variable %u\n", v);
9695 			break;
9696 		default:
9697 			break;
9698 		}
9699 	}
9700 
9701 	return (err);
9702 }
9703 
9704 /*
9705  * Validate a DTrace DIF object that it is to be used as a helper.  Helpers
9706  * are much more constrained than normal DIFOs.  Specifically, they may
9707  * not:
9708  *
9709  * 1. Make calls to subroutines other than copyin(), copyinstr() or
9710  *    miscellaneous string routines
9711  * 2. Access DTrace variables other than the args[] array, and the
9712  *    curthread, pid, ppid, tid, execname, zonename, uid and gid variables.
9713  * 3. Have thread-local variables.
9714  * 4. Have dynamic variables.
9715  */
9716 static int
9717 dtrace_difo_validate_helper(dtrace_difo_t *dp)
9718 {
9719 	int (*efunc)(uint_t pc, const char *, ...) = dtrace_difo_err;
9720 	int err = 0;
9721 	uint_t pc;
9722 
9723 	for (pc = 0; pc < dp->dtdo_len; pc++) {
9724 		dif_instr_t instr = dp->dtdo_buf[pc];
9725 
9726 		uint_t v = DIF_INSTR_VAR(instr);
9727 		uint_t subr = DIF_INSTR_SUBR(instr);
9728 		uint_t op = DIF_INSTR_OP(instr);
9729 
9730 		switch (op) {
9731 		case DIF_OP_OR:
9732 		case DIF_OP_XOR:
9733 		case DIF_OP_AND:
9734 		case DIF_OP_SLL:
9735 		case DIF_OP_SRL:
9736 		case DIF_OP_SRA:
9737 		case DIF_OP_SUB:
9738 		case DIF_OP_ADD:
9739 		case DIF_OP_MUL:
9740 		case DIF_OP_SDIV:
9741 		case DIF_OP_UDIV:
9742 		case DIF_OP_SREM:
9743 		case DIF_OP_UREM:
9744 		case DIF_OP_COPYS:
9745 		case DIF_OP_NOT:
9746 		case DIF_OP_MOV:
9747 		case DIF_OP_RLDSB:
9748 		case DIF_OP_RLDSH:
9749 		case DIF_OP_RLDSW:
9750 		case DIF_OP_RLDUB:
9751 		case DIF_OP_RLDUH:
9752 		case DIF_OP_RLDUW:
9753 		case DIF_OP_RLDX:
9754 		case DIF_OP_ULDSB:
9755 		case DIF_OP_ULDSH:
9756 		case DIF_OP_ULDSW:
9757 		case DIF_OP_ULDUB:
9758 		case DIF_OP_ULDUH:
9759 		case DIF_OP_ULDUW:
9760 		case DIF_OP_ULDX:
9761 		case DIF_OP_STB:
9762 		case DIF_OP_STH:
9763 		case DIF_OP_STW:
9764 		case DIF_OP_STX:
9765 		case DIF_OP_ALLOCS:
9766 		case DIF_OP_CMP:
9767 		case DIF_OP_SCMP:
9768 		case DIF_OP_TST:
9769 		case DIF_OP_BA:
9770 		case DIF_OP_BE:
9771 		case DIF_OP_BNE:
9772 		case DIF_OP_BG:
9773 		case DIF_OP_BGU:
9774 		case DIF_OP_BGE:
9775 		case DIF_OP_BGEU:
9776 		case DIF_OP_BL:
9777 		case DIF_OP_BLU:
9778 		case DIF_OP_BLE:
9779 		case DIF_OP_BLEU:
9780 		case DIF_OP_RET:
9781 		case DIF_OP_NOP:
9782 		case DIF_OP_POPTS:
9783 		case DIF_OP_FLUSHTS:
9784 		case DIF_OP_SETX:
9785 		case DIF_OP_SETS:
9786 		case DIF_OP_LDGA:
9787 		case DIF_OP_LDLS:
9788 		case DIF_OP_STGS:
9789 		case DIF_OP_STLS:
9790 		case DIF_OP_PUSHTR:
9791 		case DIF_OP_PUSHTV:
9792 			break;
9793 
9794 		case DIF_OP_LDGS:
9795 			if (v >= DIF_VAR_OTHER_UBASE)
9796 				break;
9797 
9798 			if (v >= DIF_VAR_ARG0 && v <= DIF_VAR_ARG9)
9799 				break;
9800 
9801 			if (v == DIF_VAR_CURTHREAD || v == DIF_VAR_PID ||
9802 			    v == DIF_VAR_PPID || v == DIF_VAR_TID ||
9803 			    v == DIF_VAR_EXECNAME || v == DIF_VAR_ZONENAME ||
9804 			    v == DIF_VAR_UID || v == DIF_VAR_GID)
9805 				break;
9806 
9807 			err += efunc(pc, "illegal variable %u\n", v);
9808 			break;
9809 
9810 		case DIF_OP_LDTA:
9811 			if (v < DIF_VAR_OTHER_UBASE) {
9812 				err += efunc(pc, "illegal variable load\n");
9813 				break;
9814 			}
9815 			/* FALLTHROUGH */
9816 		case DIF_OP_LDTS:
9817 		case DIF_OP_LDGAA:
9818 		case DIF_OP_LDTAA:
9819 			err += efunc(pc, "illegal dynamic variable load\n");
9820 			break;
9821 
9822 		case DIF_OP_STGA:
9823 			if (v < DIF_VAR_OTHER_UBASE) {
9824 				err += efunc(pc, "illegal variable store\n");
9825 				break;
9826 			}
9827 			/* FALLTHROUGH */
9828 		case DIF_OP_STTS:
9829 		case DIF_OP_STGAA:
9830 		case DIF_OP_STTAA:
9831 			err += efunc(pc, "illegal dynamic variable store\n");
9832 			break;
9833 
9834 		case DIF_OP_CALL:
9835 			if (subr == DIF_SUBR_ALLOCA ||
9836 			    subr == DIF_SUBR_BCOPY ||
9837 			    subr == DIF_SUBR_COPYIN ||
9838 			    subr == DIF_SUBR_COPYINTO ||
9839 			    subr == DIF_SUBR_COPYINSTR ||
9840 			    subr == DIF_SUBR_INDEX ||
9841 			    subr == DIF_SUBR_INET_NTOA ||
9842 			    subr == DIF_SUBR_INET_NTOA6 ||
9843 			    subr == DIF_SUBR_INET_NTOP ||
9844 			    subr == DIF_SUBR_JSON ||
9845 			    subr == DIF_SUBR_LLTOSTR ||
9846 			    subr == DIF_SUBR_STRTOLL ||
9847 			    subr == DIF_SUBR_RINDEX ||
9848 			    subr == DIF_SUBR_STRCHR ||
9849 			    subr == DIF_SUBR_STRJOIN ||
9850 			    subr == DIF_SUBR_STRRCHR ||
9851 			    subr == DIF_SUBR_STRSTR ||
9852 			    subr == DIF_SUBR_HTONS ||
9853 			    subr == DIF_SUBR_HTONL ||
9854 			    subr == DIF_SUBR_HTONLL ||
9855 			    subr == DIF_SUBR_NTOHS ||
9856 			    subr == DIF_SUBR_NTOHL ||
9857 			    subr == DIF_SUBR_NTOHLL)
9858 				break;
9859 
9860 			err += efunc(pc, "invalid subr %u\n", subr);
9861 			break;
9862 
9863 		default:
9864 			err += efunc(pc, "invalid opcode %u\n",
9865 			    DIF_INSTR_OP(instr));
9866 		}
9867 	}
9868 
9869 	return (err);
9870 }
9871 
9872 /*
9873  * Returns 1 if the expression in the DIF object can be cached on a per-thread
9874  * basis; 0 if not.
9875  */
9876 static int
9877 dtrace_difo_cacheable(dtrace_difo_t *dp)
9878 {
9879 	int i;
9880 
9881 	if (dp == NULL)
9882 		return (0);
9883 
9884 	for (i = 0; i < dp->dtdo_varlen; i++) {
9885 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9886 
9887 		if (v->dtdv_scope != DIFV_SCOPE_GLOBAL)
9888 			continue;
9889 
9890 		switch (v->dtdv_id) {
9891 		case DIF_VAR_CURTHREAD:
9892 		case DIF_VAR_PID:
9893 		case DIF_VAR_TID:
9894 		case DIF_VAR_EXECNAME:
9895 		case DIF_VAR_ZONENAME:
9896 			break;
9897 
9898 		default:
9899 			return (0);
9900 		}
9901 	}
9902 
9903 	/*
9904 	 * This DIF object may be cacheable.  Now we need to look for any
9905 	 * array loading instructions, any memory loading instructions, or
9906 	 * any stores to thread-local variables.
9907 	 */
9908 	for (i = 0; i < dp->dtdo_len; i++) {
9909 		uint_t op = DIF_INSTR_OP(dp->dtdo_buf[i]);
9910 
9911 		if ((op >= DIF_OP_LDSB && op <= DIF_OP_LDX) ||
9912 		    (op >= DIF_OP_ULDSB && op <= DIF_OP_ULDX) ||
9913 		    (op >= DIF_OP_RLDSB && op <= DIF_OP_RLDX) ||
9914 		    op == DIF_OP_LDGA || op == DIF_OP_STTS)
9915 			return (0);
9916 	}
9917 
9918 	return (1);
9919 }
9920 
9921 static void
9922 dtrace_difo_hold(dtrace_difo_t *dp)
9923 {
9924 	int i;
9925 
9926 	ASSERT(MUTEX_HELD(&dtrace_lock));
9927 
9928 	dp->dtdo_refcnt++;
9929 	ASSERT(dp->dtdo_refcnt != 0);
9930 
9931 	/*
9932 	 * We need to check this DIF object for references to the variable
9933 	 * DIF_VAR_VTIMESTAMP.
9934 	 */
9935 	for (i = 0; i < dp->dtdo_varlen; i++) {
9936 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
9937 
9938 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
9939 			continue;
9940 
9941 		if (dtrace_vtime_references++ == 0)
9942 			dtrace_vtime_enable();
9943 	}
9944 }
9945 
9946 /*
9947  * This routine calculates the dynamic variable chunksize for a given DIF
9948  * object.  The calculation is not fool-proof, and can probably be tricked by
9949  * malicious DIF -- but it works for all compiler-generated DIF.  Because this
9950  * calculation is likely imperfect, dtrace_dynvar() is able to gracefully fail
9951  * if a dynamic variable size exceeds the chunksize.
9952  */
9953 static void
9954 dtrace_difo_chunksize(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
9955 {
9956 	uint64_t sval;
9957 	dtrace_key_t tupregs[DIF_DTR_NREGS + 2]; /* +2 for thread and id */
9958 	const dif_instr_t *text = dp->dtdo_buf;
9959 	uint_t pc, srd = 0;
9960 	uint_t ttop = 0;
9961 	size_t size, ksize;
9962 	uint_t id, i;
9963 
9964 	for (pc = 0; pc < dp->dtdo_len; pc++) {
9965 		dif_instr_t instr = text[pc];
9966 		uint_t op = DIF_INSTR_OP(instr);
9967 		uint_t rd = DIF_INSTR_RD(instr);
9968 		uint_t r1 = DIF_INSTR_R1(instr);
9969 		uint_t nkeys = 0;
9970 		uchar_t scope;
9971 
9972 		dtrace_key_t *key = tupregs;
9973 
9974 		switch (op) {
9975 		case DIF_OP_SETX:
9976 			sval = dp->dtdo_inttab[DIF_INSTR_INTEGER(instr)];
9977 			srd = rd;
9978 			continue;
9979 
9980 		case DIF_OP_STTS:
9981 			key = &tupregs[DIF_DTR_NREGS];
9982 			key[0].dttk_size = 0;
9983 			key[1].dttk_size = 0;
9984 			nkeys = 2;
9985 			scope = DIFV_SCOPE_THREAD;
9986 			break;
9987 
9988 		case DIF_OP_STGAA:
9989 		case DIF_OP_STTAA:
9990 			nkeys = ttop;
9991 
9992 			if (DIF_INSTR_OP(instr) == DIF_OP_STTAA)
9993 				key[nkeys++].dttk_size = 0;
9994 
9995 			key[nkeys++].dttk_size = 0;
9996 
9997 			if (op == DIF_OP_STTAA) {
9998 				scope = DIFV_SCOPE_THREAD;
9999 			} else {
10000 				scope = DIFV_SCOPE_GLOBAL;
10001 			}
10002 
10003 			break;
10004 
10005 		case DIF_OP_PUSHTR:
10006 			if (ttop == DIF_DTR_NREGS)
10007 				return;
10008 
10009 			if ((srd == 0 || sval == 0) && r1 == DIF_TYPE_STRING) {
10010 				/*
10011 				 * If the register for the size of the "pushtr"
10012 				 * is %r0 (or the value is 0) and the type is
10013 				 * a string, we'll use the system-wide default
10014 				 * string size.
10015 				 */
10016 				tupregs[ttop++].dttk_size =
10017 				    dtrace_strsize_default;
10018 			} else {
10019 				if (srd == 0)
10020 					return;
10021 
10022 				if (sval > LONG_MAX)
10023 					return;
10024 
10025 				tupregs[ttop++].dttk_size = sval;
10026 			}
10027 
10028 			break;
10029 
10030 		case DIF_OP_PUSHTV:
10031 			if (ttop == DIF_DTR_NREGS)
10032 				return;
10033 
10034 			tupregs[ttop++].dttk_size = 0;
10035 			break;
10036 
10037 		case DIF_OP_FLUSHTS:
10038 			ttop = 0;
10039 			break;
10040 
10041 		case DIF_OP_POPTS:
10042 			if (ttop != 0)
10043 				ttop--;
10044 			break;
10045 		}
10046 
10047 		sval = 0;
10048 		srd = 0;
10049 
10050 		if (nkeys == 0)
10051 			continue;
10052 
10053 		/*
10054 		 * We have a dynamic variable allocation; calculate its size.
10055 		 */
10056 		for (ksize = 0, i = 0; i < nkeys; i++)
10057 			ksize += P2ROUNDUP(key[i].dttk_size, sizeof (uint64_t));
10058 
10059 		size = sizeof (dtrace_dynvar_t);
10060 		size += sizeof (dtrace_key_t) * (nkeys - 1);
10061 		size += ksize;
10062 
10063 		/*
10064 		 * Now we need to determine the size of the stored data.
10065 		 */
10066 		id = DIF_INSTR_VAR(instr);
10067 
10068 		for (i = 0; i < dp->dtdo_varlen; i++) {
10069 			dtrace_difv_t *v = &dp->dtdo_vartab[i];
10070 
10071 			if (v->dtdv_id == id && v->dtdv_scope == scope) {
10072 				size += v->dtdv_type.dtdt_size;
10073 				break;
10074 			}
10075 		}
10076 
10077 		if (i == dp->dtdo_varlen)
10078 			return;
10079 
10080 		/*
10081 		 * We have the size.  If this is larger than the chunk size
10082 		 * for our dynamic variable state, reset the chunk size.
10083 		 */
10084 		size = P2ROUNDUP(size, sizeof (uint64_t));
10085 
10086 		/*
10087 		 * Before setting the chunk size, check that we're not going
10088 		 * to set it to a negative value...
10089 		 */
10090 		if (size > LONG_MAX)
10091 			return;
10092 
10093 		/*
10094 		 * ...and make certain that we didn't badly overflow.
10095 		 */
10096 		if (size < ksize || size < sizeof (dtrace_dynvar_t))
10097 			return;
10098 
10099 		if (size > vstate->dtvs_dynvars.dtds_chunksize)
10100 			vstate->dtvs_dynvars.dtds_chunksize = size;
10101 	}
10102 }
10103 
10104 static void
10105 dtrace_difo_init(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10106 {
10107 	int i, oldsvars, osz, nsz, otlocals, ntlocals;
10108 	uint_t id;
10109 
10110 	ASSERT(MUTEX_HELD(&dtrace_lock));
10111 	ASSERT(dp->dtdo_buf != NULL && dp->dtdo_len != 0);
10112 
10113 	for (i = 0; i < dp->dtdo_varlen; i++) {
10114 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10115 		dtrace_statvar_t *svar, ***svarp;
10116 		size_t dsize = 0;
10117 		uint8_t scope = v->dtdv_scope;
10118 		int *np;
10119 
10120 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10121 			continue;
10122 
10123 		id -= DIF_VAR_OTHER_UBASE;
10124 
10125 		switch (scope) {
10126 		case DIFV_SCOPE_THREAD:
10127 			while (id >= (otlocals = vstate->dtvs_ntlocals)) {
10128 				dtrace_difv_t *tlocals;
10129 
10130 				if ((ntlocals = (otlocals << 1)) == 0)
10131 					ntlocals = 1;
10132 
10133 				osz = otlocals * sizeof (dtrace_difv_t);
10134 				nsz = ntlocals * sizeof (dtrace_difv_t);
10135 
10136 				tlocals = kmem_zalloc(nsz, KM_SLEEP);
10137 
10138 				if (osz != 0) {
10139 					bcopy(vstate->dtvs_tlocals,
10140 					    tlocals, osz);
10141 					kmem_free(vstate->dtvs_tlocals, osz);
10142 				}
10143 
10144 				vstate->dtvs_tlocals = tlocals;
10145 				vstate->dtvs_ntlocals = ntlocals;
10146 			}
10147 
10148 			vstate->dtvs_tlocals[id] = *v;
10149 			continue;
10150 
10151 		case DIFV_SCOPE_LOCAL:
10152 			np = &vstate->dtvs_nlocals;
10153 			svarp = &vstate->dtvs_locals;
10154 
10155 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10156 				dsize = NCPU * (v->dtdv_type.dtdt_size +
10157 				    sizeof (uint64_t));
10158 			else
10159 				dsize = NCPU * sizeof (uint64_t);
10160 
10161 			break;
10162 
10163 		case DIFV_SCOPE_GLOBAL:
10164 			np = &vstate->dtvs_nglobals;
10165 			svarp = &vstate->dtvs_globals;
10166 
10167 			if (v->dtdv_type.dtdt_flags & DIF_TF_BYREF)
10168 				dsize = v->dtdv_type.dtdt_size +
10169 				    sizeof (uint64_t);
10170 
10171 			break;
10172 
10173 		default:
10174 			ASSERT(0);
10175 		}
10176 
10177 		while (id >= (oldsvars = *np)) {
10178 			dtrace_statvar_t **statics;
10179 			int newsvars, oldsize, newsize;
10180 
10181 			if ((newsvars = (oldsvars << 1)) == 0)
10182 				newsvars = 1;
10183 
10184 			oldsize = oldsvars * sizeof (dtrace_statvar_t *);
10185 			newsize = newsvars * sizeof (dtrace_statvar_t *);
10186 
10187 			statics = kmem_zalloc(newsize, KM_SLEEP);
10188 
10189 			if (oldsize != 0) {
10190 				bcopy(*svarp, statics, oldsize);
10191 				kmem_free(*svarp, oldsize);
10192 			}
10193 
10194 			*svarp = statics;
10195 			*np = newsvars;
10196 		}
10197 
10198 		if ((svar = (*svarp)[id]) == NULL) {
10199 			svar = kmem_zalloc(sizeof (dtrace_statvar_t), KM_SLEEP);
10200 			svar->dtsv_var = *v;
10201 
10202 			if ((svar->dtsv_size = dsize) != 0) {
10203 				svar->dtsv_data = (uint64_t)(uintptr_t)
10204 				    kmem_zalloc(dsize, KM_SLEEP);
10205 			}
10206 
10207 			(*svarp)[id] = svar;
10208 		}
10209 
10210 		svar->dtsv_refcnt++;
10211 	}
10212 
10213 	dtrace_difo_chunksize(dp, vstate);
10214 	dtrace_difo_hold(dp);
10215 }
10216 
10217 static dtrace_difo_t *
10218 dtrace_difo_duplicate(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10219 {
10220 	dtrace_difo_t *new;
10221 	size_t sz;
10222 
10223 	ASSERT(dp->dtdo_buf != NULL);
10224 	ASSERT(dp->dtdo_refcnt != 0);
10225 
10226 	new = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
10227 
10228 	ASSERT(dp->dtdo_buf != NULL);
10229 	sz = dp->dtdo_len * sizeof (dif_instr_t);
10230 	new->dtdo_buf = kmem_alloc(sz, KM_SLEEP);
10231 	bcopy(dp->dtdo_buf, new->dtdo_buf, sz);
10232 	new->dtdo_len = dp->dtdo_len;
10233 
10234 	if (dp->dtdo_strtab != NULL) {
10235 		ASSERT(dp->dtdo_strlen != 0);
10236 		new->dtdo_strtab = kmem_alloc(dp->dtdo_strlen, KM_SLEEP);
10237 		bcopy(dp->dtdo_strtab, new->dtdo_strtab, dp->dtdo_strlen);
10238 		new->dtdo_strlen = dp->dtdo_strlen;
10239 	}
10240 
10241 	if (dp->dtdo_inttab != NULL) {
10242 		ASSERT(dp->dtdo_intlen != 0);
10243 		sz = dp->dtdo_intlen * sizeof (uint64_t);
10244 		new->dtdo_inttab = kmem_alloc(sz, KM_SLEEP);
10245 		bcopy(dp->dtdo_inttab, new->dtdo_inttab, sz);
10246 		new->dtdo_intlen = dp->dtdo_intlen;
10247 	}
10248 
10249 	if (dp->dtdo_vartab != NULL) {
10250 		ASSERT(dp->dtdo_varlen != 0);
10251 		sz = dp->dtdo_varlen * sizeof (dtrace_difv_t);
10252 		new->dtdo_vartab = kmem_alloc(sz, KM_SLEEP);
10253 		bcopy(dp->dtdo_vartab, new->dtdo_vartab, sz);
10254 		new->dtdo_varlen = dp->dtdo_varlen;
10255 	}
10256 
10257 	dtrace_difo_init(new, vstate);
10258 	return (new);
10259 }
10260 
10261 static void
10262 dtrace_difo_destroy(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10263 {
10264 	int i;
10265 
10266 	ASSERT(dp->dtdo_refcnt == 0);
10267 
10268 	for (i = 0; i < dp->dtdo_varlen; i++) {
10269 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10270 		dtrace_statvar_t *svar, **svarp;
10271 		uint_t id;
10272 		uint8_t scope = v->dtdv_scope;
10273 		int *np;
10274 
10275 		switch (scope) {
10276 		case DIFV_SCOPE_THREAD:
10277 			continue;
10278 
10279 		case DIFV_SCOPE_LOCAL:
10280 			np = &vstate->dtvs_nlocals;
10281 			svarp = vstate->dtvs_locals;
10282 			break;
10283 
10284 		case DIFV_SCOPE_GLOBAL:
10285 			np = &vstate->dtvs_nglobals;
10286 			svarp = vstate->dtvs_globals;
10287 			break;
10288 
10289 		default:
10290 			ASSERT(0);
10291 		}
10292 
10293 		if ((id = v->dtdv_id) < DIF_VAR_OTHER_UBASE)
10294 			continue;
10295 
10296 		id -= DIF_VAR_OTHER_UBASE;
10297 		ASSERT(id < *np);
10298 
10299 		svar = svarp[id];
10300 		ASSERT(svar != NULL);
10301 		ASSERT(svar->dtsv_refcnt > 0);
10302 
10303 		if (--svar->dtsv_refcnt > 0)
10304 			continue;
10305 
10306 		if (svar->dtsv_size != 0) {
10307 			ASSERT(svar->dtsv_data != 0);
10308 			kmem_free((void *)(uintptr_t)svar->dtsv_data,
10309 			    svar->dtsv_size);
10310 		}
10311 
10312 		kmem_free(svar, sizeof (dtrace_statvar_t));
10313 		svarp[id] = NULL;
10314 	}
10315 
10316 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
10317 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
10318 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
10319 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
10320 
10321 	kmem_free(dp, sizeof (dtrace_difo_t));
10322 }
10323 
10324 static void
10325 dtrace_difo_release(dtrace_difo_t *dp, dtrace_vstate_t *vstate)
10326 {
10327 	int i;
10328 
10329 	ASSERT(MUTEX_HELD(&dtrace_lock));
10330 	ASSERT(dp->dtdo_refcnt != 0);
10331 
10332 	for (i = 0; i < dp->dtdo_varlen; i++) {
10333 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
10334 
10335 		if (v->dtdv_id != DIF_VAR_VTIMESTAMP)
10336 			continue;
10337 
10338 		ASSERT(dtrace_vtime_references > 0);
10339 		if (--dtrace_vtime_references == 0)
10340 			dtrace_vtime_disable();
10341 	}
10342 
10343 	if (--dp->dtdo_refcnt == 0)
10344 		dtrace_difo_destroy(dp, vstate);
10345 }
10346 
10347 /*
10348  * DTrace Format Functions
10349  */
10350 static uint16_t
10351 dtrace_format_add(dtrace_state_t *state, char *str)
10352 {
10353 	char *fmt, **new;
10354 	uint16_t ndx, len = strlen(str) + 1;
10355 
10356 	fmt = kmem_zalloc(len, KM_SLEEP);
10357 	bcopy(str, fmt, len);
10358 
10359 	for (ndx = 0; ndx < state->dts_nformats; ndx++) {
10360 		if (state->dts_formats[ndx] == NULL) {
10361 			state->dts_formats[ndx] = fmt;
10362 			return (ndx + 1);
10363 		}
10364 	}
10365 
10366 	if (state->dts_nformats == USHRT_MAX) {
10367 		/*
10368 		 * This is only likely if a denial-of-service attack is being
10369 		 * attempted.  As such, it's okay to fail silently here.
10370 		 */
10371 		kmem_free(fmt, len);
10372 		return (0);
10373 	}
10374 
10375 	/*
10376 	 * For simplicity, we always resize the formats array to be exactly the
10377 	 * number of formats.
10378 	 */
10379 	ndx = state->dts_nformats++;
10380 	new = kmem_alloc((ndx + 1) * sizeof (char *), KM_SLEEP);
10381 
10382 	if (state->dts_formats != NULL) {
10383 		ASSERT(ndx != 0);
10384 		bcopy(state->dts_formats, new, ndx * sizeof (char *));
10385 		kmem_free(state->dts_formats, ndx * sizeof (char *));
10386 	}
10387 
10388 	state->dts_formats = new;
10389 	state->dts_formats[ndx] = fmt;
10390 
10391 	return (ndx + 1);
10392 }
10393 
10394 static void
10395 dtrace_format_remove(dtrace_state_t *state, uint16_t format)
10396 {
10397 	char *fmt;
10398 
10399 	ASSERT(state->dts_formats != NULL);
10400 	ASSERT(format <= state->dts_nformats);
10401 	ASSERT(state->dts_formats[format - 1] != NULL);
10402 
10403 	fmt = state->dts_formats[format - 1];
10404 	kmem_free(fmt, strlen(fmt) + 1);
10405 	state->dts_formats[format - 1] = NULL;
10406 }
10407 
10408 static void
10409 dtrace_format_destroy(dtrace_state_t *state)
10410 {
10411 	int i;
10412 
10413 	if (state->dts_nformats == 0) {
10414 		ASSERT(state->dts_formats == NULL);
10415 		return;
10416 	}
10417 
10418 	ASSERT(state->dts_formats != NULL);
10419 
10420 	for (i = 0; i < state->dts_nformats; i++) {
10421 		char *fmt = state->dts_formats[i];
10422 
10423 		if (fmt == NULL)
10424 			continue;
10425 
10426 		kmem_free(fmt, strlen(fmt) + 1);
10427 	}
10428 
10429 	kmem_free(state->dts_formats, state->dts_nformats * sizeof (char *));
10430 	state->dts_nformats = 0;
10431 	state->dts_formats = NULL;
10432 }
10433 
10434 /*
10435  * DTrace Predicate Functions
10436  */
10437 static dtrace_predicate_t *
10438 dtrace_predicate_create(dtrace_difo_t *dp)
10439 {
10440 	dtrace_predicate_t *pred;
10441 
10442 	ASSERT(MUTEX_HELD(&dtrace_lock));
10443 	ASSERT(dp->dtdo_refcnt != 0);
10444 
10445 	pred = kmem_zalloc(sizeof (dtrace_predicate_t), KM_SLEEP);
10446 	pred->dtp_difo = dp;
10447 	pred->dtp_refcnt = 1;
10448 
10449 	if (!dtrace_difo_cacheable(dp))
10450 		return (pred);
10451 
10452 	if (dtrace_predcache_id == DTRACE_CACHEIDNONE) {
10453 		/*
10454 		 * This is only theoretically possible -- we have had 2^32
10455 		 * cacheable predicates on this machine.  We cannot allow any
10456 		 * more predicates to become cacheable:  as unlikely as it is,
10457 		 * there may be a thread caching a (now stale) predicate cache
10458 		 * ID. (N.B.: the temptation is being successfully resisted to
10459 		 * have this cmn_err() "Holy shit -- we executed this code!")
10460 		 */
10461 		return (pred);
10462 	}
10463 
10464 	pred->dtp_cacheid = dtrace_predcache_id++;
10465 
10466 	return (pred);
10467 }
10468 
10469 static void
10470 dtrace_predicate_hold(dtrace_predicate_t *pred)
10471 {
10472 	ASSERT(MUTEX_HELD(&dtrace_lock));
10473 	ASSERT(pred->dtp_difo != NULL && pred->dtp_difo->dtdo_refcnt != 0);
10474 	ASSERT(pred->dtp_refcnt > 0);
10475 
10476 	pred->dtp_refcnt++;
10477 }
10478 
10479 static void
10480 dtrace_predicate_release(dtrace_predicate_t *pred, dtrace_vstate_t *vstate)
10481 {
10482 	dtrace_difo_t *dp = pred->dtp_difo;
10483 
10484 	ASSERT(MUTEX_HELD(&dtrace_lock));
10485 	ASSERT(dp != NULL && dp->dtdo_refcnt != 0);
10486 	ASSERT(pred->dtp_refcnt > 0);
10487 
10488 	if (--pred->dtp_refcnt == 0) {
10489 		dtrace_difo_release(pred->dtp_difo, vstate);
10490 		kmem_free(pred, sizeof (dtrace_predicate_t));
10491 	}
10492 }
10493 
10494 /*
10495  * DTrace Action Description Functions
10496  */
10497 static dtrace_actdesc_t *
10498 dtrace_actdesc_create(dtrace_actkind_t kind, uint32_t ntuple,
10499     uint64_t uarg, uint64_t arg)
10500 {
10501 	dtrace_actdesc_t *act;
10502 
10503 	ASSERT(!DTRACEACT_ISPRINTFLIKE(kind) || (arg != 0 &&
10504 	    arg >= KERNELBASE) || (arg == 0 && kind == DTRACEACT_PRINTA));
10505 
10506 	act = kmem_zalloc(sizeof (dtrace_actdesc_t), KM_SLEEP);
10507 	act->dtad_kind = kind;
10508 	act->dtad_ntuple = ntuple;
10509 	act->dtad_uarg = uarg;
10510 	act->dtad_arg = arg;
10511 	act->dtad_refcnt = 1;
10512 
10513 	return (act);
10514 }
10515 
10516 static void
10517 dtrace_actdesc_hold(dtrace_actdesc_t *act)
10518 {
10519 	ASSERT(act->dtad_refcnt >= 1);
10520 	act->dtad_refcnt++;
10521 }
10522 
10523 static void
10524 dtrace_actdesc_release(dtrace_actdesc_t *act, dtrace_vstate_t *vstate)
10525 {
10526 	dtrace_actkind_t kind = act->dtad_kind;
10527 	dtrace_difo_t *dp;
10528 
10529 	ASSERT(act->dtad_refcnt >= 1);
10530 
10531 	if (--act->dtad_refcnt != 0)
10532 		return;
10533 
10534 	if ((dp = act->dtad_difo) != NULL)
10535 		dtrace_difo_release(dp, vstate);
10536 
10537 	if (DTRACEACT_ISPRINTFLIKE(kind)) {
10538 		char *str = (char *)(uintptr_t)act->dtad_arg;
10539 
10540 		ASSERT((str != NULL && (uintptr_t)str >= KERNELBASE) ||
10541 		    (str == NULL && act->dtad_kind == DTRACEACT_PRINTA));
10542 
10543 		if (str != NULL)
10544 			kmem_free(str, strlen(str) + 1);
10545 	}
10546 
10547 	kmem_free(act, sizeof (dtrace_actdesc_t));
10548 }
10549 
10550 /*
10551  * DTrace ECB Functions
10552  */
10553 static dtrace_ecb_t *
10554 dtrace_ecb_add(dtrace_state_t *state, dtrace_probe_t *probe)
10555 {
10556 	dtrace_ecb_t *ecb;
10557 	dtrace_epid_t epid;
10558 
10559 	ASSERT(MUTEX_HELD(&dtrace_lock));
10560 
10561 	ecb = kmem_zalloc(sizeof (dtrace_ecb_t), KM_SLEEP);
10562 	ecb->dte_predicate = NULL;
10563 	ecb->dte_probe = probe;
10564 
10565 	/*
10566 	 * The default size is the size of the default action: recording
10567 	 * the header.
10568 	 */
10569 	ecb->dte_size = ecb->dte_needed = sizeof (dtrace_rechdr_t);
10570 	ecb->dte_alignment = sizeof (dtrace_epid_t);
10571 
10572 	epid = state->dts_epid++;
10573 
10574 	if (epid - 1 >= state->dts_necbs) {
10575 		dtrace_ecb_t **oecbs = state->dts_ecbs, **ecbs;
10576 		int necbs = state->dts_necbs << 1;
10577 
10578 		ASSERT(epid == state->dts_necbs + 1);
10579 
10580 		if (necbs == 0) {
10581 			ASSERT(oecbs == NULL);
10582 			necbs = 1;
10583 		}
10584 
10585 		ecbs = kmem_zalloc(necbs * sizeof (*ecbs), KM_SLEEP);
10586 
10587 		if (oecbs != NULL)
10588 			bcopy(oecbs, ecbs, state->dts_necbs * sizeof (*ecbs));
10589 
10590 		dtrace_membar_producer();
10591 		state->dts_ecbs = ecbs;
10592 
10593 		if (oecbs != NULL) {
10594 			/*
10595 			 * If this state is active, we must dtrace_sync()
10596 			 * before we can free the old dts_ecbs array:  we're
10597 			 * coming in hot, and there may be active ring
10598 			 * buffer processing (which indexes into the dts_ecbs
10599 			 * array) on another CPU.
10600 			 */
10601 			if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
10602 				dtrace_sync();
10603 
10604 			kmem_free(oecbs, state->dts_necbs * sizeof (*ecbs));
10605 		}
10606 
10607 		dtrace_membar_producer();
10608 		state->dts_necbs = necbs;
10609 	}
10610 
10611 	ecb->dte_state = state;
10612 
10613 	ASSERT(state->dts_ecbs[epid - 1] == NULL);
10614 	dtrace_membar_producer();
10615 	state->dts_ecbs[(ecb->dte_epid = epid) - 1] = ecb;
10616 
10617 	return (ecb);
10618 }
10619 
10620 static int
10621 dtrace_ecb_enable(dtrace_ecb_t *ecb)
10622 {
10623 	dtrace_probe_t *probe = ecb->dte_probe;
10624 
10625 	ASSERT(MUTEX_HELD(&cpu_lock));
10626 	ASSERT(MUTEX_HELD(&dtrace_lock));
10627 	ASSERT(ecb->dte_next == NULL);
10628 
10629 	if (probe == NULL) {
10630 		/*
10631 		 * This is the NULL probe -- there's nothing to do.
10632 		 */
10633 		return (0);
10634 	}
10635 
10636 	if (probe->dtpr_ecb == NULL) {
10637 		dtrace_provider_t *prov = probe->dtpr_provider;
10638 
10639 		/*
10640 		 * We're the first ECB on this probe.
10641 		 */
10642 		probe->dtpr_ecb = probe->dtpr_ecb_last = ecb;
10643 
10644 		if (ecb->dte_predicate != NULL)
10645 			probe->dtpr_predcache = ecb->dte_predicate->dtp_cacheid;
10646 
10647 		return (prov->dtpv_pops.dtps_enable(prov->dtpv_arg,
10648 		    probe->dtpr_id, probe->dtpr_arg));
10649 	} else {
10650 		/*
10651 		 * This probe is already active.  Swing the last pointer to
10652 		 * point to the new ECB, and issue a dtrace_sync() to assure
10653 		 * that all CPUs have seen the change.
10654 		 */
10655 		ASSERT(probe->dtpr_ecb_last != NULL);
10656 		probe->dtpr_ecb_last->dte_next = ecb;
10657 		probe->dtpr_ecb_last = ecb;
10658 		probe->dtpr_predcache = 0;
10659 
10660 		dtrace_sync();
10661 		return (0);
10662 	}
10663 }
10664 
10665 static int
10666 dtrace_ecb_resize(dtrace_ecb_t *ecb)
10667 {
10668 	dtrace_action_t *act;
10669 	uint32_t curneeded = UINT32_MAX;
10670 	uint32_t aggbase = UINT32_MAX;
10671 
10672 	/*
10673 	 * If we record anything, we always record the dtrace_rechdr_t.  (And
10674 	 * we always record it first.)
10675 	 */
10676 	ecb->dte_size = sizeof (dtrace_rechdr_t);
10677 	ecb->dte_alignment = sizeof (dtrace_epid_t);
10678 
10679 	for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10680 		dtrace_recdesc_t *rec = &act->dta_rec;
10681 		ASSERT(rec->dtrd_size > 0 || rec->dtrd_alignment == 1);
10682 
10683 		ecb->dte_alignment = MAX(ecb->dte_alignment,
10684 		    rec->dtrd_alignment);
10685 
10686 		if (DTRACEACT_ISAGG(act->dta_kind)) {
10687 			dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10688 
10689 			ASSERT(rec->dtrd_size != 0);
10690 			ASSERT(agg->dtag_first != NULL);
10691 			ASSERT(act->dta_prev->dta_intuple);
10692 			ASSERT(aggbase != UINT32_MAX);
10693 			ASSERT(curneeded != UINT32_MAX);
10694 
10695 			agg->dtag_base = aggbase;
10696 
10697 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10698 			rec->dtrd_offset = curneeded;
10699 			if (curneeded + rec->dtrd_size < curneeded)
10700 				return (EINVAL);
10701 			curneeded += rec->dtrd_size;
10702 			ecb->dte_needed = MAX(ecb->dte_needed, curneeded);
10703 
10704 			aggbase = UINT32_MAX;
10705 			curneeded = UINT32_MAX;
10706 		} else if (act->dta_intuple) {
10707 			if (curneeded == UINT32_MAX) {
10708 				/*
10709 				 * This is the first record in a tuple.  Align
10710 				 * curneeded to be at offset 4 in an 8-byte
10711 				 * aligned block.
10712 				 */
10713 				ASSERT(act->dta_prev == NULL ||
10714 				    !act->dta_prev->dta_intuple);
10715 				ASSERT3U(aggbase, ==, UINT32_MAX);
10716 				curneeded = P2PHASEUP(ecb->dte_size,
10717 				    sizeof (uint64_t), sizeof (dtrace_aggid_t));
10718 
10719 				aggbase = curneeded - sizeof (dtrace_aggid_t);
10720 				ASSERT(IS_P2ALIGNED(aggbase,
10721 				    sizeof (uint64_t)));
10722 			}
10723 			curneeded = P2ROUNDUP(curneeded, rec->dtrd_alignment);
10724 			rec->dtrd_offset = curneeded;
10725 			if (curneeded + rec->dtrd_size < curneeded)
10726 				return (EINVAL);
10727 			curneeded += rec->dtrd_size;
10728 		} else {
10729 			/* tuples must be followed by an aggregation */
10730 			ASSERT(act->dta_prev == NULL ||
10731 			    !act->dta_prev->dta_intuple);
10732 
10733 			ecb->dte_size = P2ROUNDUP(ecb->dte_size,
10734 			    rec->dtrd_alignment);
10735 			rec->dtrd_offset = ecb->dte_size;
10736 			if (ecb->dte_size + rec->dtrd_size < ecb->dte_size)
10737 				return (EINVAL);
10738 			ecb->dte_size += rec->dtrd_size;
10739 			ecb->dte_needed = MAX(ecb->dte_needed, ecb->dte_size);
10740 		}
10741 	}
10742 
10743 	if ((act = ecb->dte_action) != NULL &&
10744 	    !(act->dta_kind == DTRACEACT_SPECULATE && act->dta_next == NULL) &&
10745 	    ecb->dte_size == sizeof (dtrace_rechdr_t)) {
10746 		/*
10747 		 * If the size is still sizeof (dtrace_rechdr_t), then all
10748 		 * actions store no data; set the size to 0.
10749 		 */
10750 		ecb->dte_size = 0;
10751 	}
10752 
10753 	ecb->dte_size = P2ROUNDUP(ecb->dte_size, sizeof (dtrace_epid_t));
10754 	ecb->dte_needed = P2ROUNDUP(ecb->dte_needed, (sizeof (dtrace_epid_t)));
10755 	ecb->dte_state->dts_needed = MAX(ecb->dte_state->dts_needed,
10756 	    ecb->dte_needed);
10757 	return (0);
10758 }
10759 
10760 static dtrace_action_t *
10761 dtrace_ecb_aggregation_create(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10762 {
10763 	dtrace_aggregation_t *agg;
10764 	size_t size = sizeof (uint64_t);
10765 	int ntuple = desc->dtad_ntuple;
10766 	dtrace_action_t *act;
10767 	dtrace_recdesc_t *frec;
10768 	dtrace_aggid_t aggid;
10769 	dtrace_state_t *state = ecb->dte_state;
10770 
10771 	agg = kmem_zalloc(sizeof (dtrace_aggregation_t), KM_SLEEP);
10772 	agg->dtag_ecb = ecb;
10773 
10774 	ASSERT(DTRACEACT_ISAGG(desc->dtad_kind));
10775 
10776 	switch (desc->dtad_kind) {
10777 	case DTRACEAGG_MIN:
10778 		agg->dtag_initial = INT64_MAX;
10779 		agg->dtag_aggregate = dtrace_aggregate_min;
10780 		break;
10781 
10782 	case DTRACEAGG_MAX:
10783 		agg->dtag_initial = INT64_MIN;
10784 		agg->dtag_aggregate = dtrace_aggregate_max;
10785 		break;
10786 
10787 	case DTRACEAGG_COUNT:
10788 		agg->dtag_aggregate = dtrace_aggregate_count;
10789 		break;
10790 
10791 	case DTRACEAGG_QUANTIZE:
10792 		agg->dtag_aggregate = dtrace_aggregate_quantize;
10793 		size = (((sizeof (uint64_t) * NBBY) - 1) * 2 + 1) *
10794 		    sizeof (uint64_t);
10795 		break;
10796 
10797 	case DTRACEAGG_LQUANTIZE: {
10798 		uint16_t step = DTRACE_LQUANTIZE_STEP(desc->dtad_arg);
10799 		uint16_t levels = DTRACE_LQUANTIZE_LEVELS(desc->dtad_arg);
10800 
10801 		agg->dtag_initial = desc->dtad_arg;
10802 		agg->dtag_aggregate = dtrace_aggregate_lquantize;
10803 
10804 		if (step == 0 || levels == 0)
10805 			goto err;
10806 
10807 		size = levels * sizeof (uint64_t) + 3 * sizeof (uint64_t);
10808 		break;
10809 	}
10810 
10811 	case DTRACEAGG_LLQUANTIZE: {
10812 		uint16_t factor = DTRACE_LLQUANTIZE_FACTOR(desc->dtad_arg);
10813 		uint16_t low = DTRACE_LLQUANTIZE_LOW(desc->dtad_arg);
10814 		uint16_t high = DTRACE_LLQUANTIZE_HIGH(desc->dtad_arg);
10815 		uint16_t nsteps = DTRACE_LLQUANTIZE_NSTEP(desc->dtad_arg);
10816 		int64_t v;
10817 
10818 		agg->dtag_initial = desc->dtad_arg;
10819 		agg->dtag_aggregate = dtrace_aggregate_llquantize;
10820 
10821 		if (factor < 2 || low >= high || nsteps < factor)
10822 			goto err;
10823 
10824 		/*
10825 		 * Now check that the number of steps evenly divides a power
10826 		 * of the factor.  (This assures both integer bucket size and
10827 		 * linearity within each magnitude.)
10828 		 */
10829 		for (v = factor; v < nsteps; v *= factor)
10830 			continue;
10831 
10832 		if ((v % nsteps) || (nsteps % factor))
10833 			goto err;
10834 
10835 		size = (dtrace_aggregate_llquantize_bucket(factor,
10836 		    low, high, nsteps, INT64_MAX) + 2) * sizeof (uint64_t);
10837 		break;
10838 	}
10839 
10840 	case DTRACEAGG_AVG:
10841 		agg->dtag_aggregate = dtrace_aggregate_avg;
10842 		size = sizeof (uint64_t) * 2;
10843 		break;
10844 
10845 	case DTRACEAGG_STDDEV:
10846 		agg->dtag_aggregate = dtrace_aggregate_stddev;
10847 		size = sizeof (uint64_t) * 4;
10848 		break;
10849 
10850 	case DTRACEAGG_SUM:
10851 		agg->dtag_aggregate = dtrace_aggregate_sum;
10852 		break;
10853 
10854 	default:
10855 		goto err;
10856 	}
10857 
10858 	agg->dtag_action.dta_rec.dtrd_size = size;
10859 
10860 	if (ntuple == 0)
10861 		goto err;
10862 
10863 	/*
10864 	 * We must make sure that we have enough actions for the n-tuple.
10865 	 */
10866 	for (act = ecb->dte_action_last; act != NULL; act = act->dta_prev) {
10867 		if (DTRACEACT_ISAGG(act->dta_kind))
10868 			break;
10869 
10870 		if (--ntuple == 0) {
10871 			/*
10872 			 * This is the action with which our n-tuple begins.
10873 			 */
10874 			agg->dtag_first = act;
10875 			goto success;
10876 		}
10877 	}
10878 
10879 	/*
10880 	 * This n-tuple is short by ntuple elements.  Return failure.
10881 	 */
10882 	ASSERT(ntuple != 0);
10883 err:
10884 	kmem_free(agg, sizeof (dtrace_aggregation_t));
10885 	return (NULL);
10886 
10887 success:
10888 	/*
10889 	 * If the last action in the tuple has a size of zero, it's actually
10890 	 * an expression argument for the aggregating action.
10891 	 */
10892 	ASSERT(ecb->dte_action_last != NULL);
10893 	act = ecb->dte_action_last;
10894 
10895 	if (act->dta_kind == DTRACEACT_DIFEXPR) {
10896 		ASSERT(act->dta_difo != NULL);
10897 
10898 		if (act->dta_difo->dtdo_rtype.dtdt_size == 0)
10899 			agg->dtag_hasarg = 1;
10900 	}
10901 
10902 	/*
10903 	 * We need to allocate an id for this aggregation.
10904 	 */
10905 	aggid = (dtrace_aggid_t)(uintptr_t)vmem_alloc(state->dts_aggid_arena, 1,
10906 	    VM_BESTFIT | VM_SLEEP);
10907 
10908 	if (aggid - 1 >= state->dts_naggregations) {
10909 		dtrace_aggregation_t **oaggs = state->dts_aggregations;
10910 		dtrace_aggregation_t **aggs;
10911 		int naggs = state->dts_naggregations << 1;
10912 		int onaggs = state->dts_naggregations;
10913 
10914 		ASSERT(aggid == state->dts_naggregations + 1);
10915 
10916 		if (naggs == 0) {
10917 			ASSERT(oaggs == NULL);
10918 			naggs = 1;
10919 		}
10920 
10921 		aggs = kmem_zalloc(naggs * sizeof (*aggs), KM_SLEEP);
10922 
10923 		if (oaggs != NULL) {
10924 			bcopy(oaggs, aggs, onaggs * sizeof (*aggs));
10925 			kmem_free(oaggs, onaggs * sizeof (*aggs));
10926 		}
10927 
10928 		state->dts_aggregations = aggs;
10929 		state->dts_naggregations = naggs;
10930 	}
10931 
10932 	ASSERT(state->dts_aggregations[aggid - 1] == NULL);
10933 	state->dts_aggregations[(agg->dtag_id = aggid) - 1] = agg;
10934 
10935 	frec = &agg->dtag_first->dta_rec;
10936 	if (frec->dtrd_alignment < sizeof (dtrace_aggid_t))
10937 		frec->dtrd_alignment = sizeof (dtrace_aggid_t);
10938 
10939 	for (act = agg->dtag_first; act != NULL; act = act->dta_next) {
10940 		ASSERT(!act->dta_intuple);
10941 		act->dta_intuple = 1;
10942 	}
10943 
10944 	return (&agg->dtag_action);
10945 }
10946 
10947 static void
10948 dtrace_ecb_aggregation_destroy(dtrace_ecb_t *ecb, dtrace_action_t *act)
10949 {
10950 	dtrace_aggregation_t *agg = (dtrace_aggregation_t *)act;
10951 	dtrace_state_t *state = ecb->dte_state;
10952 	dtrace_aggid_t aggid = agg->dtag_id;
10953 
10954 	ASSERT(DTRACEACT_ISAGG(act->dta_kind));
10955 	vmem_free(state->dts_aggid_arena, (void *)(uintptr_t)aggid, 1);
10956 
10957 	ASSERT(state->dts_aggregations[aggid - 1] == agg);
10958 	state->dts_aggregations[aggid - 1] = NULL;
10959 
10960 	kmem_free(agg, sizeof (dtrace_aggregation_t));
10961 }
10962 
10963 static int
10964 dtrace_ecb_action_add(dtrace_ecb_t *ecb, dtrace_actdesc_t *desc)
10965 {
10966 	dtrace_action_t *action, *last;
10967 	dtrace_difo_t *dp = desc->dtad_difo;
10968 	uint32_t size = 0, align = sizeof (uint8_t), mask;
10969 	uint16_t format = 0;
10970 	dtrace_recdesc_t *rec;
10971 	dtrace_state_t *state = ecb->dte_state;
10972 	dtrace_optval_t *opt = state->dts_options, nframes, strsize;
10973 	uint64_t arg = desc->dtad_arg;
10974 
10975 	ASSERT(MUTEX_HELD(&dtrace_lock));
10976 	ASSERT(ecb->dte_action == NULL || ecb->dte_action->dta_refcnt == 1);
10977 
10978 	if (DTRACEACT_ISAGG(desc->dtad_kind)) {
10979 		/*
10980 		 * If this is an aggregating action, there must be neither
10981 		 * a speculate nor a commit on the action chain.
10982 		 */
10983 		dtrace_action_t *act;
10984 
10985 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
10986 			if (act->dta_kind == DTRACEACT_COMMIT)
10987 				return (EINVAL);
10988 
10989 			if (act->dta_kind == DTRACEACT_SPECULATE)
10990 				return (EINVAL);
10991 		}
10992 
10993 		action = dtrace_ecb_aggregation_create(ecb, desc);
10994 
10995 		if (action == NULL)
10996 			return (EINVAL);
10997 	} else {
10998 		if (DTRACEACT_ISDESTRUCTIVE(desc->dtad_kind) ||
10999 		    (desc->dtad_kind == DTRACEACT_DIFEXPR &&
11000 		    dp != NULL && dp->dtdo_destructive)) {
11001 			state->dts_destructive = 1;
11002 		}
11003 
11004 		switch (desc->dtad_kind) {
11005 		case DTRACEACT_PRINTF:
11006 		case DTRACEACT_PRINTA:
11007 		case DTRACEACT_SYSTEM:
11008 		case DTRACEACT_FREOPEN:
11009 		case DTRACEACT_DIFEXPR:
11010 			/*
11011 			 * We know that our arg is a string -- turn it into a
11012 			 * format.
11013 			 */
11014 			if (arg == 0) {
11015 				ASSERT(desc->dtad_kind == DTRACEACT_PRINTA ||
11016 				    desc->dtad_kind == DTRACEACT_DIFEXPR);
11017 				format = 0;
11018 			} else {
11019 				ASSERT(arg != 0);
11020 				ASSERT(arg > KERNELBASE);
11021 				format = dtrace_format_add(state,
11022 				    (char *)(uintptr_t)arg);
11023 			}
11024 
11025 			/*FALLTHROUGH*/
11026 		case DTRACEACT_LIBACT:
11027 		case DTRACEACT_TRACEMEM:
11028 		case DTRACEACT_TRACEMEM_DYNSIZE:
11029 			if (dp == NULL)
11030 				return (EINVAL);
11031 
11032 			if ((size = dp->dtdo_rtype.dtdt_size) != 0)
11033 				break;
11034 
11035 			if (dp->dtdo_rtype.dtdt_kind == DIF_TYPE_STRING) {
11036 				if (!(dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11037 					return (EINVAL);
11038 
11039 				size = opt[DTRACEOPT_STRSIZE];
11040 			}
11041 
11042 			break;
11043 
11044 		case DTRACEACT_STACK:
11045 			if ((nframes = arg) == 0) {
11046 				nframes = opt[DTRACEOPT_STACKFRAMES];
11047 				ASSERT(nframes > 0);
11048 				arg = nframes;
11049 			}
11050 
11051 			size = nframes * sizeof (pc_t);
11052 			break;
11053 
11054 		case DTRACEACT_JSTACK:
11055 			if ((strsize = DTRACE_USTACK_STRSIZE(arg)) == 0)
11056 				strsize = opt[DTRACEOPT_JSTACKSTRSIZE];
11057 
11058 			if ((nframes = DTRACE_USTACK_NFRAMES(arg)) == 0)
11059 				nframes = opt[DTRACEOPT_JSTACKFRAMES];
11060 
11061 			arg = DTRACE_USTACK_ARG(nframes, strsize);
11062 
11063 			/*FALLTHROUGH*/
11064 		case DTRACEACT_USTACK:
11065 			if (desc->dtad_kind != DTRACEACT_JSTACK &&
11066 			    (nframes = DTRACE_USTACK_NFRAMES(arg)) == 0) {
11067 				strsize = DTRACE_USTACK_STRSIZE(arg);
11068 				nframes = opt[DTRACEOPT_USTACKFRAMES];
11069 				ASSERT(nframes > 0);
11070 				arg = DTRACE_USTACK_ARG(nframes, strsize);
11071 			}
11072 
11073 			/*
11074 			 * Save a slot for the pid.
11075 			 */
11076 			size = (nframes + 1) * sizeof (uint64_t);
11077 			size += DTRACE_USTACK_STRSIZE(arg);
11078 			size = P2ROUNDUP(size, (uint32_t)(sizeof (uintptr_t)));
11079 
11080 			break;
11081 
11082 		case DTRACEACT_SYM:
11083 		case DTRACEACT_MOD:
11084 			if (dp == NULL || ((size = dp->dtdo_rtype.dtdt_size) !=
11085 			    sizeof (uint64_t)) ||
11086 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11087 				return (EINVAL);
11088 			break;
11089 
11090 		case DTRACEACT_USYM:
11091 		case DTRACEACT_UMOD:
11092 		case DTRACEACT_UADDR:
11093 			if (dp == NULL ||
11094 			    (dp->dtdo_rtype.dtdt_size != sizeof (uint64_t)) ||
11095 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11096 				return (EINVAL);
11097 
11098 			/*
11099 			 * We have a slot for the pid, plus a slot for the
11100 			 * argument.  To keep things simple (aligned with
11101 			 * bitness-neutral sizing), we store each as a 64-bit
11102 			 * quantity.
11103 			 */
11104 			size = 2 * sizeof (uint64_t);
11105 			break;
11106 
11107 		case DTRACEACT_STOP:
11108 		case DTRACEACT_BREAKPOINT:
11109 		case DTRACEACT_PANIC:
11110 			break;
11111 
11112 		case DTRACEACT_CHILL:
11113 		case DTRACEACT_DISCARD:
11114 		case DTRACEACT_RAISE:
11115 			if (dp == NULL)
11116 				return (EINVAL);
11117 			break;
11118 
11119 		case DTRACEACT_EXIT:
11120 			if (dp == NULL ||
11121 			    (size = dp->dtdo_rtype.dtdt_size) != sizeof (int) ||
11122 			    (dp->dtdo_rtype.dtdt_flags & DIF_TF_BYREF))
11123 				return (EINVAL);
11124 			break;
11125 
11126 		case DTRACEACT_SPECULATE:
11127 			if (ecb->dte_size > sizeof (dtrace_rechdr_t))
11128 				return (EINVAL);
11129 
11130 			if (dp == NULL)
11131 				return (EINVAL);
11132 
11133 			state->dts_speculates = 1;
11134 			break;
11135 
11136 		case DTRACEACT_COMMIT: {
11137 			dtrace_action_t *act = ecb->dte_action;
11138 
11139 			for (; act != NULL; act = act->dta_next) {
11140 				if (act->dta_kind == DTRACEACT_COMMIT)
11141 					return (EINVAL);
11142 			}
11143 
11144 			if (dp == NULL)
11145 				return (EINVAL);
11146 			break;
11147 		}
11148 
11149 		default:
11150 			return (EINVAL);
11151 		}
11152 
11153 		if (size != 0 || desc->dtad_kind == DTRACEACT_SPECULATE) {
11154 			/*
11155 			 * If this is a data-storing action or a speculate,
11156 			 * we must be sure that there isn't a commit on the
11157 			 * action chain.
11158 			 */
11159 			dtrace_action_t *act = ecb->dte_action;
11160 
11161 			for (; act != NULL; act = act->dta_next) {
11162 				if (act->dta_kind == DTRACEACT_COMMIT)
11163 					return (EINVAL);
11164 			}
11165 		}
11166 
11167 		action = kmem_zalloc(sizeof (dtrace_action_t), KM_SLEEP);
11168 		action->dta_rec.dtrd_size = size;
11169 	}
11170 
11171 	action->dta_refcnt = 1;
11172 	rec = &action->dta_rec;
11173 	size = rec->dtrd_size;
11174 
11175 	for (mask = sizeof (uint64_t) - 1; size != 0 && mask > 0; mask >>= 1) {
11176 		if (!(size & mask)) {
11177 			align = mask + 1;
11178 			break;
11179 		}
11180 	}
11181 
11182 	action->dta_kind = desc->dtad_kind;
11183 
11184 	if ((action->dta_difo = dp) != NULL)
11185 		dtrace_difo_hold(dp);
11186 
11187 	rec->dtrd_action = action->dta_kind;
11188 	rec->dtrd_arg = arg;
11189 	rec->dtrd_uarg = desc->dtad_uarg;
11190 	rec->dtrd_alignment = (uint16_t)align;
11191 	rec->dtrd_format = format;
11192 
11193 	if ((last = ecb->dte_action_last) != NULL) {
11194 		ASSERT(ecb->dte_action != NULL);
11195 		action->dta_prev = last;
11196 		last->dta_next = action;
11197 	} else {
11198 		ASSERT(ecb->dte_action == NULL);
11199 		ecb->dte_action = action;
11200 	}
11201 
11202 	ecb->dte_action_last = action;
11203 
11204 	return (0);
11205 }
11206 
11207 static void
11208 dtrace_ecb_action_remove(dtrace_ecb_t *ecb)
11209 {
11210 	dtrace_action_t *act = ecb->dte_action, *next;
11211 	dtrace_vstate_t *vstate = &ecb->dte_state->dts_vstate;
11212 	dtrace_difo_t *dp;
11213 	uint16_t format;
11214 
11215 	if (act != NULL && act->dta_refcnt > 1) {
11216 		ASSERT(act->dta_next == NULL || act->dta_next->dta_refcnt == 1);
11217 		act->dta_refcnt--;
11218 	} else {
11219 		for (; act != NULL; act = next) {
11220 			next = act->dta_next;
11221 			ASSERT(next != NULL || act == ecb->dte_action_last);
11222 			ASSERT(act->dta_refcnt == 1);
11223 
11224 			if ((format = act->dta_rec.dtrd_format) != 0)
11225 				dtrace_format_remove(ecb->dte_state, format);
11226 
11227 			if ((dp = act->dta_difo) != NULL)
11228 				dtrace_difo_release(dp, vstate);
11229 
11230 			if (DTRACEACT_ISAGG(act->dta_kind)) {
11231 				dtrace_ecb_aggregation_destroy(ecb, act);
11232 			} else {
11233 				kmem_free(act, sizeof (dtrace_action_t));
11234 			}
11235 		}
11236 	}
11237 
11238 	ecb->dte_action = NULL;
11239 	ecb->dte_action_last = NULL;
11240 	ecb->dte_size = 0;
11241 }
11242 
11243 static void
11244 dtrace_ecb_disable(dtrace_ecb_t *ecb)
11245 {
11246 	/*
11247 	 * We disable the ECB by removing it from its probe.
11248 	 */
11249 	dtrace_ecb_t *pecb, *prev = NULL;
11250 	dtrace_probe_t *probe = ecb->dte_probe;
11251 
11252 	ASSERT(MUTEX_HELD(&dtrace_lock));
11253 
11254 	if (probe == NULL) {
11255 		/*
11256 		 * This is the NULL probe; there is nothing to disable.
11257 		 */
11258 		return;
11259 	}
11260 
11261 	for (pecb = probe->dtpr_ecb; pecb != NULL; pecb = pecb->dte_next) {
11262 		if (pecb == ecb)
11263 			break;
11264 		prev = pecb;
11265 	}
11266 
11267 	ASSERT(pecb != NULL);
11268 
11269 	if (prev == NULL) {
11270 		probe->dtpr_ecb = ecb->dte_next;
11271 	} else {
11272 		prev->dte_next = ecb->dte_next;
11273 	}
11274 
11275 	if (ecb == probe->dtpr_ecb_last) {
11276 		ASSERT(ecb->dte_next == NULL);
11277 		probe->dtpr_ecb_last = prev;
11278 	}
11279 
11280 	/*
11281 	 * The ECB has been disconnected from the probe; now sync to assure
11282 	 * that all CPUs have seen the change before returning.
11283 	 */
11284 	dtrace_sync();
11285 
11286 	if (probe->dtpr_ecb == NULL) {
11287 		/*
11288 		 * That was the last ECB on the probe; clear the predicate
11289 		 * cache ID for the probe, disable it and sync one more time
11290 		 * to assure that we'll never hit it again.
11291 		 */
11292 		dtrace_provider_t *prov = probe->dtpr_provider;
11293 
11294 		ASSERT(ecb->dte_next == NULL);
11295 		ASSERT(probe->dtpr_ecb_last == NULL);
11296 		probe->dtpr_predcache = DTRACE_CACHEIDNONE;
11297 		prov->dtpv_pops.dtps_disable(prov->dtpv_arg,
11298 		    probe->dtpr_id, probe->dtpr_arg);
11299 		dtrace_sync();
11300 	} else {
11301 		/*
11302 		 * There is at least one ECB remaining on the probe.  If there
11303 		 * is _exactly_ one, set the probe's predicate cache ID to be
11304 		 * the predicate cache ID of the remaining ECB.
11305 		 */
11306 		ASSERT(probe->dtpr_ecb_last != NULL);
11307 		ASSERT(probe->dtpr_predcache == DTRACE_CACHEIDNONE);
11308 
11309 		if (probe->dtpr_ecb == probe->dtpr_ecb_last) {
11310 			dtrace_predicate_t *p = probe->dtpr_ecb->dte_predicate;
11311 
11312 			ASSERT(probe->dtpr_ecb->dte_next == NULL);
11313 
11314 			if (p != NULL)
11315 				probe->dtpr_predcache = p->dtp_cacheid;
11316 		}
11317 
11318 		ecb->dte_next = NULL;
11319 	}
11320 }
11321 
11322 static void
11323 dtrace_ecb_destroy(dtrace_ecb_t *ecb)
11324 {
11325 	dtrace_state_t *state = ecb->dte_state;
11326 	dtrace_vstate_t *vstate = &state->dts_vstate;
11327 	dtrace_predicate_t *pred;
11328 	dtrace_epid_t epid = ecb->dte_epid;
11329 
11330 	ASSERT(MUTEX_HELD(&dtrace_lock));
11331 	ASSERT(ecb->dte_next == NULL);
11332 	ASSERT(ecb->dte_probe == NULL || ecb->dte_probe->dtpr_ecb != ecb);
11333 
11334 	if ((pred = ecb->dte_predicate) != NULL)
11335 		dtrace_predicate_release(pred, vstate);
11336 
11337 	dtrace_ecb_action_remove(ecb);
11338 
11339 	ASSERT(state->dts_ecbs[epid - 1] == ecb);
11340 	state->dts_ecbs[epid - 1] = NULL;
11341 
11342 	kmem_free(ecb, sizeof (dtrace_ecb_t));
11343 }
11344 
11345 static dtrace_ecb_t *
11346 dtrace_ecb_create(dtrace_state_t *state, dtrace_probe_t *probe,
11347     dtrace_enabling_t *enab)
11348 {
11349 	dtrace_ecb_t *ecb;
11350 	dtrace_predicate_t *pred;
11351 	dtrace_actdesc_t *act;
11352 	dtrace_provider_t *prov;
11353 	dtrace_ecbdesc_t *desc = enab->dten_current;
11354 
11355 	ASSERT(MUTEX_HELD(&dtrace_lock));
11356 	ASSERT(state != NULL);
11357 
11358 	ecb = dtrace_ecb_add(state, probe);
11359 	ecb->dte_uarg = desc->dted_uarg;
11360 
11361 	if ((pred = desc->dted_pred.dtpdd_predicate) != NULL) {
11362 		dtrace_predicate_hold(pred);
11363 		ecb->dte_predicate = pred;
11364 	}
11365 
11366 	if (probe != NULL) {
11367 		/*
11368 		 * If the provider shows more leg than the consumer is old
11369 		 * enough to see, we need to enable the appropriate implicit
11370 		 * predicate bits to prevent the ecb from activating at
11371 		 * revealing times.
11372 		 *
11373 		 * Providers specifying DTRACE_PRIV_USER at register time
11374 		 * are stating that they need the /proc-style privilege
11375 		 * model to be enforced, and this is what DTRACE_COND_OWNER
11376 		 * and DTRACE_COND_ZONEOWNER will then do at probe time.
11377 		 */
11378 		prov = probe->dtpr_provider;
11379 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLPROC) &&
11380 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11381 			ecb->dte_cond |= DTRACE_COND_OWNER;
11382 
11383 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_ALLZONE) &&
11384 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_USER))
11385 			ecb->dte_cond |= DTRACE_COND_ZONEOWNER;
11386 
11387 		/*
11388 		 * If the provider shows us kernel innards and the user
11389 		 * is lacking sufficient privilege, enable the
11390 		 * DTRACE_COND_USERMODE implicit predicate.
11391 		 */
11392 		if (!(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL) &&
11393 		    (prov->dtpv_priv.dtpp_flags & DTRACE_PRIV_KERNEL))
11394 			ecb->dte_cond |= DTRACE_COND_USERMODE;
11395 	}
11396 
11397 	if (dtrace_ecb_create_cache != NULL) {
11398 		/*
11399 		 * If we have a cached ecb, we'll use its action list instead
11400 		 * of creating our own (saving both time and space).
11401 		 */
11402 		dtrace_ecb_t *cached = dtrace_ecb_create_cache;
11403 		dtrace_action_t *act = cached->dte_action;
11404 
11405 		if (act != NULL) {
11406 			ASSERT(act->dta_refcnt > 0);
11407 			act->dta_refcnt++;
11408 			ecb->dte_action = act;
11409 			ecb->dte_action_last = cached->dte_action_last;
11410 			ecb->dte_needed = cached->dte_needed;
11411 			ecb->dte_size = cached->dte_size;
11412 			ecb->dte_alignment = cached->dte_alignment;
11413 		}
11414 
11415 		return (ecb);
11416 	}
11417 
11418 	for (act = desc->dted_action; act != NULL; act = act->dtad_next) {
11419 		if ((enab->dten_error = dtrace_ecb_action_add(ecb, act)) != 0) {
11420 			dtrace_ecb_destroy(ecb);
11421 			return (NULL);
11422 		}
11423 	}
11424 
11425 	if ((enab->dten_error = dtrace_ecb_resize(ecb)) != 0) {
11426 		dtrace_ecb_destroy(ecb);
11427 		return (NULL);
11428 	}
11429 
11430 	return (dtrace_ecb_create_cache = ecb);
11431 }
11432 
11433 static int
11434 dtrace_ecb_create_enable(dtrace_probe_t *probe, void *arg)
11435 {
11436 	dtrace_ecb_t *ecb;
11437 	dtrace_enabling_t *enab = arg;
11438 	dtrace_state_t *state = enab->dten_vstate->dtvs_state;
11439 
11440 	ASSERT(state != NULL);
11441 
11442 	if (probe != NULL && probe->dtpr_gen < enab->dten_probegen) {
11443 		/*
11444 		 * This probe was created in a generation for which this
11445 		 * enabling has previously created ECBs; we don't want to
11446 		 * enable it again, so just kick out.
11447 		 */
11448 		return (DTRACE_MATCH_NEXT);
11449 	}
11450 
11451 	if ((ecb = dtrace_ecb_create(state, probe, enab)) == NULL)
11452 		return (DTRACE_MATCH_DONE);
11453 
11454 	if (dtrace_ecb_enable(ecb) < 0)
11455 		return (DTRACE_MATCH_FAIL);
11456 
11457 	return (DTRACE_MATCH_NEXT);
11458 }
11459 
11460 static dtrace_ecb_t *
11461 dtrace_epid2ecb(dtrace_state_t *state, dtrace_epid_t id)
11462 {
11463 	dtrace_ecb_t *ecb;
11464 
11465 	ASSERT(MUTEX_HELD(&dtrace_lock));
11466 
11467 	if (id == 0 || id > state->dts_necbs)
11468 		return (NULL);
11469 
11470 	ASSERT(state->dts_necbs > 0 && state->dts_ecbs != NULL);
11471 	ASSERT((ecb = state->dts_ecbs[id - 1]) == NULL || ecb->dte_epid == id);
11472 
11473 	return (state->dts_ecbs[id - 1]);
11474 }
11475 
11476 static dtrace_aggregation_t *
11477 dtrace_aggid2agg(dtrace_state_t *state, dtrace_aggid_t id)
11478 {
11479 	dtrace_aggregation_t *agg;
11480 
11481 	ASSERT(MUTEX_HELD(&dtrace_lock));
11482 
11483 	if (id == 0 || id > state->dts_naggregations)
11484 		return (NULL);
11485 
11486 	ASSERT(state->dts_naggregations > 0 && state->dts_aggregations != NULL);
11487 	ASSERT((agg = state->dts_aggregations[id - 1]) == NULL ||
11488 	    agg->dtag_id == id);
11489 
11490 	return (state->dts_aggregations[id - 1]);
11491 }
11492 
11493 /*
11494  * DTrace Buffer Functions
11495  *
11496  * The following functions manipulate DTrace buffers.  Most of these functions
11497  * are called in the context of establishing or processing consumer state;
11498  * exceptions are explicitly noted.
11499  */
11500 
11501 /*
11502  * Note:  called from cross call context.  This function switches the two
11503  * buffers on a given CPU.  The atomicity of this operation is assured by
11504  * disabling interrupts while the actual switch takes place; the disabling of
11505  * interrupts serializes the execution with any execution of dtrace_probe() on
11506  * the same CPU.
11507  */
11508 static void
11509 dtrace_buffer_switch(dtrace_buffer_t *buf)
11510 {
11511 	caddr_t tomax = buf->dtb_tomax;
11512 	caddr_t xamot = buf->dtb_xamot;
11513 	dtrace_icookie_t cookie;
11514 	hrtime_t now;
11515 
11516 	ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11517 	ASSERT(!(buf->dtb_flags & DTRACEBUF_RING));
11518 
11519 	cookie = dtrace_interrupt_disable();
11520 	now = dtrace_gethrtime();
11521 	buf->dtb_tomax = xamot;
11522 	buf->dtb_xamot = tomax;
11523 	buf->dtb_xamot_drops = buf->dtb_drops;
11524 	buf->dtb_xamot_offset = buf->dtb_offset;
11525 	buf->dtb_xamot_errors = buf->dtb_errors;
11526 	buf->dtb_xamot_flags = buf->dtb_flags;
11527 	buf->dtb_offset = 0;
11528 	buf->dtb_drops = 0;
11529 	buf->dtb_errors = 0;
11530 	buf->dtb_flags &= ~(DTRACEBUF_ERROR | DTRACEBUF_DROPPED);
11531 	buf->dtb_interval = now - buf->dtb_switched;
11532 	buf->dtb_switched = now;
11533 	dtrace_interrupt_enable(cookie);
11534 }
11535 
11536 /*
11537  * Note:  called from cross call context.  This function activates a buffer
11538  * on a CPU.  As with dtrace_buffer_switch(), the atomicity of the operation
11539  * is guaranteed by the disabling of interrupts.
11540  */
11541 static void
11542 dtrace_buffer_activate(dtrace_state_t *state)
11543 {
11544 	dtrace_buffer_t *buf;
11545 	dtrace_icookie_t cookie = dtrace_interrupt_disable();
11546 
11547 	buf = &state->dts_buffer[CPU->cpu_id];
11548 
11549 	if (buf->dtb_tomax != NULL) {
11550 		/*
11551 		 * We might like to assert that the buffer is marked inactive,
11552 		 * but this isn't necessarily true:  the buffer for the CPU
11553 		 * that processes the BEGIN probe has its buffer activated
11554 		 * manually.  In this case, we take the (harmless) action
11555 		 * re-clearing the bit INACTIVE bit.
11556 		 */
11557 		buf->dtb_flags &= ~DTRACEBUF_INACTIVE;
11558 	}
11559 
11560 	dtrace_interrupt_enable(cookie);
11561 }
11562 
11563 static int
11564 dtrace_buffer_alloc(dtrace_buffer_t *bufs, size_t size, int flags,
11565     processorid_t cpu, int *factor)
11566 {
11567 	cpu_t *cp;
11568 	dtrace_buffer_t *buf;
11569 	int allocated = 0, desired = 0;
11570 
11571 	ASSERT(MUTEX_HELD(&cpu_lock));
11572 	ASSERT(MUTEX_HELD(&dtrace_lock));
11573 
11574 	*factor = 1;
11575 
11576 	if (size > dtrace_nonroot_maxsize &&
11577 	    !PRIV_POLICY_CHOICE(CRED(), PRIV_ALL, B_FALSE))
11578 		return (EFBIG);
11579 
11580 	cp = cpu_list;
11581 
11582 	do {
11583 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11584 			continue;
11585 
11586 		buf = &bufs[cp->cpu_id];
11587 
11588 		/*
11589 		 * If there is already a buffer allocated for this CPU, it
11590 		 * is only possible that this is a DR event.  In this case,
11591 		 * the buffer size must match our specified size.
11592 		 */
11593 		if (buf->dtb_tomax != NULL) {
11594 			ASSERT(buf->dtb_size == size);
11595 			continue;
11596 		}
11597 
11598 		ASSERT(buf->dtb_xamot == NULL);
11599 
11600 		if ((buf->dtb_tomax = kmem_zalloc(size,
11601 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11602 			goto err;
11603 
11604 		buf->dtb_size = size;
11605 		buf->dtb_flags = flags;
11606 		buf->dtb_offset = 0;
11607 		buf->dtb_drops = 0;
11608 
11609 		if (flags & DTRACEBUF_NOSWITCH)
11610 			continue;
11611 
11612 		if ((buf->dtb_xamot = kmem_zalloc(size,
11613 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL)
11614 			goto err;
11615 	} while ((cp = cp->cpu_next) != cpu_list);
11616 
11617 	return (0);
11618 
11619 err:
11620 	cp = cpu_list;
11621 
11622 	do {
11623 		if (cpu != DTRACE_CPUALL && cpu != cp->cpu_id)
11624 			continue;
11625 
11626 		buf = &bufs[cp->cpu_id];
11627 		desired += 2;
11628 
11629 		if (buf->dtb_xamot != NULL) {
11630 			ASSERT(buf->dtb_tomax != NULL);
11631 			ASSERT(buf->dtb_size == size);
11632 			kmem_free(buf->dtb_xamot, size);
11633 			allocated++;
11634 		}
11635 
11636 		if (buf->dtb_tomax != NULL) {
11637 			ASSERT(buf->dtb_size == size);
11638 			kmem_free(buf->dtb_tomax, size);
11639 			allocated++;
11640 		}
11641 
11642 		buf->dtb_tomax = NULL;
11643 		buf->dtb_xamot = NULL;
11644 		buf->dtb_size = 0;
11645 	} while ((cp = cp->cpu_next) != cpu_list);
11646 
11647 	*factor = desired / (allocated > 0 ? allocated : 1);
11648 
11649 	return (ENOMEM);
11650 }
11651 
11652 /*
11653  * Note:  called from probe context.  This function just increments the drop
11654  * count on a buffer.  It has been made a function to allow for the
11655  * possibility of understanding the source of mysterious drop counts.  (A
11656  * problem for which one may be particularly disappointed that DTrace cannot
11657  * be used to understand DTrace.)
11658  */
11659 static void
11660 dtrace_buffer_drop(dtrace_buffer_t *buf)
11661 {
11662 	buf->dtb_drops++;
11663 }
11664 
11665 /*
11666  * Note:  called from probe context.  This function is called to reserve space
11667  * in a buffer.  If mstate is non-NULL, sets the scratch base and size in the
11668  * mstate.  Returns the new offset in the buffer, or a negative value if an
11669  * error has occurred.
11670  */
11671 static intptr_t
11672 dtrace_buffer_reserve(dtrace_buffer_t *buf, size_t needed, size_t align,
11673     dtrace_state_t *state, dtrace_mstate_t *mstate)
11674 {
11675 	intptr_t offs = buf->dtb_offset, soffs;
11676 	intptr_t woffs;
11677 	caddr_t tomax;
11678 	size_t total;
11679 
11680 	if (buf->dtb_flags & DTRACEBUF_INACTIVE)
11681 		return (-1);
11682 
11683 	if ((tomax = buf->dtb_tomax) == NULL) {
11684 		dtrace_buffer_drop(buf);
11685 		return (-1);
11686 	}
11687 
11688 	if (!(buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL))) {
11689 		while (offs & (align - 1)) {
11690 			/*
11691 			 * Assert that our alignment is off by a number which
11692 			 * is itself sizeof (uint32_t) aligned.
11693 			 */
11694 			ASSERT(!((align - (offs & (align - 1))) &
11695 			    (sizeof (uint32_t) - 1)));
11696 			DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11697 			offs += sizeof (uint32_t);
11698 		}
11699 
11700 		if ((soffs = offs + needed) > buf->dtb_size) {
11701 			dtrace_buffer_drop(buf);
11702 			return (-1);
11703 		}
11704 
11705 		if (mstate == NULL)
11706 			return (offs);
11707 
11708 		mstate->dtms_scratch_base = (uintptr_t)tomax + soffs;
11709 		mstate->dtms_scratch_size = buf->dtb_size - soffs;
11710 		mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11711 
11712 		return (offs);
11713 	}
11714 
11715 	if (buf->dtb_flags & DTRACEBUF_FILL) {
11716 		if (state->dts_activity != DTRACE_ACTIVITY_COOLDOWN &&
11717 		    (buf->dtb_flags & DTRACEBUF_FULL))
11718 			return (-1);
11719 		goto out;
11720 	}
11721 
11722 	total = needed + (offs & (align - 1));
11723 
11724 	/*
11725 	 * For a ring buffer, life is quite a bit more complicated.  Before
11726 	 * we can store any padding, we need to adjust our wrapping offset.
11727 	 * (If we've never before wrapped or we're not about to, no adjustment
11728 	 * is required.)
11729 	 */
11730 	if ((buf->dtb_flags & DTRACEBUF_WRAPPED) ||
11731 	    offs + total > buf->dtb_size) {
11732 		woffs = buf->dtb_xamot_offset;
11733 
11734 		if (offs + total > buf->dtb_size) {
11735 			/*
11736 			 * We can't fit in the end of the buffer.  First, a
11737 			 * sanity check that we can fit in the buffer at all.
11738 			 */
11739 			if (total > buf->dtb_size) {
11740 				dtrace_buffer_drop(buf);
11741 				return (-1);
11742 			}
11743 
11744 			/*
11745 			 * We're going to be storing at the top of the buffer,
11746 			 * so now we need to deal with the wrapped offset.  We
11747 			 * only reset our wrapped offset to 0 if it is
11748 			 * currently greater than the current offset.  If it
11749 			 * is less than the current offset, it is because a
11750 			 * previous allocation induced a wrap -- but the
11751 			 * allocation didn't subsequently take the space due
11752 			 * to an error or false predicate evaluation.  In this
11753 			 * case, we'll just leave the wrapped offset alone: if
11754 			 * the wrapped offset hasn't been advanced far enough
11755 			 * for this allocation, it will be adjusted in the
11756 			 * lower loop.
11757 			 */
11758 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
11759 				if (woffs >= offs)
11760 					woffs = 0;
11761 			} else {
11762 				woffs = 0;
11763 			}
11764 
11765 			/*
11766 			 * Now we know that we're going to be storing to the
11767 			 * top of the buffer and that there is room for us
11768 			 * there.  We need to clear the buffer from the current
11769 			 * offset to the end (there may be old gunk there).
11770 			 */
11771 			while (offs < buf->dtb_size)
11772 				tomax[offs++] = 0;
11773 
11774 			/*
11775 			 * We need to set our offset to zero.  And because we
11776 			 * are wrapping, we need to set the bit indicating as
11777 			 * much.  We can also adjust our needed space back
11778 			 * down to the space required by the ECB -- we know
11779 			 * that the top of the buffer is aligned.
11780 			 */
11781 			offs = 0;
11782 			total = needed;
11783 			buf->dtb_flags |= DTRACEBUF_WRAPPED;
11784 		} else {
11785 			/*
11786 			 * There is room for us in the buffer, so we simply
11787 			 * need to check the wrapped offset.
11788 			 */
11789 			if (woffs < offs) {
11790 				/*
11791 				 * The wrapped offset is less than the offset.
11792 				 * This can happen if we allocated buffer space
11793 				 * that induced a wrap, but then we didn't
11794 				 * subsequently take the space due to an error
11795 				 * or false predicate evaluation.  This is
11796 				 * okay; we know that _this_ allocation isn't
11797 				 * going to induce a wrap.  We still can't
11798 				 * reset the wrapped offset to be zero,
11799 				 * however: the space may have been trashed in
11800 				 * the previous failed probe attempt.  But at
11801 				 * least the wrapped offset doesn't need to
11802 				 * be adjusted at all...
11803 				 */
11804 				goto out;
11805 			}
11806 		}
11807 
11808 		while (offs + total > woffs) {
11809 			dtrace_epid_t epid = *(uint32_t *)(tomax + woffs);
11810 			size_t size;
11811 
11812 			if (epid == DTRACE_EPIDNONE) {
11813 				size = sizeof (uint32_t);
11814 			} else {
11815 				ASSERT3U(epid, <=, state->dts_necbs);
11816 				ASSERT(state->dts_ecbs[epid - 1] != NULL);
11817 
11818 				size = state->dts_ecbs[epid - 1]->dte_size;
11819 			}
11820 
11821 			ASSERT(woffs + size <= buf->dtb_size);
11822 			ASSERT(size != 0);
11823 
11824 			if (woffs + size == buf->dtb_size) {
11825 				/*
11826 				 * We've reached the end of the buffer; we want
11827 				 * to set the wrapped offset to 0 and break
11828 				 * out.  However, if the offs is 0, then we're
11829 				 * in a strange edge-condition:  the amount of
11830 				 * space that we want to reserve plus the size
11831 				 * of the record that we're overwriting is
11832 				 * greater than the size of the buffer.  This
11833 				 * is problematic because if we reserve the
11834 				 * space but subsequently don't consume it (due
11835 				 * to a failed predicate or error) the wrapped
11836 				 * offset will be 0 -- yet the EPID at offset 0
11837 				 * will not be committed.  This situation is
11838 				 * relatively easy to deal with:  if we're in
11839 				 * this case, the buffer is indistinguishable
11840 				 * from one that hasn't wrapped; we need only
11841 				 * finish the job by clearing the wrapped bit,
11842 				 * explicitly setting the offset to be 0, and
11843 				 * zero'ing out the old data in the buffer.
11844 				 */
11845 				if (offs == 0) {
11846 					buf->dtb_flags &= ~DTRACEBUF_WRAPPED;
11847 					buf->dtb_offset = 0;
11848 					woffs = total;
11849 
11850 					while (woffs < buf->dtb_size)
11851 						tomax[woffs++] = 0;
11852 				}
11853 
11854 				woffs = 0;
11855 				break;
11856 			}
11857 
11858 			woffs += size;
11859 		}
11860 
11861 		/*
11862 		 * We have a wrapped offset.  It may be that the wrapped offset
11863 		 * has become zero -- that's okay.
11864 		 */
11865 		buf->dtb_xamot_offset = woffs;
11866 	}
11867 
11868 out:
11869 	/*
11870 	 * Now we can plow the buffer with any necessary padding.
11871 	 */
11872 	while (offs & (align - 1)) {
11873 		/*
11874 		 * Assert that our alignment is off by a number which
11875 		 * is itself sizeof (uint32_t) aligned.
11876 		 */
11877 		ASSERT(!((align - (offs & (align - 1))) &
11878 		    (sizeof (uint32_t) - 1)));
11879 		DTRACE_STORE(uint32_t, tomax, offs, DTRACE_EPIDNONE);
11880 		offs += sizeof (uint32_t);
11881 	}
11882 
11883 	if (buf->dtb_flags & DTRACEBUF_FILL) {
11884 		if (offs + needed > buf->dtb_size - state->dts_reserve) {
11885 			buf->dtb_flags |= DTRACEBUF_FULL;
11886 			return (-1);
11887 		}
11888 	}
11889 
11890 	if (mstate == NULL)
11891 		return (offs);
11892 
11893 	/*
11894 	 * For ring buffers and fill buffers, the scratch space is always
11895 	 * the inactive buffer.
11896 	 */
11897 	mstate->dtms_scratch_base = (uintptr_t)buf->dtb_xamot;
11898 	mstate->dtms_scratch_size = buf->dtb_size;
11899 	mstate->dtms_scratch_ptr = mstate->dtms_scratch_base;
11900 
11901 	return (offs);
11902 }
11903 
11904 static void
11905 dtrace_buffer_polish(dtrace_buffer_t *buf)
11906 {
11907 	ASSERT(buf->dtb_flags & DTRACEBUF_RING);
11908 	ASSERT(MUTEX_HELD(&dtrace_lock));
11909 
11910 	if (!(buf->dtb_flags & DTRACEBUF_WRAPPED))
11911 		return;
11912 
11913 	/*
11914 	 * We need to polish the ring buffer.  There are three cases:
11915 	 *
11916 	 * - The first (and presumably most common) is that there is no gap
11917 	 *   between the buffer offset and the wrapped offset.  In this case,
11918 	 *   there is nothing in the buffer that isn't valid data; we can
11919 	 *   mark the buffer as polished and return.
11920 	 *
11921 	 * - The second (less common than the first but still more common
11922 	 *   than the third) is that there is a gap between the buffer offset
11923 	 *   and the wrapped offset, and the wrapped offset is larger than the
11924 	 *   buffer offset.  This can happen because of an alignment issue, or
11925 	 *   can happen because of a call to dtrace_buffer_reserve() that
11926 	 *   didn't subsequently consume the buffer space.  In this case,
11927 	 *   we need to zero the data from the buffer offset to the wrapped
11928 	 *   offset.
11929 	 *
11930 	 * - The third (and least common) is that there is a gap between the
11931 	 *   buffer offset and the wrapped offset, but the wrapped offset is
11932 	 *   _less_ than the buffer offset.  This can only happen because a
11933 	 *   call to dtrace_buffer_reserve() induced a wrap, but the space
11934 	 *   was not subsequently consumed.  In this case, we need to zero the
11935 	 *   space from the offset to the end of the buffer _and_ from the
11936 	 *   top of the buffer to the wrapped offset.
11937 	 */
11938 	if (buf->dtb_offset < buf->dtb_xamot_offset) {
11939 		bzero(buf->dtb_tomax + buf->dtb_offset,
11940 		    buf->dtb_xamot_offset - buf->dtb_offset);
11941 	}
11942 
11943 	if (buf->dtb_offset > buf->dtb_xamot_offset) {
11944 		bzero(buf->dtb_tomax + buf->dtb_offset,
11945 		    buf->dtb_size - buf->dtb_offset);
11946 		bzero(buf->dtb_tomax, buf->dtb_xamot_offset);
11947 	}
11948 }
11949 
11950 /*
11951  * This routine determines if data generated at the specified time has likely
11952  * been entirely consumed at user-level.  This routine is called to determine
11953  * if an ECB on a defunct probe (but for an active enabling) can be safely
11954  * disabled and destroyed.
11955  */
11956 static int
11957 dtrace_buffer_consumed(dtrace_buffer_t *bufs, hrtime_t when)
11958 {
11959 	int i;
11960 
11961 	for (i = 0; i < NCPU; i++) {
11962 		dtrace_buffer_t *buf = &bufs[i];
11963 
11964 		if (buf->dtb_size == 0)
11965 			continue;
11966 
11967 		if (buf->dtb_flags & DTRACEBUF_RING)
11968 			return (0);
11969 
11970 		if (!buf->dtb_switched && buf->dtb_offset != 0)
11971 			return (0);
11972 
11973 		if (buf->dtb_switched - buf->dtb_interval < when)
11974 			return (0);
11975 	}
11976 
11977 	return (1);
11978 }
11979 
11980 static void
11981 dtrace_buffer_free(dtrace_buffer_t *bufs)
11982 {
11983 	int i;
11984 
11985 	for (i = 0; i < NCPU; i++) {
11986 		dtrace_buffer_t *buf = &bufs[i];
11987 
11988 		if (buf->dtb_tomax == NULL) {
11989 			ASSERT(buf->dtb_xamot == NULL);
11990 			ASSERT(buf->dtb_size == 0);
11991 			continue;
11992 		}
11993 
11994 		if (buf->dtb_xamot != NULL) {
11995 			ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
11996 			kmem_free(buf->dtb_xamot, buf->dtb_size);
11997 		}
11998 
11999 		kmem_free(buf->dtb_tomax, buf->dtb_size);
12000 		buf->dtb_size = 0;
12001 		buf->dtb_tomax = NULL;
12002 		buf->dtb_xamot = NULL;
12003 	}
12004 }
12005 
12006 /*
12007  * DTrace Enabling Functions
12008  */
12009 static dtrace_enabling_t *
12010 dtrace_enabling_create(dtrace_vstate_t *vstate)
12011 {
12012 	dtrace_enabling_t *enab;
12013 
12014 	enab = kmem_zalloc(sizeof (dtrace_enabling_t), KM_SLEEP);
12015 	enab->dten_vstate = vstate;
12016 
12017 	return (enab);
12018 }
12019 
12020 static void
12021 dtrace_enabling_add(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb)
12022 {
12023 	dtrace_ecbdesc_t **ndesc;
12024 	size_t osize, nsize;
12025 
12026 	/*
12027 	 * We can't add to enablings after we've enabled them, or after we've
12028 	 * retained them.
12029 	 */
12030 	ASSERT(enab->dten_probegen == 0);
12031 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12032 
12033 	if (enab->dten_ndesc < enab->dten_maxdesc) {
12034 		enab->dten_desc[enab->dten_ndesc++] = ecb;
12035 		return;
12036 	}
12037 
12038 	osize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12039 
12040 	if (enab->dten_maxdesc == 0) {
12041 		enab->dten_maxdesc = 1;
12042 	} else {
12043 		enab->dten_maxdesc <<= 1;
12044 	}
12045 
12046 	ASSERT(enab->dten_ndesc < enab->dten_maxdesc);
12047 
12048 	nsize = enab->dten_maxdesc * sizeof (dtrace_enabling_t *);
12049 	ndesc = kmem_zalloc(nsize, KM_SLEEP);
12050 	bcopy(enab->dten_desc, ndesc, osize);
12051 	kmem_free(enab->dten_desc, osize);
12052 
12053 	enab->dten_desc = ndesc;
12054 	enab->dten_desc[enab->dten_ndesc++] = ecb;
12055 }
12056 
12057 static void
12058 dtrace_enabling_addlike(dtrace_enabling_t *enab, dtrace_ecbdesc_t *ecb,
12059     dtrace_probedesc_t *pd)
12060 {
12061 	dtrace_ecbdesc_t *new;
12062 	dtrace_predicate_t *pred;
12063 	dtrace_actdesc_t *act;
12064 
12065 	/*
12066 	 * We're going to create a new ECB description that matches the
12067 	 * specified ECB in every way, but has the specified probe description.
12068 	 */
12069 	new = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
12070 
12071 	if ((pred = ecb->dted_pred.dtpdd_predicate) != NULL)
12072 		dtrace_predicate_hold(pred);
12073 
12074 	for (act = ecb->dted_action; act != NULL; act = act->dtad_next)
12075 		dtrace_actdesc_hold(act);
12076 
12077 	new->dted_action = ecb->dted_action;
12078 	new->dted_pred = ecb->dted_pred;
12079 	new->dted_probe = *pd;
12080 	new->dted_uarg = ecb->dted_uarg;
12081 
12082 	dtrace_enabling_add(enab, new);
12083 }
12084 
12085 static void
12086 dtrace_enabling_dump(dtrace_enabling_t *enab)
12087 {
12088 	int i;
12089 
12090 	for (i = 0; i < enab->dten_ndesc; i++) {
12091 		dtrace_probedesc_t *desc = &enab->dten_desc[i]->dted_probe;
12092 
12093 		cmn_err(CE_NOTE, "enabling probe %d (%s:%s:%s:%s)", i,
12094 		    desc->dtpd_provider, desc->dtpd_mod,
12095 		    desc->dtpd_func, desc->dtpd_name);
12096 	}
12097 }
12098 
12099 static void
12100 dtrace_enabling_destroy(dtrace_enabling_t *enab)
12101 {
12102 	int i;
12103 	dtrace_ecbdesc_t *ep;
12104 	dtrace_vstate_t *vstate = enab->dten_vstate;
12105 
12106 	ASSERT(MUTEX_HELD(&dtrace_lock));
12107 
12108 	for (i = 0; i < enab->dten_ndesc; i++) {
12109 		dtrace_actdesc_t *act, *next;
12110 		dtrace_predicate_t *pred;
12111 
12112 		ep = enab->dten_desc[i];
12113 
12114 		if ((pred = ep->dted_pred.dtpdd_predicate) != NULL)
12115 			dtrace_predicate_release(pred, vstate);
12116 
12117 		for (act = ep->dted_action; act != NULL; act = next) {
12118 			next = act->dtad_next;
12119 			dtrace_actdesc_release(act, vstate);
12120 		}
12121 
12122 		kmem_free(ep, sizeof (dtrace_ecbdesc_t));
12123 	}
12124 
12125 	kmem_free(enab->dten_desc,
12126 	    enab->dten_maxdesc * sizeof (dtrace_enabling_t *));
12127 
12128 	/*
12129 	 * If this was a retained enabling, decrement the dts_nretained count
12130 	 * and take it off of the dtrace_retained list.
12131 	 */
12132 	if (enab->dten_prev != NULL || enab->dten_next != NULL ||
12133 	    dtrace_retained == enab) {
12134 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12135 		ASSERT(enab->dten_vstate->dtvs_state->dts_nretained > 0);
12136 		enab->dten_vstate->dtvs_state->dts_nretained--;
12137 		dtrace_retained_gen++;
12138 	}
12139 
12140 	if (enab->dten_prev == NULL) {
12141 		if (dtrace_retained == enab) {
12142 			dtrace_retained = enab->dten_next;
12143 
12144 			if (dtrace_retained != NULL)
12145 				dtrace_retained->dten_prev = NULL;
12146 		}
12147 	} else {
12148 		ASSERT(enab != dtrace_retained);
12149 		ASSERT(dtrace_retained != NULL);
12150 		enab->dten_prev->dten_next = enab->dten_next;
12151 	}
12152 
12153 	if (enab->dten_next != NULL) {
12154 		ASSERT(dtrace_retained != NULL);
12155 		enab->dten_next->dten_prev = enab->dten_prev;
12156 	}
12157 
12158 	kmem_free(enab, sizeof (dtrace_enabling_t));
12159 }
12160 
12161 static int
12162 dtrace_enabling_retain(dtrace_enabling_t *enab)
12163 {
12164 	dtrace_state_t *state;
12165 
12166 	ASSERT(MUTEX_HELD(&dtrace_lock));
12167 	ASSERT(enab->dten_next == NULL && enab->dten_prev == NULL);
12168 	ASSERT(enab->dten_vstate != NULL);
12169 
12170 	state = enab->dten_vstate->dtvs_state;
12171 	ASSERT(state != NULL);
12172 
12173 	/*
12174 	 * We only allow each state to retain dtrace_retain_max enablings.
12175 	 */
12176 	if (state->dts_nretained >= dtrace_retain_max)
12177 		return (ENOSPC);
12178 
12179 	state->dts_nretained++;
12180 	dtrace_retained_gen++;
12181 
12182 	if (dtrace_retained == NULL) {
12183 		dtrace_retained = enab;
12184 		return (0);
12185 	}
12186 
12187 	enab->dten_next = dtrace_retained;
12188 	dtrace_retained->dten_prev = enab;
12189 	dtrace_retained = enab;
12190 
12191 	return (0);
12192 }
12193 
12194 static int
12195 dtrace_enabling_replicate(dtrace_state_t *state, dtrace_probedesc_t *match,
12196     dtrace_probedesc_t *create)
12197 {
12198 	dtrace_enabling_t *new, *enab;
12199 	int found = 0, err = ENOENT;
12200 
12201 	ASSERT(MUTEX_HELD(&dtrace_lock));
12202 	ASSERT(strlen(match->dtpd_provider) < DTRACE_PROVNAMELEN);
12203 	ASSERT(strlen(match->dtpd_mod) < DTRACE_MODNAMELEN);
12204 	ASSERT(strlen(match->dtpd_func) < DTRACE_FUNCNAMELEN);
12205 	ASSERT(strlen(match->dtpd_name) < DTRACE_NAMELEN);
12206 
12207 	new = dtrace_enabling_create(&state->dts_vstate);
12208 
12209 	/*
12210 	 * Iterate over all retained enablings, looking for enablings that
12211 	 * match the specified state.
12212 	 */
12213 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12214 		int i;
12215 
12216 		/*
12217 		 * dtvs_state can only be NULL for helper enablings -- and
12218 		 * helper enablings can't be retained.
12219 		 */
12220 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12221 
12222 		if (enab->dten_vstate->dtvs_state != state)
12223 			continue;
12224 
12225 		/*
12226 		 * Now iterate over each probe description; we're looking for
12227 		 * an exact match to the specified probe description.
12228 		 */
12229 		for (i = 0; i < enab->dten_ndesc; i++) {
12230 			dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12231 			dtrace_probedesc_t *pd = &ep->dted_probe;
12232 
12233 			if (strcmp(pd->dtpd_provider, match->dtpd_provider))
12234 				continue;
12235 
12236 			if (strcmp(pd->dtpd_mod, match->dtpd_mod))
12237 				continue;
12238 
12239 			if (strcmp(pd->dtpd_func, match->dtpd_func))
12240 				continue;
12241 
12242 			if (strcmp(pd->dtpd_name, match->dtpd_name))
12243 				continue;
12244 
12245 			/*
12246 			 * We have a winning probe!  Add it to our growing
12247 			 * enabling.
12248 			 */
12249 			found = 1;
12250 			dtrace_enabling_addlike(new, ep, create);
12251 		}
12252 	}
12253 
12254 	if (!found || (err = dtrace_enabling_retain(new)) != 0) {
12255 		dtrace_enabling_destroy(new);
12256 		return (err);
12257 	}
12258 
12259 	return (0);
12260 }
12261 
12262 static void
12263 dtrace_enabling_retract(dtrace_state_t *state)
12264 {
12265 	dtrace_enabling_t *enab, *next;
12266 
12267 	ASSERT(MUTEX_HELD(&dtrace_lock));
12268 
12269 	/*
12270 	 * Iterate over all retained enablings, destroy the enablings retained
12271 	 * for the specified state.
12272 	 */
12273 	for (enab = dtrace_retained; enab != NULL; enab = next) {
12274 		next = enab->dten_next;
12275 
12276 		/*
12277 		 * dtvs_state can only be NULL for helper enablings -- and
12278 		 * helper enablings can't be retained.
12279 		 */
12280 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12281 
12282 		if (enab->dten_vstate->dtvs_state == state) {
12283 			ASSERT(state->dts_nretained > 0);
12284 			dtrace_enabling_destroy(enab);
12285 		}
12286 	}
12287 
12288 	ASSERT(state->dts_nretained == 0);
12289 }
12290 
12291 static int
12292 dtrace_enabling_match(dtrace_enabling_t *enab, int *nmatched)
12293 {
12294 	int i = 0;
12295 	int total_matched = 0, matched = 0;
12296 
12297 	ASSERT(MUTEX_HELD(&cpu_lock));
12298 	ASSERT(MUTEX_HELD(&dtrace_lock));
12299 
12300 	for (i = 0; i < enab->dten_ndesc; i++) {
12301 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
12302 
12303 		enab->dten_current = ep;
12304 		enab->dten_error = 0;
12305 
12306 		/*
12307 		 * If a provider failed to enable a probe then get out and
12308 		 * let the consumer know we failed.
12309 		 */
12310 		if ((matched = dtrace_probe_enable(&ep->dted_probe, enab)) < 0)
12311 			return (EBUSY);
12312 
12313 		total_matched += matched;
12314 
12315 		if (enab->dten_error != 0) {
12316 			/*
12317 			 * If we get an error half-way through enabling the
12318 			 * probes, we kick out -- perhaps with some number of
12319 			 * them enabled.  Leaving enabled probes enabled may
12320 			 * be slightly confusing for user-level, but we expect
12321 			 * that no one will attempt to actually drive on in
12322 			 * the face of such errors.  If this is an anonymous
12323 			 * enabling (indicated with a NULL nmatched pointer),
12324 			 * we cmn_err() a message.  We aren't expecting to
12325 			 * get such an error -- such as it can exist at all,
12326 			 * it would be a result of corrupted DOF in the driver
12327 			 * properties.
12328 			 */
12329 			if (nmatched == NULL) {
12330 				cmn_err(CE_WARN, "dtrace_enabling_match() "
12331 				    "error on %p: %d", (void *)ep,
12332 				    enab->dten_error);
12333 			}
12334 
12335 			return (enab->dten_error);
12336 		}
12337 	}
12338 
12339 	enab->dten_probegen = dtrace_probegen;
12340 	if (nmatched != NULL)
12341 		*nmatched = total_matched;
12342 
12343 	return (0);
12344 }
12345 
12346 static void
12347 dtrace_enabling_matchall(void)
12348 {
12349 	dtrace_enabling_t *enab;
12350 
12351 	mutex_enter(&cpu_lock);
12352 	mutex_enter(&dtrace_lock);
12353 
12354 	/*
12355 	 * Iterate over all retained enablings to see if any probes match
12356 	 * against them.  We only perform this operation on enablings for which
12357 	 * we have sufficient permissions by virtue of being in the global zone
12358 	 * or in the same zone as the DTrace client.  Because we can be called
12359 	 * after dtrace_detach() has been called, we cannot assert that there
12360 	 * are retained enablings.  We can safely load from dtrace_retained,
12361 	 * however:  the taskq_destroy() at the end of dtrace_detach() will
12362 	 * block pending our completion.
12363 	 */
12364 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12365 		dtrace_cred_t *dcr = &enab->dten_vstate->dtvs_state->dts_cred;
12366 		cred_t *cr = dcr->dcr_cred;
12367 		zoneid_t zone = cr != NULL ? crgetzoneid(cr) : 0;
12368 
12369 		if ((dcr->dcr_visible & DTRACE_CRV_ALLZONE) || (cr != NULL &&
12370 		    (zone == GLOBAL_ZONEID || getzoneid() == zone)))
12371 			(void) dtrace_enabling_match(enab, NULL);
12372 	}
12373 
12374 	mutex_exit(&dtrace_lock);
12375 	mutex_exit(&cpu_lock);
12376 }
12377 
12378 /*
12379  * If an enabling is to be enabled without having matched probes (that is, if
12380  * dtrace_state_go() is to be called on the underlying dtrace_state_t), the
12381  * enabling must be _primed_ by creating an ECB for every ECB description.
12382  * This must be done to assure that we know the number of speculations, the
12383  * number of aggregations, the minimum buffer size needed, etc. before we
12384  * transition out of DTRACE_ACTIVITY_INACTIVE.  To do this without actually
12385  * enabling any probes, we create ECBs for every ECB decription, but with a
12386  * NULL probe -- which is exactly what this function does.
12387  */
12388 static void
12389 dtrace_enabling_prime(dtrace_state_t *state)
12390 {
12391 	dtrace_enabling_t *enab;
12392 	int i;
12393 
12394 	for (enab = dtrace_retained; enab != NULL; enab = enab->dten_next) {
12395 		ASSERT(enab->dten_vstate->dtvs_state != NULL);
12396 
12397 		if (enab->dten_vstate->dtvs_state != state)
12398 			continue;
12399 
12400 		/*
12401 		 * We don't want to prime an enabling more than once, lest
12402 		 * we allow a malicious user to induce resource exhaustion.
12403 		 * (The ECBs that result from priming an enabling aren't
12404 		 * leaked -- but they also aren't deallocated until the
12405 		 * consumer state is destroyed.)
12406 		 */
12407 		if (enab->dten_primed)
12408 			continue;
12409 
12410 		for (i = 0; i < enab->dten_ndesc; i++) {
12411 			enab->dten_current = enab->dten_desc[i];
12412 			(void) dtrace_probe_enable(NULL, enab);
12413 		}
12414 
12415 		enab->dten_primed = 1;
12416 	}
12417 }
12418 
12419 /*
12420  * Called to indicate that probes should be provided due to retained
12421  * enablings.  This is implemented in terms of dtrace_probe_provide(), but it
12422  * must take an initial lap through the enabling calling the dtps_provide()
12423  * entry point explicitly to allow for autocreated probes.
12424  */
12425 static void
12426 dtrace_enabling_provide(dtrace_provider_t *prv)
12427 {
12428 	int i, all = 0;
12429 	dtrace_probedesc_t desc;
12430 	dtrace_genid_t gen;
12431 
12432 	ASSERT(MUTEX_HELD(&dtrace_lock));
12433 	ASSERT(MUTEX_HELD(&dtrace_provider_lock));
12434 
12435 	if (prv == NULL) {
12436 		all = 1;
12437 		prv = dtrace_provider;
12438 	}
12439 
12440 	do {
12441 		dtrace_enabling_t *enab;
12442 		void *parg = prv->dtpv_arg;
12443 
12444 retry:
12445 		gen = dtrace_retained_gen;
12446 		for (enab = dtrace_retained; enab != NULL;
12447 		    enab = enab->dten_next) {
12448 			for (i = 0; i < enab->dten_ndesc; i++) {
12449 				desc = enab->dten_desc[i]->dted_probe;
12450 				mutex_exit(&dtrace_lock);
12451 				prv->dtpv_pops.dtps_provide(parg, &desc);
12452 				mutex_enter(&dtrace_lock);
12453 				/*
12454 				 * Process the retained enablings again if
12455 				 * they have changed while we weren't holding
12456 				 * dtrace_lock.
12457 				 */
12458 				if (gen != dtrace_retained_gen)
12459 					goto retry;
12460 			}
12461 		}
12462 	} while (all && (prv = prv->dtpv_next) != NULL);
12463 
12464 	mutex_exit(&dtrace_lock);
12465 	dtrace_probe_provide(NULL, all ? NULL : prv);
12466 	mutex_enter(&dtrace_lock);
12467 }
12468 
12469 /*
12470  * Called to reap ECBs that are attached to probes from defunct providers.
12471  */
12472 static void
12473 dtrace_enabling_reap(void)
12474 {
12475 	dtrace_provider_t *prov;
12476 	dtrace_probe_t *probe;
12477 	dtrace_ecb_t *ecb;
12478 	hrtime_t when;
12479 	int i;
12480 
12481 	mutex_enter(&cpu_lock);
12482 	mutex_enter(&dtrace_lock);
12483 
12484 	for (i = 0; i < dtrace_nprobes; i++) {
12485 		if ((probe = dtrace_probes[i]) == NULL)
12486 			continue;
12487 
12488 		if (probe->dtpr_ecb == NULL)
12489 			continue;
12490 
12491 		prov = probe->dtpr_provider;
12492 
12493 		if ((when = prov->dtpv_defunct) == 0)
12494 			continue;
12495 
12496 		/*
12497 		 * We have ECBs on a defunct provider:  we want to reap these
12498 		 * ECBs to allow the provider to unregister.  The destruction
12499 		 * of these ECBs must be done carefully:  if we destroy the ECB
12500 		 * and the consumer later wishes to consume an EPID that
12501 		 * corresponds to the destroyed ECB (and if the EPID metadata
12502 		 * has not been previously consumed), the consumer will abort
12503 		 * processing on the unknown EPID.  To reduce (but not, sadly,
12504 		 * eliminate) the possibility of this, we will only destroy an
12505 		 * ECB for a defunct provider if, for the state that
12506 		 * corresponds to the ECB:
12507 		 *
12508 		 *  (a)	There is no speculative tracing (which can effectively
12509 		 *	cache an EPID for an arbitrary amount of time).
12510 		 *
12511 		 *  (b)	The principal buffers have been switched twice since the
12512 		 *	provider became defunct.
12513 		 *
12514 		 *  (c)	The aggregation buffers are of zero size or have been
12515 		 *	switched twice since the provider became defunct.
12516 		 *
12517 		 * We use dts_speculates to determine (a) and call a function
12518 		 * (dtrace_buffer_consumed()) to determine (b) and (c).  Note
12519 		 * that as soon as we've been unable to destroy one of the ECBs
12520 		 * associated with the probe, we quit trying -- reaping is only
12521 		 * fruitful in as much as we can destroy all ECBs associated
12522 		 * with the defunct provider's probes.
12523 		 */
12524 		while ((ecb = probe->dtpr_ecb) != NULL) {
12525 			dtrace_state_t *state = ecb->dte_state;
12526 			dtrace_buffer_t *buf = state->dts_buffer;
12527 			dtrace_buffer_t *aggbuf = state->dts_aggbuffer;
12528 
12529 			if (state->dts_speculates)
12530 				break;
12531 
12532 			if (!dtrace_buffer_consumed(buf, when))
12533 				break;
12534 
12535 			if (!dtrace_buffer_consumed(aggbuf, when))
12536 				break;
12537 
12538 			dtrace_ecb_disable(ecb);
12539 			ASSERT(probe->dtpr_ecb != ecb);
12540 			dtrace_ecb_destroy(ecb);
12541 		}
12542 	}
12543 
12544 	mutex_exit(&dtrace_lock);
12545 	mutex_exit(&cpu_lock);
12546 }
12547 
12548 /*
12549  * DTrace DOF Functions
12550  */
12551 /*ARGSUSED*/
12552 static void
12553 dtrace_dof_error(dof_hdr_t *dof, const char *str)
12554 {
12555 	if (dtrace_err_verbose)
12556 		cmn_err(CE_WARN, "failed to process DOF: %s", str);
12557 
12558 #ifdef DTRACE_ERRDEBUG
12559 	dtrace_errdebug(str);
12560 #endif
12561 }
12562 
12563 /*
12564  * Create DOF out of a currently enabled state.  Right now, we only create
12565  * DOF containing the run-time options -- but this could be expanded to create
12566  * complete DOF representing the enabled state.
12567  */
12568 static dof_hdr_t *
12569 dtrace_dof_create(dtrace_state_t *state)
12570 {
12571 	dof_hdr_t *dof;
12572 	dof_sec_t *sec;
12573 	dof_optdesc_t *opt;
12574 	int i, len = sizeof (dof_hdr_t) +
12575 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)) +
12576 	    sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12577 
12578 	ASSERT(MUTEX_HELD(&dtrace_lock));
12579 
12580 	dof = kmem_zalloc(len, KM_SLEEP);
12581 	dof->dofh_ident[DOF_ID_MAG0] = DOF_MAG_MAG0;
12582 	dof->dofh_ident[DOF_ID_MAG1] = DOF_MAG_MAG1;
12583 	dof->dofh_ident[DOF_ID_MAG2] = DOF_MAG_MAG2;
12584 	dof->dofh_ident[DOF_ID_MAG3] = DOF_MAG_MAG3;
12585 
12586 	dof->dofh_ident[DOF_ID_MODEL] = DOF_MODEL_NATIVE;
12587 	dof->dofh_ident[DOF_ID_ENCODING] = DOF_ENCODE_NATIVE;
12588 	dof->dofh_ident[DOF_ID_VERSION] = DOF_VERSION;
12589 	dof->dofh_ident[DOF_ID_DIFVERS] = DIF_VERSION;
12590 	dof->dofh_ident[DOF_ID_DIFIREG] = DIF_DIR_NREGS;
12591 	dof->dofh_ident[DOF_ID_DIFTREG] = DIF_DTR_NREGS;
12592 
12593 	dof->dofh_flags = 0;
12594 	dof->dofh_hdrsize = sizeof (dof_hdr_t);
12595 	dof->dofh_secsize = sizeof (dof_sec_t);
12596 	dof->dofh_secnum = 1;	/* only DOF_SECT_OPTDESC */
12597 	dof->dofh_secoff = sizeof (dof_hdr_t);
12598 	dof->dofh_loadsz = len;
12599 	dof->dofh_filesz = len;
12600 	dof->dofh_pad = 0;
12601 
12602 	/*
12603 	 * Fill in the option section header...
12604 	 */
12605 	sec = (dof_sec_t *)((uintptr_t)dof + sizeof (dof_hdr_t));
12606 	sec->dofs_type = DOF_SECT_OPTDESC;
12607 	sec->dofs_align = sizeof (uint64_t);
12608 	sec->dofs_flags = DOF_SECF_LOAD;
12609 	sec->dofs_entsize = sizeof (dof_optdesc_t);
12610 
12611 	opt = (dof_optdesc_t *)((uintptr_t)sec +
12612 	    roundup(sizeof (dof_sec_t), sizeof (uint64_t)));
12613 
12614 	sec->dofs_offset = (uintptr_t)opt - (uintptr_t)dof;
12615 	sec->dofs_size = sizeof (dof_optdesc_t) * DTRACEOPT_MAX;
12616 
12617 	for (i = 0; i < DTRACEOPT_MAX; i++) {
12618 		opt[i].dofo_option = i;
12619 		opt[i].dofo_strtab = DOF_SECIDX_NONE;
12620 		opt[i].dofo_value = state->dts_options[i];
12621 	}
12622 
12623 	return (dof);
12624 }
12625 
12626 static dof_hdr_t *
12627 dtrace_dof_copyin(uintptr_t uarg, int *errp)
12628 {
12629 	dof_hdr_t hdr, *dof;
12630 
12631 	ASSERT(!MUTEX_HELD(&dtrace_lock));
12632 
12633 	/*
12634 	 * First, we're going to copyin() the sizeof (dof_hdr_t).
12635 	 */
12636 	if (copyin((void *)uarg, &hdr, sizeof (hdr)) != 0) {
12637 		dtrace_dof_error(NULL, "failed to copyin DOF header");
12638 		*errp = EFAULT;
12639 		return (NULL);
12640 	}
12641 
12642 	/*
12643 	 * Now we'll allocate the entire DOF and copy it in -- provided
12644 	 * that the length isn't outrageous.
12645 	 */
12646 	if (hdr.dofh_loadsz >= dtrace_dof_maxsize) {
12647 		dtrace_dof_error(&hdr, "load size exceeds maximum");
12648 		*errp = E2BIG;
12649 		return (NULL);
12650 	}
12651 
12652 	if (hdr.dofh_loadsz < sizeof (hdr)) {
12653 		dtrace_dof_error(&hdr, "invalid load size");
12654 		*errp = EINVAL;
12655 		return (NULL);
12656 	}
12657 
12658 	dof = kmem_alloc(hdr.dofh_loadsz, KM_SLEEP);
12659 
12660 	if (copyin((void *)uarg, dof, hdr.dofh_loadsz) != 0 ||
12661 	    dof->dofh_loadsz != hdr.dofh_loadsz) {
12662 		kmem_free(dof, hdr.dofh_loadsz);
12663 		*errp = EFAULT;
12664 		return (NULL);
12665 	}
12666 
12667 	return (dof);
12668 }
12669 
12670 static dof_hdr_t *
12671 dtrace_dof_property(const char *name)
12672 {
12673 	uchar_t *buf;
12674 	uint64_t loadsz;
12675 	unsigned int len, i;
12676 	dof_hdr_t *dof;
12677 
12678 	/*
12679 	 * Unfortunately, array of values in .conf files are always (and
12680 	 * only) interpreted to be integer arrays.  We must read our DOF
12681 	 * as an integer array, and then squeeze it into a byte array.
12682 	 */
12683 	if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY, dtrace_devi, 0,
12684 	    (char *)name, (int **)&buf, &len) != DDI_PROP_SUCCESS)
12685 		return (NULL);
12686 
12687 	for (i = 0; i < len; i++)
12688 		buf[i] = (uchar_t)(((int *)buf)[i]);
12689 
12690 	if (len < sizeof (dof_hdr_t)) {
12691 		ddi_prop_free(buf);
12692 		dtrace_dof_error(NULL, "truncated header");
12693 		return (NULL);
12694 	}
12695 
12696 	if (len < (loadsz = ((dof_hdr_t *)buf)->dofh_loadsz)) {
12697 		ddi_prop_free(buf);
12698 		dtrace_dof_error(NULL, "truncated DOF");
12699 		return (NULL);
12700 	}
12701 
12702 	if (loadsz >= dtrace_dof_maxsize) {
12703 		ddi_prop_free(buf);
12704 		dtrace_dof_error(NULL, "oversized DOF");
12705 		return (NULL);
12706 	}
12707 
12708 	dof = kmem_alloc(loadsz, KM_SLEEP);
12709 	bcopy(buf, dof, loadsz);
12710 	ddi_prop_free(buf);
12711 
12712 	return (dof);
12713 }
12714 
12715 static void
12716 dtrace_dof_destroy(dof_hdr_t *dof)
12717 {
12718 	kmem_free(dof, dof->dofh_loadsz);
12719 }
12720 
12721 /*
12722  * Return the dof_sec_t pointer corresponding to a given section index.  If the
12723  * index is not valid, dtrace_dof_error() is called and NULL is returned.  If
12724  * a type other than DOF_SECT_NONE is specified, the header is checked against
12725  * this type and NULL is returned if the types do not match.
12726  */
12727 static dof_sec_t *
12728 dtrace_dof_sect(dof_hdr_t *dof, uint32_t type, dof_secidx_t i)
12729 {
12730 	dof_sec_t *sec = (dof_sec_t *)(uintptr_t)
12731 	    ((uintptr_t)dof + dof->dofh_secoff + i * dof->dofh_secsize);
12732 
12733 	if (i >= dof->dofh_secnum) {
12734 		dtrace_dof_error(dof, "referenced section index is invalid");
12735 		return (NULL);
12736 	}
12737 
12738 	if (!(sec->dofs_flags & DOF_SECF_LOAD)) {
12739 		dtrace_dof_error(dof, "referenced section is not loadable");
12740 		return (NULL);
12741 	}
12742 
12743 	if (type != DOF_SECT_NONE && type != sec->dofs_type) {
12744 		dtrace_dof_error(dof, "referenced section is the wrong type");
12745 		return (NULL);
12746 	}
12747 
12748 	return (sec);
12749 }
12750 
12751 static dtrace_probedesc_t *
12752 dtrace_dof_probedesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_probedesc_t *desc)
12753 {
12754 	dof_probedesc_t *probe;
12755 	dof_sec_t *strtab;
12756 	uintptr_t daddr = (uintptr_t)dof;
12757 	uintptr_t str;
12758 	size_t size;
12759 
12760 	if (sec->dofs_type != DOF_SECT_PROBEDESC) {
12761 		dtrace_dof_error(dof, "invalid probe section");
12762 		return (NULL);
12763 	}
12764 
12765 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12766 		dtrace_dof_error(dof, "bad alignment in probe description");
12767 		return (NULL);
12768 	}
12769 
12770 	if (sec->dofs_offset + sizeof (dof_probedesc_t) > dof->dofh_loadsz) {
12771 		dtrace_dof_error(dof, "truncated probe description");
12772 		return (NULL);
12773 	}
12774 
12775 	probe = (dof_probedesc_t *)(uintptr_t)(daddr + sec->dofs_offset);
12776 	strtab = dtrace_dof_sect(dof, DOF_SECT_STRTAB, probe->dofp_strtab);
12777 
12778 	if (strtab == NULL)
12779 		return (NULL);
12780 
12781 	str = daddr + strtab->dofs_offset;
12782 	size = strtab->dofs_size;
12783 
12784 	if (probe->dofp_provider >= strtab->dofs_size) {
12785 		dtrace_dof_error(dof, "corrupt probe provider");
12786 		return (NULL);
12787 	}
12788 
12789 	(void) strncpy(desc->dtpd_provider,
12790 	    (char *)(str + probe->dofp_provider),
12791 	    MIN(DTRACE_PROVNAMELEN - 1, size - probe->dofp_provider));
12792 
12793 	if (probe->dofp_mod >= strtab->dofs_size) {
12794 		dtrace_dof_error(dof, "corrupt probe module");
12795 		return (NULL);
12796 	}
12797 
12798 	(void) strncpy(desc->dtpd_mod, (char *)(str + probe->dofp_mod),
12799 	    MIN(DTRACE_MODNAMELEN - 1, size - probe->dofp_mod));
12800 
12801 	if (probe->dofp_func >= strtab->dofs_size) {
12802 		dtrace_dof_error(dof, "corrupt probe function");
12803 		return (NULL);
12804 	}
12805 
12806 	(void) strncpy(desc->dtpd_func, (char *)(str + probe->dofp_func),
12807 	    MIN(DTRACE_FUNCNAMELEN - 1, size - probe->dofp_func));
12808 
12809 	if (probe->dofp_name >= strtab->dofs_size) {
12810 		dtrace_dof_error(dof, "corrupt probe name");
12811 		return (NULL);
12812 	}
12813 
12814 	(void) strncpy(desc->dtpd_name, (char *)(str + probe->dofp_name),
12815 	    MIN(DTRACE_NAMELEN - 1, size - probe->dofp_name));
12816 
12817 	return (desc);
12818 }
12819 
12820 static dtrace_difo_t *
12821 dtrace_dof_difo(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12822     cred_t *cr)
12823 {
12824 	dtrace_difo_t *dp;
12825 	size_t ttl = 0;
12826 	dof_difohdr_t *dofd;
12827 	uintptr_t daddr = (uintptr_t)dof;
12828 	size_t max = dtrace_difo_maxsize;
12829 	int i, l, n;
12830 
12831 	static const struct {
12832 		int section;
12833 		int bufoffs;
12834 		int lenoffs;
12835 		int entsize;
12836 		int align;
12837 		const char *msg;
12838 	} difo[] = {
12839 		{ DOF_SECT_DIF, offsetof(dtrace_difo_t, dtdo_buf),
12840 		offsetof(dtrace_difo_t, dtdo_len), sizeof (dif_instr_t),
12841 		sizeof (dif_instr_t), "multiple DIF sections" },
12842 
12843 		{ DOF_SECT_INTTAB, offsetof(dtrace_difo_t, dtdo_inttab),
12844 		offsetof(dtrace_difo_t, dtdo_intlen), sizeof (uint64_t),
12845 		sizeof (uint64_t), "multiple integer tables" },
12846 
12847 		{ DOF_SECT_STRTAB, offsetof(dtrace_difo_t, dtdo_strtab),
12848 		offsetof(dtrace_difo_t, dtdo_strlen), 0,
12849 		sizeof (char), "multiple string tables" },
12850 
12851 		{ DOF_SECT_VARTAB, offsetof(dtrace_difo_t, dtdo_vartab),
12852 		offsetof(dtrace_difo_t, dtdo_varlen), sizeof (dtrace_difv_t),
12853 		sizeof (uint_t), "multiple variable tables" },
12854 
12855 		{ DOF_SECT_NONE, 0, 0, 0, 0, NULL }
12856 	};
12857 
12858 	if (sec->dofs_type != DOF_SECT_DIFOHDR) {
12859 		dtrace_dof_error(dof, "invalid DIFO header section");
12860 		return (NULL);
12861 	}
12862 
12863 	if (sec->dofs_align != sizeof (dof_secidx_t)) {
12864 		dtrace_dof_error(dof, "bad alignment in DIFO header");
12865 		return (NULL);
12866 	}
12867 
12868 	if (sec->dofs_size < sizeof (dof_difohdr_t) ||
12869 	    sec->dofs_size % sizeof (dof_secidx_t)) {
12870 		dtrace_dof_error(dof, "bad size in DIFO header");
12871 		return (NULL);
12872 	}
12873 
12874 	dofd = (dof_difohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
12875 	n = (sec->dofs_size - sizeof (*dofd)) / sizeof (dof_secidx_t) + 1;
12876 
12877 	dp = kmem_zalloc(sizeof (dtrace_difo_t), KM_SLEEP);
12878 	dp->dtdo_rtype = dofd->dofd_rtype;
12879 
12880 	for (l = 0; l < n; l++) {
12881 		dof_sec_t *subsec;
12882 		void **bufp;
12883 		uint32_t *lenp;
12884 
12885 		if ((subsec = dtrace_dof_sect(dof, DOF_SECT_NONE,
12886 		    dofd->dofd_links[l])) == NULL)
12887 			goto err; /* invalid section link */
12888 
12889 		if (ttl + subsec->dofs_size > max) {
12890 			dtrace_dof_error(dof, "exceeds maximum size");
12891 			goto err;
12892 		}
12893 
12894 		ttl += subsec->dofs_size;
12895 
12896 		for (i = 0; difo[i].section != DOF_SECT_NONE; i++) {
12897 			if (subsec->dofs_type != difo[i].section)
12898 				continue;
12899 
12900 			if (!(subsec->dofs_flags & DOF_SECF_LOAD)) {
12901 				dtrace_dof_error(dof, "section not loaded");
12902 				goto err;
12903 			}
12904 
12905 			if (subsec->dofs_align != difo[i].align) {
12906 				dtrace_dof_error(dof, "bad alignment");
12907 				goto err;
12908 			}
12909 
12910 			bufp = (void **)((uintptr_t)dp + difo[i].bufoffs);
12911 			lenp = (uint32_t *)((uintptr_t)dp + difo[i].lenoffs);
12912 
12913 			if (*bufp != NULL) {
12914 				dtrace_dof_error(dof, difo[i].msg);
12915 				goto err;
12916 			}
12917 
12918 			if (difo[i].entsize != subsec->dofs_entsize) {
12919 				dtrace_dof_error(dof, "entry size mismatch");
12920 				goto err;
12921 			}
12922 
12923 			if (subsec->dofs_entsize != 0 &&
12924 			    (subsec->dofs_size % subsec->dofs_entsize) != 0) {
12925 				dtrace_dof_error(dof, "corrupt entry size");
12926 				goto err;
12927 			}
12928 
12929 			*lenp = subsec->dofs_size;
12930 			*bufp = kmem_alloc(subsec->dofs_size, KM_SLEEP);
12931 			bcopy((char *)(uintptr_t)(daddr + subsec->dofs_offset),
12932 			    *bufp, subsec->dofs_size);
12933 
12934 			if (subsec->dofs_entsize != 0)
12935 				*lenp /= subsec->dofs_entsize;
12936 
12937 			break;
12938 		}
12939 
12940 		/*
12941 		 * If we encounter a loadable DIFO sub-section that is not
12942 		 * known to us, assume this is a broken program and fail.
12943 		 */
12944 		if (difo[i].section == DOF_SECT_NONE &&
12945 		    (subsec->dofs_flags & DOF_SECF_LOAD)) {
12946 			dtrace_dof_error(dof, "unrecognized DIFO subsection");
12947 			goto err;
12948 		}
12949 	}
12950 
12951 	if (dp->dtdo_buf == NULL) {
12952 		/*
12953 		 * We can't have a DIF object without DIF text.
12954 		 */
12955 		dtrace_dof_error(dof, "missing DIF text");
12956 		goto err;
12957 	}
12958 
12959 	/*
12960 	 * Before we validate the DIF object, run through the variable table
12961 	 * looking for the strings -- if any of their size are under, we'll set
12962 	 * their size to be the system-wide default string size.  Note that
12963 	 * this should _not_ happen if the "strsize" option has been set --
12964 	 * in this case, the compiler should have set the size to reflect the
12965 	 * setting of the option.
12966 	 */
12967 	for (i = 0; i < dp->dtdo_varlen; i++) {
12968 		dtrace_difv_t *v = &dp->dtdo_vartab[i];
12969 		dtrace_diftype_t *t = &v->dtdv_type;
12970 
12971 		if (v->dtdv_id < DIF_VAR_OTHER_UBASE)
12972 			continue;
12973 
12974 		if (t->dtdt_kind == DIF_TYPE_STRING && t->dtdt_size == 0)
12975 			t->dtdt_size = dtrace_strsize_default;
12976 	}
12977 
12978 	if (dtrace_difo_validate(dp, vstate, DIF_DIR_NREGS, cr) != 0)
12979 		goto err;
12980 
12981 	dtrace_difo_init(dp, vstate);
12982 	return (dp);
12983 
12984 err:
12985 	kmem_free(dp->dtdo_buf, dp->dtdo_len * sizeof (dif_instr_t));
12986 	kmem_free(dp->dtdo_inttab, dp->dtdo_intlen * sizeof (uint64_t));
12987 	kmem_free(dp->dtdo_strtab, dp->dtdo_strlen);
12988 	kmem_free(dp->dtdo_vartab, dp->dtdo_varlen * sizeof (dtrace_difv_t));
12989 
12990 	kmem_free(dp, sizeof (dtrace_difo_t));
12991 	return (NULL);
12992 }
12993 
12994 static dtrace_predicate_t *
12995 dtrace_dof_predicate(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
12996     cred_t *cr)
12997 {
12998 	dtrace_difo_t *dp;
12999 
13000 	if ((dp = dtrace_dof_difo(dof, sec, vstate, cr)) == NULL)
13001 		return (NULL);
13002 
13003 	return (dtrace_predicate_create(dp));
13004 }
13005 
13006 static dtrace_actdesc_t *
13007 dtrace_dof_actdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13008     cred_t *cr)
13009 {
13010 	dtrace_actdesc_t *act, *first = NULL, *last = NULL, *next;
13011 	dof_actdesc_t *desc;
13012 	dof_sec_t *difosec;
13013 	size_t offs;
13014 	uintptr_t daddr = (uintptr_t)dof;
13015 	uint64_t arg;
13016 	dtrace_actkind_t kind;
13017 
13018 	if (sec->dofs_type != DOF_SECT_ACTDESC) {
13019 		dtrace_dof_error(dof, "invalid action section");
13020 		return (NULL);
13021 	}
13022 
13023 	if (sec->dofs_offset + sizeof (dof_actdesc_t) > dof->dofh_loadsz) {
13024 		dtrace_dof_error(dof, "truncated action description");
13025 		return (NULL);
13026 	}
13027 
13028 	if (sec->dofs_align != sizeof (uint64_t)) {
13029 		dtrace_dof_error(dof, "bad alignment in action description");
13030 		return (NULL);
13031 	}
13032 
13033 	if (sec->dofs_size < sec->dofs_entsize) {
13034 		dtrace_dof_error(dof, "section entry size exceeds total size");
13035 		return (NULL);
13036 	}
13037 
13038 	if (sec->dofs_entsize != sizeof (dof_actdesc_t)) {
13039 		dtrace_dof_error(dof, "bad entry size in action description");
13040 		return (NULL);
13041 	}
13042 
13043 	if (sec->dofs_size / sec->dofs_entsize > dtrace_actions_max) {
13044 		dtrace_dof_error(dof, "actions exceed dtrace_actions_max");
13045 		return (NULL);
13046 	}
13047 
13048 	for (offs = 0; offs < sec->dofs_size; offs += sec->dofs_entsize) {
13049 		desc = (dof_actdesc_t *)(daddr +
13050 		    (uintptr_t)sec->dofs_offset + offs);
13051 		kind = (dtrace_actkind_t)desc->dofa_kind;
13052 
13053 		if ((DTRACEACT_ISPRINTFLIKE(kind) &&
13054 		    (kind != DTRACEACT_PRINTA ||
13055 		    desc->dofa_strtab != DOF_SECIDX_NONE)) ||
13056 		    (kind == DTRACEACT_DIFEXPR &&
13057 		    desc->dofa_strtab != DOF_SECIDX_NONE)) {
13058 			dof_sec_t *strtab;
13059 			char *str, *fmt;
13060 			uint64_t i;
13061 
13062 			/*
13063 			 * The argument to these actions is an index into the
13064 			 * DOF string table.  For printf()-like actions, this
13065 			 * is the format string.  For print(), this is the
13066 			 * CTF type of the expression result.
13067 			 */
13068 			if ((strtab = dtrace_dof_sect(dof,
13069 			    DOF_SECT_STRTAB, desc->dofa_strtab)) == NULL)
13070 				goto err;
13071 
13072 			str = (char *)((uintptr_t)dof +
13073 			    (uintptr_t)strtab->dofs_offset);
13074 
13075 			for (i = desc->dofa_arg; i < strtab->dofs_size; i++) {
13076 				if (str[i] == '\0')
13077 					break;
13078 			}
13079 
13080 			if (i >= strtab->dofs_size) {
13081 				dtrace_dof_error(dof, "bogus format string");
13082 				goto err;
13083 			}
13084 
13085 			if (i == desc->dofa_arg) {
13086 				dtrace_dof_error(dof, "empty format string");
13087 				goto err;
13088 			}
13089 
13090 			i -= desc->dofa_arg;
13091 			fmt = kmem_alloc(i + 1, KM_SLEEP);
13092 			bcopy(&str[desc->dofa_arg], fmt, i + 1);
13093 			arg = (uint64_t)(uintptr_t)fmt;
13094 		} else {
13095 			if (kind == DTRACEACT_PRINTA) {
13096 				ASSERT(desc->dofa_strtab == DOF_SECIDX_NONE);
13097 				arg = 0;
13098 			} else {
13099 				arg = desc->dofa_arg;
13100 			}
13101 		}
13102 
13103 		act = dtrace_actdesc_create(kind, desc->dofa_ntuple,
13104 		    desc->dofa_uarg, arg);
13105 
13106 		if (last != NULL) {
13107 			last->dtad_next = act;
13108 		} else {
13109 			first = act;
13110 		}
13111 
13112 		last = act;
13113 
13114 		if (desc->dofa_difo == DOF_SECIDX_NONE)
13115 			continue;
13116 
13117 		if ((difosec = dtrace_dof_sect(dof,
13118 		    DOF_SECT_DIFOHDR, desc->dofa_difo)) == NULL)
13119 			goto err;
13120 
13121 		act->dtad_difo = dtrace_dof_difo(dof, difosec, vstate, cr);
13122 
13123 		if (act->dtad_difo == NULL)
13124 			goto err;
13125 	}
13126 
13127 	ASSERT(first != NULL);
13128 	return (first);
13129 
13130 err:
13131 	for (act = first; act != NULL; act = next) {
13132 		next = act->dtad_next;
13133 		dtrace_actdesc_release(act, vstate);
13134 	}
13135 
13136 	return (NULL);
13137 }
13138 
13139 static dtrace_ecbdesc_t *
13140 dtrace_dof_ecbdesc(dof_hdr_t *dof, dof_sec_t *sec, dtrace_vstate_t *vstate,
13141     cred_t *cr)
13142 {
13143 	dtrace_ecbdesc_t *ep;
13144 	dof_ecbdesc_t *ecb;
13145 	dtrace_probedesc_t *desc;
13146 	dtrace_predicate_t *pred = NULL;
13147 
13148 	if (sec->dofs_size < sizeof (dof_ecbdesc_t)) {
13149 		dtrace_dof_error(dof, "truncated ECB description");
13150 		return (NULL);
13151 	}
13152 
13153 	if (sec->dofs_align != sizeof (uint64_t)) {
13154 		dtrace_dof_error(dof, "bad alignment in ECB description");
13155 		return (NULL);
13156 	}
13157 
13158 	ecb = (dof_ecbdesc_t *)((uintptr_t)dof + (uintptr_t)sec->dofs_offset);
13159 	sec = dtrace_dof_sect(dof, DOF_SECT_PROBEDESC, ecb->dofe_probes);
13160 
13161 	if (sec == NULL)
13162 		return (NULL);
13163 
13164 	ep = kmem_zalloc(sizeof (dtrace_ecbdesc_t), KM_SLEEP);
13165 	ep->dted_uarg = ecb->dofe_uarg;
13166 	desc = &ep->dted_probe;
13167 
13168 	if (dtrace_dof_probedesc(dof, sec, desc) == NULL)
13169 		goto err;
13170 
13171 	if (ecb->dofe_pred != DOF_SECIDX_NONE) {
13172 		if ((sec = dtrace_dof_sect(dof,
13173 		    DOF_SECT_DIFOHDR, ecb->dofe_pred)) == NULL)
13174 			goto err;
13175 
13176 		if ((pred = dtrace_dof_predicate(dof, sec, vstate, cr)) == NULL)
13177 			goto err;
13178 
13179 		ep->dted_pred.dtpdd_predicate = pred;
13180 	}
13181 
13182 	if (ecb->dofe_actions != DOF_SECIDX_NONE) {
13183 		if ((sec = dtrace_dof_sect(dof,
13184 		    DOF_SECT_ACTDESC, ecb->dofe_actions)) == NULL)
13185 			goto err;
13186 
13187 		ep->dted_action = dtrace_dof_actdesc(dof, sec, vstate, cr);
13188 
13189 		if (ep->dted_action == NULL)
13190 			goto err;
13191 	}
13192 
13193 	return (ep);
13194 
13195 err:
13196 	if (pred != NULL)
13197 		dtrace_predicate_release(pred, vstate);
13198 	kmem_free(ep, sizeof (dtrace_ecbdesc_t));
13199 	return (NULL);
13200 }
13201 
13202 /*
13203  * Apply the relocations from the specified 'sec' (a DOF_SECT_URELHDR) to the
13204  * specified DOF.  At present, this amounts to simply adding 'ubase' to the
13205  * site of any user SETX relocations to account for load object base address.
13206  * In the future, if we need other relocations, this function can be extended.
13207  */
13208 static int
13209 dtrace_dof_relocate(dof_hdr_t *dof, dof_sec_t *sec, uint64_t ubase)
13210 {
13211 	uintptr_t daddr = (uintptr_t)dof;
13212 	uintptr_t ts_end;
13213 	dof_relohdr_t *dofr =
13214 	    (dof_relohdr_t *)(uintptr_t)(daddr + sec->dofs_offset);
13215 	dof_sec_t *ss, *rs, *ts;
13216 	dof_relodesc_t *r;
13217 	uint_t i, n;
13218 
13219 	if (sec->dofs_size < sizeof (dof_relohdr_t) ||
13220 	    sec->dofs_align != sizeof (dof_secidx_t)) {
13221 		dtrace_dof_error(dof, "invalid relocation header");
13222 		return (-1);
13223 	}
13224 
13225 	ss = dtrace_dof_sect(dof, DOF_SECT_STRTAB, dofr->dofr_strtab);
13226 	rs = dtrace_dof_sect(dof, DOF_SECT_RELTAB, dofr->dofr_relsec);
13227 	ts = dtrace_dof_sect(dof, DOF_SECT_NONE, dofr->dofr_tgtsec);
13228 	ts_end = (uintptr_t)ts + sizeof (dof_sec_t);
13229 
13230 	if (ss == NULL || rs == NULL || ts == NULL)
13231 		return (-1); /* dtrace_dof_error() has been called already */
13232 
13233 	if (rs->dofs_entsize < sizeof (dof_relodesc_t) ||
13234 	    rs->dofs_align != sizeof (uint64_t)) {
13235 		dtrace_dof_error(dof, "invalid relocation section");
13236 		return (-1);
13237 	}
13238 
13239 	r = (dof_relodesc_t *)(uintptr_t)(daddr + rs->dofs_offset);
13240 	n = rs->dofs_size / rs->dofs_entsize;
13241 
13242 	for (i = 0; i < n; i++) {
13243 		uintptr_t taddr = daddr + ts->dofs_offset + r->dofr_offset;
13244 
13245 		switch (r->dofr_type) {
13246 		case DOF_RELO_NONE:
13247 			break;
13248 		case DOF_RELO_SETX:
13249 			if (r->dofr_offset >= ts->dofs_size || r->dofr_offset +
13250 			    sizeof (uint64_t) > ts->dofs_size) {
13251 				dtrace_dof_error(dof, "bad relocation offset");
13252 				return (-1);
13253 			}
13254 
13255 			if (taddr >= (uintptr_t)ts && taddr < ts_end) {
13256 				dtrace_dof_error(dof, "bad relocation offset");
13257 				return (-1);
13258 			}
13259 
13260 			if (!IS_P2ALIGNED(taddr, sizeof (uint64_t))) {
13261 				dtrace_dof_error(dof, "misaligned setx relo");
13262 				return (-1);
13263 			}
13264 
13265 			*(uint64_t *)taddr += ubase;
13266 			break;
13267 		default:
13268 			dtrace_dof_error(dof, "invalid relocation type");
13269 			return (-1);
13270 		}
13271 
13272 		r = (dof_relodesc_t *)((uintptr_t)r + rs->dofs_entsize);
13273 	}
13274 
13275 	return (0);
13276 }
13277 
13278 /*
13279  * The dof_hdr_t passed to dtrace_dof_slurp() should be a partially validated
13280  * header:  it should be at the front of a memory region that is at least
13281  * sizeof (dof_hdr_t) in size -- and then at least dof_hdr.dofh_loadsz in
13282  * size.  It need not be validated in any other way.
13283  */
13284 static int
13285 dtrace_dof_slurp(dof_hdr_t *dof, dtrace_vstate_t *vstate, cred_t *cr,
13286     dtrace_enabling_t **enabp, uint64_t ubase, int noprobes)
13287 {
13288 	uint64_t len = dof->dofh_loadsz, seclen;
13289 	uintptr_t daddr = (uintptr_t)dof;
13290 	dtrace_ecbdesc_t *ep;
13291 	dtrace_enabling_t *enab;
13292 	uint_t i;
13293 
13294 	ASSERT(MUTEX_HELD(&dtrace_lock));
13295 	ASSERT(dof->dofh_loadsz >= sizeof (dof_hdr_t));
13296 
13297 	/*
13298 	 * Check the DOF header identification bytes.  In addition to checking
13299 	 * valid settings, we also verify that unused bits/bytes are zeroed so
13300 	 * we can use them later without fear of regressing existing binaries.
13301 	 */
13302 	if (bcmp(&dof->dofh_ident[DOF_ID_MAG0],
13303 	    DOF_MAG_STRING, DOF_MAG_STRLEN) != 0) {
13304 		dtrace_dof_error(dof, "DOF magic string mismatch");
13305 		return (-1);
13306 	}
13307 
13308 	if (dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_ILP32 &&
13309 	    dof->dofh_ident[DOF_ID_MODEL] != DOF_MODEL_LP64) {
13310 		dtrace_dof_error(dof, "DOF has invalid data model");
13311 		return (-1);
13312 	}
13313 
13314 	if (dof->dofh_ident[DOF_ID_ENCODING] != DOF_ENCODE_NATIVE) {
13315 		dtrace_dof_error(dof, "DOF encoding mismatch");
13316 		return (-1);
13317 	}
13318 
13319 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
13320 	    dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_2) {
13321 		dtrace_dof_error(dof, "DOF version mismatch");
13322 		return (-1);
13323 	}
13324 
13325 	if (dof->dofh_ident[DOF_ID_DIFVERS] != DIF_VERSION_2) {
13326 		dtrace_dof_error(dof, "DOF uses unsupported instruction set");
13327 		return (-1);
13328 	}
13329 
13330 	if (dof->dofh_ident[DOF_ID_DIFIREG] > DIF_DIR_NREGS) {
13331 		dtrace_dof_error(dof, "DOF uses too many integer registers");
13332 		return (-1);
13333 	}
13334 
13335 	if (dof->dofh_ident[DOF_ID_DIFTREG] > DIF_DTR_NREGS) {
13336 		dtrace_dof_error(dof, "DOF uses too many tuple registers");
13337 		return (-1);
13338 	}
13339 
13340 	for (i = DOF_ID_PAD; i < DOF_ID_SIZE; i++) {
13341 		if (dof->dofh_ident[i] != 0) {
13342 			dtrace_dof_error(dof, "DOF has invalid ident byte set");
13343 			return (-1);
13344 		}
13345 	}
13346 
13347 	if (dof->dofh_flags & ~DOF_FL_VALID) {
13348 		dtrace_dof_error(dof, "DOF has invalid flag bits set");
13349 		return (-1);
13350 	}
13351 
13352 	if (dof->dofh_secsize == 0) {
13353 		dtrace_dof_error(dof, "zero section header size");
13354 		return (-1);
13355 	}
13356 
13357 	/*
13358 	 * Check that the section headers don't exceed the amount of DOF
13359 	 * data.  Note that we cast the section size and number of sections
13360 	 * to uint64_t's to prevent possible overflow in the multiplication.
13361 	 */
13362 	seclen = (uint64_t)dof->dofh_secnum * (uint64_t)dof->dofh_secsize;
13363 
13364 	if (dof->dofh_secoff > len || seclen > len ||
13365 	    dof->dofh_secoff + seclen > len) {
13366 		dtrace_dof_error(dof, "truncated section headers");
13367 		return (-1);
13368 	}
13369 
13370 	if (!IS_P2ALIGNED(dof->dofh_secoff, sizeof (uint64_t))) {
13371 		dtrace_dof_error(dof, "misaligned section headers");
13372 		return (-1);
13373 	}
13374 
13375 	if (!IS_P2ALIGNED(dof->dofh_secsize, sizeof (uint64_t))) {
13376 		dtrace_dof_error(dof, "misaligned section size");
13377 		return (-1);
13378 	}
13379 
13380 	/*
13381 	 * Take an initial pass through the section headers to be sure that
13382 	 * the headers don't have stray offsets.  If the 'noprobes' flag is
13383 	 * set, do not permit sections relating to providers, probes, or args.
13384 	 */
13385 	for (i = 0; i < dof->dofh_secnum; i++) {
13386 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13387 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13388 
13389 		if (noprobes) {
13390 			switch (sec->dofs_type) {
13391 			case DOF_SECT_PROVIDER:
13392 			case DOF_SECT_PROBES:
13393 			case DOF_SECT_PRARGS:
13394 			case DOF_SECT_PROFFS:
13395 				dtrace_dof_error(dof, "illegal sections "
13396 				    "for enabling");
13397 				return (-1);
13398 			}
13399 		}
13400 
13401 		if (DOF_SEC_ISLOADABLE(sec->dofs_type) &&
13402 		    !(sec->dofs_flags & DOF_SECF_LOAD)) {
13403 			dtrace_dof_error(dof, "loadable section with load "
13404 			    "flag unset");
13405 			return (-1);
13406 		}
13407 
13408 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
13409 			continue; /* just ignore non-loadable sections */
13410 
13411 		if (!ISP2(sec->dofs_align)) {
13412 			dtrace_dof_error(dof, "bad section alignment");
13413 			return (-1);
13414 		}
13415 
13416 		if (sec->dofs_offset & (sec->dofs_align - 1)) {
13417 			dtrace_dof_error(dof, "misaligned section");
13418 			return (-1);
13419 		}
13420 
13421 		if (sec->dofs_offset > len || sec->dofs_size > len ||
13422 		    sec->dofs_offset + sec->dofs_size > len) {
13423 			dtrace_dof_error(dof, "corrupt section header");
13424 			return (-1);
13425 		}
13426 
13427 		if (sec->dofs_type == DOF_SECT_STRTAB && *((char *)daddr +
13428 		    sec->dofs_offset + sec->dofs_size - 1) != '\0') {
13429 			dtrace_dof_error(dof, "non-terminating string table");
13430 			return (-1);
13431 		}
13432 	}
13433 
13434 	/*
13435 	 * Take a second pass through the sections and locate and perform any
13436 	 * relocations that are present.  We do this after the first pass to
13437 	 * be sure that all sections have had their headers validated.
13438 	 */
13439 	for (i = 0; i < dof->dofh_secnum; i++) {
13440 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13441 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13442 
13443 		if (!(sec->dofs_flags & DOF_SECF_LOAD))
13444 			continue; /* skip sections that are not loadable */
13445 
13446 		switch (sec->dofs_type) {
13447 		case DOF_SECT_URELHDR:
13448 			if (dtrace_dof_relocate(dof, sec, ubase) != 0)
13449 				return (-1);
13450 			break;
13451 		}
13452 	}
13453 
13454 	if ((enab = *enabp) == NULL)
13455 		enab = *enabp = dtrace_enabling_create(vstate);
13456 
13457 	for (i = 0; i < dof->dofh_secnum; i++) {
13458 		dof_sec_t *sec = (dof_sec_t *)(daddr +
13459 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13460 
13461 		if (sec->dofs_type != DOF_SECT_ECBDESC)
13462 			continue;
13463 
13464 		if ((ep = dtrace_dof_ecbdesc(dof, sec, vstate, cr)) == NULL) {
13465 			dtrace_enabling_destroy(enab);
13466 			*enabp = NULL;
13467 			return (-1);
13468 		}
13469 
13470 		dtrace_enabling_add(enab, ep);
13471 	}
13472 
13473 	return (0);
13474 }
13475 
13476 /*
13477  * Process DOF for any options.  This routine assumes that the DOF has been
13478  * at least processed by dtrace_dof_slurp().
13479  */
13480 static int
13481 dtrace_dof_options(dof_hdr_t *dof, dtrace_state_t *state)
13482 {
13483 	int i, rval;
13484 	uint32_t entsize;
13485 	size_t offs;
13486 	dof_optdesc_t *desc;
13487 
13488 	for (i = 0; i < dof->dofh_secnum; i++) {
13489 		dof_sec_t *sec = (dof_sec_t *)((uintptr_t)dof +
13490 		    (uintptr_t)dof->dofh_secoff + i * dof->dofh_secsize);
13491 
13492 		if (sec->dofs_type != DOF_SECT_OPTDESC)
13493 			continue;
13494 
13495 		if (sec->dofs_align != sizeof (uint64_t)) {
13496 			dtrace_dof_error(dof, "bad alignment in "
13497 			    "option description");
13498 			return (EINVAL);
13499 		}
13500 
13501 		if ((entsize = sec->dofs_entsize) == 0) {
13502 			dtrace_dof_error(dof, "zeroed option entry size");
13503 			return (EINVAL);
13504 		}
13505 
13506 		if (entsize < sizeof (dof_optdesc_t)) {
13507 			dtrace_dof_error(dof, "bad option entry size");
13508 			return (EINVAL);
13509 		}
13510 
13511 		for (offs = 0; offs < sec->dofs_size; offs += entsize) {
13512 			desc = (dof_optdesc_t *)((uintptr_t)dof +
13513 			    (uintptr_t)sec->dofs_offset + offs);
13514 
13515 			if (desc->dofo_strtab != DOF_SECIDX_NONE) {
13516 				dtrace_dof_error(dof, "non-zero option string");
13517 				return (EINVAL);
13518 			}
13519 
13520 			if (desc->dofo_value == DTRACEOPT_UNSET) {
13521 				dtrace_dof_error(dof, "unset option");
13522 				return (EINVAL);
13523 			}
13524 
13525 			if ((rval = dtrace_state_option(state,
13526 			    desc->dofo_option, desc->dofo_value)) != 0) {
13527 				dtrace_dof_error(dof, "rejected option");
13528 				return (rval);
13529 			}
13530 		}
13531 	}
13532 
13533 	return (0);
13534 }
13535 
13536 /*
13537  * DTrace Consumer State Functions
13538  */
13539 int
13540 dtrace_dstate_init(dtrace_dstate_t *dstate, size_t size)
13541 {
13542 	size_t hashsize, maxper, min, chunksize = dstate->dtds_chunksize;
13543 	void *base;
13544 	uintptr_t limit;
13545 	dtrace_dynvar_t *dvar, *next, *start;
13546 	int i;
13547 
13548 	ASSERT(MUTEX_HELD(&dtrace_lock));
13549 	ASSERT(dstate->dtds_base == NULL && dstate->dtds_percpu == NULL);
13550 
13551 	bzero(dstate, sizeof (dtrace_dstate_t));
13552 
13553 	if ((dstate->dtds_chunksize = chunksize) == 0)
13554 		dstate->dtds_chunksize = DTRACE_DYNVAR_CHUNKSIZE;
13555 
13556 	VERIFY(dstate->dtds_chunksize < LONG_MAX);
13557 
13558 	if (size < (min = dstate->dtds_chunksize + sizeof (dtrace_dynhash_t)))
13559 		size = min;
13560 
13561 	if ((base = kmem_zalloc(size, KM_NOSLEEP | KM_NORMALPRI)) == NULL)
13562 		return (ENOMEM);
13563 
13564 	dstate->dtds_size = size;
13565 	dstate->dtds_base = base;
13566 	dstate->dtds_percpu = kmem_cache_alloc(dtrace_state_cache, KM_SLEEP);
13567 	bzero(dstate->dtds_percpu, NCPU * sizeof (dtrace_dstate_percpu_t));
13568 
13569 	hashsize = size / (dstate->dtds_chunksize + sizeof (dtrace_dynhash_t));
13570 
13571 	if (hashsize != 1 && (hashsize & 1))
13572 		hashsize--;
13573 
13574 	dstate->dtds_hashsize = hashsize;
13575 	dstate->dtds_hash = dstate->dtds_base;
13576 
13577 	/*
13578 	 * Set all of our hash buckets to point to the single sink, and (if
13579 	 * it hasn't already been set), set the sink's hash value to be the
13580 	 * sink sentinel value.  The sink is needed for dynamic variable
13581 	 * lookups to know that they have iterated over an entire, valid hash
13582 	 * chain.
13583 	 */
13584 	for (i = 0; i < hashsize; i++)
13585 		dstate->dtds_hash[i].dtdh_chain = &dtrace_dynhash_sink;
13586 
13587 	if (dtrace_dynhash_sink.dtdv_hashval != DTRACE_DYNHASH_SINK)
13588 		dtrace_dynhash_sink.dtdv_hashval = DTRACE_DYNHASH_SINK;
13589 
13590 	/*
13591 	 * Determine number of active CPUs.  Divide free list evenly among
13592 	 * active CPUs.
13593 	 */
13594 	start = (dtrace_dynvar_t *)
13595 	    ((uintptr_t)base + hashsize * sizeof (dtrace_dynhash_t));
13596 	limit = (uintptr_t)base + size;
13597 
13598 	VERIFY((uintptr_t)start < limit);
13599 	VERIFY((uintptr_t)start >= (uintptr_t)base);
13600 
13601 	maxper = (limit - (uintptr_t)start) / NCPU;
13602 	maxper = (maxper / dstate->dtds_chunksize) * dstate->dtds_chunksize;
13603 
13604 	for (i = 0; i < NCPU; i++) {
13605 		dstate->dtds_percpu[i].dtdsc_free = dvar = start;
13606 
13607 		/*
13608 		 * If we don't even have enough chunks to make it once through
13609 		 * NCPUs, we're just going to allocate everything to the first
13610 		 * CPU.  And if we're on the last CPU, we're going to allocate
13611 		 * whatever is left over.  In either case, we set the limit to
13612 		 * be the limit of the dynamic variable space.
13613 		 */
13614 		if (maxper == 0 || i == NCPU - 1) {
13615 			limit = (uintptr_t)base + size;
13616 			start = NULL;
13617 		} else {
13618 			limit = (uintptr_t)start + maxper;
13619 			start = (dtrace_dynvar_t *)limit;
13620 		}
13621 
13622 		VERIFY(limit <= (uintptr_t)base + size);
13623 
13624 		for (;;) {
13625 			next = (dtrace_dynvar_t *)((uintptr_t)dvar +
13626 			    dstate->dtds_chunksize);
13627 
13628 			if ((uintptr_t)next + dstate->dtds_chunksize >= limit)
13629 				break;
13630 
13631 			VERIFY((uintptr_t)dvar >= (uintptr_t)base &&
13632 			    (uintptr_t)dvar <= (uintptr_t)base + size);
13633 			dvar->dtdv_next = next;
13634 			dvar = next;
13635 		}
13636 
13637 		if (maxper == 0)
13638 			break;
13639 	}
13640 
13641 	return (0);
13642 }
13643 
13644 void
13645 dtrace_dstate_fini(dtrace_dstate_t *dstate)
13646 {
13647 	ASSERT(MUTEX_HELD(&cpu_lock));
13648 
13649 	if (dstate->dtds_base == NULL)
13650 		return;
13651 
13652 	kmem_free(dstate->dtds_base, dstate->dtds_size);
13653 	kmem_cache_free(dtrace_state_cache, dstate->dtds_percpu);
13654 }
13655 
13656 static void
13657 dtrace_vstate_fini(dtrace_vstate_t *vstate)
13658 {
13659 	/*
13660 	 * Logical XOR, where are you?
13661 	 */
13662 	ASSERT((vstate->dtvs_nglobals == 0) ^ (vstate->dtvs_globals != NULL));
13663 
13664 	if (vstate->dtvs_nglobals > 0) {
13665 		kmem_free(vstate->dtvs_globals, vstate->dtvs_nglobals *
13666 		    sizeof (dtrace_statvar_t *));
13667 	}
13668 
13669 	if (vstate->dtvs_ntlocals > 0) {
13670 		kmem_free(vstate->dtvs_tlocals, vstate->dtvs_ntlocals *
13671 		    sizeof (dtrace_difv_t));
13672 	}
13673 
13674 	ASSERT((vstate->dtvs_nlocals == 0) ^ (vstate->dtvs_locals != NULL));
13675 
13676 	if (vstate->dtvs_nlocals > 0) {
13677 		kmem_free(vstate->dtvs_locals, vstate->dtvs_nlocals *
13678 		    sizeof (dtrace_statvar_t *));
13679 	}
13680 }
13681 
13682 static void
13683 dtrace_state_clean(dtrace_state_t *state)
13684 {
13685 	if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE)
13686 		return;
13687 
13688 	dtrace_dynvar_clean(&state->dts_vstate.dtvs_dynvars);
13689 	dtrace_speculation_clean(state);
13690 }
13691 
13692 static void
13693 dtrace_state_deadman(dtrace_state_t *state)
13694 {
13695 	hrtime_t now;
13696 
13697 	dtrace_sync();
13698 
13699 	now = dtrace_gethrtime();
13700 
13701 	if (state != dtrace_anon.dta_state &&
13702 	    now - state->dts_laststatus >= dtrace_deadman_user)
13703 		return;
13704 
13705 	/*
13706 	 * We must be sure that dts_alive never appears to be less than the
13707 	 * value upon entry to dtrace_state_deadman(), and because we lack a
13708 	 * dtrace_cas64(), we cannot store to it atomically.  We thus instead
13709 	 * store INT64_MAX to it, followed by a memory barrier, followed by
13710 	 * the new value.  This assures that dts_alive never appears to be
13711 	 * less than its true value, regardless of the order in which the
13712 	 * stores to the underlying storage are issued.
13713 	 */
13714 	state->dts_alive = INT64_MAX;
13715 	dtrace_membar_producer();
13716 	state->dts_alive = now;
13717 }
13718 
13719 dtrace_state_t *
13720 dtrace_state_create(dev_t *devp, cred_t *cr)
13721 {
13722 	minor_t minor;
13723 	major_t major;
13724 	char c[30];
13725 	dtrace_state_t *state;
13726 	dtrace_optval_t *opt;
13727 	int bufsize = NCPU * sizeof (dtrace_buffer_t), i;
13728 
13729 	ASSERT(MUTEX_HELD(&dtrace_lock));
13730 	ASSERT(MUTEX_HELD(&cpu_lock));
13731 
13732 	minor = (minor_t)(uintptr_t)vmem_alloc(dtrace_minor, 1,
13733 	    VM_BESTFIT | VM_SLEEP);
13734 
13735 	if (ddi_soft_state_zalloc(dtrace_softstate, minor) != DDI_SUCCESS) {
13736 		vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
13737 		return (NULL);
13738 	}
13739 
13740 	state = ddi_get_soft_state(dtrace_softstate, minor);
13741 	state->dts_epid = DTRACE_EPIDNONE + 1;
13742 
13743 	(void) snprintf(c, sizeof (c), "dtrace_aggid_%d", minor);
13744 	state->dts_aggid_arena = vmem_create(c, (void *)1, UINT32_MAX, 1,
13745 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
13746 
13747 	if (devp != NULL) {
13748 		major = getemajor(*devp);
13749 	} else {
13750 		major = ddi_driver_major(dtrace_devi);
13751 	}
13752 
13753 	state->dts_dev = makedevice(major, minor);
13754 
13755 	if (devp != NULL)
13756 		*devp = state->dts_dev;
13757 
13758 	/*
13759 	 * We allocate NCPU buffers.  On the one hand, this can be quite
13760 	 * a bit of memory per instance (nearly 36K on a Starcat).  On the
13761 	 * other hand, it saves an additional memory reference in the probe
13762 	 * path.
13763 	 */
13764 	state->dts_buffer = kmem_zalloc(bufsize, KM_SLEEP);
13765 	state->dts_aggbuffer = kmem_zalloc(bufsize, KM_SLEEP);
13766 	state->dts_cleaner = CYCLIC_NONE;
13767 	state->dts_deadman = CYCLIC_NONE;
13768 	state->dts_vstate.dtvs_state = state;
13769 
13770 	for (i = 0; i < DTRACEOPT_MAX; i++)
13771 		state->dts_options[i] = DTRACEOPT_UNSET;
13772 
13773 	/*
13774 	 * Set the default options.
13775 	 */
13776 	opt = state->dts_options;
13777 	opt[DTRACEOPT_BUFPOLICY] = DTRACEOPT_BUFPOLICY_SWITCH;
13778 	opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_AUTO;
13779 	opt[DTRACEOPT_NSPEC] = dtrace_nspec_default;
13780 	opt[DTRACEOPT_SPECSIZE] = dtrace_specsize_default;
13781 	opt[DTRACEOPT_CPU] = (dtrace_optval_t)DTRACE_CPUALL;
13782 	opt[DTRACEOPT_STRSIZE] = dtrace_strsize_default;
13783 	opt[DTRACEOPT_STACKFRAMES] = dtrace_stackframes_default;
13784 	opt[DTRACEOPT_USTACKFRAMES] = dtrace_ustackframes_default;
13785 	opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_default;
13786 	opt[DTRACEOPT_AGGRATE] = dtrace_aggrate_default;
13787 	opt[DTRACEOPT_SWITCHRATE] = dtrace_switchrate_default;
13788 	opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_default;
13789 	opt[DTRACEOPT_JSTACKFRAMES] = dtrace_jstackframes_default;
13790 	opt[DTRACEOPT_JSTACKSTRSIZE] = dtrace_jstackstrsize_default;
13791 
13792 	state->dts_activity = DTRACE_ACTIVITY_INACTIVE;
13793 
13794 	/*
13795 	 * Depending on the user credentials, we set flag bits which alter probe
13796 	 * visibility or the amount of destructiveness allowed.  In the case of
13797 	 * actual anonymous tracing, or the possession of all privileges, all of
13798 	 * the normal checks are bypassed.
13799 	 */
13800 	if (cr == NULL || PRIV_POLICY_ONLY(cr, PRIV_ALL, B_FALSE)) {
13801 		state->dts_cred.dcr_visible = DTRACE_CRV_ALL;
13802 		state->dts_cred.dcr_action = DTRACE_CRA_ALL;
13803 	} else {
13804 		/*
13805 		 * Set up the credentials for this instantiation.  We take a
13806 		 * hold on the credential to prevent it from disappearing on
13807 		 * us; this in turn prevents the zone_t referenced by this
13808 		 * credential from disappearing.  This means that we can
13809 		 * examine the credential and the zone from probe context.
13810 		 */
13811 		crhold(cr);
13812 		state->dts_cred.dcr_cred = cr;
13813 
13814 		/*
13815 		 * CRA_PROC means "we have *some* privilege for dtrace" and
13816 		 * unlocks the use of variables like pid, zonename, etc.
13817 		 */
13818 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE) ||
13819 		    PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13820 			state->dts_cred.dcr_action |= DTRACE_CRA_PROC;
13821 		}
13822 
13823 		/*
13824 		 * dtrace_user allows use of syscall and profile providers.
13825 		 * If the user also has proc_owner and/or proc_zone, we
13826 		 * extend the scope to include additional visibility and
13827 		 * destructive power.
13828 		 */
13829 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_USER, B_FALSE)) {
13830 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE)) {
13831 				state->dts_cred.dcr_visible |=
13832 				    DTRACE_CRV_ALLPROC;
13833 
13834 				state->dts_cred.dcr_action |=
13835 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13836 			}
13837 
13838 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE)) {
13839 				state->dts_cred.dcr_visible |=
13840 				    DTRACE_CRV_ALLZONE;
13841 
13842 				state->dts_cred.dcr_action |=
13843 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13844 			}
13845 
13846 			/*
13847 			 * If we have all privs in whatever zone this is,
13848 			 * we can do destructive things to processes which
13849 			 * have altered credentials.
13850 			 */
13851 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13852 			    cr->cr_zone->zone_privset)) {
13853 				state->dts_cred.dcr_action |=
13854 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13855 			}
13856 		}
13857 
13858 		/*
13859 		 * Holding the dtrace_kernel privilege also implies that
13860 		 * the user has the dtrace_user privilege from a visibility
13861 		 * perspective.  But without further privileges, some
13862 		 * destructive actions are not available.
13863 		 */
13864 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_KERNEL, B_FALSE)) {
13865 			/*
13866 			 * Make all probes in all zones visible.  However,
13867 			 * this doesn't mean that all actions become available
13868 			 * to all zones.
13869 			 */
13870 			state->dts_cred.dcr_visible |= DTRACE_CRV_KERNEL |
13871 			    DTRACE_CRV_ALLPROC | DTRACE_CRV_ALLZONE;
13872 
13873 			state->dts_cred.dcr_action |= DTRACE_CRA_KERNEL |
13874 			    DTRACE_CRA_PROC;
13875 			/*
13876 			 * Holding proc_owner means that destructive actions
13877 			 * for *this* zone are allowed.
13878 			 */
13879 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13880 				state->dts_cred.dcr_action |=
13881 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13882 
13883 			/*
13884 			 * Holding proc_zone means that destructive actions
13885 			 * for this user/group ID in all zones is allowed.
13886 			 */
13887 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13888 				state->dts_cred.dcr_action |=
13889 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13890 
13891 			/*
13892 			 * If we have all privs in whatever zone this is,
13893 			 * we can do destructive things to processes which
13894 			 * have altered credentials.
13895 			 */
13896 			if (priv_isequalset(priv_getset(cr, PRIV_EFFECTIVE),
13897 			    cr->cr_zone->zone_privset)) {
13898 				state->dts_cred.dcr_action |=
13899 				    DTRACE_CRA_PROC_DESTRUCTIVE_CREDCHG;
13900 			}
13901 		}
13902 
13903 		/*
13904 		 * Holding the dtrace_proc privilege gives control over fasttrap
13905 		 * and pid providers.  We need to grant wider destructive
13906 		 * privileges in the event that the user has proc_owner and/or
13907 		 * proc_zone.
13908 		 */
13909 		if (PRIV_POLICY_ONLY(cr, PRIV_DTRACE_PROC, B_FALSE)) {
13910 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_OWNER, B_FALSE))
13911 				state->dts_cred.dcr_action |=
13912 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLUSER;
13913 
13914 			if (PRIV_POLICY_ONLY(cr, PRIV_PROC_ZONE, B_FALSE))
13915 				state->dts_cred.dcr_action |=
13916 				    DTRACE_CRA_PROC_DESTRUCTIVE_ALLZONE;
13917 		}
13918 	}
13919 
13920 	return (state);
13921 }
13922 
13923 static int
13924 dtrace_state_buffer(dtrace_state_t *state, dtrace_buffer_t *buf, int which)
13925 {
13926 	dtrace_optval_t *opt = state->dts_options, size;
13927 	processorid_t cpu;
13928 	int flags = 0, rval, factor, divisor = 1;
13929 
13930 	ASSERT(MUTEX_HELD(&dtrace_lock));
13931 	ASSERT(MUTEX_HELD(&cpu_lock));
13932 	ASSERT(which < DTRACEOPT_MAX);
13933 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_INACTIVE ||
13934 	    (state == dtrace_anon.dta_state &&
13935 	    state->dts_activity == DTRACE_ACTIVITY_ACTIVE));
13936 
13937 	if (opt[which] == DTRACEOPT_UNSET || opt[which] == 0)
13938 		return (0);
13939 
13940 	if (opt[DTRACEOPT_CPU] != DTRACEOPT_UNSET)
13941 		cpu = opt[DTRACEOPT_CPU];
13942 
13943 	if (which == DTRACEOPT_SPECSIZE)
13944 		flags |= DTRACEBUF_NOSWITCH;
13945 
13946 	if (which == DTRACEOPT_BUFSIZE) {
13947 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_RING)
13948 			flags |= DTRACEBUF_RING;
13949 
13950 		if (opt[DTRACEOPT_BUFPOLICY] == DTRACEOPT_BUFPOLICY_FILL)
13951 			flags |= DTRACEBUF_FILL;
13952 
13953 		if (state != dtrace_anon.dta_state ||
13954 		    state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
13955 			flags |= DTRACEBUF_INACTIVE;
13956 	}
13957 
13958 	for (size = opt[which]; size >= sizeof (uint64_t); size /= divisor) {
13959 		/*
13960 		 * The size must be 8-byte aligned.  If the size is not 8-byte
13961 		 * aligned, drop it down by the difference.
13962 		 */
13963 		if (size & (sizeof (uint64_t) - 1))
13964 			size -= size & (sizeof (uint64_t) - 1);
13965 
13966 		if (size < state->dts_reserve) {
13967 			/*
13968 			 * Buffers always must be large enough to accommodate
13969 			 * their prereserved space.  We return E2BIG instead
13970 			 * of ENOMEM in this case to allow for user-level
13971 			 * software to differentiate the cases.
13972 			 */
13973 			return (E2BIG);
13974 		}
13975 
13976 		rval = dtrace_buffer_alloc(buf, size, flags, cpu, &factor);
13977 
13978 		if (rval != ENOMEM) {
13979 			opt[which] = size;
13980 			return (rval);
13981 		}
13982 
13983 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
13984 			return (rval);
13985 
13986 		for (divisor = 2; divisor < factor; divisor <<= 1)
13987 			continue;
13988 	}
13989 
13990 	return (ENOMEM);
13991 }
13992 
13993 static int
13994 dtrace_state_buffers(dtrace_state_t *state)
13995 {
13996 	dtrace_speculation_t *spec = state->dts_speculations;
13997 	int rval, i;
13998 
13999 	if ((rval = dtrace_state_buffer(state, state->dts_buffer,
14000 	    DTRACEOPT_BUFSIZE)) != 0)
14001 		return (rval);
14002 
14003 	if ((rval = dtrace_state_buffer(state, state->dts_aggbuffer,
14004 	    DTRACEOPT_AGGSIZE)) != 0)
14005 		return (rval);
14006 
14007 	for (i = 0; i < state->dts_nspeculations; i++) {
14008 		if ((rval = dtrace_state_buffer(state,
14009 		    spec[i].dtsp_buffer, DTRACEOPT_SPECSIZE)) != 0)
14010 			return (rval);
14011 	}
14012 
14013 	return (0);
14014 }
14015 
14016 static void
14017 dtrace_state_prereserve(dtrace_state_t *state)
14018 {
14019 	dtrace_ecb_t *ecb;
14020 	dtrace_probe_t *probe;
14021 
14022 	state->dts_reserve = 0;
14023 
14024 	if (state->dts_options[DTRACEOPT_BUFPOLICY] != DTRACEOPT_BUFPOLICY_FILL)
14025 		return;
14026 
14027 	/*
14028 	 * If our buffer policy is a "fill" buffer policy, we need to set the
14029 	 * prereserved space to be the space required by the END probes.
14030 	 */
14031 	probe = dtrace_probes[dtrace_probeid_end - 1];
14032 	ASSERT(probe != NULL);
14033 
14034 	for (ecb = probe->dtpr_ecb; ecb != NULL; ecb = ecb->dte_next) {
14035 		if (ecb->dte_state != state)
14036 			continue;
14037 
14038 		state->dts_reserve += ecb->dte_needed + ecb->dte_alignment;
14039 	}
14040 }
14041 
14042 static int
14043 dtrace_state_go(dtrace_state_t *state, processorid_t *cpu)
14044 {
14045 	dtrace_optval_t *opt = state->dts_options, sz, nspec;
14046 	dtrace_speculation_t *spec;
14047 	dtrace_buffer_t *buf;
14048 	cyc_handler_t hdlr;
14049 	cyc_time_t when;
14050 	int rval = 0, i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14051 	dtrace_icookie_t cookie;
14052 
14053 	mutex_enter(&cpu_lock);
14054 	mutex_enter(&dtrace_lock);
14055 
14056 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
14057 		rval = EBUSY;
14058 		goto out;
14059 	}
14060 
14061 	/*
14062 	 * Before we can perform any checks, we must prime all of the
14063 	 * retained enablings that correspond to this state.
14064 	 */
14065 	dtrace_enabling_prime(state);
14066 
14067 	if (state->dts_destructive && !state->dts_cred.dcr_destructive) {
14068 		rval = EACCES;
14069 		goto out;
14070 	}
14071 
14072 	dtrace_state_prereserve(state);
14073 
14074 	/*
14075 	 * Now we want to do is try to allocate our speculations.
14076 	 * We do not automatically resize the number of speculations; if
14077 	 * this fails, we will fail the operation.
14078 	 */
14079 	nspec = opt[DTRACEOPT_NSPEC];
14080 	ASSERT(nspec != DTRACEOPT_UNSET);
14081 
14082 	if (nspec > INT_MAX) {
14083 		rval = ENOMEM;
14084 		goto out;
14085 	}
14086 
14087 	spec = kmem_zalloc(nspec * sizeof (dtrace_speculation_t),
14088 	    KM_NOSLEEP | KM_NORMALPRI);
14089 
14090 	if (spec == NULL) {
14091 		rval = ENOMEM;
14092 		goto out;
14093 	}
14094 
14095 	state->dts_speculations = spec;
14096 	state->dts_nspeculations = (int)nspec;
14097 
14098 	for (i = 0; i < nspec; i++) {
14099 		if ((buf = kmem_zalloc(bufsize,
14100 		    KM_NOSLEEP | KM_NORMALPRI)) == NULL) {
14101 			rval = ENOMEM;
14102 			goto err;
14103 		}
14104 
14105 		spec[i].dtsp_buffer = buf;
14106 	}
14107 
14108 	if (opt[DTRACEOPT_GRABANON] != DTRACEOPT_UNSET) {
14109 		if (dtrace_anon.dta_state == NULL) {
14110 			rval = ENOENT;
14111 			goto out;
14112 		}
14113 
14114 		if (state->dts_necbs != 0) {
14115 			rval = EALREADY;
14116 			goto out;
14117 		}
14118 
14119 		state->dts_anon = dtrace_anon_grab();
14120 		ASSERT(state->dts_anon != NULL);
14121 		state = state->dts_anon;
14122 
14123 		/*
14124 		 * We want "grabanon" to be set in the grabbed state, so we'll
14125 		 * copy that option value from the grabbing state into the
14126 		 * grabbed state.
14127 		 */
14128 		state->dts_options[DTRACEOPT_GRABANON] =
14129 		    opt[DTRACEOPT_GRABANON];
14130 
14131 		*cpu = dtrace_anon.dta_beganon;
14132 
14133 		/*
14134 		 * If the anonymous state is active (as it almost certainly
14135 		 * is if the anonymous enabling ultimately matched anything),
14136 		 * we don't allow any further option processing -- but we
14137 		 * don't return failure.
14138 		 */
14139 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14140 			goto out;
14141 	}
14142 
14143 	if (opt[DTRACEOPT_AGGSIZE] != DTRACEOPT_UNSET &&
14144 	    opt[DTRACEOPT_AGGSIZE] != 0) {
14145 		if (state->dts_aggregations == NULL) {
14146 			/*
14147 			 * We're not going to create an aggregation buffer
14148 			 * because we don't have any ECBs that contain
14149 			 * aggregations -- set this option to 0.
14150 			 */
14151 			opt[DTRACEOPT_AGGSIZE] = 0;
14152 		} else {
14153 			/*
14154 			 * If we have an aggregation buffer, we must also have
14155 			 * a buffer to use as scratch.
14156 			 */
14157 			if (opt[DTRACEOPT_BUFSIZE] == DTRACEOPT_UNSET ||
14158 			    opt[DTRACEOPT_BUFSIZE] < state->dts_needed) {
14159 				opt[DTRACEOPT_BUFSIZE] = state->dts_needed;
14160 			}
14161 		}
14162 	}
14163 
14164 	if (opt[DTRACEOPT_SPECSIZE] != DTRACEOPT_UNSET &&
14165 	    opt[DTRACEOPT_SPECSIZE] != 0) {
14166 		if (!state->dts_speculates) {
14167 			/*
14168 			 * We're not going to create speculation buffers
14169 			 * because we don't have any ECBs that actually
14170 			 * speculate -- set the speculation size to 0.
14171 			 */
14172 			opt[DTRACEOPT_SPECSIZE] = 0;
14173 		}
14174 	}
14175 
14176 	/*
14177 	 * The bare minimum size for any buffer that we're actually going to
14178 	 * do anything to is sizeof (uint64_t).
14179 	 */
14180 	sz = sizeof (uint64_t);
14181 
14182 	if ((state->dts_needed != 0 && opt[DTRACEOPT_BUFSIZE] < sz) ||
14183 	    (state->dts_speculates && opt[DTRACEOPT_SPECSIZE] < sz) ||
14184 	    (state->dts_aggregations != NULL && opt[DTRACEOPT_AGGSIZE] < sz)) {
14185 		/*
14186 		 * A buffer size has been explicitly set to 0 (or to a size
14187 		 * that will be adjusted to 0) and we need the space -- we
14188 		 * need to return failure.  We return ENOSPC to differentiate
14189 		 * it from failing to allocate a buffer due to failure to meet
14190 		 * the reserve (for which we return E2BIG).
14191 		 */
14192 		rval = ENOSPC;
14193 		goto out;
14194 	}
14195 
14196 	if ((rval = dtrace_state_buffers(state)) != 0)
14197 		goto err;
14198 
14199 	if ((sz = opt[DTRACEOPT_DYNVARSIZE]) == DTRACEOPT_UNSET)
14200 		sz = dtrace_dstate_defsize;
14201 
14202 	do {
14203 		rval = dtrace_dstate_init(&state->dts_vstate.dtvs_dynvars, sz);
14204 
14205 		if (rval == 0)
14206 			break;
14207 
14208 		if (opt[DTRACEOPT_BUFRESIZE] == DTRACEOPT_BUFRESIZE_MANUAL)
14209 			goto err;
14210 	} while (sz >>= 1);
14211 
14212 	opt[DTRACEOPT_DYNVARSIZE] = sz;
14213 
14214 	if (rval != 0)
14215 		goto err;
14216 
14217 	if (opt[DTRACEOPT_STATUSRATE] > dtrace_statusrate_max)
14218 		opt[DTRACEOPT_STATUSRATE] = dtrace_statusrate_max;
14219 
14220 	if (opt[DTRACEOPT_CLEANRATE] == 0)
14221 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14222 
14223 	if (opt[DTRACEOPT_CLEANRATE] < dtrace_cleanrate_min)
14224 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_min;
14225 
14226 	if (opt[DTRACEOPT_CLEANRATE] > dtrace_cleanrate_max)
14227 		opt[DTRACEOPT_CLEANRATE] = dtrace_cleanrate_max;
14228 
14229 	hdlr.cyh_func = (cyc_func_t)dtrace_state_clean;
14230 	hdlr.cyh_arg = state;
14231 	hdlr.cyh_level = CY_LOW_LEVEL;
14232 
14233 	when.cyt_when = 0;
14234 	when.cyt_interval = opt[DTRACEOPT_CLEANRATE];
14235 
14236 	state->dts_cleaner = cyclic_add(&hdlr, &when);
14237 
14238 	hdlr.cyh_func = (cyc_func_t)dtrace_state_deadman;
14239 	hdlr.cyh_arg = state;
14240 	hdlr.cyh_level = CY_LOW_LEVEL;
14241 
14242 	when.cyt_when = 0;
14243 	when.cyt_interval = dtrace_deadman_interval;
14244 
14245 	state->dts_alive = state->dts_laststatus = dtrace_gethrtime();
14246 	state->dts_deadman = cyclic_add(&hdlr, &when);
14247 
14248 	state->dts_activity = DTRACE_ACTIVITY_WARMUP;
14249 
14250 	if (state->dts_getf != 0 &&
14251 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14252 		/*
14253 		 * We don't have kernel privs but we have at least one call
14254 		 * to getf(); we need to bump our zone's count, and (if
14255 		 * this is the first enabling to have an unprivileged call
14256 		 * to getf()) we need to hook into closef().
14257 		 */
14258 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf++;
14259 
14260 		if (dtrace_getf++ == 0) {
14261 			ASSERT(dtrace_closef == NULL);
14262 			dtrace_closef = dtrace_getf_barrier;
14263 		}
14264 	}
14265 
14266 	/*
14267 	 * Now it's time to actually fire the BEGIN probe.  We need to disable
14268 	 * interrupts here both to record the CPU on which we fired the BEGIN
14269 	 * probe (the data from this CPU will be processed first at user
14270 	 * level) and to manually activate the buffer for this CPU.
14271 	 */
14272 	cookie = dtrace_interrupt_disable();
14273 	*cpu = CPU->cpu_id;
14274 	ASSERT(state->dts_buffer[*cpu].dtb_flags & DTRACEBUF_INACTIVE);
14275 	state->dts_buffer[*cpu].dtb_flags &= ~DTRACEBUF_INACTIVE;
14276 
14277 	dtrace_probe(dtrace_probeid_begin,
14278 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14279 	dtrace_interrupt_enable(cookie);
14280 	/*
14281 	 * We may have had an exit action from a BEGIN probe; only change our
14282 	 * state to ACTIVE if we're still in WARMUP.
14283 	 */
14284 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_WARMUP ||
14285 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING);
14286 
14287 	if (state->dts_activity == DTRACE_ACTIVITY_WARMUP)
14288 		state->dts_activity = DTRACE_ACTIVITY_ACTIVE;
14289 
14290 	/*
14291 	 * Regardless of whether or not now we're in ACTIVE or DRAINING, we
14292 	 * want each CPU to transition its principal buffer out of the
14293 	 * INACTIVE state.  Doing this assures that no CPU will suddenly begin
14294 	 * processing an ECB halfway down a probe's ECB chain; all CPUs will
14295 	 * atomically transition from processing none of a state's ECBs to
14296 	 * processing all of them.
14297 	 */
14298 	dtrace_xcall(DTRACE_CPUALL,
14299 	    (dtrace_xcall_t)dtrace_buffer_activate, state);
14300 	goto out;
14301 
14302 err:
14303 	dtrace_buffer_free(state->dts_buffer);
14304 	dtrace_buffer_free(state->dts_aggbuffer);
14305 
14306 	if ((nspec = state->dts_nspeculations) == 0) {
14307 		ASSERT(state->dts_speculations == NULL);
14308 		goto out;
14309 	}
14310 
14311 	spec = state->dts_speculations;
14312 	ASSERT(spec != NULL);
14313 
14314 	for (i = 0; i < state->dts_nspeculations; i++) {
14315 		if ((buf = spec[i].dtsp_buffer) == NULL)
14316 			break;
14317 
14318 		dtrace_buffer_free(buf);
14319 		kmem_free(buf, bufsize);
14320 	}
14321 
14322 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14323 	state->dts_nspeculations = 0;
14324 	state->dts_speculations = NULL;
14325 
14326 out:
14327 	mutex_exit(&dtrace_lock);
14328 	mutex_exit(&cpu_lock);
14329 
14330 	return (rval);
14331 }
14332 
14333 static int
14334 dtrace_state_stop(dtrace_state_t *state, processorid_t *cpu)
14335 {
14336 	dtrace_icookie_t cookie;
14337 
14338 	ASSERT(MUTEX_HELD(&dtrace_lock));
14339 
14340 	if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE &&
14341 	    state->dts_activity != DTRACE_ACTIVITY_DRAINING)
14342 		return (EINVAL);
14343 
14344 	/*
14345 	 * We'll set the activity to DTRACE_ACTIVITY_DRAINING, and issue a sync
14346 	 * to be sure that every CPU has seen it.  See below for the details
14347 	 * on why this is done.
14348 	 */
14349 	state->dts_activity = DTRACE_ACTIVITY_DRAINING;
14350 	dtrace_sync();
14351 
14352 	/*
14353 	 * By this point, it is impossible for any CPU to be still processing
14354 	 * with DTRACE_ACTIVITY_ACTIVE.  We can thus set our activity to
14355 	 * DTRACE_ACTIVITY_COOLDOWN and know that we're not racing with any
14356 	 * other CPU in dtrace_buffer_reserve().  This allows dtrace_probe()
14357 	 * and callees to know that the activity is DTRACE_ACTIVITY_COOLDOWN
14358 	 * iff we're in the END probe.
14359 	 */
14360 	state->dts_activity = DTRACE_ACTIVITY_COOLDOWN;
14361 	dtrace_sync();
14362 	ASSERT(state->dts_activity == DTRACE_ACTIVITY_COOLDOWN);
14363 
14364 	/*
14365 	 * Finally, we can release the reserve and call the END probe.  We
14366 	 * disable interrupts across calling the END probe to allow us to
14367 	 * return the CPU on which we actually called the END probe.  This
14368 	 * allows user-land to be sure that this CPU's principal buffer is
14369 	 * processed last.
14370 	 */
14371 	state->dts_reserve = 0;
14372 
14373 	cookie = dtrace_interrupt_disable();
14374 	*cpu = CPU->cpu_id;
14375 	dtrace_probe(dtrace_probeid_end,
14376 	    (uint64_t)(uintptr_t)state, 0, 0, 0, 0);
14377 	dtrace_interrupt_enable(cookie);
14378 
14379 	state->dts_activity = DTRACE_ACTIVITY_STOPPED;
14380 	dtrace_sync();
14381 
14382 	if (state->dts_getf != 0 &&
14383 	    !(state->dts_cred.dcr_visible & DTRACE_CRV_KERNEL)) {
14384 		/*
14385 		 * We don't have kernel privs but we have at least one call
14386 		 * to getf(); we need to lower our zone's count, and (if
14387 		 * this is the last enabling to have an unprivileged call
14388 		 * to getf()) we need to clear the closef() hook.
14389 		 */
14390 		ASSERT(state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf > 0);
14391 		ASSERT(dtrace_closef == dtrace_getf_barrier);
14392 		ASSERT(dtrace_getf > 0);
14393 
14394 		state->dts_cred.dcr_cred->cr_zone->zone_dtrace_getf--;
14395 
14396 		if (--dtrace_getf == 0)
14397 			dtrace_closef = NULL;
14398 	}
14399 
14400 	return (0);
14401 }
14402 
14403 static int
14404 dtrace_state_option(dtrace_state_t *state, dtrace_optid_t option,
14405     dtrace_optval_t val)
14406 {
14407 	ASSERT(MUTEX_HELD(&dtrace_lock));
14408 
14409 	if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE)
14410 		return (EBUSY);
14411 
14412 	if (option >= DTRACEOPT_MAX)
14413 		return (EINVAL);
14414 
14415 	if (option != DTRACEOPT_CPU && val < 0)
14416 		return (EINVAL);
14417 
14418 	switch (option) {
14419 	case DTRACEOPT_DESTRUCTIVE:
14420 		if (dtrace_destructive_disallow)
14421 			return (EACCES);
14422 
14423 		state->dts_cred.dcr_destructive = 1;
14424 		break;
14425 
14426 	case DTRACEOPT_BUFSIZE:
14427 	case DTRACEOPT_DYNVARSIZE:
14428 	case DTRACEOPT_AGGSIZE:
14429 	case DTRACEOPT_SPECSIZE:
14430 	case DTRACEOPT_STRSIZE:
14431 		if (val < 0)
14432 			return (EINVAL);
14433 
14434 		if (val >= LONG_MAX) {
14435 			/*
14436 			 * If this is an otherwise negative value, set it to
14437 			 * the highest multiple of 128m less than LONG_MAX.
14438 			 * Technically, we're adjusting the size without
14439 			 * regard to the buffer resizing policy, but in fact,
14440 			 * this has no effect -- if we set the buffer size to
14441 			 * ~LONG_MAX and the buffer policy is ultimately set to
14442 			 * be "manual", the buffer allocation is guaranteed to
14443 			 * fail, if only because the allocation requires two
14444 			 * buffers.  (We set the the size to the highest
14445 			 * multiple of 128m because it ensures that the size
14446 			 * will remain a multiple of a megabyte when
14447 			 * repeatedly halved -- all the way down to 15m.)
14448 			 */
14449 			val = LONG_MAX - (1 << 27) + 1;
14450 		}
14451 	}
14452 
14453 	state->dts_options[option] = val;
14454 
14455 	return (0);
14456 }
14457 
14458 static void
14459 dtrace_state_destroy(dtrace_state_t *state)
14460 {
14461 	dtrace_ecb_t *ecb;
14462 	dtrace_vstate_t *vstate = &state->dts_vstate;
14463 	minor_t minor = getminor(state->dts_dev);
14464 	int i, bufsize = NCPU * sizeof (dtrace_buffer_t);
14465 	dtrace_speculation_t *spec = state->dts_speculations;
14466 	int nspec = state->dts_nspeculations;
14467 	uint32_t match;
14468 
14469 	ASSERT(MUTEX_HELD(&dtrace_lock));
14470 	ASSERT(MUTEX_HELD(&cpu_lock));
14471 
14472 	/*
14473 	 * First, retract any retained enablings for this state.
14474 	 */
14475 	dtrace_enabling_retract(state);
14476 	ASSERT(state->dts_nretained == 0);
14477 
14478 	if (state->dts_activity == DTRACE_ACTIVITY_ACTIVE ||
14479 	    state->dts_activity == DTRACE_ACTIVITY_DRAINING) {
14480 		/*
14481 		 * We have managed to come into dtrace_state_destroy() on a
14482 		 * hot enabling -- almost certainly because of a disorderly
14483 		 * shutdown of a consumer.  (That is, a consumer that is
14484 		 * exiting without having called dtrace_stop().) In this case,
14485 		 * we're going to set our activity to be KILLED, and then
14486 		 * issue a sync to be sure that everyone is out of probe
14487 		 * context before we start blowing away ECBs.
14488 		 */
14489 		state->dts_activity = DTRACE_ACTIVITY_KILLED;
14490 		dtrace_sync();
14491 	}
14492 
14493 	/*
14494 	 * Release the credential hold we took in dtrace_state_create().
14495 	 */
14496 	if (state->dts_cred.dcr_cred != NULL)
14497 		crfree(state->dts_cred.dcr_cred);
14498 
14499 	/*
14500 	 * Now we can safely disable and destroy any enabled probes.  Because
14501 	 * any DTRACE_PRIV_KERNEL probes may actually be slowing our progress
14502 	 * (especially if they're all enabled), we take two passes through the
14503 	 * ECBs:  in the first, we disable just DTRACE_PRIV_KERNEL probes, and
14504 	 * in the second we disable whatever is left over.
14505 	 */
14506 	for (match = DTRACE_PRIV_KERNEL; ; match = 0) {
14507 		for (i = 0; i < state->dts_necbs; i++) {
14508 			if ((ecb = state->dts_ecbs[i]) == NULL)
14509 				continue;
14510 
14511 			if (match && ecb->dte_probe != NULL) {
14512 				dtrace_probe_t *probe = ecb->dte_probe;
14513 				dtrace_provider_t *prov = probe->dtpr_provider;
14514 
14515 				if (!(prov->dtpv_priv.dtpp_flags & match))
14516 					continue;
14517 			}
14518 
14519 			dtrace_ecb_disable(ecb);
14520 			dtrace_ecb_destroy(ecb);
14521 		}
14522 
14523 		if (!match)
14524 			break;
14525 	}
14526 
14527 	/*
14528 	 * Before we free the buffers, perform one more sync to assure that
14529 	 * every CPU is out of probe context.
14530 	 */
14531 	dtrace_sync();
14532 
14533 	dtrace_buffer_free(state->dts_buffer);
14534 	dtrace_buffer_free(state->dts_aggbuffer);
14535 
14536 	for (i = 0; i < nspec; i++)
14537 		dtrace_buffer_free(spec[i].dtsp_buffer);
14538 
14539 	if (state->dts_cleaner != CYCLIC_NONE)
14540 		cyclic_remove(state->dts_cleaner);
14541 
14542 	if (state->dts_deadman != CYCLIC_NONE)
14543 		cyclic_remove(state->dts_deadman);
14544 
14545 	dtrace_dstate_fini(&vstate->dtvs_dynvars);
14546 	dtrace_vstate_fini(vstate);
14547 	kmem_free(state->dts_ecbs, state->dts_necbs * sizeof (dtrace_ecb_t *));
14548 
14549 	if (state->dts_aggregations != NULL) {
14550 #ifdef DEBUG
14551 		for (i = 0; i < state->dts_naggregations; i++)
14552 			ASSERT(state->dts_aggregations[i] == NULL);
14553 #endif
14554 		ASSERT(state->dts_naggregations > 0);
14555 		kmem_free(state->dts_aggregations,
14556 		    state->dts_naggregations * sizeof (dtrace_aggregation_t *));
14557 	}
14558 
14559 	kmem_free(state->dts_buffer, bufsize);
14560 	kmem_free(state->dts_aggbuffer, bufsize);
14561 
14562 	for (i = 0; i < nspec; i++)
14563 		kmem_free(spec[i].dtsp_buffer, bufsize);
14564 
14565 	kmem_free(spec, nspec * sizeof (dtrace_speculation_t));
14566 
14567 	dtrace_format_destroy(state);
14568 
14569 	vmem_destroy(state->dts_aggid_arena);
14570 	ddi_soft_state_free(dtrace_softstate, minor);
14571 	vmem_free(dtrace_minor, (void *)(uintptr_t)minor, 1);
14572 }
14573 
14574 /*
14575  * DTrace Anonymous Enabling Functions
14576  */
14577 static dtrace_state_t *
14578 dtrace_anon_grab(void)
14579 {
14580 	dtrace_state_t *state;
14581 
14582 	ASSERT(MUTEX_HELD(&dtrace_lock));
14583 
14584 	if ((state = dtrace_anon.dta_state) == NULL) {
14585 		ASSERT(dtrace_anon.dta_enabling == NULL);
14586 		return (NULL);
14587 	}
14588 
14589 	ASSERT(dtrace_anon.dta_enabling != NULL);
14590 	ASSERT(dtrace_retained != NULL);
14591 
14592 	dtrace_enabling_destroy(dtrace_anon.dta_enabling);
14593 	dtrace_anon.dta_enabling = NULL;
14594 	dtrace_anon.dta_state = NULL;
14595 
14596 	return (state);
14597 }
14598 
14599 static void
14600 dtrace_anon_property(void)
14601 {
14602 	int i, rv;
14603 	dtrace_state_t *state;
14604 	dof_hdr_t *dof;
14605 	char c[32];		/* enough for "dof-data-" + digits */
14606 
14607 	ASSERT(MUTEX_HELD(&dtrace_lock));
14608 	ASSERT(MUTEX_HELD(&cpu_lock));
14609 
14610 	for (i = 0; ; i++) {
14611 		(void) snprintf(c, sizeof (c), "dof-data-%d", i);
14612 
14613 		dtrace_err_verbose = 1;
14614 
14615 		if ((dof = dtrace_dof_property(c)) == NULL) {
14616 			dtrace_err_verbose = 0;
14617 			break;
14618 		}
14619 
14620 		/*
14621 		 * We want to create anonymous state, so we need to transition
14622 		 * the kernel debugger to indicate that DTrace is active.  If
14623 		 * this fails (e.g. because the debugger has modified text in
14624 		 * some way), we won't continue with the processing.
14625 		 */
14626 		if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
14627 			cmn_err(CE_NOTE, "kernel debugger active; anonymous "
14628 			    "enabling ignored.");
14629 			dtrace_dof_destroy(dof);
14630 			break;
14631 		}
14632 
14633 		/*
14634 		 * If we haven't allocated an anonymous state, we'll do so now.
14635 		 */
14636 		if ((state = dtrace_anon.dta_state) == NULL) {
14637 			state = dtrace_state_create(NULL, NULL);
14638 			dtrace_anon.dta_state = state;
14639 
14640 			if (state == NULL) {
14641 				/*
14642 				 * This basically shouldn't happen:  the only
14643 				 * failure mode from dtrace_state_create() is a
14644 				 * failure of ddi_soft_state_zalloc() that
14645 				 * itself should never happen.  Still, the
14646 				 * interface allows for a failure mode, and
14647 				 * we want to fail as gracefully as possible:
14648 				 * we'll emit an error message and cease
14649 				 * processing anonymous state in this case.
14650 				 */
14651 				cmn_err(CE_WARN, "failed to create "
14652 				    "anonymous state");
14653 				dtrace_dof_destroy(dof);
14654 				break;
14655 			}
14656 		}
14657 
14658 		rv = dtrace_dof_slurp(dof, &state->dts_vstate, CRED(),
14659 		    &dtrace_anon.dta_enabling, 0, B_TRUE);
14660 
14661 		if (rv == 0)
14662 			rv = dtrace_dof_options(dof, state);
14663 
14664 		dtrace_err_verbose = 0;
14665 		dtrace_dof_destroy(dof);
14666 
14667 		if (rv != 0) {
14668 			/*
14669 			 * This is malformed DOF; chuck any anonymous state
14670 			 * that we created.
14671 			 */
14672 			ASSERT(dtrace_anon.dta_enabling == NULL);
14673 			dtrace_state_destroy(state);
14674 			dtrace_anon.dta_state = NULL;
14675 			break;
14676 		}
14677 
14678 		ASSERT(dtrace_anon.dta_enabling != NULL);
14679 	}
14680 
14681 	if (dtrace_anon.dta_enabling != NULL) {
14682 		int rval;
14683 
14684 		/*
14685 		 * dtrace_enabling_retain() can only fail because we are
14686 		 * trying to retain more enablings than are allowed -- but
14687 		 * we only have one anonymous enabling, and we are guaranteed
14688 		 * to be allowed at least one retained enabling; we assert
14689 		 * that dtrace_enabling_retain() returns success.
14690 		 */
14691 		rval = dtrace_enabling_retain(dtrace_anon.dta_enabling);
14692 		ASSERT(rval == 0);
14693 
14694 		dtrace_enabling_dump(dtrace_anon.dta_enabling);
14695 	}
14696 }
14697 
14698 /*
14699  * DTrace Helper Functions
14700  */
14701 static void
14702 dtrace_helper_trace(dtrace_helper_action_t *helper,
14703     dtrace_mstate_t *mstate, dtrace_vstate_t *vstate, int where)
14704 {
14705 	uint32_t size, next, nnext, i;
14706 	dtrace_helptrace_t *ent, *buffer;
14707 	uint16_t flags = cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14708 
14709 	if ((buffer = dtrace_helptrace_buffer) == NULL)
14710 		return;
14711 
14712 	ASSERT(vstate->dtvs_nlocals <= dtrace_helptrace_nlocals);
14713 
14714 	/*
14715 	 * What would a tracing framework be without its own tracing
14716 	 * framework?  (Well, a hell of a lot simpler, for starters...)
14717 	 */
14718 	size = sizeof (dtrace_helptrace_t) + dtrace_helptrace_nlocals *
14719 	    sizeof (uint64_t) - sizeof (uint64_t);
14720 
14721 	/*
14722 	 * Iterate until we can allocate a slot in the trace buffer.
14723 	 */
14724 	do {
14725 		next = dtrace_helptrace_next;
14726 
14727 		if (next + size < dtrace_helptrace_bufsize) {
14728 			nnext = next + size;
14729 		} else {
14730 			nnext = size;
14731 		}
14732 	} while (dtrace_cas32(&dtrace_helptrace_next, next, nnext) != next);
14733 
14734 	/*
14735 	 * We have our slot; fill it in.
14736 	 */
14737 	if (nnext == size) {
14738 		dtrace_helptrace_wrapped++;
14739 		next = 0;
14740 	}
14741 
14742 	ent = (dtrace_helptrace_t *)((uintptr_t)buffer + next);
14743 	ent->dtht_helper = helper;
14744 	ent->dtht_where = where;
14745 	ent->dtht_nlocals = vstate->dtvs_nlocals;
14746 
14747 	ent->dtht_fltoffs = (mstate->dtms_present & DTRACE_MSTATE_FLTOFFS) ?
14748 	    mstate->dtms_fltoffs : -1;
14749 	ent->dtht_fault = DTRACE_FLAGS2FLT(flags);
14750 	ent->dtht_illval = cpu_core[CPU->cpu_id].cpuc_dtrace_illval;
14751 
14752 	for (i = 0; i < vstate->dtvs_nlocals; i++) {
14753 		dtrace_statvar_t *svar;
14754 
14755 		if ((svar = vstate->dtvs_locals[i]) == NULL)
14756 			continue;
14757 
14758 		ASSERT(svar->dtsv_size >= NCPU * sizeof (uint64_t));
14759 		ent->dtht_locals[i] =
14760 		    ((uint64_t *)(uintptr_t)svar->dtsv_data)[CPU->cpu_id];
14761 	}
14762 }
14763 
14764 static uint64_t
14765 dtrace_helper(int which, dtrace_mstate_t *mstate,
14766     dtrace_state_t *state, uint64_t arg0, uint64_t arg1)
14767 {
14768 	uint16_t *flags = &cpu_core[CPU->cpu_id].cpuc_dtrace_flags;
14769 	uint64_t sarg0 = mstate->dtms_arg[0];
14770 	uint64_t sarg1 = mstate->dtms_arg[1];
14771 	uint64_t rval;
14772 	dtrace_helpers_t *helpers = curproc->p_dtrace_helpers;
14773 	dtrace_helper_action_t *helper;
14774 	dtrace_vstate_t *vstate;
14775 	dtrace_difo_t *pred;
14776 	int i, trace = dtrace_helptrace_buffer != NULL;
14777 
14778 	ASSERT(which >= 0 && which < DTRACE_NHELPER_ACTIONS);
14779 
14780 	if (helpers == NULL)
14781 		return (0);
14782 
14783 	if ((helper = helpers->dthps_actions[which]) == NULL)
14784 		return (0);
14785 
14786 	vstate = &helpers->dthps_vstate;
14787 	mstate->dtms_arg[0] = arg0;
14788 	mstate->dtms_arg[1] = arg1;
14789 
14790 	/*
14791 	 * Now iterate over each helper.  If its predicate evaluates to 'true',
14792 	 * we'll call the corresponding actions.  Note that the below calls
14793 	 * to dtrace_dif_emulate() may set faults in machine state.  This is
14794 	 * okay:  our caller (the outer dtrace_dif_emulate()) will simply plow
14795 	 * the stored DIF offset with its own (which is the desired behavior).
14796 	 * Also, note the calls to dtrace_dif_emulate() may allocate scratch
14797 	 * from machine state; this is okay, too.
14798 	 */
14799 	for (; helper != NULL; helper = helper->dtha_next) {
14800 		if ((pred = helper->dtha_predicate) != NULL) {
14801 			if (trace)
14802 				dtrace_helper_trace(helper, mstate, vstate, 0);
14803 
14804 			if (!dtrace_dif_emulate(pred, mstate, vstate, state))
14805 				goto next;
14806 
14807 			if (*flags & CPU_DTRACE_FAULT)
14808 				goto err;
14809 		}
14810 
14811 		for (i = 0; i < helper->dtha_nactions; i++) {
14812 			if (trace)
14813 				dtrace_helper_trace(helper,
14814 				    mstate, vstate, i + 1);
14815 
14816 			rval = dtrace_dif_emulate(helper->dtha_actions[i],
14817 			    mstate, vstate, state);
14818 
14819 			if (*flags & CPU_DTRACE_FAULT)
14820 				goto err;
14821 		}
14822 
14823 next:
14824 		if (trace)
14825 			dtrace_helper_trace(helper, mstate, vstate,
14826 			    DTRACE_HELPTRACE_NEXT);
14827 	}
14828 
14829 	if (trace)
14830 		dtrace_helper_trace(helper, mstate, vstate,
14831 		    DTRACE_HELPTRACE_DONE);
14832 
14833 	/*
14834 	 * Restore the arg0 that we saved upon entry.
14835 	 */
14836 	mstate->dtms_arg[0] = sarg0;
14837 	mstate->dtms_arg[1] = sarg1;
14838 
14839 	return (rval);
14840 
14841 err:
14842 	if (trace)
14843 		dtrace_helper_trace(helper, mstate, vstate,
14844 		    DTRACE_HELPTRACE_ERR);
14845 
14846 	/*
14847 	 * Restore the arg0 that we saved upon entry.
14848 	 */
14849 	mstate->dtms_arg[0] = sarg0;
14850 	mstate->dtms_arg[1] = sarg1;
14851 
14852 	return (0);
14853 }
14854 
14855 static void
14856 dtrace_helper_action_destroy(dtrace_helper_action_t *helper,
14857     dtrace_vstate_t *vstate)
14858 {
14859 	int i;
14860 
14861 	if (helper->dtha_predicate != NULL)
14862 		dtrace_difo_release(helper->dtha_predicate, vstate);
14863 
14864 	for (i = 0; i < helper->dtha_nactions; i++) {
14865 		ASSERT(helper->dtha_actions[i] != NULL);
14866 		dtrace_difo_release(helper->dtha_actions[i], vstate);
14867 	}
14868 
14869 	kmem_free(helper->dtha_actions,
14870 	    helper->dtha_nactions * sizeof (dtrace_difo_t *));
14871 	kmem_free(helper, sizeof (dtrace_helper_action_t));
14872 }
14873 
14874 static int
14875 dtrace_helper_destroygen(int gen)
14876 {
14877 	proc_t *p = curproc;
14878 	dtrace_helpers_t *help = p->p_dtrace_helpers;
14879 	dtrace_vstate_t *vstate;
14880 	int i;
14881 
14882 	ASSERT(MUTEX_HELD(&dtrace_lock));
14883 
14884 	if (help == NULL || gen > help->dthps_generation)
14885 		return (EINVAL);
14886 
14887 	vstate = &help->dthps_vstate;
14888 
14889 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
14890 		dtrace_helper_action_t *last = NULL, *h, *next;
14891 
14892 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
14893 			next = h->dtha_next;
14894 
14895 			if (h->dtha_generation == gen) {
14896 				if (last != NULL) {
14897 					last->dtha_next = next;
14898 				} else {
14899 					help->dthps_actions[i] = next;
14900 				}
14901 
14902 				dtrace_helper_action_destroy(h, vstate);
14903 			} else {
14904 				last = h;
14905 			}
14906 		}
14907 	}
14908 
14909 	/*
14910 	 * Interate until we've cleared out all helper providers with the
14911 	 * given generation number.
14912 	 */
14913 	for (;;) {
14914 		dtrace_helper_provider_t *prov;
14915 
14916 		/*
14917 		 * Look for a helper provider with the right generation. We
14918 		 * have to start back at the beginning of the list each time
14919 		 * because we drop dtrace_lock. It's unlikely that we'll make
14920 		 * more than two passes.
14921 		 */
14922 		for (i = 0; i < help->dthps_nprovs; i++) {
14923 			prov = help->dthps_provs[i];
14924 
14925 			if (prov->dthp_generation == gen)
14926 				break;
14927 		}
14928 
14929 		/*
14930 		 * If there were no matches, we're done.
14931 		 */
14932 		if (i == help->dthps_nprovs)
14933 			break;
14934 
14935 		/*
14936 		 * Move the last helper provider into this slot.
14937 		 */
14938 		help->dthps_nprovs--;
14939 		help->dthps_provs[i] = help->dthps_provs[help->dthps_nprovs];
14940 		help->dthps_provs[help->dthps_nprovs] = NULL;
14941 
14942 		mutex_exit(&dtrace_lock);
14943 
14944 		/*
14945 		 * If we have a meta provider, remove this helper provider.
14946 		 */
14947 		mutex_enter(&dtrace_meta_lock);
14948 		if (dtrace_meta_pid != NULL) {
14949 			ASSERT(dtrace_deferred_pid == NULL);
14950 			dtrace_helper_provider_remove(&prov->dthp_prov,
14951 			    p->p_pid);
14952 		}
14953 		mutex_exit(&dtrace_meta_lock);
14954 
14955 		dtrace_helper_provider_destroy(prov);
14956 
14957 		mutex_enter(&dtrace_lock);
14958 	}
14959 
14960 	return (0);
14961 }
14962 
14963 static int
14964 dtrace_helper_validate(dtrace_helper_action_t *helper)
14965 {
14966 	int err = 0, i;
14967 	dtrace_difo_t *dp;
14968 
14969 	if ((dp = helper->dtha_predicate) != NULL)
14970 		err += dtrace_difo_validate_helper(dp);
14971 
14972 	for (i = 0; i < helper->dtha_nactions; i++)
14973 		err += dtrace_difo_validate_helper(helper->dtha_actions[i]);
14974 
14975 	return (err == 0);
14976 }
14977 
14978 static int
14979 dtrace_helper_action_add(int which, dtrace_ecbdesc_t *ep)
14980 {
14981 	dtrace_helpers_t *help;
14982 	dtrace_helper_action_t *helper, *last;
14983 	dtrace_actdesc_t *act;
14984 	dtrace_vstate_t *vstate;
14985 	dtrace_predicate_t *pred;
14986 	int count = 0, nactions = 0, i;
14987 
14988 	if (which < 0 || which >= DTRACE_NHELPER_ACTIONS)
14989 		return (EINVAL);
14990 
14991 	help = curproc->p_dtrace_helpers;
14992 	last = help->dthps_actions[which];
14993 	vstate = &help->dthps_vstate;
14994 
14995 	for (count = 0; last != NULL; last = last->dtha_next) {
14996 		count++;
14997 		if (last->dtha_next == NULL)
14998 			break;
14999 	}
15000 
15001 	/*
15002 	 * If we already have dtrace_helper_actions_max helper actions for this
15003 	 * helper action type, we'll refuse to add a new one.
15004 	 */
15005 	if (count >= dtrace_helper_actions_max)
15006 		return (ENOSPC);
15007 
15008 	helper = kmem_zalloc(sizeof (dtrace_helper_action_t), KM_SLEEP);
15009 	helper->dtha_generation = help->dthps_generation;
15010 
15011 	if ((pred = ep->dted_pred.dtpdd_predicate) != NULL) {
15012 		ASSERT(pred->dtp_difo != NULL);
15013 		dtrace_difo_hold(pred->dtp_difo);
15014 		helper->dtha_predicate = pred->dtp_difo;
15015 	}
15016 
15017 	for (act = ep->dted_action; act != NULL; act = act->dtad_next) {
15018 		if (act->dtad_kind != DTRACEACT_DIFEXPR)
15019 			goto err;
15020 
15021 		if (act->dtad_difo == NULL)
15022 			goto err;
15023 
15024 		nactions++;
15025 	}
15026 
15027 	helper->dtha_actions = kmem_zalloc(sizeof (dtrace_difo_t *) *
15028 	    (helper->dtha_nactions = nactions), KM_SLEEP);
15029 
15030 	for (act = ep->dted_action, i = 0; act != NULL; act = act->dtad_next) {
15031 		dtrace_difo_hold(act->dtad_difo);
15032 		helper->dtha_actions[i++] = act->dtad_difo;
15033 	}
15034 
15035 	if (!dtrace_helper_validate(helper))
15036 		goto err;
15037 
15038 	if (last == NULL) {
15039 		help->dthps_actions[which] = helper;
15040 	} else {
15041 		last->dtha_next = helper;
15042 	}
15043 
15044 	if (vstate->dtvs_nlocals > dtrace_helptrace_nlocals) {
15045 		dtrace_helptrace_nlocals = vstate->dtvs_nlocals;
15046 		dtrace_helptrace_next = 0;
15047 	}
15048 
15049 	return (0);
15050 err:
15051 	dtrace_helper_action_destroy(helper, vstate);
15052 	return (EINVAL);
15053 }
15054 
15055 static void
15056 dtrace_helper_provider_register(proc_t *p, dtrace_helpers_t *help,
15057     dof_helper_t *dofhp)
15058 {
15059 	ASSERT(MUTEX_NOT_HELD(&dtrace_lock));
15060 
15061 	mutex_enter(&dtrace_meta_lock);
15062 	mutex_enter(&dtrace_lock);
15063 
15064 	if (!dtrace_attached() || dtrace_meta_pid == NULL) {
15065 		/*
15066 		 * If the dtrace module is loaded but not attached, or if
15067 		 * there aren't isn't a meta provider registered to deal with
15068 		 * these provider descriptions, we need to postpone creating
15069 		 * the actual providers until later.
15070 		 */
15071 
15072 		if (help->dthps_next == NULL && help->dthps_prev == NULL &&
15073 		    dtrace_deferred_pid != help) {
15074 			help->dthps_deferred = 1;
15075 			help->dthps_pid = p->p_pid;
15076 			help->dthps_next = dtrace_deferred_pid;
15077 			help->dthps_prev = NULL;
15078 			if (dtrace_deferred_pid != NULL)
15079 				dtrace_deferred_pid->dthps_prev = help;
15080 			dtrace_deferred_pid = help;
15081 		}
15082 
15083 		mutex_exit(&dtrace_lock);
15084 
15085 	} else if (dofhp != NULL) {
15086 		/*
15087 		 * If the dtrace module is loaded and we have a particular
15088 		 * helper provider description, pass that off to the
15089 		 * meta provider.
15090 		 */
15091 
15092 		mutex_exit(&dtrace_lock);
15093 
15094 		dtrace_helper_provide(dofhp, p->p_pid);
15095 
15096 	} else {
15097 		/*
15098 		 * Otherwise, just pass all the helper provider descriptions
15099 		 * off to the meta provider.
15100 		 */
15101 
15102 		int i;
15103 		mutex_exit(&dtrace_lock);
15104 
15105 		for (i = 0; i < help->dthps_nprovs; i++) {
15106 			dtrace_helper_provide(&help->dthps_provs[i]->dthp_prov,
15107 			    p->p_pid);
15108 		}
15109 	}
15110 
15111 	mutex_exit(&dtrace_meta_lock);
15112 }
15113 
15114 static int
15115 dtrace_helper_provider_add(dof_helper_t *dofhp, int gen)
15116 {
15117 	dtrace_helpers_t *help;
15118 	dtrace_helper_provider_t *hprov, **tmp_provs;
15119 	uint_t tmp_maxprovs, i;
15120 
15121 	ASSERT(MUTEX_HELD(&dtrace_lock));
15122 
15123 	help = curproc->p_dtrace_helpers;
15124 	ASSERT(help != NULL);
15125 
15126 	/*
15127 	 * If we already have dtrace_helper_providers_max helper providers,
15128 	 * we're refuse to add a new one.
15129 	 */
15130 	if (help->dthps_nprovs >= dtrace_helper_providers_max)
15131 		return (ENOSPC);
15132 
15133 	/*
15134 	 * Check to make sure this isn't a duplicate.
15135 	 */
15136 	for (i = 0; i < help->dthps_nprovs; i++) {
15137 		if (dofhp->dofhp_addr ==
15138 		    help->dthps_provs[i]->dthp_prov.dofhp_addr)
15139 			return (EALREADY);
15140 	}
15141 
15142 	hprov = kmem_zalloc(sizeof (dtrace_helper_provider_t), KM_SLEEP);
15143 	hprov->dthp_prov = *dofhp;
15144 	hprov->dthp_ref = 1;
15145 	hprov->dthp_generation = gen;
15146 
15147 	/*
15148 	 * Allocate a bigger table for helper providers if it's already full.
15149 	 */
15150 	if (help->dthps_maxprovs == help->dthps_nprovs) {
15151 		tmp_maxprovs = help->dthps_maxprovs;
15152 		tmp_provs = help->dthps_provs;
15153 
15154 		if (help->dthps_maxprovs == 0)
15155 			help->dthps_maxprovs = 2;
15156 		else
15157 			help->dthps_maxprovs *= 2;
15158 		if (help->dthps_maxprovs > dtrace_helper_providers_max)
15159 			help->dthps_maxprovs = dtrace_helper_providers_max;
15160 
15161 		ASSERT(tmp_maxprovs < help->dthps_maxprovs);
15162 
15163 		help->dthps_provs = kmem_zalloc(help->dthps_maxprovs *
15164 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15165 
15166 		if (tmp_provs != NULL) {
15167 			bcopy(tmp_provs, help->dthps_provs, tmp_maxprovs *
15168 			    sizeof (dtrace_helper_provider_t *));
15169 			kmem_free(tmp_provs, tmp_maxprovs *
15170 			    sizeof (dtrace_helper_provider_t *));
15171 		}
15172 	}
15173 
15174 	help->dthps_provs[help->dthps_nprovs] = hprov;
15175 	help->dthps_nprovs++;
15176 
15177 	return (0);
15178 }
15179 
15180 static void
15181 dtrace_helper_provider_destroy(dtrace_helper_provider_t *hprov)
15182 {
15183 	mutex_enter(&dtrace_lock);
15184 
15185 	if (--hprov->dthp_ref == 0) {
15186 		dof_hdr_t *dof;
15187 		mutex_exit(&dtrace_lock);
15188 		dof = (dof_hdr_t *)(uintptr_t)hprov->dthp_prov.dofhp_dof;
15189 		dtrace_dof_destroy(dof);
15190 		kmem_free(hprov, sizeof (dtrace_helper_provider_t));
15191 	} else {
15192 		mutex_exit(&dtrace_lock);
15193 	}
15194 }
15195 
15196 static int
15197 dtrace_helper_provider_validate(dof_hdr_t *dof, dof_sec_t *sec)
15198 {
15199 	uintptr_t daddr = (uintptr_t)dof;
15200 	dof_sec_t *str_sec, *prb_sec, *arg_sec, *off_sec, *enoff_sec;
15201 	dof_provider_t *provider;
15202 	dof_probe_t *probe;
15203 	uint8_t *arg;
15204 	char *strtab, *typestr;
15205 	dof_stridx_t typeidx;
15206 	size_t typesz;
15207 	uint_t nprobes, j, k;
15208 
15209 	ASSERT(sec->dofs_type == DOF_SECT_PROVIDER);
15210 
15211 	if (sec->dofs_offset & (sizeof (uint_t) - 1)) {
15212 		dtrace_dof_error(dof, "misaligned section offset");
15213 		return (-1);
15214 	}
15215 
15216 	/*
15217 	 * The section needs to be large enough to contain the DOF provider
15218 	 * structure appropriate for the given version.
15219 	 */
15220 	if (sec->dofs_size <
15221 	    ((dof->dofh_ident[DOF_ID_VERSION] == DOF_VERSION_1) ?
15222 	    offsetof(dof_provider_t, dofpv_prenoffs) :
15223 	    sizeof (dof_provider_t))) {
15224 		dtrace_dof_error(dof, "provider section too small");
15225 		return (-1);
15226 	}
15227 
15228 	provider = (dof_provider_t *)(uintptr_t)(daddr + sec->dofs_offset);
15229 	str_sec = dtrace_dof_sect(dof, DOF_SECT_STRTAB, provider->dofpv_strtab);
15230 	prb_sec = dtrace_dof_sect(dof, DOF_SECT_PROBES, provider->dofpv_probes);
15231 	arg_sec = dtrace_dof_sect(dof, DOF_SECT_PRARGS, provider->dofpv_prargs);
15232 	off_sec = dtrace_dof_sect(dof, DOF_SECT_PROFFS, provider->dofpv_proffs);
15233 
15234 	if (str_sec == NULL || prb_sec == NULL ||
15235 	    arg_sec == NULL || off_sec == NULL)
15236 		return (-1);
15237 
15238 	enoff_sec = NULL;
15239 
15240 	if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1 &&
15241 	    provider->dofpv_prenoffs != DOF_SECT_NONE &&
15242 	    (enoff_sec = dtrace_dof_sect(dof, DOF_SECT_PRENOFFS,
15243 	    provider->dofpv_prenoffs)) == NULL)
15244 		return (-1);
15245 
15246 	strtab = (char *)(uintptr_t)(daddr + str_sec->dofs_offset);
15247 
15248 	if (provider->dofpv_name >= str_sec->dofs_size ||
15249 	    strlen(strtab + provider->dofpv_name) >= DTRACE_PROVNAMELEN) {
15250 		dtrace_dof_error(dof, "invalid provider name");
15251 		return (-1);
15252 	}
15253 
15254 	if (prb_sec->dofs_entsize == 0 ||
15255 	    prb_sec->dofs_entsize > prb_sec->dofs_size) {
15256 		dtrace_dof_error(dof, "invalid entry size");
15257 		return (-1);
15258 	}
15259 
15260 	if (prb_sec->dofs_entsize & (sizeof (uintptr_t) - 1)) {
15261 		dtrace_dof_error(dof, "misaligned entry size");
15262 		return (-1);
15263 	}
15264 
15265 	if (off_sec->dofs_entsize != sizeof (uint32_t)) {
15266 		dtrace_dof_error(dof, "invalid entry size");
15267 		return (-1);
15268 	}
15269 
15270 	if (off_sec->dofs_offset & (sizeof (uint32_t) - 1)) {
15271 		dtrace_dof_error(dof, "misaligned section offset");
15272 		return (-1);
15273 	}
15274 
15275 	if (arg_sec->dofs_entsize != sizeof (uint8_t)) {
15276 		dtrace_dof_error(dof, "invalid entry size");
15277 		return (-1);
15278 	}
15279 
15280 	arg = (uint8_t *)(uintptr_t)(daddr + arg_sec->dofs_offset);
15281 
15282 	nprobes = prb_sec->dofs_size / prb_sec->dofs_entsize;
15283 
15284 	/*
15285 	 * Take a pass through the probes to check for errors.
15286 	 */
15287 	for (j = 0; j < nprobes; j++) {
15288 		probe = (dof_probe_t *)(uintptr_t)(daddr +
15289 		    prb_sec->dofs_offset + j * prb_sec->dofs_entsize);
15290 
15291 		if (probe->dofpr_func >= str_sec->dofs_size) {
15292 			dtrace_dof_error(dof, "invalid function name");
15293 			return (-1);
15294 		}
15295 
15296 		if (strlen(strtab + probe->dofpr_func) >= DTRACE_FUNCNAMELEN) {
15297 			dtrace_dof_error(dof, "function name too long");
15298 			return (-1);
15299 		}
15300 
15301 		if (probe->dofpr_name >= str_sec->dofs_size ||
15302 		    strlen(strtab + probe->dofpr_name) >= DTRACE_NAMELEN) {
15303 			dtrace_dof_error(dof, "invalid probe name");
15304 			return (-1);
15305 		}
15306 
15307 		/*
15308 		 * The offset count must not wrap the index, and the offsets
15309 		 * must also not overflow the section's data.
15310 		 */
15311 		if (probe->dofpr_offidx + probe->dofpr_noffs <
15312 		    probe->dofpr_offidx ||
15313 		    (probe->dofpr_offidx + probe->dofpr_noffs) *
15314 		    off_sec->dofs_entsize > off_sec->dofs_size) {
15315 			dtrace_dof_error(dof, "invalid probe offset");
15316 			return (-1);
15317 		}
15318 
15319 		if (dof->dofh_ident[DOF_ID_VERSION] != DOF_VERSION_1) {
15320 			/*
15321 			 * If there's no is-enabled offset section, make sure
15322 			 * there aren't any is-enabled offsets. Otherwise
15323 			 * perform the same checks as for probe offsets
15324 			 * (immediately above).
15325 			 */
15326 			if (enoff_sec == NULL) {
15327 				if (probe->dofpr_enoffidx != 0 ||
15328 				    probe->dofpr_nenoffs != 0) {
15329 					dtrace_dof_error(dof, "is-enabled "
15330 					    "offsets with null section");
15331 					return (-1);
15332 				}
15333 			} else if (probe->dofpr_enoffidx +
15334 			    probe->dofpr_nenoffs < probe->dofpr_enoffidx ||
15335 			    (probe->dofpr_enoffidx + probe->dofpr_nenoffs) *
15336 			    enoff_sec->dofs_entsize > enoff_sec->dofs_size) {
15337 				dtrace_dof_error(dof, "invalid is-enabled "
15338 				    "offset");
15339 				return (-1);
15340 			}
15341 
15342 			if (probe->dofpr_noffs + probe->dofpr_nenoffs == 0) {
15343 				dtrace_dof_error(dof, "zero probe and "
15344 				    "is-enabled offsets");
15345 				return (-1);
15346 			}
15347 		} else if (probe->dofpr_noffs == 0) {
15348 			dtrace_dof_error(dof, "zero probe offsets");
15349 			return (-1);
15350 		}
15351 
15352 		if (probe->dofpr_argidx + probe->dofpr_xargc <
15353 		    probe->dofpr_argidx ||
15354 		    (probe->dofpr_argidx + probe->dofpr_xargc) *
15355 		    arg_sec->dofs_entsize > arg_sec->dofs_size) {
15356 			dtrace_dof_error(dof, "invalid args");
15357 			return (-1);
15358 		}
15359 
15360 		typeidx = probe->dofpr_nargv;
15361 		typestr = strtab + probe->dofpr_nargv;
15362 		for (k = 0; k < probe->dofpr_nargc; k++) {
15363 			if (typeidx >= str_sec->dofs_size) {
15364 				dtrace_dof_error(dof, "bad "
15365 				    "native argument type");
15366 				return (-1);
15367 			}
15368 
15369 			typesz = strlen(typestr) + 1;
15370 			if (typesz > DTRACE_ARGTYPELEN) {
15371 				dtrace_dof_error(dof, "native "
15372 				    "argument type too long");
15373 				return (-1);
15374 			}
15375 			typeidx += typesz;
15376 			typestr += typesz;
15377 		}
15378 
15379 		typeidx = probe->dofpr_xargv;
15380 		typestr = strtab + probe->dofpr_xargv;
15381 		for (k = 0; k < probe->dofpr_xargc; k++) {
15382 			if (arg[probe->dofpr_argidx + k] > probe->dofpr_nargc) {
15383 				dtrace_dof_error(dof, "bad "
15384 				    "native argument index");
15385 				return (-1);
15386 			}
15387 
15388 			if (typeidx >= str_sec->dofs_size) {
15389 				dtrace_dof_error(dof, "bad "
15390 				    "translated argument type");
15391 				return (-1);
15392 			}
15393 
15394 			typesz = strlen(typestr) + 1;
15395 			if (typesz > DTRACE_ARGTYPELEN) {
15396 				dtrace_dof_error(dof, "translated argument "
15397 				    "type too long");
15398 				return (-1);
15399 			}
15400 
15401 			typeidx += typesz;
15402 			typestr += typesz;
15403 		}
15404 	}
15405 
15406 	return (0);
15407 }
15408 
15409 static int
15410 dtrace_helper_slurp(dof_hdr_t *dof, dof_helper_t *dhp)
15411 {
15412 	dtrace_helpers_t *help;
15413 	dtrace_vstate_t *vstate;
15414 	dtrace_enabling_t *enab = NULL;
15415 	int i, gen, rv, nhelpers = 0, nprovs = 0, destroy = 1;
15416 	uintptr_t daddr = (uintptr_t)dof;
15417 
15418 	ASSERT(MUTEX_HELD(&dtrace_lock));
15419 
15420 	if ((help = curproc->p_dtrace_helpers) == NULL)
15421 		help = dtrace_helpers_create(curproc);
15422 
15423 	vstate = &help->dthps_vstate;
15424 
15425 	if ((rv = dtrace_dof_slurp(dof, vstate, NULL, &enab,
15426 	    dhp != NULL ? dhp->dofhp_addr : 0, B_FALSE)) != 0) {
15427 		dtrace_dof_destroy(dof);
15428 		return (rv);
15429 	}
15430 
15431 	/*
15432 	 * Look for helper providers and validate their descriptions.
15433 	 */
15434 	if (dhp != NULL) {
15435 		for (i = 0; i < dof->dofh_secnum; i++) {
15436 			dof_sec_t *sec = (dof_sec_t *)(uintptr_t)(daddr +
15437 			    dof->dofh_secoff + i * dof->dofh_secsize);
15438 
15439 			if (sec->dofs_type != DOF_SECT_PROVIDER)
15440 				continue;
15441 
15442 			if (dtrace_helper_provider_validate(dof, sec) != 0) {
15443 				dtrace_enabling_destroy(enab);
15444 				dtrace_dof_destroy(dof);
15445 				return (-1);
15446 			}
15447 
15448 			nprovs++;
15449 		}
15450 	}
15451 
15452 	/*
15453 	 * Now we need to walk through the ECB descriptions in the enabling.
15454 	 */
15455 	for (i = 0; i < enab->dten_ndesc; i++) {
15456 		dtrace_ecbdesc_t *ep = enab->dten_desc[i];
15457 		dtrace_probedesc_t *desc = &ep->dted_probe;
15458 
15459 		if (strcmp(desc->dtpd_provider, "dtrace") != 0)
15460 			continue;
15461 
15462 		if (strcmp(desc->dtpd_mod, "helper") != 0)
15463 			continue;
15464 
15465 		if (strcmp(desc->dtpd_func, "ustack") != 0)
15466 			continue;
15467 
15468 		if ((rv = dtrace_helper_action_add(DTRACE_HELPER_ACTION_USTACK,
15469 		    ep)) != 0) {
15470 			/*
15471 			 * Adding this helper action failed -- we are now going
15472 			 * to rip out the entire generation and return failure.
15473 			 */
15474 			(void) dtrace_helper_destroygen(help->dthps_generation);
15475 			dtrace_enabling_destroy(enab);
15476 			dtrace_dof_destroy(dof);
15477 			return (-1);
15478 		}
15479 
15480 		nhelpers++;
15481 	}
15482 
15483 	if (nhelpers < enab->dten_ndesc)
15484 		dtrace_dof_error(dof, "unmatched helpers");
15485 
15486 	gen = help->dthps_generation++;
15487 	dtrace_enabling_destroy(enab);
15488 
15489 	if (dhp != NULL && nprovs > 0) {
15490 		/*
15491 		 * Now that this is in-kernel, we change the sense of the
15492 		 * members:  dofhp_dof denotes the in-kernel copy of the DOF
15493 		 * and dofhp_addr denotes the address at user-level.
15494 		 */
15495 		dhp->dofhp_addr = dhp->dofhp_dof;
15496 		dhp->dofhp_dof = (uint64_t)(uintptr_t)dof;
15497 
15498 		if (dtrace_helper_provider_add(dhp, gen) == 0) {
15499 			mutex_exit(&dtrace_lock);
15500 			dtrace_helper_provider_register(curproc, help, dhp);
15501 			mutex_enter(&dtrace_lock);
15502 
15503 			destroy = 0;
15504 		}
15505 	}
15506 
15507 	if (destroy)
15508 		dtrace_dof_destroy(dof);
15509 
15510 	return (gen);
15511 }
15512 
15513 static dtrace_helpers_t *
15514 dtrace_helpers_create(proc_t *p)
15515 {
15516 	dtrace_helpers_t *help;
15517 
15518 	ASSERT(MUTEX_HELD(&dtrace_lock));
15519 	ASSERT(p->p_dtrace_helpers == NULL);
15520 
15521 	help = kmem_zalloc(sizeof (dtrace_helpers_t), KM_SLEEP);
15522 	help->dthps_actions = kmem_zalloc(sizeof (dtrace_helper_action_t *) *
15523 	    DTRACE_NHELPER_ACTIONS, KM_SLEEP);
15524 
15525 	p->p_dtrace_helpers = help;
15526 	dtrace_helpers++;
15527 
15528 	return (help);
15529 }
15530 
15531 static void
15532 dtrace_helpers_destroy(proc_t *p)
15533 {
15534 	dtrace_helpers_t *help;
15535 	dtrace_vstate_t *vstate;
15536 	int i;
15537 
15538 	mutex_enter(&dtrace_lock);
15539 
15540 	ASSERT(p->p_dtrace_helpers != NULL);
15541 	ASSERT(dtrace_helpers > 0);
15542 
15543 	help = p->p_dtrace_helpers;
15544 	vstate = &help->dthps_vstate;
15545 
15546 	/*
15547 	 * We're now going to lose the help from this process.
15548 	 */
15549 	p->p_dtrace_helpers = NULL;
15550 	if (p == curproc) {
15551 		dtrace_sync();
15552 	} else {
15553 		/*
15554 		 * It is sometimes necessary to clean up dtrace helpers from a
15555 		 * an incomplete child process as part of a failed fork
15556 		 * operation.  In such situations, a dtrace_sync() call should
15557 		 * be unnecessary as the process should be devoid of threads,
15558 		 * much less any in probe context.
15559 		 */
15560 		VERIFY(p->p_stat == SIDL);
15561 	}
15562 
15563 	/*
15564 	 * Destroy the helper actions.
15565 	 */
15566 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15567 		dtrace_helper_action_t *h, *next;
15568 
15569 		for (h = help->dthps_actions[i]; h != NULL; h = next) {
15570 			next = h->dtha_next;
15571 			dtrace_helper_action_destroy(h, vstate);
15572 			h = next;
15573 		}
15574 	}
15575 
15576 	mutex_exit(&dtrace_lock);
15577 
15578 	/*
15579 	 * Destroy the helper providers.
15580 	 */
15581 	if (help->dthps_maxprovs > 0) {
15582 		mutex_enter(&dtrace_meta_lock);
15583 		if (dtrace_meta_pid != NULL) {
15584 			ASSERT(dtrace_deferred_pid == NULL);
15585 
15586 			for (i = 0; i < help->dthps_nprovs; i++) {
15587 				dtrace_helper_provider_remove(
15588 				    &help->dthps_provs[i]->dthp_prov, p->p_pid);
15589 			}
15590 		} else {
15591 			mutex_enter(&dtrace_lock);
15592 			ASSERT(help->dthps_deferred == 0 ||
15593 			    help->dthps_next != NULL ||
15594 			    help->dthps_prev != NULL ||
15595 			    help == dtrace_deferred_pid);
15596 
15597 			/*
15598 			 * Remove the helper from the deferred list.
15599 			 */
15600 			if (help->dthps_next != NULL)
15601 				help->dthps_next->dthps_prev = help->dthps_prev;
15602 			if (help->dthps_prev != NULL)
15603 				help->dthps_prev->dthps_next = help->dthps_next;
15604 			if (dtrace_deferred_pid == help) {
15605 				dtrace_deferred_pid = help->dthps_next;
15606 				ASSERT(help->dthps_prev == NULL);
15607 			}
15608 
15609 			mutex_exit(&dtrace_lock);
15610 		}
15611 
15612 		mutex_exit(&dtrace_meta_lock);
15613 
15614 		for (i = 0; i < help->dthps_nprovs; i++) {
15615 			dtrace_helper_provider_destroy(help->dthps_provs[i]);
15616 		}
15617 
15618 		kmem_free(help->dthps_provs, help->dthps_maxprovs *
15619 		    sizeof (dtrace_helper_provider_t *));
15620 	}
15621 
15622 	mutex_enter(&dtrace_lock);
15623 
15624 	dtrace_vstate_fini(&help->dthps_vstate);
15625 	kmem_free(help->dthps_actions,
15626 	    sizeof (dtrace_helper_action_t *) * DTRACE_NHELPER_ACTIONS);
15627 	kmem_free(help, sizeof (dtrace_helpers_t));
15628 
15629 	--dtrace_helpers;
15630 	mutex_exit(&dtrace_lock);
15631 }
15632 
15633 static void
15634 dtrace_helpers_duplicate(proc_t *from, proc_t *to)
15635 {
15636 	dtrace_helpers_t *help, *newhelp;
15637 	dtrace_helper_action_t *helper, *new, *last;
15638 	dtrace_difo_t *dp;
15639 	dtrace_vstate_t *vstate;
15640 	int i, j, sz, hasprovs = 0;
15641 
15642 	mutex_enter(&dtrace_lock);
15643 	ASSERT(from->p_dtrace_helpers != NULL);
15644 	ASSERT(dtrace_helpers > 0);
15645 
15646 	help = from->p_dtrace_helpers;
15647 	newhelp = dtrace_helpers_create(to);
15648 	ASSERT(to->p_dtrace_helpers != NULL);
15649 
15650 	newhelp->dthps_generation = help->dthps_generation;
15651 	vstate = &newhelp->dthps_vstate;
15652 
15653 	/*
15654 	 * Duplicate the helper actions.
15655 	 */
15656 	for (i = 0; i < DTRACE_NHELPER_ACTIONS; i++) {
15657 		if ((helper = help->dthps_actions[i]) == NULL)
15658 			continue;
15659 
15660 		for (last = NULL; helper != NULL; helper = helper->dtha_next) {
15661 			new = kmem_zalloc(sizeof (dtrace_helper_action_t),
15662 			    KM_SLEEP);
15663 			new->dtha_generation = helper->dtha_generation;
15664 
15665 			if ((dp = helper->dtha_predicate) != NULL) {
15666 				dp = dtrace_difo_duplicate(dp, vstate);
15667 				new->dtha_predicate = dp;
15668 			}
15669 
15670 			new->dtha_nactions = helper->dtha_nactions;
15671 			sz = sizeof (dtrace_difo_t *) * new->dtha_nactions;
15672 			new->dtha_actions = kmem_alloc(sz, KM_SLEEP);
15673 
15674 			for (j = 0; j < new->dtha_nactions; j++) {
15675 				dtrace_difo_t *dp = helper->dtha_actions[j];
15676 
15677 				ASSERT(dp != NULL);
15678 				dp = dtrace_difo_duplicate(dp, vstate);
15679 				new->dtha_actions[j] = dp;
15680 			}
15681 
15682 			if (last != NULL) {
15683 				last->dtha_next = new;
15684 			} else {
15685 				newhelp->dthps_actions[i] = new;
15686 			}
15687 
15688 			last = new;
15689 		}
15690 	}
15691 
15692 	/*
15693 	 * Duplicate the helper providers and register them with the
15694 	 * DTrace framework.
15695 	 */
15696 	if (help->dthps_nprovs > 0) {
15697 		newhelp->dthps_nprovs = help->dthps_nprovs;
15698 		newhelp->dthps_maxprovs = help->dthps_nprovs;
15699 		newhelp->dthps_provs = kmem_alloc(newhelp->dthps_nprovs *
15700 		    sizeof (dtrace_helper_provider_t *), KM_SLEEP);
15701 		for (i = 0; i < newhelp->dthps_nprovs; i++) {
15702 			newhelp->dthps_provs[i] = help->dthps_provs[i];
15703 			newhelp->dthps_provs[i]->dthp_ref++;
15704 		}
15705 
15706 		hasprovs = 1;
15707 	}
15708 
15709 	mutex_exit(&dtrace_lock);
15710 
15711 	if (hasprovs)
15712 		dtrace_helper_provider_register(to, newhelp, NULL);
15713 }
15714 
15715 /*
15716  * DTrace Hook Functions
15717  */
15718 static void
15719 dtrace_module_loaded(struct modctl *ctl)
15720 {
15721 	dtrace_provider_t *prv;
15722 
15723 	mutex_enter(&dtrace_provider_lock);
15724 	mutex_enter(&mod_lock);
15725 
15726 	ASSERT(ctl->mod_busy);
15727 
15728 	/*
15729 	 * We're going to call each providers per-module provide operation
15730 	 * specifying only this module.
15731 	 */
15732 	for (prv = dtrace_provider; prv != NULL; prv = prv->dtpv_next)
15733 		prv->dtpv_pops.dtps_provide_module(prv->dtpv_arg, ctl);
15734 
15735 	mutex_exit(&mod_lock);
15736 	mutex_exit(&dtrace_provider_lock);
15737 
15738 	/*
15739 	 * If we have any retained enablings, we need to match against them.
15740 	 * Enabling probes requires that cpu_lock be held, and we cannot hold
15741 	 * cpu_lock here -- it is legal for cpu_lock to be held when loading a
15742 	 * module.  (In particular, this happens when loading scheduling
15743 	 * classes.)  So if we have any retained enablings, we need to dispatch
15744 	 * our task queue to do the match for us.
15745 	 */
15746 	mutex_enter(&dtrace_lock);
15747 
15748 	if (dtrace_retained == NULL) {
15749 		mutex_exit(&dtrace_lock);
15750 		return;
15751 	}
15752 
15753 	(void) taskq_dispatch(dtrace_taskq,
15754 	    (task_func_t *)dtrace_enabling_matchall, NULL, TQ_SLEEP);
15755 
15756 	mutex_exit(&dtrace_lock);
15757 
15758 	/*
15759 	 * And now, for a little heuristic sleaze:  in general, we want to
15760 	 * match modules as soon as they load.  However, we cannot guarantee
15761 	 * this, because it would lead us to the lock ordering violation
15762 	 * outlined above.  The common case, of course, is that cpu_lock is
15763 	 * _not_ held -- so we delay here for a clock tick, hoping that that's
15764 	 * long enough for the task queue to do its work.  If it's not, it's
15765 	 * not a serious problem -- it just means that the module that we
15766 	 * just loaded may not be immediately instrumentable.
15767 	 */
15768 	delay(1);
15769 }
15770 
15771 static void
15772 dtrace_module_unloaded(struct modctl *ctl)
15773 {
15774 	dtrace_probe_t template, *probe, *first, *next;
15775 	dtrace_provider_t *prov;
15776 
15777 	template.dtpr_mod = ctl->mod_modname;
15778 
15779 	mutex_enter(&dtrace_provider_lock);
15780 	mutex_enter(&mod_lock);
15781 	mutex_enter(&dtrace_lock);
15782 
15783 	if (dtrace_bymod == NULL) {
15784 		/*
15785 		 * The DTrace module is loaded (obviously) but not attached;
15786 		 * we don't have any work to do.
15787 		 */
15788 		mutex_exit(&dtrace_provider_lock);
15789 		mutex_exit(&mod_lock);
15790 		mutex_exit(&dtrace_lock);
15791 		return;
15792 	}
15793 
15794 	for (probe = first = dtrace_hash_lookup(dtrace_bymod, &template);
15795 	    probe != NULL; probe = probe->dtpr_nextmod) {
15796 		if (probe->dtpr_ecb != NULL) {
15797 			mutex_exit(&dtrace_provider_lock);
15798 			mutex_exit(&mod_lock);
15799 			mutex_exit(&dtrace_lock);
15800 
15801 			/*
15802 			 * This shouldn't _actually_ be possible -- we're
15803 			 * unloading a module that has an enabled probe in it.
15804 			 * (It's normally up to the provider to make sure that
15805 			 * this can't happen.)  However, because dtps_enable()
15806 			 * doesn't have a failure mode, there can be an
15807 			 * enable/unload race.  Upshot:  we don't want to
15808 			 * assert, but we're not going to disable the
15809 			 * probe, either.
15810 			 */
15811 			if (dtrace_err_verbose) {
15812 				cmn_err(CE_WARN, "unloaded module '%s' had "
15813 				    "enabled probes", ctl->mod_modname);
15814 			}
15815 
15816 			return;
15817 		}
15818 	}
15819 
15820 	probe = first;
15821 
15822 	for (first = NULL; probe != NULL; probe = next) {
15823 		ASSERT(dtrace_probes[probe->dtpr_id - 1] == probe);
15824 
15825 		dtrace_probes[probe->dtpr_id - 1] = NULL;
15826 
15827 		next = probe->dtpr_nextmod;
15828 		dtrace_hash_remove(dtrace_bymod, probe);
15829 		dtrace_hash_remove(dtrace_byfunc, probe);
15830 		dtrace_hash_remove(dtrace_byname, probe);
15831 
15832 		if (first == NULL) {
15833 			first = probe;
15834 			probe->dtpr_nextmod = NULL;
15835 		} else {
15836 			probe->dtpr_nextmod = first;
15837 			first = probe;
15838 		}
15839 	}
15840 
15841 	/*
15842 	 * We've removed all of the module's probes from the hash chains and
15843 	 * from the probe array.  Now issue a dtrace_sync() to be sure that
15844 	 * everyone has cleared out from any probe array processing.
15845 	 */
15846 	dtrace_sync();
15847 
15848 	for (probe = first; probe != NULL; probe = first) {
15849 		first = probe->dtpr_nextmod;
15850 		prov = probe->dtpr_provider;
15851 		prov->dtpv_pops.dtps_destroy(prov->dtpv_arg, probe->dtpr_id,
15852 		    probe->dtpr_arg);
15853 		kmem_free(probe->dtpr_mod, strlen(probe->dtpr_mod) + 1);
15854 		kmem_free(probe->dtpr_func, strlen(probe->dtpr_func) + 1);
15855 		kmem_free(probe->dtpr_name, strlen(probe->dtpr_name) + 1);
15856 		vmem_free(dtrace_arena, (void *)(uintptr_t)probe->dtpr_id, 1);
15857 		kmem_free(probe, sizeof (dtrace_probe_t));
15858 	}
15859 
15860 	mutex_exit(&dtrace_lock);
15861 	mutex_exit(&mod_lock);
15862 	mutex_exit(&dtrace_provider_lock);
15863 }
15864 
15865 void
15866 dtrace_suspend(void)
15867 {
15868 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_suspend));
15869 }
15870 
15871 void
15872 dtrace_resume(void)
15873 {
15874 	dtrace_probe_foreach(offsetof(dtrace_pops_t, dtps_resume));
15875 }
15876 
15877 static int
15878 dtrace_cpu_setup(cpu_setup_t what, processorid_t cpu)
15879 {
15880 	ASSERT(MUTEX_HELD(&cpu_lock));
15881 	mutex_enter(&dtrace_lock);
15882 
15883 	switch (what) {
15884 	case CPU_CONFIG: {
15885 		dtrace_state_t *state;
15886 		dtrace_optval_t *opt, rs, c;
15887 
15888 		/*
15889 		 * For now, we only allocate a new buffer for anonymous state.
15890 		 */
15891 		if ((state = dtrace_anon.dta_state) == NULL)
15892 			break;
15893 
15894 		if (state->dts_activity != DTRACE_ACTIVITY_ACTIVE)
15895 			break;
15896 
15897 		opt = state->dts_options;
15898 		c = opt[DTRACEOPT_CPU];
15899 
15900 		if (c != DTRACE_CPUALL && c != DTRACEOPT_UNSET && c != cpu)
15901 			break;
15902 
15903 		/*
15904 		 * Regardless of what the actual policy is, we're going to
15905 		 * temporarily set our resize policy to be manual.  We're
15906 		 * also going to temporarily set our CPU option to denote
15907 		 * the newly configured CPU.
15908 		 */
15909 		rs = opt[DTRACEOPT_BUFRESIZE];
15910 		opt[DTRACEOPT_BUFRESIZE] = DTRACEOPT_BUFRESIZE_MANUAL;
15911 		opt[DTRACEOPT_CPU] = (dtrace_optval_t)cpu;
15912 
15913 		(void) dtrace_state_buffers(state);
15914 
15915 		opt[DTRACEOPT_BUFRESIZE] = rs;
15916 		opt[DTRACEOPT_CPU] = c;
15917 
15918 		break;
15919 	}
15920 
15921 	case CPU_UNCONFIG:
15922 		/*
15923 		 * We don't free the buffer in the CPU_UNCONFIG case.  (The
15924 		 * buffer will be freed when the consumer exits.)
15925 		 */
15926 		break;
15927 
15928 	default:
15929 		break;
15930 	}
15931 
15932 	mutex_exit(&dtrace_lock);
15933 	return (0);
15934 }
15935 
15936 static void
15937 dtrace_cpu_setup_initial(processorid_t cpu)
15938 {
15939 	(void) dtrace_cpu_setup(CPU_CONFIG, cpu);
15940 }
15941 
15942 static void
15943 dtrace_toxrange_add(uintptr_t base, uintptr_t limit)
15944 {
15945 	if (dtrace_toxranges >= dtrace_toxranges_max) {
15946 		int osize, nsize;
15947 		dtrace_toxrange_t *range;
15948 
15949 		osize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15950 
15951 		if (osize == 0) {
15952 			ASSERT(dtrace_toxrange == NULL);
15953 			ASSERT(dtrace_toxranges_max == 0);
15954 			dtrace_toxranges_max = 1;
15955 		} else {
15956 			dtrace_toxranges_max <<= 1;
15957 		}
15958 
15959 		nsize = dtrace_toxranges_max * sizeof (dtrace_toxrange_t);
15960 		range = kmem_zalloc(nsize, KM_SLEEP);
15961 
15962 		if (dtrace_toxrange != NULL) {
15963 			ASSERT(osize != 0);
15964 			bcopy(dtrace_toxrange, range, osize);
15965 			kmem_free(dtrace_toxrange, osize);
15966 		}
15967 
15968 		dtrace_toxrange = range;
15969 	}
15970 
15971 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_base == (uintptr_t)NULL);
15972 	ASSERT(dtrace_toxrange[dtrace_toxranges].dtt_limit == (uintptr_t)NULL);
15973 
15974 	dtrace_toxrange[dtrace_toxranges].dtt_base = base;
15975 	dtrace_toxrange[dtrace_toxranges].dtt_limit = limit;
15976 	dtrace_toxranges++;
15977 }
15978 
15979 static void
15980 dtrace_getf_barrier()
15981 {
15982 	/*
15983 	 * When we have unprivileged (that is, non-DTRACE_CRV_KERNEL) enablings
15984 	 * that contain calls to getf(), this routine will be called on every
15985 	 * closef() before either the underlying vnode is released or the
15986 	 * file_t itself is freed.  By the time we are here, it is essential
15987 	 * that the file_t can no longer be accessed from a call to getf()
15988 	 * in probe context -- that assures that a dtrace_sync() can be used
15989 	 * to clear out any enablings referring to the old structures.
15990 	 */
15991 	if (curthread->t_procp->p_zone->zone_dtrace_getf != 0 ||
15992 	    kcred->cr_zone->zone_dtrace_getf != 0)
15993 		dtrace_sync();
15994 }
15995 
15996 /*
15997  * DTrace Driver Cookbook Functions
15998  */
15999 /*ARGSUSED*/
16000 static int
16001 dtrace_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
16002 {
16003 	dtrace_provider_id_t id;
16004 	dtrace_state_t *state = NULL;
16005 	dtrace_enabling_t *enab;
16006 
16007 	mutex_enter(&cpu_lock);
16008 	mutex_enter(&dtrace_provider_lock);
16009 	mutex_enter(&dtrace_lock);
16010 
16011 	if (ddi_soft_state_init(&dtrace_softstate,
16012 	    sizeof (dtrace_state_t), 0) != 0) {
16013 		cmn_err(CE_NOTE, "/dev/dtrace failed to initialize soft state");
16014 		mutex_exit(&cpu_lock);
16015 		mutex_exit(&dtrace_provider_lock);
16016 		mutex_exit(&dtrace_lock);
16017 		return (DDI_FAILURE);
16018 	}
16019 
16020 	if (ddi_create_minor_node(devi, DTRACEMNR_DTRACE, S_IFCHR,
16021 	    DTRACEMNRN_DTRACE, DDI_PSEUDO, 0) == DDI_FAILURE ||
16022 	    ddi_create_minor_node(devi, DTRACEMNR_HELPER, S_IFCHR,
16023 	    DTRACEMNRN_HELPER, DDI_PSEUDO, 0) == DDI_FAILURE) {
16024 		cmn_err(CE_NOTE, "/dev/dtrace couldn't create minor nodes");
16025 		ddi_remove_minor_node(devi, NULL);
16026 		ddi_soft_state_fini(&dtrace_softstate);
16027 		mutex_exit(&cpu_lock);
16028 		mutex_exit(&dtrace_provider_lock);
16029 		mutex_exit(&dtrace_lock);
16030 		return (DDI_FAILURE);
16031 	}
16032 
16033 	ddi_report_dev(devi);
16034 	dtrace_devi = devi;
16035 
16036 	dtrace_modload = dtrace_module_loaded;
16037 	dtrace_modunload = dtrace_module_unloaded;
16038 	dtrace_cpu_init = dtrace_cpu_setup_initial;
16039 	dtrace_helpers_cleanup = dtrace_helpers_destroy;
16040 	dtrace_helpers_fork = dtrace_helpers_duplicate;
16041 	dtrace_cpustart_init = dtrace_suspend;
16042 	dtrace_cpustart_fini = dtrace_resume;
16043 	dtrace_debugger_init = dtrace_suspend;
16044 	dtrace_debugger_fini = dtrace_resume;
16045 
16046 	register_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
16047 
16048 	ASSERT(MUTEX_HELD(&cpu_lock));
16049 
16050 	dtrace_arena = vmem_create("dtrace", (void *)1, UINT32_MAX, 1,
16051 	    NULL, NULL, NULL, 0, VM_SLEEP | VMC_IDENTIFIER);
16052 	dtrace_minor = vmem_create("dtrace_minor", (void *)DTRACEMNRN_CLONE,
16053 	    UINT32_MAX - DTRACEMNRN_CLONE, 1, NULL, NULL, NULL, 0,
16054 	    VM_SLEEP | VMC_IDENTIFIER);
16055 	dtrace_taskq = taskq_create("dtrace_taskq", 1, maxclsyspri,
16056 	    1, INT_MAX, 0);
16057 
16058 	dtrace_state_cache = kmem_cache_create("dtrace_state_cache",
16059 	    sizeof (dtrace_dstate_percpu_t) * NCPU, DTRACE_STATE_ALIGN,
16060 	    NULL, NULL, NULL, NULL, NULL, 0);
16061 
16062 	ASSERT(MUTEX_HELD(&cpu_lock));
16063 	dtrace_bymod = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_mod),
16064 	    offsetof(dtrace_probe_t, dtpr_nextmod),
16065 	    offsetof(dtrace_probe_t, dtpr_prevmod));
16066 
16067 	dtrace_byfunc = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_func),
16068 	    offsetof(dtrace_probe_t, dtpr_nextfunc),
16069 	    offsetof(dtrace_probe_t, dtpr_prevfunc));
16070 
16071 	dtrace_byname = dtrace_hash_create(offsetof(dtrace_probe_t, dtpr_name),
16072 	    offsetof(dtrace_probe_t, dtpr_nextname),
16073 	    offsetof(dtrace_probe_t, dtpr_prevname));
16074 
16075 	if (dtrace_retain_max < 1) {
16076 		cmn_err(CE_WARN, "illegal value (%lu) for dtrace_retain_max; "
16077 		    "setting to 1", dtrace_retain_max);
16078 		dtrace_retain_max = 1;
16079 	}
16080 
16081 	/*
16082 	 * Now discover our toxic ranges.
16083 	 */
16084 	dtrace_toxic_ranges(dtrace_toxrange_add);
16085 
16086 	/*
16087 	 * Before we register ourselves as a provider to our own framework,
16088 	 * we would like to assert that dtrace_provider is NULL -- but that's
16089 	 * not true if we were loaded as a dependency of a DTrace provider.
16090 	 * Once we've registered, we can assert that dtrace_provider is our
16091 	 * pseudo provider.
16092 	 */
16093 	(void) dtrace_register("dtrace", &dtrace_provider_attr,
16094 	    DTRACE_PRIV_NONE, 0, &dtrace_provider_ops, NULL, &id);
16095 
16096 	ASSERT(dtrace_provider != NULL);
16097 	ASSERT((dtrace_provider_id_t)dtrace_provider == id);
16098 
16099 	dtrace_probeid_begin = dtrace_probe_create((dtrace_provider_id_t)
16100 	    dtrace_provider, NULL, NULL, "BEGIN", 0, NULL);
16101 	dtrace_probeid_end = dtrace_probe_create((dtrace_provider_id_t)
16102 	    dtrace_provider, NULL, NULL, "END", 0, NULL);
16103 	dtrace_probeid_error = dtrace_probe_create((dtrace_provider_id_t)
16104 	    dtrace_provider, NULL, NULL, "ERROR", 1, NULL);
16105 
16106 	dtrace_anon_property();
16107 	mutex_exit(&cpu_lock);
16108 
16109 	/*
16110 	 * If there are already providers, we must ask them to provide their
16111 	 * probes, and then match any anonymous enabling against them.  Note
16112 	 * that there should be no other retained enablings at this time:
16113 	 * the only retained enablings at this time should be the anonymous
16114 	 * enabling.
16115 	 */
16116 	if (dtrace_anon.dta_enabling != NULL) {
16117 		ASSERT(dtrace_retained == dtrace_anon.dta_enabling);
16118 
16119 		dtrace_enabling_provide(NULL);
16120 		state = dtrace_anon.dta_state;
16121 
16122 		/*
16123 		 * We couldn't hold cpu_lock across the above call to
16124 		 * dtrace_enabling_provide(), but we must hold it to actually
16125 		 * enable the probes.  We have to drop all of our locks, pick
16126 		 * up cpu_lock, and regain our locks before matching the
16127 		 * retained anonymous enabling.
16128 		 */
16129 		mutex_exit(&dtrace_lock);
16130 		mutex_exit(&dtrace_provider_lock);
16131 
16132 		mutex_enter(&cpu_lock);
16133 		mutex_enter(&dtrace_provider_lock);
16134 		mutex_enter(&dtrace_lock);
16135 
16136 		if ((enab = dtrace_anon.dta_enabling) != NULL)
16137 			(void) dtrace_enabling_match(enab, NULL);
16138 
16139 		mutex_exit(&cpu_lock);
16140 	}
16141 
16142 	mutex_exit(&dtrace_lock);
16143 	mutex_exit(&dtrace_provider_lock);
16144 
16145 	if (state != NULL) {
16146 		/*
16147 		 * If we created any anonymous state, set it going now.
16148 		 */
16149 		(void) dtrace_state_go(state, &dtrace_anon.dta_beganon);
16150 	}
16151 
16152 	return (DDI_SUCCESS);
16153 }
16154 
16155 /*ARGSUSED*/
16156 static int
16157 dtrace_open(dev_t *devp, int flag, int otyp, cred_t *cred_p)
16158 {
16159 	dtrace_state_t *state;
16160 	uint32_t priv;
16161 	uid_t uid;
16162 	zoneid_t zoneid;
16163 
16164 	if (getminor(*devp) == DTRACEMNRN_HELPER)
16165 		return (0);
16166 
16167 	/*
16168 	 * If this wasn't an open with the "helper" minor, then it must be
16169 	 * the "dtrace" minor.
16170 	 */
16171 	if (getminor(*devp) != DTRACEMNRN_DTRACE)
16172 		return (ENXIO);
16173 
16174 	/*
16175 	 * If no DTRACE_PRIV_* bits are set in the credential, then the
16176 	 * caller lacks sufficient permission to do anything with DTrace.
16177 	 */
16178 	dtrace_cred2priv(cred_p, &priv, &uid, &zoneid);
16179 	if (priv == DTRACE_PRIV_NONE)
16180 		return (EACCES);
16181 
16182 	/*
16183 	 * Ask all providers to provide all their probes.
16184 	 */
16185 	mutex_enter(&dtrace_provider_lock);
16186 	dtrace_probe_provide(NULL, NULL);
16187 	mutex_exit(&dtrace_provider_lock);
16188 
16189 	mutex_enter(&cpu_lock);
16190 	mutex_enter(&dtrace_lock);
16191 	dtrace_opens++;
16192 	dtrace_membar_producer();
16193 
16194 	/*
16195 	 * If the kernel debugger is active (that is, if the kernel debugger
16196 	 * modified text in some way), we won't allow the open.
16197 	 */
16198 	if (kdi_dtrace_set(KDI_DTSET_DTRACE_ACTIVATE) != 0) {
16199 		dtrace_opens--;
16200 		mutex_exit(&cpu_lock);
16201 		mutex_exit(&dtrace_lock);
16202 		return (EBUSY);
16203 	}
16204 
16205 	if (dtrace_helptrace_enable && dtrace_helptrace_buffer == NULL) {
16206 		/*
16207 		 * If DTrace helper tracing is enabled, we need to allocate the
16208 		 * trace buffer and initialize the values.
16209 		 */
16210 		dtrace_helptrace_buffer =
16211 		    kmem_zalloc(dtrace_helptrace_bufsize, KM_SLEEP);
16212 		dtrace_helptrace_next = 0;
16213 		dtrace_helptrace_wrapped = 0;
16214 		dtrace_helptrace_enable = 0;
16215 	}
16216 
16217 	state = dtrace_state_create(devp, cred_p);
16218 	mutex_exit(&cpu_lock);
16219 
16220 	if (state == NULL) {
16221 		if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16222 			(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16223 		mutex_exit(&dtrace_lock);
16224 		return (EAGAIN);
16225 	}
16226 
16227 	mutex_exit(&dtrace_lock);
16228 
16229 	return (0);
16230 }
16231 
16232 /*ARGSUSED*/
16233 static int
16234 dtrace_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
16235 {
16236 	minor_t minor = getminor(dev);
16237 	dtrace_state_t *state;
16238 	dtrace_helptrace_t *buf = NULL;
16239 
16240 	if (minor == DTRACEMNRN_HELPER)
16241 		return (0);
16242 
16243 	state = ddi_get_soft_state(dtrace_softstate, minor);
16244 
16245 	mutex_enter(&cpu_lock);
16246 	mutex_enter(&dtrace_lock);
16247 
16248 	if (state->dts_anon) {
16249 		/*
16250 		 * There is anonymous state. Destroy that first.
16251 		 */
16252 		ASSERT(dtrace_anon.dta_state == NULL);
16253 		dtrace_state_destroy(state->dts_anon);
16254 	}
16255 
16256 	if (dtrace_helptrace_disable) {
16257 		/*
16258 		 * If we have been told to disable helper tracing, set the
16259 		 * buffer to NULL before calling into dtrace_state_destroy();
16260 		 * we take advantage of its dtrace_sync() to know that no
16261 		 * CPU is in probe context with enabled helper tracing
16262 		 * after it returns.
16263 		 */
16264 		buf = dtrace_helptrace_buffer;
16265 		dtrace_helptrace_buffer = NULL;
16266 	}
16267 
16268 	dtrace_state_destroy(state);
16269 	ASSERT(dtrace_opens > 0);
16270 
16271 	/*
16272 	 * Only relinquish control of the kernel debugger interface when there
16273 	 * are no consumers and no anonymous enablings.
16274 	 */
16275 	if (--dtrace_opens == 0 && dtrace_anon.dta_enabling == NULL)
16276 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
16277 
16278 	if (buf != NULL) {
16279 		kmem_free(buf, dtrace_helptrace_bufsize);
16280 		dtrace_helptrace_disable = 0;
16281 	}
16282 
16283 	mutex_exit(&dtrace_lock);
16284 	mutex_exit(&cpu_lock);
16285 
16286 	return (0);
16287 }
16288 
16289 /*ARGSUSED*/
16290 static int
16291 dtrace_ioctl_helper(int cmd, intptr_t arg, int *rv)
16292 {
16293 	int rval;
16294 	dof_helper_t help, *dhp = NULL;
16295 
16296 	switch (cmd) {
16297 	case DTRACEHIOC_ADDDOF:
16298 		if (copyin((void *)arg, &help, sizeof (help)) != 0) {
16299 			dtrace_dof_error(NULL, "failed to copyin DOF helper");
16300 			return (EFAULT);
16301 		}
16302 
16303 		dhp = &help;
16304 		arg = (intptr_t)help.dofhp_dof;
16305 		/*FALLTHROUGH*/
16306 
16307 	case DTRACEHIOC_ADD: {
16308 		dof_hdr_t *dof = dtrace_dof_copyin(arg, &rval);
16309 
16310 		if (dof == NULL)
16311 			return (rval);
16312 
16313 		mutex_enter(&dtrace_lock);
16314 
16315 		/*
16316 		 * dtrace_helper_slurp() takes responsibility for the dof --
16317 		 * it may free it now or it may save it and free it later.
16318 		 */
16319 		if ((rval = dtrace_helper_slurp(dof, dhp)) != -1) {
16320 			*rv = rval;
16321 			rval = 0;
16322 		} else {
16323 			rval = EINVAL;
16324 		}
16325 
16326 		mutex_exit(&dtrace_lock);
16327 		return (rval);
16328 	}
16329 
16330 	case DTRACEHIOC_REMOVE: {
16331 		mutex_enter(&dtrace_lock);
16332 		rval = dtrace_helper_destroygen(arg);
16333 		mutex_exit(&dtrace_lock);
16334 
16335 		return (rval);
16336 	}
16337 
16338 	default:
16339 		break;
16340 	}
16341 
16342 	return (ENOTTY);
16343 }
16344 
16345 /*ARGSUSED*/
16346 static int
16347 dtrace_ioctl(dev_t dev, int cmd, intptr_t arg, int md, cred_t *cr, int *rv)
16348 {
16349 	minor_t minor = getminor(dev);
16350 	dtrace_state_t *state;
16351 	int rval;
16352 
16353 	if (minor == DTRACEMNRN_HELPER)
16354 		return (dtrace_ioctl_helper(cmd, arg, rv));
16355 
16356 	state = ddi_get_soft_state(dtrace_softstate, minor);
16357 
16358 	if (state->dts_anon) {
16359 		ASSERT(dtrace_anon.dta_state == NULL);
16360 		state = state->dts_anon;
16361 	}
16362 
16363 	switch (cmd) {
16364 	case DTRACEIOC_PROVIDER: {
16365 		dtrace_providerdesc_t pvd;
16366 		dtrace_provider_t *pvp;
16367 
16368 		if (copyin((void *)arg, &pvd, sizeof (pvd)) != 0)
16369 			return (EFAULT);
16370 
16371 		pvd.dtvd_name[DTRACE_PROVNAMELEN - 1] = '\0';
16372 		mutex_enter(&dtrace_provider_lock);
16373 
16374 		for (pvp = dtrace_provider; pvp != NULL; pvp = pvp->dtpv_next) {
16375 			if (strcmp(pvp->dtpv_name, pvd.dtvd_name) == 0)
16376 				break;
16377 		}
16378 
16379 		mutex_exit(&dtrace_provider_lock);
16380 
16381 		if (pvp == NULL)
16382 			return (ESRCH);
16383 
16384 		bcopy(&pvp->dtpv_priv, &pvd.dtvd_priv, sizeof (dtrace_ppriv_t));
16385 		bcopy(&pvp->dtpv_attr, &pvd.dtvd_attr, sizeof (dtrace_pattr_t));
16386 		if (copyout(&pvd, (void *)arg, sizeof (pvd)) != 0)
16387 			return (EFAULT);
16388 
16389 		return (0);
16390 	}
16391 
16392 	case DTRACEIOC_EPROBE: {
16393 		dtrace_eprobedesc_t epdesc;
16394 		dtrace_ecb_t *ecb;
16395 		dtrace_action_t *act;
16396 		void *buf;
16397 		size_t size;
16398 		uintptr_t dest;
16399 		int nrecs;
16400 
16401 		if (copyin((void *)arg, &epdesc, sizeof (epdesc)) != 0)
16402 			return (EFAULT);
16403 
16404 		mutex_enter(&dtrace_lock);
16405 
16406 		if ((ecb = dtrace_epid2ecb(state, epdesc.dtepd_epid)) == NULL) {
16407 			mutex_exit(&dtrace_lock);
16408 			return (EINVAL);
16409 		}
16410 
16411 		if (ecb->dte_probe == NULL) {
16412 			mutex_exit(&dtrace_lock);
16413 			return (EINVAL);
16414 		}
16415 
16416 		epdesc.dtepd_probeid = ecb->dte_probe->dtpr_id;
16417 		epdesc.dtepd_uarg = ecb->dte_uarg;
16418 		epdesc.dtepd_size = ecb->dte_size;
16419 
16420 		nrecs = epdesc.dtepd_nrecs;
16421 		epdesc.dtepd_nrecs = 0;
16422 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16423 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16424 				continue;
16425 
16426 			epdesc.dtepd_nrecs++;
16427 		}
16428 
16429 		/*
16430 		 * Now that we have the size, we need to allocate a temporary
16431 		 * buffer in which to store the complete description.  We need
16432 		 * the temporary buffer to be able to drop dtrace_lock()
16433 		 * across the copyout(), below.
16434 		 */
16435 		size = sizeof (dtrace_eprobedesc_t) +
16436 		    (epdesc.dtepd_nrecs * sizeof (dtrace_recdesc_t));
16437 
16438 		buf = kmem_alloc(size, KM_SLEEP);
16439 		dest = (uintptr_t)buf;
16440 
16441 		bcopy(&epdesc, (void *)dest, sizeof (epdesc));
16442 		dest += offsetof(dtrace_eprobedesc_t, dtepd_rec[0]);
16443 
16444 		for (act = ecb->dte_action; act != NULL; act = act->dta_next) {
16445 			if (DTRACEACT_ISAGG(act->dta_kind) || act->dta_intuple)
16446 				continue;
16447 
16448 			if (nrecs-- == 0)
16449 				break;
16450 
16451 			bcopy(&act->dta_rec, (void *)dest,
16452 			    sizeof (dtrace_recdesc_t));
16453 			dest += sizeof (dtrace_recdesc_t);
16454 		}
16455 
16456 		mutex_exit(&dtrace_lock);
16457 
16458 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16459 			kmem_free(buf, size);
16460 			return (EFAULT);
16461 		}
16462 
16463 		kmem_free(buf, size);
16464 		return (0);
16465 	}
16466 
16467 	case DTRACEIOC_AGGDESC: {
16468 		dtrace_aggdesc_t aggdesc;
16469 		dtrace_action_t *act;
16470 		dtrace_aggregation_t *agg;
16471 		int nrecs;
16472 		uint32_t offs;
16473 		dtrace_recdesc_t *lrec;
16474 		void *buf;
16475 		size_t size;
16476 		uintptr_t dest;
16477 
16478 		if (copyin((void *)arg, &aggdesc, sizeof (aggdesc)) != 0)
16479 			return (EFAULT);
16480 
16481 		mutex_enter(&dtrace_lock);
16482 
16483 		if ((agg = dtrace_aggid2agg(state, aggdesc.dtagd_id)) == NULL) {
16484 			mutex_exit(&dtrace_lock);
16485 			return (EINVAL);
16486 		}
16487 
16488 		aggdesc.dtagd_epid = agg->dtag_ecb->dte_epid;
16489 
16490 		nrecs = aggdesc.dtagd_nrecs;
16491 		aggdesc.dtagd_nrecs = 0;
16492 
16493 		offs = agg->dtag_base;
16494 		lrec = &agg->dtag_action.dta_rec;
16495 		aggdesc.dtagd_size = lrec->dtrd_offset + lrec->dtrd_size - offs;
16496 
16497 		for (act = agg->dtag_first; ; act = act->dta_next) {
16498 			ASSERT(act->dta_intuple ||
16499 			    DTRACEACT_ISAGG(act->dta_kind));
16500 
16501 			/*
16502 			 * If this action has a record size of zero, it
16503 			 * denotes an argument to the aggregating action.
16504 			 * Because the presence of this record doesn't (or
16505 			 * shouldn't) affect the way the data is interpreted,
16506 			 * we don't copy it out to save user-level the
16507 			 * confusion of dealing with a zero-length record.
16508 			 */
16509 			if (act->dta_rec.dtrd_size == 0) {
16510 				ASSERT(agg->dtag_hasarg);
16511 				continue;
16512 			}
16513 
16514 			aggdesc.dtagd_nrecs++;
16515 
16516 			if (act == &agg->dtag_action)
16517 				break;
16518 		}
16519 
16520 		/*
16521 		 * Now that we have the size, we need to allocate a temporary
16522 		 * buffer in which to store the complete description.  We need
16523 		 * the temporary buffer to be able to drop dtrace_lock()
16524 		 * across the copyout(), below.
16525 		 */
16526 		size = sizeof (dtrace_aggdesc_t) +
16527 		    (aggdesc.dtagd_nrecs * sizeof (dtrace_recdesc_t));
16528 
16529 		buf = kmem_alloc(size, KM_SLEEP);
16530 		dest = (uintptr_t)buf;
16531 
16532 		bcopy(&aggdesc, (void *)dest, sizeof (aggdesc));
16533 		dest += offsetof(dtrace_aggdesc_t, dtagd_rec[0]);
16534 
16535 		for (act = agg->dtag_first; ; act = act->dta_next) {
16536 			dtrace_recdesc_t rec = act->dta_rec;
16537 
16538 			/*
16539 			 * See the comment in the above loop for why we pass
16540 			 * over zero-length records.
16541 			 */
16542 			if (rec.dtrd_size == 0) {
16543 				ASSERT(agg->dtag_hasarg);
16544 				continue;
16545 			}
16546 
16547 			if (nrecs-- == 0)
16548 				break;
16549 
16550 			rec.dtrd_offset -= offs;
16551 			bcopy(&rec, (void *)dest, sizeof (rec));
16552 			dest += sizeof (dtrace_recdesc_t);
16553 
16554 			if (act == &agg->dtag_action)
16555 				break;
16556 		}
16557 
16558 		mutex_exit(&dtrace_lock);
16559 
16560 		if (copyout(buf, (void *)arg, dest - (uintptr_t)buf) != 0) {
16561 			kmem_free(buf, size);
16562 			return (EFAULT);
16563 		}
16564 
16565 		kmem_free(buf, size);
16566 		return (0);
16567 	}
16568 
16569 	case DTRACEIOC_ENABLE: {
16570 		dof_hdr_t *dof;
16571 		dtrace_enabling_t *enab = NULL;
16572 		dtrace_vstate_t *vstate;
16573 		int err = 0;
16574 
16575 		*rv = 0;
16576 
16577 		/*
16578 		 * If a NULL argument has been passed, we take this as our
16579 		 * cue to reevaluate our enablings.
16580 		 */
16581 		if (arg == 0) {
16582 			dtrace_enabling_matchall();
16583 
16584 			return (0);
16585 		}
16586 
16587 		if ((dof = dtrace_dof_copyin(arg, &rval)) == NULL)
16588 			return (rval);
16589 
16590 		mutex_enter(&cpu_lock);
16591 		mutex_enter(&dtrace_lock);
16592 		vstate = &state->dts_vstate;
16593 
16594 		if (state->dts_activity != DTRACE_ACTIVITY_INACTIVE) {
16595 			mutex_exit(&dtrace_lock);
16596 			mutex_exit(&cpu_lock);
16597 			dtrace_dof_destroy(dof);
16598 			return (EBUSY);
16599 		}
16600 
16601 		if (dtrace_dof_slurp(dof, vstate, cr, &enab, 0, B_TRUE) != 0) {
16602 			mutex_exit(&dtrace_lock);
16603 			mutex_exit(&cpu_lock);
16604 			dtrace_dof_destroy(dof);
16605 			return (EINVAL);
16606 		}
16607 
16608 		if ((rval = dtrace_dof_options(dof, state)) != 0) {
16609 			dtrace_enabling_destroy(enab);
16610 			mutex_exit(&dtrace_lock);
16611 			mutex_exit(&cpu_lock);
16612 			dtrace_dof_destroy(dof);
16613 			return (rval);
16614 		}
16615 
16616 		if ((err = dtrace_enabling_match(enab, rv)) == 0) {
16617 			err = dtrace_enabling_retain(enab);
16618 		} else {
16619 			dtrace_enabling_destroy(enab);
16620 		}
16621 
16622 		mutex_exit(&cpu_lock);
16623 		mutex_exit(&dtrace_lock);
16624 		dtrace_dof_destroy(dof);
16625 
16626 		return (err);
16627 	}
16628 
16629 	case DTRACEIOC_REPLICATE: {
16630 		dtrace_repldesc_t desc;
16631 		dtrace_probedesc_t *match = &desc.dtrpd_match;
16632 		dtrace_probedesc_t *create = &desc.dtrpd_create;
16633 		int err;
16634 
16635 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16636 			return (EFAULT);
16637 
16638 		match->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16639 		match->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16640 		match->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16641 		match->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16642 
16643 		create->dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16644 		create->dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16645 		create->dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16646 		create->dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16647 
16648 		mutex_enter(&dtrace_lock);
16649 		err = dtrace_enabling_replicate(state, match, create);
16650 		mutex_exit(&dtrace_lock);
16651 
16652 		return (err);
16653 	}
16654 
16655 	case DTRACEIOC_PROBEMATCH:
16656 	case DTRACEIOC_PROBES: {
16657 		dtrace_probe_t *probe = NULL;
16658 		dtrace_probedesc_t desc;
16659 		dtrace_probekey_t pkey;
16660 		dtrace_id_t i;
16661 		int m = 0;
16662 		uint32_t priv;
16663 		uid_t uid;
16664 		zoneid_t zoneid;
16665 
16666 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16667 			return (EFAULT);
16668 
16669 		desc.dtpd_provider[DTRACE_PROVNAMELEN - 1] = '\0';
16670 		desc.dtpd_mod[DTRACE_MODNAMELEN - 1] = '\0';
16671 		desc.dtpd_func[DTRACE_FUNCNAMELEN - 1] = '\0';
16672 		desc.dtpd_name[DTRACE_NAMELEN - 1] = '\0';
16673 
16674 		/*
16675 		 * Before we attempt to match this probe, we want to give
16676 		 * all providers the opportunity to provide it.
16677 		 */
16678 		if (desc.dtpd_id == DTRACE_IDNONE) {
16679 			mutex_enter(&dtrace_provider_lock);
16680 			dtrace_probe_provide(&desc, NULL);
16681 			mutex_exit(&dtrace_provider_lock);
16682 			desc.dtpd_id++;
16683 		}
16684 
16685 		if (cmd == DTRACEIOC_PROBEMATCH)  {
16686 			dtrace_probekey(&desc, &pkey);
16687 			pkey.dtpk_id = DTRACE_IDNONE;
16688 		}
16689 
16690 		dtrace_cred2priv(cr, &priv, &uid, &zoneid);
16691 
16692 		mutex_enter(&dtrace_lock);
16693 
16694 		if (cmd == DTRACEIOC_PROBEMATCH) {
16695 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16696 				if ((probe = dtrace_probes[i - 1]) != NULL &&
16697 				    (m = dtrace_match_probe(probe, &pkey,
16698 				    priv, uid, zoneid)) != 0)
16699 					break;
16700 			}
16701 
16702 			if (m < 0) {
16703 				mutex_exit(&dtrace_lock);
16704 				return (EINVAL);
16705 			}
16706 
16707 		} else {
16708 			for (i = desc.dtpd_id; i <= dtrace_nprobes; i++) {
16709 				if ((probe = dtrace_probes[i - 1]) != NULL &&
16710 				    dtrace_match_priv(probe, priv, uid, zoneid))
16711 					break;
16712 			}
16713 		}
16714 
16715 		if (probe == NULL) {
16716 			mutex_exit(&dtrace_lock);
16717 			return (ESRCH);
16718 		}
16719 
16720 		dtrace_probe_description(probe, &desc);
16721 		mutex_exit(&dtrace_lock);
16722 
16723 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16724 			return (EFAULT);
16725 
16726 		return (0);
16727 	}
16728 
16729 	case DTRACEIOC_PROBEARG: {
16730 		dtrace_argdesc_t desc;
16731 		dtrace_probe_t *probe;
16732 		dtrace_provider_t *prov;
16733 
16734 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16735 			return (EFAULT);
16736 
16737 		if (desc.dtargd_id == DTRACE_IDNONE)
16738 			return (EINVAL);
16739 
16740 		if (desc.dtargd_ndx == DTRACE_ARGNONE)
16741 			return (EINVAL);
16742 
16743 		mutex_enter(&dtrace_provider_lock);
16744 		mutex_enter(&mod_lock);
16745 		mutex_enter(&dtrace_lock);
16746 
16747 		if (desc.dtargd_id > dtrace_nprobes) {
16748 			mutex_exit(&dtrace_lock);
16749 			mutex_exit(&mod_lock);
16750 			mutex_exit(&dtrace_provider_lock);
16751 			return (EINVAL);
16752 		}
16753 
16754 		if ((probe = dtrace_probes[desc.dtargd_id - 1]) == NULL) {
16755 			mutex_exit(&dtrace_lock);
16756 			mutex_exit(&mod_lock);
16757 			mutex_exit(&dtrace_provider_lock);
16758 			return (EINVAL);
16759 		}
16760 
16761 		mutex_exit(&dtrace_lock);
16762 
16763 		prov = probe->dtpr_provider;
16764 
16765 		if (prov->dtpv_pops.dtps_getargdesc == NULL) {
16766 			/*
16767 			 * There isn't any typed information for this probe.
16768 			 * Set the argument number to DTRACE_ARGNONE.
16769 			 */
16770 			desc.dtargd_ndx = DTRACE_ARGNONE;
16771 		} else {
16772 			desc.dtargd_native[0] = '\0';
16773 			desc.dtargd_xlate[0] = '\0';
16774 			desc.dtargd_mapping = desc.dtargd_ndx;
16775 
16776 			prov->dtpv_pops.dtps_getargdesc(prov->dtpv_arg,
16777 			    probe->dtpr_id, probe->dtpr_arg, &desc);
16778 		}
16779 
16780 		mutex_exit(&mod_lock);
16781 		mutex_exit(&dtrace_provider_lock);
16782 
16783 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16784 			return (EFAULT);
16785 
16786 		return (0);
16787 	}
16788 
16789 	case DTRACEIOC_GO: {
16790 		processorid_t cpuid;
16791 		rval = dtrace_state_go(state, &cpuid);
16792 
16793 		if (rval != 0)
16794 			return (rval);
16795 
16796 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16797 			return (EFAULT);
16798 
16799 		return (0);
16800 	}
16801 
16802 	case DTRACEIOC_STOP: {
16803 		processorid_t cpuid;
16804 
16805 		mutex_enter(&dtrace_lock);
16806 		rval = dtrace_state_stop(state, &cpuid);
16807 		mutex_exit(&dtrace_lock);
16808 
16809 		if (rval != 0)
16810 			return (rval);
16811 
16812 		if (copyout(&cpuid, (void *)arg, sizeof (cpuid)) != 0)
16813 			return (EFAULT);
16814 
16815 		return (0);
16816 	}
16817 
16818 	case DTRACEIOC_DOFGET: {
16819 		dof_hdr_t hdr, *dof;
16820 		uint64_t len;
16821 
16822 		if (copyin((void *)arg, &hdr, sizeof (hdr)) != 0)
16823 			return (EFAULT);
16824 
16825 		mutex_enter(&dtrace_lock);
16826 		dof = dtrace_dof_create(state);
16827 		mutex_exit(&dtrace_lock);
16828 
16829 		len = MIN(hdr.dofh_loadsz, dof->dofh_loadsz);
16830 		rval = copyout(dof, (void *)arg, len);
16831 		dtrace_dof_destroy(dof);
16832 
16833 		return (rval == 0 ? 0 : EFAULT);
16834 	}
16835 
16836 	case DTRACEIOC_AGGSNAP:
16837 	case DTRACEIOC_BUFSNAP: {
16838 		dtrace_bufdesc_t desc;
16839 		caddr_t cached;
16840 		dtrace_buffer_t *buf;
16841 
16842 		if (copyin((void *)arg, &desc, sizeof (desc)) != 0)
16843 			return (EFAULT);
16844 
16845 		if (desc.dtbd_cpu < 0 || desc.dtbd_cpu >= NCPU)
16846 			return (EINVAL);
16847 
16848 		mutex_enter(&dtrace_lock);
16849 
16850 		if (cmd == DTRACEIOC_BUFSNAP) {
16851 			buf = &state->dts_buffer[desc.dtbd_cpu];
16852 		} else {
16853 			buf = &state->dts_aggbuffer[desc.dtbd_cpu];
16854 		}
16855 
16856 		if (buf->dtb_flags & (DTRACEBUF_RING | DTRACEBUF_FILL)) {
16857 			size_t sz = buf->dtb_offset;
16858 
16859 			if (state->dts_activity != DTRACE_ACTIVITY_STOPPED) {
16860 				mutex_exit(&dtrace_lock);
16861 				return (EBUSY);
16862 			}
16863 
16864 			/*
16865 			 * If this buffer has already been consumed, we're
16866 			 * going to indicate that there's nothing left here
16867 			 * to consume.
16868 			 */
16869 			if (buf->dtb_flags & DTRACEBUF_CONSUMED) {
16870 				mutex_exit(&dtrace_lock);
16871 
16872 				desc.dtbd_size = 0;
16873 				desc.dtbd_drops = 0;
16874 				desc.dtbd_errors = 0;
16875 				desc.dtbd_oldest = 0;
16876 				sz = sizeof (desc);
16877 
16878 				if (copyout(&desc, (void *)arg, sz) != 0)
16879 					return (EFAULT);
16880 
16881 				return (0);
16882 			}
16883 
16884 			/*
16885 			 * If this is a ring buffer that has wrapped, we want
16886 			 * to copy the whole thing out.
16887 			 */
16888 			if (buf->dtb_flags & DTRACEBUF_WRAPPED) {
16889 				dtrace_buffer_polish(buf);
16890 				sz = buf->dtb_size;
16891 			}
16892 
16893 			if (copyout(buf->dtb_tomax, desc.dtbd_data, sz) != 0) {
16894 				mutex_exit(&dtrace_lock);
16895 				return (EFAULT);
16896 			}
16897 
16898 			desc.dtbd_size = sz;
16899 			desc.dtbd_drops = buf->dtb_drops;
16900 			desc.dtbd_errors = buf->dtb_errors;
16901 			desc.dtbd_oldest = buf->dtb_xamot_offset;
16902 			desc.dtbd_timestamp = dtrace_gethrtime();
16903 
16904 			mutex_exit(&dtrace_lock);
16905 
16906 			if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16907 				return (EFAULT);
16908 
16909 			buf->dtb_flags |= DTRACEBUF_CONSUMED;
16910 
16911 			return (0);
16912 		}
16913 
16914 		if (buf->dtb_tomax == NULL) {
16915 			ASSERT(buf->dtb_xamot == NULL);
16916 			mutex_exit(&dtrace_lock);
16917 			return (ENOENT);
16918 		}
16919 
16920 		cached = buf->dtb_tomax;
16921 		ASSERT(!(buf->dtb_flags & DTRACEBUF_NOSWITCH));
16922 
16923 		dtrace_xcall(desc.dtbd_cpu,
16924 		    (dtrace_xcall_t)dtrace_buffer_switch, buf);
16925 
16926 		state->dts_errors += buf->dtb_xamot_errors;
16927 
16928 		/*
16929 		 * If the buffers did not actually switch, then the cross call
16930 		 * did not take place -- presumably because the given CPU is
16931 		 * not in the ready set.  If this is the case, we'll return
16932 		 * ENOENT.
16933 		 */
16934 		if (buf->dtb_tomax == cached) {
16935 			ASSERT(buf->dtb_xamot != cached);
16936 			mutex_exit(&dtrace_lock);
16937 			return (ENOENT);
16938 		}
16939 
16940 		ASSERT(cached == buf->dtb_xamot);
16941 
16942 		/*
16943 		 * We have our snapshot; now copy it out.
16944 		 */
16945 		if (copyout(buf->dtb_xamot, desc.dtbd_data,
16946 		    buf->dtb_xamot_offset) != 0) {
16947 			mutex_exit(&dtrace_lock);
16948 			return (EFAULT);
16949 		}
16950 
16951 		desc.dtbd_size = buf->dtb_xamot_offset;
16952 		desc.dtbd_drops = buf->dtb_xamot_drops;
16953 		desc.dtbd_errors = buf->dtb_xamot_errors;
16954 		desc.dtbd_oldest = 0;
16955 		desc.dtbd_timestamp = buf->dtb_switched;
16956 
16957 		mutex_exit(&dtrace_lock);
16958 
16959 		/*
16960 		 * Finally, copy out the buffer description.
16961 		 */
16962 		if (copyout(&desc, (void *)arg, sizeof (desc)) != 0)
16963 			return (EFAULT);
16964 
16965 		return (0);
16966 	}
16967 
16968 	case DTRACEIOC_CONF: {
16969 		dtrace_conf_t conf;
16970 
16971 		bzero(&conf, sizeof (conf));
16972 		conf.dtc_difversion = DIF_VERSION;
16973 		conf.dtc_difintregs = DIF_DIR_NREGS;
16974 		conf.dtc_diftupregs = DIF_DTR_NREGS;
16975 		conf.dtc_ctfmodel = CTF_MODEL_NATIVE;
16976 
16977 		if (copyout(&conf, (void *)arg, sizeof (conf)) != 0)
16978 			return (EFAULT);
16979 
16980 		return (0);
16981 	}
16982 
16983 	case DTRACEIOC_STATUS: {
16984 		dtrace_status_t stat;
16985 		dtrace_dstate_t *dstate;
16986 		int i, j;
16987 		uint64_t nerrs;
16988 
16989 		/*
16990 		 * See the comment in dtrace_state_deadman() for the reason
16991 		 * for setting dts_laststatus to INT64_MAX before setting
16992 		 * it to the correct value.
16993 		 */
16994 		state->dts_laststatus = INT64_MAX;
16995 		dtrace_membar_producer();
16996 		state->dts_laststatus = dtrace_gethrtime();
16997 
16998 		bzero(&stat, sizeof (stat));
16999 
17000 		mutex_enter(&dtrace_lock);
17001 
17002 		if (state->dts_activity == DTRACE_ACTIVITY_INACTIVE) {
17003 			mutex_exit(&dtrace_lock);
17004 			return (ENOENT);
17005 		}
17006 
17007 		if (state->dts_activity == DTRACE_ACTIVITY_DRAINING)
17008 			stat.dtst_exiting = 1;
17009 
17010 		nerrs = state->dts_errors;
17011 		dstate = &state->dts_vstate.dtvs_dynvars;
17012 
17013 		for (i = 0; i < NCPU; i++) {
17014 			dtrace_dstate_percpu_t *dcpu = &dstate->dtds_percpu[i];
17015 
17016 			stat.dtst_dyndrops += dcpu->dtdsc_drops;
17017 			stat.dtst_dyndrops_dirty += dcpu->dtdsc_dirty_drops;
17018 			stat.dtst_dyndrops_rinsing += dcpu->dtdsc_rinsing_drops;
17019 
17020 			if (state->dts_buffer[i].dtb_flags & DTRACEBUF_FULL)
17021 				stat.dtst_filled++;
17022 
17023 			nerrs += state->dts_buffer[i].dtb_errors;
17024 
17025 			for (j = 0; j < state->dts_nspeculations; j++) {
17026 				dtrace_speculation_t *spec;
17027 				dtrace_buffer_t *buf;
17028 
17029 				spec = &state->dts_speculations[j];
17030 				buf = &spec->dtsp_buffer[i];
17031 				stat.dtst_specdrops += buf->dtb_xamot_drops;
17032 			}
17033 		}
17034 
17035 		stat.dtst_specdrops_busy = state->dts_speculations_busy;
17036 		stat.dtst_specdrops_unavail = state->dts_speculations_unavail;
17037 		stat.dtst_stkstroverflows = state->dts_stkstroverflows;
17038 		stat.dtst_dblerrors = state->dts_dblerrors;
17039 		stat.dtst_killed =
17040 		    (state->dts_activity == DTRACE_ACTIVITY_KILLED);
17041 		stat.dtst_errors = nerrs;
17042 
17043 		mutex_exit(&dtrace_lock);
17044 
17045 		if (copyout(&stat, (void *)arg, sizeof (stat)) != 0)
17046 			return (EFAULT);
17047 
17048 		return (0);
17049 	}
17050 
17051 	case DTRACEIOC_FORMAT: {
17052 		dtrace_fmtdesc_t fmt;
17053 		char *str;
17054 		int len;
17055 
17056 		if (copyin((void *)arg, &fmt, sizeof (fmt)) != 0)
17057 			return (EFAULT);
17058 
17059 		mutex_enter(&dtrace_lock);
17060 
17061 		if (fmt.dtfd_format == 0 ||
17062 		    fmt.dtfd_format > state->dts_nformats) {
17063 			mutex_exit(&dtrace_lock);
17064 			return (EINVAL);
17065 		}
17066 
17067 		/*
17068 		 * Format strings are allocated contiguously and they are
17069 		 * never freed; if a format index is less than the number
17070 		 * of formats, we can assert that the format map is non-NULL
17071 		 * and that the format for the specified index is non-NULL.
17072 		 */
17073 		ASSERT(state->dts_formats != NULL);
17074 		str = state->dts_formats[fmt.dtfd_format - 1];
17075 		ASSERT(str != NULL);
17076 
17077 		len = strlen(str) + 1;
17078 
17079 		if (len > fmt.dtfd_length) {
17080 			fmt.dtfd_length = len;
17081 
17082 			if (copyout(&fmt, (void *)arg, sizeof (fmt)) != 0) {
17083 				mutex_exit(&dtrace_lock);
17084 				return (EINVAL);
17085 			}
17086 		} else {
17087 			if (copyout(str, fmt.dtfd_string, len) != 0) {
17088 				mutex_exit(&dtrace_lock);
17089 				return (EINVAL);
17090 			}
17091 		}
17092 
17093 		mutex_exit(&dtrace_lock);
17094 		return (0);
17095 	}
17096 
17097 	default:
17098 		break;
17099 	}
17100 
17101 	return (ENOTTY);
17102 }
17103 
17104 /*ARGSUSED*/
17105 static int
17106 dtrace_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
17107 {
17108 	dtrace_state_t *state;
17109 
17110 	switch (cmd) {
17111 	case DDI_DETACH:
17112 		break;
17113 
17114 	case DDI_SUSPEND:
17115 		return (DDI_SUCCESS);
17116 
17117 	default:
17118 		return (DDI_FAILURE);
17119 	}
17120 
17121 	mutex_enter(&cpu_lock);
17122 	mutex_enter(&dtrace_provider_lock);
17123 	mutex_enter(&dtrace_lock);
17124 
17125 	ASSERT(dtrace_opens == 0);
17126 
17127 	if (dtrace_helpers > 0) {
17128 		mutex_exit(&dtrace_provider_lock);
17129 		mutex_exit(&dtrace_lock);
17130 		mutex_exit(&cpu_lock);
17131 		return (DDI_FAILURE);
17132 	}
17133 
17134 	if (dtrace_unregister((dtrace_provider_id_t)dtrace_provider) != 0) {
17135 		mutex_exit(&dtrace_provider_lock);
17136 		mutex_exit(&dtrace_lock);
17137 		mutex_exit(&cpu_lock);
17138 		return (DDI_FAILURE);
17139 	}
17140 
17141 	dtrace_provider = NULL;
17142 
17143 	if ((state = dtrace_anon_grab()) != NULL) {
17144 		/*
17145 		 * If there were ECBs on this state, the provider should
17146 		 * have not been allowed to detach; assert that there is
17147 		 * none.
17148 		 */
17149 		ASSERT(state->dts_necbs == 0);
17150 		dtrace_state_destroy(state);
17151 
17152 		/*
17153 		 * If we're being detached with anonymous state, we need to
17154 		 * indicate to the kernel debugger that DTrace is now inactive.
17155 		 */
17156 		(void) kdi_dtrace_set(KDI_DTSET_DTRACE_DEACTIVATE);
17157 	}
17158 
17159 	bzero(&dtrace_anon, sizeof (dtrace_anon_t));
17160 	unregister_cpu_setup_func((cpu_setup_func_t *)dtrace_cpu_setup, NULL);
17161 	dtrace_cpu_init = NULL;
17162 	dtrace_helpers_cleanup = NULL;
17163 	dtrace_helpers_fork = NULL;
17164 	dtrace_cpustart_init = NULL;
17165 	dtrace_cpustart_fini = NULL;
17166 	dtrace_debugger_init = NULL;
17167 	dtrace_debugger_fini = NULL;
17168 	dtrace_modload = NULL;
17169 	dtrace_modunload = NULL;
17170 
17171 	ASSERT(dtrace_getf == 0);
17172 	ASSERT(dtrace_closef == NULL);
17173 
17174 	mutex_exit(&cpu_lock);
17175 
17176 	kmem_free(dtrace_probes, dtrace_nprobes * sizeof (dtrace_probe_t *));
17177 	dtrace_probes = NULL;
17178 	dtrace_nprobes = 0;
17179 
17180 	dtrace_hash_destroy(dtrace_bymod);
17181 	dtrace_hash_destroy(dtrace_byfunc);
17182 	dtrace_hash_destroy(dtrace_byname);
17183 	dtrace_bymod = NULL;
17184 	dtrace_byfunc = NULL;
17185 	dtrace_byname = NULL;
17186 
17187 	kmem_cache_destroy(dtrace_state_cache);
17188 	vmem_destroy(dtrace_minor);
17189 	vmem_destroy(dtrace_arena);
17190 
17191 	if (dtrace_toxrange != NULL) {
17192 		kmem_free(dtrace_toxrange,
17193 		    dtrace_toxranges_max * sizeof (dtrace_toxrange_t));
17194 		dtrace_toxrange = NULL;
17195 		dtrace_toxranges = 0;
17196 		dtrace_toxranges_max = 0;
17197 	}
17198 
17199 	ddi_remove_minor_node(dtrace_devi, NULL);
17200 	dtrace_devi = NULL;
17201 
17202 	ddi_soft_state_fini(&dtrace_softstate);
17203 
17204 	ASSERT(dtrace_vtime_references == 0);
17205 	ASSERT(dtrace_opens == 0);
17206 	ASSERT(dtrace_retained == NULL);
17207 
17208 	mutex_exit(&dtrace_lock);
17209 	mutex_exit(&dtrace_provider_lock);
17210 
17211 	/*
17212 	 * We don't destroy the task queue until after we have dropped our
17213 	 * locks (taskq_destroy() may block on running tasks).  To prevent
17214 	 * attempting to do work after we have effectively detached but before
17215 	 * the task queue has been destroyed, all tasks dispatched via the
17216 	 * task queue must check that DTrace is still attached before
17217 	 * performing any operation.
17218 	 */
17219 	taskq_destroy(dtrace_taskq);
17220 	dtrace_taskq = NULL;
17221 
17222 	return (DDI_SUCCESS);
17223 }
17224 
17225 /*ARGSUSED*/
17226 static int
17227 dtrace_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
17228 {
17229 	int error;
17230 
17231 	switch (infocmd) {
17232 	case DDI_INFO_DEVT2DEVINFO:
17233 		*result = (void *)dtrace_devi;
17234 		error = DDI_SUCCESS;
17235 		break;
17236 	case DDI_INFO_DEVT2INSTANCE:
17237 		*result = (void *)0;
17238 		error = DDI_SUCCESS;
17239 		break;
17240 	default:
17241 		error = DDI_FAILURE;
17242 	}
17243 	return (error);
17244 }
17245 
17246 static struct cb_ops dtrace_cb_ops = {
17247 	dtrace_open,		/* open */
17248 	dtrace_close,		/* close */
17249 	nulldev,		/* strategy */
17250 	nulldev,		/* print */
17251 	nodev,			/* dump */
17252 	nodev,			/* read */
17253 	nodev,			/* write */
17254 	dtrace_ioctl,		/* ioctl */
17255 	nodev,			/* devmap */
17256 	nodev,			/* mmap */
17257 	nodev,			/* segmap */
17258 	nochpoll,		/* poll */
17259 	ddi_prop_op,		/* cb_prop_op */
17260 	0,			/* streamtab  */
17261 	D_NEW | D_MP		/* Driver compatibility flag */
17262 };
17263 
17264 static struct dev_ops dtrace_ops = {
17265 	DEVO_REV,		/* devo_rev */
17266 	0,			/* refcnt */
17267 	dtrace_info,		/* get_dev_info */
17268 	nulldev,		/* identify */
17269 	nulldev,		/* probe */
17270 	dtrace_attach,		/* attach */
17271 	dtrace_detach,		/* detach */
17272 	nodev,			/* reset */
17273 	&dtrace_cb_ops,		/* driver operations */
17274 	NULL,			/* bus operations */
17275 	nodev,			/* dev power */
17276 	ddi_quiesce_not_needed,		/* quiesce */
17277 };
17278 
17279 static struct modldrv modldrv = {
17280 	&mod_driverops,		/* module type (this is a pseudo driver) */
17281 	"Dynamic Tracing",	/* name of module */
17282 	&dtrace_ops,		/* driver ops */
17283 };
17284 
17285 static struct modlinkage modlinkage = {
17286 	MODREV_1,
17287 	(void *)&modldrv,
17288 	NULL
17289 };
17290 
17291 int
17292 _init(void)
17293 {
17294 	return (mod_install(&modlinkage));
17295 }
17296 
17297 int
17298 _info(struct modinfo *modinfop)
17299 {
17300 	return (mod_info(&modlinkage, modinfop));
17301 }
17302 
17303 int
17304 _fini(void)
17305 {
17306 	return (mod_remove(&modlinkage));
17307 }
17308